skm_tools.cytoscape_utils

Cytoscape automation: load networks, apply the SKM styles, highlight nodes, edges and paths, create subnetworks, and export images.

Requires the cytoscape extra (pip install skm-tools[cytoscape]) and a running Cytoscape (https://cytoscape.org) for py4cytoscape to talk to.

Functions acting on a network take it as network (a SUID or a name; default: the current network in Cytoscape). Needs Cytoscape 3.10 or later.

py4cytoscape’s console output (e.g. the text of errors that are handled, such as the retries in clone_network()) is silenced when this module is imported, see silence_py4cytoscape().

The helpers that don’t need Cytoscape (matching image files to nodes, number badges, chart definitions) are in skm_tools.node_images, and also available here.

Nodes and edges are matched to Cytoscape by name: a node’s name is its networkx node id, and an edge’s name is "source (interaction) target", where interaction is the edge’s interaction attribute ("interacts with" if it has none), as set by load_network() / py4cytoscape.create_network_from_networkx. Parallel edges between the same two nodes are matched together.

Attributes

logger

IMAGE_POSITIONS

Functions

silence_py4cytoscape([silence])

Silence (or restore) py4cytoscape's console output.

set_style(style[, network])

Apply a visual style to one network.

load_network(g, title[, collection, style, ...])

Load a networkx graph into Cytoscape.

apply_builtin_style([style, network])

Apply one of the bundled SKM visual styles to a Cytoscape network.

highlight_nodes(nodes[, color, label_color, ...])

Highlight nodes with style bypasses.

highlight_edges(edges, color[, skip_edges, ...])

Highlight edges with style bypasses (colour and line width).

highlight_path(nodes, color[, skip_nodes, skip_edges, ...])

Highlight the nodes and edges of a path.

clear_highlights([nodes, edges, network])

Remove the highlights (style bypasses) of highlight_nodes(),

apply_shortest_paths_style(g, sources, path_lists[, ...])

Colour the results of several path searches (e.g. one per source) in a new visual style.

clone_network([name, collection, network])

Clone a Cytoscape network into a new collection, optionally renaming both.

copy_style(style, new_style[, networks, overwrite])

Copy a visual style, and apply the copy to networks.

flag_column(g, column, flags[, fallback])

Set a node attribute that marks some nodes and otherwise holds another attribute, for a style mapping.

extend_discrete_mapping(style, visual_property, ...[, ...])

Map a visual property on a flag column: the entries of an existing discrete mapping, plus new ones.

delete_other_networks(keep)

Delete every Cytoscape network except keep, and make it the current network.

subnetwork_edge_induced(edges, parent_suid[, name])

New Cytoscape network with only the given edges (and their nodes).

subnetwork_edge_induced_from_paths(g, paths, parent_suid)

New Cytoscape network with only the edges along paths.

subnetwork_node_induced(nodes, parent_suid[, name])

New Cytoscape network with the given nodes and every edge between them.

get_or_create_subnetwork(nodes, parent_suid, name)

The network called name in the collection of parent_suid, created with

subnetwork_neighbours(g, nodes, parent_suid[, depth, ...])

New Cytoscape network with nodes, their neighbours, and every edge between them.

layout_from_coords(positions[, flip_y, scale, network])

Place nodes at given coordinates (e.g. from a networkx or graphviz layout).

load_node_images(images, column[, network, ...])

Load image file locations into a node table column, for show_node_images().

show_node_images(style, column[, slot, position, size])

Show the images in a node table column (see load_node_images()) in a style.

add_custom_png(create_png[, style, column, slot, ...])

Show an image (e.g. a small plot of experimental data) by each node, from a

export_network(filename[, format, wait, network])

Export a network view as an image, fitted to the content and with nothing selected.

export_collection(folder[, format, crop, network])

Export every network of a collection as an image (see export_network()).

Module Contents

skm_tools.cytoscape_utils.logger
skm_tools.cytoscape_utils.silence_py4cytoscape(silence=True)

Silence (or restore) py4cytoscape’s console output.

py4cytoscape prints the text of every error it raises, also of errors that are caught and handled (e.g. the retries in clone_network()), and prints progress messages in notebooks, and its log of every request reaches the console when the root logger has a handler (e.g. after logging.basicConfig()). Silenced when this module is imported. The errors are still raised, usually with the same text. But when Cytoscape’s error response isn’t JSON, py4cytoscape prints the response and raises a plain HTTPError (“500 Server Error … for url …”): silenced, Cytoscape’s message is then only in py4cytoscape’s log file (logs/py4cytoscape.log in the working directory, which still gets everything). When debugging, call silence_py4cytoscape(False).

Parameters:

silence (bool) – True (default): no console output from py4cytoscape. False: as py4cytoscape does by default.

skm_tools.cytoscape_utils.set_style(style, network=None)

Apply a visual style to one network.

Cytoscape also applies the style to the network(s) selected in its Network panel, so py4cytoscape.set_visual_style can change other networks too. This makes network the current (selected) network first.

Parameters:
  • style (str) – Visual style name.

  • network (int or str, optional) – Cytoscape network, SUID or name (default: the current network).

skm_tools.cytoscape_utils.load_network(g, title, collection=None, style=None, namespaces=None, significant_digits=None)

Load a networkx graph into Cytoscape.

Parameters:
  • g (networkx.Graph) – Network to load. Node ids become the Cytoscape name; node and edge attributes become table columns.

  • title (str) – Network name in Cytoscape.

  • collection (str, optional) – Collection to add the network to (default: a new collection named title).

  • style ({"skm", "skm-reactions"}, optional) – Built-in SKM style to apply (see apply_builtin_style()); without it, Cytoscape’s default style.

  • namespaces (dict, optional) – Attribute-name prefix -> Cytoscape column namespace, for node and edge attributes. Cytoscape groups columns named namespace::name under their namespace in the table browser. E.g. {"gwas ": "gwas"} loads the attributes gwas maxLog10P and gwas Rust maxLog10P as the columns gwas::maxLog10P and gwas::Rust maxLog10P. The longest matching prefix is used; an attribute that equals a prefix keeps its name ({"translation": "translation"}: translation::translation). Other attributes, and the networkx graph itself, are unchanged. Style mappings and other functions then use the Cytoscape column names.

  • significant_digits (int, optional) – Round float node and edge values to this many significant digits (e.g. 3: 0.000123456 -> 0.000123, 13.4651 -> 13.5) in the loaded tables, for smaller sessions; the networkx graph is unchanged.

Returns:

SUID of the new Cytoscape network.

Return type:

int

Notes

Table columns are created with the type of the attribute’s values before the values are loaded: Cytoscape guesses a new column’s type from the data, and can make a numeric column with missing values (e.g. data on only some nodes) a String column, which a continuous style mapping can’t use. The type comes from the networkx values, so the same attribute gets the same type in every network: integers become Integer columns (Long beyond 32 bits), other numbers Double, booleans Boolean, anything else String; lists (and tuples, sets) become List columns of the type of their elements. Attributes that are missing on every node (edge) are left out. Networks in one collection share their columns: a column that exists already keeps its type, with a warning if it differs.

Cytoscape namespaces have one level (a column name is split at the first ::) and ignore case, so a namespace can’t contain ::, and two attributes whose column names differ only in case raise a ValueError.

skm_tools.cytoscape_utils.apply_builtin_style(style='skm', network=None)

Apply one of the bundled SKM visual styles to a Cytoscape network.

The styles are imported into Cytoscape on first use (from skm-styles.xml).

Parameters:
  • style ({"skm", "skm-reactions"}) – "skm" (style SKM, default): for CKN, the PSS interaction network and the PSS gene networks. Nodes by node_type (the PSS classes, in the PSS Explorer’s colours), labelled with display_label; edges coloured and with arrows by interaction, dashed for mutual (directed False) edges, and thicker for better supported ones (rank). "skm-reactions" (style SKM-reactions): for the PSS reaction graph, with reactions as nodes, and edges by edge_type (activation, inhibition, substrate, product, …) labelled with their role.

  • network (int or str, optional) – Cytoscape network, SUID or name (default: the current network).

Returns:

The style name (SKM or SKM-reactions).

Return type:

str

skm_tools.cytoscape_utils.highlight_nodes(nodes, color=None, label_color=None, border_color=None, border_width=None, node_height=None, node_width=None, network=None)

Highlight nodes with style bypasses.

Only the given properties are changed. Bypasses stay when the visual style changes; see clear_highlights() to undo them.

Parameters:
  • nodes (node or iterable of nodes) – Nodes to highlight (names not in the network are skipped, with a warning).

  • color (str, optional) – Fill, label and border colours, as hex ("#FF0000").

  • label_color (str, optional) – Fill, label and border colours, as hex ("#FF0000").

  • border_color (str, optional) – Fill, label and border colours, as hex ("#FF0000").

  • border_width (float, optional) – Sizes in pixels.

  • node_height (float, optional) – Sizes in pixels.

  • node_width (float, optional) – Sizes in pixels.

  • network (int or str, optional) – Cytoscape network, SUID or name (default: the current network).

Returns:

The names of the highlighted nodes.

Return type:

list of str

skm_tools.cytoscape_utils.highlight_edges(edges, color, skip_edges=None, edge_line_width=10, directed=True, network=None)

Highlight edges with style bypasses (colour and line width).

Parameters:
  • edges (iterable of tuple) – Edges as (u, v) or (u, v, key) tuples, e.g. from skm_tools.paths.path_edges(). All parallel edges between u and v are highlighted.

  • color (str) – Edge colour, as hex.

  • skip_edges (iterable of tuple, optional) – (u, v) pairs not to highlight, e.g. edges already highlighted in another colour.

  • edge_line_width (float) – Line width in pixels (default 10).

  • directed (bool) – If False, also highlight the edges v -> u (e.g. for paths from get_paths(..., directed=False), which can use an edge against its direction).

  • network (int or str, optional) – Cytoscape network, SUID or name (default: the current network).

Returns:

The (u, v) pairs highlighted: found in the network, and not skipped.

Return type:

list of tuple

skm_tools.cytoscape_utils.highlight_path(nodes, color, skip_nodes=None, skip_edges=None, label_color='white', border_color='black', border_width=10, edge_line_width=10, directed=True, network=None)

Highlight the nodes and edges of a path.

To highlight several paths in different colours without painting over earlier ones, pass the nodes and edges returned by the earlier calls as skip_nodes and skip_edges.

Parameters:
  • nodes (list) – The path, as a list of nodes.

  • color (str) – Node fill and edge colour, as hex.

  • skip_nodes (iterable, optional) – Nodes not to highlight.

  • skip_edges (iterable of tuple, optional) – (u, v) pairs not to highlight.

  • label_color (str) – Node label and border colours (default white and black).

  • border_color (str) – Node label and border colours (default white and black).

  • border_width (float) – Node border and edge widths in pixels (default 10).

  • edge_line_width (float) – Node border and edge widths in pixels (default 10).

  • directed (bool) – If False, also highlight the edge v -> u of each step u, v (for paths from get_paths(..., directed=False)).

  • network (int or str, optional) – Cytoscape network, SUID or name (default: the current network).

Returns:

  • nodes (list) – The path’s nodes that were highlighted.

  • edges (list of tuple) – The path’s (u, v) edges that were highlighted.

skm_tools.cytoscape_utils.clear_highlights(nodes=None, edges=None, network=None)

Remove the highlights (style bypasses) of highlight_nodes(), highlight_edges() and highlight_path().

Cytoscape clears bypasses one node and one property at a time, which takes a while for many nodes: pass the nodes and edges that were highlighted (as returned by the highlight functions) rather than clearing everything.

Parameters:
  • nodes (iterable, optional) – Nodes to clear. Default: all nodes, if edges isn’t given either.

  • edges (iterable of tuple, optional) – (u, v) edges to clear. Default: all edges, if nodes isn’t given either.

  • network (int or str, optional) – Cytoscape network, SUID or name (default: the current network).

skm_tools.cytoscape_utils.apply_shortest_paths_style(g, sources, path_lists, edge_colors=None, node_colors=None, style_name=None, network=None)

Colour the results of several path searches (e.g. one per source) in a new visual style.

Adds node columns distance-to-target (the number of steps to the end of the path; on several paths, the smallest) and node-path-source (the first search whose paths have the node), and the edge column edge-priority ("direct path (<source>)"), then copies the network’s current style to style_name, with colour mappings on them.

Parameters:
  • g (networkx.Graph) – Graph the paths were found in (to find their edges, see skm_tools.paths.path_edges()).

  • sources (list) – The source of each search (its label in edge-priority).

  • path_lists (list of list) – Paths found by each search: one list of paths per source, in the same order.

  • edge_colors (list of str, optional) – Hex colour for the edges of each source’s paths, one per source.

  • node_colors (list of str, optional) – Hex colours for a continuous node colour mapping on distance-to-target, from the target (distance 0) to the farthest node. With one colour, the second is white.

  • style_name (str, optional) – Name of the new style (default: "<current style>-shortest-paths"; replaced if it exists).

  • network (int or str, optional) – Cytoscape network, SUID or name (default: the current network).

Returns:

The style name.

Return type:

str

skm_tools.cytoscape_utils.clone_network(name=None, collection=None, network=None)

Clone a Cytoscape network into a new collection, optionally renaming both.

py4cytoscape’s clone_network doesn’t rename the new collection; this does.

Parameters:
  • name (str, optional) – Name of the clone.

  • collection (str, optional) – Name of the clone’s new collection.

  • network (int or str, optional) – Cytoscape network to clone, SUID or name (default: the current network).

Returns:

SUID of the clone.

Return type:

int

skm_tools.cytoscape_utils.copy_style(style, new_style, networks=(), overwrite=False)

Copy a visual style, and apply the copy to networks.

Parameters:
  • style (str) – Visual style to copy.

  • new_style (str) – Name of the copy.

  • networks (iterable of int or str, optional) – Networks to apply the copy to.

  • overwrite (bool) – If a style new_style exists: replace it (True), or raise ValueError (False, default). Cytoscape itself would add a number to the name.

Returns:

new_style.

Return type:

str

skm_tools.cytoscape_utils.flag_column(g, column, flags, fallback='node_type')

Set a node attribute that marks some nodes and otherwise holds another attribute, for a style mapping.

E.g. flag_column(g, "border_flag", {"AT2G38470": "robust DEG"}) gives WRKY33 "robust DEG" and every other node its node_type, so one discrete mapping on border_flag can colour the flagged nodes and keep the usual colour per node type for the rest (see extend_discrete_mapping()). Changes g in place.

Parameters:
  • g (networkx.Graph)

  • column (str) – Attribute to set.

  • flags (dict) – Node -> flag (str). Nodes not in g are ignored.

  • fallback (str or None) – Attribute whose value the other nodes get (default "node_type"); None: an empty string.

Returns:

g.

Return type:

networkx.Graph

skm_tools.cytoscape_utils.extend_discrete_mapping(style, visual_property, column, extra, base_style=None, network=None)

Map a visual property on a flag column: the entries of an existing discrete mapping, plus new ones.

For marking nodes with a style mapping instead of bypasses: e.g. the SKM style maps NODE_SHAPE on node_type; with a column that holds "TF" for transcription factors and the node_type otherwise (flag_column()), extend_discrete_mapping(style, "NODE_SHAPE", "shape_key", {"TF": "DIAMOND"}) draws TFs as diamonds and every other node with its usual shape. Without an existing mapping, only extra is mapped (unmapped values get the style’s default).

Parameters:
  • style (str) – Style to change (e.g. a copy of the SKM style, see copy_style()).

  • visual_property (str) – E.g. "NODE_SHAPE", "NODE_BORDER_PAINT", "NODE_BORDER_WIDTH", "NODE_FILL_COLOR".

  • column (str) – Node column to map on. Must exist in network (py4cytoscape checks it).

  • extra (dict) – Column value -> property value, added to (or replacing) the existing entries.

  • base_style (str, optional) – Style whose mapping of visual_property provides the existing entries (default: style).

  • network (int or str, optional) – Network with the column (default: the current network).

Returns:

The mapped column value -> property value.

Return type:

dict

skm_tools.cytoscape_utils.delete_other_networks(keep)

Delete every Cytoscape network except keep, and make it the current network.

Handy for starting over while debugging a notebook. Can’t be undone (save the session first if needed).

Parameters:

keep (int) – SUID of the network to keep.

Returns:

SUIDs of the deleted networks.

Return type:

list of int

skm_tools.cytoscape_utils.subnetwork_edge_induced(edges, parent_suid, name='subnetwork (edge induced)')

New Cytoscape network with only the given edges (and their nodes).

Parameters:
  • edges (iterable of tuple) – Edges as (u, v) or (u, v, key) tuples; all parallel edges between u and v are included.

  • parent_suid (int) – SUID of the Cytoscape network to take them from.

  • name (str) – Name of the new network.

Returns:

SUID of the new network.

Return type:

int

skm_tools.cytoscape_utils.subnetwork_edge_induced_from_paths(g, paths, parent_suid, name='subnetwork (edge induced)')

New Cytoscape network with only the edges along paths.

Parameters:
Returns:

SUID of the new network.

Return type:

int

skm_tools.cytoscape_utils.subnetwork_node_induced(nodes, parent_suid, name='subnetwork (node induced)')

New Cytoscape network with the given nodes and every edge between them.

Node-induced: the result includes every edge of parent_suid between the given nodes, not just edges from whatever selection process produced nodes (e.g. a curated reaction/edge list). To keep an exact edge subset instead, use subnetwork_edge_induced().

Parameters:
  • nodes (iterable) – Nodes to include (names not in the network are skipped, with a warning).

  • parent_suid (int) – SUID of the Cytoscape network to take them from.

  • name (str) – Name of the new network.

Returns:

SUID of the new network.

Return type:

int

skm_tools.cytoscape_utils.get_or_create_subnetwork(nodes, parent_suid, name)

The network called name in the collection of parent_suid, created with subnetwork_node_induced() if it doesn’t exist yet.

For re-running notebook cells without making duplicate networks.

Parameters:
  • nodes (iterable) – Nodes to include, if the network is created.

  • parent_suid (int) – SUID of the Cytoscape network to take them from.

  • name (str) – Name of the network.

Returns:

SUID of the (existing or new) network.

Return type:

int

skm_tools.cytoscape_utils.subnetwork_neighbours(g, nodes, parent_suid, depth=1, direction='both', name='subnetwork (neighbours)')

New Cytoscape network with nodes, their neighbours, and every edge between them.

The neighbours are found in g (see skm_tools.neighbors.neighborhood_nodes()), so the selection in Cytoscape doesn’t change.

Parameters:
  • g (networkx.Graph) – The network loaded as parent_suid (or the part of it to search).

  • nodes (iterable) – Nodes whose neighbourhood to include.

  • parent_suid (int) – SUID of the Cytoscape network to take them from.

  • depth (int or None) – Number of steps (default 1: first neighbours).

  • direction ({"both", "out", "in"}) – For directed graphs: neighbours in both directions (default), downstream or upstream.

  • name (str) – Name of the new network.

Returns:

SUID of the new network.

Return type:

int

skm_tools.cytoscape_utils.layout_from_coords(positions, flip_y=True, scale=1.0, network=None)

Place nodes at given coordinates (e.g. from a networkx or graphviz layout).

Uses a temporary visual style that maps temporary node columns to the node positions, and removes both afterwards (also on errors); the network’s style and columns are left as they were.

Parameters:
  • positions (dict or pandas.DataFrame) – {node: (x, y)} (as returned by the networkx layout functions), or a DataFrame indexed by node name with columns x and y.

  • flip_y (bool) – Mirror the y coordinates (default True): in networkx and graphviz y grows upwards, in Cytoscape downwards.

  • scale (float) – Multiply the coordinates by this (default 1). networkx layouts are within -1 and 1, so use e.g. scale=500 for them.

  • network (int or str, optional) – Cytoscape network, SUID or name (default: the current network).

skm_tools.cytoscape_utils.IMAGE_POSITIONS
skm_tools.cytoscape_utils.load_node_images(images, column, network=None, unique_dir=None, to_png=False)

Load image file locations into a node table column, for show_node_images().

Parameters:
  • images (dict) – Node name -> image path (e.g. from skm_tools.node_images.match_files_to_nodes()). Nodes not in the network are ignored.

  • column (str) – Node table column to load them into, e.g. "image_heat_Desiree".

  • network (int or str, optional) – Cytoscape network, SUID or name (default: the current network).

  • unique_dir (str or pathlib.Path, optional) – Copy the images to this folder first, each to a new, unique file name (see skm_tools.node_images.unique_image_copies()), so that Cytoscape’s image cache can’t show an old or a different image instead.

  • to_png (bool) – With unique_dir: convert SVG images to PNG.

Returns:

Node -> the path loaded.

Return type:

dict

skm_tools.cytoscape_utils.show_node_images(style, column, slot=1, position='below', size=110)

Show the images in a node table column (see load_node_images()) in a style.

Maps the column to one of Cytoscape’s custom graphics slots (NODE_CUSTOMGRAPHICS_<slot>), so a node can show several images (e.g. one per data type) in different slots and positions.

Parameters:
  • style (str) – Visual style to change. To show different columns (e.g. conditions) on copies of a network, use a copy of the style per column, see copy_style().

  • column (str) – Node table column with the image locations.

  • slot (int) – Custom graphics slot, 1 to 9 (default 1).

  • position (str) – "below" (default), "above", "left", "right", "center", a corner ("top-right", "top-left", "bottom-right", "bottom-left": centred on it, e.g. for number_badges()), or a Cytoscape custom graphics position ("S,N,c,0.00,0.00": the image’s north side on the node’s south side, centred, no offset).

  • size (float) – Image size (default 110). The images aren’t resized with the node.

skm_tools.cytoscape_utils.add_custom_png(create_png, style=None, column='fig_location', slot=1, position='below', size=110, unique_dir=None, to_png=False, network=None, **kwargs)

Show an image (e.g. a small plot of experimental data) by each node, from a function that gives the image of a node.

Combines load_node_images() and show_node_images().

Parameters:
  • create_png (callable) – create_png(node_name, **kwargs) returns the path of a node’s image, or None for no image. It can make the image (e.g. plot it with matplotlib), or only return the path of an existing one.

  • style (str, optional) – Visual style to show the images in (default: the network’s current style). The bundled SKM styles (SKM, SKM-reactions) are shared by all networks, so they are not changed: a copy, "<style>-<column>", is made (or replaced) and applied to the network instead.

  • column (str) – Node table column for the image locations (default "fig_location").

  • slot – As for show_node_images().

  • position – As for show_node_images().

  • size – As for show_node_images().

  • unique_dir – As for load_node_images().

  • to_png – As for load_node_images().

  • network (int or str, optional) – Cytoscape network, SUID or name (default: the current network).

  • **kwargs – Passed on to create_png.

Returns:

The style the images are shown in.

Return type:

str

skm_tools.cytoscape_utils.export_network(filename, format='PDF', wait=1.0, network=None, **kwargs)

Export a network view as an image, fitted to the content and with nothing selected.

Parameters:
  • filename (str or pathlib.Path) – File to write (overwritten if it exists). py4cytoscape adds the extension of the format if the name doesn’t end with it.

  • format (str) – "PDF" (default), "PNG", "SVG", "JPEG", …: see py4cytoscape.network_views.export_image.

  • wait (float) – Seconds to wait before exporting (default 1). Cytoscape applies style changes (e.g. a new style, node images or charts) in the background, and an image exported right after them can miss some of them.

  • network (int or str, optional) – Cytoscape network, SUID or name (default: the current network).

  • **kwargs – Passed on to py4cytoscape.network_views.export_image, e.g. zoom=300 or transparent_background=True for PNG. Needs Cytoscape 3.10 or later.

Returns:

The file written.

Return type:

pathlib.Path

skm_tools.cytoscape_utils.export_collection(folder, format='PNG', crop=False, network=None, **kwargs)

Export every network of a collection as an image (see export_network()).

Parameters:
Returns:

The files written.

Return type:

list of pathlib.Path