Upload
others
View
5
Download
0
Embed Size (px)
Citation preview
ISMB 2015 1
John “Scooter” Morris, Ph.D., UCSF
Network Visualization and Analysis
Cytoscape 3.3 Developers Tutorial
4
Outline• Introduc/ons&Setup• “Varia/onsonatheme–HelloWorld”
– Step1:CytoscapeandOSGi– Step2:Cytoscapenetworkmodel– Step3:Cytoscapetablemodel– Step4:Cytoscapevisualmodel– Step5:Cytoscapeuserinterfacemechanisms– Step6:Events– Step7:Commands
• APItour• Discussion:BestPrac/ces
6
Introductions
• John“Scooter”Morris– Currently
• AdjunctAssistantProfessor,Pharmaceu/calChemistry• Director,NIHResourceforBiocompu/ng,Visualiza/on,andInforma/cs(RBVI)@UCSF
• RovingEngineer,NIHNa/onalResourceforNetworkBiology(NRNB)– 1985-2004
• Dis/nguishedSystemsArchitect:Genentech,Inc.
– Cytoscapecoreteamsince2006– AuthorofseveralCytoscapeplugins
• SFLDLoader,structureViz,clusterMaker,chemViz,metanodePlugin,groupTool,commandTool,bioCycPlugin
9
Caveats
• I’massumingyou’reallcompetentJavaprogrammers
• Can’tcovereverything– Youwouldbeoverwhelmedevenifwetried
• We’regoingtocoverCytoscape3.3BundledAppAPI– Simpleappsaredifferentinmanyways
• We’llbebuildingonthingsaswego– Stopmeandaskques/ons
10
Setup – Shell
• Downloadsamplefilesfrom:hlp://www.cgl.ucsf.edu/home/scooter/Cytoscape3DevTut/setup.zip
• Unpack
11
Setup – Eclipse
• InstallEclipse– Alsowant:
• m2e
• Downloadsamplefile• Unpack• InEclipse:
– FileàImportàMavenàExis/ngMavenProjects– NavigatetotheHelloWorlddirectoryfromthedownloadabove
12
Debugging with Eclipse
RemoteExecu+onforDebugging• RunCytoscapewithdebugasthefirstcommandlineargumentInWindows
cytoscape.bat debugInLinux/Mac
./cytoscape.sh debug Makesureyoucanseethefollowingmessageintheterminal:Listeningfortransportdt_socketataddress:12345NOTE:mustbeintheCytoscapedirectory
13
Debugging with Eclipse RunDebuggerFromEclipse• ClickRunandselectDebugConfigura/ons...• SelectRemoteJavaApplica/onsandcreatenewconfigura/on• Select/EnterthefollowingandpressApply:
– Name:Cytoscape3– Project:myproject(yourprojectnamemaybedifferent;so"browse"tofindthe
oneyouareabouttodebug)– Connec/onType:Standard(SocketAlach)– Host:localhost– Port:12345(ortheportspecifiedinthecytoscape.shfile)
• PressDebug.ThisstartsupCytoscape3.Arer20-30seconds,youwillseeCytoscapeDesktop.
• SetabreakpointinEclipse• SwitchPerspec/vetoDebugmode:Window→Perspec/ve→Debug• LoadthebundleintoyourOSGIcontainerandrun
14
Step 1: Cytoscape & OSGi
• Cytoscape3designgoals– Scalability– Performance– Stability
• Applica/onstability• APIstability• Modularity
– EnforcedbyOSGi
15
OSGi
• Wikipedia:TheOSGiframeworkisamodulesystemandservicepla9ormfortheJavaprogramminglanguagethatimplementsacompleteanddynamiccomponentmodel,somethingthatdoesnotexistinstandaloneJava/VMenvironments.ApplicaAonsorcomponents(comingintheformofbundlesfordeployment)canberemotelyinstalled,started,stopped,updated,anduninstalledwithoutrequiringareboot;managementofJavapackages/classesisspecifiedingreatdetail.ApplicaAonlifecyclemanagement(start,stop,install,etc.)isdoneviaAPIsthatallowforremotedownloadingofmanagementpolicies.TheserviceregistryallowsbundlestodetecttheaddiAonofnewservices,ortheremovalofservices,andadaptaccordingly.
16
OSGi
• Service-oriented• A“bundle”istheunitofaccess
– Bundlescanbestartedandstoppedindependently• Bundlesimplementservices
– Canberegisteredandunregistered– Generally,inter-bundleaccessisthroughaservice
• Enforcedsepara/onofAPIandImplementa/on– RulesarethatyoucandependonAPIbundles,butnotimplementa/onbundles
17
Anatomy of a Bundle
• JARwithextrametadata
• Imports– TheJavapackagesusedbythebundle
• Exports– Javapackagesinthebundlethatotherbundlesareallowedtouse(usuallyjustAPI)
• Ac/vator– Triggeredwhenbundleisstarted/stopped
BundleAc+vator
Exports
Imports
18
Cytoscape 3 • Service-orientedmicrokernel
• OSGicore– Dynamicallyloads/unloadsmodules,a.k.a.bundles
• EachsubsysteminCy3hasseparateOSGibundle(s)
• Appscanalsobepackagedasbundles
OSGi
DataModel ViewModel
Renderer I/O
MyApp
19
Example: HelloWorld
• pom.xml!– Mavenprojectdescriptor
– Maveniden/fier• Groupid• Ar/factid• Version
– OSGiiden/fier• Bundle-SymbolicName
– Describesimports/exports
• Activator.java!– Bundleac/vator
20
Maven Project Layout
• pom.xml!– Projectdescriptor
• src/main/java !– Bundlecode
• src/test/java !– Testcode– NotincludedinbundleJAR
• src/main/resources !– Non-codefilesthatshouldbeincludedinbundleJAR
21
Core Bundles
• app• applica/on• command-executor• core-task• custom-graphics• datasource• equa/ons• event• group• io• layout
• model• presenta/on• property• service• session• swing-u/l• viewmodel• vizmap• vizmap-gui• webservice• work
22
Core Bundles
• Usuallycomeinsets:– API(op/onal)
• Noac/vator– Implementa/on
• AtleastoneperAPIbundle• Noexports
• SeparateAPIsowecankeepimplementa/onmodular– Desktopapplica/on– Consoleapplica/on,forscripts
Impl.BundleAc+vator
APIBundle
Imports
Exports
23
Core Bundles
• Nothingshouldimportimplementa/onbundles
• Unlessit’sforunittes/ng
Impl.BundleAc+vator
APIBundle
Imports
Exports
24
Core Bundles
• Taskbundles– work-api– work-swing-api– work-impl– work-swing-impl– work-headless-impl
• VizMapperbundles– vizmap-api– vizmap-gui-api– vizmap-gui-core-impl– vizmap-gui-impl– vizmap-impl
25
OSGi Services
• Service– AninstanceofaJavainterface
– ThegluebehindAPIandimplementa/onbundles
– UsuallyregisteredbyaBundleAc/vator
• InCy3:– DefinedbyanAPIbundle– Registeredbyanimplementa/onbundle
Impl.BundleAc+vator
APIBundle
Imports
Exports
26
OSGi Services
• Interface
• Implementa/on• Proper/es
– Arbitrarykey-valuepairs
• interface MyService { … } !
• class MyServiceImpl implements MyService { … } !
• (“title”, “My Service”) !(“preferredMenu”, “Apps”) !
27
Cytoscape API
• AvailableasOSGiservices• Twomaintypes:
– API:Applica/onProgrammingInterface• Justfetchanduse:
MyService service = getService(context, MyService.class); !
– SPI:ServiceProviderInterface• Implement/extendandregister:
registerService(context, new MyServiceImpl(), ! MyService.class, properties); !
28
OSGi Services
• Mostcommontypesofservices:– Factories
• Createnewinstances– Managers
• Track,provideaccessto,oroperateoncollec/onsofobjects
– U/li/es• Collec/onsofu/lityfunc/ons
29
Cytoscape TaskFactories
• TaskFactories– MainunitofworkinCytoscapeisa“Task”– TasksarecreatedbyTaskFactories
31
Cytoscape TaskFactories
• TaskFactories– MainunitofworkinCytoscapeisa“Task”– TasksarecreatedbyTaskFactories– TaskFactoriesareOSGiservices– CanberegisteredinyourCyAc/vator:
TaskFactory factory =
registerService(bc, myFactory, TaskFactory.class, properties);wheremyFactoryisthetaskfactoryyouwanttoregister
– proper/esprovidemeta-dataaboutthefactory• JavaProper/es
32
Cytoscape TaskFactories
• CytoscapeTaskFactoryProper/es– Proper/eshavespecialmeaninginCytoscape– Definedinorg.cytoscape.work.ServiceProper/es– Keyproper/es
• TITLE–Ifusedasamenu,thisisthemenu/tle• PREFERRED_MENU–Wherethiswillbeadded• ENABLE_FOR–Whenthismenuisac/ve• IN_TOOL_BAR–isitinthetoolbar?• IN_MENU_BAR–isitinthetop-levelmenus?• MENU_GRAVITY–Thespecificgravityofthisitem.
33
Cytoscape TaskFactories
• Example:import org.cytoscape.work.AbstractTaskFactory;import org.cytoscape.work.TaskIterator;
class MyTaskFactory extends AbstractTaskFactory {public MyTaskFactory() {
super();}
public TaskIterator createTaskIterator() {return null; // Fill in
}
public boolean isReady() { return true; }}
34
Cytoscape TaskFactories
• Example(inCyAc/vator):MyTaskFactory myFactory = new MyTaskFactory();Properties props= new Properties();// Note the “.” notation for cascading menusprops.setProperty(PREFERRED_MENU, "Apps.cddApp");props.setProperty(TITLE, "Load CDD Domains for Node");// Not all task factories will be commandsprops.setProperty(COMMAND, "loadCDDDomains4node");props.setProperty(COMMAND_NAMESPACE, "cddApp");props.setProperty(IN_MENU_BAR, "true");// Usually means the second menu itemprops.setProperty(MENU_GRAVITY, "2.0");registerService(bc, loadCDDDomainNodeView, NodeViewTaskFactory.class, nodeViewProps);
36
Important Factories
• CyNetworkFactory– model-api
• CyTableFactory– model-api
• CyGroupFactory– group-api
• CyNetworkViewFactory– viewmodel-api
• VisualMappingFunc/onFactory– vizmap-api
• VisualStyleFactory– vizmap-api
37
Important Managers
• CyApplica/onManager– applica/on-api– Lotsof“state”informa/on
• CyNetworkManager– model-api
• CyTableManager– model-api
• CyNetworkTableManager– model-api– Managestheassocia/onbetweentablesandnetworkobjects
• CyNetworkViewManager– viewmodel-api
• CyGroupManager– group-api
• VisualMappingManager– vizmap-api
38
Special Task Factories
• core-task-api– NetworkViewTaskFactory
• Networkbackgroundcontextmenu
– NodeViewTaskFactory• Nodecontextmenu
– EdgeViewTaskFactory• Edgecontextmenu
39
Tasks
• Intendedtoruninmul/pleenvironments– Desktopapplica/on– Headless,viascrip/ng– Programma/cally,viaanapp
• Notappropriatetoassumetaskwillberuninapar/cularway– OnlyuseSwingwithintasksifnecessary
41
Concepts: Data Model
• CyNetwork– Mul/graph– Directedorundirected– CyNode– CyEdge
• CyTable– CyColumn
• Primarykey
– CyRow• SUID
– Session-uniqueiden/fier
42
Concepts: Data Model
• CyNetwork– Mul/graph– Directedorundirected– CyNode– CyEdge
• CyTable– CyColumn
• Primarykey
– CyRow• SUID
– Session-uniqueiden/fier
Node Edge Network
43
A
C
B
Concepts: Data Model • CyNetwork
– Canhavemul/plenetworksina“collec/on”• Essen/allyasingle-levelhierarchy
– CyRootNetwork• TopCyNetworkinthecollec/on• Containsallnodesandedges• org.cytoscape.model.subnetwork
– CySubNetwork• Projec/onofpartofCyRootNetwork• Possiblymul/plesubnetworks• NodesandedgeshavethesameSUIDsasinCyRootNetwork
• AllCyNetworksnotexplicitlyCyRootNetworksareCySubNetworks
Node Edge Network
A
C
Network Collection
44
Concepts: Data Model • CyNetwork
– Canhavemul/plenetworksina“collec/on”
– CyNodeandCyEdgealributescanbeshared
– Networkalributesarenotshared
• CyTable– Actuallyhavethree“types”of
tables:• Sharedalributes
– Sharedwithinnetworkcollec/on• Localalributes
– Notshared• “Façade”table
– Aviewofthemergedlocalandsharedtables
A
C
B
Node Edge Network
A
C
Network Collection
45
Concepts: Data Model • Crea/nganetwork
– UseCyNetworkFactorytocreatethenetworkandCyNetworkManagertoaddit• Commonpalern• NeedtogettheminyourCyAc/vator:CyNetworkFactory networkFactory =
getService(bc, CyNetworkFactory.class);CyNetworkManager networkManager =
getService(bc, CyNetworkManager.class);
• Thenpassthemtoyourtaskfactoryinitsconstructor
– Thenjustusethem:CyNetwork newNetwork = networkFactory.createNetwork();networkManager.addNetwork(newNetwork);
– Mostopera/ons(includingaddingnodesandedges)areonCyNetwork
46
Step 2: Project
• AddatasktotheTaskFactoryfromStep1• Taskshouldaddanodetothenetwork
– IrecommendthatyourTaskextendsAbstractTask– Ifyouhave/me,addtwonodesandoneedgebetweenthem
• NOTE:Youwillhavetocreateaviewmanually• HINT:youwillneedtoedityourpom.xmlfiletoincludetheaddi/onaldependency
47
Step 3: Table Model
• CyTables– Standardtablemodel:
• Columnsarefixed-type:– Boolean,String,Integer,Long,Double– List<Boolean>,List<String>,List<Integer>,List<Long>,List<Double>
• Rowsaresinglyindexedbyakey– Columnscanbe“virtual”
• Essen/allyfunc/onsasalinkfromonetableintoanother
48
Tables and Networks
– Crea/ngaCyNetworkcreates:• Networktables
– LOCAL_ATTRSandHIDDEN_ATTRSforeachnetwork• Nodetables
– LOCAL_ATTRSandHIDDEN_ATTRSeachnetwork– DEFAULT_ATTRSforeachnetwork
» Allcolumnsexceptkeyarevirtual(CombinesLOCAL_ATTRSandSHARED_ATTRS
– SHARED_ATTRSforeachcollec/on• Edgetables
– LOCAL_ATTRS,HIDDEN_ATTRS,andDEFAULT_ATTRSforeachnetwork
– SHARED_ATTRSforeachcollec/on
49
Tables and Networks
ModelObject
Table Key Notes
CyNetwork LOCAL_ATTRS CyNetwork.SUID Standardlocaltable
CyNetwork HIDDEN_ATTRS CyNetwork.SUID Notshowntouser
CyNode LOCAL_ATTRS CyNode.SUID Localtablenotsharedacrossnetworksinthesamecollec/on
CyNode SHARED_ATTRS CyNode.SUID
Sharedtable.Oneforeachnetworkcollec/on.
CyNode DEFAULT_ATTRS CyNode.SUID
Thefaçadetable.Essen/allyallvirtualcolumnspoin/ngtoLOCAL_ATTRSandSHARED_ATTRStables
CyNode HIDDEN_ATTRS CyNode.SUID
Localalributesnotshowntotheuser
CyEdge LOCAL_ATTRS CyEdge.SUID Localtablenotsharedacrossnetworksinthesamecollec/on
CyEdge SHARED_ATTRS CyEdge.SUID
Sharedtable.Oneforeachnetworkcollec/on.
CyEdge DEFAULT_ATTRS CyEdge.SUID
Thefaçadetable.Essen/allyallvirtualcolumnspoin/ngtoLOCAL_ATTRSandSHARED_ATTRStables
CyEdge HIDDEN_ATTRS CyEdge.SUID
Localalributesnotshowntotheuser
50
Table Model
• Standardcolumns– CyNetwork.NAME
• Nameofthenode,edge,ornetwork
– CyNetwork.SELECTED• IfTRUE,thisobjectisselected
– CyRootNetwork.SHARED_NAME• IntheSHARED_ATTRStables• Shared(root)nameoftheobject
51
Table Model
• Canalsocreateyourowntables– Boundtonetworkobjects
• KeyisalwaysSUID(Long)• ShouldberegisteredwithCyNetworkTableManager• CanbeeasilypulledfromCyNetwork:
CyNetwork.getTable(Class<? extends CyIdentifiable> type, String namespace);
• Shortcuttogetarow:CyNetwork.getRow(CyIdentifiable entry, String namespace);– Unbound
• Keyisanyvalidtype• ShouldberegisteredwithCyTableManager
52
Accessing Tables
• Tes/ngforcolumns– Musttestforcolumnexistencebeforeaccessif (table.getColumn(String columnName) != null)
• Crea/ngnewcolumns– Columnsmustbetyped– Listcolumnsmustincludethelisttype
• Gezngrows– Fromtable:
getRow(Objectkey)– Fromanetwork:
getRow(CyIden/fiableentry,Stringnamespace)
53
Accessing Tables
• Gezngdata– Alldataaccessisthroughrows:<T> T CyRow.get(String columnName, Class<? extends T> type)Integer I = row.get(“clusterNumber”, Integer.class);
– Where“type”isthecolumntype.Itisanerrorifthetypeiswrong
• SezngdataCyRow.set(String columnName, T value)
– WhereTisthecolumntype
• Note:addingnodesandedgesautoma/callyaddsthecorrespondingrows
54
Step 3: Project
• Inthenetworkyoucreatedbefore:– Changethenameofthenodeornodes– Createtwonewnodecolumns:
• HelloàListofStrings• WorldàDouble
– Adddatatothenewcolumns
55
Step 4: View Model
• CyNetworkView– View<CyNode>– View<CyEdge>
• VisualProperty– Examples:
• NODE_X_LOCATION• EDGE_WIDTH• NETWORK_HEIGHT
56
View Model • Crea/nganetworkview
CyNetworkViewFactory.createNetworkView(CyNetworknetwork);
– NeedtogetCyNetworkViewFactoryinyourCyAc/vator– WillcreateViewsforallnodesandedges
• GeznganetworkviewCyNetworkViewManager.getNetworkViews(CyNetworknetwork);
– NeedtogetCyNetworkViewManagerinyourCyAc/vator– Noteyougetacollec/onofviewsback–i.e.therecanbemul/pleviewspernetwork
• GezngnodeandedgeviewsView<CyEdge>edgeView=CyNetworkView.getNodeView(CyNodenode);
View<CyNode>nodeView=CyNetworkView.getEdgeView(CyEdgeedge);
57
Visual Properties
• VisualLexicon– VisualPropertyhierarchy– Childproper/esinheritvaluesfromparents
• Node– NODE_PAINT
• NODE_BORDER_PAINT• NODE_FILL_COLOR
58
Visual Properties
• VisualLexicon– VisualPropertyhierarchy– Childproper/esinheritvaluesfromparents
• Node– NODE_PAINT
• NODE_BORDER_PAINT• NODE_FILL_COLOR
59
Visual Properties
• VisualLexicon– VisualPropertyhierarchy– Childproper/esinheritvaluesfromparents
• Node– NODE_PAINT
• NODE_BORDER_PAINT• NODE_FILL_COLOR
60
Visual Properties
• VisualLexicon– VisualPropertyhierarchy– Childproper/esinheritvaluesfromparents
• Node– NODE_PAINT
• NODE_BORDER_PAINT• NODE_FILL_COLOR
61
Setting a Visual Property
• Visualproper/escanbedirectlysetinViewinterface: view.setLockedValue(VisualProperty<? extends T> vp, V value)
…whereViewisanodeview(View<CyNode>)oranedgeview(View<CyEdge>)
• UsuallygettheVisualPropertyfromBasicVisualLexicon• Typesareimportant.NeedtomakesureVisanappropriatetypefortheVisualProperty
• Example: nodeView.setLockedValue(BasicVisualLexicon.NODE_FILL_COLOR, Color.BLUE);
62
Visual Styles
• VisualMappingFunc/on– MapsbetweenaCyColumnvalueandaVisualPropertyvalue
– E.g.“name”columnmappedtoNODE_LABEL
• VisualStyle– Collec/onofVisualMappingFunc/ons
• Threemappingtypes:– Passthrough
• Usuallyusedforlabels– Discrete
• Categoricaldata– Con/nuous
• Range-to-rangemappings• Nodecolorgradient• Nodesize
63
Building a Visual Mapping
• VisualMappingManager– Managesallvisualstyles– GetitinyourCyAc/vatorasaservice
• Gezngthevisualstyleforanetwork: VisualStyle style =
vmm.getVisualStyle(CyNetworkView networkView);
..wherevmmistheVisualMappingManager
• CreateaVisualStyle(usuallymakeacopy)– UseVisualStyleFactory.createVisualStyle(style);– GetitinyourCyAc/vatorasaservice
64
Building a Visual Mapping
• GetthedesiredVisualMappingFunc/onFactoryinyourCyAc/vator:
VisualMappingFunctionFactory vmfFactoryC = getService(bc,VisualMappingFunctionFactory.class,
"(mapping.type=continuous)"); VisualMappingFunctionFactory vmfFactoryD =
getService(bc,VisualMappingFunctionFactory.class, "(mapping.type=discrete)"); VisualMappingFunctionFactory vmfFactoryP =
getService(bc,VisualMappingFunctionFactory.class, "(mapping.type=passthrough)");
• Notethisisalilledifferent.We’reusingthefilterargumenttogetService
65
Building a Visual Mapping
• Passthrough://Use pass-through mapping String ctrAttrName1 = "SUID"; PassthroughMapping pMapping = (PassthroughMapping) vmfFactoryP.createVisualMappingFunction(ctrAttrName1,
String.class, BasicVisualLexicon.NODE_LABEL); vs.addVisualMappingFunction(pMapping);
// Add the new style to the VisualMappingManagervmm.addVisualStyle(vs);
// Apply the visual style to the NetworkViewvs.apply(myNetworkView); myNetworkView.updateView();
66
Building a Visual Mapping
• Con/nuous:// Set node color map to attribute "Degree” ContinuousMapping mapping = (ContinuousMapping) vmfFactoryC.createVisualMappingFunction("Degree", Integer.class,
BasicVisualLexicon.NODE_FILL_COLOR); // Define the points Double val1 = 2d;BoundaryRangeValues<Paint> brv1 = new BoundaryRangeValues<Paint>(Color.RED, Color.GREEN, Color.GREEN); Double val2 = 12d;
BoundaryRangeValues<Paint> brv2 = new BoundaryRangeValues<Paint>(Color.YELLOW, Color.YELLOW, Color.BLACK); // Set the points mapping.addPoint(val1, brv1); mapping.addPoint(val2, brv2);
// add the mapping to visual style
vs.addVisualMappingFunction(mapping);
67
Visual Property Precedence
• HowVisualPropertyisdeterminedforaView:1. LockedvaluefromView(a.k.a.bypass)2. MappedvaluefromVisualStyle3. DefaultvalueforVisualStyle4. DefaultvalueforVisualProperty
68
Step 4: Project
• Modifyyourapplica/ontocreateanini/alview• Changetheshapeofyourtwonodes• Createavisualstylethat:
– UsesthefirstvalueintheHellocolumntolabelthenode• WillneedtouseaVisualBypass,notapassthroughmapper
– UsesthevalueintheWorldcolumntosetthecolorusingacon/nuousmapper
69
Step 5: User Interface
• Tasksshouldworkinboth– Headless(i.e.nongui)mode
• Howdotasksgetexecuted?– GUImode
• SeparateSwingUI?
• Commands:headlessmode• Tunables:argumenthandling
70
Commands
• ExportsTaskFactoriesto:– Commandlinedialog– RESTinterface
• Simple– AddtoyourTaskFactoryproper/es:
• COMMAND_NAMESPACE– Generallythenameofyourapp.– Allofyourcommandswillbegroupedunderthis
• COMMAND– Thecommanditself
• Arguments?NOTE:wanttobecarefulaboutwhatTaskFactoriesyouexport(nonguionly)
71
Tunables
• Tunables:– areJavaAnnota/ons– automa/callygenerateGUI– automa/callyexposecommandarguments
• Example:import org.cytoscape.work.Tunable;import org.cytoscape.work.AbstractTask;class MyClass extends AbstractTask {
@Tunable (description=“My integer value”)public int value;
}
72
Tunables
• BasicTypes– int,double,float,String,long,boolean– File,URL
• ClassesformorecomplicatedTunables– ListSingleSelec/on,ListMul/pleSelec/on– BoundedDouble,BoundedFloat,BoundedInteger,BoundedLong
• Example:@Tunable (description=“Choose from the list”)public ListSingleSelection color= new ListSingleSelection(“red”, “blue”, “green”);
73
Tunables
• Command-onlyTunables– Usedforselec/onofnodes,edges,androws– CyNetwork– U/lityClasses
• EdgeList,NodeList,RowList
74
Tunables
• Commonlyusedtunableparameters– context:limittunabletocertaincontext(“gui”,“nongui”,“both”)
– dependsOn:dependencybetweentunables– gravity:controlorderofpanels– groups:grouptunablepanelstogether– listenForChange:listoftunablesthatwillupdatethistunable
– Tool/p
75
Tunables
• GelersandSelersapproach– Canalsoexplicitlyusegelersandselers– Allowsbelercontrolovervalues
@Tunable (description=“Test”)public int getTest() { return value; }public void setTest(int v) { value = v; }
– Veryusefulforini/aliza/onvaluesandreac/ngtochanges
76
Tunables
• OddsandEnds– Canhavecontextclasseswithmul/pletunables
• ContainsTunables:@ContainsTunablespublic MyContext context;
• Resul/ngUIwillincludecontextTunables– Providinga/tleforthedialog
• ProvidesTitle:@ProvidesTitlepublic String getTitle() {return “MyTitle”;}
77
Status Messages
• Twowaystoinformusersofstatus:– org.cytoscape.work.TaskMonitor
• Passedasargumenttorun()methodofTasks• setTitle()andshowMessage()providestatusmessages
– MessagesarealsorecordedintheCytoscapeTaskHistory
• setProgress()updatestheprogressbar– org.cytoscape.applicaAon.CyUserLog
• Generalloggingfacilityforusermessages– Uses(orcanuse)Log4J
• MessagesareloggedintotheCytoscapeTaskHistory
78
Step 5: Project
• ModifyyourTask:– Inputtheshapetomakeyournodes– Inputthehighandlowcolorsforyourange
• Exportacommandforyourtask
79
Step 6: Events
• Cytoscapephilosophy:– Effectlowerlayersbymethodinvoca/on– Effectupperlayersbyeventhandling
• Lowerlayersfireeventstobehandledbyupperlayers
• Lookfor“.events”packages:– org.cytoscape.model.events– org.cytoscape.view.model.events– org.cytoscape.applica/on.events
80
Events
• Registeryoureventlistenersasservices:MyListener listener = new MyListener();registerService(listener, NetworkAddedListener.class);
• YourclassjustneedstoimplementtheappropriatehandleEvent:class MyListener implements NetworkAddedListener {
public void handleEvent(NetworkAddedEvent ev) {// handle your data
}
}
81
Events (Selection)
• Listeningforselec/on– (wereallydidn’ttrytomakethishard…– …butwesucceeded)
• Programma/callyselec/ngnodesoredges:– SetCyNetwork.SELECTEDtoTrueintheappropriatedefaulttable
• Listeningforselec/on:– Listenforchangestorows(RowsSetListener)
82
RowsSetListener
• Probablywanteither– Thenetworksyoucareabout,or– CyNetworkTableManager…inyourconstructor
• ImplementRowsSetListener• RowsSetEvent:
– sourceistheCyTablethatcontainsthechangedrows– getColumnRecords(Stringcolumn)returnsacollec/onofRowSetRecords
– Finally,theeachRowSetRecordhastherow,column,andvalue
83
RowsSetListener Example public class NetworkSelectionLinker implements RowsSetListener { // Define variablespublic NetworkSelectionLinker(CyRootNetwork rootNetwork, CyEventHelper eventHelper) { this.rootNetwork = rootNetwork;
this.eventHelper = eventHelper; this.viewManager = clusterManager.getService(CyNetworkViewManager.class);
}
public void handleEvent(RowsSetEvent e) {
if (!e.containsColumn(CyNetwork.SELECTED) || ignoreSelection) return;
CyNetworkView currentNetworkView = clusterManager.getNetworkView(); ignoreSelection = true; Map<CyNetwork, Boolean> stateMap = new HashMap<CyNetwork, Boolean>();
for (CySubNetwork subNetwork: rootNetwork.getSubNetworkList()) { if (e.getSource().equals(subNetwork.getTable(CyNode.class, CyNetwork.LOCAL_ATTRS))) { for (RowSetRecord record: e.getColumnRecords(CyNetwork.SELECTED)) {
Long suid = record.getRow().get(CyIdentifiable.SUID, Long.class); Boolean value = (Boolean)record.getValue();
for (CySubNetwork sub2: rootNetwork.getSubNetworkList()) { if (subNetwork.equals(sub2) || sub2.getDefaultNodeTable().getRow(suid) == null) continue;
sub2.getDefaultNodeTable().getRow(suid).set(CyNetwork.SELECTED, value); }
} } if (viewManager.viewExists(subNetwork)) {
for (CyNetworkView view: viewManager.getNetworkViews(subNetwork)) { if (!view.equals(currentNetworkView)) { view.updateView(); }
} } }
eventHelper.flushPayloadEvents(); ignoreSelection = false;
}}
85
Step 7: Commands
• Loosely-coupledwaytoaccessfunc/onality– Core– Apps
• Generalidea:– CommandsareexportedtotheCommandTool
• Tools->CommandLineDialog
– Otherappscanexecutethosecommandsusingtheorg.cytoscape.commandpackage
86
Commands Availablenamespaces:
cddchemvizclusterclustervizcommandedgegpmlgrouplayoutnetworknoderinalyzerseqVizsessionsetsAppstructureViztableviewvizmapwikipathways
87
Commands
helpnetworkAvailablecommands:structureVizalignPerformsequence-drivenstructuralsuperposiAononagroupofstructures.structureVizannotateRIN AnnotatearesidueinteracAonnetwork(RIN)withtheaUributesofthe
correspondingresiduesinChimera.structureVizclosestructureVizcreateRIN CreatearesidueinteracAonnetwork(RIN)fromthecurrentmodel(s)inChimera.structureVizexitCloseallopenmodelsandexitChimerastructureVizlaunchLaunchChimera.structureVizlistmodelsListcurrentlyopenChimeramodels.structureVizopenOpennewstructuresinChimerastructureVizsendSendacommandtoChimera.structureVizsetChangestructureVizseWngsstructureVizshowDialogShowthemolecularnavigatordialogstructureVizsyncColorsSynchronizecolorsbetweenstructureresiduesandnetworknodes.helpstructureVizopenstructureVizopenarguments:
edgeList=[edgeColumn:value|edgename,...]|all|selected|unselected:ListofedgestoopenstructuresformodbaseID=<String>:Modbasemodelstofetchnetwork=current|[column:value|networkname]:Networkfortheselectednodes/edgesnodeList=[nodeColumn:value|nodename,...]|all|selected|unselected:ListofnodestoopenstructuresforpdbID=<String>:PDBIDtofetchshowDialog=true|false:ShowtheMolecularStructureNavigatordialogareropeningthestructureinChimerastructureFile=<File>:Structurefile
88
Commands
helpnetworkAvailablecommands:
networkaddAddnodesandedgestoanetwork(theymustbeinthecurrentcollecAon)networkaddedgeAddanedgebetweentwonodesnetworkaddnodeAddanewnodetoanetworknetworkcloneMakeacopyofthecurrentnetworknetworkcreateCreateanewnetworknetworkcreateaRributeCreateanewaUribute(column)inthenetworktablenetworkcreateemptyCreateanemptynetworknetworkdeleteDeletenodesoredgesfromanetworknetworkdeselectDeselectnodesoredgesinanetworknetworkdestroyDestroy(delete)anetworknetworkexportExportanetworkanditsviewtoafilenetworkgetReturnanetworknetworkgetaRributeGetthevalueforanetworkaUributenetworkgetproper+esGetthevisualpropertyvalueforanetworknetworkhideHidenodesoredgesinanetworknetworkimportfileImportanetworkfromafilenetworkimporturlImportanetworkfromaURLnetworklistListalloftheavailablenetworksnetworklistaRributesListalloftheaUributes(columns)fornetworksnetworklistproper+esListallofthenetworkvisualproperAesnetworkloadfileLoadanetworkfile(e.g.XGMML)networkloadurlLoadanetworkfile(e.g.XGMML)fromaurlnetworkrenameRenameanetworknetworkselectSelectnodesoredgesinanetworknetworksetaRributeSetavalueinthenetworktablenetworksetcurrentSetthecurrentnetworknetworksetproper+esSetnetworkvisualproperAesnetworkshowShowhiddennodesandedges
89
Executing Commands
1. Seeifthecommandisavilable1. Use
org.cytoscape.command.AvailableCommands
2. GetaTaskManager3. PopulateCreateaTaskIteratorusingthe
CommandExecutorTaskFactory
4. UseaTaskObservertogetresults
90
Commands Example // My Manager class
// From http://github.com/RBVI/StEMAPApp
public class StEMAPManager {
final CyServiceRegistrar serviceRegistrar;
final CyEventHelper eventHelper;
CommandExecutorTaskFactory commandTaskFactory = null;
SynchronousTaskManager taskManager = null;
AvailableCommands availableCommands = null;
public StEMAPManager(final CyServiceRegistrar cyRegistrar) {
this.serviceRegistrar = cyRegistrar;
}
public <S> S getService(Class<S> serviceClass) {
return serviceRegistrar.getService(serviceClass);
}
public void executeCommand(String namespace, String command,
Map<String, Object> args, TaskObserver observer) {
if (commandTaskFactory == null)
commandTaskFactory = getService(CommandExecutorTaskFactory.class);
if (availableCommands == null)
availableCommands= getService(AvailableCommands.class);
if (taskManager == null)
taskManager = getService(SynchronousTaskManager.class);
if (availableCommands.getNamespace(namespace) == null ||
!availableCommands.getCommands(namespace).contains(command))
throw new RuntimeException(“Can’t find command “+namespace+” “+command);
TaskIterator ti = commandTaskFactory.createTaskIterator(namespace, command, args, observer);
taskManager.execute(ti);
}
91
Commands Example // Load a PDB file into UCSF Chimer
// From http://github.com/RBVI/StEMAPApp
public void loadPDB(String pdbPath, String extraCommands) {
Map<String, Object> args = new HashMap<>();
if (pdbPath != null)
args.put("structureFile", pdbPath);
else
args.put("pdbID", getPDB());
args.put("showDialog", "true");
// Assumes that calling class implements TaskObserver
// StructureViz will give us a text string containing the
// name an number of the opened model
executeCommand("structureViz", "open", args, this);
try {
// Wait for things to process
Thread.sleep(500);
} catch (Exception e) {}
if (extraCommands != null) {
args = new HashMap<>();
args.put("command", extraCommands);
executeCommand("structureViz", "send", args, null);
}
}
}
92
Step 7: Project
• Writeanewapp– ExecutethecommandyouexportedinStep5– WillneedtosetthevaluesfortheTunables…
93
Sample Code
• Sampleapps– hlps://github.com/cytoscape/cytoscape-samples– Canuseastemplateforyourownapps
• Realappexample:– SIREN:SIgningofREgulatoryNetworks– hlp://baderlab.org/PegahKhosravi/SIREN– hlps://github.com/BaderLab/SirenApp
• Someappsonappstorelinktotheirsourcecode(e.g.DynNetwork)
95
API Tour
• hlp://chian/.ucsd.edu/cytoscape-3.2.1/API/• app-api
– SimpleappAPI(tohelpCy2plugindevelopers;notmeantforbundleapps)
• core-task-api– Commonlyusedhigh-leveltasks– e.g.loadingnetworks/styles/tables,applyinglayouts
96
API Tour
• model-api– Network,tablemodel
• event-api– Eventmodel
• work-api– Tasks,TaskFactory
• layout-api– Defininglayouts
97
API Tour
• presenta/on-api– Visualpropertydefini/ons
• viewmodel-api– Sezngvisualproper/es
• vizmap-api– Visualmapping
• swing-u/l– GUIu/li/es;e.g.fileload/savedialog;colorchooserdialog
98
API Tour
• equa/ons-api– DefiningCyTableequa/ons(likeExcelfunc/ons)
• group-api– WorkingwithCyGroups(a.k.ametanodes)
• io-api– Definingimporters/exporters;readingstreams
• (swing-)applica/on-api– Accessingsystem-levelstateandevents(e.g.UIpanels,toolbar,menus,mainJFrame)
99
API Tour
• property-api– Access/definesystemproper/es;Accesssession-levelproper/es
• service-api– AbstractCyAc/vator;service(un)registra/on;servicelistenerregistra/on
• session-api– Accesscurrentsessionfilename;takesnapshotofcurrentsession
100
API Tour
• command-executor-api– Supportforexecu/ngcommandsfromtasks
• group-api– SupportforCyGroups,includingcollapse/expand,alributeaggrega/on,andvisualiza/onop/ons
101
Best Practices
• Bundlesshouldminimizewhattheyexport– Don’tmakesomethingAPIunlesssomeoneasksforitandyou’rereadytocommittoitlongterm
• Bundleac/vatorsshoulddoaslilleworkaspossible– Ideally,justregisterservices– Doexpensiveini/aliza/onaslazilyaspossible
• E.g.duringmenuac/va/on
104
Slides and Solutions
• Slidesavailableat– hlp://www.cgl.ucsf.edu/home/scooter/Cytoscape3DevTut/ISMBslides.pdf
• Mysolu/onsavailableat:– hlp://www.cgl.ucsf.edu/home/scooter/Cytoscape3DevTut/solu/ons.zip
105
Conclusions
• Youarenowreadytowritenon-trivialCytoscapeapps
• ThistutorialispartoftheCytoscapedevelopmentladder:hlp://wiki.cytoscape.org/Cytoscape_3/AppDeveloper/Cytoscape_App_Ladder
• Youarenow½ofthewaythroughtheladder!• ManyAPIsnotcovered
– Opensourcecommunity:stealborrowfromothers• Alwaysacknowledgethesource