/* histogramn.java
 * 14/05/2000 - jpq
 * modification et ajout de main() le 07/02/18
 */

import java.awt.event.*;
import java.awt.*;
import java.applet.*;
import java.util.*;

public class histogramn extends java.applet.Applet {
  static final long serialVersionUID = 180207L;
  controles C;
  dessin D;
  table T;

  private int gpn (String s, int i) {
    try {
	  s = getParameter (s);
	  i = Integer.parseInt (s);
	}
    catch (NumberFormatException e) {}
	catch (NullPointerException e) {}
    return Math.max (i, 1);
  }

  private double gpd (String s, double d) {
    try {
	  s = getParameter (s);
	  d = Double.parseDouble (s);
	}
    catch (NumberFormatException e) {}
	catch (NullPointerException e) {}
    return d;
  }

  public void init ()
  { boolean affkhi2 = false;
    try {
	  String s = getParameter ("affkhi2");
	  affkhi2 = s.toLowerCase().equals("oui");
	}
    catch (NumberFormatException e) {}
	catch (NullPointerException e) {}
    setLayout (new BorderLayout ());
    D = new dessin (gpd ("min", -2.0), gpd ("max", 2.0), gpn ("nclasses", 10), gpn ("nvaleurs", 100), affkhi2);
    T = new table (D);
    C = new controles (D, T);
    add (C, BorderLayout.NORTH);
    add (D, BorderLayout.CENTER);
    add (T, BorderLayout.SOUTH);
  }

  public void destroy ()
  { remove (D); remove (C); remove (T); }

  public String getAppletInfo ()
  { return "histogrammes par j.-p. Quelen"; }

////////////////////////////////////////////////////////////////////////////////
protected class dessin extends Canvas {
  static final long serialVersionUID = 180207L;
  Image img;
  Graphics g;
  int w, h, hmax, nclasses, nvaleurs, histomin, histomax;
  int [] histogramme;
  double [] ref;
  int arrond = 2;
  double min, max;
  double darrond = 100.0;
  boolean retrace, affkhi2;
  String surl, message;
  donnees don;

  public dessin (double min, double max, int nclasses, int nvaleurs, boolean affkhi2)
  { this.min = min;
    this.max = max;
    this.nclasses = nclasses;
    this.nvaleurs = nvaleurs;
    this.affkhi2 = affkhi2;
    don = new donnees (nvaleurs);
    init ();
  }

  private void init ()
  { if ((histogramme == null) || (nclasses > histogramme.length))
    { histogramme = new int [nclasses];
      ref = new double [nclasses];
    }
    for (int i = 0; i < nclasses; i ++)
    { histogramme [i] = 0;
      ref [i] = min + (max - min) * i / nclasses;
    }
    hmax = 0;
    retrace = true;
  }

  private String sarrondi (double d)
  { if (arrond > 0) d = Math.floor (d * darrond) / darrond;
    return Double.toString (d);
  }

  public void update (Graphics g)
  { paint (g); }

  public void message (Graphics g, String s)
  { g.setColor (Color.black);
    g.drawString (s, 10, 10);
  }

  private void painthisto (Graphics g)
  { g.setColor (Color.black);
    g.drawRect (0, 0, w -1, h - 1);
    g.setColor (Color.blue);
    int wpas = w / nclasses;
    double hpas = (double)(h - 100) / hmax;
    for (int i = 0; i < nclasses; i ++)
    { int dy = (int)(hpas * histogramme [i]);
      g.drawRect (wpas * i, h - dy - 1, wpas, dy + 1);
    }
    g.setColor (Color.black);
    int Y = h - (int)(hpas * hmax) - 1;
    g.drawString (Integer.toString (hmax), 0, Y); 
    g.drawLine (20, Y, 40, Y);
  }

  public void paint (Graphics g1)
  { if (img == null || w != getSize().width || h != getSize().height)
    { w = getSize().width;
      h = getSize().height;
      img = createImage (w, h);
      g = img.getGraphics ();
      if (T != null) T.retrace = true;
    }
    double total = don.valeurs.length;
    if (retrace)
    { retrace = false;
      hmax = 0;
      histomin = histomax = 0;
      for (int i = 0; i < total; i ++)
      { double dv = don.valeurs [i];
        if (dv < min) histomin ++;
        else if (dv >= max) histomax ++;
        else
        { int k = 0;
          while ((k < nclasses) && (dv > ref [k])) k ++;
          histogramme [-- k] ++;
          if (histogramme [k] > hmax) hmax = histogramme [k];
        }
        g.setColor (Color.white);
        g.fillRect (0, 0, w, h);
        painthisto (g);
        g1.drawImage (img, 0, 0, this);
      }
    }
    g.setColor (Color.yellow);
    int wpas = w / nclasses;
    double hpas = (double)(h - 100) / hmax;
    for (int i = 0; i < nclasses; i ++)
    { int dy = (int)(hpas * total * don.proba (min + (max - min) * i / nclasses, min + (max - min) * (i + 1) / nclasses));
      g.drawRect (wpas * i, h - dy - 1, wpas, dy + 1);
    }
    painthisto (g);
    if (affkhi2)
    { double dpi = don.normal (min);
      double d = histomin - dpi * total;
      double khi2 = d * d / dpi;
      dpi = 1.0 - don.normal (max);
      d = histomax - dpi * total;
      khi2 += d * d / dpi;
      for (int i = 0; i < nclasses; i ++)
      { dpi = don.proba (min + (max - min) * i / nclasses, min + (max - min) * (i + 1) / nclasses);
        d = histogramme [i] - dpi * total;
        khi2 += d * d / dpi;
      }
      g.drawString ("khi2 = " + new Double(khi2 / total).toString() + "; " + Integer.toString (nclasses + 1) + " degrés de liberté", 0, 10);
    }
    g1.drawImage (img, 0, 0, this);
  }
}
////////////////////////////////////////////////////////////////////////////////
protected class controles extends Panel implements ActionListener {
  static final long serialVersionUID = 180207L;
  dessin D;
  table T;
  Font f;
  Button ok, nv;
  TextField tmin, tmax, tnclasses, tnvaleurs;

  private Label ajoutlbl (String s)
  { Label lbl = new Label (s);
    lbl.setBackground (Color.lightGray);
    lbl.setFont (f);
    return lbl;
  }

  private TextField ajouttf (int n)
  { TextField tf = new TextField (Integer.toString (n));
    tf.setFont (f);
    return tf;
  }

  private TextField ajouttfd (double d)
  { TextField tf = new TextField (new Double(d).toString ());
    tf.setFont (f);
    return tf;
  }

  private Button ajoutb (String s)
  { Button b = new Button (s);
    b.setFont (f);
    b.addActionListener (this);
    return b;
  }

  public controles (dessin D, table T)
  { this.D = D;
    this.T = T;
    setLayout (new FlowLayout());
    setBackground (Color.lightGray);
    f = new Font ("Arial", Font.PLAIN, 10);
    add (ajoutlbl ("min"));
    add (tmin = ajouttfd (D.min));
    add (ajoutlbl ("max"));
    add (tmax = ajouttfd (D.max));
    add (ajoutlbl ("classes"));
    add (tnclasses = ajouttf (D.nclasses));
    add (ok = ajoutb ("Ok"));
    add (ajoutlbl ("données"));
    add (tnvaleurs = ajouttf (D.nvaleurs));
    add (nv = ajoutb ("NV"));
  }

  public void actionPerformed (ActionEvent e)
  { if ((e.getSource () == ok) || (e.getSource () == nv))
    { if (e.getSource () == nv)
      { try { D.nvaleurs = Integer.parseInt (tnvaleurs.getText ()); }
        catch (NumberFormatException nfe) { }
        if (D.nvaleurs <= 0) D.nvaleurs = 1;
        tnvaleurs.setText (Integer.toString (D.nvaleurs));
        D.don = new donnees (D.nvaleurs);
      }
      try { D.min = new Double(tmin.getText()).doubleValue(); }
      catch (NumberFormatException nfe) { }
      try { D.max = new Double(tmax.getText()).doubleValue(); }
      catch (NumberFormatException nfe) { }
      if (D.min > D.max) { double d = D.min; D.min = D.max; D.max = d; }
      tmin.setText (new Double(D.min).toString());
      tmax.setText (new Double(D.max).toString());
      try { D.nclasses = Integer.parseInt (tnclasses.getText ()); }
      catch (NumberFormatException nfe) { }
      if (D.nclasses <= 0) D.nclasses = 1;
      tnclasses.setText (Integer.toString (D.nclasses));
      D.init ();
    }
    D.retrace = T.retrace = true;
    D.repaint ();
    T.repaint ();
  }
}

////////////////////////////////////////////////////////////////////////////////
protected class table extends Panel {
  static final long serialVersionUID = 180207L;
  TextArea ta;
  dessin D;
  boolean retrace;

  public table (dessin D)
  { this.D = D;
    setLayout (new FlowLayout());
    setBackground (Color.lightGray);
    add (ta = new TextArea ("", 3, 50, TextArea.SCROLLBARS_HORIZONTAL_ONLY));
    retrace = false;
  }

  public void paint (Graphics g)
  { if (retrace)
    { retrace = false;
      String s = "]-inf;" + D.sarrondi (D.min) + "]\t";
      for (int i = 0; i < D.nclasses; i ++) s = s + "[" + D.sarrondi (D.min + (D.max - D.min) * i / D.nclasses) + ";" + D.sarrondi (D.min + (D.max - D.min) * (i + 1) / D.nclasses) + "[\t";
      s += "]" + D.sarrondi (D.max) + ";inf[\n" + Integer.toString (D.histomin) + "\t";
      for (int i = 0; i < D.nclasses; i ++) s += Integer.toString (D.histogramme [i]) + "\t";
      s += Integer.toString (D.histomax);
      ta.setText (s);
    }
  }
}
////////////////////////////////////////////////////////////////////////////////
protected class donnees {
  static final long serialVersionUID = 180207L;
  double [] valeurs;
  Random rnd;

  public donnees (int n)
  { rnd = new Random ();
    double pi2 = 2.0 * Math.PI;
    valeurs = new double [n];
    for (int i = 0; i < n; i ++)
    { double d1 = Math.sqrt (- 2.0 * Math.log (rnd.nextDouble ()));
      double d2 = pi2 * rnd.nextDouble ();
      valeurs [i] = Math.sin (d2) * d1;
      i ++;
      if (i < n) valeurs [i] = Math.cos (d2) * d1;
    } 
  }

  public double proba (double a, double b)
  { return (a < b) ? normal (b) - normal (a) : 0.0;
  }

/**
 * Retourne l'intégrale entre - infini et x de 1 / racine(2 pi) exp (- t^2 / 2)
 * (fonction de répartition de la loi normale)
 */

  public double normal (double x)
  { if (Math.abs (x) < 0.0000001) return 0.5;
    double h [] = { 0.319382, -0.356564, 1.781478, -1.821256, 1.330274 };
    double y = Math.exp (- x * x / 2.0) * 0.39894228;
    double q = 1.0 / (1.0 + 0.2316419 * Math.abs (x));
    double som = 0.0;
    for (int i = 0; i < 5; i ++)
    { double qi = q;
      for (int j = 0; j < i; j ++) qi *= q;
      som += h [i] * qi;
    }
    return (x >= 0.0) ? 1.0 - y * som : y * som;
  }
}

////////////////////////////////////////////////////////////////////////////////

	public static void main (String [] args) {
		histogramn a = new histogramn();
		a.init ();
		a.start ();

		Frame f = new Frame ("histogramn");
		f.addWindowListener (new fermer ());
		f.add (a);
		f.setSize (500, 400);
		f.setVisible (true);
    }

// Permet la fermeture de la fenêtre contenant l'applet
	protected static final class fermer extends WindowAdapter {
		public void windowClosing (WindowEvent e) {
			System.exit (0);
		}
	}

}
