Python networkx.write_gexf() Examples

The following are 24 code examples of networkx.write_gexf(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module networkx , or try the search function .
Example #1
Source File: networkx.py    From Verum with Apache License 2.0 6 votes vote down vote up
def write_graph(self, G=None, subgraph_file=None):
        if G is None:
            G = self.context_graph
        if subgraph_file is None:
            subgraph_file = self.context_graph_file
        logging.info("Writing graph.")
        # write the graph out
        file_format = subgraph_file.split(".")[-1]
        if file_format == "graphml":
            nx.write_graphml(G, subgraph_file)
        elif file_format == "gml":
            nx.write_gml(G, subgraph_file)
        elif file_format == "gexf":
            nx.write_gexf(G, subgraph_file)
        elif file_format == "net":
            nx.write_pajek(G, subgraph_file)
        elif file_format == "yaml":
            nx.write_yaml(G, subgraph_file)
        elif file_format == "gpickle":
            nx.write_gpickle(G, subgraph_file)
        else:
            print "File format not found, writing graphml."
            nx.write_graphml(G, subgraph_file) 
Example #2
Source File: test_gexf.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_default_attribute(self):
        G = nx.Graph()
        G.add_node(1, label='1', color='green')
        nx.add_path(G, [0, 1, 2, 3])
        G.add_edge(1, 2, foo=3)
        G.graph['node_default'] = {'color': 'yellow'}
        G.graph['edge_default'] = {'foo': 7}
        fh = io.BytesIO()
        nx.write_gexf(G, fh)
        fh.seek(0)
        H = nx.read_gexf(fh, node_type=int)
        assert_equal(sorted(G.nodes()), sorted(H.nodes()))
        assert_equal(
            sorted(sorted(e) for e in G.edges()),
            sorted(sorted(e) for e in H.edges()))
        # Reading a gexf graph always sets mode attribute to either
        # 'static' or 'dynamic'. Remove the mode attribute from the
        # read graph for the sake of comparing remaining attributes.
        del H.graph['mode']
        assert_equal(G.graph, H.graph) 
Example #3
Source File: main.py    From scTDA with GNU General Public License v3.0 6 votes vote down vote up
def save(self, name, resolution, gain, equalize=True, cluster='agglomerative', statistics='db', max_K=5):
        """
        Generates a topological representation using the Mapper algorithm with resolution and gain specified by the
        parameters 'resolution' and 'gain'. When equalize is set to True, patches are chosen such that they
        contain the same number of points. The parameter 'cluster' specifies the clustering method ('agglomerative' or
        'kmeans'). The parameter 'statistics' specifies the criterion for choosing the optimal number of clusters
        ('db' for Davies-Bouildin index, or 'gap' for the gap statistic). The parameter 'max_K' specifies the maximum
        number of clusters to be considered within each patch. The topological representation is stored in the files
        'name.gexf' and 'name.json'. It returns a dictionary with the patches.
        """
        G, all_clusters, patches = sakmapper.mapper_graph(self.df, lens_data=self.lens_data_mds,
                                                          resolution=resolution,
                                                          gain=gain, equalize=equalize, clust=cluster,
                                                          stat=statistics, max_K=max_K)
        dic = {}
        for n, rs in enumerate(all_clusters):
            dic[str(n)] = map(lambda x: int(x), rs)
        with open(name + '.json', 'wb') as handle3:
            json.dump(dic, handle3)
        networkx.write_gexf(G, name + '.gexf')
        return patches 
Example #4
Source File: ABPUtils.py    From SDA with MIT License 6 votes vote down vote up
def WriteAdjList(adjList, graphName, colorLabels=None):
    g = nx.Graph()

    for i in range(0,len(adjList)):
        if (colorLabels is not None):
            g.add_node(i, color=colorLabels[i], id=str(i))
        else:
            g.add_node(i)

    idx = 0
    for i in range(0,len(adjList)):
        for j in range(0,len(adjList[i])):
            g.add_edge(i, adjList[i][j][0], capacity=adjList[i][j][1])

    if (graphName.find("gml") >= 0):
        nx.write_gml(g, graphName)
    elif (graphName.find("gexf") >= 0):
        nx.write_gexf(g, graphName)
    elif (graphName.find("graphml") >= 0):
        nx.write_graphml(g, graphName) 
Example #5
Source File: test_gexf.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_default_attribute(self):
        G=nx.Graph()
        G.add_node(1,label='1',color='green')
        G.add_path([0,1,2,3])
        G.add_edge(1,2,foo=3)
        G.graph['node_default']={'color':'yellow'}
        G.graph['edge_default']={'foo':7}
        fh = io.BytesIO()
        nx.write_gexf(G,fh)
        fh.seek(0)
        H=nx.read_gexf(fh,node_type=int)
        assert_equal(sorted(G.nodes()),sorted(H.nodes()))
        assert_equal(
            sorted(sorted(e) for e in G.edges()),
            sorted(sorted(e) for e in H.edges()))
        # Reading a gexf graph always sets mode attribute to either
        # 'static' or 'dynamic'. Remove the mode attribute from the
        # read graph for the sake of comparing remaining attributes.
        del H.graph['mode']
        assert_equal(G.graph,H.graph) 
Example #6
Source File: test_gexf.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_default_attribute(self):
        G = nx.Graph()
        G.add_node(1, label='1', color='green')
        nx.add_path(G, [0, 1, 2, 3])
        G.add_edge(1, 2, foo=3)
        G.graph['node_default'] = {'color': 'yellow'}
        G.graph['edge_default'] = {'foo': 7}
        fh = io.BytesIO()
        nx.write_gexf(G, fh)
        fh.seek(0)
        H = nx.read_gexf(fh, node_type=int)
        assert_equal(sorted(G.nodes()), sorted(H.nodes()))
        assert_equal(
            sorted(sorted(e) for e in G.edges()),
            sorted(sorted(e) for e in H.edges()))
        # Reading a gexf graph always sets mode attribute to either
        # 'static' or 'dynamic'. Remove the mode attribute from the
        # read graph for the sake of comparing remaining attributes.
        del H.graph['mode']
        assert_equal(G.graph, H.graph) 
Example #7
Source File: test_gexf.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_bool(self):
        G=nx.Graph()
        G.add_node(1, testattr=True)
        fh = io.BytesIO()
        nx.write_gexf(G,fh)
        fh.seek(0)
        H=nx.read_gexf(fh,node_type=int)
        assert_equal(H.node[1]['testattr'], True) 
Example #8
Source File: test_gexf.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_bool(self):
        G = nx.Graph()
        G.add_node(1, testattr=True)
        fh = io.BytesIO()
        nx.write_gexf(G, fh)
        fh.seek(0)
        H = nx.read_gexf(fh, node_type=int)
        assert_equal(H.nodes[1]['testattr'], True) 
Example #9
Source File: test_gexf.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_serialize_ints_to_strings(self):
        G = nx.Graph()
        G.add_node(1, id=7, label=77)
        fh = io.BytesIO()
        nx.write_gexf(G, fh)
        fh.seek(0)
        H = nx.read_gexf(fh, node_type=int)
        assert_equal(list(H), [7])
        assert_equal(H.nodes[7]['label'], '77') 
Example #10
Source File: test_gexf.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_write_read_simple_directed_graphml(self):
        G = self.simple_directed_graph
        fh = io.BytesIO()
        nx.write_gexf(G, fh)
        fh.seek(0)
        H = nx.read_gexf(fh)
        assert_equal(sorted(G.nodes()), sorted(H.nodes()))
        assert_equal(sorted(G.edges()), sorted(H.edges()))
        assert_equal(sorted(G.edges(data=True)),
                     sorted(H.edges(data=True)))
        self.simple_directed_fh.seek(0) 
Example #11
Source File: test_gexf.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_bool(self):
        G = nx.Graph()
        G.add_node(1, testattr=True)
        fh = io.BytesIO()
        nx.write_gexf(G, fh)
        fh.seek(0)
        H = nx.read_gexf(fh, node_type=int)
        assert_equal(H.nodes[1]['testattr'], True) 
Example #12
Source File: test_gexf.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_serialize_ints_to_strings(self):
        G = nx.Graph()
        G.add_node(1, id=7, label=77)
        fh = io.BytesIO()
        nx.write_gexf(G, fh)
        fh.seek(0)
        H = nx.read_gexf(fh, node_type=int)
        assert_equal(list(H), [7])
        assert_equal(H.nodes[7]['label'], '77') 
Example #13
Source File: test_gexf.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_write_read_simple_directed_graphml(self):
        G = self.simple_directed_graph
        fh = io.BytesIO()
        nx.write_gexf(G, fh)
        fh.seek(0)
        H = nx.read_gexf(fh)
        assert_equal(sorted(G.nodes()), sorted(H.nodes()))
        assert_equal(sorted(G.edges()), sorted(H.edges()))
        assert_equal(sorted(G.edges(data=True)),
                     sorted(H.edges(data=True)))
        self.simple_directed_fh.seek(0) 
Example #14
Source File: gexf.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def write_gexf(G, path, encoding='utf-8',prettyprint=True,version='1.1draft'):
    """Write G in GEXF format to path.

    "GEXF (Graph Exchange XML Format) is a language for describing
    complex networks structures, their associated data and dynamics" [1]_.

    Parameters
    ----------
    G : graph
       A NetworkX graph
    path : file or string
       File or file name to write.
       File names ending in .gz or .bz2 will be compressed.
    encoding : string (optional)
       Encoding for text data.
    prettyprint : bool (optional)
       If True use line breaks and indenting in output XML.

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_gexf(G, "test.gexf")

    Notes
    -----
    This implementation does not support mixed graphs (directed and undirected
    edges together).

    The node id attribute is set to be the string of the node label.
    If you want to specify an id use set it as node data, e.g.
    node['a']['id']=1 to set the id of node 'a' to 1.

    References
    ----------
    .. [1] GEXF graph format, http://gexf.net/format/
    """
    writer = GEXFWriter(encoding=encoding,prettyprint=prettyprint,
                        version=version)
    writer.add_graph(G)
    writer.write(path) 
Example #15
Source File: test_gexf.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_serialize_ints_to_strings(self):
        G=nx.Graph()
        G.add_node(1,id=7,label=77)
        fh = io.BytesIO()
        nx.write_gexf(G,fh)
        fh.seek(0)
        H=nx.read_gexf(fh,node_type=int)
        assert_equal(H.nodes(),[7])
        assert_equal(H.node[7]['label'],'77') 
Example #16
Source File: test_gexf.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_write_read_simple_directed_graphml(self):
        G=self.simple_directed_graph
        fh=io.BytesIO()
        nx.write_gexf(G,fh)
        fh.seek(0)
        H=nx.read_gexf(fh)
        assert_equal(sorted(G.nodes()),sorted(H.nodes()))
        assert_equal(sorted(G.edges()),sorted(H.edges()))
        assert_equal(sorted(G.edges(data=True)),
                     sorted(H.edges(data=True)))
        self.simple_directed_fh.seek(0) 
Example #17
Source File: ABPUtils.py    From SDA with MIT License 5 votes vote down vote up
def WriteGraph(g, graphName, colorLabels=None):

    if (graphName.find("gml") >= 0):
        nx.write_gml(g, graphName)
    elif (graphName.find("gexf") >= 0):
        nx.write_gexf(g, graphName)
    elif (graphName.find("graphml") >= 0):
        nx.write_graphml(g, graphName) 
Example #18
Source File: feedback_graph.py    From acl2017-interactive_summarizer with Apache License 2.0 5 votes vote down vote up
def get_weights(self):
        G = self.G
        pr = self.pr
        max_pagerank = max(pr.itervalues())
        # get the largest count to scale weights between 0 and 1.

        t = datetime.datetime.now()
        ts = int(time.mktime(t.timetuple()))
        temp = tempfile.mktemp(prefix=str(ts), suffix=".gexf")

        nx.write_gexf(G, temp)

        for (k, v) in pr.iteritems():
            yield (k, float(v / max_pagerank)) 
Example #19
Source File: topology.py    From YAFS with MIT License 5 votes vote down vote up
def write(self,path):
        nx.write_gexf(self.G, path) 
Example #20
Source File: rede_cnpj.py    From CNPJ-full with GNU General Public License v3.0 5 votes vote down vote up
def gera_gexf_G(self, G, path):
        # Antes de gerar esse formato, necessario adaptar alguns atributos do grafo
        G_adapt = G.copy()

        pos = nx.spring_layout(G_adapt, dim=4, scale=1000)
        
        for node in G_adapt.nodes:
            tipo_pessoa = G_adapt.nodes[node]['tipo_pessoa']

            G_adapt.nodes[node]['label'] = G_adapt.nodes[node]['nome']

            # Configura atributos de visualizacao necessarios para alguns leitores
            G_adapt.nodes[node]['viz'] = {'size':10}

            if tipo_pessoa == 1:
                if G_adapt.nodes[node]['situacao'] == '02':
                    G_adapt.nodes[node]['viz']['color'] = {'a':1,'r':1,'g':57,'b':155}
                else:
                    G_adapt.nodes[node]['viz']['color'] = {'a':1,'r':255,'g':0,'b':0}
            else:
                G_adapt.nodes[node]['viz']['color'] = {'a':1,'r':46,'g':125,'b':32}

            G_adapt.nodes[node]['viz']['position'] = {'x':pos[node][0],
                                                      'y':pos[node][1],
                                                      'z':5}

            # Converte cols para float, por incompatibilidade do nx com o numpy.float64
            for coluna in COL_FLOAT64:
                if coluna in G_adapt.nodes[node]:
                    G_adapt.nodes[node][coluna] = float(G_adapt.nodes[node][coluna])

        nx.write_gexf(G_adapt, path) 
Example #21
Source File: main.py    From dcc with Apache License 2.0 4 votes vote down vote up
def androcg_main(verbose,
                 APK,
                 classname,
                 methodname,
                 descriptor,
                 accessflag,
                 no_isolated,
                 show,
                 output):
    from androguard.core.androconf import show_logging
    from androguard.core.bytecode import FormatClassToJava
    from androguard.misc import AnalyzeAPK
    import networkx as nx
    import logging
    log = logging.getLogger("androcfg")
    if verbose:
        show_logging(logging.INFO)

    a, d, dx = AnalyzeAPK(APK)

    entry_points = map(FormatClassToJava,
                       a.get_activities() + a.get_providers() +
                       a.get_services() + a.get_receivers())
    entry_points = list(entry_points)

    log.info("Found The following entry points by search AndroidManifest.xml: "
             "{}".format(entry_points))

    CG = dx.get_call_graph(classname,
                           methodname,
                           descriptor,
                           accessflag,
                           no_isolated,
                           entry_points,
                           )

    write_methods = dict(gml=_write_gml,
                         gexf=nx.write_gexf,
                         gpickle=nx.write_gpickle,
                         graphml=nx.write_graphml,
                         yaml=nx.write_yaml,
                         net=nx.write_pajek,
                         )

    if show:
        plot(CG)
    else:
        writer = output.rsplit(".", 1)[1]
        if writer in ["bz2", "gz"]:
            writer = output.rsplit(".", 2)[1]
        if writer not in write_methods:
            print("Could not find a method to export files to {}!"
                  .format(writer))
            sys.exit(1)

        write_methods[writer](CG, output) 
Example #22
Source File: gexf.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def write_gexf(G, path, encoding='utf-8', prettyprint=True, version='1.2draft'):
    """Write G in GEXF format to path.

    "GEXF (Graph Exchange XML Format) is a language for describing
    complex networks structures, their associated data and dynamics" [1]_.

    Node attributes are checked according to the version of the GEXF
    schemas used for parameters which are not user defined,
    e.g. visualization 'viz' [2]_. See example for usage.

    Parameters
    ----------
    G : graph
       A NetworkX graph
    path : file or string
       File or file name to write.
       File names ending in .gz or .bz2 will be compressed.
    encoding : string (optional, default: 'utf-8')
       Encoding for text data.
    prettyprint : bool (optional, default: True)
       If True use line breaks and indenting in output XML.

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> nx.write_gexf(G, "test.gexf")

    # visualization data
    >>> G.nodes[0]['viz'] = {'size': 54}
    >>> G.nodes[0]['viz']['position'] = {'x' : 0, 'y' : 1}
    >>> G.nodes[0]['viz']['color'] = {'r' : 0, 'g' : 0, 'b' : 256}


    Notes
    -----
    This implementation does not support mixed graphs (directed and undirected
    edges together).

    The node id attribute is set to be the string of the node label.
    If you want to specify an id use set it as node data, e.g.
    node['a']['id']=1 to set the id of node 'a' to 1.

    References
    ----------
    .. [1] GEXF File Format, https://gephi.org/gexf/format/
    .. [2] GEXF viz schema 1.1, https://gephi.org/gexf/1.1draft/viz
    """
    writer = GEXFWriter(encoding=encoding, prettyprint=prettyprint,
                        version=version)
    writer.add_graph(G)
    writer.write(path) 
Example #23
Source File: analyse_results_paper_v2.py    From YAFS with MIT License 4 votes vote down vote up
def topology_description_of_services():
    for exp in experimentos:
        pathSimple = "exp1/results_case_%s/"%exp    
    
        dep_MCDA = distributionServices_withplot(pathSimple,"MCDA")
        dep_WA = distributionServices_withplot(pathSimple,"WA")
       
     
        ## discovering source entities
        sources_MCDA,sources_WA = {},{}
        sources2_MCDA,sources2_WA = {},{}
        case= "MCDA"
        dr = pd.read_pickle(pathSimple+"dr_%s_%i.pkl"%(case,0))
        nodeSources = dr.user.values
        for k in range(200):
            sources_MCDA[str(k)]=k in nodeSources
            if k in nodeSources:
                sources2_MCDA[str(k)] = 10.0
            else:
                sources2_MCDA[str(k)] = 0.0     
        case=  "WA"
        dr = pd.read_pickle(pathSimple+"dr_%s_%i.pkl"%(case,0))
        nodeSources = dr.user.values
        for k in range(200):
            sources_WA[str(k)]=k in nodeSources
            if k in nodeSources:
                sources2_WA[str(k)] = 10.0
            else:
                sources2_WA[str(k)] = 0.0 
            
        #Ok
        G = nx.read_gexf(pathEXP+"network.gexf")
        nx.set_node_attributes(G, values=dep_MCDA, name='deploys_MCDA')
        nx.set_node_attributes(G, values=dep_WA, name='deploys_WA')
        nx.set_node_attributes(G, values=sources_MCDA, name='sources_MCDA')
        nx.set_node_attributes(G, values=sources2_MCDA, name='sourcesValue_MCDA')
        nx.set_node_attributes(G, values=sources_WA, name='sources_WA')
        nx.set_node_attributes(G, values=sources2_WA, name='sourcesValue_WA')
        nx.write_gexf(G,pathSimple+"netwok-WA-MCDA.gexf")    
            
                
# =============================================================================
# =============================================================================
# #  GLOBAL VARIABLES
# =============================================================================
# ============================================================================= 
Example #24
Source File: gexf.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def write_gexf(G, path, encoding='utf-8', prettyprint=True, version='1.2draft'):
    """Write G in GEXF format to path.

    "GEXF (Graph Exchange XML Format) is a language for describing
    complex networks structures, their associated data and dynamics" [1]_.

    Node attributes are checked according to the version of the GEXF
    schemas used for parameters which are not user defined,
    e.g. visualization 'viz' [2]_. See example for usage.

    Parameters
    ----------
    G : graph
       A NetworkX graph
    path : file or string
       File or file name to write.
       File names ending in .gz or .bz2 will be compressed.
    encoding : string (optional, default: 'utf-8')
       Encoding for text data.
    prettyprint : bool (optional, default: True)
       If True use line breaks and indenting in output XML.

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> nx.write_gexf(G, "test.gexf")

    # visualization data
    >>> G.nodes[0]['viz'] = {'size': 54}
    >>> G.nodes[0]['viz']['position'] = {'x' : 0, 'y' : 1}
    >>> G.nodes[0]['viz']['color'] = {'r' : 0, 'g' : 0, 'b' : 256}


    Notes
    -----
    This implementation does not support mixed graphs (directed and undirected
    edges together).

    The node id attribute is set to be the string of the node label.
    If you want to specify an id use set it as node data, e.g.
    node['a']['id']=1 to set the id of node 'a' to 1.

    References
    ----------
    .. [1] GEXF File Format, https://gephi.org/gexf/format/
    .. [2] GEXF viz schema 1.1, https://gephi.org/gexf/1.1draft/viz
    """
    writer = GEXFWriter(encoding=encoding, prettyprint=prettyprint,
                        version=version)
    writer.add_graph(G)
    writer.write(path)