Пример #1
0
int main(int argc, const char *argv[])
{
    LoaderWorker lw(100);
    AutoFileLoader<load_data_type_t, LoaderWorker> afl("afl_test", "data/test.in", lw);
    int ret = afl.init();
    if (ret != 0) {
        std::cerr << "init AutoFileLoader failed with code " << ret << std::endl;
        return -1;
    }

    while (true) {
        load_data_type_t* data = afl.get();
        if (data == NULL) {
            std::cerr << "get loader buffer errro!" << std::endl;
            break;
        }
        std::cerr << "print loaded data:" << std::endl;
        std::cerr << "data size: " << data->size() << std::endl;
        for (load_data_type_t::iterator it = data->begin();
                it != data->end();
                ++it) {
            std::cout << it->first << " |\\t| " << it->second << std::endl;
            std::cout << std::flush;
        }
        sleep(10);
    }
    return 0;
}
Пример #2
0
JData * Jack::getJDataMessage(String message) { //preleva i dati dal messaggio e crea il messaggio nel formato JData
	
	//Serial.print("JDATAGET: ");
	//Serial.println(freeMemory());
	
	
	JData * messageJData = new JData();
	
	String temp = "";
	String temp2 = "";
	
	int nChar = 0;
	
	int value;
	
	message = message.substring(2, message.length());
	
	for(int i = 0; i < 2; i++) {
	
		temp = "";
		
		//Serial.println(message);
		
		if (message.startsWith(MESSAGE_ID)) { //id
			
			message = message.substring(MESSAGE_ID.length() + 2, message.length());
			
			for(int x = 0; message.charAt(x) != ','; x++) { //prelevo l'id dal messaggio
				
				temp += message.charAt(x);
				
			}
			
			if (i < 1) {
				message = message.substring(temp.length() + 2, message.length());
			}
			
			LongWrapper lw(temp);
			
			messageJData->addLong(MESSAGE_ID, lw.getLong());
			
			//Serial.println("id: " + temp);
			
			
		} else if (message.startsWith(MESSAGE_TYPE_ACK)) { //ack
		
			messageJData->addString(MESSAGE_TYPE, MESSAGE_TYPE_ACK);
			
			if (i < 1) {
				message = message.substring(MESSAGE_TYPE_DATA.length() + 5, message.length());
			}
			
			//Serial.println("ack");
		}
	
	}
	
	return messageJData;

}
Пример #3
0
inline bool semaphore_timed_wait(sem_t *handle, const boost::posix_time::ptime &abs_time)
{
   #ifdef BOOST_INTERPROCESS_POSIX_TIMEOUTS
   //Posix does not support infinity absolute time so handle it here
   if(abs_time == boost::posix_time::pos_infin){
      semaphore_wait(handle);
      return true;
   }

   timespec tspec = ptime_to_timespec(abs_time);
   for (;;){
      int res = sem_timedwait(handle, &tspec);
      if(res == 0)
         return true;
      if (res > 0){
         //buggy glibc, copy the returned error code to errno
         errno = res;
      }
      if(system_error_code() == ETIMEDOUT){
         return false;
      }
      error_info err = system_error_code();
      throw interprocess_exception(err);
   }
   return false;
   #else //#ifdef BOOST_INTERPROCESS_POSIX_TIMEOUTS

   semaphore_wrapper_try_wrapper swtw(handle);
   ipcdetail::lock_to_wait<semaphore_wrapper_try_wrapper> lw(swtw);
   return ipcdetail::try_based_timed_lock(lw, abs_time);

   #endif   //#ifdef BOOST_INTERPROCESS_POSIX_TIMEOUTS
}
Пример #4
0
/**
 3.2 Initialize region growing
   3.2.1 Determine memory offset inside the original image
   3.2.2 Determine initial region growing parameters from the level window settings of the image
   3.2.3 Perform a region growing (which generates a new feedback contour)
*/
bool mitk::RegionGrowingTool::OnMousePressedOutside(Action* itkNotUsed( action ), const StateEvent* stateEvent)
{
  const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent()); // checked in OnMousePressed
  // 3.2 If we have a reference image, then perform an initial region growing, considering the reference image's level window

  // if click was outside the image, don't continue
  const Geometry3D* sliceGeometry = m_ReferenceSlice->GetGeometry();
  Point3D mprojectedPointIn2D;
  sliceGeometry->WorldToIndex( positionEvent->GetWorldPosition(), mprojectedPointIn2D );
  itk::Index<2> projectedPointIn2D;
  projectedPointIn2D[0] = static_cast<int>( mprojectedPointIn2D[0] - 0.5 );
  projectedPointIn2D[1] = static_cast<int>( mprojectedPointIn2D[1] - 0.5 );

  if ( sliceGeometry->IsIndexInside( mprojectedPointIn2D ) )
  {
    MITK_DEBUG << "OnMousePressed: point " << positionEvent->GetWorldPosition() << " (index coordinates " << mprojectedPointIn2D << ") IS in reference slice" << std::endl;

    // 3.2.1 Remember Y cursor position and initial seed point
    //m_ScreenYPositionAtStart = static_cast<int>(positionEvent->GetDisplayPosition()[1]);
    m_LastScreenPosition = ApplicationCursor::GetInstance()->GetCursorPosition();
    m_ScreenYDifference = 0;

    m_SeedPointMemoryOffset = projectedPointIn2D[1] * m_OriginalPicSlice->n[0] + projectedPointIn2D[0];
    m_LastWorkingSeed = m_SeedPointMemoryOffset; // remember for skeletonization

    if ( m_SeedPointMemoryOffset < static_cast<int>( m_OriginalPicSlice->n[0] * m_OriginalPicSlice->n[1] ) &&
         m_SeedPointMemoryOffset >= 0 )
    {

      // 3.2.2 Get level window from reference DataNode
      //       Use some logic to determine initial gray value bounds
      LevelWindow lw(0, 500);
      m_ToolManager->GetReferenceData(0)->GetLevelWindow(lw); // will fill lw if levelwindow property is present, otherwise won't touch it.

      ScalarType currentVisibleWindow = lw.GetWindow();

      if (!mitk::Equal(currentVisibleWindow, m_VisibleWindow))
      {
        m_InitialLowerThreshold = currentVisibleWindow / 20.0;
        m_InitialUpperThreshold = currentVisibleWindow / 20.0;
        m_LowerThreshold = m_InitialLowerThreshold;
        m_UpperThreshold = m_InitialUpperThreshold;

        // 3.2.3. Actually perform region growing
        mitkIpPicDescriptor* result = PerformRegionGrowingAndUpdateContour();
        ipMITKSegmentationFree( result);

        // display the contour
        FeedbackContourTool::SetFeedbackContourVisible(true);
        mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());

        m_FillFeedbackContour = true;
      }
    }

  return true;
  }

  return false;
}
Пример #5
0
void mem(bool registrylocation[8], bool memlocation[16], bool read, bool write) {  //(may use if() to choose one of the two following functions)
	if (read) {
		lw(registrylocation, memlocation);
	}
	else if (write) {
		sw(registrylocation , memlocation);
	}
	else std::cout<<"Invalid memory operation. Read = 0. Write = 0.\n";
}
Пример #6
0
std::string symbol_implementation_name(const TreePtr<Interface>& interface, const PSI_STD::vector<TreePtr<Term> >& parameters) {
  std::ostringstream ss;
  ss << "_Y1";
  SymbolLocationWriter lw(ss);
  lw.write(interface->location().logical, true, '\0', '\0');
  for (PSI_STD::vector<TreePtr<Term> >::const_iterator ii = parameters.begin(), ie = parameters.end(); ii != ie; ++ii)
    symbol_type_name(lw, *ii);
  return ss.str();
}
Пример #7
0
dev::eth::ExecutionResult MixClient::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, bool _gasAuto, FudgeFactor _ff)
{
	(void)_blockNumber;
	Block block = asOf(eth::PendingBlock);
	u256 n = block.transactionsFrom(_from);
	Transaction t(_value, _gasPrice, _gas, _dest, _data, n);
	t.forceSender(_from);
	if (_ff == FudgeFactor::Lenient)
		block.mutableState().addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value()));
	WriteGuard lw(x_state); //TODO: lock is required only for last execution state
	executeTransaction(t, block, true, _gasAuto);
	return lastExecution().result;
}
Пример #8
0
dev::eth::ExecutionResult MixClient::call(Secret _secret, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, bool _gasAuto, FudgeFactor _ff)
{
	(void)_blockNumber;
	Address a = toAddress(_secret);
	State temp = asOf(eth::PendingBlock);
	u256 n = temp.transactionsFrom(a);
	Transaction t(_value, _gasPrice, _gas, _dest, _data, n, _secret);
	if (_ff == FudgeFactor::Lenient)
		temp.addBalance(a, (u256)(t.gasRequired() * t.gasPrice() + t.value()));
	bytes rlp = t.rlp();
	WriteGuard lw(x_state); //TODO: lock is required only for last execution state
	executeTransaction(t, temp, true, _gasAuto, _secret);
	return lastExecution().result;
}
Пример #9
0
dev::eth::ExecutionResult MixClient::create(Address const& _from, u256 _value, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, eth::FudgeFactor _ff)
{
	(void)_blockNumber;
	u256 n;
	Block temp;
	{
		ReadGuard lr(x_state);
		temp = asOf(eth::PendingBlock);
		n = temp.transactionsFrom(_from);
	}
	Transaction t(_value, _gasPrice, _gas, _data, n);
	t.forceSender(_from);
	if (_ff == FudgeFactor::Lenient)
		temp.mutableState().addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value()));
	WriteGuard lw(x_state); //TODO: lock is required only for last execution state
	executeTransaction(t, temp, true, false);
	return lastExecution().result;
}
Пример #10
0
const std::string& SymbolNameSet::symbol_name(const TreePtr<ModuleGlobal>& global) {
  std::string& name = m_symbol_names[global];
  if (!name.empty())
    return name;
  
  if (!global->symbol_name.empty()) {
    PSI_ASSERT(global->linkage != link_local);
    name = global->symbol_name;
  } else {
    std::ostringstream ss;
    ss << "_Y0";
    SymbolLocationWriter lw(ss);
    lw.write(global->location().logical, true, '\0', '\0');
    name = ss.str();
    if (global->linkage == link_local)
      name = unique_name(name);
  }
  return name;
}
Пример #11
0
bn::graph_t make_network()
{
    bn::graph_t graph;

    // Add Nodes. (4 nodes)
    graph.add_vertex();
    graph.add_vertex();
    graph.add_vertex();
    graph.add_vertex();

    // Get nodes list.
    // stored in the order that invoked "add_vertex()"
    // so, "returned value of add_vertex" == graph.vertex_list[i]
    std::vector<bn::vertex_type> const& vertex_list = graph.vertex_list();

    // Set selectable_num.
    // The number of values that can be took by the random variable(node).
    // ex. if "NodeA" can be {0, 1, 2, 3}, then you set it 4.
    vertex_list[0]->selectable_num = vertex_list[2]-selectable_num = 2;
    vertex_list[1]->selectable_num = vertex_list[3]-selectable_num = 6;

    // Add Edges.
    // if invoke "add_edge(A, B)", then make edge "A -> B".
    graph.add_edge(node_E, node_T);
    graph.add_edge(node_T, node_T_next);
    graph.add_edge(node_E, node_T_next);
    graph.add_edge(node_E_next, node_T_next);

    // !!! Make CPT by your Samples !!!
    //
    // if you use CSV data file(1 row = 1 sample, 1 column == 1 random variable), you can use bn::bayesian_network::load_data.
    //   ex1. bn::bayesian_network<void> bn;
    //        bn.load_data("samples.csv", graph.vertex_list());
    //        bn.load_cpt(graph);
    //   ex2. bn::bayesian_network<void> bn;
    //        bn.load_cpt_by_save_memory("samples.csv", graph.vertex_list(), graph);
    //
    // otherwise, repeat below code
    //   vertex_list[i]->cpt.assign({parent_nodes}, vertex_list[i]);
    //   bn::condition_t const cond = {{parent_node1, ?}, {parent_node2, ?}};
    //   vertex_list[i]->cpt[cond].second = {0.5, 0.3, ...};
    //

    // Set evidence node. In this example, vertex_list[i] is constantly 2. (and selectable_num is 4)
    std::unordered_map<bn::vertex_type, int> evidence_for_likelihood_weighting;
    evidence_for_likelihood_weighting[vertex_list[i]] = 2;

    std::unordered_map<bn::vertex_type, matrix_type> evidence_for_belief_propagation;
    evidence_for_belief_propagation[vertex_list[i]].resize(1, 4, 0.0);
    evidence_for_belief_propagation[vertex_list[i]][0][2] = 1;

    // Calculate! (Loopy Belief Propagation)
    bn::inference::belief_propagation bp(graph);
    std::unordered_map<vertex_type, matrix_type> const result_bp =
        bp(evidence_for_belief_propagation, 0.000001/* Radius of convergence */);

    // Calculate! (Likelihood Weighting)
    bn::inference::likelihood_weighting lw(graph);
    std::unordered_map<vertex_type, matrix_type> const result_bp =
        func_lw(evidence_for_likelihood_weighting, 1'000'000/* Num of auto sample */);
}
Пример #12
0
void execution(int index){
    if(test==1) printf("enter EX, with index=%d\n",index);

    if(index==0 || index==34){ //NOP or HALT
        return;
    }
    /**R-type instructions**/
    else if(index==1){
        add(RS,RT,RD);
    }
    else if(index==2){
        addu(RS,RT,RD);
    }
    else if(index==3){
        sub(RS,RT,RD);
    }
    else if(index==4){
        and(RS,RT,RD);
    }
    else if(index==5){
        or(RS,RT,RD);
    }
    else if(index==6){
        xor(RS,RT,RD);
    }
    else if(index==7){
        nor(RS,RT,RD);
    }
    else if(index==8){
        nand(RS,RT,RD);
    }
    else if(index==9){
        slt(RS,RT,RD);
    }
    else if(index==10){
        sll(RT,RD,SHAMT);
    }
    else if(index==11){
        srl(RT,RD,SHAMT);
    }
    else if(index==12){
        sra(RT,RD,SHAMT);
    }
    /**J-type instructions**/
    /*else if(index==13){
        jr(RS);
    }
    else if(index==14){
        jj(C);
    }
    else if(index==15){
        jal(C);
    }*/
    /**I-type instructions**/
    else if(index==16){
        addi(RS,RT,C);
    }
    else if(index==17){
        addiu(RS,RT,C);
    }
    else if(index==18){
        lw(RS,RT,signedC);
    }
    else if(index==19){
        lh(RS,RT,signedC);
    }
    else if(index==20){
        lhu(RS,RT,C);
    }
    else if(index==21){
        lb(RS,RT,signedC);
    }
    else if(index==22){
        lbu(RS,RT,C);
    }
    else if(index==23){
        sw(RS,RT,signedC);
    }
    else if(index==24){
        sh(RS,RT,signedC);
    }
    else if(index==25){
        sb(RS,RT,signedC);
    }
    else if(index==26){
        lui(RT,C);
    }
    else if(index==27){
        andi(RS,RT,C);
    }
    else if(index==28){
        or(RS,RT,C);
    }
    else if(index==29){
        nor(RS,RT,C);
    }
    else if(index==30){
        slti(RS,RT,C);
    }
    /*else if(index==31){
        beq(RS,RT,signedC);
    }
    else if(index==32){
        bne(RS,RT,signedC);
    }
    else if(index==33){
        bgtz(RS,signedC);
    }*/
    else{
        if(test==1) printf("this is error instruction or is done in ID\n");
    }
    EX_prev=index;
    DM_index=index;
}
Пример #13
0
void read_file(char * filename)
{
	fp = fopen(filename, "r");

    char * line = malloc(sizeof(char) * 255);
   	while (fgets(line,255,fp) != NULL) 
  	{

      char * buf[] = {" "," "," "," "};
      char * check = strtok(line, " ");
      int i = 0;
      while (check != NULL)
      {

        if (check != NULL)
        {
          buf[i] = malloc(strlen(check) + 1);
          strcpy(buf[i],check);
        }
        check = strtok(NULL, " ");
        i++;
      } 


  		if(strcmp(buf[0],"addu") == 0)
  		{
  			addu(trim(buf[2], ','),trim(buf[3], ','),trim(buf[1], '\n'));
  		} 
  		else if (strcmp(buf[0],"subu") == 0)
  		{
  			subu(trim(buf[2], ','),trim(buf[3], ','),trim(buf[1], '\n'));
  		}
  		else if(strcmp(buf[0],"slt") ==0)
  		{
  			slt(trim(buf[2], ','),trim(buf[3], ','),trim(buf[1], '\n'));
  		}
  		else if(strcmp(buf[0],"and") == 0)
  		{
  			and(trim(buf[2], ','),trim(buf[3], ','),trim(buf[1], '\n'));
  		}
  		else if(strcmp(buf[0],"or") == 0)
  		{
  			or(trim(buf[2], ','),trim(buf[3], ','),trim(buf[1], '\n'));
  		}
  		else if(strcmp(buf[0],"lw") == 0)
  		{
  			lw(rs_I(buf[2]), trim(buf[1], ','), trim(buf[2], '('));
  		}
  		else if (strcmp(buf[0],"sw") == 0)
  		{
  			sw(rs_I(buf[2]), trim(buf[1], ','), trim(buf[2], '('));
  		}
  		else if(strcmp(buf[0],"bne") == 0)
  		{
  			bne(trim(buf[2], ','),trim(buf[1], ','),trim(buf[3], 'j'));
  		}
  		else if(strcmp(buf[0],"j")== 0)
  		{
  			j(trim(buf[1], 'j'));
  		}

  		
  	}
    fclose(fp);
  	printf("End Scan\n");
}
Пример #14
0
void simulate_MainWindow::simulate()
{
    currInstr=instrList[PC/4];
    currBin=binList[PC/4];

    vector<string> result;
    string temp=currInstr.toStdString();
    string_split(temp,result);

    coutString="";
    RD=RS=RT=immediate=address=0;
    v0=v1=v2=v3="None";
    v0=result[0];
    v1=result[1];
    printf("v0=%s\nv1=%s\n",v0.c_str(),v1.c_str());
    if(v0=="jr"||v0=="j"||v0=="jal")  // 2 parametes
    {
        if(v0=="jr")
        {
            jr();
        }
        else if(v0=="j")
            j();
        else if(v0=="jal")
            jal();
    }
    else if(v0=="lui")    // 3 parameters
    {
        v2=result[2];
        lui();
    }
    else                 // 4 parameters
    {
        v2=result[2];
        v3=result[3];
        if(v0=="add")
            add();
        else if(v0=="addu")
            addu();
        else if(v0=="sub")
            sub();
        else if(v0=="subu")
            subu();
        else if(v0=="and")
            and_funct();
        else if(v0=="or")
            or_funct();
        else if(v0=="xor")
            xor_funct();
        else if(v0=="nor")
            nor();
        else if(v0=="slt")
            slt();
        else if(v0=="sltu")
            sltu();
        else if(v0=="sll")
            sll();
        else if(v0=="srl")
            srl();
        else if(v0=="sllv")
            sllv();
        else if(v0=="srlv")
            srlv();
        else if(v0=="srav")
            srav();
        else if(v0=="addi")
            addi();
        else if(v0=="addiu")
            addiu();
        else if(v0=="andi")
            andi();
        else if(v0=="ori")
            ori();
        else if(v0=="xori")
            xori();
        else if(v0=="sw")
            sw();
        else if(v0=="lw")
            lw();
        else if(v0=="beq")
            beq();
        else if(v0=="bne")
            bne();
        else if(v0=="slti")
            slti();
        else if(v0=="sltiu")
            sltiu();
    }
    display_all();
}
Пример #15
0
Eigen::MatrixXd RmullwlskCC( const Eigen::Map<Eigen::VectorXd> & bw, const std::string kernel_type, const Eigen::Map<Eigen::MatrixXd> & tPairs, const Eigen::Map<Eigen::MatrixXd> & cxxn, const Eigen::Map<Eigen::VectorXd> & win,  const Eigen::Map<Eigen::VectorXd> & xgrid, const Eigen::Map<Eigen::VectorXd> & ygrid, const bool & bwCheck){ 

  // tPairs : xin (in MATLAB code)
  // cxxn : yin (in MATLAB code)
  // xgrid: out1 (in MATLAB code)
  // ygrid: out2 (in MATLAB code)
  // bwCheck : boolean/ cause the function to simply run the bandwidth check.

  const double invSqrt2pi=  1./(sqrt(2.*M_PI));

  // Map the kernel name so we can use switches  
  std::map<std::string,int> possibleKernels; 
  possibleKernels["epan"]    = 1;   possibleKernels["rect"]    = 2;
  possibleKernels["gauss"]   = 3;   possibleKernels["gausvar"] = 4; 
  possibleKernels["quar"]    = 5; 
   
  // The following test is here for completeness, we mightwant to move it up a 
  // level (in the wrapper) in the future. 

  // If the kernel_type key exists set KernelName appropriately
  int KernelName = 0;
  if ( possibleKernels.count( kernel_type ) != 0){ 
    KernelName = possibleKernels.find( kernel_type )->second; //Set kernel choice
  } else {
  // otherwise use "epan"as the kernel_type 
    //Rcpp::Rcout << "Kernel_type argument was not set correctly; Epanechnikov kernel used." << std::endl;
    Rcpp::warning("Kernel_type argument was not set correctly; Epanechnikov kernel used.");
    KernelName = possibleKernels.find( "epan" )->second;;
  }

  // Check that we do not have zero weights // Should do a try-catch here
  // Again this might be best moved a level-up. 
  if ( !(win.all()) ){  // 
    Rcpp::Rcout << "Cases with zero-valued windows are not yet implemented" << std::endl;
    return (tPairs);
  } 

  // Start the actual smoother here  
  unsigned int xgridN = xgrid.size();  
  unsigned int ygridN = ygrid.size();  
  
  Eigen::MatrixXd mu(xgrid.size(), ygrid.size());
  mu.setZero();    
  const  double bufSmall = 1e-6; // pow(double(10),-6);

  for (unsigned int j = 0; j != ygridN; ++j) { 
    for (unsigned int i = 0; i != xgridN; ++i) {  

      //locating local window (LOL) (bad joke)
      std::vector <unsigned int> indx; 
      //if the kernel is not Gaussian
      if ( KernelName != 3) { 
        //construct listX as vectors / size is unknown originally
        for (unsigned int y = 0; y != tPairs.cols(); y++){ 
          if (  (std::abs( tPairs(0,y) - xgrid(i) ) <= (bw(0)+ bufSmall ) && std::abs( tPairs(1,y) - ygrid(j) ) <= (bw(1)+ bufSmall)) ) {
            indx.push_back(y);
          }
        }
  
      } else{ // just get the whole deal
        for (unsigned int y = 0; y != tPairs.cols(); ++y){
          indx.push_back(y);
        }
      }  
      
     //  for (unsigned int y = 0; y != indx.size(); ++y){
     //    Rcpp::Rcout << "indx.at(y): " << indx.at(y)<< ", ";
     //  }

      unsigned int indxSize = indx.size();
      Eigen::VectorXd lw(indxSize);  
      Eigen::VectorXd ly(indxSize);
      Eigen::MatrixXd lx(2,indxSize);

      for (unsigned int u = 0; u !=indxSize; ++u){ 
        lx.col(u) = tPairs.col(indx[u]); 
        lw(u) = win(indx[u]); 
        ly(u) = cxxn(indx[u]); 
      }

      // check enough points are in the local window 
      unsigned int meter=1;  
      for (unsigned int u =0; u< indxSize; ++u) { 
        for (unsigned int t = u + 1; t < indxSize; ++t) {
          if ( (lx(0,u) !=  lx(0,t) ) || (lx(1,u) != lx(1,t) ) ) {
            meter++;
          }
        }
        if (meter >= 3) { 
          break; 
        }
      }
   
      //computing weight matrix 
      if (meter >=  3 && !bwCheck) { 
        Eigen::VectorXd temp(indxSize);
        Eigen::MatrixXd llx(2, indxSize );  
        llx.row(0) = (lx.row(0).array() - xgrid(i))/bw(0);  
        llx.row(1) = (lx.row(1).array() - ygrid(j))/bw(1); 

        //define the kernel used 

        switch (KernelName){
          case 1: // Epan
            temp=  ((1-llx.row(0).array().pow(2))*(1- llx.row(1).array().pow(2))).array() * 
                   ((9./16)*lw).transpose().array(); 
            break;  
          case 2 : // Rect
            temp=(lw.array())*.25 ; 
            break;
          case 3 : // Gauss
            temp = ((-.5*(llx.row(1).array().pow(2))).exp()) * invSqrt2pi  *   
                   ((-.5*(llx.row(0).array().pow(2))).exp()) * invSqrt2pi  *
                   (lw.transpose().array()); 
            break;
          case 4 : // GausVar
            temp = (lw.transpose().array()) * 
		   ((-0.5 * llx.row(0).array().pow(2)).array().exp() * invSqrt2pi).array() *
                   ((-0.5 * llx.row(1).array().pow(2)).array().exp() * invSqrt2pi).array() * 
                   (1.25 - (0.25 * (llx.row(0).array().pow(2))).array())  * 
                   (1.50 - (0.50 * (llx.row(1).array().pow(2))).array()); 
            break;
          case 5 :  // Quar
              temp = (lw.transpose().array()) * 
                     ((1.-llx.row(0).array().pow(2)).array().pow(2)).array() *
                     ((1.-llx.row(1).array().pow(2)).array().pow(2)).array() * (225./256.);
            break;
        } 

        // make the design matrix
        Eigen::MatrixXd X(indxSize ,3);
        X.setOnes();    
        X.col(1) = lx.row(0).array() - xgrid(i);
        X.col(2) = lx.row(1).array() - ygrid(j); 
        Eigen::LDLT<Eigen::MatrixXd> ldlt_XTWX(X.transpose() * temp.asDiagonal() *X);
        // The solver should stop if the value is NaN. See the HOLE example in gcvlwls2dV2.
        // Rcpp::Rcout << X << std::endl;
        Eigen::VectorXd beta = ldlt_XTWX.solve(X.transpose() * temp.asDiagonal() * ly);  
        mu(i,j)=beta(0); 
      } else if(meter < 3){
        // Rcpp::Rcout <<"The meter value is:" << meter << std::endl;  
        if (bwCheck) {
            Eigen::MatrixXd checker(1,1);
            checker(0,0) = 0.;
            return(checker);
        } else {
            Rcpp::stop("No enough points in local window, please increase bandwidth.");
        }
      }
    }
  }

  if (bwCheck){
     Eigen::MatrixXd checker(1,1); 
     checker(0,0) = 1.; 
     return(checker);
  } 
      
  return ( mu ); 
}
Пример #16
0
Eigen::MatrixXd RmullwlskCCsort2( const Eigen::Map<Eigen::VectorXd> & bw, const std::string kernel_type, const Eigen::Map<Eigen::MatrixXd> & tPairs, const Eigen::Map<Eigen::MatrixXd> & cxxn, const Eigen::Map<Eigen::VectorXd> & win,  const Eigen::Map<Eigen::VectorXd> & xgrid, const Eigen::Map<Eigen::VectorXd> & ygrid, const bool & bwCheck){ 
// Assumes the first row of tPairs is sorted in increasing order.
  // tPairs : xin (in MATLAB code)
  // cxxn : yin (in MATLAB code)
  // xgrid: out1 (in MATLAB code)
  // ygrid: out2 (in MATLAB code)
  // bwCheck : boolean/ cause the function to simply run the bandwidth check.

  const double invSqrt2pi=  1./(sqrt(2.*M_PI));

  // Map the kernel name so we can use switches  
  std::map<std::string,int> possibleKernels; 
  possibleKernels["epan"]    = 1;   possibleKernels["rect"]    = 2;
  possibleKernels["gauss"]   = 3;   possibleKernels["gausvar"] = 4; 
  possibleKernels["quar"]    = 5; 
   
  // The following test is here for completeness, we mightwant to move it up a 
  // level (in the wrapper) in the future. 

  // If the kernel_type key exists set KernelName appropriately
  int KernelName = 0;
  if ( possibleKernels.count( kernel_type ) != 0){ 
    KernelName = possibleKernels.find( kernel_type )->second; //Set kernel choice
  } else {
  // otherwise use "epan"as the kernel_type 
    //Rcpp::Rcout << "Kernel_type argument was not set correctly; Epanechnikov kernel used." << std::endl;
    Rcpp::warning("Kernel_type argument was not set correctly; Epanechnikov kernel used.");
    KernelName = possibleKernels.find( "epan" )->second;;
  }

  // Check that we do not have zero weights // Should do a try-catch here
  // Again this might be best moved a level-up. 
  if ( !(win.all()) ){  // 
    Rcpp::Rcout << "Cases with zero-valued windows are not yet implemented" << std::endl;
    return (tPairs);
  } 

  // ProfilerStart("sort.log");
  // Start the actual smoother here  
  const unsigned int xgridN = xgrid.size();  
  const unsigned int ygridN = ygrid.size();  
  const unsigned int n = tPairs.cols();
  
  // For sorted x1
  Eigen::VectorXd x1(tPairs.row(0).transpose());
  const double* tDat = x1.data();
  
  Eigen::MatrixXd mu(xgrid.size(), ygrid.size());
  mu.setZero();    


  for (unsigned int i = 0; i != xgridN; ++i) {  
    const double xl = xgrid(i) - bw(0) - 1e-6, 
                 xu = xgrid(i) + bw(0) + 1e-6;

    unsigned int indl = std::lower_bound(tDat, tDat + n, xl) - tDat,  
                 indu = std::upper_bound(tDat, tDat + n, xu) - tDat;

    // sort the y index
    std::vector<valIndPair> yval(indu - indl);
    for (unsigned int k = 0; k < yval.size(); ++k){
      yval[k] = std::make_pair(tPairs(1, k + indl), k + indl);
    }
    std::sort<std::vector<valIndPair>::iterator>(yval.begin(), yval.end(), compPair);

    std::vector<valIndPair>::iterator ylIt = yval.begin(), 
                                      yuIt = yval.begin();

    for (unsigned int j = 0; j != ygridN; ++j) { 
      const double yl = ygrid(j) - bw(1) - 1e-6, 
                   yu = ygrid(j) + bw(1) + 1e-6;

      //locating local window (LOL) (bad joke)
      std::vector <unsigned int> indx; 
      
      //if the kernel is not Gaussian
      if ( KernelName != 3) { 
      // Search the lower and upper bounds increasingly.
        ylIt = std::lower_bound(ylIt, yval.end(), valIndPair(yl, 0), compPair);
        yuIt = std::upper_bound(yuIt, yval.end(), valIndPair(yu, 0), compPair);

        // The following works nice for the Gaussian 
        //  but for very small samples it complains  
        //} else {
        //  ylIt = yval.begin();
        //  yuIt = yval.end();
        //}

        for (std::vector<valIndPair>::iterator y = ylIt; y != yuIt; ++y){ 
          indx.push_back(y->second);
        } 
      } else { //When we finally get c++11 we will use std::iota
        for( unsigned int y = 0; y != n; ++y){
          indx.push_back(y);
        }
      }

      // for (unsigned int y = 0; y != indx.size(); ++y){
      //  Rcpp::Rcout << "indx.at(y):  " << indx.at(y)<< ", ";
      //  }
      unsigned int indxSize = indx.size();
      Eigen::VectorXd lw(indxSize);  
      Eigen::VectorXd ly(indxSize);
      Eigen::MatrixXd lx(2,indxSize);

      for (unsigned int u = 0; u !=indxSize; ++u){ 
        lx.col(u) = tPairs.col(indx[u]); 
        lw(u) = win(indx[u]); 
        ly(u) = cxxn(indx[u]); 
      }

      // check enough points are in the local window 
      unsigned int meter=1;  
      for (unsigned int u =0; u< indxSize; ++u) { 
        for (unsigned int t = u + 1; t < indxSize; ++t) {
          if ( (lx(0,u) !=  lx(0,t) ) || (lx(1,u) != lx(1,t) ) ) {
            meter++;
          }
        }
        if (meter >= 3) { 
          break; 
        }
      }
    
      //computing weight matrix 
      if (meter >=  3 && !bwCheck) { 
        Eigen::VectorXd temp(indxSize);
        Eigen::MatrixXd llx(2, indxSize );  
        llx.row(0) = (lx.row(0).array() - xgrid(i))/bw(0);  
        llx.row(1) = (lx.row(1).array() - ygrid(j))/bw(1); 

        //define the kernel used 

        switch (KernelName){
          case 1: // Epan
            temp=  ((1-llx.row(0).array().pow(2))*(1- llx.row(1).array().pow(2))).array() * 
                   ((9./16)*lw).transpose().array(); 
            break;  
          case 2 : // Rect
            temp=(lw.array())*.25 ; 
            break;
          case 3 : // Gauss
            temp = ((-.5*(llx.row(1).array().pow(2))).exp()) * invSqrt2pi  *   
                   ((-.5*(llx.row(0).array().pow(2))).exp()) * invSqrt2pi  *
                   (lw.transpose().array()); 
            break;
          case 4 : // GausVar
            temp = (lw.transpose().array()) * 
		   ((-0.5 * llx.row(0).array().pow(2)).array().exp() * invSqrt2pi).array() *
                   ((-0.5 * llx.row(1).array().pow(2)).array().exp() * invSqrt2pi).array() * 
                   (1.25 - (0.25 * (llx.row(0).array().pow(2))).array())  * 
                   (1.50 - (0.50 * (llx.row(1).array().pow(2))).array()); 
            break;
          case 5 :  // Quar
              temp = (lw.transpose().array()) * 
                     ((1.-llx.row(0).array().pow(2)).array().pow(2)).array() *
                     ((1.-llx.row(1).array().pow(2)).array().pow(2)).array() * (225./256.);
            break;
        } 

        // make the design matrix
        Eigen::MatrixXd X(indxSize ,3);
        X.setOnes();    
        X.col(1) = lx.row(0).array() - xgrid(i);
        X.col(2) = lx.row(1).array() - ygrid(j); 
        Eigen::LDLT<Eigen::MatrixXd> ldlt_XTWX(X.transpose() * temp.asDiagonal() *X);
        // The solver should stop if the value is NaN. See the HOLE example in gcvlwls2dV2.
        Eigen::VectorXd beta = ldlt_XTWX.solve(X.transpose() * temp.asDiagonal() * ly);  
        mu(i,j)=beta(0); 
      } 
      // else if(meter < 3){
        // // Rcpp::Rcout <<"The meter value is:" << meter << std::endl;  
        // if (bwCheck) {
            // Eigen::MatrixXd checker(1,1);
            // checker(0,0) = 0.;
            // return(checker);
        // } else {
            // Rcpp::stop("No enough points in local window, please increase bandwidth.");
        // }
      // }
    }
  }

  if (bwCheck){
     Eigen::MatrixXd checker(1,1); 
     checker(0,0) = 1.; 
     return(checker);
  } 
      
// ProfilerStop();
  return ( mu ); 
}
Пример #17
0
inline bool spin_semaphore::timed_wait(const boost::posix_time::ptime &abs_time)
{
   ipcdetail::lock_to_wait<spin_semaphore> lw(*this);
   return ipcdetail::try_based_timed_lock(lw, abs_time);
}
Пример #18
0
inline void spin_semaphore::wait()
{
   ipcdetail::lock_to_wait<spin_semaphore> lw(*this);
   return ipcdetail::try_based_lock(lw);
}
Пример #19
0
void FamilyTree::saveGraphViz(const char* iFileName)
{
    std::ofstream ofs(iFileName, std::ofstream::out);
    LabelWriter<graph> lw(mGraph);
    write_graphviz(ofs, mGraph, lw);
}
Пример #20
0
void mitk::RegionGrowingTool::OnMousePressedOutside(StateMachineAction*, InteractionEvent* interactionEvent)
{
    mitk::InteractionPositionEvent* positionEvent = dynamic_cast<mitk::InteractionPositionEvent*>(interactionEvent);

    if (positionEvent)
    {
        // Get geometry and indices
        mitk::BaseGeometry::Pointer workingSliceGeometry;
        workingSliceGeometry = m_WorkingSlice->GetTimeGeometry()->GetGeometryForTimeStep(m_LastEventSender->GetTimeStep());
        itk::Index<2> indexInWorkingSlice2D;
        indexInWorkingSlice2D[0] = m_SeedPoint[0];
        indexInWorkingSlice2D[1] = m_SeedPoint[1];

        mitk::BaseGeometry::Pointer referenceSliceGeometry;
        referenceSliceGeometry = m_ReferenceSlice->GetTimeGeometry()->GetGeometryForTimeStep(m_LastEventSender->GetTimeStep());
        itk::Index<3> indexInReferenceSlice;
        itk::Index<2> indexInReferenceSlice2D;
        referenceSliceGeometry->WorldToIndex(positionEvent->GetPositionInWorld(), indexInReferenceSlice);
        indexInReferenceSlice2D[0] = indexInReferenceSlice[0];
        indexInReferenceSlice2D[1] = indexInReferenceSlice[1];

        // Get seed neighborhood
        ScalarType averageValue(0);
        AccessFixedDimensionByItk_3(m_ReferenceSlice, GetNeighborhoodAverage, 2, indexInReferenceSlice2D, &averageValue, 1);
        m_SeedValue = averageValue;
        MITK_DEBUG << "Seed value is " << m_SeedValue;

        // Get level window settings
        LevelWindow lw(0, 500); // default window 0 to 500, can we do something smarter here?
        m_ToolManager->GetReferenceData(0)->GetLevelWindow(lw); // will fill lw if levelwindow property is present, otherwise won't touch it.
        ScalarType currentVisibleWindow = lw.GetWindow();
        MITK_DEBUG << "Level window width is " << currentVisibleWindow;
        m_InitialThresholds[0] = m_SeedValue - currentVisibleWindow / 20.0; // 20 is arbitrary (though works reasonably well), is there a better alternative (maybe option in preferences)?
        m_InitialThresholds[1] = m_SeedValue + currentVisibleWindow / 20.0;
        m_Thresholds[0] = m_InitialThresholds[0];
        m_Thresholds[1] = m_InitialThresholds[1];

        // Perform region growing
        mitk::Image::Pointer resultImage = mitk::Image::New();
        AccessFixedDimensionByItk_3(m_ReferenceSlice, StartRegionGrowing, 2, indexInWorkingSlice2D, m_Thresholds, resultImage);
        resultImage->SetGeometry(workingSliceGeometry);

        // Extract contour
        if (resultImage.IsNotNull() && m_ConnectedComponentValue >= 1)
        {
            mitk::ImageToContourModelFilter::Pointer contourExtractor = mitk::ImageToContourModelFilter::New();
            contourExtractor->SetInput(resultImage);
            contourExtractor->SetContourValue(m_ConnectedComponentValue - 0.5);
            contourExtractor->Update();
            ContourModel::Pointer resultContour = ContourModel::New();
            resultContour = contourExtractor->GetOutput();

            // Show contour
            if (resultContour.IsNotNull())
            {
                ContourModel::Pointer resultContourWorld = FeedbackContourTool::BackProjectContourFrom2DSlice(workingSliceGeometry, FeedbackContourTool::ProjectContourTo2DSlice(m_WorkingSlice, resultContour));
                FeedbackContourTool::SetFeedbackContour(resultContourWorld);
                FeedbackContourTool::SetFeedbackContourVisible(true);
                mitk::RenderingManager::GetInstance()->RequestUpdate(m_LastEventSender->GetRenderWindow());
            }
        }
    }
}
Пример #21
0
int exe(FILE* program)  //program指向存有待执行程序机器码的文件
{

     char* tmp_instru=(char*)malloc(33*sizeof(char)); //读机器码
     programTail=programHead;
     while(fscanf(program,"%s",tmp_instru)!=EOF)
     {
         instru=0;
         int i=0;
         unsigned j=1;
         for(i=31;i>=0;i--)
         {
            if(tmp_instru[i]=='1')
            {
                instru+=j;
                j*=2;
            }
            else
            {
                j*=2;
            }
         }//将机器码转为unsi
         unsigned char* tmp_R=&instru;
         for(i=0;i<4;i++)
         {
             writeMymemory(programTail+i,tmp_R+i);//装载指令
         }
         programTail+=4;//最后一条指令的下一条指令的地址,用来判断程序是否执行完
     }
     pcShort=programHead;
     pc=pcShort;
     while(pcShort!=programTail)
    {
        instru=0;   //指令寄存器清零
    unsigned char* tmp_R=&instru;
    unsigned short addr=addrToMyAddr(pc);
    int i;
    for(i=0;i<4;i++)
    {
        readMymemory(addr+i,tmp_R+i);//取指令
    }
    unsigned tmp=instru>>26;//得到指令op

    //printf("the op is :  %u\n",tmp);

    unsigned numRs=0,numRt=0,numRd=0,numFs=0,numFt=0,numFd=0,tmp_fuc=0;
    switch(tmp)
    {
    case 0x00000023:
        numRs=instru<<6>>27;
        numRt=instru<<11>>27;
        RS1=myRegister+numRt;
        RS2=myRegister+numRs;
        lig=instru<<16>>16;
        pc=lw(pc);
        break;
    case 0x0000002B:
        numRs=instru<<6>>27;
        numRt=instru<<11>>27;
        RS1=myRegister+numRt;
        RS2=myRegister+numRs;
        lig=instru<<16>>16;
        pc=sw(pc);
        break;
    case 0x00000008:
        numRs=instru<<6>>27;
        numRt=instru<<11>>27;
        RS1=myRegister+numRt;
        RS2=myRegister+numRs;
        lig=instru<<16>>16;
        pc=addi(pc);
        break;
    case 0x00000009:
        numRs=instru<<6>>27;
        numRt=instru<<11>>27;
        RS1=myRegister+numRt;
        RS2=myRegister+numRs;
        lig=instru<<16>>16;
        pc=addiu(pc);
        break;
    case 0x0000000A:
        numRs=instru<<6>>27;
        numRt=instru<<11>>27;
        RS1=myRegister+numRt;
        RS2=myRegister+numRs;
        lig=instru<<16>>16;
        pc=slti(pc);
        break;
    case 0x0000000B:
        numRs=instru<<6>>27;
        numRt=instru<<11>>27;
        RS1=myRegister+numRt;
        RS2=myRegister+numRs;
        lig=instru<<16>>16;
        pc=sltiu(pc);
        break;
    case 0x0000000C:
        numRs=instru<<6>>27;
        numRt=instru<<11>>27;
        RS1=myRegister+numRt;
        RS2=myRegister+numRs;
        lig=instru<<16>>16;
        pc=andi(pc);
        break;
    case 0x0000000D:
        numRs=instru<<6>>27;
        numRt=instru<<11>>27;
        RS1=myRegister+numRt;
        RS2=myRegister+numRs;
        lig=instru<<16>>16;
        pc=ori(pc);
        break;
    case 0x0000000E:
        numRs=instru<<6>>27;
        numRt=instru<<11>>27;
        RS1=myRegister+numRt;
        RS2=myRegister+numRs;
        lig=instru<<16>>16;
        pc=xori(pc);
        break;
    case 0x00000024:
        numRs=instru<<6>>27;
        numRt=instru<<11>>27;
        RS1=myRegister+numRt;
        RS2=myRegister+numRs;
        lig=instru<<16>>16;
        pc=lbu(pc);
        break;
    case 0x00000020:
        numRs=instru<<6>>27;
        numRt=instru<<11>>27;
        RS1=myRegister+numRt;
        RS2=myRegister+numRs;
        lig=instru<<16>>16;
        pc=lb(pc);
        break;
    case 0x00000028:
        numRs=instru<<6>>27;
        numRt=instru<<11>>27;
        RS1=myRegister+numRt;
        RS2=myRegister+numRs;
        lig=instru<<16>>16;
        pc=sb(pc);
        break;
    case 0x0000000F:
        numRs=instru<<6>>27;
        numRt=instru<<11>>27;
        RS1=myRegister+numRt;
        RS2=myRegister+numRs;
        lig=instru<<16>>16;
        pc=lui(pc);
        break;
    case 0x00000004:
        numRs=instru<<6>>27;
        numRt=instru<<11>>27;
        RS1=myRegister+numRt;
        RS2=myRegister+numRs;
        lig=instru<<16>>16;
        pc=beq(pc);
        break;
    case 0x00000005:
        numRs=instru<<6>>27;
        numRt=instru<<11>>27;
        RS1=myRegister+numRt;
        RS2=myRegister+numRs;
        //printf("%u,%u,%u,%u\n",numRt,numRs,*RS1,*RS2);
        lig=instru<<16>>16;
       // printf("%u\n",lig);
        pc=bne(pc);
        break;
    case 0x00000006:
        numRs=instru<<6>>27;
        numRt=instru<<11>>27;
        RS1=myRegister+numRt;
        RS2=myRegister+numRs;
        lig=instru<<16>>16;
        pc=blez(pc);
        break;
    case 0x00000007:
        numRs=instru<<6>>27;
        numRt=instru<<11>>27;
        RS1=myRegister+numRt;
        RS2=myRegister+numRs;
        lig=instru<<16>>16;
        pc=bgtz(pc);
        break;
    case 0x00000001:
        numRs=instru<<6>>27;
        numRt=instru<<11>>27;
        RS1=myRegister+numRt;
        RS2=myRegister+numRs;
        lig=instru<<16>>16;
        pc=bltz(pc);
        break;
    case 0x00000002:
        pc=j(pc);
        break;
    case 0x00000003:
        pc=jal(pc);
        break;
    case 0x00000000:
        numRs=instru<<6>>27;
        numRt=instru<<11>>27;
        numRd=instru<<16>>27;
        RS1=myRegister+numRt;
        RS2=myRegister+numRs;
        RD=myRegister+numRd;
        tmp_fuc=instru%64;
        switch(tmp_fuc)
        {
        case 32:
            pc=add(pc);
            break;
        case 33:
            pc=addu(pc);
            break;
        case 34:
            pc=sub(pc);
            break;
        case 35:
            pc=subu(pc);
            break;
        case 24:
            pc=mul(pc);
            break;
        case 25:
            pc=mulu(pc);
            break;
        case 26:
            pc=myDiv(pc);
            break;
        case 27:
            pc=divu(pc);
            break;
        case 42:
            pc=slt(pc);
            break;
        case 43:
            pc=sltu(pc);
            break;
        case 36:
            pc=myAnd(pc);
            break;
        case 37:
            pc=myOr(pc);
            break;
        case 39:
            pc=nor(pc);
            break;
        case 40:
            pc=myXor(pc);
            break;
        case 8:
            pc=jr(pc);
            break;
        case 9:
            pc=jalr(pc);
            break;
        case 0:
            pc=nop(pc);
            break;
        case 16:
            pc=mfhi(pc);
            break;
        case 18:
            pc=mflo(pc);
            break;
        default:
            break;
        }
        break;
    case 0x00000010:
        numRt=instru<<11>>27;
        numRd=instru<<16>>27;
        RS1=myRegister+numRt;
        if(numRd==14)
        {
            pc=mfepc(pc);
        }
        else if(numRd==13)
        {
            pc=mfco(pc);
        }
        else return -1;
        break;
    case 0x00000031:
        numRs=instru<<6>>27;
        numFt=instru<<11>>27;
        RS2=myRegister+numRs;
        FS1=myFloatReg+numFt;
        lig=instru<<16>>16;
        pc=lwc1(pc);


            //printf("/********\nL.S %u %u\n****************/\n",numFt,numRs);

        break;
    case 0x0000001F:
        numRs=instru<<6>>27;
        numFt=instru<<11>>27;
        RS2=myRegister+numRs;
        FS1=myFloatReg+numFt;
        lig=instru<<16>>16;
        pc=S_D(pc);


            //printf("/********\nL.D %u %u\n****************/\n",numFt,numRs);

        break;
    case 0x0000001E:
        numRs=instru<<6>>27;
        numFt=instru<<11>>27;
        RS2=myRegister+numRs;
        FS1=myFloatReg+numFt;
        lig=instru<<16>>16;
        //printf("/********\nS.D %u %u\n****************/\n",numFt,numRs);
        pc=S_D(pc);
        break;

    case 0x00000039:
        numRs=instru<<6>>27;
        numFt=instru<<11>>27;
        RS2=myRegister+numRs;
        FS1=myFloatReg+numFt;
        lig=instru<<16>>16;
        //printf("/********\nS.S %u %u\n****************/\n",numFt,numRs);
        pc=swc1(pc);
        break;
    case 0x00000011:
        numFt=instru<<11>>27;
        numFs=instru<<16>>27;
        numFd=instru<<21>>27;
        FS1=myFloatReg+numFt;
        FS2=myFloatReg+numFs;
        FD=myFloatReg+numFd;
        numRs=instru<<6>>27;
        tmp_fuc=instru%64;
        //printf("%u %u\n",tmp_fuc,numRs);
        if(numRs==0)
        {
            switch(tmp_fuc)
            {
            case 0:
                pc=add_s(pc);
                break;
            case 1:
                pc=sub_s(pc);
                break;
            case 2:
                pc=mul_s(pc);
            case 3:
                pc=div_s(pc);
            default:
                break;
            }
        }
        else if(numRs==1)
        {
            switch(tmp_fuc)
            {
            case 0:
                pc=add_d(pc);
                //printf("/****************\nADD.D %u %u %u\n*****************/\n",numFd,numFt,numFs);
                break;
            case 1:
                pc=sub_d(pc);
                break;
            case 2:
                pc=mul_d(pc);
            case 3:
                pc=div_d(pc);
            default:
                break;
            }
        }
        default:break;
    }
    pcShort=pc%0x00010000;
    //printf("%u %u\n",pc,pcShort);
    //printf("%u %u\n",pcShort,programTail);
    }
    return 0;
}
Пример #22
0
Eigen::VectorXd Rrotatedmullwlsk( const Eigen::Map<Eigen::VectorXd> & bw, const std::string kernel_type, const Eigen::Map<Eigen::MatrixXd> & tPairs, const Eigen::Map<Eigen::MatrixXd> & cxxn, const Eigen::Map<Eigen::VectorXd> & win,  const Eigen::Map<Eigen::MatrixXd> & xygrid, const unsigned int npoly, const bool & bwCheck){ 

  // tPairs : xin (in MATLAB code)
  // cxxn : yin (in MATLAB code)
  // xygrid: d (in MATLAB code)
  // npoly: redundant?

  const double invSqrt2pi=  1./(sqrt(2.*M_PI));

  // Map the kernel name so we can use switches  
  std::map<std::string,int> possibleKernels; 
  possibleKernels["epan"]    = 1;   possibleKernels["rect"]    = 2;
  possibleKernels["gauss"]   = 3;   possibleKernels["gausvar"] = 4; 
  possibleKernels["quar"]    = 5; 
   
  // The following test is here for completeness, we mightwant to move it up a 
  // level (in the wrapper) in the future. 

  // If the kernel_type key exists set KernelName appropriately
  int KernelName = 0;
  if ( possibleKernels.count( kernel_type ) != 0){ 
    KernelName = possibleKernels.find( kernel_type )->second; //Set kernel choice
  } else {
  // otherwise use "epan"as the kernel_type 
  // Rcpp::Rcout << "Kernel_type argument was not set correctly; Epanechnikov kernel used." << std::endl;
    Rcpp::warning("Kernel_type argument was not set correctly; Epanechnikov kernel used.");
    KernelName = possibleKernels.find( "epan" )->second;;
  }

  // Check that we do not have zero weights // Should do a try-catch here
  // Again this might be best moved a level-up. 
  if ( !(win.all()) ){  // 
    Rcpp::Rcout << "Cases with zero-valued windows are not yet implemented" << std::endl;
    return (tPairs);
  } 

  Eigen::Matrix2d RC;  // Rotation Coordinates
  RC << 1, -1, 1, 1; 
  RC *= sqrt(2.)/2.; 

  Eigen::MatrixXd rtPairs = RC * tPairs;
  Eigen::MatrixXd rxygrid = RC * xygrid;
  
  unsigned int xygridN = rxygrid.cols();  
  
  Eigen::VectorXd mu(xygridN);
  mu.setZero();     

  for (unsigned int i = 0; i !=  xygridN; ++i){   

    //locating local window (LOL) (bad joke)
    std::vector <unsigned int> indx; 
    //if the kernel is not Gaussian or Gaussian-like
    if ( KernelName != 3 && KernelName != 4 ) { 
      //construct listX as vectors / size is unknown originally
      std::vector <unsigned int> list1, list2; 
      for (unsigned int y = 0; y != tPairs.cols(); y++){ 
        if ( std::abs( rtPairs(0,y) - rxygrid(0,i) ) <= bw(0)  ) {
          list1.push_back(y);
        }         
        if ( std::abs( rtPairs(1,y) - rxygrid(1,i) ) <= bw(1)  ) {
          list2.push_back(y);
        }
      }
      
    //get intersection between the two lists 
    std::set_intersection(list1.begin(), list1.begin() + list1.size(), list2.begin(), list2.begin() + list2.size(), std::back_inserter(indx));   
  
    } else { // just get the whole deal
      for (unsigned int y = 0; y != tPairs.cols(); ++y){
        indx.push_back(y);
      }
    }   

    unsigned int indxSize = indx.size();
    Eigen::VectorXd lw(indxSize);  
    Eigen::VectorXd ly(indxSize);
    Eigen::MatrixXd lx(2,indxSize);
    for (unsigned int u = 0; u !=indxSize; ++u){ 
      lx.col(u) = rtPairs.col(indx[u]); 
      lw(u) = win(indx[u]); 
      ly(u) = cxxn(indx[u]); 
    }


    if (ly.size()>=npoly+1 && !bwCheck ){

      //computing weight matrix 
      Eigen::VectorXd temp(indxSize);
      Eigen::MatrixXd llx(2, indxSize );  
      llx.row(0) = (lx.row(0).array() - rxygrid(0,i))/bw(0);  
      llx.row(1) = (lx.row(1).array() - rxygrid(1,i))/bw(1); 
 
      //define the kernel used 
      switch (KernelName){
        case 1: // Epan
          temp=  ((1-llx.row(0).array().pow(2))*(1- llx.row(1).array().pow(2))).array() * 
                 ((9./16)*lw).transpose().array(); 
          break;  
        case 2 : // Rect
          temp=(lw.array())*.25 ; 
          break;
      case 3 : // Gauss
          temp = ((-.5*(llx.row(1).array().pow(2))).exp()) * invSqrt2pi  *   
                 ((-.5*(llx.row(0).array().pow(2))).exp()) * invSqrt2pi  *
                 (lw.transpose().array()); 
          break;
      case 4 : // GausVar
          temp = (lw.transpose().array()) * 
                 ((-0.5 * llx.row(0).array().pow(2)).array().exp() * invSqrt2pi).array() *
                 ((-0.5 * llx.row(1).array().pow(2)).array().exp() * invSqrt2pi).array() * 
                  (1.25 - (0.25 * (llx.row(0).array().pow(2))).array())  * 
                  (1.50 - (0.50 * (llx.row(1).array().pow(2))).array()); 
          break;
        case 5 :  // Quar
          temp = (lw.transpose().array()) * 
                 ((1.-llx.row(0).array().pow(2)).array().pow(2)).array() *
                 ((1.-llx.row(1).array().pow(2)).array().pow(2)).array() * (225./256.);
          break;
      } 
      
      // make the design matrix
      Eigen::MatrixXd X(indxSize ,3);
      X.setOnes();    
      X.col(1) = (lx.row(0).array() - rxygrid(0,i)).array().pow(2);
      X.col(2) = (lx.row(1).array() - rxygrid(1,i)); 
      Eigen::LDLT<Eigen::MatrixXd> ldlt_XTWX(X.transpose() * temp.asDiagonal() *X);
      Eigen::VectorXd beta = ldlt_XTWX.solve(X.transpose() * temp.asDiagonal() * ly);
      mu(i)=beta(0); 
    } else if ( ly.size() == 1 && !bwCheck) { // Why only one but not two is handled?
      mu(i) = ly(0);
    } else if ( ly.size() != 1 && (ly.size() < npoly+1) ) {
      if ( bwCheck ){
        Eigen::VectorXd checker(1); 
        checker(0) = 0.; 
        return(checker);
      } else {  
        Rcpp::stop("No enough points in local window, please increase bandwidth.");
      }
    }
  } 
  
  if (bwCheck){
     Eigen::VectorXd checker(1); 
     checker(0) = 1.; 
     return(checker);
  }
  
  return ( mu ); 
}