Exemplo n.º 1
0
/////////////////////////////////////////////////
// Trawling the web for emerging communities
// graph, left points to right
TTrawling::TTrawling(const PNGraph& Graph, const int& MinSupport) : MinSup(MinSupport) {
  TIntH ItemCntH;
  for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
    IAssert(NI.GetOutDeg()==0 || NI.GetInDeg()==0); // edges only point from left to right
    if (NI.GetOutDeg()==0) { continue; }
    for (int e = 0; e < NI.GetOutDeg(); e++) {
      ItemCntH.AddDat(NI.GetOutNId(e)) += 1;
    }
  }

  TIntV RightV;
  for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
    IAssert(NI.GetOutDeg()==0 || NI.GetInDeg()==0); // edges only point from left to right
    if (NI.GetOutDeg()==0) { continue; }
    RightV.Clr(false);
    for (int e = 0; e < NI.GetOutDeg(); e++) {
      const int itm = NI.GetOutNId(e);
      // only include items that already are above minimum support
      if (ItemCntH.GetDat(itm) >= MinSup) {
        RightV.Add(itm); }
    }
    if (! RightV.Empty()) {
      NIdSetH.AddDat(NI.GetId(), RightV);
    }
  }
  //
  for (int n = 0; n < NIdSetH.Len(); n++) {
    const TIntV& Set = NIdSetH[n];
    for (int s = 0; s < Set.Len(); s++) {
      SetNIdH.AddDat(Set[s]).Add(n);
    }
  }
}
Exemplo n.º 2
0
void OnlyD3CEdgesNoBack(PNGraph& dir_graph, PNGraph& d3c_graph) {
    // Add all of the nodes into the new graph
    for (TNGraph::TNodeI node = dir_graph->BegNI(); node < dir_graph->EndNI();
         node++) {
        int curr_node = node.GetId();
        d3c_graph->AddNode(curr_node);
    }
    for (TNGraph::TNodeI node = dir_graph->BegNI(); node < dir_graph->EndNI();
         node++) {
        int curr_node = node.GetId();
        auto curr_node_it = dir_graph->GetNI(curr_node);
        for (int out_edge = 0; out_edge < curr_node_it.GetOutDeg(); ++out_edge) {
            int out_node = curr_node_it.GetOutNId(out_edge);
            for (int in_edge = 0; in_edge < curr_node_it.GetInDeg(); ++in_edge) {
                int in_node = curr_node_it.GetInNId(in_edge);
                if (dir_graph->IsEdge(out_node, in_node) && out_node != in_node) {
		    if (!d3c_graph->IsEdge(in_node, out_node) &&
			!d3c_graph->IsEdge(curr_node, in_node) &&
			!d3c_graph->IsEdge(out_node, curr_node)) {
			if (!d3c_graph->IsEdge(out_node, in_node)) { d3c_graph->AddEdge(out_node, in_node); }
			if (!d3c_graph->IsEdge(in_node, curr_node)) { d3c_graph->AddEdge(in_node, curr_node); }
			if (!d3c_graph->IsEdge(curr_node, out_node)) { d3c_graph->AddEdge(curr_node, out_node); }
		    }
                }
            }
        }
    }
}
Exemplo n.º 3
0
void OnlyD3CEdges(PNGraph& dir_graph, PNGraph& d3c_graph, bool recip_edges) {
    // Add all of the nodes into the new graph
    for (TNGraph::TNodeI node = dir_graph->BegNI(); node < dir_graph->EndNI();
         node++) {
        int curr_node = node.GetId();
        d3c_graph->AddNode(curr_node);
    }
    for (TNGraph::TNodeI node = dir_graph->BegNI(); node < dir_graph->EndNI();
         node++) {
        int curr_node = node.GetId();
        auto curr_node_it = dir_graph->GetNI(curr_node);
        for (int out_edge = 0; out_edge < curr_node_it.GetOutDeg(); ++out_edge) {
            int out_node = curr_node_it.GetOutNId(out_edge);
            for (int in_edge = 0; in_edge < curr_node_it.GetInDeg(); ++in_edge) {
                int in_node = curr_node_it.GetInNId(in_edge);
		if (out_node == in_node && !recip_edges) { continue; }
                if (dir_graph->IsEdge(out_node, in_node) || recip_edges) {
                    if (!d3c_graph->IsEdge(out_node, in_node)) {
			d3c_graph->AddEdge(out_node, in_node);
		    }
                    if (!d3c_graph->IsEdge(in_node, curr_node)) {
			d3c_graph->AddEdge(in_node, curr_node);
		    }
                    if (!d3c_graph->IsEdge(curr_node, out_node)) {
			d3c_graph->AddEdge(curr_node, out_node);
		    }
                }
            }
        }
    }
#ifdef _VERBOSE_
    std::cout << "Original graph edge count: " << dir_graph->GetEdges() << std::endl
	      << "D3C graph edge count: " << d3c_graph->GetEdges() << std::endl;
#endif
}
Exemplo n.º 4
0
void GetSngVec(const PNGraph& Graph, TFltV& LeftSV, TFltV& RightSV) {
  const int Nodes = Graph->GetNodes();
  TFltVV LSingV, RSingV;
  TFltV SngValV;
  if (Nodes < 500) {
    // perform full SVD
    TFltVV AdjMtx(Nodes+1, Nodes+1);
    TIntH NodeIdH;
    // create adjecency matrix
    for (TNGraph::TNodeI NodeI = Graph->BegNI(); NodeI < Graph->EndNI(); NodeI++) {
      NodeIdH.AddKey(NodeI.GetId()); }
    for (TNGraph::TNodeI NodeI = Graph->BegNI(); NodeI < Graph->EndNI(); NodeI++) {
      const int NodeId = NodeIdH.GetKeyId(NodeI.GetId()) + 1;
      for (int e = 0; e < NodeI.GetOutDeg(); e++) {
        const int DstNId = NodeIdH.GetKeyId(NodeI.GetOutNId(e)) + 1;  // no self edges
        if (NodeId != DstNId) AdjMtx.At(NodeId, DstNId) = 1;
      }
    }
    try { // can fail to converge but results seem to be good
      TSvd::Svd1Based(AdjMtx, LSingV, SngValV, RSingV); }
    catch(...) {
      printf("\n***No SVD convergence: G(%d, %d)\n", Nodes, Graph->GetEdges()); }
  } else { // Lanczos
    TNGraphMtx GraphMtx(Graph);
    TSparseSVD::LanczosSVD(GraphMtx, 1, 8, ssotFull, SngValV, LSingV, RSingV);
  }
  TFlt MxSngVal = TFlt::Mn;
  int ValN = 0;
  for (int i = 0; i < SngValV.Len(); i++) {
    if (MxSngVal < SngValV[i]) { MxSngVal = SngValV[i]; ValN = i; } }
  LSingV.GetCol(ValN, LeftSV);
  RSingV.GetCol(ValN, RightSV);
  IsAllValVNeg(LeftSV, true);
  IsAllValVNeg(RightSV, true);
}
Exemplo n.º 5
0
double DirectedModularity(PNGraph& graph, std::vector<int>& communities) {
    if (graph->GetNodes() != communities.size()) {
        throw std::logic_error("Number of nodes does not match community size.");
    }

    int num_edges = graph->GetEdges();
    double score = 0.0;

    int num_unique = 10;
    std::map<int, double> outdeg_sums;
    std::map<int, double> indeg_sums;

    for (TNGraph::TNodeI node = graph->BegNI(); node < graph->EndNI(); node++) {
        int comm = communities[node.GetId()];
        outdeg_sums[comm] += node.GetOutDeg();
        indeg_sums[comm] += node.GetInDeg();
    }

    for (auto& kv : outdeg_sums) {
        score -= (kv.second / num_edges) * indeg_sums[kv.first];
    }

    for (TNGraph::TNodeI node = graph->BegNI(); node < graph->EndNI(); node++) {
        int node_ID = node.GetId();
        for (int e = 0; e < node.GetOutDeg(); ++e) {
            int nbr = node.GetOutNId(e);
            if (communities[node_ID] == communities[nbr]) {
                score += 1.0;
            }
        }
    }  

    return score / num_edges;
}
Exemplo n.º 6
0
//GraphSON Node Formatting
std::string GraphSONNodes(const PNGraph & graph){
	std::string nodes;
	for (PNGraph::TObj::TNodeI NI = graph->BegNI(); NI < graph->EndNI(); ) {
		nodes.append("{ \"id\": \"");
		nodes.append(Helper::intToString(NI.GetId()));
		nodes.append("\" }");
		if (NI++ == graph->EndNI())
			nodes.append(" ],\n");
		else
			nodes.append(",\n");
	}
	return nodes;
}
Exemplo n.º 7
0
void TGraphKey::TakeSig(const PNGraph& Graph, const int& MnSvdGraph, const int& MxSvdGraph) {
  const int Edges = Graph->GetEdges();
  Nodes = Graph->GetNodes();
  VariantId = 0;
  SigV.Gen(2+Nodes, 0);
  // degree sequence
  TIntPrV DegV(Nodes, 0);
  for (TNGraph::TNodeI NodeI = Graph->BegNI(); NodeI < Graph->EndNI(); NodeI++) {
    DegV.Add(TIntPr(NodeI.GetInDeg(), NodeI.GetOutDeg()));
  }
  DegV.Sort(false);
  SigV.Add(TFlt(Nodes));
  SigV.Add(TFlt(Edges));
  for (int i = 0; i < DegV.Len(); i++) {
    SigV.Add(DegV[i].Val1());
    SigV.Add(DegV[i].Val2());
  }
  // singular values signature
  //   it turns out that it is cheaper to do brute force isomorphism
  //   checking than to calculate SVD and then check isomorphism
  if (Nodes >= MnSvdGraph && Nodes < MxSvdGraph) {
    // perform full SVD
    TFltVV AdjMtx(Nodes+1, Nodes+1);
    TFltV SngValV;
    TFltVV LSingV, RSingV;
    TIntH NodeIdH;
    // create adjecency matrix
    for (TNGraph::TNodeI NodeI = Graph->BegNI(); NodeI < Graph->EndNI(); NodeI++) {
      NodeIdH.AddKey(NodeI.GetId());
    }
    for (TNGraph::TNodeI NodeI = Graph->BegNI(); NodeI < Graph->EndNI(); NodeI++) {
      const int NodeId = NodeIdH.GetKeyId(NodeI.GetId()) + 1;
      for (int e = 0; e < NodeI.GetOutDeg(); e++) {
        const int DstNId = NodeIdH.GetKeyId(NodeI.GetOutNId(e)) + 1;  // no self edges
        if (NodeId != DstNId) AdjMtx.At(NodeId, DstNId) = 1;
      }
    }
    try { // can fail to converge but results seem to be good
      TSvd::Svd(AdjMtx, LSingV, SngValV, RSingV);
    } catch(...) {
      printf("\n***No SVD convergence: G(%d, %d): SngValV.Len():%d\n", Nodes(), Graph->GetEdges(), SngValV.Len());
    }
    // round singular values
    SngValV.Sort(false);
    for (int i = 0; i < SngValV.Len(); i++) {
      SigV.Add(TMath::Round(SngValV[i], RoundTo));
    }
  }
  //printf("SIG:\n");  for (int i = 0; i < SigV.Len(); i++) { printf("\t%f\n", SigV[i]); }
  SigV.Pack();
}
Exemplo n.º 8
0
void GetSngVals(const PNGraph& Graph, const int& SngVals, TFltV& SngValV) {
  const int Nodes = Graph->GetNodes();
  IAssert(SngVals > 0);
  if (Nodes < 100) {
    // perform full SVD
    TFltVV AdjMtx(Nodes+1, Nodes+1);
    TFltVV LSingV, RSingV;
    TIntH NodeIdH;
    // create adjecency matrix
    for (TNGraph::TNodeI NodeI = Graph->BegNI(); NodeI < Graph->EndNI(); NodeI++) {
      NodeIdH.AddKey(NodeI.GetId()); }
    for (TNGraph::TNodeI NodeI = Graph->BegNI(); NodeI < Graph->EndNI(); NodeI++) {
      const int NodeId = NodeIdH.GetKeyId(NodeI.GetId()) + 1;
      for (int e = 0; e < NodeI.GetOutDeg(); e++) {
        const int DstNId = NodeIdH.GetKeyId(NodeI.GetOutNId(e)) + 1;  // no self edges
        if (NodeId != DstNId) AdjMtx.At(NodeId, DstNId) = 1;
      }
    }
    try { // can fail to converge but results seem to be good
      TSvd::Svd1Based(AdjMtx, LSingV, SngValV, RSingV); }
    catch(...) {
      printf("\n***No SVD convergence: G(%d, %d)\n", Nodes, Graph->GetEdges()); }
  } else {
    // Lanczos
    TNGraphMtx GraphMtx(Graph);
    int CalcVals = int(2*SngVals);
    //if (CalcVals > Nodes) { CalcVals = int(2*Nodes); }
    //if (CalcVals > Nodes) { CalcVals = Nodes; }
    //while (SngValV.Len() < SngVals && CalcVals < 10*SngVals) {
    try {
      if (SngVals > 4) { 
        TSparseSVD::SimpleLanczosSVD(GraphMtx, 2*SngVals, SngValV, false); }
      else { TFltVV LSingV, RSingV;  // this is much more precise, but also much slower
        TSparseSVD::LanczosSVD(GraphMtx, SngVals, 3*SngVals, ssotFull, SngValV, LSingV, RSingV); }
    }
    catch(...) {
      printf("\n  ***EXCEPTION:  TRIED %d GOT %d values** \n", 2*SngVals, SngValV.Len()); }
    if (SngValV.Len() < SngVals) {
      printf("  ***TRIED %d GOT %d values** \n", CalcVals, SngValV.Len()); }
    //  CalcVals += SngVals;
    //}
  }
  SngValV.Sort(false);
  //if (SngValV.Len() > SngVals) {
  //  SngValV.Del(SngVals, SngValV.Len()-1); }
  //else {
  //  while (SngValV.Len() < SngVals) SngValV.Add(1e-6); }
  //IAssert(SngValV.Len() == SngVals);
}
Exemplo n.º 9
0
// renumbers nodes
void TGraphKey::TakeGraph(const PNGraph& Graph) {
  TIntH NodeIdH;
  for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
    NodeIdH.AddKey(NI.GetId()); }
  Nodes = Graph->GetNodes();
  EdgeV.Gen(Nodes, 0);
  for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
    const int NewNId = NodeIdH.GetKeyId(NI.GetId());
    for (int i = 0; i < NI.GetOutDeg(); i++) {
      EdgeV.Add(TIntPr(NewNId, NodeIdH.GetKeyId(NI.GetOutNId(i))));
    }
  }
  EdgeV.Sort(true);
  EdgeV.Pack();
}
Exemplo n.º 10
0
// Save directed, undirected and multi-graphs in GraphVizp .DOT format
void IOGViz() {
  
  const int NNodes = 500;
  const int NEdges = 2000;
  
  const char *FName1 = "demo1.dot.dat", *FName2 = "demo2.dot.dat";
  const char *Desc = "Randomly generated GgraphVizp for input/output.";
  
  PNGraph GOut;     // Can be PNEGraph or PUNGraph
  GOut = GenRndGnm<PNGraph>(NNodes, NEdges);
  
  SaveGViz(GOut, FName1);
  
  // Output node IDs as numbers
  TIntStrH NIdLabelH;
  
  // Generate labels for random graph
  for (TNGraph::TNodeI NI = GOut->BegNI(); NI < GOut->EndNI(); NI++) {
    NIdLabelH.AddDat(NI.GetId(), TStr::Fmt("Node%d", NI.GetId()));
    
  }
  SaveGViz(GOut, FName2, Desc, NIdLabelH);
  
  PrintGStats("IOGViz - In", GOut);
}
Exemplo n.º 11
0
//GDF Node Formatting
std::string GDFNodes(const PNGraph & graph){
	std::string nodes;
	for (PNGraph::TObj::TNodeI NI = graph->BegNI(); NI < graph->EndNI(); NI++){
		nodes.append(Helper::intToString(NI.GetId()));
		nodes.append("\n");
	}
	return nodes;
}
Exemplo n.º 12
0
void GetSngVec(const PNGraph& Graph, const int& SngVecs, TFltV& SngValV, TVec<TFltV>& LeftSV, TVec<TFltV>& RightSV) {
  const int Nodes = Graph->GetNodes();
  SngValV.Clr();
  LeftSV.Clr();
  RightSV.Clr();
  TFltVV LSingV, RSingV;
  if (Nodes < 100) {
    // perform full SVD
    TFltVV AdjMtx(Nodes+1, Nodes+1);
    TIntH NodeIdH;
    // create adjecency matrix (1-based)
    for (TNGraph::TNodeI NodeI = Graph->BegNI(); NodeI < Graph->EndNI(); NodeI++) {
      NodeIdH.AddKey(NodeI.GetId()); }
    for (TNGraph::TNodeI NodeI = Graph->BegNI(); NodeI < Graph->EndNI(); NodeI++) {
      const int NodeId = NodeIdH.GetKeyId(NodeI.GetId())+1;
      for (int e = 0; e < NodeI.GetOutDeg(); e++) {
        const int DstNId = NodeIdH.GetKeyId(NodeI.GetOutNId(e))+1;  // no self edges
        if (NodeId != DstNId) AdjMtx.At(NodeId, DstNId) = 1;
      }
    }
    try { // can fail to converge but results seem to be good
      TSvd::Svd1Based(AdjMtx, LSingV, SngValV, RSingV);
    } catch(...) {
      printf("\n***No SVD convergence: G(%d, %d)\n", Nodes, Graph->GetEdges()); 
    }
  } else { // Lanczos
    TNGraphMtx GraphMtx(Graph);
    TSparseSVD::LanczosSVD(GraphMtx, SngVecs, 2*SngVecs, ssotFull, SngValV, LSingV, RSingV);
    //TGAlg::SaveFullMtx(Graph, "adj_mtx.txt");
    //TLAMisc::DumpTFltVVMjrSubMtrx(LSingV, LSingV.GetRows(), LSingV.GetCols(), "LSingV2.txt"); // save MTX
  }
  TFltIntPrV SngValIdV;
  for (int i = 0; i < SngValV.Len(); i++) {
    SngValIdV.Add(TFltIntPr(SngValV[i], i)); 
  }
  SngValIdV.Sort(false);
  SngValV.Sort(false);
  for (int v = 0; v < SngValIdV.Len(); v++) { 
    LeftSV.Add();
    LSingV.GetCol(SngValIdV[v].Val2, LeftSV.Last());
    RightSV.Add();
    RSingV.GetCol(SngValIdV[v].Val2, RightSV.Last());
  }
  IsAllValVNeg(LeftSV[0], true);
  IsAllValVNeg(RightSV[0], true);
}
Exemplo n.º 13
0
/////////////////////////////////////////////////
// TGraphEnumUtils implementation
void TGraphEnumUtils::GetNormalizedMap(const PNGraph &G, THash<TInt,TInt> &map) {
	int nId=0;
	for(TNGraph::TNodeI it=G->BegNI(); it<G->EndNI(); it++) {
		//printf("%d -> %d\n", it.GetId(), nId);
		map.AddDat(it.GetId(), nId);
		nId++;
	}
}
Exemplo n.º 14
0
void UndirCopy(PNGraph& dir_graph, PUNGraph& undir_graph) {
    // Add all of the nodes into the new graph
    for (TNGraph::TNodeI node = dir_graph->BegNI(); node < dir_graph->EndNI();
         node++) {
        int curr_node = node.GetId();
        undir_graph->AddNode(curr_node);
    }
    for (TNGraph::TNodeI node = dir_graph->BegNI(); node < dir_graph->EndNI();
         node++) {
        int curr_node = node.GetId();
        for (int e = 0; e < node.GetOutDeg(); ++e) {
            int nbr_node = node.GetOutNId(e);
            if (!undir_graph->IsEdge(curr_node, nbr_node)) {
                undir_graph->AddEdge(curr_node, nbr_node);
            }
        }
    }
}
Exemplo n.º 15
0
void gdf(PNGraph Graph){
        std::ofstream graph;
        graph.open("graph.gdf");
        graph << "nodedef>name VARCHAR\n";

        for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++)
                graph << NI.GetId() << ",\n";
        graph << "edgedef>node1 VARCHAR,node2 VARCHAR\n";
        for (TNGraph::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++)
                graph << EI.GetSrcNId() << "," << EI.GetDstNId() << "\n";
        graph.close();
}
Exemplo n.º 16
0
void analyzeSimNetProps(TStr messGraph, TStr netGraph) {
	// Make graphs
	PNGraph eGraph = TSnap::LoadEdgeListStr<PNGraph>(netGraph, 0, 1);
	PNGraph mGraph = TSnap::LoadEdgeListStr<PNGraph>(messGraph, 0, 1);
        PNGraph randGraph = TSnap::GenRndGnm<PNGraph>(mGraph->GetNodes(), mGraph->GetEdges(), true, TInt::Rnd);

	// Induce network graph from the entire network based on message graph
	TIntV NIdV;
	for (TNGraph::TNodeI NI = mGraph->BegNI(); NI < mGraph->EndNI(); NI++)
		NIdV.AddUnique(NI.GetId());
	PNGraph indGraph = TSnap::GetSubGraph<PNGraph>(eGraph, NIdV);

	//printf("%s:: ", messGraph.CStr()); printf("nodes %d; ", indGraph->GetNodes());
	//printf("induced edges %d, random edges %d\n", indGraph->GetEdges(), randGraph->GetEdges());
	printf("%d\t%d\t%d\n", indGraph->GetNodes(), indGraph->GetEdges(), mGraph->GetEdges());
}
Exemplo n.º 17
0
// network cascade: add spurious edges
// for more details see "Correcting for Missing Data in Information Cascades" by E. Sadikov, M. Medina, J. Leskovec, H. Garcia-Molina. WSDM, 2011
PNGraph AddSpuriousEdges(const PUNGraph& Graph, const PNGraph& Casc, TIntH NIdTmH) {
  TIntPrV EdgeV;
  for (TNGraph::TNodeI NI = Casc->BegNI(); NI < Casc->EndNI(); NI++) {
    TUNGraph::TNodeI GNI = Graph->GetNI(NI.GetId());
    const int Tm = NIdTmH.GetDat(NI.GetId());
    for (int i=0,j=0; i < GNI.GetOutDeg(); i++) {
      const int Dst = GNI.GetOutNId(i);
      if (NIdTmH.IsKey(Dst) && Tm<NIdTmH.GetDat(Dst) && ! NI.IsNbhNId(Dst)) {
        EdgeV.Add(TIntPr(GNI.GetId(), Dst)); }
    }
  }
  PNGraph NetCasc = TNGraph::New();
  *NetCasc = *Casc;
  for (int e = 0; e < EdgeV.Len(); e++) {
    NetCasc->AddEdge(EdgeV[e].Val1, EdgeV[e].Val2); }
  return NetCasc;
}
Exemplo n.º 18
0
void graphson(PNGraph Graph){
        std::ofstream graph;
        graph.open("graph.json");
        graph << "{\n";
        graph << "    \"graph\": {\n";
        graph << "        " << "\"mode\": \"NORMAL\", \n";
        graph << "        " << "\"vertices\": [\n";
        int i = 0;
        for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
                i++;
                graph << "            " << "{\n";
                graph << "                " << "\"_id\": \"" << NI.GetId() << "\",\n";
                graph << "                " << "\"_type\": \"vertex\"\n";
                if (i == Graph->GetNodes()) {
                        graph << "            " << "}\n";
                } else {
                        graph << "            " << "},\n";
                }
        }


        graph << "        " << "],\n";
        graph << "        " << "\"edges\": [\n";

        i = 0;
        printf("Edges: %d", Graph->GetEdges());
        for (TNGraph::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) {
                graph << "            " << "{\n"
                      << "                " << "\"_id\": \"" << i++ << "\",\n"
                      << "                " << "\"_type\": \"edge\"\n"
                      << "                " << "\"_outV\": \"" << EI.GetSrcNId() << "\"\n"
                      << "                " << "\"_inV\": \""<< EI.GetDstNId() << "\"\n";

                if (i == Graph->GetEdges())
                        graph << "            " << "}\n";
                else
                        graph << "            " << "},\n";

        }
        graph << "        " << "]\n";
        graph << "    " << "}\n";
        graph << "}\n";

        graph.close();
}
Exemplo n.º 19
0
/// Rewire the network. Keeps node degrees as is but randomly rewires the edges.
/// Use this function to generate a random graph with the same degree sequence
/// as the OrigGraph.
/// See:  On the uniform generation of random graphs with prescribed degree
/// sequences by R. Milo, N. Kashtan, S. Itzkovitz, M. E. J. Newman, U. Alon.
/// URL: http://arxiv.org/abs/cond-mat/0312028
PNGraph GenRewire(const PNGraph& OrigGraph, const int& NSwitch, TRnd& Rnd) {
  const int Nodes = OrigGraph->GetNodes();
  const int Edges = OrigGraph->GetEdges();
  PNGraph GraphPt = TNGraph::New();
  TNGraph& Graph = *GraphPt;
  Graph.Reserve(Nodes, -1);
  TExeTm ExeTm;
  // generate a graph that satisfies the constraints
  printf("Randomizing edges (%d, %d)...\n", Nodes, Edges);
  TIntPrSet EdgeSet(Edges);
  for (TNGraph::TNodeI NI = OrigGraph->BegNI(); NI < OrigGraph->EndNI(); NI++) {
    const int NId = NI.GetId();
    for (int e = 0; e < NI.GetOutDeg(); e++) {
      EdgeSet.AddKey(TIntPr(NId, NI.GetOutNId(e))); }
    Graph.AddNode(NI);
  }
  // edge switching
  uint skip=0;
  for (uint swps = 0; swps < 2*uint(Edges)*uint(NSwitch); swps++) {
    const int keyId1 = EdgeSet.GetRndKeyId(Rnd);
    const int keyId2 = EdgeSet.GetRndKeyId(Rnd);
    if (keyId1 == keyId2) { skip++; continue; }
    const TIntPr& E1 = EdgeSet[keyId1];
    const TIntPr& E2 = EdgeSet[keyId2];
    TIntPr NewE1(E1.Val1, E2.Val1), NewE2(E1.Val2, E2.Val2);
    if (NewE1.Val1!=NewE2.Val1 && NewE1.Val2!=NewE2.Val1 && NewE1.Val2!=NewE2.Val1 && NewE1.Val2!=NewE2.Val2 && ! EdgeSet.IsKey(NewE1) && ! EdgeSet.IsKey(NewE2)) {
      EdgeSet.DelKeyId(keyId1);  EdgeSet.DelKeyId(keyId2);
      EdgeSet.AddKey(TIntPr(NewE1));
      EdgeSet.AddKey(TIntPr(NewE2));
    } else { skip++; }
    if (swps % Edges == 0) {
      printf("\r  %uk/%uk: %uk skip [%s]", swps/1000u, 2*uint(Edges)*uint(NSwitch)/1000u, skip/1000u, ExeTm.GetStr());
      if (ExeTm.GetSecs() > 2*3600) { printf(" *** Time limit!\n"); break; } // time limit 2 hours
    }
  }
  printf("\r  total %uk switchings attempted, %uk skiped  [%s]\n", 2*uint(Edges)*uint(NSwitch)/1000u, skip/1000u, ExeTm.GetStr());
  for (int e = 0; e < EdgeSet.Len(); e++) {
    Graph.AddEdge(EdgeSet[e].Val1, EdgeSet[e].Val2); }
  return GraphPt;
}
Exemplo n.º 20
0
int main(int argc, char* argv[]) {
  // create a graph and save it
  { PNGraph Graph = TNGraph::New();
  for (int i = 0; i < 10; i++) {
    Graph->AddNode(i); }
  for (int i = 0; i < 10; i++) {
    Graph->AddEdge(i, TInt::Rnd.GetUniDevInt(10)); }
  TSnap::SaveEdgeList(Graph, "graph.txt", "Edge list format"); }
  // load a graph
  PNGraph Graph;
  Graph = TSnap::LoadEdgeList<PNGraph>("graph.txt", 0, 1);
  // traverse nodes
  for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
    printf("NodeId: %d, InDegree: %d, OutDegree: %d\n", NI.GetId(), NI.GetInDeg(), NI.GetOutDeg());
    printf("OutNodes: ");
    for (int e = 0; e < NI.GetOutDeg(); e++) { printf("  %d", NI.GetOutNId(e)); }
    printf("\nInNodes: ");
    for (int e = 0; e < NI.GetInDeg(); e++) { printf("  %d", NI.GetInNId(e)); }
    printf("\n\n");
  }
  // graph statistic
  TSnap::PrintInfo(Graph, "Graph info");
  PNGraph MxWcc = TSnap::GetMxWcc(Graph);
  TSnap::PrintInfo(MxWcc, "Largest Weakly connected component");
  // random graph
  PNGraph RndGraph = TSnap::GenRndGnm<PNGraph>(100, 1000);
  TGStat GraphStat(RndGraph, TSecTm(1), TGStat::AllStat(), "Gnm graph");
  GraphStat.PlotAll("RndGraph", "Random graph on 1000 nodes");
  // Forest Fire graph
  { TFfGGen ForestFire(false, 1, 0.35, 0.30, 1.0, 0.0, 0.0);
  ForestFire.GenGraph(100);
  PNGraph FfGraph = ForestFire.GetGraph(); }
  // network
  TPt<TNodeEDatNet<TStr, TStr> > Net = TNodeEDatNet<TStr, TStr>::New();
  Net->AddNode(0, "zero");
  Net->AddNode(1, "one");
  Net->AddEdge(0, 1, "zero to one");
  return 0;
}
Exemplo n.º 21
0
void graphMl(PNGraph Graph){
        std::ofstream graphml;
        graphml.open("graph.graphml");

        graphml << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
        graphml << "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\"\n";
        graphml << "    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
        graphml << "    xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns\n";
        graphml << "     http://graphml.graphdrawing.org/xmlns/1.1/graphml.xsd\">\n";
        graphml << "  <graph id=\"G\" edgedefault=\"directed\">\n";

        for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++)
                graphml << "    <node id=\"" << NI.GetId() << "\"/>\n";
        int i = 1;
        for (TNGraph::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) {
                graphml << "    <edge id=\"e" << i++ << "\" directed=\"true"
                        << "\" source=\""     << EI.GetSrcNId()
                        << "\" target=\""     << EI.GetDstNId() << "\"/>\n";
        }
        graphml << "  </graph>\n";
        graphml << "</graphml>\n";
        graphml.close();
}
Exemplo n.º 22
0
void gexf(PNGraph Graph){
        std::ofstream graph;
        graph.open("graph.gexf");
        graph << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
              << "<gexf xmlns=\"http://www.gexf.net/1.2draft\" version=\"1.2\">\n"
              << "  <graph mode=\"static\" defaultedgetype=\"directed\">\n"
              << "    <nodes>\n";
        for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++)
                graph << "      <node id=\"" << NI.GetId() << "\"/>\n";

        graph << "    </nodes>\n";
        graph << "    <edges>\n";
        int i = 1;
        for (TNGraph::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++)
                graph << "      <edge id=\"e" << i++
                      << "\" directed=\"true" << "\" source=\""
                      << EI.GetSrcNId()       << "\" target=\""
                      << EI.GetDstNId()      << "\"/>\n";

        graph << "    </edges>\n"
              << "  </graph>\n"
              << "</gexf>\n";
        graph.close();
}
Exemplo n.º 23
0
// Test node, edge creation
void ManipulateNodesEdges() {
  int NNodes = 10000;
  int NEdges = 100000;
  const char *FName = "demo.graph.dat";

  PNGraph Graph;
  PNGraph Graph1;
  PNGraph Graph2;
  int i;
  int n;
  int NCount;
  int ECount1;
  int ECount2;
  int x,y;
  bool t;

  Graph = TNGraph::New();
  t = Graph->Empty();

  // create the nodes
  for (i = 0; i < NNodes; i++) {
    Graph->AddNode(i);
  }
  t = Graph->Empty();
  n = Graph->GetNodes();

  // create random edges
  NCount = NEdges;
  while (NCount > 0) {
    x = rand() % NNodes;
    y = rand() % NNodes;
    // Graph->GetEdges() is not correct for the loops (x == y),
    // skip the loops in this test
    if (x != y  &&  !Graph->IsEdge(x,y)) {
      n = Graph->AddEdge(x, y);
      NCount--;
    }
  }
  PrintGStats("ManipulateNodesEdges:Graph",Graph);

  // get all the nodes
  NCount = 0;
  for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
    NCount++;
  }

  // get all the edges for all the nodes
  ECount1 = 0;
  for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
    for (int e = 0; e < NI.GetOutDeg(); e++) {
      ECount1++;
    }
  }

  // get all the edges directly
  ECount2 = 0;
  for (TNGraph::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) {
    ECount2++;
  }
  printf("ManipulateNodesEdges:Graph, nodes %d, edges1 %d, edges2 %d\n",
      NCount, ECount1, ECount2);

  // assignment
  Graph1 = TNGraph::New();
  *Graph1 = *Graph;
  PrintGStats("ManipulateNodesEdges:Graph1",Graph1);

  // save the graph
  {
    TFOut FOut(FName);
    Graph->Save(FOut);
    FOut.Flush();
  }

  // load the graph
  {
    TFIn FIn(FName);
    Graph2 = TNGraph::Load(FIn);
  }
  PrintGStats("ManipulateNodesEdges:Graph2",Graph2);

  // remove all the nodes and edges
  for (i = 0; i < NNodes; i++) {
    n = Graph->GetRndNId();
    Graph->DelNode(n);
  }

  PrintGStats("ManipulateNodesEdges:Graph",Graph);

  Graph1->Clr();
  PrintGStats("ManipulateNodesEdges:Graph1",Graph1);
}
Exemplo n.º 24
0
int main(int argc, char* argv[]) {
 Env = TEnv(argc, argv, TNotify::StdNotify);
 Env.PrepArgs(TStr::Fmt("Inverse PageRank. Build: %s, %s. Time: %s", __TIME__, __DATE__, TExeTm::GetCurTm()));
 TExeTm ExeTm;
 Try
	const TStr Iput = Env.GetIfArgPrefixStr("-i:", "Input.txt", "Input File" );
	const TStr Oput = Env.GetIfArgPrefixStr("-o:", "Output.txt", "Output File");
	FILE* fpI = fopen(Iput.CStr(), "r");
	FILE* fpO = fopen(Oput.CStr(), "w");
	

	const double C    = 0.85;
	const int MaxIter = 50;
	const double Eps  = 1e-9;

	PNGraph Graph = TSnap::LoadEdgeList< PNGraph > (Iput);
	fprintf(fpO, "\nNodes: %d, Edges: %d\n\n", Graph->GetNodes(), Graph->GetEdges());
	const int NNodes = Graph->GetNodes();
	const double OneOver = (double) 1.0 / (double) NNodes;
	
	TIntFltH PRankH;
	PRankH.Gen(NNodes);
	
	for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++)
    	PRankH.AddDat(NI.GetId(), OneOver);
    
    TFltV TmpV(NNodes);
	for (int iter = 0; iter < MaxIter; iter++) {
    	int j = 0;
    	for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++, j++) {
			TmpV[j] = 0;
	        for (int e = 0; e < NI.GetOutDeg(); e++) {
				const int OutNId = NI.GetOutNId(e);
				const int InDeg = Graph->GetNI(OutNId).GetInDeg();
				if (InDeg > 0) 
					TmpV[j] += PRankH.GetDat(OutNId) / InDeg;
			}
			TmpV[j] =  C * TmpV[j]; 
    	}
    	
	for (int i = 0; i < PRankH.Len(); i++)
		PRankH[i] = TmpV[i];
    	/*
    	double diff = 0, sum = 0, NewVal;
		for (int i = 0; i < TmpV.Len(); i++)
			sum += TmpV[i];

		const double Leaked = (double) (1.0 - sum) / (double) NNodes;
		for (int i = 0; i < PRankH.Len(); i++) {
			NewVal = TmpV[i] + Leaked;
			diff += fabs(NewVal - PRankH[i]);
			PRankH[i] = NewVal;
		}
		if (diff < Eps)
			break;
		*/
	}
	
	fprintf(fpO, "Node ID\t\tInverse PageRank\n");
	for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++){
		int Id = NI.GetId();
		double ipr = PRankH.GetDat(Id);
		fprintf(fpO, "%d\t\t\t%.5lf\n", Id, ipr);
	}
 Catch
	printf("\nRun Time: %s (%s)\n", ExeTm.GetTmStr(), TSecTm::GetCurTm().GetTmStr().CStr());
	
	return 0;
}
Exemplo n.º 25
0
int main(int argc, char* argv[]) {
  
  setbuf(stdout, NULL); // disables the buffer so that print statements are not buffered and display immediately (?)
  
  Env = TEnv(argc, argv, TNotify::StdNotify);
  Env.PrepArgs(TStr::Fmt("Graph connectivity. build: %s, %s. Time: %s", __TIME__, __DATE__, TExeTm::GetCurTm()));
  
  TExeTm ExeTm;
  
  Try
  
  const TStr InFNm = Env.GetIfArgPrefixStr("-i:", "", "input network");
  const TStr SubsetNIdVFNm = Env.GetIfArgPrefixStr("-j:", "", "subset of nodes");
  const TStr OutFNm = Env.GetIfArgPrefixStr("-o:", "", "output prefix (filename extensions added)");
  const TStr BseFNm = OutFNm.RightOfLast('/');
  const bool c = Env.GetIfArgPrefixBool("-c:", false, "collate centralities into matrix (T / F)");
  
  // Load graph and create directed and undirected graphs (pointer to the same memory)
  printf("\nLoading %s...", InFNm.CStr());
  PNGraph Graph = TSnap::LoadEdgeList<PNGraph>(InFNm);
  printf(" DONE\n");
  printf("  nodes: %d\n", Graph->GetNodes());
  printf("  edges: %d\n", Graph->GetEdges());
  printf("  time elapsed: %s (%s)\n", ExeTm.GetTmStr(), TSecTm::GetCurTm().GetTmStr().CStr());
  
  // Load subset nodes
  TIntV SubsetNIdV = TSnap::LoadTxtIntV(SubsetNIdVFNm);
  
  // Declare variables
  TIntIntH InNodesH, InDiameterH, OutNodesH, OutDiameterH, NodesH, DiameterH;
  TNGraph::TNodeI NI;
  
  // SUBSET DIAMETER AND NODE COUNTS
  
  printf("Computing subset diameter and node counts\n");
  TSnap::TFixedMemorySubsetDiameter<PNGraph> FixedMemorySubsetDiameter(Graph);
  printf("  ...");
  FixedMemorySubsetDiameter.ComputeInSubsetDiameter(SubsetNIdV, InNodesH, InDiameterH);
  printf(" DONE (time elapsed: %s (%s))\n", ExeTm.GetTmStr(), TSecTm::GetCurTm().GetTmStr().CStr());
  printf("  ...");
  FixedMemorySubsetDiameter.ComputeOutSubsetDiameter(SubsetNIdV, OutNodesH, OutDiameterH);
  printf(" DONE (time elapsed: %s (%s))\n", ExeTm.GetTmStr(), TSecTm::GetCurTm().GetTmStr().CStr());
  printf("  ...");
  FixedMemorySubsetDiameter.ComputeSubsetDiameter(SubsetNIdV, NodesH, DiameterH);
  printf(" DONE (time elapsed: %s (%s))\n", ExeTm.GetTmStr(), TSecTm::GetCurTm().GetTmStr().CStr());
 
  // OUTPUTTING (mostly verbose printing statements, don't get scared)
  
  if (c) {
    
    printf("\nSaving %s.diameters.combined...", BseFNm.CStr());
    const TStr CombinedFNm = TStr::Fmt("%s.diameters.combined", OutFNm.CStr());
    FILE *F = fopen(CombinedFNm.CStr(), "wt");
    fprintf(F,"# Subset diameters and node counts (in / out / undirected)\n");
    fprintf(F,"# Nodes: %d\tEdges: %d\t Subset size: %d\n", Graph->GetNodes(), Graph->GetEdges(), SubsetNIdV.Len());
    fprintf(F,"# SubsetNodeId\tInDiameter\tInNodes\tOutDiameter\tOutNodes\tDiameter\tNodes\n");
    for (NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
      const int NId = NI.GetId(); fprintf(F, "%d", NId);
      fprintf(F, "\t%d\t%d", int(InDiameterH.GetDat(NId)), int(InNodesH.GetDat(NId)));
      fprintf(F, "\t%d\t%d", int(OutDiameterH.GetDat(NId)), int(OutNodesH.GetDat(NId)));
      fprintf(F, "\t%d\t%d", int(DiameterH.GetDat(NId)), int(NodesH.GetDat(NId)));
      fprintf(F, "\n");
    }
    printf(" DONE\n");
    
  } else {
    
    printf("\nSaving %s.nodes.IN...", BseFNm.CStr());
    TSnap::SaveTxt(InNodesH, TStr::Fmt("%s.nodes.IN", OutFNm.CStr()), "Number of nodes in neighborhood (in) ", "Node", "Number");
    printf(" DONE");
    
    printf("\nSaving %s.nodes.OUT...", BseFNm.CStr());
    TSnap::SaveTxt(OutNodesH, TStr::Fmt("%s.nodes.OUT", OutFNm.CStr()), "Number of nodes in neighborhood (out) ", "Node", "Number");
    printf(" DONE");
    
    printf("\nSaving %s.nodes...", BseFNm.CStr());
    TSnap::SaveTxt(NodesH, TStr::Fmt("%s.nodes", OutFNm.CStr()), "Number of nodes in neighborhood (undirected) ", "Node", "Number");
    printf(" DONE\n");
   
    printf("\nSaving %s.diameter.IN...", BseFNm.CStr());
    TSnap::SaveTxt(InDiameterH, TStr::Fmt("%s.diameter.IN", OutFNm.CStr()), "Diameter of neighborhood (in) ", "Node", "Diameter");
    printf(" DONE");
    
    printf("\nSaving %s.diameter.OUT...", BseFNm.CStr());
    TSnap::SaveTxt(OutDiameterH, TStr::Fmt("%s.diameter.OUT", OutFNm.CStr()), "Diameter of neighborhood (out) ", "Node", "Diameter");
    printf(" DONE");
    
    printf("\nSaving %s.diameter...", BseFNm.CStr());
    TSnap::SaveTxt(DiameterH, TStr::Fmt("%s.diameter", OutFNm.CStr()), "Diameter of neighborhood (undirected) ", "Node", "Diameter");
    printf(" DONE\n");
 
  }
  
  Catch
  
  printf("\nTotal run time: %s (%s)\n", ExeTm.GetTmStr(), TSecTm::GetCurTm().GetTmStr().CStr());
  return 0;
  
}
Exemplo n.º 26
0
void exportNodeList(const PNGraph& graph, std::vector<int>& idList) {
	for (TNGraph::TNodeI ni = graph->BegNI(); ni != graph->EndNI(); ni++) {
		idList.push_back(ni.GetId());
	}
}
Exemplo n.º 27
0
int64 CountTriangles2(const PNGraph &Graph) {
  struct timeval start, end;
  float delta;
  TTmProfiler Profiler;
  int TimerId = Profiler.AddTimer("Profiler");
  const int NNodes = Graph->GetNodes();

  TIntV MapV(NNodes);
  TVec<TNGraph::TNodeI> NV(NNodes);
  NV.Reduce(0);

  Profiler.ResetTimer(TimerId);
  Profiler.StartTimer(TimerId);
  gettimeofday(&start, NULL);

  int MxId = -1;
  int ind = 0;
  for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++)   {
    NV.Add(NI);
    int Id = NI.GetId();
    if (Id > MxId) {
      MxId = Id;
    }
    MapV[ind] = Id;
    ind++;
  }

  TIntV IndV(MxId+1);

  for (int j = 0; j < NNodes; j++) {
    IndV[MapV[j]] = j;
  }

  gettimeofday(&end, NULL);
  Profiler.StopTimer(TimerId);
  delta = ((end.tv_sec  - start.tv_sec) * 1000000u +
          end.tv_usec - start.tv_usec) / 1.e6;
  printf("__nodemap__\ttime %7.3f\tcpu %8.3f\n", delta, Profiler.GetTimerSec(TimerId));

  Profiler.ResetTimer(TimerId);
  Profiler.StartTimer(TimerId);
  gettimeofday(&start, NULL);

  ind = MapV.Len();

  Profiler.ResetTimer(TimerId);
  Profiler.StartTimer(TimerId);
  gettimeofday(&start, NULL);

  TVec<TIntV> HigherDegNbrV(ind);

  for (int i = 0; i < ind; i++) {
    HigherDegNbrV[i] = TVec<TInt>();
    HigherDegNbrV[i].Reserve(NV[i].GetDeg());
    HigherDegNbrV[i].Reduce(0);
  }

  gettimeofday(&end, NULL);
  Profiler.StopTimer(TimerId);
  delta = ((end.tv_sec  - start.tv_sec) * 1000000u +
            end.tv_usec - start.tv_usec) / 1.e6;
  printf("__valloc__\ttime %7.3f\tcpu %8.3f\n", delta, Profiler.GetTimerSec(TimerId));

  Profiler.ResetTimer(TimerId);
  Profiler.StartTimer(TimerId);
  gettimeofday(&start, NULL);

#pragma omp parallel for schedule(dynamic)
  for (TInt i = 0; i < ind; i++) {
    TNGraph::TNodeI NI = NV[i];
    //HigherDegNbrV[i] = TVec<TInt>();
    //HigherDegNbrV[i].Reserve(NI.GetDeg());
    //HigherDegNbrV[i].Reduce(0);

    GetMergeSortedV(HigherDegNbrV[i], NI);

    int k = 0;
    for (TInt j = 0; j < HigherDegNbrV[i].Len(); j++) {
      TInt Vert = HigherDegNbrV[i][j];
      TInt Deg = NV[IndV[Vert]].GetDeg();
      if (Deg > NI.GetDeg() ||
         (Deg == NI.GetDeg() && Vert > NI.GetId())) {
        HigherDegNbrV[i][k] = Vert;
        k++;
      }
    }
    HigherDegNbrV[i].Reduce(k);
  }

  gettimeofday(&end, NULL);
  Profiler.StopTimer(TimerId);
  delta = ((end.tv_sec  - start.tv_sec) * 1000000u +
            end.tv_usec - start.tv_usec) / 1.e6;
  printf("__sort__\ttime %7.3f\tcpu %8.3f\n", delta, Profiler.GetTimerSec(TimerId));

  Profiler.ResetTimer(TimerId);
  Profiler.StartTimer(TimerId);
  gettimeofday(&start, NULL);

  int64 cnt = 0;
#pragma omp parallel for schedule(dynamic) reduction(+:cnt)
  for (TInt i = 0; i < HigherDegNbrV.Len(); i++) {
    for (TInt j = 0; j < HigherDegNbrV[i].Len(); j++) {
      //TInt NbrInd = H.GetDat(HigherDegNbrV[i][j]);
      TInt NbrInd = IndV[HigherDegNbrV[i][j]];

      int64 num = GetCommon(HigherDegNbrV[i], HigherDegNbrV[NbrInd]);
      cnt += num;
    }
  }

  gettimeofday(&end, NULL);
  Profiler.StopTimer(TimerId);
  delta = ((end.tv_sec  - start.tv_sec) * 1000000u +
            end.tv_usec - start.tv_usec) / 1.e6;
  printf("__count__\ttime %7.3f\tcpu %8.3f\n", delta, Profiler.GetTimerSec(TimerId));

  return cnt;
}
Exemplo n.º 28
0
// Test node, edge creation
TEST(TNGraph, ManipulateNodesEdges) {
  int NNodes = 10000;
  int NEdges = 100000;
  const char *FName = "test.graph.dat";

  PNGraph Graph;
  PNGraph Graph1;
  PNGraph Graph2;
  int i;
  int n;
  int NCount;
  int x,y;
  int Deg, InDeg, OutDeg;

  Graph = TNGraph::New();
  EXPECT_EQ(1,Graph->Empty());

  // create the nodes
  for (i = 0; i < NNodes; i++) {
    Graph->AddNode(i);
  }
  EXPECT_EQ(0,Graph->Empty());
  EXPECT_EQ(NNodes,Graph->GetNodes());

  // create random edges
  NCount = NEdges;
  while (NCount > 0) {
    x = (long) (drand48() * NNodes);
    y = (long) (drand48() * NNodes);
    // Graph->GetEdges() is not correct for the loops (x == y),
    // skip the loops in this test
    if (x != y  &&  !Graph->IsEdge(x,y)) {
      n = Graph->AddEdge(x, y);
      NCount--;
    }
  }

  EXPECT_EQ(NEdges,Graph->GetEdges());

  EXPECT_EQ(0,Graph->Empty());
  EXPECT_EQ(1,Graph->IsOk());

  for (i = 0; i < NNodes; i++) {
    EXPECT_EQ(1,Graph->IsNode(i));
  }

  EXPECT_EQ(0,Graph->IsNode(NNodes));
  EXPECT_EQ(0,Graph->IsNode(NNodes+1));
  EXPECT_EQ(0,Graph->IsNode(2*NNodes));

  // nodes iterator
  NCount = 0;
  for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
    NCount++;
  }
  EXPECT_EQ(NNodes,NCount);

  // edges per node iterator
  NCount = 0;
  for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
    for (int e = 0; e < NI.GetOutDeg(); e++) {
      NCount++;
    }
  }
  EXPECT_EQ(NEdges,NCount);

  // edges iterator
  NCount = 0;
  for (TNGraph::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) {
    NCount++;
  }
  EXPECT_EQ(NEdges,NCount);

  // node degree
  for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
    Deg = NI.GetDeg();
    InDeg = NI.GetInDeg();
    OutDeg = NI.GetOutDeg();

    EXPECT_EQ(Deg,InDeg+OutDeg);
  }

  // assignment
  Graph1 = TNGraph::New();
  *Graph1 = *Graph;

  EXPECT_EQ(NNodes,Graph1->GetNodes());
  EXPECT_EQ(NEdges,Graph1->GetEdges());
  EXPECT_EQ(0,Graph1->Empty());
  EXPECT_EQ(1,Graph1->IsOk());

  // saving and loading
  {
    TFOut FOut(FName);
    Graph->Save(FOut);
    FOut.Flush();
  }

  {
    TFIn FIn(FName);
    Graph2 = TNGraph::Load(FIn);
  }

  EXPECT_EQ(NNodes,Graph2->GetNodes());
  EXPECT_EQ(NEdges,Graph2->GetEdges());
  EXPECT_EQ(0,Graph2->Empty());
  EXPECT_EQ(1,Graph2->IsOk());

  // remove all the nodes and edges
  for (i = 0; i < NNodes; i++) {
    n = Graph->GetRndNId();
    Graph->DelNode(n);
  }

  EXPECT_EQ(0,Graph->GetNodes());
  EXPECT_EQ(0,Graph->GetEdges());

  EXPECT_EQ(1,Graph->IsOk());
  EXPECT_EQ(1,Graph->Empty());

  Graph1->Clr();

  EXPECT_EQ(0,Graph1->GetNodes());
  EXPECT_EQ(0,Graph1->GetEdges());

  EXPECT_EQ(1,Graph1->IsOk());
  EXPECT_EQ(1,Graph1->Empty());
}
Exemplo n.º 29
0
int main(int argc, char* argv[]) {
 Env = TEnv(argc, argv, TNotify::StdNotify);
 Env.PrepArgs(TStr::Fmt("Trust Rank. Build: %s, %s. Time: %s", __TIME__, __DATE__, TExeTm::GetCurTm()));
 TExeTm ExeTm;
 Try
	const TStr Gnod = Env.GetIfArgPrefixStr("-g:", "Gnode.txt", "Good Nodes");
	const TStr Bnod = Env.GetIfArgPrefixStr("-b:", "Bnode.txt", "Bad Nodes" );
	const TStr Iput = Env.GetIfArgPrefixStr("-i:", "Input.txt", "Input File");
	const TStr Oput = Env.GetIfArgPrefixStr("-o:", "Output.txt", "Output File");
	const double C	  = 0.85;
	const int MaxIter = 50;
	const double Eps  = 1e-9;
	
	FILE* fpO = fopen(Oput.CStr(), "w");
	
	PNGraph Graph = TSnap::LoadEdgeList< PNGraph > (Iput);
	fprintf(fpO, "\nNodes: %d, Edges: %d\n\n", Graph->GetNodes(), Graph->GetEdges());
	const int NNodes = Graph->GetNodes();
	TIntFltH TRankH;
	TRankH.Gen(NNodes);
	int maxNId = 0, NId = 0, ret = 0;
	for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++)
		maxNId = max(maxNId, NI.GetId());
	
	TFltV initialTrustScore(maxNId + 1);
	for (int i = 0; i < initialTrustScore.Len(); i++)
		initialTrustScore[i] = 0.5;

	FILE* fpI = fopen(Gnod.CStr(), "r");
	while (true) {
		ret = fscanf(fpI, "%d", &NId);
		if (ret == EOF) break;
		if (Graph->IsNode(NId))
			initialTrustScore[NId] = 1.0;
	}
	fclose(fpI);
	
	fpI = fopen(Bnod.CStr(), "r");
	while (true) {
		ret = fscanf(fpI, "%d", &NId);
		if (ret == EOF) break;
		if (Graph->IsNode(NId))
			initialTrustScore[NId] = 0.0;
	}
	fclose(fpI);

	double Tot = 0.0;
	for(int i = 0; i < initialTrustScore.Len(); i++)
		Tot += initialTrustScore[i];
	for(int i = 0; i < initialTrustScore.Len(); i++)
		initialTrustScore[i] /= Tot;
	
	for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++)
		TRankH.AddDat( NI.GetId(), initialTrustScore[NI.GetId()] );
	
	TFltV TmpV(NNodes);
	for (int iter = 0; iter < MaxIter; iter++) {
		int j = 0;
		for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++, j++) {
			TmpV[j] = 0;
			for (int e = 0; e < NI.GetOutDeg(); e++) {
				const int OutNId = NI.GetOutNId(e);
				const int InDeg  = Graph->GetNI(InNId).GetInDeg();
				if (InDeg > 0) 
					TmpV[j] += (double) TRankH.GetDat(OutNId) / (double) InDeg; 
        	}
			TmpV[j] =  C * TmpV[j] + (1.0 - C) * initialTrustScore[NI.GetId()]; 
		}

		for (int i = 0; i < TRankH.Len(); i++) 
			TRankH[i] = TmpV[i];
	}
	
	fprintf(fpO, "Node ID\t\tTrustRank\n");
	for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++){
		int Id = NI.GetId();
		double tr = TRankH.GetDat(Id);
		fprintf(fpO, "%d\t\t\t%.5lf\n", Id, tr);
	}
	fclose(fpO);
	
 Catch
	printf("\nRun Time: %s (%s)\n", ExeTm.GetTmStr(), TSecTm::GetCurTm().GetTmStr().CStr());
	
	return 0;
}