/**********************************************************************
# Copyright (c) EWA Systems Inc. 1998 - 2005 All Rights Reserved
#               No part of this program may be photocopied, reproduced,
#               or translated to another programming language without
#               the prior written consent of EWA Systems.
**********************************************************************/

package com.ewasystems.chart.test;

import java.awt.Color;
import java.util.Random;
import com.ewasystems.chart.AxesXY;
import com.ewasystems.chart.Chart;
import com.ewasystems.chart.ChartData;
import com.ewasystems.chart.ChartFunction;
import com.ewasystems.chart.JFrameChart;
import com.ewasystems.chart.bar.ChartBar;

/**
 * <p>Title: Sample Histogram</p>
 * <p>Copyright: (c) 1998 - 2005</p>
 * <p>Company: EWA Systems, Inc.</p>
 * @author Lincoln Evans-Beauchamp
 * @version 1.0
 */

public class SampleHistogram extends JFrameChart
{
  public SampleHistogram()
  {
    int nSamples = 1000;
    int nBins = 20;

    // Setup the bins
    double bins[] = new double[nBins];
    double dx = 6.0/nBins;
    double x[] = new double[nBins];
    for (int k = 0;  k < nBins;  k++) {
      x[k] = -3.0 + (k+0.5)*dx;
    }

    Random r = new Random(123457);
    for (int k = 0;  k < nSamples;  k++) {
      double t = r.nextGaussian();//.nextNormal();
      int j = nBins/2 + (int)Math.round(t*nBins/6-0.5);
      //int j = (int)Math.round((t-3.0-0.5*dx)/dx);
      if (j >= 0  &&  j < nBins)  bins[j]++;
    }

    // Scale the bins
    for (int k = 0;  k < nBins;  k++) {
      bins[k] /= nSamples*dx;
    }

    // create the chart
    Chart chart = getChart();

    chart.getChartTitle().setTitle("Normal Distribution");
    chart.getChartLegend().setPaint(true);
    chart.getChartLegend().setViewport(0.7, 1.0, 0.7, 0.8);
    chart.getChartLegend().setFillOutlineType(chart.FILL_TYPE_NONE);

    AxesXY barAxes = new AxesXY(chart);
    ChartBar bar = new ChartBar(barAxes, x, bins);
    bar.setBarType(bar.BAR_TYPE_VERTICAL);
    bar.setFillColor(Color.green);
    bar.setBarWidth(0.5*dx);
    bar.setTitle("Random Samples");

    // plot the expected curve
    ChartFunction f = new ChartFunction() {
      public double f(double x) {
        return Math.exp(-0.5*x*x)/Math.sqrt(2.0*Math.PI);
      }
    };
    AxesXY funcAxes = new AxesXY(chart);
    funcAxes.getAxisX().setPaint(false);
    funcAxes.getAxisY().setPaint(false);
    funcAxes.getAxisY().setWindow(0d, .5d);
    ChartData data = new ChartData(funcAxes, f, -3.0, 3.0);
    data.setLineColor(Color.blue);
    data.setTitle("Exact Curve");
    data.setLineWidth(2.0f);
  }

  public static void main(String argv[])
  {
    new SampleHistogram().setVisible(true);
  }

  public String toString()
      {return "Sample Histogram";}
}
