Cytoscape automation
skm_tools.cytoscape_utils sends networks and analysis results to
Cytoscape, to look at, style and export them. It uses
py4cytoscape, which controls a running Cytoscape
through its REST interface (CyREST).
Getting started
You need:
the
cytoscapeextra:pip install "skm-tools[cytoscape]"(see Installation),Cytoscape 3.10 or later, open on the same computer. Python talks to it while it runs, so leave it open.
Check the connection:
import py4cytoscape as p4c
from skm_tools import cytoscape_utils as cu
p4c.cytoscape_ping() # "You are connected to Cytoscape!"
A few Cytoscape terms used below:
SUID: Cytoscape’s id for a network (and for each node and edge). Functions here return the SUID of the networks they create, and take a network as
network(its SUID or its name; without it, the network currently selected in Cytoscape). SUIDs are not kept: they change when a session is saved and opened again. To find a network again, use its name, e.g.p4c.get_network_suid("PSS").Collection: a group of networks, e.g. a network and its subnetworks; shown as a folder in Cytoscape’s Network panel. The networks of a collection share their node and edge tables: a column added in one network is there in all of them.
Visual style: how a network is drawn (shapes, colours, labels), from the values in the node and edge tables. Several networks can share a style.
Node and edge tables: the node and edge attributes, one column per attribute. Loading data into a new column, and using that column in a style, is how data is shown on the network.
Loading a network
load_network() sends a networkx graph to Cytoscape. The
node and edge attributes become table columns, typed from their values (Double, Integer,
Boolean, String, or List of these for list attributes), also when only some nodes have a
value, e.g. data added with add_node_data(). style
is optional: it applies one of the SKM styles; without it, Cytoscape uses its default style.
suid = cu.load_network(pss, title="PSS", style="skm")
Cytoscape groups columns named namespace::name under their namespace in the table
browser. namespaces puts attributes in a namespace by their name’s prefix, only in
Cytoscape (the networkx attributes keep their names). Style mappings then use the Cytoscape
column names:
# "gwas maxLog10P" -> "gwas::maxLog10P", "gwas Rust maxLog10P" -> "gwas::Rust maxLog10P"
suid = cu.load_network(ckn_gwas, title="GWAS", style="skm", namespaces={"gwas ": "gwas"})
p4c.set_node_color_mapping("gwas::Rust maxLog10P", [5, 18], ["#fdd0a2", "#a63603"], network=suid)
Cytoscape namespaces have one level, and column names ignore case.
The SKM styles are bundled with skm-tools, and imported into Cytoscape the first time
they are used (also with apply_builtin_style()). CKN and
PSS use the same node classes (node_type) and edge attributes, so they share a style:
"skm"(SKM): for CKN, the PSS interaction network and the PSS gene networks. Nodes are coloured and shaped bynode_type, in the colours of the PSS Explorer, and labelled withdisplay_label. Edges are coloured, and get their arrow, byinteraction(positive: green, negative: red, unknown: grey); mutual (directedFalse) edges are dashed, and better supported edges (lowerrank) are thicker."skm-reactions"(SKM-reactions): for the PSS reaction graph. The same nodes, plus the reactions (blue); edges as in the PSS Explorer, byedge_type(activation: green, inhibition: red, substrate and product: grey), labelled with the participant’srole.
To change a style for one analysis, copy it first (see
copy_style()), so the original stays as it is: the SKM
styles are shared by every network they are applied to.
Marking nodes with a style mapping
Instead of bypasses (see Highlighting), nodes can be marked through a column and a style
mapping, which stays with the data: flag_column() sets a node
attribute to a flag for some nodes and to another attribute (default node_type) for the
rest, and extend_discrete_mapping() maps a visual property on
that column, keeping the entries of an existing mapping (e.g. the SKM shapes per
node_type) and adding the flags.
cu.flag_column(g, "shape_key", {tf: "TF" for tf in tfs})
cu.flag_column(g, "border_flag", {n: "robust DEG" for n in robust})
suid = cu.load_network(g, "DEGs", style="skm", significant_digits=3)
style = cu.copy_style("SKM", "SKM-flags", networks=[suid])
cu.extend_discrete_mapping(style, "NODE_SHAPE", "shape_key", {"TF": "DIAMOND"}, network=suid)
cu.extend_discrete_mapping(style, "NODE_BORDER_PAINT", "border_flag", {"robust DEG": "#e0a100"}, network=suid)
cu.extend_discrete_mapping(style, "NODE_BORDER_WIDTH", "border_flag", {"robust DEG": 6}, network=suid)
significant_digits in load_network() rounds the float
values loaded into the tables (here to 3 significant digits), for smaller sessions.
Highlighting
Highlighting changes the look of single nodes and edges, on top of the style (Cytoscape calls these bypasses: they stay when the style changes, until cleared in Cytoscape).
highlight_nodes(): fill, label and border colour, border width, size.highlight_edges(): colour and line width.highlight_path(): the nodes and edges of a path. For paths fromget_paths(..., directed=False), which can use an edge against its direction, passdirected=Falseto highlight the edges either way.
Each returns what it highlighted; clear_highlights()
removes the highlights of the nodes and edges given (or of all, which is slow for large
networks).
To highlight several paths in different colours, pass what was already highlighted as
skip_nodes and skip_edges, so later paths don’t paint over earlier ones. The
example below highlights the shortest paths from JA to SA in red, and then those from ABA
to SA in blue; nodes and edges on both (e.g. SA itself) stay red:
from skm_tools.paths import get_paths
done_nodes, done_edges = [], []
for paths, color in [(get_paths(pss, "JA", "SA"), "#E41A1C"),
(get_paths(pss, "ABA", "SA"), "#377EB8")]:
for p in paths:
nodes, edges = cu.highlight_path(p, color, skip_nodes=done_nodes,
skip_edges=done_edges, network=suid)
done_nodes += nodes
done_edges += edges
apply_shortest_paths_style() shows the results of several
path searches (e.g. one per source) in one go, through a style instead of highlights. It
adds three columns to the tables: for the nodes on the paths, their number of steps to the
end of the path (distance-to-target; on several paths, the smallest) and the source
whose paths they are on (node-path-source; the first source, if on several), and for
the edges on the paths, edge-priority ("direct path (<source>)"). It then makes a
copy of the network’s style, <style>-shortest-paths (or style_name), in which node
colour shows the distance to the target (from the first of node_colors, at the target,
to the last; with one colour, to white), and edge colour the source (one of
edge_colors per source). It returns the name of the style:
sources = ["JA", "ABA"]
path_lists = [get_paths(pss, source, "SA") for source in sources]
style = cu.apply_shortest_paths_style(pss, sources, path_lists,
edge_colors=["#E41A1C", "#377EB8"],
node_colors=["#D7191C", "#FDAE61", "#FFFFFF"],
network=suid)
Subnetworks
Subnetworks are new networks in the same collection, with part of a network; they keep its layout and style.
subnetwork_node_induced(): the given nodes and every edge between them.subnetwork_edge_induced(): only the given edges (and their nodes).subnetwork_edge_induced_from_paths(): only the edges along paths, e.g. the paths found byget_paths().subnetwork_neighbours(): the given nodes, their neighbours (found in the networkx graph, seeneighborhood_nodes(); first neighbours by default) and every edge between them.
paths = get_paths(pss, "JA", "SA")
paths_suid = cu.subnetwork_edge_induced_from_paths(pss, paths, suid, name="JA to SA")
around_suid = cu.subnetwork_neighbours(pss, "JA", suid, depth=2, name="around JA")
get_or_create_subnetwork() returns the network of that
name in the collection if it already exists, so notebook cells can be run again without
making duplicates.
For layouts, use Cytoscape’s own (p4c.layout_network), or place the nodes at
coordinates computed in Python with layout_from_coords().
networkx and graphviz layouts have the y axis pointing up and Cytoscape down, so the y
coordinates are mirrored (flip_y=True); networkx layouts are within -1 and 1, so scale
them up:
import networkx as nx
cu.layout_from_coords(nx.kamada_kawai_layout(g_paths), scale=500, network=paths_suid)
Showing data as images on nodes
Small plots, e.g. a heatmap of a gene’s logFC per time point, can be shown next to each node. This takes three steps:
Find the image of each node.
match_files_to_nodes()matches the image files in a folder to the nodes by name.Load the image locations into a node table column.
load_node_images().Show that column in a style.
show_node_images(). Use a copy of the SKM style, so the other networks with that style don’t show the images.
images = cu.match_files_to_nodes("heatmaps", pss.nodes())
cu.load_node_images(images, "heatmap", network=suid)
style = cu.copy_style("SKM", "SKM-heatmaps", networks=[suid])
cu.show_node_images(style, "heatmap")
heatmap_images() draws such images: one small heatmap per node
from a table (e.g. log2FC per time point and dose), with a star on marked cells (e.g. DE), and
returns node -> image path for load_node_images() (needs
matplotlib).
from skm_tools.node_images import heatmap_images
# lfc: one row per gene, columns "4h IC50", "4h IC99", "24h IC50", "24h IC99"
images = heatmap_images(lfc, "heatmaps", [["4h IC50", "4h IC99"], ["24h IC50", "24h IC99"]],
marks=padj < 0.05)
cu.load_node_images(images, "heatmap", network=suid)
The helpers that don’t need Cytoscape (match_files_to_nodes(),
node_file_key(), chart_column(),
…) are in skm_tools.node_images, and also available in
skm_tools.cytoscape_utils; import them from skm_tools.node_images when making
the images, without Cytoscape.
Matching files to nodes
A file matches a node if the file name (without the extension) is the node name, with the
characters that can’t be in file names replaced by _. For example:
WRKY33_fc00166_.pngis the image ofWRKY33[fc00166],11-_12-OH-JA.pngis the image of11-/12-OH-JA,AT2G38470.pngis the image of the geneAT2G38470(gene ids stay as they are).
node_file_key() gives the file name for a node name, to
use when making the images. For files that aren’t named after their node, give the node
name in aliases, e.g. aliases={"Pro": "Proline accumulation"}. Files that match no
node are logged (see Messages), so they can be checked.
Several images per node
A node can show up to nine images, each in its own slot, e.g. transcriptomics above the node and metabolomics below it. Load each kind into its own column, and show each column in its own slot and position:
style = cu.copy_style("SKM", "SKM-omics", networks=[suid])
for omics, slot, position in [("transcriptomics", 1, "above"), ("metabolomics", 2, "below")]:
images = cu.match_files_to_nodes(f"heatmaps/{omics}", pss.nodes())
cu.load_node_images(images, f"image_{omics}", network=suid)
cu.show_node_images(style, f"image_{omics}", slot=slot, position=position)
The position puts a side of the image against a side of the node, centred:
"below": the top of the image against the bottom of the node,"above": the bottom of the image against the top of the node,"left"and"right": the image’s right or left side against the node’s left or right side,"center": the image on the middle of the node.
Other positions can be given in Cytoscape’s own form, "<node point>,<image
point>,c,<x offset>,<y offset>", with the points as compass directions (N, NE,
E, …, C for the centre): "below" is "S,N,c,0.00,0.00", the image’s north
(top) point on the node’s south (bottom) point. size sets the size of the images.
Comparing conditions
To compare conditions (e.g. heat and drought), show each condition on its own copy of the
network. Each copy also needs its own style: a style says which column’s images to show
(e.g. “show the images in column image_heat below the nodes”), so all networks with
the same style show the same images. The example loads each condition’s images, makes a
copy of the network and a copy of the style for it, and sets that style to show the
condition’s column:
for condition in ["heat", "drought"]:
images = cu.match_files_to_nodes(f"heatmaps/{condition}", pss.nodes())
cu.load_node_images(images, f"image_{condition}", network=suid, unique_dir="images")
copy = cu.clone_network(name=condition, collection=f"PSS - {condition}", network=suid)
style = cu.copy_style("SKM", f"SKM-{condition}", networks=[copy])
cu.show_node_images(style, f"image_{condition}")
copy_style() raises an error if a style of that name exists
(Cytoscape would add a number to the name); overwrite=True replaces it, e.g. when
running a notebook cell again.
clone_network() copies the network into a new collection,
which has its own tables: load the images before cloning (as here), or into the clone.
get_or_create_subnetwork() makes a copy in the same
collection instead, which shares the tables.
Image caching
Cytoscape keeps the images it has shown in a cache, and how it uses the cache is hard to predict: it can show an image it loaded before instead of the right one, e.g. an image of another file with the same name, or the old version of a file that has since been changed. Two things help:
Keep the number of images down, e.g. only for the nodes and conditions you need.
Give
unique_dirtoload_node_images(). The images are then first copied to that folder, each under a new name that no file had before (the file name plus a random id), every time, so Cytoscape has to load them again. The copies are not deleted afterwards; empty the folder from time to time.
SVG images
Cytoscape can show SVG images, but sizes them differently from PNG images: in our tests,
SVG images were drawn larger than PNG images of the same size. PNG images are
therefore easier to place. To convert SVG images (e.g. plots made in R) to PNG, use
to_png=True together with unique_dir: the SVG images are converted while they are
copied. The conversion needs the cairosvg package, which is not installed with
skm-tools: install it with pip install cairosvg.
Images made on the fly
add_custom_png() does the three steps in one call. Instead
of a folder of images, it takes a function you write, which gets a node name and returns
the file name of that node’s image (or None for no image). The function can make the
image (e.g. plot the node’s data with matplotlib and save it), or only return the name of
an existing file. The images are shown in the network’s current style, below the nodes
(see slot, position and size); if that is one of the SKM styles, which are
shared, in a copy of it (<style>-<column>).
Charts instead of images
Cytoscape can also draw simple charts itself, with the
enhancedGraphics app.
chart_column() makes a chart for each node from a table
with a row per node: by default a bar chart, with one bar per given column, in the given
colours, and the value axis from value_range. Other chart types are set with
chart, e.g. chart="linechart" or chart="heatstripchart" (see the
enhancedGraphics documentation). enhancedGraphics separates the labels by commas, and can’t
escape them: labels can’t contain , or ". Load the charts as a node table column,
and show them like images:
# df: logFC per gene (rows) and time point (columns)
charts = cu.chart_column(df, ["10min", "30min", "1h"], "#E41A1C", value_range=(-2, 2))
p4c.load_table_data(charts.to_frame("chart"), network=suid)
style = cu.copy_style("SKM", "SKM-charts", networks=[suid])
cu.show_node_images(style, "chart")
Exporting
export_network(): a network as an image (PDF, PNG, SVG, …), zoomed to fit and with nothing selected. Returns the file written (py4cytoscape adds the format’s extension if the name doesn’t have it).export_collection(): every network of a collection, one image each. For PDFs,crop=Truecrops their margins (needs thepdfextra).combine_pdfs()combines PDFs into one document, a page each, with captions (needs thepdfextra; no Cytoscape).
from skm_tools.pdf_utils import combine_pdfs
files = cu.export_collection("figures", format="PDF", crop=True, network=suid)
combine_pdfs(files, "figures.pdf", captions=[f.stem for f in files])
Tips
Running scripts in the background
Cytoscape brings its window to the front for many operations, which makes it hard to do anything else while a script runs. On Linux, run Cytoscape in its own window with Xephyr, a display inside a window: Cytoscape can only take the focus inside it.
Xephyr :2 -screen 1600x1000 -resizeable &
cd /path/to/Cytoscape && DISPLAY=:2 bash -c 'sleep infinity | ./cytoscape.sh' &
(sleep infinity | keeps Cytoscape’s console input open; without it, Cytoscape shuts
down right away when started in the background.)
Messages from py4cytoscape
py4cytoscape prints the text of every error, also of errors that are expected and
handled (e.g. while waiting for Cytoscape to finish creating a network). This output is
switched off when skm_tools.cytoscape_utils is imported; errors are still raised as
usual, mostly with the same text. When Cytoscape’s error response can’t be read, though,
py4cytoscape raises a plain HTTPError (“500 Server Error … for url …”) and only
prints Cytoscape’s message: it is then only in py4cytoscape’s log file
(logs/py4cytoscape.log). When debugging, switch the output back on with
silence_py4cytoscape() and False.
Housekeeping
delete_other_networks(): delete every network but one, e.g. to start over while trying things out.
How nodes and edges are found
The functions here find nodes in Cytoscape by their name (the networkx node id), and
edges by their name, "source (interaction) target", both set by
load_network(). Networks loaded in other ways need the
same names. All parallel edges between two nodes are found (and highlighted) together.
Useful links
Network layout notebook. The Copycat layout app can be installed from the Cytoscape App store; yFiles layouts can’t be used from scripts.