Search in sources :

Example 1 with JSparklinesDataSeries

use of no.uib.jsparklines.data.JSparklinesDataSeries in project peptide-shaker by compomics.

the class OverviewPanel method updatePtmCoveragePlot.

/**
 * Update the protein coverage PTM plot.
 *
 * @param proteinAccession the protein accession
 */
private void updatePtmCoveragePlot(String proteinAccession) {
    if (proteinTable.getSelectedRow() != -1) {
        try {
            SelfUpdatingTableModel tableModel = (SelfUpdatingTableModel) proteinTable.getModel();
            long proteinKey = proteinKeys[tableModel.getViewIndex(proteinTable.getSelectedRow())];
            // get the ptms
            ArrayList<JSparklinesDataSeries> sparkLineDataSeriesPtm = new ArrayList<>();
            HashMap<Integer, ArrayList<ResidueAnnotation>> proteinTooltips = new HashMap<>();
            // we need to add a first empty filler as the coverage table starts at 0
            ArrayList<Double> data = new ArrayList<>();
            data.add(Double.valueOf(0));
            JSparklinesDataSeries sparklineDataseriesPtm = new JSparklinesDataSeries(data, new Color(0, 0, 0, 0), null);
            sparkLineDataSeriesPtm.add(sparklineDataseriesPtm);
            Identification identification = peptideShakerGUI.getIdentification();
            ProteinMatch proteinMatch = identification.getProteinMatch(proteinKey);
            PSModificationScores psPtmScores = (PSModificationScores) proteinMatch.getUrParam(PSModificationScores.dummy);
            String sequence = peptideShakerGUI.getSequenceProvider().getSequence(proteinAccession);
            int unmodifiedCounter = 0;
            // get the fixed ptms
            // @TODO: note that this only supports one fixed ptm per residue
            HashMap<Integer, String> fixedPtms = new HashMap<>();
            DisplayParameters displayParameters = peptideShakerGUI.getDisplayParameters();
            // see if fixed ptms are displayed
            if (displayParameters.getDisplayedModifications().size() != peptideShakerGUI.getIdentificationParameters().getSearchParameters().getModificationParameters().getVariableModifications().size()) {
                for (long peptideKey : peptideKeys) {
                    PeptideMatch peptideMatch = identification.getPeptideMatch(peptideKey);
                    Peptide peptide = peptideMatch.getPeptide();
                    int[] indexesOnProtein = peptide.getProteinMapping().get(proteinAccession);
                    String[] fixedModifications = peptide.getFixedModifications(peptideShakerGUI.getIdentificationParameters().getSearchParameters().getModificationParameters(), peptideShakerGUI.getSequenceProvider(), peptideShakerGUI.getIdentificationParameters().getModificationLocalizationParameters().getSequenceMatchingParameters());
                    for (int site = 0; site < fixedModifications.length; site++) {
                        String modName = fixedModifications[site];
                        if (modName != null && displayParameters.isDisplayedPTM(modName)) {
                            for (int index : indexesOnProtein) {
                                if (site == 0) {
                                    fixedPtms.put(site + index, modName);
                                } else if (site == peptide.getSequence().length() + 1) {
                                    fixedPtms.put(site + index - 2, modName);
                                } else {
                                    fixedPtms.put(site + index - 1, modName);
                                }
                            }
                        }
                    }
                }
            }
            for (int aa = 0; aa < sequence.length(); aa++) {
                String modName = fixedPtms.get(aa);
                for (String variablePTM : psPtmScores.getModificationsAtRepresentativeSite(aa)) {
                    if (displayParameters.isDisplayedPTM(variablePTM)) {
                        modName = variablePTM;
                        break;
                    }
                }
                for (String variablePTM : psPtmScores.getConfidentModificationsAt(aa)) {
                    if (displayParameters.isDisplayedPTM(variablePTM)) {
                        modName = variablePTM;
                        break;
                    }
                }
                if (modName != null) {
                    // add the non-modified area
                    if (unmodifiedCounter > 0) {
                        data = new ArrayList<>(1);
                        data.add(Double.valueOf(unmodifiedCounter));
                        sparklineDataseriesPtm = new JSparklinesDataSeries(data, new Color(0, 0, 0, 0), null);
                        sparkLineDataSeriesPtm.add(sparklineDataseriesPtm);
                    }
                    // @TODO: what about multiple ptms on the same residue..?
                    // if (psPtmScores.getMainModificationsAt(aa).size() > 1) {
                    // for (int i=0; i<psPtmScores.getMainModificationsAt(aa).size(); i++) {
                    // psPtmScores.getMainModificationsAt(aa).get(i);
                    // }
                    // }
                    Color ptmColor = new Color(peptideShakerGUI.getIdentificationParameters().getSearchParameters().getModificationParameters().getColor(modName));
                    if (ptmColor == null) {
                        ptmColor = Color.lightGray;
                    }
                    ArrayList<ResidueAnnotation> annotations = new ArrayList<>(1);
                    // @TODO: note that terminal ptms are annotated one residue too early or too late...
                    annotations.add(new ResidueAnnotation(modName + " (" + (aa + 1) + ")", 0l, false));
                    proteinTooltips.put(sparkLineDataSeriesPtm.size(), annotations);
                    data = new ArrayList<>(1);
                    data.add(Double.valueOf(1));
                    sparklineDataseriesPtm = new JSparklinesDataSeries(data, ptmColor, null);
                    sparkLineDataSeriesPtm.add(sparklineDataseriesPtm);
                    // reset the non-modified area counter
                    unmodifiedCounter = 0;
                } else {
                    unmodifiedCounter++;
                }
            }
            if (unmodifiedCounter > 0) {
                // add the remaining non-modified area
                data = new ArrayList<>();
                data.add(Double.valueOf(unmodifiedCounter));
                sparklineDataseriesPtm = new JSparklinesDataSeries(data, new Color(0, 0, 0, 0), null);
                sparkLineDataSeriesPtm.add(sparklineDataseriesPtm);
            }
            ptmSequencePanel = new ProteinSequencePanel(Color.WHITE);
            ptmChart = ptmSequencePanel.getSequencePlot(this, new JSparklinesDataset(sparkLineDataSeriesPtm), proteinTooltips, false, false);
            sequencePtmsPanel.removeAll();
            sequencePtmsPanel.add(ptmChart);
            sequencePtmsPanel.revalidate();
            sequencePtmsPanel.repaint();
        } catch (ClassCastException e) {
        // ignore   @TODO: this should not happen, but can happen if the table does not update fast enough for the filtering
        }
    }
}
Also used : JSparklinesDataset(no.uib.jsparklines.data.JSparklinesDataset) ResidueAnnotation(eu.isas.peptideshaker.gui.protein_sequence.ResidueAnnotation) DisplayParameters(eu.isas.peptideshaker.preferences.DisplayParameters) Identification(com.compomics.util.experiment.identification.Identification) SelfUpdatingTableModel(com.compomics.util.gui.tablemodels.SelfUpdatingTableModel) Peptide(com.compomics.util.experiment.biology.proteins.Peptide) JSparklinesDataSeries(no.uib.jsparklines.data.JSparklinesDataSeries) ProteinSequencePanel(eu.isas.peptideshaker.gui.protein_sequence.ProteinSequencePanel) PSModificationScores(com.compomics.util.experiment.identification.peptide_shaker.PSModificationScores)

Example 2 with JSparklinesDataSeries

use of no.uib.jsparklines.data.JSparklinesDataSeries in project peptide-shaker by compomics.

the class OverviewPanel method updateSequenceCoverage.

/**
 * Updates the sequence coverage panel.
 *
 * @param proteinAccession the protein accession
 * @param updateProtein if true, force a complete recreation of the plot
 */
private void updateSequenceCoverage(long proteinKey, String proteinAccession, boolean updateProtein) {
    // @TODO: should be in a separate thread that is possible to cancel if the selection changes
    try {
        // only need to redo this if the protein changes
        if (updateProtein || !proteinAccession.equalsIgnoreCase(currentProteinAccession) || coverage == null) {
            updateProteinSequenceCoveragePanelTitle(proteinAccession);
            updatePtmCoveragePlot(proteinAccession);
            updatePeptideVariationsCoveragePlot(proteinAccession);
        }
        currentProteinAccession = proteinAccession;
        SearchParameters searchParameters = peptideShakerGUI.getIdentificationParameters().getSearchParameters();
        ArrayList<Integer> selectedPeptideStart = new ArrayList<>();
        int selectionLength = 0;
        if (peptideTable.getSelectedRow() != -1) {
            SelfUpdatingTableModel tableModel = (SelfUpdatingTableModel) peptideTable.getModel();
            int peptideIndex = tableModel.getViewIndex(peptideTable.getSelectedRow());
            long peptideKey = peptideKeys[peptideIndex];
            PeptideMatch peptideMatch = peptideShakerGUI.getIdentification().getPeptideMatch(peptideKey);
            String peptideSequence = peptideMatch.getPeptide().getSequence();
            selectionLength = peptideSequence.length();
            try {
                for (int startIndex : peptideMatch.getPeptide().getProteinMapping().get(currentProteinAccession)) {
                    selectedPeptideStart.add(startIndex);
                }
            } catch (Exception e) {
            // ignore errors due to the user switching too quickly between rows. seems to solve themselves anyway
            }
        }
        IdentificationFeaturesGenerator identificationFeaturesGenerator = peptideShakerGUI.getIdentificationFeaturesGenerator();
        int[] validationCoverage;
        if (coverageShowAllPeptidesJRadioButtonMenuItem.isSelected()) {
            validationCoverage = identificationFeaturesGenerator.getAACoverage(proteinKey);
        } else {
            validationCoverage = identificationFeaturesGenerator.estimateAACoverage(proteinKey, coverageShowEnzymaticPeptidesOnlyJRadioButtonMenuItem.isSelected());
        }
        double minHeight = 0.2, maxHeight = 1;
        NonSymmetricalNormalDistribution peptideLengthDistribution = peptideShakerGUI.getMetrics().getPeptideLengthDistribution();
        if (peptideLengthDistribution != null) {
            double medianLength = peptideLengthDistribution.getMean();
            maxHeight = (1 - minHeight) * peptideLengthDistribution.getProbabilityAt(medianLength);
        }
        double[] coverageLikelihood = identificationFeaturesGenerator.getCoverableAA(proteinKey);
        double[] coverageHeight = new double[coverageLikelihood.length];
        for (int i = 0; i < coverageLikelihood.length; i++) {
            double p = coverageLikelihood[i];
            coverageHeight[i] = minHeight + p / maxHeight;
        }
        HashMap<Integer, Color> colors = new HashMap<>();
        colors.put(MatchValidationLevel.confident.getIndex(), peptideShakerGUI.getSparklineColor());
        colors.put(MatchValidationLevel.doubtful.getIndex(), peptideShakerGUI.getUtilitiesUserParameters().getSparklineColorDoubtful());
        colors.put(MatchValidationLevel.not_validated.getIndex(), peptideShakerGUI.getSparklineColorNonValidated());
        colors.put(MatchValidationLevel.none.getIndex(), peptideShakerGUI.getSparklineColorNotFound());
        int userSelectionIndex = 0;
        while (colors.containsKey(userSelectionIndex)) {
            userSelectionIndex++;
        }
        // @TODO: use non hard coded value
        colors.put(userSelectionIndex, Color.blue);
        int[] coverageColor = validationCoverage.clone();
        for (int aaStart : selectedPeptideStart) {
            for (int aa = aaStart; aa < aaStart + selectionLength; aa++) {
                coverageColor[aa] = userSelectionIndex;
            }
        }
        // Dirty fix until the width of the sparkline can change
        int transparentIndex = userSelectionIndex + 1;
        colors.put(userSelectionIndex + 1, new Color(0, 0, 0, 0));
        for (int aa = 0; aa < coverageHeight.length; aa++) {
            if (coverageColor[aa] == MatchValidationLevel.none.getIndex()) {
                if (coverageLikelihood[aa] < 0.01 || !coverageShowPossiblePeptidesJCheckBoxMenuItem.isSelected()) {
                    // NOTE: if the fix is removed, make sure that this line is kept!!!
                    coverageColor[aa] = transparentIndex;
                }
            }
        }
        // create the coverage plot
        ArrayList<JSparklinesDataSeries> sparkLineDataSeriesCoverage = ProteinSequencePanel.getSparkLineDataSeriesCoverage(coverageHeight, coverageColor, colors);
        HashMap<Integer, ArrayList<ResidueAnnotation>> proteinTooltips = peptideShakerGUI.getDisplayFeaturesGenerator().getResidueAnnotation(proteinKey, peptideShakerGUI.getIdentificationParameters().getSequenceMatchingParameters(), identificationFeaturesGenerator, peptideShakerGUI.getMetrics(), peptideShakerGUI.getIdentification(), coverageShowAllPeptidesJRadioButtonMenuItem.isSelected(), searchParameters, coverageShowEnzymaticPeptidesOnlyJRadioButtonMenuItem.isSelected());
        // Dirty fix for a bloc-level annotation
        HashMap<Integer, ArrayList<ResidueAnnotation>> blocTooltips = new HashMap<>();
        int aaCpt = 0, blocCpt = 0;
        for (JSparklinesDataSeries jSparklinesDataSeries : sparkLineDataSeriesCoverage) {
            double sparkLineLength = jSparklinesDataSeries.getData().get(0);
            ArrayList<ResidueAnnotation> blocAnnotation = new ArrayList<>();
            for (int j = 0; j < sparkLineLength; j++, aaCpt++) {
                ArrayList<ResidueAnnotation> aaAnnotation = proteinTooltips.get(aaCpt);
                if (aaAnnotation != null) {
                    for (ResidueAnnotation residueAnnotation : aaAnnotation) {
                        if (!blocAnnotation.contains(residueAnnotation)) {
                            blocAnnotation.add(residueAnnotation);
                        }
                    }
                }
            }
            blocTooltips.put(blocCpt, blocAnnotation);
            blocCpt++;
        }
        proteinSequencePanel = new ProteinSequencePanel(Color.WHITE);
        coverageChart = proteinSequencePanel.getSequencePlot(this, new JSparklinesDataset(sparkLineDataSeriesCoverage), blocTooltips, true, true);
        // make sure that the range is the same for all the sequence annotation charts
        coverageChart.getChart().addChangeListener(new ChartChangeListener() {

            @Override
            public void chartChanged(ChartChangeEvent cce) {
                if (ptmChart != null) {
                    Range range = ((CategoryPlot) coverageChart.getChart().getPlot()).getRangeAxis().getRange();
                    ((CategoryPlot) ptmChart.getChart().getPlot()).getRangeAxis().setRange(range);
                    ptmChart.revalidate();
                    ptmChart.repaint();
                }
                if (peptideVariationsChart != null) {
                    Range range = ((CategoryPlot) coverageChart.getChart().getPlot()).getRangeAxis().getRange();
                    ((CategoryPlot) peptideVariationsChart.getChart().getPlot()).getRangeAxis().setRange(range);
                    peptideVariationsChart.revalidate();
                    peptideVariationsChart.repaint();
                }
            }
        });
        sequenceCoverageInnerPanel.removeAll();
        sequenceCoverageInnerPanel.add(coverageChart);
        sequenceCoverageInnerPanel.revalidate();
        sequenceCoverageInnerPanel.repaint();
    } catch (ClassCastException e) {
    // ignore   @TODO: this should not happen, but can happen if the table does not update fast enough for the filtering
    }
}
Also used : IdentificationFeaturesGenerator(com.compomics.util.experiment.identification.features.IdentificationFeaturesGenerator) JSparklinesDataset(no.uib.jsparklines.data.JSparklinesDataset) ResidueAnnotation(eu.isas.peptideshaker.gui.protein_sequence.ResidueAnnotation) SearchParameters(com.compomics.util.parameters.identification.search.SearchParameters) SelfUpdatingTableModel(com.compomics.util.gui.tablemodels.SelfUpdatingTableModel) NonSymmetricalNormalDistribution(com.compomics.util.math.statistics.distributions.NonSymmetricalNormalDistribution) JSparklinesDataSeries(no.uib.jsparklines.data.JSparklinesDataSeries) Range(org.jfree.data.Range) FileNotFoundException(java.io.FileNotFoundException) CategoryPlot(org.jfree.chart.plot.CategoryPlot) ProteinSequencePanel(eu.isas.peptideshaker.gui.protein_sequence.ProteinSequencePanel) ChartChangeListener(org.jfree.chart.event.ChartChangeListener) ChartChangeEvent(org.jfree.chart.event.ChartChangeEvent)

Example 3 with JSparklinesDataSeries

use of no.uib.jsparklines.data.JSparklinesDataSeries in project peptide-shaker by compomics.

the class OverviewPanel method updatePeptideVariationsCoveragePlot.

/**
 * Update the peptide variations coverage plot.
 *
 * @param proteinAccession the protein accession
 */
private void updatePeptideVariationsCoveragePlot(String proteinAccession) {
    if (proteinTable.getSelectedRow() != -1) {
        try {
            ArrayList<JSparklinesDataSeries> sparkLineDataSeriesPtm = new ArrayList<>();
            HashMap<Integer, ArrayList<ResidueAnnotation>> proteinTooltips = new HashMap<>();
            // we need to add a first empty filler as the coverage table starts at 0
            ArrayList<Double> data = new ArrayList<>();
            data.add(Double.valueOf(1));
            JSparklinesDataSeries sparklineDataseriesPtm = new JSparklinesDataSeries(data, new Color(0, 0, 0, 0), null);
            sparkLineDataSeriesPtm.add(sparklineDataseriesPtm);
            Identification identification = peptideShakerGUI.getIdentification();
            String sequence = peptideShakerGUI.getSequenceProvider().getSequence(proteinAccession);
            int unmodifiedCounter = 0;
            // get the variants
            HashMap<Integer, String> variantMapping = new HashMap<>();
            DisplayParameters displayParameters = peptideShakerGUI.getDisplayParameters();
            // see if fixed ptms are displayed
            if (displayParameters.getDisplayedModifications().size() != peptideShakerGUI.getIdentificationParameters().getSearchParameters().getModificationParameters().getVariableModifications().size()) {
                for (long peptideKey : peptideKeys) {
                    PeptideMatch peptideMatch = identification.getPeptideMatch(peptideKey);
                    Peptide peptide = peptideMatch.getPeptide();
                    HashMap<String, HashMap<Integer, PeptideVariantMatches>> allVariants = peptide.getVariantMatches();
                    if (allVariants != null && allVariants.containsKey(proteinAccession)) {
                        HashMap<Integer, PeptideVariantMatches> peptideVariants = allVariants.get(proteinAccession);
                        for (Integer peptideStart : peptideVariants.keySet()) {
                            PeptideVariantMatches peptideVariantMatches = peptideVariants.get(peptideStart);
                            HashMap<Integer, Variant> variants = peptideVariantMatches.getVariantMatches();
                            for (Integer site : variants.keySet()) {
                                Variant variant = variants.get(site);
                                variantMapping.put(site + peptideStart - 1, variant.getDescription());
                            }
                        }
                    }
                }
            }
            for (int aa = 1; aa < sequence.length(); aa++) {
                String variantName = variantMapping.get(aa + 1);
                if (variantName != null) {
                    // add the unmodified area
                    if (unmodifiedCounter > 0) {
                        data = new ArrayList<>(1);
                        data.add(Double.valueOf(unmodifiedCounter));
                        sparklineDataseriesPtm = new JSparklinesDataSeries(data, new Color(0, 0, 0, 0), null);
                        sparkLineDataSeriesPtm.add(sparklineDataseriesPtm);
                    }
                    // @TODO: get different colors for the different variant types?
                    // @TODO: what about multiple variants on the same residue..?
                    Color ptmColor = Color.ORANGE;
                    ArrayList<ResidueAnnotation> annotations = new ArrayList<>(1);
                    annotations.add(new ResidueAnnotation(variantName + " (" + aa + ")", 0l, false));
                    proteinTooltips.put(sparkLineDataSeriesPtm.size(), annotations);
                    data = new ArrayList<>(1);
                    data.add(Double.valueOf(1));
                    sparklineDataseriesPtm = new JSparklinesDataSeries(data, ptmColor, null);
                    sparkLineDataSeriesPtm.add(sparklineDataseriesPtm);
                    // reset the unmodified area counter
                    unmodifiedCounter = 0;
                } else {
                    unmodifiedCounter++;
                }
            }
            if (unmodifiedCounter > 0) {
                // add the remaining unmodified area
                data = new ArrayList<>();
                data.add(Double.valueOf(unmodifiedCounter));
                sparklineDataseriesPtm = new JSparklinesDataSeries(data, new Color(0, 0, 0, 0), null);
                sparkLineDataSeriesPtm.add(sparklineDataseriesPtm);
            }
            peptideVariationSequencePanel = new ProteinSequencePanel(Color.WHITE);
            peptideVariationsChart = peptideVariationSequencePanel.getSequencePlot(this, new JSparklinesDataset(sparkLineDataSeriesPtm), proteinTooltips, false, false);
            sequenceVariationsPanel.removeAll();
            sequenceVariationsPanel.add(peptideVariationsChart);
            sequenceVariationsPanel.revalidate();
            sequenceVariationsPanel.repaint();
        } catch (ClassCastException e) {
        // ignore   @TODO: this should not happen, but can happen if the
        // table does not update fast enough for the filtering
        }
    }
}
Also used : JSparklinesDataset(no.uib.jsparklines.data.JSparklinesDataset) ResidueAnnotation(eu.isas.peptideshaker.gui.protein_sequence.ResidueAnnotation) DisplayParameters(eu.isas.peptideshaker.preferences.DisplayParameters) Identification(com.compomics.util.experiment.identification.Identification) Peptide(com.compomics.util.experiment.biology.proteins.Peptide) JSparklinesDataSeries(no.uib.jsparklines.data.JSparklinesDataSeries) Variant(com.compomics.util.experiment.biology.variants.Variant) ProteinSequencePanel(eu.isas.peptideshaker.gui.protein_sequence.ProteinSequencePanel)

Example 4 with JSparklinesDataSeries

use of no.uib.jsparklines.data.JSparklinesDataSeries in project peptide-shaker by compomics.

the class ProteinSequencePanel method getSequencePlot.

/**
 * Returns a sequence plot as a ChartPanel.
 *
 * @param aProteinSequencePanelParent the protein sequence panel parent
 * @param sparklineDataset the dataset
 * @param proteinAnnotations the protein annotations
 * @param addReferenceLine if true, a reference line is added
 * @param allowZooming if true, the user can zoom in the created plot/chart
 * @return a sequence plot
 */
public ChartPanel getSequencePlot(ProteinSequencePanelParent aProteinSequencePanelParent, JSparklinesDataset sparklineDataset, HashMap<Integer, ArrayList<ResidueAnnotation>> proteinAnnotations, boolean addReferenceLine, boolean allowZooming) {
    this.proteinSequencePanelParent = aProteinSequencePanelParent;
    DefaultCategoryDataset barChartDataset = new DefaultCategoryDataset();
    StackedBarRenderer renderer = new StackedBarRenderer();
    renderer.setShadowVisible(false);
    CategoryToolTipGenerator myTooltips = new ProteinAnnotations(proteinAnnotations);
    // add the data
    for (int i = 0; i < sparklineDataset.getData().size(); i++) {
        JSparklinesDataSeries sparklineDataSeries = sparklineDataset.getData().get(i);
        for (int j = 0; j < sparklineDataSeries.getData().size(); j++) {
            barChartDataset.addValue(sparklineDataSeries.getData().get(j), "" + i, "" + j);
            renderer.setSeriesPaint(i, sparklineDataSeries.getSeriesColor());
            renderer.setSeriesToolTipGenerator(i, myTooltips);
        }
    }
    // create the chart
    JFreeChart chart = ChartFactory.createStackedBarChart(null, null, null, barChartDataset, PlotOrientation.HORIZONTAL, false, false, false);
    // fine tune the chart properites
    CategoryPlot plot = chart.getCategoryPlot();
    // remove space before/after the domain axis
    plot.getDomainAxis().setUpperMargin(0);
    plot.getDomainAxis().setLowerMargin(0);
    // remove space before/after the range axis
    plot.getRangeAxis().setUpperMargin(0);
    plot.getRangeAxis().setLowerMargin(0);
    renderer.setRenderAsPercentages(true);
    renderer.setBaseToolTipGenerator(new IntervalCategoryToolTipGenerator());
    // add the dataset to the plot
    plot.setDataset(barChartDataset);
    // hide unwanted chart details
    plot.getRangeAxis().setVisible(false);
    plot.getDomainAxis().setVisible(false);
    plot.setRangeGridlinesVisible(false);
    plot.setDomainGridlinesVisible(false);
    // add a reference line in the middle of the dataset
    if (addReferenceLine) {
        DefaultCategoryDataset referenceLineDataset = new DefaultCategoryDataset();
        referenceLineDataset.addValue(1.0, "A", "B");
        plot.setDataset(1, referenceLineDataset);
        LayeredBarRenderer referenceLineRenderer = new LayeredBarRenderer();
        referenceLineRenderer.setSeriesBarWidth(0, referenceLineWidth);
        referenceLineRenderer.setSeriesFillPaint(0, referenceLineColor);
        referenceLineRenderer.setSeriesPaint(0, referenceLineColor);
        plot.setRenderer(1, referenceLineRenderer);
    }
    // set up the chart renderer
    plot.setRenderer(0, renderer);
    // hide the outline
    chart.getPlot().setOutlineVisible(false);
    // make sure the background is the same as the panel
    chart.getPlot().setBackgroundPaint(backgroundColor);
    chart.setBackgroundPaint(backgroundColor);
    final HashMap<Integer, ArrayList<ResidueAnnotation>> blockTooltips = proteinAnnotations;
    // create the chart panel
    chartPanel = new ChartPanel(chart);
    chartPanel.addChartMouseListener(new ChartMouseListener() {

        @Override
        public void chartMouseClicked(ChartMouseEvent cme) {
            if (cme.getEntity() != null && cme.getTrigger().getButton() == MouseEvent.BUTTON1) {
                ((CategoryItemEntity) cme.getEntity()).getDataset();
                Integer blockNumber = Integer.valueOf((String) ((CategoryItemEntity) cme.getEntity()).getRowKey());
                ArrayList<ResidueAnnotation> annotation = blockTooltips.get(blockNumber);
                if (annotation != null) {
                    proteinSequencePanelParent.annotationClicked(annotation, cme);
                }
            }
        }

        @Override
        public void chartMouseMoved(ChartMouseEvent cme) {
            cme.getTrigger().getComponent().setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
            if (cme.getEntity() != null && cme.getEntity() instanceof CategoryItemEntity) {
                ((CategoryItemEntity) cme.getEntity()).getDataset();
                Integer blockNumber = Integer.valueOf((String) ((CategoryItemEntity) cme.getEntity()).getRowKey());
                ArrayList<ResidueAnnotation> annotation = blockTooltips.get(blockNumber);
                if (annotation != null && !annotation.isEmpty()) {
                    if (blockTooltips.get(blockNumber).get(0).clickable) {
                        cme.getTrigger().getComponent().setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
                    }
                }
            }
        }
    });
    if (!allowZooming) {
        chartPanel.setPopupMenu(null);
        chartPanel.setRangeZoomable(false);
    }
    chartPanel.setBackground(backgroundColor);
    return chartPanel;
}
Also used : IntervalCategoryToolTipGenerator(org.jfree.chart.labels.IntervalCategoryToolTipGenerator) StackedBarRenderer(org.jfree.chart.renderer.category.StackedBarRenderer) ArrayList(java.util.ArrayList) JSparklinesDataSeries(no.uib.jsparklines.data.JSparklinesDataSeries) CategoryPlot(org.jfree.chart.plot.CategoryPlot) LayeredBarRenderer(org.jfree.chart.renderer.category.LayeredBarRenderer) IntervalCategoryToolTipGenerator(org.jfree.chart.labels.IntervalCategoryToolTipGenerator) CategoryToolTipGenerator(org.jfree.chart.labels.CategoryToolTipGenerator) DefaultCategoryDataset(org.jfree.data.category.DefaultCategoryDataset) CategoryItemEntity(org.jfree.chart.entity.CategoryItemEntity)

Example 5 with JSparklinesDataSeries

use of no.uib.jsparklines.data.JSparklinesDataSeries in project peptide-shaker by compomics.

the class GOEAPanel method displayResults.

/**
 * Update the GO mappings.
 */
public void displayResults() {
    if (peptideShakerGUI.getIdentification() != null) {
        GeneMaps geneMaps = peptideShakerGUI.getGeneMaps();
        if (geneMaps.hasGoMappings()) {
            progressDialog = new ProgressDialogX(peptideShakerGUI, Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker.gif")), Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker-orange.gif")), true);
            progressDialog.setTitle("Getting GO Mappings. Please Wait...");
            progressDialog.setPrimaryProgressCounterIndeterminate(true);
            new Thread(new Runnable() {

                public void run() {
                    try {
                        progressDialog.setVisible(true);
                    } catch (IndexOutOfBoundsException e) {
                    // ignore
                    }
                }
            }, "ProgressDialog").start();
            new Thread("GoThread") {

                @Override
                public void run() {
                    // clear old table
                    DefaultTableModel dm = (DefaultTableModel) goMappingsTable.getModel();
                    dm.getDataVector().removeAllElements();
                    dm.fireTableDataChanged();
                    TreeMap<String, Integer> datasetGoTermUsage = new TreeMap<>();
                    try {
                        progressDialog.setTitle("Importing GO (1/3). Please Wait...");
                        GoMapping backgroundGoMapping = new GoMapping();
                        Integer taxon = null;
                        IdentificationParameters identificationParameters = peptideShakerGUI.getIdentificationParameters();
                        GeneParameters genePreferences = identificationParameters.getGeneParameters();
                        if (genePreferences != null) {
                            taxon = genePreferences.getBackgroundSpecies();
                        }
                        if (taxon == null) {
                            FastaSummary fastaSummary = FastaSummary.getSummary(peptideShakerGUI.getProjectDetails().getFastaFile(), identificationParameters.getFastaParameters(), progressDialog);
                            BackgroundSpeciesDialog backgroundSpeciesDialog = new BackgroundSpeciesDialog(peptideShakerGUI, genePreferences, fastaSummary);
                            if (!backgroundSpeciesDialog.isCanceled()) {
                                genePreferences = backgroundSpeciesDialog.getGeneParameters();
                                identificationParameters.setGeneParameters(genePreferences);
                                taxon = genePreferences.getBackgroundSpecies();
                            }
                        }
                        if (taxon != null) {
                            SpeciesFactory speciesFactory = SpeciesFactory.getInstance();
                            String ensemblDatasetName = speciesFactory.getEnsemblDataset(taxon);
                            File goMappingFile = ProteinGeneDetailsProvider.getGoMappingFile(ensemblDatasetName);
                            backgroundGoMapping.loadMappingsFromFile(goMappingFile, progressDialog);
                            GoDomains goDomains = new GoDomains();
                            File goDomainsFile = ProteinGeneDetailsProvider.getGoDomainsFile();
                            goDomains.laodMappingFromFile(goDomainsFile, progressDialog);
                            Identification identification = peptideShakerGUI.getIdentification();
                            progressDialog.setTitle("Getting GO Mappings (2/3). Please Wait...");
                            progressDialog.setPrimaryProgressCounterIndeterminate(false);
                            progressDialog.setMaxPrimaryProgressCounter(identification.getProteinIdentification().size());
                            progressDialog.setValue(0);
                            int totalNumberOfGoMappedProteinsInProject = 0;
                            ProteinMatchesIterator proteinMatchesIterator = identification.getProteinMatchesIterator(progressDialog);
                            ProteinMatch proteinMatch;
                            while ((proteinMatch = proteinMatchesIterator.next()) != null) {
                                PSParameter psParameter = (PSParameter) proteinMatch.getUrParam(PSParameter.dummy);
                                if (psParameter.getMatchValidationLevel().isValidated() && !proteinMatch.isDecoy() && !psParameter.getHidden()) {
                                    String mainMatch = proteinMatch.getLeadingAccession();
                                    HashSet<String> goTerms = backgroundGoMapping.getGoAccessions(mainMatch);
                                    if (goTerms != null && !goTerms.isEmpty()) {
                                        totalNumberOfGoMappedProteinsInProject++;
                                        for (String goTerm : goTerms) {
                                            Integer usage = datasetGoTermUsage.get(goTerm);
                                            if (usage == null) {
                                                usage = 0;
                                            }
                                            datasetGoTermUsage.put(goTerm, usage + 1);
                                        }
                                    }
                                }
                                if (progressDialog.isRunCanceled()) {
                                    return;
                                }
                                progressDialog.increasePrimaryProgressCounter();
                            }
                            ArrayList<String> termNamesMapped = backgroundGoMapping.getSortedTermNames();
                            int nBackgroundProteins = backgroundGoMapping.getProteinToGoMap().size();
                            progressDialog.setTitle("Creating GO Plots (3/3). Please Wait...");
                            progressDialog.setValue(0);
                            progressDialog.setMaxPrimaryProgressCounter(termNamesMapped.size());
                            // update the table
                            Double maxLog2Diff = 0.0;
                            ArrayList<Integer> indexes = new ArrayList<>();
                            ArrayList<Double> pValues = new ArrayList<>();
                            // display the number of go mapped proteins
                            goProteinCountLabel.setText("[GO Proteins: Ensembl: " + nBackgroundProteins + ", Project: " + totalNumberOfGoMappedProteinsInProject + "]");
                            boolean goDomainChanged = false;
                            for (String goTermName : termNamesMapped) {
                                if (progressDialog.isRunCanceled()) {
                                    break;
                                }
                                String goAccession = backgroundGoMapping.getTermAccession(goTermName);
                                Integer frequencyBackground = backgroundGoMapping.getProteinAccessions(goAccession).size();
                                Integer frequencyDataset = 0;
                                Double percentDataset = 0.0;
                                if (datasetGoTermUsage.get(goAccession) != null) {
                                    frequencyDataset = datasetGoTermUsage.get(goAccession);
                                    percentDataset = ((double) frequencyDataset) * 100 / totalNumberOfGoMappedProteinsInProject;
                                }
                                Double percentAll = ((double) frequencyBackground) * 100 / nBackgroundProteins;
                                Double pValue = new HypergeometricDistributionImpl(// population size
                                nBackgroundProteins, // number of successes
                                frequencyBackground, // sample size
                                totalNumberOfGoMappedProteinsInProject).probability(frequencyDataset);
                                Double log2Diff = Math.log(percentDataset / percentAll) / Math.log(2);
                                if (!log2Diff.isInfinite() && Math.abs(log2Diff) > maxLog2Diff) {
                                    maxLog2Diff = Math.abs(log2Diff);
                                }
                                String goDomain = goDomains.getTermDomain(goAccession);
                                if (goDomain == null) {
                                    // URL to the JSON file for the given GO term
                                    URL u = new URL("https://www.ebi.ac.uk/QuickGO/services/ontology/go/terms/" + goAccession);
                                    JsonMarshaller jsonMarshaller = new JsonMarshaller();
                                    QuickGoTerm result = (QuickGoTerm) jsonMarshaller.fromJson(QuickGoTerm.class, u);
                                    // get the domain
                                    for (DummyResults tempResult : result.results) {
                                        goDomain = tempResult.aspect;
                                    }
                                    // add the domain to the list
                                    goDomains.addDomain(goAccession, goDomain);
                                    goDomainChanged = true;
                                }
                                // add the data points for the first data series
                                ArrayList<Double> dataAll = new ArrayList<>();
                                dataAll.add(percentAll);
                                ArrayList<Double> dataDataset = new ArrayList<>();
                                dataDataset.add(percentDataset);
                                // create a JSparklineDataSeries
                                JSparklinesDataSeries sparklineDataseriesAll = new JSparklinesDataSeries(dataAll, Color.RED, "All");
                                JSparklinesDataSeries sparklineDataseriesDataset = new JSparklinesDataSeries(dataDataset, peptideShakerGUI.getSparklineColor(), "Dataset");
                                // add the data series to JSparklineDataset
                                ArrayList<JSparklinesDataSeries> sparkLineDataSeries = new ArrayList<>();
                                sparkLineDataSeries.add(sparklineDataseriesAll);
                                sparkLineDataSeries.add(sparklineDataseriesDataset);
                                JSparklinesDataset dataset = new JSparklinesDataset(sparkLineDataSeries);
                                pValues.add(pValue);
                                indexes.add(goMappingsTable.getRowCount());
                                ((DefaultTableModel) goMappingsTable.getModel()).addRow(new Object[] { goMappingsTable.getRowCount() + 1, peptideShakerGUI.getDisplayFeaturesGenerator().addGoLink(goAccession), goTermName, goDomain, percentAll, percentDataset, dataset, new ValueAndBooleanDataPoint(log2Diff, false), pValue, true });
                                progressDialog.increasePrimaryProgressCounter();
                            }
                            if (indexes.isEmpty()) {
                                progressDialog.setRunCanceled();
                            }
                            int significantCounter = 0;
                            double significanceLevel = 0.05;
                            if (onePercentRadioButton.isSelected()) {
                                significanceLevel = 0.01;
                            }
                            if (!progressDialog.isRunCanceled()) {
                                ((DefaultTableModel) goMappingsTable.getModel()).fireTableDataChanged();
                                // correct the p-values for multiple testing using benjamini-hochberg
                                sortPValues(pValues, indexes);
                                ((ValueAndBooleanDataPoint) ((DefaultTableModel) goMappingsTable.getModel()).getValueAt(indexes.get(0), goMappingsTable.getColumn("Log2 Diff").getModelIndex())).setSignificant(pValues.get(0) < significanceLevel);
                                ((DefaultTableModel) goMappingsTable.getModel()).setValueAt(new XYDataPoint(pValues.get(0), pValues.get(0)), indexes.get(0), goMappingsTable.getColumn("p-value").getModelIndex());
                                if (pValues.get(0) < significanceLevel) {
                                    significantCounter++;
                                }
                                for (int i = 1; i < pValues.size(); i++) {
                                    if (progressDialog.isRunCanceled()) {
                                        break;
                                    }
                                    double tempPvalue = pValues.get(i) * pValues.size() / (pValues.size() - i);
                                    // have to check if the correction results in a p-value bigger than 1
                                    if (tempPvalue > 1) {
                                        tempPvalue = 1;
                                    }
                                    ((ValueAndBooleanDataPoint) ((DefaultTableModel) goMappingsTable.getModel()).getValueAt(indexes.get(i), goMappingsTable.getColumn("Log2 Diff").getModelIndex())).setSignificant(tempPvalue < significanceLevel);
                                    ((DefaultTableModel) goMappingsTable.getModel()).setValueAt(new XYDataPoint(tempPvalue, tempPvalue), indexes.get(i), goMappingsTable.getColumn("p-value").getModelIndex());
                                    if (tempPvalue < significanceLevel) {
                                        significantCounter++;
                                    }
                                }
                            }
                            if (!progressDialog.isRunCanceled()) {
                                ((TitledBorder) mappingsPanel.getBorder()).setTitle(PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING + "Gene Ontology Mappings (" + significantCounter + "/" + goMappingsTable.getRowCount() + ")" + PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING);
                                mappingsPanel.repaint();
                                progressDialog.setPrimaryProgressCounterIndeterminate(true);
                                // set the preferred size of the accession column
                                Integer width = ProteinTableModel.getPreferredAccessionColumnWidth(goMappingsTable, goMappingsTable.getColumn("GO Accession").getModelIndex(), 6, peptideShakerGUI.getMetrics().getMaxProteinAccessionLength());
                                if (width != null) {
                                    goMappingsTable.getColumn("GO Accession").setMinWidth(width);
                                    goMappingsTable.getColumn("GO Accession").setMaxWidth(width);
                                } else {
                                    goMappingsTable.getColumn("GO Accession").setMinWidth(15);
                                    goMappingsTable.getColumn("GO Accession").setMaxWidth(Integer.MAX_VALUE);
                                }
                                maxLog2Diff = Math.ceil(maxLog2Diff);
                                goMappingsTable.getColumn("Log2 Diff").setCellRenderer(new JSparklinesBarChartTableCellRenderer(PlotOrientation.HORIZONTAL, -maxLog2Diff, maxLog2Diff, Color.RED, peptideShakerGUI.getSparklineColor(), Color.lightGray, 0));
                                ((JSparklinesBarChartTableCellRenderer) goMappingsTable.getColumn("Log2 Diff").getCellRenderer()).showNumberAndChart(true, TableProperties.getLabelWidth());
                                // update the plots
                                updateGoPlots();
                                // enable the contextual export options
                                exportMappingsJButton.setEnabled(true);
                                exportPlotsJButton.setEnabled(true);
                                peptideShakerGUI.setUpdated(PeptideShakerGUI.GO_ANALYSIS_TAB_INDEX, true);
                            }
                            if (goDomainChanged && goDomainsFile.exists()) {
                                goDomains.saveMapping(goDomainsFile);
                            }
                            progressDialog.setRunFinished();
                        }
                    } catch (Exception e) {
                        progressDialog.setRunFinished();
                        peptideShakerGUI.catchException(e);
                    }
                }
            }.start();
        }
    }
}
Also used : JSparklinesDataset(no.uib.jsparklines.data.JSparklinesDataset) DefaultTableModel(javax.swing.table.DefaultTableModel) Identification(com.compomics.util.experiment.identification.Identification) FastaSummary(com.compomics.util.experiment.io.biology.protein.FastaSummary) URL(java.net.URL) GeneParameters(com.compomics.util.parameters.identification.advanced.GeneParameters) IdentificationParameters(com.compomics.util.parameters.identification.IdentificationParameters) JSparklinesBarChartTableCellRenderer(no.uib.jsparklines.renderers.JSparklinesBarChartTableCellRenderer) GoDomains(com.compomics.util.experiment.biology.genes.go.GoDomains) XYDataPoint(no.uib.jsparklines.data.XYDataPoint) GeneMaps(com.compomics.util.experiment.biology.genes.GeneMaps) ProteinMatchesIterator(com.compomics.util.experiment.identification.matches_iterators.ProteinMatchesIterator) PSParameter(com.compomics.util.experiment.identification.peptide_shaker.PSParameter) JsonMarshaller(com.compomics.util.io.json.JsonMarshaller) ValueAndBooleanDataPoint(no.uib.jsparklines.data.ValueAndBooleanDataPoint) BackgroundSpeciesDialog(com.compomics.util.gui.parameters.identification.advanced.BackgroundSpeciesDialog) HypergeometricDistributionImpl(org.apache.commons.math.distribution.HypergeometricDistributionImpl) SpeciesFactory(com.compomics.util.experiment.biology.taxonomy.SpeciesFactory) GoMapping(com.compomics.util.experiment.biology.genes.go.GoMapping) JSparklinesDataSeries(no.uib.jsparklines.data.JSparklinesDataSeries) ProgressDialogX(com.compomics.util.gui.waiting.waitinghandlers.ProgressDialogX) ProteinMatch(com.compomics.util.experiment.identification.matches.ProteinMatch) DummyResults(eu.isas.peptideshaker.gui.tabpanels.GOEAPanel.QuickGoTerm.DummyResults)

Aggregations

JSparklinesDataSeries (no.uib.jsparklines.data.JSparklinesDataSeries)7 JSparklinesDataset (no.uib.jsparklines.data.JSparklinesDataset)5 Identification (com.compomics.util.experiment.identification.Identification)4 ProteinSequencePanel (eu.isas.peptideshaker.gui.protein_sequence.ProteinSequencePanel)4 Peptide (com.compomics.util.experiment.biology.proteins.Peptide)3 SelfUpdatingTableModel (com.compomics.util.gui.tablemodels.SelfUpdatingTableModel)3 ResidueAnnotation (eu.isas.peptideshaker.gui.protein_sequence.ResidueAnnotation)3 ArrayList (java.util.ArrayList)3 ProteinMatch (com.compomics.util.experiment.identification.matches.ProteinMatch)2 PSParameter (com.compomics.util.experiment.identification.peptide_shaker.PSParameter)2 DisplayParameters (eu.isas.peptideshaker.preferences.DisplayParameters)2 DefaultTableModel (javax.swing.table.DefaultTableModel)2 CategoryPlot (org.jfree.chart.plot.CategoryPlot)2 DefaultCategoryDataset (org.jfree.data.category.DefaultCategoryDataset)2 GeneMaps (com.compomics.util.experiment.biology.genes.GeneMaps)1 GoDomains (com.compomics.util.experiment.biology.genes.go.GoDomains)1 GoMapping (com.compomics.util.experiment.biology.genes.go.GoMapping)1 SpeciesFactory (com.compomics.util.experiment.biology.taxonomy.SpeciesFactory)1 Variant (com.compomics.util.experiment.biology.variants.Variant)1 IdentificationFeaturesGenerator (com.compomics.util.experiment.identification.features.IdentificationFeaturesGenerator)1