private void checkView(final CyNetworkView view) { assertEquals(Color.BLACK, view.getVisualProperty(NETWORK_BACKGROUND_PAINT)); assertEquals(new Double(639.0d), view.getVisualProperty(NETWORK_WIDTH)); assertEquals(new Double(624.0d), view.getVisualProperty(NETWORK_HEIGHT)); assertEquals( new Double(3091.2991395970175d), view.getVisualProperty(NETWORK_CENTER_X_LOCATION)); assertEquals(new Double(3610.396738076269d), view.getVisualProperty(NETWORK_CENTER_Y_LOCATION)); assertEquals(new Double(0.05044042295795177d), view.getVisualProperty(NETWORK_SCALE_FACTOR)); // All nodes have the same size, border and shape final View<CyNode> nv = view.getNodeView(view.getModel().getNodeList().iterator().next()); assertEquals(80, nv.getVisualProperty(NODE_WIDTH).intValue()); assertEquals(30, nv.getVisualProperty(NODE_HEIGHT).intValue()); assertEquals(NodeShapeVisualProperty.ROUND_RECTANGLE, nv.getVisualProperty(NODE_SHAPE)); assertEquals(180, nv.getVisualProperty(NODE_TRANSPARENCY).intValue()); assertEquals(2, nv.getVisualProperty(NODE_BORDER_WIDTH).intValue()); assertEquals(LineTypeVisualProperty.SOLID, nv.getVisualProperty(NODE_BORDER_LINE_TYPE)); assertEquals(new Color(153, 153, 255), nv.getVisualProperty(NODE_BORDER_PAINT)); assertEquals(255, nv.getVisualProperty(NODE_BORDER_TRANSPARENCY).intValue()); assertEquals(new Color(255, 255, 255), nv.getVisualProperty(NODE_LABEL_COLOR)); assertEquals(255, nv.getVisualProperty(NODE_LABEL_TRANSPARENCY).intValue()); // All edges have the same width and other properties final View<CyEdge> ev = view.getEdgeView(view.getModel().getEdgeList().iterator().next()); assertEquals(new Double(1.0), ev.getVisualProperty(EDGE_WIDTH)); assertEquals(255, ev.getVisualProperty(EDGE_TRANSPARENCY).intValue()); assertEquals(ArrowShapeVisualProperty.NONE, ev.getVisualProperty(EDGE_SOURCE_ARROW_SHAPE)); assertEquals(ArrowShapeVisualProperty.NONE, ev.getVisualProperty(EDGE_TARGET_ARROW_SHAPE)); }
/** * By passing a list of key-value pairs for each Visual Property, update network view. * * <p>The body should have the following JSON: * * <pre> * [ * { * "visualProperty": "Visual Property Name, like NETWORK_BACKGROUND_PAINT", * "value": "Serialized form of value, like 'red.'" * }, * ... * {} * ] * </pre> * * Note that this API directly set the value to the view objects, and once Visual Style applied, * those values are overridden by the Visual Style. * * @summary Update single network view value, such as background color or zoom level. * @param networkId Network SUID * @param viewId Network view SUID */ @PUT @Path("/{viewId}/network") @Consumes(MediaType.APPLICATION_JSON) public Response updateNetworkView( @PathParam("networkId") Long networkId, @PathParam("viewId") Long viewId, final InputStream is) { final CyNetworkView networkView = getView(networkId, viewId); final ObjectMapper objMapper = new ObjectMapper(); try { // This should be an JSON array. final JsonNode rootNode = objMapper.readValue(is, JsonNode.class); styleMapper.updateView(networkView, rootNode, getLexicon()); } catch (Exception e) { throw getError( "Could not parse the input JSON for updating view because: " + e.getMessage(), e, Response.Status.INTERNAL_SERVER_ERROR); } // Repaint networkView.updateView(); return Response.ok().build(); }
/** * To use this API, you need to know SUID of the CyNetworkView, in addition to CyNetwork SUID. * * @summary Get a network view (as JSON or a file) * @param networkId Network SUID * @param viewId Network View SUID * @param file (Optional) If you want to get the view as a file, you can specify output file name * with extension. For example, file=test.sif creates new SIF file in the current directory. * @return View in Cytoscape.js JSON. Currently, view information is (x, y) location only. If you * specify <strong>file</strong> option, this returns absolute path to the file. */ @GET @Path("/{viewId}") @Produces(MediaType.APPLICATION_JSON) public Response getNetworkView( @PathParam("networkId") Long networkId, @PathParam("viewId") Long viewId, @QueryParam("file") String file) { final Collection<CyNetworkView> views = this.getCyNetworkViews(networkId); CyNetworkView targetView = null; for (final CyNetworkView view : views) { final Long vid = view.getSUID(); if (vid.equals(viewId)) { targetView = view; break; } } if (targetView == null) { return Response.ok("{}").build(); } else { if (file != null) { return Response.ok(writeNetworkFile(file, targetView)).build(); } else { return Response.ok(getNetworkViewString(targetView)).build(); } } }
@GET @Path("/{viewId}/{objectType}/{objectId}/{visualProperty}") @Produces(MediaType.APPLICATION_JSON) public String getSingleVisualPropertyValue( @PathParam("networkId") Long networkId, @PathParam("viewId") Long viewId, @PathParam("objectType") String objectType, @PathParam("objectId") Long objectId, @PathParam("visualProperty") String visualProperty) { final CyNetworkView networkView = getView(networkId, viewId); Collection<VisualProperty<?>> vps = null; View<? extends CyIdentifiable> view = null; if (nodeLexicon == null) { initLexicon(); } if (objectType.equals("nodes")) { view = networkView.getNodeView(networkView.getModel().getNode(objectId)); vps = nodeLexicon; } else if (objectType.equals("edges")) { view = networkView.getNodeView(networkView.getModel().getNode(objectId)); vps = edgeLexicon; } if (view == null) { throw getError( "Could not find view.", new IllegalArgumentException(), Response.Status.NOT_FOUND); } return getSingleVp(visualProperty, view, vps); }
private final String getViewForVPList( final Long networkId, final Long viewId, final String objectType, Collection<VisualProperty<?>> vps) { final CyNetworkView networkView = getView(networkId, viewId); Collection<? extends View<? extends CyIdentifiable>> graphObjects = null; if (objectType.equals("nodes")) { graphObjects = networkView.getNodeViews(); } else if (objectType.equals("edges")) { graphObjects = networkView.getEdgeViews(); } else if (objectType.equals("network")) { try { return styleSerializer.serializeView(networkView, vps); } catch (IOException e) { throw getError( "Could not serialize the view object.", e, Response.Status.INTERNAL_SERVER_ERROR); } } if (graphObjects == null || graphObjects.isEmpty()) { throw getError( "Could not find views.", new IllegalArgumentException(), Response.Status.NOT_FOUND); } try { return styleSerializer.serializeViews(graphObjects, vps); } catch (IOException e) { throw getError( "Could not serialize the view object.", e, Response.Status.INTERNAL_SERVER_ERROR); } }
public TaskIterator createTaskIterator(View<CyNode> nView, CyNetworkView netView) { List<CyNode> selectedNodes = CyTableUtil.getNodesInState(netView.getModel(), CyNetwork.SELECTED, true); if (selectedNodes == null || selectedNodes.size() == 0) selectedNodes = Collections.singletonList(nView.getModel()); return new TaskIterator( new SMARTSSearchTask(netView.getModel(), selectedNodes, scope, showResult, settings)); }
private final CyNetworkView getView(Long networkId, Long viewId) { final Collection<CyNetworkView> views = this.getCyNetworkViews(networkId); for (final CyNetworkView view : views) { final Long vid = view.getSUID(); if (vid.equals(viewId)) { return view; } } throw new NotFoundException("Could not find view: " + viewId); }
private void display() { CyServiceRegistrarImpl register = new CyServiceRegistrarImpl(bc); CyNetworkViewManager viewManager = register.getService(CyNetworkViewManager.class); CyNetworkViewFactory viewFactory = register.getService(CyNetworkViewFactory.class); CyNetworkView networkView = viewFactory.createNetworkView(network); viewManager.addNetworkView(networkView); VisualMappingFunctionFactory passthroughFactory = register.getService(VisualMappingFunctionFactory.class, "(mapping.type=passthrough)"); VisualMappingFunctionFactory continuousFactory = register.getService(VisualMappingFunctionFactory.class, "(mapping.type=continuous)"); VisualMappingManager vmManager = register.getService(VisualMappingManager.class); VisualStyleFactory vsFactory = register.getService(VisualStyleFactory.class); VisualStyle vs = vsFactory.createVisualStyle( network.getDefaultNetworkTable().getRow(network.getSUID()).get("name", String.class)); PassthroughMapping pMapping = (PassthroughMapping) passthroughFactory.createVisualMappingFunction( "name", String.class, BasicVisualLexicon.NODE_LABEL); vs.addVisualMappingFunction(pMapping); vs.apply(networkView); ContinuousMapping mapping = (ContinuousMapping) continuousFactory.createVisualMappingFunction( "score", Double.class, BasicVisualLexicon.NODE_FILL_COLOR); Double val1 = getMinimum(network.getDefaultNodeTable().getColumn("score")); BoundaryRangeValues<Paint> brv1 = new BoundaryRangeValues<Paint>(Color.GREEN, Color.GREEN, Color.GREEN); Double val3 = getMaximum(network.getDefaultNodeTable().getColumn("score")); BoundaryRangeValues<Paint> brv3 = new BoundaryRangeValues<Paint>(Color.RED, Color.RED, Color.RED); Double val2 = (val1 + val3 + val1 + val1) / 4; BoundaryRangeValues<Paint> brv2 = new BoundaryRangeValues<Paint>(Color.YELLOW, Color.YELLOW, Color.YELLOW); mapping.addPoint(val1, brv1); mapping.addPoint(val2, brv2); mapping.addPoint(val3, brv3); vs.addVisualMappingFunction(mapping); vs.apply(networkView); vmManager.addVisualStyle(vs); vmManager.setVisualStyle(vs, networkView); networkView.updateView(); }
private Response getImageForView(String fileType, Long networkId, Long viewId, Integer height) { final Collection<CyNetworkView> views = this.getCyNetworkViews(networkId); for (final CyNetworkView view : views) { final Long vid = view.getSUID(); if (vid.equals(viewId)) { return getImage(fileType, networkId, height); } } throw new NotFoundException("Could not find view for the network: " + networkId); }
/** * @summary Create view for the network * @param networkId Network SUID * @return SUID for the new Network View. */ @POST @Path("/") @Produces(MediaType.APPLICATION_JSON) public Response createNetworkView(@PathParam("networkId") Long networkId) { final CyNetwork network = getCyNetwork(networkId); final CyNetworkView view = networkViewFactory.createNetworkView(network); networkViewManager.addNetworkView(view); return Response.status(Response.Status.CREATED) .entity(getNumberObjectString("networkViewSUID", view.getSUID())) .build(); }
/** * This returns the first view of the network. As of Cytoscape 3.2.x, this is the only view * accessible Cytoscape GUI. * * @summary Convenience method to get the first view model. * @param networkId Network SUID * @param file (Optional) If you want to get the view as a file, you can specify output file name * with extension. For example, file=test.sif creates new SIF file in the current directory. * @return Network view in JSON or location of the file */ @GET @Path("/first") @Produces(MediaType.APPLICATION_JSON) public Response getFirstNetworkView( @PathParam("networkId") Long networkId, @QueryParam("file") String file) { final Collection<CyNetworkView> views = this.getCyNetworkViews(networkId); if (views.isEmpty()) { throw new NotFoundException("Could not find view for the network: " + networkId); } final CyNetworkView view = views.iterator().next(); return getNetworkView(networkId, view.getSUID(), file); }
/** * @summary Get SUID of all network views * @param networkId Network SUID * @return Array of all network view SUIDs */ @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) public Collection<Long> getAllNetworkViews(@PathParam("networkId") Long networkId) { final Collection<CyNetworkView> views = this.getCyNetworkViews(networkId); final Collection<Long> suids = new HashSet<Long>(); for (final CyNetworkView view : views) { final Long viewId = view.getSUID(); suids.add(viewId); } return suids; }
private Set<View<CyNode>> getLayoutNodes(CyLayoutAlgorithm layout, CyNetworkView networkView) { if (layout.getSupportsSelectedOnly() && selectedTunable.selectedNodesOnly) { Set<View<CyNode>> nodeViews = new HashSet<View<CyNode>>(); CyNetwork network = networkView.getModel(); for (View<CyNode> view : networkView.getNodeViews()) { if (network.getRow(view.getModel()).get(CyNetwork.SELECTED, Boolean.class) && view.getVisualProperty(BasicVisualLexicon.NODE_VISIBLE)) { nodeViews.add(view); } } return nodeViews; } return CyLayoutAlgorithm.ALL_NODE_VIEWS; }
void setNetworkView(final CyNetworkView view) { getApplyBtn().setEnabled(view != null); if (layoutAttrPnl == null) return; layoutAttrPnl.removeAll(); layoutAttrTunable = new LayoutAttributeTunable(); if (view != null) { List<String> attributeList = getAttributeList( view.getModel(), currentLayout.getSupportedNodeAttributeTypes(), currentLayout.getSupportedEdgeAttributeTypes()); if (attributeList.size() > 0) { layoutAttrTunable.layoutAttribute = new ListSingleSelection<String>(attributeList); layoutAttrTunable.layoutAttribute.setSelectedValue(attributeList.get(0)); final PanelTaskManager taskMgr = serviceRegistrar.getService(PanelTaskManager.class); JPanel panel = taskMgr.getConfiguration(null, layoutAttrTunable); setPanelsTransparent(panel); layoutAttrPnl.add(panel); panel.invalidate(); } } }
private boolean hasSelectedNodes(final CyNetworkView view) { if (view == null) return false; final CyNetwork network = view.getModel(); final CyTable table = network.getDefaultNodeTable(); return table.countMatchingRows(CyNetwork.SELECTED, Boolean.TRUE) > 0; }
public void undo() { final Collection<CyNetworkView> views = networkViewManager.getNetworkViews(network); CyNetworkView view = null; if (views.size() != 0) view = views.iterator().next(); networkCenterX = view.getVisualProperty(NETWORK_CENTER_X_LOCATION); networkCenterY = view.getVisualProperty(NETWORK_CENTER_Y_LOCATION); networkCenterZ = view.getVisualProperty(NETWORK_CENTER_Z_LOCATION); networkScaleFactor = view.getVisualProperty(NETWORK_SCALE_FACTOR); final Collection<View<CyNode>> nodeViews = view.getNodeViews(); nodesAndLocations = new WeakHashMap<CyNode, NodeLocations>(nodeViews.size()); for (final View<CyNode> nodeView : nodeViews) nodesAndLocations.put(nodeView.getModel(), new NodeLocations(nodeView)); networkViewManager.destroyNetworkView(view); }
/** 'typical' means that all lines have the form "node1 pd node2 [node3 node4 ...] */ @Test public void testReadFromTypicalFile() throws Exception { List<CyNetworkView> views = getViews("sample.sif"); for (CyNetworkView view : views) { for (CyNode n : view.getModel().getNodeList()) { System.out.println( "sample.sif: NODE " + view.getModel().getRow(n).get("name", String.class)); } for (CyEdge e : view.getModel().getEdgeList()) { System.out.println( "sample.sif: EDGE " + view.getModel().getRow(e).get("name", String.class)); } } CyNetwork net = checkSingleNetwork(views, 31, 27); findInteraction(net, "YNL312W", "YPL111W", "pd", 1); }
private void checkNetwork(final CyNetwork network) { checkNodeEdgeCount(network, 331, 362, 0, 0); // Non-default columns should not be immutable assertCy2CustomColumnsAreMutable(network); // View test Collection<CyNetworkView> views = viewManager.getNetworkViews(network); assertEquals(1, views.size()); final CyNetworkView view = views.iterator().next(); assertEquals(331, view.getNodeViews().size()); assertEquals(362, view.getEdgeViews().size()); // Check updated view final VisualStyle style = vmm.getVisualStyle(view); style.apply(view); checkView(view); }
@Override public void run(final TaskMonitor taskMonitor) { if (network == null) network = appMgr.getCurrentNetwork(); Collection<CyNetworkView> views = viewMgr.getNetworkViews(network); nodes = nodeList.getValue(); for (CyNetworkView view : views) { Set<View<CyNode>> nodeViews = new HashSet<View<CyNode>>(); if (nodes == null || nodes.size() == 0) { nodeViews = CyLayoutAlgorithm.ALL_NODE_VIEWS; } else { for (CyNode node : nodes) nodeViews.add(view.getNodeView(node)); } insertTasksAfterCurrentTask( algorithm.createTaskIterator(view, layoutContext, nodeViews, getLayoutAttribute())); } }
@Override public boolean isReady(CyNetworkView networkView) { if (!super.isReady(networkView)) return false; // Make sure we've got something selected List<CyNode> selNodes = CyTableUtil.getNodesInState(networkView.getModel(), CyNetwork.SELECTED, true); if (selNodes != null && selNodes.size() > 0) return true; return false; }
/** * @summary Get view object for the specified type (node or edge) * @param networkId Network SUID * @param viewId Network view SUID * @param objectType nodes or edges * @param objectId Object's SUID */ @GET @Path("/{viewId}/{objectType}/{objectId}") @Produces(MediaType.APPLICATION_JSON) public String getView( @PathParam("networkId") Long networkId, @PathParam("viewId") Long viewId, @PathParam("objectType") String objectType, @PathParam("objectId") Long objectId) { final CyNetworkView networkView = getView(networkId, viewId); View<? extends CyIdentifiable> view = null; Collection<VisualProperty<?>> lexicon = null; if (nodeLexicon == null) { initLexicon(); } if (objectType.equals("nodes")) { view = networkView.getNodeView(networkView.getModel().getNode(objectId)); lexicon = nodeLexicon; } else if (objectType.equals("edges")) { view = networkView.getNodeView(networkView.getModel().getNode(objectId)); lexicon = edgeLexicon; } if (view == null) { throw getError( "Could not find view.", new IllegalArgumentException(), Response.Status.NOT_FOUND); } try { return styleSerializer.serializeView(view, lexicon); } catch (IOException e) { throw getError( "Could not serialize the view object.", e, Response.Status.INTERNAL_SERVER_ERROR); } }
/** * By passing list of key-value pair for each Visual Property, update node view. * * <p>The body should have the following JSON: * * <pre> * [ * { * "SUID": SUID of node, * "view": [ * { * "visualProperty": "Visual Property Name, like NODE_FILL_COLOR", * "value": "Serialized form of value, like 'red.'" * }, * ... * {} * ] * }, * ... * {} * ] * </pre> * * Note that this API directly set the value to the view objects, and once Visual Style applied, * those values are overridden by the Visual Style. * * @summary Update node/edge view objects at once * @param networkId Network SUID * @param viewId Network view SUID * @param objectType Type of objects ("nodes" or "edges") */ @PUT @Path("/{viewId}/{objectType}") @Consumes(MediaType.APPLICATION_JSON) public Response updateViews( @PathParam("networkId") Long networkId, @PathParam("viewId") Long viewId, @PathParam("objectType") String objectType, final InputStream is) { final CyNetworkView networkView = getView(networkId, viewId); final ObjectMapper objMapper = new ObjectMapper(); try { // This should be an JSON array. final JsonNode rootNode = objMapper.readValue(is, JsonNode.class); for (JsonNode entry : rootNode) { final Long objectId = entry.get(CyIdentifiable.SUID).asLong(); final JsonNode viewNode = entry.get("view"); if (objectId == null || viewNode == null) { continue; } View<? extends CyIdentifiable> view = null; if (objectType.equals("nodes")) { view = networkView.getNodeView(networkView.getModel().getNode(objectId)); } else if (objectType.equals("edges")) { view = networkView.getEdgeView(networkView.getModel().getEdge(objectId)); } else if (objectType.equals("network")) { view = networkView; } else { throw getError( "Method not supported.", new IllegalStateException(), Response.Status.INTERNAL_SERVER_ERROR); } if (view == null) { throw getError( "Could not find view.", new IllegalArgumentException(), Response.Status.NOT_FOUND); } styleMapper.updateView(view, viewNode, getLexicon()); } // Repaint networkView.updateView(); } catch (Exception e) { throw getError( "Could not parse the input JSON for updating view because: " + e.getMessage(), e, Response.Status.INTERNAL_SERVER_ERROR); } return Response.ok().build(); }
/** * Sets the given AnnotationSet as the "selected" one. If null is passed then all AnnotationSets * will be unselected. * * <p>Note: Currently switching selection is not supported when the currently selected * AnnotationSet has collapsed clusters. It is the responsibility of the UI to expand all the * clusters before switching the AnnotationSet. * * <p>MKTODO: It would be better for the model to handle expanding the clusters, but for now we * will force the UI to do it. * * @throws IllegalStateException If the currently active AnnotationSet has collapsed clusters. */ public void select(AnnotationSet annotationSet) { if (annotationSet == null || annotationSets.contains(annotationSet)) { if (Optional.ofNullable(annotationSet).equals(activeSet)) { return; } if (activeSet.map(AnnotationSet::hasCollapsedCluster).orElse(false)) { throw new IllegalStateException("Current AnnotationSet has collapsed clusters"); } CyNetwork network = networkView.getModel(); activeSet = Optional.ofNullable(annotationSet); // ModelManager.handle(AboutToRemoveNodesEvent) only removes nodes from the active annotation // set. // When switching to a new annotation set we need to "fix" the clusters to remove any nodes // that // were deleted previously. // MKTODO: probably need to test for deleted nodes when serializing the model if (annotationSet != null) { Set<Cluster> clusters = annotationSet.getClusters(); for (Cluster cluster : new HashSet<>( clusters)) { // avoid ConcurrentModificationException because removeNodes() can call // delete() Set<CyNode> nodesToRemove = cluster .getNodes() .stream() .filter(node -> !network.containsNode(node)) .collect(Collectors.toSet()); // Fires ClusterChangedEvent, UI listeners should test if the cluster is part of the // active annotation set. if (!nodesToRemove.isEmpty()) { cluster.removeNodes(nodesToRemove); } } } parent.postEvent(new ModelEvents.AnnotationSetSelected(this, activeSet)); } }
private final void clearAll( final CyNetworkView netView, final View<? extends CyIdentifiable> nodeView) { boolean needToUpdateView = false; final VisualStyle style = vmm.getCurrentVisualStyle(); for (VisualProperty<?> vp : vpSet) { final boolean lock = nodeView.isDirectlyLocked(vp); if (lock) { nodeView.clearValueLock(vp); needToUpdateView = true; } } if (needToUpdateView) { style.apply(netView); netView.updateView(); } }
/** * Apply bypass * * @param netView * @param graphObjectView * @param vp */ private final void applBypassValue( final CyNetworkView netView, final View<? extends CyIdentifiable> graphObjectView, VisualProperty<?> vp) { final ValueEditor<Object> editor = (ValueEditor<Object>) editorManager.getValueEditor(vp.getRange().getType()); final Object bypassValue = editor.showEditor(null, graphObjectView.getVisualProperty(vp)); // Set lock for the vp graphObjectView.setLockedValue(vp, bypassValue); // Apply the new value only for the given view // TODO don't do this, because it overwrites some bypassed values with default ones!!! Calling // setLockedValue should be enough // final CyRow row = netView.getModel().getRow(graphObjectView.getModel()); // vmm.getCurrentVisualStyle().apply(row, graphObjectView); // Redraw the view netView.updateView(); }
public void redo() { ; final CyNetworkView view = viewFactory.createNetworkView(network); networkViewManager.addNetworkView(view); for (final View<CyNode> nodeView : view.getNodeViews()) nodesAndLocations.get(nodeView.getModel()).restoreLocations(nodeView); view.setVisualProperty(NETWORK_CENTER_X_LOCATION, networkCenterX); view.setVisualProperty(NETWORK_CENTER_Y_LOCATION, networkCenterY); view.setVisualProperty(NETWORK_CENTER_Z_LOCATION, networkCenterZ); view.setVisualProperty(NETWORK_SCALE_FACTOR, networkScaleFactor); eventHelper.flushPayloadEvents(); view.updateView(); }
public CyNetwork getNetwork() { return networkView.getModel(); }
@Override public List<BarLayer> getLayers( CyNetworkView networkView, View<? extends CyIdentifiable> nodeView) { CyNetwork network = networkView.getModel(); if (!(nodeView.getModel() instanceof CyNode)) return null; layers = new ArrayList<>(); CyNode node = (CyNode) nodeView.getModel(); // Create all of our pie slices. Each slice becomes a layer if (attributes != null && attributes.size() > 0) { // System.out.println("Getting data from attributes for node "+node); values = getDataFromAttributes(network, node, attributes, labels); // System.out.println("Data from attributes returns "+values.size()+" values"); colorList = convertInputToColor(colorString, values); } // Protect against missing values in the input stream // if (values == null || colorList == null) return layers; if (labels != null && labels.size() > 0 && (labels.size() != values.size() || labels.size() != colorList.size())) { logger.error( "barchart: number of labels (" + labels.size() + "), values (" + values.size() + "), and colors (" + colorList.size() + ") don't match"); return null; } List<BarLayer> labelList = new ArrayList<BarLayer>(); double minValue = 0.000001; double maxValue = -minValue; for (Double val : values) { if (val == null) continue; minValue = Math.min(minValue, val); maxValue = Math.max(maxValue, val); } double labelMin = minValue; if (normalized) { minValue = rangeMin; maxValue = rangeMax; } int nBars = values.size(); Font font = getFont(); for (int bar = 0; bar < nBars; bar++) { String label = null; if (labels != null && labels.size() > 0) label = labels.get(bar); if (values.get(bar) == null || values.get(bar) == 0.0) continue; // System.out.println("Creating bar #"+bar); // Create the slice BarLayer bl = new BarLayer( bar, nBars, separation, values.get(bar), minValue, maxValue, normalized, ybase, colorList.get(bar), showAxes, borderWidth, scale); if (bl == null) continue; layers.add(bl); // System.out.println("BarLayer: "+bar+" bounds: "+bl.getShape().getBounds2D()); if (label != null) { // System.out.println("Creating label for bar #"+bar); // Now, create the label BarLayer labelLayer = new BarLayer( bar, nBars, separation, minValue, maxValue, normalized, labelMin, ybase, label, font, labelColor, showAxes, scale); if (labelLayer != null) labelList.add(labelLayer); } } // System.out.println("Created "+layers.size()+" bar layers"); // Now add all of our labels so they will be on top of our slices if (labelList != null && labelList.size() > 0) layers.addAll(labelList); // System.out.println("Created "+layers.size()+" total layers"); shapeLayers = layers; return layers; }
@Override public void run(TaskMonitor taskMonitor) throws Exception { desktopApp.getJFrame().getGlassPane().setVisible(true); taskMonitor.setTitle("Gene Set / Mutation Analysis"); taskMonitor.setStatusMessage("Loading file..."); taskMonitor.setProgress(.25d); try { Map<String, Integer> geneToSampleNumber = null; Map<String, String> geneToSampleString = null; Map<String, Set<String>> sampleToGenes = null; Set<String> selectedGenes = null; if (format.equals("MAF")) { sampleToGenes = new MATFileLoader().loadSampleToGenes(file.getAbsolutePath(), chooseHomoGenes); selectedGenes = CancerAnalysisUtilitites.selectGenesInSamples(sampleCutoffValue, sampleToGenes); } else if (format.equals("GeneSample")) { geneToSampleNumber = new HashMap<String, Integer>(); geneToSampleString = new HashMap<String, String>(); loadGeneSampleFile(file, geneToSampleNumber, geneToSampleString); selectedGenes = selectGenesBasedOnSampleCutoff(geneToSampleNumber, sampleCutoffValue); } else if (format.equals("GeneSet")) { selectedGenes = loadGeneSetFile(file); } // Check if it is possible to construct the network // given the sample size. if (useLinkers) { taskMonitor.setStatusMessage("Checking FI Network size..."); FINetworkService fiService = PlugInScopeObjectManager.getManager().getNetworkService(); Integer cutoff = fiService.getNetworkBuildSizeCutoff(); if (cutoff != null && selectedGenes.size() >= cutoff) { JOptionPane.showMessageDialog( desktopApp.getJFrame(), "The size of the gene set is too big. Linker genes should not be used!\n" + "Please try again without using linker genes.", "Error in Building Network", JOptionPane.ERROR_MESSAGE); desktopApp.getJFrame().getGlassPane().setVisible(false); return; } } CytoPanel controlPane = desktopApp.getCytoPanel(CytoPanelName.WEST); int selectedIndex = controlPane.getSelectedIndex(); taskMonitor.setStatusMessage("Constructing FI Network..."); taskMonitor.setProgress(.50d); CyNetwork network = constructFINetwork(selectedGenes, file.getName()); network.getDefaultNetworkTable().getRow(network.getSUID()).set("name", file.getName()); if (network == null) { JOptionPane.showMessageDialog( desktopApp.getJFrame(), "Cannot find any functional interaction among provided genes.\n" + "No network can be constructed.\n" + "Note: only human gene names are supported.", "Empty Network", JOptionPane.INFORMATION_MESSAGE); desktopApp.getJFrame().getGlassPane().setVisible(false); return; } netManager.addNetwork(network); // Fix for missing default value persistence in CyTables // Should be remedied in the 3.1 api CyTable nodeTable = network.getDefaultNodeTable(); for (Object name : network.getNodeList()) { CyNode node = (CyNode) name; Long nodeSUID = node.getSUID(); nodeTable.getRow(nodeSUID).set("isLinker", false); } controlPane.setSelectedIndex(selectedIndex); if (sampleToGenes != null) { geneToSampleNumber = new HashMap<String, Integer>(); geneToSampleString = new HashMap<String, String>(); Map<String, Set<String>> geneToSamples = InteractionUtilities.switchKeyValues(sampleToGenes); geneToSamples.keySet().retainAll(selectedGenes); for (String gene : geneToSamples.keySet()) { Set<String> samples = geneToSamples.get(gene); geneToSampleNumber.put(gene, samples.size()); geneToSampleString.put(gene, InteractionUtilities.joinStringElements(";", samples)); } } taskMonitor.setStatusMessage("Formatting network attributes..."); taskMonitor.setProgress(.65d); CyTableManager tableManager = new CyTableManager(); CyNetworkView view = viewFactory.createNetworkView(network); tableManager.storeFINetworkVersion(view); tableManager.storeDataSetType(network, CyTableFormatter.getSampleMutationData()); viewManager.addNetworkView(view); if (geneToSampleNumber != null && !geneToSampleNumber.isEmpty()) { tableManager.loadNodeAttributesByName(view, "sampleNumber", geneToSampleNumber); } if (geneToSampleString != null && !geneToSampleString.isEmpty()) { tableManager.loadNodeAttributesByName(view, "samples", geneToSampleString); } // Check if linker genes are to be used. if (useLinkers) { taskMonitor.setStatusMessage("Fetching linker genes..."); Map<String, Boolean> geneToIsLinker = new HashMap<String, Boolean>(); for (Object name : network.getNodeList()) { CyNode node = (CyNode) name; Long suid = node.getSUID(); String nodeName = network.getDefaultNodeTable().getRow(suid).get("name", String.class); geneToIsLinker.put(nodeName, !selectedGenes.contains(nodeName)); } tableManager.loadNodeAttributesByName(view, "isLinker", geneToIsLinker); } if (fetchFIAnnotations) { taskMonitor.setStatusMessage("Fetching FI annotations..."); new FIAnnotationHelper().annotateFIs(view, new RESTFulFIService(), tableManager); } if (view.getModel().getEdgeCount() != 0) { for (CyEdge edge : view.getModel().getEdgeList()) { tableManager.storeEdgeName(edge, view); } } BundleContext context = PlugInScopeObjectManager.getManager().getBundleContext(); ServiceReference visHelperRef = context.getServiceReference(FIVisualStyle.class.getName()); if (visHelperRef != null) { FIVisualStyleImpl styleHelper = (FIVisualStyleImpl) context.getService(visHelperRef); styleHelper.setVisualStyle(view); styleHelper.setLayout(); } // BundleContext context = // PlugInScopeObjectManager.getManager().getBundleContext(); // ServiceReference styleHelperRef = // context.getServiceReference(FIVisualStyleImpl.class.getName()); // FIVisualStyleImpl styleHelper = (FIVisualStyleImpl) // context.getService(styleHelperRef); taskMonitor.setProgress(1.0d); } catch (Exception e) { JOptionPane.showMessageDialog( desktopApp.getJFrame(), "Error in Loading File: " + e.getMessage(), "Error in Loading", JOptionPane.ERROR_MESSAGE); desktopApp.getJFrame().getGlassPane().setVisible(false); } desktopApp.getJFrame().getGlassPane().setVisible(false); }
@Override public void serialize(CyNetworkView networkView, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.useDefaultPrettyPrinter(); jgen.writeStartObject(); jgen.writeStringField( CytoscapeJsNetworkModule.FORMAT_VERSION_TAG, CytoscapeJsNetworkModule.FORMAT_VERSION); jgen.writeStringField(CytoscapeJsNetworkModule.GENERATED_BY_TAG, "cytoscape-" + version); jgen.writeStringField( CytoscapeJsNetworkModule.TARGET_CYJS_VERSION_TAG, CytoscapeJsNetworkModule.CYTOSCAPEJS_VERSION); final CyNetwork network = networkView.getModel(); // Serialize network data table jgen.writeObjectFieldStart(DATA.getTag()); jgen.writeObject(network.getRow(network)); jgen.writeEndObject(); jgen.writeObjectFieldStart(ELEMENTS.getTag()); // Write array final List<CyNode> nodes = network.getNodeList(); final List<CyEdge> edges = network.getEdgeList(); jgen.writeArrayFieldStart(NODES.getTag()); for (final CyNode node : nodes) { jgen.writeStartObject(); // Data field jgen.writeObjectFieldStart(DATA.getTag()); jgen.writeStringField(ID.getTag(), node.getSUID().toString()); // Write CyRow in "data" field jgen.writeObject(network.getRow(node)); jgen.writeEndObject(); // Position and other visual props jgen.writeObject(networkView.getNodeView(node)); // Special case for cytoscape.js format: // - Selected jgen.writeBooleanField( CyNetwork.SELECTED, network.getRow(node).get(CyNetwork.SELECTED, Boolean.class)); jgen.writeEndObject(); } jgen.writeEndArray(); jgen.writeArrayFieldStart(EDGES.getTag()); for (final CyEdge edge : edges) { jgen.writeStartObject(); jgen.writeObjectFieldStart(DATA.getTag()); jgen.writeStringField(ID.getTag(), edge.getSUID().toString()); jgen.writeStringField(SOURCE.getTag(), edge.getSource().getSUID().toString()); jgen.writeStringField(TARGET.getTag(), edge.getTarget().getSUID().toString()); // Write CyRow in "data" field jgen.writeObject(network.getRow(edge)); jgen.writeEndObject(); // Special case for cytoscape.js format: // - Selected jgen.writeBooleanField( CyNetwork.SELECTED, network.getRow(edge).get(CyNetwork.SELECTED, Boolean.class)); jgen.writeEndObject(); } jgen.writeEndArray(); jgen.writeEndObject(); }