Esempio n. 1
0
def sampleNodesFromGraph(inputGraph, proportionToKeep): 
        # 0.9 ... keep 90% of the nodes, remove the rest along with incident edges

        filename = inputGraph+'_sampled_'+str(proportionToKeep)
        if os.path.isfile(filename):
                 G = nx.read_dot(filename)
                 print "Cached %s loaded." % filename
                 return G
                 
        Gorig = nx.read_dot(inputGraph)
        G = nx.read_dot(inputGraph)
        #G = nx.Graph(Gorig)
        print "%s loaded." % inputGraph

        nodes = Gorig.nodes()
        random.shuffle(nodes)
        N = len(nodes)
        # keep k nodes
        k = int(round(N*(1-proportionToKeep)))
        
        for n in range(0,k):
                G.remove_node(nodes[n])

        nx.write_dot(G, filename)
        print "\tGraph sampled. Original graph had %d nodes, sampled graph has %d nodes." % (len(Gorig.nodes()), len(G.nodes())) 

        return G
Esempio n. 2
0
def sampleNodesFromGraph(inputGraph, proportionToKeep):
    # 0.9 ... keep 90% of the nodes, remove the rest along with incident edges

    filename = inputGraph + '_sampled_' + str(proportionToKeep)
    if os.path.isfile(filename):
        G = nx.read_dot(filename)
        print "Cached %s loaded." % filename
        return G

    Gorig = nx.read_dot(inputGraph)
    G = nx.read_dot(inputGraph)
    #G = nx.Graph(Gorig)
    print "%s loaded." % inputGraph

    nodes = Gorig.nodes()
    random.shuffle(nodes)
    N = len(nodes)
    # keep k nodes
    k = int(round(N * (1 - proportionToKeep)))

    for n in range(0, k):
        G.remove_node(nodes[n])

    nx.write_dot(G, filename)
    print "\tGraph sampled. Original graph had %d nodes, sampled graph has %d nodes." % (
        len(Gorig.nodes()), len(G.nodes()))

    return G
Esempio n. 3
0
 def __init__(self, physical_net_f, virtual_net_f, node_mappings_file):
     self.phy_g = nx.read_dot(physical_net_f)
     self.virt_g = nx.read_dot(virtual_net_f)
     self.virtual_phy_map = self.get_mapping_dict_from_file(node_mappings_file)
     self.virtual_phy_ip_map = {}
     self.virtual_node_index_dict = {}
     for vh,ph in self.virtual_phy_map.iteritems():
         str_ip = self.phy_g.node[ph]['ip']
         str_ip = str.replace(str_ip, "\"", "")
         self.virtual_phy_ip_map[vh] = str_ip
Esempio n. 4
0
def main(argv):
    
    file1 = argv[1]
    file2 = argv[2]
    file3 = argv[3]

    network = nx.read_dot(file1) 
    traffic = nx.read_dot(file3)
    
    file2 = open(file2,'r')
    rawNodeCaps = file2.readlines()
    nodeCaps={}
    for line in rawNodeCaps:
        splitLine = line.split()
        nodeCaps[str(splitLine[0])]= int(splitLine[1])

    #while (network.number_of_edges())>(int(network.number_of_nodes())/2):

    for node1 in network:
	for node2 in network:
	    if node1 != node2:
	    
		if(node1 in network.neighbors(node2) and (node2 in network.neighbors(node1))): 
		
		    print "~~~~~~~~~~~~~~~~~~~"             #this is how to reference edge weights
                                                                                        # |
                                                                                        # |
                                                                                        # V
		    print(node1+"->"+node2+" weight: " + str(network[node1][node2][0]['label']))    
		
		elif (node2 in network.neighbors(node1)and (node1 in network.neighbors(node2))):
	
		    print "~~~~~~~~~~~~~~~~~~~"
		    print(node2+"->"+node1+" weight: " + str(network[node2][node1][0]['label']))

		else:
		    n = network.number_of_edges(node1, node2)
		    #print(n)              
		     
		
	    #do anti-parallel edge removal by adding intermediate node
    
    #print(network.nodes())
    print("~~~~~~~~~~~~~~~~~~~")
    #print(network.edges())

    #print(network)
    #print(nodeCaps)
    #print(traffic)

    
    file2.close()
Esempio n. 5
0
    def fromStatement(self,statement,fname):
        """ Populates the BuchiAutomaton's fields to construct an automaton
        that is used to check a given LTL formula.  Wraps to lbt.
        Inputs:
            statement: A string using ltl2ba syntax that gives the 
                LTL formula to be checked
            fname: file name used to save intermediate data
        """
        ###Begin wrapping to lbt####
#        txtfile= fname+ '.txt'
#        subprocess.call(['touch',txtfile])
#        fout = open(txtfile,'w');fout.write(statement);fout.close()
#        subprocess.call(paths.PATH_TO_IN2PRE+"in2preLTL " + txtfile + " " + txtfile,shell=True)
#        subprocess.call("lbt < "+ txtfile+" > automaton.txt",shell=True) 
#        subprocess.call("lbt2dot < automaton.txt > automaton.dot",shell=True)
        txtfile= fname+ '.txt'
        fout = open(txtfile,'w');fout.write(statement);fout.close()
        subprocess.call("./ltl2dot_new.sh "+fname,shell=True)
        #### End wrapping to lbt ###
        self.graph = nx.read_dot(fname+".dot")
        for node in self.graph.nodes():
            self.states.add(node)
            label = self.graph.node[node]['label']
            if self.graph.node[node]['shape'] == "doublecircle":
            #if 'n' in label:
            #if peripheries:
                self.acceptingStates.add(node)
        for edge in self.graph.edges():
            label = self.graph[edge[0]][edge[1]][0]['label']
            for prop in stripProps(buchiProcess(label)):
                self.inputLanguage.add(prop)
        self.calculateDistanceToacceptingStates()
        self.initialStates.add('0')
        self.currentStates.add('0')
def compose_breakpoint_graph(base_dot, predicted_dot, true_edges):
    base_graph = nx.read_dot(base_dot)
    predicted_edges = nx.read_dot(predicted_dot)
    out_graph = nx.MultiGraph()

    for v1, v2, data in base_graph.edges_iter(data=True):
        color = g2c(data["genome_id"])
        out_graph.add_edge(v1, v2, color=color)
    for v1, v2 in predicted_edges.edges_iter():
        out_graph.add_edge(v1, v2, color="red", style="dashed")
    for (v1, v2, infinite) in true_edges:
        label = "oo" if infinite else ""
        out_graph.add_edge(str(v1), str(v2), color="red",
                           style="bold", label=label)

    return out_graph
Esempio n. 7
0
 def read(self, path='', nx=False):
     if len(path) < 1:
         path = '%s.dot' % self.name
     if nx:
         self._nx = nx.read_dot(path)
     else:
         self._dot = gv.Source.from_file(path)
Esempio n. 8
0
def add_overlap_edges(graph, overlap_dot, contigs_file):
    contigs = get_contig_permutations(contigs_file)
    contig_begins = {}
    contig_ends = {}
    for name, blocks in contigs.items():
        contig_begins[blocks[0]] = "+" + name
        contig_begins[-blocks[-1]] = "-" + name
        contig_ends[-blocks[-1]] = "+" + name
        contig_ends[blocks[0]] = "-" + name

    overlap_graph = nx.read_dot(overlap_dot)

    subgraphs = nx.connected_component_subgraphs(graph)
    for subgr in subgraphs:
        for v1, v2 in combinations(subgr.nodes, 2):
            v1, v2 = int(v1), int(v2)

            if v1 in contig_ends and v2 in contig_begins:
                src = contig_ends[v1]
                dst = contig_begins[v2]
            elif v2 in contig_ends and v1 in contig_begins:
                src = contig_ends[v2]
                dst = contig_begins[v1]
            else:
                continue

            if not (overlap_graph.has_node(src)
                    and overlap_graph.has_node(dst)):
                continue

            if not nx.has_path(overlap_graph, src, dst):
                continue

            if my_has_path(overlap_graph, contigs, src, dst):
                graph.add_edge(str(v1), str(v2), weight=0.1)
def main(argv):

	#Script usage
    	try:
        	opts, args = getopt.getopt(argv,"ha:b:c:",["help", "fileName=", "field=", "type="])
    	except getopt.GetoptError:
        	print 'USAGE: python workflow_graph.py -p <parameter-file>'
        	sys.exit(2)
    	for opt, arg in opts:
        	if opt == '-h':
            		print 'USAGE: python workflow_graph.py -p <parameter-file>'
            		sys.exit()
        	elif opt in ("-a", "--fileName"):
            		fileName = arg
        	elif opt in ("-b", "--field"):
            		field = arg
        	elif opt in ("-c", "--type"):
            		fieldType = arg

	g=nx.DiGraph(nx.read_dot(fileName))
	if fieldType == 'edge':
		aux_init_data = np.ndarray(len(g.edges()), dtype='float')
		indexE = 0
		for e in g.edges():
			aux_init_data[indexE] = g.edge[e[0]][e[1]][field]
			indexE = indexE + 1
	elif fieldType == 'node':
		aux_init_data = np.ndarray(len(g.nodes()), dtype='float')
		for v in g.nodes():	
			aux_init_data[int(v[1:])] = g.node[v][field]
	g.clear()

	np.save(field, aux_init_data)
Esempio n. 10
0
def main():
    args = parse_args(sys.argv)
    graph = nx.read_dot(args.infile)

    droppers = [re.compile(pattern) for pattern in args.drop]
    keepers = [re.compile(pattern) for pattern in args.keep]

    rm_nodes = []
    num_parents = graph.out_degree()
    degree = graph.degree()
    for node in graph.nodes():
        if matches_any(node, droppers) and not matches_any(node, keepers):
            rm_nodes.append(node)
        elif degree[node] == 0:
            rm_nodes.append(node)
        elif num_parents[node] == 0:
            graph.node[node]['shape'] = 'hexagon'
        else:
            pass  # Node will not be changed.

    detours = get_detours(graph, rm_nodes)
    graph.remove_nodes_from(rm_nodes)
    graph.add_edges_from(detours, style='dashed')

    graph.graph = {}  # Clear all graph, edge, and node attributes
    # nx.write_dot(graph) should work,
    # but doesn't, because it calls nx.to_agraph(graph).clear()
    a = nx.to_agraph(graph)
    # print(graph.edge, file=sys.stderr)
    a.write(sys.stdout)
Esempio n. 11
0
	def testDot(self):
		self.assertEqual( self.g.number_of_edges(), 4 )	
		self.assertEqual( self.g.number_of_edges(), 4 )	
		nx.write_dot( self.g, './test.dot' )
		g1 = nx.read_dot( './test.dot' )
		self.assertEqual( g1.number_of_edges(), self.g.number_of_edges() )
		self.assertEqual( g1.number_of_edges(), 4 )
def main(argv):

	#Script usage
    	try:
        	opts, args = getopt.getopt(argv,"ha:b:",["help", "fileName=", "field="])
    	except getopt.GetoptError:
        	print 'USAGE: python workflow_graph.py -p <parameter-file>'
        	sys.exit(2)
    	for opt, arg in opts:
        	if opt == '-h':
            		print 'USAGE: python workflow_graph.py -p <parameter-file>'
            		sys.exit()
        	elif opt in ("-a", "--fileName"):
            		fileName = arg
        	elif opt in ("-b", "--field"):
            		field = arg

	g=nx.DiGraph(nx.read_dot(fileName))
	aux_init_data = [None] * len(g.nodes())
	for v in g.nodes():
		pop = np.ndarray(g.out_degree(v), dtype='float')
		index = 0
		for vn in g.neighbors(v):
			pop[index] = g.node[vn][field]
			index = index + 1
		aux_init_data[int(v[1:])] = pop
	g.clear()

	np.save(field, aux_init_data)
Esempio n. 13
0
def add_overlap_edges(graph, overlap_dot, contigs_file):
    contigs = get_contig_permutations(contigs_file)
    contig_begins = {}
    contig_ends = {}
    for name, blocks in contigs.items():
        contig_begins[blocks[0]] = "+" + name
        contig_begins[-blocks[-1]] = "-" + name
        contig_ends[-blocks[-1]] = "+" + name
        contig_ends[blocks[0]] = "-" + name

    overlap_graph = nx.read_dot(overlap_dot)

    subgraphs = nx.connected_component_subgraphs(graph)
    for subgr in subgraphs:
        for v1, v2 in combinations(subgr.nodes, 2):
            v1, v2 = int(v1), int(v2)

            if v1 in contig_ends and v2 in contig_begins:
                src = contig_ends[v1]
                dst = contig_begins[v2]
            elif v2 in contig_ends and v1 in contig_begins:
                src = contig_ends[v2]
                dst = contig_begins[v1]
            else:
                continue

            if not (overlap_graph.has_node(src) and
                    overlap_graph.has_node(dst)):
                continue

            if not nx.has_path(overlap_graph, src, dst):
                continue

            if my_has_path(overlap_graph, contigs, src, dst):
                graph.add_edge(str(v1), str(v2), weight=0.1)
Esempio n. 14
0
 def __init__(self, parent, data=None, nodes=None, **kwargs):
     """
     :param parent: type of the graph. nx.Graph, nx.DiGraph or nx.MultiGraph
     :param data: see :meth:`to_networkx_graph` for valid types
     """
     self.parent=parent 
     self.idx=None # index is created at first call to add_node
     
     self._map={} #map from original node name to position for AGraph and other graphs were 'pos' is a node attribute
     
     if data:
         if isinstance(data,six.string_types): # suppose data is a filename
             ext=data.split('.')[-1].lower()
             if ext=='dot':
                 data=nx.read_dot(data)
             else:
                 raise(Exception('unknown file format'))
         elif isinstance(data,AGraph):
             if not getattr(data,'has_layout',False):
                 data.layout()
             
         to_networkx_graph(data,self)
     elif nodes:
         for node in nodes:
             self.add_node(node)
         
     self.render_args={}
Esempio n. 15
0
 def __init__(self, path = None):
   """
     Load and convert dot graph.
   """
   self._G = nx.MultiDiGraph()
   if not path is None:
     self._file_path = path
     self._G = nx.read_dot(path)
     self._transform()
Esempio n. 16
0
def get_node_fasta(dot_files):
    for dot_file in dot_files:
        
        g = nx.read_dot(dot_file)
        
        name = g.graph['name']
        
        for n, n_info in g.node.iteritems():
            print ">%s:%s\n%s\n" % (name, n, n_info['label'].split("(")[0]),
Esempio n. 17
0
    def test_graphviz():
        G=nx.complete_graph(5)   # start with K5 in networkx
        A=nx.to_agraph(G)        # convert to a graphviz graph
        X1=nx.from_agraph(A)     # convert back to networkx (but as Graph)
        X2=nx.Graph(A)          # fancy way to do conversion
        G1=nx.Graph(X1)          # now make it a Graph

        A.write('k5.dot')     # write to dot file
        X3=nx.read_dot('k5.dot') # read from dotfile
        pass
Esempio n. 18
0
def compose_breakpoint_graph(base_dot, predicted_dot, true_edges):
    base_graph = nx.read_dot(base_dot)
    predicted_edges = nx.read_dot(predicted_dot)
    out_graph = nx.MultiGraph()

    for v1, v2, data in base_graph.edges_iter(data=True):
        color = g2c(data["genome_id"])
        out_graph.add_edge(v1, v2, color=color)
    for v1, v2 in predicted_edges.edges_iter():
        out_graph.add_edge(v1, v2, color="red", style="dashed")
    for (v1, v2, infinite) in true_edges:
        label = "oo" if infinite else ""
        out_graph.add_edge(str(v1),
                           str(v2),
                           color="red",
                           style="bold",
                           label=label)

    return out_graph
Esempio n. 19
0
def dotStr2Graph(dotstr):
    tfile = os.tmpfile()
    tfile.write(dotstr)
    tfile.seek(0)

    g = nx.read_dot(tfile)

    tfile.close()

    return g
Esempio n. 20
0
    def analyze(self):

        results = []

        for atemplate in self.template_list:

            try:
                the_template = nx.DiGraph(
                    nx.read_dot(os.path.join(self.path1, atemplate)))

            except:
                print "Error Reading Template in /template/%s" % (
                    str(atemplate))
                print Exception
                continue

            for afile in self.file_list:

                try:
                    the_graph_to_test = nx.DiGraph(
                        nx.read_dot(os.path.join(self.path, afile)))

                except:
                    print "Error Reading Graph in /tmp/%ss" % (str(afile))
                    print Exception
                    continue

                if the_graph_to_test != None or the_template != None:

                    # Get a Mapping
                    Mapping = self.SubGraphIsomorphism(the_graph_to_test,
                                                       the_template)

                    # Append to Results
                    if Mapping[0] == True:

                        results.append([
                            atemplate, afile, Mapping,
                            nx.number_of_nodes(the_graph_to_test) -
                            nx.number_of_nodes(the_template)
                        ])

        return results
Esempio n. 21
0
def get_splice_graph(dot_file):
    g = nx.read_dot(dot_file)
    
    for n in g.node:
        g.node[n] = {'label': g.node[n]['label'].split("(")[0]}
    
    for n1, n2 in g.edges():
        g[n1][n2][0] = {}
    
    return g
Esempio n. 22
0
def get_physical_net():
    global physical_net_f, phy_g, pos_phy
    options = {}
    options['title'] = 'Select physical network DOT format file'
    options['filetypes'] = [('dot files', '.dot')]
    options['defaultextension'] = '.dot'
    physical_net_f = tkFileDialog.askopenfilename(**options)
    phy_g = nx.read_dot(physical_net_f)
    pos_phy = nx.graphviz_layout(phy_g, prog='fdp')
    update_color_physical_network(nx.nodes(phy_g), 'r')
    canvas.draw()
Esempio n. 23
0
def get_physical_net():
    global physical_net_f, phy_g, pos_phy
    options = {}
    options['title'] = 'Select physical network DOT format file'
    options['filetypes'] = [('dot files', '.dot')]
    options['defaultextension'] = '.dot'
    physical_net_f = tkFileDialog.askopenfilename(**options)
    phy_g = nx.read_dot(physical_net_f)
    pos_phy=nx.graphviz_layout(phy_g, prog='fdp')
    update_color_physical_network(nx.nodes(phy_g), 'r')
    canvas.draw()
Esempio n. 24
0
def get_experimental_net():
    global virtual_net_f, pos_virt, virt_g
    options = {}
    options['title'] = 'Select virtual network DOT format file'
    options['filetypes'] = [('dot files', '.dot')]
    options['defaultextension'] = '.dot'
    virtual_net_f = tkFileDialog.askopenfilename(**options)
    virt_g = nx.read_dot(virtual_net_f)
    pos_virt=nx.graphviz_layout(virt_g, prog='fdp')
    update_color_virtual_network(nx.nodes(virt_g), 'g')
    canvas.draw()
Esempio n. 25
0
def main(vnet_f):
    virt_g = nx.read_dot(vnet_f)
    nodes_ct = nx.betweenness_centrality(virt_g, normalized=False)
    print(nodes_ct)
    print(str(""))
    G = nx.Graph()
    G.add_path([0, 1, 2, 4])
    G.add_path([0, 5, 3, 4])
    G.add_path([5, 2])
    print([p for p in nx.all_shortest_paths(G, source=0, target=4)])
    print(nx.betweenness_centrality(G, normalized=False))
Esempio n. 26
0
def get_experimental_net():
    global virtual_net_f, pos_virt, virt_g
    options = {}
    options['title'] = 'Select virtual network DOT format file'
    options['filetypes'] = [('dot files', '.dot')]
    options['defaultextension'] = '.dot'
    virtual_net_f = tkFileDialog.askopenfilename(**options)
    virt_g = nx.read_dot(virtual_net_f)
    pos_virt = nx.graphviz_layout(virt_g, prog='fdp')
    update_color_virtual_network(nx.nodes(virt_g), 'g')
    canvas.draw()
    def __init__(self, directory, name, weight_id, aggregate_number):

        self.name               = name
        self.directory          = directory 
        # self.G                  = nx.read_gexf(self.directory+self.name+'.gexf')
        self.G                  = nx.read_dot(self.directory+self.name+'.dot')
        self.weight_id          = weight_id
        self.features           = []
        self.aggregate_number   = aggregate_number
        self.Stats              = StatsHandler(name)
        
        self.standard_text_distribution = ',standard deviation,skewness,kurtosis,hhi,q90%,q80%,q70%,q60%,q50%,q40%,q30%,q20%,q10%,q5%,q1%'
Esempio n. 28
0
 def load_config(self, config, configtype="json"):
     try:
         if configtype == "dot":
             self.graph = read_dot(config)
         elif configtype == "json":
             self.graph = json_graph.node_link_graph(json.load(open(config)))
         elif configtype == "gml":
             self.graph = read_gml(config)
     except Exception,e:
         print "Config read error: {}".format(str(e))
         self.logger.error("Error reading configuration: {}".format(str(e)))
         sys.exit(-1)
Esempio n. 29
0
def pruneGraphKeepDir(inputGraph, MIN_CLIQUE_SIZE=1):
    # remove all cliques of size less than

    G = nx.read_dot(inputGraph)
    print "%s loaded." % inputGraph

    ########################################################
    # find cliques

    cliques = list(nx.find_cliques(G))

    num_cliques = 0
    keep = set()
    NODEtoCOLOR = {}

    print "---------------------------"
    print "Cliques:"
    print "["
    for c in sorted(cliques, cmp=bylength, reverse=True):
        if len(c) < MIN_CLIQUE_SIZE:
            break
        num_cliques += 1
        print "%s," % (c)
        for node in c:
            keep.add(node)
            # colorize nodes
            color = num_cliques / len(c)
            try:
                # blend
                NODEtoCOLOR[node] = (NODEtoCOLOR[node] + float(color)) / 2.0
            except KeyError:
                NODEtoCOLOR[node] = float(color)

    print "]"
    print "\tCliques considered: %s." % (num_cliques)
    print "---------------------------"

    # remove nodes not belonging to larger cliques
    node_size = []
    node_color = []
    #G = nx.read_dot(inputGraph)
    for n in G.nodes():
        if not (n in keep):
            G.remove_node(n)
        else:
            # get node size
            node_size.append(
                float(len(G.predecessors(n)) + len(G.successors(n)) + 0.5))
            node_color.append(NODEtoCOLOR[n])

    print "\tNodes kept: %s (out of %s original)." % (len(keep), len(
        G.nodes()))
    return (G, node_size, node_color)
Esempio n. 30
0
def pruneGraphKeepDir(inputGraph, MIN_CLIQUE_SIZE=1):
        # remove all cliques of size less than 

        G = nx.read_dot(inputGraph)
        print "%s loaded." % inputGraph

        ########################################################
        # find cliques

        cliques = list(nx.find_cliques(G))

        num_cliques = 0
        keep = set()
        NODEtoCOLOR = {}

        print "---------------------------"
        print "Cliques:"
        print "["
        for c in sorted(cliques, cmp=bylength, reverse=True):
                if len(c) < MIN_CLIQUE_SIZE:
                        break
                num_cliques += 1
                print "%s," % (c)
                for node in c:
                        keep.add(node)
                        # colorize nodes
                        color = num_cliques/len(c)
                        try:
                                # blend
                                NODEtoCOLOR[node] = (NODEtoCOLOR[node]+float(color))/2.0
                        except KeyError:
                                NODEtoCOLOR[node] = float(color)

        print "]"
        print "\tCliques considered: %s." % (num_cliques)
        print "---------------------------"

        # remove nodes not belonging to larger cliques
        node_size = []
        node_color = []
        #G = nx.read_dot(inputGraph)
        for n in G.nodes():
                if not(n in keep):
                        G.remove_node(n)
                else:
                        # get node size
                        node_size.append( float(len(G.predecessors(n)) + len(G.successors(n)) + 0.5) )
                        node_color.append( NODEtoCOLOR[n] )

        print "\tNodes kept: %s (out of %s original)." % (len(keep), len(G.nodes()))
        return (G, node_size, node_color)
Esempio n. 31
0
def countStats(old, new, t):
	count = GraphStatistic.objects.get(id='1').data
	edges = GraphStatistic.objects.get(id='2').data
	nodes = GraphStatistic.objects.get(id='3').data
	if new != None:
		G_new=nx.Graph(nx.read_dot("def_dots/" + new))
	if old != None:
		G_old=nx.Graph(nx.read_dot("def_dots/" + old))
	#DELETE
	if old != None and new == None and t == "delete":
		GraphStatistic.objects.filter(id='1').update(data=count-1)
		GraphStatistic.objects.filter(id='2').update(data=edges-G_old.number_of_edges())
		GraphStatistic.objects.filter(id='3').update(data=nodes-G_old.number_of_nodes())
	elif old == None and new != None and t == "new": #NEW
		GraphStatistic.objects.filter(id='1').update(data=count+1)
		GraphStatistic.objects.filter(id='2').update(data=edges+G_new.number_of_edges())
		GraphStatistic.objects.filter(id='3').update(data=nodes+G_new.number_of_nodes())
	elif old != None and new != None and t == "update": #EDIT
		asd = G_new.number_of_nodes()
		asd2 = G_old.number_of_nodes()
		GraphStatistic.objects.filter(id='2').update(data=edges+G_new.number_of_edges()-G_old.number_of_edges())
		GraphStatistic.objects.filter(id='3').update(data=nodes+G_new.number_of_nodes()-G_old.number_of_nodes())
	return 0
Esempio n. 32
0
def __main__():
    g = nx.read_dot('shortened_winter_wheat_56mresolution_upstate_ny_20box_radius_inf.dot')
    cc = nx.connected_component_subgraphs(g)
    for sub_graph in cc:
        if len(sub_graph.nodes()) > 2:
            A = nx.adjacency_matrix(sub_graph)
            eigenvalues = eig(A)[0]
            MFPT_matrix = find_MFPT_matrix(A, sub_graph, 0.005, 1000)
        
            fout = open('Connected Component ' + str(cc.index(sub_graph)) + '.npz', 'w+')
            np.savez(fout, A, eigenvalues, MFPT_matrix)
            fout.close
                 
    return None
def __main__():
    g = nx.read_dot('shortened_winter_wheat_56mresolution_upstate_ny_20box_radius_inf.dot')
    #g = nx.read_dot('ExampleGraph1.dot')
    cc = nx.connected_component_subgraphs(g)
    for sub_graph in cc:
        if len(sub_graph.nodes()) > 2:
            A = nx.adjacency_matrix(sub_graph)
            MFPTs = []
            for node in sub_graph.nodes():
                MFPTs.append(find_analytical_ring_MFPT(node, sub_graph, 0.001, 500))
            fout = open('ring_MFPT_connected_component' + str(cc.index(sub_graph)) + '.npy', 'w+')
            np.save(fout, MFPTs)
            fout.close
                 
    return None
Esempio n. 34
0
def generate_dot_following(users,edges,file_name,encode='utf-8'):
    '''生成Dot文件
    '''
    OUT = file_name.decode('utf-8','ignore')+'_following_'+encode+'.dot'##中文需为unicode编码
    dot = ['"%s" -> "%s" ' % ( e[0],e[1]) for e in edges]
    label=['"%s" [label="%s"];' % (u[0],u[1].encode(encode,'ignore')) for u in users]
    with open(OUT,'wb') as f:
        f.write('strict digraph {\nnode [fontname="FangSong"]\n%s;\n' % (';\n'.join(dot),))
        f.write('\n'.join(label))
        ##输出原帖作者
        f.write('\n}')
        print OUT,'exported'
    DG=nx.DiGraph(nx.read_dot(OUT))
    nx.write_gexf(DG, file_name+"_following_utf-8.gexf")
    print 'generated GEXF complete!'
Esempio n. 35
0
def simplify_trinity_dot(in_file, out_file):
    g = nx.read_dot(in_file)

    node_re = re.compile(r"(\w*)\((\w*)\)\[(\d*)\]")

    for n in g.node:
        label = g.node[n]["label"]
        _, name, length = node_re.search(label).groups()
        new_n = {"label": "name:%s,len:%s" % (name, length)}
        g.node[n] = new_n

    for n1, n2 in g.edges():
        g[n1][n2][0] = {}

    nx.write_dot(g, out_file)
Esempio n. 36
0
def callgraph_parser(dotpath, target_path):
    callgraph = nx.read_dot(dotpath)
    graph = nx.DiGraph()
    for src, dst in callgraph.edges():
        try:
            src_name = str(
                callgraph.node[src]['label'].split('{')[1].split('}')[0])
            dst_name = str(
                callgraph.node[dst]['label'].split('{')[1].split('}')[0])
            graph.add_edge(src_name, dst_name)
        except:
            continue
    #pdb.set_trace()
    pickle.dump(graph, open(target_path, "w"))
    return graph
Esempio n. 37
0
def dashboard_graph(request, graphID = -1):
	if graphID != -1:
		try:
		    graph = Graph.objects.get(id__exact= graphID);
		except Graph.DoesNotExist:
		    graph = None
		
		if(graph):
			with open ("def_dots/" + graph.link, "r") as myfile:
				data=myfile.read().replace('\r\n', '').replace(os.linesep, '').replace('\t', '').replace('digraph finite_state_machine ', '')
			G=nx.Graph(nx.read_dot("def_dots/" + graph.link))
			graph.data = data
			return render(request, 'dashboard/graph.html', {'graph' : graph, 'info' : getInfo(G)})
		else:
			return HttpResponseRedirect("/grafvizualizacio/")
	else:
		return HttpResponseRedirect("/grafvizualizacio/")
Esempio n. 38
0
 def readStatement(self,fname):
     """This is like fromStatement, but it just reads from a .dot file"""
     self.graph = nx.read_dot(fname+".dot")
     for node in self.graph.nodes():
         self.states.add(node)
         label = self.graph.node[node]['label']
         if self.graph.node[node]['shape'] == "doublecircle":
         #if 'n' in label:
         #if peripheries:
             self.acceptingStates.add(node)
     for edge in self.graph.edges():
         label = self.graph[edge[0]][edge[1]][0]['label']
         for prop in stripProps(buchiProcess(label)):
             self.inputLanguage.add(prop)
     self.calculateDistanceToacceptingStates()
     self.initialStates.add('0')
     self.currentStates.add('0')       
Esempio n. 39
0
def main(pname, dname1, dname2, oname):
    # Pull in node positions from my positions CSV
    mypos = importPos(pname)

    # Create a basic figure and subplot
    fig = plt.figure(figsize=(20, 20))
    ax = fig.add_subplot(111)

    # Pull in network structure from dot file
    G1 = nx.read_dot(dname1)

    # Read in factor flags from SAS output
    mycol = importFactor(dname2)

    # Figure out how many factors there are
    numFactors = max(mycol.values())

    # Color pallet based on the jet colors
    jet = plt.cm.jet
    bounds = np.linspace(0, jet.N, numFactors + 1)

    # Color each factor differently on the network
    # Add factor color attribute to each node
    colArray = list()
    for node in G1.nodes():
        try:
            colArray.append(bounds[mycol[node]])
        except:
            colArray.append(0)

    # Draw network colors
    nx.draw_networkx(G1,
                     mypos,
                     node_size=3000,
                     font_size=12,
                     node_color=colArray,
                     sytle='solid',
                     cmap='jet',
                     font_color='w',
                     font_weight='bold')

    # Create Legend and Plot
    p, labels = buildLegend(numFactors, jet, bounds)
    plt.legend(p, labels)
    plt.axis('off')
    plt.savefig(oname)
Esempio n. 40
0
def to_c2_(dot, c2, key):
    """
    parse a dot and save a WeightedNetwork in a c2 file with key `key`

    Parameters:
       dot: path to dot (ex /home/..../graph.dot)
       c2: path in which save c2 (ex. /home/.../graph.c2)
       key: key of dictionary in c2 that identify the network
       (ex. {'network':'Advogato','date':'2000-01-01'} for Advogato-like network
        and {'network':'Wiki','lang':'it','date':'2000-01-01'} for wiki network)
    """

    w = read_dot(dot)

    nodes, edges = trustlet.helpers.toPynetwork(w)

    return trustlet.helpers.save(key, (nodes, edges), c2)
Esempio n. 41
0
def readDigraph(file, format, force_dag=False, multi=False):
    """Read a directed graph from file

    Arguments:
    - `file`: file object
    - `format`: file format
    - `force_dag`: enforces whether graph must be acyclic
    - `multi`:     multiple edge allowed

    Return: a networkx.DiGraph / networkx.MultiDiGraph object.
    """
    if format not in _graphformats['digraph']:
        raise ValueError("Invalid format for directed graph")

    if multi:
        grtype = networkx.MultiDiGraph
    else:
        grtype = networkx.DiGraph

    if format == 'dot':

        D = grtype(networkx.read_dot(file))
        #D=grtype(pygraphviz.AGraph(file.read()).edges())

    elif format == 'gml':

        D = grtype(networkx.read_gml(file))

    elif format == 'kth':

        D = _read_graph_kth_format(file, grtype)

    elif format == 'dimacs':

        D = _read_graph_dimacs_format(file, grtype)

    else:
        raise RuntimeError(
            "Internal error, format {} not implemented".format(format))

    if force_dag and not networkx.algorithms.is_directed_acyclic_graph(D):
        raise ValueError("Graph must be acyclic".format(format))

    return D
Esempio n. 42
0
def get_repost_edges(post_id, edges=[], reposts=[]):
    '''获得转发路径,生成Dot文件,CSV及GEXF文件
    '''
    total_number = get_repost_timeline(id=post_id, count=200)['total_number']
    ##print 'Total Number:',total_number
    ##flag参数有问题,翻页获得所有转发,有可能缺失
    page_reposts = get_repost_timeline(id=post_id, count=200)['reposts']
    reposts += page_reposts
    page_number = int(math.ceil(total_number / 200))
    ##print 'Total Page Number:',page_number
    for i in range(1, page_number):
        ##print 'page_number:',i
        reposts += get_repost_timeline(id=post_id, count=200,
                                       page=i + 1)['reposts']
    for repost in reposts:
        edge = dict(
            weibo_mid=repost['id'],
            weibo_url='http://api.t.sina.com.cn/' + str(repost['user']['id']) +
            '/statuses/' + str(repost['id']),
            original_mid=repost['retweeted_status']['id'],
            pid=repost.get('pid', repost['retweeted_status']['id']),
            original_poster_id=repost['retweeted_status']['user']['id'],
            original_poster=repost['retweeted_status']['user']
            ['screen_name'].encode('utf-8', 'ignore'),
            original_weibo_url='http://api.t.sina.com.cn/' +
            str(repost['retweeted_status']['user']['id']) + '/statuses/' +
            str(repost['retweeted_status']['id']),
            ##original_content=repost['retweeted_status']['text'].encode('utf-8','ignore'),
            poster=repost['user']['screen_name'].encode('utf-8', 'ignore'),
            poster_id=repost['user']['id'],
            content=repost['text'].encode('utf-8', 'ignore'),
            created_at=repost['created_at'],
            repost=repost['reposts_count'],
            comment=repost['comments_count'])
        edges.append(edge)
    DataFrame(edges).to_csv(str(post_id) + '_edges_utf8.csv', index=False)
    print '当前路径为:' + os.getcwd()
    print 'edges获取完毕'
    generate_dot(str(post_id), edges)
    DG = nx.DiGraph(nx.read_dot(str(post_id) + "_utf8.dot"))
    nx.write_gexf(DG, str(post_id) + ".gexf")
    print 'generated GEXF complete!'
    return edges
Esempio n. 43
0
    def loadProgramGraph(self):
        temp = nx.read_dot(self.fileName)

        if temp is None:
            print ("Failed to load program graph: " + self.fileName)

        #Because the default graph is multigraph and we want a digraph
        #convert to digraph
        programGraph = nx.DiGraph(temp)

        #Add source, destination data to edges so that generating json becomes easy, if you don't do this,
        #then generating JSON representation of the graph becomes a problem
        counter = 1
        for edge in programGraph.edges_iter(data=True):
            edge[2]["id"] = str(counter)
            edge[2]["source"] = edge[0]
            edge[2]["target"] = edge[1]

        return programGraph
def __main__():
    g = nx.read_dot(
        'shortened_winter_wheat_56mresolution_upstate_ny_20box_radius_inf.dot')
    #g = nx.read_dot('ExampleGraph1.dot')
    cc = nx.connected_component_subgraphs(g)
    for sub_graph in cc:
        if len(sub_graph.nodes()) > 2:
            A = nx.adjacency_matrix(sub_graph)
            MFPTs = []
            for node in sub_graph.nodes():
                MFPTs.append(
                    find_analytical_ring_MFPT(node, sub_graph, 0.001, 500))
            fout = open(
                'ring_MFPT_connected_component' + str(cc.index(sub_graph)) +
                '.npy', 'w+')
            np.save(fout, MFPTs)
            fout.close

    return None
Esempio n. 45
0
    def read_dot(cls, path):
        """
        Reads dot file and returns new cls object, where cls can be Graph,
        Dag, or BayesNet.

        Parameters
        ----------
        path : str
            eg. for Windows, you can use an absolute path like
            'C:/Documents and Settings/ROBERT/Desktop/tempo.dot' or a
            relative one like '../examples_cbnets/tempo.dot'

        Returns
        -------
        Graph

        """
        nx_graph = nx.read_dot(path)
        return cls.new_from_nx_graph(nx_graph)
Esempio n. 46
0
def main(*args):
    if len(args) != 3:
        print 'Usage: {} <input file> <output file>'.format(args[0])
        return 2

    try:
        NFA = nx.read_dot(args[1])
    except IOError:
        print '{}: file does not exist or is not readable.  Terminating.'.format(
            args[1])
        return 3

    remove_quotes(NFA)

    Sigma, q0, F = NFA_parameters(NFA)

    # for node in NFA.nodes(data=True):
    # print('{}'.format(node))
    # for edge in NFA.edges(data=True):
    # print edge
    t = input_transition(NFA, Sigma)
    # print '*** input_transition() result ***'
    # for node in sorted(t):
    # print('{} {}'.format(node, t[node]))
    q0_closure = lambda_closure(NFA, q0)
    DFA = powerset_construction(t, q0_closure, Sigma)
    DFA = rebuild_pretty(DFA, q0_closure, F)
    # print '=== powerset_construction() results ==='
    # for node in DFA.nodes(data=True):
    # print('{}'.format(node))
    # for edge in DFA.edges(data=True):
    # print edge

    DFAdot = nx.to_pydot(DFA)
    DFAdot.set_rankdir(RANKDIR)
    DFAdot.set_charset(CHARSET)
    try:
        DFAdot.write(args[2])
    except IOError:
        print '{}: IO error writing file.  Terminating.'.format(args[2])
        return 3

    return 0
Esempio n. 47
0
def readDigraph(file,format,force_dag=False,multi=False):
    """Read a directed graph from file

    Arguments:
    - `file`: file object
    - `format`: file format
    - `force_dag`: enforces whether graph must be acyclic
    - `multi`:     multiple edge allowed

    Return: a networkx.DiGraph / networkx.MultiDiGraph object.
    """
    if format not in _graphformats['digraph']:
        raise ValueError("Invalid format for directed graph")

    if multi:
        grtype=networkx.MultiDiGraph
    else:
        grtype=networkx.DiGraph

    if format=='dot':

        D=grtype(networkx.read_dot(file))
        #D=grtype(pygraphviz.AGraph(file.read()).edges())

    elif format=='gml':

        D=grtype(networkx.read_gml(file))

    elif format=='kth':

        D=_read_graph_kth_format(file,grtype)

    elif format=='dimacs':

        D=_read_graph_dimacs_format(file,grtype)

    else:
        raise RuntimeError("Internal error, format {} not implemented".format(format))

    if force_dag and not networkx.algorithms.is_directed_acyclic_graph(D):
        raise ValueError("Graph must be acyclic".format(format))

    return D
Esempio n. 48
0
def dashboard_graph_name(request, graphName = ''):
	if(graphName!=''):

		try:
		    graph = Graph.objects.filter(name__exact=graphName)
		except Graph.DoesNotExist:
		    graph = None
		
		if(graph.count() == 1):
			graph = graph.first()
			with open ("def_dots/" + graph.link, "r") as myfile:
				data=myfile.read().replace('\r\n', '').replace(os.linesep, '').replace('\t', '').replace('digraph finite_state_machine ', '')
			G=nx.Graph(nx.read_dot("def_dots/" + graph.link))
			graph.data = data
			return render(request, 'dashboard/graph.html', {'graph' : graph, 'info' : getInfo(G)})
		else:
			return HttpResponseRedirect('/grafvizualizacio/search/' + graphName)
	else:
		return HttpResponseRedirect("/grafvizualizacio/")
Esempio n. 49
0
def main(vnet_f):
    virt_g = nx.read_dot(vnet_f)
    # nodes_ct = nx.betweenness_centrality(virt_g, normalized=False)
    # print(nodes_ct)
    print(str("----------------------"))

    # G = virt_g

    G = nx.Graph()
    G.add_path([0, 1, 2, 4])
    G.add_path([0, 5, 3, 4])
    G.add_path([5, 2])
    T = nx.Graph()
    # T.add_path(['vs1', 'vs2'])
    T.add_path([0, 1])
    group_members = [3]
    # print(virt_g.node['vs1'])

    # print("\n"+str(input_trees))
    all_pair_all_shortest_paths_dict = create_all_pair_all_shortest_path_map(G)
Esempio n. 50
0
def generate_dot_following(users, edges, file_name, encode='utf-8'):
    '''生成Dot文件
    '''
    OUT = file_name.decode(
        'utf-8', 'ignore') + '_following_' + encode + '.dot'  ##中文需为unicode编码
    dot = ['"%s" -> "%s" ' % (e[0], e[1]) for e in edges]
    label = [
        '"%s" [label="%s"];' % (u[0], u[1].encode(encode, 'ignore'))
        for u in users
    ]
    with open(OUT, 'wb') as f:
        f.write('strict digraph {\nnode [fontname="FangSong"]\n%s;\n' %
                (';\n'.join(dot), ))
        f.write('\n'.join(label))
        ##输出原帖作者
        f.write('\n}')
        print OUT, 'exported'
    DG = nx.DiGraph(nx.read_dot(OUT))
    nx.write_gexf(DG, file_name + "_following_utf-8.gexf")
    print 'generated GEXF complete!'
Esempio n. 51
0
def readDotFile(fileName):

    #if there is no clean file (i.e. some usernames start with digits, producing an error)
    #run removeNumbers to avoid this error
    if os.path.exists('CLEAN-' + fileName) == False:
        print 'Creating clean .dot file'
        removeNumbers(fileName, 'CLEAN-' + fileName)

    DG = nx.DiGraph(nx.read_dot('CLEAN-' + fileName))

    #remove all of the self loop edges
    DG.remove_edges_from(DG.selfloop_edges())

    #remove all nodes with no edges
    toRemove = []
    for node in DG:
        if DG.in_degree(node) == 0 and DG.out_degree(node) == 0:
            toRemove.append(node)
    DG.remove_nodes_from(toRemove)

    return DG
Esempio n. 52
0
def __draw_state_nodes__(dot_file):
    """
    Read in a .dot file, draw the nodes and return their positions
    """
    import networkx as nx
    import pygraphviz as pyg
    from matplotlib.pyplot import gca, draw, gcf

    gpy = pyg.AGraph(dot_file)
    gpy.layout(prog=__dot_defs__.PROGRAM, args=__dot_defs__.ARGS)
    pos = dict()
    pos_labels = dict()
    for nod in gpy.nodes_iter():
        _pos = nod.attr[u'pos'].split(',')
        _name = nod.name
        _pos = map(float, _pos)
        _pos_label = map(float, _pos)
        _pos_label[1] += __networkx_defs__.NODE_LABEL_Y_OFFSET
        pos[str(_name)] = tuple(_pos)
        pos_labels[str(_name)] = tuple(_pos_label)

    gnx = nx.read_dot(dot_file)
    node_labels = {str(n[0]): str(n[1]['label']) for n in gnx.node.items()}
    nx.draw_networkx(gnx,
                     pos=pos,
                     with_labels=False,
                     node_color='w',
                     node_size=__networkx_defs__.NODE_SIZE)
    nx.draw_networkx_labels(gnx, labels=node_labels, pos=pos_labels)

    current_ax = gca()
    current_ax.spines['top'].set_visible(False)
    current_ax.spines['right'].set_visible(False)
    current_ax.spines['bottom'].set_visible(False)
    current_ax.spines['left'].set_visible(False)
    current_ax.xaxis.set_ticks([])
    current_ax.yaxis.set_ticks([])
    gcf().set_tight_layout(True)
    draw()
    return pos
Esempio n. 53
0
def readGraph(file, format, multi=False):
    """Read a graph from file

    Arguments:
    - `file`: file object
    - `format`: file format
    - `multi`: multiple edge allowed

    Return: a networkx.Graph / networkx.MultiGraph object.
    """
    if format not in _graphformats['simple']:
        raise ValueError("Invalid format for undirected graph")

    if multi:
        grtype = networkx.MultiGraph
    else:
        grtype = networkx.Graph

    if format == 'dot':

        D = grtype(networkx.read_dot(file))

    elif format == 'gml':

        G = grtype(networkx.read_gml(file))

    elif format == 'kth':

        G = _read_graph_kth_format(file, grtype)

    elif format == 'dimacs':

        G = _read_graph_dimacs_format(file, grtype)

    else:
        raise RuntimeError(
            "Internal error, format {} not implemented".format(format))

    return G
Esempio n. 54
0
def main():

    path = ""
    if (len(sys.argv) > 1):
        path = sys.argv[1]
    else:
        usage()
        sys.exit(1)

    try:
        fh = open(path)
    except IOError as e:
        sys.stderr.write("ERROR: could not read file " + path + "\n")
        usage()
        sys.exit(1)

    # read in the specified file, create a networkx DiGraph
    G = nx.DiGraph(nx.read_dot(path))

    C = nx.simple_cycles(G)
    for i in C:
        print i
def readData(fname):
    """ Importing a large DOT file is slow. This function will read a pickle
    file if available. If no pickle, then read DOT and create a pickle for next
    time. """

    pname = os.path.splitext(fname)[0] + ".gpickle"
    try:
        # If there is a pickle, unpickle it
        logging.info("Unpickling file")
        nxGraph = nx.Graph(nx.read_gpickle(pname))
    except:
        logging.info("No Pickled file, will import DOT")
        try:
            # No pickle, try the dot file
            logging.info("Importing dot file")
            nxGraph = nx.Graph(nx.read_dot(fname))

            # Make pickle for next time
            logging.info("Pickle graph for later use.")
            nx.write_gpickle(nxGraph, pname)
        except Exception:
            logging.exception("Please provide a DOT formated file.")
    return (nxGraph)