(* 	$Id: ex2.ml,v 1.4 2004-11-22 19:54:26 chris_77 Exp $	 *)
open Printf
open Parse_args
module P = Gnuplot.Array

let pi = 4. *. atan 1.

(* Angle in degrees of the vector (x,y) with the x axis *)
let deg_angle x y = 180. /. pi *. atan2 y x

let () =
  (* Log plot with different scales. *)
  let n = 101 in
  let freq = Array.make n 0.
  and ampl = Array.make n 0.
  and phase = Array.make n 0. in
  for i = 0 to n - 1 do
    freq.(i) <- 10.**(-2. +. float i /. 20.);
    ampl.(i) <- 20. *. log10(1. /. sqrt(1. +. freq.(i) *. freq.(i)));
    phase.(i) <- -180. /. pi *. atan freq.(i)
  done;

  let g = P.init ?offline:(offline 1) (device 1) in
  P.title g "Single Pole Low-Pass filter";
  P.xlabel g "Frequency";
  (* 1st plot *)
  P.env g ~xlog:true (1.E-2) (1.E3) (-80.) 0.;
  P.pen g 1;
  P.ylabel g "Amplitude (dB)";
  P.xy g freq ampl;
  P.text g (10.**1.6) (-30.) ~rotate:(-40.) "-20 dB/decade";
  (* 2nd plot -- we use the second y axis *)
  P.win g (1.E-2) (1.E3) (-100.) 0.;
  P.box g ~x:[] ~y:[P.tics ~which:[2] ~step:10. ();
                    P.labels ~which:[2] ()];
  P.pen g 2;
  P.ylabel g "Phase shift (degrees)";
  P.xy g freq phase;
  P.close g


module G = Gnuplot.Bigarray
open Bigarray

let () =
  (* Histogram of binomial distribution.  (Illustrate how to plot
     Bigarrays.) *)
  let p = 0.2 (* probability of success of a single trial *)
  and n = 15  (* number of trials *) in
  let x = Array1.create float64 c_layout (n+1)
  and y = Array1.create float64 c_layout (n+1) in
  let nf = float n in
  let mean = nf *. p
  and sigma = sqrt(nf *. p *. (1. -. p))
  and nchooseu = ref 1. in
  for i = 0 to n do
    let u = float i in
    x.{i} <- (u -. mean) /. sigma;
    y.{i} <- sigma *. !nchooseu *. p**u *. (1. -. p)**(nf -. u);
    nchooseu := !nchooseu *. (nf -. u) /. (u +. 1.);
  done;
  let pi = 4. *. atan 1. in
  let gauss x = 1. /. sqrt(2. *. pi) *. exp(-.(x**2.)/.2.) in
  let a = (nf -. mean) /. sigma in
  (* You can mix freely calls to functions of [Gnuplot.Bigarray] and
     of [Gnuplot.Array]*)
  let g = P.init (device 2) in
  P.box g;
  P.title g (sprintf "Bin(p=%g,n=%i) --> Gauss" p n);
  P.pen g 1;
  P.pen_width g 2.;
  G.bin g x y;
  G.pen g 3;
  G.fx g gauss (-. a) a;
  G.close g
