TryCalculateClustersSnap
(
IGraph oGraph,
SnapGraphMetrics eSnapGraphMetric,
BackgroundWorker oBackgroundWorker,
out ICollection<Community> oGraphMetrics
)
{
Debug.Assert(oGraph != null);
AssertValid();
LinkedList<Community> oCommunities = new LinkedList<Community>();
oGraphMetrics = oCommunities;
if ( !ReportProgressAndCheckCancellationPending(
1, 3, oBackgroundWorker) )
{
return (false);
}
// Make it easy to find the graph's vertices by vertex ID. The key is
// a vertex ID and the value is the corresponding vertex object.
IVertexCollection oVertices = oGraph.Vertices;
Dictionary<Int32, IVertex> oVertexIDDictionary =
new Dictionary<Int32, IVertex>(oVertices.Count);
foreach (IVertex oVertex in oVertices)
{
oVertexIDDictionary.Add(oVertex.ID, oVertex);
}
// Tell the SNAP graph library to calculate the clusters.
String sOutputFilePath = CalculateSnapGraphMetrics(oGraph,
eSnapGraphMetric);
if ( !ReportProgressAndCheckCancellationPending(
2, 3, oBackgroundWorker) )
{
return (false);
}
// The output file for cluster metrics has a header line followed by
// one line for each vertex that identifies which cluster the vertex is
// in. The vertices are sorted by cluster.
using ( StreamReader oStreamReader = new StreamReader(
sOutputFilePath) )
{
String sLine = oStreamReader.ReadLine();
Debug.Assert(sLine == "Cluster ID\tVertex ID");
Int32 iLastClusterID = -1;
Community oCommunity = null;
while (oStreamReader.Peek() >= 0)
{
sLine = oStreamReader.ReadLine();
String [] asFields = sLine.Split('\t');
Debug.Assert(asFields.Length == 2);
Int32 iClusterID = ParseSnapInt32GraphMetricValue(asFields, 0);
Int32 iVertexID = ParseSnapInt32GraphMetricValue(asFields, 1);
if (iClusterID != iLastClusterID)
{
oCommunity = new Community();
oCommunity.ID = iClusterID;
oCommunities.AddLast(oCommunity);
iLastClusterID = iClusterID;
}
Debug.Assert(oCommunity != null);
oCommunity.Vertices.Add( oVertexIDDictionary[iVertexID] );
}
}
File.Delete(sOutputFilePath);
return (true);
}