def readFile(self, filename): self.reset() try: parser = GraphMLParser() g = parser.parse(filename) except Exception: box.showerror("Chyba při zpracování vstupního souboru", "Chybný formát souboru.") return nodeMap = {} try: for gnode in g.nodes(): nodeMap[gnode.id] = self.__add_node(int(gnode['x']), int(gnode['y'])) except KeyError: box.showerror("Chyba při zpracování vstupního souboru", "Uzlum chybi udaje o pozici (atributy x a y).") self.reset() return try: for gedge in g.edges(): start = nodeMap[gedge.node1.id] end = nodeMap[gedge.node2.id] isCurve = gedge.node1.id == gedge.node2.id self.__add_edge(start, end, isCurve) self.label.configure(text=os.path.basename(filename)) except KeyError: box.showerror("Chyba při zpracování vstupního souboru", "Soubor obsahuje hrany spojujici neexistujici hrany") self.reset() return self.repaint()
def fromGraph(cls, rs, args): session = Session() file, cpu = args parser = GraphMLParser() g = parser.parse(os.path.join(DATA_FOLDER, file)) nodes = [Node(name=str(n.id), cpu_capacity=cpu) for n in g.nodes()] nodes_from_g = {str(n.id): n for n in g.nodes()} session.add_all(nodes) session.flush() edges = [Edge (node_1=session.query(Node).filter(Node.name == str(e.node1.id)).one(), node_2=session.query(Node).filter(Node.name == str(e.node2.id)).one(), bandwidth=float(e.attributes()["d42"].value), delay=get_delay(nodes_from_g[str(e.node1.id)], nodes_from_g[str(e.node2.id)]) ) for e in g.edges() if "d42" in e.attributes() and isOK(nodes_from_g[str(e.node1.id)], nodes_from_g[str(e.node2.id)]) ] session.add_all(edges) session.flush() # filter out nodes for which we have edges valid_nodes = list(set([e.node_1.name for e in edges] + [e.node_2.name for e in edges])) nodes = list(set([n for n in nodes if str(n.name) in valid_nodes])) session.add_all(nodes) session.flush() session.add_all(edges) session.flush() return cls(edges, nodes)
def leeGraphML(file): ''' Lee un grafo en formato graphML usando la libreria pygraphMl, y lo devuelve como lista con pesos ''' parser = GraphMLParser() g = parser.parse(file) V = [] E = [] for node in g.nodes(): V.append(node['label']) for e in g.edges(): source = e.node1 target = e.node2 try: peso = float(e['d1']) except: peso = None E.append((source['label'], target['label'], peso)) return (V, E)
def leeGraphML(file): ''' Lee un grafo en formato graphML usando la libreria pygraphMl, y lo devuelve como lista con pesos ''' parser = GraphMLParser() g = parser.parse(file) V = [] E = [] for node in g.nodes(): V.append(node['label']) for e in g.edges(): source = e.node1 target = e.node2 try: peso = float(e['d1']) except: peso = None E.append((source['label'], target['label'], peso)) return (V,E)
def readGraphMLFile(graphMLFile): graphMLParser = GraphMLParser() try: graphNet = graphMLParser.parse(graphMLFile) except xml.parsers.expat.ExpatError as e: print("%s is not a GraphML file\n" % graphMLFile) print("Error message is %s" % str(e)) sys.exit(-1) return graphNet
def from_graphml(fname: str) -> Graph: parser = GraphMLParser() gml = parser.parse(fname) g = Graph() for node in gml._nodes: g.adj[Node(id=node.id)] for edge in gml._edges: g.adj[Node(id=edge.node1.id)].append(Node(id=edge.node2.id)) return g
def _graphml2nx(fname): g=nx.DiGraph() def _attrdict(node): attrs=node.attributes() return {key:attrs[key].value for key in attrs if key not in attr_blacklist} parser=GraphMLParser() imported_graph=parser.parse(fname) edges=[(edge.node1.id, edge.node2.id) for edge in imported_graph.edges()] nodes=[(node.id, _attrdict(node)) for node in imported_graph.nodes()] g.add_edges_from(edges) g.add_nodes_from(nodes) assert(nx.is_tree(g)) assert(nx.is_directed(g)) return g
def test_graph_io(): g = create_graph() fname = tempfile.mktemp() parser = GraphMLParser() parser.write(g, fname) with open(fname) as f: print(f.read()) parser = GraphMLParser() g = parser.parse(fname) assert len(g.nodes()) == 5 assert len(g.edges()) == 4
from pygraphml import Graph from pygraphml import GraphMLParser # data sets are from http://www.graphdrawing.org/data.html parser = GraphMLParser() g = parser.parse('./random-dag/g.400.12.graphml') with open('example.lgf', 'w') as fp: fp.write('@nodes\nlabel\n') for n in g.nodes(): fp.write(n['label'][1:] + '\n') fp.write('@arcs\n\t\tlabel\n') counter = 0 for n in g.nodes(): for nn in g.children(n): fp.write(n['label'][1:] + '\t' + nn['label'][1:] + '\t' + str(counter) + '\n') counter += 1 fp.write('@end\n')
'Mehadia': 241, 'Neamt': 234, 'Oradea': 380, 'Pitesti': 100, 'Rimnicu Vilcea': 193, 'Sibiu': 253, 'Timisoara': 329, 'Urziceni': 80, 'Vaslui': 199, 'Zerind': 374 } def romania_heuristic(problem, node): return romania_sld_table[ node['label'] ] romania_graph = parser.parse("test-graphs/romania.graphml") romania_start_node = "Arad" romania_problem = Problem(romania_graph, romania_start_node, romania_goal_test) romania_sln = Informed.a_star(romania_problem, romania_heuristic) # romania_sln = Uninformed.ucs(romania_problem) print("A* solution for the Romania problem: \n %s \n" % romania_sln) ####### Radiation problem from the HW1 ####### def radiation_goal_test(node): return node['label'] == '4' # TODO: come up with a good heuristic for this problem
def open_file(file): parser = GraphMLParser() graph = parser.parse(file) #graph.show() return graph
from pygraphml import GraphMLParser import sys reload(sys) sys.setdefaultencoding("latin-1") file = "mln.graphml" parser = GraphMLParser() g = parser.parse(file) friends = [] friends_with_no_count = [] nodes = g.nodes() count = 0 for node in nodes: uid = node['uid'] friend_count = node.attr.get('friend_count', None) if friend_count is not None: friends.append(int(friend_count.value)) else: friends_with_no_count.append(node['Label']) count += 1 friends.append(len(friends)) facebook = open("facebook_friends_count.csv", "w") facebook.write("NUM,COUNT\n") num=1
ALSlm = [] allpms = [] alllms = [] #alllsPn = [] #lllsPm = [] #allpmlengths = [] #allpmdiverse = [] #alllsPnOnPm = [] #alltermWithoutConst = [] ginfos = ["nodes", "paths", "edges"] #alllinks = [] #get the graph parser = GraphMLParser() gname = "bridge2" #"Bics"#"BeyondTheNetwork"#"Cogentco"#"bridge2"#"BeyondTheNetwork"#"Getnet" g = parser.parse("./archive/{}.graphml".format(gname)) """ #pmlengths = ["top 1 traversal", "avg"] gname="AS20965"#"AS8717"#"AS20965"#"AS8717" g = ipM.loadgraph("./MatlabData/CAIDA_{}.mat".format(gname)) """ expinfo["init"] = init expinfo["t"] = t expinfo["tmax"] = tmax expinfo["numberMonitors"] = numberMonitors expinfo["loops"] = loops expinfo["cond"] = cond #expinfo["numberPathsBtw2M"]=numberPathsBtw2M expinfo["gname"] = gname expinfo["budgets"] = budgets expinfo["# of nodes with {} degree".format(degreeLimit)] = paH.getnNodes(
from pygraphml import Graph from pygraphml import GraphMLParser parser = GraphMLParser() g = parser.parse( 'rendered_55days_inconsistency_graph_with_AggregationAndLabel.graphml') nodes = g.BFS() for node in nodes: node['r'] = node['r'] node['g'] = node['g'] node['b'] = node['b'] parser.write(g, "myGraph.graphml")
from pygraphml import GraphMLParser from lxml import etree if (__name__ == "__main__"): gp = GraphMLParser() g = gp.parse("weather.graphml") node0 = g.get_node("in the middle", "NodeLabel") group = node0.container_node[0] g.set_root(node0) nodes = g.BFS(direction="contained_nodes") for node in nodes: print(node.attr.get("NodeLabel")) node1 = g.get_node("n0", "id") test = etree.tostring(g.xml, encoding=str) gp.write(g)
from pygraphml import Graph from pygraphml import GraphMLParser import numpy import sys reload(sys) sys.setdefaultencoding('utf-8') parser=GraphMLParser() g=parser.parse("mln.graphml") #g.show() datafile=open("facebook.data","w") dropfile=open("facebook_dropped.data","w") nodes = g.nodes() friendCounts=[] for node in nodes: try: count=node['friend_count'] friendCounts.append(int(count)) except Exception, e: dropfile.write(str(node)+"\n") friendCounts.append(len(nodes)) friendCounts=sorted(friendCounts) datafile.write("Friend_count\t"+str(len(nodes))+"\n") datafile.write("std\t"+str(numpy.std(friendCounts))+"\n") datafile.write("mean\t"+str(numpy.mean(friendCounts))+"\n") datafile.write("median\t"+str(numpy.median(friendCounts))+"\n") for fcount in friendCounts: datafile.write(str(fcount)+"\n") datafile.close() dropfile.close()
def read_graphml(filename, color_map=[]): parser = GraphMLParser() g = parser.parse(filename) g.set_root('n0') print dir(g) id = '%s_%s'%(filename.split('.')[0],filename.split('.')[1]) net = Network(id=id) net.notes = "NeuroMLlite conversion of %s from https://www.neurodata.io/project/connectomes/"%filename #net.parameters = {} dummy_cell = Cell(id='testcell', pynn_cell='IF_cond_alpha') dummy_cell.parameters = { "tau_refrac":5, "i_offset":0 } net.cells.append(dummy_cell) net.synapses.append(Synapse(id='ampa', pynn_receptor_type='excitatory', pynn_synapse_type='cond_alpha', parameters={'e_rev':0, 'tau_syn':2})) for node in g.nodes(): info = '' for a in node.attributes(): info+=node.attr[a].value+'; ' if len(info)>2: info = info[:-4] color = '%s %s %s'%(random.random(),random.random(),random.random()) \ if not info in color_map else color_map[info] print('> Node: %s (%s), color: %s'%(node.id, info, color)) p0 = Population(id=node.id, size=1, component=dummy_cell.id, properties={'color':color}) net.populations.append(p0) for edge in g.edges(): #print dir(edge) #print edge.attributes() src = edge.node1.id tgt = edge.node2.id weight = float(str(edge.attr['e_weight'].value)) if 'e_weight' in edge.attr else 1 #print('>> Edge from %s -> %s, weight %s'%(src, tgt, weight)) net.projections.append(Projection(id='proj_%s_%s'%(src,tgt), presynaptic=src, postsynaptic=tgt, synapse='ampa', weight=weight, random_connectivity=RandomConnectivity(probability=1))) #g.show() #print(net) #print(net.to_json()) new_file = net.to_json_file('%s.json'%net.id) duration=1000 dt = 0.1 sim = Simulation(id='Sim%s'%net.id, network=new_file, duration=duration, dt=dt, recordRates={'all':'*'}) check_to_generate_or_run(sys.argv, sim)