Пример #1
0
// Arijit
void GetMergeSortedV(TIntV& NeighbourV, TNGraph::TNodeI NI) {
  int ind, j, k;
  ind = j = k = 0;
  while (j < NI.GetInDeg() && k < NI.GetOutDeg()) {
    int v1 = NI.GetInNId(j);
    int v2 = NI.GetOutNId(k);
    if (v1 <= v2) {
      if ((ind == 0) || (NeighbourV[ind-1] != v1)) {
        NeighbourV.Add(v1);
        ind += 1;
      }
      j += 1;
    }
    else {
      if ((ind == 0) || (NeighbourV[ind-1] != v2)) {
        NeighbourV.Add(v2);
        ind += 1;
      }
      k += 1;
    }
  }
  while (j < NI.GetInDeg()) {
    int v = NI.GetInNId(j);
    if ((ind == 0) || (NeighbourV[ind-1] != v)) {
        NeighbourV.Add(v);
        ind += 1;
    }
    j += 1;
  }
  while (k < NI.GetOutDeg()) {
    int v = NI.GetOutNId(k);
    if ((ind == 0) || (NeighbourV[ind-1] != v)) {
        NeighbourV.Add(v);
        ind += 1;
    }
    k += 1;
  }
}
Пример #2
0
void TGraphKey::TakeGraph(const PNGraph& Graph, TIntPrV& NodeMap) {
  TIntSet NodeIdH;
  int n = 0;
  NodeMap.Gen(Graph->GetNodes(), 0);
  for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++, n++) {
    NodeIdH.AddKey(NI.GetId());
    NodeMap.Add(TIntPr(NI.GetId(), n));
  }
  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();
}
Пример #3
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);
}
Пример #4
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);
            }
        }
    }
}
Пример #5
0
float JaccardSim(TNGraph::TNodeI NI1, TNGraph::TNodeI NI2) {
  int lenA = NI1.GetOutDeg();
  int lenB = NI2.GetOutDeg();
  int ct = 0;
  int j = 0;
  int i = 0;
  while (i < lenA  &&  j < lenB) {
    if (NI1.GetOutNId(i) == NI2.GetOutNId(j)) {
      ct++; i++; j++;
    } else if (NI1.GetOutNId(i) > NI2.GetOutNId(j)) {
      j++;
    } else {
      i++;
    }
  }
  return ct*1.0/(lenA+lenB-ct);

}
Пример #6
0
void TNetInfBs::Init() {
	THash<TInt, TIntV> CascPN;
    Graph = TNGraph::New();

    // reset vectors
    EdgeGainV.Clr();
    CascPerEdge.Clr();
    PrecisionRecall.Clr();

    for (int c = 0; c < CascV.Len(); c++) {
      for (int i = 0; i < CascV[c].Len(); i++) {
        if (!Graph->IsNode(CascV[c].GetNode(i))) Graph->AddNode(CascV[c].GetNode(i));
        if (!CascPN.IsKey(CascV[c].GetNode(i))) CascPN.AddDat(CascV[c].GetNode(i)) = TIntV();
        CascPN.GetDat(CascV[c].GetNode(i)).Add(c);
      }
      CascV[c].InitProb();
    }

    // only add edges that make sense (i.e., at least once coherent in time)
    for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
    	TIntV &Cascs = CascPN.GetDat(NI.GetId());
    	for (int c = 0; c < Cascs.Len(); c++) {
    		for (int i=0; i < CascV[Cascs[c]].Len(); i++) {
    			if (CascV[Cascs[c]].GetNode(i)==NI.GetId())
    				continue;

    			if (CascV[Cascs[c]].GetTm(CascV[Cascs[c]].GetNode(i)) < CascV[Cascs[c]].GetTm(NI.GetId()) ) {
    				if (!CascPerEdge.IsKey(TIntPr(CascV[Cascs[c]].GetNode(i), NI.GetId()))) {
    					EdgeGainV.Add(TPair<TFlt, TIntPr>(TFlt::Mx, TIntPr(CascV[Cascs[c]].GetNode(i), NI.GetId())));
    					CascPerEdge.AddDat(TIntPr(CascV[Cascs[c]].GetNode(i), NI.GetId())) = TIntV();
    				}
    				// Add cascade to hash of cascades per edge (to implement localized update)
    				CascPerEdge.GetDat(TIntPr(CascV[Cascs[c]].GetNode(i), NI.GetId())).Add(Cascs[c]);
    			}
    		}
    	}
    }
}
Пример #7
0
// RenumberNodes ... Renumber node ids in the subgraph to 0...N-1
PNGraph GetSubGraph(const PNGraph& Graph, const TIntV& NIdV, const bool& RenumberNodes) {
    //if (! RenumberNodes) { return TSnap::GetSubGraph(Graph, NIdV); }
    PNGraph NewGraphPt = TNGraph::New();
    TNGraph& NewGraph = *NewGraphPt;
    NewGraph.Reserve(NIdV.Len(), -1);
    TIntSet NIdSet(NIdV.Len());
    for (int n = 0; n < NIdV.Len(); n++) {
        if (Graph->IsNode(NIdV[n])) {
            NIdSet.AddKey(NIdV[n]);
            if (! RenumberNodes) {
                NewGraph.AddNode(NIdV[n]);
            }
            else {
                NewGraph.AddNode(NIdSet.GetKeyId(NIdV[n]));
            }
        }
    }
    if (! RenumberNodes) {
        for (int n = 0; n < NIdSet.Len(); n++) {
            const int SrcNId = NIdSet[n];
            const TNGraph::TNodeI NI = Graph->GetNI(SrcNId);
            for (int edge = 0; edge < NI.GetOutDeg(); edge++) {
                const int OutNId = NI.GetOutNId(edge);
                if (NIdSet.IsKey(OutNId)) {
                    NewGraph.AddEdge(SrcNId, OutNId);
                }
            }
        }
    } else {
        for (int n = 0; n < NIdSet.Len(); n++) {
            const int SrcNId = NIdSet[n];
            const TNGraph::TNodeI NI = Graph->GetNI(SrcNId);
            for (int edge = 0; edge < NI.GetOutDeg(); edge++) {
                const int OutNId = NI.GetOutNId(edge);
                if (NIdSet.IsKey(OutNId)) {
                    NewGraph.AddEdge(NIdSet.GetKeyId(SrcNId), NIdSet.GetKeyId(OutNId));
                }
            }
        }
    }
    return NewGraphPt;
}
Пример #8
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;
}
Пример #9
0
// Rok #13
//template<class PGraph> 
int64 CountTriangles1(const TVec<TNGraph::TNodeI,int>& NV, const TIntV& IndV, const TIntV& MapV) {
  struct timeval start, end;
  float delta;
  TTmProfiler Profiler;
  int TimerId = Profiler.AddTimer("Profiler");

  int 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;
}
Пример #10
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;
}
Пример #11
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());
}
Пример #12
0
// Node selects N~geometric(1.0-FwdBurnProb)-1 out-links and burns them. Then same for in-links.
// geometirc(p) has mean 1/(p), so for given FwdBurnProb, we burn 1/(1-FwdBurnProb)
void TForestFire::BurnGeoFire() {
	const double OldFwdBurnProb = FwdBurnProb;
	const double OldBckBurnProb = BckBurnProb;
	const int& NInfect = InfectNIdV.Len();
	const TNGraph& G = *Graph;
	TIntH BurnedNIdH;               // burned nodes
	TIntV BurningNIdV = InfectNIdV; // currently burning nodes
	TIntV NewBurnedNIdV;            // nodes newly burned in current step
	bool HasAliveInNbrs, HasAliveOutNbrs; // has unburned neighbors
	TIntV AliveNIdV;                // NIds of alive neighbors
	int NBurned = NInfect, time;
	for (int i = 0; i < InfectNIdV.Len(); i++) {
		BurnedNIdH.AddDat(InfectNIdV[i]);
	}
	NBurnedTmV.Clr(false);  NBurningTmV.Clr(false);  NewBurnedTmV.Clr(false);
	for (time = 0;; time++) {
		NewBurnedNIdV.Clr(false);
		for (int node = 0; node < BurningNIdV.Len(); node++) {
			const int& BurningNId = BurningNIdV[node];
			const TNGraph::TNodeI Node = G.GetNI(BurningNId);
			// find unburned links
			HasAliveOutNbrs = false;
			AliveNIdV.Clr(false); // unburned links
			for (int e = 0; e < Node.GetOutDeg(); e++) {
				const int OutNId = Node.GetOutNId(e);
				if (!BurnedNIdH.IsKey(OutNId)) {
					HasAliveOutNbrs = true;  AliveNIdV.Add(OutNId);
				}
			}
			// number of links to burn (geometric coin). Can also burn 0 links
			const int BurnNFwdLinks = Rnd.GetGeoDev(1.0 - FwdBurnProb) - 1;
			if (HasAliveOutNbrs && BurnNFwdLinks > 0) {
				AliveNIdV.Shuffle(Rnd);
				for (int i = 0; i < TMath::Mn(BurnNFwdLinks, AliveNIdV.Len()); i++) {
					BurnedNIdH.AddDat(AliveNIdV[i]);
					NewBurnedNIdV.Add(AliveNIdV[i]);  NBurned++;
				}
			}
			// backward links
			if (BckBurnProb > 0.0) {
				// find unburned links
				HasAliveInNbrs = false;
				AliveNIdV.Clr(false);
				for (int e = 0; e < Node.GetInDeg(); e++) {
					const int InNId = Node.GetInNId(e);
					if (!BurnedNIdH.IsKey(InNId)) {
						HasAliveInNbrs = true;  AliveNIdV.Add(InNId);
					}
				}
				// number of links to burn (geometric coin). Can also burn 0 links
				const int BurnNBckLinks = Rnd.GetGeoDev(1.0 - BckBurnProb) - 1;
				if (HasAliveInNbrs && BurnNBckLinks > 0) {
					AliveNIdV.Shuffle(Rnd);
					for (int i = 0; i < TMath::Mn(BurnNBckLinks, AliveNIdV.Len()); i++) {
						BurnedNIdH.AddDat(AliveNIdV[i]);
						NewBurnedNIdV.Add(AliveNIdV[i]);  NBurned++;
					}
				}
			}
		}
		NBurnedTmV.Add(NBurned);  NBurningTmV.Add(BurningNIdV.Len());  NewBurnedTmV.Add(NewBurnedNIdV.Len());
		// BurningNIdV.AddV(NewBurnedNIdV);   // node is burning eternally
		BurningNIdV.Swap(NewBurnedNIdV);   // node is burning just 1 time step
		if (BurningNIdV.Empty()) break;
		FwdBurnProb = FwdBurnProb * ProbDecay;
		BckBurnProb = BckBurnProb * ProbDecay;
	}
	BurnedNIdV.Gen(BurnedNIdH.Len(), 0);
	for (int i = 0; i < BurnedNIdH.Len(); i++) {
		BurnedNIdV.Add(BurnedNIdH.GetKey(i));
	}
	FwdBurnProb = OldFwdBurnProb;
	BckBurnProb = OldBckBurnProb;
}
Пример #13
0
// burn each link independently (forward with FwdBurnProb, backward with BckBurnProb)
void TForestFire::BurnExpFire() {
	const double OldFwdBurnProb = FwdBurnProb;
	const double OldBckBurnProb = BckBurnProb;
	const int NInfect = InfectNIdV.Len();
	const TNGraph& G = *Graph;
	TIntH BurnedNIdH;               // burned nodes
	TIntV BurningNIdV = InfectNIdV; // currently burning nodes
	TIntV NewBurnedNIdV;            // nodes newly burned in current step
	bool HasAliveNbrs;              // has unburned neighbors
	int NBurned = NInfect, NDiedFire = 0;
	for (int i = 0; i < InfectNIdV.Len(); i++) {
		BurnedNIdH.AddDat(InfectNIdV[i]);
	}
	NBurnedTmV.Clr(false);  NBurningTmV.Clr(false);  NewBurnedTmV.Clr(false);
	for (int time = 0;; time++) {
		NewBurnedNIdV.Clr(false);
		// for each burning node
		for (int node = 0; node < BurningNIdV.Len(); node++) {
			const int& BurningNId = BurningNIdV[node];
			const TNGraph::TNodeI Node = G.GetNI(BurningNId);
			HasAliveNbrs = false;
			NDiedFire = 0;
			// burn forward links  (out-links)
			for (int e = 0; e < Node.GetOutDeg(); e++) {
				const int OutNId = Node.GetOutNId(e);
				if (!BurnedNIdH.IsKey(OutNId)) { // not yet burned
					HasAliveNbrs = true;
					if (Rnd.GetUniDev() < FwdBurnProb) {
						BurnedNIdH.AddDat(OutNId);  NewBurnedNIdV.Add(OutNId);  NBurned++;
					}
				}
			}
			// burn backward links (in-links)
			if (BckBurnProb > 0.0) {
				for (int e = 0; e < Node.GetInDeg(); e++) {
					const int InNId = Node.GetInNId(e);
					if (!BurnedNIdH.IsKey(InNId)) { // not yet burned
						HasAliveNbrs = true;
						if (Rnd.GetUniDev() < BckBurnProb) {
							BurnedNIdH.AddDat(InNId);  NewBurnedNIdV.Add(InNId);  NBurned++;
						}
					}
				}
			}
			if (!HasAliveNbrs) { NDiedFire++; }
		}
		NBurnedTmV.Add(NBurned);
		NBurningTmV.Add(BurningNIdV.Len() - NDiedFire);
		NewBurnedTmV.Add(NewBurnedNIdV.Len());
		//BurningNIdV.AddV(NewBurnedNIdV);   // node is burning eternally
		BurningNIdV.Swap(NewBurnedNIdV);    // node is burning just 1 time step
		if (BurningNIdV.Empty()) break;
		FwdBurnProb = FwdBurnProb * ProbDecay;
		BckBurnProb = BckBurnProb * ProbDecay;
	}
	BurnedNIdV.Gen(BurnedNIdH.Len(), 0);
	for (int i = 0; i < BurnedNIdH.Len(); i++) {
		BurnedNIdV.Add(BurnedNIdH.GetKey(i));
	}
	FwdBurnProb = OldFwdBurnProb;
	BckBurnProb = OldBckBurnProb;
}
Пример #14
0
/////////////////////////////////////////////////
// Forest Fire
void TForestFire::InfectAll() {
	InfectNIdV.Gen(Graph->GetNodes());
	for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
		InfectNIdV.Add(NI.GetId());
	}
}
Пример #15
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;
}
Пример #16
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);
    }
  }
}
Пример #17
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;
  
}
Пример #18
0
PNEANet KNNJaccard(PNGraph Graph, int K) {
  PNEANet KNN = TNEANet::New();

  int sum_neighbors = 0;
  int ct;
  int end;
  end = Graph->GetNodes();
  TIntV* Neighbors_old = new TIntV();
  TIntV* Neighbors = new TIntV();
  TIntV* temp;
  TIntV NIdV;
  Graph->GetNIdV (NIdV);
  int size = NIdV.Len();
  for (int ind = 0; ind < size; ind++) {
    KNN->AddNode(NIdV[ind]);
  }
  KNN->AddFltAttrE("sim");

  for (int ind = 0; ind < size; ind++) {
    TNGraph::TNodeI NI = Graph->GetNI(NIdV[ind]);
    if (NI.GetInDeg() > 0) {
      continue;
    }
    if (NI.GetOutDeg() == 0) {
      continue;
    }
    ct ++;

    TVec<TPair<TFlt, TInt> > TopK;
    for (int i = 0; i < K; i++) {
      TopK.Add(TPair<TFlt,TInt>(0.0, -1));
    }

    Neighbors->Clr(false);
    Neighbors_old->Clr(false);

    for (int i = 0; i < NI.GetOutDeg(); i++) {
      TNGraph::TNodeI Inst_NI = Graph->GetNI(NI.GetOutNId(i));
      MergeNbrs(Neighbors, Neighbors_old, Inst_NI);

      temp = Neighbors_old;
      temp->Clr(false);
      Neighbors_old = Neighbors;
      Neighbors = temp;
    }
    int num = Neighbors_old->Len();
    sum_neighbors += num;

    //Swap neighbors and Neighbors_old

    temp = Neighbors_old;
    Neighbors_old = Neighbors;
    Neighbors = temp;
    for (int j = 0; j< Neighbors->Len(); j++) {

      TNGraph::TNodeI Auth_NI = Graph->GetNI((*Neighbors)[j]);

      float similarity = JaccardSim(NI, Auth_NI);
      if (TopK[K-1].GetVal1() < similarity) {
        int index = 0;
        for (int i = K-2; i >= 0; i--)
          if (TopK[i].GetVal1() < similarity) {
            TopK.SetVal(i+1, TopK[i]);
          } else {
            index = i+1;
            break;
          }
        TopK.SetVal(index, TPair<TFlt, TInt>(similarity, (*Neighbors)[j]));
      }
    }

    for (int i = 0; i < K; i++) {
      int EId = KNN->AddEdge(NI.GetId(), TopK[i].GetVal2());
      KNN->AddFltAttrDatE(EId, TopK[i].GetVal1(), "sim");
    }

//    if (ct%10000 == 0)
//    	cout<<ct<<" avg neighbor degree = "<<sum_neighbors*1.0/ct<<" "<<currentDateTime()<<endl;

  }

  return KNN;
}
Пример #19
0
void TNetInfBs::GenCascade(TCascade& C, const int& TModel, const double &window, TIntPrIntH& EdgesUsed, const double& delta,
						   const double& std_waiting_time, const double& std_beta) {
	TIntFltH InfectedNIdH; TIntH InfectedBy;
	double GlobalTime; int StartNId;
	double alpha, beta;

	if (GroundTruth->GetNodes() == 0)
		return;

	while (C.Len() < 2) {
		C.Clr();
		InfectedNIdH.Clr();
		InfectedBy.Clr();
		GlobalTime = 0;

		StartNId = GroundTruth->GetRndNId();
		InfectedNIdH.AddDat(StartNId) = GlobalTime;

		while (true) {
			// sort by time & get the oldest node that did not run infection
			InfectedNIdH.SortByDat(true);
			const int& NId = InfectedNIdH.BegI().GetKey();
			GlobalTime = InfectedNIdH.BegI().GetDat();

			// all the nodes has run infection
			if (GlobalTime >= window)
				break;

			// add current oldest node to the network and set its time
			C.Add(NId, GlobalTime);

			// run infection from the current oldest node
			const TNGraph::TNodeI NI = GroundTruth->GetNI(NId);
			for (int e = 0; e < NI.GetOutDeg(); e++) {
				const int DstNId = NI.GetOutNId(e);

				beta = Betas.GetDat(TIntPr(NId, DstNId));

				// flip biased coin (set by beta)
				if (TInt::Rnd.GetUniDev() > beta+std_beta*TFlt::Rnd.GetNrmDev())
					continue;

				alpha = Alphas.GetDat(TIntPr(NId, DstNId));

				// not infecting the parent
				if (InfectedBy.IsKey(NId) && InfectedBy.GetDat(NId).Val == DstNId)
					continue;

				double sigmaT;
				switch (TModel) {
				case 0:
					// exponential with alpha parameter
					sigmaT = TInt::Rnd.GetExpDev(alpha);
					break;
				case 1:
					// power-law with alpha parameter
					sigmaT = TInt::Rnd.GetPowerDev(alpha);
					while (sigmaT < delta) { sigmaT = TInt::Rnd.GetPowerDev(alpha); }
					break;
				case 2:
					// rayleigh with alpha parameter
					sigmaT = TInt::Rnd.GetRayleigh(1/sqrt(alpha));
					break;
				default:
					sigmaT = 1;
					break;
				}

				// avoid negative time diffs in case of noise
				if (std_waiting_time > 0)
					sigmaT = TFlt::GetMx(0.0, sigmaT + std_waiting_time*TFlt::Rnd.GetNrmDev());

				double t1 = GlobalTime + sigmaT;

				if (InfectedNIdH.IsKey(DstNId)) {
					double t2 = InfectedNIdH.GetDat(DstNId);
					if (t2 > t1 && t2 != window) {
						InfectedNIdH.GetDat(DstNId) = t1;
						InfectedBy.GetDat(DstNId) = NId;
					}
				} else {
					InfectedNIdH.AddDat(DstNId) = t1;
					InfectedBy.AddDat(DstNId) = NId;
				}
			}

			// we cannot delete key (otherwise, we cannot sort), so we assign a big time (window cut-off)
			InfectedNIdH.GetDat(NId) = window;
		}

	}

	C.Sort();

	for (TIntH::TIter EI = InfectedBy.BegI(); EI < InfectedBy.EndI(); EI++) {
		TIntPr Edge(EI.GetDat().Val, EI.GetKey().Val);

		if (!EdgesUsed.IsKey(Edge)) EdgesUsed.AddDat(Edge) = 0;

		EdgesUsed.GetDat(Edge) += 1;
	}
}
Пример #20
0
PNEANet KNNJaccardParallel(PNGraph Graph,int K) {
  PNEANet KNN = TNEANet::New();
  TIntV NIdV;
  Graph->GetNIdV (NIdV);
  int size = NIdV.Len();
  for (int ind = 0; ind < size; ind++) {
    KNN->AddNode(NIdV[ind]);
  }
  KNN->AddFltAttrE("sim");
  TVec<TVec<TPair<TFlt, TInt>, int >, int > TopKList;
  TVec<TVec<TPair<TFlt, TInt>, int >, int > ThTopK; // for each thread
  TIntV NodeList;
  TIntV ThNodeList;// for each thread
  int NumThreads = omp_get_max_threads();
  omp_set_num_threads(NumThreads);
  #pragma omp parallel private(ThNodeList, ThTopK)
  {
    TIntV* Neighbors_old = new TIntV();
    TIntV* Neighbors = new TIntV();
    TIntV* temp;

    #pragma omp for schedule(dynamic,1000)
    for (int ind = 0; ind < size; ind++) {
      TNGraph::TNodeI NI = Graph->GetNI(NIdV[ind]);
      if (NI.GetInDeg() > 0) {
        continue;
      }
      if (NI.GetOutDeg() == 0) {
        continue;
      }

      TVec<TPair<TFlt, TInt>, int > TopK;
      for (int i = 0; i < K; i++) {
          TopK.Add(TPair<TFlt,TInt>(0.0, -1));
      }

      Neighbors->Clr(false);
      Neighbors_old->Clr(false);

      for (int i = 0; i < NI.GetOutDeg(); i++) {
        TNGraph::TNodeI Inst_NI = Graph->GetNI(NI.GetOutNId(i));
        MergeNbrs(Neighbors, Neighbors_old, Inst_NI);

        temp = Neighbors_old;
        temp->Clr(false);
        Neighbors_old = Neighbors;
        Neighbors = temp;
      }

      // Swap neighbors and Neighbors_old

      temp = Neighbors_old;
      Neighbors_old = Neighbors;
      Neighbors = temp;
      for(int j = 0; j< Neighbors->Len(); j++) {

        TNGraph::TNodeI Auth_NI = Graph->GetNI((*Neighbors)[j]);

        float similarity = JaccardSim(NI, Auth_NI);
        if (TopK[K-1].GetVal1() < similarity) {
          int index = 0;
          for (int i = K-2; i >= 0; i--)
            if (TopK[i].GetVal1() < similarity) {
              TopK.SetVal(i+1, TopK[i]);
            } else {
              index = i+1;
              break;
            }
          TopK.SetVal(index, TPair<TFlt, TInt>(similarity, (*Neighbors)[j]));
        }
      }

      ThTopK.Add(TopK);
      ThNodeList.Add(NIdV[ind]);

//    if (ct%10000 == 0)
//    	cout<<ct<<" avg neighbor degree = "<<sum_neighbors*1.0/ct<<" "<<currentDateTime()<<endl;

    }
    #pragma omp critical
    {
      for (int j = 0; j < ThTopK.Len(); j++) {
        TopKList.Add(ThTopK[j]);
        NodeList.Add(ThNodeList[j]);
      }
    }
	}

  int size2 = NodeList.Len();
  for (int i= 0; i < size2 ; i++) {

    for (int j = 0; j < K; j++) {
      if (TopKList[i][j].GetVal2() <= -1) {
        break;
      }
      int EId = KNN->AddEdge(NodeList[i], TopKList[i][j].GetVal2());
      KNN->AddFltAttrDatE(EId, TopKList[i][j].GetVal1(), "sim");
    }
  }
  return KNN;
}
Пример #21
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);
}
Пример #22
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());
	}
}