Cytoscape developer's tutorial by nutailor

VIEWS: 39 PAGES: 11

									                               Cytoscape developer's tutorial

     1. How to add a tabbed Panel to Control panel? ......................................................... 2
     2. How to add an image icon (menu item) to the toolbar? .......................................... 2
     3. How to create a submenu? ...................................................................................... 2
     4. How to create, modify, and destroy a network, nodes, and edges? ........................ 2
     5. How to create, modify, and destroy a network view?............................................. 3
     6. How to determine which nodes are currently selected on a network? .................... 4
     7. How to handle events from a network (and discuss each event type)? .................. 4
     8. How to change the background color of a view? .................................................... 4
     9. How to zoom a network view? ............................................................................... 5
     10. How to load attribute data? ................................................................................... 5
     11. How to remove attributes? .................................................................................... 6
     12. How to use a web service client? .......................................................................... 6
     13. How to write a web service client? ....................................................................... 6
     14. How to use the VizMapper programmatically? .................................................... 7
     15. How to apply a continuous color gradient to nodes according to their degree? ... 8
     16. How to load a visual properties file? .................................................................... 9
     17. How to write a layout algorithm? ......................................................................... 9
     18. How to customize node graphics? ........................................................................ 9
     19. How to write a Group Viewer? ............................................................................. 9
     20. How to add components to the node view, edge view, and attribute browser
     context menus?............................................................................................................ 9
     21. How to save/restore plugin states? ...................................................................... 10
     22. How to use Cytoscape task monitor to show the progress of my job? ............... 11


This tutorial will show some code snippets about how to use Cytoscape APIs on plugin
development. Each feature is included in a sample plugin, which can serve as a starting
point or template for new plugin developers. The code snippets can also be used as
reference for experienced developers.

Cytoscape plugin is usually packaged in a jar file and deployed to the plugins directory of
Cytoscape. When Cytoscape starts up and initializes, its plugin manager will look up all
the plugins in plugins directory. A plugin should have following three components.

1. A class, which extends CytoscapePlugin. This is the entry point to Cytoscape.
2. A manifest file, explicitly list the class, which extended CytoscapePlugin class
3. A plugin.props file, which list the information about the plugin, such as plugin name,
   author, release date and more. Although this file is not absolutely required, it is
   recommended to have one, since plugin manager will need the information to handle
   the plugin properly. See the page at http://www.cytoscape.org/cgi-
   bin/moin.cgi/Cytoscape_Plugin_Tutorial for detail about the definition of a
   plugin.props.
If plugin developer will share and publish their plugins, they are encouraged to submit
their plugins to Cytoscape plugin website at http://cytoscape.org/plugins/index.php .



1. How to add a tabbed Panel to Control panel?
It takes three steps to add a tabbed panel to the control panel.
(1) Get a handler to the cytoPanel west, which is the control panel
   CytoPanelImp ctrlPanel = (CytoPanelImp)
   Cytoscape.getDesktop().getCytoPanel(SwingConstants.WEST);

(2) Create a JPanel object (a class extends JPanel, say, MyPanel)
   MyPanel myPanel = new MyPanel();

(3) Add it to the control panel.
   ctrlPanel.add("myPanel", myPanel);

Download a sample plugin, here.

2. How to add an image icon (menu item) to the toolbar?

(1) Create a toolbarAction
ImageIcon icon = new ImageIcon(getClass().getResource("/tiger.jpg"));
MyPluginToolBarAction toolbarAction = new MyPluginToolBarAction(icon, this);
The toolbarAction must extend the class cytoscape.util.CytoscapeAction and its method
isInToolBar()returns true.

(2) Add the action to Cytoscape toolbar
Cytoscape.getDesktop().getCyMenus().addCytoscapeAction((CytoscapeAction) toolbarAction);


Download a sample plugin, here.

3. How to create a submenu?

Same as adding an image icon to the toolbar, the difference is that its method
“isInMenuBar()” in CytoscapeAction should return true.

Download a sample plugin, here.

4. How to create, modify, and destroy a network, nodes, and edges?

A general procedure to create a network is, first create a bunch of CyNodes using the
Cytoscape.getCyNode() method, then create edges using those nodes with
Cytoscape.getCyEdge() method. Then call Cytoscape.createNetwork() with the list of
nodes and edges just created.
The following snippet of code will create network with three nodes and three edges. The
name of the network is “network1”.

//create a network without a view
CyNetwork cyNetwork = Cytoscape.createNetwork("network1", false);

CyNode   node0   =   Cytoscape.getCyNode("rain", true);
CyNode   node1   =   Cytoscape.getCyNode("rainbow", true);
CyNode   node2   =   Cytoscape.getCyNode("rabbit", true);
CyNode   node3   =   Cytoscape.getCyNode("yellow", true);

cyNetwork.addNode(node0);
cyNetwork.addNode(node1);
cyNetwork.addNode(node2);
cyNetwork.addNode(node3);

CyEdge edge0 = Cytoscape.getCyEdge(node0, node1, Semantics.INTERACTION,
"pp", true);
CyEdge edge1 = Cytoscape.getCyEdge(node0, node2, Semantics.INTERACTION,
"pp", true);
CyEdge edge2 = Cytoscape.getCyEdge(node0, node3, Semantics.INTERACTION,
"pp", true);
cyNetwork.addEdge(edge0);
cyNetwork.addEdge(edge1);
cyNetwork.addEdge(edge2);

To remove a node, we use the RootGraphIndex of the Node as follows. Note that when
we remove a node, we have the option to remove it from the invisible rootGrpah or just
hide it from current network.
cyNetwork.removeNode(node1.getRootGraphIndex(), true);
//Cytoscape.firePropertyChange(Cytoscape.NETWORK_MODIFIED, null,
//cyNetwork);

The following statement will destroy a network. Sometime, it is necessary to fire a event
to notify other listeners after a network is destroyed.

Cytoscape.destroyNetwork(cyNetwork);
//Cytoscape.firePropertyChange(Cytoscape.NETWORK_DESTROYED, cyNetwork,
//null);

5. How to create, modify, and destroy a network view?
A network may or may not have a view. If we already have a network, we can create a
view with the following statement.
// Create a view for the network
CyNetworkView cyView = Cytoscape.createNetworkView(cyNetwork,
"MyNetwork");

If a node is hidden, the node and all of its incident edges will be hidden.
// hide a node
cyNetwork.hideNode(node1.getRootGraphIndex());
The following statement will destroy a network view.
Cytoscape.destroyNetworkView(cyView);


6. How to determine which nodes are currently selected on a
network?

The following snippet of code will get the list of selected nodes in current network and
print out the node identifiers in console window.

CyNetwork current_network = Cytoscape.getCurrentNetwork();
Set selectedNodes = current_network.getSelectedNodes();

Iterator<Node> it = selectedNodes.iterator();
while (it.hasNext()) {
      Node aNode = (Node) it.next();
      System.out.println(aNode.getIdentifier());
}

Download a sample plugin, here.


7. How to handle events from a network (and discuss each event
type)?

// Handle PropertyChangeEvent
public void propertyChange(PropertyChangeEvent e) {
if (e.getPropertyName().equalsIgnoreCase(Cytoscape.ATTRIBUTES_CHANGED))
{
       System.out.println("Received an event --
Cytoscape.ATTRIBUTES_CHANGED!");
}
if
(e.getPropertyName().equalsIgnoreCase(CytoscapeDesktop.NETWORK_VIEW_FOC
USED))
{
                         System.out.println("Received an event --
CytoscapeDesktop.NETWORK_VIEW_FOCUSED!");
}


}


8. How to change the background color of a view?
The network view (DingNetworkView) is composed of three layers of canvases
(foreground, network and background). To change the background color of a view, we
first get the background canvas, and then set the color for the background. The following
snippet of code will change the background color of network view, which has the focus.
//Let user choose a color
Color bkColor = JColorChooser.showDialog(Cytoscape.getDesktop(),
"Please choose a background color", Color.white);

// Change the background color for current view
DingNetworkView theView = (DingNetworkView)
Cytoscape.getCurrentNetworkView();
DingCanvas backgroundCanvas =
theView.getCanvas(DGraphView.Canvas.BACKGROUND_CANVAS);
backgroundCanvas.setBackground(bkColor);

// Refresh the view
Cytoscape.getCurrentNetworkView().updateView();

Download a sample plugin, here.


9. How to zoom a network view?
To zoom a network view, all we need to know is the scale factor. Here is how,

// Get reference to the view
final CyNetworkView networkView = Cytoscape.getCurrentNetworkView();

networkView.setZoom(scaleFactor);
networkView.updateView();

Download a sample plugin, here.


10. How to load attribute data?
Attributes are global variables. There are three types of attributes, NODE, EDGE and
NETWORK. The following snippet of code shows how to add an attribute for a node –
the key value will be the same as the ID of a node.

String attributeName = "testAttribute";
String AttributeValue = "testValue";
CyAttributes cyNodeAttrs = Cytoscape.getNodeAttributes();
cyNodeAttrs.setAttribute(node.getIdentifier(), attributeName,
AttributeValue);

After attributes are loaded, it may be necessary to fire an event to notify other listeners
that may have interest to the change.

// inform others via property change event.
Cytoscape.firePropertyChange(Cytoscape.ATTRIBUTES_CHANGED, null, null);

Download a sample plugin, here.
11. How to remove attributes?
To remove an attribute, we need to know the attribute name and its type
(NODE/EDGE/NETWORK). The following two statements will remove a node attribute.

CyAttributes cyNodeAttrs = Cytoscape.getNodeAttributes();
cyNodeAttrs.deleteAttribute(attributeName);

Download a sample plugin, here.


12. How to use a web service client?
After a webservice is registered with the WebServiceManager, it can be used by other
plugins. The following code snippet shows how to get the handler to a client by querying
the WebServiceManager,

WebServiceClient<EUtilsServiceSoap> client =
      WebServiceClientManager.getClient("tutorial13");

if (client == null) {
      System.out.println("Web service client tutorial13 is not
found!");
      return;
}

If the manager found the webservice client and return it successfully, the client can be
used. The client can be used directly by get a handler to the client stub, or by fire
webservice event. The following snippet of code will get the database information from
NCBI.

// eInfo utility returns a list of available databases
EUtilsServiceSoap utils = (EUtilsServiceSoap) client.getClientStub();

// call NCBI EInfo utility, "Available databases from NCBI";
EInfoResult res = utils.run_eInfo(new EInfoRequest());

Download a sample plugin, here.


13. How to write a web service client?
Cytoscape provides a WebServiceManager and a set of webservice APIs. Each
webservice should be wrapped into a plugin and register to the WebServiceManager, so
that other plugins can easily use the webservice by query the WebServiceManager and
get access to the specific web service.

We use NCBI web service “E-Utilities” as an example here.
1. Go to the NCBI webservice site, look at the WSDL
   http://eutils.ncbi.nlm.nih.gov/entrez/eutils/soap/eutils.wsdl, and generate stubs by
   following the instructions there. Put all the depended jar files used by the stubs into
   the lib directory of the plugin, then pack all the generated class into a jar file, say
   “eutils.jar”. For the jar files in the lib, we can either pack them into “eutils.jar”, or
   copy them into the lib directory of Cytoscape. To pack all jar into a single plugin jar
   is preferred, which will make it easy for the distribution of the plugin.
2. Create a webservice client class, say “My_NCBIClient”, which extends
   WebServiceClientImpl. The client class should implement methods, such as provide
   an ID and description of the client, and handle the WebserviceEvents.
3. Register the client with the WebServiceClientManager
       WebServiceClientManager.registerClient(My_NCBIClient.getClient());

Download a sample plugin, here.


14. How to use the VizMapper programmatically?

All the VisualStyles defined are available through the VisualMappingManager. The
following two statements will get the handler of VisualMappingManager and the Set of
names of all visual styles there.

VisualMappingManager vmm = Cytoscape.getVisualMappingManager();
Set<String> names = vmm.getCalculatorCatalog().getVisualStyleNames();

To create a VisualStyle for a network view, an easy way is to use VisualStyleBuilder.
The following code snippet will create a VisualStyle with name “myVisualStyle”. After
the visualStyle is created, it will appear in the comboBox of VizMapper main panel.

// Create a visual style "myVisualStyle"
String styleName = "myVisualStyle";
VisualStyleBuilder graphStyle = new VisualStyleBuilder(styleName, false);
graphStyle.setNodeSizeLocked(false);

// set some visual property for two nodes
graphStyle.addProperty(node1.getIdentifier(), VisualPropertyType.NODE_WIDTH,
"30");
graphStyle.addProperty(node1.getIdentifier(),
VisualPropertyType.NODE_FILL_COLOR, "#E1E1E1");
graphStyle.addProperty(node1.getIdentifier(), VisualPropertyType.NODE_SHAPE,
NodeShape.DIAMOND.getShapeName());
       graphStyle.addProperty(node2.getIdentifier(),
       VisualPropertyType.NODE_WIDTH, "80");
graphStyle.addProperty(node2.getIdentifier(),
VisualPropertyType.NODE_FILL_COLOR, "#0000E1");
       graphStyle.addProperty(node2.getIdentifier(),
VisualPropertyType.NODE_SHAPE, NodeShape.TRIANGLE.getShapeName());

// Create the visual style
graphStyle.buildStyle();

// Set the background color for this visual style
GlobalAppearanceCalculator gac =
Cytoscape.getVisualMappingManager().getVisualStyle().getGlobalAppearanceCalcula
tor();
gac.setDefaultBackgroundColor(Color.red);

// Refresh the view
Cytoscape.getCurrentNetworkView().redrawGraph(false, true);
15. How to apply a continuous color gradient to nodes according to
their degree?
To map node degree to node color, first we need to define a calculator with continuous
mapping for the visual attribute NODE_FILL_COLOR. Then set the calculator to the
NodeAppearanceCalculator of the visual style to be applied.

The following code snippet will set the calculator for a visualStyle.
// Create a node color calculator for "Degree" attribute
Calculator nodeColorCalculator = createCalculator(); // see below

// Set the calculator to the visualStyle
vs.getNodeAppearanceCalculator().setCalculator(nodeColorCalculator);


The following code snippet shows how to create a calculator using Degree as controlling
attribute.

VisualPropertyType type = VisualPropertyType.NODE_FILL_COLOR;
final Object defaultObj =
type.getDefault(Cytoscape.getVisualMappingManager().getVisualStyle());

ContinuousMapping cm = new ContinuousMapping(defaultObj,
ObjectMapping.NODE_MAPPING);
// Set controlling Attribute
cm.setControllingAttributeName("Degree", Cytoscape.getCurrentNetwork(), false);

Interpolator numToColor = new LinearNumberToColorInterpolator();
cm.setInterpolator(numToColor);

Color   underColor = Color.GRAY;
Color   minColor = Color.RED;
Color   midColor = Color.WHITE;
Color   maxColor = Color.GREEN;
Color   overColor = Color.BLUE;

BoundaryRangeValues bv0 = new BoundaryRangeValues(underColor, minColor,
minColor);
BoundaryRangeValues bv1 = new BoundaryRangeValues(midColor, midColor,
midColor);
BoundaryRangeValues bv2 = new BoundaryRangeValues(maxColor, maxColor,
overColor);

// Set the attribute point values associated with the boundary values
// The points p1, p2, p3 are the values between (min~max) of the degree
cm.addPoint(p1, bv0); cm.addPoint(p2, bv1); cm.addPoint(p3, bv2);

// Create a calculator
BasicCalculator myCalculator = new BasicCalculator("My degree calcualtor", cm,
VisualPropertyType.NODE_FILL_COLOR);
16. How to load a visual properties file?
Cytoscape already support import/export of visual properties file. They can be found at
File Import  Vizmap Property File and File Export  Vizmap Property File


17. How to write a layout algorithm?
All Cytoscape layout algorithms are grouped together and accessible though the layout
menu. To add a new layout algorithm, the new layout class should implement the
interface CyLayoutAlgorithm, or extend the AbstractLayout class. The new algorithm
should then register with the CyLayout manager. In this way, a new menu item, name
defined in the new layout algorithm, will be available under Layout menu.

The following line shows how to register a layout algorithm with the layout manager,
       CyLayouts.addLayout(new MyLayout(), "My Layouts");

One of the methods that a CyLayoutAlgorithm must implement is a getSettings() method,
which returns an object of LayoutProperties that winds up under the Settings menu.
Layout parameters may be supplied with the LayoutProperties. For example, the
following statement defines a parameter in the LayoutProperties – name, description, data
type and value.

layoutProperties.add(new Tunable("groupcount", "Number of random groups ",
             Tunable.INTEGER, new Integer(2)));


Download a sample plugin, here.


18. How to customize node graphics?


19. How to write a Group Viewer?


20. How to add components to the node view, edge view, and
attribute browser context menus?
To add a component to content menu of a node view, first we need create a listener class,
which implements the interface NodeContextMenuListener, then register this listener
through the network view.

Here is how the listener class looks like,
class MyNodeContextMenuListener implements NodeContextMenuListener {
       public void addNodeContextMenuItems(NodeView nodeView, JPopupMenu menu)
       {
               JMenuItem myMenuItem = new JMenuItem("MyNodeMenuItem");

               myMenuItem.addActionListener(new MyNodeAction(nodeView));

               if (menu == null) {
                       menu = new JPopupMenu();
               }
               menu.add(myMenuItem);
       }
}


The method addNodeContentMenuItems() takes two arguments, NodeView and
JPopupMenu. The JPopupMenu will be the one show up when user right-click on the
NodeView on canvas. The sample code above will add a new menu item
“MyNodeMenuItem” in the popupMenu. The MyNodeAction class, which implements
ActionListener, will be the class performs the action after the menu item is clicked. The
NodeView parameter to the listener will provide the reference to the Node via
NodeView.getNode() method and take whatever action desired.

The following two lines will register the listener with the current view,

MyNodeContextMenuListener l = new MyNodeContextMenuListener();
Cytoscape.getCurrentNetworkView().addNodeContextMenuListener(l);

The sample works for NodeView, case for the EdgeView is very similar.

Attribute browser is a Cytoscape core plugin, it also provides interface to add new menu
item to the conextMenu (since Cytoscape 2.6).

import browser.AttributeBrowserPlugin;
…

JMenuItem menuItem = new JMenuItem("MyMenuItem_browser");
menuItem.addActionListener(actionListener);
AttributeBrowserPlugin.addMenuItem(browser.DataObjectType.NODES,
menuItem);

Note that there are three browser panels for NODE, EDGE and NETWORK, we should
explicitly specify which browser a menuItem will be added. In the sample code above, a
menu item is added to contextMenu of the node browser.

Download a sample plugin, here.


21. How to save/restore plugin states?
All Cytoscape plugin extends CytoscapePlugin class, which implements
PropertychangeListener. In order to save/restore plugin properties (globally), the plugin
need to overwrite the method “onCytoscapeExit()” for property saving and some code in
plugin constructor for restore.

/**
* Save global state to "tutorial21.props"
*/
public void onCytoscapeExit() {}

// restore state
public void restoreInitState() {
      File global_prop_file =
CytoscapeInit.getConfigFile("tutorial21.props");
}

If plugin need to save states in Session, overwrite the following two methods.

public void saveSessionStateFiles(List<File> pFileList) {}
public void restoreSessionState(List<File> pStateFileList) {}

Download a sample plugin, here.


22. How to use Cytoscape task monitor to show the progress of my
job?
If a task will take a long time to finish, it is better to use Cytoscape task manager to run it
in a separate thread and show its progress to the user. With the Task manager, it is
possible to cancel the task, and the window won’t freeze.




strategy to ensure that once written, the code doesn't become out of date, which means
that it compiles and runs for each new version of Cytoscape.



Time line

Week 1 (4/7/08 – 4/11/08)
      Draft for the main webpage, outlines for each plugin, ant build file, first complete
      plugin


A single web page organizing the topics providing links to each howto and links to
download the code.

Need a text description of how to accomplish the task. This should be 1-3 paragraphs
with samples of code interspersed.

								
To top