Search in sources :

Example 36 with DataStore

use of uk.ac.babraham.SeqMonk.DataTypes.DataStore in project SeqMonk by s-andrews.

the class HeatmapGenomePanel method paint.

public void paint(Graphics g) {
    super.paint(g);
    if (drawnPixels.length != getWidth() || drawnPixels[0].length != getHeight()) {
        drawnPixels = new boolean[getWidth()][getHeight()];
    } else {
        for (int i = 0; i < getWidth(); i++) {
            for (int j = 0; j < getHeight(); j++) {
                drawnPixels[i][j] = false;
            }
        }
    }
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, getWidth(), getHeight());
    g.setColor(Color.BLACK);
    // Add a label at the top to signify current filters
    StringBuffer topLabel = new StringBuffer();
    // First include the position
    Chromosome xStartChr = getChrForPosition(currentXStartBp);
    if (xStartChr != null) {
        topLabel.append("X=Chr");
        topLabel.append(xStartChr.name());
        topLabel.append(":");
        topLabel.append(PositionFormat.formatLength(currentXStartBp - chromosomeBaseOffsets.get(xStartChr)));
        topLabel.append("-");
        Chromosome xEndChr = getChrForPosition(currentXEndBp);
        if (xStartChr != xEndChr) {
            topLabel.append("Chr");
            topLabel.append(xEndChr.name());
            topLabel.append(":");
        }
        topLabel.append(PositionFormat.formatLength(currentXEndBp - chromosomeBaseOffsets.get(xEndChr)));
        if (probeSortingOrder == null) {
            topLabel.append(" Y=Chr");
            Chromosome yStartChr = getChrForPosition(currentYStartBp);
            topLabel.append(yStartChr.name());
            topLabel.append(":");
            topLabel.append(PositionFormat.formatLength(currentYStartBp - chromosomeBaseOffsets.get(yStartChr)));
            topLabel.append("-");
            Chromosome yEndChr = getChrForPosition(currentYEndBp);
            if (yStartChr != yEndChr) {
                topLabel.append("Chr");
                topLabel.append(yEndChr.name());
                topLabel.append(":");
            }
            topLabel.append(PositionFormat.formatLength(currentYEndBp - chromosomeBaseOffsets.get(yEndChr)));
        }
        topLabel.append(" ");
    }
    // Now append any current limits
    if (matrix.currentMinStrength() > 0) {
        topLabel.append("Strength > ");
        topLabel.append(df.format(matrix.currentMinStrength()));
        topLabel.append(" ");
    }
    if (matrix.minDifference() > 0) {
        topLabel.append("Difference > ");
        topLabel.append(df.format(matrix.minDifference()));
        topLabel.append(" ");
    }
    if (matrix.currentMaxSignficance() < 1) {
        topLabel.append("P-value < ");
        topLabel.append(df.format(matrix.currentMaxSignficance()));
        topLabel.append(" ");
    }
    if (topLabel.length() == 0) {
        topLabel.append("No filters");
    }
    g.drawString(topLabel.toString(), getWidth() / 2 - (g.getFontMetrics().stringWidth(topLabel.toString()) / 2), 15 + (g.getFontMetrics().getAscent() / 2));
    Chromosome[] chrs = genome.getAllChromosomes();
    Arrays.sort(chrs);
    // Find the max height and width of the chromosome names in this genome
    if (maxNameWidth == 0) {
        nameHeight = g.getFontMetrics().getHeight();
        maxNameWidth = 0;
        for (int c = 0; c < chrs.length; c++) {
            int thisWidth = g.getFontMetrics().stringWidth(chrs[c].name());
            if (thisWidth > maxNameWidth)
                maxNameWidth = thisWidth;
        }
        // Give both the width and height a bit of breathing space
        nameHeight += 6;
        maxNameWidth += 6;
    }
    // Make the background of the plot black
    g.setColor(Color.WHITE);
    g.fillRect(maxNameWidth, 30, getWidth() - (maxNameWidth + 10), getHeight() - (nameHeight + 30));
    // Draw the actual data
    InteractionProbePair[] interactions = matrix.filteredInteractions();
    // Cache some values for use with the quantitation colouring
    double minQuantitatedValue;
    double maxQuantitatedValue;
    if (DisplayPreferences.getInstance().getScaleType() == DisplayPreferences.SCALE_TYPE_POSITIVE) {
        minQuantitatedValue = 0;
        maxQuantitatedValue = DisplayPreferences.getInstance().getMaxDataValue();
    } else {
        maxQuantitatedValue = DisplayPreferences.getInstance().getMaxDataValue();
        minQuantitatedValue = 0 - maxQuantitatedValue;
    }
    for (int i = 0; i < interactions.length; i++) {
        // the plot symmetrical
        for (int forRev = 0; forRev <= 1; forRev++) {
            int yIndex;
            Probe probe1;
            Probe probe2;
            if (forRev == 0) {
                yIndex = interactions[i].probe2Index();
                probe1 = interactions[i].probe1();
                probe2 = interactions[i].probe2();
            } else {
                yIndex = interactions[i].probe1Index();
                probe2 = interactions[i].probe1();
                probe1 = interactions[i].probe2();
            }
            if (probeSortingOrder != null) {
                yIndex = probeSortingOrder[yIndex];
                if (yIndex < currentYStartIndex || yIndex > currentYEndIndex) {
                    // System.err.println("Skipping for y zoom");
                    continue;
                }
            }
            int xStart = getXForPosition(chromosomeBaseOffsets.get(probe1.chromosome()) + probe1.start());
            if (xStart < maxNameWidth)
                continue;
            if (chromosomeBaseOffsets.get(probe1.chromosome()) + probe1.start() > currentXEndBp) {
                // System.err.println("Skipping for x end");
                continue;
            }
            int xEnd = getXForPosition(chromosomeBaseOffsets.get(probe1.chromosome()) + probe1.end());
            if (xEnd > getWidth() - 10)
                continue;
            if (chromosomeBaseOffsets.get(probe1.chromosome()) + probe1.end() < currentXStartBp) {
                // System.err.println("Skipping for x start");
                continue;
            }
            int yStart;
            int yEnd;
            if (probeSortingOrder == null) {
                if (chromosomeBaseOffsets.get(probe2.chromosome()) + probe2.start() > currentYEndBp)
                    continue;
                if (chromosomeBaseOffsets.get(probe2.chromosome()) + probe2.end() < currentYStartBp)
                    continue;
                yStart = getYForPosition(chromosomeBaseOffsets.get(probe2.chromosome()) + probe2.start());
                yEnd = getYForPosition(chromosomeBaseOffsets.get(probe2.chromosome()) + probe2.end());
            } else {
                yStart = getYForIndex(probeSortingOrder[yIndex]);
                yEnd = getYForIndex(probeSortingOrder[yIndex] + 1);
            }
            if (yStart > getHeight() - nameHeight) {
                continue;
            }
            if (yEnd < 30)
                continue;
            if (xEnd - xStart < 3) {
                xEnd += 1;
                xStart -= 1;
            }
            if (yStart - yEnd < 3) {
                // System.err.println("Expanding y selection");
                yEnd -= 1;
                yStart += 1;
            }
            // To be skipped there has to be colour at two corners and the middle.
            if (drawnPixels[xStart][yEnd] && drawnPixels[xEnd][yStart] && drawnPixels[xStart + ((xEnd - xStart) / 2)][yEnd + ((yStart - yEnd) / 2)]) {
                // System.err.println("Skipping for overlap with existing");
                continue;
            }
            switch(matrix.currentColourSetting()) {
                case HeatmapMatrix.COLOUR_BY_OBS_EXP:
                    if (matrix.initialMinStrength() < 1) {
                        // They're interested in depletion as well as enrichment.
                        // Make a symmetrical gradient around 0 and the max strength
                        g.setColor(matrix.colourGradient().getColor(Math.log10(interactions[i].strength()), Math.log10(1 / matrix.maxValue()), Math.log10(matrix.maxValue())));
                    } else {
                        g.setColor(matrix.colourGradient().getColor(Math.log10(interactions[i].strength() - matrix.initialMinStrength()), Math.log10(matrix.initialMinStrength()), Math.log10(matrix.maxValue() - matrix.initialMinStrength())));
                    }
                    break;
                case HeatmapMatrix.COLOUR_BY_INTERACTIONS:
                    g.setColor(matrix.colourGradient().getColor(interactions[i].absolute(), matrix.initialMinAbsolute(), 50));
                    break;
                case HeatmapMatrix.COLOUR_BY_P_VALUE:
                    g.setColor(matrix.colourGradient().getColor(Math.log10(interactions[i].signficance()) * -10, Math.log10(matrix.initialMaxSignificance()) * -10, 50));
                    break;
                case HeatmapMatrix.COLOUR_BY_QUANTITATION:
                    Probe probeForQuantitation;
                    if (forRev == 0) {
                        probeForQuantitation = interactions[i].lowestProbe();
                    } else {
                        probeForQuantitation = interactions[i].highestProbe();
                    }
                    try {
                        g.setColor(matrix.colourGradient().getColor(((DataStore) dataSet).getValueForProbe(probeForQuantitation), minQuantitatedValue, maxQuantitatedValue));
                    } catch (SeqMonkException e) {
                    }
                    break;
            }
            g.fillRect(xStart, yEnd, xEnd - xStart, yStart - yEnd);
            // If we're looking for selected probes check this now.
            if (displayXProbe || displayYProbe) {
                if (xStart <= displayX && xEnd >= displayX && yEnd <= displayY && yStart >= displayY) {
                    if (displayXProbe) {
                        DisplayPreferences.getInstance().setLocation(interactions[i].probe1().chromosome(), interactions[i].probe1().packedPosition());
                        displayXProbe = false;
                    }
                    if (displayYProbe) {
                        DisplayPreferences.getInstance().setLocation(interactions[i].probe2().chromosome(), interactions[i].probe2().packedPosition());
                        displayYProbe = false;
                    }
                }
            }
            // them again
            for (int x = Math.min(xStart, xEnd); x <= Math.min(xStart, xEnd) + Math.abs(xStart - xEnd); x++) {
                for (int y = Math.min(yStart, yEnd); y <= Math.min(yStart, yEnd) + Math.abs(yStart - yEnd); y++) {
                    drawnPixels[x][y] = true;
                }
            }
        }
    }
    // System.err.println("Skipped "+skipped+" and drew "+drawn+" out of "+(interactions.length*2)+" interactions");
    // Draw the chromosome lines
    g.setColor(Color.GRAY);
    // Draw Chr Lines on X axis
    long runningGenomeLength = 0;
    for (int c = 0; c < chrs.length; c++) {
        int startPos = getXForPosition(runningGenomeLength);
        int endPos = getXForPosition(runningGenomeLength + chrs[c].length());
        if (c > 0) {
            if (startPos >= maxNameWidth && startPos <= getWidth() - 10) {
                g.drawLine(startPos, 30, startPos, getHeight() - nameHeight);
            }
        }
        if (c + 1 == chrs.length) {
            if (endPos >= maxNameWidth && endPos <= getWidth() - 10) {
                g.drawLine(endPos, 30, endPos, getHeight() - nameHeight);
            }
        }
        int nameWidth = g.getFontMetrics().stringWidth(chrs[c].name());
        g.drawString(chrs[c].name(), (startPos + ((endPos - startPos) / 2)) - (nameWidth / 2), getHeight() - 3);
        runningGenomeLength += chrs[c].length();
    }
    // Draw Chr Lines on Y axis
    if (probeSortingOrder == null) {
        runningGenomeLength = 0;
        for (int c = 0; c < chrs.length; c++) {
            int startPos = getYForPosition(runningGenomeLength);
            int endPos = getYForPosition(runningGenomeLength + chrs[c].length());
            if (c > 0) {
                if (startPos <= getHeight() - nameHeight && startPos >= 30) {
                    g.drawLine(maxNameWidth, startPos, getWidth() - 10, startPos);
                }
            }
            if (c + 1 == chrs.length) {
                if (endPos <= getHeight() - nameHeight && endPos >= 30) {
                    g.drawLine(maxNameWidth, endPos, getWidth() - 10, endPos);
                }
            }
            int nameWidth = g.getFontMetrics().stringWidth(chrs[c].name());
            g.drawString(chrs[c].name(), (maxNameWidth / 2) - (nameWidth / 2), (endPos + ((startPos - endPos) / 2)) + (g.getFontMetrics().getAscent() / 2));
            runningGenomeLength += chrs[c].length();
        }
    } else {
        int runningListPosition = 0;
        for (int l = 0; l < clusterIntervals.length; l++) {
            runningListPosition += clusterIntervals[l];
            if (runningListPosition < currentYStartIndex)
                continue;
            if (runningListPosition > currentYEndIndex)
                break;
            int pos = getYForIndex(runningListPosition);
            g.drawLine(maxNameWidth, pos, getWidth() - 10, pos);
        }
    }
    // Draw the axes
    g.drawLine(maxNameWidth, getHeight() - nameHeight, getWidth() - 10, getHeight() - nameHeight);
    g.drawLine(maxNameWidth, getHeight() - nameHeight, maxNameWidth, 30);
    // Draw a selection if we're making one
    if (makingSelection) {
        g.setColor(ColourScheme.DRAGGED_SELECTION);
        g.drawRect(Math.min(selectionEndX, selectionStartX), Math.min(selectionEndY, selectionStartY), Math.abs(selectionEndX - selectionStartX), Math.abs(selectionEndY - selectionStartY));
    }
    displayXProbe = false;
    displayYProbe = false;
}
Also used : InteractionProbePair(uk.ac.babraham.SeqMonk.DataTypes.Interaction.InteractionProbePair) DataStore(uk.ac.babraham.SeqMonk.DataTypes.DataStore) HiCDataStore(uk.ac.babraham.SeqMonk.DataTypes.HiCDataStore) Chromosome(uk.ac.babraham.SeqMonk.DataTypes.Genome.Chromosome) SeqMonkException(uk.ac.babraham.SeqMonk.SeqMonkException) Probe(uk.ac.babraham.SeqMonk.DataTypes.Probes.Probe)

Example 37 with DataStore

use of uk.ac.babraham.SeqMonk.DataTypes.DataStore in project SeqMonk by s-andrews.

the class GroupEditor method actionPerformed.

/* (non-Javadoc)
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
public void actionPerformed(ActionEvent ae) {
    String c = ae.getActionCommand();
    if (c.equals("add")) {
        Object[] addObj = availableList.getSelectedValues();
        DataStore[] adds = new DataStore[addObj.length];
        for (int i = 0; i < adds.length; i++) {
            adds[i] = (DataStore) addObj[i];
        }
        usedModel.addElements(adds);
        availableModel.removeElements(adds);
        availableList.setSelectedIndices(new int[0]);
        usedList.setSelectedIndices(new int[0]);
        Object[] o = usedModel.getStores();
        DataSet[] s = new DataSet[o.length];
        for (int i = 0; i < s.length; i++) {
            s[i] = (DataSet) o[i];
        }
        DataGroup r = (DataGroup) groupList.getSelectedValue();
        r.setDataSets(s);
    } else if (c.equals("select_named")) {
        new NameGatherer();
    } else if (c.equals("remove")) {
        Object[] addObj = usedList.getSelectedValues();
        DataStore[] adds = new DataStore[addObj.length];
        for (int i = 0; i < adds.length; i++) {
            adds[i] = (DataStore) addObj[i];
        }
        usedModel.removeElements(adds);
        availableModel.addElements(adds);
        availableList.setSelectedIndices(new int[0]);
        usedList.setSelectedIndices(new int[0]);
        Object[] o = usedModel.getStores();
        DataSet[] s = new DataSet[o.length];
        for (int i = 0; i < s.length; i++) {
            s[i] = (DataSet) o[i];
        }
        DataGroup r = (DataGroup) groupList.getSelectedValue();
        r.setDataSets(s);
    } else if (c.equals("new_set")) {
        String setName = null;
        while (true) {
            setName = (String) JOptionPane.showInputDialog(this, "Enter group name", "Group Name", JOptionPane.QUESTION_MESSAGE, null, null, "New Data Group");
            if (setName == null)
                // They cancelled
                return;
            if (setName.length() == 0)
                // Try again
                continue;
            break;
        }
        DataGroup s = new DataGroup(setName, new DataSet[0]);
        application.dataCollection().addDataGroup(s);
        groupModel.addElements(new DataStore[] { s });
    } else if (c.equals("rename_set")) {
        DataGroup s = (DataGroup) groupList.getSelectedValue();
        String setName = null;
        while (true) {
            setName = (String) JOptionPane.showInputDialog(this, "Enter group name", "Set Name", JOptionPane.QUESTION_MESSAGE, null, null, s.name());
            // They cancelled
            if (setName == null)
                return;
            if (setName.length() > 0)
                break;
        }
        s.setName(setName);
        groupModel.setElementAt(s, groupList.getSelectedIndex());
    } else if (c.equals("delete_set")) {
        Object[] o = groupList.getSelectedValues();
        DataGroup[] dataGroups = new DataGroup[o.length];
        for (int i = 0; i < o.length; i++) {
            dataGroups[i] = (DataGroup) o[i];
        }
        groupModel.removeElements(dataGroups);
        application.dataCollection().removeDataGroups(dataGroups);
    } else if (c.equals("close")) {
        setVisible(false);
        dispose();
    }
}
Also used : DataGroup(uk.ac.babraham.SeqMonk.DataTypes.DataGroup) DataSet(uk.ac.babraham.SeqMonk.DataTypes.DataSet) DataStore(uk.ac.babraham.SeqMonk.DataTypes.DataStore)

Example 38 with DataStore

use of uk.ac.babraham.SeqMonk.DataTypes.DataStore in project SeqMonk by s-andrews.

the class GroupEditor method valueChanged.

/* (non-Javadoc)
	 * @see javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event.ListSelectionEvent)
	 */
public void valueChanged(ListSelectionEvent ae) {
    // Check for a new set being selected
    if (ae.getSource() == groupList) {
        // Move all samples back to the available list
        DataStore[] o = usedModel.getStores();
        availableModel.addElements(o);
        usedModel.removeAllElements();
        if (groupList.getSelectedValues().length == 1) {
            renameButton.setEnabled(true);
            deleteButton.setEnabled(true);
            DataGroup s = (DataGroup) groupList.getSelectedValue();
            DataSet[] st = s.dataSets();
            usedModel.addElements(st);
            availableModel.removeElements(st);
        } else if (groupList.getSelectedValues().length > 1) {
            deleteButton.setEnabled(true);
        } else {
            deleteButton.setEnabled(false);
        }
    }
    // Check to see if we can add anything...
    if (availableList.getSelectedIndices().length > 0 && groupList.getSelectedIndices().length == 1) {
        addButton.setEnabled(true);
    } else {
        addButton.setEnabled(false);
    }
    // Or remove anything
    if (usedList.getSelectedIndices().length > 0 && groupList.getSelectedIndices().length == 1) {
        removeButton.setEnabled(true);
    } else {
        removeButton.setEnabled(false);
    }
}
Also used : DataGroup(uk.ac.babraham.SeqMonk.DataTypes.DataGroup) DataSet(uk.ac.babraham.SeqMonk.DataTypes.DataSet) DataStore(uk.ac.babraham.SeqMonk.DataTypes.DataStore)

Example 39 with DataStore

use of uk.ac.babraham.SeqMonk.DataTypes.DataStore in project SeqMonk by s-andrews.

the class DataTrackSelector method actionPerformed.

/* (non-Javadoc)
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
public void actionPerformed(ActionEvent ae) {
    String c = ae.getActionCommand();
    if (c.equals("add")) {
        Object[] addObj = availableGroupList.getSelectedValues();
        DataStore[] adds = new DataStore[addObj.length];
        for (int i = 0; i < adds.length; i++) {
            adds[i] = (DataStore) addObj[i];
        }
        usedModel.addElements(adds);
        availableGroupModel.removeElements(adds);
        usedList.setSelectedIndices(new int[0]);
        availableGroupList.setSelectedIndices(new int[0]);
        addObj = availableSetList.getSelectedValues();
        adds = new DataStore[addObj.length];
        for (int i = 0; i < adds.length; i++) {
            adds[i] = (DataStore) addObj[i];
        }
        usedModel.addElements(adds);
        availableSetModel.removeElements(adds);
        availableSetList.setSelectedIndices(new int[0]);
        addObj = availableReplicateList.getSelectedValues();
        adds = new DataStore[addObj.length];
        for (int i = 0; i < adds.length; i++) {
            adds[i] = (DataStore) addObj[i];
        }
        usedModel.addElements(adds);
        availableReplicatesModel.removeElements(adds);
        availableReplicateList.setSelectedIndices(new int[0]);
    } else if (c.equals("remove")) {
        Object[] removeObj = usedList.getSelectedValues();
        DataStore[] removes = new DataStore[removeObj.length];
        for (int i = 0; i < removes.length; i++) {
            removes[i] = (DataStore) removeObj[i];
        }
        usedModel.removeElements(removes);
        usedList.setSelectedIndices(new int[0]);
        Vector<DataStore> removeSets = new Vector<DataStore>();
        Vector<DataStore> removeGroups = new Vector<DataStore>();
        Vector<DataStore> removeReps = new Vector<DataStore>();
        for (int i = 0; i < removes.length; i++) {
            if (removes[i] instanceof DataSet) {
                removeSets.add(removes[i]);
            } else if (removes[i] instanceof ReplicateSet) {
                removeReps.add(removes[i]);
            } else if (removes[i] instanceof DataGroup) {
                removeGroups.add(removes[i]);
            } else {
                throw new IllegalStateException("Unknown type of removed store " + removes[i]);
            }
        }
        availableSetModel.addElements(removeSets.toArray(new DataStore[0]));
        availableGroupModel.addElements(removeGroups.toArray(new DataStore[0]));
        availableReplicatesModel.addElements(removeReps.toArray(new DataStore[0]));
        availableSetList.setSelectedIndices(new int[0]);
        availableGroupList.setSelectedIndices(new int[0]);
        availableReplicateList.setSelectedIndices(new int[0]);
    } else if (c.equals("up")) {
        // Collect the list of selected indices
        int[] s = usedList.getSelectedIndices();
        Arrays.sort(s);
        // Get the set of objects associated with the selected indices
        DataStore[] current = new DataStore[s.length];
        for (int i = 0; i < s.length; i++) {
            current[i] = usedModel.elementAt(s[i]);
        }
        // Get the object above, which is going to move below
        DataStore above = usedModel.elementAt(s[0] - 1);
        // Move all the selected indices up one
        for (int i = 0; i < s.length; i++) {
            usedModel.setElementAt(current[i], s[i] - 1);
        }
        // Move the above object below the selected ones
        usedModel.setElementAt(above, s[s.length - 1]);
        // Decrease the set of selected indices and select them again
        for (int i = 0; i < s.length; i++) {
            s[i]--;
        }
        usedList.setSelectedIndices(s);
    } else if (c.equals("down")) {
        // Collect the list of selected indices
        int[] s = usedList.getSelectedIndices();
        Arrays.sort(s);
        // Get the set of objects associated with the selected indices
        DataStore[] current = new DataStore[s.length];
        for (int i = 0; i < s.length; i++) {
            current[i] = usedModel.elementAt(s[i]);
        }
        // Get the object below, which is going to move below
        DataStore below = usedModel.elementAt(s[s.length - 1] + 1);
        // Move all the selected indices down one
        for (int i = 0; i < s.length; i++) {
            usedModel.setElementAt(current[i], s[i] + 1);
        }
        // Move the below object above the selected ones
        usedModel.setElementAt(below, s[0]);
        // Increase the set of selected indices and select them again
        for (int i = 0; i < s.length; i++) {
            s[i]++;
        }
        usedList.setSelectedIndices(s);
    } else if (c.equals("cancel")) {
        setVisible(false);
        dispose();
    } else if (c.equals("ok")) {
        DataStore[] s = usedModel.getStores();
        application.setDrawnDataStores(s);
        setVisible(false);
        dispose();
    }
}
Also used : DataGroup(uk.ac.babraham.SeqMonk.DataTypes.DataGroup) DataSet(uk.ac.babraham.SeqMonk.DataTypes.DataSet) ReplicateSet(uk.ac.babraham.SeqMonk.DataTypes.ReplicateSet) DataStore(uk.ac.babraham.SeqMonk.DataTypes.DataStore) Vector(java.util.Vector)

Example 40 with DataStore

use of uk.ac.babraham.SeqMonk.DataTypes.DataStore in project SeqMonk by s-andrews.

the class EdgeRFilter method generateProbeList.

/* (non-Javadoc)
	 * @see uk.ac.babraham.SeqMonk.Filters.ProbeFilter#generateProbeList()
	 */
@Override
protected void generateProbeList() {
    // We need to make a temporary directory, save the data into it, write out the R script
    // and then run it an collect the list of results, then clean up.
    // Make up the list of DataStores in each replicate set
    DataStore[] fromStores = replicateSets[0].dataStores();
    DataStore[] toStores = replicateSets[1].dataStores();
    File tempDir;
    try {
        progressUpdated("Creating temp directory", 0, 1);
        tempDir = TempDirectory.createTempDirectory();
        System.err.println("Temp dir is " + tempDir.getAbsolutePath());
        progressUpdated("Writing R script", 0, 1);
        // Get the template script
        Template template = new Template(ClassLoader.getSystemResource("uk/ac/babraham/SeqMonk/Filters/EdgeRFilter/edger_template.r"));
        // Substitute in the variables we need to change
        template.setValue("WORKING", tempDir.getAbsolutePath().replace("\\", "/"));
        // Say which p value column we're filtering on
        if (multiTest) {
            template.setValue("CORRECTED", "FDR");
        } else {
            template.setValue("CORRECTED", "PValue");
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < fromStores.length; i++) {
            if (i > 0)
                sb.append(",");
            sb.append("1");
        }
        for (int i = 0; i < toStores.length; i++) {
            sb.append(",");
            sb.append("2");
        }
        template.setValue("CONDITIONS", sb.toString());
        template.setValue("PVALUE", "" + cutoff);
        // Write the script file
        File scriptFile = new File(tempDir.getAbsoluteFile() + "/script.r");
        PrintWriter pr = new PrintWriter(scriptFile);
        pr.print(template.toString());
        pr.close();
        // Write the count data
        File countFile = new File(tempDir.getAbsoluteFile() + "/counts.txt");
        pr = new PrintWriter(countFile);
        sb = new StringBuffer();
        sb.append("probe");
        for (int i = 0; i < fromStores.length; i++) {
            sb.append("\t");
            sb.append("from");
            sb.append(i);
        }
        for (int i = 0; i < toStores.length; i++) {
            sb.append("\t");
            sb.append("to");
            sb.append(i);
        }
        pr.println(sb.toString());
        progressUpdated("Writing count data", 0, 1);
        Probe[] probes = startingList.getAllProbes();
        float value;
        for (int p = 0; p < probes.length; p++) {
            if (p % 1000 == 0) {
                progressUpdated("Writing count data", p, probes.length);
            }
            sb = new StringBuffer();
            sb.append(p);
            for (int i = 0; i < fromStores.length; i++) {
                sb.append("\t");
                value = fromStores[i].getValueForProbe(probes[p]);
                if (value != (int) value) {
                    progressExceptionReceived(new IllegalArgumentException("Inputs to the EdgeR filter MUST be raw, incorrected counts, not things like " + value));
                    pr.close();
                    return;
                }
                sb.append(value);
            }
            for (int i = 0; i < toStores.length; i++) {
                sb.append("\t");
                value = toStores[i].getValueForProbe(probes[p]);
                if (value != (int) value) {
                    progressExceptionReceived(new IllegalArgumentException("Inputs to the EdgeR filter MUST be raw, incorrected counts, not things like " + value));
                    pr.close();
                    return;
                }
                sb.append(value);
            }
            pr.println(sb.toString());
        }
        pr.close();
        progressUpdated("Running R Script", 0, 1);
        RScriptRunner runner = new RScriptRunner(tempDir);
        RProgressListener listener = new RProgressListener(runner);
        runner.addProgressListener(new ProgressRecordDialog("R Session", runner));
        runner.runScript();
        while (true) {
            if (listener.cancelled()) {
                progressCancelled();
                return;
            }
            if (listener.exceptionReceived()) {
                progressExceptionReceived(new SeqMonkException("R Script failed"));
                return;
            }
            if (listener.complete())
                break;
            Thread.sleep(500);
        }
        // We can now parse the results and put the hits into a new probe list
        ProbeList newList;
        newList = new ProbeList(startingList, "", "", "FDR");
        File hitsFile = new File(tempDir.getAbsolutePath() + "/hits.txt");
        BufferedReader br = new BufferedReader(new FileReader(hitsFile));
        String line = br.readLine();
        while ((line = br.readLine()) != null) {
            String[] sections = line.split("\t");
            int probeIndex = Integer.parseInt(sections[0]);
            float pValue = Float.parseFloat(sections[sections.length - 1]);
            newList.addProbe(probes[probeIndex], pValue);
        }
        br.close();
        runner.cleanUp();
        filterFinished(newList);
    } catch (Exception ioe) {
        progressExceptionReceived(ioe);
        return;
    }
// filterFinished(newList);
}
Also used : ProbeList(uk.ac.babraham.SeqMonk.DataTypes.Probes.ProbeList) Probe(uk.ac.babraham.SeqMonk.DataTypes.Probes.Probe) RProgressListener(uk.ac.babraham.SeqMonk.R.RProgressListener) SeqMonkException(uk.ac.babraham.SeqMonk.SeqMonkException) Template(uk.ac.babraham.SeqMonk.Utilities.Templates.Template) ProgressRecordDialog(uk.ac.babraham.SeqMonk.Dialogs.ProgressRecordDialog) DataStore(uk.ac.babraham.SeqMonk.DataTypes.DataStore) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) SeqMonkException(uk.ac.babraham.SeqMonk.SeqMonkException) File(java.io.File) RScriptRunner(uk.ac.babraham.SeqMonk.R.RScriptRunner) PrintWriter(java.io.PrintWriter)

Aggregations

DataStore (uk.ac.babraham.SeqMonk.DataTypes.DataStore)46 Probe (uk.ac.babraham.SeqMonk.DataTypes.Probes.Probe)21 SeqMonkException (uk.ac.babraham.SeqMonk.SeqMonkException)19 Vector (java.util.Vector)15 ProbeList (uk.ac.babraham.SeqMonk.DataTypes.Probes.ProbeList)15 DataGroup (uk.ac.babraham.SeqMonk.DataTypes.DataGroup)11 DataSet (uk.ac.babraham.SeqMonk.DataTypes.DataSet)11 Chromosome (uk.ac.babraham.SeqMonk.DataTypes.Genome.Chromosome)11 JPanel (javax.swing.JPanel)10 ReplicateSet (uk.ac.babraham.SeqMonk.DataTypes.ReplicateSet)10 GridBagConstraints (java.awt.GridBagConstraints)9 JLabel (javax.swing.JLabel)9 GridBagLayout (java.awt.GridBagLayout)8 File (java.io.File)8 ActionEvent (java.awt.event.ActionEvent)7 BufferedReader (java.io.BufferedReader)7 FileReader (java.io.FileReader)7 JComboBox (javax.swing.JComboBox)7 JScrollPane (javax.swing.JScrollPane)7 HiCDataStore (uk.ac.babraham.SeqMonk.DataTypes.HiCDataStore)7