// [[Rcpp::export]]
SEXP eval_hessian_lambda_delta_theta1_cpp(SEXP deltain , SEXP  theta1 ,SEXP wdcMergedday , SEXP points,
         SEXP no_st, SEXP max_walking_dis,
         SEXP v0_vec, SEXP wdc_sto_state_local_in, 
         SEXP wdc_local_stations_in, SEXP points_local_stations_in,
         SEXP lambda_multiplers_in) {
 
  //try {
    std::vector<string> wdc_sto_state_local = Rcpp::as< std::vector<string> >(wdc_sto_state_local_in); 
    std::vector<string> wdc_local_stations = Rcpp::as< std::vector<string> >(wdc_local_stations_in); 
    std::vector<string> points_local_stations = Rcpp::as< std::vector<string> >(points_local_stations_in);    
    NumericVector deltain_r(deltain);
    colvec xdeltain(deltain_r.begin(),deltain_r.size(),true);
    NumericVector xtheta1(theta1);
    NumericMatrix xwdcMergedday(wdcMergedday);
    NumericMatrix xpoints_temp(points);
    arma::mat xpoints(xpoints_temp.begin(), xpoints_temp.nrow(), xpoints_temp.ncol(), 
                      true);  

    uint min_points_col = 2;
    uint max_points_col = xpoints.n_cols-1;
    assert(max_points_col-min_points_col==xtheta1.size()-2); //to assert other points covariates supplied correspond to density vector.
    
    int xno_st = as<int>(no_st); 
    double xmax_walking_dis = as<double>(max_walking_dis);
    NumericVector xv0_vec(v0_vec);
    NumericVector lambda_multiplers(lambda_multiplers_in);
    assert(lambda_multiplers.size()==xwdcMergedday.nrow());
    double beta1 = xtheta1(0);
    double sigma0 = xtheta1(1);
    
    uint wdclat1_col = 3;
    uint wdclon1_col = 4;
    uint wdcobswt_col = 5;
    uint wdcstation_id_index_col = 2;
    
    NumericVector lat1_r = xwdcMergedday(_,wdclat1_col);
    NumericVector lon1_r = xwdcMergedday(_,wdclon1_col);
    NumericVector wdcobswt_r = xwdcMergedday(_,wdcobswt_col);      
    colvec lat1(lat1_r.begin(),lat1_r.size(),true);
    colvec lon1(lon1_r.begin(),lon1_r.size(),true);
    colvec wdcobswt(wdcobswt_r.begin(),wdcobswt_r.size(),true);
        
    mat hessian_theta1_delta(xtheta1.size(),xwdcMergedday.nrow(),fill::zeros);
    
    uint pointslat1_col = 0;
    uint pointslon1_col = 1;
    
    arma::mat xwdcmat(xwdcMergedday.begin(), xwdcMergedday.nrow(), xwdcMergedday.ncol(), 
                      true);  
    
    uvec station_id_index_r = conv_to< uvec >::from(xwdcmat.col(wdcstation_id_index_col));
    station_id_index_r -=1; //subtracting 1 to create 0 based indexes in c++
    mat station_data_all = xwdcmat.rows(unique_idx(station_id_index_r));
    
    //station_data_all <- unique(wdcMerged[,c("station_id","lat","lon","station_id_index")])
    
    for(uint i=0;i<xpoints.n_rows;i++) {
    //  cout << "point no" << i << endl;
    // for(uint i=0;i<1;i++) {
    //     cout << "only one point: " << endl;
        colvec dis_vIdx = latlondistance(lat1, lon1, 
                                         xpoints(i,pointslat1_col), xpoints(i,pointslon1_col));
        // ref for find - http://arma.sourceforge.net/docs.html#find
//        uvec list_obs = find(dis_vIdx <=xmax_walking_dis);
//        if(list_obs.size()==0) continue;
//        print_vec(list_obs);
        
        
        //for the observations that are within range of points, 
        //find the list of states of stations in neighbourhood of points
        //compute share of points for each of those states and add to correponding lambda
        //list of stations near point
        //uvec st_point_list = conv_to<uvec>::from(split(points_local_stations[i],'_'));
        vector<int> st_point_list_org = (split(points_local_stations[i],'_'));
        vector<int> st_point_list = st_point_list_org;
        for(uint j=0; j<st_point_list.size();++j) {
          st_point_list[j] -=1; //subtracting 1 to create 0 based indexes in c++
        }
        
        uvec list_obs = which_r(conv_to< Vi >::from(station_id_index_r),st_point_list);
        //print_vec(list_obs);
        //st_point_list = st_point_list - vector<int>(st_point_list.size(),fill::ones); //subtracting 1 to create 0 based indexes in c++
        //alternatively could select list_obs from st_point_list instead of calculating distances above
        
        umat mat_st_state(list_obs.size(),st_point_list.size());
        imat obs_st_state(list_obs.size(),st_point_list.size());
        uvec st_point_list_uvec = conv_to<uvec>::from(st_point_list);        

        //for each station compute the states of local stations of points 
        for(uint j=0; j<list_obs.size();++j) {
          //for(uint j=0; j<1;++j) {
          vector<int> j_loc_st = (split(wdc_local_stations[list_obs(j)],'_'));
          uvec j_st_state = conv_to<uvec>::from(split(wdc_sto_state_local[list_obs(j)],'_'));
          uvec Idx = conv_to<uvec>::from(which_r(j_loc_st, st_point_list_org));
          mat_st_state.row(j) = conv_to<urowvec>::from(j_st_state.rows(Idx));            
          irowvec obs_st_state_row(st_point_list.size());
          obs_st_state_row.fill(-1); // -1 serves a equivalent of NA in R
          uint st_id_temp = station_id_index_r(list_obs(j));
          
          vector<int> st_vec(1);
          st_vec[0] = st_id_temp;
          assert(which_r(st_point_list,st_vec).size()==1);
          obs_st_state_row(which_r(st_point_list,st_vec)[0]) = list_obs(j);
          obs_st_state.row(j) = obs_st_state_row;
          //print_vec(conv_to<vec>::from(obs_st_state.row(j)));
          //join_cols(mat_st_state1,j_st_state.rows(Idx));
          //mat_st_state <- rbind(mat_st_state,j_st_state[which(j_loc_st %in% st_point_list)])
        }
        vector<string> mat_st_state_str = covert_row_str(mat_st_state);
        vector<string> mat_st_state_str_unq = unique_str(mat_st_state_str);        
        
        for(uint j=0; j< mat_st_state_str_unq.size(); ++j) {
        //for(uint j=0; j< 1; ++j) {
          vector<string> str_vec(1);
          str_vec[0] = mat_st_state_str_unq[j];          
          //cout << which_r_str(mat_st_state_str,str_vec) << endl;
          imat a = obs_st_state.rows(which_r_str(mat_st_state_str,str_vec));
          urowvec mat_st_state_row = mat_st_state.row(which_r_str(mat_st_state_str,str_vec)[0]);
          //cout << a << endl;
          //now for each column of a remove the -1's and get the expanded grid
          //convert to vector of vectors from columns of a, remove -1 
          //and then apply the recursive strategy to create all combinations
          vector< vector<int> > a_vec;
          urowvec col_na(st_point_list.size(),fill::zeros);
          for(uint k=0; k <a.n_cols; ++k) {
            //cout << a.col(k)(find(a.col(k)>=0)) << endl;
            ivec a_sub = a.col(k);
            vector<int> a_vec_elem = conv_to< vector<int> >::from(a_sub.elem(find(a_sub>=0)));
            //if a_vec_elem is empty add the first element of that station_id to this 
            //also make correponding entry in col_na =1, which will restrict us from updating those rows, but only
            //use those delta;s for computation of other station probabilities

            if(a_vec_elem.size()==0) {
              uint st_k = which_r(conv_to< vector<int> >::from(station_id_index_r),
              vector<int>(1,st_point_list[k]))[0];
              a_vec_elem.push_back(st_k);
              col_na(k) = 1;
            }
            a_vec.push_back(a_vec_elem);            
          }


          //create prob_a to store probabilities of observatiosn corresponding to 
          //obs_no in a_vec and           
          vector< vector<double> > prob_a;
          vector< vector<double> > delta_a;
          for(uint k=0; k <a_vec.size(); ++k) {
            uvec a_vec_col = conv_to<uvec>::from(a_vec[k]);
            //get obs_wt corresponding to this vector
            colvec obs_wt_col = wdcobswt.elem(a_vec_col);
            colvec prob_col = obs_wt_col/sum(obs_wt_col);
            prob_a.push_back(conv_to< vector<double> >::from(prob_col));
            colvec delta_col = xdeltain.elem(a_vec_col);
            delta_a.push_back(conv_to< vector<double> >::from(delta_col));
          }

          rowvec delta_avg(st_point_list.size(),fill::zeros);
          for(uint k=0; k <a_vec.size(); ++k) {
            uvec a_vec_col = conv_to<uvec>::from(a_vec[k]);
            colvec delta_col = xdeltain.elem(a_vec_col);
            colvec prob_a_col = conv_to<colvec>::from(prob_a[k]);
            delta_avg(k) = sum(delta_col % prob_a_col);  //this is wrong as it woudl a do a term by term prod without summing
          }

          //and prob_table by expanding similar to obs_no_table          
//          Vvd prob_table;
//          Vd outputTemp2;
//          cart_product(prob_table, outputTemp2, prob_a.begin(), prob_a.end());          
          //now for each row of delta_table compute the probabilities for each station and gradients,
          //multiply them with weights from
          //prob_table and add to corresponding row.
          mat station_data = station_data_all.rows(st_point_list_uvec);
                              
          for(uint k=0; k <a_vec.size(); ++k) {
            if(col_na(k)==0) {
            uvec a_vec_col = conv_to<uvec>::from(a_vec[k]);
            for(uint l=0; l <a_vec_col.size(); ++l) {
              rowvec deltain_row = delta_avg;

              deltain_row(k) = delta_a[k][l];
           
              if(lambda_multiplers(a_vec[k][l])==0) continue;

              mat hessian_theta1_delta_kl = compute_hessian_theta1_delta_weighted(i, station_data, wdclat1_col, wdclon1_col, xpoints(i,pointslat1_col), 
                xpoints(i,pointslon1_col), beta1, sigma0, xdeltain, st_point_list_uvec, deltain_row, mat_st_state_row,  
              xv0_vec, k, xtheta1.size(), xpoints(i, min_points_col), xpoints(i,span(min_points_col+1,max_points_col)));
              //multiply with observation wt & lambda_multiplers_in(a_vec[k][l])
              
              hessian_theta1_delta_kl *=  wdcobswt(a_vec[k][l])*lambda_multiplers(a_vec[k][l]);
              
              //need to expand hessian_delta_sq_kl to reflect gradients wrt
              //a_vec columns to reflect the deltaaveraged gradients.
              //test in a seperate Rcpp file how to repeat rows and columns and then 
              //multiply rows and columns with prob_a values.
              //creating version of a_vec and prob_a which have the focal station 
              //with only one entry and rest of the stations with actual list.
              vector< vector<double> > prob_a_temp = prob_a;
              vector<double> temp_vec1(1); temp_vec1[0]=1;
              prob_a_temp[k] = temp_vec1;
              vector< vector<int> > a_vec_temp = a_vec;
              vector<int> temp_vec2(1); temp_vec2[0]=a_vec[k][l];
              a_vec_temp[k] = temp_vec2;
              //cout << "simplify above lines, there should be way of direclty assigning\
              //instead of creating temp vecs" << endl; 
              //unlisting above lists
              vector<int> a_vec_unlisted;
              vector<double> prob_a_unlisted;
              //create list of hessian_delta_sq_kl indexes to expand
              uvec hessian_expand_index;

              for(uint m=0; m <prob_a_temp.size(); ++m) {  
                uvec hessian_expand_index_temp(prob_a_temp[m].size());
                hessian_expand_index_temp.fill(m);
                hessian_expand_index.insert_rows( hessian_expand_index.size(), hessian_expand_index_temp ); 
                a_vec_unlisted.insert(a_vec_unlisted.end(),a_vec_temp[m].begin(),a_vec_temp[m].end());
                prob_a_unlisted.insert(prob_a_unlisted.end(),prob_a_temp[m].begin(),prob_a_temp[m].end());                
              }              
              mat weights_mat(prob_a_unlisted.size(),prob_a_unlisted.size(),fill::zeros);
              weights_mat.diag()  = conv_to<vec>::from(prob_a_unlisted);
              mat hessian_theta1_delta_kl_expanded = hessian_delta_sq_kl_expanded.cols(hessian_expand_index);
              //hessian_delta_sq_kl_expanded = hessian_delta_sq_kl_expanded.cols(hessian_expand_index);
              hessian_theta1_delta_kl_expanded = hessian_theta1_delta_kl_expanded * weights_mat;
              uvec a_vec_unlisted_uvec = conv_to<uvec>::from(a_vec_unlisted);
              hessian_theta1_delta.cols(a_vec_unlisted_uvec) += hessian_theta1_delta_kl_expanded;
            }
            }
          }

        }
    }//end of points loop  

    return(wrap(hessian_theta1_delta));  
      
}
Esempio n. 2
0
TEST_F(FileMatchTrieTest, EmptyTrie) {
  EXPECT_TRUE(find("//net/some/path").empty());
}
Esempio n. 3
0
TEST_F(FileMatchTrieTest, RootElementDifferent) {
  Trie.insert("//net/path/file.cc");
  Trie.insert("//net/otherpath/file.cc");
  EXPECT_EQ("//net/path/file.cc", find("//net/path/file.cc"));
}
Esempio n. 4
0
TEST_F(FileMatchTrieTest, ReturnsBestResults) {
  Trie.insert("//net/d/c/b.cc");
  Trie.insert("//net/d/b/b.cc");
  EXPECT_EQ("//net/d/b/b.cc", find("//net/d/b/b.cc"));
}
Esempio n. 5
0
TEST_F(FileMatchTrieTest, ReportsSymlinkAmbiguity) {
  Trie.insert("//net/Aa/file.cc");
  Trie.insert("//net/aA/file.cc");
  EXPECT_TRUE(find("//net/aa/file.cc").empty());
  EXPECT_EQ("Path is ambiguous", Error);
}
Esempio n. 6
0
extern int main(int argc, char *argv[])
{
  unsigned i;
  Addr base, limit;
  mps_arena_t mpsArena;
  Arena arena; /* the ANSI arena which we use to allocate the BT */
  CBSStruct cbsStruct;
  CBS cbs;
  void *p;
  Addr dummyBlock;
  BT allocTable;
  Size size;
  Bool high;
  CBSFindDelete findDelete = CBSFindDeleteNONE;

  randomize(argc, argv);

  NAllocateTried = NAllocateSucceeded = NDeallocateTried =
    NDeallocateSucceeded = NNewBlocks = NDeleteBlocks =
    NGrowBlocks = NShrinkBlocks = 0;

  clearExpectations();

  die(mps_arena_create(&mpsArena, mps_arena_class_vm(), testArenaSIZE),
      "mps_arena_create");
  arena = (Arena)mpsArena; /* avoid pun */

  die((mps_res_t)BTCreate(&allocTable, arena, ArraySize),
      "failed to create alloc table");

  die((mps_res_t)CBSInit(arena, &cbsStruct, NULL, &cbsNewCallback,
                         &cbsDeleteCallback, &cbsGrowCallback,
                         &cbsShrinkCallback, MinSize,
                         Alignment, TRUE, TRUE),
      "failed to initialise CBS");
  cbs = &cbsStruct;

  BTSetRange(allocTable, 0, ArraySize); /* Initially all allocated */

  /* We're not going to use this block, but I feel unhappy just */
  /* inventing addresses. */
  die((mps_res_t)ControlAlloc(&p, arena, ArraySize * Alignment,
                              /* withReservoirPermit */ FALSE),
      "failed to allocate block");
  dummyBlock = (Addr)p; /* avoid pun */

  printf("Allocated block [%p, %p)\n", (void*)dummyBlock,
         (char *)dummyBlock + ArraySize);

  checkCBS(cbs, allocTable, dummyBlock);
  for(i = 0; i < NOperations; i++) {
    switch(cbsRnd(3)) {
    case 0: {
      randomRange(&base, &limit, allocTable, dummyBlock);
      allocate(cbs, dummyBlock, allocTable, base, limit);
    } break;
    case 1: {
      randomRange(&base, &limit, allocTable, dummyBlock);
      deallocate(cbs, dummyBlock, allocTable, base, limit);
    } break;
    case 2: {
      size = cbsRnd(ArraySize / 10) + 1;
      high = cbsRnd(2) ? TRUE : FALSE;
      switch(cbsRnd(6)) {
      case 0:
      case 1:
      case 2: findDelete = CBSFindDeleteNONE; break;
      case 3: findDelete = CBSFindDeleteLOW; break;
      case 4: findDelete = CBSFindDeleteHIGH; break;
      case 5: findDelete = CBSFindDeleteENTIRE; break;
      }
      find(cbs, dummyBlock, allocTable, size, high, findDelete);
    } break;
    }
    if (i % 5000 == 0)
      checkCBS(cbs, allocTable, dummyBlock);
  }

  checkExpectations();

  /* CBSDescribe prints a very long line. */
  /* CBSDescribe(cbs, mps_lib_get_stdout()); */

  printf("\nNumber of allocations attempted: %ld\n", NAllocateTried);
  printf("Number of allocations succeeded: %ld\n", NAllocateSucceeded);
  printf("Number of deallocations attempted: %ld\n", NDeallocateTried);
  printf("Number of deallocations succeeded: %ld\n", NDeallocateSucceeded);
  printf("Number of new large blocks: %ld\n", NNewBlocks);
  printf("Number of deleted large blocks: %ld\n", NDeleteBlocks);
  printf("Number of grown large blocks: %ld\n", NGrowBlocks);
  printf("Number of shrunk large blocks: %ld\n", NShrinkBlocks);
  printf("\nNo problems detected.\n");
  return 0;
}
Esempio n. 7
0
TEST_F(FileMatchTrieTest, InsertingRelativePath) {
  Trie.insert("//net/path/file.cc");
  Trie.insert("file.cc");
  EXPECT_EQ("//net/path/file.cc", find("//net/path/file.cc"));
}
std::string WizardImpl::searchForSpell(std::string const &wish) {
	auto const spell = find(begin(books), end(books), wish);
	return spell!=end(books)?*spell:"";
}
Potion WizardImpl::mixPotion(std::string const &recipe) {
	auto const potion = find(begin(potions), end(potions), recipe);
	return potion!=end(potions)?*potion:"";
}
Esempio n. 10
0
void fp_directory::del(fp_node *node){

	del(find(node));
}
Esempio n. 11
0
fp_item* fp_directory::get_item(fp_node *node) const {
	return find(node);
}
void Adafruit_ESP8266::closeTCP(void) {
  println(F("AT+CIPCLOSE"));
  find(F("Unlink\r\n"));
}
void Adafruit_ESP8266::closeAP(void) {
  println(F("AT+CWQAP")); // Quit access point
  find(); // Purge 'OK'
}
Esempio n. 14
0
int main()
{
	int t,n,i,j,k,p,s,e,x,y,c,ans,f,d;

	for(i=0;i<100;i++)
		check[i]=0;
	prime[0]=2;
	c=genprime(1000000);
//	printf("%d\n",prime[c-1]);
//	printf("%d\n",c);
//	for(i=0;i<c;i++)
//		printf("%d ",prime[i]);
//	printf("\n");

	scanf("%d",&t);
	while(t--)
	{
		scanf("%d %lld %d",&n,&m,&p);
		for(i=1;i<=n;i++)
		{
			scanf("%d",&tazo[i]);
			a[i].root=i;
			a[i].wt=tazo[i];
			a[i].count=1;
		}
		for(i=0;i<m;i++)
		{
			scanf("%d %d",&s,&e);

			x=find(s);
			y=find(e);
//			printf("%d %d\n",x,y);
			if(x!=y)
			{
				unionset(x,y);
			}
		}
		ans=0;
		for(i=1;i<=n;i++)
		{
//			printf("%d %d %d %d\n",i,a[i].root,a[i].wt,a[i].count);
			if(a[i].root==i)
			{
				f=0;
				d=(a[i].wt+p);
				for(j=0;j<c;j++)
				{
					if(d==prime[j])
					{
						f=1;
						break;
					}
				}
//				printf("f : %d\n",f);
				if(f==1)
				{
					ans++;
				}
			}
		}
		printf("%d\n",ans);
	}
	
	return 0;
}
void ShortestPath::CalculateShortestPath() {

	//The number of vertices in the graph.
	const unsigned int NumVertices = m_Graph -> getNumVertices();

	//The graph's adjacency matrix.
	double** ParentMatrix = m_Graph -> getMatrix();

	//Vector that stores the distance between the current vertices and the remaing vertices in the graph.
	vector<double> Distance(NumVertices , c_INFINITY);

	//Vector that stores the predecesor of each vertex.  Used to determine the path.
	vector<unsigned int> Predecessor(NumVertices , -1);

	//Vector that states if a vertex has been traversed before in the path or not.
	vector<unsigned int> Used;

	//The current vertex.
	unsigned int CurrentVertex;

	//A flag that states if the algorithm changed the path or not.  If not then the algorithm terminates.
	bool Change;
				 
	//Initialization.
	Distance[m_Source] = 0.0;
	m_Cost = 0.0;
	Predecessor[m_Source] = m_Source;
	CurrentVertex = m_Source;
	Used.push_back(m_Source);
	m_Path.clear();
	
	
	do {
		Change = false;

		//DO IT FOR ADJACENT ONLY.
		for(unsigned int j = 0; j < NumVertices; ++j) {
			if( Distance[CurrentVertex] + ParentMatrix[CurrentVertex][j] <  Distance[j] ) {
				Change = true;
				Distance[j] = Distance[CurrentVertex] + ParentMatrix[CurrentVertex][j];
				Predecessor[j] = CurrentVertex;
			}
		}
		
		//Find the next current vertex which is the minimum vector in Distance and not in Used.
		vector<double>::iterator MinimumLoc;
		MinimumLoc = Distance.begin();

		bool FirstElement = true;
		do {  
			if( (!FirstElement))
				MinimumLoc++;
			MinimumLoc = min_element(MinimumLoc, Distance.end()-1);
			FirstElement = false;
		}
		while( find(Used.begin(), Used.end(), MinimumLoc - Distance.begin() ) != Used.end());
		
		CurrentVertex = MinimumLoc - Distance.begin();
		Used.push_back(CurrentVertex);

		//Reached the destination vertex.
		if(CurrentVertex == m_Destination)
			break;

		//If the current vertex is INIFINTELY away from the source vertex,
		//then no path exists between the source and destination vertices.
		if(Distance[CurrentVertex] == c_INFINITY)
			throw NoPathFound( GraphUtils::getVertexName(*m_Graph, m_Source), GraphUtils::getVertexName(*m_Graph, m_Destination) );
		
	} while( (Change == true) && (Used.size() != NumVertices -1) );

	//Find the path from the destination to the source, by following the
	//Predecessor of the destination until you reach the source.
	cout<<"Path is: ";
	unsigned int lol = m_Destination;
	m_Path.push_back(m_Destination);
	do {
		lol = Predecessor[lol];
		m_Path.push_back(lol);
	}while(lol != m_Source);
	
	//The path is stored in reverse order, so reverse it to get the right
	//order.
	reverse(m_Path.begin(), m_Path.end());

	vector<unsigned int>::const_iterator LookAhead;
	//Dump the path and the cost.
	for(vector<unsigned int>::const_iterator L = m_Path.begin(); L != m_Path.end(); ++L) {

		//Get the next vertex in the path.
		LookAhead = L;
		if( (++LookAhead) != m_Path.end() )
			m_Cost += GraphUtils::getEdgeWeight(*m_Graph, *L, *LookAhead);

		cout << *L << " ";
	}
#if DEBUG
	cout << endl << "Cost of path: " << m_Cost << endl;
#endif
		
}
Esempio n. 16
0
void balance() {
	if (tot == 0) return;
	int old = med;
	med = val[find((tot + 1) / 2) + 1];
	if (med > old) dist -= 2ll * (med - old);
}
Esempio n. 17
0
/**
 * This function should compress paths, and works as described
 * in lecture.
 */
int DisjointSets::find(int a)
{
	if(elems[a]<0) return a;
	return elems[a] = find(elems[a]);
}
Esempio n. 18
0
	bool isExist(int value, Set *&curSet)
	{
		return (find(value, curSet->root) != NULL);
	}
Esempio n. 19
0
bool inset(Tile *t,tiles &set)
{
    return set.end()!=find(set.begin(),set.end(),t);
};
Esempio n. 20
0
NodeList* Pathfinder::PathBetweenPoints(int x1, int y1, int x2, int y2) {

	// Set up all the data structures we need, lots o' stuff
	NodeList Q;
	PreviousNodeMap prev;
	PopulateListWithNodes(Q);
	Node* source = m_nodeMap[x1][y1];
	Node* dest = m_nodeMap[x2][y2];
	// Make sure source and dest are in Q
	if(find(Q.begin(), Q.end(), source) == Q.end()) {
		Q.push_back(source);
	}
	if(find(Q.begin(), Q.end(), dest) == Q.end()) {
		Q.push_back(dest);
	}
	ResetNodes(Q, x2, y2);
	source->SetDistance(0);

	while(Q.size() > 0) {
		Q.sort(NodesByScore);
		Node* u = Q.front();
		if(u == dest) {
			// found our node, break!
			break;
		}
		if(u->GetDistance() == NODE_INFINITY) {
			// In this case, no valid path from point 1 to point 2
			return NULL;
		}

		// Remove it from the unvisited queue
		Q.remove(u);

		// Update its neighbors
		int x = u->GetX();
		int y = u->GetY();

		if(x - 1 >= 0 && m_nodeMap[x-1][y]) {
			Node* toUpdate = m_nodeMap[x-1][y];
			if(u->GetDistance() + 1 < toUpdate->GetDistance()) {
				prev[toUpdate] = u;
				toUpdate->SetDistance(u->GetDistance() + 1);
			}
		}
		if(x + 1 < m_currentLevel->GetWidth() && m_nodeMap[x+1][y]) {
			Node* toUpdate = m_nodeMap[x+1][y];
			if(u->GetDistance() + 1 < toUpdate->GetDistance()) {
				prev[toUpdate] = u;
				toUpdate->SetDistance(u->GetDistance() + 1);
			}
		}
		if(y - 1 >= 0 && m_nodeMap[x][y-1]) {
			Node* toUpdate = m_nodeMap[x][y-1];
			if(u->GetDistance() + 1 < toUpdate->GetDistance()) {
				prev[toUpdate] = u;
				toUpdate->SetDistance(u->GetDistance() + 1);
			}
		}
		if(y + 1 < m_currentLevel->GetHeight() && m_nodeMap[x][y+1]) {
			Node* toUpdate = m_nodeMap[x][y+1];
			if(u->GetDistance() + 1 < toUpdate->GetDistance()) {
				prev[toUpdate] = u;
				toUpdate->SetDistance(u->GetDistance() + 1);
			}
		}
	}
	// Prep the list of path nodes to send back
	NodeList* toReturn = new NodeList();
	Node* next = prev[dest];
	toReturn->push_back(next);
	while(prev.find(next) != prev.end() && prev[next] != source) {
		next = prev[next];
		toReturn->push_back(next);
	}

	return toReturn;

}
Esempio n. 21
0
TEST_F(FileMatchTrieTest, MatchingRelativePath) {
  EXPECT_EQ("", find("file.cc"));
}
Esempio n. 22
0
 vector<vector<int> > pathSum(TreeNode *root, int sum) {
     vector<vector<int> > result;
     vector<int> sol;
     find(root,sum,result,sol);
     return result;
 }
Esempio n. 23
0
TEST_F(FileMatchTrieTest, HandlesSymlinks) {
  Trie.insert("//net/AA/file.cc");
  EXPECT_EQ("//net/AA/file.cc", find("//net/aa/file.cc"));
}
Esempio n. 24
0
	bool Configure::exists(const wstring &name) const
	{
		return find(name) != confMap.end();
	}
Esempio n. 25
0
TEST_F(FileMatchTrieTest, LongerMatchingSuffixPreferred) {
  Trie.insert("//net/src/Aa/file.cc");
  Trie.insert("//net/src/aA/file.cc");
  Trie.insert("//net/SRC/aa/file.cc");
  EXPECT_EQ("//net/SRC/aa/file.cc", find("//net/src/aa/file.cc"));
}
Esempio n. 26
0
SEXP getExceptional( int *G_edges, int G_nnodes, 
		int M_Min_nnodes, int M_Max_nnodes, 
		int *NodeToClass, double *Pi, int NbrClasses, 
		double PValue, int Directed, 
		int &n_prot) {
  //
  // Get all occurrences of size k = M_nnodes
  //

  //
  //  Find all motif with size k
  //
  FindMotif find( StoreMode, 0);
  FindMotif f( CountMode, 0);

  vector<int*> *list;
  SparseAdjacency G( G_edges, G_nnodes, true );
  // G.print( "G");
  SparseAdjacency H( G_edges, G_nnodes, ! Directed  );
  // H.print( "H");

  SEXP S_ReturnList; 

  // All components are store even if they are NULL
  PROTECT( S_ReturnList = allocVector( VECSXP, 
				   M_Max_nnodes - M_Min_nnodes + 1)); n_prot++;

  // Index in the Returned list
  int i_k = 0;

  /// Previous non NULL value of k index
  int prev_k_index = -1;

  for ( int k= M_Min_nnodes; k <= M_Max_nnodes; k++, i_k++) {

    // To optimize the motifs
    // int perm_0[k-1];
    int *perm_0 = new int[k];
    int *perm_1 = new int[k];

    SEXP S_Result; 

    // Occurence list 'list' must be deallocated"
    // Doesn't belong to 'find'
    // TODO To improve
    find.clearFoundList();
    list = find.findAllMotifs( G, k ); 
    
    S_Result = sort_m_mp_u( H, G_nnodes, k, list, 
			    Pi, NodeToClass, NbrClasses, 
			    0, -1,
			    PValue,
			    n_prot, false );

    if ( S_Result != R_NilValue ) {
      // Store k value
      SEXP S_k;
      PROTECT( S_k = allocVector( INTSXP, 1) ); n_prot++; 	  
      int *p_k = INTEGER_POINTER( S_k );
      p_k[0] = k;

      SEXP S_Struct; 
      PROTECT( S_Struct = allocVector( VECSXP, 2 ));  n_prot++;;
      SET_VECTOR_ELT( S_Struct, 0, S_k ); 
      SET_VECTOR_ELT( S_Struct, 1, S_Result ); 
      SET_VECTOR_ELT( S_ReturnList, i_k, S_Struct );

      SEXP S_Adj_1 = VECTOR_ELT( S_Result, 0 ); 
      int MotifNbr_1 = LENGTH( S_Adj_1 );

      // Skip First motif
      // if ( prev_k_index != -1 ) {

      for ( int k_index = 0; k_index <= (prev_k_index); k_index++ ) {

	SEXP S_k_value = VECTOR_ELT( 
				    VECTOR_ELT( S_ReturnList, 
						k_index ), 
				    0 );
	int prev_k_value = INTEGER_POINTER( S_k_value ) [0];
 
	// Get Adjacency matrix with i-1 nodes
	SEXP S_Adj_0 = VECTOR_ELT( 
				  VECTOR_ELT( 
					     VECTOR_ELT( S_ReturnList, 
							 k_index ), 
					     1 ), 
				  0);
	// Get M_list 
	SEXP S_m_0 = VECTOR_ELT( 
				VECTOR_ELT( 
					   VECTOR_ELT( S_ReturnList,
						       k_index ), 
					   1 ), 
				1);

	int MotifNbr_0 = LENGTH( S_Adj_0 );


	for(int m = 0; m <  MotifNbr_0; m++ ) {

	  // Test NULL SEXP
	  if( VECTOR_ELT(S_Adj_0, m) !=  R_NilValue ) {
	    // int debug = LENGTH( VECTOR_ELT(S_Adj_0, m) );
	    int *adj_0 =  INTEGER_POINTER( VECTOR_ELT(S_Adj_0, m) );
	    // printList( "canonic ", adj_0, adj_0+ (k-1)*(k-1), " ", true); 

	    SparseAdjacency motif0( adj_0, prev_k_value, "dense", (Directed == 0) );
	    SparseAdjacency motif0_canon( motif0 );
	    motif0.optimizeConnexity( perm_0 );

	    // motif0.print( "motif opt 0" );
	    // printList( " perm 0 ", perm_0, perm_0 + (k-1), true );

	    // Number of Del class
	    SEXP S_m_mp_0 = VECTOR_ELT( S_m_0, m );
	    int m_mp_len_0 = LENGTH( S_m_mp_0 );
	    int *del_class_0 = new int[ m_mp_len_0 ];

	    // get the first node ID of the del class
	    getDelClassNode( S_m_mp_0, m_mp_len_0, del_class_0 );
	       

	      // printList( "Del class 0 ", del_class_0, 
	      //	   del_class_0 + m_mp_len_0, " ", true);
 
	      // Get Degree of delete node
	      // int deg_in_0  = 0;
	      // int deg_out_0 = 0;

	      for(int p = 0; p <  MotifNbr_1; p++ ) {

		// Test NULL SEXP
		if( VECTOR_ELT(S_Adj_1, p) !=  R_NilValue ) {

		  //		  int debug_1 = LENGTH( VECTOR_ELT(S_Adj_1, p) );
		  int *adj_1  = INTEGER_POINTER( VECTOR_ELT(S_Adj_1, p) );


#if            ( MSG > 0 )
		  printList( "canonic 1 ", adj_1, adj_1 + (k)*(k), " ", true); 
#endif

		  SparseAdjacency motif1( adj_1, k, "dense", (Directed == 0) );
		  SparseAdjacency motif1_canonic( motif1 );

		  motif1.optimizeConnexity( perm_1 );

		  // get M List
		  SEXP S_m_1 = VECTOR_ELT( 
					  VECTOR_ELT( 
						     VECTOR_ELT( S_ReturnList, 
								 i_k ), 
						     1 ), 
					  1);

		  // Number of Del class
		  SEXP S_m_mp_1 = VECTOR_ELT( S_m_1, p );
		  int m_mp_len_1 = LENGTH( S_m_mp_1 ) ; 
		  int *del_class_1 = new int [ m_mp_len_1 ];

		  // get the first node ID of the del class
		  getDelClassNode( S_m_mp_1, m_mp_len_1, del_class_1 ); 
	  
		    // printList( "Del class 1 ", del_class_1, 
		    //	     del_class_1 + m_mp_len_1, " ", true); 
	    
		    // printList( "canonic ", adj_0, adj_0 + (k-1)*(k-1), " ", true); 
		    // printList( "canonic ", adj_1, adj_1 + (k)*(k), " ", true); 
	    

		    for( int del_0 = 0;  del_0 <  m_mp_len_0; del_0++) {

		      if( del_class_0[del_0] >= 0 ) {
			// Get Degree of delete node
			int deg_in_0  = 0;
			int deg_out_0 = 0;
			if ( Directed ) {
			  deg_in_0  = motif0_canon.getRowSize( del_class_0[ del_0 ] );
			  deg_out_0 = motif0_canon.getColSize( del_class_0[ del_0] );
			} else {
			  deg_in_0  = motif0_canon.getAllRowSize( del_class_0[ del_0 ] );
			}
	      
			for( int del_1 = 0;  del_1 <  m_mp_len_1; del_1++) {
			  if( del_class_1[ del_1 ] >= 0 ) {		    
			    if( getPValue( S_m_mp_1, del_1 ) <= PValue ) {
		      
			      if( getPValue( S_m_mp_0, del_0 ) <= PValue ) {
		    
				// Get Degree of delete node
				int deg_in_1 = 0;
				int deg_out_1 = 0;
				if ( Directed ) {
				  deg_in_1  = motif1_canonic.getRowSize( del_class_1[ del_1 ] );
				  deg_out_1 = motif1_canonic.getColSize( del_class_1[ del_1 ] );
				} else {
				  deg_in_1  = motif1_canonic.getAllRowSize( del_class_1[ del_1 ] );
				}
			
		    
				// cout << "del_0 :" << del_0 << ", del_1 :" << del_1 << endl;
			
				if ( ( deg_in_0 == deg_in_1 ) && (deg_out_0 == deg_out_1 ) ) {
		      
				  int *color_0 = new int [ prev_k_value ];
				  int *color_1 = new int [ k ];
		      
				  for( int *ptr=color_0, 
					 *ptr_end= color_0 + (prev_k_value); 
				       ptr != ptr_end; ptr++ ) {
				    *ptr=0;
				  }
				  for( int *ptr=color_1, *ptr_end= color_1 + (k); 
				       ptr != ptr_end; ptr++ ) {
				    *ptr=0;
				  }
		      
				  color_0[ perm_0[ del_class_0[ del_0 ] ]] = 1;
				  color_1[ perm_1[ del_class_1[ del_1 ] ]] = 1;
				  // printList( " color_0 ", color_0,color_0+ (k-1), true); 
				  // printList( " color_1 ", color_1,color_1+ (k), true); 
		      
		    
				  bool incl = f.isExactlyIncluded( motif0, motif1, color_0, color_1 );
				  if( incl ) {
				    setMotifFilter( S_m_mp_1, del_1, 0, 1, m, del_class_0[ del_0 ] );
				  } else {
				    setMotifFilter( S_m_mp_1, del_1, 1, 0, 0, 0 );
				  }
		      
				  // cout << "( k=" <<  k-1 <<  ", motif=" << m << ", del=" 
				  //        << del_class_0[ del_0 ]  << ") ";
				  // cout << "( k=" <<  k <<  ", motif=" << p  << ", del=" 
				  //     << del_class_1[ del_1 ] << ") : " <<  incl << endl ;
				  delete [] color_0;
				  delete [] color_1;
				    
				} else {
				  // Different degrees => over-represented
				  setMotifFilter( S_m_mp_1, del_1, 1, 0, 0, 0);
				}
		    
			      } else {
				// Parent motif not over-represented
				setMotifFilter( S_m_mp_1, del_1, 1, 0, 0, 0);
			      }
		  
			    } else {
			      // motif not over-represented
			      setMotifFilter( S_m_mp_1, del_1, 0, 0, 0, 0);	
			    }
			  }  // Valid DelClass - if( del_class_1[del_1] >= 0 ) 
			}    // for( int del_1 = 0; ...
		      }  // Valid DelClass - if( del_class_0[del_0] >= 0 ) 
		    }    // for( int del_0 = 0; ...

		    delete [] del_class_1;

		}   //  if( VECTOR_ELT(S_Adj_1, p) !=  R_NilValue ) {
	      }     //  for(int p = 0; p <  MotifNbr_1; p++ )

	      delete [] del_class_0;
	  }    // if( VECTOR_ELT(S_Adj_0, m) !=  R_NilValue ) {
	}      // for(int m = 0; m <  MotifNbr_0; m++ ) {
     
      }
      if (  prev_k_index == -1 ) {

	// First value of k

	SEXP S_m_0 = VECTOR_ELT( 
				VECTOR_ELT( 
					   VECTOR_ELT( S_ReturnList, i_k ), 
					   1 ), 
				1);

	int MotifNbr_0 = LENGTH( S_m_0 );

	for(int m = 0; m <  MotifNbr_0; m++ ) {
	  SEXP  S_m_mp_0 = VECTOR_ELT( S_m_0, m );
	  if (  S_m_mp_0 != R_NilValue ) {
	    int m_mp_len_0 = LENGTH( S_m_mp_0 );
	    for( int del_0 = 0;  del_0 <  m_mp_len_0; del_0++) {

	      if ( VECTOR_ELT( S_m_mp_0, del_0) != R_NilValue ) {
		if( getPValue( S_m_mp_0, del_0 ) < PValue ) {
		  setMotifFilter( S_m_mp_0, del_0, 1, 0, 0, 0);
		} else {
		  setMotifFilter( S_m_mp_0, del_0, 0, 0, 0, 0);
		}
	      }
	    }
	  }
	}  // for(int m = 0; m <  MotifNbr_0; m++ )

      }
      prev_k_index = i_k;
    } else {
      // S_Result NULL
    }
    // for ( vector<int*>::iterator it = list->begin(),
    //	    it_end=list->end();it != it_end; it++ ) {
    //  delete [] *it;
    // }
    FindMotif::deallocateFoundList( list );
    delete [] perm_0;
    delete [] perm_1;
  }
  
  return S_ReturnList;
}
Esempio n. 27
0
TEST_F(FileMatchTrieTest, NoResult) {
  Trie.insert("//net/somepath/otherfile.cc");
  Trie.insert("//net/otherpath/somefile.cc");
  EXPECT_EQ("", find("//net/somepath/somefile.cc"));
}
Esempio n. 28
0
	int find(int x) {
		if (f[x] == -1 || x == f[x]) return x;
		return f[x] = find(f[x]); 
	}
Esempio n. 29
0
TEST_F(FileMatchTrieTest, CannotResolveRelativePath) {
  EXPECT_EQ("", find("relative-path.cc"));
  EXPECT_EQ("Cannot resolve relative paths", Error);
}
Esempio n. 30
0
inline size_t String::find(StringParam substr) const {
	return find(substr, 0);
}