Search in sources :

Example 86 with CySubNetwork

use of org.cytoscape.model.subnetwork.CySubNetwork in project clusterMaker2 by RBVI.

the class NewNetworkView method createClusteredNetwork.

@SuppressWarnings("unchecked")
private void createClusteredNetwork(String clusterAttribute, TaskMonitor monitor) {
    boolean isFuzzy = isFuzzy(clusterAttribute);
    // System.out.println("isFuzzy = "+isFuzzy);
    // Get the clustering parameters
    Map<String, String> params = getParams();
    List<CyNode> nodeList = new ArrayList<CyNode>();
    Map<Integer, List<CyNode>> clusterMap = getClusterMap(clusterAttribute, nodeList);
    // Special handling for edge weight thresholds
    EdgeWeightConverter converter = edgeConverterList.getConverter(getParam(params, "converter"));
    String dataAttribute = getParam(params, "dataAttribute");
    double cutOff = 0.0;
    if (getParam(params, "edgeCutOff") != null)
        cutOff = Double.parseDouble(getParam(params, "edgeCutOff"));
    HashMap<CyEdge, CyEdge> edgeMap = new HashMap<CyEdge, CyEdge>();
    List<CyEdge> edgeList = new ArrayList<CyEdge>();
    // System.out.println("Getting the edges");
    for (Integer cluster : clusterMap.keySet()) {
        // Get the list of nodes
        List<CyNode> clusterNodes = clusterMap.get(cluster);
        // Get the list of edges
        List<CyEdge> connectingEdges = ModelUtils.getConnectingEdges(network, clusterNodes);
        for (CyEdge edge : connectingEdges) {
            if (converter != null && dataAttribute != null) {
                if (edgeWeightCheck(edge, dataAttribute, converter, cutOff))
                    continue;
            }
            edgeMap.put(edge, edge);
            // Add the cluster attribute to the edge so we can style it later
            ModelUtils.createAndSetLocal(network, edge, clusterAttribute, new Integer(1), Integer.class, null);
            edgeList.add(edge);
        }
    }
    // System.out.println("Getting the style");
    VisualStyle style = ViewUtils.getCurrentVisualStyle(manager);
    // System.out.println("Creating the network");
    CyNetwork newNetwork = ModelUtils.createChildNetwork(manager, network, nodeList, edgeList, "--clustered");
    // Now, copy the cluster attribute from the original network to this one
    ModelUtils.copyLocalColumn(network, newNetwork, CyNode.class, clusterAttribute);
    // Copy the clustering information over
    ModelUtils.copyLocalColumn(network, newNetwork, CyNetwork.class, "__clusterType");
    ModelUtils.copyLocalColumn(network, newNetwork, CyNetwork.class, "__clusterAttribute");
    ModelUtils.copyLocalColumn(network, newNetwork, CyNetwork.class, "__clusterParams");
    // Finally, if we're fuzzy, see if we had an initial seed and copy that over
    if (isFuzzy && ModelUtils.hasAttribute(network, network, "__fuzzifierSeed")) {
        ModelUtils.copyLocalColumn(network, newNetwork, CyNetwork.class, "__fuzzifierSeed");
        String seedAttribute = network.getRow(network, CyNetwork.LOCAL_ATTRS).get("__fuzzifierSeed", String.class);
        ModelUtils.copyLocalColumn(network, newNetwork, CyNode.class, seedAttribute);
    }
    // System.out.println("Getting the view");
    networkView = ViewUtils.createView(manager, newNetwork, false);
    ViewUtils.doLayout(manager, networkView, monitor, "force-directed");
    // Now, if we're supposed to, restore the inter-cluster edges
    if (restoreEdges || (context != null && context.restoreEdges)) {
        for (CyEdge edge : network.getEdgeList()) {
            if (!edgeMap.containsKey(edge)) {
                ((CySubNetwork) networkView.getModel()).addEdge(edge);
                ModelUtils.createAndSetLocal(networkView.getModel(), edge, clusterAttribute, new Integer(0), Integer.class, null);
            }
        }
        style = styleNewView(style, clusterAttribute);
    }
    // System.out.println("Setting the style");
    ViewUtils.setVisualStyle(manager, networkView, style);
    if (isFuzzy) {
        long fuzzyClusterTableSUID = network.getRow(network).get(clusterAttribute + "_Table.SUID", Long.class);
        newNetwork.getRow(newNetwork).set(clusterAttribute + "_Table.SUID", fuzzyClusterTableSUID);
        // System.out.println("NetworkName: "+ network.getRow(network).get(CyNetwork.NAME, String.class));
        // System.out.println("Fuzzy Table SUID: " + fuzzyClusterTableSUID );
        CyTable fuzzyClusterTable = manager.getTableManager().getTable(fuzzyClusterTableSUID);
        // System.out.println("Creating membership edges");
        createMembershipEdges(newNetwork, networkView, manager, fuzzyClusterTable);
    }
    ViewUtils.registerView(manager, networkView);
    return;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CyNetwork(org.cytoscape.model.CyNetwork) CyEdge(org.cytoscape.model.CyEdge) CyTable(org.cytoscape.model.CyTable) EdgeWeightConverter(edu.ucsf.rbvi.clusterMaker2.internal.algorithms.edgeConverters.EdgeWeightConverter) CyNode(org.cytoscape.model.CyNode) ArrayList(java.util.ArrayList) List(java.util.List) VisualStyle(org.cytoscape.view.vizmap.VisualStyle) CySubNetwork(org.cytoscape.model.subnetwork.CySubNetwork)

Example 87 with CySubNetwork

use of org.cytoscape.model.subnetwork.CySubNetwork in project PhenomeScape by soulj.

the class PhenomeExpress method run.

@Override
public void run(TaskMonitor taskMonitor) throws Exception {
    taskMonitor.setTitle("Running PhenomeExpress");
    taskMonitor.setStatusMessage("Preparing Networks");
    long time = System.currentTimeMillis();
    inputCheck();
    setUpNetworks();
    double[] relativeWeighting = { 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8 };
    double[] alphas = { 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8 };
    double[] piValues = proteinNetwork.getPivalues();
    Map<String, Integer> phenotypeMap = phenomeNetwork.getName2IndexMap();
    double[] phenoArray = new double[phenomeNetwork.getName2IndexMap().size()];
    selectedPhenotypes = new ArrayList<Phenotype>();
    boolean first = true;
    for (Phenotype phenotype : phenotypes) {
        if (phenotype.getSelected()) {
            if (first) {
                phenotypeSelected = phenotype.getID();
                phenotypeNamesSelected = phenotype.getName();
                selectedPhenotypes.add(phenotype);
                phenoArray[phenotypeMap.get(phenotype.getID())] = 1.0;
                first = false;
            } else {
                phenotypeSelected = phenotypeSelected + " ," + phenotype.getID();
                phenotypeNamesSelected = phenotypeNamesSelected + " ," + phenotype.getName();
                phenoArray[phenotypeMap.get(phenotype.getID())] = 1.0;
                selectedPhenotypes.add(phenotype);
            }
        }
    }
    Map<CyNode, Integer> map = proteinNetwork.getNode2IndexMap();
    int size = proteinNetwork.getNetwork().getNodeCount();
    int[] occuranceArray = new int[size];
    HashMap<CyNode, Protein> node2Protein = new HashMap<CyNode, Protein>();
    if (cancelled) {
        return;
    }
    taskMonitor.setStatusMessage("Calculating Activity Scores");
    taskMonitor.setProgress(0.0);
    double progress = 0.0;
    SparseRowMatrix adjMatrix = SparseRowMatrix.create(size, size);
    double[] transitionProbs = { 0.5, 0.6, 0.7, 0.8 };
    for (double transitionProb : transitionProbs) {
        TransitionMatrix transitionMatrix = new TransitionMatrix(phenomeNetwork.normalise(transitionProb, phenoGeneNetwork), proteinNetwork.normalise(transitionProb, phenoGeneNetwork), phenoGeneNetwork.normaliseT(transitionProb), phenoGeneNetwork.normalise(transitionProb));
        for (double weighting : relativeWeighting) {
            if (cancelled) {
                return;
            }
            transitionMatrix.prepareVector(piValues, phenoArray, weighting);
            for (double alpha : alphas) {
                progress += 0.0051;
                taskMonitor.setProgress(progress);
                double[] pageRankResults = transitionMatrix.pageRank(alpha);
                HashMap<Integer, Protein> index2ProteinMap = proteinNetwork.getIndex2ProteinMap();
                for (int i = 0; i < index2ProteinMap.size(); i++) {
                    Protein protein = index2ProteinMap.get(i);
                    protein.setValue(pageRankResults[i]);
                }
                List<Protein> proteinList = new ArrayList<Protein>(index2ProteinMap.values());
                Collections.sort(proteinList, new DescendingScoreComparator());
                int rank = 0;
                for (Protein protein : proteinList) {
                    rank++;
                    protein.setRank(rank);
                    node2Protein.put(protein.getNode(), protein);
                }
                Collections.sort(proteinList, new DescendingScoreComparator());
                GIGA giga = new GIGA(proteinList, node2Protein, proteinNetwork, maxNetworkSize);
                giga.compute();
                for (GIGACluster cluster : giga.getClusters()) {
                    for (CyNode node : cluster.getCluster()) {
                        Integer index = map.get(node);
                        AVector row = adjMatrix.getRow(index);
                        if (!row.isMutable()) {
                            row = row.mutable();
                        }
                        for (CyNode node2 : cluster.getCluster()) {
                            Integer index2 = map.get(node2);
                            row.set(index2, row.get(index2) + 1.0);
                            occuranceArray[index2]++;
                        }
                        adjMatrix.replaceRow(index, row);
                    }
                }
            }
        }
    }
    if (cancelled) {
        return;
    }
    taskMonitor.setProgress(1.0);
    taskMonitor.setStatusMessage("Creating Consensus Subnetworks");
    AMatrix cooccuranceMat = adjMatrix.transposeInnerProduct(adjMatrix);
    for (int i = 0; i < size; i++) {
        AVector row = cooccuranceMat.getRow(i);
        if (row.elementSum() > 0) {
            row.divide(occuranceArray[i]);
            Index nonSparse = row.nonSparseIndex();
            for (int j = 0; j < nonSparse.length(); j++) {
                if (row.get(nonSparse.get(j)) < 1.0) {
                    row.set(nonSparse.get(j), 0.0);
                }
            }
            cooccuranceMat.replaceRow(i, row.sparse());
        }
    }
    ConnectedComponentAnalyser CCA = new ConnectedComponentAnalyser(node2Protein);
    ArrayList<PhenomeExpressSubnetwork> subnetworks = CCA.ccFromAdjMatrix(adjMatrix, proteinNetwork);
    Iterator<PhenomeExpressSubnetwork> it = subnetworks.iterator();
    while (it.hasNext()) {
        PhenomeExpressSubnetwork subnetwork = it.next();
        if (subnetwork.getNodeList().size() < this.minNetSize) {
            it.remove();
        }
    }
    if (cancelled) {
        return;
    }
    taskMonitor.setStatusMessage("Calculating Subnetwork Significance");
    subnetworksSignificance(subnetworks);
    taskMonitor.setStatusMessage("Visualising Subnetworks");
    List<Double> foldChangeValues = proteinNetwork.getNodeTable().getColumn(foldChange).getValues(Double.class);
    double fcMax = Collections.max(foldChangeValues);
    double fcMin = Collections.min(foldChangeValues);
    // Apply the visual style to a NetworkView
    VizStyle vizStyle = new VizStyle();
    VisualStyle vs = vizStyle.createVizStyle(cyServiceRegistrar, geneName, foldChange, fcMax, fcMin);
    this.property = getNodeLabelPositionProperty();
    vs.setDefaultValue(property, property.parseSerializableString("N,S,c,0.0,0.0"));
    VisualMappingManager visualMappingManager = cyServiceRegistrar.getService(VisualMappingManager.class);
    visualMappingManager.setCurrentVisualStyle(vs);
    ArrayList<CyNetworkView> networkViewList = new ArrayList<CyNetworkView>();
    Iterator<PhenomeExpressSubnetwork> it2 = subnetworks.iterator();
    CyNetworkManager networkManager = cyServiceRegistrar.getService(CyNetworkManager.class);
    CyNetworkViewFactory networkViewFactory = cyServiceRegistrar.getService(CyNetworkViewFactory.class);
    CyLayoutAlgorithmManager layoutManager = cyServiceRegistrar.getService(CyLayoutAlgorithmManager.class);
    CyApplicationManager cyApplicationManager = cyServiceRegistrar.getService(CyApplicationManager.class);
    CyLayoutAlgorithm layout = layoutManager.getLayout("force-directed");
    Map<String, Object> settings = new HashMap<String, Object>();
    settings.put("defaultSpringLength", 5.0);
    settings.put("defaultSpringNodeMass", 2.0);
    TunableSetter setter = cyServiceRegistrar.getService(TunableSetter.class);
    Object context = layout.createLayoutContext();
    setter.applyTunables(context, settings);
    GOTermAnalyser2 goTermAnalyser = new GOTermAnalyser2(proteinNetwork, species);
    while (it2.hasNext()) {
        PhenomeExpressSubnetwork subnet = it2.next();
        if (subnet.getPvalue() > this.threshold) {
            it2.remove();
        } else {
            goTermAnalyser.calculateGOTermPValues(subnet, proteinNetwork);
            String subnetworkName = NetworkUtils.getUniqueNetworkName(cyServiceRegistrar, networkName + "_" + subnet.getBestGOTerm());
            subnet.setName(subnetworkName);
            CySubNetwork subnetwork = NetworkUtils.createSubNetwork(((CySubNetwork) proteinNetwork.getNetwork()).getRootNetwork(), subnet.getNodeList());
            subnetwork.getRow(subnetwork).set(CyNetwork.NAME, subnetworkName);
            addSeedPhenotypes(subnetwork);
            networkManager.addNetwork(subnetwork);
            CyNetworkViewManager viewManager = cyServiceRegistrar.getService(CyNetworkViewManager.class);
            CyNetworkView nv = networkViewFactory.createNetworkView(subnetwork);
            viewManager.addNetworkView(nv);
            cyApplicationManager.setCurrentNetworkView(nv);
            for (CyNode phenoNode : phenotypesAdded) {
                View<CyNode> nodeView = nv.getNodeView(phenoNode);
                nodeView.setLockedValue(BasicVisualLexicon.NODE_SHAPE, NodeShapeVisualProperty.RECTANGLE);
                nodeView.setLockedValue(BasicVisualLexicon.NODE_FILL_COLOR, Color.BLUE);
            }
            for (CyEdge phenoEdge : phenoEdges) {
                View<CyEdge> edgeView = nv.getEdgeView(phenoEdge);
                edgeView.setLockedValue(BasicVisualLexicon.EDGE_LINE_TYPE, LineTypeVisualProperty.DOT);
                edgeView.setLockedValue(BasicVisualLexicon.EDGE_PAINT, Color.BLUE);
            }
            networkViewList.add(nv);
            Set<View<CyNode>> nodeSet = Collections.emptySet();
            cyServiceRegistrar.getService(TaskManager.class).execute(layout.createTaskIterator(nv, context, nodeSet, null));
        }
    }
    CyEventHelper cyEventHelper = cyServiceRegistrar.getService(CyEventHelper.class);
    for (CyNetworkView nv : networkViewList) {
        visualMappingManager.setVisualStyle(vs, nv);
        vs.apply(nv);
        cyEventHelper.flushPayloadEvents();
        cyApplicationManager.setCurrentNetworkView(nv);
        nv.updateView();
    }
    phenomeNetwork = null;
    proteinNetwork = null;
    ResultsPanel resultsPanel = (ResultsPanel) CytoPanelUtils.getCytoPanel(cyServiceRegistrar, ResultsPanel.class, CytoPanelName.EAST);
    resultsPanel.newTableData(getResultsSummary(subnetworks), getParameterList());
    CytoPanelUtils.showCytoPanel(cyServiceRegistrar, CytoPanelName.EAST);
}
Also used : CyEventHelper(org.cytoscape.event.CyEventHelper) HashMap(java.util.HashMap) AMatrix(mikera.matrixx.AMatrix) ArrayList(java.util.ArrayList) Index(mikera.indexz.Index) TunableSetter(org.cytoscape.work.TunableSetter) AVector(mikera.vectorz.AVector) CyNode(org.cytoscape.model.CyNode) GOTermAnalyser2(org.cytoscape.phenomescape.internal.util.GOTermAnalyser2) CyNetworkViewManager(org.cytoscape.view.model.CyNetworkViewManager) CyApplicationManager(org.cytoscape.application.CyApplicationManager) Phenotype(org.cytoscape.phenomescape.internal.util.Phenotype) CyNetworkManager(org.cytoscape.model.CyNetworkManager) CyNetworkViewFactory(org.cytoscape.view.model.CyNetworkViewFactory) CyLayoutAlgorithmManager(org.cytoscape.view.layout.CyLayoutAlgorithmManager) ConnectedComponentAnalyser(org.cytoscape.phenomescape.internal.util.ConnectedComponentAnalyser) DescendingScoreComparator(org.cytoscape.phenomescape.internal.Protein.DescendingScoreComparator) CyLayoutAlgorithm(org.cytoscape.view.layout.CyLayoutAlgorithm) VisualStyle(org.cytoscape.view.vizmap.VisualStyle) VizStyle(org.cytoscape.phenomescape.internal.util.VizStyle) CyEdge(org.cytoscape.model.CyEdge) View(org.cytoscape.view.model.View) CyNetworkView(org.cytoscape.view.model.CyNetworkView) SparseRowMatrix(mikera.matrixx.impl.SparseRowMatrix) TaskManager(org.cytoscape.work.TaskManager) VisualMappingManager(org.cytoscape.view.vizmap.VisualMappingManager) CyNetworkView(org.cytoscape.view.model.CyNetworkView) CySubNetwork(org.cytoscape.model.subnetwork.CySubNetwork)

Example 88 with CySubNetwork

use of org.cytoscape.model.subnetwork.CySubNetwork in project PhenomeScape by soulj.

the class NetworkUtils method createSubNetwork.

public static CySubNetwork createSubNetwork(CyRootNetwork cyRootNetwork, Collection<CyNode> cyNodes) {
    Set<CyEdge> cyEdges = new HashSet<CyEdge>();
    for (CyNode n : cyNodes) {
        Set<CyEdge> adjacentEdges = new HashSet<CyEdge>(cyRootNetwork.getAdjacentEdgeList(n, CyEdge.Type.ANY));
        // Get only the edges that connect nodes that belong to the subnetwork:
        for (CyEdge e : adjacentEdges) {
            if (cyNodes.contains(e.getSource()) && cyNodes.contains(e.getTarget())) {
                cyEdges.add(e);
            }
        }
    }
    CySubNetwork subNet = cyRootNetwork.addSubNetwork(cyNodes, cyEdges);
    return subNet;
}
Also used : CyNode(org.cytoscape.model.CyNode) CyEdge(org.cytoscape.model.CyEdge) CySubNetwork(org.cytoscape.model.subnetwork.CySubNetwork) HashSet(java.util.HashSet)

Aggregations

CySubNetwork (org.cytoscape.model.subnetwork.CySubNetwork)88 CyNode (org.cytoscape.model.CyNode)44 CyRootNetwork (org.cytoscape.model.subnetwork.CyRootNetwork)35 CyNetwork (org.cytoscape.model.CyNetwork)31 CyEdge (org.cytoscape.model.CyEdge)28 Test (org.junit.Test)19 CyRow (org.cytoscape.model.CyRow)15 ArrayList (java.util.ArrayList)12 CyTable (org.cytoscape.model.CyTable)11 CyNetworkView (org.cytoscape.view.model.CyNetworkView)11 HashSet (java.util.HashSet)7 CyGroup (org.cytoscape.group.CyGroup)7 HashMap (java.util.HashMap)6 CyNetworkManager (org.cytoscape.model.CyNetworkManager)6 CyApplicationManager (org.cytoscape.application.CyApplicationManager)5 CyEventHelper (org.cytoscape.event.CyEventHelper)5 CyNetworkViewManager (org.cytoscape.view.model.CyNetworkViewManager)5 Dimension (java.awt.Dimension)3 GroupCollapsedEvent (org.cytoscape.group.events.GroupCollapsedEvent)3 VisualStyle (org.cytoscape.view.vizmap.VisualStyle)3