Input and Output

Input and output functions for BEL graphs.

PyBEL provides multiple lossless interchange options for BEL. Lossy output formats are also included for convenient export to other programs. Notably, a de facto interchange using Resource Description Framework (RDF) to match the ability of other existing software is excluded due the immaturity of the BEL to RDF mapping.

Import

Parsing Modes

The PyBEL parser has several modes that can be enabled and disabled. They are described below.

Allow Naked Names

By default, this is set to False. The parser does not allow identifiers that are not qualified with namespaces (naked names), like in p(YFG). A proper namespace, like p(HGNC:YFG) must be used. By setting this to True, the parser becomes permissive to naked names. In general, this is bad practice and this feature will be removed in the future.

Allow Nested

By default, this is set to False. The parser does not allow nested statements is disabled. See overview. By setting this to True the parser will accept nested statements one level deep.

Citation Clearing

By default, this is set to True. While the BEL specification clearly states how the language should be used as a state machine, many BEL documents do not conform to the strict SET/UNSET rules. To guard against annotations accidentally carried from one set of statements to the next, the parser has two modes. By default, in citation clearing mode, when a SET CITATION command is reached, it will clear all other annotations (except the STATEMENT_GROUP, which has higher priority). This behavior can be disabled by setting this to False to re-enable strict parsing.

Reference

pybel.from_bel_script(path, **kwargs)[source]

Load a BEL graph from a file resource. This function is a thin wrapper around from_lines().

Parameters

path (Union[str, TextIO]) – A path or file-like

The remaining keyword arguments are passed to pybel.io.line_utils.parse_lines(), which populates a BELGraph.

Return type

BELGraph

pybel.from_bel_script_url(url, **kwargs)[source]

Load a BEL graph from a URL resource.

Parameters

url (str) – A valid URL pointing to a BEL document

The remaining keyword arguments are passed to pybel.io.line_utils.parse_lines().

Return type

BELGraph

pybel.to_bel_script(graph, path)[source]

Write the BELGraph as a canonical BEL script.

Parameters
  • graph (BELGraph) – the BEL Graph to output as a BEL Script

  • path (Union[str, TextIO]) – A path or file-like.

Return type

None

Transport

All transport pairs are reflective and data-preserving.

Bytes

Conversion functions for BEL graphs with bytes and Python pickles.

pybel.from_bytes(bytes_graph, check_version=True)[source]

Read a graph from bytes (the result of pickling the graph).

Parameters
  • bytes_graph (bytes) – File or filename to write

  • check_version (bool) – Checks if the graph was produced by this version of PyBEL

Return type

BELGraph

pybel.to_bytes(graph, protocol=4)[source]

Convert a graph to bytes with pickle.

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

Parameters
  • graph (BELGraph) – A BEL network

  • protocol (int) – Pickling protocol to use. Defaults to HIGHEST_PROTOCOL.

Return type

bytes

pybel.from_pickle(path, check_version=True)[source]

Read a graph from a pickle file.

Parameters
  • path (Union[str, BinaryIO]) – File or filename to read. Filenames ending in .gz or .bz2 will be uncompressed.

  • check_version (bool) – Checks if the graph was produced by this version of PyBEL

Return type

BELGraph

pybel.to_pickle(graph, path, protocol=4)[source]

Write this graph to a pickle object with 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.

Parameters
  • graph (BELGraph) – A BEL graph

  • path (Union[str, BinaryIO]) – A path or file-like

  • protocol (int) – Pickling protocol to use. Defaults to HIGHEST_PROTOCOL.

Return type

None

Cyberinfrastructure Exchange

This module wraps conversion between pybel.BELGraph and the Cyberinfrastructure Exchange (CX) JSON.

CX is an aspect-oriented network interchange format encoded in JSON with a format inspired by the JSON-LD encoding of Resource Description Framework (RDF). It is primarily used by the Network Data Exchange (NDEx) and more recent versions of Cytoscape.

See also

pybel.from_cx(cx)[source]

Rebuild a BELGraph from CX JSON output from PyBEL.

Parameters

cx (List[Dict]) – The CX JSON for this graph

Return type

BELGraph

pybel.to_cx(graph)[source]

Convert a BEL Graph to a CX JSON object for use with NDEx.

Return type

List[Dict]

pybel.from_cx_jsons(graph_json_str)[source]

Read a BEL graph from a CX JSON string.

Return type

BELGraph

pybel.to_cx_jsons(graph, **kwargs)[source]

Dump this graph as a CX JSON object to a string.

Return type

str

pybel.from_cx_file(path)[source]

Read a file containing CX JSON and converts to a BEL graph.

Parameters

path (Union[str, TextIO]) – A readable file or file-like containing the CX JSON for this graph

Return type

BELGraph

Returns

A BEL Graph representing the CX graph contained in the file

pybel.to_cx_file(graph, path, indent=2, **kwargs)[source]

Write a BEL graph to a JSON file in CX format.

Parameters
  • graph (BELGraph) – A BEL graph

  • path (Union[str, TextIO]) – A writable file or file-like

  • indent (Optional[int]) – How many spaces to use to pretty print. Change to None for no pretty printing

Example: >>> from pybel.examples import sialic_acid_graph >>> from pybel import to_cx_file >>> with open(‘graph.cx’, ‘w’) as f: >>> … to_cx_file(sialic_acid_graph, f)

Return type

None

pybel.from_cx_gz(path)[source]

Read a graph as CX JSON from a gzip file.

Return type

BELGraph

pybel.to_cx_gz(graph, path, **kwargs)[source]

Write a graph as CX JSON to a gzip file.

Return type

None

JSON Graph Interchange Format

Conversion functions for BEL graphs with JGIF JSON.

The JSON Graph Interchange Format (JGIF) is specified similarly to the Node-Link JSON. Interchange with this format provides compatibilty with other software and repositories, such as the Causal Biological Network Database.

pybel.from_jgif(graph_jgif_dict)[source]

Build a BEL graph from a JGIF JSON object.

Parameters

graph_jgif_dict (dict) – The JSON object representing the graph in JGIF format

Return type

BELGraph

pybel.to_jgif(graph)[source]

Build a JGIF dictionary from a BEL graph.

Parameters

graph (pybel.BELGraph) – A BEL graph

Returns

A JGIF dictionary

Return type

dict

Warning

Untested! This format is not general purpose and is therefore time is not heavily invested. If you want to use Cytoscape.js, we suggest using pybel.to_cx() instead.

Example: >>> import pybel, os, json >>> graph_url = ‘https://arty.scai.fraunhofer.de/artifactory/bel/knowledge/selventa-small-corpus/selventa-small-corpus-20150611.bel’ >>> graph = pybel.from_bel_script_url(graph_url) >>> graph_jgif_json = pybel.to_jgif(graph) >>> with open(os.path.expanduser(‘~/Desktop/small_corpus.json’), ‘w’) as f: … json.dump(graph_jgif_json, f)

pybel.from_jgif_jsons(graph_json_str)[source]

Read a BEL graph from a JGIF JSON string.

Return type

BELGraph

pybel.to_jgif_jsons(graph, **kwargs)[source]

Dump this graph as a JGIF JSON object to a string.

Return type

str

pybel.from_jgif_file(path)[source]

Build a graph from the JGIF JSON contained in the given file.

Parameters

path (Union[str, TextIO]) – A path or file-like

Return type

BELGraph

pybel.to_jgif_file(graph, file, **kwargs)[source]

Write JGIF to a file.

Return type

None

pybel.from_jgif_gz(path)[source]

Read a graph as JGIF JSON from a gzip file.

Return type

BELGraph

pybel.to_jgif_gz(graph, path, **kwargs)[source]

Write a graph as JGIF JSON to a gzip file.

Return type

None

pybel.post_jgif(graph, url=None, **kwargs)[source]

Post the JGIF to a given URL.

Return type

Response

pybel.from_cbn_jgif(graph_jgif_dict)[source]

Build a BEL graph from CBN JGIF.

Map the JGIF used by the Causal Biological Network Database to standard namespace and annotations, then builds a BEL graph using pybel.from_jgif().

Parameters

graph_jgif_dict (dict) – The JSON object representing the graph in JGIF format

Return type

BELGraph

Example: >>> import requests >>> from pybel import from_cbn_jgif >>> apoptosis_url = ‘http://causalbionet.com/Networks/GetJSONGraphFile?networkId=810385422’ >>> graph_jgif_dict = requests.get(apoptosis_url).json() >>> graph = from_cbn_jgif(graph_jgif_dict)

Warning

Handling the annotations is not yet supported, since the CBN documents do not refer to the resources used to create them. This may be added in the future, but the annotations must be stripped from the graph before uploading to the network store using pybel.struct.mutation.strip_annotations().

Export

GraphML

Conversion functions for BEL graphs with GraphML.

pybel.to_graphml(graph, path, schema=None)[source]

Write a graph to a GraphML XML file using networkx.write_graphml().

Parameters
  • graph (BELGraph) – BEL Graph

  • path (Union[str, BinaryIO]) – Path to the new exported file

  • schema (Optional[str]) – Type of export. Currently supported: “simple” and “umbrella”.

The .graphml file extension is suggested so Cytoscape can recognize it. By default, this function exports using the PyBEL schema of including modifier information into the edges. As an alternative, this function can also distinguish between

Return type

None

Miscellaneous

This module contains IO functions for outputting BEL graphs to lossy formats, such as GraphML and CSV.

pybel.to_csv(graph, path, sep=None)[source]

Write the graph as a tab-separated edge list.

The resulting file will contain the following columns:

  1. Source BEL term

  2. Relation

  3. Target BEL term

  4. Edge data dictionary

See the Data Models section of the documentation for which data are stored in the edge data dictionary, such as queryable information about transforms on the subject and object and their associated metadata.

Return type

None

pybel.to_sif(graph, path, sep=None)[source]

Write the graph as a tab-separated SIF file.

The resulting file will contain the following columns:

  1. Source BEL term

  2. Relation

  3. Target BEL term

This format is simple and can be used readily with many applications, but is lossy in that it does not include relation metadata.

Return type

None

pybel.to_gsea(graph, path)[source]

Write the genes/gene products to a GRP file for use with GSEA gene set enrichment analysis.

See also

Return type

None

pybel.to_tsv(graph, path, *, use_tqdm=False, sep='\t')[source]

Write the graph as a TSV.

Parameters
  • graph (BELGraph) – A BEL graph

  • path (Union[str, TextIO]) – A path or file-like

  • use_tqdm (bool) – Should a progress bar be shown?

  • sep – The separator to use

Return type

None

Databases

SQL Databases

Conversion functions for BEL graphs with a SQL database.

pybel.from_database(name, version=None, manager=None)[source]

Load a BEL graph from a database.

If name and version are given, finds it exactly with pybel.manager.Manager.get_network_by_name_version(). If just the name is given, finds most recent with pybel.manager.Manager.get_network_by_name_version()

Parameters
  • name (str) – The name of the graph

  • version (Optional[str]) – The version string of the graph. If not specified, loads most recent graph added with this name

Returns

A BEL graph loaded from the database

Return type

Optional[BELGraph]

pybel.to_database(graph, manager=None, use_tqdm=False)[source]

Store a graph in a database.

Parameters

graph (BELGraph) – A BEL graph

Returns

If successful, returns the network object from the database.

Return type

Optional[Network]

Neo4j

Output functions for BEL graphs to Neo4j.

pybel.to_neo4j(graph, neo_connection, use_tqdm=False)[source]

Upload a BEL graph to a Neo4j graph database using py2neo.

Parameters

Example Usage:

>>> import py2neo
>>> import pybel
>>> from pybel.examples import sialic_acid_graph
>>> neo_graph = py2neo.Graph("http://localhost:7474/db/data/")  # use your own connection settings
>>> pybel.to_neo4j(sialic_acid_graph, neo_graph)

BEL Commons

This module facilitates rudimentary data exchange with BEL Commons.

pybel.from_web(network_id, host=None)[source]

Retrieve a public network from BEL Commons.

In the future, this function may be extended to support authentication.

Parameters
  • network_id (int) – The BEL Commons network identifier

  • host (Optional[str]) – The location of the BEL Commons server. Alternatively, looks up in PyBEL config with PYBEL_REMOTE_HOST or the environment as PYBEL_REMOTE_HOST Defaults to pybel.constants.DEFAULT_SERVICE_URL

Return type

BELGraph

pybel.to_web(graph, host=None, user=None, password=None, public=False)[source]

Send a graph to the receiver service and returns the requests response object.

Parameters
  • graph (BELGraph) – A BEL graph

  • host (Optional[str]) – The location of the BEL Commons server. Alternatively, looks up in PyBEL config with PYBEL_REMOTE_HOST or the environment as PYBEL_REMOTE_HOST Defaults to pybel.constants.DEFAULT_SERVICE_URL

  • user (Optional[str]) – Username for BEL Commons. Alternatively, looks up in PyBEL config with PYBEL_REMOTE_USER or the environment as PYBEL_REMOTE_USER

  • password (Optional[str]) – Password for BEL Commons. Alternatively, looks up in PyBEL config with PYBEL_REMOTE_PASSWORD or the environment as PYBEL_REMOTE_PASSWORD

Return type

Response

Returns

The response object from requests

INDRA

Conversion functions for BEL graphs with INDRA.

After assembling a model with INDRA, a list of indra.statements.Statement can be converted to a pybel.BELGraph with indra.assemblers.pybel.PybelAssembler.

from indra.assemblers.pybel import PybelAssembler
import pybel

stmts = [
    # A list of INDRA statements
]

pba = PybelAssembler(
    stmts,
    name='Graph Name',
    version='0.0.1',
    description='Graph Description'
)
graph = pba.make_model()

# Write to BEL file
pybel.to_bel_path(belgraph, 'simple_pybel.bel')

Warning

These functions are hard to unit test because they rely on a whole set of java dependencies and will likely not be for a while.

pybel.from_indra_statements(stmts, name=None, version=None, description=None, authors=None, contact=None, license=None, copyright=None, disclaimer=None)[source]

Import a model from indra.

Parameters
  • stmts (List[indra.statements.Statement]) – A list of statements

  • name (Optional[str]) – The graph’s name

  • version (Optional[str]) – The graph’s version. Recommended to use semantic versioning or YYYYMMDD format.

  • description (Optional[str]) – The description of the graph

  • authors (Optional[str]) – The authors of this graph

  • contact (Optional[str]) – The contact email for this graph

  • license (Optional[str]) – The license for this graph

  • copyright (Optional[str]) – The copyright for this graph

  • disclaimer (Optional[str]) – The disclaimer for this graph

Return type

pybel.BELGraph

pybel.to_indra_statements(graph)[source]

Export this graph as a list of INDRA statements using the indra.sources.pybel.PybelProcessor.

Parameters

graph (pybel.BELGraph) – A BEL graph

Return type

list[indra.statements.Statement]

pybel.from_biopax(path, name=None, version=None, description=None, authors=None, contact=None, license=None, copyright=None, disclaimer=None)[source]

Import a model encoded in Pathway Commons BioPAX via indra.

Parameters
  • path (str) – Path to a BioPAX OWL file

  • name (Optional[str]) – The name for the BEL graph

  • version (Optional[str]) – The version of the BEL graph

  • description (Optional[str]) – The description of the graph

  • authors (Optional[str]) – The authors of this graph

  • contact (Optional[str]) – The contact email for this graph

  • license (Optional[str]) – The license for this graph

  • copyright (Optional[str]) – The copyright for this graph

  • disclaimer (Optional[str]) – The disclaimer for this graph

Return type

pybel.BELGraph

Warning

Not compatible with all BioPAX! See INDRA documentation.