当前位置: 首页>>代码示例>>Python>>正文


Python networkx.write_gpickle方法代码示例

本文整理汇总了Python中networkx.write_gpickle方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.write_gpickle方法的具体用法?Python networkx.write_gpickle怎么用?Python networkx.write_gpickle使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在networkx的用法示例。


在下文中一共展示了networkx.write_gpickle方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: write_graph

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import write_gpickle [as 别名]
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) 
开发者ID:vz-risk,项目名称:Verum,代码行数:25,代码来源:networkx.py

示例2: serialize_network

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import write_gpickle [as 别名]
def serialize_network(network, path):
    """
    Serialize the meta schema index
    :param network:
    :param path:
    :return:
    """
    G = network._get_underlying_repr_graph()
    id_to_field_info = network._get_underlying_repr_id_to_field_info()
    table_to_ids = network._get_underlying_repr_table_to_ids()

    # Make sure we create directory if this does not exist
    path = path + '/'  # force separator
    os.makedirs(os.path.dirname(path), exist_ok=True)

    nx.write_gpickle(G, path + "graph.pickle")
    nx.write_gpickle(id_to_field_info, path + "id_info.pickle")
    nx.write_gpickle(table_to_ids, path + "table_ids.pickle") 
开发者ID:mitdbg,项目名称:aurum-datadiscovery,代码行数:20,代码来源:fieldnetwork.py

示例3: save_cache

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import write_gpickle [as 别名]
def save_cache(self, mg, src, dst, ntid, etid, ntypes, etypes):
        nx.write_gpickle(mg, os.path.join(self._dir, 'cached_mg.gpickle'))
        np.save(os.path.join(self._dir, 'cached_src.npy'), src)
        np.save(os.path.join(self._dir, 'cached_dst.npy'), dst)
        np.save(os.path.join(self._dir, 'cached_ntid.npy'), ntid)
        np.save(os.path.join(self._dir, 'cached_etid.npy'), etid)
        save_strlist(os.path.join(self._dir, 'cached_ntypes.txt'), ntypes)
        save_strlist(os.path.join(self._dir, 'cached_etypes.txt'), etypes)
        np.save(os.path.join(self._dir, 'cached_train_idx.npy'), F.asnumpy(self.train_idx))
        np.save(os.path.join(self._dir, 'cached_test_idx.npy'), F.asnumpy(self.test_idx))
        np.save(os.path.join(self._dir, 'cached_labels.npy'), F.asnumpy(self.labels)) 
开发者ID:dmlc,项目名称:dgl,代码行数:13,代码来源:rdf.py

示例4: to_pickle

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import write_gpickle [as 别名]
def to_pickle(graph: BELGraph, path: Union[str, BinaryIO], protocol: int = HIGHEST_PROTOCOL) -> None:
    """Write this graph to a pickle object with :func:`networkx.write_gpickle`.

    Note that the pickle module has some incompatibilities between Python 2 and 3. To export a universally importable
    pickle, choose 0, 1, or 2.

    :param graph: A BEL graph
    :param path: A path or file-like
    :param protocol: Pickling protocol to use. Defaults to ``HIGHEST_PROTOCOL``.

    .. seealso:: https://docs.python.org/3.6/library/pickle.html#data-stream-format
    """
    raise_for_not_bel(graph)
    nx.write_gpickle(graph, path, protocol=protocol) 
开发者ID:pybel,项目名称:pybel,代码行数:16,代码来源:gpickle.py

示例5: saveRealGraphSeries

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import write_gpickle [as 别名]
def saveRealGraphSeries(G, file_prefix='graphs/day_'):
    for idx in range(len(G)):
        f_name = file_prefix + str(idx) + "_graph.gpickle"
        # cPickle.dump(G[idx], open(f_name, 'wb'))
        nx.write_gpickle(G[idx], f_name) 
开发者ID:palash1992,项目名称:GEM-Benchmark,代码行数:7,代码来源:graph_util.py

示例6: saveDynamicSBmGraph

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import write_gpickle [as 别名]
def saveDynamicSBmGraph(file_perfix, dynamic_graphs):
    length = len(dynamic_graphs)
    graph_files = ['%s_%d_graph.gpickle' % (file_perfix, i) for i in xrange(length)]
    info_files = ['%s_%d_node.pkl' % (file_perfix, i) for i in xrange(length)]

    for i in xrange(length):
        # save graph
        nx.write_gpickle(dynamic_graphs[i][0], graph_files[i])
        # save additional node info
        with open(info_files[i], 'wb') as fp:
            node_infos = {}
            node_infos['community'] = dynamic_graphs[i][1]
            node_infos['perturbation'] = dynamic_graphs[i][2]
            pickle.dump(node_infos, fp) 
开发者ID:palash1992,项目名称:GEM-Benchmark,代码行数:16,代码来源:graph_util.py

示例7: save_network

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import write_gpickle [as 别名]
def save_network(self, **kwargs):
        if 'output_file' in kwargs:
            output_file = kwargs['output_file']
        else:
            output_file = os.path.join(os.getcwd(), self.path_to_network_file + '.gpickle')

        nx.write_gpickle(self.graph, output_file) 
开发者ID:baryshnikova-lab,项目名称:safepy,代码行数:9,代码来源:safe.py

示例8: cached_reading_graph_edges

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import write_gpickle [as 别名]
def cached_reading_graph_edges(self):
        """
        Checks if networkx and edges dictionary pickles are present. If they are older than
        CACHING_RETENTION_MINUTES, make fresh pickles, else read them from the files.
        """
        cache_dir = os.path.join(settings.home_dir, 'cache')
        if not os.path.exists(cache_dir):
            os.mkdir(cache_dir)
        cache_edges_filename = os.path.join(cache_dir, 'graph.gpickle')
        cache_graph_filename = os.path.join(cache_dir, 'edges.gpickle')

        try:
            timestamp_graph = os.path.getmtime(cache_graph_filename)
        except FileNotFoundError:
            timestamp_graph = 0  # set very old timestamp

        if timestamp_graph < time.time() - settings.CACHING_RETENTION_MINUTES * 60:  # old graph in file
            logger.info(f"Saved graph is too old. Fetching new one.")
            self.set_graph_and_edges()
            nx.write_gpickle(self.graph, cache_graph_filename)
            with open(cache_edges_filename, 'wb') as file:
                pickle.dump(self.edges, file)
        else:  # recent graph in file
            logger.info("Reading graph from file.")
            self.graph = nx.read_gpickle(cache_graph_filename)
            with open(cache_edges_filename, 'rb') as file:
                self.edges = pickle.load(file) 
开发者ID:bitromortac,项目名称:lndmanage,代码行数:29,代码来源:network.py

示例9: save_cpnet

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import write_gpickle [as 别名]
def save_cpnet():
    global concept2id, relation2id, id2relation, id2concept, blacklist
    load_resources()
    graph = nx.MultiDiGraph()
    with open(config["paths"]["conceptnet_en"], "r", encoding="utf8") as f:
        lines = f.readlines()

        def not_save(cpt):
            if cpt in blacklist:
                return True
            for t in cpt.split("_"):
                if t in nltk_stopwords:
                    return True
            return False

        for line in tqdm(lines, desc="saving to graph"):
            ls = line.strip().split('\t')
            rel = relation2id[ls[0]]
            subj = concept2id[ls[1]]
            obj = concept2id[ls[2]]
            weight = float(ls[3])
            if id2relation[rel] == "hascontext":
                continue
            if not_save(ls[1]) or not_save(ls[2]):
                continue
            if id2relation[rel] == "relatedto" or id2relation[rel] == "antonym":
                weight -= 0.3
                # continue
            if subj == obj: # delete loops
                continue
            weight = 1+float(math.exp(1-weight))
            graph.add_edge(subj, obj, rel=rel, weight=weight)
            graph.add_edge(obj, subj, rel=rel+len(relation2id), weight=weight)


    nx.write_gpickle(graph, config["paths"]["conceptnet_en_graph"])
    # with open(config["paths"]["conceptnet_en_graph"], 'w') as f:
    #     f.write(json.dumps(nx.node_link_data(graph))) 
开发者ID:INK-USC,项目名称:KagNet,代码行数:40,代码来源:graph_construction.py

示例10: nx_save_to_file

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import write_gpickle [as 别名]
def nx_save_to_file(self, graph, file_path='output-amazon.pkl'):
        nx.write_gpickle(graph, file_path) 
开发者ID:laugustyniak,项目名称:textlytics,代码行数:4,代码来源:amazon_review_network.py

示例11: saveDynamicSBmGraph

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import write_gpickle [as 别名]
def saveDynamicSBmGraph(file_perfix, dynamic_graphs):
    length = len(dynamic_graphs)
    graph_files = ['%s_%d_graph.gpickle' % (file_perfix, i) for i in range(length)]
    info_files = ['%s_%d_node.pkl' % (file_perfix, i) for i in range(length)]

    for i in xrange(length):
        # save graph
        nx.write_gpickle(dynamic_graphs[i][0], graph_files[i])
        # save additional node info
        with open(info_files[i], 'wb') as fp:
            node_infos = {}
            node_infos['community'] = dynamic_graphs[i][1]
            node_infos['perturbation'] = dynamic_graphs[i][2]
            pickle.dump(node_infos, fp) 
开发者ID:palash1992,项目名称:GEM,代码行数:16,代码来源:graph_util.py

示例12: write_gpickle

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import write_gpickle [as 别名]
def write_gpickle(G, path, protocol=pickle.HIGHEST_PROTOCOL):
    """Write graph in Python pickle format.

    Pickles are a serialized byte stream of a Python object [1]_.
    This format will preserve Python objects used as nodes or edges.

    Parameters
    ----------
    G : graph
       A NetworkX graph

    path : file or string
       File or filename to write.
       Filenames ending in .gz or .bz2 will be compressed.

    protocol : integer
        Pickling protocol to use. Default value: ``pickle.HIGHEST_PROTOCOL``.

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> nx.write_gpickle(G, "test.gpickle")

    References
    ----------
    .. [1] http://docs.python.org/library/pickle.html
    """
    pickle.dump(G, path, protocol) 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:30,代码来源:gpickle.py

示例13: read_gpickle

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import write_gpickle [as 别名]
def read_gpickle(path):
    """Read graph object in Python pickle format.

    Pickles are a serialized byte stream of a Python object [1]_.
    This format will preserve Python objects used as nodes or edges.

    Parameters
    ----------
    path : file or string
       File or filename to write.
       Filenames ending in .gz or .bz2 will be uncompressed.

    Returns
    -------
    G : graph
       A NetworkX graph

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> nx.write_gpickle(G, "test.gpickle")
    >>> G = nx.read_gpickle("test.gpickle")

    References
    ----------
    .. [1] http://docs.python.org/library/pickle.html
    """
    return pickle.load(path)

# fixture for nose tests 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:32,代码来源:gpickle.py

示例14: test_gpickle

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import write_gpickle [as 别名]
def test_gpickle(self):
        for G in [self.G, self.DG, self.MG, self.MDG,
                  self.fG, self.fDG, self.fMG, self.fMDG]:
            (fd,fname)=tempfile.mkstemp()
            nx.write_gpickle(G,fname)
            Gin=nx.read_gpickle(fname)
            assert_nodes_equal(G.nodes(data=True),
                                Gin.nodes(data=True))
            assert_edges_equal(G.edges(data=True),
                                Gin.edges(data=True))
            assert_graphs_equal(G, Gin)
            os.close(fd)
            os.unlink(fname) 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:15,代码来源:test_gpickle.py

示例15: test_protocol

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import write_gpickle [as 别名]
def test_protocol(self):
        for G in [self.G, self.DG, self.MG, self.MDG,
                  self.fG, self.fDG, self.fMG, self.fMDG]:
            with tempfile.TemporaryFile() as f:
                nx.write_gpickle(G, f, 0)
                f.seek(0)
                Gin = nx.read_gpickle(f)
                assert_nodes_equal(G.nodes(data=True),
                                   Gin.nodes(data=True))
                assert_edges_equal(G.edges(data=True),
                                   Gin.edges(data=True))
                assert_graphs_equal(G, Gin) 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:14,代码来源:test_gpickle.py


注:本文中的networkx.write_gpickle方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。