Commit fc579fa2 authored by leoborn's avatar leoborn
Browse files

Added graph stats script

parent 090e8357
Loading
Loading
Loading
Loading

src/graph_stats.py

0 → 100644
+119 −0
Original line number Diff line number Diff line
import argparse
import json
import collections
import numpy as np
import networkx as nx

parser = argparse.ArgumentParser(description="Analyze a given file.")
parser.add_argument("-general", help="Show some general info on the graph", action="store_true")
parser.add_argument("-top-nodes", type=int, metavar="N", help="Show N top nodes according to degree")
parser.add_argument("-detail", type=str, choices=["defendant","victim","participant","verdict","offence","punishment","description"], help="Show details on selected category over all trials")
parser.add_argument("file", help="Path to the graph file to analyze")
args = parser.parse_args()

inputfile = args.file
print("Processing", inputfile)
with open(inputfile) as f:
	data = json.load(f)

nodes = data["nodes"]
edges = data["links"]

G = nx.MultiDiGraph()

for edge in edges:
	source = edge["source"]
	target = edge["target"]
	G.add_edge(source, target)

if args.general:
	print("\nNumber of nodes:", len(nodes))
	print("Number of edges:", len(edges))
	print("Number of trials:", len([x for x in nodes if x['label'] == "Trial"]))

	output_dict = [x for x in nodes if 'category' in x['nodeobj'] and x['nodeobj']['category'] == 'DUMMYCAT']
	print("\nNodes with DUMMYCAT:", output_dict)

	newdict = {}
	l = [value["source"] for value in edges]
	newdict["source"] = dict(collections.Counter(l))

	l = [value["target"] for value in edges]
	newdict["target"] = dict(collections.Counter(l))

	allindegrees = []
	alloutdegrees = []
	degreedict = {}
	for key, value in newdict.items():
		if key == 'source':
			for nkey, nvalue in value.items():
				alloutdegrees.append(nvalue)
				degreedict[nkey] = nvalue
		if key == 'target':
			for nkey, nvalue in value.items():
				allindegrees.append(nvalue)
				if nkey in degreedict:
					previousval = degreedict[nkey]
					degreedict[nkey] = nvalue + previousval
				else:
					degreedict[nkey] = nvalue
		
	alldegrees = []
	for key, value in degreedict.items():
		alldegrees.append(value)

	print("Average indegree:", np.mean(allindegrees))
	print("Maximum indegree:", np.max(allindegrees))
	print("Average outdegree:", np.mean(alloutdegrees))
	print("Maximum outdegree:", np.max(alloutdegrees))
	print("Average degree:", np.mean(alldegrees))
	print("Maximum degree:", np.max(alldegrees))

if args.top_nodes:
	idtonode = {}
	for el in nodes:
		idtonode[el["id"]] = el

	print("\nTop " + str(args.top_nodes) + " nodes sorted by degree:")
	for el in sorted(G.degree, key=lambda x: x[1], reverse=True)[:args.top_nodes]:
		node_id = el[0]
		print("Node:", idtonode[node_id])
		print("Degree:", el[1])

if args.detail:
	trial_ids = [x['id'] for x in nodes if x['label'] == "Trial"]
	trial_to_count = {}
	total_count = 0
	if args.detail == "description":
		node_type = "offence-description"
	else:
		node_type = args.detail
		
	for trial in trial_ids:
		alledges = [e for e in edges if (e['source'] == trial or e['target'] == trial)]
		for edge in alledges:
			if "with-"+node_type == edge['edge_class']:
				total_count+=1
				if trial in trial_to_count:
					trial_to_count[trial] += 1
				else:
					trial_to_count[trial] = 1
	average = np.mean(list(trial_to_count.values()))
	print("\nTotal number of " + args.detail + "s:", total_count)
	
	node_count = 0
	category_to_count = {}
	for node in nodes:
		if  node['label'].lower() == args.detail:
			node_count += 1
			if 'category' in node['nodeobj']:
				category = node['label'] + '-' + node['nodeobj']['category']
				id = node['id']
				count = len([e for e in edges if (e['source'] == id or e['target'] == id)])
				category_to_count[category] = count
			
	print("Number of distinct " + args.detail + " nodes:", node_count)
	for k in category_to_count.keys():
		print(k + ": " + str(category_to_count[k]))
		
	print("\nAverage number of " + args.detail + "s per trial:", average)
 No newline at end of file