protected CyNode getNodeByName(CyNetwork net, String name) { for (CyNode n : net.getNodeList()) { if (name.equals(net.getRow(n).get(NAME, String.class))) return n; } return null; }
protected CyEdge getEdgeByName(CyNetwork net, String name) { for (CyEdge e : net.getEdgeList()) { if (name.equals(net.getRow(e).get(NAME, String.class))) return e; } return null; }
/** * Inform User of Network Stats. * * @param taskMonitor */ private void informUserOfGraphStats(CyNetwork newNetwork, TaskMonitor taskMonitor) { NumberFormat formatter = new DecimalFormat("#,###,###"); StringBuffer sb = new StringBuffer(); // Give the user some confirmation sb.append("Successfully loaded network from: "); sb.append(url); sb.append("\n\nNetwork contains " + formatter.format(newNetwork.getNodeCount())); sb.append(" nodes and " + formatter.format(newNetwork.getEdgeCount())); sb.append(" edges.\n\n"); // TODO: Port this // if (newNetwork.getNodeCount() < Integer.parseInt(CytoscapeInit.getProperties() // // .getProperty("viewThreshold"))) { // sb.append("Network is under " // + CytoscapeInit.getProperties().getProperty("viewThreshold") // + " nodes. A view will be automatically created."); // } else { // sb.append("Network is over " // + CytoscapeInit.getProperties().getProperty("viewThreshold") // + " nodes. A view has not been created." // + " If you wish to view this network, use " // + "\"Create View\" from the \"Edit\" menu."); // } taskMonitor.setStatusMessage(sb.toString()); }
private List<String> getAttributeList( CyNetwork network, Set<Class<?>> allowedNodeAttributeTypes, Set<Class<?>> allowedEdgeAttributeTypes) { List<String> attributes = new ArrayList<String>(); Set<Class<?>> allowedTypes; CyTable table; if (allowedNodeAttributeTypes.size() > 0) { allowedTypes = allowedNodeAttributeTypes; table = network.getDefaultNodeTable(); } else if (allowedEdgeAttributeTypes.size() > 0) { allowedTypes = allowedEdgeAttributeTypes; table = network.getDefaultEdgeTable(); } else { return attributes; } for (final CyColumn column : table.getColumns()) { if (allowedTypes.contains(column.getType())) { attributes.add(column.getName()); } } if (attributes.size() > 0) attributes.add(0, UNWEIGHTED); return attributes; }
/** all lines have the degenerate form "node1" that is, with no interaction type and no target */ @Test public void testReadFileWithNoInteractions() throws Exception { List<CyNetworkView> views = getViews("degenerate.sif"); CyNetwork net = checkSingleNetwork(views, 9, 0); for (CyNode n : net.getNodeList()) assertTrue(net.getRow(n).get("name", String.class).startsWith("Y")); }
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; }
private void initVariables() { edgeAttributes = context.getSelectedEdgeAttributes(); graph = new DirectedSparseMultigraph<>(); idToNode = new HashMap<>(); nodeList = network.getNodeList(); edgeList = network.getEdgeList(); nodeTable = network.getDefaultNodeTable(); edgeTable = network.getDefaultEdgeTable(); }
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(); }
@Test public void testRemoveNodeIndexStaysConstant() { assertEquals(0, net.getNodeCount()); CyNode n0 = net.addNode(); CyNode n1 = net.addNode(); long n0i = n0.getSUID(); long n1i = n1.getSUID(); net.removeNodes(Collections.singletonList(n0)); long nnli = n1.getSUID(); assertEquals(nnli, n1i); }
@Inject public CreateThematicMapDialog( CySwingApplication application, CyApplicationManager applicationManager) { super(application.getJFrame(), true); CyNetwork inputNetwork = applicationManager.getCurrentNetwork(); this.networkName = inputNetwork.getRow(inputNetwork).get(CyNetwork.NAME, String.class); setTitle("Create Thematic Map: " + networkName); this.applicationManager = applicationManager; createContents(); updateEnablement(); }
/** * @param args the function arguments which must be either one object of type Double or Long * @return the result of the function evaluation which is the natural logarithm of the first * argument */ public Object evaluateFunction(final Object[] args) { final Long edgeID = FunctionUtil.getArgAsLong(args[0]); final CyNetwork currentNetwork = applicationManager.getCurrentNetwork(); if (currentNetwork == null) return (Long) (-1L); final CyEdge edge = currentNetwork.getEdge(edgeID); if (edge == null) throw new IllegalArgumentException("\"" + edgeID + "\" is not a valid edge identifier."); return edge.getSource().getSUID(); }
/** Assuming we only create one network. */ protected CyNetwork checkSingleNetwork(List<CyNetworkView> views, int numNodes, int numEdges) { assertNotNull(views); assertEquals(1, views.size()); CyNetwork net = views.get(0).getModel(); assertNotNull(net); assertEquals(numNodes, net.getNodeCount()); assertEquals(numEdges, net.getEdgeCount()); return net; }
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; }
protected final CyNode getNode(final CyNetwork network, final Long nodeId) { final CyNode node = network.getNode(nodeId); if (node == null) { throw new NotFoundException("Could not find node with SUID: " + nodeId); } return node; }
public boolean isReady(CyNetwork network) { if (scope == Scope.ALLNODES && settings.hasNodeCompounds(network.getNodeList())) return true; if (scope == Scope.SELECTEDNODES) return selectedNodesReady(network); return false; }
private void extractNetworks(InputStream is, String entryName) throws Exception { CyNetworkReader reader = networkReaderMgr.getReader(is, entryName); reader.run(taskMonitor); final CyNetwork[] netArray = reader.getNetworks(); for (final CyNetwork net : netArray) { // Add its root-network to the lookup map first final CyRootNetwork rootNet = rootNetworkManager.getRootNetwork(net); if (!networkLookup.containsKey(rootNet.getSUID())) ; networkLookup.put(rootNet.getSUID(), rootNet); networkLookup.put(net.getSUID(), net); networks.add(net); // Note: do NOT add the root-network to this set! } }
/** Add any nodes that are above the neighbor threshold to our cluster */ public NodeCluster doFilter(List<CyNode> nodeList, Map<NodeCluster, List<CyNode>> addedNodeMap) { Set<CyNode> clusterNodes = new HashSet<CyNode>(nodeList); List<CyNode> newNodeList = new ArrayList<CyNode>(); newNodeList.addAll(nodeList); List<CyNode> nodesToAdd = new ArrayList<CyNode>(); for (CyNode node : nodeList) { for (CyNode neighbor : network.getNeighborList(node, CyEdge.Type.ANY)) { if (clusterNodes.contains(neighbor)) continue; double adjacency = getAdjacency(neighbor, clusterNodes); if (adjacency > context.threshold) { // Add this node to our list nodesToAdd.add(neighbor); } } } newNodeList.addAll(nodesToAdd); if (newNodeList.size() > 1) { NodeCluster newNodeCluster = new NodeCluster(newNodeList); if (nodesToAdd.size() > 0) addedNodeMap.put(newNodeCluster, nodesToAdd); return newNodeCluster; } return null; }
@Test public void testGetIndex() { CyNode n1 = net.addNode(); CyNode n2 = net.addNode(); assertTrue("index >= 0", n1.getSUID() >= 0); assertTrue("index >= 0", n2.getSUID() >= 0); }
// self nested networks are allowed @Test public void testSetSelfNestedNetwork() { CyNode n1 = net.addNode(); n1.setNetworkPointer(net); assertNotNull(n1.getNetworkPointer()); assertEquals(net, n1.getNetworkPointer()); }
@Test public void testSetNestedNetwork() { CyNode n1 = net.addNode(); CyNetwork net2 = mock(CyNetwork.class); n1.setNetworkPointer(net2); assertNotNull(n1.getNetworkPointer()); assertEquals(net2, n1.getNetworkPointer()); }
/** * 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)); } }
public boolean initWeights() { weights = new ArrayList<Double>(edges.size()); for (int i = 0; i < edges.size(); i++) { Double weight = net.getRow(edges.get(i)).get(influenceAttr, Double.class); if (weight != null) weights.add(weight); else return false; } return true; }
/** {@inheritDoc} */ @Override public void mapToTable(Graph graph, Edge edge, Evidence evidence, CyTable table) { if (graph == null) throw new NullPointerException("graph cannot be null"); if (edge == null) throw new NullPointerException("edge cannot be null"); if (evidence == null) throw new NullPointerException("evidence cannot be null"); if (table == null) throw new NullPointerException("table cannot be null"); if (graph.cyNetwork == null) throw new IllegalArgumentException("graph's cyNetwork cannot be null"); if (edge.cyEdge == null) throw new IllegalArgumentException("edge's cyEdge cannot be null"); CyNetwork cyN = graph.cyNetwork; CyEdge cyE = edge.cyEdge; CyRow networkRow = cyN.getRow(cyN); String networkName = networkRow.get(CyNetwork.NAME, String.class); CyRow row = table.getRow(SUIDFactory.getNextSUID()); row.set(NETWORK_SUID, cyN.getSUID()); row.set(NETWORK_NAME, networkName); row.set(EDGE_SUID, cyE.getSUID()); row.set(BEL_STATEMENT, evidence.belStatement); row.set(SUMMARY_TEXT, evidence.summaryText); if (evidence.citation != null) { row.set(CITATION_TYPE, evidence.citation.type); row.set(CITATION_ID, evidence.citation.id); row.set(CITATION_NAME, evidence.citation.name); } if (evidence.biologicalContext != null) { // create any annotation columns that do not already exist BiologicalContext bc = evidence.biologicalContext; for (String varyingKey : bc.variedAnnotations.keySet()) { getOrCreateColumn(varyingKey, String.class, false, table); } // set annotation values row.set(SPECIES, bc.speciesCommonName); Map<String, Object> varying = bc.variedAnnotations; for (Entry<String, Object> entry : varying.entrySet()) { row.set(entry.getKey(), getOrEmptyString(entry.getKey(), varying)); } } }
public TaskIterator createTaskIterator(CyNetwork network) { if (scope == Scope.ALLNODES) return new TaskIterator( new SMARTSSearchTask(network, network.getNodeList(), scope, showResult, settings)); else { List<CyNode> selectedNodes = CyTableUtil.getNodesInState(network, CyNetwork.SELECTED, true); return new TaskIterator( new SMARTSSearchTask(network, selectedNodes, scope, showResult, settings)); } }
private String convertToName(final String id) { final Collection<CyRow> rows = ontologyDAG.getDefaultNodeTable().getMatchingRows(CyNetwork.NAME, id); if (!rows.isEmpty()) { final CyRow row = rows.iterator().next(); final String termName = row.get(OBOReader.TERM_NAME, String.class); if (termName != null) return termName; else return id; } else return id; }
private Collection<String> getAttributes(boolean node) { CyNetwork network = applicationManager.getCurrentNetwork(); CyTable table = node ? network.getDefaultNodeTable() : network.getDefaultEdgeTable(); Collection<CyColumn> columns = table.getColumns(); Set<String> attributes = new TreeSet<String>( new Comparator<String>() { public int compare(String s1, String s2) { return s1.compareToIgnoreCase(s2); } }); for (CyColumn column : columns) { if (!CyIdentifiable.SUID.equals(column.getName()) && (node || Number.class.isAssignableFrom(column.getType()))) { attributes.add(column.getName()); } } return attributes; }
protected final String getGraphObject(final CyNetwork network, final CyIdentifiable obj) { final CyRow row = network.getRow(obj); try { return this.serializer.serializeGraphObject(obj, row); } catch (IOException e) { throw getError( "Could not serialize graph object with SUID: " + obj.getSUID(), e, Response.Status.INTERNAL_SERVER_ERROR); } }
/** Will fail if it doesn't find the specified interaction. */ protected void findInteraction( CyNetwork net, String source, String target, String interaction, int count) { for (CyNode n : net.getNodeList()) { String sname = net.getRow(n).get(CyNetwork.NAME, String.class); assertNotNull("Source name is NULL", sname); if (source.equals(sname)) { List<CyNode> neigh = net.getNeighborList(n, CyEdge.Type.ANY); assertEquals("wrong number of neighbors", count, neigh.size()); for (CyNode nn : neigh) { String tname = net.getRow(nn).get(CyNetwork.NAME, String.class); assertNotNull("Target name is NULL", tname); if (tname.equals(target)) { List<CyEdge> con = net.getConnectingEdgeList(n, nn, CyEdge.Type.ANY); assertTrue("Connecting edge list is empty", con.size() > 0); for (CyEdge e : con) { String inter = net.getRow(e).get(CyEdge.INTERACTION, String.class); assertNotNull("Edge interaction is NULL", inter); if (inter.equals(interaction)) { return; } } } } } } fail("couldn't find interaction: " + source + " " + interaction + " " + target); }
/** * Save node attributes computed by NetworkAnalyzer for this network into a tab-delimited file * with extension "nattributes" (1st column corresponds to the node ids, each subsequent column * contains the values of a node attribute). * * @param aNetwork Target network. * @param aDir Flag indicating if the network interpretation is directed. * @param aOutputDir Output directory for writing files as chosen by the user. * @param aExtendedName Name of the analyzed network including the current interpretation. * @return <code>true</code> if any node attributes where present and have been saved, and <code> * false</code> otherwise. */ private boolean saveNodeAttributes( CyNetwork aNetwork, boolean aDir, File aOutputDir, String aExtendedName) { // get node attributes computed in the last analysis run Set<String> netAnayzerAttr = new HashSet<String>(); if (aDir) { netAnayzerAttr = Messages.getDirNodeAttributes(); } else { netAnayzerAttr = Messages.getUndirNodeAttributes(); } if (netAnayzerAttr.size() == 0) { return false; } // save chosen node attributes in a file, 1st column corresponds to the node ids, each // subsequent column // contains the values of a node attribute try { final FileWriter writer = new FileWriter(new File(outputDir, aExtendedName + ".nattributes")); writer.write("Node ID"); for (final String attr : netAnayzerAttr) { writer.write("\t" + attr); } writer.write("\n"); for (CyNode n : aNetwork.getNodeList()) { final String id = aNetwork.getRow(n).get("name", String.class); writer.write(id); for (final String attr : netAnayzerAttr) { final Object attrValue = aNetwork.getRow(n).getRaw(attr); if (attrValue != null) { writer.write("\t" + attrValue.toString()); } } writer.write("\n"); } writer.close(); } catch (IOException ex) { // attributes file could not be written return false; } return true; }
public BellmanFordStatsImpl findPath( CyNetwork network, CyNode source, boolean directed, WeightFunction function) { Map<CyNode, MetaNode> nodeToMetaNodeMap = new IdentityHashMap<CyNode, MetaNode>(); boolean negativeCycle = true; for (CyNode node : network.getNodeList()) { MetaNode metaNode = new MetaNode(node, Double.POSITIVE_INFINITY, null); nodeToMetaNodeMap.put(node, metaNode); } nodeToMetaNodeMap.get(source).setDistance(0.0); for (int i = 0; i < network.getNodeCount() - 1; i++) { for (CyEdge edge : network.getEdgeList()) { MetaNode sourceMetaNode = nodeToMetaNodeMap.get(edge.getSource()); MetaNode targetMetaNode = nodeToMetaNodeMap.get(edge.getTarget()); if (targetMetaNode.getDistance() > sourceMetaNode.getDistance() + function.getWeight(edge)) { targetMetaNode.setDistance(sourceMetaNode.getDistance() + function.getWeight(edge)); targetMetaNode.setPredecessor(sourceMetaNode.getNode()); } } } for (CyEdge edge : network.getEdgeList()) { MetaNode sourceMetaNode = nodeToMetaNodeMap.get(edge.getSource()); MetaNode targetMetaNode = nodeToMetaNodeMap.get(edge.getTarget()); if (targetMetaNode.getDistance() > sourceMetaNode.getDistance() + function.getWeight(edge)) negativeCycle = false; } return new BellmanFordStatsImpl(source, nodeToMetaNodeMap, negativeCycle); }