Esempio n. 1
0
void shortest_path(const Graph g){
    const Vertex from = S;
    const Vertex to = F;

    // shortest path
    std::vector<Vertex> parents(boost::num_vertices(g));
    boost::dijkstra_shortest_paths(g, from, 
            boost::predecessor_map(&parents[0]));         // TODO: ここいまいち分かってない.


    // no path
    if (parents[to] == to) {
        std::cout << "no path" << std::endl;
        return;
    }

    //
    std::deque<Vertex> route;
    for (Vertex v = to; v != from; v = parents[v]){
        route.push_front(v);
    }
    route.push_front(from);

    for(const Vertex v: route){
        std::cout << Names[v] << std::endl;
    }
}
Esempio n. 2
0
void testSelectMany(eoSelect<EOT> & _select, std::string _name)
{
    unsigned i;
  std::cout << "\n\n" << fitnessType + _name << std::endl;
  std::cout << "===============\n";

    eoDummyPop parents(parentsOrg);
    eoDummyPop offspring(0);

    // do the selection
    _select(parents, offspring);

    // compute stats
    std::vector<unsigned> nb(parents.size(), 0);
    for (i=0; i<offspring.size();  i++)
      {
	unsigned trouve = isInPop<Dummy>(offspring[i], parents);
	if (trouve == parents.size()) // pas trouve
	  throw std::runtime_error("Pas trouve ds parents");
	nb[trouve]++;
       }
    // dump to file so you can plot using gnuplot - dir name is hardcoded!
    std::string fName = "ResSelect/" + fitnessType + _name + ".select";
    std::ofstream os(fName.c_str());
    for (i=0; i<parents.size();  i++)
      {
	std::cout << i << " -> " << ( (double)nb[i])/offspring.size() << std::endl;
	os << i << " " << ( (double)nb[i])/offspring.size() << std::endl;
      }

}
Esempio n. 3
0
NbrTuple::NbrTuple(//ScenSim-Port://
    const shared_ptr<SimulationEngineInterface>& initSimulationEngineInterfacePtr)//ScenSim-Port://
    ://ScenSim-Port://
    simulationEngineInterfacePtr(initSimulationEngineInterfacePtr),//ScenSim-Port://
    parents(initSimulationEngineInterfacePtr),//ScenSim-Port://
    children(initSimulationEngineInterfacePtr),//ScenSim-Port://
    stepparents(initSimulationEngineInterfacePtr)//ScenSim-Port://
#else //ScenSim-Port://
NbrTuple::NbrTuple()
#endif //ScenSim-Port://
{
  N_spf = 128;//middle of the road value for default 0-255 for one link
  N_minmax = 128;//middle of the road value for default 0-255 for one link
  N_status = 0;
  N_macstatus = 0;
  N_willingness = 0;
  N_sort = 0;
  N_time = 0;
  N_time2 = 0;
  hop = 0;
  cdegree = 0;
  tdegree = 0;
  seq_num = 0;
  konectivity = 0;
  recievedHello = 0;
}

#ifdef SCENSIM_NRLOLSR //ScenSim-Port://
NbrTuple::NbrTuple(//ScenSim-Port://
    const shared_ptr<SimulationEngineInterface>& initSimulationEngineInterfacePtr,//ScenSim-Port://
double hold)//ScenSim-Port://
    ://ScenSim-Port://
    simulationEngineInterfacePtr(initSimulationEngineInterfacePtr),//ScenSim-Port://
    parents(initSimulationEngineInterfacePtr),//ScenSim-Port://
    children(initSimulationEngineInterfacePtr),//ScenSim-Port://
    stepparents(initSimulationEngineInterfacePtr)//ScenSim-Port://
#else //ScenSim-Port://
NbrTuple::NbrTuple(double hold)
#endif //ScenSim-Port://
{
  was_used = 0;
  N_spf = 128;//middle of the road value for default when 0-255 for one link
  N_spf_link_set = false; //this is set to true when an outside app sets the link metric
  N_minmax = 128;//middle of the road value for default 0-255 for one link
  N_minmax_link_set = false; //this is set to true when an outside app sets the link metric
  N_status = 0;
  N_willingness = 0;
  N_sort = 0;
  N_time = 0;
  N_time2 = 0;
  hop = 0;
  cdegree = 0;
  tdegree = 0;
  seq_num = 0;
  konectivity = 0;
  recievedHello = 0;
  parents.SetHoldTime(hold);
  children.SetHoldTime(hold);
  stepparents.SetHoldTime(hold);
}
Esempio n. 4
0
/* Calculate  the set A: The set of siblings to head
   that is not delayed by merging head with its predecessors.
   Returned by reference, also returning size as return value.
*/
int MergeAllParents::calculateAB(std::pair<ParentsIterator, ParentsIterator> pair,
         VertexID head,
         set<VertexID> &A,
         set<VertexID> &B)

{
  int size=0;
  double tlevel_newc = maxTlevel(parents(head,*m_taskgraph))
    + totalExecCost(pair,head); //This calcuation is not correct. It should be even lower.

  ParentsIterator p,p_end;
  ChildrenIterator c, c_end;
  for (tie(p,p_end)=pair; p != p_end; p++) {
    if (*p != m_invartask) {
      for (tie(c,c_end) = children(*p,*m_taskgraph); c != c_end; c++) {
  if (*c != head) {
    EdgeID e; bool tmp;
    tie(e,tmp) = edge(*p,*c,*m_taskgraph);
    assert(tmp);
    if (tlevel(*p) > tlevel_newc +
        getCommCost(e)/m_bandwidth + m_latency ) {
    A.insert(*c); // A - set of siblings not affecting merge.
    size++;
    } else {
        B.insert(*p); // B - set of parents to be kept.
    }
  }
      }
    } else { // invartask should not be merged.
      B.insert(*p);
    }
  }
  //cerr << "calculateAB, size =" << size << endl;
  return size;
}
Esempio n. 5
0
// Connect the nodes by filling in the node.children vectors.
void InputTreeBuilder::ConnectNodes(InputTree &out)
{
  // Create a vector that records the parent of each node (except the root).
  std::vector<InputTree::Node*> parents(out.nodes.size(), NULL);
  for (std::size_t i = 0; i < out.nodes.size()-1; ++i) {
    const InputTree::Node &node = out.nodes[i];
    std::size_t start = node.pvertex.span.GetStartPos();
    std::size_t end = node.pvertex.span.GetEndPos();
    // Find the next node (in post-order) that completely covers node's span.
    std::size_t j = i+1;
    while (true) {
      const InputTree::Node &succ = out.nodes[j];
      std::size_t succStart = succ.pvertex.span.GetStartPos();
      std::size_t succEnd = succ.pvertex.span.GetEndPos();
      if (succStart <= start && succEnd >= end) {
        break;
      }
      ++j;
    }
    parents[i] = &(out.nodes[j]);
  }

  // Add each node to its parent's list of children (except the root).
  for (std::size_t i = 0; i < out.nodes.size()-1; ++i) {
    InputTree::Node &child = out.nodes[i];
    InputTree::Node &parent = *(parents[i]);
    parent.children.push_back(&child);
  }
}
Esempio n. 6
0
// check inheritance
QString BrowserNode::check_inherit(const BrowserNode * new_parent) const {
  Q3PtrList<BrowserNode> all_parents;
  Q3PtrList<BrowserNode> notyet = parents();

  if (notyet.findRef(new_parent) != -1)
    return TR("already generalize / realize");
  
  notyet.append(new_parent);
  
  do {
    BrowserNode * cl = notyet.getFirst();
    
    notyet.removeFirst();
    if (cl == this)
      return TR("can't have circular generalization / realization");
    if (all_parents.findRef(cl) == -1) {
      all_parents.append(cl);
      
      Q3PtrList<BrowserNode> grand_parents = cl->parents();
      
      for (cl = grand_parents.first(); cl; cl = grand_parents.next())
	if (notyet.findRef(cl) == -1)
	  notyet.append(cl);
    }
  } while (! notyet.isEmpty());
  
  return 0;
}
Esempio n. 7
0
void BuildAtom::rightMousePressEvent(QMouseEvent* e) 
{
   int nObjects(m_viewer->m_objects.size());
   if ((m_beginAtom == 0) && 
       (nObjects > 0) && 
       (e->modifiers() != int(Viewer::s_buildModifier))) {
      // Manipulating in Build mode
      e->ignore();
      return;
   }

   initPointers();
   if (m_viewer->m_selectedObjects.isEmpty()) return;

   m_deleteTarget  = m_beginAtom;

   if (m_deleteTarget == 0) {
      // Should really check for a primitive
      m_deleteTarget = m_viewer->m_selectedObjects[0];
   }

   // Determine the parent molecule
   if (m_molecule == 0) {
      MoleculeList parents(m_deleteTarget->findLayers<Layer::Molecule>(Layer::Parents));
      if (parents.isEmpty()) {
         m_molecule = m_viewer->m_viewerModel.activeMolecule();
      }else {
         m_molecule = parents.first();
      }
   }

   if (m_deleteTarget) m_manipulateOnly = false;
   if (!m_molecule) qDebug() << "Molecule not set in buidler";
   e->accept();
}
Esempio n. 8
0
void ict::Topic::_words_relations(std::vector<std::vector<int> > &matrix, int thresh,
		                         std::vector<std::string> &key_words,
								 std::map<int, std::vector<std::string> > &words_cluster)
{
	int m = matrix.size();
	int n = matrix[0].size();
	std::vector<int> parents(m, 0);
	for (int i = 0; i < m; ++i)
		parents[i] = i;
	for (int i = 0; i < m; ++i)
	{
		for (int j = 0; j < n; ++j)
		{
			if (matrix[i][j] >= thresh)
			{
				tools::RelationTreeInterface::union_node(i, j, parents);
			}
		}
	}
	
	for (int i = 0; i < m; ++i)
	{
		int id = parents[i];
		std::vector<std::string> words;
		words_cluster[id] = words;
	}
	for (int i = 0; i < m; ++i)
	{
		words_cluster[parents[i]].push_back(key_words[i]);
	}
}
Esempio n. 9
0
void
APG::ConstraintSolver::mutate_population( APG::ConstraintSolver::Population& population )
{
    if ( population.size() < 1 )
        return;
    
    const double mutantPercentage = 0.35; // TODO: tune this parameter
    
    QList<Meta::TrackList*> parents( population.keys() );
    int maxMutants = (int)( mutantPercentage * (double)(m_populationSize) );
    for ( int i = parents.size(); i < maxMutants; i++ ) {
        int idx = KRandom::random() % parents.size();
        Meta::TrackList* child = new Meta::TrackList( *(parents.at( idx )) );
        int op = KRandom::random() % 5;
        int s = child->size();
        switch (op) {
            case 0:
                child->removeAt( KRandom::random() % s );
            case 1:
                child->insert( KRandom::random() % ( s + 1 ), random_track_from_domain() );
            case 2:
                child->replace( KRandom::random() % s, random_track_from_domain() );
            case 3:
                child->swap( KRandom::random() % s, KRandom::random() % s );
            case 4:
                child = crossover( child, parents.at( KRandom::random() % parents.size() ) );
            default:
                (void)0; // effectively a no-op. the default is here so that the compiler doesn't complain about missing default in switch
        }
        population.insert( child, m_constraintTreeRoot->satisfaction( *child ) );
    }
    return;
}
Esempio n. 10
0
// Run a DFS over the heap, remember the first pointer id to each
// reachable node, aka its "parent". The tree formed by the parent
// edges is a spanning tree for the reachable nodes.
// Given a node, you can walk the parents towards roots to find out
// why the node is reachable. parent[k] == -1 for unreachable nodes.
std::vector<int> makeParentTree(const HeapGraph& g) {
  std::vector<int> parents(g.nodes.size(), -1);
  dfs_ptrs(g, g.roots, [&](int node, int ptr) {
    parents[node] = ptr;
  });
  return parents;
}
Esempio n. 11
0
void MergeAllParents::mergeAll(std::pair<ParentsIterator,ParentsIterator> pair,
             VertexID child,
             set<VertexID> &A,
             set<VertexID> &B)
{
  set<VertexID> parents2;
  set<VertexID> parents1;
  set<VertexID>::iterator pit,Aelt,Belt;
  ParentsIterator p,p_end,p2,p2_end;
  InEdgeIterator e,e_end;

  for (tie(p,p_end) = pair; p != p_end; p++) {
    if (*p != m_invartask) {
      parents1.insert(*p);
    }
  }

  for (pit=parents1.begin(); pit != parents1.end(); pit++) {
    addContainsTask(child,*pit);

    for (tie(p2,p2_end) = parents(*pit,*m_taskgraph); p2 != p2_end; p2++) {
      if (parents1.find(*pit) == parents1.end() && *p2 != m_invartask)
  parents2.insert(*p2);
    }
    // Add edge from parents^2 to child
    for(tie(e,e_end) = in_edges(*pit,*m_taskgraph); e != e_end; e++) {
      // Adding edge here invalidates pair iterators
      if (parents1.find(source(*e,*m_taskgraph)) == parents1.end()) {
  EdgeID newEdge = add_edge(source(*e,*m_taskgraph),child,m_taskgraph);
  ResultSet &set = getResultSet(newEdge,m_taskgraph);
  ResultSet &oldSet = getResultSet(*e,m_taskgraph);
  set.make_union(&oldSet);
      }
    }
  }

  // Add edge from new node to all in A
  for (Aelt=A.begin(); Aelt != A.end(); Aelt++) {
    add_edge(child,*Aelt,m_taskgraph);
  }

  // Can not iterate through pair since add_edge above invalidates that
  // iterator.
  for (pit=parents1.begin(); pit != parents1.end(); pit++) {
    if (B.find(*pit) == B.end() && *pit != m_invartask) {
      (*m_taskRemoved)[*pit] = true;
      clear_vertex(*pit,*m_taskgraph);
      remove_vertex(*pit,*m_taskgraph);
    }
  }

  // Remove edges from elts in B to child, the elts are already dupl. into child.
  for (Belt = B.begin(); Belt != B.end(); Belt++) {
    remove_edge(*Belt,child,*m_taskgraph);
  }
}
Esempio n. 12
0
/*
============
TestUntransformJoints
============
*/
void TestUntransformJoints() {
	int i, j;
	TIME_TYPE start, end, bestClocksGeneric, bestClocksSIMD;
	idTempArray< idJointMat > joints( COUNT+1 );
	idTempArray< idJointMat > joints1( COUNT+1 );
	idTempArray< idJointMat > joints2( COUNT+1 );
	idTempArray< int > parents( COUNT+1 );
	const char *result;

	idRandom srnd( RANDOM_SEED );

	for ( i = 0; i <= COUNT; i++ ) {
		idAngles angles;
		angles[0] = srnd.CRandomFloat() * 180.0f;
		angles[1] = srnd.CRandomFloat() * 180.0f;
		angles[2] = srnd.CRandomFloat() * 180.0f;
		joints[i].SetRotation( angles.ToMat3() );
		idVec3 v;
		v[0] = srnd.CRandomFloat() * 2.0f;
		v[1] = srnd.CRandomFloat() * 2.0f;
		v[2] = srnd.CRandomFloat() * 2.0f;
		joints[i].SetTranslation( v );
		parents[i] = i - 1;
	}

	bestClocksGeneric = 0;
	for ( i = 0; i < NUMTESTS; i++ ) {
		for ( j = 0; j <= COUNT; j++ ) {
			joints1[j] = joints[j];
		}
		StartRecordTime( start );
		p_generic->UntransformJoints( joints1.Ptr(), parents.Ptr(), 1, COUNT );
		StopRecordTime( end );
		GetBest( start, end, bestClocksGeneric );
	}
	PrintClocks( "generic->UntransformJoints()", COUNT, bestClocksGeneric );

	bestClocksSIMD = 0;
	for ( i = 0; i < NUMTESTS; i++ ) {
		for ( j = 0; j <= COUNT; j++ ) {
			joints2[j] = joints[j];
		}
		StartRecordTime( start );
		p_simd->UntransformJoints( joints2.Ptr(), parents.Ptr(), 1, COUNT );
		StopRecordTime( end );
		GetBest( start, end, bestClocksSIMD );
	}

	for ( i = 1; i <= COUNT; i++ ) {
		if ( !joints1[i].Compare( joints2[i], 1e-3f ) ) {
			break;
		}
	}
	result = ( i >= COUNT ) ? "ok" : S_COLOR_RED"X";
	PrintClocks( va( "   simd->UntransformJoints() %s", result ), COUNT, bestClocksSIMD, bestClocksGeneric );
}
Esempio n. 13
0
std::vector<ompl::control::ProductGraph::State*>
ompl::control::ProductGraph::computeLead(
    ProductGraph::State* start,
    const boost::function<double(ProductGraph::State*, ProductGraph::State*)>& edgeWeight)
{
    std::vector<GraphType::vertex_descriptor> parents(boost::num_vertices(graph_));
    std::vector<double> distances(boost::num_vertices(graph_));
    EdgeIter ei, eend;
    //first build up the edge weights
    for (boost::tie(ei,eend) = boost::edges(graph_); ei != eend; ++ei)
    {
        GraphType::vertex_descriptor src = boost::source(*ei, graph_);
        GraphType::vertex_descriptor target = boost::target(*ei, graph_);
        graph_[*ei].cost = edgeWeight(graph_[src], graph_[target]);
    }
    int startIndex = stateToIndex_[start];
    boost::dijkstra_shortest_paths(graph_, boost::vertex(startIndex,graph_),
                                   boost::weight_map(get(&Edge::cost, graph_)).distance_map(
                                       boost::make_iterator_property_map(distances.begin(), get(boost::vertex_index, graph_)
                                                                        )).predecessor_map(
                                       boost::make_iterator_property_map(parents.begin(), get(boost::vertex_index, graph_))
                                   )
                                  );
    //pick state from solutionStates_ such that distance[state] is minimized
    State* bestSoln = *solutionStates_.begin();
    double cost = distances[boost::vertex(stateToIndex_[bestSoln], graph_)];
    for (std::vector<State*>::const_iterator s = solutionStates_.begin()+1; s != solutionStates_.end(); ++s)
    {
        if (distances[boost::vertex(stateToIndex_[*s], graph_)] < cost)
        {
            cost = distances[boost::vertex(stateToIndex_[*s], graph_)];
            bestSoln = *s;
        }
    }
    //build lead from bestSoln parents
    std::stack<State*> leadStack;
    while (!(bestSoln == start))
    {
        leadStack.push(bestSoln);
        bestSoln = graph_[parents[boost::vertex(stateToIndex_[bestSoln], graph_)]];
    }
    leadStack.push(bestSoln);

    std::vector<State*> lead;
    while (!leadStack.empty())
    {
        lead.push_back(leadStack.top());
        leadStack.pop();
        // Truncate the lead as early when it hits the desired automaton states
        // \todo: more elegant way to do this?
        if (lead.back()->cosafeState == solutionStates_.front()->cosafeState
                && lead.back()->safeState == solutionStates_.front()->safeState)
            break;
    }
    return lead;
}
Esempio n. 14
0
bool MergeAllParents::apply(VertexID v)
{
  bool change = false;
  if (v != m_invartask && v != m_outvartask) {
    set<VertexID> A, B;
    if (in_degree(v,*m_taskgraph) > 1 &&

      tlevel(v) > maxTlevel(parents(v,*m_taskgraph))
               + totalExecCost(parents(v,*m_taskgraph),v)
      /* &&
         calculateAB(parents(v,*m_taskgraph),v,A,B) > 0  */
      ) {
    calculateAB(parents(v,*m_taskgraph),v,A,B);
    // Do the merge
    //cerr << "MergeAllParents, child: "<< getTaskID(v,m_taskgraph) << " (";
    //printContainTasks(v,cerr);
    //cerr << ")" << endl;
    //cerr << "parents :" ;
    //ParentsIterator p,p_end;
    //for (tie(p,p_end)=parents(v,*m_taskgraph); p != p_end; p++) {
    // cerr << getTaskID(*p,m_taskgraph) << "(" ;
    // printContainTasks(*p,cerr);
    // cerr << ")  " ;
    //  }
    //cerr << endl;
    // cerr << "siblings (A: " ;
    //printVertexSet(A,cerr);
    //cerr << endl << "A complement: " ;
    //printVertexSet(B,cerr);
    //cerr << endl;

    mergeAll(parents(v,*m_taskgraph),v,A,B);
    //cerr << "parent now contains: " ;
    //printContainTasks(v,cerr);
    //cerr << endl;
    change=true;
  }
  }
  return change;
}
Esempio n. 15
0
BOOL	cmd_part(t_get *word, t_get **words, t_cmd *link, char **bad_sintax)
{
  word->prev = NULL;
  link->type = PARENTS;
  if (MATCH(word->word, "("))
    return (parents(word, words, link, bad_sintax));
  link->type = OREDIR;
  link->redir = NULL;
  if ((link->params = list_cmd(word, link, NULL, bad_sintax)) == NULL)
    if (link->type != OREDIR || *bad_sintax)
      return (FALSE);
  return (TRUE);
}
 bool validTree(int n, vector<pair<int, int>>& edges) {
     if(n == 0) return true;
     if(n != edges.size() + 1) return false;
     int cnt = n - 1;
     vector<int> parents(n, 0);
     for(int i = 0; i < n; ++i)
         parents[i] = i;
     for(int i = 0; i < edges.size(); ++i){
         if(Union(edges[i].first, edges[i].second, parents))
             cnt--;
     }
     return cnt == 0;
 }
std::vector<int> containing_tree(const std::vector<Rectangle<T>> &rects){
	typedef std::pair<int, int> pii;
	typedef std::tuple<int, int, int, int> tiiii;
	const int n = rects.size();
	CoordinateCompressor<T> xcomp, ycomp;
	for(int i = 0; i < n; ++i){
		xcomp.push(rects[i].x1);
		ycomp.push(rects[i].y1);
		xcomp.push(rects[i].x2);
		ycomp.push(rects[i].y2);
	}
	xcomp.build();
	ycomp.build();
	std::vector<std::pair<Rectangle<int>, int>> rs(n);
	for(int i = 0; i < n; ++i){
		const auto &r = rects[i];
		rs[i] = std::make_pair(Rectangle<int>(
			xcomp.compress(r.x1), ycomp.compress(r.y1),
			xcomp.compress(r.x2), ycomp.compress(r.y2)), i);
	}
	std::sort(rs.begin(), rs.end());
	const int m = xcomp.size();
	std::vector<std::set<pii>> raw_bit(m + 1);
	std::priority_queue<tiiii, std::vector<tiiii>, std::greater<tiiii>> pq;
	std::vector<int> parents(n, -1);
	for(int i = 0; i < n; ++i){
		const auto &r = rs[i].first;
		while(!pq.empty() && std::get<0>(pq.top()) <= r.y1){
			for(int j = std::get<1>(pq.top()) + 1; j <= m; j += j & -j){
				raw_bit[j].erase(std::make_pair(
					std::get<2>(pq.top()), std::get<3>(pq.top())));
			}
			pq.pop();
		}
		pii answer(xcomp.size(), n);
		for(int j = r.x1; j > 0; j -= j & -j){
			const auto it = raw_bit[j].lower_bound(std::make_pair(r.x2, -1));
			if(it != raw_bit[j].end()){
				answer = std::min(answer, *it);
			}
		}
		const int k = rs[i].second;
		for(int j = r.x1 + 1; j <= m; j += j & -j){
			raw_bit[j].insert(std::make_pair(r.x2, k));
		}
		parents[k] = (answer.second >= n ? -1 : answer.second);
		pq.push(std::make_tuple(r.y2, r.x1, r.x2, k));
	}
	return parents;
}
Esempio n. 18
0
QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::ReadOnly))
        return new QStringListModel(completer);

#ifndef QT_NO_CURSOR
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
#endif
    QStringList words;

    QStandardItemModel *model = new QStandardItemModel(completer);
    QVector<QStandardItem *> parents(10);
    parents[0] = model->invisibleRootItem();

    while (!file.atEnd()) {
        QString line = file.readLine();
        QString trimmedLine = line.trimmed();
        if (line.isEmpty() || trimmedLine.isEmpty())
            continue;

        QRegExp re("^\\s+");
        int nonws = re.indexIn(line);
        int level = 0;
        if (nonws == -1) {
            level = 0;
        } else {
            if (line.startsWith("\t")) {
                level = re.cap(0).length();
            } else {
                level = re.cap(0).length()/4;
            }
        }

        if (level+1 >= parents.size())
            parents.resize(parents.size()*2);

        QStandardItem *item = new QStandardItem;
        item->setText(trimmedLine);
        parents[level]->appendRow(item);
        parents[level+1] = item;
    }

#ifndef QT_NO_CURSOR
    QApplication::restoreOverrideCursor();
#endif

    return model;
}
Esempio n. 19
0
void findInnerLoops(LoopAnalysis& la) {
    sparse_id_set<LoopID> parents(la.loops.size());
    for (auto& loop : la.loops) {
        if (loop.parent != kInvalidLoopID) {
            parents.insert(loop.parent);
        }
    }

    la.innerLoops.reserve(la.loops.size() - parents.size());
    for (auto& loop : la.loops) {
        if (!parents.contains(loop.id)) {
            la.innerLoops.push_back(loop.id);
        }
    }
}
Esempio n. 20
0
void dijkstra(Graph & G, int v, bool bench)
{
    int size = G->GetNodes();
    std::vector<float> distances (size,inf);
    std::vector<int> parents (size,-1);
    std::priority_queue<std::pair<float, Graph::TObj::TNodeI> > queue;

    distances[v-1] = 0;
	parents[v-1] = -1;

    for(SnapNode NI = G->BegNI(); NI != G->EndNI(); NI++)
    {
		queue.push(std::make_pair(distances[NI.GetDat()-1], NI));
    }

    while(!queue.empty())
    {
        SnapNode u = queue.top().second;
        float dist = queue.top().first;
        queue.pop();

        int sourceNode = u.GetDat();
        for (int ed = 0; ed < u.GetOutDeg(); ed++)//For each adjacent vertex to node NI
        {
            int destNode = u.GetOutNDat(ed);
            SnapEdge e =  G->GetEI(sourceNode,destNode);
			float alt = dist + e.GetDat();
            if(alt < distances[destNode-1])//relax
            {
                distances[destNode-1] = alt;
                parents[destNode-1] = sourceNode;
                queue.push(std::make_pair(alt, G->GetNI(destNode)));
            }
        }
    }
    if(!bench)
    {
        int node = 1;
        for (int i = 0 ; i< parents.size(); i++)
        {
            if(parents[node-1] == -1)
                std::cout << "start -> " << node << " distance:  " << distances[node-1] << std::endl;
            else
                std::cout << parents[node-1] << " -> " << node << " distance:  " << distances[node-1] << std::endl;
            node++;
        }
    }
}
Esempio n. 21
0
std::vector<int> primPrincipal(Graph & G, float & length, int v)
{
    int size = G->GetNodes();
    std::vector<float> distances (size,inf);
    std::vector<bool> visitedNodes (size,false);
    std::vector<int> parents (size,-1);
    std::deque<QueueItem> queue;
    for(int i=0; i<size; i++)
    {
        QueueItem q;
        q.VertexID = i+1;
        q.distance = inf;
        queue.push_back(q);
    }
    distances[v-1] = 0;
    visitedNodes[v-1] = true;
    while(!queue.empty())
    {
        std::sort(queue.begin(), queue.end(), sortQueue);
        QueueItem u = queue.front();
        queue.pop_front();
        SnapEdge EI;
        if(parents[u.VertexID-1] != -1)
        {
            TNodeEDatNet<TInt, TFlt>::TEdgeI EI = G->GetEI(parents[u.VertexID-1],u.VertexID);
            length+=(float)EI.GetDat();
        }
        visitedNodes[u.VertexID-1] = true;
        SnapNode NI = G->GetNI(u.VertexID);
        for (int e = 0; e < NI.GetOutDeg(); e++)
        {
            SnapEdge EI = G->GetEI(u.VertexID,NI.GetOutNDat(e));
            int outNode = NI.GetOutNDat(e);
            float edgeWeight = (float)EI.GetDat();
            if(!visitedNodes[outNode-1] && distances[outNode-1] > edgeWeight)
            {
                parents[outNode-1] = u.VertexID;
                distances[outNode-1] = edgeWeight;
                for(int i=0; i< queue.size(); i++)
                {
                    if(queue[i].VertexID == outNode)
                        queue[i].distance = edgeWeight;
                }
            }
        }
    }
    return parents;
}
Esempio n. 22
0
void Build::mousePressEvent(QMouseEvent* e) 
{
   m_viewer->clearSelection();
   m_viewer->setSelectionHighlighting(false);
   m_buildObjects.clear();
   m_manipulateOnly = true;
   m_beginAtom = 0;
   m_molecule  = 0;
   m_button    = e->button();

   // Check to see if we clicked on an atom
   m_selectionMode = None;
   m_viewer->QGLViewer::select(e);
   for (int i = 0; i < m_viewer->m_selectedObjects.size(); ++i) {
      m_beginAtom = qobject_cast<Layer::Atom*>(m_viewer->m_selectedObjects[i]);
      if (m_beginAtom) break;
   }

   // Determine the parent molecule
   if (m_beginAtom == 0) {
      m_molecule = m_viewer->m_viewerModel.activeMolecule();
   }else {
      MoleculeList parents(m_beginAtom->findLayers<Layer::Molecule>(Layer::Parents));
      if (parents.isEmpty()) {
         m_molecule = m_viewer->m_viewerModel.activeMolecule();
      }else {
         m_molecule = parents.first();
      }
   }

   if (!m_molecule) {
      QMsgBox::warning(0, "IQmol", "No molecule available");
      return;
   }

   switch (m_button) {
      case Qt::LeftButton:
         leftMousePressEvent(e);
         break;
      case Qt::RightButton:
         rightMousePressEvent(e);
         break;
      default:
         e->ignore();
         break;
   }
}
Esempio n. 23
0
bool InspectionCompressorTab::save(const QString &customer_id, const QString &circuit_id,
                                   const QString &original_inspection_date, const QString &inspection_date)
{
    MTDictionary parents(QStringList() << "customer_id" << "circuit_id" << "date" << "compressor_id",
                         QStringList() << customer_id << circuit_id << original_inspection_date << QString::number(m_id));
    InspectionsCompressor record(m_record_id > 0 ? QString::number(m_record_id) : QString(), parents);

    QVariantMap values;
    if (inspection_date != original_inspection_date)
        values.insert("date", inspection_date);
    for (QList<MDAbstractInputWidget *>::const_iterator i = md_inputwidgets.constBegin(); i != md_inputwidgets.constEnd(); ++i) {
        if ((*i)->skipSave())
            continue;
        values.insert((*i)->id(), (*i)->variantValue());
    }
    return record.update(values, true, record.exists());
}
Esempio n. 24
0
  /* ************************************************************************* */
  bool GaussianConditional::equals(const GaussianFactor& f, double tol) const
  {
    if (const GaussianConditional* c = dynamic_cast<const GaussianConditional*>(&f))
    {
      // check if the size of the parents_ map is the same
      if (parents().size() != c->parents().size())
        return false;

      // check if R_ and d_ are linear independent
      for (DenseIndex i = 0; i < Ab_.rows(); i++) {
        list<Vector> rows1; rows1.push_back(Vector(get_R().row(i)));
        list<Vector> rows2; rows2.push_back(Vector(c->get_R().row(i)));

        // check if the matrices are the same
        // iterate over the parents_ map
        for (const_iterator it = beginParents(); it != endParents(); ++it) {
          const_iterator it2 = c->beginParents() + (it - beginParents());
          if (*it != *(it2))
            return false;
          rows1.push_back(row(getA(it), i));
          rows2.push_back(row(c->getA(it2), i));
        }

        Vector row1 = concatVectors(rows1);
        Vector row2 = concatVectors(rows2);
        if (!linear_dependent(row1, row2, tol))
          return false;
      }

      // check if sigmas are equal
      if ((model_ && !c->model_) || (!model_ && c->model_)
        || (model_ && c->model_ && !model_->equals(*c->model_, tol)))
        return false;

      return true;
    }
    else
    {
      return false;
    }
  }
Esempio n. 25
0
 vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) {
     vector<int> parents(m * n, -1);
     vector<int> rank(m * n, 0);
     unordered_set<int> isIsland;
     int count = 0;
     vector<int> res;
     int dx[4] = {1,0,-1,0};
     int dy[4] = {0,1,0,-1};
     for (int i = 0; i < positions.size(); i++) {
         count++;
         int cx = positions[i].first;
         int cy = positions[i].second;
         int cid = cx * n + cy;
         isIsland.insert(cid);
         int cp = find(cid, parents);
         for (int j = 0; j < 4; j++) {
             int nx = cx + dx[j];
             int ny = cy + dy[j];
             int nid = nx * n + ny;
             if (nx >= 0 && nx < m && ny >= 0 && ny < n && isIsland.count(nid) > 0) {
                 cp = find(cid, parents);
                 int np = find(nid, parents);
                 if (np != cp) {
                     count--;
                     if (rank[cp] < rank[np]) {
                         parents[cp] = np;
                     }
                     else if (rank[cp] > rank[np]) {
                         parents[np] = cp;
                     }
                     else {
                         parents[cp] = np;
                         rank[np]++;
                     }
                 }
             }
         }
         res.push_back(count);
     }
     return res;
 }
Esempio n. 26
0
void UpdatingFileModel::loadModelFromFile()
{
  QFile file(fileName);
  if (!file.open(QFile::ReadOnly)) {
    qWarning() << "Cannot load model from file" << fileName;
    return;
  }

  QStringList words;

  QVector<QStandardItem *> parents(10);
  parents[0] = invisibleRootItem();

  while (!file.atEnd()) {
    QString line = file.readLine();
    QString trimmedLine = line.trimmed();
    if (line.isEmpty() || trimmedLine.isEmpty())
      continue;

    QRegExp re("^\\s+");
    int nonws = re.indexIn(line);
    int level = 0;
    if (nonws == -1) {
      level = 0;
    } else if (line.startsWith("\t")) {
             level = re.cap(0).length();
    } else {
             level = re.cap(0).length() / 4;
    }

    if ((level + 1) >= parents.size())
      parents.resize(parents.size() * 2);

    QStandardItem *item = new QStandardItem;
    item->setText(trimmedLine);
    parents[level]->appendRow(item);
    parents[level + 1] = item;
  }
}
Esempio n. 27
0
	std::vector<GraphNodeID> justine::sampleclient::ExtendedGraph::DetermineDijkstraPath(GraphNodeID from, GraphNodeID to)
	{
	
    std::vector<NRGVertex> parents ( boost::num_vertices ( *nrg ) );
    std::vector<int> distances ( boost::num_vertices ( *nrg ) );

    VertexIndexMap vertexIndexMap = boost::get ( boost::vertex_index, *nrg );

    PredecessorMap predecessorMap ( &parents[0], vertexIndexMap );
    DistanceMap distanceMap ( &distances[0], vertexIndexMap );

    boost::dijkstra_shortest_paths ( *nrg, nr2v[from],
                                     boost::distance_map ( distanceMap ).predecessor_map ( predecessorMap ) );

    VertexNameMap vertexNameMap = boost::get ( boost::vertex_name, *nrg );

    std::vector<osmium::unsigned_object_id_type> path;

    NRGVertex tov = nr2v[to];
    NRGVertex fromv = predecessorMap[tov];


    while ( fromv != tov )
      {

        NRGEdge edge = boost::edge ( fromv, tov, *nrg ).first;


        path.push_back ( vertexNameMap[boost::target ( edge, *nrg )] );

        tov = fromv;
        fromv = predecessorMap[tov];
      }
    path.push_back ( from );

    std::reverse ( path.begin(), path.end() );

    return path;
	}
Esempio n. 28
0
  void Refinement :: ValidateSecondOrder (Mesh & mesh)
  {
    PrintMessage (3, "Validate mesh");
    int np = mesh.GetNP();
    int ne = mesh.GetNE();
    // int i, j;
    Array<INDEX_2> parents(np);
  
    for (int i = 1; i <= np; i++)
      parents.Elem(i) = INDEX_2(0,0);

    for (int i = 1; i <= ne; i++)
      {
	const Element & el = mesh.VolumeElement(i);
	if (el.GetType() == TET10)
	  {
	    static int betweentab[6][3] =
	      { { 1, 2, 5 },
		{ 1, 3, 6 },
		{ 1, 4, 7 },
		{ 2, 3, 8 },
		{ 2, 4, 9 },
		{ 3, 4, 10 } };
	    for (int j = 0; j < 6; j++)
	      {
		int f1 = el.PNum (betweentab[j][0]);
		int f2 = el.PNum (betweentab[j][1]);
		int son = el.PNum (betweentab[j][2]);
		parents.Elem(son).I1() = f1;
		parents.Elem(son).I2() = f2;
	      }
	  }
      }

    ValidateRefinedMesh (mesh, parents);
  }
Esempio n. 29
0
CIDNet* CreateRandomIDNet(int num_nodes, int num_indep_nodes,
  int max_size_family, int num_decision_nodes, int max_num_states_chance_nodes,
  int max_num_states_decision_nodes, int min_utility, int max_utility,
  bool is_uniform_start_policy)
{
  PNL_CHECK_RANGES(num_decision_nodes, 1, num_nodes-1);
  PNL_CHECK_LEFT_BORDER(max_num_states_chance_nodes, 1);
  PNL_CHECK_LEFT_BORDER(max_num_states_decision_nodes, 1);
  PNL_CHECK_LEFT_BORDER(max_utility, min_utility);
  
  CGraph* pGraph = 
    CreateRandomAndSpecificForIDNetGraph(num_nodes, num_indep_nodes,
    max_size_family);
  
  if (!pGraph->IsDAG())
  {
    PNL_THROW(CInconsistentType, " the graph should be a DAG ");
  }
  
  if (!pGraph->IsTopologicallySorted())
  {
    PNL_THROW(CInconsistentType, 
      " the graph should be sorted topologically ");
  }
  if (pGraph->NumberOfConnectivityComponents() > 1)
  {
    PNL_THROW(CInconsistentType, " the graph should be linked ");
  }
  
  int i, j, k;
  
  CNodeType *nodeTypes = new CNodeType [num_nodes];
  
  intVector nonValueNodes(0);
  intVector posibleDecisionNodes(0);
  nonValueNodes.resize(0);
  posibleDecisionNodes.resize(0);
  for (i = 0; i < num_nodes; i++)
  {
    if (pGraph->GetNumberOfChildren(i) == 0)
    {
      nodeTypes[i].SetType(1, 1, nsValue);
    }
    else
    {
      nonValueNodes.push_back(i);
      posibleDecisionNodes.push_back(i);
    }
  }
  int ind_decision_node;
  int num_states;
  int index;
  int node;
  intVector neighbors(0);
  neighborTypeVector neigh_types(0);

  num_decision_nodes = (num_decision_nodes > posibleDecisionNodes.size()) ? 
    posibleDecisionNodes.size() : num_decision_nodes;
  for (i = 0; (i < num_decision_nodes) && (posibleDecisionNodes.size()>0); i++)
  {
    ind_decision_node = rand() % posibleDecisionNodes.size();
    node = posibleDecisionNodes[ind_decision_node];
    num_states = GetRandomNumberOfStates(max_num_states_decision_nodes);
    nodeTypes[node].SetType(1, num_states, nsDecision);
    
    index = -1;
    for (j = 0; j < nonValueNodes.size(); j++)
    {
      if (nonValueNodes[j] == node)
      {
        index = j;
        break;
      }
    }
    if (index != -1)
      nonValueNodes.erase(nonValueNodes.begin() + index);
      
    posibleDecisionNodes.erase(posibleDecisionNodes.begin() + 
      ind_decision_node);
    pGraph->GetNeighbors(node, &neighbors, &neigh_types);
    for (j = 0; j < neighbors.size(); j++)
    {
      index = -1;
      for (k = 0; k < posibleDecisionNodes.size(); k++)
      {
        if (neighbors[j] == posibleDecisionNodes[k])
        {
          index = k;
          break;
        }
      }
      if (index != -1)
        posibleDecisionNodes.erase(posibleDecisionNodes.begin() + index);
    }
  }
  for (i = 0; i < nonValueNodes.size(); i++)
  {
    num_states = GetRandomNumberOfStates(max_num_states_chance_nodes);
    nodeTypes[nonValueNodes[i]].SetType(1, num_states, nsChance);
  }
  
  int *nodeAssociation = new int[num_nodes];
  for (i = 0; i < num_nodes; i++)
  {
    nodeAssociation[i] = i;
  }
  
  CIDNet *pIDNet = CIDNet::Create(num_nodes, num_nodes, nodeTypes,
    nodeAssociation, pGraph);
  pGraph = pIDNet->GetGraph();
  CModelDomain* pMD = pIDNet->GetModelDomain();
  
  CFactor **myParams = new CFactor*[num_nodes];
  int *nodeNumbers = new int[num_nodes];
  int **domains = new int*[num_nodes];
  
  intVector parents(0);
  for (i = 0; i < num_nodes; i++)
  {
    nodeNumbers[i] = pGraph->GetNumberOfParents(i) + 1;
    domains[i] = new int[nodeNumbers[i]];
    pGraph->GetParents(i, &parents);
    
    for (j = 0; j < parents.size(); j++)
    {
      domains[i][j] = parents[j];
    }
    domains[i][nodeNumbers[i]-1] = i;
  }
  
  pIDNet->AllocFactors();
  
  for (i = 0; i < num_nodes; i++)
  {
    myParams[i] = CTabularCPD::Create(domains[i], nodeNumbers[i], pMD);
  }
  
  float **data = new float*[num_nodes];
  int size_data;
  int num_states_node;
  int num_blocks;
  intVector size_nodes(0);
  float belief, sum_beliefs;
  
  for (i = 0; i < num_nodes; i++)
  {
    size_data = 1;
    size_nodes.resize(0);
    for (j = 0; j < nodeNumbers[i]; j++)
    {
      size_nodes.push_back(pIDNet->GetNodeType(domains[i][j])->GetNodeSize());
      size_data *= size_nodes[j];
    }
    num_states_node = size_nodes[size_nodes.size() - 1];
    num_blocks = size_data / num_states_node;
    
    data[i] = new float[size_data];
    switch (pIDNet->GetNodeType(i)->GetNodeState())
    {
      case nsChance:
      {
        for (j = 0; j < num_blocks; j++)
        {
          sum_beliefs = 0.0;
          for (k = 0; k < num_states_node - 1; k++)
          {
            belief = GetBelief(1.0f - sum_beliefs);
            data[i][j * num_states_node + k] = belief;
            sum_beliefs += belief;
          }
          belief = 1.0f - sum_beliefs;
          data[i][j * num_states_node + num_states_node - 1] = belief;
        }
        break;
      }
      case nsDecision:
      {
        if (is_uniform_start_policy)
        {
          belief = 1.0f / float(num_states_node);
          for (j = 0; j < num_blocks; j++)
          {
            sum_beliefs = 0.0;
            for (k = 0; k < num_states_node - 1; k++)
            {
              data[i][j * num_states_node + k] = belief;
              sum_beliefs += belief;
            }
            data[i][j * num_states_node + num_states_node - 1] = 
              1.0f - sum_beliefs;
          }
        }
        else
        {
          for (j = 0; j < num_blocks; j++)
          {
            sum_beliefs = 0.0;
            for (k = 0; k < num_states_node - 1; k++)
            {
              belief = GetBelief(1.0f - sum_beliefs);
              data[i][j * num_states_node + k] = belief;
              sum_beliefs += belief;
            }
            belief = 1.0f - sum_beliefs;
            data[i][j * num_states_node + num_states_node - 1] = belief;
          }
        }
        break;
      }
      case nsValue:
      {
        for (j = 0; j < num_blocks; j++)
        {
          data[i][j] = float(GetUtility(min_utility, max_utility));
        }
        break;
      }
    }
  }

  for (i = 0; i < num_nodes; i++)
  {
    myParams[i]->AllocMatrix(data[i], matTable);
    pIDNet->AttachFactor(myParams[i]);
  }

  delete [] nodeTypes;
  delete [] nodeAssociation;

  return pIDNet;
}
Esempio n. 30
0
void ompl::control::Syclop::computeLead(int startRegion, int goalRegion)
{
    lead_.clear();
    if (startRegion == goalRegion)
    {
        lead_.push_back(startRegion);
        return;
    }

    else if (rng_.uniform01() < probShortestPath_)
    {
        std::vector<RegionGraph::vertex_descriptor> parents(decomp_->getNumRegions());
        std::vector<double> distances(decomp_->getNumRegions());

        try
        {
            boost::astar_search(graph_, boost::vertex(startRegion, graph_), DecompositionHeuristic(this, getRegionFromIndex(goalRegion)),
                boost::weight_map(get(&Adjacency::cost, graph_)).distance_map(
                    boost::make_iterator_property_map(distances.begin(), get(boost::vertex_index, graph_)
                )).predecessor_map(
                    boost::make_iterator_property_map(parents.begin(), get(boost::vertex_index, graph_))
                ).visitor(GoalVisitor(goalRegion))
            );
        }
        catch (found_goal fg)
        {
            int region = goalRegion;
            int leadLength = 1;

            while (region != startRegion)
            {
                region = parents[region];
                ++leadLength;
            }
            lead_.resize(leadLength);
            region = goalRegion;
            for (int i = leadLength-1; i >= 0; --i)
            {
                lead_[i] = region;
                region = parents[region];
            }
        }
    }
    else
    {
        /* Run a random-DFS over the decomposition graph from the start region to the goal region.
           There may be a way to do this using boost::depth_first_search. */
        VertexIndexMap index = get(boost::vertex_index, graph_);
        std::stack<int> nodesToProcess;
        std::vector<int> parents(decomp_->getNumRegions(), -1);
        parents[startRegion] = startRegion;
        nodesToProcess.push(startRegion);
        bool goalFound = false;
        while (!goalFound && !nodesToProcess.empty())
        {
            const int v = nodesToProcess.top();
            nodesToProcess.pop();
            std::vector<int> neighbors;
            boost::graph_traits<RegionGraph>::adjacency_iterator ai, aend;
            for (boost::tie(ai,aend) = adjacent_vertices(boost::vertex(v,graph_),graph_); ai != aend; ++ai)
            {
                if (parents[index[*ai]] < 0)
                {
                    neighbors.push_back(index[*ai]);
                    parents[index[*ai]] = v;
                }
            }
            for (std::size_t i = 0; i < neighbors.size(); ++i)
            {
                const int choice = rng_.uniformInt(i, neighbors.size()-1);
                if (neighbors[choice] == goalRegion)
                {
                    int region = goalRegion;
                    int leadLength = 1;
                    while (region != startRegion)
                    {
                        region = parents[region];
                        ++leadLength;
                    }
                    lead_.resize(leadLength);
                    region = goalRegion;
                    for (int j = leadLength-1; j >= 0; --j)
                    {
                        lead_[j] = region;
                        region = parents[region];
                    }
                    goalFound = true;
                    break;
                }
                nodesToProcess.push(neighbors[choice]);
                std::swap(neighbors[i], neighbors[choice]);
            }
        }
    }

    //Now that we have a lead, update the edge weights.
    for (std::size_t i = 0; i < lead_.size()-1; ++i)
    {
        Adjacency& adj = *regionsToEdge_[std::pair<int,int>(lead_[i], lead_[i+1])];
        if (adj.empty)
        {
            ++adj.numLeadInclusions;
            updateEdge(adj);
        }
    }
}