SNAP Library 2.3, User Reference  2014-06-16 11:58:46
SNAP, a general purpose, high performance system for analysis and manipulation of large networks
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
TSnap Namespace Reference

Main namespace for all the Snap global entities. More...

Namespaces

 TSnapDetail
 

Classes

struct  IsBipart
 Tests (at compile time) if the graph is a bipartite graph type. More...
 
struct  IsBipart< TBPGraph >
 
struct  IsDirected
 Tests (at compile time) if the graph is directed. More...
 
struct  IsDirected< TBigNet< TNodeData, IsDir > >
 
struct  IsDirected< TBigNet< TNodeData, true > >
 
struct  IsDirected< TNEANet >
 
struct  IsDirected< TNEGraph >
 
struct  IsDirected< TNGraph >
 
struct  IsDirected< TNodeEDatNet< TNodeData, TEdgeData > >
 
struct  IsDirected< TNodeEdgeNet< TNodeData, TEdgeData > >
 
struct  IsDirected< TNodeNet< TNodeData > >
 
struct  IsDirected< TTimeNENet >
 
struct  IsDirected< TTimeNet >
 
struct  IsEdgeDat
 Tests (at compile time) if the graph is a network with data on edges. More...
 
struct  IsEdgeDat< TNodeEDatNet< TNodeData, TEdgeData > >
 
struct  IsEdgeDat< TNodeEdgeNet< TNodeData, TEdgeData > >
 
struct  IsEdgeDat< TTimeNENet >
 
struct  IsMultiGraph
 Tests (at compile time) if the graph is a multigraph with multiple edges between the same nodes. More...
 
struct  IsMultiGraph< TNEANet >
 
struct  IsMultiGraph< TNEGraph >
 
struct  IsMultiGraph< TNodeEdgeNet< TNodeData, TEdgeData > >
 
struct  IsMultiGraph< TTimeNENet >
 
struct  IsNodeDat
 Tests (at compile time) if the graph is a network with data on nodes. More...
 
struct  IsNodeDat< TBigNet< TNodeData, IsDir > >
 
struct  IsNodeDat< TNodeEDatNet< TNodeData, TEdgeData > >
 
struct  IsNodeDat< TNodeEdgeNet< TNodeData, TEdgeData > >
 
struct  IsNodeDat< TNodeNet< TNodeData > >
 
struct  IsNodeDat< TTimeNENet >
 
struct  IsNodeDat< TTimeNet >
 
struct  IsSources
 Tests (at compile time) if the nodes store only out-edges, but not in-edges. More...
 
class  TPRManager
 Push relabel attr manager. More...
 

Functions

template<class PGraph >
int CntInDegNodes (const PGraph &Graph, const int &NodeInDeg)
 Returns the number of nodes with in-degree NodeInDeg. More...
 
template<class PGraph >
int CntOutDegNodes (const PGraph &Graph, const int &NodeOutDeg)
 Returns the number of nodes with out-degree NodeOutDeg. More...
 
template<class PGraph >
int CntDegNodes (const PGraph &Graph, const int &NodeDeg)
 Returns the number of nodes with degree NodeDeg. More...
 
template<class PGraph >
int CntNonZNodes (const PGraph &Graph)
 Returns the number of nodes with degree greater than 0. More...
 
template<class PGraph >
int CntEdgesToSet (const PGraph &Graph, const int &NId, const TIntSet &NodeSet)
 Returns the number of nodes in NodeSet that have an edge to the node NId. More...
 
template<class PGraph >
int GetMxDegNId (const PGraph &Graph)
 Returns a randomly chosen node from all the nodes with the maximum degree. More...
 
template<class PGraph >
int GetMxInDegNId (const PGraph &Graph)
 Returns a randomly chosen node from all the nodes with the maximum in-degree. More...
 
template<class PGraph >
int GetMxOutDegNId (const PGraph &Graph)
 Returns a randomly chosen node from all the nodes with the maximum out-degree. More...
 
template<class PGraph >
void GetInDegCnt (const PGraph &Graph, TIntPrV &DegToCntV)
 Returns an in-degree histogram: a set of pairs (in-degree, number of nodes of such in-degree) More...
 
template<class PGraph >
void GetInDegCnt (const PGraph &Graph, TFltPrV &DegToCntV)
 Returns an in-degree histogram: a set of pairs (in-degree, number of nodes of such in-degree) More...
 
template<class PGraph >
void GetOutDegCnt (const PGraph &Graph, TIntPrV &DegToCntV)
 Returns an out-degree histogram: a set of pairs (out-degree, number of nodes of such out-degree) More...
 
template<class PGraph >
void GetOutDegCnt (const PGraph &Graph, TFltPrV &DegToCntV)
 Returns an out-degree histogram: a set of pairs (out-degree, number of nodes of such out-degree) More...
 
template<class PGraph >
void GetDegCnt (const PGraph &Graph, TIntPrV &DegToCntV)
 Returns a degree histogram: a set of pairs (degree, number of nodes of such degree) More...
 
template<class PGraph >
void GetDegCnt (const PGraph &Graph, TFltPrV &DegToCntV)
 Returns a degree histogram: a set of pairs (degree, number of nodes of such degree) More...
 
template<class PGraph >
void GetDegSeqV (const PGraph &Graph, TIntV &DegV)
 Returns a degree sequence vector. More...
 
template<class PGraph >
void GetDegSeqV (const PGraph &Graph, TIntV &InDegV, TIntV &OutDegV)
 Returns an in- and out-degree sequence vectors. More...
 
template<class PGraph >
void GetNodeInDegV (const PGraph &Graph, TIntPrV &NIdInDegV)
 Returns a vector of pairs (node id, node in-degree) More...
 
template<class PGraph >
void GetNodeOutDegV (const PGraph &Graph, TIntPrV &NIdOutDegV)
 Returns a vector of pairs (node id, node out-degree) More...
 
template<class PGraph >
int CntUniqUndirEdges (const PGraph &Graph)
 Counts unique undirected edges in the graph Graph. Nodes (u,v)<. More...
 
template<class PGraph >
int CntUniqDirEdges (const PGraph &Graph)
 Counts unique directed edges in the graph Graph. Nodes (u,v)<. More...
 
template<class PGraph >
int CntUniqBiDirEdges (const PGraph &Graph)
 Counts unique bidirectional edges in the graph Graph. Edge is bidirectional is there exist directed edges in both directions: (u,v) and (v,u) More...
 
template<class PGraph >
int CntSelfEdges (const PGraph &Graph)
 Counts the number fo of self-edges in a graph. Edge (u,u) is a self-edge. More...
 
template<class PGraph >
PGraph GetUnDir (const PGraph &Graph)
 Returs an undirected version of the graph. For every edge (u,v) an edge (v,u) is added (if it does not yet exist). More...
 
template<class PGraph >
void MakeUnDir (const PGraph &Graph)
 Makes the graph undirected. For every edge (u,v) an edge (v,u) is added (if it does not yet exist). More...
 
template<class PGraph >
void AddSelfEdges (const PGraph &Graph)
 Adds a self-edge to every node in the graph. More...
 
template<class PGraph >
void DelSelfEdges (const PGraph &Graph)
 Removes all the self-edges from the graph. More...
 
template<class PGraph >
void DelNodes (PGraph &Graph, const TIntV &NIdV)
 Removes nodes with ids stored in NIdV from the graph. More...
 
template<class PGraph >
void DelZeroDegNodes (PGraph &Graph)
 Removes all the zero-degree nodes, that isolated nodes, from the graph. More...
 
template<class PGraph >
void DelDegKNodes (PGraph &Graph, const int &OutDegK, const int &InDegK)
 Removes all the node of out-degree OutDegK and all the nodes of in-degree InDegK from the graph. More...
 
template<class PGraph >
bool IsTree (const PGraph &Graph, int &RootNIdX)
 
template<class PGraph >
int GetTreeRootNId (const PGraph &Graph)
 
template<class PGraph >
void GetTreeSig (const PGraph &Graph, const int &RootNId, TIntV &Sig)
 
template<class PGraph >
void GetTreeSig (const PGraph &Graph, const int &RootNId, TIntV &Sig, TIntPrV &NodeMap)
 
template<class PGraph >
void GetAnf (const PGraph &Graph, const int &SrcNId, TIntFltKdV &DistNbrsV, const int &MxDist, const bool &IsDir, const int &NApprox=32)
 
template<class PGraph >
void GetAnf (const PGraph &Graph, TIntFltKdV &DistNbrsV, const int &MxDist, const bool &IsDir, const int &NApprox=32)
 
template<class PGraph >
double GetAnfEffDiam (const PGraph &Graph, const bool &IsDir, const double &Percentile, const int &NApprox)
 
template<class PGraph >
double GetAnfEffDiam (const PGraph &Graph, const int NRuns=1, int NApprox=-1)
 
template<class PGraph >
void TestAnf ()
 
template<class PGraph >
PNGraph GetBfsTree (const PGraph &Graph, const int &StartNId, const bool &FollowOut, const bool &FollowIn)
 Returns a directed Breadth-First-Search tree rooted at StartNId. More...
 
template<class PGraph >
int GetSubTreeSz (const PGraph &Graph, const int &StartNId, const bool &FollowOut, const bool &FollowIn, int &TreeSzX, int &TreeDepthX)
 Returns the BFS tree size (number of nodes) and depth (number of levels) by following in-links (parameter FollowIn = true) and/or out-links (parameter FollowOut = true) of node StartNId. More...
 
template<class PGraph >
int GetNodesAtHop (const PGraph &Graph, const int &StartNId, const int &Hop, TIntV &NIdV, const bool &IsDir=false)
 Finds IDs of all nodes that are at distance Hop from node StartNId. More...
 
template<class PGraph >
int GetNodesAtHops (const PGraph &Graph, const int &StartNId, TIntPrV &HopCntV, const bool &IsDir=false)
 Returns the number of nodes at each hop distance from the starting node StartNId. More...
 
template<class PGraph >
int GetShortPath (const PGraph &Graph, const int &SrcNId, const int &DstNId, const bool &IsDir=false)
 Returns the length of the shortest path from node SrcNId to node DstNId. More...
 
template<class PGraph >
int GetShortPath (const PGraph &Graph, const int &SrcNId, TIntH &NIdToDistH, const bool &IsDir=false, const int &MaxDist=TInt::Mx)
 Returns the length of the shortest path from node SrcNId to all other nodes in the network. More...
 
template<class PGraph >
int GetBfsFullDiam (const PGraph &Graph, const int &NTestNodes, const bool &IsDir=false)
 Returns the (approximation of the) Diameter (maximum shortest path length) of a graph (by performing BFS from NTestNodes random starting nodes). More...
 
template<class PGraph >
double GetBfsEffDiam (const PGraph &Graph, const int &NTestNodes, const bool &IsDir=false)
 Returns the (approximation of the) Effective Diameter (90-th percentile of the distribution of shortest path lengths) of a graph (by performing BFS from NTestNodes random starting nodes). More...
 
template<class PGraph >
double GetBfsEffDiam (const PGraph &Graph, const int &NTestNodes, const bool &IsDir, double &EffDiamX, int &FullDiamX)
 Returns the (approximation of the) Effective Diameter and the Diameter of a graph (by performing BFS from NTestNodes random starting nodes). More...
 
template<class PGraph >
double GetBfsEffDiam (const PGraph &Graph, const int &NTestNodes, const bool &IsDir, double &EffDiamX, int &FullDiamX, double &AvgSPLX)
 Returns the (approximation of the) Effective Diameter, the Diameter and the Average Shortest Path length in a graph (by performing BFS from NTestNodes random starting nodes). GetBfsEffDiam3. More...
 
template<class PGraph >
double GetBfsEffDiam (const PGraph &Graph, const int &NTestNodes, const TIntV &SubGraphNIdV, const bool &IsDir, double &EffDiamX, int &FullDiamX)
 Use the whole graph (all edges) to measure the shortest path lengths but only report the path lengths between nodes in the SubGraphNIdV. GetBfsEffDiam4. More...
 
double GetDegreeCentr (const PUNGraph &Graph, const int &NId)
 
double GetFarnessCentr (const PUNGraph &Graph, const int &NId)
 
double GetClosenessCentr (const PUNGraph &Graph, const int &NId)
 
void GetBetweennessCentr (const PUNGraph &Graph, const TIntV &BtwNIdV, TIntFltH &NodeBtwH, const bool &DoNodeCent, TIntPrFltH &EdgeBtwH, const bool &DoEdgeCent)
 
void GetBetweennessCentr (const PUNGraph &Graph, TIntFltH &NodeBtwH, const double &NodeFrac)
 
void GetBetweennessCentr (const PUNGraph &Graph, TIntPrFltH &EdgeBtwH, const double &NodeFrac)
 
void GetBetweennessCentr (const PUNGraph &Graph, TIntFltH &NodeBtwH, TIntPrFltH &EdgeBtwH, const double &NodeFrac)
 
void GetEigenVectorCentr (const PUNGraph &Graph, TIntFltH &NIdEigenH, const double &Eps, const int &MaxIter)
 
template<class PGraph >
int GetNodeEcc (const PGraph &Graph, const int &NId, const bool &IsDir=false)
 
template<class PGraph >
void GetPageRank (const PGraph &Graph, TIntFltH &PRankH, const double &C=0.85, const double &Eps=1e-4, const int &MaxIter=100)
 
template<class PGraph >
void GetHits (const PGraph &Graph, TIntFltH &NIdHubH, TIntFltH &NIdAuthH, const int &MaxIter=20)
 
double CommunityGirvanNewman (PUNGraph &Graph, TCnComV &CmtyV)
 
double Infomap (PUNGraph &Graph, TCnComV &CmtyV)
 
double CommunityCNM (const PUNGraph &Graph, TCnComV &CmtyV)
 
template<typename PGraph >
double GetModularity (const PGraph &G, const TIntV &NIdV, int GEdges=-1)
 
template<typename PGraph >
double GetModularity (const PGraph &G, const TCnComV &CmtyV, int GEdges=-1)
 
template<typename PGraph >
void GetEdgesInOut (const PGraph &Graph, const TIntV &NIdV, int &EdgesInX, int &EdgesOutX)
 
void GetBiConSzCnt (const PUNGraph &Graph, TIntPrV &SzCntV)
 Returns a distribution of bi-connected component sizes. More...
 
void GetBiCon (const PUNGraph &Graph, TCnComV &BiCnComV)
 Returns all bi-connected components of a Graph. More...
 
void GetArtPoints (const PUNGraph &Graph, TIntV &ArtNIdV)
 Returns articulation points of a Graph. More...
 
void GetEdgeBridges (const PUNGraph &Graph, TIntPrV &EdgeV)
 Returns bridge edges of a Graph. More...
 
void Get1CnComSzCnt (const PUNGraph &Graph, TIntPrV &SzCntV)
 Distribution of sizes of 1-components, maximal number of components that can be disconnected from the Graph by removing a single edge. More...
 
void Get1CnCom (const PUNGraph &Graph, TCnComV &Cn1ComV)
 Returns 1-components: maximal connected components of that can be disconnected from the Graph by removing a single edge. More...
 
PUNGraph GetMxBiCon (const PUNGraph &Graph, const bool &RenumberNodes=false)
 Returns a graph representing the largest bi-connected component on an undirected Graph. More...
 
template<class PGraph >
void GetNodeWcc (const PGraph &Graph, const int &NId, TIntV &CnCom)
 Returns (via output parameter CnCom) all nodes that are in the same connected component as node NId. More...
 
template<class PGraph >
bool IsConnected (const PGraph &Graph)
 Tests whether the Graph is (weakly) connected. More...
 
template<class PGraph >
bool IsWeaklyConn (const PGraph &Graph)
 Tests whether the Graph is weakly connected. More...
 
template<class PGraph >
void GetWccSzCnt (const PGraph &Graph, TIntPrV &WccSzCnt)
 Returns a distribution of weakly connected component sizes. More...
 
template<class PGraph >
void GetWccs (const PGraph &Graph, TCnComV &CnComV)
 Returns all weakly connected components in a Graph. More...
 
template<class PGraph >
void GetSccSzCnt (const PGraph &Graph, TIntPrV &SccSzCnt)
 Returns a distribution of strongly connected component sizes. More...
 
template<class PGraph >
void GetSccs (const PGraph &Graph, TCnComV &CnComV)
 Returns all strongly connected components in a Graph. More...
 
template<class PGraph >
double GetMxWccSz (const PGraph &Graph)
 Returns the fraction of nodes in the largest weakly connected component of a Graph. More...
 
template<class PGraph >
double GetMxSccSz (const PGraph &Graph)
 Returns the fraction of nodes in the largest strongly connected component of a Graph. More...
 
template<class PGraph >
PGraph GetMxWcc (const PGraph &Graph)
 Returns a graph representing the largest weakly connected component on an input Graph. More...
 
template<class PGraph >
PGraph GetMxScc (const PGraph &Graph)
 Returns a graph representing the largest strongly connected component on an input Graph. More...
 
template<class PGraph >
PGraph GetMxBiCon (const PGraph &Graph)
 Returns a graph representing the largest bi-connected component on an input Graph. More...
 
int IntFlowBiDBFS (const PNEANet &Net, const int &CapIndex, TIntV &Flow, TIntQ &FwdNodeQ, TIntH &PredEdgeH, TIntQ &BwdNodeQ, TIntH &SuccEdgeH, const int &SrcNId, const int &SnkNId)
 
int FindAugV (const PNEANet &Net, const int &CapIndex, TIntV &Flow, TIntQ &FwdNodeQ, TIntH &PredEdgeH, TIntQ &BwdNodeQ, TIntH &SuccEdgeH, TIntV &MidToSrcAugV, TIntV &MidToSnkAugV, const int &SrcNId, const int &SnkNId)
 Returns the amount the flow can be augmented over the paths, 0 if no path can be found. More...
 
int GetMaxFlowIntEK (PNEANet &Net, const int &SrcNId, const int &SnkNId)
 Returns the maximum integer valued flow in the network Net from source SrcNId to sink SnkNId. More...
 
void PushToOutNbr (TPRManager &PRM, const int &NId, const int &OutNId, const int &EId)
 Pushes flow from a node NId to a neighbor OutNId over edge EId. More...
 
void PushToInNbr (TPRManager &PRM, const int &NId, const int &InNId, const int &EId)
 Returns flow from a node NId to a neighbor InNId over edge EId. More...
 
void Relabel (TPRManager &PRM, const int &NId, const TNEANet::TNodeI &NI)
 Increases the label of a node NId to allow valid pushes to some neighbor. More...
 
int PushRelabel (TPRManager &PRM, const int &NId, const TNEANet::TNodeI &NI)
 Returns the ID of the neighbor that NId pushes to, -1 if no push was made. More...
 
void GlobalRelabel (PNEANet &Net, TPRManager &PRM, const int &SrcNId, const int &SnkNId)
 Implements the Global Relabeling heuristic. More...
 
int GetMaxFlowIntPR (PNEANet &Net, const int &SrcNId, const int &SnkNId)
 Returns the maximum integer valued flow in the network Net from source SrcNId to sink SnkNId. More...
 
const TStr CapAttrName ("capacity")
 
TStr GetFlagStr (const TGraphFlag &GraphFlag)
 Returns a string representation of a flag. More...
 
template<class PGraph >
void PrintInfo (const PGraph &Graph, const TStr &Desc="", const TStr &OutFNm="", const bool &Fast=true)
 Prints basic graph statistics. More...
 
template<class PGraph >
int64 GetTriads (const PGraph &Graph, int64 &ClosedTriadsX, int64 &OpenTriadsX, int SampleNodes)
 Computes the number of Closed and Open triads. More...
 
template<class PGraph >
int GetKCoreNodes (const PGraph &Graph, TIntPrV &CoreIdSzV)
 Returns the number of nodes in each core of order K (where K=0, 1, ...) More...
 
template<class PGraph >
int GetKCoreEdges (const PGraph &Graph, TIntPrV &CoreIdSzV)
 Returns the number of edges in each core of order K (where K=0, 1, ...) More...
 
PBPGraph GenRndBipart (const int &LeftNodes, const int &RightNodes, const int &Edges, TRnd &Rnd=TInt::Rnd)
 Generates a random bipartite graph. More...
 
PUNGraph GenRndDegK (const int &Nodes, const int &NodeDeg, const int &NSwitch=100, TRnd &Rnd=TInt::Rnd)
 Generates a random graph where each node has degree exactly NodeDeg. More...
 
PUNGraph GenRndPowerLaw (const int &Nodes, const double &PowerExp, const bool &ConfModel=true, TRnd &Rnd=TInt::Rnd)
 Generates a random scale-free graph with power-law degree distribution. More...
 
PUNGraph GenDegSeq (const TIntV &DegSeqV, TRnd &Rnd=TInt::Rnd)
 Generates a random graph with exact degree sequence. More...
 
PUNGraph GenConfModel (const TIntV &DegSeqV, TRnd &Rnd=TInt::Rnd)
 Generates a random undirect graph with a given degree sequence. More...
 
PUNGraph GenRewire (const PUNGraph &Graph, const int &NSwitch=100, TRnd &Rnd=TInt::Rnd)
 Rewire a random undirected graph. Keeps node degrees the same, but randomly rewires the edges. More...
 
PNGraph GenRewire (const PNGraph &Graph, const int &NSwitch=100, TRnd &Rnd=TInt::Rnd)
 Rewire a random directed graph. Keeps node degrees the same, but randomly rewires the edges. More...
 
PBPGraph GenRewire (const PBPGraph &Graph, const int &NSwitch=100, TRnd &Rnd=TInt::Rnd)
 Rewire a random bipartite graph. Keeps node degrees the same, but randomly rewires the edges. More...
 
PUNGraph GenPrefAttach (const int &Nodes, const int &NodeOutDeg, TRnd &Rnd=TInt::Rnd)
 Generates a power-law degree distribution using Barabasi-Albert model of scale-free graphs. More...
 
PUNGraph GenConfModel (const PUNGraph &G)
 Generate a random graph using (approximately) the same node degrees as in G using the configuration model. More...
 
PUNGraph GenGeoPrefAttach (const int &Nodes, const int &OutDeg, const double &Beta, TRnd &Rnd=TInt::Rnd)
 Generates a random scale-free graph using the Geometric Preferential model. More...
 
PUNGraph GenSmallWorld (const int &Nodes, const int &NodeOutDeg, const double &RewireProb, TRnd &Rnd=TInt::Rnd)
 Generates a randomly small-world graph using the Watts-Strogatz model. More...
 
PNGraph GenForestFire (const int &Nodes, const double &FwdProb, const double &BckProb)
 Generates a random Forest Fire, directed graph with given probabilities. More...
 
PNGraph GenCopyModel (const int &Nodes, const double &Beta, TRnd &Rnd=TInt::Rnd)
 Generates a random scale-free network using the Copying Model. More...
 
PNGraph GenRMat (const int &Nodes, const int &Edges, const double &A, const double &B, const double &C, TRnd &Rnd=TInt::Rnd)
 Generates a R-MAT graph using recursive descent into a 2x2 matrix [A,B; C, 1-(A+B+C)]. More...
 
PNGraph GenRMatEpinions ()
 Generates a R-Mat graph, with a synthetic copy of the Epinions social network. More...
 
template<class PGraph >
PGraph GenGrid (const int &Rows, const int &Cols, const bool &IsDir=true)
 Generates a 2D-grid graph of Rows rows and Cols columns. More...
 
template<class PGraph >
PGraph GenStar (const int &Nodes, const bool &IsDir=true)
 Generates a graph with star topology. Node id 0 is in the center and then links to all other nodes. More...
 
template<class PGraph >
PGraph GenCircle (const int &Nodes, const int &NodeOutDeg=1, const bool &IsDir=true)
 Generates a circle graph where every node creates out-links to NodeOutDeg forward nodes. More...
 
template<class PGraph >
PGraph GenFull (const int &Nodes)
 Generates a complete graph on Nodes nodes. Graph has no self-loops. More...
 
template<class PGraph >
PGraph GenTree (const int &Fanout, const int &Levels, const bool &IsDir=true, const bool &ChildPointsToParent=true)
 Generates a tree graph of Levels levels with every parent having Fanout children. More...
 
template<class PGraph >
PGraph GenBaraHierar (const int &Levels, const bool &IsDir=true)
 Generates a Ravasz-Barabasi deterministic scale-free graph. More...
 
template<class PGraph >
PGraph GenRndGnm (const int &Nodes, const int &Edges, const bool &IsDir=true, TRnd &Rnd=TInt::Rnd)
 Generates an Erdos-Renyi random graph. More...
 
PNGraph LoadDyNet (const TStr &FNm)
 For more info see ORA Network Analysis Data (http://www.casos.cs.cmu.edu/computational_tools/data2.php) More...
 
TVec< PNGraphLoadDyNetGraphV (const TStr &FNm)
 For more info see ORA Network Analysis Data (http://www.casos.cs.cmu.edu/computational_tools/data2.php) More...
 
template<class PGraph >
PGraph LoadEdgeList (const TStr &InFNm, const int &SrcColId=0, const int &DstColId=1)
 Loads a (directed, undirected or multi) graph from a text file InFNm with 1 edge per line (whitespace separated columns, integer node ids). More...
 
template<class PGraph >
PGraph LoadEdgeList (const TStr &InFNm, const int &SrcColId, const int &DstColId, const char &Separator)
 Loads a (directed, undirected or multi) graph from a text file InFNm with 1 edge per line ('Separator' separated columns, integer node ids). More...
 
template<class PGraph >
PGraph LoadEdgeListStr (const TStr &InFNm, const int &SrcColId=0, const int &DstColId=1)
 Loads a (directed, undirected or multi) graph from a text file InFNm with 1 edge per line (whitespace separated columns, arbitrary string node ids). More...
 
template<class PGraph >
PGraph LoadEdgeListStr (const TStr &InFNm, const int &SrcColId, const int &DstColId, TStrHash< TInt > &StrToNIdH)
 Loads a (directed, undirected or multi) graph from a text file InFNm with 1 edge per line (whitespace separated columns, arbitrary string node ids). More...
 
template<class PGraph >
PGraph LoadConnList (const TStr &InFNm)
 Loads a (directed, undirected or multi) graph from a text file InFNm with 1 node and all its edges in a single line. More...
 
template<class PGraph >
PGraph LoadConnListStr (const TStr &InFNm, TStrHash< TInt > &StrToNIdH)
 Loads a (directed, undirected or multi) graph from a text file InFNm with 1 node and all its edges in a single line. More...
 
template<class PGraph >
PGraph LoadPajek (const TStr &InFNm)
 Loads a (directed, undirected or multi) graph from Pajek .PAJ format file. More...
 
template<class PGraph >
void SaveEdgeList (const PGraph &Graph, const TStr &OutFNm, const TStr &Desc=TStr())
 Saves a graph into a text file. Each line contains two columns and encodes a single edge: <source node="" id>=""><tab><destination node="" id>=""> More...
 
template<class PGraph >
void SavePajek (const PGraph &Graph, const TStr &OutFNm)
 Saves a graph in a Pajek .NET format. More...
 
template<class PGraph >
void SavePajek (const PGraph &Graph, const TStr &OutFNm, const TIntStrH &NIdColorH)
 Saves a graph in a Pajek .NET format. More...
 
template<class PGraph >
void SavePajek (const PGraph &Graph, const TStr &OutFNm, const TIntStrH &NIdColorH, const TIntStrH &NIdLabelH)
 Saves a graph in a Pajek .NET format. More...
 
template<class PGraph >
void SavePajek (const PGraph &Graph, const TStr &OutFNm, const TIntStrH &NIdColorH, const TIntStrH &NIdLabelH, const TIntStrH &EIdColorH)
 Saves a graph in a Pajek .NET format. More...
 
template<class PGraph >
void SaveMatlabSparseMtx (const PGraph &Graph, const TStr &OutFNm)
 Saves a graph in a MATLAB sparse matrix format. More...
 
template<class PGraph >
void SaveGViz (const PGraph &Graph, const TStr &OutFNm, const TStr &Desc=TStr(), const bool &NodeLabels=false, const TIntStrH &NIdColorH=TIntStrH())
 Save a graph in GraphVizp .DOT format. More...
 
template<class PGraph >
void SaveGViz (const PGraph &Graph, const TStr &OutFNm, const TStr &Desc, const TIntStrH &NIdLabelH)
 Save a graph in GraphVizp .DOT format. More...
 
void SetAllInvertSign (TFltV &ValV, const double &Val)
 
bool IsAllValVNeg (TFltV &ValV, const bool &InvertSign)
 
void GetSngVals (const PNGraph &Graph, const int &SngVals, TFltV &SngValV)
 Computes largest SngVals singular values of the adjacency matrix representing a directed Graph. More...
 
void GetSngVec (const PNGraph &Graph, TFltV &LeftSV, TFltV &RightSV)
 Computes the leading left and right singular vector of the adjacency matrix representing a directed Graph. More...
 
void GetSngVec (const PNGraph &Graph, const int &SngVecs, TFltV &SngValV, TVec< TFltV > &LeftSV, TVec< TFltV > &RightSV)
 
void GetEigVals (const PUNGraph &Graph, const int &EigVals, TFltV &EigValV)
 Computes top EigVals eigenvalues of the adjacency matrix representing a given undirected Graph. More...
 
void GetEigVec (const PUNGraph &Graph, TFltV &EigVecV)
 Computes the leading eigenvector of the adjacency matrix representing a given undirected Graph. More...
 
void GetEigVec (const PUNGraph &Graph, const int &EigVecs, TFltV &EigValV, TVec< TFltV > &EigVecV)
 Computes top EigVecs eigenvalues and eigenvectors of the adjacency matrix representing a given undirected Graph. More...
 
void GetInvParticipRat (const PUNGraph &Graph, int MaxEigVecs, int TimeLimit, TFltPrV &EigValIprV)
 
template<class PGraph >
void DrawGViz (const PGraph &Graph, const TGVizLayout &Layout, const TStr &PltFNm, const TStr &Desc=TStr(), const bool &NodeLabels=false, const TIntStrH &NIdColorH=TIntStrH())
 Draws a given Graph using a selected GraphViz Layout engine with nodes colored. More...
 
template<class PGraph >
void DrawGViz (const PGraph &Graph, const TGVizLayout &Layout, const TStr &PltFNm, const TStr &Desc, const TIntStrH &NodeLabelH)
 Draws a given Graph using a selected GraphViz Layout engine with nodes labeled. More...
 
template<class PGraph >
PGraph GetKCore (const PGraph &Graph, const int &K)
 
void PlotEigValRank (const PUNGraph &Graph, const int &EigVals, const TStr &FNmPref, TStr DescStr=TStr())
 Plots the eigen-value rank distribution of the Graph adjacency matrix. Plots first EigVals eigenvalues. More...
 
void PlotEigValDistr (const PUNGraph &Graph, const int &EigVals, const TStr &FNmPref, TStr DescStr=TStr())
 Plots the distribution of components of the leading eigen-vector of the Graph adjacency matrix. Plots first EigVals values. More...
 
void PlotInvParticipRat (const PUNGraph &Graph, const int &MaxEigVecs, const int &TimeLimit, const TStr &FNmPref, TStr DescStr)
 
void PlotSngValRank (const PNGraph &Graph, const int &SngVals, const TStr &FNmPref, TStr DescStr=TStr())
 Plots the rank distribution of singular values of the Graph adjacency matrix. Plots first SngVals values. More...
 
void PlotSngValDistr (const PNGraph &Graph, const int &SngVals, const TStr &FNmPref, TStr DescStr=TStr())
 Plots the rank distribution of singular values of the Graph adjacency matrix. Plots first SngVals values. More...
 
void PlotSngVec (const PNGraph &Graph, const TStr &FNmPref, TStr DescStr=TStr())
 Plots the distribution of the values of the leading left singular vector of the Graph adjacency matrix. Plots first SngVals values. More...
 
template<class PGraph >
void PlotInDegDistr (const PGraph &Graph, const TStr &FNmPref, TStr DescStr=TStr(), const bool &PlotCCdf=false, const bool &PowerFit=false)
 
template<class PGraph >
void PlotOutDegDistr (const PGraph &Graph, const TStr &FNmPref, TStr DescStr=TStr(), const bool &PlotCCdf=false, const bool &PowerFit=false)
 
template<class PGraph >
void PlotWccDistr (const PGraph &Graph, const TStr &FNmPref, TStr DescStr=TStr())
 Plots the distribution of sizes of weakly connected components of a Graph. More...
 
template<class PGraph >
void PlotSccDistr (const PGraph &Graph, const TStr &FNmPref, TStr DescStr=TStr())
 Plots the distribution of sizes of strongly connected components of a Graph. More...
 
template<class PGraph >
void PlotClustCf (const PGraph &Graph, const TStr &FNmPref, TStr DescStr=TStr())
 Plots the distribution of clustering coefficient of a Graph. More...
 
template<class PGraph >
void PlotHops (const PGraph &Graph, const TStr &FNmPref, TStr DescStr=TStr(), const bool &IsDir=false, const int &NApprox=32)
 
template<class PGraph >
void PlotShortPathDistr (const PGraph &Graph, const TStr &FNmPref, TStr DescStr=TStr(), int TestNodes=TInt::Mx)
 Plots the distribution of the shortest path lengths of a Graph. Implementation is based on BFS. More...
 
template<class PGraph >
void PlotKCoreNodes (const PGraph &Graph, const TStr &FNmPref, TStr DescStr=TStr())
 Plots the k-Core node-size distribution: Core k vs. number of nodes in k-core. More...
 
template<class PGraph >
void PlotKCoreEdges (const PGraph &Graph, const TStr &FNmPref, TStr DescStr=TStr())
 Plots the k-Core edge-size distribution: Core k vs. number of edges in k-core. More...
 
PUNGraph GetSubGraph (const PUNGraph &Graph, const TIntV &NIdV, const bool &RenumberNodes=false)
 Returns an induced subgraph of an undirected graph Graph with NIdV nodes with an optional node renumbering. More...
 
PNGraph GetSubGraph (const PNGraph &Graph, const TIntV &NIdV, const bool &RenumberNodes)
 
PUNGraph GetEgonet (const PUNGraph &Graph, const int CtrNId, int &ArndEdges)
 Returns the egonet of node CtrNId as center in undirected graph Graph. And returns number of edges around the egonet. More...
 
PNGraph GetEgonet (const PNGraph &Graph, const int CtrNId, int &InEdges, int &OutEdges)
 Returns the egonet of node CtrNId as center in directed graph Graph. And returns number of edges go in and out the egonet. More...
 
template<class PGraph >
PGraph GetSubGraph (const PGraph &Graph, const TIntV &NIdV)
 Returns an induced subgraph of graph Graph with NIdV nodes. More...
 
template<class PGraph >
PGraph GetESubGraph (const PGraph &Graph, const TIntV &EIdV)
 Returns a subgraph of graph Graph with EIdV edges. More...
 
template<class PGraph >
PGraph GetESubGraph (const PGraph &Graph, const TIntPrV &EdgeV)
 
template<class PGraph , class TEdgeDat >
PGraph GetEDatSubGraph (const PGraph &Graph, const TEdgeDat &EDat, const int &Cmp)
 Returns a subgraph of graph Graph with edges where edge data matches the parameters. More...
 
template<class PGraph , class TEdgeDat >
PGraph GetEDatSubGraph (const PGraph &Graph, const TIntV &NIdV, const TEdgeDat &EDat, const int &Cmp)
 Returns a subgraph of graph Graph with NIdV nodes and edges where edge data matches the parameters. More...
 
template<class POutGraph , class PInGraph >
POutGraph ConvertGraph (const PInGraph &InGraph, const bool &RenumberNodes=false)
 Performs conversion of graph InGraph with an optional node renumbering. More...
 
template<class POutGraph , class PInGraph >
POutGraph ConvertSubGraph (const PInGraph &InGraph, const TIntV &NIdV, const bool &RenumberNodes=false)
 Returns an induced subgraph of graph InGraph with NIdV nodes with an optional node renumbering. More...
 
template<class POutGraph , class PInGraph >
POutGraph ConvertESubGraph (const PInGraph &InGraph, const TIntV &EIdV, const bool &RenumberNodes=false)
 Returns a subgraph of graph InGraph with EIdV edges with an optional node renumbering. More...
 
template<class PGraph >
PGraph GetRndSubGraph (const PGraph &Graph, const int &NNodes)
 Returns an induced random subgraph of graph Graph with NNodes nodes. More...
 
template<class PGraph >
PGraph GetRndESubGraph (const PGraph &Graph, const int &NEdges)
 Returns a random subgraph of graph Graph with NEdges edges. More...
 
template<class PGraph >
double GetClustCf (const PGraph &Graph, int SampleNodes=-1)
 Computes the average clustering coefficient as defined in Watts and Strogatz, Collective dynamics of 'small-world' networks. More...
 
template<class PGraph >
double GetClustCf (const PGraph &Graph, TFltPrV &DegToCCfV, int SampleNodes=-1)
 Computes the distribution of average clustering coefficient. More...
 
template<class PGraph >
double GetClustCf (const PGraph &Graph, TFltPrV &DegToCCfV, int64 &ClosedTriadsX, int64 &OpenTriadsX, int SampleNodes=-1)
 Computes the distribution of average clustering coefficient as well as the number of open and closed triads in the graph. More...
 
template<class PGraph >
double GetNodeClustCf (const PGraph &Graph, const int &NId)
 Returns clustering coefficient of a particular node. More...
 
template<class PGraph >
void GetNodeClustCf (const PGraph &Graph, TIntFltH &NIdCCfH)
 Computes clustering coefficient of each node of the Graph. More...
 
template<class PGraph >
int64 GetTriads (const PGraph &Graph, int SampleNodes=-1)
 Returns the number of triangles in a graph. More...
 
template<class PGraph >
void GetTriads (const PGraph &Graph, TIntTrV &NIdCOTriadV, int SampleNodes=-1)
 Computes the number of open and close triads for every node of the network. More...
 
template<class PGraph >
int GetTriadEdges (const PGraph &Graph, int SampleEdges=-1)
 Counts the number of edges that participate in at least one triad. More...
 
template<class PGraph >
int GetNodeTriads (const PGraph &Graph, const int &NId)
 Returns the number of undirected triads a node NId participates in. More...
 
template<class PGraph >
int GetNodeTriads (const PGraph &Graph, const int &NId, int &ClosedNTriadsX, int &OpenNTriadsX)
 Returns number of Open and Closed triads a node NId participates in. More...
 
template<class PGraph >
int GetNodeTriads (const PGraph &Graph, const int &NId, const TIntSet &GroupSet, int &InGroupEdgesX, int &InOutGroupEdgesX, int &OutGroupEdgesX)
 Returns the number of triads between a node NId and a subset of its neighbors GroupSet. More...
 
template<class PGraph >
void GetTriadParticip (const PGraph &Graph, TIntPrV &TriadCntV)
 Triangle Participation Ratio: For each node counts how many triangles it participates in and then returns a set of pairs (number of triangles, number of such nodes). More...
 
template<class PGraph >
int GetCmnNbrs (const PGraph &Graph, const int &NId1, const int &NId2)
 Returns a number of shared neighbors between a pair of nodes NId1 and NId2. More...
 
template<class PGraph >
int GetCmnNbrs (const PGraph &Graph, const int &NId1, const int &NId2, TIntV &NbrV)
 Returns the shared neighbors between a pair of nodes NId1 and NId2. More...
 
template<class PGraph >
int GetLen2Paths (const PGraph &Graph, const int &NId1, const int &NId2)
 Returns the number of length 2 directed paths between a pair of nodes NId1, NId2 (NId1 –> U –> NId2). More...
 
template<class PGraph >
int GetLen2Paths (const PGraph &Graph, const int &NId1, const int &NId2, TIntV &NbrV)
 Returns the 2 directed paths between a pair of nodes NId1, NId2 (NId1 –> U –> NId2). More...
 
template<>
int GetCmnNbrs< PUNGraph > (const PUNGraph &Graph, const int &NId1, const int &NId2, TIntV &NbrV)
 

Detailed Description

Main namespace for all the Snap global entities.

Function Documentation

template<class PGraph >
void TSnap::AddSelfEdges ( const PGraph &  Graph)

Adds a self-edge to every node in the graph.

Definition at line 369 of file alg.h.

369  {
370  TIntV EdgeV;
371  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
372  const int NId = NI.GetId();
373  if (! Graph->IsEdge(NId, NId)) {
374  EdgeV.Add(NId);
375  }
376  }
377  for (int i = 0; i < EdgeV.Len(); i++) {
378  Graph->AddEdge(EdgeV[i], EdgeV[i]);
379  }
380 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
const TStr TSnap::CapAttrName ( "capacity"  )
template<class PGraph >
int TSnap::CntDegNodes ( const PGraph &  Graph,
const int &  NodeDeg 
)

Returns the number of nodes with degree NodeDeg.

Definition at line 105 of file alg.h.

105  {
106  int Cnt = 0;
107  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
108  if (NI.GetDeg() == NodeDeg) Cnt++;
109  }
110  return Cnt;
111 }
template<class PGraph >
int TSnap::CntEdgesToSet ( const PGraph &  Graph,
const int &  NId,
const TIntSet NodeSet 
)

Returns the number of nodes in NodeSet that have an edge to the node NId.

Definition at line 123 of file alg.h.

123  {
124  if (! Graph->IsNode(NId)) { return 0; }
125  const bool IsDir = Graph->HasFlag(gfDirected);
126  const typename PGraph::TObj::TNodeI NI = Graph->GetNI(NId);
127  if (! IsDir) {
128  int EdgesToSet = 0;
129  for (int e = 0; e < NI.GetOutDeg(); e++) {
130  if (NodeSet.IsKey(NI.GetOutNId(e))) { EdgesToSet++; } }
131  return EdgesToSet;
132  } else {
133  TIntSet Set(NI.GetDeg());
134  for (int e = 0; e < NI.GetOutDeg(); e++) {
135  if (NodeSet.IsKey(NI.GetOutNId(e))) { Set.AddKey(NI.GetOutNId(e)); } }
136  for (int e = 0; e < NI.GetInDeg(); e++) {
137  if (NodeSet.IsKey(NI.GetInNId(e))) { Set.AddKey(NI.GetInNId(e)); } }
138  return Set.Len();
139  }
140 }
bool IsKey(const TKey &Key) const
Definition: shash.h:1142
int AddKey(const TKey &Key)
Definition: shash.h:1248
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
template<class PGraph >
int TSnap::CntInDegNodes ( const PGraph &  Graph,
const int &  NodeInDeg 
)

Returns the number of nodes with in-degree NodeInDeg.

Definition at line 87 of file alg.h.

87  {
88  int Cnt = 0;
89  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
90  if (NI.GetInDeg() == NodeInDeg) Cnt++;
91  }
92  return Cnt;
93 }
template<class PGraph >
int TSnap::CntNonZNodes ( const PGraph &  Graph)

Returns the number of nodes with degree greater than 0.

Definition at line 114 of file alg.h.

114  {
115  int Cnt = 0;
116  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
117  if (NI.GetDeg() > 0) Cnt++;
118  }
119  return Cnt;
120 }
template<class PGraph >
int TSnap::CntOutDegNodes ( const PGraph &  Graph,
const int &  NodeOutDeg 
)

Returns the number of nodes with out-degree NodeOutDeg.

Definition at line 96 of file alg.h.

96  {
97  int Cnt = 0;
98  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
99  if (NI.GetOutDeg() == NodeOutDeg) Cnt++;
100  }
101  return Cnt;
102 }
template<class PGraph >
int TSnap::CntSelfEdges ( const PGraph &  Graph)

Counts the number fo of self-edges in a graph. Edge (u,u) is a self-edge.

Definition at line 334 of file alg.h.

334  {
335  int Cnt = 0;
336  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
337  for (int e = 0; e < NI.GetOutDeg(); e++) {
338  if (NI.GetId() == NI.GetOutNId(e)) { Cnt++; }
339  }
340  }
341  return Cnt;
342 }
template<class PGraph >
int TSnap::CntUniqBiDirEdges ( const PGraph &  Graph)

Counts unique bidirectional edges in the graph Graph. Edge is bidirectional is there exist directed edges in both directions: (u,v) and (v,u)

Definition at line 316 of file alg.h.

316  {
317  if (! Graph->HasFlag(gfDirected)) { // graph is undirected
318  return CntUniqUndirEdges(Graph); // then every edge is bi-directional
319  }
320  TIntSet NbrSet;
321  int Cnt = 0;
322  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
323  const int SrcId = NI.GetId();
324  for (int e = 0; e < NI.GetOutDeg(); e++) {
325  const int DstId = NI.GetOutNId(e);
326  if (DstId <= SrcId) { continue; } // count each un-dir edge only once
327  if (Graph->IsEdge(DstId, SrcId)) { Cnt++; }
328  }
329  }
330  return Cnt;
331 }
int CntUniqUndirEdges(const PGraph &Graph)
Counts unique undirected edges in the graph Graph. Nodes (u,v)<.
Definition: alg.h:279
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
template<class PGraph >
int TSnap::CntUniqDirEdges ( const PGraph &  Graph)

Counts unique directed edges in the graph Graph. Nodes (u,v)<.

> (where <code>u!=v</code>) are connected via an directted edge if there exists a directed edge from node \c u to node \c v.

Definition at line 301 of file alg.h.

301  {
302  TIntSet NbrSet;
303  int Cnt = 0;
304  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
305  NbrSet.Clr(false);
306  for (int e = 0; e < NI.GetOutDeg(); e++) { // unique out-neighbors of a node
307  if (NI.GetOutNId(e) != NI.GetId()) { // skip self-edges
308  NbrSet.AddKey(NI.GetOutNId(e)); }
309  }
310  Cnt += NbrSet.Len();
311  }
312  return Cnt;
313 }
void Clr(const bool &DoDel=true, const int &NoDelLim=-1)
Definition: shash.h:1237
int AddKey(const TKey &Key)
Definition: shash.h:1248
int Len() const
Definition: shash.h:1115
template<class PGraph >
int TSnap::CntUniqUndirEdges ( const PGraph &  Graph)

Counts unique undirected edges in the graph Graph. Nodes (u,v)<.

> (where <code>u!=v</code>) are connected via an undirected edge if there exists an edge in either direction <code>(u,v)</code> or <code>(v,u)</code>.

Definition at line 279 of file alg.h.

279  {
280  TIntSet NbrSet;
281  TIntSet SelfNbrSet;
282  int Cnt = 0;
283  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
284  NbrSet.Clr(false);
285  for (int e = 0; e < NI.GetDeg(); e++) { // unique neighbors of a node
286  const int NbrId = NI.GetNbrNId(e);
287  if (NbrId == NI.GetId()) { // remember self-edges
288  SelfNbrSet.AddKey(NbrId);
289  } else {
290  NbrSet.AddKey(NbrId);
291  }
292  }
293  Cnt += NbrSet.Len();
294  }
295  // OP RS 2014/06/11 self-edges are currently not used
296  //return Cnt / 2 + SelfNbrSet.Len();
297  return Cnt / 2;
298 }
void Clr(const bool &DoDel=true, const int &NoDelLim=-1)
Definition: shash.h:1237
int AddKey(const TKey &Key)
Definition: shash.h:1248
int Len() const
Definition: shash.h:1115
double TSnap::CommunityCNM ( const PUNGraph Graph,
TCnComV CmtyV 
)

Clauset-Newman-Moore community detection method for large networks. At every step of the algorithm two communities that contribute maximum positive value to global modularity are merged. See: Finding community structure in very large networks, A. Clauset, M.E.J. Newman, C. Moore, 2004

Definition at line 304 of file cmty.cpp.

304  {
305  return TSnapDetail::TCNMQMatrix::CmtyCMN(Graph, CmtyV);
306 }
double TSnap::CommunityGirvanNewman ( PUNGraph Graph,
TCnComV CmtyV 
)

Girvan-Newman community detection algorithm based on Betweenness centrality. See: Girvan M. and Newman M. E. J., Community structure in social and biological networks, Proc. Natl. Acad. Sci. USA 99, 7821-7826 (2002)

Definition at line 98 of file cmty.cpp.

98  {
99  TIntH OutDegH;
100  const int NEdges = Graph->GetEdges();
101  for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
102  OutDegH.AddDat(NI.GetId(), NI.GetOutDeg());
103  }
104  double BestQ = -1; // modularity
105  TCnComV CurCmtyV;
106  CmtyV.Clr();
107  TIntV Cmty1, Cmty2;
108  while (true) {
109  TSnapDetail::CmtyGirvanNewmanStep(Graph, Cmty1, Cmty2);
110  const double Q = TSnapDetail::_GirvanNewmanGetModularity(Graph, OutDegH, NEdges, CurCmtyV);
111  //printf("current modularity: %f\n", Q);
112  if (Q > BestQ) {
113  BestQ = Q;
114  CmtyV.Swap(CurCmtyV);
115  }
116  if (Cmty1.Len()==0 || Cmty2.Len() == 0) { break; }
117  }
118  return BestQ;
119 }
int GetEdges() const
Returns the number of edges in the graph.
Definition: graph.cpp:74
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
Node iterator. Only forward iteration (operator++) is supported.
Definition: graph.h:63
void Swap(TVec< TVal, TSizeTy > &Vec)
Swaps the contents of the vector with Vec.
Definition: ds.h:1011
void Clr(const bool &DoDel=true, const TSizeTy &NoDelLim=-1)
Clears the contents of the vector.
Definition: ds.h:953
TNodeI EndNI() const
Returns an iterator referring to the past-the-end node in the graph.
Definition: graph.h:203
TNodeI BegNI() const
Returns an iterator referring to the first node in the graph.
Definition: graph.h:201
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
double _GirvanNewmanGetModularity(const PUNGraph &G, const TIntH &OutDegH, const int &OrigEdges, TCnComV &CnComV)
Definition: cmty.cpp:36
void CmtyGirvanNewmanStep(PUNGraph &Graph, TIntV &Cmty1, TIntV &Cmty2)
A single step of Girvan-Newman clustering procedure.
Definition: cmty.cpp:14
template<class POutGraph , class PInGraph >
POutGraph TSnap::ConvertESubGraph ( const PInGraph &  InGraph,
const TIntV EIdV,
const bool &  RenumberNodes = false 
)

Returns a subgraph of graph InGraph with EIdV edges with an optional node renumbering.

Creates a subgraph of the input graph InGraph on EIdV edges and returns an output graph. Input and output graphs can have different types. Node and edge data is not copied, but it is shared by input and output graphs.

Parameter RenumberNodes determines, whether the node IDs are preserved or not. If RenumberNodes is false, then nodes in the resulting graph have the same node IDs as nodes in InGraph. If RenumberNodes is true, then nodes in the resulting graph are renumbered sequentially from 0 to N-1. By default, the nodes are not renumbered.

Definition at line 403 of file subgraph.h.

403  {
404  CAssert(HasGraphFlag(typename PInGraph::TObj, gfMultiGraph)); // needs to have explicit edges
405  POutGraph NewGraphPt = POutGraph::TObj::New();
406  typename POutGraph::TObj& NewGraph = *NewGraphPt;
407  NewGraph.Reserve(-1, EIdV.Len());
408  if (! RenumberNodes) {
409  for (int edge = 0; edge < EIdV.Len(); edge++) {
410  const int EId = EIdV[edge];
411  IAssert(InGraph->IsEdge(EId));
412  const typename PInGraph::TObj::TEdgeI EI = InGraph->GetEI(EId);
413  const int SrcNId = EI.GetSrcNId();
414  const int DstNId = EI.GetDstNId();
415  if (! NewGraph.IsNode(SrcNId)) {
416  NewGraph.AddNode(SrcNId); }
417  if (! NewGraph.IsNode(DstNId)) {
418  NewGraph.AddNode(DstNId); }
419  NewGraph.AddEdge(SrcNId, DstNId);
420  }
421  } else {
422  // renumber nodes so that node ids are 0...N-1
423  TIntSet NIdSet(InGraph->GetNodes());
424  for (int edge = 0; edge < EIdV.Len(); edge++) {
425  const int EId = EIdV[edge];
426  IAssert(InGraph->IsEdge(EId));
427  const typename PInGraph::TObj::TEdgeI EI = InGraph->GetEI(EId);
428  const int SrcNId = NIdSet.AddKey(EI.GetSrcNId()); // map node ids
429  const int DstNId = NIdSet.AddKey(EI.GetDstNId());
430  if (! NewGraph.IsNode(SrcNId)) {
431  NewGraph.AddNode(SrcNId); }
432  if (! NewGraph.IsNode(DstNId)) {
433  NewGraph.AddNode(DstNId); }
434  NewGraph.AddEdge(SrcNId, DstNId);
435  }
436  }
437  return NewGraphPt;
438 }
#define IAssert(Cond)
Definition: bd.h:262
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
have explicit edges (multigraph): TNEGraph, TNodeEdgeNet
Definition: gbase.h:14
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
#define CAssert(Cond)
Definition: bd.h:302
template<class POutGraph , class PInGraph >
POutGraph TSnap::ConvertGraph ( const PInGraph &  InGraph,
const bool &  RenumberNodes = false 
)

Performs conversion of graph InGraph with an optional node renumbering.

Takes an input graph InGraph and returns an output graph. Input and output graphs can have different types. Node and edge data is not copied, but it is shared by input and output graphs.

Parameter RenumberNodes determines, whether the node IDs are preserved or not. If RenumberNodes is false, then nodes in the resulting graph have the same node IDs as nodes in InGraph. If RenumberNodes is true, then nodes in the resulting graph are renumbered sequentially from 0 to N-1. By default, the nodes are not renumbered.

Definition at line 288 of file subgraph.h.

288  {
289  POutGraph OutGraphPt = POutGraph::TObj::New();
290  typename POutGraph::TObj& OutGraph = *OutGraphPt;
291  OutGraph.Reserve(InGraph->GetNodes(), InGraph->GetEdges());
292  if (! RenumberNodes) {
293  for (typename PInGraph::TObj::TNodeI NI = InGraph->BegNI(); NI < InGraph->EndNI(); NI++) {
294  OutGraph.AddNode(NI.GetId());
295  }
296  for (typename PInGraph::TObj::TEdgeI EI = InGraph->BegEI(); EI < InGraph->EndEI(); EI++) {
297  OutGraph.AddEdge(EI.GetSrcNId(), EI.GetDstNId());
298  if (! HasGraphFlag(typename PInGraph::TObj, gfDirected) && HasGraphFlag(typename POutGraph::TObj, gfDirected)) { // add edge in the other direction
299  OutGraph.AddEdge(EI.GetDstNId(), EI.GetSrcNId()); }
300  }
301  } else { // renumber nodes so that node ids are 0...N-1
302  TIntSet NIdSet(InGraph->GetNodes());
303  for (typename PInGraph::TObj::TNodeI NI = InGraph->BegNI(); NI < InGraph->EndNI(); NI++) {
304  const int nid = NIdSet.AddKey(NI.GetId());
305  OutGraph.AddNode(nid);
306  }
307  for (typename PInGraph::TObj::TEdgeI EI = InGraph->BegEI(); EI < InGraph->EndEI(); EI++) {
308  const int SrcNId = NIdSet.GetKeyId(EI.GetSrcNId());
309  const int DstNId = NIdSet.GetKeyId(EI.GetDstNId());
310  OutGraph.AddEdge(SrcNId, DstNId);
311  if (! HasGraphFlag(typename PInGraph::TObj, gfDirected) && HasGraphFlag(typename POutGraph::TObj, gfDirected)) {
312  OutGraph.AddEdge(DstNId, SrcNId); }
313  }
314  }
315  //OutGraph.Defrag();
316  return OutGraphPt;
317 }
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
int AddKey(const TKey &Key)
Definition: shash.h:1248
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
template<class POutGraph , class PInGraph >
POutGraph TSnap::ConvertSubGraph ( const PInGraph &  InGraph,
const TIntV NIdV,
const bool &  RenumberNodes = false 
)

Returns an induced subgraph of graph InGraph with NIdV nodes with an optional node renumbering.

Creates a subgraph of the input graph InGraph on NIdV nodes and returns an output graph. Input and output graphs can have different types. Node and edge data is not copied, but it is shared by input and output graphs.

Parameter RenumberNodes determines, whether the node IDs are preserved or not. If RenumberNodes is false, then nodes in the resulting graph have the same node IDs as nodes in InGraph. If RenumberNodes is true, then nodes in the resulting graph are renumbered sequentially from 0 to N-1. By default, the nodes are not renumbered.

Definition at line 398 of file subgraph.h.

398  {
399  return TSnapDetail::TConvertSubGraph<POutGraph, PInGraph, HasGraphFlag(typename PInGraph::TObj, gfMultiGraph)>::Do(InGraph, NIdV, RenumberNodes);
400 }
template<class PGraph >
void TSnap::DelDegKNodes ( PGraph &  Graph,
const int &  OutDegK,
const int &  InDegK 
)

Removes all the node of out-degree OutDegK and all the nodes of in-degree InDegK from the graph.

Definition at line 445 of file alg.h.

445  {
446  TIntV DelNIdV;
447  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
448  if (NI.GetOutDeg() == OutDegK || NI.GetInDeg() == InDegK) {
449  DelNIdV.Add(NI.GetId());
450  }
451  }
452  for (int i = 0; i < DelNIdV.Len(); i++) {
453  Graph->DelNode(DelNIdV[i]);
454  }
455 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph >
void TSnap::DelNodes ( PGraph &  Graph,
const TIntV NIdV 
)

Removes nodes with ids stored in NIdV from the graph.

Definition at line 425 of file alg.h.

425  {
426  for (int n = 0; n < NIdV.Len(); n++) {
427  Graph->DelNode(NIdV[n]);
428  }
429 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
template<class PGraph >
void TSnap::DelSelfEdges ( const PGraph &  Graph)

Removes all the self-edges from the graph.

Definition at line 419 of file alg.h.

419  {
420  TSnapDetail::TDelSelfEdges<PGraph, HasGraphFlag(typename PGraph::TObj, gfMultiGraph)>
421  ::Do(Graph);
422 }
template<class PGraph >
void TSnap::DelZeroDegNodes ( PGraph &  Graph)

Removes all the zero-degree nodes, that isolated nodes, from the graph.

Definition at line 432 of file alg.h.

432  {
433  TIntV DelNIdV;
434  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
435  if (NI.GetDeg() == 0) {
436  DelNIdV.Add(NI.GetId());
437  }
438  }
439  for (int i = 0; i < DelNIdV.Len(); i++) {
440  Graph->DelNode(DelNIdV[i]);
441  }
442 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph >
void TSnap::DrawGViz ( const PGraph &  Graph,
const TGVizLayout Layout,
const TStr PltFNm,
const TStr Desc = TStr(),
const bool &  NodeLabels = false,
const TIntStrH NIdColorH = TIntStrH() 
)

Draws a given Graph using a selected GraphViz Layout engine with nodes colored.

Useful for drawing small (<100 node) graphs.

Parameters
PltFNmOutput filename (extension .ps, .png, .gif) determines the output format.
NIdColorHMaps node ids to node colors (see GraphViz documentation for more details).

Definition at line 34 of file gviz.h.

34  {
35  const TStr Ext = PltFNm.GetFExt();
36  const TStr GraphFNm = PltFNm.GetSubStr(0, PltFNm.Len()-Ext.Len()) + "dot";
37  SaveGViz(Graph, GraphFNm, Desc, NodeLabels, NIdColorH);
38  TSnap::TSnapDetail::GVizDoLayout(GraphFNm, PltFNm, Layout);
39 }
int Len() const
Definition: dt.h:487
void SaveGViz(const PGraph &Graph, const TStr &OutFNm, const TStr &Desc=TStr(), const bool &NodeLabels=false, const TIntStrH &NIdColorH=TIntStrH())
Save a graph in GraphVizp .DOT format.
Definition: gio.h:369
TStr GetSubStr(const int &BChN, const int &EChN) const
Definition: dt.cpp:811
TStr GetFExt() const
Definition: dt.cpp:1421
void GVizDoLayout(const TStr &GraphInFNm, TStr OutFNm, const TGVizLayout &Layout)
Runs GraphViz layout engine over a graph saved in the file GraphInFNm with output saved to OutFNm...
Definition: gviz.cpp:5
Definition: dt.h:412
template<class PGraph >
void TSnap::DrawGViz ( const PGraph &  Graph,
const TGVizLayout Layout,
const TStr PltFNm,
const TStr Desc,
const TIntStrH NodeLabelH 
)

Draws a given Graph using a selected GraphViz Layout engine with nodes labeled.

Useful for drawing small (<100 node) graphs.

Parameters
PltFNmOutput filename (extension .ps, .png, .gif) determines the output format.
NIdColorHMaps node ids to node colors (see GraphViz documentation for more details).

Definition at line 42 of file gviz.h.

42  {
43  const TStr Ext = PltFNm.GetFExt();
44  const TStr GraphFNm = PltFNm.GetSubStr(0, PltFNm.Len()-Ext.Len()) + "dot";
45  SaveGViz(Graph, GraphFNm, Desc, NodeLabelH);
46  TSnap::TSnapDetail::GVizDoLayout(GraphFNm, PltFNm, Layout);
47 }
int Len() const
Definition: dt.h:487
void SaveGViz(const PGraph &Graph, const TStr &OutFNm, const TStr &Desc=TStr(), const bool &NodeLabels=false, const TIntStrH &NIdColorH=TIntStrH())
Save a graph in GraphVizp .DOT format.
Definition: gio.h:369
TStr GetSubStr(const int &BChN, const int &EChN) const
Definition: dt.cpp:811
TStr GetFExt() const
Definition: dt.cpp:1421
void GVizDoLayout(const TStr &GraphInFNm, TStr OutFNm, const TGVizLayout &Layout)
Runs GraphViz layout engine over a graph saved in the file GraphInFNm with output saved to OutFNm...
Definition: gviz.cpp:5
Definition: dt.h:412
int TSnap::FindAugV ( const PNEANet Net,
const int &  CapIndex,
TIntV Flow,
TIntQ FwdNodeQ,
TIntH PredEdgeH,
TIntQ BwdNodeQ,
TIntH SuccEdgeH,
TIntV MidToSrcAugV,
TIntV MidToSnkAugV,
const int &  SrcNId,
const int &  SnkNId 
)

Returns the amount the flow can be augmented over the paths, 0 if no path can be found.

Find the augmenting path. Calls bidirectional BFS to find the path, and then builds the two path vectors.

Parameters
MidToSrcAugVContains the path vector from the midpoint node where the bi-d search met back to the source node.
MidToSnkAugVContains the path vector from the midpoint node where the bi-d search met back to the sink node.

Definition at line 71 of file flow.cpp.

71  {
72  int MidPtNId = IntFlowBiDBFS(Net, CapIndex, Flow, FwdNodeQ, PredEdgeH, BwdNodeQ, SuccEdgeH, SrcNId, SnkNId);
73  if (MidPtNId == -1) { return 0; }
74  int MinAug = TInt::Mx, NId = MidPtNId, AugFlow = 0;
75  // Build the path from the midpoint back to the source by tracing through the PredEdgeH
76  for (int EId = PredEdgeH.GetDat(NId); NId != SrcNId; EId = PredEdgeH.GetDat(NId)) {
77  MidToSrcAugV.Add(EId);
78  const TNEANet::TEdgeI &EI = Net->GetEI(EId);
79  if (EI.GetSrcNId() == NId) {
80  NId = EI.GetDstNId();
81  AugFlow = Flow[EId];
82  } else {
83  NId = EI.GetSrcNId();
84  AugFlow = Net->GetIntAttrIndDatE(EId, CapIndex) - Flow[EId];
85  }
86  if (AugFlow < MinAug) { MinAug = AugFlow; }
87  }
88  NId = MidPtNId;
89  // Build the path from the midpoint back to the sink by tracing through the SuccEdgeH
90  for (int EId = SuccEdgeH.GetDat(NId); NId != SnkNId; EId = SuccEdgeH.GetDat(NId)) {
91  MidToSnkAugV.Add(EId);
92  const TNEANet::TEdgeI &EI = Net->GetEI(EId);
93  if (EI.GetDstNId() == NId) {
94  NId = EI.GetSrcNId();
95  AugFlow = Flow[EId];
96  } else {
97  NId = EI.GetDstNId();
98  AugFlow = Net->GetIntAttrIndDatE(EId, CapIndex) - Flow[EId];
99  }
100  if (AugFlow < MinAug) { MinAug = AugFlow; }
101  }
102  return MinAug;
103 }
static const int Mx
Definition: dt.h:1046
const TDat & GetDat(const TKey &Key) const
Definition: hash.h:220
int GetDstNId() const
Returns the destination of the edge.
Definition: network.h:1718
int GetSrcNId() const
Returns the source of the edge.
Definition: network.h:1716
int IntFlowBiDBFS(const PNEANet &Net, const int &CapIndex, TIntV &Flow, TIntQ &FwdNodeQ, TIntH &PredEdgeH, TIntQ &BwdNodeQ, TIntH &SuccEdgeH, const int &SrcNId, const int &SnkNId)
Definition: flow.cpp:4
Edge iterator. Only forward iteration (operator++) is supported.
Definition: network.h:1699
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph >
PGraph TSnap::GenBaraHierar ( const int &  Levels,
const bool &  IsDir 
)

Generates a Ravasz-Barabasi deterministic scale-free graph.

Corners of the graph are recursively expanded with miniature copies of the base graph (below). The graph has power-law degree distribution with the exponent 1+ln(5)/ln(4) and clustering coefficient with power-law decay exponent -1. Base graph:

///   o---o
///   |\ /|
///   | o |
///   |/ \|
///   o---o
/// 

See: Hierarchical organization in complex networks. Ravasz and Barabasi. URL: http://arxiv.org/abs/cond-mat/0206130

Definition at line 174 of file ggen.h.

174  {
175  const int Nodes = (int) TMath::Round(TMath::Power(5, Levels));
176  PGraph GraphPt = PGraph::New();
177  typename PGraph::TObj& Graph = *GraphPt;
178  Graph.Reserve(Nodes, -1);
179  // base graph
180  for (int i = 0; i < 5; i++) { Graph.AddNode(i); }
181  Graph.AddEdge(1,2); Graph.AddEdge(2,3);
182  Graph.AddEdge(3,4); Graph.AddEdge(4,1);
183  Graph.AddEdge(1,0); Graph.AddEdge(3,0);
184  Graph.AddEdge(2,0); Graph.AddEdge(4,0);
185  // expansion
186  const int CenterId = 0;
187  for (int lev = 1; lev < Levels+1; lev++) {
188  const int MxNId = Graph.GetNodes();
189  // make 4 duplicate copies
190  for (int d = 0; d < 4; d++) {
191  for (int n = 0; n < MxNId; n++) { Graph.AddNode(); }
192  for (int n = 0; n < MxNId; n++) {
193  typename PGraph::TObj::TNodeI NI = Graph.GetNI(n);
194  const int SrcId = n+MxNId*(d+1);
195  for (int e = 0; e < NI.GetOutDeg(); e++) {
196  Graph.AddEdge(SrcId, NI.GetOutNId(e)+MxNId*(d+1));
197  }
198  }
199  }
200  // add edges to the center
201  //const int LevPow = (int)TMath::Round(TMath::Power(5,lev-1));
202  for (int n = MxNId; n < Graph.GetNodes(); n++) {
203  typename PGraph::TObj::TNodeI NI = Graph.GetNI(n);
204  const int SrcId = n;
205  int Pow = 1; bool Skip = false;
206  for (int p = 1; p <= lev; p++) {
207  if (SrcId % (5*Pow) < Pow) { Skip=true; break; }
208  Pow *= 5;
209  }
210  if (Skip) { continue; }
211  Graph.AddEdge(SrcId, CenterId);
212  }
213  }
214  return GraphPt;
215 }
static double Round(const double &Val)
Definition: xmath.h:16
static double Power(const double &Base, const double &Exponent)
Definition: xmath.h:25
template<class PGraph >
PGraph TSnap::GenCircle ( const int &  Nodes,
const int &  NodeOutDeg = 1,
const bool &  IsDir = true 
)

Generates a circle graph where every node creates out-links to NodeOutDeg forward nodes.

Definition at line 104 of file ggen.h.

104  {
105  PGraph Graph = PGraph::TObj::New();
106  Graph->Reserve(Nodes, Nodes*NodeOutDeg);
107  for (int n = 0; n < Nodes; n++) {
108  Graph->AddNode(n); }
109  for (int n = 0; n < Nodes; n++) {
110  for (int x = 0; x < NodeOutDeg; x++) {
111  Graph->AddEdge(n, (n+x+1) % Nodes);
112  if (Graph->HasFlag(gfDirected) && ! IsDir) { Graph->AddEdge((n+x+1) % Nodes, n); }
113  }
114  }
115  return Graph;
116 }
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
PUNGraph TSnap::GenConfModel ( const TIntV DegSeqV,
TRnd Rnd 
)

Generates a random undirect graph with a given degree sequence.

Generates a random undirect graph with a given degree sequence DegSeqV. Configuration model operates as follows. For each node N, of degree DeqSeqV[N] we create DeqSeqV[N] spokes (half-edges). We then pick two spokes at random, and connect the spokes endpoints. We continue this process until no spokes are left. Generally this generates a multigraph (i.e., spokes out of same nodes can be chosen multiple times).We ignore (discard) self-loops and multiple edges. Thus, the generated graph will only approximate follow the given degree sequence. The method is very fast!

Definition at line 119 of file ggen.cpp.

119  {
120  const int Nodes = DegSeqV.Len();
121  PUNGraph GraphPt = TUNGraph::New();
122  TUNGraph& Graph = *GraphPt;
123  Graph.Reserve(Nodes, -1);
124  TIntV NIdDegV(DegSeqV.Len(), 0);
125  int DegSum=0, edges=0;
126  for (int node = 0; node < Nodes; node++) {
127  Graph.AddNode(node);
128  for (int d = 0; d < DegSeqV[node]; d++) { NIdDegV.Add(node); }
129  DegSum += DegSeqV[node];
130  }
131  NIdDegV.Shuffle(Rnd);
132  TIntPrSet EdgeH(DegSum/2); // set of all edges, is faster than graph edge lookup
133  if (DegSum % 2 != 0) {
134  printf("Seg seq is odd [%d]: ", DegSeqV.Len());
135  for (int d = 0; d < TMath::Mn(100, DegSeqV.Len()); d++) { printf(" %d", (int)DegSeqV[d]); }
136  printf("\n");
137  }
138  int u=0, v=0;
139  for (int c = 0; NIdDegV.Len() > 1; c++) {
140  u = Rnd.GetUniDevInt(NIdDegV.Len());
141  while ((v = Rnd.GetUniDevInt(NIdDegV.Len())) == u) { }
142  if (u > v) { Swap(u, v); }
143  const int E1 = NIdDegV[u];
144  const int E2 = NIdDegV[v];
145  if (v == NIdDegV.Len()-1) { NIdDegV.DelLast(); }
146  else { NIdDegV[v] = NIdDegV.Last(); NIdDegV.DelLast(); }
147  if (u == NIdDegV.Len()-1) { NIdDegV.DelLast(); }
148  else { NIdDegV[u] = NIdDegV.Last(); NIdDegV.DelLast(); }
149  if (E1 == E2 || EdgeH.IsKey(TIntPr(E1, E2))) { continue; }
150  EdgeH.AddKey(TIntPr(E1, E2));
151  Graph.AddEdge(E1, E2);
152  edges++;
153  if (c % (DegSum/100+1) == 0) { printf("\r configuration model: iter %d: edges: %d, left: %d", c, edges, NIdDegV.Len()/2); }
154  }
155  printf("\n");
156  return GraphPt;
157 }
static const T & Mn(const T &LVal, const T &RVal)
Definition: xmath.h:36
TPair< TInt, TInt > TIntPr
Definition: ds.h:83
int AddNode(int NId=-1)
Adds a node of ID NId to the graph.
Definition: graph.cpp:8
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
Undirected graph.
Definition: graph.h:32
void Reserve(const int &Nodes, const int &Edges)
Reserves memory for a graph of Nodes nodes and Edges edges.
Definition: graph.h:249
static PUNGraph New()
Static constructor that returns a pointer to the graph. Call: PUNGraph Graph = TUNGraph::New().
Definition: graph.h:149
int AddEdge(const int &SrcNId, const int &DstNId)
Adds an edge between node IDs SrcNId and DstNId to the graph.
Definition: graph.cpp:84
Definition: ds.h:32
int GetUniDevInt(const int &Range=0)
Definition: dt.cpp:39
void Swap(TRec &Rec1, TRec &Rec2)
Definition: bd.h:568
PUNGraph TSnap::GenConfModel ( const PUNGraph G)

Generate a random graph using (approximately) the same node degrees as in G using the configuration model.

Definition at line 335 of file ggen.cpp.

335  {
336  TIntV DegSeqV(G->GetNodes(), 0);
337  TSnap::GetDegSeqV(G, DegSeqV);
338  return TSnap::GenConfModel(DegSeqV);
339 }
int GetNodes() const
Returns the number of nodes in the graph.
Definition: graph.h:162
void GetDegSeqV(const PGraph &Graph, TIntV &DegV)
Returns a degree sequence vector.
Definition: alg.h:245
PUNGraph GenConfModel(const TIntV &DegSeqV, TRnd &Rnd)
Generates a random undirect graph with a given degree sequence.
Definition: ggen.cpp:119
PNGraph TSnap::GenCopyModel ( const int &  Nodes,
const double &  Beta,
TRnd Rnd 
)

Generates a random scale-free network using the Copying Model.

Generates a random scale-free network using the Copying Model. The generating process operates as follows: Node u is added to a graph, it selects a random node v, and with prob Beta it links to v, with 1-Beta links u links to neighbor of v. The power-law degree exponent is -1/(1-Beta). See: Stochastic models for the web graph. Kumar, Raghavan, Rajagopalan, Sivakumar, Tomkins, Upfal. URL: http://snap.stanford.edu/class/cs224w-readings/kumar00stochastic.pdf

Definition at line 453 of file ggen.cpp.

453  {
454  PNGraph GraphPt = TNGraph::New();
455  TNGraph& Graph = *GraphPt;
456  Graph.Reserve(Nodes, Nodes);
457  const int startNId = Graph.AddNode();
458  Graph.AddEdge(startNId, startNId);
459  for (int n = 1; n < Nodes; n++) {
460  const int rnd = Graph.GetRndNId();
461  const int NId = Graph.AddNode();
462  if (Rnd.GetUniDev() < Beta) {
463  Graph.AddEdge(NId, rnd); }
464  else {
465  const TNGraph::TNodeI NI = Graph.GetNI(rnd);
466  const int rnd2 = Rnd.GetUniDevInt(NI.GetOutDeg());
467  Graph.AddEdge(NId, NI.GetOutNId(rnd2));
468  }
469  }
470  return GraphPt;
471 }
static PNGraph New()
Static constructor that returns a pointer to the graph. Call: PNGraph Graph = TNGraph::New().
Definition: graph.h:405
TNodeI GetNI(const int &NId) const
Returns an iterator referring to the node of ID NId in the graph.
Definition: graph.h:461
int AddNode(int NId=-1)
Adds a node of ID NId to the graph.
Definition: graph.cpp:208
int AddEdge(const int &SrcNId, const int &DstNId)
Adds an edge from node IDs SrcNId to node DstNId to the graph.
Definition: graph.cpp:286
int GetRndNId(TRnd &Rnd=TInt::Rnd)
Returns an ID of a random node in the graph.
Definition: graph.h:497
Directed graph.
Definition: graph.h:293
int GetOutDeg() const
Returns out-degree of the current node.
Definition: graph.h:344
Node iterator. Only forward iteration (operator++) is supported.
Definition: graph.h:324
double GetUniDev()
Definition: dt.h:30
void Reserve(const int &Nodes, const int &Edges)
Reserves memory for a graph of Nodes nodes and Edges edges.
Definition: graph.h:508
Definition: bd.h:196
int GetUniDevInt(const int &Range=0)
Definition: dt.cpp:39
int GetOutNId(const int &NodeN) const
Returns ID of NodeN-th out-node (the node the current node points to).
Definition: graph.h:352
PUNGraph TSnap::GenDegSeq ( const TIntV DegSeqV,
TRnd Rnd 
)

Generates a random graph with exact degree sequence.

Generates a random graph with exact degree sequence DegSeqV. The generated graph has no self loops. The graph generation process simulates the Configuration Model but if a duplicate edge occurs, we find a random edge, break it and reconnect it with the duplicate.

Definition at line 58 of file ggen.cpp.

58  {
59  const int Nodes = DegSeqV.Len();
60  PUNGraph GraphPt = TUNGraph::New();
61  TUNGraph& Graph = *GraphPt;
62  Graph.Reserve(Nodes, -1);
63  TIntH DegH(DegSeqV.Len(), true);
64 
65  IAssertR(DegSeqV.IsSorted(false), "DegSeqV must be sorted in descending order.");
66  int DegSum=0, edge=0;
67  for (int node = 0; node < Nodes; node++) {
68  IAssert(Graph.AddNode(node) == node);
69  DegH.AddDat(node, DegSeqV[node]);
70  DegSum += DegSeqV[node];
71  }
72  IAssert(DegSum % 2 == 0);
73  while (! DegH.Empty()) {
74  // pick random nodes and connect
75  const int NId1 = DegH.GetKey(DegH.GetRndKeyId(TInt::Rnd, 0.5));
76  const int NId2 = DegH.GetKey(DegH.GetRndKeyId(TInt::Rnd, 0.5));
77  IAssert(DegH.IsKey(NId1) && DegH.IsKey(NId2));
78  if (NId1 == NId2) {
79  if (DegH.GetDat(NId1) == 1) { continue; }
80  // find rnd edge, break it, and connect the endpoints to the nodes
81  const TIntPr Edge = TSnapDetail::GetRndEdgeNonAdjNode(GraphPt, NId1, -1);
82  if (Edge.Val1==-1) { continue; }
83  Graph.DelEdge(Edge.Val1, Edge.Val2);
84  Graph.AddEdge(Edge.Val1, NId1);
85  Graph.AddEdge(NId1, Edge.Val2);
86  if (DegH.GetDat(NId1) == 2) { DegH.DelKey(NId1); }
87  else { DegH.GetDat(NId1) -= 2; }
88  } else {
89  if (! Graph.IsEdge(NId1, NId2)) {
90  Graph.AddEdge(NId1, NId2); } // good edge
91  else {
92  // find rnd edge, break and cross-connect
93  const TIntPr Edge = TSnapDetail::GetRndEdgeNonAdjNode(GraphPt, NId1, NId2);
94  if (Edge.Val1==-1) {continue; }
95  Graph.DelEdge(Edge.Val1, Edge.Val2);
96  Graph.AddEdge(NId1, Edge.Val1);
97  Graph.AddEdge(NId2, Edge.Val2);
98  }
99  if (DegH.GetDat(NId1)==1) { DegH.DelKey(NId1); }
100  else { DegH.GetDat(NId1) -= 1; }
101  if (DegH.GetDat(NId2)==1) { DegH.DelKey(NId2); }
102  else { DegH.GetDat(NId2) -= 1; }
103  }
104  if (++edge % 1000 == 0) {
105  printf("\r %dk / %dk", edge/1000, DegSum/2000); }
106  }
107  return GraphPt;
108 }
#define IAssert(Cond)
Definition: bd.h:262
#define IAssertR(Cond, Reason)
Definition: bd.h:265
int AddNode(int NId=-1)
Adds a node of ID NId to the graph.
Definition: graph.cpp:8
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
static TRnd Rnd
Definition: dt.h:1050
TIntPr GetRndEdgeNonAdjNode(const PGraph &Graph, int NId1, int NId2)
Returns a random edge in a graph Graph where the edge does not touch nodes NId1 and NId2...
Definition: ggen.h:240
Undirected graph.
Definition: graph.h:32
void Reserve(const int &Nodes, const int &Edges)
Reserves memory for a graph of Nodes nodes and Edges edges.
Definition: graph.h:249
static PUNGraph New()
Static constructor that returns a pointer to the graph. Call: PUNGraph Graph = TUNGraph::New().
Definition: graph.h:149
void DelEdge(const int &SrcNId, const int &DstNId)
Deletes an edge between node IDs SrcNId and DstNId from the graph.
Definition: graph.cpp:95
int AddEdge(const int &SrcNId, const int &DstNId)
Adds an edge between node IDs SrcNId and DstNId to the graph.
Definition: graph.cpp:84
Definition: ds.h:32
bool IsSorted(const bool &Asc=true) const
Checks whether the vector is sorted in ascending (if Asc=true) or descending (if Asc=false) order...
Definition: ds.h:1223
TVal1 Val1
Definition: ds.h:34
TVal2 Val2
Definition: ds.h:35
bool IsEdge(const int &SrcNId, const int &DstNId) const
Tests whether an edge between node IDs SrcNId and DstNId exists in the graph.
Definition: graph.cpp:108
PNGraph TSnap::GenForestFire ( const int &  Nodes,
const double &  FwdProb,
const double &  BckProb 
)

Generates a random Forest Fire, directed graph with given probabilities.

Definition at line 442 of file ggen.cpp.

442  {
443  return TForestFire::GenGraph(Nodes, FwdProb, BckProb);
444 }
static PNGraph GenGraph(const int &Nodes, const double &FwdProb, const double &BckProb)
Definition: ff.cpp:250
template<class PGraph >
PGraph TSnap::GenFull ( const int &  Nodes)

Generates a complete graph on Nodes nodes. Graph has no self-loops.

Definition at line 119 of file ggen.h.

119  {
120  PGraph Graph = PGraph::TObj::New();
121  Graph->Reserve(Nodes, Nodes*Nodes);
122  for (int n = 0; n < Nodes; n++) {
123  Graph->AddNode(n); }
124  for (int n1 = 0; n1 < Nodes; n1++) {
125  for (int n2 = 0; n2 < Nodes; n2++) {
126  if (n1 != n2) { Graph->AddEdge(n1, n2); }
127  }
128  }
129  return Graph;
130 }
PUNGraph TSnap::GenGeoPrefAttach ( const int &  Nodes,
const int &  OutDeg,
const double &  Beta,
TRnd Rnd 
)

Generates a random scale-free graph using the Geometric Preferential model.

Generates a random scale-free graph using the Geometric Preferential Attachment model by Flexman, Frieze and Vera. See: A geometric preferential attachment model of networks by Flexman, Frieze and Vera. WAW 2004. URL: http://math.cmu.edu/~af1p/Texfiles/GeoWeb.pdf

Definition at line 361 of file ggen.cpp.

361  {
362  PUNGraph G = TUNGraph::New(Nodes, Nodes*OutDeg);
363  TFltTrV PointV(Nodes, 0);
364  TFltV ValV;
365  // points on a sphere of radius 1/(2*pi)
366  const double Rad = 0.5 * TMath::Pi;
367  for (int i = 0; i < Nodes; i++) {
368  TSnapDetail::GetSphereDev(3, Rnd, ValV);
369  PointV.Add(TFltTr(Rad*ValV[0], Rad*ValV[1], Rad*ValV[2]));
370  }
371  const double R2 = TMath::Sqr(log((double) Nodes) / (pow((double) Nodes, 0.5-Beta)));
372  TIntV DegV, NIdV;
373  int SumDeg;
374  for (int t = 0; t < Nodes; t++) {
375  const int pid = t;
376  const TFltTr& P1 = PointV[pid];
377  // add node
378  if (! G->IsNode(pid)) { G->AddNode(pid); }
379  // find neighborhood
380  DegV.Clr(false); NIdV.Clr(false); SumDeg=0;
381  for (int p = 0; p < t; p++) {
382  const TFltTr& P2 = PointV[p];
383  if (TMath::Sqr(P1.Val1-P2.Val1)+TMath::Sqr(P1.Val2-P2.Val2)+TMath::Sqr(P1.Val3-P2.Val3) < R2) {
384  NIdV.Add(p);
385  DegV.Add(G->GetNI(p).GetDeg()+1);
386  SumDeg += DegV.Last();
387  }
388  }
389  // add edges
390  for (int m = 0; m < OutDeg; m++) {
391  const int rnd = Rnd.GetUniDevInt(SumDeg);
392  int sum = 0, dst = -1;
393  for (int s = 0; s < DegV.Len(); s++) {
394  sum += DegV[s];
395  if (rnd < sum) { dst=s; break; }
396  }
397  if (dst != -1) {
398  G->AddEdge(pid, NIdV[dst]);
399  SumDeg -= DegV[dst];
400  NIdV.Del(dst); DegV.Del(dst);
401  }
402  }
403  }
404  return G;
405 }
Definition: ds.h:129
void Del(const TSizeTy &ValN)
Removes the element at position ValN.
Definition: ds.h:1094
int AddNode(int NId=-1)
Adds a node of ID NId to the graph.
Definition: graph.cpp:8
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
TVal1 Val1
Definition: ds.h:131
static double Sqr(const double &x)
Definition: xmath.h:12
int GetDeg() const
Returns degree of the current node.
Definition: graph.h:82
void GetSphereDev(const int &Dim, TRnd &Rnd, TFltV &ValV)
Sample random point from the surface of a Dim-dimensional unit sphere.
Definition: ggen.cpp:343
TVal2 Val2
Definition: ds.h:132
void Clr(const bool &DoDel=true, const TSizeTy &NoDelLim=-1)
Clears the contents of the vector.
Definition: ds.h:953
TNodeI GetNI(const int &NId) const
Returns an iterator referring to the node of ID NId in the graph.
Definition: graph.h:205
static PUNGraph New()
Static constructor that returns a pointer to the graph. Call: PUNGraph Graph = TUNGraph::New().
Definition: graph.h:149
const TVal & Last() const
Returns a reference to the last element of the vector.
Definition: ds.h:539
TTriple< TFlt, TFlt, TFlt > TFltTr
Definition: ds.h:175
static double Pi
Definition: xmath.h:8
int AddEdge(const int &SrcNId, const int &DstNId)
Adds an edge between node IDs SrcNId and DstNId to the graph.
Definition: graph.cpp:84
bool IsNode(const int &NId) const
Tests whether ID NId is a node.
Definition: graph.h:199
int GetUniDevInt(const int &Range=0)
Definition: dt.cpp:39
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
TVal3 Val3
Definition: ds.h:133
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
template<class PGraph >
PGraph TSnap::GenGrid ( const int &  Rows,
const int &  Cols,
const bool &  IsDir = true 
)

Generates a 2D-grid graph of Rows rows and Cols columns.

Definition at line 65 of file ggen.h.

65  {
66  PGraph GraphPt = PGraph::New();
67  typename PGraph::TObj& Graph = *GraphPt;
68  Graph.Reserve(Rows*Cols, 4*Rows*Cols);
69  int node, r, c;
70  for (node = 0; node < Rows * Cols; node++) {
71  Graph.AddNode(node); }
72  for (r = 0; r < Rows; r++) {
73  for (c = 0; c < Cols; c++) {
74  const int nodeId = Cols*r + c;
75  if (r < Rows-1) { // bottom node
76  Graph.AddEdge(nodeId, nodeId+Cols);
77  if (Graph.HasFlag(gfDirected) && ! IsDir) {
78  Graph.AddEdge(nodeId+Cols, nodeId); }
79  }
80  if (c < Cols-1) { // right node
81  Graph.AddEdge(nodeId, nodeId+1);
82  if (Graph.HasFlag(gfDirected) && ! IsDir) {
83  Graph.AddEdge(nodeId+1, nodeId); }
84  }
85  }
86  }
87  return GraphPt;
88 }
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
PUNGraph TSnap::GenPrefAttach ( const int &  Nodes,
const int &  NodeOutDeg,
TRnd Rnd 
)

Generates a power-law degree distribution using Barabasi-Albert model of scale-free graphs.

Barabasi-Albert model of scale-free graphs. The graph has power-law degree distribution. See: Emergence of scaling in random networks by Barabasi and Albert. URL: http://arxiv.org/abs/cond-mat/9910332

Definition at line 310 of file ggen.cpp.

310  {
311  PUNGraph GraphPt = PUNGraph::New();
312  TUNGraph& Graph = *GraphPt;
313  Graph.Reserve(Nodes, NodeOutDeg*Nodes);
314  TIntV NIdV(NodeOutDeg*Nodes, 0);
315  // first edge
316  Graph.AddNode(0); Graph.AddNode(1);
317  NIdV.Add(0); NIdV.Add(1);
318  Graph.AddEdge(0, 1);
319  TIntSet NodeSet;
320  for (int node = 2; node < Nodes; node++) {
321  NodeSet.Clr(false);
322  while (NodeSet.Len() < NodeOutDeg && NodeSet.Len() < node) {
323  NodeSet.AddKey(NIdV[TInt::Rnd.GetUniDevInt(NIdV.Len())]);
324  }
325  const int N = Graph.AddNode();
326  for (int i = 0; i < NodeSet.Len(); i++) {
327  Graph.AddEdge(N, NodeSet[i]);
328  NIdV.Add(N);
329  NIdV.Add(NodeSet[i]);
330  }
331  }
332  return GraphPt;
333 }
void Clr(const bool &DoDel=true, const int &NoDelLim=-1)
Definition: shash.h:1237
static TPt New()
Definition: bd.h:479
int AddNode(int NId=-1)
Adds a node of ID NId to the graph.
Definition: graph.cpp:8
static TRnd Rnd
Definition: dt.h:1050
Undirected graph.
Definition: graph.h:32
void Reserve(const int &Nodes, const int &Edges)
Reserves memory for a graph of Nodes nodes and Edges edges.
Definition: graph.h:249
int AddKey(const TKey &Key)
Definition: shash.h:1248
int AddEdge(const int &SrcNId, const int &DstNId)
Adds an edge between node IDs SrcNId and DstNId to the graph.
Definition: graph.cpp:84
int Len() const
Definition: shash.h:1115
PUNGraph TSnap::GenRewire ( const PUNGraph OrigGraph,
const int &  NSwitch,
TRnd Rnd 
)

Rewire a random undirected graph. Keeps node degrees the same, but randomly rewires the edges.

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

Definition at line 165 of file ggen.cpp.

165  {
166  const int Nodes = OrigGraph->GetNodes();
167  const int Edges = OrigGraph->GetEdges();
168  PUNGraph GraphPt = TUNGraph::New();
169  TUNGraph& Graph = *GraphPt;
170  Graph.Reserve(Nodes, -1);
171  TExeTm ExeTm;
172  // generate a graph that satisfies the constraints
173  printf("Randomizing edges (%d, %d)...\n", Nodes, Edges);
174  TIntPrSet EdgeSet(Edges);
175  for (TUNGraph::TNodeI NI = OrigGraph->BegNI(); NI < OrigGraph->EndNI(); NI++) {
176  const int NId = NI.GetId();
177  for (int e = 0; e < NI.GetOutDeg(); e++) {
178  if (NId <= NI.GetOutNId(e)) { continue; }
179  EdgeSet.AddKey(TIntPr(NId, NI.GetOutNId(e)));
180  }
181  Graph.AddNode(NI.GetId());
182  }
183  // edge switching
184  uint skip=0;
185  for (uint swps = 0; swps < 2*uint(Edges)*uint(NSwitch); swps++) {
186  const int keyId1 = EdgeSet.GetRndKeyId(Rnd);
187  const int keyId2 = EdgeSet.GetRndKeyId(Rnd);
188  if (keyId1 == keyId2) { skip++; continue; }
189  const TIntPr& E1 = EdgeSet[keyId1];
190  const TIntPr& E2 = EdgeSet[keyId2];
191  TIntPr NewE1(E1.Val1, E2.Val1), NewE2(E1.Val2, E2.Val2);
192  if (NewE1.Val1 > NewE1.Val2) { Swap(NewE1.Val1, NewE1.Val2); }
193  if (NewE2.Val1 > NewE2.Val2) { Swap(NewE2.Val1, NewE2.Val2); }
194  if (NewE1!=NewE2 && NewE1.Val1!=NewE1.Val2 && NewE2.Val1!=NewE2.Val2 && ! EdgeSet.IsKey(NewE1) && ! EdgeSet.IsKey(NewE2)) {
195  EdgeSet.DelKeyId(keyId1); EdgeSet.DelKeyId(keyId2);
196  EdgeSet.AddKey(TIntPr(NewE1));
197  EdgeSet.AddKey(TIntPr(NewE2));
198  } else { skip++; }
199  if (swps % Edges == 0) {
200  printf("\r %uk/%uk: %uk skip [%s]", swps/1000u, 2*uint(Edges)*uint(NSwitch)/1000u, skip/1000u, ExeTm.GetStr());
201  if (ExeTm.GetSecs() > 2*3600) { printf(" *** Time limit!\n"); break; } // time limit 2 hours
202  }
203  }
204  printf("\r total %uk switchings attempted, %uk skiped [%s]\n", 2*uint(Edges)*uint(NSwitch)/1000u, skip/1000u, ExeTm.GetStr());
205  for (int e = 0; e < EdgeSet.Len(); e++) {
206  Graph.AddEdge(EdgeSet[e].Val1, EdgeSet[e].Val2); }
207  return GraphPt;
208 }
TPair< TInt, TInt > TIntPr
Definition: ds.h:83
Definition: tm.h:354
unsigned int uint
Definition: bd.h:11
int AddNode(int NId=-1)
Adds a node of ID NId to the graph.
Definition: graph.cpp:8
int GetEdges() const
Returns the number of edges in the graph.
Definition: graph.cpp:74
Node iterator. Only forward iteration (operator++) is supported.
Definition: graph.h:63
int GetNodes() const
Returns the number of nodes in the graph.
Definition: graph.h:162
Undirected graph.
Definition: graph.h:32
void Reserve(const int &Nodes, const int &Edges)
Reserves memory for a graph of Nodes nodes and Edges edges.
Definition: graph.h:249
static PUNGraph New()
Static constructor that returns a pointer to the graph. Call: PUNGraph Graph = TUNGraph::New().
Definition: graph.h:149
int AddEdge(const int &SrcNId, const int &DstNId)
Adds an edge between node IDs SrcNId and DstNId to the graph.
Definition: graph.cpp:84
Definition: ds.h:32
double GetSecs() const
Definition: tm.h:365
TNodeI EndNI() const
Returns an iterator referring to the past-the-end node in the graph.
Definition: graph.h:203
TVal1 Val1
Definition: ds.h:34
TVal2 Val2
Definition: ds.h:35
const char * GetStr() const
Definition: tm.h:367
TNodeI BegNI() const
Returns an iterator referring to the first node in the graph.
Definition: graph.h:201
void Swap(TRec &Rec1, TRec &Rec2)
Definition: bd.h:568
PNGraph TSnap::GenRewire ( const PNGraph OrigGraph,
const int &  NSwitch,
TRnd Rnd 
)

Rewire a random directed graph. Keeps node degrees the same, but randomly rewires the edges.

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

Definition at line 216 of file ggen.cpp.

216  {
217  const int Nodes = OrigGraph->GetNodes();
218  const int Edges = OrigGraph->GetEdges();
219  PNGraph GraphPt = TNGraph::New();
220  TNGraph& Graph = *GraphPt;
221  Graph.Reserve(Nodes, -1);
222  TExeTm ExeTm;
223  // generate a graph that satisfies the constraints
224  printf("Randomizing edges (%d, %d)...\n", Nodes, Edges);
225  TIntPrSet EdgeSet(Edges);
226  for (TNGraph::TNodeI NI = OrigGraph->BegNI(); NI < OrigGraph->EndNI(); NI++) {
227  const int NId = NI.GetId();
228  for (int e = 0; e < NI.GetOutDeg(); e++) {
229  EdgeSet.AddKey(TIntPr(NId, NI.GetOutNId(e))); }
230  Graph.AddNode(NI);
231  }
232  // edge switching
233  uint skip=0;
234  for (uint swps = 0; swps < 2*uint(Edges)*uint(NSwitch); swps++) {
235  const int keyId1 = EdgeSet.GetRndKeyId(Rnd);
236  const int keyId2 = EdgeSet.GetRndKeyId(Rnd);
237  if (keyId1 == keyId2) { skip++; continue; }
238  const TIntPr& E1 = EdgeSet[keyId1];
239  const TIntPr& E2 = EdgeSet[keyId2];
240  TIntPr NewE1(E1.Val1, E2.Val1), NewE2(E1.Val2, E2.Val2);
241  if (NewE1.Val1!=NewE2.Val1 && NewE1.Val2!=NewE2.Val1 && NewE1.Val2!=NewE2.Val1 && NewE1.Val2!=NewE2.Val2 && ! EdgeSet.IsKey(NewE1) && ! EdgeSet.IsKey(NewE2)) {
242  EdgeSet.DelKeyId(keyId1); EdgeSet.DelKeyId(keyId2);
243  EdgeSet.AddKey(TIntPr(NewE1));
244  EdgeSet.AddKey(TIntPr(NewE2));
245  } else { skip++; }
246  if (swps % Edges == 0) {
247  printf("\r %uk/%uk: %uk skip [%s]", swps/1000u, 2*uint(Edges)*uint(NSwitch)/1000u, skip/1000u, ExeTm.GetStr());
248  if (ExeTm.GetSecs() > 2*3600) { printf(" *** Time limit!\n"); break; } // time limit 2 hours
249  }
250  }
251  printf("\r total %uk switchings attempted, %uk skiped [%s]\n", 2*uint(Edges)*uint(NSwitch)/1000u, skip/1000u, ExeTm.GetStr());
252  for (int e = 0; e < EdgeSet.Len(); e++) {
253  Graph.AddEdge(EdgeSet[e].Val1, EdgeSet[e].Val2); }
254  return GraphPt;
255 }
TPair< TInt, TInt > TIntPr
Definition: ds.h:83
Definition: tm.h:354
static PNGraph New()
Static constructor that returns a pointer to the graph. Call: PNGraph Graph = TNGraph::New().
Definition: graph.h:405
unsigned int uint
Definition: bd.h:11
int AddNode(int NId=-1)
Adds a node of ID NId to the graph.
Definition: graph.cpp:208
int AddEdge(const int &SrcNId, const int &DstNId)
Adds an edge from node IDs SrcNId to node DstNId to the graph.
Definition: graph.cpp:286
Directed graph.
Definition: graph.h:293
Definition: ds.h:32
Node iterator. Only forward iteration (operator++) is supported.
Definition: graph.h:324
double GetSecs() const
Definition: tm.h:365
TVal1 Val1
Definition: ds.h:34
void Reserve(const int &Nodes, const int &Edges)
Reserves memory for a graph of Nodes nodes and Edges edges.
Definition: graph.h:508
TVal2 Val2
Definition: ds.h:35
Definition: bd.h:196
const char * GetStr() const
Definition: tm.h:367
PBPGraph TSnap::GenRewire ( const PBPGraph OrigGraph,
const int &  NSwitch,
TRnd Rnd 
)

Rewire a random bipartite graph. Keeps node degrees the same, but randomly rewires the edges.

Rewire a bipartite graph. 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

Definition at line 263 of file ggen.cpp.

263  {
264  const int Nodes = OrigGraph->GetNodes();
265  const int Edges = OrigGraph->GetEdges();
266  PBPGraph GraphPt = TBPGraph::New();
267  TBPGraph& Graph = *GraphPt;
268  Graph.Reserve(Nodes, -1);
269  TExeTm ExeTm;
270  // generate a graph that satisfies the constraints
271  printf("Randomizing edges (%d, %d)...\n", Nodes, Edges);
272  TIntPrSet EdgeSet(Edges);
273  for (TBPGraph::TNodeI NI = OrigGraph->BegLNI(); NI < OrigGraph->EndLNI(); NI++) {
274  const int NId = NI.GetId();
275  for (int e = 0; e < NI.GetOutDeg(); e++) {
276  EdgeSet.AddKey(TIntPr(NId, NI.GetOutNId(e))); } // edges left-->right
277  Graph.AddNode(NI.GetId(), true); } // left nodes
278  for (TBPGraph::TNodeI NI = OrigGraph->BegRNI(); NI < OrigGraph->EndRNI(); NI++) {
279  Graph.AddNode(NI.GetId(), false); } // right nodes
280  IAssert(EdgeSet.Len() == Edges);
281  // edge switching
282  uint skip=0;
283  for (uint swps = 0; swps < 2*uint(Edges)*uint(NSwitch); swps++) {
284  const int keyId1 = EdgeSet.GetRndKeyId(Rnd);
285  const int keyId2 = EdgeSet.GetRndKeyId(Rnd);
286  if (keyId1 == keyId2) { skip++; continue; }
287  const TIntPr& E1 = EdgeSet[keyId1];
288  const TIntPr& E2 = EdgeSet[keyId2];
289  TIntPr NewE1(E1.Val1, E2.Val2), NewE2(E2.Val1, E1.Val2);
290  if (NewE1!=NewE2 && NewE1.Val1!=NewE1.Val2 && NewE2.Val1!=NewE2.Val2 && ! EdgeSet.IsKey(NewE1) && ! EdgeSet.IsKey(NewE2)) {
291  EdgeSet.DelKeyId(keyId1); EdgeSet.DelKeyId(keyId2);
292  EdgeSet.AddKey(TIntPr(NewE1));
293  EdgeSet.AddKey(TIntPr(NewE2));
294  } else { skip++; }
295  if (swps % Edges == 0) {
296  printf("\r %uk/%uk: %uk skip [%s]", swps/1000u, 2*uint(Edges)*uint(NSwitch)/1000u, skip/1000u, ExeTm.GetStr());
297  if (ExeTm.GetSecs() > 2*3600) { printf(" *** Time limit!\n"); break; } // time limit 2 hours
298  }
299  }
300  printf("\r total %uk switchings attempted, %uk skiped [%s]\n", 2*uint(Edges)*uint(NSwitch)/1000u, skip/1000u, ExeTm.GetStr());
301  for (int e = 0; e < EdgeSet.Len(); e++) {
302  Graph.AddEdge(EdgeSet[e].Val1, EdgeSet[e].Val2); }
303  return GraphPt;
304 }
#define IAssert(Cond)
Definition: bd.h:262
TPair< TInt, TInt > TIntPr
Definition: ds.h:83
void Reserve(const int &Nodes, const int &Edges)
Reserves memory for a biparite graph of Nodes nodes and Edges edges.
Definition: graph.cpp:740
Definition: tm.h:354
unsigned int uint
Definition: bd.h:11
Node iterator. Only forward iteration (operator++) is supported.
Definition: graph.h:857
int AddNode(int NId=-1, const bool &LeftNode=true)
Adds a node of ID NId to the graph.
Definition: graph.cpp:621
int AddEdge(const int &LeftNId, const int &RightNId)
Adds an edge between a node LeftNId on the left and a node RightNId on the right side of the bipartit...
Definition: graph.cpp:655
Definition: ds.h:32
Bipartite graph.
Definition: graph.h:825
double GetSecs() const
Definition: tm.h:365
TVal1 Val1
Definition: ds.h:34
static PBPGraph New()
Static constructor that returns a pointer to the graph. Call: PBPGraph BPGraph = TBPGraph::New();.
Definition: graph.h:951
TVal2 Val2
Definition: ds.h:35
Definition: bd.h:196
const char * GetStr() const
Definition: tm.h:367
PNGraph TSnap::GenRMat ( const int &  Nodes,
const int &  Edges,
const double &  A,
const double &  B,
const double &  C,
TRnd Rnd 
)

Generates a R-MAT graph using recursive descent into a 2x2 matrix [A,B; C, 1-(A+B+C)].

R-MAT Generator. The modes is based on the recursive descent into a 2x2 matrix [A,B; C, 1-(A+B+C)]. See: R-MAT Generator: A Recursive Model for Graph Mining. D. Chakrabarti, Y. Zhan and C. Faloutsos, in SIAM Data Mining 2004. URL: http://www.cs.cmu.edu/~deepay/mywww/papers/siam04.pdf

Definition at line 478 of file ggen.cpp.

478  {
479  PNGraph GraphPt = TNGraph::New();
480  TNGraph& Graph = *GraphPt;
481  Graph.Reserve(Nodes, Edges);
482  IAssert(A+B+C < 1.0);
483  int rngX, rngY, offX, offY;
484  int Depth=0, Collisions=0, Cnt=0, PctDone=0;
485  const int EdgeGap = Edges / 100 + 1;
486  // sum of parameters (probabilities)
487  TVec<double> sumA(128, 0), sumAB(128, 0), sumAC(128, 0), sumABC(128, 0); // up to 2^128 vertices ~ 3.4e38
488  for (int i = 0; i < 128; i++) {
489  const double a = A * (Rnd.GetUniDev() + 0.5);
490  const double b = B * (Rnd.GetUniDev() + 0.5);
491  const double c = C * (Rnd.GetUniDev() + 0.5);
492  const double d = (1.0 - (A+B+C)) * (Rnd.GetUniDev() + 0.5);
493  const double abcd = a+b+c+d;
494  sumA.Add(a / abcd);
495  sumAB.Add((a+b) / abcd);
496  sumAC.Add((a+c) / abcd);
497  sumABC.Add((a+b+c) / abcd);
498  }
499  // nodes
500  for (int node = 0; node < Nodes; node++) {
501  IAssert(Graph.AddNode(-1) == node);
502  }
503  // edges
504  for (int edge = 0; edge < Edges; ) {
505  rngX = Nodes; rngY = Nodes; offX = 0; offY = 0;
506  Depth = 0;
507  // recurse the matrix
508  while (rngX > 1 || rngY > 1) {
509  const double RndProb = Rnd.GetUniDev();
510  if (rngX>1 && rngY>1) {
511  if (RndProb < sumA[Depth]) { rngX/=2; rngY/=2; }
512  else if (RndProb < sumAB[Depth]) { offX+=rngX/2; rngX-=rngX/2; rngY/=2; }
513  else if (RndProb < sumABC[Depth]) { offY+=rngY/2; rngX/=2; rngY-=rngY/2; }
514  else { offX+=rngX/2; offY+=rngY/2; rngX-=rngX/2; rngY-=rngY/2; }
515  } else
516  if (rngX>1) { // row vector
517  if (RndProb < sumAC[Depth]) { rngX/=2; rngY/=2; }
518  else { offX+=rngX/2; rngX-=rngX/2; rngY/=2; }
519  } else
520  if (rngY>1) { // column vector
521  if (RndProb < sumAB[Depth]) { rngX/=2; rngY/=2; }
522  else { offY+=rngY/2; rngX/=2; rngY-=rngY/2; }
523  } else { Fail; }
524  Depth++;
525  }
526  // add edge
527  const int NId1 = offX;
528  const int NId2 = offY;
529  if (NId1 != NId2 && ! Graph.IsEdge(NId1, NId2)) {
530  Graph.AddEdge(NId1, NId2);
531  if (++Cnt > EdgeGap) {
532  Cnt=0; printf("\r %d%% edges", ++PctDone); }
533  edge++;
534  } else {
535  Collisions++; }
536  }
537  printf("\r RMat: nodes:%d, edges:%d, Iterations:%d, Collisions:%d (%.1f%%).\n", Nodes, Edges,
538  Edges+Collisions, Collisions, 100*Collisions/double(Edges+Collisions));
539  Graph.Defrag();
540  return GraphPt;
541 }
#define IAssert(Cond)
Definition: bd.h:262
static PNGraph New()
Static constructor that returns a pointer to the graph. Call: PNGraph Graph = TNGraph::New().
Definition: graph.h:405
#define Fail
Definition: bd.h:238
int AddNode(int NId=-1)
Adds a node of ID NId to the graph.
Definition: graph.cpp:208
int AddEdge(const int &SrcNId, const int &DstNId)
Adds an edge from node IDs SrcNId to node DstNId to the graph.
Definition: graph.cpp:286
bool IsEdge(const int &SrcNId, const int &DstNId, const bool &IsDir=true) const
Tests whether an edge from node IDs SrcNId to DstNId exists in the graph.
Definition: graph.cpp:313
void Defrag(const bool &OnlyNodeLinks=false)
Defragments the graph.
Definition: graph.cpp:332
Directed graph.
Definition: graph.h:293
double GetUniDev()
Definition: dt.h:30
void Reserve(const int &Nodes, const int &Edges)
Reserves memory for a graph of Nodes nodes and Edges edges.
Definition: graph.h:508
Definition: bd.h:196
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
PNGraph TSnap::GenRMatEpinions ( )

Generates a R-Mat graph, with a synthetic copy of the Epinions social network.

R-Mat generator with parameters set so that it generates a synthetic copy of the Epinions social network. The original Epinions social network can be downloaded at http://snap.stanford.edu/data/soc-Epinions1.html

Definition at line 547 of file ggen.cpp.

547  {
548  return GenRMat(75888, 508837, 0.550, 0.228, 0.212);
549 }
PNGraph GenRMat(const int &Nodes, const int &Edges, const double &A, const double &B, const double &C, TRnd &Rnd)
Generates a R-MAT graph using recursive descent into a 2x2 matrix [A,B; C, 1-(A+B+C)].
Definition: ggen.cpp:478
PBPGraph TSnap::GenRndBipart ( const int &  LeftNodes,
const int &  RightNodes,
const int &  Edges,
TRnd Rnd 
)

Generates a random bipartite graph.

Definition at line 5 of file ggen.cpp.

5  {
7  for (int i = 0; i < LeftNodes; i++) { G->AddNode(i, true); }
8  for (int i = 0; i < RightNodes; i++) { G->AddNode(LeftNodes+i, false); }
9  IAssertR(Edges <= LeftNodes*RightNodes, "Too many edges in the bipartite graph!");
10  for (int edges = 0; edges < Edges; ) {
11  const int LNId = Rnd.GetUniDevInt(LeftNodes);
12  const int RNId = LeftNodes + Rnd.GetUniDevInt(RightNodes);
13  if (G->AddEdge(LNId, RNId) != -2) { edges++; } // is new edge
14  }
15  return G;
16 }
#define IAssertR(Cond, Reason)
Definition: bd.h:265
static PBPGraph New()
Static constructor that returns a pointer to the graph. Call: PBPGraph BPGraph = TBPGraph::New();.
Definition: graph.h:951
Definition: bd.h:196
int GetUniDevInt(const int &Range=0)
Definition: dt.cpp:39
PUNGraph TSnap::GenRndDegK ( const int &  Nodes,
const int &  NodeDeg,
const int &  NSwitch,
TRnd Rnd 
)

Generates a random graph where each node has degree exactly NodeDeg.

Definition at line 18 of file ggen.cpp.

18  {
19  // create degree sequence
20  TIntV DegV(Nodes, 0);
21  int DegSum=0;
22  for (int i = 0; i < Nodes; i++) {
23  DegV.Add(NodeDeg);
24  DegSum += NodeDeg;
25  }
26  IAssert(DegSum % 2 == 0);
27  PUNGraph G = GenDegSeq(DegV, Rnd); // get some graph that obeys the degree sequnce
28  return GenRewire(G, NSwitch, Rnd); // make it random
29 }
#define IAssert(Cond)
Definition: bd.h:262
PUNGraph GenDegSeq(const TIntV &DegSeqV, TRnd &Rnd)
Generates a random graph with exact degree sequence.
Definition: ggen.cpp:58
PBPGraph GenRewire(const PBPGraph &OrigGraph, const int &NSwitch, TRnd &Rnd)
Rewire a random bipartite graph. Keeps node degrees the same, but randomly rewires the edges...
Definition: ggen.cpp:263
template<class PGraph >
PGraph TSnap::GenRndGnm ( const int &  Nodes,
const int &  Edges,
const bool &  IsDir = true,
TRnd Rnd = TInt::Rnd 
)

Generates an Erdos-Renyi random graph.

Definition at line 218 of file ggen.h.

218  {
219  PGraph GraphPt = PGraph::New();
220  typename PGraph::TObj& Graph = *GraphPt;
221  Graph.Reserve(Nodes, Edges);
222  IAssertR((1.0 * (Nodes-1) / 2 * (IsDir ? 2 : 1)) >= (1.0 * Edges / Nodes), TStr::Fmt("Not enough nodes (%d), for edges (%d).", Nodes, Edges));
223  for (int node = 0; node < Nodes; node++) {
224  IAssert(Graph.AddNode(node) == node);
225  }
226  for (int edge = 0; edge < Edges; ) {
227  const int SrcNId = Rnd.GetUniDevInt(Nodes);
228  const int DstNId = Rnd.GetUniDevInt(Nodes);
229  if (SrcNId != DstNId && Graph.AddEdge(SrcNId, DstNId) != -2) { // is new edge
230  if (! IsDir) { Graph.AddEdge(DstNId, SrcNId); }
231  edge++;
232  }
233  }
234  return GraphPt;
235 }
#define IAssert(Cond)
Definition: bd.h:262
#define IAssertR(Cond, Reason)
Definition: bd.h:265
static TStr Fmt(const char *FmtStr,...)
Definition: dt.cpp:1599
int GetUniDevInt(const int &Range=0)
Definition: dt.cpp:39
PUNGraph TSnap::GenRndPowerLaw ( const int &  Nodes,
const double &  PowerExp,
const bool &  ConfModel,
TRnd Rnd 
)

Generates a random scale-free graph with power-law degree distribution.

Generates a random scale-free graph with power-law degree distribution with exponent PowerExp. The method uses either the Configuration model (fast but the result is approximate) or the Edge Rewiring method (slow but exact).

Definition at line 34 of file ggen.cpp.

34  {
35  TIntV DegSeqV;
36  uint DegSum=0;
37  for (int n = 0; n < Nodes; n++) {
38  const int Val = (int) TMath::Round(Rnd.GetPowerDev(PowerExp));
39  if (! (Val >= 1 && Val < Nodes/2)) { n--; continue; } // skip nodes with too large degree
40  DegSeqV.Add(Val);
41  DegSum += Val;
42  }
43  printf("%d nodes, %u edges\n", Nodes, DegSum);
44  if (DegSum % 2 == 1) { DegSeqV[0] += 1; }
45  if (ConfModel) {
46  // use configuration model -- fast but does not exactly obey the degree sequence
47  return GenConfModel(DegSeqV, Rnd);
48  } else {
49  PUNGraph G = TSnap::GenDegSeq(DegSeqV, Rnd);
50  return TSnap::GenRewire(G, 10, Rnd);
51  }
52 }
PUNGraph GenRewire(const PUNGraph &OrigGraph, const int &NSwitch, TRnd &Rnd)
Rewire a random undirected graph. Keeps node degrees the same, but randomly rewires the edges...
Definition: ggen.cpp:165
unsigned int uint
Definition: bd.h:11
PUNGraph GenDegSeq(const TIntV &DegSeqV, TRnd &Rnd)
Generates a random graph with exact degree sequence.
Definition: ggen.cpp:58
static double Round(const double &Val)
Definition: xmath.h:16
PUNGraph GenConfModel(const PUNGraph &G)
Generate a random graph using (approximately) the same node degrees as in G using the configuration m...
Definition: ggen.cpp:335
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
double GetPowerDev(const double &AlphaSlope)
Definition: dt.h:47
PUNGraph TSnap::GenSmallWorld ( const int &  Nodes,
const int &  NodeOutDeg,
const double &  RewireProb,
TRnd Rnd 
)

Generates a randomly small-world graph using the Watts-Strogatz model.

Generates a small-world graph using the Watts-Strogatz model. We assume a circle where each node creates links to NodeOutDeg other nodes. This way at the end each node is connected to 2*NodeOutDeg other nodes. See: Collective dynamics of 'small-world' networks. Watts and Strogatz. URL: http://research.yahoo.com/files/w_s_NATURE_0.pdf

Definition at line 412 of file ggen.cpp.

412  {
413  THashSet<TIntPr> EdgeSet(Nodes*NodeOutDeg);
414 
415  IAssertR(Nodes > NodeOutDeg, TStr::Fmt("Insufficient nodes for out degree, %d!", NodeOutDeg));
416  for (int node = 0; node < Nodes; node++) {
417  const int src = node;
418  for (int edge = 1; edge <= NodeOutDeg; edge++) {
419  int dst = (node+edge) % Nodes; // edge to next neighbor
420  if (Rnd.GetUniDev() < RewireProb) { // random edge
421  dst = Rnd.GetUniDevInt(Nodes);
422  while (dst == src || EdgeSet.IsKey(TIntPr(src, dst))) {
423  dst = Rnd.GetUniDevInt(Nodes); }
424  }
425  EdgeSet.AddKey(TIntPr(src, dst));
426  }
427  }
428  PUNGraph GraphPt = TUNGraph::New();
429  TUNGraph& Graph = *GraphPt;
430  Graph.Reserve(Nodes, EdgeSet.Len());
431  int node;
432  for (node = 0; node < Nodes; node++) {
433  IAssert(Graph.AddNode(node) == node);
434  }
435  for (int edge = 0; edge < EdgeSet.Len(); edge++) {
436  Graph.AddEdge(EdgeSet[edge].Val1, EdgeSet[edge].Val2);
437  }
438  Graph.Defrag();
439  return GraphPt;
440 }
#define IAssert(Cond)
Definition: bd.h:262
TPair< TInt, TInt > TIntPr
Definition: ds.h:83
#define IAssertR(Cond, Reason)
Definition: bd.h:265
int AddNode(int NId=-1)
Adds a node of ID NId to the graph.
Definition: graph.cpp:8
Undirected graph.
Definition: graph.h:32
void Reserve(const int &Nodes, const int &Edges)
Reserves memory for a graph of Nodes nodes and Edges edges.
Definition: graph.h:249
static PUNGraph New()
Static constructor that returns a pointer to the graph. Call: PUNGraph Graph = TUNGraph::New().
Definition: graph.h:149
int AddEdge(const int &SrcNId, const int &DstNId)
Adds an edge between node IDs SrcNId and DstNId to the graph.
Definition: graph.cpp:84
Definition: ds.h:32
static TStr Fmt(const char *FmtStr,...)
Definition: dt.cpp:1599
void Defrag(const bool &OnlyNodeLinks=false)
Defragments the graph.
Definition: graph.cpp:132
double GetUniDev()
Definition: dt.h:30
int GetUniDevInt(const int &Range=0)
Definition: dt.cpp:39
template<class PGraph >
PGraph TSnap::GenStar ( const int &  Nodes,
const bool &  IsDir = true 
)

Generates a graph with star topology. Node id 0 is in the center and then links to all other nodes.

Definition at line 91 of file ggen.h.

91  {
92  PGraph Graph = PGraph::TObj::New();
93  Graph->Reserve(Nodes, Nodes);
94  Graph->AddNode(0);
95  for (int n = 1; n < Nodes; n++) {
96  Graph->AddNode(n);
97  Graph->AddEdge(0, n);
98  if (Graph->HasFlag(gfDirected) && ! IsDir) { Graph->AddEdge(n, 0); }
99  }
100  return Graph;
101 }
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
template<class PGraph >
PGraph TSnap::GenTree ( const int &  Fanout,
const int &  Levels,
const bool &  IsDir = true,
const bool &  ChildPointsToParent = true 
)

Generates a tree graph of Levels levels with every parent having Fanout children.

Definition at line 133 of file ggen.h.

133  {
134  const int Nodes = (int) (pow(double(Fanout), double(Levels+1)) - 1) / (Fanout - 1);
135  const int Edges = Nodes - 1;
136  PGraph GraphPt = PGraph::New();
137  typename PGraph::TObj& Graph = *GraphPt;
138  Graph.Reserve(Nodes, Edges);
139  int node;
140  for (node = 0; node < Nodes; node++) {
141  Graph.AddNode(node); }
142  // non-leaf nodes
143  for (node = 0; node < (int) Nodes - (int) pow(double(Fanout), double(Levels)); node++) {
144  for (int edge = 1; edge <= Fanout; edge++) {
145  if (IsDir) {
146  if (ChildPointsToParent) { Graph.AddEdge(Fanout*node+edge, node); }
147  else { Graph.AddEdge(node, Fanout*node+edge); }
148  } else {
149  Graph.AddEdge(node, Fanout*node+edge); // link children
150  Graph.AddEdge(Fanout*node+edge, node);
151  }
152  }
153  }
154  return GraphPt;
155 }
void TSnap::Get1CnCom ( const PUNGraph Graph,
TCnComV Cn1ComV 
)

Returns 1-components: maximal connected components of that can be disconnected from the Graph by removing a single edge.

We find such components as follows: Find all bridge edges, remove them from the Graph, find largest component K and add back all bridges that do not touch K. Now, find the connected components of this graph.

Definition at line 98 of file cncom.cpp.

98  {
99  //TCnCom::GetWccCnt(Graph, SzCntV); IAssertR(SzCntV.Len() == 1, "Graph is not connected.");
100  TIntPrV EdgeV;
101  GetEdgeBridges(Graph, EdgeV);
102  if (EdgeV.Empty()) { Cn1ComV.Clr(false); return; }
103  PUNGraph TmpG = TUNGraph::New();
104  *TmpG = *Graph;
105  for (int e = 0; e < EdgeV.Len(); e++) {
106  TmpG->DelEdge(EdgeV[e].Val1, EdgeV[e].Val2); }
107  TCnComV CnComV; GetWccs(TmpG, CnComV);
108  IAssert(CnComV.Len() >= 2);
109  const TIntV& MxWcc = CnComV[0].NIdV;
110  TIntSet MxCcSet(MxWcc.Len());
111  for (int i = 0; i < MxWcc.Len(); i++) {
112  MxCcSet.AddKey(MxWcc[i]); }
113  // create new graph: bridges not touching MxCc of G with no bridges
114  for (int e = 0; e < EdgeV.Len(); e++) {
115  if (! MxCcSet.IsKey(EdgeV[e].Val1) && ! MxCcSet.IsKey(EdgeV[e].Val2)) {
116  TmpG->AddEdge(EdgeV[e].Val1, EdgeV[e].Val2); }
117  }
118  GetWccs(TmpG, Cn1ComV);
119  // remove the largest component of G
120  for (int c = 0; c < Cn1ComV.Len(); c++) {
121  if (MxCcSet.IsKey(Cn1ComV[c].NIdV[0])) {
122  Cn1ComV.Del(c); break; }
123  }
124 }
#define IAssert(Cond)
Definition: bd.h:262
void Del(const TSizeTy &ValN)
Removes the element at position ValN.
Definition: ds.h:1094
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
bool Empty() const
Tests whether the vector is empty.
Definition: ds.h:530
void Clr(const bool &DoDel=true, const TSizeTy &NoDelLim=-1)
Clears the contents of the vector.
Definition: ds.h:953
static PUNGraph New()
Static constructor that returns a pointer to the graph. Call: PUNGraph Graph = TUNGraph::New().
Definition: graph.h:149
int AddKey(const TKey &Key)
Definition: shash.h:1248
void DelEdge(const int &SrcNId, const int &DstNId)
Deletes an edge between node IDs SrcNId and DstNId from the graph.
Definition: graph.cpp:95
int AddEdge(const int &SrcNId, const int &DstNId)
Adds an edge between node IDs SrcNId and DstNId to the graph.
Definition: graph.cpp:84
void GetEdgeBridges(const PUNGraph &Graph, TIntPrV &EdgeV)
Returns bridge edges of a Graph.
Definition: cncom.cpp:55
void GetWccs(const PGraph &Graph, TCnComV &CnComV)
Returns all weakly connected components in a Graph.
Definition: cncom.h:376
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
void TSnap::Get1CnComSzCnt ( const PUNGraph Graph,
TIntPrV SzCntV 
)

Distribution of sizes of 1-components, maximal number of components that can be disconnected from the Graph by removing a single edge.

We find such components as follows: Find all bridge edges, remove them from the Graph, find largest component K and add back all bridges that do not touch K. Now, find the connected components of this graph.

Definition at line 70 of file cncom.cpp.

70  {
71  //TCnCom::GetWccCnt(Graph, SzCntV); IAssertR(SzCntV.Len() == 1, "Graph is not connected.");
72  TIntPrV EdgeV;
73  GetEdgeBridges(Graph, EdgeV);
74  if (EdgeV.Empty()) { SzCntV.Clr(false); return; }
75  PUNGraph TmpG = TUNGraph::New();
76  *TmpG = *Graph;
77  for (int e = 0; e < EdgeV.Len(); e++) {
78  TmpG->DelEdge(EdgeV[e].Val1, EdgeV[e].Val2); }
79  TCnComV CnComV; GetWccs(TmpG, CnComV);
80  IAssert(CnComV.Len() >= 2);
81  const TIntV& MxWcc = CnComV[0].NIdV;
82  TIntSet MxCcSet(MxWcc.Len());
83  for (int i = 0; i < MxWcc.Len(); i++) {
84  MxCcSet.AddKey(MxWcc[i]); }
85  // create new graph: bridges not touching MxCc of G with no bridges
86  for (int e = 0; e < EdgeV.Len(); e++) {
87  if (! MxCcSet.IsKey(EdgeV[e].Val1) && ! MxCcSet.IsKey(EdgeV[e].Val2)) {
88  TmpG->AddEdge(EdgeV[e].Val1, EdgeV[e].Val2); }
89  }
90  GetWccSzCnt(TmpG, SzCntV);
91  for (int c = 0; c < SzCntV.Len(); c++) {
92  if (SzCntV[c].Val1 == MxCcSet.Len()) {
93  SzCntV.Del(c); break; }
94  }
95 }
#define IAssert(Cond)
Definition: bd.h:262
void Del(const TSizeTy &ValN)
Removes the element at position ValN.
Definition: ds.h:1094
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
bool Empty() const
Tests whether the vector is empty.
Definition: ds.h:530
void Clr(const bool &DoDel=true, const TSizeTy &NoDelLim=-1)
Clears the contents of the vector.
Definition: ds.h:953
static PUNGraph New()
Static constructor that returns a pointer to the graph. Call: PUNGraph Graph = TUNGraph::New().
Definition: graph.h:149
int AddKey(const TKey &Key)
Definition: shash.h:1248
void DelEdge(const int &SrcNId, const int &DstNId)
Deletes an edge between node IDs SrcNId and DstNId from the graph.
Definition: graph.cpp:95
int AddEdge(const int &SrcNId, const int &DstNId)
Adds an edge between node IDs SrcNId and DstNId to the graph.
Definition: graph.cpp:84
void GetEdgeBridges(const PUNGraph &Graph, TIntPrV &EdgeV)
Returns bridge edges of a Graph.
Definition: cncom.cpp:55
void GetWccSzCnt(const PGraph &Graph, TIntPrV &WccSzCnt)
Returns a distribution of weakly connected component sizes.
Definition: cncom.h:337
void GetWccs(const PGraph &Graph, TCnComV &CnComV)
Returns all weakly connected components in a Graph.
Definition: cncom.h:376
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
template<class PGraph >
void TSnap::GetAnf ( const PGraph &  Graph,
const int &  SrcNId,
TIntFltKdV DistNbrsV,
const int &  MxDist,
const bool &  IsDir,
const int &  NApprox = 32 
)

Approximate Neighborhood Function of a node: Returns the (approximate) number of nodes reachable from SrcNId in less than H hops.

Parameters
SrcNIdStarting node.
DistNbrsVMaps between the distance H (in hops) and the number of nodes reachable in <=H hops.
MxDistMaximum number of hops the algorithm spreads from SrcNId.
IsDirfalse: consider links as undirected (drop link directions).
NApproxQuality of approximation. See the ANF paper.

Definition at line 205 of file anf.h.

205  {
206  TGraphAnf<PGraph> Anf(Graph, NApprox, 5, 0);
207  Anf.GetNodeAnf(SrcNId, DistNbrsV, MxDist, IsDir);
208 }
Definition: anf.h:33
template<class PGraph >
void TSnap::GetAnf ( const PGraph &  Graph,
TIntFltKdV DistNbrsV,
const int &  MxDist,
const bool &  IsDir,
const int &  NApprox = 32 
)

Approximate Neighborhood Function of a Graph: Returns the number of pairs of nodes reachable in less than H hops. For example, DistNbrsV.GetDat(0) is the number of nodes in the graph, DistNbrsV.GetDat(1) is the number of nodes+edges and so on.

Parameters
DistNbrsVMaps between the distance H (in hops) and the number of nodes reachable in <=H hops.
MxDistMaximum number of hops the algorithm spreads from SrcNId.
IsDirfalse: consider links as undirected (drop link directions).
NApproxQuality of approximation. See the ANF paper.

Definition at line 211 of file anf.h.

211  {
212  TGraphAnf<PGraph> Anf(Graph, NApprox, 5, 0);
213  Anf.GetGraphAnf(DistNbrsV, MxDist, IsDir);
214 }
Definition: anf.h:33
template<class PGraph >
double TSnap::GetAnfEffDiam ( const PGraph &  Graph,
const bool &  IsDir,
const double &  Percentile,
const int &  NApprox 
)

Returns a given Percentile of the shortest path length distribution of a Graph (based on a single run of ANF of approximation quality NApprox).

Parameters
IsDirfalse: consider links as undirected (drop link directions).

Definition at line 217 of file anf.h.

217  {
218  TIntFltKdV DistNbrsV;
219  TGraphAnf<PGraph> Anf(Graph, NApprox, 5, 0);
220  Anf.GetGraphAnf(DistNbrsV, -1, IsDir);
221  return TSnap::TSnapDetail::CalcEffDiam(DistNbrsV, Percentile);
222 }
double CalcEffDiam(const TIntFltKdV &DistNbrsCdfV, const double &Percentile)
Helper function for computing a given Percentile of a (unnormalized) cumulative distribution function...
Definition: anf.cpp:7
Definition: anf.h:33
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
template<class PGraph >
double TSnap::GetAnfEffDiam ( const PGraph &  Graph,
const int  NRuns = 1,
int  NApprox = -1 
)

Returns a 90-th percentile of the shortest path length distribution of a Graph (based on a NRuns runs of ANF of approximation quality NApprox).

Parameters
IsDirfalse: consider links as undirected (drop link directions).

Definition at line 225 of file anf.h.

225  {
226  //return TSnap::GetEffDiam(Graph, IsDir, 0.9, 32);
227  TMom Mom;
228  if (NApprox == -1) {
229  if (Graph->GetNodes() < 100000) { NApprox = 64; }
230  else if (Graph->GetNodes() < 1000000) { NApprox = 32; }
231  else { NApprox = 16; }
232  }
233  const bool IsDir = false;
234  for (int r = 0; r < NRuns; r++) {
235  Mom.Add(TSnap::GetAnfEffDiam(Graph, IsDir, 0.9, NApprox));
236  }
237  Mom.Def();
238  return Mom.GetMean();
239 }
double GetAnfEffDiam(const PGraph &Graph, const bool &IsDir, const double &Percentile, const int &NApprox)
Definition: anf.h:217
Definition: xmath.h:129
void Add(const TFlt &Val, const TFlt &Wgt=1)
Definition: xmath.h:217
double GetMean() const
Definition: xmath.h:240
void Def()
Definition: xmath.cpp:339
void TSnap::GetArtPoints ( const PUNGraph Graph,
TIntV ArtNIdV 
)

Returns articulation points of a Graph.

Articulation point (or a cut vertex) is any node that when removed increases the number of connected components.

Definition at line 48 of file cncom.cpp.

48  {
49  TArtPointVisitor Visitor(Graph->GetNodes());
50  TCnCom::GetDfsVisitor(Graph, Visitor);
51  Visitor.ArtSet.GetKeyV(ArtNIdV);
52 }
int GetNodes() const
Returns the number of nodes in the graph.
Definition: graph.h:162
static void GetDfsVisitor(const PGraph &Graph, TVisitor &Visitor)
Definition: cncom.h:124
Articulation point Depth-First-Search visitor class.
Definition: cncom.h:169
void TSnap::GetBetweennessCentr ( const PUNGraph Graph,
const TIntV BtwNIdV,
TIntFltH NodeBtwH,
const bool &  DoNodeCent,
TIntPrFltH EdgeBtwH,
const bool &  DoEdgeCent 
)

Computes (approximate) Beetweenness Centrality of all nodes and all edges of the network. To obtain exact betweenness values one needs to solve single-source shortest-path problem for every node. To speed up the algorithm we solve the shortest-path problem for the BtwNIdV subset of nodes. This gives centrality values that are about Graph->GetNodes()/BtwNIdV.Len() times lower than the exact betweenness centrality valus. See "A Faster Algorithm for Beetweenness Centrality", Ulrik Brandes, Journal of Mathematical Sociology, 2001, and "Centrality Estimation in Large Networks", Urlik Brandes and Christian Pich, 2006 for more details.

Definition at line 28 of file centr.cpp.

28  {
29  if (DoNodeCent) { NodeBtwH.Clr(); }
30  if (DoEdgeCent) { EdgeBtwH.Clr(); }
31  const int nodes = Graph->GetNodes();
32  TIntS S(nodes);
33  TIntQ Q(nodes);
34  TIntIntVH P(nodes); // one vector for every node
35  TIntFltH delta(nodes);
36  TIntH sigma(nodes), d(nodes);
37  // init
38  for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
39  if (DoNodeCent) {
40  NodeBtwH.AddDat(NI.GetId(), 0); }
41  if (DoEdgeCent) {
42  for (int e = 0; e < NI.GetOutDeg(); e++) {
43  if (NI.GetId() < NI.GetOutNId(e)) {
44  EdgeBtwH.AddDat(TIntPr(NI.GetId(), NI.GetOutNId(e)), 0); }
45  }
46  }
47  sigma.AddDat(NI.GetId(), 0);
48  d.AddDat(NI.GetId(), -1);
49  P.AddDat(NI.GetId(), TIntV());
50  delta.AddDat(NI.GetId(), 0);
51  }
52  // calc betweeness
53  for (int k=0; k < BtwNIdV.Len(); k++) {
54  const TUNGraph::TNodeI NI = Graph->GetNI(BtwNIdV[k]);
55  // reset
56  for (int i = 0; i < sigma.Len(); i++) {
57  sigma[i]=0; d[i]=-1; delta[i]=0; P[i].Clr(false);
58  }
59  S.Clr(false);
60  Q.Clr(false);
61  sigma.AddDat(NI.GetId(), 1);
62  d.AddDat(NI.GetId(), 0);
63  Q.Push(NI.GetId());
64  while (! Q.Empty()) {
65  const int v = Q.Top(); Q.Pop();
66  const TUNGraph::TNodeI NI2 = Graph->GetNI(v);
67  S.Push(v);
68  const int VDat = d.GetDat(v);
69  for (int e = 0; e < NI2.GetOutDeg(); e++) {
70  const int w = NI2.GetOutNId(e);
71  if (d.GetDat(w) < 0) { // find w for the first time
72  Q.Push(w);
73  d.AddDat(w, VDat+1);
74  }
75  //shortest path to w via v ?
76  if (d.GetDat(w) == VDat+1) {
77  sigma.AddDat(w) += sigma.GetDat(v);
78  P.GetDat(w).Add(v);
79  }
80  }
81  }
82  while (! S.Empty()) {
83  const int w = S.Top();
84  const double SigmaW = sigma.GetDat(w);
85  const double DeltaW = delta.GetDat(w);
86  const TIntV NIdV = P.GetDat(w);
87  S.Pop();
88  for (int i = 0; i < NIdV.Len(); i++) {
89  const int nid = NIdV[i];
90  const double c = (sigma.GetDat(nid)*1.0/SigmaW) * (1+DeltaW);
91  delta.AddDat(nid) += c;
92  if (DoEdgeCent) {
93  EdgeBtwH.AddDat(TIntPr(TMath::Mn(nid, w), TMath::Mx(nid, w))) += c; }
94  }
95  if (DoNodeCent && w != NI.GetId()) {
96  NodeBtwH.AddDat(w) += delta.GetDat(w)/2.0; }
97  }
98  }
99 }
static const T & Mn(const T &LVal, const T &RVal)
Definition: xmath.h:36
TPair< TInt, TInt > TIntPr
Definition: ds.h:83
static const T & Mx(const T &LVal, const T &RVal)
Definition: xmath.h:32
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
Node iterator. Only forward iteration (operator++) is supported.
Definition: graph.h:63
int GetNodes() const
Returns the number of nodes in the graph.
Definition: graph.h:162
int GetOutDeg() const
Returns out-degree of the current node (returns same as value GetDeg() since the graph is undirected)...
Definition: graph.h:86
const TVal & GetDat(const TVal &Val) const
Returns reference to the first occurrence of element Val.
Definition: ds.h:792
TNodeI GetNI(const int &NId) const
Returns an iterator referring to the node of ID NId in the graph.
Definition: graph.h:205
int GetOutNId(const int &NodeN) const
Returns ID of NodeN-th out-node (the node the current node points to).
Definition: graph.h:96
TNodeI EndNI() const
Returns an iterator referring to the past-the-end node in the graph.
Definition: graph.h:203
TVec< TInt > TIntV
Definition: ds.h:2473
void Clr(const bool &DoDel=true, const int &NoDelLim=-1, const bool &ResetDat=true)
Definition: hash.h:315
int GetId() const
Returns ID of the current node.
Definition: graph.h:80
TNodeI BegNI() const
Returns an iterator referring to the first node in the graph.
Definition: graph.h:201
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
void TSnap::GetBetweennessCentr ( const PUNGraph Graph,
TIntFltH NIdBtwH,
const double &  NodeFrac = 1.0 
)

Computes (approximate) Node Beetweenness Centrality based on a sample of NodeFrac nodes.

Parameters
NIdBtwHhash table mapping node ids to their corresponding betweenness centrality values.
NodeFracquality of approximation. NodeFrac=1.0 gives exact betweenness values.

Definition at line 103 of file centr.cpp.

103  {
104  TIntPrFltH EdgeBtwH;
105  TIntV NIdV; Graph->GetNIdV(NIdV);
106  if (NodeFrac < 1.0) { // calculate beetweenness centrality for a subset of nodes
107  NIdV.Shuffle(TInt::Rnd);
108  for (int i = int((1.0-NodeFrac)*NIdV.Len()); i > 0; i--) {
109  NIdV.DelLast(); }
110  }
111  GetBetweennessCentr(Graph, NIdV, NodeBtwH, true, EdgeBtwH, false);
112 }
void GetBetweennessCentr(const PUNGraph &Graph, TIntFltH &NodeBtwH, TIntPrFltH &EdgeBtwH, const double &NodeFrac)
Definition: centr.cpp:125
void GetNIdV(TIntV &NIdV) const
Gets a vector IDs of all nodes in the graph.
Definition: graph.cpp:125
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
static TRnd Rnd
Definition: dt.h:1050
void Shuffle(TRnd &Rnd)
Randomly shuffles the elements of the vector.
Definition: ds.h:1235
void DelLast()
Removes the last element of the vector.
Definition: ds.h:609
void TSnap::GetBetweennessCentr ( const PUNGraph Graph,
TIntPrFltH EdgeBtwH,
const double &  NodeFrac = 1.0 
)

Computes (approximate) Edge Beetweenness Centrality based on a sample of NodeFrac nodes.

Parameters
EdgeBtwHhash table mapping edges (pairs of node ids) to their corresponding betweenness centrality values.
NodeFracquality of approximation. NodeFrac=1.0 gives exact betweenness values.

Definition at line 114 of file centr.cpp.

114  {
115  TIntFltH NodeBtwH;
116  TIntV NIdV; Graph->GetNIdV(NIdV);
117  if (NodeFrac < 1.0) { // calculate beetweenness centrality for a subset of nodes
118  NIdV.Shuffle(TInt::Rnd);
119  for (int i = int((1.0-NodeFrac)*NIdV.Len()); i > 0; i--) {
120  NIdV.DelLast(); }
121  }
122  GetBetweennessCentr(Graph, NIdV, NodeBtwH, false, EdgeBtwH, true);
123 }
void GetBetweennessCentr(const PUNGraph &Graph, TIntFltH &NodeBtwH, TIntPrFltH &EdgeBtwH, const double &NodeFrac)
Definition: centr.cpp:125
void GetNIdV(TIntV &NIdV) const
Gets a vector IDs of all nodes in the graph.
Definition: graph.cpp:125
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
static TRnd Rnd
Definition: dt.h:1050
void Shuffle(TRnd &Rnd)
Randomly shuffles the elements of the vector.
Definition: ds.h:1235
void DelLast()
Removes the last element of the vector.
Definition: ds.h:609
void TSnap::GetBetweennessCentr ( const PUNGraph Graph,
TIntFltH NIdBtwH,
TIntPrFltH EdgeBtwH,
const double &  NodeFrac = 1.0 
)

Computes (approximate) Node and Edge Beetweenness Centrality based on a sample of NodeFrac nodes.

Parameters
NIdBtwHhash table mapping node ids to their corresponding betweenness centrality values.
EdgeBtwHhash table mapping edges (pairs of node ids) to their corresponding betweenness centrality values.
NodeFracquality of approximation. NodeFrac=1.0 gives exact betweenness values.

Definition at line 125 of file centr.cpp.

125  {
126  TIntV NIdV; Graph->GetNIdV(NIdV);
127  if (NodeFrac < 1.0) { // calculate beetweenness centrality for a subset of nodes
128  NIdV.Shuffle(TInt::Rnd);
129  for (int i = int((1.0-NodeFrac)*NIdV.Len()); i > 0; i--) {
130  NIdV.DelLast(); }
131  }
132  GetBetweennessCentr(Graph, NIdV, NodeBtwH, true, EdgeBtwH, true);
133 }
void GetBetweennessCentr(const PUNGraph &Graph, TIntFltH &NodeBtwH, TIntPrFltH &EdgeBtwH, const double &NodeFrac)
Definition: centr.cpp:125
void GetNIdV(TIntV &NIdV) const
Gets a vector IDs of all nodes in the graph.
Definition: graph.cpp:125
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
static TRnd Rnd
Definition: dt.h:1050
void Shuffle(TRnd &Rnd)
Randomly shuffles the elements of the vector.
Definition: ds.h:1235
void DelLast()
Removes the last element of the vector.
Definition: ds.h:609
template<class PGraph >
double TSnap::GetBfsEffDiam ( const PGraph &  Graph,
const int &  NTestNodes,
const bool &  IsDir = false 
)

Returns the (approximation of the) Effective Diameter (90-th percentile of the distribution of shortest path lengths) of a graph (by performing BFS from NTestNodes random starting nodes).

Parameters
IsDirfalse: ignore edge directions and consider edges/paths as undirected (in case they are directed).

Definition at line 278 of file bfsdfs.h.

278  {
279  int FullDiam;
280  double EffDiam;
281  GetBfsEffDiam(Graph, NTestNodes, IsDir, EffDiam, FullDiam);
282  return EffDiam;
283 }
double GetBfsEffDiam(const PGraph &Graph, const int &NTestNodes, const TIntV &SubGraphNIdV, const bool &IsDir, double &EffDiamX, int &FullDiamX)
Use the whole graph (all edges) to measure the shortest path lengths but only report the path lengths...
Definition: bfsdfs.h:321
template<class PGraph >
double TSnap::GetBfsEffDiam ( const PGraph &  Graph,
const int &  NTestNodes,
const bool &  IsDir,
double &  EffDiamX,
int &  FullDiamX 
)

Returns the (approximation of the) Effective Diameter and the Diameter of a graph (by performing BFS from NTestNodes random starting nodes).

Parameters
IsDirfalse: ignore edge directions and consider edges/paths as undirected (in case they are directed).

Definition at line 286 of file bfsdfs.h.

286  {
287  double AvgDiam;
288  EffDiam = -1; FullDiam = -1;
289  return GetBfsEffDiam(Graph, NTestNodes, IsDir, EffDiam, FullDiam, AvgDiam);
290 }
double GetBfsEffDiam(const PGraph &Graph, const int &NTestNodes, const TIntV &SubGraphNIdV, const bool &IsDir, double &EffDiamX, int &FullDiamX)
Use the whole graph (all edges) to measure the shortest path lengths but only report the path lengths...
Definition: bfsdfs.h:321
template<class PGraph >
double TSnap::GetBfsEffDiam ( const PGraph &  Graph,
const int &  NTestNodes,
const bool &  IsDir,
double &  EffDiamX,
int &  FullDiamX,
double &  AvgSPLX 
)

Returns the (approximation of the) Effective Diameter, the Diameter and the Average Shortest Path length in a graph (by performing BFS from NTestNodes random starting nodes). GetBfsEffDiam3.

Definition at line 293 of file bfsdfs.h.

293  {
294  EffDiam = -1; FullDiam = -1; AvgSPL = -1;
295  TIntFltH DistToCntH;
296  TBreathFS<PGraph> BFS(Graph);
297  // shotest paths
298  TIntV NodeIdV;
299  Graph->GetNIdV(NodeIdV); NodeIdV.Shuffle(TInt::Rnd);
300  for (int tries = 0; tries < TMath::Mn(NTestNodes, Graph->GetNodes()); tries++) {
301  const int NId = NodeIdV[tries];
302  BFS.DoBfs(NId, true, ! IsDir, -1, TInt::Mx);
303  for (int i = 0; i < BFS.NIdDistH.Len(); i++) {
304  DistToCntH.AddDat(BFS.NIdDistH[i]) += 1; }
305  }
306  TIntFltKdV DistNbrsPdfV;
307  double SumPathL=0, PathCnt=0;
308  for (int i = 0; i < DistToCntH.Len(); i++) {
309  DistNbrsPdfV.Add(TIntFltKd(DistToCntH.GetKey(i), DistToCntH[i]));
310  SumPathL += DistToCntH.GetKey(i) * DistToCntH[i];
311  PathCnt += DistToCntH[i];
312  }
313  DistNbrsPdfV.Sort();
314  EffDiam = TSnap::TSnapDetail::CalcEffDiamPdf(DistNbrsPdfV, 0.9); // effective diameter (90-th percentile)
315  FullDiam = DistNbrsPdfV.Last().Key; // approximate full diameter (max shortest path length over the sampled nodes)
316  AvgSPL = SumPathL/PathCnt; // average shortest path length
317  return EffDiam;
318 }
static const T & Mn(const T &LVal, const T &RVal)
Definition: xmath.h:36
static const int Mx
Definition: dt.h:1046
TKeyDat< TInt, TFlt > TIntFltKd
Definition: ds.h:371
static TRnd Rnd
Definition: dt.h:1050
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
double CalcEffDiamPdf(const TIntFltKdV &DistNbrsPdfV, const double &Percentile)
Helper function for computing a given Percentile of a (unnormalized) probability distribution functio...
Definition: anf.cpp:29
const TVal & Last() const
Returns a reference to the last element of the vector.
Definition: ds.h:539
void Shuffle(TRnd &Rnd)
Randomly shuffles the elements of the vector.
Definition: ds.h:1235
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
int Len() const
Definition: hash.h:186
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
const TKey & GetKey(const int &KeyId) const
Definition: hash.h:210
template<class PGraph >
double TSnap::GetBfsEffDiam ( const PGraph &  Graph,
const int &  NTestNodes,
const TIntV SubGraphNIdV,
const bool &  IsDir,
double &  EffDiamX,
int &  FullDiamX 
)

Use the whole graph (all edges) to measure the shortest path lengths but only report the path lengths between nodes in the SubGraphNIdV. GetBfsEffDiam4.

Definition at line 321 of file bfsdfs.h.

321  {
322  EffDiam = -1;
323  FullDiam = -1;
324 
325  TIntFltH DistToCntH;
326  TBreathFS<PGraph> BFS(Graph);
327  // shotest paths
328  TIntV NodeIdV(SubGraphNIdV); NodeIdV.Shuffle(TInt::Rnd);
329  TInt Dist;
330  for (int tries = 0; tries < TMath::Mn(NTestNodes, SubGraphNIdV.Len()); tries++) {
331  const int NId = NodeIdV[tries];
332  BFS.DoBfs(NId, true, ! IsDir, -1, TInt::Mx);
333  for (int i = 0; i < SubGraphNIdV.Len(); i++) {
334  if (BFS.NIdDistH.IsKeyGetDat(SubGraphNIdV[i], Dist)) {
335  DistToCntH.AddDat(Dist) += 1;
336  }
337  }
338  }
339  TIntFltKdV DistNbrsPdfV;
340  for (int i = 0; i < DistToCntH.Len(); i++) {
341  DistNbrsPdfV.Add(TIntFltKd(DistToCntH.GetKey(i), DistToCntH[i]));
342  }
343  DistNbrsPdfV.Sort();
344  EffDiam = TSnap::TSnapDetail::CalcEffDiamPdf(DistNbrsPdfV, 0.9); // effective diameter (90-th percentile)
345  FullDiam = DistNbrsPdfV.Last().Key; // approximate full diameter (max shortest path length over the sampled nodes)
346  return EffDiam; // average shortest path length
347 }
static const T & Mn(const T &LVal, const T &RVal)
Definition: xmath.h:36
static const int Mx
Definition: dt.h:1046
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
TKeyDat< TInt, TFlt > TIntFltKd
Definition: ds.h:371
static TRnd Rnd
Definition: dt.h:1050
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
double CalcEffDiamPdf(const TIntFltKdV &DistNbrsPdfV, const double &Percentile)
Helper function for computing a given Percentile of a (unnormalized) probability distribution functio...
Definition: anf.cpp:29
const TVal & Last() const
Returns a reference to the last element of the vector.
Definition: ds.h:539
Definition: dt.h:1041
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
int Len() const
Definition: hash.h:186
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
const TKey & GetKey(const int &KeyId) const
Definition: hash.h:210
template<class PGraph >
int TSnap::GetBfsFullDiam ( const PGraph &  Graph,
const int &  NTestNodes,
const bool &  IsDir = false 
)

Returns the (approximation of the) Diameter (maximum shortest path length) of a graph (by performing BFS from NTestNodes random starting nodes).

Parameters
IsDirfalse: ignore edge directions and consider edges/paths as undirected (in case they are directed).

Definition at line 270 of file bfsdfs.h.

270  {
271  int FullDiam;
272  double EffDiam;
273  GetBfsEffDiam(Graph, NTestNodes, IsDir, EffDiam, FullDiam);
274  return FullDiam;
275 }
double GetBfsEffDiam(const PGraph &Graph, const int &NTestNodes, const TIntV &SubGraphNIdV, const bool &IsDir, double &EffDiamX, int &FullDiamX)
Use the whole graph (all edges) to measure the shortest path lengths but only report the path lengths...
Definition: bfsdfs.h:321
template<class PGraph >
PNGraph TSnap::GetBfsTree ( const PGraph &  Graph,
const int &  StartNId,
const bool &  FollowOut,
const bool &  FollowIn 
)

Returns a directed Breadth-First-Search tree rooted at StartNId.

Returns a directed graph where a parent points to its child node. Tree is created by following in-links (parameter FollowIn = true) and/or out-links (parameter FollowOut = true).

Definition at line 186 of file bfsdfs.h.

186  {
187  TBreathFS<PGraph> BFS(Graph, false);
188  BFS.DoBfs(StartNId, FollowOut, FollowIn, -1, TInt::Mx);
189  PNGraph Tree = TNGraph::New();
190  BFS.NIdDistH.SortByDat();
191  for (int i = 0; i < BFS.NIdDistH.Len(); i++) {
192  const int NId = BFS.NIdDistH.GetKey(i);
193  const int Dist = BFS.NIdDistH[i];
194  typename PGraph::TObj::TNodeI NI = Graph->GetNI(NId);
195  if (!Tree->IsNode(NId)) {
196  Tree->AddNode(NId);
197  }
198  if (FollowOut) {
199  for (int e = 0; e < NI.GetInDeg(); e++) {
200  const int Prev = NI.GetInNId(e);
201  if (Tree->IsNode(Prev) && BFS.NIdDistH.GetDat(Prev)==Dist-1) {
202  Tree->AddEdge(Prev, NId); }
203  }
204  }
205  if (FollowIn) {
206  for (int e = 0; e < NI.GetOutDeg(); e++) {
207  const int Prev = NI.GetOutNId(e);
208  if (Tree->IsNode(Prev) && BFS.NIdDistH.GetDat(Prev)==Dist-1) {
209  Tree->AddEdge(Prev, NId); }
210  }
211  }
212  }
213  return Tree;
214 }
static PNGraph New()
Static constructor that returns a pointer to the graph. Call: PNGraph Graph = TNGraph::New().
Definition: graph.h:405
static const int Mx
Definition: dt.h:1046
Definition: bd.h:196
void TSnap::GetBiCon ( const PUNGraph Graph,
TCnComV BiCnComV 
)

Returns all bi-connected components of a Graph.

Parameters
BiCnComVis a vector of bi-connected components. Each component is defined by the IDs of its member nodes.

Definition at line 42 of file cncom.cpp.

42  {
43  TBiConVisitor Visitor(Graph->GetNodes());
44  TCnCom::GetDfsVisitor(Graph, Visitor);
45  BiCnComV = Visitor.CnComV;
46 }
int GetNodes() const
Returns the number of nodes in the graph.
Definition: graph.h:162
static void GetDfsVisitor(const PGraph &Graph, TVisitor &Visitor)
Definition: cncom.h:124
Biconnected componetns Depth-First-Search visitor class.
Definition: cncom.h:195
void TSnap::GetBiConSzCnt ( const PUNGraph Graph,
TIntPrV SzCntV 
)

Returns a distribution of bi-connected component sizes.

Parameters
SzCntVreturns a set of pairs (number of nodes in the bi-component, number of such components)

Definition at line 31 of file cncom.cpp.

31  {
32  TCnComV BiCnComV;
33  GetBiCon(Graph, BiCnComV);
34  TIntH SzCntH;
35  for (int c =0; c < BiCnComV.Len(); c++) {
36  SzCntH.AddDat(BiCnComV[c].Len()) += 1;
37  }
38  SzCntH.GetKeyDatPrV(SzCntV);
39  SzCntV.Sort();
40 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
void GetBiCon(const PUNGraph &Graph, TCnComV &BiCnComV)
Returns all bi-connected components of a Graph.
Definition: cncom.cpp:42
void GetKeyDatPrV(TVec< TPair< TKey, TDat > > &KeyDatPrV) const
Definition: hash.h:454
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
double TSnap::GetClosenessCentr ( const PUNGraph Graph,
const int &  NId 
)

Returns Closeness centrality of a given node NId. Closeness centrality of a node is defined as 1/FarnessCentrality.

Definition at line 22 of file centr.cpp.

22  {
23  const double Farness = GetFarnessCentr(Graph, NId);
24  if (Farness != 0.0) { return 1.0/Farness; }
25  else { return 0.0; }
26 }
double GetFarnessCentr(const PUNGraph &Graph, const int &NId)
Definition: centr.cpp:11
template<class PGraph >
double TSnap::GetClustCf ( const PGraph &  Graph,
int  SampleNodes = -1 
)

Computes the average clustering coefficient as defined in Watts and Strogatz, Collective dynamics of 'small-world' networks.

Considers the graph as undirected.

Definition at line 100 of file triad.h.

100  {
101  TIntTrV NIdCOTriadV;
102  GetTriads(Graph, NIdCOTriadV, SampleNodes);
103  if (NIdCOTriadV.Empty()) { return 0.0; }
104  double SumCcf = 0.0;
105  for (int i = 0; i < NIdCOTriadV.Len(); i++) {
106  const double OpenCnt = NIdCOTriadV[i].Val2()+NIdCOTriadV[i].Val3();
107  if (OpenCnt > 0) {
108  SumCcf += NIdCOTriadV[i].Val2() / OpenCnt; }
109  }
110  IAssert(SumCcf>=0);
111  return SumCcf / double(NIdCOTriadV.Len());
112 }
#define IAssert(Cond)
Definition: bd.h:262
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
bool Empty() const
Tests whether the vector is empty.
Definition: ds.h:530
void GetTriads(const PGraph &Graph, TIntTrV &NIdCOTriadV, int SampleNodes=-1)
Computes the number of open and close triads for every node of the network.
Definition: triad.h:212
template<class PGraph >
double TSnap::GetClustCf ( const PGraph &  Graph,
TFltPrV DegToCCfV,
int  SampleNodes = -1 
)

Computes the distribution of average clustering coefficient.

Considers the graph as undirected.

Parameters
DegToCCfVVector of pairs (degree, avg. clustering coefficient of nodes of that degree).
SampleNodesIf !=-1 then compute clustering coefficient only for a random sample of SampleNodes nodes. Useful for approximate but quick computations.

Definition at line 114 of file triad.h.

114  {
115  TIntTrV NIdCOTriadV;
116  GetTriads(Graph, NIdCOTriadV, SampleNodes);
117  THash<TInt, TFltPr> DegSumCnt;
118  double SumCcf = 0.0;
119  for (int i = 0; i < NIdCOTriadV.Len(); i++) {
120  const int D = NIdCOTriadV[i].Val2()+NIdCOTriadV[i].Val3();
121  const double Ccf = D!=0 ? NIdCOTriadV[i].Val2() / double(D) : 0.0;
122  TFltPr& SumCnt = DegSumCnt.AddDat(Graph->GetNI(NIdCOTriadV[i].Val1).GetDeg());
123  SumCnt.Val1 += Ccf;
124  SumCnt.Val2 += 1;
125  SumCcf += Ccf;
126  }
127  // get average clustering coefficient for each degree
128  DegToCCfV.Gen(DegSumCnt.Len(), 0);
129  for (int d = 0; d < DegSumCnt.Len(); d++) {
130  DegToCCfV.Add(TFltPr(DegSumCnt.GetKey(d).Val, double(DegSumCnt[d].Val1()/DegSumCnt[d].Val2())));
131  }
132  DegToCCfV.Sort();
133  return SumCcf / double(NIdCOTriadV.Len());
134 }
int Val
Definition: dt.h:1043
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
TPair< TFlt, TFlt > TFltPr
Definition: ds.h:99
void GetTriads(const PGraph &Graph, TIntTrV &NIdCOTriadV, int SampleNodes=-1)
Computes the number of open and close triads for every node of the network.
Definition: triad.h:212
Definition: hash.h:88
TVal1 Val1
Definition: ds.h:34
TVal2 Val2
Definition: ds.h:35
void Gen(const TSizeTy &_Vals)
Constructs a vector (an array) of _Vals elements.
Definition: ds.h:486
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
int Len() const
Definition: hash.h:186
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
const TKey & GetKey(const int &KeyId) const
Definition: hash.h:210
template<class PGraph >
double TSnap::GetClustCf ( const PGraph &  Graph,
TFltPrV DegToCCfV,
int64 ClosedTriadsX,
int64 OpenTriadsX,
int  SampleNodes = -1 
)

Computes the distribution of average clustering coefficient as well as the number of open and closed triads in the graph.

Considers the graph as undirected.

Parameters
DegToCCfVVector of pairs (degree, avg. clustering coefficient of nodes of that degree).
SampleNodesIf !=-1 then compute clustering coefficient only for a random sample of SampleNodes nodes. Useful for approximate but quick computations.

Definition at line 137 of file triad.h.

137  {
138  TIntTrV NIdCOTriadV;
139  GetTriads(Graph, NIdCOTriadV, SampleNodes);
140  THash<TInt, TFltPr> DegSumCnt;
141  double SumCcf = 0.0;
142  int64 closedTriads = 0;
143  int64 openTriads = 0;
144  for (int i = 0; i < NIdCOTriadV.Len(); i++) {
145  const int D = NIdCOTriadV[i].Val2()+NIdCOTriadV[i].Val3();
146  const double Ccf = D!=0 ? NIdCOTriadV[i].Val2() / double(D) : 0.0;
147  closedTriads += NIdCOTriadV[i].Val2;
148  openTriads += NIdCOTriadV[i].Val3;
149  TFltPr& SumCnt = DegSumCnt.AddDat(Graph->GetNI(NIdCOTriadV[i].Val1).GetDeg());
150  SumCnt.Val1 += Ccf;
151  SumCnt.Val2 += 1;
152  SumCcf += Ccf;
153  }
154  // get average clustering coefficient for each degree
155  DegToCCfV.Gen(DegSumCnt.Len(), 0);
156  for (int d = 0; d < DegSumCnt.Len(); d++) {
157  DegToCCfV.Add(TFltPr(DegSumCnt.GetKey(d).Val, DegSumCnt[d].Val1()/DegSumCnt[d].Val2()));
158  }
159  //if(closedTriads/3 > (uint64) TInt::Mx) { WarnNotify(TStr::Fmt("[%s line %d] %g closed triads.\n", __FILE__, __LINE__, float(closedTriads/3)).CStr()); }
160  //if(openTriads > (uint64) TInt::Mx) { WarnNotify(TStr::Fmt("[%s line %d] %g open triads.\n", __FILE__, __LINE__, float(openTriads/3)).CStr()); }
161  ClosedTriads = closedTriads/int64(3); // each triad is counted 3 times
162  OpenTriads = openTriads;
163  DegToCCfV.Sort();
164  return SumCcf / double(NIdCOTriadV.Len());
165 }
int Val
Definition: dt.h:1043
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
TPair< TFlt, TFlt > TFltPr
Definition: ds.h:99
void GetTriads(const PGraph &Graph, TIntTrV &NIdCOTriadV, int SampleNodes=-1)
Computes the number of open and close triads for every node of the network.
Definition: triad.h:212
long long int64
Definition: bd.h:27
Definition: hash.h:88
TVal1 Val1
Definition: ds.h:34
TVal2 Val2
Definition: ds.h:35
void Gen(const TSizeTy &_Vals)
Constructs a vector (an array) of _Vals elements.
Definition: ds.h:486
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
int Len() const
Definition: hash.h:186
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
const TKey & GetKey(const int &KeyId) const
Definition: hash.h:210
template<class PGraph >
int TSnap::GetCmnNbrs ( const PGraph &  Graph,
const int &  NId1,
const int &  NId2 
)

Returns a number of shared neighbors between a pair of nodes NId1 and NId2.

Definition at line 383 of file triad.h.

383  {
384  TIntV NbrV;
385  return GetCmnNbrs(Graph, NId1, NId2, NbrV);
386 }
int GetCmnNbrs(const PGraph &Graph, const int &NId1, const int &NId2, TIntV &NbrV)
Returns the shared neighbors between a pair of nodes NId1 and NId2.
Definition: triad.h:390
template<class PGraph >
int TSnap::GetCmnNbrs ( const PGraph &  Graph,
const int &  NId1,
const int &  NId2,
TIntV NbrV 
)

Returns the shared neighbors between a pair of nodes NId1 and NId2.

Definition at line 390 of file triad.h.

390  {
391  if (! Graph->IsNode(NId1) || ! Graph->IsNode(NId2)) { NbrV.Clr(false); return 0; }
392  typename PGraph::TObj::TNodeI NI1 = Graph->GetNI(NId1);
393  typename PGraph::TObj::TNodeI NI2 = Graph->GetNI(NId2);
394  NbrV.Clr(false);
395  NbrV.Reserve(TMath::Mn(NI1.GetDeg(), NI2.GetDeg()));
396  TIntSet NSet1(NI1.GetDeg()), NSet2(NI2.GetDeg());
397  for (int i = 0; i < NI1.GetDeg(); i++) {
398  const int nid = NI1.GetNbrNId(i);
399  if (nid!=NId1 && nid!=NId2) {
400  NSet1.AddKey(nid); }
401  }
402  for (int i = 0; i < NI2.GetDeg(); i++) {
403  const int nid = NI2.GetNbrNId(i);
404  if (NSet1.IsKey(nid)) {
405  NSet2.AddKey(nid);
406  }
407  }
408  NSet2.GetKeyV(NbrV);
409  return NbrV.Len();
410 }
static const T & Mn(const T &LVal, const T &RVal)
Definition: xmath.h:36
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
void Clr(const bool &DoDel=true, const TSizeTy &NoDelLim=-1)
Clears the contents of the vector.
Definition: ds.h:953
int AddKey(const TKey &Key)
Definition: shash.h:1248
void Reserve(const TSizeTy &_MxVals)
Reserves enough memory for the vector to store _MxVals elements.
Definition: ds.h:506
template<>
int TSnap::GetCmnNbrs< PUNGraph > ( const PUNGraph Graph,
const int &  NId1,
const int &  NId2,
TIntV NbrV 
)
inline

Definition at line 413 of file triad.h.

413  {
414  if (! Graph->IsNode(NId1) || ! Graph->IsNode(NId2)) { NbrV.Clr(false); return 0; }
415  const TUNGraph::TNodeI NI1 = Graph->GetNI(NId1);
416  const TUNGraph::TNodeI NI2 = Graph->GetNI(NId2);
417  int i=0, j=0;
418  NbrV.Clr(false);
419  NbrV.Reserve(TMath::Mn(NI1.GetDeg(), NI2.GetDeg()));
420  while (i < NI1.GetDeg() && j < NI2.GetDeg()) {
421  const int nid = NI1.GetNbrNId(i);
422  while (j < NI2.GetDeg() && NI2.GetNbrNId(j) < nid) { j++; }
423  if (j < NI2.GetDeg() && nid==NI2.GetNbrNId(j) && nid!=NId1 && nid!=NId2) {
424  IAssert(NbrV.Empty() || NbrV.Last() < nid);
425  NbrV.Add(nid);
426  j++;
427  }
428  i++;
429  }
430  return NbrV.Len();
431 }
#define IAssert(Cond)
Definition: bd.h:262
static const T & Mn(const T &LVal, const T &RVal)
Definition: xmath.h:36
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
Node iterator. Only forward iteration (operator++) is supported.
Definition: graph.h:63
bool Empty() const
Tests whether the vector is empty.
Definition: ds.h:530
int GetDeg() const
Returns degree of the current node.
Definition: graph.h:82
void Clr(const bool &DoDel=true, const TSizeTy &NoDelLim=-1)
Clears the contents of the vector.
Definition: ds.h:953
TNodeI GetNI(const int &NId) const
Returns an iterator referring to the node of ID NId in the graph.
Definition: graph.h:205
const TVal & Last() const
Returns a reference to the last element of the vector.
Definition: ds.h:539
int GetNbrNId(const int &NodeN) const
Returns ID of NodeN-th neighboring node.
Definition: graph.h:101
bool IsNode(const int &NId) const
Tests whether ID NId is a node.
Definition: graph.h:199
void Reserve(const TSizeTy &_MxVals)
Reserves enough memory for the vector to store _MxVals elements.
Definition: ds.h:506
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph >
void TSnap::GetDegCnt ( const PGraph &  Graph,
TIntPrV DegToCntV 
)

Returns a degree histogram: a set of pairs (degree, number of nodes of such degree)

Definition at line 223 of file alg.h.

223  {
224  TIntH DegToCntH;
225  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
226  DegToCntH.AddDat(NI.GetDeg())++; }
227  DegToCntV.Gen(DegToCntH.Len(), 0);
228  for (int i = 0; i < DegToCntH.Len(); i++) {
229  DegToCntV.Add(TIntPr(DegToCntH.GetKey(i), DegToCntH[i])); }
230  DegToCntV.Sort();
231 }
TPair< TInt, TInt > TIntPr
Definition: ds.h:83
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
void Gen(const TSizeTy &_Vals)
Constructs a vector (an array) of _Vals elements.
Definition: ds.h:486
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
int Len() const
Definition: hash.h:186
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
const TKey & GetKey(const int &KeyId) const
Definition: hash.h:210
template<class PGraph >
void TSnap::GetDegCnt ( const PGraph &  Graph,
TFltPrV DegToCntV 
)

Returns a degree histogram: a set of pairs (degree, number of nodes of such degree)

Definition at line 234 of file alg.h.

234  {
235  TIntH DegToCntH;
236  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
237  DegToCntH.AddDat(NI.GetDeg())++; }
238  DegToCntV.Gen(DegToCntH.Len(), 0);
239  for (int i = 0; i < DegToCntH.Len(); i++) {
240  DegToCntV.Add(TFltPr(DegToCntH.GetKey(i).Val, DegToCntH[i].Val)); }
241  DegToCntV.Sort();
242 }
int Val
Definition: dt.h:1043
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
TPair< TFlt, TFlt > TFltPr
Definition: ds.h:99
void Gen(const TSizeTy &_Vals)
Constructs a vector (an array) of _Vals elements.
Definition: ds.h:486
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
int Len() const
Definition: hash.h:186
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
const TKey & GetKey(const int &KeyId) const
Definition: hash.h:210
double TSnap::GetDegreeCentr ( const PUNGraph Graph,
const int &  NId 
)

Returns Degree centrality of a given node NId. Degree centrality if a node is defined as its degree/(N-1), where N is the number of nodes in the network.

Definition at line 5 of file centr.cpp.

5  {
6  if (Graph->GetNodes() > 1) {
7  return double(Graph->GetNI(NId).GetDeg())/double(Graph->GetNodes()-1); }
8  else { return 0.0; }
9 }
int GetNodes() const
Returns the number of nodes in the graph.
Definition: graph.h:162
int GetDeg() const
Returns degree of the current node.
Definition: graph.h:82
TNodeI GetNI(const int &NId) const
Returns an iterator referring to the node of ID NId in the graph.
Definition: graph.h:205
template<class PGraph >
void TSnap::GetDegSeqV ( const PGraph &  Graph,
TIntV DegV 
)

Returns a degree sequence vector.

Definition at line 245 of file alg.h.

245  {
246  DegV.Gen(Graph->GetNodes(), 0);
247  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
248  DegV.Add(NI.GetDeg());
249  }
250 }
void Gen(const TSizeTy &_Vals)
Constructs a vector (an array) of _Vals elements.
Definition: ds.h:486
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph >
void TSnap::GetDegSeqV ( const PGraph &  Graph,
TIntV InDegV,
TIntV OutDegV 
)

Returns an in- and out-degree sequence vectors.

Definition at line 253 of file alg.h.

253  {
254  InDegV.Gen(Graph->GetNodes(), 0);
255  OutDegV.Gen(Graph->GetNodes(), 0);
256  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
257  InDegV.Add(NI.GetInDeg());
258  OutDegV.Add(NI.GetOutDeg());
259  }
260 }
void Gen(const TSizeTy &_Vals)
Constructs a vector (an array) of _Vals elements.
Definition: ds.h:486
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph , class TEdgeDat >
PGraph TSnap::GetEDatSubGraph ( const PGraph &  Graph,
const TEdgeDat &  EDat,
const int &  Cmp 
)

Returns a subgraph of graph Graph with edges where edge data matches the parameters.

EDat provides the value for edge data matching. Cmp determines the comparison function. Edges whose edge data matches EDat are included in the resulting subgraph as well as all the nodes which connect to at least one edge in the subgraph. Node IDs are preserved. Nodes in the resulting subgraph have the same node IDs as nodes in Graph.

Values of Cmp can be -1, 0, or +1. If Cmp is -1, edges with edge data less than EDat are included in the resulting subgraph. If Cmp equals 0, the values of edge data and EDat have to match. If Cmp is +1, edge data has to be greater than EDat.

Definition at line 248 of file subgraph.h.

248  {
249  CAssert(HasGraphFlag(typename PGraph::TObj, gfEdgeDat));
250  PGraph NewGraphPt = PGraph::TObj::New();
251  typename PGraph::TObj& NewGraph = *NewGraphPt;
252  for (typename PGraph::TObj::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) {
253  if ((Cmp==1 && EI()>EDat) || (Cmp==-1 && EI()<EDat) || (Cmp==0 && EI()==EDat)) {
254  if (! NewGraph.IsNode(EI.GetSrcNId())) {
255  NewGraph.AddNode(Graph->GetNI(EI.GetSrcNId()));
256  }
257  if (! NewGraph.IsNode(EI.GetDstNId())) {
258  NewGraph.AddNode(Graph->GetNI(EI.GetDstNId()));
259  }
260  NewGraph.AddEdge(EI);
261  }
262  }
263  return NewGraphPt;
264 }
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
network with data on edges
Definition: gbase.h:16
#define CAssert(Cond)
Definition: bd.h:302
bool Cmp(const int &RelOp, const TRec &Rec1, const TRec &Rec2)
Definition: bd.h:426
template<class PGraph , class TEdgeDat >
PGraph TSnap::GetEDatSubGraph ( const PGraph &  Graph,
const TIntV NIdV,
const TEdgeDat &  EDat,
const int &  Cmp 
)

Returns a subgraph of graph Graph with NIdV nodes and edges where edge data matches the parameters.

The resulting subgraph contains all the nodes from Graph, which have node IDs in the NIdV vector and edges with both nodes in NIdV and whose edge data matches the parameters. Node IDs are preserved. Nodes in the resulting subgraph have the same node IDs as nodes in Graph.

EDat provides the value for edge data matching. Cmp determines the comparison function. Values of Cmp can be -1, 0, or +1. If Cmp is -1, edges with edge data less than EDat are included in the resulting subgraph. If Cmp equals 0, the values of edge data and EDat have to match. If Cmp is +1, edge data has to be greater than EDat.

Definition at line 268 of file subgraph.h.

268  {
269  CAssert(HasGraphFlag(typename PGraph::TObj, gfEdgeDat));
270  PGraph NewGraphPt = PGraph::TObj::New();
271  typename PGraph::TObj& NewGraph = *NewGraphPt;
272  NewGraph.Reserve(NIdV.Len(), -1);
273  for (int n = 0; n < NIdV.Len(); n++) {
274  NewGraph.AddNode(Graph->GetNI(NIdV[n]));
275  }
276  for (typename PGraph::TObj::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) {
277  if (NewGraph.IsNode(EI.GetSrcNId()) && NewGraph.IsNode(EI.GetDstNId()) &&
278  ((Cmp==1 && EI()>EDat)|| (Cmp==-1 && EI()<EDat) || (Cmp==0 && EI()==EDat))) {
279  NewGraph.AddEdge(EI); }
280  }
281  NewGraph.Defrag();
282  return NewGraphPt;
283 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
network with data on edges
Definition: gbase.h:16
#define CAssert(Cond)
Definition: bd.h:302
bool Cmp(const int &RelOp, const TRec &Rec1, const TRec &Rec2)
Definition: bd.h:426
void TSnap::GetEdgeBridges ( const PUNGraph Graph,
TIntPrV EdgeV 
)

Returns bridge edges of a Graph.

Edge is a bridge if, when removed, increases the number of connected components. See http://en.wikipedia.org/wiki/Bridge_(graph_theory)

Definition at line 55 of file cncom.cpp.

55  {
56  TCnComV BiCnComV;
57  GetBiCon(Graph, BiCnComV);
58  TIntPrSet EdgeSet;
59  for (int c = 0; c < BiCnComV.Len(); c++) {
60  const TIntV& NIdV = BiCnComV[c].NIdV;
61  if (NIdV.Len() == 2) {
62  EdgeSet.AddKey(TIntPr(TMath::Mn(NIdV[0], NIdV[1]), TMath::Mx(NIdV[0], NIdV[1])));
63  }
64  }
65  EdgeSet.GetKeyV(EdgeV);
66 }
static const T & Mn(const T &LVal, const T &RVal)
Definition: xmath.h:36
TPair< TInt, TInt > TIntPr
Definition: ds.h:83
static const T & Mx(const T &LVal, const T &RVal)
Definition: xmath.h:32
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
void GetKeyV(TVec< TKey > &KeyV) const
Definition: shash.h:1341
int AddKey(const TKey &Key)
Definition: shash.h:1248
void GetBiCon(const PUNGraph &Graph, TCnComV &BiCnComV)
Returns all bi-connected components of a Graph.
Definition: cncom.cpp:42
template<typename PGraph >
void TSnap::GetEdgesInOut ( const PGraph &  Graph,
const TIntV NIdV,
int &  EdgesInX,
int &  EdgesOutX 
)

Returns the number of edges between the nodes NIdV and the edges pointing outside the set NIdV.

Parameters
EdgesInNumber of edges between the nodes NIdV.
EdgesOutNumber of edges between the nodes in NIdV and the rest of the graph.

Definition at line 66 of file cmty.h.

66  {
67  EdgesIn=0;
68  EdgesOut=0;
69  TIntSet NIdSet(NIdV.Len());
70  for (int e = 0; e < NIdV.Len(); e++) {
71  NIdSet.AddKey(NIdV[e]); }
72  for (int e = 0; e < NIdV.Len(); e++) {
73  typename PGraph::TObj::TNodeI NI = Graph->GetNI(NIdV[e]);
74  for (int i = 0; i < NI.GetOutDeg(); i++) {
75  if (NIdSet.IsKey(NI.GetOutNId(i))) { EdgesIn += 1; }
76  else { EdgesOut += 1; }
77  }
78  }
79  EdgesIn /= 2;
80 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
int AddKey(const TKey &Key)
Definition: shash.h:1248
PUNGraph TSnap::GetEgonet ( const PUNGraph Graph,
const int  CtrNId,
int &  ArndEdges 
)

Returns the egonet of node CtrNId as center in undirected graph Graph. And returns number of edges around the egonet.

Definition at line 82 of file subgraph.cpp.

82  {
83  PUNGraph NewGraphPt = TUNGraph::New();
84  TUNGraph& NewGraph = *NewGraphPt;
85  NewGraph.AddNode(CtrNId);
86  const TUNGraph::TNodeI& CtrNode = Graph->GetNI(CtrNId);
87  for (int i = 0; i < CtrNode.GetInDeg(); ++i) {
88  NewGraph.AddNode(CtrNode.GetInNId(i));
89  }
90  ArndEdges = 0;
91  for (int i = 0; i < CtrNode.GetInDeg(); ++i) {
92  int NbrNId = CtrNode.GetInNId(i);
93  const TUNGraph::TNodeI& NbrNode = Graph->GetNI(NbrNId);
94  for (int j = 0; j < NbrNode.GetInDeg(); ++j) {
95  int NbrNbrNId = NbrNode.GetInNId(j);
96  if (NewGraph.IsNode(NbrNbrNId)) {
97  if (!NewGraph.IsEdge(NbrNId, NbrNbrNId)) {
98  NewGraph.AddEdge(NbrNId, NbrNbrNId);
99  }
100  } else {
101  ArndEdges++;
102  }
103  }
104  }
105  return NewGraphPt;
106 }
int AddNode(int NId=-1)
Adds a node of ID NId to the graph.
Definition: graph.cpp:8
Node iterator. Only forward iteration (operator++) is supported.
Definition: graph.h:63
Undirected graph.
Definition: graph.h:32
TNodeI GetNI(const int &NId) const
Returns an iterator referring to the node of ID NId in the graph.
Definition: graph.h:205
static PUNGraph New()
Static constructor that returns a pointer to the graph. Call: PUNGraph Graph = TUNGraph::New().
Definition: graph.h:149
int AddEdge(const int &SrcNId, const int &DstNId)
Adds an edge between node IDs SrcNId and DstNId to the graph.
Definition: graph.cpp:84
int GetInDeg() const
Returns in-degree of the current node (returns same as value GetDeg() since the graph is undirected)...
Definition: graph.h:84
bool IsNode(const int &NId) const
Tests whether ID NId is a node.
Definition: graph.h:199
bool IsEdge(const int &SrcNId, const int &DstNId) const
Tests whether an edge between node IDs SrcNId and DstNId exists in the graph.
Definition: graph.cpp:108
int GetInNId(const int &NodeN) const
Returns ID of NodeN-th in-node (the node pointing to the current node).
Definition: graph.h:91
PNGraph TSnap::GetEgonet ( const PNGraph Graph,
const int  CtrNId,
int &  InEdges,
int &  OutEdges 
)

Returns the egonet of node CtrNId as center in directed graph Graph. And returns number of edges go in and out the egonet.

Definition at line 108 of file subgraph.cpp.

108  {
109  PNGraph NewGraphPt = TNGraph::New();
110  TNGraph& NewGraph = *NewGraphPt;
111  NewGraph.AddNode(CtrNId);
112  const TNGraph::TNodeI& CtrNode = Graph->GetNI(CtrNId);
113  for (int i = 0; i < CtrNode.GetDeg(); ++i) {
114  NewGraph.AddNode(CtrNode.GetNbrNId(i));
115  }
116  InEdges = 0;
117  OutEdges = 0;
118  for (int i = 0; i < CtrNode.GetDeg(); ++i) {
119  int NbrNId = CtrNode.GetNbrNId(i);
120  const TNGraph::TNodeI& NbrNode = Graph->GetNI(NbrNId);
121  for (int j = 0; j < NbrNode.GetInDeg(); ++j) {
122  int NbrNbrNId = NbrNode.GetInNId(j);
123  if (NewGraph.IsNode(NbrNbrNId)) {
124  NewGraph.AddEdge(NbrNbrNId, NbrNId);
125  } else {
126  InEdges++;
127  }
128  }
129  for (int j = 0; j < NbrNode.GetOutDeg(); ++j) {
130  int NbrNbrNId = NbrNode.GetOutNId(j);
131  if (!NewGraph.IsNode(NbrNbrNId)) {
132  OutEdges++;
133  }
134  }
135  }
136  return NewGraphPt;
137 }
int GetNbrNId(const int &NodeN) const
Returns ID of NodeN-th neighboring node.
Definition: graph.h:356
static PNGraph New()
Static constructor that returns a pointer to the graph. Call: PNGraph Graph = TNGraph::New().
Definition: graph.h:405
int AddNode(int NId=-1)
Adds a node of ID NId to the graph.
Definition: graph.cpp:208
int AddEdge(const int &SrcNId, const int &DstNId)
Adds an edge from node IDs SrcNId to node DstNId to the graph.
Definition: graph.cpp:286
bool IsNode(const int &NId) const
Tests whether ID NId is a node.
Definition: graph.h:455
int GetDeg() const
Returns degree of the current node, the sum of in-degree and out-degree.
Definition: graph.h:340
Directed graph.
Definition: graph.h:293
int GetOutDeg() const
Returns out-degree of the current node.
Definition: graph.h:344
Node iterator. Only forward iteration (operator++) is supported.
Definition: graph.h:324
Definition: bd.h:196
int GetInDeg() const
Returns in-degree of the current node.
Definition: graph.h:342
int GetInNId(const int &NodeN) const
Returns ID of NodeN-th in-node (the node pointing to the current node).
Definition: graph.h:348
int GetOutNId(const int &NodeN) const
Returns ID of NodeN-th out-node (the node the current node points to).
Definition: graph.h:352
void TSnap::GetEigenVectorCentr ( const PUNGraph Graph,
TIntFltH NIdEigenH,
const double &  Eps = 1e-4,
const int &  MaxIter = 100 
)

Computes Eigenvector Centrality of all nodes in the network Eigenvector Centrality of a node N is defined recursively as the average of centrality values of N's neighbors in the network.

Definition at line 135 of file centr.cpp.

135  {
136  const int NNodes = Graph->GetNodes();
137  NIdEigenH.Gen(NNodes);
138  // initialize vector values
139  for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
140  NIdEigenH.AddDat(NI.GetId(), 1.0/NNodes);
141  IAssert(NI.GetId() == NIdEigenH.GetKey(NIdEigenH.Len()-1));
142  }
143  TFltV TmpV(NNodes);
144  for (int iter = 0; iter < MaxIter; iter++) {
145  int j = 0;
146  // add neighbor values
147  for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++, j++) {
148  TmpV[j] = 0;
149  for (int e = 0; e < NI.GetOutDeg(); e++) {
150  TmpV[j] += NIdEigenH.GetDat(NI.GetOutNId(e)); }
151  }
152 
153  // normalize
154  double sum = 0;
155  for (int i = 0; i < TmpV.Len(); i++) {
156  sum += (TmpV[i]*TmpV[i]);
157  }
158  sum = sqrt(sum);
159  for (int i = 0; i < TmpV.Len(); i++) {
160  TmpV[i] /= sum;
161  }
162 
163  // compute difference
164  double diff = 0.0;
165  j = 0;
166  for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++, j++) {
167  diff += fabs(NIdEigenH.GetDat(NI.GetId())-TmpV[j]);
168  }
169 
170  // set new values
171  j = 0;
172  for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++, j++) {
173  NIdEigenH.AddDat(NI.GetId(), TmpV[j]);
174  }
175 
176  if (diff < Eps) {
177  break;
178  }
179  }
180 }
#define IAssert(Cond)
Definition: bd.h:262
Node iterator. Only forward iteration (operator++) is supported.
Definition: graph.h:63
const TDat & GetDat(const TKey &Key) const
Definition: hash.h:220
int GetNodes() const
Returns the number of nodes in the graph.
Definition: graph.h:162
void Gen(const int &ExpectVals)
Definition: hash.h:180
TNodeI EndNI() const
Returns an iterator referring to the past-the-end node in the graph.
Definition: graph.h:203
TNodeI BegNI() const
Returns an iterator referring to the first node in the graph.
Definition: graph.h:201
int Len() const
Definition: hash.h:186
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
const TKey & GetKey(const int &KeyId) const
Definition: hash.h:210
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
void TSnap::GetEigVals ( const PUNGraph Graph,
const int &  EigVals,
TFltV EigValV 
)

Computes top EigVals eigenvalues of the adjacency matrix representing a given undirected Graph.

Definition at line 308 of file gsvd.cpp.

308  {
309  // Lanczos
310  TUNGraphMtx GraphMtx(Graph);
311  //const int Nodes = Graph->GetNodes();
312  //int CalcVals = int(2*EigVals);
313  //if (CalcVals > Nodes) { CalcVals = Nodes; }
314  //while (EigValV.Len() < EigVals && CalcVals < 3*EigVals) {
315  try {
316  if (EigVals > 4) {
317  TSparseSVD::SimpleLanczos(GraphMtx, 2*EigVals, EigValV, false); }
318  else { TFltVV EigVecVV; // this is much more precise, but also much slower
319  TSparseSVD::Lanczos(GraphMtx, EigVals, 3*EigVals, ssotFull, EigValV, EigVecVV, false); }
320  }
321  catch(...) {
322  printf("\n ***EXCEPTION: TRIED %d GOT %d values** \n", 2*EigVals, EigValV.Len()); }
323  if (EigValV.Len() < EigVals) {
324  printf(" ***TRIED %d GOT %d values** \n", 2*EigVals, EigValV.Len()); }
325  // CalcVals += EigVals;
326  //}
327  EigValV.Sort(false);
328  /*if (EigValV.Len() > EigVals) {
329  EigValV.Del(EigVals, EigValV.Len()-1); }
330  else {
331  while (EigValV.Len() < EigVals) EigValV.Add(1e-6);
332  }
333  IAssert(EigValV.Len() == EigVals);*/
334 }
static void Lanczos(const TMatrix &Matrix, int NumEig, int Iters, const TSpSVDReOrtoType &ReOrtoType, TFltV &EigValV, TFltVV &EigVecVV, const bool &SvdMatrixProductP=false)
Definition: linalg.cpp:1134
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
Definition: ds.h:3100
static void SimpleLanczos(const TMatrix &Matrix, const int &NumEig, TFltV &EigValV, const bool &DoLocalReortoP=false, const bool &SvdMatrixProductP=false)
Definition: linalg.cpp:1053
void TSnap::GetEigVec ( const PUNGraph Graph,
TFltV EigVecV 
)

Computes the leading eigenvector of the adjacency matrix representing a given undirected Graph.

Definition at line 336 of file gsvd.cpp.

336  {
337  TUNGraphMtx GraphMtx(Graph);
338  TFltV EigValV;
339  TFltVV EigVecVV;
340  TSparseSVD::Lanczos(GraphMtx, 1, 8, ssotFull, EigValV, EigVecVV, false);
341  EigVecVV.GetCol(0, EigVecV); // vector components are not sorted!!!
342  IsAllValVNeg(EigVecV, true);
343 }
static void Lanczos(const TMatrix &Matrix, int NumEig, int Iters, const TSpSVDReOrtoType &ReOrtoType, TFltV &EigValV, TFltVV &EigVecVV, const bool &SvdMatrixProductP=false)
Definition: linalg.cpp:1134
bool IsAllValVNeg(TFltV &ValV, const bool &InvertSign)
Definition: gsvd.cpp:163
void GetCol(const int &ColN, TVec< TVal > &Vec) const
Definition: ds.h:3267
Definition: ds.h:3100
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
void TSnap::GetEigVec ( const PUNGraph Graph,
const int &  EigVecs,
TFltV EigValV,
TVec< TFltV > &  EigVecV 
)

Computes top EigVecs eigenvalues and eigenvectors of the adjacency matrix representing a given undirected Graph.

Definition at line 346 of file gsvd.cpp.

346  {
347  const int Nodes = Graph->GetNodes();
348  // Lanczos
349  TUNGraphMtx GraphMtx(Graph);
350  int CalcVals = int(2*EigVecs);
351  if (CalcVals > Nodes) { CalcVals = Nodes; }
352  TFltVV EigVecVV;
353  //while (EigValV.Len() < EigVecs && CalcVals < 10*EigVecs) {
354  try {
355  TSparseSVD::Lanczos(GraphMtx, EigVecs, 2*EigVecs, ssotFull, EigValV, EigVecVV, false); }
356  catch(...) {
357  printf("\n ***EXCEPTION: TRIED %d GOT %d values** \n", CalcVals, EigValV.Len()); }
358  if (EigValV.Len() < EigVecs) {
359  printf(" ***TRIED %d GOT %d values** \n", CalcVals, EigValV.Len()); }
360  // CalcVals += EigVecs;
361  //}
362  TFltIntPrV EigValIdV;
363  for (int i = 0; i < EigValV.Len(); i++) {
364  EigValIdV.Add(TFltIntPr(EigValV[i], i));
365  }
366  EigValIdV.Sort(false);
367  EigValV.Sort(false);
368  for (int v = 0; v < EigValIdV.Len(); v++) { // vector components are not sorted!!!
369  EigVecV.Add();
370  EigVecVV.GetCol(EigValIdV[v].Val2, EigVecV.Last());
371  }
372  IsAllValVNeg(EigVecV[0], true);
373 }
TPair< TFlt, TInt > TFltIntPr
Definition: ds.h:97
static void Lanczos(const TMatrix &Matrix, int NumEig, int Iters, const TSpSVDReOrtoType &ReOrtoType, TFltV &EigValV, TFltVV &EigVecVV, const bool &SvdMatrixProductP=false)
Definition: linalg.cpp:1134
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
bool IsAllValVNeg(TFltV &ValV, const bool &InvertSign)
Definition: gsvd.cpp:163
void GetCol(const int &ColN, TVec< TVal > &Vec) const
Definition: ds.h:3267
int GetNodes() const
Returns the number of nodes in the graph.
Definition: graph.h:162
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
Definition: ds.h:3100
const TVal & Last() const
Returns a reference to the last element of the vector.
Definition: ds.h:539
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
template<class PGraph >
PGraph TSnap::GetESubGraph ( const PGraph &  Graph,
const TIntV EIdV 
)

Returns a subgraph of graph Graph with EIdV edges.

The resulting subgraph contains all the edges from Graph, which have edge IDs in the EIdV vector and all the nodes which connect to at least one edge in EIdV. Node and edge IDs are preserved. Nodes and edges in the resulting subgraph have the same IDs as in Graph.

Use this function for multi-graphs, where the edges have edge IDs.

Definition at line 206 of file subgraph.h.

206  {
207  CAssert(HasGraphFlag(typename PGraph::TObj, gfMultiGraph));
208  PGraph NewGraphPt = PGraph::TObj::New();
209  typename PGraph::TObj& NewGraph = *NewGraphPt;
210  NewGraph.Reserve(-1, EIdV.Len());
211  for (int edge = 0; edge < EIdV.Len(); edge++) {
212  const int EId = EIdV[edge];
213  IAssert(Graph->IsEdge(EId));
214  const typename PGraph::TObj::TEdgeI EI = Graph->GetEI(EId);
215  if (! NewGraph.IsNode(EI.GetSrcNId())) {
216  NewGraph.AddNode(Graph->GetNI(EI.GetSrcNId()));
217  }
218  if (! NewGraph.IsNode(EI.GetDstNId())) {
219  NewGraph.AddNode(Graph->GetNI(EI.GetDstNId()));
220  }
221  NewGraph.AddEdge(EI);
222  }
223  return NewGraphPt;
224 }
#define IAssert(Cond)
Definition: bd.h:262
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
have explicit edges (multigraph): TNEGraph, TNodeEdgeNet
Definition: gbase.h:14
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
#define CAssert(Cond)
Definition: bd.h:302
template<class PGraph >
PGraph TSnap::GetESubGraph ( const PGraph &  Graph,
const TIntPrV EdgeV 
)

Definition at line 227 of file subgraph.h.

227  {
228  PGraph NewGraphPt = PGraph::TObj::New();
229  typename PGraph::TObj& NewGraph = *NewGraphPt;
230  NewGraph.Reserve(-1, EdgeV.Len());
231  for (int edge = 0; edge < EdgeV.Len(); edge++) {
232  const int SrcNId = EdgeV[edge].Val1;
233  const int DstNId = EdgeV[edge].Val2;
234  const typename PGraph::TObj::TEdgeI EI = Graph->GetEI(SrcNId, DstNId);
235  if (! NewGraph.IsNode(EI.GetSrcNId())) {
236  NewGraph.AddNode(Graph->GetNI(EI.GetSrcNId()));
237  }
238  if (! NewGraph.IsNode(EI.GetDstNId())) {
239  NewGraph.AddNode(Graph->GetNI(EI.GetDstNId()));
240  }
241  NewGraph.AddEdge(EI);
242  }
243  return NewGraphPt;
244 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
double TSnap::GetFarnessCentr ( const PUNGraph Graph,
const int &  NId 
)

Returns Farness centrality of a given node NId. Farness centrality of a node is the average shortest path length to all other nodes that reside is the same connected component as the given node.

Definition at line 11 of file centr.cpp.

11  {
12  TIntH NDistH(Graph->GetNodes());
13  TSnap::GetShortPath<PUNGraph>(Graph, NId, NDistH, true, TInt::Mx);
14  double sum = 0;
15  for (TIntH::TIter I = NDistH.BegI(); I < NDistH.EndI(); I++) {
16  sum += I->Dat();
17  }
18  if (NDistH.Len() > 1) { return sum/double(NDistH.Len()-1); }
19  else { return 0.0; }
20 }
static const int Mx
Definition: dt.h:1046
int GetNodes() const
Returns the number of nodes in the graph.
Definition: graph.h:162
THKeyDat * EndI
Definition: hash.h:45
TStr TSnap::GetFlagStr ( const TGraphFlag GraphFlag)

Returns a string representation of a flag.

Definition at line 5 of file gbase.cpp.

5  {
6  switch (GraphFlag) {
7  case gfUndef : return "Undef";
8  case gfDirected : return "Directed";
9  case gfMultiGraph : return "Multigraph";
10  case gfNodeDat : return "NodeDat";
11  case gfEdgeDat : return "EdgeDat";
12  case gfSources : return "Sources";
13  case gfBipart : return "Bipartite";
14  default: FailR("Unknown graph type");
15  };
16  return TStr();
17 }
default value, no flags
Definition: gbase.h:12
have explicit edges (multigraph): TNEGraph, TNodeEdgeNet
Definition: gbase.h:14
network with data on edges
Definition: gbase.h:16
#define FailR(Reason)
Definition: bd.h:240
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
Definition: dt.h:412
nodes only store out-edges (but not in-edges). See TBigNet
Definition: gbase.h:17
network with data on nodes
Definition: gbase.h:15
bipartite graph
Definition: gbase.h:18
template<class PGraph >
void TSnap::GetHits ( const PGraph &  Graph,
TIntFltH NIdHubH,
TIntFltH NIdAuthH,
const int &  MaxIter = 20 
)

HITS: Hubs and Authorities For more info see: http://en.wikipedia.org/wiki/HITS_algorithm)

Definition at line 111 of file centr.h.

111  {
112  const int NNodes = Graph->GetNodes();
113  NIdHubH.Gen(NNodes);
114  NIdAuthH.Gen(NNodes);
115  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
116  NIdHubH.AddDat(NI.GetId(), 1.0);
117  NIdAuthH.AddDat(NI.GetId(), 1.0);
118  }
119  double Norm=0;
120  for (int iter = 0; iter < MaxIter; iter++) {
121  // update authority scores
122  Norm = 0;
123  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
124  double& Auth = NIdAuthH.GetDat(NI.GetId()).Val;
125  Auth = 0;
126  for (int e = 0; e < NI.GetInDeg(); e++) {
127  Auth += NIdHubH.GetDat(NI.GetInNId(e)); }
128  Norm += Auth*Auth;
129  }
130  Norm = sqrt(Norm);
131  for (int i = 0; i < NIdAuthH.Len(); i++) { NIdAuthH[i] /= Norm; }
132  // update hub scores
133  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
134  double& Hub = NIdHubH.GetDat(NI.GetId()).Val;
135  Hub = 0;
136  for (int e = 0; e < NI.GetOutDeg(); e++) {
137  Hub += NIdAuthH.GetDat(NI.GetOutNId(e)); }
138  Norm += Hub*Hub;
139  }
140  Norm = sqrt(Norm);
141  for (int i = 0; i < NIdHubH.Len(); i++) { NIdHubH[i] /= Norm; }
142  }
143  // make sure Hub and Authority scores normalize to L2 norm 1
144  Norm = 0.0;
145  for (int i = 0; i < NIdHubH.Len(); i++) { Norm += TMath::Sqr(NIdHubH[i]); }
146  Norm = sqrt(Norm);
147  for (int i = 0; i < NIdHubH.Len(); i++) { NIdHubH[i] /= Norm; }
148  Norm = 0.0;
149  for (int i = 0; i < NIdAuthH.Len(); i++) { Norm += TMath::Sqr(NIdAuthH[i]); }
150  Norm = sqrt(Norm);
151  for (int i = 0; i < NIdAuthH.Len(); i++) { NIdAuthH[i] /= Norm; }
152 }
const TDat & GetDat(const TKey &Key) const
Definition: hash.h:220
static double Sqr(const double &x)
Definition: xmath.h:12
void Gen(const int &ExpectVals)
Definition: hash.h:180
int Len() const
Definition: hash.h:186
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
template<class PGraph >
void TSnap::GetInDegCnt ( const PGraph &  Graph,
TIntPrV DegToCntV 
)

Returns an in-degree histogram: a set of pairs (in-degree, number of nodes of such in-degree)

Definition at line 179 of file alg.h.

179  {
180  TIntH DegToCntH;
181  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
182  DegToCntH.AddDat(NI.GetInDeg())++; }
183  DegToCntV.Gen(DegToCntH.Len(), 0);
184  for (int i = 0; i < DegToCntH.Len(); i++) {
185  DegToCntV.Add(TIntPr(DegToCntH.GetKey(i), DegToCntH[i])); }
186  DegToCntV.Sort();
187 }
TPair< TInt, TInt > TIntPr
Definition: ds.h:83
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
void Gen(const TSizeTy &_Vals)
Constructs a vector (an array) of _Vals elements.
Definition: ds.h:486
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
int Len() const
Definition: hash.h:186
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
const TKey & GetKey(const int &KeyId) const
Definition: hash.h:210
template<class PGraph >
void TSnap::GetInDegCnt ( const PGraph &  Graph,
TFltPrV DegToCntV 
)

Returns an in-degree histogram: a set of pairs (in-degree, number of nodes of such in-degree)

Definition at line 190 of file alg.h.

190  {
191  TIntH DegToCntH;
192  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
193  DegToCntH.AddDat(NI.GetInDeg())++; }
194  DegToCntV.Gen(DegToCntH.Len(), 0);
195  for (int i = 0; i < DegToCntH.Len(); i++) {
196  DegToCntV.Add(TFltPr(DegToCntH.GetKey(i).Val, DegToCntH[i].Val)); }
197  DegToCntV.Sort();
198 }
int Val
Definition: dt.h:1043
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
TPair< TFlt, TFlt > TFltPr
Definition: ds.h:99
void Gen(const TSizeTy &_Vals)
Constructs a vector (an array) of _Vals elements.
Definition: ds.h:486
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
int Len() const
Definition: hash.h:186
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
const TKey & GetKey(const int &KeyId) const
Definition: hash.h:210
void TSnap::GetInvParticipRat ( const PUNGraph Graph,
int  MaxEigVecs,
int  TimeLimit,
TFltPrV EigValIprV 
)

Computes Inverse participation ratio of a given graph. See Spectra of "real-world" graphs: Beyond the semicircle law by Farkas, Derenyi, Barabasi and Vicsek

Definition at line 377 of file gsvd.cpp.

377  {
378  TUNGraphMtx GraphMtx(Graph);
379  TFltVV EigVecVV;
380  TFltV EigValV;
381  TExeTm ExeTm;
382  if (MaxEigVecs<=1) { MaxEigVecs=1000; }
383  int EigVecs = TMath::Mn(Graph->GetNodes(), MaxEigVecs);
384  printf("start %d vecs...", EigVecs);
385  try {
386  TSparseSVD::Lanczos2(GraphMtx, EigVecs, TimeLimit, ssotFull, EigValV, EigVecVV, false);
387  } catch(...) {
388  printf("\n ***EXCEPTION: TRIED %d GOT %d values** \n", EigVecs, EigValV.Len()); }
389  printf(" ***TRIED %d GOT %d values in %s\n", EigVecs, EigValV.Len(), ExeTm.GetStr());
390  TFltV EigVec;
391  EigValIprV.Clr();
392  if (EigValV.Empty()) { return; }
393  for (int v = 0; v < EigVecVV.GetCols(); v++) {
394  EigVecVV.GetCol(v, EigVec);
395  EigValIprV.Add(TFltPr(EigValV[v], TSnapDetail::GetInvParticipRatEig(EigVec)));
396  }
397  EigValIprV.Sort();
398 }
static const T & Mn(const T &LVal, const T &RVal)
Definition: xmath.h:36
double GetInvParticipRatEig(const TFltV &EigVec)
Definition: gsvd.cpp:401
Definition: tm.h:354
static void Lanczos2(const TMatrix &Matrix, int MaxNumEig, int MaxSecs, const TSpSVDReOrtoType &ReOrtoType, TFltV &EigValV, TFltVV &EigVecVV, const bool &SvdMatrixProductP=false)
Definition: linalg.cpp:1290
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
void GetCol(const int &ColN, TVec< TVal > &Vec) const
Definition: ds.h:3267
int GetNodes() const
Returns the number of nodes in the graph.
Definition: graph.h:162
bool Empty() const
Tests whether the vector is empty.
Definition: ds.h:530
void Clr(const bool &DoDel=true, const TSizeTy &NoDelLim=-1)
Clears the contents of the vector.
Definition: ds.h:953
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
Definition: ds.h:3100
TPair< TFlt, TFlt > TFltPr
Definition: ds.h:99
const char * GetStr() const
Definition: tm.h:367
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
int GetCols() const
Definition: ds.h:3130
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
template<class PGraph >
PGraph TSnap::GetKCore ( const PGraph &  Graph,
const int &  K 
)

Returns the K-core of a graph. If the core of order K does not exist the function returns an empty graph.

Definition at line 106 of file kcore.h.

106  {
107  TKCore<PGraph> KCore(Graph);
108  KCore.GetCoreK(K);
109  return TSnap::GetSubGraph(Graph, KCore.GetNIdV());
110 }
PUNGraph GetSubGraph(const PUNGraph &Graph, const TIntV &NIdV, const bool &RenumberNodes)
Returns an induced subgraph of an undirected graph Graph with NIdV nodes with an optional node renumb...
Definition: subgraph.cpp:7
Definition: kcore.h:11
template<class PGraph >
int TSnap::GetKCoreEdges ( const PGraph &  Graph,
TIntPrV CoreIdSzV 
)

Returns the number of edges in each core of order K (where K=0, 1, ...)

Definition at line 126 of file kcore.h.

126  {
127  TKCore<PGraph> KCore(Graph);
128  CoreIdSzV.Clr();
129  CoreIdSzV.Add(TIntPr(0, Graph->GetEdges()));
130  for (int i = 1; KCore.GetNextCore() > 0; i++) {
131  CoreIdSzV.Add(TIntPr(i, KCore.GetCoreEdges()));
132  }
133  return KCore.GetCurK();
134 }
TPair< TInt, TInt > TIntPr
Definition: ds.h:83
void Clr(const bool &DoDel=true, const TSizeTy &NoDelLim=-1)
Clears the contents of the vector.
Definition: ds.h:953
Definition: kcore.h:11
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph >
int TSnap::GetKCoreNodes ( const PGraph &  Graph,
TIntPrV CoreIdSzV 
)

Returns the number of nodes in each core of order K (where K=0, 1, ...)

Definition at line 114 of file kcore.h.

114  {
115  TKCore<PGraph> KCore(Graph);
116  CoreIdSzV.Clr();
117  CoreIdSzV.Add(TIntPr(0, Graph->GetNodes()));
118  for (int i = 1; KCore.GetNextCore() > 0; i++) {
119  CoreIdSzV.Add(TIntPr(i, KCore.GetCoreNodes()));
120  }
121  return KCore.GetCurK();
122 }
TPair< TInt, TInt > TIntPr
Definition: ds.h:83
void Clr(const bool &DoDel=true, const TSizeTy &NoDelLim=-1)
Clears the contents of the vector.
Definition: ds.h:953
Definition: kcore.h:11
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph >
int TSnap::GetLen2Paths ( const PGraph &  Graph,
const int &  NId1,
const int &  NId2 
)

Returns the number of length 2 directed paths between a pair of nodes NId1, NId2 (NId1 –> U –> NId2).

Definition at line 436 of file triad.h.

436  {
437  TIntV NbrV;
438  return GetLen2Paths(Graph, NId1, NId2, NbrV);
439 }
int GetLen2Paths(const PGraph &Graph, const int &NId1, const int &NId2, TIntV &NbrV)
Returns the 2 directed paths between a pair of nodes NId1, NId2 (NId1 –> U –> NId2).
Definition: triad.h:444
template<class PGraph >
int TSnap::GetLen2Paths ( const PGraph &  Graph,
const int &  NId1,
const int &  NId2,
TIntV NbrV 
)

Returns the 2 directed paths between a pair of nodes NId1, NId2 (NId1 –> U –> NId2).

NbrV intermediary stores nodes U.

Definition at line 444 of file triad.h.

444  {
445  const typename PGraph::TObj::TNodeI NI = Graph->GetNI(NId1);
446  NbrV.Clr(false);
447  NbrV.Reserve(NI.GetOutDeg());
448  for (int e = 0; e < NI.GetOutDeg(); e++) {
449  const typename PGraph::TObj::TNodeI MidNI = Graph->GetNI(NI.GetOutNId(e));
450  if (MidNI.IsOutNId(NId2)) {
451  NbrV.Add(MidNI.GetId());
452  }
453  }
454  return NbrV.Len();
455 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
void Clr(const bool &DoDel=true, const TSizeTy &NoDelLim=-1)
Clears the contents of the vector.
Definition: ds.h:953
void Reserve(const TSizeTy &_MxVals)
Reserves enough memory for the vector to store _MxVals elements.
Definition: ds.h:506
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
int TSnap::GetMaxFlowIntEK ( PNEANet Net,
const int &  SrcNId,
const int &  SnkNId 
)

Returns the maximum integer valued flow in the network Net from source SrcNId to sink SnkNId.

Implements max flow using the Edmonds-Karp algorithm. http://en.wikipedia.org/wiki/Edmonds%E2%80%93Karp_algorithm Although the asymptotic run time of Edmonds-Karp is worse than that of Push Relabel, in practice Edmonds Karp works very well, especially if the network is sparse. Unless the degree of each node is on the order of the number of nodes, it is best to use Edmonds Karp over Push Relabel.

Definition at line 105 of file flow.cpp.

105  {
106  IAssert(Net->IsNode(SrcNId));
107  IAssert(Net->IsNode(SnkNId));
108  if (SrcNId == SnkNId) { return 0; }
109  int CapIndex = Net->GetIntAttrIndE(CapAttrName);
110  TIntV Flow(Net->GetMxEId());
111  // Initialize flow values to 0, and make sure capacities are nonnegative
112  for (TNEANet::TEdgeI EI = Net->BegEI(); EI != Net->EndEI(); EI++) {
113  IAssert(Net->GetIntAttrIndDatE(EI, CapIndex) >= 0);
114  Flow[EI.GetId()] = 0;
115  }
116  // Return 0 if user attempts to flow from a node to itself.
117  if (SrcNId == SnkNId) { return 0; }
118  int MaxFlow = 0, MinAug, CurNId;
119  while (true) {
120  TIntV MidToSrcAugV; TIntV MidToSnkAugV;
121  TIntQ FwdNodeQ; TIntQ BwdNodeQ;
122  TIntH PredEdgeH; TIntH SuccEdgeH;
123  MinAug = FindAugV(Net, CapIndex, Flow, FwdNodeQ, PredEdgeH, BwdNodeQ, SuccEdgeH, MidToSrcAugV, MidToSnkAugV, SrcNId, SnkNId);
124  if (MinAug == 0) { break; }
125  MaxFlow += MinAug;
126  CurNId = SrcNId;
127  for (int i = MidToSrcAugV.Len() - 1; i >= 0; i--) {
128  int NextEId = MidToSrcAugV[i];
129  const TNEANet::TEdgeI &EI = Net->GetEI(NextEId);
130  if (EI.GetSrcNId() == CurNId) {
131  Flow[NextEId] += MinAug;
132  CurNId = EI.GetDstNId();
133  } else {
134  Flow[NextEId] -= MinAug;
135  CurNId = EI.GetSrcNId();
136  }
137  }
138  for (int i = 0; i < MidToSnkAugV.Len(); i++) {
139  int NextEId = MidToSnkAugV[i];
140  const TNEANet::TEdgeI &EI = Net->GetEI(NextEId);
141  if (EI.GetSrcNId() == CurNId) {
142  Flow[NextEId] += MinAug;
143  CurNId = EI.GetDstNId();
144  } else {
145  Flow[NextEId] -= MinAug;
146  CurNId = EI.GetSrcNId();
147  }
148  }
149  }
150  return MaxFlow;
151 }
#define IAssert(Cond)
Definition: bd.h:262
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
int FindAugV(const PNEANet &Net, const int &CapIndex, TIntV &Flow, TIntQ &FwdNodeQ, TIntH &PredEdgeH, TIntQ &BwdNodeQ, TIntH &SuccEdgeH, TIntV &MidToSrcAugV, TIntV &MidToSnkAugV, const int &SrcNId, const int &SnkNId)
Returns the amount the flow can be augmented over the paths, 0 if no path can be found.
Definition: flow.cpp:71
int GetDstNId() const
Returns the destination of the edge.
Definition: network.h:1718
const TStr CapAttrName("capacity")
int GetSrcNId() const
Returns the source of the edge.
Definition: network.h:1716
Edge iterator. Only forward iteration (operator++) is supported.
Definition: network.h:1699
int TSnap::GetMaxFlowIntPR ( PNEANet Net,
const int &  SrcNId,
const int &  SnkNId 
)

Returns the maximum integer valued flow in the network Net from source SrcNId to sink SnkNId.

Implements max flow using the Edmonds-Karp algorithm. http://en.wikipedia.org/wiki/Edmonds%E2%80%93Karp_algorithm Although the asymptotic run time of Edmonds-Karp is worse than that of Push Relabel, in practice Edmonds Karp works very well, especially if the network is sparse. Unless the degree of each node is on the order of the number of nodes, it is best to use Edmonds Karp over Push Relabel.

Definition at line 410 of file flow.cpp.

410  {
411  IAssert(Net->IsNode(SrcNId));
412  IAssert(Net->IsNode(SnkNId));
413  if (SrcNId == SnkNId) { return 0; }
414 
415  TPRManager PRM(Net);
416  int MaxLabel = PRM.GetMaxLabel();
417 
418  TNEANet::TNodeI SrcNI = Net->GetNI(SrcNId);
419  for (int EdgeN = 0; EdgeN < SrcNI.GetOutDeg(); EdgeN++) {
420  int EId = SrcNI.GetOutEId(EdgeN);
421  int OutNId = SrcNI.GetOutNId(EdgeN);
422  if (OutNId != SrcNId) {
423  int Capacity = PRM.Capacity(EId);
424  PRM.Flow(EId) = Capacity;
425  PRM.Excess(OutNId) = Capacity;
426  }
427  }
428  GlobalRelabel(Net, PRM, SrcNId, SnkNId);
429  PRM.SetLabel(SrcNId, MaxLabel);
430  int RelabelCount = 1;
431  int GRRate = Net->GetNodes();
432  while (PRM.HasActive()) {
433  int NId = PRM.PopActive();
434  const TNEANet::TNodeI &NI = Net->GetNI(NId);
435  int PrevLabel = MaxLabel;
436  while (PRM.Excess(NId) > 0 && PRM.Label(NId) <= PrevLabel) {
437  PrevLabel = PRM.Label(NId);
438  int NbrNId = PushRelabel(PRM, NId, NI);
439  if (NbrNId != -1 && NbrNId != SnkNId && PRM.Excess(NbrNId) > 0 && !PRM.IsActive(NbrNId)) {
440  PRM.PushActive(NbrNId);
441  }
442  }
443  if (PRM.Excess(NId) > 0 && PRM.Label(NId) < MaxLabel) {
444  PRM.PushActive(NId);
445  }
446  if (RelabelCount % GRRate == 0) { GlobalRelabel(Net, PRM, SrcNId, SnkNId); }
447  }
448  return PRM.Excess(SnkNId);
449 }
#define IAssert(Cond)
Definition: bd.h:262
int PushRelabel(TPRManager &PRM, const int &NId, const TNEANet::TNodeI &NI)
Returns the ID of the neighbor that NId pushes to, -1 if no push was made.
Definition: flow.cpp:328
int GetOutNId(const int &EdgeN) const
Returns ID of EdgeN-th out-node (the node the current node points to).
Definition: network.h:1657
int GetOutDeg() const
Returns out-degree of the current node.
Definition: network.h:1649
int GetOutEId(const int &EdgeN) const
Returns ID of EdgeN-th out-edge.
Definition: network.h:1671
Node iterator. Only forward iteration (operator++) is supported.
Definition: network.h:1628
void GlobalRelabel(PNEANet &Net, TPRManager &PRM, const int &SrcNId, const int &SnkNId)
Implements the Global Relabeling heuristic.
Definition: flow.cpp:363
template<typename PGraph >
double TSnap::GetModularity ( const PGraph &  G,
const TIntV NIdV,
int  GEdges = -1 
)

Computes Modularity score of a set of nodes NIdV in a graph G. The function runs much faster if the number of edges in graph G is given (GEdges parameter).

Definition at line 37 of file cmty.h.

37  {
38  if (GEdges == -1) { GEdges = Graph->GetEdges(); }
39  double EdgesIn = 0.0, EEdgesIn = 0.0; // EdgesIn=2*number of edges inside the cluster, EEdgesIn=expected edges inside
40  TIntSet NIdSet(NIdV.Len());
41  for (int e = 0; e < NIdV.Len(); e++) { // edges inside
42  NIdSet.AddKey(NIdV[e]); }
43  for (int e1 = 0; e1 < NIdV.Len(); e1++) {
44  typename PGraph::TObj::TNodeI NI = Graph->GetNI(NIdV[e1]);
45  EEdgesIn += NI.GetOutDeg();
46  for (int i = 0; i < NI.GetOutDeg(); i++) {
47  if (NIdSet.IsKey(NI.GetOutNId(i))) { EdgesIn += 1; }
48  }
49  }
50  EEdgesIn = EEdgesIn*EEdgesIn/(2.0*GEdges);
51  if ((EdgesIn - EEdgesIn) == 0) { return 0; }
52  else { return (EdgesIn - EEdgesIn) / (2.0*GEdges); } // modularity
53 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
int AddKey(const TKey &Key)
Definition: shash.h:1248
template<typename PGraph >
double TSnap::GetModularity ( const PGraph &  G,
const TCnComV CmtyV,
int  GEdges = -1 
)

Computes Modularity score of a set of communities (each community is defined by its member nodes) in a graph G. The function runs much faster if the number of edges in graph G is given (GEdges parameter).

Definition at line 56 of file cmty.h.

56  {
57  if (GEdges == -1) { GEdges = G->GetEdges(); }
58  double Modularity = 0;
59  for (int c = 0; c < CmtyV.Len(); c++) {
60  Modularity += GetModularity(G, CmtyV[c](), GEdges);
61  }
62  return Modularity;
63 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
double GetModularity(const PGraph &G, const TCnComV &CmtyV, int GEdges=-1)
Definition: cmty.h:56
template<class PGraph >
PGraph TSnap::GetMxBiCon ( const PGraph &  Graph)

Returns a graph representing the largest bi-connected component on an input Graph.

An undirected graph is bi-connected if by removing any single node does not disconnect the graph. http://en.wikipedia.org/wiki/Biconnected_component

Definition at line 486 of file cncom.h.

486  {
487  TCnComV CnComV;
488  GetBiCon(TSnap::ConvertGraph<PUNGraph, PGraph>(Graph), CnComV);
489  if (CnComV.Empty()) { return PGraph::TObj::New(); }
490  int CcId = 0, MxSz = 0;
491  for (int i = 0; i < CnComV.Len(); i++) {
492  if (MxSz < CnComV[i].Len()) {
493  MxSz=CnComV[i].Len(); CcId=i; }
494  }
495  if (CnComV[CcId].Len()==Graph->GetNodes()) {
496  return Graph; }
497  else {
498  return TSnap::GetSubGraph(Graph, CnComV[CcId]());
499  }
500 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
bool Empty() const
Tests whether the vector is empty.
Definition: ds.h:530
PUNGraph GetSubGraph(const PUNGraph &Graph, const TIntV &NIdV, const bool &RenumberNodes)
Returns an induced subgraph of an undirected graph Graph with NIdV nodes with an optional node renumb...
Definition: subgraph.cpp:7
void GetBiCon(const PUNGraph &Graph, TCnComV &BiCnComV)
Returns all bi-connected components of a Graph.
Definition: cncom.cpp:42
PUNGraph TSnap::GetMxBiCon ( const PUNGraph Graph,
const bool &  RenumberNodes = false 
)

Returns a graph representing the largest bi-connected component on an undirected Graph.

An undirected graph is bi-connected if by removing any single node does not disconnect the graph. http://en.wikipedia.org/wiki/Biconnected_component

Definition at line 126 of file cncom.cpp.

126  {
127  TCnComV CnComV;
128  GetBiCon(Graph, CnComV);
129  if (CnComV.Empty()) {
130  return PUNGraph();
131  }
132  int CcId = 0, MxSz = 0;
133  for (int i = 0; i < CnComV.Len(); i++) {
134  if (MxSz < CnComV[i].Len()) {
135  MxSz = CnComV[i].Len();
136  CcId=i;
137  }
138  }
139  return TSnap::GetSubGraph(Graph, CnComV[CcId](), RenumberNodes);
140 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
bool Empty() const
Tests whether the vector is empty.
Definition: ds.h:530
PUNGraph GetSubGraph(const PUNGraph &Graph, const TIntV &NIdV, const bool &RenumberNodes)
Returns an induced subgraph of an undirected graph Graph with NIdV nodes with an optional node renumb...
Definition: subgraph.cpp:7
void GetBiCon(const PUNGraph &Graph, TCnComV &BiCnComV)
Returns all bi-connected components of a Graph.
Definition: cncom.cpp:42
TPt< TUNGraph > PUNGraph
Pointer to an undirected graph (TUNGraph)
Definition: graph.h:5
template<class PGraph >
int TSnap::GetMxDegNId ( const PGraph &  Graph)

Returns a randomly chosen node from all the nodes with the maximum degree.

Definition at line 143 of file alg.h.

143  {
144  TIntV MxDegV;
145  int MxDeg=-1;
146  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
147  if (MxDeg < NI.GetDeg()) { MxDegV.Clr(); MxDeg = NI.GetDeg(); }
148  if (MxDeg == NI.GetDeg()) { MxDegV.Add(NI.GetId()); }
149  }
150  EAssertR(! MxDegV.Empty(), "Input graph is empty!");
151  return MxDegV[TInt::Rnd.GetUniDevInt(MxDegV.Len())];
152 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
static TRnd Rnd
Definition: dt.h:1050
bool Empty() const
Tests whether the vector is empty.
Definition: ds.h:530
void Clr(const bool &DoDel=true, const TSizeTy &NoDelLim=-1)
Clears the contents of the vector.
Definition: ds.h:953
#define EAssertR(Cond, MsgStr)
Definition: bd.h:283
int GetUniDevInt(const int &Range=0)
Definition: dt.cpp:39
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph >
int TSnap::GetMxInDegNId ( const PGraph &  Graph)

Returns a randomly chosen node from all the nodes with the maximum in-degree.

Definition at line 155 of file alg.h.

155  {
156  TIntV MxDegV;
157  int MxDeg=-1;
158  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
159  if (MxDeg < NI.GetInDeg()) { MxDegV.Clr(); MxDeg = NI.GetInDeg(); }
160  if (MxDeg == NI.GetInDeg()) { MxDegV.Add(NI.GetId()); }
161  }
162  EAssertR(! MxDegV.Empty(), "Input graph is empty!");
163  return MxDegV[TInt::Rnd.GetUniDevInt(MxDegV.Len())];
164 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
static TRnd Rnd
Definition: dt.h:1050
bool Empty() const
Tests whether the vector is empty.
Definition: ds.h:530
void Clr(const bool &DoDel=true, const TSizeTy &NoDelLim=-1)
Clears the contents of the vector.
Definition: ds.h:953
#define EAssertR(Cond, MsgStr)
Definition: bd.h:283
int GetUniDevInt(const int &Range=0)
Definition: dt.cpp:39
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph >
int TSnap::GetMxOutDegNId ( const PGraph &  Graph)

Returns a randomly chosen node from all the nodes with the maximum out-degree.

Definition at line 167 of file alg.h.

167  {
168  TIntV MxDegV;
169  int MxDeg=-1;
170  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
171  if (MxDeg < NI.GetOutDeg()) { MxDegV.Clr(); MxDeg = NI.GetOutDeg(); }
172  if (MxDeg == NI.GetOutDeg()) { MxDegV.Add(NI.GetId()); }
173  }
174  EAssertR(! MxDegV.Empty(), "Input graph is empty!");
175  return MxDegV[TInt::Rnd.GetUniDevInt(MxDegV.Len())];
176 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
static TRnd Rnd
Definition: dt.h:1050
bool Empty() const
Tests whether the vector is empty.
Definition: ds.h:530
void Clr(const bool &DoDel=true, const TSizeTy &NoDelLim=-1)
Clears the contents of the vector.
Definition: ds.h:953
#define EAssertR(Cond, MsgStr)
Definition: bd.h:283
int GetUniDevInt(const int &Range=0)
Definition: dt.cpp:39
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph >
PGraph TSnap::GetMxScc ( const PGraph &  Graph)

Returns a graph representing the largest strongly connected component on an input Graph.

A directed graph is strongly connected if there exists a directed path from any vertex to any other vertex in the graph. See http://en.wikipedia.org/wiki/Strongly_connected_component

Definition at line 469 of file cncom.h.

469  {
470  TCnComV CnComV;
471  GetSccs(Graph, CnComV);
472  if (CnComV.Empty()) { return PGraph::TObj::New(); }
473  int CcId = 0, MxSz = 0;
474  for (int i = 0; i < CnComV.Len(); i++) {
475  if (MxSz < CnComV[i].Len()) {
476  MxSz=CnComV[i].Len(); CcId=i; }
477  }
478  if (CnComV[CcId].Len()==Graph->GetNodes()) {
479  return Graph; }
480  else {
481  return TSnap::GetSubGraph(Graph, CnComV[CcId]());
482  }
483 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
void GetSccs(const PGraph &Graph, TCnComV &CnComV)
Returns all strongly connected components in a Graph.
Definition: cncom.h:428
bool Empty() const
Tests whether the vector is empty.
Definition: ds.h:530
PUNGraph GetSubGraph(const PUNGraph &Graph, const TIntV &NIdV, const bool &RenumberNodes)
Returns an induced subgraph of an undirected graph Graph with NIdV nodes with an optional node renumb...
Definition: subgraph.cpp:7
template<class PGraph >
double TSnap::GetMxSccSz ( const PGraph &  Graph)

Returns the fraction of nodes in the largest strongly connected component of a Graph.

Definition at line 444 of file cncom.h.

444  {
445  TCnComV CnComV;
446  GetSccs(Graph, CnComV);
447  if (Graph->GetNodes() == 0) { return 0; }
448  else { return CnComV[0].Len() / double(Graph->GetNodes()); }
449 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
void GetSccs(const PGraph &Graph, TCnComV &CnComV)
Returns all strongly connected components in a Graph.
Definition: cncom.h:428
template<class PGraph >
PGraph TSnap::GetMxWcc ( const PGraph &  Graph)

Returns a graph representing the largest weakly connected component on an input Graph.

A directed/undirected graph is connected if there exist an undirected path between any pair of nodes. See http://en.wikipedia.org/wiki/Connected_component_(graph_theory)

Definition at line 452 of file cncom.h.

452  {
453  TCnComV CnComV;
454  GetWccs(Graph, CnComV);
455  if (CnComV.Empty()) { return PGraph::TObj::New(); }
456  int CcId = 0, MxSz = 0;
457  for (int i = 0; i < CnComV.Len(); i++) {
458  if (MxSz < CnComV[i].Len()) {
459  MxSz=CnComV[i].Len(); CcId=i; }
460  }
461  if (CnComV[CcId].Len()==Graph->GetNodes()) {
462  return Graph; }
463  else {
464  return TSnap::GetSubGraph(Graph, CnComV[CcId]());
465  }
466 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
bool Empty() const
Tests whether the vector is empty.
Definition: ds.h:530
PUNGraph GetSubGraph(const PUNGraph &Graph, const TIntV &NIdV, const bool &RenumberNodes)
Returns an induced subgraph of an undirected graph Graph with NIdV nodes with an optional node renumb...
Definition: subgraph.cpp:7
void GetWccs(const PGraph &Graph, TCnComV &CnComV)
Returns all weakly connected components in a Graph.
Definition: cncom.h:376
template<class PGraph >
double TSnap::GetMxWccSz ( const PGraph &  Graph)

Returns the fraction of nodes in the largest weakly connected component of a Graph.

Definition at line 436 of file cncom.h.

436  {
437  TCnComV CnComV;
438  GetWccs(Graph, CnComV);
439  if (Graph->GetNodes() == 0) { return 0; }
440  else { return CnComV[0].Len() / double(Graph->GetNodes()); }
441 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
void GetWccs(const PGraph &Graph, TCnComV &CnComV)
Returns all weakly connected components in a Graph.
Definition: cncom.h:376
template<class PGraph >
double TSnap::GetNodeClustCf ( const PGraph &  Graph,
const int &  NId 
)

Returns clustering coefficient of a particular node.

Considers the graph as undirected.

Definition at line 168 of file triad.h.

168  {
169  int Open, Closed;
170  GetNodeTriads(Graph, NId, Open, Closed);
171  //const double Deg = Graph->GetNI(NId).GetDeg();
172  return (Open+Closed)==0 ? 0 : double(Open)/double(Open+Closed);
173 }
int GetNodeTriads(const PGraph &Graph, const int &NId, const TIntSet &GroupSet, int &InGroupEdgesX, int &InOutGroupEdgesX, int &OutGroupEdgesX)
Returns the number of triads between a node NId and a subset of its neighbors GroupSet.
Definition: triad.h:335
template<class PGraph >
void TSnap::GetNodeClustCf ( const PGraph &  Graph,
TIntFltH NIdCCfH 
)

Computes clustering coefficient of each node of the Graph.

Considers the graph as undirected.

Parameters
DegToCCfVVector of pairs (degree, avg. clustering coefficient of nodes of that degree).
SampleNodesIf !=-1 then compute clustering coefficient only for a random sample of SampleNodes nodes. Useful for approximate but quick computations.

Definition at line 176 of file triad.h.

176  {
177  TIntTrV NIdCOTriadV;
178  GetTriads(Graph, NIdCOTriadV);
179  NIdCCfH.Clr(false);
180  for (int i = 0; i < NIdCOTriadV.Len(); i++) {
181  const int D = NIdCOTriadV[i].Val2()+NIdCOTriadV[i].Val3();
182  const double CCf = D!=0 ? NIdCOTriadV[i].Val2() / double(D) : 0.0;
183  NIdCCfH.AddDat(NIdCOTriadV[i].Val1, CCf);
184  }
185 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
void GetTriads(const PGraph &Graph, TIntTrV &NIdCOTriadV, int SampleNodes=-1)
Computes the number of open and close triads for every node of the network.
Definition: triad.h:212
void Clr(const bool &DoDel=true, const int &NoDelLim=-1, const bool &ResetDat=true)
Definition: hash.h:315
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
template<class PGraph >
int TSnap::GetNodeEcc ( const PGraph &  Graph,
const int &  NId,
const bool &  IsDir = false 
)

Returns node Eccentricity, the largest shortest-path distance from the node NId to any other node in the Graph.

Parameters
IsDirfalse: ignore edge directions and consider edges as undirected (in case they are directed).

Definition at line 53 of file centr.h.

53  {
54  int NodeEcc;
55  int Dist;
56  TBreathFS<PGraph> BFS(Graph);
57  // get shortest paths to all the nodes
58  BFS.DoBfs(NId, true, ! IsDir, -1, TInt::Mx);
59 
60  NodeEcc = 0;
61  // find the largest value
62  for (int i = 0; i < BFS.NIdDistH.Len(); i++) {
63  Dist = BFS.NIdDistH[i];
64  if (Dist > NodeEcc) {
65  NodeEcc = Dist;
66  }
67  }
68  return NodeEcc;
69 }
static const int Mx
Definition: dt.h:1046
template<class PGraph >
void TSnap::GetNodeInDegV ( const PGraph &  Graph,
TIntPrV NIdInDegV 
)

Returns a vector of pairs (node id, node in-degree)

Definition at line 263 of file alg.h.

263  {
264  NIdInDegV.Reserve(Graph->GetNodes(), 0);
265  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
266  NIdInDegV.Add(TIntPr(NI.GetId(), NI.GetInDeg()));
267  }
268 }
TPair< TInt, TInt > TIntPr
Definition: ds.h:83
void Reserve(const TSizeTy &_MxVals)
Reserves enough memory for the vector to store _MxVals elements.
Definition: ds.h:506
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph >
void TSnap::GetNodeOutDegV ( const PGraph &  Graph,
TIntPrV NIdOutDegV 
)

Returns a vector of pairs (node id, node out-degree)

Definition at line 271 of file alg.h.

271  {
272  NIdOutDegV.Reserve(Graph->GetNodes(), 0);
273  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
274  NIdOutDegV.Add(TIntPr(NI.GetId(), NI.GetOutDeg()));
275  }
276 }
TPair< TInt, TInt > TIntPr
Definition: ds.h:83
void Reserve(const TSizeTy &_MxVals)
Reserves enough memory for the vector to store _MxVals elements.
Definition: ds.h:506
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph >
int TSnap::GetNodesAtHop ( const PGraph &  Graph,
const int &  StartNId,
const int &  Hop,
TIntV NIdV,
const bool &  IsDir = false 
)

Finds IDs of all nodes that are at distance Hop from node StartNId.

false: ignore edge directions and consider edges/paths as undirected (in case they are directed).

Definition at line 229 of file bfsdfs.h.

229  {
230  TBreathFS<PGraph> BFS(Graph);
231  BFS.DoBfs(StartNId, true, !IsDir, -1, Hop);
232  NIdV.Clr(false);
233  for (int i = 0; i < BFS.NIdDistH.Len(); i++) {
234  if (BFS.NIdDistH[i] == Hop) {
235  NIdV.Add(BFS.NIdDistH.GetKey(i)); }
236  }
237  return NIdV.Len();
238 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
void Clr(const bool &DoDel=true, const TSizeTy &NoDelLim=-1)
Clears the contents of the vector.
Definition: ds.h:953
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph >
int TSnap::GetNodesAtHops ( const PGraph &  Graph,
const int &  StartNId,
TIntPrV HopCntV,
const bool &  IsDir = false 
)

Returns the number of nodes at each hop distance from the starting node StartNId.

false: ignore edge directions and consider edges/paths as undirected (in case they are directed).

Definition at line 241 of file bfsdfs.h.

241  {
242  TBreathFS<PGraph> BFS(Graph);
243  BFS.DoBfs(StartNId, true, !IsDir, -1, TInt::Mx);
244  TIntH HopCntH;
245  for (int i = 0; i < BFS.NIdDistH.Len(); i++) {
246  HopCntH.AddDat(BFS.NIdDistH[i]) += 1;
247  }
248  HopCntH.GetKeyDatPrV(HopCntV);
249  HopCntV.Sort();
250  return HopCntV.Len();
251 }
static const int Mx
Definition: dt.h:1046
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
void GetKeyDatPrV(TVec< TPair< TKey, TDat > > &KeyDatPrV) const
Definition: hash.h:454
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
template<class PGraph >
int TSnap::GetNodeTriads ( const PGraph &  Graph,
const int &  NId 
)

Returns the number of undirected triads a node NId participates in.

Considers the graph as undirected.

Parameters
GraphInput graph
NIdInput node

Definition at line 295 of file triad.h.

295  {
296  int ClosedTriads=0, OpenTriads=0;
297  return GetNodeTriads(Graph, NId, ClosedTriads, OpenTriads);
298 }
int GetNodeTriads(const PGraph &Graph, const int &NId, const TIntSet &GroupSet, int &InGroupEdgesX, int &InOutGroupEdgesX, int &OutGroupEdgesX)
Returns the number of triads between a node NId and a subset of its neighbors GroupSet.
Definition: triad.h:335
template<class PGraph >
int TSnap::GetNodeTriads ( const PGraph &  Graph,
const int &  NId,
int &  ClosedNTriadsX,
int &  OpenNTriadsX 
)

Returns number of Open and Closed triads a node NId participates in.

Considers the graph as undirected.

Parameters
GraphInput graph
NIdInput node
ClosedNTriadsXOn return contains the number of closed triads
OpenNTriadsXOn return contains the number of open triads

Definition at line 302 of file triad.h.

302  {
303  const typename PGraph::TObj::TNodeI NI = Graph->GetNI(NId);
304  ClosedTriads=0; OpenTriads=0;
305  if (NI.GetDeg() < 2) { return 0; }
306  // find neighborhood
307  TIntSet NbrSet(NI.GetDeg());
308  for (int e = 0; e < NI.GetOutDeg(); e++) {
309  if (NI.GetOutNId(e) != NI.GetId()) { // exclude self edges
310  NbrSet.AddKey(NI.GetOutNId(e)); }
311  }
312  if (Graph->HasFlag(gfDirected)) {
313  for (int e = 0; e < NI.GetInDeg(); e++) {
314  if (NI.GetInNId(e) != NI.GetId()) { // exclude self edges
315  NbrSet.AddKey(NI.GetInNId(e)); }
316  }
317  }
318  // count connected neighbors
319  for (int srcNbr = 0; srcNbr < NbrSet.Len(); srcNbr++) {
320  const typename PGraph::TObj::TNodeI SrcNode = Graph->GetNI(NbrSet.GetKey(srcNbr));
321  for (int dstNbr = srcNbr+1; dstNbr < NbrSet.Len(); dstNbr++) {
322  const int dstNId = NbrSet.GetKey(dstNbr);
323  if (SrcNode.IsNbrNId(dstNId)) { ClosedTriads++; }
324  else { OpenTriads++; }
325  }
326  }
327  return ClosedTriads;
328 }
int AddKey(const TKey &Key)
Definition: shash.h:1248
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
template<class PGraph >
int TSnap::GetNodeTriads ( const PGraph &  Graph,
const int &  NId,
const TIntSet GroupSet,
int &  InGroupEdgesX,
int &  InOutGroupEdgesX,
int &  OutGroupEdgesX 
)

Returns the number of triads between a node NId and a subset of its neighbors GroupSet.

Considers the graph as undirected.

Parameters
GraphInput graph
NIdInput node
GroupSetInput set with node neighbors
InGroupEdgesXOn return contains the number of triads (NId, G1, G2), where G1 and G2 are in GroupSet
InOutGroupEdgesXOn return contains the number of triads (NId, G1, O1), where G1 is in GroupSet and O1 not in GroupSet
OutGroupEdgesXOn return contains the number of triads (NId, O1, O2), where O1 and O2 are not in GroupSet

Definition at line 335 of file triad.h.

335  {
336  const typename PGraph::TObj::TNodeI NI = Graph->GetNI(NId);
337  const bool IsDir = Graph->HasFlag(gfDirected);
338  InGroupEdges=0; InOutGroupEdges=0; OutGroupEdges=0;
339  if (NI.GetDeg() < 2) { return 0; }
340  // find neighborhood
341  TIntSet NbrSet(NI.GetDeg());
342  for (int e = 0; e < NI.GetOutDeg(); e++) {
343  if (NI.GetOutNId(e) != NI.GetId()) { // exclude self edges
344  NbrSet.AddKey(NI.GetOutNId(e)); }
345  }
346  if (IsDir) {
347  for (int e = 0; e < NI.GetInDeg(); e++) {
348  if (NI.GetInNId(e) != NI.GetId()) {
349  NbrSet.AddKey(NI.GetInNId(e)); }
350  }
351  }
352  // count connected neighbors
353  for (int srcNbr = 0; srcNbr < NbrSet.Len(); srcNbr++) {
354  const int NbrId = NbrSet.GetKey(srcNbr);
355  const bool NbrIn = GroupSet.IsKey(NbrId);
356  const typename PGraph::TObj::TNodeI SrcNode = Graph->GetNI(NbrId);
357  for (int dstNbr = srcNbr+1; dstNbr < NbrSet.Len(); dstNbr++) {
358  const int DstNId = NbrSet.GetKey(dstNbr);
359  if (SrcNode.IsNbrNId(DstNId)) { // triad (NId, NbrId, DstNid)
360  bool DstIn = GroupSet.IsKey(DstNId);
361  if (NbrIn && DstIn) { InGroupEdges++; }
362  else if (NbrIn || DstIn) { InOutGroupEdges++; }
363  else { OutGroupEdges++; }
364  }
365  }
366  }
367  return InGroupEdges;
368 }
bool IsKey(const TKey &Key) const
Definition: shash.h:1142
int AddKey(const TKey &Key)
Definition: shash.h:1248
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
template<class PGraph >
void TSnap::GetNodeWcc ( const PGraph &  Graph,
const int &  NId,
TIntV CnCom 
)

Returns (via output parameter CnCom) all nodes that are in the same connected component as node NId.

Definition at line 277 of file cncom.h.

277  {
278  typename PGraph::TObj::TNodeI NI;
279  THashSet<TInt> VisitedNId(Graph->GetNodes()+1);
280  TSnapQueue<int> NIdQ(Graph->GetNodes()+1);
281  VisitedNId.AddKey(NId);
282  NIdQ.Push(NId);
283  while (! NIdQ.Empty()) {
284  const typename PGraph::TObj::TNodeI Node = Graph->GetNI(NIdQ.Top()); NIdQ.Pop();
285  if (HasGraphFlag(typename PGraph::TObj, gfDirected)) {
286  for (int e = 0; e < Node.GetInDeg(); e++) {
287  const int InNId = Node.GetInNId(e);
288  if (! VisitedNId.IsKey(InNId)) {
289  NIdQ.Push(InNId); VisitedNId.AddKey(InNId); }
290  }
291  }
292  for (int e = 0; e < Node.GetOutDeg(); e++) {
293  const int OutNId = Node.GetOutNId(e);
294  if (! VisitedNId.IsKey(OutNId)) {
295  NIdQ.Push(OutNId); VisitedNId.AddKey(OutNId); }
296  }
297  }
298  CnCom.Gen(VisitedNId.Len(), 0);
299  for (int i = 0; i < VisitedNId.Len(); i++) {
300  CnCom.Add(VisitedNId.GetKey(i));
301  }
302 }
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
void Push(const TVal &Val)
Adds an element at the end of the queue.
Definition: gbase.h:198
void Gen(const TSizeTy &_Vals)
Constructs a vector (an array) of _Vals elements.
Definition: ds.h:486
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph >
void TSnap::GetOutDegCnt ( const PGraph &  Graph,
TIntPrV DegToCntV 
)

Returns an out-degree histogram: a set of pairs (out-degree, number of nodes of such out-degree)

Definition at line 201 of file alg.h.

201  {
202  TIntH DegToCntH;
203  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
204  DegToCntH.AddDat(NI.GetOutDeg())++; }
205  DegToCntV.Gen(DegToCntH.Len(), 0);
206  for (int i = 0; i < DegToCntH.Len(); i++) {
207  DegToCntV.Add(TIntPr(DegToCntH.GetKey(i), DegToCntH[i])); }
208  DegToCntV.Sort();
209 }
TPair< TInt, TInt > TIntPr
Definition: ds.h:83
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
void Gen(const TSizeTy &_Vals)
Constructs a vector (an array) of _Vals elements.
Definition: ds.h:486
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
int Len() const
Definition: hash.h:186
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
const TKey & GetKey(const int &KeyId) const
Definition: hash.h:210
template<class PGraph >
void TSnap::GetOutDegCnt ( const PGraph &  Graph,
TFltPrV DegToCntV 
)

Returns an out-degree histogram: a set of pairs (out-degree, number of nodes of such out-degree)

Definition at line 212 of file alg.h.

212  {
213  TIntH DegToCntH;
214  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
215  DegToCntH.AddDat(NI.GetOutDeg())++; }
216  DegToCntV.Gen(DegToCntH.Len(), 0);
217  for (int i = 0; i < DegToCntH.Len(); i++) {
218  DegToCntV.Add(TFltPr(DegToCntH.GetKey(i).Val, DegToCntH[i].Val)); }
219  DegToCntV.Sort();
220 }
int Val
Definition: dt.h:1043
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
TPair< TFlt, TFlt > TFltPr
Definition: ds.h:99
void Gen(const TSizeTy &_Vals)
Constructs a vector (an array) of _Vals elements.
Definition: ds.h:486
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
int Len() const
Definition: hash.h:186
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
const TKey & GetKey(const int &KeyId) const
Definition: hash.h:210
template<class PGraph >
void TSnap::GetPageRank ( const PGraph &  Graph,
TIntFltH PRankH,
const double &  C = 0.85,
const double &  Eps = 1e-4,
const int &  MaxIter = 100 
)

PageRank For more info see: http://en.wikipedia.org/wiki/PageRank

Definition at line 75 of file centr.h.

75  {
76  const int NNodes = Graph->GetNodes();
77  //const double OneOver = 1.0/double(NNodes);
78  PRankH.Gen(NNodes);
79  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
80  PRankH.AddDat(NI.GetId(), 1.0/NNodes);
81  //IAssert(NI.GetId() == PRankH.GetKey(PRankH.Len()-1));
82  }
83  TFltV TmpV(NNodes);
84  for (int iter = 0; iter < MaxIter; iter++) {
85  int j = 0;
86  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++, j++) {
87  TmpV[j] = 0;
88  for (int e = 0; e < NI.GetInDeg(); e++) {
89  const int InNId = NI.GetInNId(e);
90  const int OutDeg = Graph->GetNI(InNId).GetOutDeg();
91  if (OutDeg > 0) {
92  TmpV[j] += PRankH.GetDat(InNId) / OutDeg; }
93  }
94  TmpV[j] = C*TmpV[j]; // Berkhin (the correct way of doing it)
95  //TmpV[j] = C*TmpV[j] + (1.0-C)*OneOver; // iGraph
96  }
97  double diff=0, sum=0, NewVal;
98  for (int i = 0; i < TmpV.Len(); i++) { sum += TmpV[i]; }
99  const double Leaked = (1.0-sum) / double(NNodes);
100  for (int i = 0; i < PRankH.Len(); i++) { // re-instert leaked PageRank
101  NewVal = TmpV[i] + Leaked; // Berkhin
102  //NewVal = TmpV[i] / sum; // iGraph
103  diff += fabs(NewVal-PRankH[i]);
104  PRankH[i] = NewVal;
105  }
106  if (diff < Eps) { break; }
107  }
108 }
const TDat & GetDat(const TKey &Key) const
Definition: hash.h:220
void Gen(const int &ExpectVals)
Definition: hash.h:180
int Len() const
Definition: hash.h:186
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
template<class PGraph >
PGraph TSnap::GetRndESubGraph ( const PGraph &  Graph,
const int &  NEdges 
)

Returns a random subgraph of graph Graph with NEdges edges.

Randomly selects NEdges edges from the input graph and returns a subgraph on those edges.

Definition at line 452 of file subgraph.h.

452  {
453  CAssert(! HasGraphFlag(typename PGraph::TObj, gfMultiGraph));
454  TIntPrV EdgeV(Graph->GetEdges(), 0);
455  for (typename PGraph::TObj::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) {
456  EdgeV.Add(TIntPr(EI.GetSrcNId(), EI.GetDstNId()));
457  }
458  EdgeV.Shuffle(TInt::Rnd);
459  EdgeV.Del(NEdges, EdgeV.Len()-1);
460  IAssert(EdgeV.Len() == NEdges);
461  return GetESubGraph(Graph, EdgeV);
462 }
#define IAssert(Cond)
Definition: bd.h:262
TPair< TInt, TInt > TIntPr
Definition: ds.h:83
PGraph GetESubGraph(const PGraph &Graph, const TIntPrV &EdgeV)
Definition: subgraph.h:227
static TRnd Rnd
Definition: dt.h:1050
have explicit edges (multigraph): TNEGraph, TNodeEdgeNet
Definition: gbase.h:14
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
#define CAssert(Cond)
Definition: bd.h:302
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
template<class PGraph >
PGraph TSnap::GetRndSubGraph ( const PGraph &  Graph,
const int &  NNodes 
)

Returns an induced random subgraph of graph Graph with NNodes nodes.

Randomly selects NNodes nodes from the input graph and returns an induced graph on those nodes.

Definition at line 441 of file subgraph.h.

441  {
442  IAssert(NNodes <= Graph->GetNodes());
443  TIntV NIdV;
444  Graph->GetNIdV(NIdV);
445  NIdV.Shuffle(TInt::Rnd);
446  NIdV.Del(NNodes, NIdV.Len()-1);
447  IAssert(NIdV.Len() == NNodes);
448  return GetSubGraph(Graph, NIdV);
449 }
#define IAssert(Cond)
Definition: bd.h:262
void Del(const TSizeTy &ValN)
Removes the element at position ValN.
Definition: ds.h:1094
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
static TRnd Rnd
Definition: dt.h:1050
PGraph GetSubGraph(const PGraph &Graph, const TIntV &NIdV)
Returns an induced subgraph of graph Graph with NIdV nodes.
Definition: subgraph.h:200
void Shuffle(TRnd &Rnd)
Randomly shuffles the elements of the vector.
Definition: ds.h:1235
template<class PGraph >
void TSnap::GetSccs ( const PGraph &  Graph,
TCnComV CnComV 
)

Returns all strongly connected components in a Graph.

Parameters
CnComVis a vector of connected components. Each component is defined by the IDs of its member nodes.

Definition at line 428 of file cncom.h.

428  {
429  TSccVisitor<PGraph, false> Visitor(Graph);
430  TCnCom::GetDfsVisitor(Graph, Visitor);
431  CnComV = Visitor.CnComV;
432  CnComV.Sort(false);
433 }
static void GetDfsVisitor(const PGraph &Graph, TVisitor &Visitor)
Definition: cncom.h:124
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
Strongly connected componetns Depht-First-Search visitor class.
Definition: cncom.h:234
template<class PGraph >
void TSnap::GetSccSzCnt ( const PGraph &  Graph,
TIntPrV SccSzCnt 
)

Returns a distribution of strongly connected component sizes.

Parameters
SccSzCntreturns a set of pairs (number of nodes in the component, number of such components)

Definition at line 420 of file cncom.h.

420  {
421  TSccVisitor<PGraph, true> Visitor(Graph);
422  TCnCom::GetDfsVisitor(Graph, Visitor);
423  Visitor.SccCntH.GetKeyDatPrV(SccSzCnt);
424  SccSzCnt.Sort(true);
425 }
static void GetDfsVisitor(const PGraph &Graph, TVisitor &Visitor)
Definition: cncom.h:124
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
Strongly connected componetns Depht-First-Search visitor class.
Definition: cncom.h:234
template<class PGraph >
int TSnap::GetShortPath ( const PGraph &  Graph,
const int &  SrcNId,
const int &  DstNId,
const bool &  IsDir = false 
)

Returns the length of the shortest path from node SrcNId to node DstNId.

Parameters
IsDirfalse: ignore edge directions and consider edges/paths as undirected (in case they are directed).

Definition at line 263 of file bfsdfs.h.

263  {
264  TBreathFS<PGraph> BFS(Graph);
265  BFS.DoBfs(SrcNId, true, ! IsDir, DstNId, TInt::Mx);
266  return BFS.GetHops(SrcNId, DstNId);
267 }
static const int Mx
Definition: dt.h:1046
template<class PGraph >
int TSnap::GetShortPath ( const PGraph &  Graph,
const int &  SrcNId,
TIntH NIdToDistH,
const bool &  IsDir = false,
const int &  MaxDist = TInt::Mx 
)

Returns the length of the shortest path from node SrcNId to all other nodes in the network.

Parameters
IsDirfalse: ignore edge directions and consider edges/paths as undirected (in case they are directed).
MaxDistMaximum number of hops that BFS expands to. This is helpful for speeding-up the code if one in interested only in nodes less than MaxDist away from SrcNId.
NIdToDistHMaps node ID to shortest path distance. NIdToDistH contains only nodes that are reachable from SrcNId.

Definition at line 254 of file bfsdfs.h.

254  {
255  TBreathFS<PGraph> BFS(Graph);
256  BFS.DoBfs(SrcNId, true, ! IsDir, -1, MaxDist);
257  NIdToDistH.Clr();
258  NIdToDistH.Swap(BFS.NIdDistH);
259  return NIdToDistH[NIdToDistH.Len()-1];
260 }
void Swap(THash &Hash)
Definition: hash.h:498
void Clr(const bool &DoDel=true, const int &NoDelLim=-1, const bool &ResetDat=true)
Definition: hash.h:315
int Len() const
Definition: hash.h:186
void TSnap::GetSngVals ( const PNGraph Graph,
const int &  SngVals,
TFltV SngValV 
)

Computes largest SngVals singular values of the adjacency matrix representing a directed Graph.

Definition at line 175 of file gsvd.cpp.

175  {
176  const int Nodes = Graph->GetNodes();
177  IAssert(SngVals > 0);
178  if (Nodes < 100) {
179  // perform full SVD
180  TFltVV AdjMtx(Nodes+1, Nodes+1);
181  TFltVV LSingV, RSingV;
182  TIntH NodeIdH;
183  // create adjecency matrix
184  for (TNGraph::TNodeI NodeI = Graph->BegNI(); NodeI < Graph->EndNI(); NodeI++) {
185  NodeIdH.AddKey(NodeI.GetId()); }
186  for (TNGraph::TNodeI NodeI = Graph->BegNI(); NodeI < Graph->EndNI(); NodeI++) {
187  const int NodeId = NodeIdH.GetKeyId(NodeI.GetId()) + 1;
188  for (int e = 0; e < NodeI.GetOutDeg(); e++) {
189  const int DstNId = NodeIdH.GetKeyId(NodeI.GetOutNId(e)) + 1; // no self edges
190  if (NodeId != DstNId) AdjMtx.At(NodeId, DstNId) = 1;
191  }
192  }
193  try { // can fail to converge but results seem to be good
194  TSvd::Svd1Based(AdjMtx, LSingV, SngValV, RSingV); }
195  catch(...) {
196  printf("\n***No SVD convergence: G(%d, %d)\n", Nodes, Graph->GetEdges()); }
197  } else {
198  // Lanczos
199  TNGraphMtx GraphMtx(Graph);
200  int CalcVals = int(2*SngVals);
201  //if (CalcVals > Nodes) { CalcVals = int(2*Nodes); }
202  //if (CalcVals > Nodes) { CalcVals = Nodes; }
203  //while (SngValV.Len() < SngVals && CalcVals < 10*SngVals) {
204  try {
205  if (SngVals > 4) {
206  TSparseSVD::SimpleLanczosSVD(GraphMtx, 2*SngVals, SngValV, false); }
207  else { TFltVV LSingV, RSingV; // this is much more precise, but also much slower
208  TSparseSVD::LanczosSVD(GraphMtx, SngVals, 3*SngVals, ssotFull, SngValV, LSingV, RSingV); }
209  }
210  catch(...) {
211  printf("\n ***EXCEPTION: TRIED %d GOT %d values** \n", 2*SngVals, SngValV.Len()); }
212  if (SngValV.Len() < SngVals) {
213  printf(" ***TRIED %d GOT %d values** \n", CalcVals, SngValV.Len()); }
214  // CalcVals += SngVals;
215  //}
216  }
217  SngValV.Sort(false);
218  //if (SngValV.Len() > SngVals) {
219  // SngValV.Del(SngVals, SngValV.Len()-1); }
220  //else {
221  // while (SngValV.Len() < SngVals) SngValV.Add(1e-6); }
222  //IAssert(SngValV.Len() == SngVals);
223 }
#define IAssert(Cond)
Definition: bd.h:262
static void SimpleLanczosSVD(const TMatrix &Matrix, const int &CalcSV, TFltV &SngValV, const bool &DoLocalReortoP=false)
Definition: linalg.cpp:1440
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
static void LanczosSVD(const TMatrix &Matrix, int NumSV, int Iters, const TSpSVDReOrtoType &ReOrtoType, TFltV &SgnValV, TFltVV &LeftSgnVecVV, TFltVV &RightSgnVecVV)
Definition: linalg.cpp:1454
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
Definition: ds.h:3100
Definition: gsvd.h:5
static void Svd1Based(const TFltVV &InMtx1, TFltVV &LSingV, TFltV &SingValV, TFltVV &RSingV)
Definition: xmath.cpp:1252
int GetKeyId(const TKey &Key) const
Definition: hash.h:420
int AddKey(const TKey &Key)
Definition: hash.h:327
Node iterator. Only forward iteration (operator++) is supported.
Definition: graph.h:324
void TSnap::GetSngVec ( const PNGraph Graph,
TFltV LeftSV,
TFltV RightSV 
)

Computes the leading left and right singular vector of the adjacency matrix representing a directed Graph.

Definition at line 225 of file gsvd.cpp.

225  {
226  const int Nodes = Graph->GetNodes();
227  TFltVV LSingV, RSingV;
228  TFltV SngValV;
229  if (Nodes < 500) {
230  // perform full SVD
231  TFltVV AdjMtx(Nodes+1, Nodes+1);
232  TIntH NodeIdH;
233  // create adjecency matrix
234  for (TNGraph::TNodeI NodeI = Graph->BegNI(); NodeI < Graph->EndNI(); NodeI++) {
235  NodeIdH.AddKey(NodeI.GetId()); }
236  for (TNGraph::TNodeI NodeI = Graph->BegNI(); NodeI < Graph->EndNI(); NodeI++) {
237  const int NodeId = NodeIdH.GetKeyId(NodeI.GetId()) + 1;
238  for (int e = 0; e < NodeI.GetOutDeg(); e++) {
239  const int DstNId = NodeIdH.GetKeyId(NodeI.GetOutNId(e)) + 1; // no self edges
240  if (NodeId != DstNId) AdjMtx.At(NodeId, DstNId) = 1;
241  }
242  }
243  try { // can fail to converge but results seem to be good
244  TSvd::Svd1Based(AdjMtx, LSingV, SngValV, RSingV); }
245  catch(...) {
246  printf("\n***No SVD convergence: G(%d, %d)\n", Nodes, Graph->GetEdges()); }
247  } else { // Lanczos
248  TNGraphMtx GraphMtx(Graph);
249  TSparseSVD::LanczosSVD(GraphMtx, 1, 8, ssotFull, SngValV, LSingV, RSingV);
250  }
251  TFlt MxSngVal = TFlt::Mn;
252  int ValN = 0;
253  for (int i = 0; i < SngValV.Len(); i++) {
254  if (MxSngVal < SngValV[i]) { MxSngVal = SngValV[i]; ValN = i; } }
255  LSingV.GetCol(ValN, LeftSV);
256  RSingV.GetCol(ValN, RightSV);
257  IsAllValVNeg(LeftSV, true);
258  IsAllValVNeg(RightSV, true);
259 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
bool IsAllValVNeg(TFltV &ValV, const bool &InvertSign)
Definition: gsvd.cpp:163
static void LanczosSVD(const TMatrix &Matrix, int NumSV, int Iters, const TSpSVDReOrtoType &ReOrtoType, TFltV &SgnValV, TFltVV &LeftSgnVecVV, TFltVV &RightSgnVecVV)
Definition: linalg.cpp:1454
void GetCol(const int &ColN, TVec< TVal > &Vec) const
Definition: ds.h:3267
Definition: dt.h:1289
Definition: ds.h:3100
Definition: gsvd.h:5
static void Svd1Based(const TFltVV &InMtx1, TFltVV &LSingV, TFltV &SingValV, TFltVV &RSingV)
Definition: xmath.cpp:1252
int GetKeyId(const TKey &Key) const
Definition: hash.h:420
int AddKey(const TKey &Key)
Definition: hash.h:327
Node iterator. Only forward iteration (operator++) is supported.
Definition: graph.h:324
static const double Mn
Definition: dt.h:1293
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
void TSnap::GetSngVec ( const PNGraph Graph,
const int &  SngVecs,
TFltV SngValV,
TVec< TFltV > &  LeftSV,
TVec< TFltV > &  RightSV 
)

Computes the singular values and left and right singular vectors of the adjacency matrix representing a directed Graph.

Parameters
SngVecsNumber of singular values/vectors to compute.

Definition at line 261 of file gsvd.cpp.

261  {
262  const int Nodes = Graph->GetNodes();
263  SngValV.Clr();
264  LeftSV.Clr();
265  RightSV.Clr();
266  TFltVV LSingV, RSingV;
267  if (Nodes < 100) {
268  // perform full SVD
269  TFltVV AdjMtx(Nodes+1, Nodes+1);
270  TIntH NodeIdH;
271  // create adjecency matrix (1-based)
272  for (TNGraph::TNodeI NodeI = Graph->BegNI(); NodeI < Graph->EndNI(); NodeI++) {
273  NodeIdH.AddKey(NodeI.GetId()); }
274  for (TNGraph::TNodeI NodeI = Graph->BegNI(); NodeI < Graph->EndNI(); NodeI++) {
275  const int NodeId = NodeIdH.GetKeyId(NodeI.GetId())+1;
276  for (int e = 0; e < NodeI.GetOutDeg(); e++) {
277  const int DstNId = NodeIdH.GetKeyId(NodeI.GetOutNId(e))+1; // no self edges
278  if (NodeId != DstNId) AdjMtx.At(NodeId, DstNId) = 1;
279  }
280  }
281  try { // can fail to converge but results seem to be good
282  TSvd::Svd1Based(AdjMtx, LSingV, SngValV, RSingV);
283  } catch(...) {
284  printf("\n***No SVD convergence: G(%d, %d)\n", Nodes, Graph->GetEdges());
285  }
286  } else { // Lanczos
287  TNGraphMtx GraphMtx(Graph);
288  TSparseSVD::LanczosSVD(GraphMtx, SngVecs, 2*SngVecs, ssotFull, SngValV, LSingV, RSingV);
289  //TGAlg::SaveFullMtx(Graph, "adj_mtx.txt");
290  //TLAMisc::DumpTFltVVMjrSubMtrx(LSingV, LSingV.GetRows(), LSingV.GetCols(), "LSingV2.txt"); // save MTX
291  }
292  TFltIntPrV SngValIdV;
293  for (int i = 0; i < SngValV.Len(); i++) {
294  SngValIdV.Add(TFltIntPr(SngValV[i], i));
295  }
296  SngValIdV.Sort(false);
297  SngValV.Sort(false);
298  for (int v = 0; v < SngValIdV.Len(); v++) {
299  LeftSV.Add();
300  LSingV.GetCol(SngValIdV[v].Val2, LeftSV.Last());
301  RightSV.Add();
302  RSingV.GetCol(SngValIdV[v].Val2, RightSV.Last());
303  }
304  IsAllValVNeg(LeftSV[0], true);
305  IsAllValVNeg(RightSV[0], true);
306 }
TPair< TFlt, TInt > TFltIntPr
Definition: ds.h:97
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
bool IsAllValVNeg(TFltV &ValV, const bool &InvertSign)
Definition: gsvd.cpp:163
static void LanczosSVD(const TMatrix &Matrix, int NumSV, int Iters, const TSpSVDReOrtoType &ReOrtoType, TFltV &SgnValV, TFltVV &LeftSgnVecVV, TFltVV &RightSgnVecVV)
Definition: linalg.cpp:1454
void GetCol(const int &ColN, TVec< TVal > &Vec) const
Definition: ds.h:3267
void Clr(const bool &DoDel=true, const TSizeTy &NoDelLim=-1)
Clears the contents of the vector.
Definition: ds.h:953
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
Definition: ds.h:3100
Definition: gsvd.h:5
static void Svd1Based(const TFltVV &InMtx1, TFltVV &LSingV, TFltV &SingValV, TFltVV &RSingV)
Definition: xmath.cpp:1252
const TVal & Last() const
Returns a reference to the last element of the vector.
Definition: ds.h:539
int GetKeyId(const TKey &Key) const
Definition: hash.h:420
int AddKey(const TKey &Key)
Definition: hash.h:327
Node iterator. Only forward iteration (operator++) is supported.
Definition: graph.h:324
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
PUNGraph TSnap::GetSubGraph ( const PUNGraph Graph,
const TIntV NIdV,
const bool &  RenumberNodes = false 
)

Returns an induced subgraph of an undirected graph Graph with NIdV nodes with an optional node renumbering.

The resulting subgraph contains all the nodes from Graph, which have node IDs in the NIdV vector and all the edges with both nodes in NIdV. Parameter RenumberNodes determines, whether the node IDs are preserved or not. If RenumberNodes is false, then nodes in the resulting subgraph have the same node IDs as nodes in Graph. If RenumberNodes is true, then nodes in the resulting subgraph are renumbered sequentially from 0 to N-1. By default, the nodes are not renumbered.

Definition at line 7 of file subgraph.cpp.

7  {
8  //if (! RenumberNodes) { return TSnap::GetSubGraph(Graph, NIdV); }
9  PUNGraph NewGraphPt = TUNGraph::New();
10  TUNGraph& NewGraph = *NewGraphPt;
11  NewGraph.Reserve(NIdV.Len(), -1);
12  TIntSet NIdSet(NIdV.Len());
13  for (int n = 0; n < NIdV.Len(); n++) {
14  if (Graph->IsNode(NIdV[n])) {
15  NIdSet.AddKey(NIdV[n]);
16  if (! RenumberNodes) { NewGraph.AddNode(NIdV[n]); }
17  else { NewGraph.AddNode(NIdSet.GetKeyId(NIdV[n])); }
18  }
19  }
20  if (! RenumberNodes) {
21  for (int n = 0; n < NIdSet.Len(); n++) {
22  const int SrcNId = NIdSet[n];
23  const TUNGraph::TNodeI NI = Graph->GetNI(SrcNId);
24  for (int edge = 0; edge < NI.GetOutDeg(); edge++) {
25  const int OutNId = NI.GetOutNId(edge);
26  if (NIdSet.IsKey(OutNId)) {
27  NewGraph.AddEdge(SrcNId, OutNId); }
28  }
29  }
30  } else {
31  for (int n = 0; n < NIdSet.Len(); n++) {
32  const int SrcNId = NIdSet[n];
33  const TUNGraph::TNodeI NI = Graph->GetNI(SrcNId);
34  for (int edge = 0; edge < NI.GetOutDeg(); edge++) {
35  const int OutNId = NI.GetOutNId(edge);
36  if (NIdSet.IsKey(OutNId)) {
37  NewGraph.AddEdge(NIdSet.GetKeyId(SrcNId), NIdSet.GetKeyId(OutNId)); }
38  }
39  }
40  }
41  return NewGraphPt;
42 }
int AddNode(int NId=-1)
Adds a node of ID NId to the graph.
Definition: graph.cpp:8
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
Node iterator. Only forward iteration (operator++) is supported.
Definition: graph.h:63
int GetOutDeg() const
Returns out-degree of the current node (returns same as value GetDeg() since the graph is undirected)...
Definition: graph.h:86
Undirected graph.
Definition: graph.h:32
void Reserve(const int &Nodes, const int &Edges)
Reserves memory for a graph of Nodes nodes and Edges edges.
Definition: graph.h:249
TNodeI GetNI(const int &NId) const
Returns an iterator referring to the node of ID NId in the graph.
Definition: graph.h:205
static PUNGraph New()
Static constructor that returns a pointer to the graph. Call: PUNGraph Graph = TUNGraph::New().
Definition: graph.h:149
int AddKey(const TKey &Key)
Definition: shash.h:1248
int AddEdge(const int &SrcNId, const int &DstNId)
Adds an edge between node IDs SrcNId and DstNId to the graph.
Definition: graph.cpp:84
int GetOutNId(const int &NodeN) const
Returns ID of NodeN-th out-node (the node the current node points to).
Definition: graph.h:96
bool IsNode(const int &NId) const
Tests whether ID NId is a node.
Definition: graph.h:199
template<class PGraph >
PGraph TSnap::GetSubGraph ( const PGraph &  Graph,
const TIntV NIdV 
)

Returns an induced subgraph of graph Graph with NIdV nodes.

The resulting subgraph contains all the nodes from Graph, which have node IDs in the NIdV vector and all the edges with both nodes in NIdV. Node IDs are preserved. Nodes in the resulting subgraph have the same node IDs as nodes in Graph.

Definition at line 200 of file subgraph.h.

200  {
201  return TSnapDetail::TGetSubGraph<PGraph, HasGraphFlag(typename PGraph::TObj, gfMultiGraph)>
202  ::Do(Graph, NIdV);
203 }
PNGraph TSnap::GetSubGraph ( const PNGraph Graph,
const TIntV NIdV,
const bool &  RenumberNodes 
)

Definition at line 45 of file subgraph.cpp.

45  {
46  //if (! RenumberNodes) { return TSnap::GetSubGraph(Graph, NIdV); }
47  PNGraph NewGraphPt = TNGraph::New();
48  TNGraph& NewGraph = *NewGraphPt;
49  NewGraph.Reserve(NIdV.Len(), -1);
50  TIntSet NIdSet(NIdV.Len());
51  for (int n = 0; n < NIdV.Len(); n++) {
52  if (Graph->IsNode(NIdV[n])) {
53  NIdSet.AddKey(NIdV[n]);
54  if (! RenumberNodes) { NewGraph.AddNode(NIdV[n]); }
55  else { NewGraph.AddNode(NIdSet.GetKeyId(NIdV[n])); }
56  }
57  }
58  if (! RenumberNodes) {
59  for (int n = 0; n < NIdSet.Len(); n++) {
60  const int SrcNId = NIdSet[n];
61  const TNGraph::TNodeI NI = Graph->GetNI(SrcNId);
62  for (int edge = 0; edge < NI.GetOutDeg(); edge++) {
63  const int OutNId = NI.GetOutNId(edge);
64  if (NIdSet.IsKey(OutNId)) {
65  NewGraph.AddEdge(SrcNId, OutNId); }
66  }
67  }
68  } else {
69  for (int n = 0; n < NIdSet.Len(); n++) {
70  const int SrcNId = NIdSet[n];
71  const TNGraph::TNodeI NI = Graph->GetNI(SrcNId);
72  for (int edge = 0; edge < NI.GetOutDeg(); edge++) {
73  const int OutNId = NI.GetOutNId(edge);
74  if (NIdSet.IsKey(OutNId)) {
75  NewGraph.AddEdge(NIdSet.GetKeyId(SrcNId), NIdSet.GetKeyId(OutNId)); }
76  }
77  }
78  }
79  return NewGraphPt;
80 }
static PNGraph New()
Static constructor that returns a pointer to the graph. Call: PNGraph Graph = TNGraph::New().
Definition: graph.h:405
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
int AddNode(int NId=-1)
Adds a node of ID NId to the graph.
Definition: graph.cpp:208
int AddEdge(const int &SrcNId, const int &DstNId)
Adds an edge from node IDs SrcNId to node DstNId to the graph.
Definition: graph.cpp:286
int AddKey(const TKey &Key)
Definition: shash.h:1248
Directed graph.
Definition: graph.h:293
int GetOutDeg() const
Returns out-degree of the current node.
Definition: graph.h:344
Node iterator. Only forward iteration (operator++) is supported.
Definition: graph.h:324
void Reserve(const int &Nodes, const int &Edges)
Reserves memory for a graph of Nodes nodes and Edges edges.
Definition: graph.h:508
Definition: bd.h:196
int GetOutNId(const int &NodeN) const
Returns ID of NodeN-th out-node (the node the current node points to).
Definition: graph.h:352
template<class PGraph >
int TSnap::GetSubTreeSz ( const PGraph &  Graph,
const int &  StartNId,
const bool &  FollowOut,
const bool &  FollowIn,
int &  TreeSzX,
int &  TreeDepthX 
)

Returns the BFS tree size (number of nodes) and depth (number of levels) by following in-links (parameter FollowIn = true) and/or out-links (parameter FollowOut = true) of node StartNId.

Definition at line 217 of file bfsdfs.h.

217  {
218  TBreathFS<PGraph> BFS(Graph);
219  BFS.DoBfs(StartNId, FollowOut, FollowIn, -1, TInt::Mx);
220  TreeSz = BFS.NIdDistH.Len();
221  TreeDepth = 0;
222  for (int i = 0; i < BFS.NIdDistH.Len(); i++) {
223  TreeDepth = TMath::Mx(TreeDepth, BFS.NIdDistH[i].Val);
224  }
225  return TreeSz;
226 }
static const T & Mx(const T &LVal, const T &RVal)
Definition: xmath.h:32
static const int Mx
Definition: dt.h:1046
template<class PGraph >
int TSnap::GetTreeRootNId ( const PGraph &  Graph)

Definition at line 80 of file alg.h.

80 { int RootNId; bool Tree; Tree = IsTree(Graph, RootNId); Assert(Tree); return RootNId; }
bool IsTree(const PGraph &Graph, int &RootNIdX)
Definition: alg.h:460
#define Assert(Cond)
Definition: bd.h:251
template<class PGraph >
void TSnap::GetTreeSig ( const PGraph &  Graph,
const int &  RootNId,
TIntV Sig 
)

Definition at line 484 of file alg.h.

484  {
485  CAssert(HasGraphFlag(typename PGraph::TObj, gfDirected));
486  Sig.Gen(Graph->GetNodes(), 0);
487  TSnapQueue<int> NIdQ(Graph->GetNodes());
488  NIdQ.Push(RootNId);
489  int LastPos = 0, NodeCnt = 1;
490  while (! NIdQ.Empty()) {
491  const typename PGraph::TObj::TNodeI Node = Graph->GetNI(NIdQ.Top()); NIdQ.Pop();
492  IAssert(Node.GetInDeg()==0 || Node.GetOutDeg()==0); // child points or is-pointed to by the parent
493  if (Node.GetInDeg() != 0) {
494  for (int e = 0; e < Node.GetInDeg(); e++) {
495  NIdQ.Push(Node.GetInNId(e)); }
496  } else if (Node.GetOutDeg() != 0) {
497  for (int e = 0; e < Node.GetOutDeg(); e++) {
498  NIdQ.Push(Node.GetOutNId(e)); }
499  }
500  Sig.Add(Node.GetInDeg());
501  if (--NodeCnt == 0) {
502  for (int i = LastPos; i < Sig.Len(); i++) NodeCnt += Sig[i];
503  Sig.QSort(LastPos, Sig.Len()-1, false);
504  LastPos = Sig.Len();
505  }
506  }
507 }
#define IAssert(Cond)
Definition: bd.h:262
void QSort(const TSizeTy &MnLValN, const TSizeTy &MxRValN, const bool &Asc)
Quick sorts the values between positions MnLValN...MxLValN.
Definition: ds.h:1205
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
#define CAssert(Cond)
Definition: bd.h:302
void Push(const TVal &Val)
Adds an element at the end of the queue.
Definition: gbase.h:198
void Gen(const TSizeTy &_Vals)
Constructs a vector (an array) of _Vals elements.
Definition: ds.h:486
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph >
void TSnap::GetTreeSig ( const PGraph &  Graph,
const int &  RootNId,
TIntV Sig,
TIntPrV NodeMap 
)

Definition at line 511 of file alg.h.

511  {
512  CAssert(HasGraphFlag(typename PGraph::TObj, gfDirected));
513  NodeMap.Gen(Graph->GetNodes(), 0);
514  Sig.Gen(Graph->GetNodes(), 0);
515  TSnapQueue<int> NIdQ(Graph->GetNodes());
516  NIdQ.Push(RootNId);
517  int LastPos = 0, NodeCnt = 1;
518  while (! NIdQ.Empty()) {
519  const typename PGraph::TObj::TNodeI Node = Graph->GetNI(NIdQ.Top()); NIdQ.Pop();
520  IAssert(Node.GetInDeg()==0 || Node.GetOutDeg()==0); // child points or is-pointed to by the parent
521  if (Node.GetInDeg() != 0) {
522  for (int e = 0; e < Node.GetInDeg(); e++) {
523  NIdQ.Push(Node.GetInNId(e)); }
524  NodeMap.Add(TIntPr(Node.GetInDeg(), Node.GetId()));
525  } else if (Node.GetOutDeg() != 0) {
526  for (int e = 0; e < Node.GetOutDeg(); e++) {
527  NIdQ.Push(Node.GetOutNId(e)); }
528  NodeMap.Add(TIntPr(Node.GetOutDeg(), Node.GetId()));
529  }
530  if (--NodeCnt == 0) {
531  for (int i = LastPos; i < NodeMap.Len(); i++) {
532  NodeCnt += NodeMap[i].Val1; }
533  NodeMap.QSort(LastPos, NodeMap.Len()-1, false);
534  LastPos = NodeMap.Len();
535  }
536  }
537  for (int i = 0; i < NodeMap.Len(); i++) {
538  Sig.Add(NodeMap[i].Val1); // degree dignature
539  NodeMap[i].Val1 = NodeMap[i].Val2;
540  NodeMap[i].Val2 = i;
541  }
542 }
#define IAssert(Cond)
Definition: bd.h:262
TPair< TInt, TInt > TIntPr
Definition: ds.h:83
void QSort(const TSizeTy &MnLValN, const TSizeTy &MxRValN, const bool &Asc)
Quick sorts the values between positions MnLValN...MxLValN.
Definition: ds.h:1205
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
#define CAssert(Cond)
Definition: bd.h:302
void Push(const TVal &Val)
Adds an element at the end of the queue.
Definition: gbase.h:198
void Gen(const TSizeTy &_Vals)
Constructs a vector (an array) of _Vals elements.
Definition: ds.h:486
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph >
int TSnap::GetTriadEdges ( const PGraph &  Graph,
int  SampleEdges = -1 
)

Counts the number of edges that participate in at least one triad.

Considers the graph as undirected.

Parameters
SampleNodesIf !=-1 then compute triads only for a random sample of SampleNodes nodes. Useful for approximate but quick computations.

Definition at line 259 of file triad.h.

259  {
260  const bool IsDir = Graph->HasFlag(gfDirected);
261  TIntSet NbrH;
262  int TriadEdges = 0;
263  for(typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
264  NbrH.Clr(false);
265  for (int e = 0; e < NI.GetOutDeg(); e++) {
266  if (NI.GetOutNId(e) != NI.GetId()) {
267  NbrH.AddKey(NI.GetOutNId(e)); }
268  }
269  if (IsDir) {
270  for (int e = 0; e < NI.GetInDeg(); e++) {
271  if (NI.GetInNId(e) != NI.GetId()) {
272  NbrH.AddKey(NI.GetInNId(e)); }
273  }
274  }
275  for (int e = 0; e < NI.GetOutDeg(); e++) {
276  if (!IsDir && NI.GetId()<NI.GetOutNId(e)) { continue; } // for undirected graphs count each edge only once
277  const typename PGraph::TObj::TNodeI SrcNode = Graph->GetNI(NI.GetOutNId(e));
278  bool Triad=false;
279  for (int e1 = 0; e1 < SrcNode.GetOutDeg(); e1++) {
280  if (NbrH.IsKey(SrcNode.GetOutNId(e1))) { Triad=true; break; }
281  }
282  if (IsDir && ! Triad) {
283  for (int e1 = 0; e1 < SrcNode.GetInDeg(); e1++) {
284  if (NbrH.IsKey(SrcNode.GetInNId(e1))) { Triad=true; break; }
285  }
286  }
287  if (Triad) { TriadEdges++; }
288  }
289  }
290  return TriadEdges;
291 }
void Clr(const bool &DoDel=true, const int &NoDelLim=-1)
Definition: shash.h:1237
bool IsKey(const TKey &Key) const
Definition: shash.h:1142
int AddKey(const TKey &Key)
Definition: shash.h:1248
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
template<class PGraph >
void TSnap::GetTriadParticip ( const PGraph &  Graph,
TIntPrV TriadCntV 
)

Triangle Participation Ratio: For each node counts how many triangles it participates in and then returns a set of pairs (number of triangles, number of such nodes).

Considers the graph as undirected.

Definition at line 372 of file triad.h.

372  {
373  TIntH TriadCntH;
374  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
375  const int Triads = GetNodeTriads(Graph, NI.GetId());
376  TriadCntH.AddDat(Triads) += 1;
377  }
378  TriadCntH.GetKeyDatPrV(TriadCntV);
379  TriadCntV.Sort();
380 }
int GetNodeTriads(const PGraph &Graph, const int &NId, const TIntSet &GroupSet, int &InGroupEdgesX, int &InOutGroupEdgesX, int &OutGroupEdgesX)
Returns the number of triads between a node NId and a subset of its neighbors GroupSet.
Definition: triad.h:335
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
void GetKeyDatPrV(TVec< TPair< TKey, TDat > > &KeyDatPrV) const
Definition: hash.h:454
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
template<class PGraph >
int64 TSnap::GetTriads ( const PGraph &  Graph,
int  SampleNodes = -1 
)

Returns the number of triangles in a graph.

The function returns the number of unique triples of connected nodes (regardless of the number of edges between each pair of nodes). In other words, the function consideres the Graph as a simple undirected graph.

Parameters
SampleNodesIf !=-1 then compute triads only for a random sample of SampleNodes nodes. Useful for approximate but quick computations.

Definition at line 188 of file triad.h.

188  {
189  int64 OpenTriads, ClosedTriads;
190  return GetTriads(Graph, ClosedTriads, OpenTriads, SampleNodes);
191 }
void GetTriads(const PGraph &Graph, TIntTrV &NIdCOTriadV, int SampleNodes=-1)
Computes the number of open and close triads for every node of the network.
Definition: triad.h:212
long long int64
Definition: bd.h:27
template<class PGraph >
void TSnap::GetTriads ( const PGraph &  Graph,
TIntTrV NIdCOTriadV,
int  SampleNodes = -1 
)

Computes the number of open and close triads for every node of the network.

Considers the graph as undirected.

Parameters
NIdCOTriadVTriple (node id, open triads: number of pairs of node's neighbors that are not connected, closed triads: number of pairs of node's neighbors that are connected between themselves).
SampleNodesIf !=-1 then compute triads only for a random sample of SampleNodes nodes. Useful for approximate but quick computations.

Definition at line 212 of file triad.h.

212  {
213  const bool IsDir = Graph->HasFlag(gfDirected);
214  TIntSet NbrH;
215  TIntV NIdV;
216  TRnd Rnd(0);
217 
218  Graph->GetNIdV(NIdV);
219  NIdV.Shuffle(Rnd);
220  if (SampleNodes == -1) {
221  SampleNodes = Graph->GetNodes(); }
222  NIdCOTriadV.Clr(false);
223  NIdCOTriadV.Reserve(SampleNodes);
224  for (int node = 0; node < SampleNodes; node++) {
225  typename PGraph::TObj::TNodeI NI = Graph->GetNI(NIdV[node]);
226  if (NI.GetDeg() < 2) {
227  NIdCOTriadV.Add(TIntTr(NI.GetId(), 0, 0)); // zero triangles
228  continue;
229  }
230  // find neighborhood
231  NbrH.Clr(false);
232  for (int e = 0; e < NI.GetOutDeg(); e++) {
233  if (NI.GetOutNId(e) != NI.GetId()) {
234  NbrH.AddKey(NI.GetOutNId(e)); }
235  }
236  if (IsDir) {
237  for (int e = 0; e < NI.GetInDeg(); e++) {
238  if (NI.GetInNId(e) != NI.GetId()) {
239  NbrH.AddKey(NI.GetInNId(e)); }
240  }
241  }
242  // count connected neighbors
243  int OpenCnt=0, CloseCnt=0;
244  for (int srcNbr = 0; srcNbr < NbrH.Len(); srcNbr++) {
245  const typename PGraph::TObj::TNodeI SrcNode = Graph->GetNI(NbrH.GetKey(srcNbr));
246  for (int dstNbr = srcNbr+1; dstNbr < NbrH.Len(); dstNbr++) {
247  const int dstNId = NbrH.GetKey(dstNbr);
248  if (SrcNode.IsNbrNId(dstNId)) { CloseCnt++; } // is edge
249  else { OpenCnt++; }
250  }
251  }
252  IAssert(2*(OpenCnt+CloseCnt) == NbrH.Len()*(NbrH.Len()-1));
253  NIdCOTriadV.Add(TIntTr(NI.GetId(), CloseCnt, OpenCnt));
254  }
255 }
void Clr(const bool &DoDel=true, const int &NoDelLim=-1)
Definition: shash.h:1237
#define IAssert(Cond)
Definition: bd.h:262
Definition: dt.h:11
const TKey & GetKey(const int &KeyId) const
Definition: shash.h:1135
void Clr(const bool &DoDel=true, const TSizeTy &NoDelLim=-1)
Clears the contents of the vector.
Definition: ds.h:953
int AddKey(const TKey &Key)
Definition: shash.h:1248
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
int Len() const
Definition: shash.h:1115
void Shuffle(TRnd &Rnd)
Randomly shuffles the elements of the vector.
Definition: ds.h:1235
TTriple< TInt, TInt, TInt > TIntTr
Definition: ds.h:166
void Reserve(const TSizeTy &_MxVals)
Reserves enough memory for the vector to store _MxVals elements.
Definition: ds.h:506
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph >
int64 TSnap::GetTriads ( const PGraph &  Graph,
int64 ClosedTriadsX,
int64 OpenTriadsX,
int  SampleNodes = -1 
)

Computes the number of Closed and Open triads.

Considers the graph as undirected.

Parameters
SampleNodesIf !=-1 then compute triads only for a random sample of SampleNodes nodes. Useful for approximate but quick computations.

Definition at line 194 of file triad.h.

194  {
195  TIntTrV NIdCOTriadV;
196  GetTriads(Graph, NIdCOTriadV, SampleNodes);
197  uint64 closedTriads = 0;
198  uint64 openTriads = 0;
199  for (int i = 0; i < NIdCOTriadV.Len(); i++) {
200  closedTriads += NIdCOTriadV[i].Val2;
201  openTriads += NIdCOTriadV[i].Val3;
202  }
203  //IAssert(closedTriads/3 < (uint64) TInt::Mx);
204  //IAssert(openTriads < (uint64) TInt::Mx);
205  ClosedTriads = int64(closedTriads/3); // each triad is counted 3 times
206  OpenTriads = int64(openTriads);
207  return ClosedTriads;
208 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
unsigned long long uint64
Definition: bd.h:38
void GetTriads(const PGraph &Graph, TIntTrV &NIdCOTriadV, int SampleNodes=-1)
Computes the number of open and close triads for every node of the network.
Definition: triad.h:212
long long int64
Definition: bd.h:27
template<class PGraph >
PGraph TSnap::GetUnDir ( const PGraph &  Graph)

Returs an undirected version of the graph. For every edge (u,v) an edge (v,u) is added (if it does not yet exist).

Definition at line 345 of file alg.h.

345  {
346  PGraph NewGraphPt = PGraph::New();
347  *NewGraphPt = *Graph;
348  MakeUnDir(NewGraphPt);
349  return NewGraphPt;
350 }
void MakeUnDir(const PGraph &Graph)
Makes the graph undirected. For every edge (u,v) an edge (v,u) is added (if it does not yet exist)...
Definition: alg.h:353
template<class PGraph >
void TSnap::GetWccs ( const PGraph &  Graph,
TCnComV CnComV 
)

Returns all weakly connected components in a Graph.

Parameters
CnComVis a vector of connected components. Each component is defined by the IDs of its member nodes.

Definition at line 376 of file cncom.h.

376  {
377  typename PGraph::TObj::TNodeI NI;
378  THashSet<TInt> VisitedNId(Graph->GetNodes()+1);
379  TSnapQueue<int> NIdQ(Graph->GetNodes()+1);
380  TIntV CcNIdV;
381  CnComV.Clr(); CcNIdV.Gen(1);
382  // zero degree nodes
383  for (NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
384  if (NI.GetDeg() == 0) {
385  const int NId = NI.GetId();
386  VisitedNId.AddKey(NId);
387  CcNIdV[0] = NId; CnComV.Add(CcNIdV);
388  }
389  }
390  // the rest of the nodes
391  for (NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
392  const int NId = NI.GetId();
393  if (! VisitedNId.IsKey(NId)) {
394  VisitedNId.AddKey(NId);
395  NIdQ.Clr(false); NIdQ.Push(NId);
396  CcNIdV.Clr(); CcNIdV.Add(NId);
397  while (! NIdQ.Empty()) {
398  const typename PGraph::TObj::TNodeI Node = Graph->GetNI(NIdQ.Top()); NIdQ.Pop();
399  if (HasGraphFlag(typename PGraph::TObj, gfDirected)) {
400  for (int e = 0; e < Node.GetInDeg(); e++) {
401  const int InNId = Node.GetInNId(e);
402  if (! VisitedNId.IsKey(InNId)) {
403  NIdQ.Push(InNId); VisitedNId.AddKey(InNId); CcNIdV.Add(InNId); }
404  }
405  }
406  for (int e = 0; e < Node.GetOutDeg(); e++) {
407  const int OutNId = Node.GetOutNId(e);
408  if (! VisitedNId.IsKey(OutNId)) {
409  NIdQ.Push(OutNId); VisitedNId.AddKey(OutNId); CcNIdV.Add(OutNId); }
410  }
411  }
412  CcNIdV.Sort(true);
413  CnComV.Add(TCnCom(CcNIdV)); // add wcc comoponent
414  }
415  }
416  CnComV.Sort(false);
417 }
void Clr(const bool &DoDel=true, const int &NoDelLim=-1)
Definition: shash.h:1237
void Gen(const int &ExpectVals)
Definition: shash.h:1109
void Clr(const bool &DoDel=true, const TSizeTy &NoDelLim=-1)
Clears the contents of the vector.
Definition: ds.h:953
Definition: cncom.h:88
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
int AddKey(const TKey &Key)
Definition: shash.h:1248
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph >
void TSnap::GetWccSzCnt ( const PGraph &  Graph,
TIntPrV WccSzCnt 
)

Returns a distribution of weakly connected component sizes.

Parameters
WccSzCntreturns a set of pairs (number of nodes in the component, number of such components)

Definition at line 337 of file cncom.h.

337  {
338  THashSet<TInt> VisitedNId(Graph->GetNodes());
339  TIntH SzToCntH;
340  TSnapQueue<int> NIdQ(Graph->GetNodes()+1);
341  typename PGraph::TObj::TNodeI NI;
342  int Cnt = 0;
343  // zero degree nodes
344  for (NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
345  if (NI.GetDeg() == 0) { Cnt++; VisitedNId.AddKey(NI.GetId()); }
346  }
347  if (Cnt > 0) SzToCntH.AddDat(1, Cnt);
348  // the rest of the nodes
349  for (NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
350  if (! VisitedNId.IsKey(NI.GetId())) {
351  VisitedNId.AddKey(NI.GetId());
352  NIdQ.Clr(false); NIdQ.Push(NI.GetId());
353  Cnt = 0;
354  while (! NIdQ.Empty()) {
355  const typename PGraph::TObj::TNodeI Node = Graph->GetNI(NIdQ.Top()); NIdQ.Pop();
356  if (HasGraphFlag(typename PGraph::TObj, gfDirected)) {
357  for (int e = 0; e < Node.GetInDeg(); e++) {
358  const int InNId = Node.GetInNId(e);
359  if (! VisitedNId.IsKey(InNId)) { NIdQ.Push(InNId); VisitedNId.AddKey(InNId); }
360  }
361  }
362  for (int e = 0; e < Node.GetOutDeg(); e++) {
363  const int OutNId = Node.GetOutNId(e);
364  if (! VisitedNId.IsKey(OutNId)) { NIdQ.Push(OutNId); VisitedNId.AddKey(OutNId); }
365  }
366  Cnt++;
367  }
368  SzToCntH.AddDat(Cnt) += 1;
369  }
370  }
371  SzToCntH.GetKeyDatPrV(WccSzCnt);
372  WccSzCnt.Sort(true);
373 }
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
int AddKey(const TKey &Key)
Definition: shash.h:1248
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
void TSnap::GlobalRelabel ( PNEANet Net,
TPRManager &  PRM,
const int &  SrcNId,
const int &  SnkNId 
)

Implements the Global Relabeling heuristic.

Since labels reflect an estimate of the distance from a node to the sink node, every now and then the Global Relabel heuristic will be run. This BFS over the residual network starting from the sink and updates each nodes label as the distance to the sink. Unreacheable nodes from the sink have their labels set to N, where N is the number of nodes.

Definition at line 363 of file flow.cpp.

363  {
364  TIntQ NodeQ;
365  int size = Net->GetMxNId();
366  TIntV NodeV(size);
367  for (int i = 0; i < size; i++) { NodeV[i] = 0; }
368  NodeQ.Push(SnkNId);
369  NodeV[SnkNId] = 1;
370  int MaxLabel = PRM.GetMaxLabel();
371  while (!NodeQ.Empty()) {
372  // Backward search
373  int NId = NodeQ.Top(); NodeQ.Pop();
374  const TNEANet::TNodeI &NI = Net->GetNI(NId);
375  // Check all edges that point out of the current node for those over which flow can be returned.
376  for (int EdgeN = 0; EdgeN < NI.GetOutDeg(); EdgeN++) {
377  int OutNId = NI.GetOutNId(EdgeN);
378  int EId = NI.GetOutEId(EdgeN);
379  if (!NodeV[OutNId] && PRM.Flow(EId) > 0) {
380  NodeV[OutNId] = 1;
381  NodeQ.Push(OutNId);
382  PRM.SetLabel(OutNId, PRM.Label(NId) + 1);
383  }
384  }
385  // Check all edges that point into the current node for those over which flow can be added.
386  for (int EdgeN = 0; EdgeN < NI.GetInDeg(); EdgeN++) {
387  int InNId = NI.GetInNId(EdgeN);
388  int EId = NI.GetInEId(EdgeN);
389  if (!NodeV[InNId] && PRM.Capacity(EId) > PRM.Flow(EId)) {
390  NodeV[InNId] = 1;
391  NodeQ.Push(InNId);
392  PRM.SetLabel(InNId, PRM.Label(NId) + 1);
393  }
394  }
395  }
396 
397  for (TNEANet::TNodeI NI = Net->BegNI(); NI != Net->EndNI(); NI++) {
398  int NId = NI.GetId();
399  if (NodeV[NId]) {
400  if (PRM.Excess(NId) > 0 && PRM.Label(NId) < MaxLabel && NId != SnkNId) {
401  if (!PRM.IsActive(NId)) { PRM.PushActive(NId); }
402  }
403  } else {
404  if (PRM.IsActive(NId)) { PRM.RemoveActive(NId); }
405  PRM.SetLabel(NId, MaxLabel);
406  }
407  }
408 }
int GetOutNId(const int &EdgeN) const
Returns ID of EdgeN-th out-node (the node the current node points to).
Definition: network.h:1657
int GetOutDeg() const
Returns out-degree of the current node.
Definition: network.h:1649
bool Empty() const
Definition: ds.h:3523
int GetInNId(const int &EdgeN) const
Returns ID of EdgeN-th in-node (the node pointing to the current node).
Definition: network.h:1653
int GetOutEId(const int &EdgeN) const
Returns ID of EdgeN-th out-edge.
Definition: network.h:1671
Node iterator. Only forward iteration (operator++) is supported.
Definition: network.h:1628
int GetInEId(const int &EdgeN) const
Returns ID of EdgeN-th in-edge.
Definition: network.h:1669
void Pop()
Definition: ds.h:3527
int GetId() const
Returns ID of the current node.
Definition: network.h:1643
int GetInDeg() const
Returns in-degree of the current node.
Definition: network.h:1647
const TVal & Top() const
Definition: ds.h:3525
void Push(const TVal &Val)
Definition: ds.h:3530
double TSnap::Infomap ( PUNGraph Graph,
TCnComV CmtyV 
)

Rosvall-Bergstrom community detection algorithm based on information theoretic approach. See: Rosvall M., Bergstrom C. T., Maps of random walks on complex networks reveal community structure, Proc. Natl. Acad. Sci. USA 105, 1118–1123 (2008)

Definition at line 123 of file cmty.cpp.

123  {
124  TIntH DegH;
125  TIntFltH PAlpha; // probability of visiting node alpha
126  TIntH Module; // module of each node
127  TIntFltH Qi; // probability of leaving each module
128  float SumPAlphaLogPAlpha = 0.0;
129  int Br = 0;
130  const int e = Graph->GetEdges();
131 
132  // initial values
133  for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
134  DegH.AddDat(NI.GetId(), NI.GetDeg());
135  float d = ((float)NI.GetDeg()/(float)(2*e));
136  PAlpha.AddDat(NI.GetId(), d);
137  SumPAlphaLogPAlpha += d*log(d);
138  Module.AddDat(NI.GetId(),Br);
139  Qi.AddDat(Module[Br],1.0);
140  Br+=1;
141  }
142 
143  float MinCodeLength = TSnapDetail::Equation(Graph,PAlpha,SumPAlphaLogPAlpha,Qi);
144  float NewCodeLength, PrevIterationCodeLength = 0.0;
145  int OldModule, NewModule;
146 
147  do {
148  PrevIterationCodeLength = MinCodeLength;
149  for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
150  MinCodeLength = TSnapDetail::Equation(Graph, PAlpha, SumPAlphaLogPAlpha, Qi);
151  for (int i=0; i<DegH.GetDat(NI.GetId()); i++) {
152  OldModule = Module.GetDat(NI.GetId());
153  NewModule = Module.GetDat(NI.GetNbrNId(i));
154  if (OldModule!=NewModule){
155  Module.DelKey(NI.GetId());
156  Module.AddDat(NI.GetId(),NewModule);
157  Qi = TSnapDetail::MapEquationNew2Modules(Graph,Module,Qi,OldModule, NewModule);
158  NewCodeLength = TSnapDetail::Equation(Graph,PAlpha,SumPAlphaLogPAlpha, Qi);
159  if (NewCodeLength<MinCodeLength) {
160  MinCodeLength = NewCodeLength;
161  OldModule = NewModule;
162  } else {
163  Module.DelKey(NI.GetId());
164  Module.AddDat(NI.GetId(),OldModule);
165  }
166  }
167  }
168  }
169  } while (MinCodeLength<PrevIterationCodeLength);
170 
171  Module.SortByDat(true);
172  int Mod=-1;
173  for (int i=0; i<Module.Len(); i++) {
174  if (Module[i]>Mod){
175  Mod = Module[i];
176  TCnCom t;
177  for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++){
178  if (Module.GetDat(NI.GetId())==Mod)
179  t.Add(NI.GetId());
180  }
181  CmtyV.Add(t);
182  }
183  }
184 
185  return MinCodeLength;
186 }
void Add(const int &NodeId)
Definition: cncom.h:104
int GetEdges() const
Returns the number of edges in the graph.
Definition: graph.cpp:74
Node iterator. Only forward iteration (operator++) is supported.
Definition: graph.h:63
const TDat & GetDat(const TKey &Key) const
Definition: hash.h:220
void DelKey(const TKey &Key)
Definition: hash.h:358
Definition: cncom.h:88
float Equation(PUNGraph &Graph, TIntFltH &PAlpha, float &SumPAlphaLogPAlpha, TIntFltH &Qi)
Definition: cmty.cpp:84
TNodeI EndNI() const
Returns an iterator referring to the past-the-end node in the graph.
Definition: graph.h:203
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
TNodeI BegNI() const
Returns an iterator referring to the first node in the graph.
Definition: graph.h:201
int Len() const
Definition: hash.h:186
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
TIntFltH MapEquationNew2Modules(PUNGraph &Graph, TIntH &Module, TIntFltH &Qi, int a, int b)
Definition: cmty.cpp:53
void SortByDat(const bool &Asc=true)
Definition: hash.h:246
int TSnap::IntFlowBiDBFS ( const PNEANet Net,
const int &  CapIndex,
TIntV Flow,
TIntQ FwdNodeQ,
TIntH PredEdgeH,
TIntQ BwdNodeQ,
TIntH SuccEdgeH,
const int &  SrcNId,
const int &  SnkNId 
)

Definition at line 4 of file flow.cpp.

4  {
5  FwdNodeQ.Push(SrcNId);
6  PredEdgeH.AddDat(SrcNId, -1);
7  BwdNodeQ.Push(SnkNId);
8  SuccEdgeH.AddDat(SnkNId, -1);
9  while (!FwdNodeQ.Empty() && !BwdNodeQ.Empty()) {
10  // Forward search
11  const TNEANet::TNodeI &FwdNI = Net->GetNI(FwdNodeQ.Top()); FwdNodeQ.Pop();
12  // Check all edges that point into the current node for those over which flow can be returned.
13  for (int EdgeN = 0; EdgeN < FwdNI.GetInDeg(); EdgeN++) {
14  int NextNId = FwdNI.GetInNId(EdgeN);
15  int NextEId = FwdNI.GetInEId(EdgeN);
16  if (!PredEdgeH.IsKey(NextNId) && Flow[NextEId] > 0) {
17  PredEdgeH.AddDat(NextNId, NextEId);
18  if (SuccEdgeH.IsKey(NextNId)) {
19  return NextNId;
20  }
21  FwdNodeQ.Push(NextNId);
22  }
23  }
24  // Check all edges that point out of the current node for those over which flow can be added.
25  for (int EdgeN = 0; EdgeN < FwdNI.GetOutDeg(); EdgeN++) {
26  int NextNId = FwdNI.GetOutNId(EdgeN);
27  int NextEId = FwdNI.GetOutEId(EdgeN);
28  if (!PredEdgeH.IsKey(NextNId) && Net->GetIntAttrIndDatE(NextEId, CapIndex) > Flow[NextEId]) {
29  PredEdgeH.AddDat(NextNId, NextEId);
30  if (SuccEdgeH.IsKey(NextNId)) {
31  return NextNId;
32  }
33  FwdNodeQ.Push(NextNId);
34  }
35  }
36  // Backward search
37  const TNEANet::TNodeI &BwdNI = Net->GetNI(BwdNodeQ.Top()); BwdNodeQ.Pop();
38  // Check all edges that point out of the current node for those over which flow can be returned.
39  for (int EdgeN = 0; EdgeN < BwdNI.GetOutDeg(); EdgeN++) {
40  int PrevNId = BwdNI.GetOutNId(EdgeN);
41  int PrevEId = BwdNI.GetOutEId(EdgeN);
42  if (!SuccEdgeH.IsKey(PrevNId) && Flow[PrevEId] > 0) {
43  SuccEdgeH.AddDat(PrevNId, PrevEId);
44  if (PredEdgeH.IsKey(PrevNId)) {
45  return PrevNId;
46  }
47  BwdNodeQ.Push(PrevNId);
48  }
49  }
50  // Check all edges that point into the current node for those over which flow can be added.
51  for (int EdgeN = 0; EdgeN < BwdNI.GetInDeg(); EdgeN++) {
52  int PrevNId = BwdNI.GetInNId(EdgeN);
53  int PrevEId = BwdNI.GetInEId(EdgeN);
54  if (!SuccEdgeH.IsKey(PrevNId) && Net->GetIntAttrIndDatE(PrevEId, CapIndex) > Flow[PrevEId]) {
55  SuccEdgeH.AddDat(PrevNId, PrevEId);
56  if (PredEdgeH.IsKey(PrevNId)) {
57  return PrevNId;
58  }
59  BwdNodeQ.Push(PrevNId);
60  }
61  }
62  }
63  return -1;
64 }
int GetOutNId(const int &EdgeN) const
Returns ID of EdgeN-th out-node (the node the current node points to).
Definition: network.h:1657
int GetOutDeg() const
Returns out-degree of the current node.
Definition: network.h:1649
bool Empty() const
Definition: ds.h:3523
int GetInNId(const int &EdgeN) const
Returns ID of EdgeN-th in-node (the node pointing to the current node).
Definition: network.h:1653
int GetOutEId(const int &EdgeN) const
Returns ID of EdgeN-th out-edge.
Definition: network.h:1671
Node iterator. Only forward iteration (operator++) is supported.
Definition: network.h:1628
int GetInEId(const int &EdgeN) const
Returns ID of EdgeN-th in-edge.
Definition: network.h:1669
void Pop()
Definition: ds.h:3527
int GetInDeg() const
Returns in-degree of the current node.
Definition: network.h:1647
const TVal & Top() const
Definition: ds.h:3525
void Push(const TVal &Val)
Definition: ds.h:3530
bool IsKey(const TKey &Key) const
Definition: hash.h:216
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
bool TSnap::IsAllValVNeg ( TFltV ValV,
const bool &  InvertSign 
)

Definition at line 163 of file gsvd.cpp.

163  {
164  bool IsAllNeg=true;
165  for (int i = 0; i < ValV.Len(); i++) {
166  if (ValV[i]>0.0) { IsAllNeg=false; break; }
167  }
168  if (IsAllNeg && InvertSign) {
169  for (int i = 0; i < ValV.Len(); i++) {
170  ValV[i] = -ValV[i]; }
171  }
172  return IsAllNeg;
173 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
template<class PGraph >
bool TSnap::IsConnected ( const PGraph &  Graph)

Tests whether the Graph is (weakly) connected.

Definition at line 305 of file cncom.h.

305  {
306  return IsWeaklyConn(Graph);
307 }
bool IsWeaklyConn(const PGraph &Graph)
Tests whether the Graph is weakly connected.
Definition: cncom.h:310
template<class PGraph >
bool TSnap::IsTree ( const PGraph &  Graph,
int &  RootNIdX 
)

Definition at line 460 of file alg.h.

460  {
461  if (Graph->GetNodes() == 1 && Graph->GetEdges() == 0) {
462  RootNId = Graph->BegNI().GetId();
463  return true;
464  }
465  RootNId = -1;
466  if (Graph->GetNodes() != Graph->GetEdges()+1) { return false; }
467  int NZeroOutDeg = 0;
468  int ZeroOutDegN = -1;
469  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
470  if (NI.GetOutDeg() == 0) {
471  ZeroOutDegN = NI.GetId(); NZeroOutDeg++;
472  }
473  if (NI.GetDeg() == 0) { return false; } // isolated nodes
474  }
475  if (NZeroOutDeg==1) {
476  if (! TSnap::IsConnected(Graph)) { return false; }
477  RootNId = ZeroOutDegN; return true;
478  }
479  return false;
480 }
bool IsConnected(const PGraph &Graph)
Tests whether the Graph is (weakly) connected.
Definition: cncom.h:305
template<class PGraph >
bool TSnap::IsWeaklyConn ( const PGraph &  Graph)

Tests whether the Graph is weakly connected.

Definition at line 310 of file cncom.h.

310  {
311  if (Graph->Empty()) {
312  return true;
313  }
314  THashSet<TInt> VisitedNId(Graph->GetNodes());
315  TSnapQueue<int> NIdQ(Graph->GetNodes()+1);
316  typename PGraph::TObj::TNodeI NI;
317  // the rest of the nodes
318  NIdQ.Push(Graph->BegNI().GetId());
319  while (! NIdQ.Empty()) {
320  const typename PGraph::TObj::TNodeI Node = Graph->GetNI(NIdQ.Top()); NIdQ.Pop();
321  if (HasGraphFlag(typename PGraph::TObj, gfDirected)) {
322  for (int e = 0; e < Node.GetInDeg(); e++) {
323  const int InNId = Node.GetInNId(e);
324  if (! VisitedNId.IsKey(InNId)) { NIdQ.Push(InNId); VisitedNId.AddKey(InNId); }
325  }
326  }
327  for (int e = 0; e < Node.GetOutDeg(); e++) {
328  const int OutNId = Node.GetOutNId(e);
329  if (! VisitedNId.IsKey(OutNId)) { NIdQ.Push(OutNId); VisitedNId.AddKey(OutNId); }
330  }
331  }
332  if (VisitedNId.Len() < Graph->GetNodes()) { return false; }
333  return true;
334 }
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
void Push(const TVal &Val)
Adds an element at the end of the queue.
Definition: gbase.h:198
template<class PGraph >
PGraph TSnap::LoadConnList ( const TStr InFNm)

Loads a (directed, undirected or multi) graph from a text file InFNm with 1 node and all its edges in a single line.

Loads Whitespace separated file of several columns: <source node="" id>=""> <destination node="" id1>=""> <destination node="" id2>="">

Whitespace separated file of several columns: <source node="" id>=""> <destination node="" id1>=""> <destination node="" id2>=""> ... First column of each line contains a source node id followed by ids of the destination nodes. For example, '1 2 3' encodes edges 1–>2 and 1–>3. Note that this format allows for saving isolated nodes.

Definition at line 152 of file gio.h.

152  {
153  TSsParser Ss(InFNm, ssfWhiteSep, true, true, true);
154  PGraph Graph = PGraph::TObj::New();
155  while (Ss.Next()) {
156  if (! Ss.IsInt(0)) { continue; }
157  const int SrcNId = Ss.GetInt(0);
158  if (! Graph->IsNode(SrcNId)) { Graph->AddNode(SrcNId); }
159  for (int dst = 1; dst < Ss.Len(); dst++) {
160  const int DstNId = Ss.GetInt(dst);
161  if (! Graph->IsNode(DstNId)) { Graph->AddNode(DstNId); }
162  Graph->AddEdge(SrcNId, DstNId);
163  }
164  }
165  Graph->Defrag();
166  return Graph;
167 }
Definition: ss.h:72
Whitespace (space or tab) separated.
Definition: ss.h:11
template<class PGraph >
PGraph TSnap::LoadConnListStr ( const TStr InFNm,
TStrHash< TInt > &  StrToNIdH 
)

Loads a (directed, undirected or multi) graph from a text file InFNm with 1 node and all its edges in a single line.

Loads Whitespace separated file of several columns: <source node="" id>=""> <destination node="" id1>=""> <destination node="" id2>="">, with a mapping of strings to node IDs.

Whitespace separated file of several columns: <source node="" name>=""> <destination node name 1> <destination node name 2> ... First colum of each line contains a source node name followed by ids of the destination nodes. For example, 'A B C' encodes edges A–>B and A–>C. Note that this format allows for saving isolated nodes. stores the mapping from node names to node ids.

Definition at line 176 of file gio.h.

176  {
177  TSsParser Ss(InFNm, ssfWhiteSep, true, true, true);
178  PGraph Graph = PGraph::TObj::New();
179  while (Ss.Next()) {
180  const int SrcNId = StrToNIdH.AddDatId(Ss[0]);
181  if (! Graph->IsNode(SrcNId)) { Graph->AddNode(SrcNId); }
182  for (int dst = 1; dst < Ss.Len(); dst++) {
183  const int DstNId = StrToNIdH.AddDatId(Ss[dst]);
184  if (! Graph->IsNode(DstNId)) { Graph->AddNode(DstNId); }
185  Graph->AddEdge(SrcNId, DstNId);
186  }
187  }
188  Graph->Defrag();
189  return Graph;
190 }
Definition: ss.h:72
TDat & AddDatId(const char *Key)
Definition: hash.h:772
Whitespace (space or tab) separated.
Definition: ss.h:11
PNGraph TSnap::LoadDyNet ( const TStr FNm)

For more info see ORA Network Analysis Data (http://www.casos.cs.cmu.edu/computational_tools/data2.php)

Loads a directed network in the DyNetML format. Loads only the first network in the file FNm.

Definition at line 4 of file gio.cpp.

4  {
6  THashSet<TStr> NIdStr;
7  while (XmlLx.GetSym()!=xsyEof) {
8  if (XmlLx.Sym==xsySTag && XmlLx.TagNm=="network") {
9  PNGraph G = TNGraph::New();
10  XmlLx.GetSym();
11  while (XmlLx.TagNm=="link") {
12  TStr Str1, Val1, Str2, Val2;
13  XmlLx.GetArg(0, Str1, Val1); XmlLx.GetArg(1, Str2, Val2);
14  IAssert(Str1=="source" && Str2=="target");
15  NIdStr.AddKey(Val1); NIdStr.AddKey(Val2);
16  const int src=NIdStr.GetKeyId(Val1);
17  const int dst=NIdStr.GetKeyId(Val2);
18  if (! G->IsNode(src)) { G->AddNode(src); }
19  if (! G->IsNode(dst)) { G->AddNode(dst); }
20  G->AddEdge(src, dst);
21  XmlLx.GetSym();
22  }
23  return G;
24  }
25  }
26  return PNGraph();
27 }
#define IAssert(Cond)
Definition: bd.h:262
static PNGraph New()
Static constructor that returns a pointer to the graph. Call: PNGraph Graph = TNGraph::New().
Definition: graph.h:405
Definition: xml.h:94
int GetKeyId(const TKey &Key) const
Definition: shash.h:1322
static bool IsZipFNm(const TStr &FNm)
Check whether the file extension of FNm is that of a compressed file (.gz, .7z, .rar, .zip, .cab, .arj. bzip2).
Definition: zipfl.h:56
static PSIn New(const TStr &FNm)
Definition: zipfl.cpp:124
static PSIn New(const TStr &FNm)
Definition: fl.cpp:290
Definition: xml.h:98
TPt< TNGraph > PNGraph
Pointer to a directed graph (TNGraph)
Definition: graph.h:16
int AddKey(const TKey &Key)
Definition: shash.h:1248
Definition: xml.h:93
Definition: dt.h:412
Definition: bd.h:196
TVec< PNGraph > TSnap::LoadDyNetGraphV ( const TStr FNm)

For more info see ORA Network Analysis Data (http://www.casos.cs.cmu.edu/computational_tools/data2.php)

Loads directed networks in the DyNetML format. Loads all the networks in the file FNm.

Definition at line 30 of file gio.cpp.

30  {
32  TVec<PNGraph> GraphV;
33  THashSet<TStr> NIdStr;
34  while (XmlLx.GetSym()!=xsyEof) {
35  if (XmlLx.Sym==xsySTag && XmlLx.TagNm=="network") {
36  PNGraph G = TNGraph::New();
37  GraphV.Add(G);
38  XmlLx.GetSym();
39  while (XmlLx.TagNm=="link") {
40  TStr Str1, Val1, Str2, Val2;
41  XmlLx.GetArg(0, Str1, Val1); XmlLx.GetArg(1, Str2, Val2);
42  IAssert(Str1=="source" && Str2=="target");
43  NIdStr.AddKey(Val1); NIdStr.AddKey(Val2);
44  const int src=NIdStr.GetKeyId(Val1);
45  const int dst=NIdStr.GetKeyId(Val2);
46  if (! G->IsNode(src)) { G->AddNode(src); }
47  if (! G->IsNode(dst)) { G->AddNode(dst); }
48  G->AddEdge(src, dst);
49  XmlLx.GetSym();
50  }
51  }
52  }
53  return GraphV;
54 }
#define IAssert(Cond)
Definition: bd.h:262
static PNGraph New()
Static constructor that returns a pointer to the graph. Call: PNGraph Graph = TNGraph::New().
Definition: graph.h:405
Definition: xml.h:94
int GetKeyId(const TKey &Key) const
Definition: shash.h:1322
static bool IsZipFNm(const TStr &FNm)
Check whether the file extension of FNm is that of a compressed file (.gz, .7z, .rar, .zip, .cab, .arj. bzip2).
Definition: zipfl.h:56
static PSIn New(const TStr &FNm)
Definition: zipfl.cpp:124
static PSIn New(const TStr &FNm)
Definition: fl.cpp:290
Definition: xml.h:98
int AddKey(const TKey &Key)
Definition: shash.h:1248
Definition: xml.h:93
Definition: dt.h:412
Definition: bd.h:196
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
template<class PGraph >
PGraph TSnap::LoadEdgeList ( const TStr InFNm,
const int &  SrcColId,
const int &  DstColId 
)

Loads a (directed, undirected or multi) graph from a text file InFNm with 1 edge per line (whitespace separated columns, integer node ids).

Loads the format saved by TSnap::SaveEdgeList()

Whitespace separated file of several columns: ... <source node="" id>=""> ... <destination node="" id>=""> ... SrcColId and DstColId are column indexes of source/destination (integer!) node ids. This means there is one edge per line and node IDs are assumed to be integers.

Definition at line 68 of file gio.h.

68  {
69  TSsParser Ss(InFNm, ssfWhiteSep, true, true, true);
70  PGraph Graph = PGraph::TObj::New();
71  int SrcNId, DstNId;
72  while (Ss.Next()) {
73  if (! Ss.GetInt(SrcColId, SrcNId) || ! Ss.GetInt(DstColId, DstNId)) { continue; }
74  if (! Graph->IsNode(SrcNId)) { Graph->AddNode(SrcNId); }
75  if (! Graph->IsNode(DstNId)) { Graph->AddNode(DstNId); }
76  Graph->AddEdge(SrcNId, DstNId);
77  }
78  Graph->Defrag();
79  return Graph;
80 }
Definition: ss.h:72
Whitespace (space or tab) separated.
Definition: ss.h:11
template<class PGraph >
PGraph TSnap::LoadEdgeList ( const TStr InFNm,
const int &  SrcColId,
const int &  DstColId,
const char &  Separator 
)

Loads a (directed, undirected or multi) graph from a text file InFNm with 1 edge per line ('Separator' separated columns, integer node ids).

Loads the format saved by TSnap::SaveEdgeList() if we set Separator=''.

'Separator' separated file of several columns: ... <source node="" id>=""> ... <destination node="" id>=""> ... SrcColId and DstColId are column indexes of source/destination (integer!) node ids. This means there is one edge per line and node IDs are assumed to be integers.

Definition at line 88 of file gio.h.

88  {
89  TSsParser Ss(InFNm, Separator);
90  PGraph Graph = PGraph::TObj::New();
91  int SrcNId, DstNId;
92  while (Ss.Next()) {
93  if (! Ss.GetInt(SrcColId, SrcNId) || ! Ss.GetInt(DstColId, DstNId)) { continue; }
94  if (! Graph->IsNode(SrcNId)) { Graph->AddNode(SrcNId); }
95  if (! Graph->IsNode(DstNId)) { Graph->AddNode(DstNId); }
96  Graph->AddEdge(SrcNId, DstNId);
97  }
98  Graph->Defrag();
99  return Graph;
100 }
Definition: ss.h:72
template<class PGraph >
PGraph TSnap::LoadEdgeListStr ( const TStr InFNm,
const int &  SrcColId,
const int &  DstColId 
)

Loads a (directed, undirected or multi) graph from a text file InFNm with 1 edge per line (whitespace separated columns, arbitrary string node ids).

Loads the format saved by TSnap::SaveEdgeList(), where node IDs are strings.

Whitespace separated file of several columns: ... <source node="" id>=""> ... <destination node="" id>=""> ... SrcColId and DstColId are column indexes of source/destination (string) node ids. This means there is one edge per line and node IDs can be arbitrary STRINGs. Note that the mapping of node names to ids is discarded.

Definition at line 109 of file gio.h.

109  {
110  TSsParser Ss(InFNm, ssfWhiteSep);
111  PGraph Graph = PGraph::TObj::New();
112  TStrHash<TInt> StrToNIdH(Mega(1), true); // hash-table mapping strings to integer node ids
113  while (Ss.Next()) {
114  const int SrcNId = StrToNIdH.AddKey(Ss[SrcColId]);
115  const int DstNId = StrToNIdH.AddKey(Ss[DstColId]);
116  if (! Graph->IsNode(SrcNId)) { Graph->AddNode(SrcNId); }
117  if (! Graph->IsNode(DstNId)) { Graph->AddNode(DstNId); }
118  Graph->AddEdge(SrcNId, DstNId);
119  }
120  Graph->Defrag();
121  return Graph;
122 }
Definition: ss.h:72
Whitespace (space or tab) separated.
Definition: ss.h:11
#define Mega(n)
Definition: gbase.h:4
Definition: hash.h:716
template<class PGraph >
PGraph TSnap::LoadEdgeListStr ( const TStr InFNm,
const int &  SrcColId,
const int &  DstColId,
TStrHash< TInt > &  StrToNIdH 
)

Loads a (directed, undirected or multi) graph from a text file InFNm with 1 edge per line (whitespace separated columns, arbitrary string node ids).

Loads the format saved by TSnap::SaveEdgeList(), where node IDs are strings and mapping of strings to node ids are stored.

Whitespace separated file of several columns: ... <source node="" id>=""> ... <destination node="" id>=""> ... SrcColId and DstColId are column indexes of source/destination (string) node ids. This means there is one edge per line and node IDs can be arbitrary STRINGs. The mapping of strings to node ids in stored in StrToNIdH. To map between node names and ids use: NId = StrToNIdH.GetKeyId(NodeName) and TStr NodeName = StrToNIdH.GetKey(NId);

Definition at line 132 of file gio.h.

132  {
133  TSsParser Ss(InFNm, ssfWhiteSep);
134  PGraph Graph = PGraph::TObj::New();
135  while (Ss.Next()) {
136  const int SrcNId = StrToNIdH.AddKey(Ss[SrcColId]);
137  const int DstNId = StrToNIdH.AddKey(Ss[DstColId]);
138  if (! Graph->IsNode(SrcNId)) { Graph->AddNode(SrcNId); }
139  if (! Graph->IsNode(DstNId)) { Graph->AddNode(DstNId); }
140  Graph->AddEdge(SrcNId, DstNId);
141  }
142  Graph->Defrag();
143  return Graph;
144 }
Definition: ss.h:72
Whitespace (space or tab) separated.
Definition: ss.h:11
int AddKey(const char *Key)
Definition: hash.h:870
template<class PGraph >
PGraph TSnap::LoadPajek ( const TStr InFNm)

Loads a (directed, undirected or multi) graph from Pajek .PAJ format file.

Function supports both the 1 edge per line (<source> <destination> <weight>) as well as the 1 node per line (<source> <destination1> <destination2> ...) formats.

Definition at line 193 of file gio.h.

193  {
194  PGraph Graph = PGraph::TObj::New();
195  TSsParser Ss(InFNm, ssfSpaceSep, true, true, true);
196  while ((Ss.Len()==0 || strstr(Ss[0], "*vertices") == NULL) && ! Ss.Eof()) {
197  Ss.Next(); Ss.ToLc(); }
198  // nodes
199  bool EdgeList = true;
200  EAssert(strstr(Ss[0], "*vertices") != NULL);
201  while (Ss.Next()) {
202  Ss.ToLc();
203  if (Ss.Len()>0 && Ss[0][0] == '%') { continue; } // comment
204  if (strstr(Ss[0], "*arcslist")!=NULL || strstr(Ss[0],"*edgeslist")!=NULL) { EdgeList=false; break; }
205  if (strstr(Ss[0], "*arcs")!=NULL || strstr(Ss[0],"*edges")!=NULL) { break; } // arcs are directed, edges are undirected
206  Graph->AddNode(Ss.GetInt(0));
207  }
208  // edges
209  while (Ss.Next()) {
210  if (Ss.Len()>0 && Ss[0][0] == '%') { continue; } // comment
211  if (Ss.Len()>0 && Ss[0][0] == '*') { break; }
212  if (EdgeList) {
213  // <source> <destination> <weight>
214  if (Ss.Len() >= 3 && Ss.IsInt(0) && Ss.IsInt(1)) {
215  Graph->AddEdge(Ss.GetInt(0), Ss.GetInt(1)); }
216  } else {
217  // <source> <destination1> <destination2> <destination3> ...
218  const int SrcNId = Ss.GetInt(0);
219  for (int i = 1; i < Ss.Len(); i++) {
220  Graph->AddEdge(SrcNId, Ss.GetInt(i)); }
221  }
222  }
223  return Graph;
224 }
Definition: ss.h:72
Space separated.
Definition: ss.h:10
#define EAssert(Cond)
Definition: bd.h:280
template<class PGraph >
void TSnap::MakeUnDir ( const PGraph &  Graph)

Makes the graph undirected. For every edge (u,v) an edge (v,u) is added (if it does not yet exist).

Definition at line 353 of file alg.h.

353  {
354  CAssert(HasGraphFlag(typename PGraph::TObj, gfDirected)); // graph has to be directed
355  TIntPrV EdgeV;
356  for (typename PGraph::TObj::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) {
357  const int SrcNId = EI.GetSrcNId();
358  const int DstNId = EI.GetDstNId();
359  if (! Graph->IsEdge(DstNId, SrcNId)) {
360  EdgeV.Add(TIntPr(DstNId, SrcNId));
361  }
362  }
363  for (int i = 0; i < EdgeV.Len(); i++) {
364  Graph->AddEdge(EdgeV[i].Val1, EdgeV[i].Val2);
365  }
366 }
TPair< TInt, TInt > TIntPr
Definition: ds.h:83
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
#define CAssert(Cond)
Definition: bd.h:302
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
template<class PGraph >
void TSnap::PlotClustCf ( const PGraph &  Graph,
const TStr FNmPref,
TStr  DescStr = TStr() 
)

Plots the distribution of clustering coefficient of a Graph.

Definition at line 111 of file statplot.h.

111  {
112  TFltPrV DegToCCfV;
113  int64 ClosedTriads, OpenTriads;
114  const double CCF = GetClustCf(Graph, DegToCCfV, ClosedTriads, OpenTriads);
115  if (DescStr.Empty()) { DescStr = FNmPref; }
116  TGnuPlot GnuPlot("ccf."+FNmPref,
117  TStr::Fmt("%s. G(%d, %d). Average clustering: %.4f OpenTriads: %d (%.4f) ClosedTriads: %d (%.4f)", DescStr.CStr(), Graph->GetNodes(), Graph->GetEdges(),
118  CCF, OpenTriads, OpenTriads/double(OpenTriads+ClosedTriads), ClosedTriads, ClosedTriads/double(OpenTriads+ClosedTriads)));
119  GnuPlot.AddPlot(DegToCCfV, gpwLinesPoints, "", "pt 6");
120  GnuPlot.SetXYLabel("Node degree", "Average clustering coefficient");
121  GnuPlot.SetScale(gpsLog10XY);
122  GnuPlot.SavePng();
123 }
long long int64
Definition: bd.h:27
bool Empty() const
Definition: dt.h:488
static TStr Fmt(const char *FmtStr,...)
Definition: dt.cpp:1599
double GetClustCf(const PGraph &Graph, int SampleNodes=-1)
Computes the average clustering coefficient as defined in Watts and Strogatz, Collective dynamics of ...
Definition: triad.h:100
char * CStr()
Definition: dt.h:476
void TSnap::PlotEigValDistr ( const PUNGraph Graph,
const int &  EigVals,
const TStr FNmPref,
TStr  DescStr 
)

Plots the distribution of components of the leading eigen-vector of the Graph adjacency matrix. Plots first EigVals values.

Definition at line 14 of file statplot.cpp.

14  {
15  const int NBuckets = 50;
16  TFltV EigValV;
17  for (int f = 1; EigValV.Empty() && f < 4; f++) {
18  TSnap::GetEigVals(Graph, f*EigVals, EigValV);
19  }
20  EigValV.Sort(true);
21  THash<TFlt, TFlt> BucketCntH;
22  double Step = (EigValV.Last()-EigValV[0]) / double(NBuckets-1);
23  for (int i = 0; i < NBuckets; i++) {
24  BucketCntH.AddDat(EigValV[0]+Step*(i+0.5), 0);
25  }
26  for (int i = 0; i < EigValV.Len(); i++) {
27  const int Bucket = (int) floor((EigValV[i]-EigValV[0]) / Step);
28  BucketCntH[Bucket] += 1;
29  }
30  TFltPrV EigCntV;
31  BucketCntH.GetKeyDatPrV(EigCntV);
32  if (DescStr.Empty()) { DescStr = FNmPref; }
33  TGnuPlot::PlotValV(EigCntV, "eigDistr."+FNmPref, TStr::Fmt("%s. G(%d, %d). Largest eig val = %f", DescStr.CStr(),
34  Graph->GetNodes(), Graph->GetEdges(), EigValV.Last().Val), "Eigen value", "Count", gpsAuto, false, gpwLinesPoints);
35 }
void GetEigVals(const PUNGraph &Graph, const int &EigVals, TFltV &EigValV)
Computes top EigVals eigenvalues of the adjacency matrix representing a given undirected Graph...
Definition: gsvd.cpp:308
int GetEdges() const
Returns the number of edges in the graph.
Definition: graph.cpp:74
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
Definition: gnuplot.h:7
int GetNodes() const
Returns the number of nodes in the graph.
Definition: graph.h:162
bool Empty() const
Tests whether the vector is empty.
Definition: ds.h:530
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
const TVal & Last() const
Returns a reference to the last element of the vector.
Definition: ds.h:539
bool Empty() const
Definition: dt.h:488
static void PlotValV(const TVec< TPair< TVal1, TVal2 > > &ValV, const TStr &OutFNmPref, const TStr &Desc="", const TStr &XLabel="", const TStr &YLabel="", const TGpScaleTy &ScaleTy=gpsAuto, const bool &PowerFit=false, const TGpSeriesTy &SeriesTy=gpwLinesPoints)
Definition: gnuplot.h:363
static TStr Fmt(const char *FmtStr,...)
Definition: dt.cpp:1599
Definition: hash.h:88
void GetKeyDatPrV(TVec< TPair< TKey, TDat > > &KeyDatPrV) const
Definition: hash.h:454
char * CStr()
Definition: dt.h:476
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
void TSnap::PlotEigValRank ( const PUNGraph Graph,
const int &  EigVals,
const TStr FNmPref,
TStr  DescStr 
)

Plots the eigen-value rank distribution of the Graph adjacency matrix. Plots first EigVals eigenvalues.

Definition at line 5 of file statplot.cpp.

5  {
6  TFltV EigValV;
7  TSnap::GetEigVals(Graph, EigVals, EigValV);
8  EigValV.Sort(false);
9  if (DescStr.Empty()) { DescStr = FNmPref; }
10  TGnuPlot::PlotValV(EigValV, "eigVal."+FNmPref, TStr::Fmt("%s. G(%d, %d). Largest eig val = %f",
11  DescStr.CStr(), Graph->GetNodes(), Graph->GetEdges(), EigValV[0].Val), "Rank", "Eigen value", gpsLog10XY, false, gpwLinesPoints);
12 }
void GetEigVals(const PUNGraph &Graph, const int &EigVals, TFltV &EigValV)
Computes top EigVals eigenvalues of the adjacency matrix representing a given undirected Graph...
Definition: gsvd.cpp:308
int GetEdges() const
Returns the number of edges in the graph.
Definition: graph.cpp:74
int GetNodes() const
Returns the number of nodes in the graph.
Definition: graph.h:162
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
bool Empty() const
Definition: dt.h:488
static void PlotValV(const TVec< TPair< TVal1, TVal2 > > &ValV, const TStr &OutFNmPref, const TStr &Desc="", const TStr &XLabel="", const TStr &YLabel="", const TGpScaleTy &ScaleTy=gpsAuto, const bool &PowerFit=false, const TGpSeriesTy &SeriesTy=gpwLinesPoints)
Definition: gnuplot.h:363
static TStr Fmt(const char *FmtStr,...)
Definition: dt.cpp:1599
char * CStr()
Definition: dt.h:476
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
template<class PGraph >
void TSnap::PlotHops ( const PGraph &  Graph,
const TStr FNmPref,
TStr  DescStr = TStr(),
const bool &  IsDir = false,
const int &  NApprox = 32 
)

Plots the cumulative distribution of the shortest path lengths of a Graph. Implementation is based on ANF.

Parameters
IsDirfalse: ignore edge directions and consider graph as undirected.

Definition at line 126 of file statplot.h.

126  {
127  TIntFltKdV DistNbrsV;
128  TSnap::GetAnf(Graph, DistNbrsV, -1, IsDir, NApprox);
129  const double EffDiam = TSnap::TSnapDetail::CalcEffDiam(DistNbrsV, 0.9);
130  if (DescStr.Empty()) { DescStr = FNmPref; }
131  TGnuPlot GnuPlot("hop."+FNmPref, TStr::Fmt("%s. Hop plot. EffDiam: %g, G(%d, %d)",
132  DescStr.CStr(), EffDiam, Graph->GetNodes(), Graph->GetEdges()));
133  GnuPlot.SetXYLabel("Number of hops", "Number of pairs of nodes");
134  GnuPlot.SetScale(gpsLog10Y);
135  GnuPlot.AddPlot(DistNbrsV, gpwLinesPoints, "", "pt 6");
136  GnuPlot.SavePng();
137 }
void GetAnf(const PGraph &Graph, const int &SrcNId, TIntFltKdV &DistNbrsV, const int &MxDist, const bool &IsDir, const int &NApprox=32)
Definition: anf.h:205
double CalcEffDiam(const TIntFltKdV &DistNbrsCdfV, const double &Percentile)
Helper function for computing a given Percentile of a (unnormalized) cumulative distribution function...
Definition: anf.cpp:7
bool Empty() const
Definition: dt.h:488
static TStr Fmt(const char *FmtStr,...)
Definition: dt.cpp:1599
char * CStr()
Definition: dt.h:476
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
template<class PGraph >
void TSnap::PlotInDegDistr ( const PGraph &  Graph,
const TStr FNmPref,
TStr  DescStr = TStr(),
const bool &  PlotCCdf = false,
const bool &  PowerFit = false 
)

Plots the in-degree distribution of a Graph.

Parameters
PlotCCdfPlots the distribution as a Complementary Cummulative distribution function.
PowerFitFits a Power-Law to the distribution.

Definition at line 47 of file statplot.h.

47  {
48  TIntPrV DegCntV;
49  TSnap::GetInDegCnt(Graph, DegCntV);
50  const double AvgDeg = 2*Graph->GetEdges()/double(Graph->GetNodes());
51  int AboveAvg=0, Above2Avg=0;
52  for (int i = 0; i < DegCntV.Len(); i++) {
53  if (DegCntV[i].Val1 > AvgDeg) { AboveAvg += DegCntV[i].Val2; }
54  if (DegCntV[i].Val1 > 2*AvgDeg) { Above2Avg += DegCntV[i].Val2; }
55  }
56  if (PlotCCdf) {
57  DegCntV = TGUtil::GetCCdf(DegCntV); }
58  if (DescStr.Empty()) { DescStr = FNmPref; }
59  TGnuPlot::PlotValV(DegCntV, (PlotCCdf?"inDegC.":"inDeg.")+FNmPref,
60  TStr::Fmt("%s. G(%d, %d). %d (%.4f) nodes with in-deg > avg deg (%.1f), %d (%.4f) with >2*avg.deg", DescStr.CStr(),
61  Graph->GetNodes(), Graph->GetEdges(), AboveAvg, AboveAvg/double(Graph->GetNodes()), AvgDeg, Above2Avg, Above2Avg/double(Graph->GetNodes())),
62  "In-degree", PlotCCdf?"Count (CCDF)":"Count", gpsLog10XY, PowerFit, gpwLinesPoints);
63 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
void GetInDegCnt(const PGraph &Graph, TIntPrV &DegToCntV)
Returns an in-degree histogram: a set of pairs (in-degree, number of nodes of such in-degree) ...
Definition: alg.h:179
static void GetCCdf(const TIntPrV &PdfV, TIntPrV &CCdfV)
Definition: util.cpp:33
bool Empty() const
Definition: dt.h:488
static void PlotValV(const TVec< TPair< TVal1, TVal2 > > &ValV, const TStr &OutFNmPref, const TStr &Desc="", const TStr &XLabel="", const TStr &YLabel="", const TGpScaleTy &ScaleTy=gpsAuto, const bool &PowerFit=false, const TGpSeriesTy &SeriesTy=gpwLinesPoints)
Definition: gnuplot.h:363
static TStr Fmt(const char *FmtStr,...)
Definition: dt.cpp:1599
char * CStr()
Definition: dt.h:476
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
void TSnap::PlotInvParticipRat ( const PUNGraph Graph,
const int &  MaxEigVecs,
const int &  TimeLimit,
const TStr FNmPref,
TStr  DescStr = TStr() 
)

Plots the inverse participation ratio. See Spectra of "real-world" graphs: Beyond the semicircle law by Farkas, Derenyi, Barabasi and Vicsek.

Definition at line 39 of file statplot.cpp.

39  {
40  TFltPrV EigIprV;
41  GetInvParticipRat(Graph, MaxEigVecs, TimeLimit, EigIprV);
42  if (DescStr.Empty()) { DescStr = FNmPref; }
43  if (EigIprV.Empty()) { DescStr+=". FAIL"; EigIprV.Add(TFltPr(-1,-1)); return; }
44  TGnuPlot::PlotValV(EigIprV, "eigIPR."+FNmPref, TStr::Fmt("%s. G(%d, %d). Largest eig val = %f (%d values)",
45  DescStr.CStr(), Graph->GetNodes(), Graph->GetEdges(), EigIprV.Last().Val1(), EigIprV.Len()),
46  "Eigenvalue", "Inverse Participation Ratio of corresponding Eigenvector", gpsLog10Y, false, gpwPoints);
47 }
void GetInvParticipRat(const PUNGraph &Graph, int MaxEigVecs, int TimeLimit, TFltPrV &EigValIprV)
Definition: gsvd.cpp:377
int GetEdges() const
Returns the number of edges in the graph.
Definition: graph.cpp:74
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
int GetNodes() const
Returns the number of nodes in the graph.
Definition: graph.h:162
bool Empty() const
Tests whether the vector is empty.
Definition: ds.h:530
const TVal & Last() const
Returns a reference to the last element of the vector.
Definition: ds.h:539
TPair< TFlt, TFlt > TFltPr
Definition: ds.h:99
bool Empty() const
Definition: dt.h:488
static void PlotValV(const TVec< TPair< TVal1, TVal2 > > &ValV, const TStr &OutFNmPref, const TStr &Desc="", const TStr &XLabel="", const TStr &YLabel="", const TGpScaleTy &ScaleTy=gpsAuto, const bool &PowerFit=false, const TGpSeriesTy &SeriesTy=gpwLinesPoints)
Definition: gnuplot.h:363
static TStr Fmt(const char *FmtStr,...)
Definition: dt.cpp:1599
TVal1 Val1
Definition: ds.h:34
char * CStr()
Definition: dt.h:476
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
template<class PGraph >
void TSnap::PlotKCoreEdges ( const PGraph &  Graph,
const TStr FNmPref,
TStr  DescStr = TStr() 
)

Plots the k-Core edge-size distribution: Core k vs. number of edges in k-core.

Definition at line 175 of file statplot.h.

175  {
176  TIntPrV CoreEdgesV;
177  TSnap::GetKCoreEdges(Graph, CoreEdgesV);
178  if (DescStr.Empty()) { DescStr = FNmPref; }
179  TGnuPlot::PlotValV(CoreEdgesV, "coreEdges."+FNmPref, TStr::Fmt("%s. G(%d, %d).", DescStr.CStr(), Graph->GetNodes(), Graph->GetEdges()), "k-Core", "Number of edges in the k-Core", gpsLog10Y, false, gpwLinesPoints);
180 }
int GetKCoreEdges(const PGraph &Graph, TIntPrV &CoreIdSzV)
Returns the number of edges in each core of order K (where K=0, 1, ...)
Definition: kcore.h:126
bool Empty() const
Definition: dt.h:488
static void PlotValV(const TVec< TPair< TVal1, TVal2 > > &ValV, const TStr &OutFNmPref, const TStr &Desc="", const TStr &XLabel="", const TStr &YLabel="", const TGpScaleTy &ScaleTy=gpsAuto, const bool &PowerFit=false, const TGpSeriesTy &SeriesTy=gpwLinesPoints)
Definition: gnuplot.h:363
static TStr Fmt(const char *FmtStr,...)
Definition: dt.cpp:1599
char * CStr()
Definition: dt.h:476
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
template<class PGraph >
void TSnap::PlotKCoreNodes ( const PGraph &  Graph,
const TStr FNmPref,
TStr  DescStr = TStr() 
)

Plots the k-Core node-size distribution: Core k vs. number of nodes in k-core.

Definition at line 167 of file statplot.h.

167  {
168  TIntPrV CoreNodesV;
169  TSnap::GetKCoreNodes(Graph, CoreNodesV);
170  if (DescStr.Empty()) { DescStr = FNmPref; }
171  TGnuPlot::PlotValV(CoreNodesV, "coreNodes."+FNmPref, TStr::Fmt("%s. G(%d, %d).", DescStr.CStr(), Graph->GetNodes(), Graph->GetEdges()), "k-Core", "Number of nodes in the k-Core", gpsLog10Y, false, gpwLinesPoints);
172 }
int GetKCoreNodes(const PGraph &Graph, TIntPrV &CoreIdSzV)
Returns the number of nodes in each core of order K (where K=0, 1, ...)
Definition: kcore.h:114
bool Empty() const
Definition: dt.h:488
static void PlotValV(const TVec< TPair< TVal1, TVal2 > > &ValV, const TStr &OutFNmPref, const TStr &Desc="", const TStr &XLabel="", const TStr &YLabel="", const TGpScaleTy &ScaleTy=gpsAuto, const bool &PowerFit=false, const TGpSeriesTy &SeriesTy=gpwLinesPoints)
Definition: gnuplot.h:363
static TStr Fmt(const char *FmtStr,...)
Definition: dt.cpp:1599
char * CStr()
Definition: dt.h:476
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
template<class PGraph >
void TSnap::PlotOutDegDistr ( const PGraph &  Graph,
const TStr FNmPref,
TStr  DescStr = TStr(),
const bool &  PlotCCdf = false,
const bool &  PowerFit = false 
)

Plots the out-degree distribution of a Graph.

Parameters
PlotCCdfPlots the distribution as a Complementary Cumulative Distribution Function (CCDF).
PowerFitFits a Power-Law to the distribution.

Definition at line 66 of file statplot.h.

66  {
67  TIntPrV DegCntV;
68  TSnap::GetOutDegCnt(Graph, DegCntV);
69  const double AvgDeg = 2*Graph->GetEdges()/double(Graph->GetNodes());
70  int AboveAvg=0, Above2Avg=0;
71  for (int i = 0; i < DegCntV.Len(); i++) {
72  if (DegCntV[i].Val1 > AvgDeg) { AboveAvg += DegCntV[i].Val2; }
73  if (DegCntV[i].Val1 > 2*AvgDeg) { Above2Avg += DegCntV[i].Val2; }
74  }
75  if (PlotCCdf) {
76  DegCntV = TGUtil::GetCCdf(DegCntV); }
77  if (DescStr.Empty()) { DescStr = FNmPref; }
78  TGnuPlot::PlotValV(DegCntV, (PlotCCdf?"outDegC.":"outDeg.")+FNmPref,
79  TStr::Fmt("%s. G(%d, %d). %d (%.4f) nodes with out-deg > avg deg (%.1f), %d (%.4f) with >2*avg.deg", DescStr.CStr(),
80  Graph->GetNodes(), Graph->GetEdges(), AboveAvg, AboveAvg/double(Graph->GetNodes()), AvgDeg, Above2Avg, Above2Avg/double(Graph->GetNodes())),
81  "Out-degree", PlotCCdf?"Count (CCDF)":"Count", gpsLog10XY, PowerFit, gpwLinesPoints);
82 }
void GetOutDegCnt(const PGraph &Graph, TIntPrV &DegToCntV)
Returns an out-degree histogram: a set of pairs (out-degree, number of nodes of such out-degree) ...
Definition: alg.h:201
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
static void GetCCdf(const TIntPrV &PdfV, TIntPrV &CCdfV)
Definition: util.cpp:33
bool Empty() const
Definition: dt.h:488
static void PlotValV(const TVec< TPair< TVal1, TVal2 > > &ValV, const TStr &OutFNmPref, const TStr &Desc="", const TStr &XLabel="", const TStr &YLabel="", const TGpScaleTy &ScaleTy=gpsAuto, const bool &PowerFit=false, const TGpSeriesTy &SeriesTy=gpwLinesPoints)
Definition: gnuplot.h:363
static TStr Fmt(const char *FmtStr,...)
Definition: dt.cpp:1599
char * CStr()
Definition: dt.h:476
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
template<class PGraph >
void TSnap::PlotSccDistr ( const PGraph &  Graph,
const TStr FNmPref,
TStr  DescStr = TStr() 
)

Plots the distribution of sizes of strongly connected components of a Graph.

Definition at line 98 of file statplot.h.

98  {
99  TIntPrV SccSzCnt;
100  TSnap::GetSccSzCnt(Graph, SccSzCnt);
101  if (DescStr.Empty()) { DescStr = FNmPref; }
102  TGnuPlot GnuPlot("scc."+FNmPref, TStr::Fmt("%s. G(%d, %d). Largest component has %f nodes",
103  DescStr.CStr(), Graph->GetNodes(), Graph->GetEdges(), SccSzCnt.Last().Val1/double(Graph->GetNodes())));
104  GnuPlot.AddPlot(SccSzCnt, gpwLinesPoints, "", "pt 6");
105  GnuPlot.SetXYLabel("Size of strongly connected component", "Number of components");
106  GnuPlot.SetScale(gpsLog10XY);
107  GnuPlot.SavePng();
108 }
void GetSccSzCnt(const PGraph &Graph, TIntPrV &SccSzCnt)
Returns a distribution of strongly connected component sizes.
Definition: cncom.h:420
const TVal & Last() const
Returns a reference to the last element of the vector.
Definition: ds.h:539
bool Empty() const
Definition: dt.h:488
static TStr Fmt(const char *FmtStr,...)
Definition: dt.cpp:1599
int AddPlot(const TIntV &YValV, const TGpSeriesTy &SeriesTy=gpwLinesPoints, const TStr &Label=TStr(), const TStr &Style=TStr())
Definition: gnuplot.cpp:182
char * CStr()
Definition: dt.h:476
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
template<class PGraph >
void TSnap::PlotShortPathDistr ( const PGraph &  Graph,
const TStr FNmPref,
TStr  DescStr = TStr(),
int  TestNodes = TInt::Mx 
)

Plots the distribution of the shortest path lengths of a Graph. Implementation is based on BFS.

Definition at line 140 of file statplot.h.

140  {
141  TIntH DistToCntH;
142  TBreathFS<PGraph> BFS(Graph);
143  // shotest paths
144  TIntV NodeIdV;
145  Graph->GetNIdV(NodeIdV); NodeIdV.Shuffle(TInt::Rnd);
146  for (int tries = 0; tries < TMath::Mn(TestNodes, Graph->GetNodes()); tries++) {
147  const int NId = NodeIdV[tries];
148  BFS.DoBfs(NId, true, false, -1, TInt::Mx);
149  for (int i = 0; i < BFS.NIdDistH.Len(); i++) {
150  DistToCntH.AddDat(BFS.NIdDistH[i]) += 1; }
151  }
152  DistToCntH.SortByKey(true);
153  TFltPrV DistNbrsPdfV;
154  for (int i = 0; i < DistToCntH.Len(); i++) {
155  DistNbrsPdfV.Add(TFltPr(DistToCntH.GetKey(i)(), DistToCntH[i]()));
156  }
157  const double EffDiam = TSnap::TSnapDetail::CalcEffDiamPdf(DistNbrsPdfV, 0.9);
158  const double AvgDiam = TSnap::TSnapDetail::CalcAvgDiamPdf(DistNbrsPdfV);
159  const int FullDiam = (int) DistNbrsPdfV.Last().Val1;
160  if (DescStr.Empty()) { DescStr = FNmPref; }
161  TGnuPlot::PlotValV(DistNbrsPdfV, "diam."+FNmPref,
162  TStr::Fmt("%s. G(%d, %d). Diam: avg:%.2f eff:%.2f max:%d", DescStr.CStr(), Graph->GetNodes(), Graph->GetEdges(),
163  AvgDiam, EffDiam, FullDiam), "Number of hops", "Number of shortest paths", gpsLog10Y, false, gpwLinesPoints);
164 }
static const T & Mn(const T &LVal, const T &RVal)
Definition: xmath.h:36
static const int Mx
Definition: dt.h:1046
static TRnd Rnd
Definition: dt.h:1050
double CalcEffDiamPdf(const TIntFltKdV &DistNbrsPdfV, const double &Percentile)
Helper function for computing a given Percentile of a (unnormalized) probability distribution functio...
Definition: anf.cpp:29
const TVal & Last() const
Returns a reference to the last element of the vector.
Definition: ds.h:539
TPair< TFlt, TFlt > TFltPr
Definition: ds.h:99
void SortByKey(const bool &Asc=true)
Definition: hash.h:245
double CalcAvgDiamPdf(const TIntFltKdV &DistNbrsPdfV)
Helper function for computing the mean of a (unnormalized) probability distribution function...
Definition: anf.cpp:41
bool Empty() const
Definition: dt.h:488
static void PlotValV(const TVec< TPair< TVal1, TVal2 > > &ValV, const TStr &OutFNmPref, const TStr &Desc="", const TStr &XLabel="", const TStr &YLabel="", const TGpScaleTy &ScaleTy=gpsAuto, const bool &PowerFit=false, const TGpSeriesTy &SeriesTy=gpwLinesPoints)
Definition: gnuplot.h:363
static TStr Fmt(const char *FmtStr,...)
Definition: dt.cpp:1599
void Shuffle(TRnd &Rnd)
Randomly shuffles the elements of the vector.
Definition: ds.h:1235
TVal1 Val1
Definition: ds.h:34
char * CStr()
Definition: dt.h:476
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
int Len() const
Definition: hash.h:186
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
const TKey & GetKey(const int &KeyId) const
Definition: hash.h:210
void TSnap::PlotSngValDistr ( const PNGraph Graph,
const int &  SngVals,
const TStr FNmPref,
TStr  DescStr 
)

Plots the rank distribution of singular values of the Graph adjacency matrix. Plots first SngVals values.

Definition at line 58 of file statplot.cpp.

58  {
59  const int NBuckets = 50;
60  TFltV SngValV;
61  for (int f = 1; SngValV.Empty() && f < 4; f++) {
62  TSnap::GetSngVals(Graph, f*SngVals, SngValV);
63  }
64  SngValV.Sort(true);
65  THash<TFlt, TFlt> BucketCntH;
66  double Step = (SngValV.Last()-SngValV[0]) / double(NBuckets-1);
67  for (int i = 0; i < NBuckets; i++) {
68  BucketCntH.AddDat(SngValV[0]+Step*(i+0.5), 0);
69  }
70  for (int i = 0; i < SngValV.Len(); i++) {
71  const int Bucket = (int) floor((SngValV[i]-SngValV[0]) / Step);
72  BucketCntH[Bucket] += 1;
73  }
74  TFltPrV EigCntV;
75  BucketCntH.GetKeyDatPrV(EigCntV);
76  if (DescStr.Empty()) { DescStr = FNmPref; }
77  TGnuPlot::PlotValV(EigCntV, "sngDistr."+FNmPref, TStr::Fmt("%s. G(%d, %d). Largest eig val = %f", DescStr.CStr(),
78  Graph->GetNodes(), Graph->GetEdges(), SngValV.Last().Val), "Singular value", "Count", gpsAuto, false, gpwLinesPoints);
79 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
Definition: gnuplot.h:7
bool Empty() const
Tests whether the vector is empty.
Definition: ds.h:530
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
const TVal & Last() const
Returns a reference to the last element of the vector.
Definition: ds.h:539
void GetSngVals(const PNGraph &Graph, const int &SngVals, TFltV &SngValV)
Computes largest SngVals singular values of the adjacency matrix representing a directed Graph...
Definition: gsvd.cpp:175
bool Empty() const
Definition: dt.h:488
static void PlotValV(const TVec< TPair< TVal1, TVal2 > > &ValV, const TStr &OutFNmPref, const TStr &Desc="", const TStr &XLabel="", const TStr &YLabel="", const TGpScaleTy &ScaleTy=gpsAuto, const bool &PowerFit=false, const TGpSeriesTy &SeriesTy=gpwLinesPoints)
Definition: gnuplot.h:363
static TStr Fmt(const char *FmtStr,...)
Definition: dt.cpp:1599
Definition: hash.h:88
void GetKeyDatPrV(TVec< TPair< TKey, TDat > > &KeyDatPrV) const
Definition: hash.h:454
char * CStr()
Definition: dt.h:476
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
void TSnap::PlotSngValRank ( const PNGraph Graph,
const int &  SngVals,
const TStr FNmPref,
TStr  DescStr 
)

Plots the rank distribution of singular values of the Graph adjacency matrix. Plots first SngVals values.

Definition at line 49 of file statplot.cpp.

49  {
50  TFltV SngValV;
51  TSnap::GetSngVals(Graph, SngVals, SngValV);
52  SngValV.Sort(false);
53  if (DescStr.Empty()) { DescStr = FNmPref; }
54  TGnuPlot::PlotValV(SngValV, "sngVal."+FNmPref, TStr::Fmt("%s. G(%d, %d). Largest eig val = %f",
55  DescStr.CStr(), Graph->GetNodes(), Graph->GetEdges(), SngValV[0].Val), "Rank", "Singular value", gpsLog10XY, false, gpwLinesPoints);
56 }
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
void GetSngVals(const PNGraph &Graph, const int &SngVals, TFltV &SngValV)
Computes largest SngVals singular values of the adjacency matrix representing a directed Graph...
Definition: gsvd.cpp:175
bool Empty() const
Definition: dt.h:488
static void PlotValV(const TVec< TPair< TVal1, TVal2 > > &ValV, const TStr &OutFNmPref, const TStr &Desc="", const TStr &XLabel="", const TStr &YLabel="", const TGpScaleTy &ScaleTy=gpsAuto, const bool &PowerFit=false, const TGpSeriesTy &SeriesTy=gpwLinesPoints)
Definition: gnuplot.h:363
static TStr Fmt(const char *FmtStr,...)
Definition: dt.cpp:1599
char * CStr()
Definition: dt.h:476
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
void TSnap::PlotSngVec ( const PNGraph Graph,
const TStr FNmPref,
TStr  DescStr 
)

Plots the distribution of the values of the leading left singular vector of the Graph adjacency matrix. Plots first SngVals values.

Definition at line 81 of file statplot.cpp.

81  {
82  TFltV LeftSV, RightSV;
83  TSnap::GetSngVec(Graph, LeftSV, RightSV);
84  LeftSV.Sort(false);
85  RightSV.Sort(false);
86  TFltV BinV;
87  if (DescStr.Empty()) { DescStr = FNmPref; }
88  TGUtil::MakeExpBins(LeftSV, BinV, 1.01);
89  TGnuPlot::PlotValV(BinV, "sngVecL."+FNmPref, TStr::Fmt("%s. G(%d, %d). Left signular vector",
90  DescStr.CStr(), Graph->GetNodes(), Graph->GetEdges()), "Rank", "Component of left singular vector", gpsLog10XY, false, gpwLinesPoints);
91  TGnuPlot::PlotValV(BinV, "sngVecL."+FNmPref, TStr::Fmt("%s. G(%d, %d). Right signular vector",
92  DescStr.CStr(), Graph->GetNodes(), Graph->GetEdges()), "Rank", "Component of right singular vector", gpsLog10XY, false, gpwLinesPoints);
93 }
static void MakeExpBins(const TFltPrV &XYValV, TFltPrV &ExpXYValV, const double &BinFactor=2, const double &MinYVal=1)
Definition: util.cpp:99
void GetSngVec(const PNGraph &Graph, TFltV &LeftSV, TFltV &RightSV)
Computes the leading left and right singular vector of the adjacency matrix representing a directed G...
Definition: gsvd.cpp:225
void Sort(const bool &Asc=true)
Sorts the elements of the vector.
Definition: ds.h:1218
bool Empty() const
Definition: dt.h:488
static void PlotValV(const TVec< TPair< TVal1, TVal2 > > &ValV, const TStr &OutFNmPref, const TStr &Desc="", const TStr &XLabel="", const TStr &YLabel="", const TGpScaleTy &ScaleTy=gpsAuto, const bool &PowerFit=false, const TGpSeriesTy &SeriesTy=gpwLinesPoints)
Definition: gnuplot.h:363
static TStr Fmt(const char *FmtStr,...)
Definition: dt.cpp:1599
char * CStr()
Definition: dt.h:476
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
template<class PGraph >
void TSnap::PlotWccDistr ( const PGraph &  Graph,
const TStr FNmPref,
TStr  DescStr = TStr() 
)

Plots the distribution of sizes of weakly connected components of a Graph.

Definition at line 85 of file statplot.h.

85  {
86  TIntPrV WccSzCnt;
87  TSnap::GetWccSzCnt(Graph, WccSzCnt);
88  if (DescStr.Empty()) { DescStr = FNmPref; }
89  TGnuPlot GnuPlot("wcc."+FNmPref, TStr::Fmt("%s. G(%d, %d). Largest component has %f nodes",
90  DescStr.CStr(), Graph->GetNodes(), Graph->GetEdges(), WccSzCnt.Last().Val1/double(Graph->GetNodes())));
91  GnuPlot.AddPlot(WccSzCnt, gpwLinesPoints, "", "pt 6");
92  GnuPlot.SetXYLabel("Size of weakly connected component", "Number of components");
93  GnuPlot.SetScale(gpsLog10XY);
94  GnuPlot.SavePng();
95 }
const TVal & Last() const
Returns a reference to the last element of the vector.
Definition: ds.h:539
bool Empty() const
Definition: dt.h:488
static TStr Fmt(const char *FmtStr,...)
Definition: dt.cpp:1599
int AddPlot(const TIntV &YValV, const TGpSeriesTy &SeriesTy=gpwLinesPoints, const TStr &Label=TStr(), const TStr &Style=TStr())
Definition: gnuplot.cpp:182
char * CStr()
Definition: dt.h:476
void GetWccSzCnt(const PGraph &Graph, TIntPrV &WccSzCnt)
Returns a distribution of weakly connected component sizes.
Definition: cncom.h:337
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420
template<class PGraph >
void TSnap::PrintInfo ( const PGraph &  Graph,
const TStr Desc = "",
const TStr OutFNm = "",
const bool &  Fast = true 
)

Prints basic graph statistics.

Parameters
Fasttrue: only computes basic statistics (that can be computed fast). For more extensive information (and longer execution times) set Fast = false.

Definition at line 84 of file gbase.h.

84  {
85  int BiDirEdges=0, ZeroNodes=0, ZeroInNodes=0, ZeroOutNodes=0, SelfEdges=0, NonZIODegNodes=0;
86  THash<TIntPr, TInt> UniqDirE, UniqUnDirE;
87  FILE *F = stdout;
88  if (! OutFNm.Empty()) F = fopen(OutFNm.CStr(), "wt");
89  if (! Desc.Empty()) { fprintf(F, "%s:", Desc.CStr()); }
90  else { fprintf(F, "Graph:"); }
91  for (int f = gfUndef; f < gfMx; f++) {
92  if (HasGraphFlag(typename PGraph::TObj, TGraphFlag(f))) {
93  fprintf(F, " %s", TSnap::GetFlagStr(TGraphFlag(f)).CStr()); }
94  }
95  // calc stat
96  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
97  if (NI.GetDeg()==0) ZeroNodes++;
98  if (NI.GetInDeg()==0) ZeroInNodes++;
99  if (NI.GetOutDeg()==0) ZeroOutNodes++;
100  if (NI.GetInDeg()!=0 && NI.GetOutDeg()!=0) NonZIODegNodes++;
101  if (! Fast || Graph->GetNodes() < 1000) {
102  const int NId = NI.GetId();
103  for (int edge = 0; edge < NI.GetOutDeg(); edge++) {
104  const int DstNId = NI.GetOutNId(edge);
105  if (Graph->IsEdge(DstNId, NId)) BiDirEdges++;
106  if (NId == DstNId) SelfEdges++;
107  UniqDirE.AddKey(TIntPr(NId, DstNId));
108  UniqUnDirE.AddKey(TIntPr(TInt::GetMn(NId, DstNId), TInt::GetMx(NId, DstNId)));
109  }
110  }
111  }
112  int64 Closed=0, Open=0;
113  double WccSz=0, SccSz=0;
114  double EffDiam=0;
115  int FullDiam=0;
116  if (! Fast) {
117  TSnap::GetTriads(Graph, Closed, Open);
118  WccSz = TSnap::GetMxWccSz(Graph);
119  SccSz = TSnap::GetMxSccSz(Graph);
120  TSnap::GetBfsEffDiam(Graph, 100, false, EffDiam, FullDiam);
121  }
122  // print info
123  fprintf(F, "\n");
124  fprintf(F, " Nodes: %d\n", Graph->GetNodes());
125  fprintf(F, " Edges: %d\n", Graph->GetEdges());
126  fprintf(F, " Zero Deg Nodes: %d\n", ZeroNodes);
127  fprintf(F, " Zero InDeg Nodes: %d\n", ZeroInNodes);
128  fprintf(F, " Zero OutDeg Nodes: %d\n", ZeroOutNodes);
129  fprintf(F, " NonZero In-Out Deg Nodes: %d\n", NonZIODegNodes);
130  if (! Fast) {
131  fprintf(F, " Unique directed edges: %d\n", UniqDirE.Len());
132  fprintf(F, " Unique undirected edges: %d\n", UniqUnDirE.Len());
133  fprintf(F, " Self Edges: %d\n", SelfEdges);
134  fprintf(F, " BiDir Edges: %d\n", BiDirEdges);
135  fprintf(F, " Closed triangles: %s\n", TUInt64::GetStr(Closed).CStr());
136  fprintf(F, " Open triangles: %s\n", TUInt64::GetStr(Open).CStr());
137  fprintf(F, " Frac. of closed triads: %f\n", Closed/double(Closed+Open));
138  fprintf(F, " Connected component size: %f\n", WccSz);
139  fprintf(F, " Strong conn. comp. size: %f\n", SccSz);
140  fprintf(F, " Approx. full diameter: %d\n", FullDiam);
141  fprintf(F, " 90%% effective diameter: %f\n", EffDiam);
142  //fprintf(F, " Core\tNodes\tEdges\n");
143  //for (int i = 0; i < CNodesV.Len(); i++) {
144  // printf(" %d\t%d\t%d\n", CNodesV[i].Val1(), CNodesV[i].Val2(), CEdgesV[i].Val2());
145  //}
146  }
147  if (! OutFNm.Empty()) { fclose(F); }
148 }
TPair< TInt, TInt > TIntPr
Definition: ds.h:83
int64 GetTriads(const PGraph &Graph, int64 &ClosedTriads, int64 &OpenTriads, int SampleNodes=-1)
Computes the number of Closed and Open triads.
Definition: triad.h:194
double GetBfsEffDiam(const PGraph &Graph, const int &NTestNodes, const bool &IsDir=false)
Returns the (approximation of the) Effective Diameter (90-th percentile of the distribution of shorte...
Definition: bfsdfs.h:278
double GetMxWccSz(const PGraph &Graph)
Returns the fraction of nodes in the largest weakly connected component of a Graph.
Definition: cncom.h:436
static int GetMx(const int &Int1, const int &Int2)
Definition: dt.h:1089
default value, no flags
Definition: gbase.h:12
TStr GetFlagStr(const TGraphFlag &GraphFlag)
Returns a string representation of a flag.
Definition: gbase.cpp:5
static int GetMn(const int &Int1, const int &Int2)
Definition: dt.h:1087
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
double GetMxSccSz(const PGraph &Graph)
Returns the fraction of nodes in the largest strongly connected component of a Graph.
Definition: cncom.h:444
int AddKey(const TKey &Key)
Definition: hash.h:327
TStr GetStr() const
Definition: dt.h:1266
long long int64
Definition: bd.h:27
bool Empty() const
Definition: dt.h:488
sentinel, last value for iteration
Definition: gbase.h:19
enum TGraphFlag_ TGraphFlag
Graph Flags, used for quick testing of graph types.
Definition: hash.h:88
char * CStr()
Definition: dt.h:476
int Len() const
Definition: hash.h:186
int TSnap::PushRelabel ( TPRManager &  PRM,
const int &  NId,
const TNEANet::TNodeI NI 
)

Returns the ID of the neighbor that NId pushes to, -1 if no push was made.

Definition at line 328 of file flow.cpp.

328  {
329  int EdgeN = PRM.EdgeNum(NId);
330  int EId = -1, NbrNId = -1, ResFlow = 0;
331  int Cutoff = NI.GetInDeg();
332  if (EdgeN < Cutoff) {
333  EId = NI.GetInEId(EdgeN);
334  NbrNId = NI.GetInNId(EdgeN);
335  ResFlow = PRM.Flow(EId);
336  } else {
337  EId = NI.GetOutEId(EdgeN - Cutoff);
338  NbrNId = NI.GetOutNId(EdgeN - Cutoff);
339  ResFlow = PRM.Capacity(EId) - PRM.Flow(EId);
340  }
341  if (ResFlow > 0 && PRM.Label(NId) - 1 == PRM.Label(NbrNId)) {
342  if (EdgeN < Cutoff) {
343  PushToInNbr(PRM, NId, NbrNId, EId);
344  } else {
345  PushToOutNbr(PRM, NId, NbrNId, EId);
346  }
347  return NbrNId;
348  }
349  if (EdgeN + 1 == NI.GetDeg()) {
350  PRM.EdgeNum(NId) = 0;
351  Relabel(PRM, NId, NI);
352  } else {
353  PRM.EdgeNum(NId)++;
354  }
355  return -1;
356 }
void PushToOutNbr(TPRManager &PRM, const int &NId, const int &OutNId, const int &EId)
Pushes flow from a node NId to a neighbor OutNId over edge EId.
Definition: flow.cpp:289
int GetOutNId(const int &EdgeN) const
Returns ID of EdgeN-th out-node (the node the current node points to).
Definition: network.h:1657
int GetInNId(const int &EdgeN) const
Returns ID of EdgeN-th in-node (the node pointing to the current node).
Definition: network.h:1653
void Relabel(TPRManager &PRM, const int &NId, const TNEANet::TNodeI &NI)
Increases the label of a node NId to allow valid pushes to some neighbor.
Definition: flow.cpp:305
int GetOutEId(const int &EdgeN) const
Returns ID of EdgeN-th out-edge.
Definition: network.h:1671
int GetDeg() const
Returns degree of the current node, the sum of in-degree and out-degree.
Definition: network.h:1645
int GetInEId(const int &EdgeN) const
Returns ID of EdgeN-th in-edge.
Definition: network.h:1669
int GetInDeg() const
Returns in-degree of the current node.
Definition: network.h:1647
void PushToInNbr(TPRManager &PRM, const int &NId, const int &InNId, const int &EId)
Returns flow from a node NId to a neighbor InNId over edge EId.
Definition: flow.cpp:297
void TSnap::PushToInNbr ( TPRManager &  PRM,
const int &  NId,
const int &  InNId,
const int &  EId 
)

Returns flow from a node NId to a neighbor InNId over edge EId.

Definition at line 297 of file flow.cpp.

297  {
298  int MinPush = min(PRM.Flow(EId), PRM.Excess(NId));
299  PRM.Flow(EId) -= MinPush;
300  PRM.Excess(NId) -= MinPush;
301  PRM.Excess(InNId) += MinPush;
302 }
#define min(a, b)
Definition: bd.h:346
void TSnap::PushToOutNbr ( TPRManager &  PRM,
const int &  NId,
const int &  OutNId,
const int &  EId 
)

Pushes flow from a node NId to a neighbor OutNId over edge EId.

Definition at line 289 of file flow.cpp.

289  {
290  int MinPush = min(PRM.Capacity(EId) - PRM.Flow(EId), PRM.Excess(NId));
291  PRM.Flow(EId) += MinPush;
292  PRM.Excess(NId) -= MinPush;
293  PRM.Excess(OutNId) += MinPush;
294 }
#define min(a, b)
Definition: bd.h:346
void TSnap::Relabel ( TPRManager &  PRM,
const int &  NId,
const TNEANet::TNodeI NI 
)

Increases the label of a node NId to allow valid pushes to some neighbor.

Definition at line 305 of file flow.cpp.

305  {
306  int MaxLabel = PRM.GetMaxLabel();
307  int MinLabel = MaxLabel;
308  for (int EdgeN = 0; EdgeN < NI.GetInDeg(); EdgeN++) {
309  if (PRM.Flow(NI.GetInEId(EdgeN)) > 0) {
310  int InLabel = PRM.Label(NI.GetInNId(EdgeN));
311  MinLabel = min(MinLabel, InLabel);
312  }
313  }
314  for (int EdgeN = 0; EdgeN < NI.GetOutDeg(); EdgeN++) {
315  if (PRM.Capacity(NI.GetOutEId(EdgeN)) > PRM.Flow(NI.GetOutEId(EdgeN))) {
316  int OutLabel = PRM.Label(NI.GetOutNId(EdgeN));
317  MinLabel = min(MinLabel, OutLabel);
318  }
319  }
320  if (MinLabel == MaxLabel) {
321  PRM.SetLabel(NId, MaxLabel);
322  } else {
323  PRM.SetLabel(NId, MinLabel + 1);
324  }
325 }
int GetOutNId(const int &EdgeN) const
Returns ID of EdgeN-th out-node (the node the current node points to).
Definition: network.h:1657
int GetOutDeg() const
Returns out-degree of the current node.
Definition: network.h:1649
int GetInNId(const int &EdgeN) const
Returns ID of EdgeN-th in-node (the node pointing to the current node).
Definition: network.h:1653
int GetOutEId(const int &EdgeN) const
Returns ID of EdgeN-th out-edge.
Definition: network.h:1671
int GetInEId(const int &EdgeN) const
Returns ID of EdgeN-th in-edge.
Definition: network.h:1669
int GetInDeg() const
Returns in-degree of the current node.
Definition: network.h:1647
#define min(a, b)
Definition: bd.h:346
template<class PGraph >
void TSnap::SaveEdgeList ( const PGraph &  Graph,
const TStr OutFNm,
const TStr Desc = TStr() 
)

Saves a graph into a text file. Each line contains two columns and encodes a single edge: <source node="" id>=""><tab><destination node="" id>="">

Definition at line 227 of file gio.h.

227  {
228  FILE *F = fopen(OutFNm.CStr(), "wt");
229  if (HasGraphFlag(typename PGraph::TObj, gfDirected)) { fprintf(F, "# Directed graph: %s \n", OutFNm.CStr()); }
230  else { fprintf(F, "# Undirected graph (each unordered pair of nodes is saved once): %s\n", OutFNm.CStr()); }
231  if (! Desc.Empty()) { fprintf(F, "# %s\n", Desc.CStr()); }
232  fprintf(F, "# Nodes: %d Edges: %d\n", Graph->GetNodes(), Graph->GetEdges());
233  if (HasGraphFlag(typename PGraph::TObj, gfDirected)) { fprintf(F, "# FromNodeId\tToNodeId\n"); }
234  else { fprintf(F, "# NodeId\tNodeId\n"); }
235  for (typename PGraph::TObj::TEdgeI ei = Graph->BegEI(); ei < Graph->EndEI(); ei++) {
236  fprintf(F, "%d\t%d\n", ei.GetSrcNId(), ei.GetDstNId());
237  }
238  fclose(F);
239 }
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
bool Empty() const
Definition: dt.h:488
char * CStr()
Definition: dt.h:476
template<class PGraph >
void TSnap::SaveGViz ( const PGraph &  Graph,
const TStr OutFNm,
const TStr Desc = TStr(),
const bool &  NodeLabels = false,
const TIntStrH NIdColorH = TIntStrH() 
)

Save a graph in GraphVizp .DOT format.

Save a graph in GraphVizp .DOT format.

Parameters
NIdColorHMaps node ids to node colors (see GraphViz documentation for more details).

Definition at line 369 of file gio.h.

369  {
370  const bool IsDir = HasGraphFlag(typename PGraph::TObj, gfDirected);
371  FILE *F = fopen(OutFNm.CStr(), "wt");
372  if (! Desc.Empty()) fprintf(F, "/*****\n%s\n*****/\n\n", Desc.CStr());
373  if (IsDir) { fprintf(F, "digraph G {\n"); } else { fprintf(F, "graph G {\n"); }
374  fprintf(F, " graph [splines=false overlap=false]\n"); //size=\"12,10\" ratio=fill
375  // node [width=0.3, height=0.3, label=\"\", style=filled, color=black]
376  // node [shape=box, width=0.3, height=0.3, label=\"\", style=filled, fillcolor=red]
377  fprintf(F, " node [shape=ellipse, width=0.3, height=0.3%s]\n", NodeLabels?"":", label=\"\"");
378  // node colors
379  //for (int i = 0; i < NIdColorH.Len(); i++) {
380  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
381  if (NIdColorH.IsKey(NI.GetId())) {
382  fprintf(F, " %d [style=filled, fillcolor=\"%s\"];\n", NI.GetId(), NIdColorH.GetDat(NI.GetId()).CStr()); }
383  else {
384  fprintf(F, " %d ;\n", NI.GetId());
385  }
386  }
387  // edges
388  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
389  if (NI.GetOutDeg()==0 && NI.GetInDeg()==0 && !NIdColorH.IsKey(NI.GetId())) {
390  fprintf(F, "%d;\n", NI.GetId()); }
391  else {
392  for (int e = 0; e < NI.GetOutDeg(); e++) {
393  if (! IsDir && NI.GetId() > NI.GetOutNId(e)) { continue; }
394  fprintf(F, " %d %s %d;\n", NI.GetId(), IsDir?"->":"--", NI.GetOutNId(e));
395  }
396  }
397  }
398  if (! Desc.Empty()) {
399  fprintf(F, " label = \"\\n%s\\n\";", Desc.CStr());
400  fprintf(F, " fontsize=24;\n");
401  }
402  fprintf(F, "}\n");
403  fclose(F);
404 }
const TDat & GetDat(const TKey &Key) const
Definition: hash.h:220
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
bool Empty() const
Definition: dt.h:488
char * CStr()
Definition: dt.h:476
bool IsKey(const TKey &Key) const
Definition: hash.h:216
template<class PGraph >
void TSnap::SaveGViz ( const PGraph &  Graph,
const TStr OutFNm,
const TStr Desc,
const TIntStrH NIdLabelH 
)

Save a graph in GraphVizp .DOT format.

Save a graph in GraphVizp .DOT format.

Parameters
NIdLabelHMaps node ids to node string labels.

Definition at line 407 of file gio.h.

407  {
408  const bool IsDir = Graph->HasFlag(gfDirected);
409  FILE *F = fopen(OutFNm.CStr(), "wt");
410  if (! Desc.Empty()) fprintf(F, "/*****\n%s\n*****/\n\n", Desc.CStr());
411  if (IsDir) { fprintf(F, "digraph G {\n"); } else { fprintf(F, "graph G {\n"); }
412  fprintf(F, " graph [splines=true overlap=false]\n"); //size=\"12,10\" ratio=fill
413  fprintf(F, " node [shape=ellipse, width=0.3, height=0.3]\n");
414  // node colors
415  //for (int i = 0; i < NodeLabelH.Len(); i++) {
416  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
417  fprintf(F, " %d [label=\"%s\"];\n", NI.GetId(), NIdLabelH.GetDat(NI.GetId()).CStr());
418 }
419  // edges
420  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
421  if (NI.GetOutDeg()==0 && NI.GetInDeg()==0 && ! NIdLabelH.IsKey(NI.GetId())) {
422  fprintf(F, "%d;\n", NI.GetId()); }
423  else {
424  for (int e = 0; e < NI.GetOutDeg(); e++) {
425  if (! IsDir && NI.GetId() > NI.GetOutNId(e)) { continue; }
426  fprintf(F, " %d %s %d;\n", NI.GetId(), IsDir?"->":"--", NI.GetOutNId(e));
427  }
428  }
429  }
430  if (! Desc.Empty()) {
431  fprintf(F, " label = \"\\n%s\\n\";", Desc.CStr());
432  fprintf(F, " fontsize=24;\n");
433  }
434  fprintf(F, "}\n");
435  fclose(F);
436 }
const TDat & GetDat(const TKey &Key) const
Definition: hash.h:220
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
bool Empty() const
Definition: dt.h:488
char * CStr()
Definition: dt.h:476
bool IsKey(const TKey &Key) const
Definition: hash.h:216
template<class PGraph >
void TSnap::SaveMatlabSparseMtx ( const PGraph &  Graph,
const TStr OutFNm 
)

Saves a graph in a MATLAB sparse matrix format.

Each line contains a tuple of 3 values: <source node="" id>=""><tab><destination node="" id>=""><tab>1.

Definition at line 351 of file gio.h.

351  {
352  FILE *F = fopen(OutFNm.CStr(), "wt");
353  TIntSet NIdSet(Graph->GetNodes()); // so that
354  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
355  NIdSet.AddKey(NI.GetId());
356  }
357  for (typename PGraph::TObj::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) {
358  const int Src = NIdSet.GetKeyId(EI.GetSrcNId())+1;
359  const int Dst = NIdSet.GetKeyId(EI.GetDstNId())+1;
360  fprintf(F, "%d\t%d\t1\n", Src, Dst);
361  if (! HasGraphFlag(typename PGraph::TObj, gfDirected) && Src!=Dst) {
362  fprintf(F, "%d\t%d\t1\n", Dst, Src);
363  }
364  }
365  fclose(F);
366 }
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
int AddKey(const TKey &Key)
Definition: shash.h:1248
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
char * CStr()
Definition: dt.h:476
template<class PGraph >
void TSnap::SavePajek ( const PGraph &  Graph,
const TStr OutFNm 
)

Saves a graph in a Pajek .NET format.

Definition at line 242 of file gio.h.

242  {
243  TIntH NIdToIdH(Graph->GetNodes(), true);
244  FILE *F = fopen(OutFNm.CStr(), "wt");
245  fprintf(F, "*Vertices %d\n", Graph->GetNodes());
246  int i = 0;
247  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++, i++) {
248  fprintf(F, "%d \"%d\" ic Red fos 10\n", i+1, NI.GetId()); // ic: internal color, fos: font size
249  NIdToIdH.AddDat(NI.GetId(), i+1);
250  }
251  if (HasGraphFlag(typename PGraph::TObj, gfDirected)) {
252  fprintf(F, "*Arcs %d\n", Graph->GetEdges()); } // arcs are directed, edges are undirected
253  else {
254  fprintf(F, "*Edges %d\n", Graph->GetEdges());
255  }
256  for (typename PGraph::TObj::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) {
257  const int SrcNId = NIdToIdH.GetDat(EI.GetSrcNId());
258  const int DstNId = NIdToIdH.GetDat(EI.GetDstNId());
259  fprintf(F, "%d %d %d c Black\n", SrcNId, DstNId, 1); // width=1
260  }
261  fclose(F);
262 }
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
char * CStr()
Definition: dt.h:476
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
template<class PGraph >
void TSnap::SavePajek ( const PGraph &  Graph,
const TStr OutFNm,
const TIntStrH NIdColorH 
)

Saves a graph in a Pajek .NET format.

NIdColorH maps node ids to node colors. Default node color is Red. See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/pajekman.pdf for a list of supported color names.

Definition at line 267 of file gio.h.

267  {
268  TIntH NIdToIdH(Graph->GetNodes(), true);
269  FILE *F = fopen(OutFNm.CStr(), "wt");
270  fprintf(F, "*Vertices %d\n", Graph->GetNodes());
271  int i = 0;
272  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++, i++) {
273  fprintf(F, "%d \"%d\" ic %s fos 10\n", i+1, NI.GetId(),
274  NIdColorH.IsKey(NI.GetId()) ? NIdColorH.GetDat(NI.GetId()).CStr() : "Red");
275  NIdToIdH.AddDat(NI.GetId(), i+1);
276  }
277  if (HasGraphFlag(typename PGraph::TObj, gfDirected)) {
278  fprintf(F, "*Arcs %d\n", Graph->GetEdges()); } // arcs are directed, edges are undirected
279  else {
280  fprintf(F, "*Edges %d\n", Graph->GetEdges());
281  }
282  for (typename PGraph::TObj::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) {
283  const int SrcNId = NIdToIdH.GetDat(EI.GetSrcNId());
284  const int DstNId = NIdToIdH.GetDat(EI.GetDstNId());
285  fprintf(F, "%d %d %d c Black\n", SrcNId, DstNId, 1);
286  }
287  fclose(F);
288 }
const TDat & GetDat(const TKey &Key) const
Definition: hash.h:220
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
char * CStr()
Definition: dt.h:476
bool IsKey(const TKey &Key) const
Definition: hash.h:216
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
template<class PGraph >
void TSnap::SavePajek ( const PGraph &  Graph,
const TStr OutFNm,
const TIntStrH NIdColorH,
const TIntStrH NIdLabelH 
)

Saves a graph in a Pajek .NET format.

NIdColorH maps node ids to node colors. Default node color is Red. NIdLabelH maps node ids to node string labels. See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/pajekman.pdf for a list of supported color names.

Definition at line 294 of file gio.h.

294  {
295  TIntH NIdToIdH(Graph->GetNodes(), true);
296  FILE *F = fopen(OutFNm.CStr(), "wt");
297  fprintf(F, "*Vertices %d\n", Graph->GetNodes());
298  int i = 0;
299  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++, i++) {
300  fprintf(F, "%d \"%s\" ic %s fos 10\n", i+1,
301  NIdLabelH.IsKey(NI.GetId()) ? NIdLabelH.GetDat(NI.GetId()).CStr() : TStr::Fmt("%d", NI.GetId()).CStr(),
302  NIdColorH.IsKey(NI.GetId()) ? NIdColorH.GetDat(NI.GetId()).CStr() : "Red");
303  NIdToIdH.AddDat(NI.GetId(), i+1);
304  }
305  if (HasGraphFlag(typename PGraph::TObj, gfDirected)) {
306  fprintf(F, "*Arcs %d\n", Graph->GetEdges()); } // arcs are directed, edges are undirected
307  else {
308  fprintf(F, "*Edges %d\n", Graph->GetEdges());
309  }
310  for (typename PGraph::TObj::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) {
311  const int SrcNId = NIdToIdH.GetDat(EI.GetSrcNId());
312  const int DstNId = NIdToIdH.GetDat(EI.GetDstNId());
313  fprintf(F, "%d %d %d c Black\n", SrcNId, DstNId, 1);
314  }
315  fclose(F);
316 }
const TDat & GetDat(const TKey &Key) const
Definition: hash.h:220
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
static TStr Fmt(const char *FmtStr,...)
Definition: dt.cpp:1599
char * CStr()
Definition: dt.h:476
bool IsKey(const TKey &Key) const
Definition: hash.h:216
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
template<class PGraph >
void TSnap::SavePajek ( const PGraph &  Graph,
const TStr OutFNm,
const TIntStrH NIdColorH,
const TIntStrH NIdLabelH,
const TIntStrH EIdColorH 
)

Saves a graph in a Pajek .NET format.

NIdColorH maps node ids to node colors. Default node color is Red. NIdLabelH maps node ids to node string labels. EIdColorH maps edge ids to node colors. Default edge color is Black. See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/pajekman.pdf for a list of supported color names.

Definition at line 323 of file gio.h.

323  {
324  CAssert(HasGraphFlag(typename PGraph::TObj, gfMultiGraph)); // network needs to have edge ids
325  TIntH NIdToIdH(Graph->GetNodes(), true);
326  FILE *F = fopen(OutFNm.CStr(), "wt");
327  fprintf(F, "*Vertices %d\n", Graph->GetNodes());
328  int i = 0;
329  for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++, i++) {
330  fprintf(F, "%d \"%s\" ic %s fos 10\n", i+1,
331  NIdLabelH.IsKey(NI.GetId()) ? NIdLabelH.GetDat(NI.GetId()).CStr() : TStr::Fmt("%d", NI.GetId()).CStr(),
332  NIdColorH.IsKey(NI.GetId()) ? NIdColorH.GetDat(NI.GetId()).CStr() : "Red");
333  NIdToIdH.AddDat(NI.GetId(), i+1);
334  }
335  if (HasGraphFlag(typename PGraph::TObj, gfDirected)) {
336  fprintf(F, "*Arcs %d\n", Graph->GetEdges()); } // arcs are directed, edges are undirected
337  else {
338  fprintf(F, "*Edges %d\n", Graph->GetEdges());
339  }
340  for (typename PGraph::TObj::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) {
341  const int SrcNId = NIdToIdH.GetDat(EI.GetSrcNId());
342  const int DstNId = NIdToIdH.GetDat(EI.GetDstNId());
343  fprintf(F, "%d %d 1 c %s\n", SrcNId, DstNId,
344  EIdColorH.IsKey(EI.GetId()) ? EIdColorH.GetDat(EI.GetId()).CStr() : "Black");
345  }
346  fclose(F);
347 }
const TDat & GetDat(const TKey &Key) const
Definition: hash.h:220
have explicit edges (multigraph): TNEGraph, TNodeEdgeNet
Definition: gbase.h:14
#define HasGraphFlag(TGraph, Flag)
For quick testing of the properties of the graph/network object (see TGraphFlag). ...
Definition: gbase.h:38
directed graph (TNGraph, TNEGraph), else graph is undirected TUNGraph
Definition: gbase.h:13
#define CAssert(Cond)
Definition: bd.h:302
static TStr Fmt(const char *FmtStr,...)
Definition: dt.cpp:1599
char * CStr()
Definition: dt.h:476
bool IsKey(const TKey &Key) const
Definition: hash.h:216
TDat & AddDat(const TKey &Key)
Definition: hash.h:196
void TSnap::SetAllInvertSign ( TFltV ValV,
const double &  Val 
)

Definition at line 158 of file gsvd.cpp.

158  {
159  for (int i = 0; i < ValV.Len(); i++) {
160  ValV[i] = -ValV[i];
161  }
162 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
template<class PGraph >
void TSnap::TestAnf ( )

Definition at line 241 of file anf.h.

241  {
242  PGraph Graph = PGraph::TObj::New();
243  //Graph:
244  // 0 2 ----> 3
245  // ^ |
246  // | |
247  // | ^
248  // 1 5 <---- 4
249  for (int v = 0; v < 6; v++) { Graph->AddNode(v); }
250  Graph->AddEdge(2, 3);
251  Graph->AddEdge(3, 4);
252  Graph->AddEdge(4, 5);
253  Graph->AddEdge(5, 2);
254  TFltV AnfV;
255  for (int t = 0; t < 10; t++) {
256  TGraphAnf<PGraph> Anf(Graph, 128, 5, t+1);
257  TIntFltKdV DistToNbrsV;
258  Anf.GetGraphAnf(DistToNbrsV, 5, true);
259  printf("\n--seed: %d---------------------\n", t+1);
260  for (int i = 0; i < DistToNbrsV.Len(); i++) {
261  printf("dist: %d\t hops:%f\n", DistToNbrsV[i].Key(), DistToNbrsV[i].Dat());
262  }
263  AnfV.Add(DistToNbrsV.Last().Dat);
264  }
265  TMom Mom(AnfV);
266  printf("-----------\nAvgAnf: %f StDev: %f\n", Mom.GetMean(), Mom.GetSDev());//*/
267  // const int NApprox = 32;
268  /*printf("\nANF vs. SAMPLE diam test (10 runs of ANF, NApprox=%d):\n", NApprox);
269  //Graph = TGGen<PGraph>::GenGrid(20, 20);
270  Graph = TGAlg::GetMxWcc(TGGen<PGraph>::GenRnd(1000, 10000));
271  TFltV FullAnf, EffAnf;
272  for (int tryn = 0; tryn < 10; tryn++) {
273  FullAnf.Add(GetEffDiam(Graph, false, 1.0, NApprox));
274  EffAnf.Add(GetEffDiam(Graph, false, 0.9, NApprox));
275  }
276  TMom FullMom(FullAnf);
277  TMom AnfMom(EffAnf);
278  printf(" Sample FullDiam: %d\n", TGAlg::GetBfsFullDiam(Graph, 100, false));
279  printf(" Anf FullDiam: %f [%f]\n", FullMom.GetMean(), FullMom.GetSDev());
280  printf(" Sample EffDiam [90%%]: %f\n", TGAlg::GetBfsEffDiam(Graph, 100, false));
281  printf(" Anf EffDiam [90%%]: %f [%f]\n", AnfMom.GetMean(), AnfMom.GetSDev());
282  // epinions
283  printf("\nEpinions graph:\n");
284  { typedef PNGraph PGraph;
285  PGraph G = TGGen<PGraph>::GenEpinions();
286  TIntFltKdV DistToPairsV;
287  GetAnf(G, DistToPairsV, 50, true);
288  for(int i = 0; i < DistToPairsV.Len(); i++) {
289  printf("\t%d\t%f\n", DistToPairsV[i].Key, DistToPairsV[i].Dat); }
290  printf("\nUndir\n");
291  TAnf<PGraph>::GetAnf(G, DistToPairsV, 50, false);
292  for(int j = 0; j < DistToPairsV.Len(); j++) {
293  printf("\t%d\t%f\n", DistToPairsV[j].Key, DistToPairsV[j].Dat); }
294  }//*/
295 }
TSizeTy Len() const
Returns the number of elements in the vector.
Definition: ds.h:535
Definition: xmath.h:129
const TVal & Last() const
Returns a reference to the last element of the vector.
Definition: ds.h:539
TSizeTy Add()
Adds a new element at the end of the vector, after its current last element.
Definition: ds.h:559
Definition: anf.h:33
Vector is a sequence TVal objects representing an array that can change in size.
Definition: ds.h:420