Overview of py4cytoscape¶
py4cytoscape is a Python package that communicates with Cytoscape via its REST API, providing access to a set over 250 functions that enable control of Cytoscape from within standalone and Notebook Python programming environments. It provides nearly identical functionality to RCy3, an R package in Bioconductor available to R programmers.
py4cytoscape provides:
functions that can be leveraged from Python code to implement network biology-oriented workflows;
access to user-written Cytoscape Apps that implement Cytoscape Automation protocols;
logging and debugging facilities that enable rapid development, maintenance, and auditing of Python-based workflow;
two-way conversion between the igraph and NetworkX graph packages, which enables interoperability with popular packages available in public repositories (e.g., PyPI); and
the ability to painlessly work with large data sets generated within Python or available on public repositories (e.g., STRING and NDEx);
execute Python code on the Cytoscape workstation or in Jupyter Notebooks on local or remote servers.
With py4cytoscape, you can leverage Cytoscape to:
load and store networks in standard and nonstandard data formats;
visualize molecular interaction networks and biological pathways;
integrate these networks with annotations, gene expression profiles and other state data;
analyze, profile, and cluster these networks based on integrated data, using new and existing algorithms.
py4cytoscape enables an agile collaboration between powerful Cytoscape, Python libraries, and novel Python code so as to realize auditable, reproducible and sharable workflows.
Look to the Tutorials section to get started with py4cytoscape.
Look to the Install section for installation instructions.
Look to the Reference section to see details on py4cytoscape functions.
Look to the Concepts section to see read about important py4cytoscape topics, including how to use py4cytoscape from a Jupyter Notebook running on a remote server.
Note that py4cytoscape and RCy3 functions implement a common interface called the Cytoscape Automation API Definition.
Audience¶
The audience for py4cytoscape includes biologists, mathematicians, physicists, biologists, computer scientists, and social scientists. A running sample of research based on Cytoscape can be found on Tumblr. Cytoscape provides tutorials, videos, and automation vignettes.
Google Scholar reports that Cytoscape was cited in over 10,000 in academic papers in 2019, most of which executed Cytoscape via the traditional mouse and keyboard. py4cytoscape can automate these results as a means of achieving reproducible science.
Python¶
Python is a powerful programming language that allows simple and flexible representations of networks as well as clear and concise expressions of network algorithms. Python has a vibrant and growing ecosystem of packages that can be used in combination with py4cytoscape to integrate with traditional workflow engines (e.g., Gene Pattern and Galaxy) to produce robust end-to-end workflows.
In order to make the most out of py4cytoscape you should know how to write basic programs in Python. Among the many guides to Python, we recommend the Python documentation and Python in a Nutshell.
Free Software¶
py4cytoscape is free software; you can redistribute it and/or modify it under the terms of the License. We welcome contributions. Join us on GitHub.
History¶
The original Python libraries for Cytoscape were written by Keiichiro Ono in 2015 as an interface to the then-new CyREST automation interface. Its original name was py2cytoscape. It was further evolved through 2019 by Kozo Nishida and Jorge Bouças.
In late 2019, py4cytoscape was undertaken by Barry Demchak as a replacement for py2cytoscape. It implemented the API defined by RCy3, an R package in Bioconductor developed by a Cytoscape Automation working group consisting of Alex Pico (primary author), Mark Grimes, Julia Gustavsen, Shraddha Pai, Ruth Isserlin, and Barry Demchak. RCy3 was based on prior work contributed by Paul Shannon, Tanja Muetze, Georgi Kolishkovski and Keiichiro Ono.
We intend to keep the function definitions available through py4cytoscape and RCy3 consistent and synchronized going forward, and to re-integrate unique features found only in py2cytoscape. This common interface is called the Cytoscape Automation API Definition.
Documentation¶
- Release
0.0.3
- Date
Oct 05, 2020
Install¶
py4cytoscape
requires Python 3.6, 3.7, or 3.8. If you do not already
have a Python environment configured on your computer, please see the
instructions for installing the full scientific Python stack.
Note
If you are on Windows and want to install optional packages (e.g., scipy), then you will need to install a Python distributions such as Anaconda, Enthought Canopy, Python(x,y), WinPython, or Pyzo. If you use one of these Python distribution, please refer to their online documentation.
PyCharm and other integrated development environments often install their own Python distributions.
Below we assume you have the default Python environment already configured on
your computer and you intend to install py4cytoscape
inside of it. If you want
to create and work with Python virtual environments, please follow instructions
on venv and virtual
environments.
First, make sure you have the latest version of pip
(the Python package manager)
installed. If you do not, refer to the Pip documentation and install pip
first.
Cytoscape Prerequisite¶
To exercise py4cytoscape
, you must first have downloaded, installed, and
executed Cytoscape. If you have not already done this, please refer to the Launching
Cytoscape
instructions.
Note
Cytoscape and py4cytoscape
must be running on the same workstation or
virtual machine. py4cytoscape
communicates with Cytoscape via a localhost
connection, which precludes py4cytoscape
from accessing Cytoscape
remotely. While this limitation can be overcome by configuring py4cytoscape
or
supplying the Cytoscape URL in py4cytoscape
calls, this can become a complex
networking problem if firewalls and routers are present on the network.
Install the development version (Python Console or Jupyter Notebook)¶
Install the current release of py4cytoscape
with pip
:
pip install python-igraph requests pandas networkx
pip install py4cytoscape
cd py4cytoscape
python setup.py install # or python setup.py install --user
To install the latest py4cytoscape development version, instead
of pip install py4cytoscape
, use:
git clone git://github.com/cytoscape/py4cytoscape
Verify Cytoscape connection¶
To verify that py4cytoscape
is properly installed and able to communicate with
Cytoscape, execute the following in a Python Console or Jupyter Notebook
(after starting Cytoscape):
import py4cytoscape as py4
dir(py4)
py4.cytoscape_ping()
py4.cytoscape_version_info()
This will import py4cytoscape
into the Python namespace, print a (long) list
of py4cytoscape
entrypoints, and then demonstrate a connection to Cytoscape
by collecting Cytoscape information.
Testing¶
py4cytoscape
uses the Python unittest
testing package. You can learn more
about unittest
on its homepage.
To execute tests from an OS command line, set the current directory to
the py4cytoscape
package directory. Then, establish the execution environment:
cd tests
set PYTHONPATH=..
Note
You must start Cytoscape before executing any tests. For Cytoscape execution, the current directory should be the Cytoscape program directory.
The py4cytoscape
test suite consists of a number of sub-suites. Executing one
or two of them is relatively quick. To execute a single sub-suite
(e.g., test_apps.py
):
python -m unittest test_apps.py
To execute more than one sub-suite (e.g., test_apps.py
and test_filters.py
):
python -m unittest test_apps.py test_filters.py
To execute the entire test suite:
python -m unittest
To execute a single test (e.g., test_get_app_information) in a single test suite:
python -m unittest test_apps.AppsTests.test_get_app_information
Note
To send test output to a file, redirect stderr and console:
python -m unittest 2>stderr.log 1>cons.log
Some tests require console input, and without console prompts, the tests will appear to stall. To avoid executing such tests, set the PY4CYTOSCAPE_SKIP_UI_TESTS environment variable described below.
The runalltests.bat
script contains all commands needed to run all tests
with all environment variables set. It must be run with the tests
directory
as the current directory.
Note
To execute tests with less console debug output, set this environment variable before executing tests:
set PY4CYTOSCAPE_SUMMARY_LOGGER=FALSE
To further configure logging, see the Logging file.
Note
To execute tests without showing test names as tests execute, set this environment variable before executing the tests:
set PY4CYTOSCAPE_SHOW_TEST_PROGRESS=FALSE
Note
To skip execution of tests that require user input, set this environment variable before executing tests:
set PY4CYTOSCAPE_SKIP_UI_TESTS=TRUE
Note
When executing a large number of tests, we recommend that all three environment variables be set as described above.
Note
When executing tests in PyCharm, you can set environment
variables using the Run | Edit Configurations...
menu item.
Tutorials¶
You can try the following tutorials in your web browser using Binder.
Launch a Binder instance by clicking the following Binder badge. (It may take some time for the instance to start up.)
Launch Linux desktop by clicking the
New ▼
button ->desktop
.

Right click the Linux Desktop and click
Open Terminal Here
, and runbash ~/cytoscape-unix-3.8.0/cytoscape.sh
(This command launches Cytoscape Desktop).


Click on the ipynb file for the tutorial you would like to try.

Basic Data Visualization¶
Cytoscape is an open source software platform for integrating, visualizing, and analyzing measurement data in the context of networks.
This tutorial presents a scenario of how expression and network data can be combined to tell a biological story and includes these concepts:
Visualizing networks using expression data.
Filtering networks based on expression data.
Assessing expression data in the context of a biological network.
Loading Network¶
You can download the demo network session file to your current working directory by running…
[5]:
!wget https://nrnb.org/data/BasicDataVizDemo.cys
--2020-07-02 23:40:44-- https://nrnb.org/data/BasicDataVizDemo.cys
Resolving nrnb.org (nrnb.org)... 185.199.108.153
Connecting to nrnb.org (nrnb.org)|185.199.108.153|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1390524 (1.3M) [application/octet-stream]
Saving to: ‘BasicDataVizDemo.cys’
BasicDataVizDemo.cy 100%[===================>] 1.33M 8.48MB/s in 0.2s
2020-07-02 23:40:45 (8.48 MB/s) - ‘BasicDataVizDemo.cys’ saved [1390524/1390524]
Now open the demo network using…
[6]:
import py4cytoscape as p4c
p4c.set_summary_logger(False)
p4c.open_session(file_location="./BasicDataVizDemo.cys")
Opening /content/BasicDataVizDemo.cys...
[6]:
{}
Now you should see a network like this.
[7]:
p4c.export_image(filename="BasicDataVizDemo.png")
from IPython.display import Image
Image('BasicDataVizDemo.png')
[7]:

Visualizing Expression Data on Networks¶
Probably the most common use of expression data in Cytoscape is to set the visual properties of the nodes (color, shape, border) in a network according to expression data. This creates a powerful visualization, portraying functional relation and experimental response at the same time. Here, we will show an example of doing this.
The data used in this example is from yeast, and represents an experiment of perturbations of the genes Gal1, Gal4, and Gal80, which are all yeast transcription factors.
For this tutorial, the experimental data was part of the Cytoscape session file you loaded earlier, and is visible in the Node Table:
You can select nodes in the network by
[8]:
p4c.select_nodes(['YDL194W', 'YLR345W'], by_col='name')
[8]:
{'edges': [], 'nodes': [66, 61]}
Selecting one or more nodes in the network will update the Node Table to show only the corresponding row(s).
We can now use the data to manipulate the visual properties of the network by mapping specific data columns to visual style properties:
The gal80Rexp expression values will be mapped to node color; nodes with low expression will be colored blue, nodes with high expression will be colored red.
Significance for expression values will be mapped to Node Border Width, so nodes with significant changes will appear with a thicker border.
Set Node Fill Color¶
Click on the Style tab in the Control Panel. And you can set node fill color by
[9]:
gal80Rexp_score_table = p4c.get_table_columns(table='node', columns='gal80Rexp')
[10]:
gal80Rexp_score_table.head()
[10]:
gal80Rexp | |
---|---|
61 | 0.449 |
62 | 0.448 |
63 | -0.232 |
64 | 0.247 |
65 | 0.94 |
[11]:
gal80Rexp_min = gal80Rexp_score_table.min().values[0]
gal80Rexp_max = gal80Rexp_score_table.max().values[0]
gal80Rexp_center = gal80Rexp_min + (gal80Rexp_max - gal80Rexp_min)/2
[12]:
p4c.set_node_color_mapping('gal80Rexp', [gal80Rexp_min, gal80Rexp_center, gal80Rexp_max], ['#0000FF', '#FFFFFF', '#FF0000'])
[12]:
''
This produces an initial gradient ranging from blue to red for expression values. Notice that the nodes in the network change color.
Set Default Node Color¶
Some nodes in the network don’t have any data, and for those nodes, the default color applies. In our case, the default color is blue, which falls within the spectrum of our blue-red gradient. This is not ideal for data visualization, so a useful trick is to choose a color outside the gradient spectrum to distinguish nodes with no defined expression value.
Still in the Style tab, And you can set default node color to dark gray by
[13]:
p4c.set_node_color_default('#666666')
[13]:
''
Set Node Border Width¶
You can set the Border Width
by
[14]:
gal80Rsig_score_table = p4c.get_table_columns(table='node', columns='gal80Rsig')
gal80Rsig_min = gal80Rsig_score_table.min().values[0]
gal80Rsig_max = gal80Rsig_score_table.max().values[0]
p4c.set_node_border_width_mapping('gal80Rsig', table_column_values=[gal80Rsig_min, gal80Rsig_max], widths=[10, 30])
[14]:
''
This defines the node border width over the range of gal80Rsig
column p-values like
Double-clicking on the diagonal graph to the right of Current Mapping
will bring up a window similar to the one below.
Layouts¶
An important aspect of network visualization is the layout, meaning the positioning of nodes and edges. Our network had a preset layout in the original file you imported, but this can be changed.
Let’s change the layout to Degree Sorted Circle Layout by
[15]:
p4c.layout_network('degree-circle')
[15]:
{}
[16]:
p4c.export_image(filename='degree-circle.png')
Image('degree-circle.png')
[16]:

In this layout, nodes are sorted by degree (connectedness), with the highest degree node at the 6 o’clock position, and remaining nodes are sorted counter clock-wise based on decreasing degree.
For this network, a degree-sorted circle layout may not be the most effective. Instead, let’s try a force-directed layout instead, which may work better with this network.
[17]:
p4c.layout_network('force-directed')
[17]:
{}
[18]:
p4c.export_image(filename='force-directed.png')
Image('force-directed.png')
[18]:

Cytoscape supports many different layout algorithms, described in detail in the Cytoscape manual.
Select Nodes¶
Cytoscape allows you to easily filter and select nodes and edges based on data attributes. Next, we will select a subset of nodes with high expression in the gal80 knockout:
Let’s create column filter for Node: gal80Rexp by
[19]:
p4c.create_column_filter('myFilter', 'gal80Rexp', 2.00, "GREATER_THAN")
No edges selected.
[19]:
{'edges': None, 'nodes': ['YBR018C', 'YBR020W', 'YBR019C']}
You should now see only a few nodes in the network selected (highlighted yellow).
[20]:
p4c.export_image(filename='column-filter.png')
Image('column-filter.png')
[20]:

Expand Selection and Create New Network¶
We have now selected only the few top expressing nodes. To see the context of these nodes in the larger network, we can expand the selection of nodes to include the nodes connecting to the selected nodes, i.e. the first neighbors. Once we have that larger selection, we can create a new network.
Select the first neighbors of selected nodes by
[21]:
p4c.select_first_neighbors()
[21]:
{'edges': [], 'nodes': [239, 240, 137, 234, 235, 237, 238]}
[22]:
p4c.export_image(filename='first-neighbors.png')
Image('first-neighbors.png')
[22]:

Digging into the biology of this network, it turns out that GAL4 is repressed by GAL80. Both nodes (GAL4 and GAL11) show fairly small changes in expression, and neither change is statistically significant: they are pale blue with thin borders. These slight changes in expression suggest that the critical change affecting the red nodes might be somewhere else in the network, and not either of these nodes. GAL4 interacts with GAL80, which shows a significant level of repression: it is medium blue with a thicker border.
Note that while GAL80 shows evidence of significant repression, most nodes interacting with GAL4 show significant levels of induction: they are rendered as red rectangles. GAL11 is a general transcription co-factor with many interactions.
Putting all of this together, we see that the *transcriptional activation activity of Gal4 is repressed by Gal80*. So, repression of Gal80 increases the transcriptional activation activity of Gal4. Even though the expression of Gal4 itself did not change much, *the Gal4 transcripts were much more likely to be active transcription factors when Gal80 was repressed.* This explains why there is so much up-regulation in the vicinity of Gal4.
In summary, we have:
Explored a yeast interactome from a transcription factor knockout experiment
Created a visual style using expression value as node color and with border width mapped to significance
Selected high expressing genes and their neighbors and created a new network
Finally, we can now export this network as a publication-quality image….
Saving Results¶
Cytoscape provides a number of ways to save results and visualizations:
As a session:
[23]:
p4c.save_session('basic-data-visualization.cys')
[23]:
{}
As an image:
[24]:
p4c.export_image('basic-data-visualization', type='PDF')
p4c.export_image('basic-data-visualization', type='PNG')
p4c.export_image('basic-data-visualization', type='JPEG')
p4c.export_image('basic-data-visualization', type='SVG')
p4c.export_image('basic-data-visualization', type='PS')
[24]:
{'file': '/content/basic-data-visualization.ps'}
To a public repository:
p4c.export_network_to_ndex('userid', 'password', True)
As a graph format file (Formats: “CX JSON”, “Cytoscape.js JSON”, “GraphML”, “XGMML”, “SIF”,…):
[25]:
p4c.export_network('basic-data-visualization', 'CX')
p4c.export_network('basic-data-visualization', 'cyjs')
p4c.export_network('basic-data-visualization', 'graphML')
p4c.export_network('basic-data-visualization', 'xGMML')
p4c.export_network('basic-data-visualization', 'SIF')
[25]:
{'file': '/content/basic-data-visualization.sif'}
[ ]:
Importing data¶
This notebook will show you how to import a DataFrame
of node attributes into Cytoscape as Node Table columns. The same approach works for edge and network attriubutes.
[5]:
import py4cytoscape as p4c
p4c.set_summary_logger(False)
p4c.cytoscape_ping()
You are connected to Cytoscape!
Always Start with a Network¶
When importing data, you are actually performing a merge function of sorts, appending columns to nodes (or edges) that are present in the referenced network. Data that do not match elements in the network are effectively discarded upon import.
So, in order to demonstrate data import, we first need to have a network. This command will import network files in any of the supported formats (e.g., SIF, GML, XGMML, etc).
[6]:
!wget https://raw.githubusercontent.com/cytoscape/RCy3/master/inst/extdata/galFiltered.sif
--2020-07-02 18:17:45-- https://raw.githubusercontent.com/cytoscape/RCy3/master/inst/extdata/galFiltered.sif
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 151.101.0.133, 151.101.64.133, 151.101.128.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|151.101.0.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 6822 (6.7K) [text/plain]
Saving to: ‘galFiltered.sif’
galFiltered.sif 100%[===================>] 6.66K --.-KB/s in 0s
2020-07-02 18:17:45 (70.3 MB/s) - ‘galFiltered.sif’ saved [6822/6822]
[7]:
!head galFiltered.sif
YKR026C pp YGL122C
YGR218W pp YGL097W
YGL097W pp YOR204W
YLR249W pp YPR080W
YLR249W pp YBR118W
YLR293C pp YGL097W
YMR146C pp YDR429C
YDR429C pp YFL017C
YPR080W pp YAL003W
YBR118W pp YAL003W
[8]:
p4c.import_network_from_file("./galFiltered.sif")
[8]:
{'networks': [51], 'views': [750]}
[9]:
p4c.export_image(filename="galFiltered.png")
from IPython.display import Image
Image('galFiltered.png')
[9]:

You should now see a network with just over 300 nodes. If you look at the Node Table, you’ll see that there are no attributes other than node names. Let’s fix that…
Import Data¶
You can import data into Cytoscape from any DataFrame
in Python as long as it contains row.names (or an arbitrary column) that match a Node Table column in Cytoscape. In this example, we are starting with a network with yeast identifiers in the “name” column. We also have a CSV file with gene expression data values keyed by yeast identifiers here:
[10]:
import pandas as pd
url="https://raw.githubusercontent.com/cytoscape/RCy3/master/inst/extdata/galExpData.csv"
df=pd.read_csv(url)
[11]:
df.head()
[11]:
name | COMMON | gal1RGexp | gal1RGsig | gal4RGexp | gal4RGsig | gal80Rexp | gal80Rsig | |
---|---|---|---|---|---|---|---|---|
0 | YDL194W | SNF3 | 0.139 | 1.804300e-02 | 0.333 | 3.396100e-02 | 0.449 | 0.011348 |
1 | YDR277C | MTH1 | 0.243 | 2.190000e-05 | 0.192 | 2.804400e-02 | 0.448 | 0.000573 |
2 | YBR043C | YBR043C | 0.454 | 5.370000e-08 | 0.023 | 9.417800e-01 | 0.000 | 0.999999 |
3 | YPR145W | ASN1 | -0.195 | 3.170000e-05 | -0.614 | 1.150000e-07 | -0.232 | 0.001187 |
4 | YER054C | GIP2 | 0.057 | 1.695800e-01 | 0.206 | 6.200000e-04 | 0.247 | 0.004360 |
Note: there may be times where your network and data identifers are of different types. This calls for identifier mapping. py4cytoscape provides a function to perform ID mapping in Cytoscape:
[12]:
help(p4c.map_table_column)
Help on function map_table_column in module py4cytoscape.tables:
map_table_column(column, species, map_from, map_to, force_single=True, table='node', namespace='default', network=None, base_url='http://localhost:1234/v1')
Map Table Column.
Perform identifier mapping using an existing column of supported identifiers to populate a new column with
identifiers mapped to the originals.
Supported species: Human, Mouse, Rat, Frog, Zebrafish, Fruit fly, Mosquito, Worm, Arabidopsis thaliana, Yeast,
E. coli, Tuberculosis. Supported identifier types (depending on species): Ensembl, Entrez Gene, Uniprot-TrEMBL,
miRBase, UniGene, HGNC (symbols), MGI, RGD, SGD, ZFIN, FlyBase, WormBase, TAIR.
Args:
column (str): Name of column containing identifiers of type specified by ``map.from``
species (str): Common name for species associated with identifiers, e.g., Human. See details.
map_from (str): Type of identifier found in specified ``column``. See details.
map.to (str): Type of identifier to populate in new column. See details.
force.single (bool): Whether to return only first result in cases of one-to-many mappings; otherwise
the new column will hold lists of identifiers. Default is TRUE.
table (str): name of Cytoscape table to load data into, e.g., node, edge or network; default is "node"
namespace (str): Namespace of table. Default is "default".
network (SUID or str or None): Name or SUID of a network. Default is the
"current" network active in Cytoscape.
base_url (str): Ignore unless you need to specify a custom domain,
port or version to connect to the CyREST API. Default is http://localhost:1234
and the latest version of the CyREST API supported by this version of py4cytoscape.
Returns:
dataframe: contains map_from and map_to columns.
Warnings:
If map_to is not unique, it will be suffixed with an incrementing number in parentheses, e.g.,
if mapIdentifiers is repeated on the same network. However, the original map_to column will be returned regardless.
Raises:
HTTPError: if table or namespace or table doesn't exist in network
CyError: if network name or SUID doesn't exist, or if mapping parameter is invalid
requests.exceptions.RequestException: if can't connect to Cytoscape or Cytoscape returns an error
Examples:
>>> map_table_column('name','Yeast','Ensembl','SGD')
name SGD
17920 YER145C S000000947
17921 YMR058W S000004662
17922 YJL190C S000003726
...
Check out the Identifier mapping tutorial for detailed examples.
Now we have a DataFrame
that includes our identifiers in a column called “name”, plus a bunch of data columns. Knowing our key columns, we can now perform the import:
[ ]:
p4c.load_table_data(df, data_key_column="name")
'Success: Data loaded in defaultnode table'
If you look back at the Node Table, you’ll now see that the corresponding rows of our DataFrame
have been imported as new columns.
Note: we relied on the default values for table (“node”) and ``table_key_column`` (“name”), but these can be specified as well. See help docs for parameter details.
[ ]:
help(p4c.load_table_data)
Help on function load_table_data in module py4cytoscape.tables:
load_table_data(data, data_key_column='row.names', table='node', table_key_column='name', namespace='default', network=None, base_url='http://localhost:1234/v1')
Loads data into Cytoscape tables keyed by row.
This function loads data into Cytoscape node/edge/network
tables provided a common key, e.g., name. Data.frame column names will be
used to set Cytoscape table column names.
Numeric values will be stored as Doubles in Cytoscape tables.
Integer values will be stored as Integers. Character or mixed values will be
stored as Strings. Logical values will be stored as Boolean. Lists are
stored as Lists by CyREST v3.9+. Existing columns with the same names will
keep original type but values will be overwritten.
Args:
data (dataframe): each row is a node and columns contain node attributes
data_key_column (str): name of data.frame column to use as key; ' default is "row.names"
table (str): name of Cytoscape table to load data into, e.g., node, edge or network; default is "node"
namespace (str): Namespace of table. Default is "default".
network (SUID or str or None): Name or SUID of a network. Default is the
"current" network active in Cytoscape.
base_url (str): Ignore unless you need to specify a custom domain,
port or version to connect to the CyREST API. Default is http://localhost:1234
and the latest version of the CyREST API supported by this version of py4cytoscape.
Returns:
str: 'Success: Data loaded in <table name> table' or 'Failed to load data: <reason>'
Raises:
HTTPError: if table or namespace or table doesn't exist in network
CyError: if network name or SUID doesn't exist
requests.exceptions.RequestException: if can't connect to Cytoscape or Cytoscape returns an error
Examples:
>>> data = df.DataFrame(data={'id':['New1','New2','New3'], 'newcol':[1,2,3]})
>>> load_table_data(data, data_key_column='id', table='node', table_key_column='name')
'Failed to load data: Provided key columns do not contain any matches'
>>> data = df.DataFrame(data={'id':['YDL194W','YDR277C','YBR043C'], 'newcol':[1,2,3]})
>>> load_table_data(data, data_key_column='id', table='node', table_key_column='name', network='galfiltered.sif')
'Success: Data loaded in defaultnode table'
[ ]:
Concepts¶
py4cytoscape is a Python module that interfaces with Cytoscape to enable researchers to write reproducible sequences of network manipulations, visualizations and analyses. py4cytoscape includes functions that accomplish network operations common to many kinds of workflows. Using py4cytoscape, a Python application can:
load a network (from a file, from the NDEx or STRING repositories, or from local Python variables)
operate on the network
retrieve results
The Python application can perform several rounds of network analysis and results retrieval, and mix visualization and analyses with existing Python libraries. Finally, it can repeat the process for one network after another.
py4cytoscape works by connecting to Cytoscape’s CyREST feature, which is the foundation of Cytoscape Automation (FullPaper or WikiPages). The connection is based on standard HTTP networking protocols. For py4cytoscape to work, you must have Cytoscape running on your workstation.
Your Python application can be run in several modes:
Standalone on the workstation that’s already running Cytoscape
In a Jupyter Notebook running on the same workstation as your Cytoscape
In a Jupyter Notebook running on a remote server (e.g., Google Colab or GenePattern Notebook)
This section discusses conceptual and miscellaneous topics relating to py4cytoscape use:
Missing Functions shows how to call Cytoscape functions not covered in py4cytoscape.
Calling Cytoscape Apps shows how to call Cytoscape apps that support automation.
Jupyter Notebook shows how to use py4cytoscape from within a Jupyter Notebook.
Sandboxing shows how to limit Cytoscape to accessing files in particular directories.
Missing Functions¶
While py4cytoscape provides hundreds of functions, there are still many Cytoscape operations for which py4cytoscape does not provide an equivalent function. However, it does provide mechanisms for you to write your own functions that can invoke many of these Cytoscape operations.
The complete list of invokable Cytoscape operations (either in py4cytoscape or not) is spread across two web pages, differing by the mechanism you would use to invoke them. Using the Cytoscape menus:
Help | Automation | CyREST API
Help | Automation | CyREST Commands API
Both pages enable you to try Cytoscape operations out directly from the web page (via the Swagger interface). Additionally, the Commands panel (View | Show Commands Panel) contains the same material as the CyREST Commands API page, but uses a command line oriented interface for experimentation.
For example, there is no py4cytoscape function for finding the name of
the Cytoscape session. However, the CyREST API page lists this function under the
Session
heading as GET /v1/session/name
. You can
try this function under Swagger by clicking the Try it now! button.
For operations on the CyREST API page, you can write your own Python functions by using one of the following py4cytoscape functions, according to the label on the CyREST API Swagger page:
commands.cyrest_get()
commands.cyrest_post()
commands.cyrest_put()
commands.cyrest_delete()
For the session rename operation, the py4cytoscape call would be:
commands.cyrest_get('session/name', {})
The {} value reflects that there are no parameters to the session/name
operation.
If there were parameters, they would be passed as Python dictionary values (e.g.,
{'param1': 'value1', 'param2': 'value2'}
).
As another example, there is no py4cytoscape function for renaming a filter.
However, the CyREST Commands API page lists this operation under the filter
heading as
POST /v1/commands/filter/rename
. You can try this operation yourself
on the CyREST Commands API page by using Swagger to specify the container
,
name
and newName
parameters and clicking the
Try it now! button. You can do the same thing in the Commands panel by first
entering help filter rename
to find the parameter names and then something like:
filter rename container='filter' name='affinity' newName='myAffinity'
For operations on the CyREST Commands API page, you can write your own Python functions by using one of the following py4cytoscape functions, according to the label on the CyREST Commands API Swagger page:
commands.commands_get()
commands.commands_post()
For the filter rename operation, the py4cytoscape call would be:
commands.commands_post('filter rename container="filter" name="affinity" newName="myAffinity"')
For commands.cyrest* and commands.commands* functions, you can determine the return result by trying the equivalent Cytoscape operation using Swagger’s Try it now! button.
Calling Cytoscape Apps¶
py4cytoscape includes operations corresponding to functions in a number of apps delivered with Cytoscape. However, there are many more App Store apps for which py4cytoscape provides no function. You can still call these apps’ functions using the techniques described in the Missing Functions section.
To find out which apps are automation-enabled, you can visit the App Store and click on the automation category on the left. At this writing, there are over 40 apps, only a few of which are delivered with Cytoscape – see the end of this section for a list.
You can also determine whether a specific app (e.g., MCODE) is enabled for automation by viewing its App Store page (e.g., http://apps.cytoscape.org/apps/mcode). If the gear icon appears below the page title, the app has functions callable via CyREST.
To determine which functions and parameters an app offers, first install the app in Cytoscape (using the Apps | App Manager menu), and then look for the app’s category in either the CyREST Commands API or the Commands panel as described in the Missing Functions section.
For example, to call the MCODE cluster function:
commands.commands_post('mcode cluster degreeCutoff=2 fluff=true fluffNodeDensityCutoff=0.1 haircut=true includeLoops=false kCore=2 maxDepthFromStart=100 network=current nodeScoreCutoff=0.2 scope=NETWORK')
Automation-enabled apps:
aMatReader
Analyzer
AutoAnnotate
autoHGPEC
cddApp
chemViz2
ClueGO
clusterMaker2
copycatLayout
CyAnimator
cyBrowser
cyChart
cyNDEx-2
Cyni Toolbox
Cyrface
CyTargetLinker
CytoCopteR
Diffusion
enhancedGraphics
EnrichmentMap
eXamine
GeneMANIA
ID Mapper
KEGGscape
MCODE
Motif-Discovery
Omics Visualizer
PathLinker
PSFC
ReactomeFIPlugin
RINalyzer
RINspector
RWRMTN
scNetViz
setsApp
stringApp
structureViz2
Synapse Client
WikiPathways
wk-shell-decomposition
WordCloud
Jupyter Notebook¶
Jupyter Notebooks can be executed on a number of platforms, including:
Your Cytoscape workstation (via PyCharm, Anaconda, and others)
Private Notebook servers (e.g., GenePattern Notebook)
Public Notebook servers (e.g., Google Collaboratory)
In each case, your Jupyter Notebook can call py4cytoscape functions that are executed by Cytoscape running on your own workstation.
To call py4cytoscape from a Notebook running on your Cytoscape workstation (a so-called local Notebook), simply use your Python environment to install the py4cytoscape library, then create a Notebook cell that imports the py4cytoscape library and calls a py4cytoscape function:
import py4cytoscape as p4c
p4c.cytoscape_version_info()
Alternatively, you can create a Notebook cell to directly install the py4cytoscape library, and then import it and call a test function:
import sys
!{sys.executable} -m pip install py4cytoscape
import py4cytoscape as p4c
p4c.cytoscape_version_info()
Alternatively, you can create a Notebook cell to load an unreleased version of the py4cytoscape library:
import sys
!{sys.executable} -m pip uninstall -y py4cytoscape
!{sys.executable} -m pip install --upgrade git+https://github.com/cytoscape/py4cytoscape
import py4cytoscape as p4c
p4c.cytoscape_version_info()
Note
To get Jupyter to recognize a py4cytoscape library different from the one first used by your Notebook, you may need to restart the Python kernel – see your Jupyter Notebook documentation.
Jupyter Notebooks that run on remote (private or public) servers can use py4cytoscape to execute Cytoscape functions on your workstation via the Jupyter-Bridge. To use the Jupyter-Bridge, you must create a cell at the beginning of your Notebook:
import sys, IPython
!{sys.executable} -m pip uninstall -y py4cytoscape
# Comment this out to avoid installing the release py4cytoscape
!{sys.executable} -m pip install --upgrade py4cytoscape
# Uncomment this to install the development py4cytoscape
# !{sys.executable} -m pip install --upgrade git+https://github.com/cytoscape/py4cytoscape
import py4cytoscape as p4c
print(f'Loading Javascript client ... {p4c.get_browser_client_channel()} on {p4c.get_jupyter_bridge_url()}')
browser_client_js = p4c.get_browser_client_js()
IPython.display.Javascript(browser_client_js) # Start browser client
All of these scenarios will result in Jupyter Notebook that can call functions executed on the Cytoscape executing in your workstation. Note, though, that without an extra step, Cytoscape generally can’t access files stored in a remote Notebook’s file system, and a remote Notebook can’t access files created by Cytoscape. See the Sandboxing section (below) for an explanation of the file sharing protocol.
Note
In all cases, py4cytoscape calls the Cytoscape running on your private workstation. Cytoscape is not a full server, and can support exactly one Notebook running at a time – multiple simultaneous Notebooks are not supported.
Note
The Jupyter-Bridge does not require any changes to the remote Notebook server and can reach your Cytoscape workstation whether or not it’s behind a firewall.
Sandboxing¶
If you use py4cytoscape to create and run a Python workflow on the same workstation as your Cytoscape instance, you may not need sandbox features (but they may make your Python coding simpler). If you use py4cytoscape from a Jupyter Notebook running on a remote server, you very likely need sandboxing.
For context, py4cytoscape functions (e.g., open_session()
, save_session()
and export_image()
) access files in either Cytoscape’s current working directory or
in a location given by a full path. When Cytoscape starts, its working directory is the
Cytoscape install directory, which has no write permissions and likely contains no user
data files. Very quickly, a Python workflow author learns to pass file names
qualified by full paths that are unique to the workstation.
This situation works well only as long as the workflow executes on the same workstation as it was written. It raises a number of problems:
Workflows with hard-coded paths are not likely to be portable to other Cytoscape workstations, which may have their own (different) file system layouts. This applies equally to both to workflows running on other Cytoscape workstations and those running in a remote Jupyter Notebook server.
To enable collaboration, workflows running on a remote Jupyter Notebook server likely prefer to store Cytoscape data and output on the Notebook server. As the server’s file system is inaccessible to the Cytoscape running on your workstation, there is no path the workflow can pass to make Cytoscape read or write those files.
Sandboxing solves these by defining a dedicated folder on the Cytoscape workstation (in the
user’s CytoscapeConfiguration/filetransfer
folder); files
read and written by Cytoscape are all contained with the folder (aka sandbox).
Sandboxing functions allow files to be transferred
between the Jupyter Notebook server’s native file system
and the sandbox. Thus, a Notebook-based workflow can maintain Cytoscape files on the
Notebook server, and transfer them to/from the Cytoscape workstation (in the sandbox) at
will.
A sandbox can contain both files and directories (which can contain files and directories, too).
A useful side effect of sandboxing is that workflows that use them stand little chance of inadvertantly (or maliciously) corrupting the Cytoscape workstation’s file system. This safety further encourages sharing of workflows between collaboratating researchers.
Notebook workflows are automatically provisioned with a default sandbox (called
default_sandbox
). To get the same effect with Python running standalone on the
Cytoscape workstation, you can explicitly create the default sandbox. (See vignettes below.)
Note
By default, a sandbox is pre-loaded with a copy of Cytoscape’s sampleData
files. This makes it easy for workflow writers to experiment on sample data.
A workflow can define any number of sandboxes and even switch between them. This promotes modularity by facilitating the creation of different sub-workflows with some certainty that a sub-workflow’s files aren’t accidentally corrupted by other sub-workflows over time.
Vignette 1: A workstation-based Python workflow calling Cytoscape to load a session and create a network image.
Without sandboxing, the workflow must provide full (non-portable) paths to Cytoscape files.
open_session('C:\Users\Me\Documents\CyFiles\mySession')
# ...
export_image('C:\Users\Me\Documents\CyFiles\myImage.png')
# ... do something with the .png
This workflow is portable only to workstations that have their Cytoscape files in the
C:\Users\Me\Documents\CyFiles
, which doesn’t seem likely.
Vignette 2: A Notebook-based version of Vignette 1.
A sandbox is automatically created for Notebook-based workflows. The workflow must transfer a session file from the Notebook’s file system to the sandbox, call Cytoscape, and then transfer the result back to the Notebook’s file system for further processing.
sandbox_send_to('data/mySession.cys') # copy session file from Notebook server to workstation
open_session('mySession')
# ...
export_image('myImage.png')
sandbox_get_from('myImage.png', 'data/myImage.png') # copy image file to Notebook server
# ... do something with the .png
This workflow can run on any Notebook server and Cytoscape workstation without knowledge of or risk to the workstation’s file system. Various Python-based libraries can process the .png after it is copied to the Notebook’s file system.
When calling sandbox functions, if you don’t specify the name of a sandbox, the operation is performed on the “current sandbox”.
Vignette 3: A workstation-based Python workflow accesses sandbox-based files
Sandboxes are stored as directories under the user’s CytoscapeConfiguration/filetransfer
folder.
By always maintaining your Cytoscape files in a sandbox folder (instead of elsewhere in the
workstation file system), you get all of the benefits of sandboxing without having to specify non-portable
file paths.
sandbox_set('mySandbox', copy_samples=False, reinitialize=False)
open_session('mySession')
# ...
export_image('myImage.png')
# ... do something with the .png
If Cytoscape files reside in the sandbox a priori, no sandbox_send_to()
or
sandbox_get_from()
calls are needed. Note that to make this workflow run in a remote
Notebook, you’ll still have to add these calls (as in Vignette 2).
Warning
The reinitialize
parameter is needed to prevent the sandbox_set()
call from erasing the sandbox folder’s contents, which is its default behavior.
Note
- Sandbox functions allow the following operations on files and sandboxes:
sandbox_set()
: Create a new sandbox or makes another sandbox the “current sandbox”sandbox_remove()
: Delete a sandbox and its files and directoriessandbox_send_to()
: Transfer a Notebook file to a sandboxsandbox_get_from()
: Transfer a sandbox file to the Notebook file systemsandbox_get_file_info()
: Get sandbox file metadatasandbox_remove_file()
: Remove a sandbox file
Reference¶
- Release
0.0.3
- Date
Oct 05, 2020
Apps¶
Functions for inspecting and managing apps for Cytoscape.
Local Apps¶
|
Disable App. |
|
Enable App. |
|
Retrieve the current status of a Cytoscape app: Installed, Uninstalled or Disabled. |
|
Retrieve list of currently installed Cytoscape apps with updates available. |
|
Retrieve list of currently disabled apps in Cytoscape. |
|
Retrieve list of currently installed apps in Cytoscape. |
|
Retrieve list of apps not currently installed in Cytoscape. |
|
Installs an app in Cytoscape |
|
Uninstall an app from Cytoscape. |
|
Update a Cytoscape app to the latest available version. |
App Store¶
|
Retrieve the name, brief description and version of a Cytoscape app. |
|
Retrieve a list of apps available for installation in Cytoscape. |
|
Opens the Cytoscape App Store in a new tab in your default browser. |
Collections¶
Functions for getting information about network COLLECTIONS.
Collections¶
|
Get Collection List. |
|
Get Collection Name. |
|
Get Collection Networks. |
|
Get Collection Suid. |
Commands¶
Functions for constructing any arbitrary CyREST API or Commands API method via standard GET, PUT, POST and DELETE protocols. These functions handle marshalling and unmarshalling of urls, parameters and returns so that higher-level functions can work with Python-friendly arguments and returns.
CyREST API functions
Commands API functions
Internal functions
CyREST API¶
|
Construct a query, make DELETE call and process the result. |
|
Construct a query, make GET call and process the result. |
|
Construct a query and body, make POST call and process the result. |
|
Construct a query and body, make PUT call and process the result. |
Cytoscape Commands API¶
|
Commands GET. |
|
Commands Help. |
|
Commands POST. |
|
Run a Command. |
Cytoscape Commands¶
|
Command Echo. |
|
Command Open Dialog. |
|
Command Pause. |
|
Command Quit. |
|
Command Run File. |
|
Command Sleep. |
Swagger API-level Documentation¶
|
Open Swagger docs for CyREST Commands API. |
|
Open Swagger docs for CyREST API. |
CyNDEx¶
Functions for communicating with NDEx from within Cytoscape.
Read/Write¶
|
Send a copy of a Cytoscape network to NDEx as a new submission. |
|
Import a network from the NDEx database into Cytoscape. |
|
Update Network In NDEx. |
Utility¶
|
Get Network NDEx Id. |
Cytoscape System¶
Functions for inspecting and managing apps for Cytoscape.
Resources¶
|
Manually call Java’s garbage collection |
|
Returns the memory resources of the server running Cytoscape. |
|
Returns the processor resources of the server running Cytoscape. |
System¶
|
Get the list of available CyREST API versions. |
|
Ping Cytoscape |
|
Return the versions of the current Cytoscape and CyREST API. |
Exceptions¶
Error classes for py4cytoscape.
Filters¶
Functions for working with FILTERS for the selection of nodes and edges in networks, including operations to import and export filters. In the Cytoscape user interface, filters are managed in the Select tab of the Control Panel.
Existing Filters¶
|
Run an existing filter by supplying the filter name. |
|
Saves filters to file in JSON format. |
|
Retrieve list of named filters in current session |
|
Loads filters from a file in JSON format. |
New Filters¶
|
Create Column Filter. |
|
Combine filters to control node and edge selection based on previously created filters. |
|
Create Degree Filter. |
Groups¶
Functions for working with GROUPS in Cytoscape.
Add/Remove Groups and Nodes¶
|
Add the specified nodes and edges to the specified group. |
|
Create a group from the specified nodes. |
|
Create a group of nodes defined by a column value. |
|
Delete one or more groups, while leaving member nodes intact. |
|
Remove the specified nodes and edges from the specified group. |
Existing Groups¶
|
Replace the representation of all of the nodes and edges in a group with a single node. |
|
Replaces the group node with member nodes for a set of groups. |
|
Retrieve information about a group by name or identifier. |
|
Retrieve a list of all group SUIDs in a network. |
Layouts¶
Functions for performing LAYOUTS in addition to getting and setting layout properties.
Perform layout functions
Get layout properties
Set layout properties
Perform Layout¶
|
Apply edge bundling to the network specified. |
|
Clear all edge bends created from edge bundling. |
|
Copy a layout from one network to another. |
|
Apply a layout to a network. |
Layout Properties¶
|
Get Layout Name Mapping. |
|
Retrieve the names of the currently supported layout algorithms. |
|
Returns a list of the tunable properties for the specified layout. |
|
Returns the type of one of the tunable properties (property_name) for the specified layout. |
|
Returns the appropriately typed value of the specified tunable property for the specified layout. |
|
Sets the specified properties for the specified layout. |
Networks¶
Basic Networks¶
Functions for NETWORK management and retrieving information on networks, nodes and edges. Includes all functions that result in the creation of a new network in Cytoscape, in addition to funcitons that extract network models into other useful objects.
General network functions
General node functions
General edge functions
Network creation
Network extraction
Internal functions
Note
Go to network_selection.py for all selection-related functions
Nodes¶
|
Add one or more nodes to a Cytoscape network. |
|
Retrieve the names of all the nodes in the network. |
|
Returns a non-redundant list of first neighbors of the supplied list of nodes or current node selection. |
|
Reports the number of nodes in the network. |
Edges¶
|
Add one or more edges to a Cytoscape network by listing source and target node pairs. |
|
Retrieve the names of all the edges in the network. |
|
Reports the number of the edges in the network. |
|
Returns source, target and edge table row values. |
Network Management¶
|
Makes a copy of a Cytoscape Network with all of its edges and nodes. |
|
Copies a subset of nodes and edges into a newly created subnetwork. |
|
Delete all networks from the current Cytoscape session. |
|
Delete a network from the current Cytoscape session. |
|
Get the number of Cytoscape networks in the current Cytoscape session. |
|
Returns the list of Cytoscape network names in the current Cytoscape session. |
|
Get the name of a network. |
|
Get the SUID of a network. |
|
Sets a new name for a network. |
|
Selects the given network as “current”. |
Import/Export¶
|
Create an igraph network from a Cytoscape network. |
|
Create a network from data frames. |
|
Create a Cytoscape network from an igraph network. |
|
Create a Cytoscape network from a NetworkX graph. |
|
Return the Cytoscape network as a networkx multi-di-graph. |
|
Export a network to one of mulitple file formats. |
|
Loads a network from specified file. |
Network Selection¶
Functions for working with SELECTIONS of nodes and edges in networks, including operations that perform selection and rely on prior selection events.
General selection functions
Node selection functions
Edge selection functions
Nodes¶
|
If any nodes are selected in the network, they will be unselected. |
|
Delete currently selected nodes from the network. |
|
Returns the number of nodes currently selected in the network. |
|
Retrieve the names of all the nodes selected in the network. |
|
Select all nodes that were not selected and deselect all nodes that were selected. |
|
Selects all nodes in a Cytoscape Network. |
|
Select nodes directly connected to currently selected nodes. |
|
Select nodes in the network by SUID, name or other column values. |
Take currently selected edges and extends the selection to connected nodes, regardless of directionality. |
Edges¶
|
If any nodes are selected in the network, they will be unselected. |
|
Remove edges with duplicate names. |
|
Delete the currently selected edges in the network. |
|
Removes edges that connect to a single node as both source and target. |
|
Return the number of edges currently selected in the network. |
|
Retrieve the names of all the edges selected in the network. |
|
Select all edges that were not selected and deselect all edges that were selected. |
|
Selects all edges in a Cytoscape Network. |
|
Select edges in the network by SUID, name or other column values. |
Take currently selected nodes and add to the selection all edges connected to those nodes, regardless of directionality. |
|
Select edges in a Cytoscape Network connecting the selected nodes, including self loops connecting single nodes. |
Network Views¶
Functions for performing VIEW operations in addition to getting and setting view properties.
Views¶
|
Save the current network view as an image file. |
|
Zoom and pan network view to maximize either height or width of current network window. |
|
Retrieve the SUID of a network view. |
|
Retrieve list of network view SUIDs. |
|
Set which network view is “current”. |
|
Toggle Graphics Details. |
Sandbox¶
Functions for performing file operations within a sandbox.
A sandbox is a directory on the Cytoscape workstation that is guaranteed writeable and is guaranteed to be isolated from the whole file system. All file operations are carried out relative to the “current sandbox”. Generally, a Notebook-based workflow doesn’t have to do anything to set up a sandbox … the default sandbox is automatically set up as part of py4cytoscape startup. However, the workflow can set different sandboxes, and can even switch between them. A sandbox can contain both files and directories, and the user can transfer files between a sandbox and the workflow’s native file system (e.g., a remote Notebook’s server).
Thus, is it possible to build workflows that don’t depend on the structure of the Cytoscape workstation’s file system. Such workflows can store workflow data files along with other workflow files on a remote Notebook server, then transfer them to a sandbox only when Cytoscape will need them. Conversely, when Cytoscape creates a file in a sandbox (e.g., exporting an image), the workflow can transfer the file to workflow storage.
A special case is when py4cytoscape is running on the same workstation as Cytoscape. The default sandbox is considered to be the whole workstation file system, and the workflow is responsible for providing full file paths to Cytoscape functions. Alternatively, the workflow could also define a sandbox, and then move files in and out of it just as a remote Notebook would.
For more information, see the Concepts section in the py4cytoscape User Manual.
Sandbox¶
|
Set a new default sandbox, creating it if necessary. |
|
Delete sandbox contents and remove its directory. |
|
Get metadata on file in sandbox (or entire sandbox). |
|
Transfer a file to a sandbox. |
|
Transfer a file from a sandbox. |
|
Remove a file from a sandbox. |
Session¶
Functions for managing Cytoscape SESSIONS, including save, open and close.
Session¶
|
Close the current session in Cytoscape, destroying all unsaved work. |
|
Open Session File or URL. |
|
Saves the current Cytoscape session as a CYS file. |
Styles¶
Basic Styles¶
Functions for managing STYLES and retrieving general lists of properties relevant to multiple style modes. Functions specific to Default, Mapping, Bypass, Dependencies and Values are in separate files.
Style management functions
General property functions
Style Management¶
|
Create a new visual style by copying a specified style. |
|
Create a style from defaults and predefined mappings. |
|
Delete the specified visual style from current session. |
|
Save one or more visual styles to file. |
|
Retrieve a list of all visual style names. |
|
Load styles from an XML file and returns the names of the loaded styles. |
|
Apply a visual style to a network. |
Visual Property Names and Values¶
|
Get Arrow Shapes. |
|
Get Line Styles. |
|
Get Node Shapes. |
|
Retrieve the names of all possible visual properties. |
Style Bypasses¶
Functions for getting and setting BYPASS values for visual properties, organized into sections:
General functions for setting/clearing node, edge and network properties
Specific functions for setting particular node, edge and network properties
NOTE: The CyREST ‘bypass’ endpoint is essential to properly set values that will persist for a given network independent of applied style and style changes, and from session to session if saved.
General Style Bypasses¶
|
Set Node Property Bypass. |
|
Set Edge Property Bypass. |
Node Style Bypasses¶
|
Clear Node Opacity Bypass. |
|
Clear Node Property Bypass. |
|
Hide Nodes. |
|
Hide Selected Nodes. |
|
Override the border color for particular nodes. |
|
Override the border opacity for particular nodes. |
|
Override the border width for particular nodes. |
|
Set the bypass value for fill color for the specified node or nodes. |
|
Override the fill opacity for particular nodes. |
|
Override the font face for particular nodes. |
|
Override the font size for particular nodes. |
|
Override the height for particular nodes. |
|
Override the label for particular nodes. |
|
Override the label color for particular nodes. |
|
Override the label opacity for particular nodes. |
|
Set the bypass value for node fill, label and border opacity for the specified node or nodes. |
|
Override the shape for particular nodes |
|
Set Node Size Bypass. |
|
Sets a bypass tooltip for one or more nodes. |
|
Override the width for particular nodes. |
|
Unhide Nodes. |
Edge Style Bypasses¶
|
Clear Edge Property Bypass. |
|
Hide Edges. |
|
Hide Selected Edges. |
|
Set the bypass value for fill color for the specified edge or edges. |
|
Override the font face for particular edges. |
|
Override the font size for particular edges. |
|
Override the label for particular edges. |
|
Override the label color for particular edges. |
|
Override the label opacity for particular edges. |
|
Override the style for particular edges. |
|
Override the width for particular edges. |
|
Override the opacity for particular edges. |
Override the target arrow color for particular edges. |
|
Override the source arrow shape for particular edges. |
|
Override the target arrow color for particular edges. |
|
Override the target arrow shape for particular edges. |
|
|
Sets a bypass tooltip for one or more edges. |
|
Unhide Edges. |
Network Style Bypasses¶
|
Clear the bypass value for center x and y for the network, effectively restoring prior default values. |
|
Clear Network Property Bypass. |
|
Clear the bypass value for the scale factor for the network, effectively restoring prior default values. |
|
Set the bypass value for center x and y for the network. |
|
Set Network Property Bypass. |
|
Set the bypass value for scale factor for the network. |
|
Unhide all previously hidden nodes and edges, by clearing the Visible property bypass value. |
Style Defaults¶
Functions for getting and setting DEFAULT values for visual properties, organized into sections:
General functions for setting node, edge and network defaults
Specific functions for setting particular node, edge and network defaults
General Style Defaults¶
|
Retrieve the default value for a visual property. |
|
Set the default value for a visual property. |
|
Update the default values of visual properties in a style. |
Custom Graphics¶
|
Remove Node Custom Graphics. |
|
Set Node Custom Bar Chart. |
|
Set Node Custom Box Chart. |
|
Set Node Custom HeatMap Chart. |
|
Set Node Custom Line Chart. |
|
Set Node Custom Linear Gradient. |
|
Set Node Custom Pie Chart. |
|
Set Node Custom Position. |
|
Set Node Custom Radial Gradient. |
|
Set Node Custom Ring Chart. |
Node Style Defaults¶
Retrieve the default selection node color. |
|
|
Set the default node border color. |
|
Set defaults opacity value for all unmapped node borders. |
|
Set the default node border width. |
|
Set the default node color. |
|
Set default opacity value for all unmapped nodes. |
|
Set the default node font. |
|
Set the default node font size. |
|
Set the default node height. |
|
Set the default node label color. |
|
Set the default node label. |
|
Set default opacity value for all unmapped node labels. |
|
Set the default node border color. |
|
Set the default node shape. |
|
Set the default node font size. |
|
Set the default node tooltip. |
|
Set the default node width. |
Edge Style Defaults¶
Retrieve the default selected edge color. |
|
|
Set the default edge color. |
|
Set the default edge font. |
|
Set the default edge font size. |
|
Set the default edge label color. |
|
Set the default edge label. |
|
Set default opacity value for all unmapped edges. |
|
Set the default edge style. |
|
Set the default edge width. |
|
Set default opacity value for all unmapped edges. |
|
Set the default selected edge color. |
|
Set the default edge source arrow color. |
|
Set the default edge source arrow shape. |
|
Set the default edge target arrow color. |
|
Set the default edge target arrow shape. |
|
Set the default edge tooltip. |
Network Style Defaults¶
|
Retrieve the default background color. |
|
Set the default background color. |
Style Dependencies¶
# Functions for getting and setting style DEPEDENDENCIES, organized into sections:
General functions for getting and setting dependencies
Specific functions for setting particular dependencies
General Style Dependencies¶
|
Get the values of dependencies in a style. |
|
Set the values of dependencies in a style, overriding any prior setting. |
Custom Graphics¶
|
Set a boolean value to have the size of custom graphics match that of the node. |
Node Style Dependencies¶
|
Set a boolean value to have node width and height fixed to a single size value. |
Edge Style Dependencies¶
|
Set a boolean value to have arrow shapes share the same color as the edge. |
Style Mappings¶
Functions for defining MAPPINGS between table column values and visual properties, organized into sections:
General functions for creating and applying mappings for node, edge and network properties
Specific functions for defining particular node, edge and network properties
General Style Mappings¶
|
Delete a specified visual style mapping from specified style. |
|
Fetch all visual property mapping in a style. |
|
Fetch a visual property mapping in a style. |
|
Create a mapping between an attribute and a visual property. |
|
Update a visual property mapping in a style. |
Node Style Mappings¶
|
Map table column values to colors to set the node border color. |
|
Set opacity for node border only. |
|
Map table column values to widths to set the node border width. |
|
Map table column values to colors to set the node fill color. |
|
Set opacity for node fill, border and label all together. |
|
Set opacity for node fill only. |
|
Sets font face for node labels. |
|
Map table column values to sizes to set the node size. |
|
Map table column values to the node heights. |
|
Map table column values to colors to set the node border color. |
|
Pass the values from a table column to display as node labels. |
|
Sets opacity for node label only. |
|
Map table column values to shapes to set the node shape. |
|
Map table column values to node sizes. |
|
Pass the values from a table column to display as node tooltips. |
|
Map table column values to the node widths. |
Edge Style Mappings¶
|
Map table column values to colors to set the edge color. |
|
Sets font face for edge labels. |
|
Map table column values to sizes to set the edge size. |
|
Map table column values to colors to set the edge border color. |
|
Pass the values from a table column to display as edge labels. |
|
Sets opacity for edge label only. |
|
Map table column values to styles to set the edge style. |
|
Map table column values to widths to set the node border width. |
|
Map table column values to opacities to set the edge opacity. |
|
Map table column values to colors to set the source arrow color. |
|
Map table column values to shapes to set the source arrow shape. |
|
Map table column values to colors to set the source arrow color. |
|
Map table column values to colors to set the target arrow color. |
|
Map table column values to shapes to set the target arrow shape. |
|
Map table column values to colors to set the target arrow color. |
|
Pass the values from a table column to display as edge tooltips. |
Style Values¶
Functions for retrieving current values for visual properties.
General functions for getting node, edge and network properties
Specific functions for getting particular node, edge and network properties
Node Style Values¶
|
Retrieve the actual fill color of specified nodes. |
|
Retrieve the actual height of specified nodes. |
|
Retrieve the actual x,y position of specified nodes. |
|
Get values for any node property of the specified nodes. |
|
Retrieve the actual size of specified nodes. |
|
Retrieve the actual width of specified nodes. |
Edge Style Values¶
|
Retrieve the actual line color of specified edges. |
|
Retrieve the actual line style of specified edges. |
|
Retrieve the actual line width of specified edge. |
|
Get values for any edge property of the specified edges. |
|
Retrieve the actual target arrow shape of specified edges. |
Network Style Values¶
|
Retrieve the center of specified network. |
|
Get values for any network property. |
|
Retrieve the scale factor of specified network. |
Tables¶
Functions for managing TABLE columns and table column functions, like map and rename, as well as loading and extracting table data in Cytoscape.
Column Manipulation¶
|
Delete a column from node, edge or network tables. |
|
Retrieve the names of all columns in a table. |
|
Retrieve the types of all columns in a table. |
|
Retrieve one or more columns of data from node, edge or network tables. |
|
Set a new name for a column. |
Column Mapping¶
|
Map Table Column. |
Data Values¶
|
Retrieve the value from a specific row and column from node, edge or network tables. |
|
Loads data into Cytoscape tables keyed by row. |
Tools¶
Functions related to TOOLS found in the Tools Menu in Cytoscape.
Browser Control¶
|
Cybrowser Close. |
|
Launch Cytoscape’s internal web browser in a separate window |
|
Cybrowser Hide. |
|
Cybrowser List. |
|
Cybrowser Send. |
|
Cybrowser Show. |
|
Display the version of the CyBrowser app. |
Diffusion¶
|
Diffusion Advanced. |
|
Diffusion Basic. |
Misc¶
|
Calculate various network statistics. |
|
Merge Networks. |
User Interface¶
Functions affecting the USER INTERFACE, such as panel management.
Panels¶
|
Dock a panel back into the UI of Cytoscape. |
|
Pop out a panel from the UI of Cytoscape. |
|
Hide control, table, tool and results panels. |
|
Hide a panel in the UI of Cytoscape. |
Utils¶
Utility functions useful across multiple modules.
Translation to/from SUIDs¶
|
Translate one edge name or a list of edge names into a list of SUIDs. |
|
Translate one edge SUID or a list of edge SUIDs into a list of names. |
|
Translate one node name or a list of node names into a list of SUIDs. |
|
Translate one node SUID or a list of node SUIDs into a list of names. |
Miscellaneous¶
|
Append a command (if it exists) to a base URL. |
|
Supply a set of colors from Brewer palettes (without requiring rColorBrewer). |
|
Checks to see if a particular column name exists in the specific table. |
|
Checks to see if min supported versions of api and cytoscape are running. |
Logging¶
py4cytoscape logging is based on the Python logging
package, which is based on Java’s logging
framework.
py4cytoscape emits log entries in SysLog format. For example:
[INFO] py4...S: ǀHTTP DELETE(http://localhost:1234/v1/networks)
[INFO] py4...S: ǀOK[200]
[INFO]
is the priority level.
py4...S
the name of the py4cytoscape package.
The count of |
indicates the nesting level of the currently executing code, where ||
indicates log entries called from code at the |
level.
The remainder of the message contains the logged information. In the example above, an HTTP DELETE call is logged along with the HTTP server’s reply.
Logger configuration is available in the py4cytoscape_logger_settings.py
module. py4cytoscape emits two independent logging streams: Summary (to the console) and Detail (to a file in the logs
directory).
By default, Summary logging is the short form (priority INFO
), which shows HTTP calls and results. You can disable Summary logging by setting _SUMMARY_LOG_LEVEL
to NOTSET
, and you can enable full logging by setting it to DEBUG
.
By default, Detail logging is the long form (priority DEBUG
), and is controlled by the _DETAIL_LOG_LEVEL
setting.
Here is an example of Detail logging involving nested calls:
2020-06-06 15:29:55,721 [DEBUG] py4...: ǀCalling cytoscape_version_info(base_url='http://localhost:1234/v1')
2020-06-06 15:29:55,721 [DEBUG] py4...: ǀǀCalling cyrest_get('version', base_url='http://localhost:1234/v1')
2020-06-06 15:29:55,721 [DEBUG] py4...: ǀǀHTTP GET(http://localhost:1234/v1/version)
2020-06-06 15:29:55,737 [DEBUG] py4...: ǀǀOK[200], content: {"apiVersion":"v1","cytoscapeVersion":"3.9.0-SNAPSHOT"}
2020-06-06 15:29:55,738 [DEBUG] py4...: ǀǀReturning 'cyrest_get': {'apiVersion': 'v1', 'cytoscapeVersion': '3.9.0-SNAPSHOT'}
2020-06-06 15:29:55,738 [DEBUG] py4...: ǀReturning 'cytoscape_version_info': {'apiVersion': 'v1', 'cytoscapeVersion': '3.9.0-SNAPSHOT'}
Runtime Control¶
For convenience, Summary logging can be controlled using an environment variable or at execution time. By default, Summary logging is disabled, but can be enabled:
set PY4CYTOSCAPE_SUMMARY_LOGGER=True
At execution time, it can be enabled by calling set_summary_logger()
. This is handy within a busy code block or when running in a Notebook environment. For example:
old_state = set_summary_logger(True)
# ... make several py4cytoscape calls ...
set_summary_logger(old_state)
Release Log¶
py4cytoscape 0.0.3¶
Release date: 05 Oct 2020
Conform to Cytoscape Automation API Definition
Change CyError logger to write exceptions to stderr
Add Sandboxing interface and functions
Add merge_network() and analyze_network()
Add Jupyter-bridge, Cytoscape Automation API, py4cytoscape versions to cytoscape_version_info
Add support for Jupyter-bridge
Add Concepts section to documentation
Release notes¶
Announcement: py4cytoscape 0.0.3¶
We’re happy to announce the release of py4cytoscape 0.0.3!
py4cytoscape is a Python package that communicates with Cytoscape via its REST API, providing access to a set over 250 functions that enable control of Cytoscape from within standalone and Notebook Python programming environments. It provides nearly identical functionality to RCy3, an R package in Bioconductor available to R programmers.
Highlights¶
This themes for this release are:
Add support for remote Notebook execution (via Jupyter-Bridge)
Sync with changes made to RCy3 since Jan 1, 2020
Remote Notebook execution involves a round trip between the Python kernel running on a remote server and Cytoscape running on a private workstation. The main component is Jupyter-Bridge, which routes py4cytoscape requests through the user’s browser and on to Cytoscape, and then returns the result in the reverse direction. Requests and responses are routed through the Jupyter-Bridge server, which is an independent entity on the web.
For most Cytoscape operations, it’s necessary to transfer files from the Notebook server so that Cytoscape can load them, or to transfer files created by Cytoscape to the Notebook server so Python can analyze them. Sandboxing was implemented to enable these transfers, and to enable portability of workflows across different Cytoscape workstations.
Finally, py4cytoscape functions and definitions were sync’d with RCy3 changes since 1/1/20, and a reference interface spec was created independent of py4cytoscape and RCy3: Conform to Cytoscape Automation API Definition.
API Changes¶
Add tools.merge_networks() and tools.analyze_network()
Add sandbox.* functions
Added a number of maintenance functions in commands and py4cytoscape_sandbox modules
Deprecations¶
None
Contributors to this release¶
Barry Demchak
Alex Pico
Kozo Nashida
Chris Churas
Yasir Demirtaş
Pull requests merged in this release¶
None
py4cytoscape 0.0.1¶
Release date: 21 Aug 2020
Initial release, matches API signatures for RCy3
Release notes¶
Announcement: py4cytoscape 0.0.1¶
We’re happy to announce the release of py4cytoscape 0.0.1!
py4cytoscape is a Python package that communicates with Cytoscape via its REST API, providing access to a set over 250 functions that enable control of Cytoscape from within standalone and Notebook Python programming environments. It provides nearly identical functionality to RCy3, an R package in Bioconductor available to R programmers.
Highlights¶
This themes for this release are:
Reproduce RCy3 functions
Create a testing system for all functions
Create the py4cytoscape user documentation
API Changes¶
None
Deprecations¶
None
Contributors to this release¶
Barry Demchak
Alex Pico
Kozo Nashida
Jorge Bouças
Stevan Georg
Chris Churas
Pull requests merged in this release¶
Set dependencies #10
Fixed broken link to the tutorials page on readthedocs #9
In the Verify Cytoscape connection code fragment made file path platform agnostic #8
Add how to try tutorial without installation (by using Binder) #6
Add a tutorial ipynb file to the Sphinx source #5
Move python-igraph from extras_require to install_requires #4
Rename the package name #3
Add How to install and use #2
License¶
Released under the MIT License:
Copyright (c) 2018-2020 The Cytoscape Consortium
Barry Demchak <bdemchak@ucsd.edu>
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Credits¶
py4cytoscape
was originally written by Barry Demchak with the help of many others, particularly the developers
of RCy3, on which py4cytoscape
is based.
Thanks to everyone who has
improved py4cytoscape
by contributing code, bug reports (and fixes), documentation,
and input on design, features, and the future of py4cytoscape
.
Contributions¶
This section aims to provide a list of people and projects that have
contributed to py4cytoscape
. It is intended to be an inclusive list, and
anyone who has contributed and wishes to make that contribution known is
welcome to add an entry into this file. Generally, no name should be added to
this list without the approval of the person associated with that name.
Creating a comprehensive list of contributors can be difficult, and the list within this file is almost certainly incomplete. Contributors include testers, bug reporters, contributors who wish to remain anonymous, funding sources, academic advisors, end users, and even build/integration systems.
Do you want to make your contribution known? If you have commit access, edit this file and add your name. If you do not have commit access, feel free to open an issue, submit a pull request, or get in contact with one of the official team members.
Original Authors¶
Contributors¶
Optionally, add your desired name and include a few relevant links. The order is partially historical, and now, mostly arbitrary.
Keiichiro Ono, GitHub: keiono
Jorge Bouças, GitHub: jorgeboucas
Kozo Nishida, GitHub: kozo2
Barry Demchak, GitHub: bdemchak
Alex Pico, GitHub: AlexanderPico
Mark Grimes, GitHub: mark-grimes
Julia Gustavsen, GitHub: jooolia
Shraddha Pai, GitHub: shraddhapai
Ruth Isserlin, GitHub: risserlin
Paul Shannon, GitHub: paul-shannon
Tanja Muetze, GitHub: tmuetze
Georgi Kolishkovski
David Otasek
The NetworkX documentation is excellent, and we borrowed both wording and structure liberally.
Support¶
py4cytoscape
and those who have contributed to py4cytoscape
have received
support throughout the years from a variety of sources. We list them below.
If you have provided support to py4cytoscape
and a support acknowledgment does
not appear below, please help us remedy the situation, and similarly, please
let us know if you’d like something modified or corrected.
Funding¶
py4cytoscape
acknowledges support from the following:
US National Institute of General Medical Sciences (NIGMS), award number R01 GM070743, PI: Trey Ideker
National Resource for Network Biology (NRNB), award number P41 GM103504, PI: Trey Ideker
Torrey Pines Software, Inc, President: Barry Demchak
Citing¶
There is no paper (yet) that describes py4cytoscape.