/** * Some checks for the addOrUpdate() method. */ public void testAddOrUpdate() { XYSeries series = new XYSeries("S1"); XYDataItem old = series.addOrUpdate(new Long(1), new Long(2)); assertTrue(old == null); assertEquals(1, series.getItemCount()); assertEquals(new Long(2), series.getY(0)); old = series.addOrUpdate(new Long(2), new Long(3)); assertTrue(old == null); assertEquals(2, series.getItemCount()); assertEquals(new Long(3), series.getY(1)); old = series.addOrUpdate(new Long(1), new Long(99)); assertEquals(new XYDataItem(new Long(1), new Long(2)), old); assertEquals(2, series.getItemCount()); assertEquals(new Long(99), series.getY(0)); assertEquals(new Long(3), series.getY(1)); }
/** * Inits * @param fftBinSizeHz * @param freqStartMHz * @param freqStopMHz * @param spectrumInitPower * @param peaks enable calculation of peaks * @param peakFallThreshold * @param peakFalloutMillis */ public DatasetSpectrum(float fftBinSizeHz, int freqStartMHz, int freqStopMHz, float spectrumInitPower) { this.fftBinSizeHz = fftBinSizeHz; this.freqStartMHz = freqStartMHz; this.freqStartHz = freqStartMHz * 1000000l; this.freqStopMHz = freqStopMHz; this.spectrumInitPower = spectrumInitPower; int datapoints = (int) (Math.ceil(freqStopMHz - freqStartMHz) * 1000000d / fftBinSizeHz); spectrum = new float[datapoints]; Arrays.fill(spectrum, spectrumInitPower); for (int j = 0; j < 5; j++) { ArrayList<XYDataItem> list = new ArrayList<>(); for (int i = 0; i < datapoints; i++) { double freq = (freqStartHz + fftBinSizeHz * i) / 1000000; list.add(new XYDataItem(freq, 0)); } cachedDataItems.add(list); } }
protected void fillToXYSeriesPriv(XYSeries series, float[] spectrum){ series.clear(); /** * caching decreases GC usage */ boolean useCached = false; if (!useCached){ for (int i = 0; i < spectrum.length; i++) { double freq = (freqStartHz + fftBinSizeHz * i) / 1000000; series.add(freq, spectrum[i]); } } else{ ArrayList<XYDataItem> items = cachedDataItems.get(cachedDataItemsIndex); for (int i = 0; i < spectrum.length; i++) { XYDataItem item = items.get(i); item.setY(spectrum[i]); series.add(item); } cachedDataItemsIndex = (cachedDataItemsIndex+1)%cachedDataItems.size(); } }
public void GenerateModel() throws IOException { XYPointCollection points = new XYPointCollection(); XYSeries series = new XYSeries("Peptide ions"); XYSeriesCollection xySeriesCollection = new XYSeriesCollection(); for (PepIonID pepA : LCMSA.GetPepIonList().values()) { if (LCMSB.GetPepIonList().containsKey(pepA.GetKey())) { PepIonID pepB = LCMSB.GetPepIonList().get(pepA.GetKey()); points.AddPoint(pepA.GetRT(), pepB.GetRT()); series.add(new XYDataItem(pepA.GetRT(), pepB.GetRT())); } } regression = new PiecewiseRegression(parameter.MaxCurveRTRange, parameter.MaxCurveRTRange); regression.SetData(points); float R2 = regression.GetR2(); Logger.getRootLogger().info("Retention time prediction model:(" + FilenameUtils.getBaseName(LCMSA.mzXMLFileName) + "-" + FilenameUtils.getBaseName(LCMSB.mzXMLFileName) + ")..R2=" + R2 + "(No. of commonly identified peptide ions=" + points.PointCount() + ")"); GenerateRTMapPNG(xySeriesCollection, series, R2); }
public void setEnglishUnits( boolean englishUnits ) { if ( englishUnits != _englishUnits ) { _englishUnits = englishUnits; // change labels and ranges updateYAxis(); // convert existing data to new units int itemCount = _series.getItemCount(); for ( int i = 0; i < itemCount; i++ ) { XYDataItem item = (XYDataItem) _series.getDataItem( i ); if ( _englishUnits ) { item.setY( UnitsConverter.metersToFeet( item.getY().doubleValue() ) ); } else { item.setY( UnitsConverter.feetToMeters( item.getY().doubleValue() ) ); } } } }
private void doBestFit() { XYSeries dataset = betaChart.getMeanDataSet(); final ArrayList dataCopy = new ArrayList(); for ( int i = 0; i < dataset.getItemCount(); i++ ) { XYDataItem x = dataset.getDataItem( i ); dataCopy.add( new Point2D.Double( x.getX().doubleValue(), x.getY().doubleValue() ) ); } LinearRegression.Result result = LinearRegression.main( new LinearRegression.Input() { public boolean isEmpty() { return dataCopy.isEmpty(); } public Point2D readPoint() { return (Point2D) dataCopy.remove( 0 ); } } ); double x0 = getMinX( dataset ); double x1 = getMaxX( dataset ); Point2D lhs = new Point2D.Double( x0, result.evaluate( x0 ) ); Point2D rhs = new Point2D.Double( x1, result.evaluate( x1 ) ); betaChart.showLine( lhs, rhs ); DecimalFormat decimalFormat = new DecimalFormat( "0.00" ); betaText.setText( "Critical Exponent = " + decimalFormat.format( result.getSlope() ) ); }
private void updateLines() { MyMultiMap multiMap = new MyMultiMap(); for ( int i = 0; i < meanSeries.getItemCount(); i++ ) { XYDataItem item = meanSeries.getDataItem( i ); multiMap.add( item.getX(), item.getY() ); } Set keySet = multiMap.keySet(); ArrayList lits = new ArrayList( keySet ); Collections.sort( lits, new Comparator() { public int compare( Object o1, Object o2 ) { Number a = (Number) o1; Number b = (Number) o2; return Double.compare( a.doubleValue(), b.doubleValue() ); } } ); lineSeries.clear(); for ( int i = 0; i < lits.size(); i++ ) { Number key = (Number) lits.get( i ); int numValues = multiMap.numValues( key ); if ( numValues > 14 ) { lineSeries.add( key.doubleValue(), average( multiMap.getList( key ) ) ); } } }
/** * This method is the one that implements some different * aspects to the XYSeries class. */ public void add(XYDataItem item, boolean notify) { if (checkValidity(item)) { if (checkDataItem(item)) { /* Check in discarded dataset. */ if (discardedItems.indexOf(item.getX()) >= 0) { throw new SeriesException("X-value already exists."); } super.add(item, notify); } else { /* Check in main dataset. */ if (super.indexOf(item.getX()) >= 0) throw new SeriesException("X-value already exists."); discardedItems.add(item); } } }
@Override public void updateByIndex(int index, Number y) { XYDataItem existing = getDataItem(index); XYDataItem item = new XYDataItem(existing.getX(), y); if (checkValidity(item)) { if (checkDataItem(item)) super.update(index, y); else { super.remove(index); discardedItems.add(item); } } }
@Override public List getItems() { List items = new LinkedList(); for (int i = 0; i < getItemCount(); i++) { XYDataItem item = super.getDataItem(i); if (this.logYAxis && item.getY().doubleValue() <= 0) items.add(new XYDataItem(item.getX(), Double.NaN)); else items.add(new XYDataItem(item.getX(), item.getY())); } return items; }
@Override public XYDataItem remove(Number x) { XYDataItem result = null; int indexD = discardedItems.indexOf(x); int indexS = super.indexOf(x); /* If in discarded items, then remove and return this. */ if (indexD >= 0) { result = discardedItems.remove(indexD); } /* If in main items, then remove and return this. (Should not be both in discarded and main items) */ if (indexS >= 0) { result = super.remove(indexS); } return result; }
/** * Calculate avg. */ // calculating an avg value that is used for identifying the top series void calculateAvg() { long sum = 0; int count = 1; synchronized (stats) { boolean useMovingAvg = getMovingAvgFrame() > 0 && getMovingAvgFrame() < stats.size(); for (ListIterator<XYDataItem> it = stats.listIterator(); it.hasNext();) { XYDataItem xy = it.next(); sum += xy.getY().longValue(); if (useMovingAvg && count % getMovingAvgFrame() == 0 || !it.hasNext()) { double thisAvg = (double) sum / count; if (thisAvg > avg) { avg = thisAvg; } sum = 0; count = 1; } else { count++; } } } }
@Override public void populate(DefaultTableXYDataset dataset, StatsCollection statsCollection, HttpServletRequest request) { String seriesParam = ServletRequestUtils.getStringParameter(request, "sp", null); for (int i = 0; i < statNames.size(); i++) { String statName = statNames.get(i); if (seriesParam != null) { statName = MessageFormat.format(statName, seriesParam); } List<XYDataItem> stats = statsCollection.getStats(statName); if (stats != null) { String series = ServletRequestUtils.getStringParameter(request, "s" + (i + 1) + "l", "series" + i); dataset.addSeries(toSeries(series, stats)); } } }
@Override public void populate(DefaultTableXYDataset dataset, StatsCollection statsCollection, HttpServletRequest request) { // get Connector name from the request String connectorName = ServletRequestUtils.getStringParameter(request, "cn", null); // type of statistic to be displayed String statType = ServletRequestUtils.getStringParameter(request, "st", null); // Series legend String series1Legend = ServletRequestUtils.getStringParameter(request, "sl", ""); if (connectorName != null && statType != null) { List<XYDataItem> stats = statsCollection.getStats("stat.connector." + connectorName + "." + statType); if (stats != null) { dataset.addSeries(toSeries(series1Legend, stats)); } } }
/** * Builds the absolute stats. * * @param name the name * @param value the value * @param time the time * @throws InterruptedException the interrupted exception */ protected void buildAbsoluteStats(String name, long value, long time) throws InterruptedException { List<XYDataItem> stats = statsCollection.getStats(name); if (stats == null) { statsCollection.newStats(name, maxSeries); } else { XYDataItem data = new XYDataItem(time, value); statsCollection.lockForUpdate(); try { stats.add(data); houseKeepStats(stats); } finally { statsCollection.releaseLock(); } if (listeners != null) { StatsCollectionEvent event = new StatsCollectionEvent(name, data); for (StatsCollectionListener listener : listeners) { if (listener.isEnabled()) { listener.statsCollected(event); } } } } }
/** * Reads stats data from file on disk. */ @Override public synchronized void afterPropertiesSet() { int index = 0; Map<String, List<XYDataItem>> stats; while (true) { File file = index == 0 ? makeFile() : new File(makeFile().getAbsolutePath() + "." + index); stats = deserialize(file); index += 1; if (stats != null || index >= maxFiles - 1) { break; } } if (stats != null) { statsData = stats; } else { logger.debug("Stats data file not found. Empty file assumed."); } }
public TonalityPanel(MediaMatrix mat) { initComponents(); this.mat = mat; renderer.setBaseToolTipGenerator(new XYToolTipGenerator() { public String generateToolTip(XYDataset dataset, int series, int item) { final XYSeriesCollection collection = (XYSeriesCollection) dataset; final XYSeries xyseries = collection.getSeries(series); final XYDataItem xyitem = xyseries.getDataItem(item); return xyseries.getKey().toString() + ": " + xyitem.getYValue(); } }); chartPanel.setDisplayToolTips(true); chartPanel.setMaximumDrawHeight(2000); xAxis.setAutoRangeIncludesZero(false); yAxis.setAutoRangeIncludesZero(false); final Font font = new Font("SanSerif", Font.PLAIN, 14); xAxis.setLabelFont(font); yAxis.setLabelFont(font); xAxis.setTickLabelFont(font); yAxis.setTickLabelFont(font); redraw(); }
/** * Some checks for the addOrUpdate() method. */ public void testAddOrUpdate() { XYSeries series = new XYSeries("S1", true, false); XYDataItem old = series.addOrUpdate(new Long(1), new Long(2)); assertTrue(old == null); assertEquals(1, series.getItemCount()); assertEquals(new Long(2), series.getY(0)); old = series.addOrUpdate(new Long(2), new Long(3)); assertTrue(old == null); assertEquals(2, series.getItemCount()); assertEquals(new Long(3), series.getY(1)); old = series.addOrUpdate(new Long(1), new Long(99)); assertEquals(new XYDataItem(new Long(1), new Long(2)), old); assertEquals(2, series.getItemCount()); assertEquals(new Long(99), series.getY(0)); assertEquals(new Long(3), series.getY(1)); }
void calculateAvg() { long sum = 0; int count = 1; synchronized (stats) { boolean useMovingAvg = getMovingAvgFrame() > 0 && getMovingAvgFrame() < stats.size(); for (Iterator i = stats.iterator(); i.hasNext();) { XYDataItem xy = (XYDataItem) i.next(); sum += xy.getY().longValue(); if ((useMovingAvg && count % getMovingAvgFrame() == 0) || ! i.hasNext()) { double a = (double) sum / count; if (a > avg) { avg = a; } sum = 0; count = 1; } else { count++; } } } }
/** * If there is a value indicating the accumulated amount of time spent on something it is possible to build a * series of values representing the percentage of time spent on doing something. For example: * <p/> * at point T1 the system has spent A milliseconds performing tasks * at point T2 the system has spent B milliseconds performing tasks * <p/> * so between in a timeframe T2-T1 the system spent B-A milliseconds being busy. Thus (B - A)/(T2 - T1) * 100 * is the percentage of all time the system spent being busy. * * @param name * @param value time in milliseconds * @param time * @throws InterruptedException */ protected void buildTimePercentageStats(String name, long value, long time) throws InterruptedException { Entry entry = (Entry) previousData.get(name); if (entry == null) { entry = new Entry(); entry.value = value; entry.time = time; previousData.put(name, entry); } else { double valueDelta = value - entry.value; double timeDelta = time - entry.time; double statValue = valueDelta * 100 / timeDelta; statsCollection.lockForUpdate(); try { List stats = statsCollection.getStats(name); if (stats == null) { stats = statsCollection.newStats(name, maxSeries); } stats.add(stats.size(), new XYDataItem(time, statValue)); houseKeepStats(stats); } finally { statsCollection.releaseLock(); } } }
private XYIntervalSeries computeRegressionData(double xStart, double xEnd) { if (scatterpointsDataset.getItemCount(0) > 1) { final double[] coefficients = Regression.getOLSRegression(scatterpointsDataset, 0); final Function2D curve = new LineFunction2D(coefficients[0], coefficients[1]); final XYSeries regressionData = DatasetUtilities.sampleFunction2DToSeries(curve, xStart, xEnd, 100, "regression line"); final XYIntervalSeries xyIntervalRegression = new XYIntervalSeries(regressionData.getKey()); for (int i = 0; i < regressionData.getItemCount(); i++) { XYDataItem item = regressionData.getDataItem(i); final double x = item.getXValue(); final double y = item.getYValue(); xyIntervalRegression.add(x, x, x, y, y, y); } return xyIntervalRegression; } else { Dialogs.showInformation("Unable to compute regression line.\n" + "At least 2 values are needed to compute regression coefficients."); return null; } }
private XYDataset createDataset() { XYSeriesCollection result = new XYSeriesCollection(); XYSeries series = new XYSeries("P-Q"); Random rand = new Random(System.currentTimeMillis()); int nKeys = rand.nextInt(300)+1200; for (int i=0; i < nKeys; i++) { Float x = rand.nextFloat()*rand.nextInt(1000); Float y = rand.nextFloat()*rand.nextInt(1000); if (rand.nextBoolean()) { x *= -1; if (x < -100) { x = (float) -100; } } if (rand.nextBoolean()) { y *= -1; } XYDataItem item = new XYDataItem(x, y); series.add(item); } result.addSeries(series); return result; }
public double meanWindow(ArrayList<XYDataItem> data, int startAt) { /* double retVal = 0.0; int windowWidth = getNoiseSearchWindowWidth(); int i = 0; int counter = 0; int iters = 0; for(i = Math.max((int)(startAt-((windowWidth+0.5)/2)),0); i<(data.size()) && (iters<=windowWidth); i++) { double tmp = data.get(i).getY().doubleValue(); iters++; if(tmp > 0.0) { counter++; retVal += data.get(i).getY().doubleValue(); } } retVal = retVal/(double)(counter); return retVal; */ return data.get(startAt).getY().doubleValue(); }
public double getMaxYofAllDaughters() { double retVal = -1; if(getDaughters() == null || getDaughters().size() == 0) return retVal; for(MRMDaughter d: getDaughters().values()){ XYSeries xys = d.getContinDaughterData(); if(xys == null || xys.getItemCount() == 0) { continue; } for(Object o: xys.getItems()) { XYDataItem xydi = (XYDataItem)o; double curY = xydi.getY().doubleValue(); if(curY>retVal){ retVal = curY; } } } return retVal; }
public double meanWindow(ArrayList<XYDataItem> data, int startAt) { double retVal = 0.0; int windowWidth = getNoiseSearchWindowWidth(); int i = 0; int counter = 0; int iters = 0; for(i = Math.max((int)(startAt-((windowWidth+0.5)/2)),0); i<(data.size()) && (iters<=windowWidth); i++) { double tmp = data.get(i).getY().doubleValue(); iters++; if(tmp > 0.0) { counter++; retVal += data.get(i).getY().doubleValue(); } } retVal = retVal/(double)(counter); return retVal; }
public void calculateHighPoints() { //this is truly annoying: XYSeries don't have a size or isEmpty if(getGraphRegion() == null || getSegments().isEmpty()) { return; } double highx=-1,highy=-1; for(Object xydo: getGraphRegion().getItems()){ XYDataItem xydi = (XYDataItem)xydo; double curY = xydi.getY().doubleValue(); if(curY > highy){ highy = curY; highx = xydi.getX().doubleValue(); } } setHighestPointX(highx); setHighestPointY(highy); }
public double meanWindow(ArrayList<XYDataItem> data, int startAt) { double retVal = 0.0; int windowWidth = noiseSearchWindowWidth; int i = 0; int counter = 0; int iters = 0; for(i = Math.max((int)(startAt-((windowWidth+0.5)/2)),0); i<(data.size()) && (iters<=windowWidth); i++) { double tmp = data.get(i).getY().doubleValue(); iters++; if(tmp > 0.0) { counter++; retVal += data.get(i).getY().doubleValue(); } } retVal = retVal/(double)(counter); return retVal; }
/** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { final XYDataItem i1 = new XYDataItem(1.0, 1.1); final XYDataItem i2 = new XYDataItem(1.0, 1.1); assertTrue(i1.equals(i2)); assertTrue(i2.equals(i1)); i1.setY(new Double(9.9)); assertFalse(i1.equals(i2)); i2.setY(new Double(9.9)); assertTrue(i1.equals(i2)); }
/** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { XYDataItem i1 = new XYDataItem(1.0, 1.1); XYDataItem i2 = new XYDataItem(1.0, 1.1); assertTrue(i1.equals(i2)); assertTrue(i2.equals(i1)); i1.setY(new Double(9.9)); assertFalse(i1.equals(i2)); i2.setY(new Double(9.9)); assertTrue(i1.equals(i2)); }
public void GenerateModel() throws IOException { XYPointCollection points = new XYPointCollection(); XYSeries series = new XYSeries("Peptide ions"); XYSeriesCollection xySeriesCollection = new XYSeriesCollection(); FileWriter writer = new FileWriter(FilenameUtils.getFullPath(TargetLCMS.mzXMLFileName) + "/" + FilenameUtils.getBaseName(TargetLCMS.mzXMLFileName) + "_" + libManager.LibID + "_RTMapPoints.txt"); for (String pepkey : libManager.PeptideFragmentLib.keySet()) { if (TargetLCMS.GetPepIonList().containsKey(pepkey)) { PepFragmentLib peplib = libManager.GetFragmentLib(pepkey); for (float rt : peplib.RetentionTime) { float y = TargetLCMS.GetPepIonList().get(pepkey).GetRT(); points.AddPoint(rt, y); series.add(new XYDataItem(rt, y)); writer.write(rt + "\t" + y + "\n"); } } } writer.close(); regression = new PiecewiseRegression(parameter.MaxCurveRTRange, parameter.MaxCurveRTRange); regression.SetData(points); float R2 = regression.GetR2(); Logger.getRootLogger().info("Retention time prediction model:(" + FilenameUtils.getBaseName(TargetLCMS.mzXMLFileName) + "..R2=" + R2 + "(No. of commonly identified peptide ions=" + points.PointCount() + ")"); GenerateRTMapPNG(xySeriesCollection, series, R2); }
public void setEnglishUnits( boolean englishUnits ) { if ( englishUnits != _englishUnits ) { _englishUnits = englishUnits; // change labels and ranges if ( englishUnits ) { _rangeAxis.setLabel( GlaciersStrings.AXIS_ELA_ENGLISH ); _rangeAxis.setRange( ELEVATION_RANGE_ENGLISH ); } else { _rangeAxis.setLabel( GlaciersStrings.AXIS_ELA_METRIC ); _rangeAxis.setRange( ELEVATION_RANGE_METRIC ); } // convert existing data to new units int itemCount = _series.getItemCount(); for ( int i = 0; i < itemCount; i++ ) { XYDataItem item = (XYDataItem) _series.getDataItem( i ); if ( _englishUnits ) { item.setY( UnitsConverter.metersToFeet( item.getY().doubleValue() ) ); } else { item.setY( UnitsConverter.feetToMeters( item.getY().doubleValue() ) ); } } } }
public void copy() { if(xySeries == null){ return; } int[] rows = table.getSelectedRows(); StringBuffer clippy = new StringBuffer(); for(int i = 0; i < rows.length ; i++) { int row = rows[i]; if (row < xySeries.getItemCount()) { if(graph instanceof Graph){ XYDataItem item = ((PrismXYSeries)xySeries).getDataItem(row); clippy.append(item.getX()+"\t"+item.getY()+"\n"); } } else { int bufferRow = row - xySeries.getItemCount(); String x = (xAxisBuffer.get(bufferRow) == null) ? "" : xAxisBuffer.get(bufferRow).toString(); String y = (yAxisBuffer.get(bufferRow) == null) ? "" : yAxisBuffer.get(bufferRow).toString(); clippy.append(x + "\t" + y + "\n"); } } Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); StringSelection gs = new StringSelection(clippy.toString()); clipboard.setContents(gs, null); }
/** * Checks validity of XYDataItem. We do NOT allow positive or negative * infinity on x-axis, on the y-axis we allow them but replace them by NaN. * Validity means this is a value we should store, otherwise we can discard it. * @param item The item to check, may be changed. * @return True if valid, false otherwise. */ private boolean checkValidity(XYDataItem item) { if (Double.isInfinite(item.getX().doubleValue()) || Double.isNaN(item.getX().doubleValue())) return false; if (Double.isInfinite(item.getY().doubleValue())) item.setY(Double.NaN); return true; }
@Override public void update(Number x, Number y) { XYDataItem item = new XYDataItem(x,y); XYDataItem result = null; /** If this is a valid update. */ if (checkValidity(item)) { int indexD = discardedItems.indexOf(item.getX()); int indexS = super.indexOf(item.getX()); /* If in discarded items, then remove and return this. */ if (indexD >= 0) { result = discardedItems.remove(indexD); } /* If in main items, then remove and return this. (Should not be both in discarded and main items) */ if (indexS >= 0) { result = super.remove(indexS); } if (result != null) this.add(item, true); else throw new SeriesException("No observation for x = " + x); } }
@Override public XYDataItem getDataItem(int index) { XYDataItem item = super.getDataItem(index); if (this.logYAxis && item.getY().doubleValue() <= 0) return new XYDataItem(item.getX(), Double.NaN); else return item; }
/** * Check whether with the current settings this data item should be in the discarded * set or in the main dataset * @param item the XYDataItem * @return true if it should be in the main set, false otherwise */ private boolean checkDataItem(XYDataItem item) { if (this.logXAxis && item.getX().doubleValue() <= 0) return false; // If logaritmic x axis and negative or zero x value, then discard for now. if (this.logYAxis && item.getY().doubleValue() <= 0) return true; // If logaritmic y axis and negative or zero y value, then do not discard, simply return NaN. else return true; // Nothing wrong }