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;
  }
  /** 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);
  }
Пример #3
0
  public boolean isReady(CyNetwork network) {
    if (scope == Scope.ALLNODES && settings.hasNodeCompounds(network.getNodeList())) return true;

    if (scope == Scope.SELECTEDNODES) return selectedNodesReady(network);

    return false;
  }
  /** 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"));
  }
Пример #5
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();
  }
Пример #6
0
 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));
   }
 }
 /**
  * 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);
  }
  @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();
  }
Пример #11
0
 void cyLoad(CyNetwork gp) {
   net = gp;
   nodes = new ArrayList<CyNode>(net.getNodeList());
   edges = new ArrayList<CyEdge>(net.getEdgeList());
 }