bool operator()(const Edge& e) const { return e.exists(); }
Edge::Edge(const Edge &e):_begin(e.getBegin()),_end(e.getEnd()) { }
void ExtendedBFS2::run() { ExtendedQueueItem *eqi = (ExtendedQueueItem*) this->queue->dequeue(); BucketItem *cur = eqi->getNode(); int currentDepth = eqi->getDepth(); List *path = eqi->getPath(); bool depthLimitSet = false; int depthLimit = -1; while (cur) { if (depthLimitSet && depthLimit < currentDepth) { delete eqi; eqi = (ExtendedQueueItem*) queue->dequeue(); if (eqi) { cur = eqi->getNode(); currentDepth = eqi->getDepth(); path = eqi->getPath(); } else cur = NULL; continue; } // If we reached endID, set depthLimit. if (cur->getNodeID() == this->endID) { depthLimitSet = true; depthLimit = currentDepth; this->shortestPathNo++; // Update shortest paths. List *newPath = new List(); if (!newPath) { cout << "ERROR: Unable to allocate memory." << endl; return; } EdgeListItem *eli = (EdgeListItem*) path->getHead(); while (eli) { Edge *e = eli->getElement(); newPath->insertItem(new EdgeListItem(new Edge(e->getStartNodeId(), e->getEndNodeId(), NULL))); eli = eli->getNext(); } ListListItem *lli = new ListListItem(newPath); if (!lli) { cout << "ERROR: Unable to allocate memory." << endl; delete newPath; return; } this->shortestPaths->insertItem(lli); } if (this->visitedIDs->Lookup(cur->getNodeID())) { delete eqi; eqi = (ExtendedQueueItem*) queue->dequeue(); if (eqi) { cur = eqi->getNode(); currentDepth = eqi->getDepth(); path = eqi->getPath(); } else cur = NULL; continue; } this->visitedIDs->Insert(new Node(cur->getNodeID(), NULL)); // Do not add children if we are at maximum depth of search.(depthLimit is set) or we already have added them if ((depthLimitSet) && (currentDepth >= depthLimit)) { continue; } // Enqueue node's neighbors List *neighbors = cur->getEdgeList(); EdgeListItem *eli = (EdgeListItem*) neighbors->getHead(); while (eli) { Edge *curEdge = eli->getElement(); BucketItem *lookupItem; if (curEdge->getStartNodeId() == cur->getNodeID()) lookupItem = this->graph->lookupItem(curEdge->getEndNodeId()); else lookupItem = this->graph->lookupItem(curEdge->getStartNodeId()); assert(lookupItem); // Enqueue only if we haven't visited it yet. if (!(visitedIDs->Lookup(lookupItem->getNodeID()))) { List *newPath = new List(); if (!newPath) { cout << "ERROR: Unable to allocate memory." << endl; return; } EdgeListItem *head = (EdgeListItem*) path->getHead(); while (head) { Edge *e = head->getElement(); EdgeListItem *newItem = new EdgeListItem(new Edge(e->getStartNodeId(), e->getEndNodeId(), NULL)); newPath->insertItem(newItem); head = head->getNext(); } EdgeListItem *eli = new EdgeListItem(new Edge(cur->getNodeID(), curEdge->getEndNodeId(), NULL)); if (!eli) { cout << "ERROR: Unable to allocate memory." << endl; delete newPath; return; } newPath->insertItem(eli); ExtendedQueueItem *newItem = new ExtendedQueueItem(lookupItem, newPath); this->queue->enqueue(newItem); } eli = eli->getNext(); } delete eqi; eqi = (ExtendedQueueItem*) queue->dequeue(); if (eqi) { cur = eqi->getNode(); currentDepth = eqi->getDepth(); path = eqi->getPath(); } else cur = NULL; } return; }
// Find bubbles (nodes where there is a split and then immediate rejoin) and mark them for removal bool SGBubbleVisitor::visit(StringGraph* /*pGraph*/, Vertex* pVertex) { bool bubble_found = false; for(size_t idx = 0; idx < ED_COUNT; idx++) { EdgeDir dir = EDGE_DIRECTIONS[idx]; EdgePtrVec edges = pVertex->getEdges(dir); if(edges.size() > 1) { Vertex* pStart = pVertex; Vertex* pEnd = NULL; // Check the vertices for(size_t i = 0; i < edges.size(); ++i) { Edge* pVWEdge = edges[i]; Vertex* pWVert = pVWEdge->getEnd(); // Get the edges from w in the same direction EdgeDir transDir = !pVWEdge->getTwinDir(); EdgePtrVec wEdges = pWVert->getEdges(transDir); if(pWVert->getColor() == GC_RED) return false; // If the bubble has collapsed, there should only be one edge if(wEdges.size() == 1) { Vertex* pBubbleEnd = wEdges.front()->getEnd(); if(pBubbleEnd->getColor() == GC_RED) return false; } } // Mark the vertices for(size_t i = 0; i < edges.size(); ++i) { Edge* pVWEdge = edges[i]; Vertex* pWVert = pVWEdge->getEnd(); // Get the edges from w in the same direction EdgeDir transDir = !pVWEdge->getTwinDir(); EdgePtrVec wEdges = pWVert->getEdges(transDir); // If the bubble has collapsed, there should only be one edge if(wEdges.size() == 1) { Vertex* pBubbleEnd = wEdges.front()->getEnd(); if(pBubbleEnd->getColor() == GC_BLACK) { // The endpoint has been visited, set this vertex as needing removal // and set the endpoint as unvisited pWVert->setColor(GC_RED); bubble_found = true; pEnd = pBubbleEnd; } else { pBubbleEnd->setColor(GC_BLACK); pWVert->setColor(GC_BLUE); } } } // Unmark vertices for(size_t i = 0; i < edges.size(); ++i) { Edge* pVWEdge = edges[i]; Vertex* pWVert = pVWEdge->getEnd(); // Get the edges from w in the same direction EdgeDir transDir = !pVWEdge->getTwinDir(); EdgePtrVec wEdges = pWVert->getEdges(transDir); // If the bubble has collapsed, there should only be one edge if(wEdges.size() == 1) { Vertex* pBubbleEnd = wEdges.front()->getEnd(); pBubbleEnd->setColor(GC_WHITE); } if(pWVert->getColor() == GC_BLUE) pWVert->setColor(GC_WHITE); } (void)pStart; (void)pEnd; if(bubble_found) { /* SGWalkVector walkVector; SGSearch::findWalks(pStart, pEnd, dir, 1000, 20, walkVector); if(walkVector.size() == 2) { SGWalk& walk1 = walkVector[0]; SGWalk& walk2 = walkVector[1]; int len1 = walk1.getStartToEndDistance(); int len2 = walk2.getStartToEndDistance(); int diff = len1 - len2; std::string type = "SNP"; if(diff != 0) { type = "INDEL"; } std::cout << "Bubble " << pStart->getID() << " to " << pEnd->getID() << " is a " << type << "(d: " << diff << ")\n"; } */ ++num_bubbles; } } } return bubble_found; }
void ExportFilterRGML::Export(Graph& G, ostream& os, VertexColoring& vertexcoloring, EdgeColoring& edgecoloring, float dpi, float edgewidth, float vertexradius) { StringTranslatorXML Translator; os << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; os << "<!-- www.Open-Graphtheory.org -->\n\n"; os << "<rdf:RDF\n" << " xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" << " xmlns=\"http://purl.org/puninj/2001/05/rgml-schema#\"\n" << " xmlns:rgml=\"http://purl.org/puninj/2001/05/rgml-schema#\"\n" << ">\n\n"; os << " <Graph rdf:ID=\"graph\" rgml:directed=\"false\">\n"; /// declare vertices os << " <nodes>\n"; os << " <rdf:Bag>\n"; for(VertexIterator v = G.BeginVertices(); v != G.EndVertices(); v++) os << " <rdf:li rdf:resource=\"#n" << (*v)->GetID() << "\"/>\n"; os << " </rdf:Bag>\n"; os << " </nodes>\n\n"; /// declare edges and arcs os << " <edges>\n"; os << " <rdf:Bag>\n"; for(EdgeIterator e = G.BeginEdges(); e != G.EndEdges(); e++) os << " <rdf:li rdf:resource=\"#e" << (*e)->GetID() << "\"/>\n"; os << " </rdf:Bag>\n"; os << " </edges>\n"; os << " </Graph>\n\n"; /// write vertices for(VertexIterator v = G.BeginVertices(); v != G.EndVertices(); v++) os << " <Node rdf:ID=\"n" << (*v)->GetID() << "\" rgml:label=\"" << Translator.Translate((*v)->GetLabel()) << "\"/>\n"; /// write edges for(EdgeIterator ei = G.BeginEdges(); ei != G.EndEdges(); ei++) { Edge* e = *ei; if(e->IsHyperedge()) continue; os << "\n <Edge rdf:ID=\"e" << e->GetID() << "\" directed=\"" << (e->IsEdge()?"false":"true") << "\"" << " rgml:label=\"" << Translator.Translate(e->GetLabel()) << "\">\n"; os << " <source rdf:resource=\"#n" << e->From()->GetID() << "\"/>\n"; os << " <target rdf:resource=\"#n" << e->To()->GetID() << "\"/>\n"; os << " </Edge>\n"; } /// write hyperedges for(EdgeIterator ei = G.BeginEdges(); ei != G.EndEdges(); ei++) { Edge *e = *ei; if(!e->IsHyperedge()) continue; os << "\n <Edge rdf:ID=\"e" << e->GetID() << "\"" << " rgml:label=\"" << Translator.Translate(e->GetLabel()) << "\">\n"; os << " <nodes>\n"; os << " <rdf:Seq>\n"; for(VertexEdgeConnectionIterator conn = e->BeginConnections(); conn != e->EndConnections(); conn++) os << " <rdf:li rdf:resource=\"#n" << (*conn)->GetVertex()->GetID() << "\"/>\n"; os << " </rdf:Seq>\n"; os << " </nodes>\n"; os << " </Edge>\n"; } os << "\n</rdf:RDF>\n"; }
void UnitDigraph::scc_generate_unit_digraph() { for (vector<Node*>::iterator iter = origin->node_vec.begin(); iter != origin->node_vec.end(); iter++) { Node* node = *iter; int maxSeparationtime = this->gcd; for (list<Edge*>::iterator iter = node->scc_out.begin(); iter != node->scc_out.end(); iter++) { Edge* edge = *iter; maxSeparationtime = std::max(maxSeparationtime, edge->separationTime); } int numNode = maxSeparationtime/this->gcd; node->unitNodes = new Node*[numNode]; node->unitNodeNum = numNode; // Create new nodes for (int j=0; j<numNode; j++) { string name = "u_"+node->name+"_"+Utility::int_to_string(j); int deadline = 1; // not important int wcet = 0; if (j==0) { wcet = node->wcet; deadline = node->deadline; // the demand bound functions of the original digraph and UDRT are same } Node* newNode = new Node(name,node->scale,wcet,deadline); this->add_node(newNode, node); node->unitNodes[j] = newNode; } // Create new edges for (int j=1; j<numNode; j++) { Node* src = node->unitNodes[j-1]; Node* snk = node->unitNodes[j]; Edge* newEdge = new Edge(src, snk); newEdge->set_separation_time(1); src->out.push_back(newEdge); snk->in.push_back(newEdge); this->add_edge(newEdge); } } for (int i=0; i<origin->edge_vec.size(); i++) { Edge* edge = origin->edge_vec.at(i); int separation = edge->separationTime/this->gcd; Node* src = edge->src_node->unitNodes[separation-1]; Node* snk = edge->snk_node->unitNodes[0]; Edge* newEdge = new Edge(src, snk); newEdge->set_separation_time(1); src->out.push_back(newEdge); snk->in.push_back(newEdge); this->add_edge(newEdge); } for (vector<Node*>::iterator iter = origin->node_vec.begin(); iter != origin->node_vec.end(); iter++) { Node* node = *iter; delete[] node->unitNodes; node->unitNodes = NULL; } }
bool SGTransitiveReductionVisitor::visit(StringGraph* /*pGraph*/, Vertex* pVertex) { size_t trans_count = 0; static const size_t FUZZ = 10; // see myers for(size_t idx = 0; idx < ED_COUNT; idx++) { EdgeDir dir = EDGE_DIRECTIONS[idx]; EdgePtrVec edges = pVertex->getEdges(dir); // These edges are already sorted if(edges.size() == 0) continue; for(size_t i = 0; i < edges.size(); ++i) (edges[i])->getEnd()->setColor(GC_GRAY); Edge* pLongestEdge = edges.back(); size_t longestLen = pLongestEdge->getSeqLen() + FUZZ; // Stage 1 for(size_t i = 0; i < edges.size(); ++i) { Edge* pVWEdge = edges[i]; Vertex* pWVert = pVWEdge->getEnd(); //std::cout << "Examining edges from " << pWVert->getID() << " longest: " << longestLen << "\n"; //std::cout << pWVert->getID() << " w_edges: \n"; EdgeDir transDir = !pVWEdge->getTwinDir(); if(pWVert->getColor() == GC_GRAY) { EdgePtrVec w_edges = pWVert->getEdges(transDir); for(size_t j = 0; j < w_edges.size(); ++j) { Edge* pWXEdge = w_edges[j]; size_t trans_len = pVWEdge->getSeqLen() + pWXEdge->getSeqLen(); if(trans_len <= longestLen) { if(pWXEdge->getEnd()->getColor() == GC_GRAY) { // X is the endpoint of an edge of V, therefore it is transitive pWXEdge->getEnd()->setColor(GC_BLACK); //std::cout << "Marking " << pWXEdge->getEndID() << " as transitive to " << pVertex->getID() << "\n"; } } else break; } } } // Stage 2 for(size_t i = 0; i < edges.size(); ++i) { Edge* pVWEdge = edges[i]; Vertex* pWVert = pVWEdge->getEnd(); //std::cout << "Examining edges from " << pWVert->getID() << " longest: " << longestLen << "\n"; //std::cout << pWVert->getID() << " w_edges: \n"; EdgeDir transDir = !pVWEdge->getTwinDir(); EdgePtrVec w_edges = pWVert->getEdges(transDir); for(size_t j = 0; j < w_edges.size(); ++j) { //std::cout << " edge: " << *w_edges[j] << "\n"; Edge* pWXEdge = w_edges[j]; size_t len = pWXEdge->getSeqLen(); if(len < FUZZ || j == 0) { if(pWXEdge->getEnd()->getColor() == GC_GRAY) { // X is the endpoint of an edge of V, therefore it is transitive pWXEdge->getEnd()->setColor(GC_BLACK); //std::cout << "Marking " << pWXEdge->getEndID() << " as transitive to " << pVertex->getID() << " in stage 2"; //std::cout << " via " << pWVert->getID() << "\n"; } } else { break; } } } for(size_t i = 0; i < edges.size(); ++i) { if(edges[i]->getEnd()->getColor() == GC_BLACK) { // Mark the edge and its twin for removal if(edges[i]->getColor() != GC_BLACK || edges[i]->getTwin()->getColor() != GC_BLACK) { edges[i]->setColor(GC_BLACK); edges[i]->getTwin()->setColor(GC_BLACK); marked_edges += 2; trans_count++; } } edges[i]->getEnd()->setColor(GC_WHITE); } } if(trans_count > 0) ++marked_verts; return false; }
double Bchart:: parse() { alreadyPopedNum = 0; SentRepIter sri(sentence_); bool haveS = false; int locTimeout = ruleiCountTimeout_; for (;;) { //check(); if( ruleiCounts_ > locTimeout ) { break; } if(get_S() && !haveS) { // once we have found a parse, the total edes is set to edges * 3.5; haveS = true; if(printDebug(10)) cerr << "Found S " << popedEdgeCount_ << endl; popedEdgeCountAtS_ = popedEdgeCount_; totEdgeCountAtS_ = ruleiCounts_; int newTime = (int)(ruleiCounts_ * timeFactor); if(newTime < ruleiCountTimeout_) locTimeout = newTime; } // We keep track of number of ruleis to decide when time out on parsing.; /* get best thing off of keylist */ Edge* edge = heap->pop(); if (!edge) { break; } int stus = edge->status(); int cD = curDemerits_[edge->start()][edge->loc()]; if(edge->demerits() < cD - 5 && !haveS) { edge->demerits() = cD; edge->setmerit(); heap->insert(edge); continue; } if(alreadyPopedNum >= 400000) { cerr << "alreadyPoped got too large" << endl; break; } if(printDebug() > 10) { cerr << popedEdgeCount_ << "\tPop"; if(stus == 0) cerr << "< "; else if(stus == 2) cerr << ". "; else cerr << "> "; cerr << *edge << "\t" << edge->prob() << "\t" << edge->merit(); cerr << endl; } popedEdgeCount_++; alreadyPoped[alreadyPopedNum++] = edge; if(!haveS) addToDemerits(edge); /* and add it to chart */ //heap->check(); switch (stus) { case 0 : add_edge(edge, 0); break; //0 => continuing left; case 1 : add_edge(edge, 1); break; //1 => continung right; case 2 : addFinishedEdge(edge); } } /* at this point we are done looking for edges etc. */ Item *snode = get_S(); /* No "S" node means the sentence was unparsable. */ if (!snode) return badParse; double ans = snode->prob(); if (ans <= 0.0L) error("zero probability parse?"); /* ans = -log2(ans); if (ans == quiet_nan(0L)) error("log returned quiet_nan()"); */ static double nat_log_2 = log( 2.0 ); ans = -log( ans )/ nat_log_2; crossEntropy_ = ans; return ans; }
ribi::cmap::QtEdge::QtEdge( const Edge& edge, QtNode * const from, QtNode * const to ) : m_arrow{nullptr}, //Will be initialized below m_edge{edge}, m_from{from}, m_qtnode{new QtNode(edge.GetNode(), this)}, //parent m_show_bounding_rect{false}, m_to{to} { //Allow mouse tracking //OTOH: must be done by the other thing //this->setAcceptHoverEvents(true); //const_cast because Arrow constant //I just need to have an initialized m_qtnode const_cast<Arrow&>(m_arrow) = new QtQuadBezierArrowItem( from, false, //edge.HasTailArrow(), this->GetQtNode(), false, //edge.HasHeadArrow(), to, this // parent ); //QtEdge is just the glue between a collection of things //this->setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsFocusable); this->m_arrow->setFlags(0); #define BELIEF_THAT_QTEDGE_SHOULD_NOT_BE_SELECTABLE #ifdef BELIEF_THAT_QTEDGE_SHOULD_NOT_BE_SELECTABLE this->setFlags(0); #else this->setFlags( QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable ); #endif GetQtNode()->setFlags( QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable ); assert(m_from); assert(m_to); assert(from != to); assert(m_from != m_to); //m_edge must be initialized before m_arrow //if 'from' or 'to' are CenterNodes, then no item must be put at the center const bool is_connected_to_center_node = dynamic_cast<QtCenterNode*>(from) || dynamic_cast<QtCenterNode*>(to); if (is_connected_to_center_node) { m_arrow->SetMidX( (m_arrow->GetFromX() + m_arrow->GetToX()) / 2.0 ); m_arrow->SetMidY( (m_arrow->GetFromY() + m_arrow->GetToY()) / 2.0 ); } m_edge.GetNode().SetX( (from->GetCenterX() + to->GetCenterX()) / 2.0 ); m_edge.GetNode().SetY( (from->GetCenterY() + to->GetCenterY()) / 2.0 ); m_qtnode->SetCenterX(m_edge.GetNode().GetX()); m_qtnode->SetCenterY(m_edge.GetNode().GetY()); m_qtnode->SetText( { m_edge.GetNode().GetConcept().GetName() } ); assert(std::abs(m_edge.GetNode().GetY() - m_qtnode->GetCenterY()) < 2.0); //Set Z values this->setZValue(-1.0); m_arrow->setZValue(-1.0); m_qtnode->setZValue(1.0); }
std::vector<const Edge*> query(const State &start, const State &goal, int iterationsAtATime = -1, bool firstInvocation = true) { bool foundGoal = false; #ifdef WITHGRAPHICS auto green = OpenGLWrapper::Color::Green(); start.draw(green); agent.drawMesh(start); goal.draw(green); #endif if(agent.isGoal(start, goal)) { dfpair(stdout, "solution cost", "0"); dfpair(stdout, "solution length", "0"); return std::vector<const Edge*>(); } if(firstInvocation) { auto root = pool.construct(start); treeInterface.insertIntoTree(root); } unsigned int iterations = 0; while(!foundGoal) { std::pair<Edge*, State> treeSample = treeInterface.getTreeSample(); samplesGenerated++; #ifdef WITHGRAPHICS samples.push_back(treeSample.second); #endif auto edge = agent.steer(treeSample.first->end, treeSample.second, steeringDT); unsigned int added = 0; Edge *parent = treeSample.first; while(added < maxExtensions && workspace.safeEdge(agent, edge, collisionCheckDT)) { added++; edgesAdded++; Edge *e = pool.construct(edge); bool addedIntoTree = treeInterface.insertIntoTree(e); if(!addedIntoTree) { pool.destroy(e); break; } e->updateParent(parent); parent = e; #ifdef WITHGRAPHICS treeEdges.push_back(e); #endif if(agent.isGoal(e->end, goal)) { dfpair(stdout, "solution cost", "%g", e->gCost()); std::vector<const Edge *> newSolution; newSolution.push_back(e); unsigned int edgeCount = 1; while(newSolution.back()->parent != NULL) { edgeCount++; newSolution.push_back(newSolution.back()->parent); } dfpair(stdout, "solution length", "%u", edgeCount); if(solutionCost < 0 || e->gCost() < solutionCost) { std::reverse(newSolution.begin(), newSolution.end()); solution.clear(); solution.insert(solution.begin(), newSolution.begin(), newSolution.end()); } foundGoal = true; #ifdef WITHGRAPHICS break; #endif return solution; } edge = agent.steerWithControl(edge.end, edge, steeringDT); } edgesRejected++; ++iterations; if(iterationsAtATime > 0 && ++iterations > iterationsAtATime) break; } #ifdef WITHGRAPHICS for(const Edge *edge : treeEdges) { edge->draw(OpenGLWrapper::Color::Red()); } for(const State &sample : samples) { sample.draw(); } if(solution.size() > 0) { auto red = OpenGLWrapper::Color::Red(); for(const Edge *edge : solution) { edge->draw(red); } agent.drawSolution(solution); // if(poseNumber >= solution.size() * 2) poseNumber = -1; // if(poseNumber >= 0) // agent.animateSolution(solution, poseNumber++); return solution; } #endif #ifdef VREPPLUGIN if(solution.size() > 0) { if(agent.validateSolution(solution, goal)) { fprintf(stderr, "VALID SOLUTION!\n"); } else { fprintf(stderr, "INVALID SOLUTION!\n"); } agent.animateSolution(solution); } #endif dfpair(stdout, "solution cost", "-1"); dfpair(stdout, "solution length", "-1"); return std::vector<const Edge*>(); }
void Bchart:: extend_rule(Edge* edge, Item * item, int right) { Edge* newEdge = new Edge(*edge, *item, right); if(printDebug() > 140) cerr << "extend_rule " << *edge << " " << *item << endl; const Term* itemTerm = item->term(); LeftRightGotIter lrgi(newEdge); globalGi = &lrgi; if(edge->loc() == edge->start()) { newEdge->prob() *= meEdgeProb(item->term(), newEdge, MCALC); /*stoprightp is p of stopping after seeing what currently passes for the rhs of the edge */ newEdge->rightMerit() = computeMerit(newEdge,RUCALC); delete edge; // just created; } else if(right) { newEdge->prob() *= meEdgeProb(item->term(),newEdge, RCALC); } else newEdge->prob() *= meEdgeProb(item->term(),newEdge, LCALC); if(right) { newEdge->rightMerit() = computeMerit(newEdge,RMCALC); } else { /* this is the left boundary stat for constituents that are continuing left, given the label and whatever currently appears on the left boundary of the constit. we only need this when going left */ newEdge->leftMerit() = computeMerit(newEdge,LMCALC); } if(itemTerm == Term::stopTerm) newEdge->status() = right ? 2 : 1; if(newEdge->status() == 2) newEdge->prob() *= endFactorComp(newEdge); if(printDebug() > 250 ) cerr << "Constructed " << *newEdge << "\t" << newEdge->leftMerit() << "\t" << newEdge->prob() << "\t" << newEdge->rightMerit() << endl; int tmp = curDemerits_[newEdge->start()][newEdge->loc()]; newEdge->demerits() = tmp; if(repeatRule(newEdge)) newEdge->rightMerit() = 0; newEdge->setmerit(); globalGi = NULL; if(newEdge->merit() == 0) { assert(alreadyPopedNum < 450000); alreadyPoped[alreadyPopedNum++] = newEdge; Edge* prd = newEdge->pred(); if(prd) prd->sucs().pop_front(); return; } ++ruleiCounts_; heap->insert(newEdge); if(itemTerm != Term::stopTerm) item->needme().push_back(newEdge); }
bool CodeThorn::operator==(const Edge& e1, const Edge& e2) { assert(&e1); assert(&e2); return e1.source==e2.source && e1.typesCode()==e2.typesCode() && e1.target==e2.target; }
set<RConstraint> RefinementConstraints::getAtomicPropositionsFromConditions(Label label) { set<RConstraint> result; Label* currentLabel = &label; bool allConditionsCollected = false; while (!allConditionsCollected) { SgNode* nodeToAnalyze=_cfanalyzer->getNode(*currentLabel); // Stop collecting constraints when either the "calculate_output" function or the "errorCheck" function is reached. // All relevant conditions of the 2014 RERS programs are to be found within those function. if(SgFunctionCallExp* funCall=SgNodeHelper::Pattern::matchFunctionCall(nodeToAnalyze)) { assert(funCall); string funName=SgNodeHelper::getFunctionName(funCall); if(funName=="calculate_output") { allConditionsCollected = true; } else if (funName=="errorCheck") { allConditionsCollected = true; } } // collect constraints from conditions if(SgNodeHelper::isCond(nodeToAnalyze)) { //cout << "DEBUG: constraints to be collected from condition: " << SgNodeHelper::unparseCond(nodeToAnalyze) // << " (Label: " << _labeler->labelToString(*currentLabel) << ")" <<endl; SgNode* rootOfCondition; nodeToAnalyze=nodeToAnalyze->get_parent(); if (SgIfStmt* ifstmt=isSgIfStmt(nodeToAnalyze)) { SgStatement* conditional = ifstmt->get_conditional(); rootOfCondition = SgNodeHelper::getExprStmtChild(conditional); } else { cout << "ERROR: type of condition unsupported by the traversal of RefinementConstraints." << endl; assert(0); } if (!dynamic_cast<SgBinaryOp*>(rootOfCondition)) { cout << "ERROR: root of Sage condition is not a binary operation." << endl; assert(0); } // add the atomic propositions of the condition to the set of constraints set<RConstraint> condConstraints = conditionToConstraints(dynamic_cast<SgBinaryOp*>(rootOfCondition)); result.insert(condConstraints.begin(), condConstraints.end()); //skip other conditions that have no effect on the occurence of "label" Flow edgeSet=_cfg->inEdges(*currentLabel); while (edgeSet.size()>=2) { // follow the {forward, false} edge leading to the current condition that would be traversed the earliest // (during a forward traversal starting from the cfg start node) Label pred = *currentLabel; for (Flow::iterator i = edgeSet.begin(); i!=edgeSet.end(); i++) { Edge inEdge = *i; if( inEdge.isType(EDGE_FALSE) && (inEdge.source.getId() < pred.getId()) ) { pred = inEdge.source; bool isCond = SgNodeHelper::isCond(_labeler->getNode(pred)); assert(isCond); } } currentLabel = &pred; edgeSet=_cfg->inEdges(*currentLabel); } } //proceed to the next label to be analyzed (predecessor in cfg) if (!allConditionsCollected) { Flow edgeSet=_cfg->inEdges(*currentLabel); // Apart from conditions, all cfg node within a RERS program's "calculate_output" and "errorCheck" functions // should have exactly one predeccesor. assert(edgeSet.size()==1); Flow::iterator predecessor = edgeSet.begin(); Edge pred = *predecessor; currentLabel = &pred.source; } } return result; }
GSSWAligner::GSSWAligner( Graph& g, int32_t _match, int32_t _mismatch, int32_t _gap_open, int32_t _gap_extension ) { match = _match; mismatch = _mismatch; gap_open = _gap_open; gap_extension = _gap_extension; // these are used when setting up the nodes // they can be cleaned up via destroy_alignable_graph() nt_table = gssw_create_nt_table(); score_matrix = gssw_create_score_matrix(match, mismatch); graph = gssw_graph_create(g.node_size()); for (int i = 0; i < g.node_size(); ++i) { Node* n = g.mutable_node(i); gssw_node* node = (gssw_node*)gssw_node_create(n, n->id(), n->sequence().c_str(), nt_table, score_matrix); nodes[n->id()] = node; gssw_graph_add_node(graph, node); } for (int i = 0; i < g.edge_size(); ++i) { // Convert all the edges Edge* e = g.mutable_edge(i); if(!e->from_start() && !e->to_end()) { // This is a normal end to start edge. gssw_nodes_add_edge(nodes[e->from()], nodes[e->to()]); } else if(e->from_start() && e->to_end()) { // This is a start to end edge, but isn't reversing and can be converted to a normal end to start edge. // Flip the start and end gssw_nodes_add_edge(nodes[e->to()], nodes[e->from()]); } else { // TODO: It's a reversing edge, which gssw doesn't support yet. What // we should really do is do a topological sort to break cycles, and // then flip everything at the lower-rank end of this edge around, // so we don't have to deal with its reversing-ness. But for now we // just die so we don't get nonsense into gssw. #pragma omp critical { // We need the critical section so we don't throw uncaught // exceptions in multiple threads at once, leading to C++ trying // to run termiante in parallel. This doesn't make it safe, just // slightly safer. cerr << "Can't gssw over reversing edge " <<e->from() << (e->from_start() ? " start" : " end") << " -> " << e->to() << (e->to_end() ? " end" : " start") << endl; // TODO: there's no safe way to kill the program without a way // to signal the master to do it, via a shared variable in the // clause that made us parallel. } exit(1); } } }
CapabilityLevel canCompile(Graph& graph) { if (graph.m_codeBlock->instructionCount() > Options::maximumFTLCandidateInstructionCount()) { if (verboseCapabilities()) dataLog("FTL rejecting ", *graph.m_codeBlock, " because it's too big.\n"); return CannotCompile; } if (graph.m_codeBlock->codeType() != FunctionCode) { if (verboseCapabilities()) dataLog("FTL rejecting ", *graph.m_codeBlock, " because it doesn't belong to a function.\n"); return CannotCompile; } CapabilityLevel result = CanCompileAndOSREnter; for (BlockIndex blockIndex = graph.numBlocks(); blockIndex--;) { BasicBlock* block = graph.block(blockIndex); if (!block) continue; // We don't care if we can compile blocks that the CFA hasn't visited. if (!block->cfaHasVisited) continue; for (unsigned nodeIndex = 0; nodeIndex < block->size(); ++nodeIndex) { Node* node = block->at(nodeIndex); for (unsigned childIndex = graph.numChildren(node); childIndex--;) { Edge edge = graph.child(node, childIndex); if (!edge) continue; switch (edge.useKind()) { case UntypedUse: case Int32Use: case KnownInt32Use: case Int52RepUse: case NumberUse: case RealNumberUse: case DoubleRepUse: case DoubleRepRealUse: case BooleanUse: case KnownBooleanUse: case CellUse: case KnownCellUse: case ObjectUse: case FunctionUse: case ObjectOrOtherUse: case StringUse: case KnownStringUse: case StringObjectUse: case StringOrStringObjectUse: case SymbolUse: case FinalObjectUse: case NotCellUse: case OtherUse: case MiscUse: case StringIdentUse: case NotStringVarUse: case MachineIntUse: case DoubleRepMachineIntUse: // These are OK. break; default: // Don't know how to handle anything else. if (verboseCapabilities()) { dataLog("FTL rejecting node in ", *graph.m_codeBlock, " because of bad use kind: ", edge.useKind(), " in node:\n"); graph.dump(WTF::dataFile(), " ", node); } return CannotCompile; } } switch (canCompile(node)) { case CannotCompile: if (verboseCapabilities()) { dataLog("FTL rejecting node in ", *graph.m_codeBlock, ":\n"); graph.dump(WTF::dataFile(), " ", node); } return CannotCompile; case CanCompile: if (result == CanCompileAndOSREnter && verboseCompilationEnabled()) { dataLog("FTL disabling OSR entry because of node:\n"); graph.dump(WTF::dataFile(), " ", node); } result = CanCompile; break; case CanCompileAndOSREnter: break; } if (node->op() == ForceOSRExit) break; } } return result; }
void DCEL::insert_new_edge(Edge* edge) { const Vertex& from = edge->from(); #ifdef DEBUG cout << "insert" << *edge << endl; if (from.point == point_type(12, 72)) { int kkkk = 10; } #endif if (vertexEdge.find(from) == vertexEdge.end() || vertexEdge[from] == NULL) { vertexEdge[from] = edge; edge->right_next(edge); return; } auto edges = get_all_edges(from); double minAngle = 2 * M_PI; double maxAngle = 0; Edge* minEdge = NULL; for (auto e : edges) { double myAngle = angle2pi(e); if (myAngle < minAngle) { minAngle = myAngle; minEdge = e; } } maxAngle = angle2pi(minEdge->right_next()); double eangle = angle2pi(edge); Edge* prevEdge = NULL; if (eangle > maxAngle || eangle < minAngle) { prevEdge = minEdge; } else { for (auto e : edges) { auto angleBefore = angle2pi(e); assert(angleBefore != eangle); // if(angleBefore == eangle){ // // } auto angleAfter = angle2pi(e->right_next()); if (angleBefore == eangle) { auto len1 = segment_length(edge->get_segment()); auto len2 = segment_length(e->get_segment()); if (edge->to().point == e->to().point) return; // cout << "add split segment from" << edge->from().point << " to split " << edge->to().point << e->to().point << endl; if (len2 > len1) { deleteEdge(e); add_segment(from.point, edge->to().point); } add_segment(edge->to().point, e->to().point); return; } if (angleBefore > eangle && angleAfter < eangle) { prevEdge = e; break; } } } #ifndef DEBUG assert(prevEdge != NULL); #else if (prevEdge == NULL) { cout << "-----------" << endl; for (auto e : edges) { cout << *e << ", "; cout << angle2pi(e) << " " << endl; } cout << "vvvvvvvvvvvvv" << endl; cout << *edge << ", "; cout << eangle << endl; cout << "***********" << endl; assert(false); } #endif edge->right_next(prevEdge->right_next()); prevEdge->right_next(edge); return; }
// report statistics // void SM_Statistics( int frameid, ExtrinsicParameters &pose ) { int i; // open the file FILE *f = fopen( "loca_stats.dat", "a" ); if ( f == NULL ) { LOG(LEVEL_ERROR, "could not open file loca_stats.dat!"); return; } // compute the distribution of correspondences double accepted=0.0, pending=0.0, unknown=0.0; int n = cq.size(); for (i=0; i<n; i++) { if (cq[i].line == NULL) continue; if (cq[i].line->status == ACCEPTED) accepted += 1.0 / n; if (cq[i].line->status == PENDING) pending += 1.0 / n; if (cq[i].line->status == UNKNOWN) unknown += 1.0 / n; } // compute the average and standard deviation of angular error for accepted correspondences doubleVector angles; Vec3d center = pose.getTranslation(); for (i=0; i<n; i++) { if ( cq[i].line == NULL ) continue; if ( cq[i].line->status != ACCEPTED ) continue; Edge *line = cq[i].line; Vec3d a = line->getA()-center; Vec3d b = line->getB()-center; EdgePlane selected_edgeplane = cq[i].eps[cq[i].eid]; EdgePlane edgeplane = EdgePlane( a, b, center, selected_edgeplane._cameraId, 0, 0 ); edgeplane.fromWorldFrameToCameraFrame( pose ); double angle = toDegrees( edgeplane.angle( selected_edgeplane ) ); angles.push_back( angle ); } int n_accepted = angles.size(); double average = 0.0; double stdev = 0.0; if ( n_accepted > 0 ) { for (i=0; i<angles.size(); i++) average += angles[i] / n_accepted; for (i=0; i<angles.size(); i++) stdev += ( angles[i] - average ) * ( angles[i] - average ); stdev = sqrt( stdev ) / n_accepted; } // write the stats into the file fprintf(f, "%d %d %.1f %.1f %.1f %.2f %.2f\n", frameid, n, 100.0 * accepted, 100.0 * pending, 100.0 * unknown, average, stdev); fclose(f); }
int exp() { /*************************************************************************** * Configuration ****************************************************************************/ // CommunicationPolicy typedef graybat::communicationPolicy::BMPI CP; // GraphPolicy typedef graybat::graphPolicy::BGL<Function> GP; // Cage typedef graybat::Cage<CP, GP> Cage; typedef typename Cage::Vertex Vertex; typedef typename Cage::Edge Edge; /*************************************************************************** * Initialize Communication ****************************************************************************/ // Create GoL Graph Config config; CP communicationPolicy(config); Cage cage(communicationPolicy); // Set communication pattern cage.setGraph(graybat::pattern::BiStar(cage.getPeers().size())); // Distribute vertices cage.distribute(graybat::mapping::Consecutive()); /*************************************************************************** * Run Simulation ****************************************************************************/ //std::vector<Event> events; std::array<unsigned, 1> input {{0}}; std::array<unsigned, 1> output {{0}}; const Vertex reply = cage.getVertex(0); for(Vertex v : cage.hostedVertices){ if(v == reply){ while(true){ Edge e = cage.recv(output); std::cout << "Got msg from " << e.source.id << ": "<< output[0] << std::endl; output[0]++; cage.send(e.inverse(), output); } } else { input[0] = v.id; v.spread(input); v.collect(input); std::cout << " Got input from master:" << input[0] << std::endl; } } return 0; }
bool SGSmoothingVisitor::visit(StringGraph* pGraph, Vertex* pVertex) { (void)pGraph; if(pVertex->getColor() == GC_RED) return false; bool found = false; for(size_t idx = 0; idx < ED_COUNT; idx++) { EdgeDir dir = EDGE_DIRECTIONS[idx]; EdgePtrVec edges = pVertex->getEdges(dir); if(edges.size() <= 1) continue; for(size_t i = 0; i < edges.size(); ++i) { if(edges[i]->getEnd()->getColor() == GC_RED) return false; } //std::cout << "Smoothing " << pVertex->getID() << "\n"; const int MAX_WALKS = 10; const int MAX_DISTANCE = 5000; bool bIsDegenerate = false; bool bFailGapCheck = false; bool bFailDivergenceCheck = false; bool bFailIndelSizeCheck = false; SGWalkVector variantWalks; SGSearch::findVariantWalks(pVertex, dir, MAX_DISTANCE, MAX_WALKS, variantWalks); if(variantWalks.size() > 0) { found = true; size_t selectedIdx = -1; size_t selectedCoverage = 0; // Calculate the minimum amount overlapped on the start/end vertex. // This is used to properly extract the sequences from walks that represent the variation. int minOverlapX = std::numeric_limits<int>::max(); int minOverlapY = std::numeric_limits<int>::max(); for(size_t i = 0; i < variantWalks.size(); ++i) { if(variantWalks[i].getNumEdges() <= 1) bIsDegenerate = true; // Calculate the walk coverage using the internal vertices of the walk. // The walk with the highest coverage will be retained size_t walkCoverage = 0; for(size_t j = 1; j < variantWalks[i].getNumVertices() - 1; ++j) walkCoverage += variantWalks[i].getVertex(j)->getCoverage(); if(walkCoverage > selectedCoverage || selectedCoverage == 0) { selectedIdx = i; selectedCoverage = walkCoverage; } Edge* pFirstEdge = variantWalks[i].getFirstEdge(); Edge* pLastEdge = variantWalks[i].getLastEdge(); if((int)pFirstEdge->getMatchLength() < minOverlapX) minOverlapX = pFirstEdge->getMatchLength(); if((int)pLastEdge->getTwin()->getMatchLength() < minOverlapY) minOverlapY = pLastEdge->getTwin()->getMatchLength(); } // Calculate the strings for each walk that represent the region of variation StringVector walkStrings; for(size_t i = 0; i < variantWalks.size(); ++i) { Vertex* pStartVertex = variantWalks[i].getStartVertex(); Vertex* pLastVertex = variantWalks[i].getLastVertex(); assert(pStartVertex != NULL && pLastVertex != NULL); std::string full = variantWalks[i].getString(SGWT_START_TO_END); int posStart = 0; int posEnd = 0; if(dir == ED_ANTISENSE) { // pLast ----------- // pStart ------------ // full -------------------- // out ---- posStart = pLastVertex->getSeqLen() - minOverlapY; posEnd = full.size() - (pStartVertex->getSeqLen() - minOverlapX); } else { // pStart -------------- // pLast ----------- // full --------------------- // out ---- posStart = pStartVertex->getSeqLen() - minOverlapX; // match start position posEnd = full.size() - (pLastVertex->getSeqLen() - minOverlapY); // match end position } std::string out; if(posEnd > posStart) out = full.substr(posStart, posEnd - posStart); walkStrings.push_back(out); } assert(selectedIdx != (size_t)-1); SGWalk& selectedWalk = variantWalks[selectedIdx]; assert(selectedWalk.isIndexed()); // Check the divergence of the other walks to this walk StringVector cigarStrings; std::vector<int> maxIndel; std::vector<double> gapPercent; // percentage of matching that is gaps std::vector<double> totalPercent; // percent of total alignment that is mismatch or gap cigarStrings.resize(variantWalks.size()); gapPercent.resize(variantWalks.size()); totalPercent.resize(variantWalks.size()); maxIndel.resize(variantWalks.size()); for(size_t i = 0; i < variantWalks.size(); ++i) { if(i == selectedIdx) continue; // We want to compute the total gap length, total mismatches and percent // divergence between the two paths. int matchLen = 0; int totalDiff = 0; int gapLength = 0; int maxGapLength = 0; // We have to handle the degenerate case where one internal string has zero length // this can happen when there is an isolated insertion/deletion and the walks are like: // x -> y -> z // x -> z if(walkStrings[selectedIdx].empty() || walkStrings[i].empty()) { matchLen = std::max(walkStrings[selectedIdx].size(), walkStrings[i].size()); totalDiff = matchLen; gapLength = matchLen; } else { AlnAln *aln_global; aln_global = aln_stdaln(walkStrings[selectedIdx].c_str(), walkStrings[i].c_str(), &aln_param_blast, 1, 1); // Calculate the alignment parameters while(aln_global->outm[matchLen] != '\0') { if(aln_global->outm[matchLen] == ' ') totalDiff += 1; matchLen += 1; } std::stringstream cigarSS; for (int j = 0; j != aln_global->n_cigar; ++j) { char cigarOp = "MID"[aln_global->cigar32[j]&0xf]; int cigarLen = aln_global->cigar32[j]>>4; if(cigarOp == 'I' || cigarOp == 'D') { gapLength += cigarLen; if(gapLength > maxGapLength) maxGapLength = gapLength; } cigarSS << cigarLen; cigarSS << cigarOp; } cigarStrings[i] = cigarSS.str(); /* printf("1: %s\n", aln_global->out1); printf("M: %s\n", aln_global->outm); printf("2: %s\n", aln_global->out2); printf("CIGAR: %s\n", cigarStrings[i].c_str()); */ aln_free_AlnAln(aln_global); } double percentDiff = (double)totalDiff / matchLen; double percentGap = (double)gapLength / matchLen; if(percentDiff > m_maxTotalDivergence) bFailDivergenceCheck = true; if(percentGap > m_maxGapDivergence) bFailGapCheck = true; if(maxGapLength > m_maxIndelLength) bFailIndelSizeCheck = true; gapPercent[i] = percentGap; totalPercent[i] = percentDiff; maxIndel[i] = maxGapLength; //printf("ml: %d tmm: %d pd: %lf pg: %lf\n", matchLen, totalDiff, percentDiff, percentGap); } if(bIsDegenerate || bFailGapCheck || bFailDivergenceCheck || bFailIndelSizeCheck) continue; // Write the selected path to the variants file as variant 0 int variantIdx = 0; std::string selectedSequence = selectedWalk.getString(SGWT_START_TO_END); std::stringstream ss; ss << "variant-" << m_numRemovedTotal << "/" << variantIdx++; writeFastaRecord(&m_outFile, ss.str(), selectedSequence); // The vertex set for each walk is not necessarily disjoint, // the selected walk may contain vertices that are part // of other paths. We handle this be initially marking all // vertices of the for(size_t i = 0; i < variantWalks.size(); ++i) { if(i == selectedIdx) continue; SGWalk& currWalk = variantWalks[i]; for(size_t j = 0; j < currWalk.getNumEdges() - 1; ++j) { Edge* currEdge = currWalk.getEdge(j); // If the vertex is also on the selected path, do not mark it Vertex* currVertex = currEdge->getEnd(); if(!selectedWalk.containsVertex(currVertex->getID())) { currEdge->getEnd()->setColor(GC_RED); } } // Write the variant to a file std::string variantSequence = currWalk.getString(SGWT_START_TO_END); std::stringstream variantID; std::stringstream ss; ss << "variant-" << m_numRemovedTotal << "/" << variantIdx++; ss << " IGD:" << (double)gapPercent[i] << " ITD:" << totalPercent[i] << " MID: " << maxIndel[i] << " InternalCigar:" << cigarStrings[i]; writeFastaRecord(&m_outFile, ss.str(), variantSequence); } if(variantWalks.size() == 2) m_simpleBubblesRemoved += 1; else m_complexBubblesRemoved += 1; ++m_numRemovedTotal; } }
//-------------------------------------------------------------------------------------------------- void IncrementalBlueNoise::swapTestEdge(Edge * diagonal) { // Note that diagonal is both input and output and it is always // kept in counterclockwise direction (this is not required by all // finctions in ttl:: now) // Swap by rotating counterclockwise // Use the same objects - no deletion or new objects Edge* eR = diagonal; /*Code less*/ if (eR == NULL) // Boundary return; Edge* eL = eR->getTwinEdge(); if (eL == NULL) // Boundary return; /**/ Edge* eL_1 = eL->getNextEdgeInFace(); Edge* eL_2 = eL_1->getNextEdgeInFace(); Edge* eR_1 = eR->getNextEdgeInFace(); Edge* eR_2 = eR_1->getNextEdgeInFace(); // avoid node to be dereferenced to zero and deleted Handle<Node2d> nR = eR_2->getSourceNode(); Handle<Node2d> nL = eL_2->getSourceNode(); //TEST HERE! /*Code less*/ Handle<Node2d> n1 = eL->getSourceNode(); Handle<Node2d> n2 = nR; Handle<Node2d> n3 = eR->getSourceNode(); Handle<Node2d> n4 = nL; if (InCircle(n1, n2, n3, n4) >= 0) return; #ifdef _Debug_Demo std::array<Handle<Node2d>, 4> flip_record; flip_record[0] = nR; flip_record[1] = n3; flip_record[2] = nL; flip_record[3] = n4; flip_records.push_back(flip_record); #endif /*Code less*/ Edge* leL; if (eL->isLeadingEdge()) leL = eL; else if (eL_1->isLeadingEdge()) leL = eL_1; else if (eL_2->isLeadingEdge()) leL = eL_2; Edge* leR; if (eR->isLeadingEdge()) leR = eR; else if (eR_1->isLeadingEdge()) leR = eR_1; else if (eR_2->isLeadingEdge()) leR = eR_2; removeLeadingEdgeFromList(leL); removeLeadingEdgeFromList(leR); Edge* eUp = new Edge; // Edge* eLow = new Edge; // eUp->setSourceNode(nR.getPtr()); eUp->setNextEdgeInFace(eL_2); eL_2->setNextEdgeInFace(eR_1); eR_1->setNextEdgeInFace(eUp); eLow->setSourceNode(nL.getPtr()); eLow->setNextEdgeInFace(eR_2); eR_2->setNextEdgeInFace(eL_1); eL_1->setNextEdgeInFace(eLow); eUp->setTwinEdge(eLow); eLow->setTwinEdge(eUp); addLeadingEdge(eUp); addLeadingEdge(eLow); swapTestEdge(eL_2); swapTestEdge(eL_1); }
bool SGSmallRepeatResolveVisitor::visit(StringGraph* /*pGraph*/, Vertex* pX) { bool changed = false; // If the vertex has more than MAX_EDGES, do not // attempt to resolve size_t MAX_EDGES = 10; for(size_t idx = 0; idx < ED_COUNT; idx++) { EdgeDir dir = EDGE_DIRECTIONS[idx]; EdgePtrVec x_edges = pX->getEdges(dir); // These edges are already sorted if(x_edges.size() < 2 || x_edges.size() > MAX_EDGES) continue; // Try to eliminate the shortest edge from this vertex (let this be X->Y) // If Y has a longer edge than Y->X in the same direction, we remove X->Y // Edges are sorted by length so the last edge is the shortest Edge* pXY = x_edges.back(); size_t xy_len = pXY->getOverlap().getOverlapLength(0); size_t x_longest_len = x_edges.front()->getOverlap().getOverlapLength(0); if(xy_len == x_longest_len) continue; Edge* pYX = pXY->getTwin(); Vertex* pY = pXY->getEnd(); EdgePtrVec y_edges = pY->getEdges(pYX->getDir()); if(y_edges.size() > MAX_EDGES) continue; size_t yx_len = pYX->getOverlap().getOverlapLength(0); size_t y_longest_len = 0; for(size_t i = 0; i < y_edges.size(); ++i) { Edge* pYZ = y_edges[i]; if(pYZ == pYX) continue; // skip Y->X size_t yz_len = pYZ->getOverlap().getOverlapLength(0); if(yz_len > y_longest_len) y_longest_len = yz_len; } if(y_longest_len > yx_len) { // Delete the edge if the difference between the shortest and longest is greater than minDiff int x_diff = x_longest_len - xy_len; int y_diff = y_longest_len - yx_len; if(x_diff > m_minDiff && y_diff > m_minDiff) { /* printf("Edge %s -> %s is likely a repeat\n", pX->getID().c_str(), pY->getID().c_str()); printf("Actual overlap lengths: %zu and %zu\n", xy_len, yx_len); printf("Spanned by longer edges of size: %zu and %zu\n", x_longest_len, y_longest_len); printf("Differences: %d and %d\n", x_diff, y_diff); */ pX->deleteEdge(pXY); pY->deleteEdge(pYX); changed = true; } } } return changed; }
bool isWithinPowerOfTwo(Edge edge) { return isWithinPowerOfTwo<power>(edge.node()); }
// Find bubbles (nodes where there is a split and then immediate rejoin) and mark them for removal bool SGBubbleEdgeVisitor::visit(StringGraph* /*pGraph*/, Vertex* pX) { bool bubble_found = false; for(size_t idx = 0; idx < ED_COUNT; idx++) { EdgeDir dir = EDGE_DIRECTIONS[idx]; EdgePtrVec edges = pX->getEdges(dir); if(edges.size() == 2) // di-bubbles only for now { // Determine which edge has a shorter overlap to pX // Call the longer overlap pY, the shorter pZ Edge* pXY; Edge* pXZ; if(edges[0]->getOverlap().getOverlapLength(0) > edges[1]->getOverlap().getOverlapLength(0)) { pXY = edges[0]; pXZ = edges[1]; } else if(edges[1]->getOverlap().getOverlapLength(0) > edges[0]->getOverlap().getOverlapLength(0)) { pXY = edges[1]; pXZ = edges[0]; } else { break; // equal length overlaps, cannot be a bubble or else the vertices would be contained } // Mark the neighbors of pZ as the "target" vertices // if they can be reached by pY we mark pY as being unreliable and remove it typedef std::list<Vertex*> VertexPtrList; VertexPtrList targetList; EdgeDir targetDir = pXZ->getTransitiveDir(); EdgePtrVec targetEdges = pXZ->getEnd()->getEdges(targetDir); for(size_t i = 0; i < targetEdges.size(); ++i) targetList.push_back(targetEdges[i]->getEnd()); // Start exploring from pY ExploreQueue queue; Overlap ovrXY = pXY->getOverlap(); EdgeDesc edXY = pXY->getDesc(); queue.push(ExploreElement(edXY, ovrXY)); int numSteps = 100; WARN_ONCE("USING FIXED NUMBER OF STEPS IN BUBBLE EDGE"); while(!queue.empty() && numSteps-- > 0) { ExploreElement ee = queue.front(); EdgeDesc& edXY = ee.ed; Vertex* pY = edXY.pVertex; Overlap& ovrXY = ee.ovr; queue.pop(); // Check if Y is on the target list VertexPtrList::iterator iter = targetList.begin(); while(iter != targetList.end()) { if(*iter == edXY.pVertex) targetList.erase(iter++); else ++iter; } if(targetList.empty()) break; // Enqueue the neighbors of pY EdgeDir dirY = edXY.getTransitiveDir(); EdgePtrVec edges = pY->getEdges(dirY); for(size_t i = 0; i < edges.size(); ++i) { Edge* pEdge = edges[i]; Vertex* pZ = pEdge->getEnd(); // Compute the edgeDesc and overlap on pX for this edge Overlap ovrYZ = pEdge->getOverlap(); if(SGAlgorithms::hasTransitiveOverlap(ovrXY, ovrYZ)) { Overlap ovrXZ = SGAlgorithms::inferTransitiveOverlap(ovrXY, ovrYZ); EdgeDesc edXZ = SGAlgorithms::overlapToEdgeDesc(pZ, ovrXZ); queue.push(ExploreElement(edXZ, ovrXZ)); } } } if(targetList.empty()) { // bubble found pXZ->getEnd()->deleteEdges(); pXZ->getEnd()->setColor(GC_RED); bubble_found = true; ++num_bubbles; } } } return bubble_found; }
/* * The method of least squares is a standard technique used to find * the equation of a straight line from a set of data. Equation for a * straight line is given by * y = mx + b * where m is the slope of the line and b is the y-intercept. * * Given a set of n points {(x1,y1), x2,y2),...,xn,yn)}, let * SUMx = x1 + x2 + ... + xn * SUMy = y1 + y2 + ... + yn * SUMxy = x1*y1 + x2*y2 + ... + xn*yn * SUMxx = x1*x1 + x2*x2 + ... + xn*xn * * The slope and y-intercept for the least-squares line can be * calculated using the following equations: * slope (m) = ( SUMx*SUMy - n*SUMxy ) / ( SUMx*SUMx - n*SUMxx ) * y-intercept (b) = ( SUMy - slope*SUMx ) / n */ Edge * IEdgesExtractor::fitLine(const VerticesMap & someVertices, int edgeID, const double errThs) const{ if(someVertices.size() < 2){ return 0; } double SUMx = 0; double SUMy = 0; double SUMxy = 0; double SUMxx = 0; double SUMyy = 0; //++ double slope; double y_intercept; double tx = 0; double ty = 0; VerticesMap::const_iterator it = someVertices.begin(); double minX = ((Vertex*)it->second)->x(); double maxX = ((Vertex*)it->second)->x(); double minY = ((Vertex*)it->second)->y(); double maxY = ((Vertex*)it->second)->y(); Vertex* prevV = it->second; while(it != someVertices.end()){ if((errThs != 1000)//ugly but for S&M && prevV->dist((*it).second) > maxVerticesDistance) { return 0; //SM } prevV = (*it).second; tx = ((Vertex*)(*it).second)->x(); ty = ((Vertex*)(*it).second)->y(); SUMx += tx; SUMy += ty; SUMxy += (tx*ty); SUMxx += (tx*tx); SUMyy += (ty*ty); //++ if(tx<minX){ minX = tx; } if(tx > maxX){ maxX = tx; } if(ty<minY){ minY = ty; } if(ty>maxY){ maxY = ty; } ++it; } int num = someVertices.size(); double slopeNumerator = (num*SUMxy)-(SUMx*SUMy); double slopeDenum = (num*SUMxx)-(SUMx*SUMx); slope = slopeNumerator / slopeDenum; y_intercept = ((SUMxx*SUMy)-(SUMx*SUMxy)) / slopeDenum; double SUMres = 0; double res = 0; Edge * edge = 0; //// case its ok for vertical distance for(it = someVertices.begin(); it != someVertices.end(); ++it){ tx = ((Vertex*)(*it).second)->x(); ty = ((Vertex*)(*it).second)->y(); res = (ty - slope*tx) - y_intercept; SUMres += res*res; } if(SUMres < errThs){ Eigen::Vector2d min, max; min[0] = minX; min[1] = minY; max[0] = maxX; max[1] = maxY; edge = segmentalize(slope, y_intercept, min, max); edge->id = edgeID; } if(edge != 0){ return edge; } //// case its ok for orizontal distance SUMres = 0; slopeNumerator = (SUMx*SUMy)-(num*SUMxy); slopeDenum = (SUMy*SUMy)-(num*SUMyy); slope = slopeNumerator / slopeDenum; y_intercept = ((SUMy*SUMxy)-(SUMyy*SUMx)) / slopeDenum; for(it = someVertices.begin(); it != someVertices.end(); ++it){ tx = ((Vertex*)(*it).second)->x(); ty = ((Vertex*)(*it).second)->y(); res = (tx - slope*ty) - y_intercept; SUMres += res*res; } Edge * e = 0; if(SUMres < errThs){ //SM Eigen::Vector2d min, max; min[0] = minY; min[1] = minX; max[0] = maxY; max[1] = maxX; edge = segmentalize(slope, y_intercept, min, max); e->id = edgeID; Vertex* f = new Vertex(edgeID,e->getVertexFrom().y(), e->getVertexFrom().x()); Vertex* t = new Vertex(edgeID,e->getVertexTo().y(), e->getVertexTo().x()); edge = new Edge(edgeID, f, t); delete e; } return edge; }
void QTessellatorPrivate::processIntersections() { QDEBUG() << "PROCESS INTERSECTIONS"; // process intersections while (!intersections.isEmpty()) { Intersections::iterator it = intersections.begin(); if (it.key().y != y) break; // swap edges QDEBUG() << " swapping intersecting edges "; int min = scanline.size; int max = 0; Q27Dot5 xmin = INT_MAX; Q27Dot5 xmax = INT_MIN; int num = 0; while (1) { const Intersection &i = it.key(); int next = it->next; int edgePos = scanline.findEdge(i.edge); if (edgePos >= 0) { ++num; min = qMin(edgePos, min); max = qMax(edgePos, max); Edge *edge = scanline.edges[edgePos]; xmin = qMin(xmin, edge->positionAt(y)); xmax = qMax(xmax, edge->positionAt(y)); } Intersection key; key.y = y; key.edge = next; it = intersections.find(key); intersections.remove(i); if (it == intersections.end()) break; } if (num < 2) continue; Q_ASSERT(min != max); QDEBUG() << "sorting between" << min << "and" << max << "xpos=" << xmin << xmax; while (min > 0 && scanline.edges[min - 1]->positionAt(y) >= xmin) { QDEBUG() << " adding edge on left"; --min; } while (max < scanline.size - 1 && scanline.edges[max + 1]->positionAt(y) <= xmax) { QDEBUG() << " adding edge on right"; ++max; } qSort(scanline.edges + min, scanline.edges + max + 1, EdgeSorter(y)); #ifdef DEBUG for (int i = min; i <= max; ++i) QDEBUG() << " " << scanline.edges[i]->edge << "at pos" << i; #endif for (int i = min; i <= max; ++i) { Edge *edge = scanline.edges[i]; edge->intersect_left = true; edge->intersect_right = true; edge->mark = true; } } }
bool Edge::operator <(Edge pEdge) { return this->SqLength() < pEdge.SqLength(); }
void Radiosity::setupVBOs() { HandleGLError("enter radiosity setupVBOs()"); mesh_tri_verts.clear(); mesh_tri_indices.clear(); mesh_textured_tri_indices.clear(); // initialize the data in each vector int num_faces = mesh->numFaces(); assert (num_faces > 0); for (int i = 0; i < num_faces; i++) { Face *f = mesh->getFace(i); Edge *e = f->getEdge(); glm::vec3 normal = f->computeNormal(); double avg_s = 0; double avg_t = 0; glm::vec3 avg_color(0,0,0); int start = mesh_tri_verts.size(); // wireframe is normally black, except when it's the special // patch, then the wireframe is red glm::vec4 wireframe_color(0,0,0,0.5); if (args->render_mode == RENDER_FORM_FACTORS && i == max_undistributed_patch) { wireframe_color = glm::vec4(1,0,0,1); } // add the 4 corner vertices for (int j = 0; j < 4; j++) { glm::vec3 pos = ((*f)[j])->get(); double s = (*f)[j]->get_s(); double t = (*f)[j]->get_t(); glm::vec3 color = setupHelperForColor(f,i,j); color = glm::vec3(linear_to_srgb(color.r), linear_to_srgb(color.g), linear_to_srgb(color.b)); avg_color += 0.25f * color; mesh_tri_verts.push_back(VBOPosNormalColor(pos,normal, glm::vec4(color.r,color.g,color.b,1.0), wireframe_color, s,t)); avg_s += 0.25 * s; avg_t += 0.25 * t; e = e->getNext(); } // the centroid (for wireframe rendering) glm::vec3 centroid = f->computeCentroid(); mesh_tri_verts.push_back(VBOPosNormalColor(centroid,normal, glm::vec4(avg_color.r,avg_color.g,avg_color.b,1), glm::vec4(1,1,1,1), avg_s,avg_t)); if (f->getMaterial()->hasTextureMap()) { mesh_textured_tri_indices.push_back(VBOIndexedTri(start+0,start+1,start+4)); mesh_textured_tri_indices.push_back(VBOIndexedTri(start+1,start+2,start+4)); mesh_textured_tri_indices.push_back(VBOIndexedTri(start+2,start+3,start+4)); mesh_textured_tri_indices.push_back(VBOIndexedTri(start+3,start+0,start+4)); } else { mesh_tri_indices.push_back(VBOIndexedTri(start+0,start+1,start+4)); mesh_tri_indices.push_back(VBOIndexedTri(start+1,start+2,start+4)); mesh_tri_indices.push_back(VBOIndexedTri(start+2,start+3,start+4)); mesh_tri_indices.push_back(VBOIndexedTri(start+3,start+0,start+4)); } } assert ((int)mesh_tri_verts.size() == num_faces*5); assert ((int)mesh_tri_indices.size() + (int)mesh_textured_tri_indices.size() == num_faces*4); // copy the data to each VBO glBindBuffer(GL_ARRAY_BUFFER,mesh_tri_verts_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(VBOPosNormalColor) * num_faces * 5, &mesh_tri_verts[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,mesh_tri_indices_VBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(VBOIndexedTri) * mesh_tri_indices.size(), &mesh_tri_indices[0], GL_STATIC_DRAW); if (mesh_textured_tri_indices.size() > 0) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,mesh_textured_tri_indices_VBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(VBOIndexedTri) * mesh_textured_tri_indices.size(), &mesh_textured_tri_indices[0], GL_STATIC_DRAW); } HandleGLError("radiosity setupVBOs() just before texture"); // WARNING: this naive VBO implementation only allows a single texture // FIXME: something still buggy about textures int num_textured_materials = 0; for (unsigned int mat = 0; mat < mesh->materials.size(); mat++) { Material *m = mesh->materials[mat]; if (m->hasTextureMap()) { // FIXME: old gl... //glBindTexture(GL_TEXTURE_2D,m->getTextureID()); num_textured_materials++; } } assert (num_textured_materials <= 1); HandleGLError("leave radiosity setupVBOs()"); }
bool Edge::operator >=(Edge pEdge) { return this->SqLength() >= pEdge.SqLength(); }
void fixupBlock(BasicBlock* block) { if (!block) return; switch (m_graph.m_form) { case SSA: break; case ThreadedCPS: { // Clean up variable links for the block. We need to do this before the actual DCE // because we need to see GetLocals, so we can bypass them in situations where the // vars-at-tail point to a GetLocal, the GetLocal is dead, but the Phi it points // to is alive. for (unsigned phiIndex = 0; phiIndex < block->phis.size(); ++phiIndex) { if (!block->phis[phiIndex]->shouldGenerate()) { // FIXME: We could actually free nodes here. Except that it probably // doesn't matter, since we don't add any nodes after this phase. // https://bugs.webkit.org/show_bug.cgi?id=126239 block->phis[phiIndex--] = block->phis.last(); block->phis.removeLast(); } } cleanVariables(block->variablesAtHead); cleanVariables(block->variablesAtTail); break; } default: RELEASE_ASSERT_NOT_REACHED(); return; } for (unsigned indexInBlock = block->size(); indexInBlock--;) { Node* node = block->at(indexInBlock); if (node->shouldGenerate()) continue; switch (node->op()) { case MovHint: { ASSERT(node->child1().useKind() == UntypedUse); if (!node->child1()->shouldGenerate()) { node->setOpAndDefaultFlags(ZombieHint); node->child1() = Edge(); break; } node->setOpAndDefaultFlags(MovHint); break; } case ZombieHint: { // Currently we assume that DCE runs only once. RELEASE_ASSERT_NOT_REACHED(); break; } default: { if (node->flags() & NodeHasVarArgs) { for (unsigned childIdx = node->firstChild(); childIdx < node->firstChild() + node->numChildren(); childIdx++) { Edge edge = m_graph.m_varArgChildren[childIdx]; if (!edge || edge.willNotHaveCheck()) continue; m_insertionSet.insertNode(indexInBlock, SpecNone, Phantom, node->codeOrigin, edge); } node->convertToPhantomUnchecked(); node->children.reset(); node->setRefCount(1); break; } node->convertToPhantom(); eliminateIrrelevantPhantomChildren(node); node->setRefCount(1); break; } } } m_insertionSet.execute(block); }
bool FactorGraph::insertEdge(Edge e){ if(&e == NULL) return false; // std::cout << e.id1() << " " << e.id2() << std::endl; _edges.insert(new Edge(e.id1(),e.id2(),e.getTransf(),e.getInf())); return true; }