Input and Output

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_lines(lines, manager=None, allow_nested=False, citation_clearing=True, **kwargs)[source]

Loads a BEL graph from an iterable over the lines of a BEL script

Parameters:
  • lines (iter[str]) – An iterable of strings (the lines in a BEL script)
  • manager (None or str or pybel.manager.Manager) – database connection string to cache, pre-built Manager, or None to use default cache
  • citation_clearing (bool) – Should SET Citation statements clear evidence and all annotations? Delegated to pybel.parser.ControlParser
  • kwargs (dict) – keyword arguments to pybel.io.line_utils.parse_lines()
Return type:

BELGraph

pybel.from_path(path, manager=None, allow_nested=False, citation_clearing=True, encoding='utf-8', **kwargs)[source]

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

Parameters:
  • path (str) – A file path
  • manager (None or str or pybel.manager.Manager) – database connection string to cache, pre-built Manager, or None to use default cache
  • allow_nested (bool) – if true, turn off nested statement failures
  • citation_clearing (bool) – Should SET Citation statements clear evidence and all annotations? Delegated to pybel.parser.ControlParser
  • encoding (str) – the encoding to use when reading this file. Is passed to codecs.open. See the python docs for a list of standard encodings. For example, files starting with a UTF-8 BOM should use utf_8_sig
  • kwargs (dict) – keyword arguments to pybel.io.line_utils.parse_lines()
Return type:

BELGraph

pybel.from_url(url, manager=None, allow_nested=False, citation_clearing=True, **kwargs)[source]

Loads a BEL graph from a URL resource. This function is a thin wrapper around from_lines().

Parameters:
  • url (str) – A valid URL pointing to a BEL resource
  • manager (None or str or pybel.manager.Manager) – database connection string to cache, pre-built Manager, or None to use default cache
  • allow_nested (bool) – if true, turn off nested statement failures
  • citation_clearing (bool) – Should SET Citation statements clear evidence and all annotations? Delegated to pybel.parser.ControlParser
  • kwargs (dict) – keyword arguments to pybel.io.line_utils.parse_lines()
Return type:

BELGraph

Canonicalization

pybel.to_bel_lines(graph)[source]

Returns an iterable over the lines of the BEL graph as a canonical BEL Script (.bel)

Parameters:graph (pybel.BELGraph) – the BEL Graph to output as a BEL Script
Returns:An iterable over the lines of the representative BEL script
Return type:iter[str]
pybel.to_bel(graph, file=None)[source]

Outputs the BEL graph as canonical BEL to the given file/file-like/stream. Defaults to standard out.

Parameters:
  • graph (BELGraph) – the BEL Graph to output as a BEL Script
  • file (file) – A writable file-like object. If None, defaults to standard out.
pybel.to_bel_path(graph, path)[source]

Writes the BEL graph as a canonical BEL Script to the given path

Parameters:
  • graph (BELGraph) – the BEL Graph to output as a BEL Script
  • path (str) – A file path

Transport

All transport pairs are reflective and data-preserving.

Bytes

This module contains IO functions for interconversion between BEL graphs and python pickle objects

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

Reads a graph from a gpickle file.

Parameters:
  • or str path (file) – 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
Returns:

A BEL graph

Return type:

BELGraph

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

Writes 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
  • or file (str) – A file or filename to write to
  • protocol (int) – Pickling protocol to use
pybel.from_bytes(bytes_graph, check_version=True)[source]

Reads 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
Returns:

A BEL graph

Return type:

BELGraph

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

Converts 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
Returns:

Pickled bytes representing the graph

Return type:

bytes

pybel.from_json(graph_json_dict, check_version=True)[source]

Builds a graph from Node-Link JSON Object

Parameters:
  • graph_json_dict (dict) – A JSON dictionary representing a graph
  • check_version (bool) – Checks if the graph was produced by this version of PyBEL
Returns:

A BEL graph

Return type:

BELGraph

pybel.to_json(graph)[source]

Converts this graph to a Node-Link JSON object

Parameters:graph (BELGraph) – A BEL graph
Returns:A Node-Link JSON object representing the given graph
Return type:dict
pybel.from_json_file(file, check_version=True)[source]

Builds a graph from the Node-Link JSON contained in the given file

Parameters:
  • file (file) – A readable file or file-like
  • check_version (bool) – Checks if the graph was produced by this version of PyBEL
Returns:

A BEL graph

Return type:

BELGraph

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

Writes this graph as Node-Link JSON to a file

Parameters:
  • graph (BELGraph) – A BEL graph
  • file (file) – A write-supporting file or file-like object
pybel.from_jsons(graph_json_str, check_version=True)[source]

Reads a BEL graph from a Node-Link JSON string

Parameters:
  • graph_json_str (str) – A Node-Link JSON string produced by PyBEL
  • check_version (bool) – Checks if the graph was produced by this version of PyBEL
Returns:

A BEL graph

Return type:

BELGraph

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

Dumps this graph as a Node-Link JSON object to a string

Parameters:graph (BELGraph) – A BEL graph
Returns:A string representation of the Node-Link JSON produced for this graph by pybel.to_json()
Return type:str

JSON Graph Interchange Format

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]

Builds a BEL graph from a JGIF JSON object.

Parameters:graph_jgif_dict (dict) – The JSON object representing the graph in JGIF format
Returns:A BEL graph
Return type:BELGraph
pybel.from_cbn_jgif(graph_jgif_dict)[source]

Maps 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
Returns:A BEL graph
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)
pybel.to_jgif(graph)[source]

Builds a JGIF dictionary from a BEL graph.

Parameters:graph (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_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)

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]

Rebuilds a BELGraph from CX JSON output from PyBEL

Parameters:cx (list) – The CX JSON for this graph
Return type:BELGraph
pybel.to_cx(graph)[source]

Converts BEL Graph to CX data format (as in-memory JSON) for use with NDEx

Parameters:graph (BELGraph) – A BEL Graph
Returns:The CX JSON for this graph
Return type:list
pybel.from_cx_file(file)[source]

Reads a file containing CX JSON and converts to a BEL graph

Parameters:file (file) – A readable file or file-like containing the CX JSON for this graph
Returns:A BEL Graph representing the CX graph contained in the file
Return type:BELGraph
pybel.to_cx_file(graph, file, indent=2, **kwargs)[source]

Writes this graph to a JSON file in CX format

Parameters:
  • graph (BELGraph) – A BEL graph
  • file (file) – 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 import from_url, to_cx_file
>>> from pybel.constants import SMALL_CORPUS_URL
>>> graph = from_url(SMALL_CORPUS_URL)
>>> with open('graph.cx', 'w') as f:
>>> ... to_cx_file(graph, f)
pybel.from_cx_jsons(graph_cx_json_str)[source]

Reconstitutes a BEL graph from a CX JSON string

Parameters:graph_cx_json_str (str) – CX JSON string
Returns:A BEL graph representing the CX graph contained in the string
Return type:BELGraph
pybel.to_cx_jsons(graph, **kwargs)[source]

Dumps a BEL graph as CX JSON to a string

Parameters:graph (BELGraph) – A BEL Graph
Returns:CX JSON string
Return type:str

Export

pybel.to_graphml(graph, file)[source]

Writes this graph to GraphML XML file using networkx.write_graphml(). The .graphml file extension is suggested so Cytoscape can recognize it.

Parameters:
  • graph (BELGraph) – A BEL graph
  • file (file) – A file or file-like object
pybel.to_csv(graph, file=None, sep='\t')[source]

Writes the graph as a tab-separated edge list with the 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.

Parameters:
  • graph (BELGraph) – A BEL graph
  • file (file) – A writable file or file-like. Defaults to stdout.
  • sep (str) – The separator. Defaults to tab.
pybel.to_sif(graph, file=None, sep='\t')[source]

Writes the graph as a tab-separated SIF file with 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.

Parameters:
  • graph (BELGraph) – A BEL graph
  • file (file) – A writable file or file-like. Defaults to stdout.
  • sep (str) – The separator. Defaults to tab.
pybel.to_gsea(graph, file=None)[source]

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

Parameters:
  • graph (BELGraph) – A BEL graph
  • file (file) – A writeable file or file-like object. Defaults to stdout.

See also

Database

SQL Database

This module provides IO functions to the relational edge store.

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

Loads 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 (str) – The version string of the graph. If not specified, loads most recent graph added with this name
  • connection (None or str or pybel.manager.Manager) – An RFC-1738 database connection string, a pre-built Manager, or None for default connection
Returns:

A BEL graph loaded from the database

Return type:

BELGraph

pybel.to_database(graph, connection=None, store_parts=True)[source]

Stores a graph in a database.

Parameters:
  • graph (BELGraph) – A BEL graph
  • connection (None or str or pybel.manager.Manager) – An RFC-1738 database connection string, a pre-built Manager, or None` for default connection
  • store_parts (bool) – Should the graph be stored in the edge store?

Neo4j

This module contains IO functions for outputting BEL graphs to a Neo4J graph database

pybel.to_neo4j(graph, neo_connection, context=None)[source]

Uploads a BEL graph to Neo4J graph database using py2neo

Parameters:
  • graph (BELGraph) – A BEL Graph
  • neo_connection (py2neo.Graph) – A py2neo connection object. Refer to the py2neo documentation for how to build this object.
  • context (str) – A disease context to allow for multiple disease models in one neo4j instance. Each edge will be assigned an attribute pybel_context with this value

Example Usage:

>>> import pybel, py2neo
>>> url = 'http://resource.belframework.org/belframework/1.0/knowledge/small_corpus.bel'
>>> g = pybel.from_url(url)
>>> neo_graph = py2neo.Graph("http://localhost:7474/db/data/")  # use your own connection settings
>>> pybel.to_neo4j(g, neo_graph)

Network Data Exchange (NDEx)

This package provides a wrapper around pybel.to_cx() and NDEx client to allow for easy upload and download of BEL documents to the NDEx database.

The programmatic API also provides options for specifying username and password. By default, it checks the environment variables: NDEX_USERNAME and NDEX_PASSWORD.

pybel.from_ndex(network_id, username=None, password=None, debug=False)[source]

Downloads a BEL Graph from NDEx

Warning

This function only will work for CX documents that have been originally exported from PyBEL

Parameters:
  • network_id (str) – The UUID assigned to the network by NDEx
  • username (str) – NDEx username
  • password (str) – NDEx password
  • debug (bool) – If true, turn on NDEx client debugging
Returns:

A BEL graph

Return type:

BELGraph

Example Usage:

>>> from pybel import from_ndex
>>> network_id = '1709e6f3-04a1-11e7-aba2-0ac135e8bacf'
>>> graph = from_ndex(network_id)
pybel.to_ndex(graph, username=None, password=None, debug=False)[source]

Uploads a BEL graph to NDEx

Parameters:
  • graph (BELGraph) – A BEL graph
  • username (str) – NDEx username
  • password (str) – NDEx password
  • debug (bool) – If true, turn on NDEx client debugging
Returns:

The UUID assigned to the network by NDEx

Return type:

str

Example Usage:

>>> import pybel
>>> graph = pybel.from_url('http://resources.openbel.org/belframework/20150611/knowledge/small_corpus.bel')
>>> pybel.to_ndex(graph)

PyBEL Web

This module facilitates rudimentary data exchange with PyBEL Web.

pybel.io.web.to_web(graph, host=None)[source]

Sends a graph to the receiver service and returns the requests response object

Parameters:
  • graph (pybel.BELGraph) – A BEL network
  • host (str) – The location of the PyBEL web server. Defaults to DEFAULT_SERVICE_URL
Returns:

The response object from requests

Return type:

requests.Response

pybel.io.web.from_web(network_id, service=None)[source]

Retrieves a public network from PyBEL Web. In the future, this function may be extended to support authentication.

Parameters:
  • network_id (int) – The PyBEL web network identifier
  • service – The location of the PyBEL web server. Defaults to DEFAULT_SERVICE_URL
Return type:

pybel.BELGraph

Warning

This is not implemented yet.

INDRA

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

from indra.assemblers 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')
pybel.io.indra.from_indra_statements(statements, name=None, version=None, description=None)[source]

Imports a model from indra.

Parameters:
  • statments (list[indra.statement.Statements]) – A list of statements
  • name (str) – The name for the BEL graph
  • version (str) – The version of the BEL graph
  • description (str) – The description of the BEL graph
Return type:

pybel.BELGraph

pybel.io.indra.from_indra_pickle(path, name=None, version=None, description=None)[source]

Imports a model from indra.

Parameters:
  • path (str) – Path to pickled list of indra.statements.Statement
  • name (str) – The name for the BEL graph
  • version (str) – The version of the BEL graph
  • description (str) – The description of the BEL graph
Return type:

pybel.BELGraph

pybel.io.indra.to_indra(graph)[source]

Exports this graph as a list of INDRA statements.

Parameters:graph (pybel.BELGraph) – A BEL graph
Return type:list[indra.statements.Statement]

Warning

Not implemented yet!

pybel.io.indra.from_biopax(path, name=None, version=None, description=None)[source]

Imports a model encoded in BioPAX via indra.

Parameters:
  • path (str) – Path to a BioPAX OWL file
  • name (str) – The name for the BEL graph
  • version (str) – The version of the BEL graph
  • description (str) – The description of the BEL graph
Return type:

pybel.BELGraph