//Generate a random complete euclidean ListGraph bool GenerateRandomEuclideanListDigraph(ListDigraph &g, DNodeStringMap &vname, // node name DNodePosMap &px, // x-position of the node DNodePosMap &py, // y-position of the node ArcValueMap & weight, // weight of edges int n, // number of nodes double SizeX, // coordinate x is a random number in [0,SizeX) double SizeY) // coordinate y is a random number in [0,SizeY) { DNode *V; V = new DNode[n]; if (V==NULL){ cout << "Memory allocation error, number of nodes " << n << " too large\n"; exit(0);} for (int i=0;i<n;i++) { // insert nodes (random points in [0,100] x [0,100] ) V[i] = g.addNode(); // new node px[V[i]] = SizeX*drand48(); py[V[i]] = SizeY*drand48(); vname[V[i]] = IntToString(i+1);// name of node is i+1 } for (int i=0;i<n;i++) for (int j=i+1;j<n;j++) { Arc e = g.addArc(V[i],V[j]); // generate new arc from v_i to v_j weight[e] = sqrt(pow(px[V[i]]-px[V[j]],2) + pow(py[V[i]]-py[V[j]],2)); Arc f = g.addArc(V[j],V[i]); // generate new arc from v_j to v_i weight[f] = weight[e]; } delete[] V; return(true); }
int read_pcpath(string input_file){ std::ifstream kinput; kinput.open(input_file.c_str()); if (!kinput) return 0; kinput >> n >> m; std::map<std::string, ListDigraph::Node> ref; for ( int i=0; i<n; i++ ){ string tmp; double r; kinput >> tmp >> r; ListDigraph::Node n = g.addNode(); node_names[n] = tmp; prizes[n] = r; ref[tmp]=n; } for ( int i=0; i<m; i++){ string v1, v2; double c_tmp; kinput >> v1 >> v2 >> c_tmp; ListDigraph::Arc a = g.addArc(ref[v1], ref[v2]); //source, target costs[a] = c_tmp; } return 1; }
//splits graph into connected components void split_graph(ListDigraph& g, vector<ListDigraph*>& graphs){ Undirector<ListDigraph> undirected(g); ListDigraph::NodeMap<int> components(g); stronglyConnectedComponents(undirected, components); int num_subgraphs = 0; for(ListDigraph::NodeIt n(g); n != INVALID; ++n){ if(components[n] > num_subgraphs) num_subgraphs = components[n]; } num_subgraphs++; ListDigraph::NodeMap<ListDigraph::Node> map(g); for(int i = 0; i < num_subgraphs; i++){ ListDigraph temp; for(ListDigraph::NodeIt n(g); n != INVALID; ++n){ if(components[n] == i){ map[n] = temp.addNode(); } } for(ListDigraph::NodeIt n(g); n != INVALID; ++n){ if(components[n] == i){ for(ListDigraph::OutArcIt o(g, n); o != INVALID; ++o){ temp.addArc(map[g.source(o)], map[g.target(o)]); } } } graphs.push_back(&temp); } }
void drawGraphToFile(ListDigraph& g){ ofstream myfile; myfile.open("graph.dot"); myfile << "digraph g {\n"; for (ListDigraph::ArcIt a(g); a!= INVALID; ++a) { myfile << g.id(g.source(a)) << " -> " << g.id(g.target(a)) << "\n"; } myfile << "}\n"; myfile.close(); }
void drawGraphToFileWithArcMap(ListDigraph& g, ListDigraph::ArcMap<int>& map){ ofstream myfile; myfile.open("graph.dot"); myfile << "digraph g {\n"; for (ListDigraph::ArcIt a(g); a!= INVALID; ++a) { myfile << g.id(g.source(a)) << " -> " << g.id(g.target(a)) << " [label=\"" << map[a] << "\"] \n"; } myfile << "}\n"; myfile.close(); }
ListDigraph::Node addSink(ListDigraph& g){ ListDigraph::Node t = g.addNode(); for(ListDigraph::NodeIt n(g); n != INVALID; ++n){ if(countOutArcs(g, n) == 0 && n != t){ g.addArc(n, t); } } return t; }
ListDigraph::Node addSource(ListDigraph& g){ ListDigraph::Node s = g.addNode(); for(ListDigraph::NodeIt n(g); n != INVALID; ++n){ if(countInArcs(g, n) == 0 && n != s){ g.addArc(s, n); } } return s; }
int main() { ListDigraph g; ListDigraph::Node u = g.addNode(); ListDigraph::Node v = g.addNode(); ListDigraph::Arc a = g.addArc( u, v ); cout << "Hello World! This is LEMON library here." << endl; cout << "We have a directed graph with " << countNodes( g ) << " nodes " << "and " << countArcs( g ) << " arc." << endl; return 0; }
/* The function purpose is to check if the node is exist, if not it create it and add it to the map*/ void nodeValidation(int input, CrossRefMap<ListDigraph, ListDigraph::Node, int> & ids, ListDigraph::Node & node, ListDigraph & g){ node = ids(input); if (node == INVALID) { // Check if node is inavlid node = g.addNode(); ids.set(node, input); // make a connection between the node and the string } }
// This routine visualize a digraph using a pdf viewer. It uses neato (from // graphviz.org) to generate a pdf file and a program to view the pdf file. The // pdf viewer name is given in the viewername parameter. int ViewListDigraph(ListDigraph &g, DNodeStringMap &vname, // node names DNodePosMap &px, // x-position of the nodes DNodePosMap &py, // y-position of the nodes DNodeColorMap &vcolor, // color of node (see myutils.h) ArcColorMap &ecolor, // color of edge string text) // text displayed below the figure { char tempname[1000],cmd[1000]; FILE *fp; double minpx=DBL_MAX,minpy=DBL_MAX,maxpx=-DBL_MAX,maxpy=-DBL_MAX,delta,factor; string str; // obtain a temporary file name strcpy(tempname,".viewdigraphtempname"); fp = fopen(tempname,"w+"); if (fp==NULL) {cout << "Error to open temporary file to visualize digraph.\n"; return(0);} for (DNodeIt v(g); v!=INVALID; ++v) { if (px[v] < minpx) minpx = px[v]; if (px[v] > maxpx) maxpx = px[v]; if (py[v] < minpy) minpy = py[v]; if (py[v] > maxpy) maxpy = py[v]; } factor = 40; // using larger values makes small nodes delta = fmax(maxpx - minpx,maxpy - minpy); // Generate a text file with the graph format of neato program fprintf(fp,"digraph g {\n"); fprintf(fp,"\tsize = \"10, 10\";\n"); fprintf(fp,"\tnode [style = filled, shape = \"circle\"];\n"); for (DNodeIt v(g); v!=INVALID; ++v) { if (vcolor[v]==NOCOLOR) continue; fprintf(fp,"\t%s [color=\"%s\", pos = \"%lf,%lf!\"];\n", vname[v].c_str(),ColorName(vcolor[v]).c_str(),factor*(px[v]-minpx)/delta,factor*(py[v]-minpy)/delta); } for (ArcIt e(g); e!=INVALID; ++e) { if (ecolor[e]==NOCOLOR) continue; fprintf(fp,"\t%s -> %s [color=\"%s\" ];\n",vname[g.source(e)].c_str(),vname[g.target(e)].c_str(),ColorName(ecolor[e]).c_str()); } fprintf(fp,"label=\"%s\";\nfontsize=50;\n",text.c_str()); fprintf(fp,"}\n"); fclose(fp); sprintf(cmd,"neato -Tpdf %s -o %s.pdf",tempname,tempname); system(cmd); str = tempname; str = str + ".pdf"; view_pdffile(str); return(1); }
int main() { ListDigraph test; ListDigraph::Node a = test.addNode(); ListDigraph::Node b = test.addNode(); ListDigraph::Node c = test.addNode(); ListDigraph::Node d = test.addNode(); ListDigraph::Node e = test.addNode(); ListDigraph::Node f = test.addNode(); ListDigraph::Arc ac = test.addArc(a, c); ListDigraph::Arc bc = test.addArc(b, c); ListDigraph::Arc cd = test.addArc(c, d); ListDigraph::Arc bf = test.addArc(b, f); ListDigraph::Arc de = test.addArc(d, e); ListDigraph::Arc df = test.addArc(d, f); ListDigraph::ArcMap<int> costs(test); costs[ac] = 1; costs[bc] = 2; costs[cd] = 2; costs[bf] = 32; costs[de] = 16; costs[df] = 8; solve_via_minflow(test, costs); return 0; }
int main(int argc, char* argv[]){ tMax = 600; int verbose = 0; std::string input_file; int option, i_f = 0; if ( argc == 1 ){ show_usage(); return 0; } while ((option = getopt(argc, argv, "t:i:v"))!=-1) switch(option){ case 't': tMax=atoi(optarg); break; case 'i': i_f = 1; input_file.assign(optarg); break; case 'v': verbose=1; break; default: break; } if ( i_f == 0 ){ std::cout << "-i mandatory argument" << std::endl; return 1; } if ( !read_pcpath(input_file) ) return 1; for ( ListDigraph::NodeIt u(g); u!=INVALID; ++u ){ if ( node_names[u].compare("s")==0 ) s=u; if ( node_names[u].compare("t")==0 ) t=u; } //if ( verbose ) // show_input(); prize_collecting_st_path_pli(g, prizes, costs, s, t, path, UB, LB, tMax); if ( verbose ){ //make_eps_graph(path, "sol"); //set_pdfreader("okular"); //set_pdfreader("open"); //set_pdfreader("xpdf"); show_graph_mygraphlib(input_file); } for ( int i=0; i<(int)path.size(); i++ ) std::cout << g.id(path[i]) << " "; std::cout << std::endl; return 0; }
int main(){ string a = "88\t567 999\t444 555\n22\t777 666\t111 000"; string file, line; int out1, out2; istringstream mStream( a ); // ifstream mStream( "/Users/sonneundasche/Dropbox/FLI/04_HIT_Transform/_node size/Schwein_BL_07_time_tmpArcIDs_amountOnArc.txt" ); // getline( mStream, file, '\n'); while(getline( mStream, file, '\n')){ istringstream lineStream( file ); lineStream >> out1; cout << "time: " << out1 << "\n"; getline( lineStream, line, '\t'); while( getline( lineStream, line, '\t') ){ istringstream pairStream( line ); pairStream >> out1; pairStream >> out2; cout << out1 << " : " << out2 << "\n"; } } // vector< int > activeTimes; ListDigraph mGraph; digraphReader( mGraph, "/Users/sonneundasche/Dropbox/FLI/04_HIT_Transform/_node size/Schwein_BL_07.lgf") .run(); map< int, vector< pair <ListDigraph::Arc, int > > > activeArcsAndWeight; activeTimes = tempGR::readTemporalArcListWeighted(mGraph, activeArcsAndWeight, "/Users/sonneundasche/Dropbox/FLI/04_HIT_Transform/_node size/Schwein_BL_07_time_tmpArcIDs_amountOnArc.txt"); for (auto i : activeArcsAndWeight[2486]) { cout << mGraph.id( activeArcsAndWeight[2492][0].first ) << " : " << i.second << "\n"; } cout << mGraph.id( activeArcsAndWeight[2492][0].first ) << " : " << activeArcsAndWeight[2492][0].second << endl; }
void createKPathGraph(ListDigraph& g, int k, int n, int m, ListDigraph::ArcMap<int>& weights, ListDigraph::ArcMap<int>& demands){ srand(time(NULL)); ListDigraph::Node* nodes[k]; for (int i = 0; i < k; ++i) { nodes[i] = (ListDigraph::Node*) calloc(n, sizeof(ListDigraph::Node)); } for (int i = 0; i < k; ++i) { for (int j = 0; j < n; ++j) { nodes[i][j] = g.addNode(); if(j != 0) g.addArc(nodes[i][j-1], nodes[i][j]); } } for (int i = 0; i < m; ++i) { int k1 = rand()%k; int k2 = rand()%k; int n1 = rand()%(n-1); int n2 = (rand()%(n-n1-1))+n1+1; if(findArc(g, nodes[k1][n1], nodes[k2][n2]) == INVALID){ g.addArc(nodes[k1][n1], nodes[k2][n2]); } } for (ListDigraph::ArcIt a(g); a != INVALID; ++a) { weights[a] = rand()%1000; } //this splits every node and sets demand for the edge between the halves to 1 for (ListDigraph::NodeIt n(g); n != INVALID; ++n){ ListDigraph::Node new_node = g.split(n, false); ListDigraph::Arc new_edge = g.addArc(n, new_node); demands[new_edge] = 1; } }
//Simple function for generating acyclic graphs void createRandomGraph(ListDigraph& g, int num_nodes, float edge_prob){ srand(time(NULL)); ListDigraph::NodeMap<int> labels(g); for(int i=0; i<num_nodes; i++){ ListDigraph::Node new_node = g.addNode(); labels[new_node] = i; } for(ListDigraph::NodeIt n(g); n != INVALID; ++n){ for(ListDigraph::NodeIt v(g); v != INVALID; ++v){ //no edges from bigger nodes to smaller to ensure acyclicity, //and no edges from node to itself //+ an attempt to create longer graphs if(labels[n] >= labels[v] || labels[n] < labels[v]-20) continue; if(rand()%100 <= edge_prob*100){ g.addArc(n, v); } } } }
//check for circle for each course with his pre courses bool checkCircle(SeasonConfig & seasonConfig) { ListDigraph g; CrossRefMap<ListDigraph, ListDigraph::Node, int> ids(g); ListDigraph::Node u, v; Bfs<ListDigraph> bfs(g); for (int i = 0; i < seasonConfig.courses.count(); i++){ nodeValidation(seasonConfig.courses.get(i).getId(), ids, u, g); for (int j = 0; j < seasonConfig.courses.get(i).pre.count(); j++) { nodeValidation(seasonConfig.courses.get(i).pre.get(j).getId(), ids, v, g); bfs.run(v); if (bfs.reached(u)){ // If there is a path to u return true; // circle was found we can exit the progeam; } g.addArc(u, v); // Else we make a connection between u and v } } return false; }
// ****************** TSP WITH REFUELING ********************************** // Directed version of adjacency matrix. Used to handle with the TSP with Refueling Problem. AdjacencyMatrixDirected::AdjacencyMatrixDirected(ListDigraph &dgraph, ArcValueMap &graphweight, double NonArcValue): DNode2Index(dgraph), Arc2Index(dgraph) { int i; g = &dgraph; this->NonArcValue = NonArcValue; weight = &graphweight; Nnodes = countNodes(dgraph); // number of nodes in the input dgraph Narcs = countArcs(dgraph); // number of edges in the input dgraph Nmatrix = Nnodes*Nnodes; // full matrix AdjMatrix = (double *) malloc(sizeof(double)*Nmatrix); Index2DNode = (DNode *) malloc(sizeof(Node)*Nnodes); Index2Arc = (Arc *) malloc(sizeof(Arc)*Narcs); if ((AdjMatrix==NULL)||(Index2DNode==NULL)||(Index2Arc==NULL)) { cout << "Out of memory in constructor of AdjacencyMatrixDirected\n"; ADJMAT_FreeNotNull(AdjMatrix); ADJMAT_FreeNotNull(Index2DNode); ADJMAT_FreeNotNull(Index2Arc); exit(0);} i = 0; for (DNodeIt v(*g); v != INVALID; ++v) { Index2DNode[i] = v; AdjacencyMatrixDirected::DNode2Index[v] = i; i++; } // Initially all edges have infinity weight for (int i=0;i<Nmatrix;i++) AdjMatrix[i] = NonArcValue; // Then, update the existing edges with the correct weight for (ArcIt a(dgraph); a != INVALID; ++a) { DNode u,v; int i_u,i_v; u = dgraph.source(a); v = dgraph.target(a); // obtain the extremities of e i_u = DNode2Index[u]; i_v = DNode2Index[v]; AdjMatrix[i_u*Nnodes+i_v] = graphweight[a]; } }
void createMACGraph(ListDigraph& g, int num_paths, int path_length, ListDigraph::ArcMap<int>& demands){ srand(time(NULL)); ListDigraph::Node prev[num_paths]; ListDigraph::Node current[num_paths]; for (int i = 0; i < num_paths; ++i) { prev[i] = g.addNode(); } for (int i = 0; i < path_length-1; ++i) { for (int j = 0; j < num_paths; ++j) { current[j] = g.addNode(); g.addArc(prev[j], current[j]); } for (int j = 0; j < num_paths; ++j) { if(rand()%100 < 50){ int targetIndex = j; while(targetIndex != j){ targetIndex = rand()%num_paths; } g.addArc(prev[j], current[targetIndex]); } } for (int j = 0; j < num_paths; ++j) { prev[j] = current[j]; } } //this splits every node and sets demand for the edge between the halves to 1 for (ListDigraph::NodeIt n(g); n != INVALID; ++n){ ListDigraph::Node new_node = g.split(n, false); ListDigraph::Arc new_edge = g.addArc(n, new_node); demands[new_edge] = 1; } }
int main(){ ListDigraph MyGraph; ListDigraph::NodeMap< long long int > idNodeMap ( MyGraph ); ListDigraph::NodeMap< double > xKoordNodeMap (MyGraph ); ListDigraph::NodeMap< double > yKoordNodeMap (MyGraph ); ListDigraph::NodeMap< long double > capacityNodeMap( MyGraph ); ListDigraph::NodeMap< bool > typeNodeMap( MyGraph ); ListDigraph::ArcMap< long double > distanceArcMap( MyGraph ); ListDigraph::ArcMap < bool > switchArcMap( MyGraph, true ); // Alle Kanten sollen an / true sein ListDigraph::ArcMap < bool > stateArcMap( MyGraph, false ); // Keine Infraktion (false) am Anfang ListDigraph::NodeMap< bool > stateNodeMap( MyGraph, false ); try { digraphReader( MyGraph, "/Users/sonneundasche/Desktop/MilkyWayDaten/MilkyWay_Solution.lgf") .nodeMap( "Type", typeNodeMap ) .run(); } catch (Exception& error) { // check if there was any error std::cerr << "Error: " << error.what() << std::endl; return -1; } // ------------------------------------------------------------------- // ---------------- Erzeuge die Glättungs Kanten ----------------- // ------------------------------------------------------------------- // Zur Abspeicherung der IDs der Glättungs Arcs // int glattArcID[ glattArcNr ]; // int m = 0; // // for ( int in = 0; in < supplyNodesNr; in++ ) // for ( int out = 0; out < supplyNodesNr ; out++ ) { // glattArcID[ m ] = MyGraph.id( MyGraph.addArc( MyGraph.nodeFromId( in ), MyGraph.nodeFromId( out ) )); // m++; // // //vice versa "in/out" // glattArcID[ m ] = MyGraph.id( MyGraph.addArc( MyGraph.nodeFromId( out ), MyGraph.nodeFromId( in ) )); // m++; // } // ------------------------------------------------------------------- // ---------------- Erzeuge eine FilterMap und Init ----------------- // ------------------------------------------------------------------- // ---------------- um Glättung umzuschalten ---------------------- // ------------------------------------------------------------------- // FilterArcs< ListDigraph >::ArcFilterMap glattArcFilterMap( MyGraph ); // FilterArcs< ListDigraph >::FilterArcs glattFilterGraph( MyGraph, glattArcFilterMap ); // // // Alle auf TRUE setzen // for ( FilterArcs< ListDigraph >::ArcIt a( glattFilterGraph ) ; a != INVALID ; ++a ) // glattArcFilterMap[ a ] = 1; // // // Glättungskanten auf FALSE setzen // for ( int i = 0; i < glattArcNr; i++ ) // glattArcFilterMap[ glattFilterGraph.arcFromId( glattArcID[ i ] ) ] = 0; // // ------------------------------------------------------------------- // ---------------- Zufalls Glättungskanten umschalten ------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ---------------- Infectious Dynamics Calculation (Range) ---------- // ------------------------------------------------------------------- // +++++ Hier sollte noch ein SubGraph / FilterMap erstellt werden für die Glättung // ++++ Gesamtschleife mit Abbruch kommt noch int infStartAmount = 1; // Anzahl der Molkerei-Knoten die am Anfang infiziert sind int infSumInfected = infStartAmount; // StartRange: Anzahl infizierten Knoten + Anfangswert // int ctrlRange[ ]; // Range die über die Out Arcs gezählt wird int ctrlRangeALL = 0; int infSumArry[ 3 ]; // AbbruchBed.: Falls nach drei Rechen-Schritten "Range" gleich, dann brich ab. infSumArry[ 0 ] = infStartAmount; // Zwangsbed., damit der Loop anfängt // ---------------- Zufällig eine Molkerei/Node infizieren ------------- // for ( int i = 0; i < infStartAmount; i++) // stateNodeMap[ MyGraph.nodeFromId( rnd( 0, ( supplyNodesNr - 1 ) ) ) ] = 1; // for ( int i = 0; i < sumSup; i++) // stateNodeMap[ MyGraph.nodeFromId( i ) ] = 1; // ------------------------------------------------------------------- // ----------------- Durchlauf durch den Graphen ---------------- // ------------------------------------------------------------------- // ++++ Man kann entweder zuerst Nodes oder Arcs durchschauen // ++++ Falls Arcs zuerst gezählt werden, breitet sich die Krankheit in weniger // ++++ Rechenschritten aus, da in anschließenden Schritt infizierte Kanten Knoten infinzieren. // ++++ Dieser Weg wird hier aus Performance-Gründen gegangen. Uns interessiert nicht die Ausbreitungsgeschw. do { // ---------------- Arc Infectious States ---------------- for ( ListDigraph::ArcIt a( MyGraph ) ; a != INVALID; ++a ) { // if ( stateArcMap[ a ] == 0 ) //Falls noch nicht infiziert if ( stateNodeMap[ MyGraph.source( a ) ] == 1 ) // Falls der QuellKnoten Infiziert, Kante auch stateArcMap[ a ] = 1; } // ---------------- Node Infectious States ---------------- for ( ListDigraph::NodeIt n( MyGraph ) ; n != INVALID; ++n ) { if ( stateNodeMap[ n ] == 0 ) // Optimierung: Nur abfragen falls es noch nicht infiziert ist for (ListDigraph::InArcIt in( MyGraph, n ) ; in != INVALID; ++in ) if ( stateArcMap[ in ] ) { stateNodeMap[ n ] = 1; infSumInfected++; // Zähle die Neuinfektion falls Knoten an ist continue; // Schleife verlassen, falls eine Kante an ist } } // Billiges Aufschieben der Werte. Damit man schauen kann, ob dreimal nichts geschah infSumArry[ 2 ] = infSumArry [ 1 ]; infSumArry[ 1 ] = infSumArry [ 0 ]; infSumArry[ 0 ] = infSumInfected; } while ( ( infSumArry[ 0 ] != infSumArry[ 1 ] ) || ( infSumArry[ 1 ] != infSumArry [ 2 ] ) ); // ------------------------------------------------------------------- // ----------------- Test Funktion zur Überprüfung der Werte ---------------- // ------------------------------------------------------------------- // +++ Einfache Berechnung des AUS-Grades // GesamtRange for ( ListDigraph::NodeIt n( MyGraph ) ; n != INVALID; ++n) for ( ListDigraph::OutArcIt o( MyGraph, n ) ; o != INVALID; ++o ){ ctrlRangeALL++; // ++++>> hier den Range Array einfügen } // ----------------- Graph schreiben ---------------- digraphWriter( MyGraph, cout ) .nodeMap( "NodeStates", stateNodeMap ) .skipArcs() .run(); cout << endl << "Range-Berechnungs-Zeit: " << time.realTime() << endl; cout << endl << "Range-Wert: " << infSumInfected << endl; return 0; }
//find minflow by reducing the maximal amount of flow (with maxflow) from a feasible flow void find_minflow_IBFS(ListDigraph& g, ListDigraph::ArcMap<int>& demands, ListDigraph::ArcMap<int>& flow, ListDigraph::NodeMap<int>& labels, ListDigraph::Node s, ListDigraph::Node t) { ListDigraph::ArcMap<int> feasible_flow(g); find_feasible_flow(g, demands, feasible_flow); //Create IBFS graph and solve maxflow in it IBFSGraph* g_ibfs = new IBFSGraph(IBFSGraph::IB_INIT_FAST); int num_nodes = countNodes(g); int num_arcs = countArcs(g); //we need a special labeling for IBFS, because we won't have s and t there //ListDigraph::Node label_to_node[num_nodes]; ListDigraph::Node* label_to_node = new ListDigraph::Node[num_nodes]; ListDigraph::NodeMap<int> labels_ibfs(g); int index_counter = 0; for(ListDigraph::NodeIt n(g); n != INVALID; ++n){ if(n == s || n == t) continue; labels_ibfs[n] = index_counter; index_counter++; label_to_node[labels_ibfs[n]] = n; } g_ibfs->initSize(num_nodes-2, num_arcs-countOutArcs(g, s) - countInArcs(g, t)); /** for(ListDigraph::NodeIt n(g); n != INVALID; ++n){ if(countInArcs(g, n) == 0){ g_ibfs->addNode(labels[n], 0, MAX_CAPACITY); } else if(countOutArcs(g, n) == 0){ g_ibfs->addNode(labels[n], MAX_CAPACITY, 0); } } **/ ListDigraph::ArcMap<int> arc_labels(g); //ListDigraph::Arc arc_labels_reverse[num_arcs]; ListDigraph::Arc* arc_labels_reverse = new ListDigraph::Arc[num_arcs]; int counter = 0; for(ListDigraph::ArcIt a(g); a != INVALID; ++a){ arc_labels[a] = counter; arc_labels_reverse[counter] = a; counter++; } for(ListDigraph::ArcIt a(g); a != INVALID; ++a){ if(g.source(a) == s){ g_ibfs->addNode(labels_ibfs[g.target(a)], 0, MAX_CAPACITY); } else if(g.target(a) == t){ g_ibfs->addNode(labels_ibfs[g.source(a)], MAX_CAPACITY, 0); } else{ g_ibfs->addEdge(labels_ibfs[g.target(a)], labels_ibfs[g.source(a)], feasible_flow[a]-demands[a], MAX_CAPACITY); } } g_ibfs->initGraph(); g_ibfs->computeMaxFlow(); /** while(g_ibfs->arcs != g_ibfs->arcEnd){ //cout << "LABEL:: " << g_ibfs->arcs->label << "\n"; if(g_ibfs->arcs->label != -1){ ListDigraph::Arc a = arc_labels_reverse[g_ibfs->arcs->label]; int flow_on_arc = MAX_CAPACITY - g_ibfs->arcs->rCap; int flow_on_reverse = (feasible_flow[a]-demands[a]) - g_ibfs->arcs->rev->rCap; //cout << g_ibfs->arcs->rCap << " " << g_ibfs->arcs->rev->rCap << "\n"; //cout << feasible_flow[a] << " " << flow_on_arc << " " << flow_on_reverse << " "; flow[a] = feasible_flow[a] + flow_on_arc - flow_on_reverse; //cout << flow[a] << "\n"; } g_ibfs->arcs++; } for(ListDigraph::OutArcIt o(g, s); o != INVALID; ++o){ for (ListDigraph::OutArcIt oa(g, g.target(o)); oa != INVALID; ++oa) { flow[o] += flow[oa]; } } for(ListDigraph::InArcIt i(g, t); i != INVALID; ++i){ for(ListDigraph::InArcIt ia(g, g.source(i)); ia != INVALID; ++ia){ flow[i] += flow[ia]; } } **/ }
#include "test_utils.h" #include <lemon/list_graph.h> #include "../decomposition.h" #include "../MPC.h" #include <stdlib.h> #include <time.h> #include "catch.hpp" #include <lemon/bfs.h> using namespace std; using namespace lemon; TEST_CASE("MACs are found in an easy test case") { ListDigraph g; ListDigraph::Node s = g.addNode(); ListDigraph::Node t = g.addNode(); ListDigraph::Node a = g.addNode(); ListDigraph::Node b = g.addNode(); ListDigraph::Node c = g.addNode(); ListDigraph::Node d = g.addNode(); ListDigraph::Arc sa = g.addArc(s, a); ListDigraph::Arc ab = g.addArc(a, b); ListDigraph::Arc bt = g.addArc(b, t); ListDigraph::Arc sc = g.addArc(s, c); ListDigraph::Arc cd = g.addArc(c, d); ListDigraph::Arc dt = g.addArc(d, t); ListDigraph::NodeMap<int> labels(g);
// Generate a triangulated ListDigraph, building the Delaunay // triangulation of random points. Each edge of the Delaunay triangulation // leads to two arcs (in both senses) // Uses the geompack program, available in // http://people.sc.fsu.edu/~jburkardt/cpp_src/geompack/geompack.html bool GenerateTriangulatedListDigraph(ListDigraph &g, DNodeStringMap &vname, // name of the nodes DNodePosMap &px, // x-position of the nodes DNodePosMap &py, // y-position of the nodes ArcValueMap & weight, // weight of edges int n, // number of nodes double SizeX, // coordinate x is a random number in [0,SizeX) double SizeY) // coordinate y is a random number in [0,SizeY) { int i; // n=number of nodes DNode *V = new DNode[n]; double *p = new double[2*n+2];// node coodinates are (x;y) = ( p[2*i] ; p[2*i+1] ) int *tri = new int[6*n]; // Each 3 elements are the indexes of a triangle int ntri; int *tri_nabe = new int[6*n]; if ((V==NULL)||(p==NULL)||(tri==NULL)||(tri_nabe==NULL)){ cout << "Memory allocation error, number of nodes " << n << " too large\n"; exit(0);} for (i=0;i<n;i++) { // insere os vértices (pontos aleatórios no plano [0,SizeX]x[0,SizeY] ) V[i] = g.addNode(); // gera um vértice nó do grafo px[V[i]] = SizeX*drand48(); // nodes are random points py[V[i]] = SizeY*drand48(); p[2*i] = px[V[i]]; p[2*i+1] = py[V[i]]; vname[V[i]] = IntToString(i+1);// name of node is i+1 } if (r8tris2 ( n, p, &ntri, tri, tri_nabe )) { printf("ERROR\n");Pause(); } for (i=0;i<ntri;i++) { int a,b,c; a = tri[3*i]-1; b = tri[3*i+1]-1; c = tri[3*i+2]-1; // each triangle if formed with nodes V[a] , V[b] , V[c] // insert arcs without duplications in both senses if (findArc(g,V[a],V[b])==INVALID){ Arc e = g.addArc(V[a],V[b]); weight[e] = sqrt(pow(px[V[a]]-px[V[b]],2) + pow(py[V[a]]-py[V[b]],2)); } if (findArc(g,V[b],V[a])==INVALID){ Arc e = g.addArc(V[b],V[a]); weight[e] = sqrt(pow(px[V[b]]-px[V[a]],2) + pow(py[V[b]]-py[V[a]],2)); } if (findArc(g,V[a],V[c])==INVALID){ Arc e = g.addArc(V[a],V[c]); weight[e] = sqrt(pow(px[V[a]]-px[V[c]],2) + pow(py[V[a]]-py[V[c]],2)); } if (findArc(g,V[c],V[a])==INVALID){ Arc e = g.addArc(V[c],V[a]); weight[e] = sqrt(pow(px[V[c]]-px[V[a]],2) + pow(py[V[c]]-py[V[a]],2)); } if (findArc(g,V[b],V[c])==INVALID) { Arc e = g.addArc(V[b],V[c]); weight[e] = sqrt(pow(px[V[b]]-px[V[c]],2) + pow(py[V[b]]-py[V[c]],2)); } if (findArc(g,V[c],V[b])==INVALID) { Arc e = g.addArc(V[c],V[b]); weight[e] = sqrt(pow(px[V[c]]-px[V[b]],2) + pow(py[V[c]]-py[V[b]],2)); } } delete[] V; delete[] p; delete[] tri; delete[] tri_nabe; return(true); }
bool ReadListDigraph(string filename, ListDigraph &g, DNodeStringMap &vname, ArcValueMap &weight, DNodePosMap &posx, DNodePosMap & posy, DNodeBoolMap &is_terminal, const bool dupla) { ifstream ifile; int i,n,m; double peso; Arc a; char nomeu[100],nomev[100]; string STR; DNode u,v; #if __cplusplus >= 201103L std::unordered_map<string,DNode> string2node,test; #else std::tr1::unordered_map<string,DNode> string2node; #endif ifile.open(filename.c_str()); if (!ifile) {cout << "File '" << filename << "' does not exist.\n"; exit(0);} PulaBrancoComentario(ifile); ifile >> n; ifile >> m; // first line have number of nodes and number of arcs if (m<0 || ifile.eof()) { cout<<"File "<<filename<<" is not a digraph given by arcs.\n"; exit(0);} for (i=0;i<n;i++) { getline(ifile,STR); if (ifile.eof()) {cout<<"Reached unexpected end of file "<<filename<<".\n";exit(0);} while (STR=="") getline(ifile,STR); { string token; istringstream ins; // Declare an input string stream. ins.str(STR); // Specify string to read. int nt = 0; while( getline(ins, token, ' ') ) { // format: <node_name> <pos_x> <pos_y> <is_terminal> if (nt==0) { auto test = string2node.find(token); if (test!=string2node.end()){cout<<"ERROR: Repeated node: "<<nomev<<endl;exit(0);} v = g.addNode(); string2node[token] = v; vname[v] = token;} else if (nt==1) { posx[v] = atof(token.c_str());} else if (nt==2) { posy[v] = atof(token.c_str());} else if (nt==3) { if(atoi(token.c_str()) == 1) is_terminal[v] = true; else is_terminal[v] = false; } nt++; } } } for (i=0;i<m;i++) { // format: <node_source> <node_target> <arc_weight> ifile >> nomeu; ifile >> nomev; ifile >> peso; if (ifile.eof()) {cout << "Reached unexpected end of file " <<filename << ".\n"; exit(0);} auto test = string2node.find(nomeu); if (test == string2node.end()) {cout<<"ERROR: Unknown node: "<<nomeu<<endl;exit(0);} else u = string2node[nomeu]; test = string2node.find(nomev); if (test == string2node.end()) {cout<<"ERROR: Unknown node: "<<nomev<<endl;exit(0);} else v = string2node[nomev]; a = g.addArc(u,v); weight[a] = peso; if (dupla) {a = g.addArc(v,u); weight[a] = peso;} } ifile.close(); return(true); }
int main(int argc, char** argv){ // ------------------------------ // --- INPUT - OUTPUT // ------------------------------ string sourceLGF, sourceTempEdge, target; ArgParser ap( argc, argv); ap.refOption("g", "Graph file of LEMON GRAPH FORMAT", sourceLGF, true); ap.refOption("t", "Temporal active edges", sourceTempEdge, true); ap.refOption("n", "Target filename", target, true); ap.parse(); // sourceLGF = "/Users/sonneundasche/Documents/FLI/DATA/02Sheep/Schaf_NEW.lgf"; // sourceTempEdge = "/Users/sonneundasche/Documents/FLI/DATA/02Sheep/Schaf_NEW_time_tmpArcIDs.txt"; // sourceLGF = "/Users/sonneundasche/Documents/FLI/DATA/03Pork/porkNEW_.lgf"; // sourceTempEdge = "/Users/sonneundasche/Documents/FLI/DATA/03Pork/porkNEW__time_tmpArcIDs.txt"; // target = "Test"; // ------------------------------ // --- Graph creation // ------------------------------ cout << "- READING\n"; ListDigraph mGraph; try { digraphReader(mGraph, sourceLGF) .run(); } catch (lemon::Exception) { cerr << "Error reading"; exit(0); } // ------------------------------ // --- Temporal Edges // ------------------------------ vector<int> times; boost::unordered_map< int, vector<ListDigraph::Arc > > mTimeToArcs; times = tempGR::readTemporalArcList(mGraph, mTimeToArcs, sourceTempEdge); // ------------------------------ // --- Determine the components // ------------------------------ cout << "- CALCULATION\n"; ListDigraph::NodeMap<int> mCompIds(mGraph); mapFill(mGraph, mCompIds, -1); int nrComponents = connectedComponents( undirector( mGraph ), mCompIds ); // Determine the ID with the biggest component vector<int> mIDcount(nrComponents,0); for (ListDigraph::NodeIt n(mGraph); n!=INVALID; ++n) { mIDcount[ mCompIds[ n ] ]++; } auto a = max_element( mIDcount.begin(), mIDcount.end() ); int maxCompID = distance( mIDcount.begin(), a ); cout << "Nodes: " << countNodes( mGraph ) << " components: " << countConnectedComponents( undirector( mGraph ) ) << endl; cout << "Max Comp ID: " << maxCompID << " size: " << *a << endl; // int i = 0; // for ( auto x : mIDcount ){ // cout << "Comp ID: " << i++ << " size: " << x << endl; // } // ------------------------------ // --- Mark nodes of the biggest component // ------------------------------ cout << "- PROCESSING\n"; vector< ListDigraph::Node > eraseNodes; for (ListDigraph::NodeIt n(mGraph); n!=INVALID; ++n) { if ( mCompIds[ n ] != maxCompID) { eraseNodes.push_back(n); } } cout << "The complete graph has " << countConnectedComponents( undirector( mGraph ) ) << " components and " << countNodes(mGraph) << " nodes" << endl; // ------------------------------ // --- erase the nodes // ------------------------------ for (auto n : eraseNodes){ mGraph.erase( n ); } cout << "The new graph has " << countConnectedComponents( undirector( mGraph ) ) << " components and " << countNodes(mGraph) << " nodes" << endl; ListDigraph newGraph; ListDigraph::ArcMap< ListDigraph::Arc > arcRef( mGraph); ListDigraph::NodeMap< ListDigraph::Node> nodeRef( mGraph ); digraphCopy( mGraph, newGraph) .arcRef(arcRef) // arcMap[ oldArc ] = newArc .nodeRef(nodeRef) .run(); // ------------------------------ // --- erase the invalid temporal edges // ------------------------------ vector< vector< ListDigraph::Arc > > newTempArcs; for (auto i : times){ vector<ListDigraph::Arc> validArcs; for (auto arc : mTimeToArcs[i]){ if ( mGraph.valid( arc ) ) validArcs.push_back( arcRef[ arc ] ); } newTempArcs.push_back( validArcs ); // assign new arc set } // ------------------------------ // --- save the static graph // ------------------------------ cout << "- WRITING\n"; string pathLFG = target; pathLFG += "_LargesComponent.lfg"; digraphWriter( mGraph, pathLFG) // .nodeMap("oldNodes", nodeRef) // .arcMap("oldArcs", arcRef) .run(); // ------------------------------ // --- save the temporal arcs // ------------------------------ string pathTempArc = target; pathTempArc += "_LargesComponent_tempArcs.txt"; tempGR::writeTempGraph<ListDigraph>( mGraph, newTempArcs, pathTempArc); cout << "- DONE\n"; }
int main( void ){ /* --- Daten Anordnung --- From To Amount Date 560739 254569 7 2682 913338 356536 1 3497 */ string edgeListSource = "TradingData.txt"; string lemonFileTmp = "DataTMP.lgf"; string lemonFileOut = "DataProcessed.lgf"; boost::unordered_set< unsigned int > uniqueNodes; // Mathematische Menge (set) der Knoten boost::unordered_set< pair< unsigned int, unsigned int > > uniqueArcs; // Menge der Kanten (set von Knoten-Paaren) ifstream myEdgeListFile( edgeListSource ); string foo; // kill first line, because it has the header getline(myEdgeListFile, foo); unsigned int from, to, amount, day; // Einlesen der Werte in die Menge. Paar-Erstellung. while ( myEdgeListFile.good() ){ myEdgeListFile >> from; myEdgeListFile >> to; myEdgeListFile >> amount; myEdgeListFile >> day; uniqueNodes.insert( from ); uniqueNodes.insert( to ); uniqueArcs.insert( make_pair( from, to ) ); } cout << "Nodes: " << uniqueNodes.size() << " Arcs: " << uniqueArcs.size() << endl;; // ---------------------------------------------------------------------------------------- // Schreiben der LFG durch eigene Routine // ---------------------------------------------------------------------------------------- ofstream myLemonFile( lemonFileTmp ); // ----- Nodes ----- myLemonFile << "@nodes" << endl; myLemonFile << "label" << "\t" << "name" << endl; for (auto iter = uniqueNodes.begin(); iter != uniqueNodes.end(); iter++) { myLemonFile << *iter << "\t" << *iter << endl; } myLemonFile << endl << endl << "@arcs" << endl; myLemonFile << "\t\tfrom\tto" << endl; for (auto iterArcs = uniqueArcs.begin(); iterArcs != uniqueArcs.end(); iterArcs++ ){ myLemonFile << (*iterArcs).first << "\t" // Erster Paar-Eintrag für LEMON, damit es mit den Nodes übereinstimmt << (*iterArcs).second << "\t" << (*iterArcs).first << "\t" // Zweiter Paar-Eintrag erhält die alten IDs, damit die Daten nicht beim Umwandeln verloren gehen << (*iterArcs).second << endl; } // ========================================================================================= // Create Graph and Format in a Lemon friendly way // Hier erhalten die Knoten und Kanten LEMON IDs ListDigraph myCulmiGraph; ListDigraph::NodeMap< unsigned int > nameNodeMap( myCulmiGraph ); ListDigraph::ArcMap< unsigned int > fromNdArcMap( myCulmiGraph ); ListDigraph::ArcMap< unsigned int> toNdArcMap ( myCulmiGraph ); ListDigraph::ArcMap< bool > activeArcsMap( myCulmiGraph ); timeToActiveArcs dayActivityArcIDs; //Menge an Zeitpunkten (int) und den dazu gehörigen aktiven Kanten (vec) boost::unordered_map< unsigned int, unsigned int > origIDtoLemon; // Hier besitzen die Knoten & Kanten noch original IDs (name) digraphReader( myCulmiGraph, lemonFileTmp) .nodeMap( "name", nameNodeMap ) .arcMap( "from", fromNdArcMap ) .arcMap( "to", toNdArcMap) .run(); cout << "LEMON - Nodes: " << countNodes( myCulmiGraph ) << " Arcs: " << countArcs( myCulmiGraph ) << endl; // Ausgabe der neuen LEMON IDs für Knoten und Kanten digraphWriter( myCulmiGraph, lemonFileOut) .nodeMap( "name", nameNodeMap ) .arcMap( "from", fromNdArcMap ) .arcMap( "to" , toNdArcMap ) .run(); // ========================================================================================= // Create HashMap of time and active arc pairs // Eine Map, die original KnotenIDs zu LEMON IDs zuweist (LemonMap Umkehr, statisch) // Nötig, da ich die orginalIDs aus der Ursprungsdatei einlese for (ListDigraph::NodeIt n( myCulmiGraph ) ; n!=INVALID; ++n) { origIDtoLemon[ nameNodeMap[ n ] ] = myCulmiGraph.id( n ); } myEdgeListFile.close(); myEdgeListFile.open( edgeListSource ); getline(myEdgeListFile, foo); // Einlesen der Werte in die Menge. Paar-Erstellung. while ( myEdgeListFile.good() ){ myEdgeListFile >> from; myEdgeListFile >> to; myEdgeListFile >> amount; myEdgeListFile >> day; (dayActivityArcIDs[ day ]).push_back( findArc( myCulmiGraph, myCulmiGraph.nodeFromId( origIDtoLemon[ from ] ), myCulmiGraph.nodeFromId( origIDtoLemon[ to ] ) ) ); } // ========================================================================================= // ================== Dies art von Map kann über alle true Werte iterieren ============ // IterableBoolMap< ListDigraph, ListDigraph::Arc > myItBoolMap( myCulmiGraph, false ); // ========================================================================================= // ===================== Creating the NetEvo System ================== // System mapSys, odeSys; ActiveArcsInteractionMap interaction( myItBoolMap ); SIRdynamic odeDyn( 10, 0.1 ); mapSys.addNodeDynamic( &interaction ); mapSys.copyDigraph( myCulmiGraph, "InteractionMap", "NoArcDynamic"); odeSys.addNodeDynamic( & odeDyn ); odeSys.copyDigraph( myCulmiGraph, "SIRdynamic", "NoArcDynamic"); SimObserverToStream coutObserver(cout); SimObserver nullObserver; ChangeLog nullLogger; SimulateMap simMap; SimulateOdeFixed simODE( RK_4, 0.01 ); State initial = State( mapSys.totalStates(), 1.0) ; initDegreeDistributed( mapSys, initial, 3, 10.0); Timer t; cout << "Days to calculate: " << dayActivityArcIDs.size() << endl; cout << "Starte Simulation!" << endl; t.restart(); for( int i = 1; i < dayActivityArcIDs.size() ; i++){ setBoolMapOfDay( myItBoolMap, dayActivityArcIDs, i ); // cout << "Zeit: " << i << " Aktive Kanten: " << myItBoolMap.trueNum() << endl << " ODE:" << endl; simODE.simulate( odeSys, 1, initial, nullObserver, nullLogger); simMap.simulate( mapSys, 1, initial, nullObserver, nullLogger); } cout << "Laufzeit: " << t.realTime() << endl; }