Skip to content

Instantly share code, notes, and snippets.

@ken57
Created June 25, 2016 05:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ken57/92c0d2d9a2254d18ccf17e493e152ec4 to your computer and use it in GitHub Desktop.
Save ken57/92c0d2d9a2254d18ccf17e493e152ec4 to your computer and use it in GitHub Desktop.
Sotera_DGA検証用に作成したスクリプト
import networkx as nx
import json
import community
import sys
from networkx.readwrite import json_graph
def calcQ(input_filename):
js_graph = json.load(open(input_filename, "r"))
graph = nx.Graph(json_graph.node_link_graph(js_graph))
node_communities = {}
for i in graph.nodes():
node_communities[i] = graph.node[i]['group']
return community.modularity(node_communities, graph)
if __name__ == "__main__":
params = sys.argv
if len(params) != 2:
print "usage: python calq_q.py [networkx json format graph file]"
sys.exit()
print "q = " + str(calcQ(params[1]))
import sys
def outputNodes(filename, org_filename):
file = open(filename, "r")
print "{ \n \"nodes\":[ "
nodes = {}
for (i, line) in enumerate(file):
if i != 0:
print ","
line = line.strip()
words = line.split()
nodes[words[0]] = i
sys.stdout.write(" {\"name\":\"" + words[0] + "\",\"group\":" + words[1] + "}")
print "\n ],"
file.close()
org_file = open(org_filename, "r")
print " \"links\":["
for (i, line) in enumerate(org_file):
if i != 0:
print ","
line = line.strip()
words = line.split(",")
sys.stdout.write(" {\"source\":" + str(nodes[words[0]]) + ",\"target\":" + str(nodes[words[1]]) + "}")
print "\n ]\n}"
org_file.close()
if __name__ == "__main__":
params = sys.argv
if len(params) != 3:
print "usage: python convert_to_json.py [outputted file by louvain runnder] [origin file]"
sys.exit()
outputNodes(params[1], params[2]
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import networkx as nx
import json
import matplotlib
import community
from networkx.readwrite import json_graph
def drawGraph(input_filename, output_filename)
js_graph = json.load(open(input_filename, "r"))
graph = nx.Graph(json_graph.node_link_graph(js_graph))
node_labels = {}
for i in graph.nodes():
node_labels[i] = graph.node[i]['name']
node_colors = [graph.node[i]['group'] for i in graph.nodes()]
pos = nx.spring_layout(graph, scale=3.0)
nx.draw_networkx(graph, pos, node_color=node_colors, node_size=100, with_labels=False)
pos_labels = {}
keys = pos.keys()
for key in keys:
x, y = pos[key]
pos_labels[key] = (x, y+0.2)
nx.draw_networkx_labels(graph, labels=node_labels, pos=pos_labels)
plt.savefig(output_filename)
if __name__ == "__main__":
params = sys.argv
if len(params) != 3:
print "usage: python graph_draw.py [networkx json format graph file] [output graph filename]"
sys.exit()
drawGraph(params[1], params[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment