Python networkx 模块,write_graphml() 实例源码

我们从Python开源项目中,提取了以下15个代码示例,用于说明如何使用networkx.write_graphml()

项目:pybel    作者:pybel    | 项目源码 | 文件源码
def to_graphml(graph, file):
    """Writes this graph to GraphML XML file using :func:`networkx.write_graphml`. The .graphml file extension is
    suggested so Cytoscape can recognize it.

    :param BELGraph graph: A BEL graph
    :param file file: A file or file-like object
    """
    g = nx.MultiDiGraph()

    for node, data in graph.nodes(data=True):
        g.add_node(node, json=json.dumps(data))

    for u, v, key, data in graph.edges(data=True, keys=True):
        g.add_edge(u, v, key=key, attr_dict=flatten_dict(data))

    nx.write_graphml(g, file)
项目:ndmg    作者:neurodata    | 项目源码 | 文件源码
def save_graph(self, graphname, fmt='gpickle'):
        """
        Saves the graph to disk

        **Positional Arguments:**

                graphname:
                    - Filename for the graph

        **Optional Arguments:**

                fmt:
                    - Output graph format
        """
        self.g.graph['ecount'] = nx.number_of_edges(self.g)
        if fmt == 'gpickle':
            nx.write_gpickle(self.g, graphname)
        elif fmt == 'graphml':
            nx.write_graphml(self.g, graphname)
        else:
            raise ValueError('graphml is the only format currently supported')
        pass
项目:anomalous-vertices-detection    作者:Kagandi    | 项目源码 | 文件源码
def save_graph(self, save_path, file_type="pickle"):
        """ Saves the graph into a file

        Parameters
        ----------
        file_type
        save_path: string,
            The path where the file shpuld be saved

        Examples
        --------
        >>> g.save_graph("Facebook.", "graphml")
        """
        if file_type == "pickle":
            nx.write_gpickle(self._graph, save_path)
        elif file_type == "sgraph":
            self.save_as_sgraph(save_path)
        elif file_type == "graphml":
            nx.write_graphml(self._graph, save_path)
        else:
            msg = "The file type %s is unknown" % file_type
            raise TypeError(msg)
项目:phasm    作者:AbeelLab    | 项目源码 | 文件源码
def _write_graphs(g, output_dir, filename_tpl, formats):
    for file_format in formats:
        if file_format.startswith('gfa'):
            version = int(file_format[-1])
            filename = filename_tpl + "gfa"
            path = os.path.join(output_dir, filename)

            with open(path, "w") as f:
                gfa.write_graph(f, g, version)
        else:
            filename = filename_tpl + "graphml"
            path = os.path.join(output_dir, filename)
            with open(path, "w") as f:
                networkx.write_graphml(g, f, encoding='unicode')
项目:graynet    作者:raamana    | 项目源码 | 文件源码
def save_summary_graph(graph, out_dir, subject,
                       str_suffix=None,
                       summary_descr='summary'):
    "Saves the features to disk."

    if out_dir is not None:
        # get outpath returned from hiwenet, based on dist name and all other parameters
        # choose out_dir name  based on dist name and all other parameters
        out_subject_dir = pjoin(out_dir, subject)
        if not pexists(out_subject_dir):
            os.mkdir(out_subject_dir)

        if str_suffix is not None:
            out_file_name = '{}_{}_multigraph_graynet.graphml'.format(str_suffix,summary_descr)
        else:
            out_file_name = '_{}_multigraph_graynet.graphml'.format(summary_descr)

        out_weights_path = pjoin(out_subject_dir, out_file_name)

        try:
            nx.info(graph)
            nx.write_graphml(graph, out_weights_path, encoding='utf-8')
            print('\nSaved the summary multi-graph to \n{}'.format(out_weights_path))
        except:
            print('\nUnable to save summary multi-graph to \n{}'.format(out_weights_path))
            traceback.print_exc()

    return
项目:graynet    作者:raamana    | 项目源码 | 文件源码
def save_graph(graph, out_path, identifier=''):
    "Saves the given graph to disk."

    if out_path is not None:
        try:
            nx.write_graphml(graph, out_path, encoding='utf-8')
            print('\nSaved the {} graph to \n{}'.format(identifier, out_path))
        except:
            print('\nUnable to save {} graph to \n{}'.format(identifier, out_path))
            traceback.print_exc()

    return out_path
项目:graynet    作者:raamana    | 项目源码 | 文件源码
def save_graph(graph_nx, out_dir, subject, str_suffix=None):
    "Saves the features to disk."

    if out_dir is not None:
        # get outpath returned from hiwenet, based on dist name and all other parameters
        # choose out_dir name  based on dist name and all other parameters
        out_subject_dir = pjoin(out_dir, subject)
        if not pexists(out_subject_dir):
            os.mkdir(out_subject_dir)

        if str_suffix is not None:
            out_file_name = '{}_graynet.graphml'.format(str_suffix)
        else:
            out_file_name = 'graynet.graphml'

        out_weights_path = pjoin(out_subject_dir, out_file_name)

        try:
            nx.info(graph_nx)
            nx.write_graphml(graph_nx, out_weights_path, encoding='utf-8')
            print('\nSaved the graph to \n{}'.format(out_weights_path))
        except:
            print('\nUnable to save graph to \n{}'.format(out_weights_path))
            traceback.print_exc()

    return
项目:pysmap    作者:SMAPPNYU    | 项目源码 | 文件源码
def test_make_retweet_network_graph(self):
        output_path = '{}/chart_tests/network-{}-retweet.graphml'.format(os.path.dirname(os.path.realpath(__file__)), datetime.now())
        file_path = '{}/{}'.format(os.path.dirname(os.path.realpath(__file__)), config['json']['valid'])
        collection = SmappCollection('json', file_path)
        digraph = networks.retweet_network(collection, ['id_str', 'retweeted_status.id_str', 'created_at', 'text', 'lang'], ['id_str', 'screen_name', 'location', 'description'])
        nx.write_graphml(digraph, output_path)
项目:pysmap    作者:SMAPPNYU    | 项目源码 | 文件源码
def test_empty_make_retweet_network_graph(self):
        output_path = '{}/chart_tests/network-{}-retweet-empty.graphml'.format(os.path.dirname(os.path.realpath(__file__)), datetime.now())
        file_path = '{}/{}'.format(os.path.dirname(os.path.realpath(__file__)), config['json']['valid'])
        collection = SmappCollection('json', file_path)
        digraph = networks.retweet_network(collection, [], [])
        nx.write_graphml(digraph, output_path)
项目:Pyscholar    作者:rfabila    | 项目源码 | 文件源码
def save_graphml(G, filename):
    """Saves a network created get_network to graphml file"""

    if "paper" in G.edges()[0]:
        H = networkx.graph.Graph()
        for e in G.edges():
            H.add_edge(e[0], e[1])
            H[e[0]][e[1]]['weight'] = len(G[e[0]][e[1]]['papers'])
        G = H
    networkx.write_graphml(G, filename)
项目:osmnx    作者:gboeing    | 项目源码 | 文件源码
def save_graphml(G, filename='graph.graphml', folder=None):
    """
    Save graph as GraphML file to disk.

    Parameters
    ----------
    G : networkx multidigraph
    filename : string
        the name of the graphml file (including file extension)
    folder : string
        the folder to contain the file, if None, use default data folder

    Returns
    -------
    None
    """

    start_time = time.time()
    if folder is None:
        folder = settings.data_folder

    # create a copy and convert all the node/edge attribute values to string or
    # it won't save
    G_save = G.copy()
    for dict_key in G_save.graph:
        # convert all the graph attribute values to strings
        G_save.graph[dict_key] = make_str(G_save.graph[dict_key])
    for _, data in G_save.nodes(data=True):
        for dict_key in data:
            # convert all the node attribute values to strings
            data[dict_key] = make_str(data[dict_key])
    for _, _, data in G_save.edges(keys=False, data=True):
        for dict_key in data:
            # convert all the edge attribute values to strings
            data[dict_key] = make_str(data[dict_key])

    if not os.path.exists(folder):
        os.makedirs(folder)

    nx.write_graphml(G_save, '{}/{}'.format(folder, filename))
    log('Saved graph "{}" to disk as GraphML at "{}/{}" in {:,.2f} seconds'.format(G_save.name, folder, filename, time.time()-start_time))
项目:twitter-social-affiliation-network    作者:zacharykstine    | 项目源码 | 文件源码
def write_to_graphml(G):
    path = "republican_test2" + ".graphml"
    nx.write_graphml(G, path, encoding='utf-8', prettyprint=True)
项目:son-cli    作者:sonata-nfv    | 项目源码 | 文件源码
def write_service_graphs(service):
        graphsdir = 'graphs'
        try:
            os.makedirs(graphsdir)
        except OSError as exc:
            if exc.errno == errno.EEXIST and os.path.isdir(graphsdir):
                pass

        service.build_topology_graph(level=3, bridges=False)

        for lvl in range(0, 4):
            g = service.build_topology_graph(level=lvl, bridges=False)
            nx.write_graphml(g, os.path.join(graphsdir,
                                             "{0}-lvl{1}.graphml"
                                             .format(service.id, lvl)))
            g = service.build_topology_graph(level=lvl, bridges=True)
            nx.write_graphml(g, os.path.join(graphsdir,
                                             "{0}-lvl{1}-br.graphml"
                                             .format(service.id, lvl)))

        g = service.build_topology_graph(level=3, bridges=True,
                                         vdu_inner_connections=False)
        service.complete_graph = nx.generate_graphml(g, encoding='utf-8',
                                                     prettyprint=True)
        nx.write_graphml(g, os.path.join(graphsdir,
                                         "{0}-lvl3-complete.graphml"
                                         .format(service.id)))
项目:open-syllabus-project    作者:davidmcclure    | 项目源码 | 文件源码
def write_graphml(self, path):

        """
        Serialize the graph as .graphml.

        Args:
            path (str)
        """

        nx.write_graphml(self.graph, path)
项目:gitnet    作者:networks-lab    | 项目源码 | 文件源码
def write_graphml(self, fname):
        """
        Converts a `MultiGraphPlus` object to a graphml file.

        **Parameters** :

        > *fname* :

        >> A string indicating the path or file name to write to. File names which end in `.gz` or `.bz2` will be compressed.

        **Return** : `None`

        > This method will have the side effect of creating a file, specified by fpath.
        > This method cannot use vector attributes within the graphml file. Instead, vector attributes are converted into
        > a semicolon-delimited string. When this occurs, a warning is raised indicating the vector attributes (node
        > attributes are preceded by 'n:' while edge attributes are preceded by 'e:').

        """

        graph = copy.deepcopy(self)

        warning = False
        warning_set = set([])
        for n in graph.nodes():
            for attr in graph.node[n].keys():
                if isinstance(graph.node[n][attr], list):
                    warning = True
                    warning_set = {'n:' + attr} | warning_set
                    graph.node[n][attr] = list_to_scd(graph.node[n][attr])

        for n1, n2, data in graph.edges(data=True):
            for k in data:
                if isinstance(data[k], list):
                    warning = True
                    warning_set = {'e:'+k} | warning_set
                    data[k] = list_to_scd(data[k])

        if warning:
            warnings.warn("The provided graph contained the vector attributes: {}. All values of vector attributes have"
                          " been converted to semicolon-delimited strings. To prevent this, remove vector attributes or"
                          " convert them to atomic attributes prior to calling .write_graphml"
                          .format(warning_set))
        nx.write_graphml(graph, fname)
        print("Success. Wrote GraphML file {} to {}".format(fname, os.getcwd()))