NiceCXNetwork

Note

Using the newer data model CX2Network is encouraged since all networks on NDEx can be retrieved in newer CX2 format via the NDEx REST Service

The NiceCXNetwork class provides a data model for working with NDEx networks that are stored in the legacy CX format

The term niceCX is CX with no duplicate aspects.

Methods are provided to add nodes, edges, node attributes, edge attributes, etc. Once a NiceCXNetwork object is populated it can be saved to the NDEx server by calling either upload_to() to create a new network or update_to() to update an existing network.

Methods

Example usage of the methods below can be found in the Jupyter notebook links here:

Tutorial Notebook Navigating NiceCXNetwork Notebook

Node methods

class ndex2.nice_cx_network.NiceCXNetwork(**attr)[source]
create_node(node_name=None, node_represents=None)[source]

Creates a new node with the corresponding name and represents (external id)

Warning

Version 3.3.1 and prior of this library had a bug that caused this method to behave incorrectly. Please upgrade to 3.3.2 or greater.

Example:

my_node = create_node(node_name='MAPK1, node_represents='1114208')

Parameters:
  • node_name (str) – Name of the node

  • node_represents (str) – Representation of the node (alternate identifier)

Returns:

Node ID

Return type:

int

get_node_attribute(node, attribute_name)[source]

Get the node attribute of a node, where the node may be specified by its id or passed in as an object.

Example:

get_node_attribute(my_node, 'Pathway') # returns: {'@id': 0, 'n': 'diffusion-heat', 'v': 0.832, 'd': 'double'}

Parameters:
  • node (int or node dict with @id attribute) – node object or node id

  • attribute_name – attribute name

Returns:

the node attibute object or None if the attribute doesn’t exist

Return type:

dict

get_node_attribute_value(node, attribute_name)[source]

Get the value(s) of an attribute of a node, where the node may be specified by its id or passed in as an object.

Example:

get_node_attribute_value(my_node, 'Pathway') # returns: 'Signal Transduction / Growth Regulation'

Parameters:
  • node (int or node dict with @id attribute) – node object or node id

  • attribute_name – attribute name

Returns:

the value of the attibute or None if the attribute doesn’t exist

Return type:

string

get_node_attributes(node)[source]

Get the attribute objects of a node, where the node may be specified by its id or passed in as an object.

Example:

get_node_attributes(my_node) # returns: [{'po': 0, 'n': 'Pathway', 'v': 'Signal Transduction / Growth Regulation'}]

Parameters:

node (int or node dict with @id attribute) – node object or node id

Returns:

node attributes

Return type:

list

get_nodes()[source]

Returns an iterator over node ids as keys and node objects as values.

Example:

for id, node in nice_cx.get_nodes():

node_name = node.get('n')

node_represents = node.get('r')

Returns:

iterator over nodes

Return type:

iterator

set_node_attribute(node, attribute_name, values, type=None, overwrite=False)[source]

Set an attribute of a node, where the node may be specified by its id or passed in as a node dict.

Example:

set_node_attribute(my_node, 'Pathway', 'Signal Transduction / Growth Regulation')

or

set_node_attribute(my_node, 'Mutation Frequency', 0.007, type='double')

Parameters:
  • node (int or node dict with @id attribute) – Node to add the attribute to

  • attribute_name (string) – attribute name

  • values (list, string, int or double) – A value or list of values of the attribute

  • type (str) – The datatype of the attribute values, defaults is string. See Supported data types

  • overwrite (bool True means to overwrite node attribute named attribute_name) – If True node attribute matching ‘attribute_name’ is removed first otherwise code blindly adds attribute

Returns:

None

Return type:

None

Edge methods

class ndex2.nice_cx_network.NiceCXNetwork(**attr)[source]
create_edge(edge_source=None, edge_target=None, edge_interaction=None)[source]

Create a new edge in the network by specifying source-interaction-target

Warning

Version 3.3.1 and prior of this library had a bug that caused this method to behave incorrectly. Please upgrade to 3.3.2 or greater.

Example:

my_edge = create_edge(edge_source=my_node, edge_target=my_node2, edge_interaction='up-regulates')

Parameters:
  • edge_source (int, dict (with EDGE_ID property)) – The source node of this edge, either its id or the node object itself.

  • edge_target (int, dict (with EDGE_ID property)) – The target node of this edge, either its id or the node object itself.

  • edge_interaction (string) – The interaction that describes the relationship between the source and target nodes

Returns:

Edge ID

Return type:

int

get_edge_attribute(edge, attribute_name)[source]

Get the edge attributes of an edge, where the edge may be specified by its id or passed in as an object.

Example:

get_edge_attribute(my_edge, 'weight')

# returns: {'@id': 0, 'n': 'weight', 'v': 0.849, 'd': 'double'}

Parameters:
  • edge (int or edge dict with @id attribute) – Edge object or edge id

  • attribute_name – Attribute name

Returns:

Edge attribute object

Return type:

list, string, int or double

get_edge_attribute_value(edge, attribute_name)[source]

Get the value(s) of an attribute of an edge, where the edge may be specified by its id or passed in as an object.

Example:

get_edge_attribute_value(my_edge, 'weight')

# returns: 0.849

Parameters:
  • edge (int or edge dict with @id attribute) – Edge object or edge id

  • attribute_name – Attribute name

Returns:

Edge attribute value(s)

Return type:

list, string, int or double

get_edge_attributes(edge)[source]

Get the attribute objects of an edge, where the edge may be specified by its id or passed in as an object.

Example:

get_edge_attributes(my_edge)

# returns: [{'@id': 0, 'n': 'weight', 'v': 0.849, 'd': 'double'}, {'@id': 0, 'n': 'Type', 'v': 'E1'}]

Parameters:

edge (int or edge dict with @id attribute) – Edge object or edge id

Returns:

Edge attribute objects

Return type:

list of edge dict

get_edges()[source]

Returns an iterator over edge ids as keys and edge objects as values.

Example:

for edge_id, edge_obj in nice_cx.get_edges():

print(edge_obj.get('i')) # print interaction

print(edge_obj.get('s')) # print source node id

Returns:

Edge iterator

Return type:

iterator

set_edge_attribute(edge, attribute_name, values, type=None)[source]

Set the value(s) of attribute of an edge, where the edge may be specified by its id or passed in an object.

Example:

set_edge_attribute(0, 'weight', 0.5, type='double')

or

set_edge_attribute(my_edge, 'Disease', 'Atherosclerosis')

Parameters:
  • edge (int or edge dict with @id attribute) – Edge to add the attribute to

  • attribute_name (str) – Attribute name

  • values (list) – A value or list of values of the attribute

  • type (str) – The datatype of the attribute values, defaults to the python datatype of the values. See Supported data types

Returns:

None

Return type:

None

Network methods

class ndex2.nice_cx_network.NiceCXNetwork(**attr)[source]
get_context()[source]

Get the @context information of the network. This information maps namespace prefixes to their defining URIs

Example:

{'pmid': 'https://www.ncbi.nlm.nih.gov/pubmed/'}

Returns:

context object

Return type:

dict

get_name()[source]

Get the network name

Returns:

Network name

Return type:

string

get_network_attribute(attribute_name)[source]

Get the value of a network attribute

Parameters:

attribute_name (string) – Attribute name

Returns:

Network attribute object

Return type:

dict

get_network_attribute_names()[source]

Creates a a generator that gets network attribute names.

Returns:

attribute name via a generator

Return type:

string

get_opaque_aspect(aspect_name)[source]

Get the elements of the aspect specified by aspect_name

Parameters:

aspect_name (string) – the name of the aspect to retrieve.

Returns:

Opaque aspect

Return type:

list of aspect elements

set_context(context)[source]

Set the @context information of the network. This information maps namespace prefixes to their defining URIs

Example:

from ndex2.nice_cx_network import NiceCXNetwork

net = NiceCXNetwork()
net.set_context({'pmid': 'https://www.ncbi.nlm.nih.gov/pubmed/'})
Parameters:

context (dict or list) – dict where key is name and value is URI or list of those dict objects

Raises:

NDExError – If context is not of type list or dict

Returns:

None

Return type:

none

set_name(network_name)[source]

Set the network name

Example:

set_name('P38 Signaling')

Parameters:

network_name (string) – Network name

Returns:

None

Return type:

None

set_network_attribute(name, values=None, type=None)[source]

Set an attribute of the network

from ndex2.nice_cx_network import NiceCXNetwork

net = NiceCXNetwork()
net.set_network_attribute(name='networkType', values='Genetic interactions')
Parameters:
Returns:

None

Return type:

none

set_opaque_aspect(aspect_name, aspect_elements)[source]

Set the aspect specified by aspect_name to the list of aspect elements. If aspect_elements is None, the aspect is removed.

Changed in version 3.5.0: Fixed bug where passing None in aspect_elements did NOT remove aspect. Code also now raises NDExError if input values are invalid

from ndex2.nice_cx_network import NiceCXNetwork
net = NiceCXNetwork()

# to set an opaque aspect
net.set_opaque_aspect('foo', [{'data': 'val'}])

# to remove an opaque aspect named 'foo'
net.set_opaque_aspect('foo', None)
Parameters:
  • aspect_name (str) – Name of the aspect

  • aspect_elements (list of dict or dict) – Aspect element

Raises:

NDExError – If aspect_name is None, or if aspect_elements is not None, dict, or list

Returns:

None

Return type:

none

Miscellaneous methods

class ndex2.nice_cx_network.NiceCXNetwork(**attr)[source]
apply_style_from_network(nicecxnetwork)[source]

Applies Cytoscape visual properties from the network passed into this method. The style is pulled from VISUAL_PROPERTIES or CY_VISUAL_PROPERTIES

Parameters:

nicecxnetwork (NiceCXNetwork) – Network to extract style from

Raises:
Returns:

None

Return type:

None

apply_template(server, uuid, username=None, password=None)[source]

Applies the Cytoscape visual properties of a network from the provided uuid to this network.

This allows the use of networks formatted in Cytoscape as templates to apply visual styles to other networks.

Changed in version 3.5.0: Fixed bug where style from template was appended instead of replacing the existing style. In most cases, method now raises NDExError and subclasses instead of more generic Exception

from ndex2.nice_cx_network import NiceCXNetwork

nice_cx = NiceCXNetwork()
nice_cx.apply_template('public.ndexbio.org',
                       '51247435-1e5f-11e8-b939-0ac135e8bacf')
Parameters:
  • server (str) – server host name (i.e. public.ndexbio.org)

  • username (str) – username (optional - used when accessing private networks)

  • password (str) – password (optional - used when accessing private networks)

  • uuid (str) – uuid of the styled network

Raises:
  • NDExError – Raised if server or uuid not set or if metaData is not found in the network specified by uuid or some other server error

  • NDExUnauthorizedError – If credentials not authorized to access network specified by uuid

  • NDExNotFoundError – If network with uuid not found

Returns:

None

Return type:

None

print_summary()[source]

Print a network summary

Returns:

Network summary

Return type:

string

to_cx(log_to_stdout=True)[source]

Return the CX corresponding to the network.

Changed in version 3.5.0: Added log_to_stdout param which lets caller silence print statement Generating CX

Parameters:

log_to_stdout (bool) – If True then code will output to standard out Generating CX

Returns:

CX representation of the network

Return type:

CX (list of dict aspects)

to_cx_stream()[source]

Returns a stream of the CX corresponding to the network. Can be used to post to endpoints that can accept streaming inputs

Returns:

The CX stream representation of this network.

Return type:

io.BytesIO

to_networkx(mode='legacy')[source]

Returns a NetworkX Graph() object or one of its subclasses based on the network. The mode parameter dictates how the translation occurs.

This method currently supports the following mode values:

Warning

legacy mode has known bugs when networkx 2.0+ or greater is installed.

See the description on legacy mode below for more information.

Modes:

legacy:

If mode set to legacy then this method will behave as it has for all versions of NDEx2 Python Client 3.1.0 and earlier which varies depending on version of networkx installed as described here:

For networkx 2.0 and greater: (see LegacyNetworkXVersionTwoPlusFactory)

For older versions of networkx the following class is used with the legacymode parameter set to True: (see DefaultNetworkXFactory)

default:

If mode is default or None then this method uses DefaultNetworkXFactory regardless of networkx installed with legacymode set to False

Note

default mode is the preferred mode to use

Examples:

# returns networkx graph using improved converter
graph = nice_cx.to_networkx(mode='default')

# returns networkx graph using legacy implementation
graph = nice_cx.to_networkx(mode='legacy)
Parameters:

mode (string) – Since translation to networkx can be done in many ways this mode lets the caller dictate the method.

Raises:

NDExError – If mode is not None, ‘legacy’, or ‘default’

Returns:

Networkx graph

Return type:

networkx.Graph or networkx.MultiGraph

to_pandas_dataframe(dataconverter=<ndex2.util.PandasDataConverter object>, include_attributes=False)[source]

Network edges exported as a pandas.DataFrame

Changed in version 3.5.0: Added include_attributes and dataconverter parameters

The following columns will be added to the pandas.DataFrame:

  • source - Name of edge source node

  • interaction - Interaction between source and target node

  • target - Name of edge target node

If include_attributes parameter is set to True then:

All edge attributes will be also added as separate columns with same name.

Attributes on source node will be added as a columns with source_ prefixed to name.

Attributes on target node will be added as columns with target_ prefixed to name.

Note

Values will converted based on CX data types. See PandasDataConverter for information on how conversion is performed

from ndex2.nice_cx_network import NiceCXNetwork

net = NiceCXNetwork()
node_one = net.create_node('node1')
node_two = net.create_node('node2')

net.set_node_attribute(node_one, 'weight', 0.5, type='double')
net.set_node_attribute(node_two, 'weight', 0.2, type='double')

edge_one = net.create_edge(edge_source=node_one, edge_target=node_two,
                           edge_interaction='binds')

net.set_edge_attribute(edge_one, 'edgelabel', 'an edge')
df = net.to_pandas_dataframe(include_attributes=True) # df is now a pandas dataframe

print(df.head())

Output from above code block:

   source interaction target edgelabel  target_weight  source_weight
0  node1       binds  node2   an edge            0.2            0.5

Note

This method only processes nodes, edges, node attributes and edge attributes, but not network attributes or other aspects

Parameters:
  • dataconverter (DataConverter) – Object that converts CX data values to native data types. Default is PandasDataConverter

  • include_attributes (bool) – If True then edge attributes are added to pandas.DataFrame, otherwise only source, target, and interaction are added

Raises:

NDExInvalidParameterError – If include_attributes is not None or a bool

Returns:

Edge table with attributes

Return type:

pandas.DataFrame

update_to(uuid, server=None, username=None, password=None, user_agent='', client=None)[source]

Replace the network on NDEx server with matching NDEx uuid with this network.

Changed in version 3.4.0: This method was switched to named arguments and the server and account credentials can be passed in one of two ways.

Option 1) Set username and password parameters.

Option 2) Set client parameter with valid Ndex2 object

Note

If client parameter is set, username, password, and server parameters are ignored.

Example:

import ndex2
nice_cx = ndex2.nice_cx_network.NiceCXNetwork()
nice_cx.create_node('foo')

# using production NDEx server
nice_cx.update_to('2ec87c51-c349-11e8-90ac-525400c25d22',
                  username=user_var,
                  password=password_var)

# if one needs to use alternate NDEx server
nice_cx.update_to('2ec87c51-c349-11e8-90ac-525400c25d22',
                  server='public.ndexbio.org',
                  username=username_var,
                  password=password_var)

# Option 2, create Ndex2 client object
ndex_client = ndex2.client.Ndex2(username=username_var,
                                 password=password_var)

# using NDEx client object for connection
nice_cx.update_to('2ec87c51-c349-11e8-90ac-525400c25d22',
                  client=ndex_client)
Parameters:
  • uuid (str) – UUID of the network on NDEx.

  • server (str) – The NDEx server to upload the network to. Leaving unset or None will use production.

  • username (str) – The username of the account to store the network.

  • password (str) – The password for the account.

  • user_agent (str) – String to append to User-Agent field sent to NDEx REST service

  • client (Ndex2) – NDEx2 object with valid credentials. If set server, username, and password parameters will be ignored.

Returns:

Empty string

Return type:

str

upload_to(server=None, username=None, password=None, user_agent='', client=None)[source]

Upload this network as a new network on NDEx server.

Changed in version 3.4.0: This method was switched to named arguments and the server and account credentials can be passed in one of two ways.

Option 1) Set username and password parameters.

Option 2) Set client parameter with valid Ndex2 object

Note

If client parameter is set, username, password, and server parameters are ignored

Example:

import ndex2
nice_cx = ndex2.nice_cx_network.NiceCXNetwork()
nice_cx.create_node('foo')

# using production NDEx server
nice_cx.update_to(username=user_var,
                  password=password_var)

# if one needs to use alternate NDEx server
nice_cx.update_to(server='public.ndexbio.org',
                  username=username_var,
                  password=password_var)

# Option 2, create Ndex2 client object
ndex_client = ndex2.client.Ndex2(username=username_var,
                                 password=password_var)

# using NDEx client object for connection
nice_cx.update_to(client=ndex_client)
Parameters:
  • server (str) – The NDEx server to upload the network to. Leaving unset or None will use production

  • username (str) – The username of the account to store the network.

  • password (str) – The password for the account.

  • user_agent (str) – String to append to User-Agent field sent to NDEx REST service

  • client (Ndex2) – NDEx2 object with valid credentials. If set server, username, and password parameters will be ignored.

Returns:

The UUID of the network on NDEx.

Return type:

str

Supported data types

The following CX Data Types are supported in methods that accept type

Example:

import ndex2
net = ndex2.nice_cx_network.NiceCXNetwork()
node_id = net.create_node('hi')
net.set_node_attribute(node_id, 'somevalue', 0.5, type='double')
  • string

  • double

  • boolean

  • integer

  • long

  • list_of_string

  • list_of_double

  • list_of_boolean

  • list_of_integer

  • list_of_long

These constants are defined here: VALID_ATTRIBUTE_DATATYPES