= Cytoscape 2.X Plugin Developer Cookbook = <> == Introduction == 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. 1. A manifest file, explicitly list the class, which extended !CytoscapePlugin class 1. 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 . == How to add a tabbed Panel to Control panel? == It takes three steps to add a tabbed panel to the control panel. {{{ #!java //First, get a handler to the cytoPanel west, which is the control panel CytoPanelImp ctrlPanel = (CytoPanelImp) Cytoscape.getDesktop().getCytoPanel(SwingConstants.WEST); //Create a JPanel object (a class extends JPanel, say, MyPanel) MyPanel myPanel = new MyPanel(); //Add it to the control panel. ctrlPanel.add("myPanel", myPanel); }}} Download a sample plugin, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial01.zip|Here]]. <
> == How to add an image icon (menu item) to the toolbar? == Create a toolbarAction {{{ #!java 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. Add the action to Cytoscape toolbar {{{ #!java Cytoscape.getDesktop().getCyMenus().addCytoscapeAction((CytoscapeAction) toolbarAction); }}} Download a sample plugin, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial02.zip|Here]]. == 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, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial03.zip|Here]]. <
> == 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”. {{{ #!java //create a network without a view CyNetwork yNetwork = 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. {{{ #!java cyNetwork.removeNode(node1.getRootGraphIndex(), true); }}} The following statement will destroy a network. {{{ #!java Cytoscape.destroyNetwork(cyNetwork); }}} Download a sample plugin, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial04.zip|Here]]. == 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. {{{ #!java // 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. {{{ #!java // hide a node cyNetwork.hideNode(node1.getRootGraphIndex()); }}} The following statement will destroy a network view. {{{ #!java Cytoscape.destroyNetworkView(cyView); }}} Download a sample plugin, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial05.zip|Here]]. <
> == 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. {{{ #!java CyNetwork current_network = Cytoscape.getCurrentNetwork(); Set selectedNodes = current_network.getSelectedNodes(); Iterator it = selectedNodes.iterator(); while (it.hasNext()) { Node aNode = (Node) it.next(); System.out.println(aNode.getIdentifier()); } }}} Download a sample plugin, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial06.zip|Here]]. <
> == How to handle events from a network (and discuss each event type)? == {{{ #!java // 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_FOCUSED)) { System.out.println("Received an event -- CytoscapeDesktop.NETWORK_VIEW_FOCUSED!"); } } }}} Download a sample plugin, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial07.zip|Here]]. <
> == 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. {{{ #!java //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, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial08.zip|Here]]. <
> == How to zoom a network view? == To zoom a network view, all we need to know is the scale factor. Here is how, {{{ #!java // Get reference to the view final CyNetworkView networkView = Cytoscape.getCurrentNetworkView(); networkView.setZoom(scaleFactor); networkView.updateView(); }}} Download a sample plugin, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial09.zip|Here]]. == 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. {{{ #!java 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. {{{ #!java // inform others via property change event. Cytoscape.firePropertyChange(Cytoscape.ATTRIBUTES_CHANGED, null, null); }}} Download a sample plugin, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial10.zip|Here]]. <
> == 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. {{{ #!java CyAttributes cyNodeAttrs = Cytoscape.getNodeAttributes(); cyNodeAttrs.deleteAttribute(attributeName); }}} Download a sample plugin, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial11.zip|Here]]. == 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, {{{ #!java WebServiceClient 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. {{{ #!java // 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, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial12.zip|Here]]. <
> == 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 {{{ #!java WebServiceClientManager.registerClient(My_NCBIClient.getClient()); }}} Download a sample plugin, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial13.zip|Here]]. == 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. {{{ #!java VisualMappingManager vmm = Cytoscape.getVisualMappingManager(); Set 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 “Example Visual Style”. {{{ #!java public static final String vsName = "Example Visual Style"; VisualStyle createVisualStyle(CyNetwork network) { NodeAppearanceCalculator nodeAppCalc = new NodeAppearanceCalculator(); EdgeAppearanceCalculator edgeAppCalc = new EdgeAppearanceCalculator(); GlobalAppearanceCalculator globalAppCalc = new GlobalAppearanceCalculator(); // Passthrough Mapping - set node label //PassThroughMapping pm = new PassThroughMapping(new String(), "attr2"); PassThroughMapping pm = new PassThroughMapping(new String(), "attr2asdf"); Calculator nlc = new BasicCalculator("Example Node Label Calculator", pm, VisualPropertyType.NODE_LABEL); nodeAppCalc.setCalculator(nlc); // Discrete Mapping - set node shapes DiscreteMapping disMapping = new DiscreteMapping(NodeShape.RECT, ObjectMapping.NODE_MAPPING); disMapping.setControllingAttributeName("attr1", network, false); disMapping.putMapValue(new Integer(1), NodeShape.DIAMOND); disMapping.putMapValue(new Integer(2), NodeShape.ELLIPSE); disMapping.putMapValue(new Integer(3), NodeShape.TRIANGLE); Calculator shapeCalculator = new BasicCalculator("Example Node Shape Calculator", disMapping, VisualPropertyType.NODE_SHAPE); nodeAppCalc.setCalculator(shapeCalculator); // Continuous Mapping - set node color ContinuousMapping continuousMapping = new ContinuousMapping(Color.WHITE, ObjectMapping.NODE_MAPPING); continuousMapping.setControllingAttributeName("attr3", network, false); Interpolator numToColor = new LinearNumberToColorInterpolator(); continuousMapping.setInterpolator(numToColor); Color underColor = Color.GRAY; Color minColor = Color.RED; Color midColor = Color.WHITE; Color maxColor = Color.GREEN; Color overColor = Color.BLUE; // Create boundary conditions less than, equals, greater than 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 continuousMapping.addPoint(0.0, bv0); continuousMapping.addPoint(1.0, bv1); continuousMapping.addPoint(2.0, bv2); Calculator nodeColorCalculator = new BasicCalculator("Example Node Color Calc", continuousMapping, VisualPropertyType.NODE_FILL_COLOR); nodeAppCalc.setCalculator(nodeColorCalculator); // Discrete Mapping - Set edge target arrow shape DiscreteMapping arrowMapping = new DiscreteMapping(ArrowShape.NONE, ObjectMapping.EDGE_MAPPING); arrowMapping.setControllingAttributeName("interaction", network, false); arrowMapping.putMapValue("pp", ArrowShape.ARROW); arrowMapping.putMapValue("pd", ArrowShape.CIRCLE); Calculator edgeArrowCalculator = new BasicCalculator("Example Edge Arrow Shape Calculator", arrowMapping, VisualPropertyType.EDGE_TGTARROW_SHAPE); edgeAppCalc.setCalculator(edgeArrowCalculator); // Create the visual style VisualStyle visualStyle = new VisualStyle(vsName, nodeAppCalc, edgeAppCalc, globalAppCalc); return visualStyle; } }}} The following snippet of code shows how to use the above createVisualStyle(network) method. After the visualStyle is created, it will appear in the comboBox of VizMapper main panel. {{{ #!java // get the network and view CyNetwork network = Cytoscape.getCurrentNetwork(); CyNetworkView networkView = Cytoscape.getCurrentNetworkView(); // get the VisualMappingManager and CalculatorCatalog VisualMappingManager manager = Cytoscape.getVisualMappingManager(); CalculatorCatalog catalog = manager.getCalculatorCatalog(); // check to see if a visual style with this name already exists VisualStyle vs = catalog.getVisualStyle(vsName); if (vs == null) { // if not, create it and add it to the catalog vs = createVisualStyle(network); catalog.addVisualStyle(vs); } networkView.setVisualStyle(vs.getName()); // not strictly necessary // actually apply the visual style manager.setVisualStyle(vs); networkView.redrawGraph(true,true); }}} Download a sample plugin, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial14.zip|Here]]. <
> == 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. {{{ #!java // 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. {{{ #!java 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); }}} Download a sample plugin, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial15.zip|Here]]. <
> == How to load a visual properties file? == Cytoscape supported import/export of visual properties file. They can be found at File --> Import --> Vizmap Property File and File--> Export --> Vizmap Property File. To load a vizmap property file programmatically, we can reuse most of the code in the Cytoscape core class “cytoscape.actions.!ImportVizmapAction”. Cytoscape already had build-in class to handle the import of Vzmap property file, all we need is to fire a VIZMAP_LOADED event as following {{{ #!java Cytoscape.firePropertyChange(Cytoscape.VIZMAP_LOADED, null, file.getAbsolutePath()); }}} After the event is fired, a dialog box will prompt the Import of Vizmap Property File. Download a sample plugin, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial16.zip|Here]]. <
> == 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, {{{ #!java 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. {{{ #!java layoutProperties.add(new Tunable("groupcount", "Number of random groups ", Tunable.INTEGER, new Integer(2))); }}} Download a sample plugin, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial17.zip|Here]]. <
> == How to write a Group Viewer? == A class of CyGroupViewer must implement the !CyGroupViewer interface and it should register with the !CyGroupManager. {{{ #!java MyGroupViewer myView = new MyGroupViewer(); // Register with CyGroup CyGroupManager.registerGroupViewer(myView); }}} Download a sample plugin, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsf/scooter/sampleGroupViewer|Here]]. <
> == 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 what the listener class looks like, {{{ #!java 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, {{{ #!java 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). {{{ #!java 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, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial20.zip|Here]]. <
> == 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. {{{ #!java /** * 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. {{{ #!java public void saveSessionStateFiles(List pFileList) {} public void restoreSessionState(List pStateFileList) {} }}} Download a sample plugin, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial21.zip|Here]]. <
> == 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. Download a sample plugin, [[http://chianti.ucsd.edu/svn/csplugins/trunk/ucsd/pwang/wikizip/tutorial22.zip|Here]]. <
> == How to add new attribute functions via a Cytoscape plug-in == Here we will go through all the steps necessary to create a new built-in function ''IXOR()''. The complete example code and can be downloaded from here [[attachment:tutorial-23.zip]]. The easiest part is writing the actual plug-in class, which look similar to this: {{{ #!java package cytoscape.tutorial23; import cytoscape.plugin.CytoscapePlugin; import org.cytoscape.equations.EqnParser; import org.cytoscape.equations.Parser; public class Tutorial23 extends CytoscapePlugin { public Tutorial23() { final EqnParser theParser = Parser.getParser(); theParser.registerFunction(new IXor()); } } }}} Here we register a new built-in function called IXor. You can also register multiple built-in functions if you prefer. The next part is creating one class each for every new built-in. Each such class has to implement the ''org.cytoscape.equations.Function'' interface usually via ''org.cytoscape.equations.!AbstractFunction''. The easiest way to get started is to peruse the existing built-ins in ''equations'' Cytoscape core library and look for a function with a similar or identical argument list. If you can't find one it may still be instructive to read through the implementation of a couple of existing functions. First you have to create the constructor where you describe the arguments that your function will take: {{{ public IXor() { super(new ArgDescriptor[] { new ArgDescriptor(ArgType.INT, "arg1", "A quantity that can be converted to an integer."), new ArgDescriptor(ArgType.INT, "arg2", "A quantity that can be converted to an integer."), }); } }}} The most trivial to implement methods are ''getName()'', and ''getFunctionSummary()''. {{{ #!java /** * Used to parse the function string. This name is treated in a case-insensitive manner! * @return the name by which you must call the function when used in an attribute equation. */ public String getName() { return "IXOR"; } /** * Used to provide help for users. * @return a description of what this function does */ public String getFunctionSummary() { return "Returns an integer value that is the exclusive-or of 2 other integer values."; } }}} The next method is still simple but already touches on the one area that is somewhat complicated in attribute functions: data types and data type conversions! {{{ #!java public Class getReturnType() { return Long.class; } }}} Our example function is supposed to return an integer value. Integers in equation functions are represented as instances of class ''java.lang.Long''. Therefore it is imperative '''not''' to return ''Integer.class''! The user of the function can be blissfully unaware of this distinction. Just remember to always substitute ''Long'' for ''Integer'' and you should be fine. The next method ''evaluateFunction()'' is the one that gets called when an expression is being evaluated. No argument type-checking is needed here because the compiler already took care of that for us. But, we need to handle all possible valid argument types and counts. (N.B., functions may be ''overloaded'' and/or ''variadic''.) In this example the arguments can be any combination of Long and Double. {{{ #!java public Object evaluateFunction(final Object[] args) { long arg1; try { arg1 = FunctionUtil.getArgAsLong(args[0]); } catch (final Exception e) { throw new IllegalArgumentException("IXOR: can't convert the 1st argument to an integer!"); } long arg2; try { arg2 = FunctionUtil.getArgAsLong(args[0]); } catch (final Exception e) { throw new IllegalArgumentException("IXOR: can't convert the 2nd argument to an integer!"); } final long result = arg1 ^ arg2; return (Long)result; } }}} === See Also === This [[Implementing_Attribute_Equations_Functions| tutorial on how to write attribute functions]] may also be helpful. === Final Comments === If you find functions in Excel^tm^ that provide similar functionality to what you plan to implement, please try to match Excel^tm^'s functionality as closely as possible. Many users are familiar with either Excel^tm^ or another spreadsheet program that implements Excel^tm^-compatible functions and by following its lead you may greatly reduce the cognitive overhead you place on your users. Also, if you believe that the functionality you request may well be generally useful and not a one-off for your own organisation, you may consider contacting the Cytoscape development team at UCSD and suggest to them to implement it for you. == How to add plug-in specific help to the Cytoscape main help system == This tutorial [[attachment:tutorial24.zip]] provides a step-by-step recipe on adding additional help topics from within a plug-in to the Cytoscape help. Start with unzipping the attached example and copying the '''help''' subdirectory tree into your own project. Next copy the '''help''' target of the example's '''build.xml''' file to your own ant file or implement equivalent functionality in your own build system. Make sure not to forget to actually invoke the '''help''' target. In the main entry point of your plug-in, add the following function: {{{ ... import cytoscape.view.CyHelpBroker; import javax.help.HelpSet; import java.net.URL; ... /** * Hook plugin help into the Cytoscape main help system: */ private void addHelp() { final String HELP_SET_NAME = "/help/jhelpset"; final ClassLoader classLoader = Tutorial24.class.getClassLoader(); URL helpSetURL; try { helpSetURL = HelpSet.findHelpSet(classLoader, HELP_SET_NAME); final HelpSet newHelpSet = new HelpSet(classLoader, helpSetURL); if (!CyHelpBroker.addHelpSet(newHelpSet)) System.err.println("Tutorial24: Failed to add help set!"); } catch (final Exception e) { System.err.println("Tutorial24: Could not find help set: \"" + HELP_SET_NAME + "!"); } } }}} Invoke this function somewhere in the constructor for the class that extends '''!CytoscapePlugin'''. Finally, edit the files in the help directory. Most likely you would want to edit the files named '''jhelpmap.jhm''' and '''Topic.html'''. You may consider removing both, '''!SubTopic.html''' and the reference to it in '''jhelpmap.jhm'''. You can also add additional topics, if you want. The effect this will have is to add a new topic at the very bottom of the Cytoscape help index. You may have a help button in your plug-in, in which case you would probably want to add code similar to the following: {{{ ... import cytoscape.view.CyHelpBroker; ... CyHelpBroker.getHelpBroker().enableHelpOnButton(helpButton, "Topic", null); ... }}} That should be all that is needed to dynamically add your own help topic(s)!