当前位置: 首页>>代码示例>>C++>>正文


C++ Graph类代码示例

本文整理汇总了C++中Graph的典型用法代码示例。如果您正苦于以下问题:C++ Graph类的具体用法?C++ Graph怎么用?C++ Graph使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Graph类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: randomHierarchy

void randomHierarchy(
	Graph &G,
	int numberOfNodes,
	int numberOfEdges,
	bool planar,
	bool singleSource,
	bool longEdges)
{
	G.clear();

	Array<node> nnr (3*numberOfNodes);
	Array<int>  vrt (3*numberOfNodes);
	Array<int>  fst (numberOfNodes+1);

	/** Place nodes **/

	for(int i = 0; i < numberOfNodes; i++)
		G.newNode();

	minstd_rand rng(randomSeed());
	uniform_real_distribution<> dist_0_1(0.0,1.0);

	int numberOfLayers = 0, totNumber = 0, realCount = 0;
	fst[0] = 0;
	for(node v : G.nodes) {
		if(longEdges && numberOfLayers) vrt[totNumber++] = 1;

		nnr[totNumber] = v;
		vrt[totNumber++] = 0;
		realCount++;
		double r = dist_0_1(rng);
		if((totNumber == 1 && singleSource) || realCount == numberOfNodes || r*r*numberOfNodes < 1)
		{
			if(longEdges && numberOfLayers)
				vrt[totNumber++] = 1;
			fst[++numberOfLayers] = totNumber;
		}
	}

	/** Determine allowed neighbours **/

	Array<int> leftN (totNumber);
	Array<int> rightN(totNumber);
	for(int l = 1; l < numberOfLayers; l++)
	{
		if(planar) {
			int n1 = fst[l-1];
			int n2 = fst[l];
			leftN[n2] = n1;
			while(n1 < fst[l] && n2 < fst[l+1]) {
				double r = dist_0_1(rng);
				if(n1 != fst[l]-1 &&
					(n2 == fst[l+1]-1 ||
					r < (double)(fst[l]-fst[l-1])/(double)(fst[l+1]-fst[l-1])))
					n1++;
				else {
					rightN[n2] = n1;
					if(++n2 < fst[l+1])
						leftN[n2] = n1;
				}
			}
		}
		else
			for(int n2 = fst[l]; n2 < fst[l+1]; n2++) {
				leftN [n2] = fst[l-1];
				rightN[n2] = fst[l]-1;
			}
	}

	/** Insert edges **/

	List<bEdge> startEdges;
	Array<SList<bEdge>> edgeIn (totNumber);
	Array<SList<bEdge>> edgeOut(totNumber);

	if (numberOfLayers) {
		double x1 = numberOfEdges;
		double x2 = 0;
		for (int n2 = fst[1]; n2 < totNumber; n2++) {
			if (!vrt[n2])
				x2 += rightN[n2] - leftN[n2] + 1;
		}

		int idc = 0;
		for (int n2 = fst[1]; n2 < totNumber; n2++) {
			if (!vrt[n2]) {
				bool connected = !singleSource;
				for (int n1 = leftN[n2]; n1 <= rightN[n2] || !connected; n1++) {
					double r = dist_0_1(rng);
					if (r < x1 / x2 || n1 > rightN[n2]) {
						int next = (n1 <= rightN[n2] ? n1 : uniform_int_distribution<>(leftN[n2], rightN[n2])(rng));
						int act = n2;
						bEdge nextEdge = OGDF_NEW BEdge(next, act, idc++);
						while (vrt[next]) {
							act = next;
							next = uniform_int_distribution<>(leftN[act], rightN[act])(rng);
							edgeOut[act].pushBack(nextEdge);
							nextEdge = OGDF_NEW BEdge(next, act, idc++);
							edgeIn[act].pushBack(nextEdge);
						}
//.........这里部分代码省略.........
开发者ID:marvin2k,项目名称:ogdf,代码行数:101,代码来源:random_hierarchy.cpp

示例2: pers_pagerank

    // Personalized pagerank starting from vertex start (at index 0)
    void pers_pagerank()
    {
        Graph *graph = sub->subgraph;
        unsigned iter = 0;
        double err = 1.0;
        // We are done when maxiteration is reached 
        // or the error is small enough.
        while (iter++ < maxiter && err > tolerance)
        {
            // copy last iteration to last array
            // and clear pagerank array
            #pragma omp parallel for
            for (unsigned i = 0; i < nvert; i++)
            {
                last[i] = pagerank[i];
                pagerank[i] = 0.0;
            }

            // sum up the nodes without outgoing edges ("dangling nodes").
            // their pagerank sum will be uniformly distributed among all nodes.
            double zsum = 0.0;
            #pragma omp parallel for reduction(+:zsum)
            for (unsigned i = 0; i < sub->zerodeg.size(); i++)
                zsum += last[ sub->zerodeg[i] ];
            double nolinks = (1.0-alpha) * zsum / nvert;
    
            pagerank[0] += alpha; // add teleport probability to the start vertex
            #pragma omp parallel for
            for (unsigned id = 0; id < nvert; id++)
            {
                double update = (1.0-alpha) * last[id];
                for (Graph::iterator e = graph->iterate_outgoing_edges(id); !e.end(); e++)
                {
                    #pragma omp atomic
                    pagerank[(*e).v2] += (update * sub->score(id, (*e).v2));
                }
                #pragma omp atomic
                pagerank[id] += nolinks; // pagerank from "dangling nodes"
            }
    
            // sum the pagerank
            double sum = 0.0;
            #pragma omp parallel for reduction(+:sum)
            for (unsigned i = 0; i < nvert; i++)
                sum += pagerank[i];

            // normalize to valid probabilities, from 0 to 1.
            sum = 1.0 / sum;
            #pragma omp parallel for 
            for (unsigned i = 0; i < nvert; i++)
                pagerank[i] *= sum;

            // sum up the error
            err = 0.0;
            #pragma omp parallel for reduction(+:err)
            for (unsigned i = 0; i < nvert; i++)
                err += fabs(pagerank[i] - last[i]);

            //cout << "Iteration " << iter << endl;
            //cout << "Error: " << err << endl;
        }
        //cout << "PageRank iterations: " << iter << endl;
    }
开发者ID:dmitrime,项目名称:srw,代码行数:64,代码来源:srw.cpp

示例3: do_degrees

void do_degrees() {
  for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) {
    std::cout << std::distance(graph.neighbor_begin(*ii), graph.neighbor_end(*ii)) << "\n";
  }
}
开发者ID:nikunjy,项目名称:parallelStuff,代码行数:5,代码来源:graph-stats.cpp

示例4: tlp_loadGraph

//==========================================================
void PlanarityTestTest::planarMetaGraphsEmbedding() {
  tlp::warning() << "===========MetaGraphsEmbedding=======================" << endl;
  graph = tlp_loadGraph(GRAPHPATH + "planar/grid1010.tlp");
  Graph *g = graph->addCloneSubGraph();
  vector<node> toGroup;
  toGroup.reserve(10);
  const std::vector<node> &nodes = graph->nodes();

  for (unsigned int i = 0; i < 10; ++i)
    toGroup.push_back(nodes[i]);

  g->createMetaNode(toGroup);
  toGroup.clear();

  for (unsigned int i = 10; i < 20; ++i)
    toGroup.push_back(nodes[i]);

  node meta2 = g->createMetaNode(toGroup);
  toGroup.clear();
  toGroup.push_back(meta2);

  for (unsigned int i = 20; i < 30; ++i)
    toGroup.push_back(nodes[i]);

  g->createMetaNode(toGroup, false);
  toGroup.clear();

  PlanarConMap *graphMap = computePlanarConMap(g);
  //  graphMap->makePlanar();
  CPPUNIT_ASSERT(PlanarityTest::isPlanar(g));        // eulerIdentity(g), graphMap->nbFaces());
  CPPUNIT_ASSERT(PlanarityTest::isPlanar(graphMap)); // eulerIdentity(g), graphMap->nbFaces());
  delete graphMap;
  graph->delSubGraph(g);
  delete graph;
  tlp::warning() << "==================================" << endl;
  /*
    graph = tlp::loadGraph(GRAPHPATH + "planar/unconnected.tlp");
    graph->setAttribute("name", string("unconnected"));
    graphMap = new PlanarConMap(graph);
    tlp::warning() << "Graph name : " << graph->getAttribute<string>("name") << endl;
    graphMap->makePlanar();*/
  /*
   * The number of faces must be adapted because the Planarity Test split the
   * external face into several faces (one by connected componnent).
   */
  /*  CPPUNIT_ASSERT_EQUAL(eulerIdentity(graph), graphMap->nbFaces() -
     (ConnectedTest::numberOfConnectedComponnents(graph) - 1));
      delete graphMap;
      delete graph;
      tlp::warning() << "==================================" << endl;
      tlp::warning() << "unbiconnected" << endl;
      graph = tlp::loadGraph(GRAPHPATH + "planar/unbiconnected.tlp");

      graphMap = new PlanarConMap(graph);

      graphMap->makePlanar();
      CPPUNIT_ASSERT_EQUAL(eulerIdentity(graph), graphMap->nbFaces());

      delete graphMap;
      delete graph;
      tlp::warning() << "==================================" << endl;*/
}
开发者ID:tulip5,项目名称:tulip,代码行数:63,代码来源:PlanarityTestTest.cpp

示例5: main

int main(int argc, char *argv[])
{
	//first argument, lowercase, if any
	std::string fl = argc>1 ? lowercase(argv[1]) : "";
	if (argc<=2) {
		if (fl=="" || fl=="--help" || fl=="-h" || fl=="/?" || fl=="/help") {
			std::cerr << "usage:\t" << argv[0] << " graph [''|solution|'='|'%'|color]" << std::endl;
			std::cerr << "where:\t" << "graph and solution are filenames" << std::endl;
			std::cerr << "\tcolor is an id in the default color palette" << std::endl;
			return 1;
		}
		else {
			try {
				Graph graph = Graph::load(argv[1]);
				signal(SIGUSR1, Metaheuristic::dump_handler);
				std::vector<int> v(graph.succ.size(), 0);
				Solution sol(v, graph);
				sol.initSolution();
				//TODO adjust parameters here!
				float alpha = 0.9f;
				float temperature = 10.0f;
				float epsilon = 1.0f;
				int niter = 10;
				//std::cerr << "HIT before create recuit" << std::endl;
				Recuit meta(sol, alpha, niter, temperature, epsilon);
				//std::cerr << "HIT before starting recuit" << std::endl;
				//LocalSearch meta(graph);
				sol = meta.getSolution();
				sol.dump();
				if(sol.isAdmissible())
					std::cerr << "GOOD" << std::endl;
				return 0;
			}
			catch (GraphException& e) {
				std::cerr << "error: " << e.what() << std::endl;
				return 2;
			}
		}
	}
	else {
		try {
			Graph g = Graph::load(argv[1]);
#ifdef USE_SDL
			Solution *s = NULL;
			int pattern = get_positive(argv[2]);
			if (pattern == -1) {
				std::string a2 = argv[2];
				if (a2 == "=")
					pattern = -1;
				else if (a2 == "%")
					pattern = -2;
				else
					s = new Solution(Solution::load(a2, g));
			}
			if (!s)
				s = new Solution(Solution::load(g, pattern));
			ui_main(g, s);
			delete s;
#else
			g.dump();
#endif //USE_SDL
			return 0;
		}
		catch (SolutionException& e) {
			std::cerr << "error: " << e.what() << std::endl;
			return 3;
		}
		catch (GraphException& e) {
			std::cerr << "error: " << e.what() << std::endl;
			return 2;
		}
	}
}
开发者ID:ghuysmans,项目名称:metacombi,代码行数:73,代码来源:metacombi.cpp

示例6: vertex_event

 void vertex_event(const char* name, Vertex v, const Graph& g)
 {
   std::cerr << "#" << process_id(g.process_group()) << ": " << name << "("
             << get_vertex_name(v, g) << ": " << local(v) << "@" << owner(v)
             << ")\n";
 }
开发者ID:LancelotGHX,项目名称:Simula,代码行数:6,代码来源:distributed_csr_algorithm_test.cpp

示例7: tryGraphs

void NodeController::tryGraphs()
{
    Graph<int> testerGraph;
    testerGraph.addVertex(7);
    testerGraph.addVertex(18);
    testerGraph.addVertex(9);
    testerGraph.addVertex(17);
    testerGraph.addVertex(6);
    testerGraph.addVertex(3);
    testerGraph.addVertex(52);
    testerGraph.addVertex(68);
    testerGraph.addVertex(23);
    testerGraph.addVertex(35);
    //Add at least 7 vertices.
    //Connct the vertices
    testerGraph.addEdge(0,1);
    testerGraph.addEdge(1,2);
    testerGraph.addEdge(2,3);
    testerGraph.addEdge(6,7);
    testerGraph.addEdge(7,8);
    testerGraph.addEdge(8,9);
    
    
    testerGraph.breadthFirstTraversal(testerGraph, 0);
    
    
    
}
开发者ID:AlexMJHS,项目名称:NodesInXCode,代码行数:28,代码来源:NodeController.cpp

示例8: makeGraph

static void makeGraph(const char* input) {
   std::vector<GNode> nodes;
   //Create local computation graph.
   typedef Galois::Graph::LC_CSR_Graph<Node, EdgeDataType> InGraph;
   typedef InGraph::GraphNode InGNode;
   InGraph in_graph;
   //Read graph from file.
   in_graph.structureFromFile(input);
   std::cout << "Read " << in_graph.size() << " nodes\n";
   //A node and a int is an element.
   typedef std::pair<InGNode, EdgeDataType> Element;
   //A vector of element is 'Elements'
   typedef std::vector<Element> Elements;
   //A vector of 'Elements' is a 'Map'
   typedef std::vector<Elements> Map;
   //'in_edges' is a vector of vector of pairs of nodes and int.
   Map edges(in_graph.size());
   //
   int numEdges = 0;
   for (InGraph::iterator src = in_graph.begin(), esrc = in_graph.end(); src != esrc; ++src) {
      for (InGraph::edge_iterator dst = in_graph.edge_begin(*src, Galois::NONE), edst = in_graph.edge_end(*src, Galois::NONE); dst != edst; ++dst) {
         if (*src == *dst) {
#if BORUVKA_DEBUG
            std::cout<<"ERR:: Self loop at "<<*src<<std::endl;
#endif
            continue;
         }
         EdgeDataType w = in_graph.getEdgeData(dst);
         Element e(*src, w);
         edges[in_graph.getEdgeDst(dst)].push_back(e);
         numEdges++;
      }
   }
#if BORUVKA_DEBUG
   std::cout<<"Number of edges "<<numEdges<<std::endl;
#endif
   nodes.resize(in_graph.size());
   for (Map::iterator i = edges.begin(), ei = edges.end(); i != ei; ++i) {
      Node n(nodeID);
      GNode node = graph.createNode(n);
      graph.addNode(node);
      nodes[nodeID] = node;
      nodeID++;
   }

   int id = 0;
   numEdges = 0;
   EdgeDataType edge_sum = 0;
   int numDups = 0;
   for (Map::iterator i = edges.begin(), ei = edges.end(); i != ei; ++i) {
      GNode src = nodes[id];
      for (Elements::iterator j = i->begin(), ej = i->end(); j != ej; ++j) {
         Graph::edge_iterator it = graph.findEdge(src, nodes[j->first], Galois::NONE);
         if (it != graph.edge_end(src, Galois::NONE)) {
            numDups++;
            EdgeDataType w = (graph.getEdgeData(it));
            if (j->second < w) {
               graph.getEdgeData(it) = j->second;
               edge_sum += (j->second-w);
            }
         } else {
            graph.getEdgeData(graph.addEdge(src, nodes[j->first], Galois::NONE)) = j->second;
            edge_sum += j->second;
         }
         numEdges++;
         assert(edge_sum < std::numeric_limits<EdgeDataType>::max());
      }
      id++;
   }
#if BORUVKA_DEBUG
   std::cout << "Final num edges " << numEdges << " Dups " << numDups << " sum :" << edge_sum << std::endl;
#endif
}
开发者ID:nikunjy,项目名称:parallelStuff,代码行数:73,代码来源:BoruvkaMorph.cpp

示例9: operator

   void operator()(GNode& src, ContextTy& lwl) {
      if (graph.containsNode(src) == false)
         return;
      graph.getData(src, Galois::ALL);
      GNode * minNeighbor = 0;
#if BORUVKA_DEBUG
      std::cout<<"Processing "<<graph.getData(src).toString()<<std::endl;
#endif
      EdgeDataType minEdgeWeight = std::numeric_limits<EdgeDataType>::max();
      //Acquire locks on neighborhood.
      for (Graph::edge_iterator dst = graph.edge_begin(src, Galois::ALL), edst = graph.edge_end(src, Galois::ALL); dst != edst; ++dst) {
         graph.getData(graph.getEdgeDst(dst));
      }
      //Find minimum neighbor
      for (Graph::edge_iterator e_it = graph.edge_begin(src, Galois::NONE), edst = graph.edge_end(src, Galois::NONE); e_it != edst; ++e_it) {
         EdgeDataType w = graph.getEdgeData(e_it, Galois::NONE);
         assert(w>=0);
         if (w < minEdgeWeight) {
            minNeighbor = &((*e_it).first());
            minEdgeWeight = w;
         }
      }
      //If there are no outgoing neighbors.
      if (minEdgeWeight == std::numeric_limits<EdgeDataType>::max()) {
         graph.removeNode(src, Galois::NONE);
         return;
      }
#if BORUVKA_DEBUG
            std::cout << " Min edge from "<<graph.getData(src) << " to "<<graph.getData(*minNeighbor)<<" " <<minEdgeWeight << " "<<std::endl;
#endif
      //Acquire locks on neighborhood of min neighbor.
      for (Graph::edge_iterator e_it = graph.edge_begin(*minNeighbor, Galois::ALL), edst = graph.edge_end(*minNeighbor, Galois::ALL); e_it != edst; ++e_it) {
         graph.getData(graph.getEdgeDst(e_it));
      }
      assert(minEdgeWeight>=0);
      //update MST weight.
      *MSTWeight.getLocal() += minEdgeWeight;
      typedef std::pair<GNode, EdgeDataType> EdgeData;
      typedef std::set<EdgeData, std::less<EdgeData>, Galois::PerIterAllocTy::rebind<EdgeData>::other> edsetTy;
      edsetTy toAdd(std::less<EdgeData>(), Galois::PerIterAllocTy::rebind<EdgeData>::other(lwl.getPerIterAlloc()));
      for (Graph::edge_iterator mdst = graph.edge_begin(*minNeighbor, Galois::NONE), medst = graph.edge_end(*minNeighbor, Galois::NONE); mdst != medst; ++mdst) {
         GNode dstNode = graph.getEdgeDst(mdst);
         int edgeWeight = graph.getEdgeData(mdst,Galois::NONE);
         if (dstNode != src) { //Do not add the edge being contracted
            Graph::edge_iterator dup_edge = graph.findEdge(src, dstNode, Galois::NONE);
            if (dup_edge != graph.edge_end(src, Galois::NONE)) {
               EdgeDataType dup_wt = graph.getEdgeData(dup_edge,Galois::NONE);
                  graph.getEdgeData(dup_edge,Galois::NONE) = std::min<EdgeDataType>(edgeWeight, dup_wt);
                  assert(std::min<EdgeDataType>(edgeWeight, dup_wt)>=0);
            } else {
                  toAdd.insert(EdgeData(dstNode, edgeWeight));
                  assert(edgeWeight>=0);
            }
         }
      }
      graph.removeNode(*minNeighbor, Galois::NONE);
      for (edsetTy::iterator it = toAdd.begin(), endIt = toAdd.end(); it != endIt; it++) {
         graph.getEdgeData(graph.addEdge(src, it->first, Galois::NONE)) = it->second;
      }
      lwl.push(src);
#if COMPILE_STATISICS
      if(stat_collector.tick().counter%BORUVKA_SAMPLE_FREQUENCY==0)
         stat_collector.snap();
#endif
   }
开发者ID:nikunjy,项目名称:parallelStuff,代码行数:65,代码来源:BoruvkaMorph.cpp

示例10: operator

template<size_t span> struct debruijn_mphf_bench {  void operator ()  (Parameter params)
{
    typedef NodeFast<span> NodeFastT;
    typedef GraphTemplate<NodeFastT,EdgeFast<span>,GraphDataVariantFast<span>> GraphFast;

    size_t kmerSize = params.k;
    
    Graph graph; 
    GraphFast graphFast;
  
    if (params.seq == "") 
    {
        graph = Graph::create (params.args.c_str());
        graphFast = GraphFast::create (params.args.c_str());
    }
    else
    {
        graph = Graph::create (new BankStrings (params.seq.c_str(), 0), params.args.c_str());
        graphFast = GraphFast::create (new BankStrings (params.seq.c_str(), 0), params.args.c_str());

    }

    cout << "graph built, benchmarking.." << endl;

    
    int miniSize = 8;
    int NB_REPETITIONS = 2000000;

    double unit = 1000000000;
    cout.setf(ios_base::fixed);
    cout.precision(3);

    Graph::Iterator<Node> nodes = graph.iterator();
    typename GraphFast::template Iterator<NodeFastT> nodesFast = graphFast.iterator();
    nodes.first ();

    /** We get the first node. */
    Node node = nodes.item();

    typedef typename Kmer<span>::Type  Type;
    typedef typename Kmer<span>::ModelCanonical  ModelCanonical;
    typedef typename Kmer<span>::ModelDirect     ModelDirect;
    typedef typename Kmer<span>::template ModelMinimizer <ModelCanonical>   ModelMini;
    typedef typename ModelMini::Kmer                        KmerType;

    ModelMini  modelMini (kmerSize, miniSize);
    ModelCanonical  modelCanonical (kmerSize);

     // for some reason.. if *compiled*, this code confuses makes later MPHF queries 3x slower. really? yes. try to replace "if (confuse_mphf)" by "if (confuse_mphf && 0)" and re-run, you will see.
    {
        bool confuse_mphf = false;
        if (confuse_mphf)
        {
            //Type b; b.setVal(0); 
            //modelCanonical.emphf_hasher(modelCanonical.adaptor(b)); 
            //typedef std::pair<u_int8_t const*, u_int8_t const*> byte_range_t;

            //int c = 0; 
            //byte_range_t brange( reinterpret_cast <u_int8_t const*> (&c), reinterpret_cast <u_int8_t const*> (&c) + 2 );
            //byte_range_t brange( (u_int8_t const*) 1,(u_int8_t const*)33);
            //auto hashes = modelCanonical.empfh_hasher(brange);
        }


        for (int i = 0; i < 0; i++)
        {
            auto start_tt=chrono::system_clock::now();
            for (nodes.first(); !nodes.isDone(); nodes.next())
                modelCanonical.EMPHFhash(nodes.item().kmer.get<Type>());
            auto end_tt=chrono::system_clock::now();
            cout << "time to do " << nodes.size() << " computing EMPHFhash of kmers on all nodes (" << kmerSize << "-mers) : " << (diff_wtime(start_tt, end_tt) / unit) << " seconds" << endl;
        }
        // it's slow. i don't understand why. see above for the "confuse mphf" part
        //return; //FIXME
    }


    /** We get the value of the first node (just an example, it's not used later). */
    Type kmer = node.kmer.get<Type>();
    
    auto start_t=chrono::system_clock::now();
    auto end_t=chrono::system_clock::now();
			
   cout << "----\non all nodes of the graph\n-----\n";

    /* disable node state (because we don't want to pay the price for overhea of checking whether a node is deleted or not in contain() */
   std::cout<< "PAY ATTENTION: this neighbor() benchmark, in the Bloom flavor, is without performing a MPHF query for each found node" << std::endl; 

   graph.disableNodeState(); 
   graphFast.disableNodeState(); 

   /* compute baseline times (= overheads we're not interested in) */

    start_t=chrono::system_clock::now();
    for (nodes.first(); !nodes.isDone(); nodes.next())
    {}
    end_t=chrono::system_clock::now();
    auto baseline_graph_time = diff_wtime(start_t, end_t) / unit;
    cout << "baseline overhead for graph nodes enumeration (" << nodes.size() << " nodes) : " << baseline_graph_time << " seconds" << endl;

//.........这里部分代码省略.........
开发者ID:pombredanne,项目名称:gatb-core,代码行数:101,代码来源:bench_graph.cpp

示例11: int

void MultiLayer::printAllLayers(QPainter *painter) {
  if (!painter) return;

  QPrinter *printer = (QPrinter *)painter->device();
  QRect paperRect = ((QPrinter *)painter->device())->paperRect();
  QRect canvasRect = canvas->rect();
  QRect pageRect = printer->pageRect();
  QRect cr = canvasRect;  // cropmarks rectangle

  if (d_scale_on_print) {
    int margin = (int)((1 / 2.54) * printer->logicalDpiY());  // 1 cm margins
    double scaleFactorX =
        (double)(paperRect.width() - 2 * margin) / (double)canvasRect.width();
    double scaleFactorY =
        (double)(paperRect.height() - 2 * margin) / (double)canvasRect.height();

    if (d_print_cropmarks) {
      cr.moveTo(QPoint(margin + int(cr.x() * scaleFactorX),
                       margin + int(cr.y() * scaleFactorY)));
      cr.setWidth(int(cr.width() * scaleFactorX));
      cr.setHeight(int(cr.height() * scaleFactorX));
    }

    for (int i = 0; i < (int)graphsList.count(); i++) {
      Graph *gr = (Graph *)graphsList.at(i);
      Plot *myPlot = gr->plotWidget();

      QPoint pos = gr->pos();
      pos = QPoint(margin + int(pos.x() * scaleFactorX),
                   margin + int(pos.y() * scaleFactorY));

      int width = int(myPlot->frameGeometry().width() * scaleFactorX);
      int height = int(myPlot->frameGeometry().height() * scaleFactorY);

      gr->print(painter, QRect(pos, QSize(width, height)));
    }
  } else {
    int x_margin = (pageRect.width() - canvasRect.width()) / 2;
    int y_margin = (pageRect.height() - canvasRect.height()) / 2;

    if (d_print_cropmarks) cr.moveTo(x_margin, y_margin);

    for (int i = 0; i < (int)graphsList.count(); i++) {
      Graph *gr = (Graph *)graphsList.at(i);
      Plot *myPlot = (Plot *)gr->plotWidget();

      QPoint pos = gr->pos();
      pos = QPoint(x_margin + pos.x(), y_margin + pos.y());
      gr->print(painter, QRect(pos, myPlot->size()));
    }
  }
  if (d_print_cropmarks) {
    cr.addCoords(-1, -1, 2, 2);
    painter->save();
    painter->setPen(QPen(QColor(Qt::black), 0.5, Qt::DashLine));
    painter->drawLine(paperRect.left(), cr.top(), paperRect.right(), cr.top());
    painter->drawLine(paperRect.left(), cr.bottom(), paperRect.right(),
                      cr.bottom());
    painter->drawLine(cr.left(), paperRect.top(), cr.left(),
                      paperRect.bottom());
    painter->drawLine(cr.right(), paperRect.top(), cr.right(),
                      paperRect.bottom());
    painter->restore();
  }
}
开发者ID:narunlifescience,项目名称:AlphaPlot,代码行数:65,代码来源:MultiLayer.cpp

示例12: gsl_vector_calloc

QSize MultiLayer::arrangeLayers(bool userSize) {
  const QRect rect = canvas->geometry();

  gsl_vector *xTopR = gsl_vector_calloc(
      graphs);  // ratio between top axis + title and canvas height
  gsl_vector *xBottomR =
      gsl_vector_calloc(graphs);  // ratio between bottom axis and canvas height
  gsl_vector *yLeftR = gsl_vector_calloc(graphs);
  gsl_vector *yRightR = gsl_vector_calloc(graphs);
  gsl_vector *maxXTopHeight =
      gsl_vector_calloc(rows);  // maximum top axis + title height in a row
  gsl_vector *maxXBottomHeight =
      gsl_vector_calloc(rows);  // maximum bottom axis height in a row
  gsl_vector *maxYLeftWidth =
      gsl_vector_calloc(cols);  // maximum left axis width in a column
  gsl_vector *maxYRightWidth =
      gsl_vector_calloc(cols);  // maximum right axis width in a column
  gsl_vector *Y = gsl_vector_calloc(rows);
  gsl_vector *X = gsl_vector_calloc(cols);

  int i;
  for (i = 0; i < graphs;
       i++) {  // calculate scales/canvas dimensions reports for each layer and
               // stores them in the above vectors
    Graph *gr = (Graph *)graphsList.at(i);
    QwtPlot *plot = gr->plotWidget();
    QwtPlotLayout *plotLayout = plot->plotLayout();
    QRect cRect = plotLayout->canvasRect();
    double ch = (double)cRect.height();
    double cw = (double)cRect.width();

    QRect tRect = plotLayout->titleRect();
    QwtScaleWidget *scale = (QwtScaleWidget *)plot->axisWidget(QwtPlot::xTop);

    int topHeight = 0;
    if (!tRect.isNull()) topHeight += tRect.height() + plotLayout->spacing();
    if (scale) {
      QRect sRect = plotLayout->scaleRect(QwtPlot::xTop);
      topHeight += sRect.height();
    }
    gsl_vector_set(xTopR, i, double(topHeight) / ch);

    scale = (QwtScaleWidget *)plot->axisWidget(QwtPlot::xBottom);
    if (scale) {
      QRect sRect = plotLayout->scaleRect(QwtPlot::xBottom);
      gsl_vector_set(xBottomR, i, double(sRect.height()) / ch);
    }

    scale = (QwtScaleWidget *)plot->axisWidget(QwtPlot::yLeft);
    if (scale) {
      QRect sRect = plotLayout->scaleRect(QwtPlot::yLeft);
      gsl_vector_set(yLeftR, i, double(sRect.width()) / cw);
    }

    scale = (QwtScaleWidget *)plot->axisWidget(QwtPlot::yRight);
    if (scale) {
      QRect sRect = plotLayout->scaleRect(QwtPlot::yRight);
      gsl_vector_set(yRightR, i, double(sRect.width()) / cw);
    }

    // calculate max scales/canvas dimensions ratio for each line and column and
    // stores them to vectors
    int row = i / cols;
    if (row >= rows) row = rows - 1;

    int col = i % cols;

    double aux = gsl_vector_get(xTopR, i);
    double old_max = gsl_vector_get(maxXTopHeight, row);
    if (aux >= old_max) gsl_vector_set(maxXTopHeight, row, aux);

    aux = gsl_vector_get(xBottomR, i);
    if (aux >= gsl_vector_get(maxXBottomHeight, row))
      gsl_vector_set(maxXBottomHeight, row, aux);

    aux = gsl_vector_get(yLeftR, i);
    if (aux >= gsl_vector_get(maxYLeftWidth, col))
      gsl_vector_set(maxYLeftWidth, col, aux);

    aux = gsl_vector_get(yRightR, i);
    if (aux >= gsl_vector_get(maxYRightWidth, col))
      gsl_vector_set(maxYRightWidth, col, aux);
  }

  double c_heights = 0.0;
  for (i = 0; i < rows; i++) {
    gsl_vector_set(Y, i, c_heights);
    c_heights += 1 + gsl_vector_get(maxXTopHeight, i) +
                 gsl_vector_get(maxXBottomHeight, i);
  }

  double c_widths = 0.0;
  for (i = 0; i < cols; i++) {
    gsl_vector_set(X, i, c_widths);
    c_widths += 1 + gsl_vector_get(maxYLeftWidth, i) +
                gsl_vector_get(maxYRightWidth, i);
  }

  if (!userSize) {
    l_canvas_width = int(
//.........这里部分代码省略.........
开发者ID:narunlifescience,项目名称:AlphaPlot,代码行数:101,代码来源:MultiLayer.cpp

示例13: main

int
main(int argc, char **argv) {
  
  srand(time(NULL));

  parse_args(argc, argv);

  time_t time_begin, time_end;
  time(&time_begin);
  display_time("start");
    
  Community c(filename, type, -1, precision);

  display_time("file read");

  double mod = c.modularity();

  //cerr << "network : " 
      // << c.g.nb_nodes << " nodes, " 
       //<< c.g.nb_links << " links, "
       //<< c.g.total_weight << " weight." << endl;
 
  double new_mod = c.one_level();

  display_time("communities computed");
  //cerr << "modularity increased from " << mod << " to " << new_mod << endl;

  if (display_level==-1)
    c.display_partition();

  Graph g = c.partition2graph_binary();

  display_time("network of communities computed");

  int level=0;
  while(new_mod-mod>precision) {
    mod=new_mod;
    Community c(g, -1, precision);

    //cerr << "\nnetwork : " 
	 //<< c.g.nb_nodes << " nodes, " 
	 //<< c.g.nb_links << " links, "
	 //<< c.g.total_weight << " weight." << endl;
    
    new_mod = c.one_level();
    
    display_time("communities computed");
    //cerr << "modularity increased from " << mod << " to " << new_mod << endl;
    
    if (display_level==-1)
      c.display_partition();
    
    g = c.partition2graph_binary();
    level++;
    
    if (level==display_level)
      g.display();
    
    display_time("network of communities computed");

  }
  time(&time_end);
  
  //cerr << precision << " " << new_mod << " " << (time_end-time_begin) << endl;
}
开发者ID:CompNet,项目名称:Orleans,代码行数:65,代码来源:main_community.cpp

示例14: verify

EdgeDataType verify(Graph & g){
   return kruskal_impl(g.size(), read_edges(g));
}
开发者ID:nikunjy,项目名称:parallelStuff,代码行数:3,代码来源:BoruvkaMorph.cpp

示例15: TEST_F

TEST_F(HexBoardTest,HexBoardSetMove) {
  //test 5x5 Hexboard
  HexBoard board(5);
  Game hexboardgame(board);
  Player playera(board, hexgonValKind_RED);

  //test with private set setPlayerBoard method and corresponding MST tree
  ASSERT_TRUE(hexboardgame.setMove(playera, 1, 1));
  HexBoard playerasboard = playera.getPlayersboard();
  EXPECT_EQ(0, playerasboard.getSizeOfEdges());
  EXPECT_EQ(board.getNumofemptyhexgons(), board.getSizeOfVertices() - 1);
  ASSERT_TRUE(hexboardgame.setMove(playera, 2, 1));
  playerasboard = playera.getPlayersboard();
  EXPECT_EQ(1, playerasboard.getSizeOfEdges());
  EXPECT_EQ(board.getNumofemptyhexgons(), board.getSizeOfVertices() - 2);
  ASSERT_TRUE(hexboardgame.setMove(playera, 3, 1));
  playerasboard = playera.getPlayersboard();
  EXPECT_EQ(2, playerasboard.getSizeOfEdges());
  EXPECT_EQ(board.getNumofemptyhexgons(), board.getSizeOfVertices() - 3);
  ASSERT_TRUE(hexboardgame.setMove(playera, 4, 1));
  playerasboard = playera.getPlayersboard();
  EXPECT_EQ(3, playerasboard.getSizeOfEdges());
  EXPECT_EQ(board.getNumofemptyhexgons(), board.getSizeOfVertices() - 4);
  ASSERT_TRUE(hexboardgame.setMove(playera, 5, 1));
  playerasboard = playera.getPlayersboard();
  EXPECT_EQ(4, playerasboard.getSizeOfEdges());
  EXPECT_EQ(board.getNumofemptyhexgons(), board.getSizeOfVertices() - 5);

  MinSpanTreeAlgo<hexgonValKind, int> mstalgo(playerasboard);
  MinSpanTreeAlgo<hexgonValKind, int>::UnionFind unionfind(mstalgo);
  mstalgo.calculate(unionfind);

  Graph<hexgonValKind, int> msttree = mstalgo.getMsttree();
  EXPECT_EQ(4, msttree.getSizeOfEdges());
  vector<vector<int> > subgraphs = msttree.getAllSubGraphs();
  EXPECT_EQ(1, subgraphs.size());

  Player playerb(board, hexgonValKind_BLUE);
  ASSERT_TRUE(hexboardgame.setMove(playerb, 1, 2));
  HexBoard playerbsboard = playerb.getPlayersboard();
  EXPECT_EQ(0, playerbsboard.getSizeOfEdges());
  EXPECT_EQ(board.getNumofemptyhexgons(), board.getSizeOfVertices() - 6);
  ASSERT_TRUE(hexboardgame.setMove(playerb, 2, 2));
  playerbsboard = playerb.getPlayersboard();
  EXPECT_EQ(1, playerbsboard.getSizeOfEdges());
  EXPECT_EQ(board.getNumofemptyhexgons(), board.getSizeOfVertices() - 7);
  ASSERT_TRUE(hexboardgame.setMove(playerb, 3, 2));
  playerbsboard = playerb.getPlayersboard();
  EXPECT_EQ(2, playerbsboard.getSizeOfEdges());
  EXPECT_EQ(board.getNumofemptyhexgons(), board.getSizeOfVertices() - 8);
  ASSERT_TRUE(hexboardgame.setMove(playerb, 4, 2));
  playerbsboard = playerb.getPlayersboard();
  EXPECT_EQ(3, playerbsboard.getSizeOfEdges());
  EXPECT_EQ(board.getNumofemptyhexgons(), board.getSizeOfVertices() - 9);
  ASSERT_TRUE(hexboardgame.setMove(playerb, 2, 5));
  EXPECT_EQ(board.getNumofemptyhexgons(), board.getSizeOfVertices() - 10);
  ASSERT_TRUE(hexboardgame.setMove(playerb, 3, 5));
  EXPECT_EQ(board.getNumofemptyhexgons(), board.getSizeOfVertices() - 11);
  playerbsboard = playerb.getPlayersboard();
  EXPECT_EQ(4, playerbsboard.getSizeOfEdges());

  MinSpanTreeAlgo<hexgonValKind, int> mstalgob(playerbsboard);
  MinSpanTreeAlgo<hexgonValKind, int>::UnionFind unionfindb(mstalgob);
  mstalgo.calculate(unionfindb);
  Graph<hexgonValKind, int> msttreeb = mstalgob.getMsttree();
  EXPECT_EQ(4, msttreeb.getSizeOfEdges());
  vector<vector<int> > subgraphsb = msttreeb.getAllSubGraphs();
  EXPECT_EQ(2, subgraphsb.size());
}
开发者ID:renewang,项目名称:HexGame,代码行数:69,代码来源:HexBoard_test.cpp


注:本文中的Graph类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。