示例#1
0
ExtendedEdge::ExtendedEdge(ListGraph &g, ListGraph::Node u,
                           ListGraph::Node v, int pos_u, int pos_v){
    _adjacentNodes.push_back(g.id(u));
    _adjacentNodes.push_back(g.id(v));
    _adjacentNodesPos.push_back(pos_u);
    _adjacentNodesPos.push_back(pos_v);
    edge = g.addEdge(u,v);
    _id = g.id(edge);
    _length = 0;
}
示例#2
0
int main( void ){
    
    Timer   T(true);
    
    int final_nodes_num, edge_addition_num;
    final_nodes_num     = 30000;
    edge_addition_num   = 7;
    
    ListGraph                           mGr;
    lemon::Random   mRandom;
    mRandom.seedFromTime();
    
    vector<int> nodeChoice;
    set<int>    mRndNodes;
    vector<int> targets(edge_addition_num, -1);
    int currentIndex = 0;
    
    // First targets are all nodes
    for(auto &v : targets){
        v = currentIndex++;
        mGr.addNode();
    }

    while (countNodes(mGr)<final_nodes_num ) {
        // Add new node and connect to targets
        currentIndex =  mGr.id( mGr.addNode() );
        for(const auto &v : targets ){
            mGr.addEdge( mGr.nodeFromId( currentIndex ), mGr.nodeFromId( v ) );
        }
        // Add the nodes, which were connented again
        nodeChoice.insert(nodeChoice.end(), targets.begin(), targets.end() );
        nodeChoice.insert(nodeChoice.end(), edge_addition_num, currentIndex);
        
        mRndNodes.clear();
        while (mRndNodes.size() < edge_addition_num) {
            mRndNodes.insert( nodeChoice[ mRandom.integer( nodeChoice.size() ) ] );
        }
        targets.clear();
        targets.insert(targets.begin(), mRndNodes.begin(), mRndNodes.end() );
    }
    
    cout << "time: " << T.realTime() << endl;
    cout << countNodes( mGr) << endl;
    cout << countEdges( mGr) << endl;
    
    
    graphWriter( mGr, "/Users/sonneundasche/Documents/FLI/DATA/05 LEMON Graphs/BaraBasiTEST.txt")
    .run();
    
    InDegMap<ListGraph>     inDeg(mGr);

    graphWriter( mGr, "/Users/sonneundasche/Documents/FLI/DATA/05 LEMON Graphs/BaraBasi_Degree_TEST.txt")
    .nodeMap("degree", inDeg)
    .skipEdges()
    .run();
    
  }
示例#3
0
int
HeuristicGroupTSP(ListGraph &g,  ListGraph::EdgeMap<double>& weights, vector<
                  set<ListGraph::Node> > &S, vector<ListGraph::Node> &sol, long
                  max_time,  double &best_time,  double &LB, string &alg_info)
{
  /**
   * Computa solucao heuristica para o Group TSP.
   *
   * Entrada:
   * @param   g           grafo simples utilizado
   * @param   weights     pesos das arestas
   * @param   S           vetor de grupos de vertices (ver def. do problema)
   * @param   max_time    tempo maximo (em seg) que o procedimento deve ocorrer
   *
   * Saida:
   * @param   sol         sequencia de vertices que representa ciclo
   * @param   best_time   momento em que solucao atual foi encontrada
   * @param   LB          limite inferior encontrado para custo otimo
   * @param   alg_info    informacoes de execucao do algoritmo, ex: cadeia de
   *                      heuristicas utilizadas
   *
   * @return          0 = nao foi possivel encontrar solucao
   *                  1 = solucao encontrada, mas nao necessariamente otima
   *                  2 = solucao otima encontrada
   */

  // Sample Algorithm
  // Until solution is not integral, sets highest variable to its closest
  // integer value.

  // Variables
  GroupTSPLPSolver::ReturnType rettype = GroupTSPLPSolver::OPTIMAL_FRACTIONARY;
  GroupTSPLPSolver solver(g, weights, S);
  ListGraph::NodeMap<double> lpsol_vertex(g);
  ListGraph::EdgeMap<double> lpsol_edge(g);
  ListGraph::NodeMap<bool> already_set(g, false);
  double objVal = 0;
  time_t start = time(NULL);

  LB = -1;

  // main loop
  cout << "STARTING\n";
  while (rettype == GroupTSPLPSolver::OPTIMAL_FRACTIONARY) {
    cout << "Solving..\n";
    rettype = solver.getSolution(lpsol_vertex, lpsol_edge, objVal);

    if (fabsl(LB - (-1)) < EPS) {
      LB = objVal;
    }


    if (rettype == GroupTSPLPSolver::OPTIMAL_FRACTIONARY) {
      // Round highest variable to closest value.
      double mx = -1;
      Node mx_idx=INVALID;

      for(NodeIt v(g); v!=INVALID; ++v) {
        if (!already_set[v]) {
          if (lpsol_vertex[v] > mx) {
            mx = lpsol_vertex[v];
            mx_idx = v;
          }
        }
      }

      if (mx_idx != INVALID) {
        // int val = (lpsol_vertex[mx_idx] > 0.5 ? 1 : 0);
        int val = calculateIntegralWithProportionalProbability(lpsol_vertex[mx_idx]);
        cout << "Fixing " << g.id(mx_idx) << " to " << val << "\n";
        solver.fixNodeVariable(mx_idx, val);
        already_set[mx_idx] = true;
      } else {
        // it seems we were unable to obtain a solution with integral x[e]
        break;
      }
    }
  }

  // OBTAIN SOLUTION
  best_time = time(NULL) - start;
  if (rettype != GroupTSPLPSolver::OPTIMAL_INTEGRAL) {
    return 0;
  } else {
    /* do dfs to find out the answer */
    ListGraph::NodeMap<bool> vis(g, false);

    for(ListGraph::NodeIt v(g); v != INVALID; ++v) {
      if ( lpsol_vertex[v] > 1.0 - EPS ) {
        queue<ListGraph::Node> q;
        vis[v] = true;
        q.push(v);

        while (!q.empty()) {
          ListGraph::Node u = q.front(); q.pop();
          sol.push_back(u);

          for(ListGraph::IncEdgeIt e(g, u); e != INVALID; ++e) {
            ListGraph::Node w = g.runningNode(e);
            if (lpsol_edge[e] > 1.0 - EPS && !vis[w]) {
              vis[w] = true;
              q.push(w);
              /* only pick one! */
              break;
            }
          }
        }

        break;
      }
    }

    // check if there are vertices outside the cycle
    for(NodeIt v(g); v != INVALID; ++v) {
      if (lpsol_vertex[v] > 1-EPS && !vis[v]) {
        sol.clear();
        return 0;
      }
    }
    return fabsl(objVal - LB) < EPS ? 2 : 1;
  }
}
示例#4
0
// This routine use the neato program to generate positions.
bool GenerateVertexPositions(ListGraph &g,
			     EdgeValueMap &custo,
			     NodePosMap   &posx,
			     NodePosMap   &posy)
{
  size_t t=0;
  double x,y;
  char tempname[1000],tempnamedot[1000],tempnameposdot[1000],cmd[1000];
  ofstream out;
  ifstream in;
  string linha,substring;

  (void) custo;// to avoid "non-used" parameter message.
  
  // obtain a temporary file name
  strcpy(tempname,".readgraphtempname");
  strcpy(tempnamedot,tempname);   strcat(tempnamedot,".dot");
  strcpy(tempnameposdot,tempname);strcat(tempnameposdot,"_pos.dot");
  
  out.open(tempnamedot);
  if (!out.is_open()) return(false);

  out << "graph g {\n";
  out << "\tsize = \"11, 11\";\n";
  out << "\tnode [shape = \"circle\"];\n";
  for (NodeIt v(g); v!=INVALID; ++v) {
    linha = "\t";    linha += IntToString(g.id(v));   linha += ";\n";
    out << linha;
  }
  for (EdgeIt a(g); a!=INVALID; ++a) {
    linha = "\t";  linha += IntToString(g.id(g.u(a)));
    linha += "  -- ";  linha += IntToString(g.id(g.v(a))); linha += ";\n";
    out << linha;
  }
  out << "}\n";
  out.close();
  sprintf(cmd,"neato -Goverlap=false %s -o %s",tempnamedot,tempnameposdot); 
  //printf("neato -Goverlap=false %s -o %s\n",tempnamedot,tempnameposdot);
  fflush(stdout);
  system(cmd); // gera outro arquivo do neato, mas com posições
  
  in.open(tempnameposdot);
  if (!in.is_open()) return(false);
  while (!in.eof()) {
    getline(in,linha);
    t = linha.find("{");
    if (t!=string::npos) break;
  }
  if (t==string::npos) {
    cout << "Temp Graphviz file is not appropriate for GenerateVertexPositions.\n";
    exit(0);
  }
  for (NodeIt v(g); v!=INVALID; ++v) {
    getline(in,linha);
    // avoid info on the graph, node or edges
    while ((!in.eof()) && ((linha.find("graph [")!=string::npos) ||
			   (linha.find("node [")!=string::npos) ||
			   (linha.find("edge [")!=string::npos) || 
			   (linha.find(" -- ")!=string::npos))) {
      while ((!in.eof()) && (linha.find("];")==string::npos)) {
	string linha2;
	getline(in,linha2);
	linha += linha2;
      }
      getline(in,linha);
      while ((!in.eof()) && (linha.find("[")==string::npos)) {
	string linha2;
	getline(in,linha2);
	linha += linha2;
      }
    }
    if (linha.find("[")!=string::npos) {
      while (linha.find("];")==string::npos) {
	string linha2;
	getline(in,linha2);
	linha += linha2;
      }
    }
    t = linha.find("pos=\"");
    if (t!=string::npos) {
      stringstream s;
      int nodeid;
      sscanf(linha.c_str(),"%d",&nodeid);
      substring = linha.substr(t+5);
      sscanf(substring.c_str(),"%lf,%lf",&x,&y);
      //printf("%lf , %lf",x,y);
      for (NodeIt vv(g); vv!=INVALID; ++vv) {
	if (nodeid==g.id(vv)){
	  posx[vv] = x;
	  posy[vv] = y;
	  //printf("interno: %d   ( %lf , %lf )\n",g.id(vv),posx[vv],posy[vv]);
	  break;
	}
      }
    } else {
      printf("GenerateVertexPositions: Error to obtain vertex coordinates.\n");
      return(false);
    }
  }
  //for (NodeIt vv(g); vv!=INVALID; ++vv) {
  // printf(" %d   ( %lf , %lf )\n",g.id(vv),posx[vv],posy[vv]);
  //}
  //printf("-------------------------------------------------------\n");
  return(true);
}