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.

New 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))

New 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_bypass(edge_id, value)[source]

Adds an edge-specific visual property bypass.

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

  • value (Any) – Visual property bypass value.

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_bypass(node_id, value)[source]

Adds a node-specific visual property bypass.

Parameters:
  • node_id (str) – 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.

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_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

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_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

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_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_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

New 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

New 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.

New 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

New in version 3.7.0.

CX2Network conversion classes

class ndex2.cx2.CX2NetworkXFactory[source]

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

New 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.

New 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’ and ‘target’ 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

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