skm_tools.cytoscape_utils ========================= .. py:module:: skm_tools.cytoscape_utils .. autoapi-nested-parse:: 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 :func:`clone_network`) is silenced when this module is imported, see :func:`silence_py4cytoscape`. The helpers that don't need Cytoscape (matching image files to nodes, number badges, chart definitions) are in :mod:`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 :func:`load_network` / ``py4cytoscape.create_network_from_networkx``. Parallel edges between the same two nodes are matched together. Attributes ---------- .. autoapisummary:: skm_tools.cytoscape_utils.logger skm_tools.cytoscape_utils.IMAGE_POSITIONS Functions --------- .. autoapisummary:: skm_tools.cytoscape_utils.silence_py4cytoscape skm_tools.cytoscape_utils.set_style skm_tools.cytoscape_utils.load_network skm_tools.cytoscape_utils.apply_builtin_style skm_tools.cytoscape_utils.highlight_nodes skm_tools.cytoscape_utils.highlight_edges skm_tools.cytoscape_utils.highlight_path skm_tools.cytoscape_utils.clear_highlights skm_tools.cytoscape_utils.apply_shortest_paths_style skm_tools.cytoscape_utils.clone_network skm_tools.cytoscape_utils.copy_style skm_tools.cytoscape_utils.flag_column skm_tools.cytoscape_utils.extend_discrete_mapping skm_tools.cytoscape_utils.delete_other_networks skm_tools.cytoscape_utils.subnetwork_edge_induced skm_tools.cytoscape_utils.subnetwork_edge_induced_from_paths skm_tools.cytoscape_utils.subnetwork_node_induced skm_tools.cytoscape_utils.get_or_create_subnetwork skm_tools.cytoscape_utils.subnetwork_neighbours skm_tools.cytoscape_utils.layout_from_coords skm_tools.cytoscape_utils.load_node_images skm_tools.cytoscape_utils.show_node_images skm_tools.cytoscape_utils.add_custom_png skm_tools.cytoscape_utils.export_network skm_tools.cytoscape_utils.export_collection Module Contents --------------- .. py:data:: logger .. py:function:: 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 :func:`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)``. :param silence: True (default): no console output from py4cytoscape. False: as py4cytoscape does by default. :type silence: bool .. py:function:: 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. :param style: Visual style name. :type style: str :param network: Cytoscape network, SUID or name (default: the current network). :type network: int or str, optional .. py:function:: load_network(g, title, collection=None, style=None, namespaces=None, significant_digits=None) Load a networkx graph into Cytoscape. :param g: Network to load. Node ids become the Cytoscape ``name``; node and edge attributes become table columns. :type g: networkx.Graph :param title: Network name in Cytoscape. :type title: str :param collection: Collection to add the network to (default: a new collection named `title`). :type collection: str, optional :param style: Built-in SKM style to apply (see :func:`apply_builtin_style`); without it, Cytoscape's default style. :type style: {"skm", "skm-reactions"}, optional :param namespaces: 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. :type namespaces: dict, optional :param significant_digits: 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. :type significant_digits: int, optional :returns: SUID of the new Cytoscape network. :rtype: int .. rubric:: 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. .. py:function:: 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``). :param style: ``"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``. :type style: {"skm", "skm-reactions"} :param network: Cytoscape network, SUID or name (default: the current network). :type network: int or str, optional :returns: The style name (*SKM* or *SKM-reactions*). :rtype: str .. py:function:: 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 :func:`clear_highlights` to undo them. :param nodes: Nodes to highlight (names not in the network are skipped, with a warning). :type nodes: node or iterable of nodes :param color: Fill, label and border colours, as hex (``"#FF0000"``). :type color: str, optional :param label_color: Fill, label and border colours, as hex (``"#FF0000"``). :type label_color: str, optional :param border_color: Fill, label and border colours, as hex (``"#FF0000"``). :type border_color: str, optional :param border_width: Sizes in pixels. :type border_width: float, optional :param node_height: Sizes in pixels. :type node_height: float, optional :param node_width: Sizes in pixels. :type node_width: float, optional :param network: Cytoscape network, SUID or name (default: the current network). :type network: int or str, optional :returns: The names of the highlighted nodes. :rtype: list of str .. py:function:: highlight_edges(edges, color, skip_edges=None, edge_line_width=10, directed=True, network=None) Highlight edges with style bypasses (colour and line width). :param edges: Edges as (u, v) or (u, v, key) tuples, e.g. from :func:`skm_tools.paths.path_edges`. All parallel edges between u and v are highlighted. :type edges: iterable of tuple :param color: Edge colour, as hex. :type color: str :param skip_edges: (u, v) pairs not to highlight, e.g. edges already highlighted in another colour. :type skip_edges: iterable of tuple, optional :param edge_line_width: Line width in pixels (default 10). :type edge_line_width: float :param directed: 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). :type directed: bool :param network: Cytoscape network, SUID or name (default: the current network). :type network: int or str, optional :returns: The (u, v) pairs highlighted: found in the network, and not skipped. :rtype: list of tuple .. py:function:: 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`. :param nodes: The path, as a list of nodes. :type nodes: list :param color: Node fill and edge colour, as hex. :type color: str :param skip_nodes: Nodes not to highlight. :type skip_nodes: iterable, optional :param skip_edges: (u, v) pairs not to highlight. :type skip_edges: iterable of tuple, optional :param label_color: Node label and border colours (default white and black). :type label_color: str :param border_color: Node label and border colours (default white and black). :type border_color: str :param border_width: Node border and edge widths in pixels (default 10). :type border_width: float :param edge_line_width: Node border and edge widths in pixels (default 10). :type edge_line_width: float :param directed: If False, also highlight the edge v -> u of each step u, v (for paths from ``get_paths(..., directed=False)``). :type directed: bool :param network: Cytoscape network, SUID or name (default: the current network). :type network: int or str, optional :returns: * **nodes** (*list*) -- The path's nodes that were highlighted. * **edges** (*list of tuple*) -- The path's (u, v) edges that were highlighted. .. py:function:: clear_highlights(nodes=None, edges=None, network=None) Remove the highlights (style bypasses) of :func:`highlight_nodes`, :func:`highlight_edges` and :func:`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. :param nodes: Nodes to clear. Default: all nodes, if `edges` isn't given either. :type nodes: iterable, optional :param edges: (u, v) edges to clear. Default: all edges, if `nodes` isn't given either. :type edges: iterable of tuple, optional :param network: Cytoscape network, SUID or name (default: the current network). :type network: int or str, optional .. py:function:: 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 ()"``), then copies the network's current style to `style_name`, with colour mappings on them. :param g: Graph the paths were found in (to find their edges, see :func:`skm_tools.paths.path_edges`). :type g: networkx.Graph :param sources: The source of each search (its label in ``edge-priority``). :type sources: list :param path_lists: Paths found by each search: one list of paths per source, in the same order. :type path_lists: list of list :param edge_colors: Hex colour for the edges of each source's paths, one per source. :type edge_colors: list of str, optional :param node_colors: 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. :type node_colors: list of str, optional :param style_name: Name of the new style (default: ``"-shortest-paths"``; replaced if it exists). :type style_name: str, optional :param network: Cytoscape network, SUID or name (default: the current network). :type network: int or str, optional :returns: The style name. :rtype: str .. py:function:: 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. :param name: Name of the clone. :type name: str, optional :param collection: Name of the clone's new collection. :type collection: str, optional :param network: Cytoscape network to clone, SUID or name (default: the current network). :type network: int or str, optional :returns: SUID of the clone. :rtype: int .. py:function:: copy_style(style, new_style, networks=(), overwrite=False) Copy a visual style, and apply the copy to `networks`. :param style: Visual style to copy. :type style: str :param new_style: Name of the copy. :type new_style: str :param networks: Networks to apply the copy to. :type networks: iterable of int or str, optional :param overwrite: If a style `new_style` exists: replace it (True), or raise ValueError (False, default). Cytoscape itself would add a number to the name. :type overwrite: bool :returns: `new_style`. :rtype: str .. py:function:: 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 :func:`extend_discrete_mapping`). Changes `g` in place. :param g: :type g: networkx.Graph :param column: Attribute to set. :type column: str :param flags: Node -> flag (str). Nodes not in `g` are ignored. :type flags: dict :param fallback: Attribute whose value the other nodes get (default ``"node_type"``); None: an empty string. :type fallback: str or None :returns: `g`. :rtype: networkx.Graph .. py:function:: 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 (:func:`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). :param style: Style to change (e.g. a copy of the SKM style, see :func:`copy_style`). :type style: str :param visual_property: E.g. ``"NODE_SHAPE"``, ``"NODE_BORDER_PAINT"``, ``"NODE_BORDER_WIDTH"``, ``"NODE_FILL_COLOR"``. :type visual_property: str :param column: Node column to map on. Must exist in `network` (py4cytoscape checks it). :type column: str :param extra: Column value -> property value, added to (or replacing) the existing entries. :type extra: dict :param base_style: Style whose mapping of `visual_property` provides the existing entries (default: `style`). :type base_style: str, optional :param network: Network with the column (default: the current network). :type network: int or str, optional :returns: The mapped column value -> property value. :rtype: dict .. py:function:: 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). :param keep: SUID of the network to keep. :type keep: int :returns: SUIDs of the deleted networks. :rtype: list of int .. py:function:: subnetwork_edge_induced(edges, parent_suid, name='subnetwork (edge induced)') New Cytoscape network with only the given edges (and their nodes). :param edges: Edges as (u, v) or (u, v, key) tuples; all parallel edges between u and v are included. :type edges: iterable of tuple :param parent_suid: SUID of the Cytoscape network to take them from. :type parent_suid: int :param name: Name of the new network. :type name: str :returns: SUID of the new network. :rtype: int .. py:function:: subnetwork_edge_induced_from_paths(g, paths, parent_suid, name='subnetwork (edge induced)') New Cytoscape network with only the edges along `paths`. :param g: Graph the paths were found in (to find their edges, see :func:`skm_tools.paths.path_edges`). :type g: networkx.Graph :param paths: Paths as lists of nodes, e.g. from :func:`skm_tools.paths.get_paths`. :type paths: list of list :param parent_suid: SUID of the Cytoscape network to take them from. :type parent_suid: int :param name: Name of the new network. :type name: str :returns: SUID of the new network. :rtype: int .. py:function:: 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 :func:`subnetwork_edge_induced`. :param nodes: Nodes to include (names not in the network are skipped, with a warning). :type nodes: iterable :param parent_suid: SUID of the Cytoscape network to take them from. :type parent_suid: int :param name: Name of the new network. :type name: str :returns: SUID of the new network. :rtype: int .. py:function:: get_or_create_subnetwork(nodes, parent_suid, name) The network called `name` in the collection of `parent_suid`, created with :func:`subnetwork_node_induced` if it doesn't exist yet. For re-running notebook cells without making duplicate networks. :param nodes: Nodes to include, if the network is created. :type nodes: iterable :param parent_suid: SUID of the Cytoscape network to take them from. :type parent_suid: int :param name: Name of the network. :type name: str :returns: SUID of the (existing or new) network. :rtype: int .. py:function:: 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 :func:`skm_tools.neighbors.neighborhood_nodes`), so the selection in Cytoscape doesn't change. :param g: The network loaded as `parent_suid` (or the part of it to search). :type g: networkx.Graph :param nodes: Nodes whose neighbourhood to include. :type nodes: iterable :param parent_suid: SUID of the Cytoscape network to take them from. :type parent_suid: int :param depth: Number of steps (default 1: first neighbours). :type depth: int or None :param direction: For directed graphs: neighbours in both directions (default), downstream or upstream. :type direction: {"both", "out", "in"} :param name: Name of the new network. :type name: str :returns: SUID of the new network. :rtype: int .. py:function:: 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. :param positions: ``{node: (x, y)}`` (as returned by the networkx layout functions), or a DataFrame indexed by node name with columns ``x`` and ``y``. :type positions: dict or pandas.DataFrame :param flip_y: Mirror the y coordinates (default True): in networkx and graphviz y grows upwards, in Cytoscape downwards. :type flip_y: bool :param scale: Multiply the coordinates by this (default 1). networkx layouts are within -1 and 1, so use e.g. ``scale=500`` for them. :type scale: float :param network: Cytoscape network, SUID or name (default: the current network). :type network: int or str, optional .. py:data:: IMAGE_POSITIONS .. py:function:: load_node_images(images, column, network=None, unique_dir=None, to_png=False) Load image file locations into a node table column, for :func:`show_node_images`. :param images: Node name -> image path (e.g. from :func:`skm_tools.node_images.match_files_to_nodes`). Nodes not in the network are ignored. :type images: dict :param column: Node table column to load them into, e.g. ``"image_heat_Desiree"``. :type column: str :param network: Cytoscape network, SUID or name (default: the current network). :type network: int or str, optional :param unique_dir: Copy the images to this folder first, each to a new, unique file name (see :func:`skm_tools.node_images.unique_image_copies`), so that Cytoscape's image cache can't show an old or a different image instead. :type unique_dir: str or pathlib.Path, optional :param to_png: With `unique_dir`: convert SVG images to PNG. :type to_png: bool :returns: Node -> the path loaded. :rtype: dict .. py:function:: show_node_images(style, column, slot=1, position='below', size=110) Show the images in a node table column (see :func:`load_node_images`) in a style. Maps the column to one of Cytoscape's custom graphics slots (``NODE_CUSTOMGRAPHICS_``), so a node can show several images (e.g. one per data type) in different slots and positions. :param style: 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 :func:`copy_style`. :type style: str :param column: Node table column with the image locations. :type column: str :param slot: Custom graphics slot, 1 to 9 (default 1). :type slot: int :param position: ``"below"`` (default), ``"above"``, ``"left"``, ``"right"``, ``"center"``, a corner (``"top-right"``, ``"top-left"``, ``"bottom-right"``, ``"bottom-left"``: centred on it, e.g. for :func:`~skm_tools.node_images.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). :type position: str :param size: Image size (default 110). The images aren't resized with the node. :type size: float .. py:function:: 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 :func:`load_node_images` and :func:`show_node_images`. :param create_png: ``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. :type create_png: callable :param style: 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, ``"