CX2Network

The CX2Network provides a data model for the CX2 format

The class provides structured access, manipulation, reading, processing, and writing of network data elements including nodes, edges, attributes, visual properties, and other features of the network.

The introduction of the CX2 format represents a significant revision over its predecessor with several key goals:

  • Simplicity: The CX2 data model is designed to be more straightforward and user-friendly, enabling easier understanding and utilization by developers.

  • Streaming Efficiency: CX2 enhances support for streaming network processing. This includes operations like filtering nodes and edges based on properties, and converting CX networks to other formats, with a significantly reduced memory footprint.

  • Compactness: The format aims to make CX networks more compact, improving data transfer speeds and efficiency.

Added in version 3.6.0.

Methods

class ndex2.cx2.CX2Network[source]

A representation of the CX2 (Cytoscape Exchange) network format.

This class provides functionality to read, process, and write data in the CX2 format. It facilitates the structured access and manipulation of network data elements such as nodes, edges, attributes, and visual properties.

The class maintains internal data structures that hold network data and provides methods to:

  1. Load data from raw CX2 files.

  2. Generate the CX2 representation of the current state.

  3. Write the current state to a CX2 formatted file.

Attributes:
  • attribute_declarations

    A dictionary representing the declarations of attributes for network elements.

  • network_attribute

    A dictionary storing global attributes of the network.

  • nodes

    A dictionary of nodes.

  • edges

    A dictionary of edges.

  • aliases

    A dictionary that maps aspect names (like “nodes” or “edges”) to their alias declarations.

  • default_values

    A dictionary that maps aspect names to their default attribute values.

  • visual_properties

    A list storing visual properties of the network.

  • node_bypasses

    A dictionary of node-specific visual properties that bypass default styles.

  • edge_bypasses

    A dictionary of edge-specific visual properties that bypass default styles.

  • opaque_aspects

    A list of other aspects in the CX2 format which don’t have a defined structure in this class.

  • status

    A dictionary representing the network’s status.

Create a two node network with one edge:

import json
from ndex2.cx2 import CX2Network

cx2_network = CX2Network()

node_one_id = cx2_network.add_node(attributes={'name': 'node 1', 'age': 5})
node_two_id = cx2_network.add_node(attributes={'name': 'node 2', 'age': 10})

cx2_network.add_edge(source=node_one_id, target=node_two_id, attributes={'weight': 0.3})

# using json.dumps to pretty print CX2
print(json.dumps(cx2_network.to_cx2(), indent=2))

Added in version 3.6.0.

add_edge(edge_id=None, source=None, target=None, attributes=None)[source]

Adds an edge to the network.

Parameters:
  • edge_id (int or str) – ID of the edge to add.

  • source (int or str) – Source node of the edge.

  • target (int or str) – Target node of the edge.

  • attributes (dict, optional) – Attributes of the edge.

add_edge_attribute(edge_id, key, value, datatype=None)[source]

Adds or updates a specific attribute for a edge in the network.

This method allows for the addition or modification of a single attribute of a specified edge. If the attribute already exists for the edge, its value is updated; otherwise, the attribute is added to the edge.

The method also allows specifying the datatype of the attribute.

Added in version 3.8.0.

Usage Example:

from ndex2.cx2 import CX2Network

cx2_network = CX2Network()
cx2_network.add_edge_attribute(edge_id=1, key='color', value='red')
Parameters:
  • edge_id (int or str) – The ID of the edge to which the attribute will be added or updated.

  • key (str) – The name of the attribute to add or update.

  • value – The value of the attribute.

  • datatype (str) – Type of the value (e.g. string, integer). If not provided, the datatype will be inferred.

Raises:

NDExError – If the edge with the given edge_id does not exist in the network.

add_edge_bypass(edge_id, value)[source]

Adds an edge-specific visual property bypass.

Parameters:
  • edge_id (str or int) – ID of the edge.

  • value (Any) – Visual property bypass value.

add_network_attribute(key, value, datatype=None)[source]

Adds or updates a single network attribute in the network’s attributes.

This method processes the given attribute value using the declared type associated with the attribute key in the attribute declarations. If the attribute already exists, its value is updated; otherwise, the attribute is added to the network.

Added in version 3.8.0.

Usage Example:

from ndex2.cx2 import CX2Network

cx2_network = CX2Network()
cx2_network.add_network_attribute(key='new_attribute', value='attribute_value', datatype='string')

print(cx2_network.get_network_attributes())

Note

If datatype is not implicitly defined, this method respects the declared type for the attribute if it existed before. If the attribute key does not have a declared type, it will be inferred from the value.

Parameters:
  • key (str) – The key (name) of the network attribute to add or update.

  • value – The value of the network attribute.

  • datatype (str) – Type of the value (e.g. string, integer). If not provided, the datatype will be inferred.

Raises:

NDExError – If the value conversion based on the declared type fails.

add_node(node_id=None, attributes=None, x=None, y=None, z=None)[source]

Adds a node to the network.

Parameters:
  • node_id (int or str) – ID of the node to add.

  • attributes (dict, optional) – Attributes of the node.

  • x (float, optional) – X-coordinate of the node.

  • y (float, optional) – Y-coordinate of the node.

  • z (float, optional) – Z-coordinate of the node.

Raises:

NDExAlreadyExists – If node with node_id already exists

add_node_attribute(node_id, key, value, datatype=None)[source]

Adds or updates a specific attribute for a node in the network.

This method allows for the addition or modification of a single attribute of a specified node. If the attribute already exists for the node, its value is updated; otherwise, the attribute is added to the node.

The method also allows specifying the datatype of the attribute.

Added in version 3.8.0.

Usage Example:

from ndex2.cx2 import CX2Network

cx2_network = CX2Network()
cx2_network.add_node_attribute(node_id=1, key='color', value='red')
Parameters:
  • node_id (int or str) – The ID of the node to which the attribute will be added or updated.

  • key (str) – The name of the attribute to add or update.

  • value – The value of the attribute.

  • datatype (str) – Type of the value (e.g. string, integer). If not provided, the datatype will be inferred.

Raises:

NDExError – If the node with the given node_id does not exist in the network.

add_node_bypass(node_id, value)[source]

Adds a node-specific visual property bypass.

Parameters:
  • node_id (str or int) – ID of the node.

  • value (Any) – Visual property bypass value.

add_opaque_aspect(aspect)[source]

Adds an opaque aspect to the list of opaque aspects.

Usage Example:

from ndex2.cx2 import CX2Network

cx2_network = CX2Network()
cx2_network.add_opaque_aspect({'aspect_key': 'aspect_value'})
Parameters:

aspect (dict) – The opaque aspect to add.

create_from_raw_cx2(cx2_data)[source]

Loads and processes a raw CX2 data into structured data within the instance.

Parameters:

cx2_data (str or list) – Path to the CX2 file or a list representing CX2 data to be processed.

Raises:
get_alias(aspect_name, attribute_name)[source]

Retrieves alias for a given aspect’s attribute.

Parameters:
  • aspect_name (str) – The name of the aspect (e.g., ‘nodes’, ‘edges’).

  • attribute_name (str) – The attribute whose declared data type needs to be retrieved.

Returns:

The alias or None if not found.

Return type:

str

get_aliases(aspect)[source]

Retrieves aliases for a given aspect’s attributes.

Parameters:

aspect (str) – The name of the aspect (e.g., ‘nodes’, ‘edges’).

Returns:

Dictionary mapping aliases to attribute names.

Return type:

dict

get_attribute_declarations()[source]

Retrieves the attribute declarations as a dict in the following format:

{
 'nodes': {'<ATTR_NAME>': {'d': '<DATA TYPE OF ATTRIBUTE>'}},
 'edges': {'<ATTR_NAME>': {'d': '<DATA TYPE OF ATTRIBUTE>'}},
}

Note

<DATA TYPE OF ATTRIBUTE> above must be one of the following types found in VALID_ATTRIBUTE_DATATYPES

Example:

from ndex2.cx2 import CX2Network

cx2_network = CX2Network()

node_one_id = cx2_network.add_node(attributes={'name': 'node 1', 'age': 5})
node_two_id = cx2_network.add_node(attributes={'name': 'node 2', 'age': 10})

cx2_network.add_edge(source=node_one_id, target=node_two_id, attributes={'weight': 0.3})

print(cx2_network.get_attribute_declarations())

# Above would output:
# {'nodes': {'name': {'d': 'string'}, 'age': {'d': 'integer'}}, 'edges': {'weight': {'d': 'double'}}}
Returns:

The attribute declarations, if none are set an empty dict is returned

Return type:

dict

get_declared_type(aspect_name, attribute_name, attribute_value=None)[source]

Retrieves the declared data type for a given aspect’s attribute.

Parameters:
  • aspect_name (str) – The name of the aspect (e.g., ‘nodes’, ‘edges’).

  • attribute_name (str) – The attribute whose declared data type needs to be retrieved.

  • attribute_value (str, int, bool, float, list) – Actual value that will be used to infer data type if data type has not yet been defined for attribute

Returns:

The declared data type or ‘string’ if not found.

Return type:

str

get_default_value(aspect_name, attribute_name)[source]

Retrieves default value for a given aspect’s attribute.

Parameters:
  • aspect_name (str) – The name of the aspect (e.g., ‘nodes’, ‘edges’).

  • attribute_name (str) – The attribute whose declared data type needs to be retrieved.

Returns:

The default value or None if not found.

Return type:

str

get_default_values(aspect)[source]

Retrieves default values for a given aspect’s attributes.

Parameters:

aspect (str) – The name of the aspect (e.g., ‘nodes’, ‘edges’).

Returns:

Dictionary mapping attribute names to their default values.

Return type:

dict

get_edge(edge_id)[source]

Retrieves an edge based on its ID.

Parameters:

edge_id (int or str) – ID of the edge to retrieve.

Returns:

Edge with the given ID or None if not found.

Return type:

dict or None

get_edge_bypasses()[source]

Retrieves the edge-specific visual property bypasses.

Returns:

The edge-specific visual property bypasses.

Return type:

dict

get_edges()[source]

Retrieves the edges in the network.

Returns:

Edges in the network.

Return type:

dict

get_name()[source]

Retrieves the network name.

Returns:

Network name or None if not set

Return type:

str

get_network_attributes()[source]

Retrieves the network attribute that will be in the following format:

{'<ATTR_NAME>': <ATTR_VAL>}

Example:

import json
from ndex2.cx2 import CX2Network

cx2_network = CX2Network()

cx2_network.set_network_attributes({'name': 'my network',
                                    'description': 'description of my network',
                                    'version': '1.0',
                                    'type': 'fake network'})

print(cx2_network.get_network_attributes())

Note

There are three reserved attribute names:

  • name - title of the network

  • description - a brief description of the network

  • version - version of the network

Returns:

The network attributes.

Return type:

dict

get_node(node_id)[source]

Retrieves a node based on its ID.

Parameters:

node_id (int or str) – ID of the node to retrieve.

Returns:

Node with the given ID or None if not found.

Return type:

dict or None

get_node_bypasses()[source]

Retrieves the node-specific visual property bypasses.

Returns:

The node-specific visual property bypasses.

Return type:

dict

get_nodes()[source]

Retrieves the nodes in the network.

Returns:

Nodes in the network.

Return type:

dict

get_opaque_aspect(aspect_name)[source]

Retrieves a specific opaque aspect from the network by its name.

Parameters:

aspect_name (str) – The name of the opaque aspect to retrieve.

Returns:

The value of the specified opaque aspect, or None if not found.

Return type:

any

get_opaque_aspects()[source]

Retrieves the opaque aspects of the network.

Returns:

The opaque aspects of the network.

Return type:

list

get_status()[source]

Retrieves the status of the network.

Returns:

The status of the network.

Return type:

list

get_visual_properties()[source]

Retrieves the visual properties of the network.

Returns:

The visual properties of the network.

Return type:

dict

lookup_node_id_by_name(name)[source]

Retrieves a node based on its name.

Added in version 3.8.0.

Parameters:

name (str) – Name of the node to retrieve.

Returns:

Node with the given name or None if not found.

Return type:

dict or None

remove_edge(edge_id)[source]

Removes an edge from the network based on its ID.

Parameters:

edge_id (int or str) – ID of the edge to remove.

Raises:

NDExNotFoundError – If edge_id is None or not found

remove_edge_attribute(edge_id, attribute_name)[source]

Removes a specific attribute from an edge.

Parameters:
  • edge_id (int) – The ID of the edge.

  • attribute_name (str) – The name of the attribute to remove.

remove_network_attribute(key)[source]

Removes network attribute matching key passed in

Parameters:

key (str)

Raises:

NDExNotFoundError – If None is passed in as key or if key is not found in network attributes

remove_node(node_id)[source]

Removes a node and checks for dangling edges (edges without both source and target).

Parameters:

node_id (int or str) – ID of the node to remove.

Raises:

NDExNotFoundError – If None is passed in as node_id or if node_id is not found

remove_node_attribute(node_id, attribute_name)[source]

Removes a specific attribute from a node.

Parameters:
  • node_id (int) – The ID of the node.

  • attribute_name (str) – The name of the attribute to remove.

set_attribute_declarations(value)[source]

Sets the attribute declarations. This is useful to do in case where data type might not easily be inferred for a given attribute or if an alias is desired for one or more attributes in a large network to generate more compact CX2

{
 'nodes': {'<ATTR_NAME>': {'d': '<DATA TYPE OF ATTRIBUTE>'}},
 'edges': {'<ATTR_NAME>': {'d': '<DATA TYPE OF ATTRIBUTE>'}},
}

Note

<DATA TYPE OF ATTRIBUTE> above must be one of the following types found in VALID_ATTRIBUTE_DATATYPES

Example:

from ndex2.cx2 import CX2Network

cx2_network = CX2Network()

# set the attribute declarations 1st with an alias
cx2_network.set_attribute_declarations({'nodes': {'name': {'a': 'n', 'd': 'string'},
                                                  'age': {'a': 'a', 'd': 'integer'}},
                                                  'edges': {'weight': {'d': 'double'}}})

# must use alias for name and age since it was set, cannot mix
node_one_id = cx2_network.add_node(attributes={'n': 'node 1', 'a': 5})
node_two_id = cx2_network.add_node(attributes={'n': 'node 2', 'a': 10})

cx2_network.add_edge(source=node_one_id, target=node_two_id, attributes={'weight': 0.3})
Parameters:

value (dict) – The attribute declarations to set.

set_name(name)[source]

Sets the name of the network.

Parameters:

name (str) – The name of the network.

set_network_attributes(network_attrs)[source]

Sets the network attributes after processing them using declared types in attribute declarations.

Expected format:

{'<ATTR_NAME>': <ATTR_VAL>}

Example:

import json
from ndex2.cx2 import CX2Network

cx2_network = CX2Network()

cx2_network.set_network_attributes({'name': 'my network',
                                    'description': 'description of my network',
                                    'version': '1.0',
                                    'type': 'fake network'})

print(cx2_network.get_network_attributes())

Note

There are three reserved attribute names:

  • name - title of the network

  • description - a brief description of the network

  • version - version of the network

Parameters:

network_attrs (dict) – The network attributes to set.

Raises:

NDExError – If network_attrs is None

set_node_attribute(node_id, attribute, value)[source]

Adds or updates a specific attribute for a node in the network. This method is similar to add_node_attribute but will be deprecated in future versions.

Deprecated since version 3.8.0: This method will be removed in future versions. Use add_node_attribute instead.

Parameters:
  • node_id (int or str) – The ID of the node to which the attribute will be added or updated.

  • attribute (str) – The name of the attribute to add or update.

  • value – The value of the attribute.

Raises:

NDExError – If the node with the given node_id does not exist in the network.

set_opaque_aspect(aspect_name, value)[source]

Sets or updates an opaque aspect in the network. If the aspect already exists, its value is updated. Otherwise, it is added to the network.

Parameters:
  • aspect_name (str) – The name of the opaque aspect to set or update.

  • value (any) – The value to set for the opaque aspect.

set_opaque_aspects(value)[source]

Sets the opaque aspects for the network.

Parameters:

value (list) – New opaque aspects for the network.

set_status(value)[source]

Sets the status for the network.

Parameters:

value (dict) – New status for the network.

set_visual_properties(value)[source]

Sets the visual properties for the network.

Parameters:

value (dict) – New visual properties for the network.

to_cx2()[source]

Generates the CX2 representation of the current state of the instance.

This method constructs a list structure representing the current state of the network in the CX2 format.

Returns:

A list representing the CX2 formatted data of the current network state.

Return type:

list

update_edge(edge_id, attributes=None)[source]

Updates the attributes of an edge.

Parameters:
  • edge_id (int or str) – ID of the edge to update.

  • attributes (dict, optional) – New attributes for the edge.

update_node(node_id, attributes=None, x=None, y=None, z=None)[source]

Updates the attributes of a node.

Parameters:
  • node_id (int or str) – ID of the node to update.

  • attributes (dict, optional) – Attributes to update.

  • x (float, optional) – X-coordinate to update.

  • y (float, optional) – Y-coordinate to update.

  • z (float, optional) – Z-coordinate to update.

Raises:

NDExError – if node with node_id passed in does not exist

write_as_raw_cx2(output_path)[source]

Writes data from CX2Network object to a raw CX2 formatted JSON file.

Parameters:

output_path (str) – Destination file path for the CX2 formatted output.

CX2NetworkFactory classes and methods

class ndex2.cx2.CX2NetworkFactory[source]

Base class for Factory classes that create CX2Network objects

Added in version 3.6.0.

get_cx2network(input_data=None) CX2Network[source]

Defines method that creates CX2Network

Warning

Subclasses should implement, this method always raises NotImplementedError

Parameters:

input_data – Optional input data for used to generate network

Raises:

NotImplementedError – Always raised. Subclasses should implement

Returns:

Generated network

Return type:

CX2Network

class ndex2.cx2.NoStyleCXToCX2NetworkFactory[source]

Creates CX2Network network from CX data or NiceCXNetwork

Added in version 3.6.0.

get_cx2network(input_data=None) CX2Network[source]

Creates CX2Network from CX data or NiceCXNetwork but does NOT convert the style associated with input network

Note

Style is NOT converted by this call

Parameters:

input_data (str, list or NiceCXNetwork) – Optional input data used to generate network

Returns:

Generated network

Return type:

CX2Network

class ndex2.cx2.RawCX2NetworkFactory[source]

Factory class responsible for creating CX2Network instances directly from raw CX2.

Added in version 3.6.0.

get_cx2network(input_data=None) CX2Network[source]

Converts the provided raw CX2 into a CX2Network object.

Parameters:

input_data (dict or similar mapping type) – Raw CX2 to be converted.

Returns:

A constructed CX2Network object from the input data.

Return type:

CX2Network

class ndex2.cx2.NetworkXToCX2NetworkFactory[source]

Factory class responsible for creating CX2Network instances from networkx.Graph

Added in version 3.7.0.

get_cx2network(input_data=None)[source]

Creates CX2Network from networkx.Graph object :param input_data: Optional input data used to generate network :type input_data: networkx.Graph, networkx.DiGraph :return: Generated network :rtype: CX2Network

class ndex2.cx2.PandasDataFrameToCX2NetworkFactory[source]

Factory class for converting a Pandas DataFrame into a CX2Network object.

Added in version 3.7.0.

Constructor

get_cx2network(input_data=None, source_field='source_name', target_field='target_name', source_id='source_id', target_id='target_id', source_node_attr=None, target_node_attr=None, source_node_attr_prefix='source_', target_node_attr_prefix='target_', edge_attr=None, edge_interaction='interacts-with') CX2Network[source]

Converts a given Pandas DataFrame into a CX2Network object. The DataFrame should contain columns ‘source’ and ‘target’ to represent source node and target node of edge, and may contain additional columns for edge and node attributes.

Changed in version 3.8.0: Added new parameters to improve flexibility of converter.

import pandas as pd
from ndex2.cx2 import PandasDataFrameToCX2NetworkFactory, CX2Network

# DataFrame with source, target, and other columns
data = {'source': [1, 2], 'target': [2, 3],
        'weight': [1.0, 0.9],
        'source_size': [5, 6], 'target_size': [6, 7]}
df = pd.DataFrame(data)

# Creating an instance of PandasDataFrameToCX2NetworkFactory
factory = PandasDataFrameToCX2NetworkFactory()

# Converting DataFrame to CX2Network
cx2_network = factory.get_cx2network(df, source_id='source', target_id='target')

# cx2_network is now a CX2Network instance based on the DataFrame data
print(cx2_network.to_cx2())

Column Naming Convention

  • Source and target nodes of an edge.

    By default, the columns source_name and target_name represent the names of the source and target nodes, respectively and source_id and target_id represent the unique identifiers for the source and target nodes.

    It can be changed by setting the parameter source_field and target_field to column names containing source/ target names, and source_id and target_id to column names containing source/target ids. Specifying ids is not necessary.

  • Node attributes.
    Node attributes can be specified with a prefix according to their node type:
    • Use the parameter source_node_attr_prefix to set prefix for attributes of the source node (default source_, e.g., source_color, the node will have attribute color).

    • Use the parameter target_node_attr_prefix to set prefix for attributes of the target node (default target_ e.g., target_size, the node will have attribute size).

    If the prefixes are used, attributes in the form prefix_x (e.g. source_x) will be used as x, y, and z coordinates of the node

    They can also be explicitly specified as a list passed in parameter source_node_attr for edge source node and target_node_attr for edge target node. The same columns can be used for both source and target node attributes (e.g. source_node_attr=['color', 'size'] and target_node_attr=['color', 'size']).

  • Edge attributes.

    Edge attributes can be specified as list in parameter edge_attr. In case the parameter is not set, all columns that were not used as node attributes will be used (e.g., weight for an edge’s weight attribute).

    The edge_interaction parameter defines the default interaction type for edges. If not specified in the data frame as edge attribute, this default value is used. If not set, the default interaction is set to interacts-with.

Parameters:
  • input_data (pd.DataFrame) – The Pandas DataFrame to be converted into CX2Network.

  • source_field (str) – The field name for the source node name.

  • target_field (str) – The field name for the target node name.

  • source_id (str) – The field name for the source node ID.

  • target_id (str) – The field name for the target node ID.

  • source_node_attr (list or None) – A list of column names to be used as source node attributes.

  • target_node_attr (list or None) – A list of column names to be used as target node attributes.

  • source_node_attr_prefix (str) – A prefix for column names to be used as source node attributes.

  • target_node_attr_prefix (str) – A prefix for column names to be used as target node attributes.

  • edge_attr (list or None) – A list of column names to be used as edge attributes.

  • edge_interaction (str) – The default interaction type for edges.

Returns:

A CX2Network object CX2Network

Return type:

CX2Network

Raises:

NDExError – If the input DataFrame is None or does not have the necessary columns.

CX2Network conversion classes

class ndex2.cx2.CX2NetworkXFactory[source]

A factory class for creating NetworkX Graph objects from CX2Network data.

Added in version 3.7.0.

Constructor

get_graph(cx2network, networkx_graph=None)[source]

Creates NetworkX Graph object which can be one of the multiple types of Graph objects

Parameters:
Returns:

networkx Graph object

Return type:

networkx.MultiDiGraph, networkx.DiGraph

class ndex2.cx2.CX2NetworkPandasDataFrameFactory[source]

Factory class for converting a CX2Network object into a Pandas DataFrame.

Added in version 3.7.0.

Constructor

get_dataframe(cx2network)[source]

Converts a given CX2Network object into a Pandas DataFrame. The DataFrame will contain columns for ‘source_id’ and ‘target_id’ of nodes of each edge, along with other edge and node attributes. Node attributes will be prefixed with source_ and target_ respectively. If coordinates exist on the nodes they will be added as source_x, source_y, source_z, target_x, target_y, target_z

Parameters:

cx2network (CX2Network) – The CX2Network object to be converted into a DataFrame.

Raises:

NDExError – If the input CX2Network is None or not an instance of CX2Network.

Returns:

A Pandas DataFrame representing the network data from CX2Network.

Return type:

pandas.DataFrame

get_nodelist_table(cx2network)[source]

Converts nodes from a CX2Network object into a pandas DataFrame.

Added in version 3.8.0.

Parameters:

cx2network (CX2Network) – An instance of CX2Network.

Returns df:

A pandas DataFrame with columns node_id and node attributes.

Rtype df:

pandas.DataFrame

Supported data types

The following Attribute Declaration Data Types are supported under the d attribute:

  • string

  • double

  • boolean

  • integer

  • long

  • list_of_string

  • list_of_double

  • list_of_boolean

  • list_of_integer

  • list_of_long