/**
   * Creates a sample dataset for testing.
   *
   * @return A sample dataset.
   */
  public DefaultXYDataset createSampleDataset1() {
    DefaultXYDataset d = new DefaultXYDataset();
    double[] x1 = new double[] {1.0, 2.0, 3.0};
    double[] y1 = new double[] {4.0, 5.0, 6.0};
    double[][] data1 = new double[][] {x1, y1};
    d.addSeries("S1", data1);

    double[] x2 = new double[] {1.0, 2.0, 3.0};
    double[] y2 = new double[] {4.0, 5.0, 6.0};
    double[][] data2 = new double[][] {x2, y2};
    d.addSeries("S2", data2);
    return d;
  }
  /**
   * Create a XYDataset based on the given arguments.
   *
   * @param name The name
   * @param timeValues The timevalues
   * @param values the values
   * @return a DefaultXYDataset.
   */
  private XYDataset createXYDataSet(String name, double[] timeValues, double[] values) {

    DefaultXYDataset ds = new DefaultXYDataset();
    ds.addSeries(name, new double[][] {timeValues, values});

    return ds;
  }
  /** Confirm that cloning works. */
  public void testCloning() {
    DefaultXYDataset d1 = new DefaultXYDataset();
    DefaultXYDataset d2 = null;
    try {
      d2 = (DefaultXYDataset) d1.clone();
    } catch (CloneNotSupportedException e) {
      e.printStackTrace();
    }
    assertTrue(d1 != d2);
    assertTrue(d1.getClass() == d2.getClass());
    assertTrue(d1.equals(d2));

    // try a dataset with some content...
    double[] x1 = new double[] {1.0, 2.0, 3.0};
    double[] y1 = new double[] {4.0, 5.0, 6.0};
    double[][] data1 = new double[][] {x1, y1};
    d1.addSeries("S1", data1);
    try {
      d2 = (DefaultXYDataset) d1.clone();
    } catch (CloneNotSupportedException e) {
      e.printStackTrace();
    }
    assertTrue(d1 != d2);
    assertTrue(d1.getClass() == d2.getClass());
    assertTrue(d1.equals(d2));

    // check that the clone doesn't share the same underlying arrays.
    x1[1] = 2.2;
    assertFalse(d1.equals(d2));
    x1[1] = 2.0;
    assertTrue(d1.equals(d2));
  }
  private static void addSeriesToDefaultXYDataset(
      ValueSource valueSource, int seriesIdx, PlotInstance plotInstance, DefaultXYDataset dataset)
      throws ChartPlottimeException {
    final int xIdx = 0;
    final int yIdx = 1;

    ValueSourceData valueSourceData = plotInstance.getPlotData().getValueSourceData(valueSource);
    assertMaxValueCountNotExceededOrThrowException(valueSourceData);

    GroupCellSeriesData dataForAllGroupCells = valueSourceData.getSeriesDataForAllGroupCells();
    GroupCellKeyAndData groupCellKeyAndData =
        dataForAllGroupCells.getGroupCellKeyAndData(seriesIdx);

    GroupCellKey groupCellKey = groupCellKeyAndData.getKey();
    GroupCellData groupCellData = groupCellKeyAndData.getData();

    // create series name
    GroupCellKey groupCellKeyClone = (GroupCellKey) groupCellKey.clone();
    String seriesName =
        generateSeriesName(
            valueSource, groupCellKeyClone, plotInstance.getCurrentPlotConfigurationClone());
    String differenceName = "__&%" + seriesName + "%&__";

    Map<PlotDimension, double[]> mainData =
        groupCellData.getDataForUsageType(SeriesUsageType.MAIN_SERIES);
    double[] xValues = mainData.get(PlotDimension.DOMAIN);
    double[] yValues = mainData.get(PlotDimension.VALUE);

    double[][] mainSeries = new double[2][xValues.length];
    mainSeries[xIdx] = xValues;
    mainSeries[yIdx] = yValues;
    dataset.addSeries(seriesName, mainSeries);

    if (valueSource.getSeriesFormat().getUtilityUsage() == IndicatorType.DIFFERENCE) {
      double[] differenceValues =
          valueSourceData.getAbsoluteUtilityValues(groupCellKeyAndData, true);
      if (differenceValues == null) {
        throw new ChartPlottimeException(
            "undefined_series", valueSource.toString(), SeriesUsageType.INDICATOR_1);
      }
      double[][] differenceSeries = new double[2][xValues.length];
      differenceSeries[xIdx] = xValues;
      differenceSeries[yIdx] = differenceValues;
      dataset.addSeries(differenceName, differenceSeries);
    }
  }
  /** Confirm that the equals method can distinguish all the required fields. */
  public void testEquals() {

    DefaultXYDataset d1 = new DefaultXYDataset();
    DefaultXYDataset d2 = new DefaultXYDataset();
    assertTrue(d1.equals(d2));
    assertTrue(d2.equals(d1));

    double[] x1 = new double[] {1.0, 2.0, 3.0};
    double[] y1 = new double[] {4.0, 5.0, 6.0};
    double[][] data1 = new double[][] {x1, y1};
    double[] x2 = new double[] {1.0, 2.0, 3.0};
    double[] y2 = new double[] {4.0, 5.0, 6.0};
    double[][] data2 = new double[][] {x2, y2};
    d1.addSeries("S1", data1);
    assertFalse(d1.equals(d2));
    d2.addSeries("S1", data2);
    assertTrue(d1.equals(d2));
  }
  /** Some tests for the addSeries() method. */
  public void testAddSeries() {
    DefaultXYDataset d = new DefaultXYDataset();
    d.addSeries("S1", new double[][] {{1.0}, {2.0}});
    assertEquals(1, d.getSeriesCount());
    assertEquals("S1", d.getSeriesKey(0));

    // check that adding a series will overwrite the old series
    d.addSeries("S1", new double[][] {{11.0}, {12.0}});
    assertEquals(1, d.getSeriesCount());
    assertEquals(12.0, d.getYValue(0, 0), EPSILON);

    // check null key
    boolean pass = false;
    try {
      d.addSeries(null, new double[][] {{1.0}, {2.0}});
    } catch (IllegalArgumentException e) {
      pass = true;
    }
    assertTrue(pass);
  }
Example #7
0
  private XYDataset createDataset(Table tbl) {
    DefaultXYDataset dataset = new DefaultXYDataset();

    if (tbl == null) return dataset;

    int xIndex = findColumnIndex(tbl, DATA_COL_X, DATA_COL_KEY, 0);
    /** If only one column, use it for Y */
    if (tbl.getRows().getSchema().size() == 1) xIndex = -1;
    int yIndex = findRangeIndex(tbl, DATA_COL_Y, DATA_COL_VALUE, xIndex);
    int lblIndex = findColumnIndex(tbl, StyleConstants.LABEL);

    xyItems = scanXY(tbl, xIndex, yIndex, lblIndex);
    double[][] xy = extractXYArray(xyItems);
    dataset.addSeries(param.getSeriesKey(0), xy);

    return dataset;
  }
  private XYDataset createDataSet(List<Pair<Integer, Integer>> list) {
    DefaultXYDataset dataSet = new DefaultXYDataset();

    int i = 0;
    int j = 0;
    double[][] values = new double[2][2 * list.size()];
    for (Pair<Integer, Integer> pair : list) {
      int count = pair.getFirst();
      int num = pair.getSecond();
      values[0][j] = Double.valueOf(i);
      values[1][j++] = Double.valueOf(count);
      i += num;
      values[0][j] = Double.valueOf(i - 1);
      values[1][j++] = Double.valueOf(count);
    }
    dataSet.addSeries("", values);

    return dataSet;
  }
  /** Serialize an instance, restore it, and check for equality. */
  public void testSerialization() {

    DefaultXYDataset d1 = new DefaultXYDataset();
    DefaultXYDataset d2 = null;

    try {
      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      ObjectOutput out = new ObjectOutputStream(buffer);
      out.writeObject(d1);
      out.close();

      ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()));
      d2 = (DefaultXYDataset) in.readObject();
      in.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    assertEquals(d1, d2);

    // try a dataset with some content...
    double[] x1 = new double[] {1.0, 2.0, 3.0};
    double[] y1 = new double[] {4.0, 5.0, 6.0};
    double[][] data1 = new double[][] {x1, y1};
    d1.addSeries("S1", data1);
    try {
      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      ObjectOutput out = new ObjectOutputStream(buffer);
      out.writeObject(d1);
      out.close();

      ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()));
      d2 = (DefaultXYDataset) in.readObject();
      in.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    assertEquals(d1, d2);
  }
  public static JFreeChartWrapper regressionChart() {

    DefaultTableXYDataset ds = new DefaultTableXYDataset();

    XYSeries series;

    series = new XYSeries("BAR", false, false);
    series.add(1, 1);
    series.add(2, 4);
    series.add(3, 6);
    series.add(4, 9);
    series.add(5, 9);
    series.add(6, 11);
    ds.addSeries(series);

    JFreeChart scatterPlot =
        ChartFactory.createScatterPlot(
            "Regression", "X", "Y", ds, PlotOrientation.HORIZONTAL, true, false, false);

    XYPlot plot = (XYPlot) scatterPlot.getPlot();

    double[] regression = Regression.getOLSRegression(ds, 0);

    // regression line points

    double v1 = regression[0] + regression[1] * 1;
    double v2 = regression[0] + regression[1] * 6;

    DefaultXYDataset ds2 = new DefaultXYDataset();
    ds2.addSeries("regline", new double[][] {new double[] {1, 6}, new double[] {v1, v2}});
    plot.setDataset(1, ds2);
    plot.setRenderer(1, new XYLineAndShapeRenderer(true, false));

    JFreeChart c = new JFreeChart(plot);

    return new JFreeChartWrapper(c);
  }
Example #11
0
  /**
   * Plot the results produced by the testing methods in this class.
   *
   * @param results The results of one or more tests. They must all have the same type {@link TYPE}.
   *     If more than one result is to be plotted then only {@link TYPE#STDP} or {@link
   *     TYPE#STDP_1D} are supported, and it is assumed that they all have the same pre- and
   *     post-synaptic spike patterns.
   * @param singlePlot If plotting more than one TestResult then whether to show the results on a
   *     single plot (true) or separate plots (false).
   * @param timeResolution The time resolution which the simulation was run at.
   * @param logSpikesAndStateVariables Whether to include pre- and post-synaptic spikes and any
   *     state variables exposed by the synapse model in the plot. This is ignored if more than one
   *     result is to be plotted.
   * @param showInFrame Whether to display the result in a frame.
   */
  public static JFreeChart createChart(
      TestResults[] results,
      boolean singlePlot,
      int timeResolution,
      boolean logSpikesAndStateVariables,
      boolean showInFrame,
      String title) {
    JFreeChart resultsPlot = null;
    int resultsCount = results.length;

    // Make sure they're all the same type.
    for (int ri = 0; ri < results.length; ri++) {
      if (ri < resultsCount - 1
          && results[ri].getProperty("type") != results[ri + 1].getProperty("type")) {
        throw new IllegalArgumentException("All results must have the same type.");
      }
      if (resultsCount > 1
          && results[ri].getProperty("type") != TYPE.STDP
          && results[ri].getProperty("type") != TYPE.STDP_1D) {
        throw new IllegalArgumentException(
            "Multiple results can only be plotted for types STDP or STDP_1D.");
      }
    }

    TYPE type = (TYPE) results[0].getProperty("type");

    XYLineAndShapeRenderer xyRenderer;
    XYToolTipGenerator tooltipGen = new StandardXYToolTipGenerator();

    if (type == TYPE.STDP) {
      CombinedDomainXYPlot combinedPlot = new CombinedDomainXYPlot(new NumberAxis("t (s)"));

      if (singlePlot) { // Plot all result sets together.
        DefaultXYDataset efficacyData = new DefaultXYDataset();
        for (TestResults result : results) {
          String efficacyLabel =
              (resultsCount == 1) ? "Efficacy" : "" + result.getProperty("label");
          efficacyData.addSeries(efficacyLabel, result.getResult("Time", "Efficacy"));
        }
        xyRenderer = new XYLineAndShapeRenderer(true, false);
        xyRenderer.setBaseToolTipGenerator(tooltipGen);
        combinedPlot.add(new XYPlot(efficacyData, null, new NumberAxis("Efficacy"), xyRenderer), 4);
      } else { // Plot each result set separately.
        for (TestResults result : results) {
          DefaultXYDataset efficacyData = new DefaultXYDataset();
          String efficacyLabel =
              (resultsCount == 1) ? "Efficacy" : "" + result.getProperty("label");
          efficacyData.addSeries(efficacyLabel, result.getResult("Time", "Efficacy"));
          xyRenderer = new XYLineAndShapeRenderer(true, false);
          xyRenderer.setBaseToolTipGenerator(tooltipGen);
          combinedPlot.add(
              new XYPlot(efficacyData, null, new NumberAxis("Efficacy"), xyRenderer), 4);
        }
      }

      // Don't plot trace data for multiple tests.
      if (resultsCount == 1 && logSpikesAndStateVariables) {
        DefaultXYDataset traceData = new DefaultXYDataset();
        for (String label : results[0].getResultLabels()) {
          if (!label.startsWith("Time")
              && !label.startsWith("Efficacy")
              && !label.equals("Pre-synaptic spikes")
              && !label.equals("Post-synaptic spikes")) {
            traceData.addSeries(label, results[0].getResult("Time", label));
          }
        }
        xyRenderer = new XYLineAndShapeRenderer(true, false);
        xyRenderer.setBaseToolTipGenerator(tooltipGen);
        combinedPlot.add(new XYPlot(traceData, null, new NumberAxis("State"), xyRenderer), 3);

        DefaultXYDataset spikeData = new DefaultXYDataset();
        spikeData.addSeries(
            "Pre-synaptic spikes", results[0].getResult("Time", "Pre-synaptic spikes"));
        spikeData.addSeries(
            "Post-synaptic spikes", results[0].getResult("Time", "Post-synaptic spikes"));
        xyRenderer = new XYLineAndShapeRenderer(true, false);
        xyRenderer.setBaseToolTipGenerator(tooltipGen);
        combinedPlot.add(
            new XYPlot(spikeData, null, new NumberAxis("Pre/post potential"), xyRenderer), 3);
      }

      resultsPlot = new JFreeChart(title, null, combinedPlot, true);
      resultsPlot.setBackgroundPaint(Color.WHITE);
      resultsPlot.getPlot().setBackgroundPaint(Color.WHITE);
      ((XYPlot) resultsPlot.getPlot()).setRangeGridlinePaint(Color.LIGHT_GRAY);
      ((XYPlot) resultsPlot.getPlot()).setDomainGridlinePaint(Color.LIGHT_GRAY);

    } else if (type == TYPE.STDP_1D) {
      DecimalFormat timeFormatter = new DecimalFormat();
      timeFormatter.setMultiplier(1000);
      NumberAxis domainAxis = new NumberAxis("\u0394t (ms)");
      domainAxis.setNumberFormatOverride(timeFormatter);
      CombinedDomainXYPlot combinedPlot = new CombinedDomainXYPlot(domainAxis);

      if (singlePlot) { // Plot all result sets together.
        DefaultXYDataset efficacyData = new DefaultXYDataset();
        for (TestResults result : results) {
          String efficacyLabel =
              (resultsCount == 1) ? "Efficacy" : "" + result.getProperty("label");
          efficacyData.addSeries(efficacyLabel, result.getResult("Time delta", "Efficacy"));
        }
        xyRenderer = new XYLineAndShapeRenderer(true, false);
        xyRenderer.setBaseToolTipGenerator(tooltipGen);
        combinedPlot.add(new XYPlot(efficacyData, null, new NumberAxis("Efficacy"), xyRenderer), 4);
      } else { // Plot each result set separately.
        for (TestResults result : results) {
          DefaultXYDataset efficacyData = new DefaultXYDataset();
          String efficacyLabel =
              (resultsCount == 1) ? "Efficacy" : "" + result.getProperty("label");
          efficacyData.addSeries(efficacyLabel, result.getResult("Time delta", "Efficacy"));
          xyRenderer = new XYLineAndShapeRenderer(true, false);
          xyRenderer.setBaseToolTipGenerator(tooltipGen);
          combinedPlot.add(
              new XYPlot(efficacyData, null, new NumberAxis("Efficacy"), xyRenderer), 4);
        }
      }

      resultsPlot = new JFreeChart(title, null, combinedPlot, true);
      resultsPlot.setBackgroundPaint(Color.WHITE);
      resultsPlot.getPlot().setBackgroundPaint(Color.WHITE);
      ((XYPlot) resultsPlot.getPlot()).setRangeGridlinePaint(Color.LIGHT_GRAY);
      ((XYPlot) resultsPlot.getPlot()).setDomainGridlinePaint(Color.LIGHT_GRAY);
    } else if (type == TYPE.STDP_2D) {
      double[][] data = results[0].getResult("Time delta 1", "Time delta 2", "Efficacy");

      DefaultXYZDataset plotData = new DefaultXYZDataset();
      plotData.addSeries("Efficacy", data);

      // Set up paint scale, and convert domain axes from seconds to
      // milliseconds (XYBlockRenderer won't deal with fractional values
      // in the domain axes)
      double min = Double.MAX_VALUE, max = -min;
      double[] efficacy = data[2];
      for (int i = 0; i < data[0].length; i++) {
        if (efficacy[i] < min) min = efficacy[i];
        if (efficacy[i] > max) max = efficacy[i];

        data[0][i] = Math.round(data[0][i] * 1000);
        data[1][i] = Math.round(data[1][i] * 1000);
      }

      XYBlockRenderer renderer = new XYBlockRenderer();

      double range = Math.max(Math.abs(min), Math.abs(max));
      double rangeBase = 0;
      if (min < 0) min = -range;
      if (max > 0) max = range;
      // If the value range does not cross the zero point, don't use a zero-based range.
      if ((min > 0) || (max < 0)) {
        range = Math.abs(max - min);
        rangeBase = Math.min(Math.abs(min), Math.abs(max));
      }
      if (min >= max) {
        max = min + Double.MIN_VALUE * 10;
      }

      LookupPaintScale scale = new LookupPaintScale(min, max, Color.WHITE);
      if (min < 0) {
        for (int ci = 0; ci <= 255; ci++) {
          double v = -(ci / 255.0) * range - rangeBase;
          scale.add(v, new Color(0, ci, ci));
        }
      }
      if (max > 0) {
        for (int ci = 0; ci <= 255; ci++) {
          double v = (ci / 255.0) * range + rangeBase;
          scale.add(v, new Color(ci, ci, 0));
        }
      }
      renderer.setPaintScale(scale);
      renderer.setSeriesToolTipGenerator(0, new StandardXYZToolTipGenerator());
      int displayResolution =
          ((Integer) results[0].getProperty("display time resolution")).intValue();
      renderer.setBlockWidth(1000.0 / displayResolution);
      renderer.setBlockHeight(1000.0 / displayResolution);

      NumberAxis xAxis = new NumberAxis("\u0394t1 (ms)");
      NumberAxis yAxis = new NumberAxis("\u0394t2 (ms)");

      XYPlot plot = new XYPlot(plotData, xAxis, yAxis, renderer);
      plot.setDomainGridlinesVisible(false);

      resultsPlot = new JFreeChart(title, plot);
      resultsPlot.removeLegend();
      NumberAxis valueAxis = new NumberAxis();
      valueAxis.setLowerBound(scale.getLowerBound());
      valueAxis.setUpperBound(scale.getUpperBound());
      PaintScaleLegend legend = new PaintScaleLegend(scale, valueAxis);
      legend.setPosition(RectangleEdge.RIGHT);
      legend.setMargin(5, 5, 5, 5);
      resultsPlot.addSubtitle(legend);
    }

    if (showInFrame) {
      JFrame plotFrame = new JFrame(title);
      plotFrame.add(new ChartPanel(resultsPlot));
      plotFrame.setExtendedState(plotFrame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
      plotFrame.pack();
      plotFrame.setVisible(true);
    }

    return resultsPlot;
  }
Example #12
0
  /**
   * Draws the first n frames of the audio streams on to a chart mapping the names given to each
   * stream into the legend. Note that the legend will only be shown if there is more than one
   * stream.
   *
   * @param numFrames The number of frames to draw
   * @param colouredFrames Whether to colour individual frames
   * @param streams The audio streams and their labels
   */
  public static void drawChart(
      final int numFrames,
      final boolean colouredFrames,
      final List<IndependentPair<AudioStream, String>> streams) {
    final DefaultXYDataset ds = new DefaultXYDataset();

    for (final IndependentPair<AudioStream, String> asl : streams) {
      final AudioStream as = asl.firstObject();
      final String label = asl.secondObject();

      SampleChunk s = as.nextSampleChunk();
      SampleBuffer b = s.getSampleBuffer();

      int x = 0;
      int y = 0;
      double[][] data = new double[2][];
      if (!colouredFrames) {
        data[0] = new double[b.size() * numFrames]; // x
        data[1] = new double[b.size() * numFrames]; // y
      }

      for (int n = 0; n < numFrames; n++) {
        s = as.nextSampleChunk();
        if (s == null) break;

        // Convert sample to a XY data plot
        if (colouredFrames) {
          data = new double[2][];
          data[0] = new double[b.size()]; // x
          data[1] = new double[b.size()]; // y
          x = 0;
        }

        System.out.println("Loop " + x + " to " + (x + b.size()) + ", y = " + y);
        // Copy the value into the data series
        for (int z = x; z < x + b.size(); z++) {
          data[0][z] = b.get(z - x);
          data[1][z] = z + y;
        }

        // Add as a series if we're using coloured frames
        if (colouredFrames) {
          y += b.size();
          ds.addSeries(label + ", Frame " + n, data);
        } else x += b.size();

        // Get ready for next loop
        b = s.getSampleBuffer();
      }

      if (!colouredFrames) ds.addSeries(label, data);
    }

    final JFreeChart chart =
        ChartFactory.createXYLineChart(
            "Sample",
            "samples",
            "amplitude",
            ds,
            PlotOrientation.HORIZONTAL,
            streams.size() > 1,
            false,
            false);
    final ChartPanel chartPanel = new ChartPanel(chart, false);
    chartPanel.setPreferredSize(new Dimension(1280, 480));

    final JFrame f = new JFrame();
    f.add(chartPanel, BorderLayout.CENTER);
    f.pack();
    f.setVisible(true);
  }