This is gsl-ref.info, produced by makeinfo version 4.2 from
gsl-ref.texi.

INFO-DIR-SECTION Scientific software
START-INFO-DIR-ENTRY
* gsl-ref: (gsl-ref).                   GNU Scientific Library - Reference
END-INFO-DIR-ENTRY


File: gsl-ref.info,  Node: Updating and accessing 2D histogram elements,  Next: Searching 2D histogram ranges,  Prev: Copying 2D Histograms,  Up: Histograms

Updating and accessing 2D histogram elements
============================================

   You can access the bins of a two-dimensional histogram either by
specifying a pair of (x,y) coordinates or by using the bin indices
(i,j) directly.  The functions for accessing the histogram through
(x,y) coordinates use binary searches in the x and y directions to
identify the bin which covers the appropriate range.

 - Function: int gsl_histogram2d_increment (gsl_histogram2d * H, double
          X, double Y)
     This function updates the histogram H by adding one (1.0) to the
     bin whose x and y ranges contain the coordinates (X,Y).

     If the point (x,y) lies inside the valid ranges of the histogram
     then the function returns zero to indicate success.  If (x,y) lies
     outside the limits of the histogram then the function returns
     `GSL_EDOM', and none of bins are modified.  The error handler is
     not called, since it is often necessary to compute histogram for a
     small range of a larger dataset, ignoring any coordinates outside
     the range of interest.

 - Function: int gsl_histogram2d_accumulate (gsl_histogram2d * H,
          double X, double Y, double WEIGHT)
     This function is similar to `gsl_histogram2d_increment' but
     increases the value of the appropriate bin in the histogram H by
     the floating-point number WEIGHT.

 - Function: double gsl_histogram2d_get (const gsl_histogram2d * H,
          size_t I, size_t J)
     This function returns the contents of the (I,J)th bin of the
     histogram H.  If (I,J) lies outside the valid range of indices for
     the histogram then the error handler is called with an error code
     of `GSL_EDOM' and the function returns 0.

 - Function: int gsl_histogram2d_get_xrange (const gsl_histogram2d * H,
          size_t I, double * XLOWER, double * XUPPER)
 - Function: int gsl_histogram2d_get_yrange (const gsl_histogram2d * H,
          size_t J, double * YLOWER, double * YUPPER)
     These functions find the upper and lower range limits of the Ith
     and Jth bins in the x and y directions of the histogram H.  The
     range limits are stored in XLOWER and XUPPER or YLOWER and YUPPER.
     The lower limits are inclusive (i.e. events with these
     coordinates are included in the bin) and the upper limits are
     exclusive (i.e. events with the value of the upper limit are not
     included and fall in the neighboring higher bin, if it exists).
     The functions return 0 to indicate success.  If I or J lies
     outside the valid range of indices for the histogram then the
     error handler is called with an error code of `GSL_EDOM'.

 - Function: double gsl_histogram2d_xmax (const gsl_histogram2d * H)
 - Function: double gsl_histogram2d_xmin (const gsl_histogram2d * H)
 - Function: size_t gsl_histogram2d_nx (const gsl_histogram2d * H)
 - Function: double gsl_histogram2d_ymax (const gsl_histogram2d * H)
 - Function: double gsl_histogram2d_ymin (const gsl_histogram2d * H)
 - Function: size_t gsl_histogram2d_ny (const gsl_histogram2d * H)
     These functions return the maximum upper and minimum lower range
     limits and the number of bins for the x and y directions of the
     histogram H.  They provide a way of determining these values
     without accessing the `gsl_histogram2d' struct directly.

 - Function: void gsl_histogram2d_reset (gsl_histogram2d * H)
     This function resets all the bins of the histogram H to zero.


File: gsl-ref.info,  Node: Searching 2D histogram ranges,  Next: 2D Histogram Statistics,  Prev: Updating and accessing 2D histogram elements,  Up: Histograms

Searching 2D histogram ranges
=============================

   The following functions are used by the access and update routines to
locate the bin which corresponds to a given (x\,y) coordinate.

 - Function: int gsl_histogram2d_find (const gsl_histogram2d * H,
          double X, double Y, size_t * I, size_t * J)
     This function finds and sets the indices I and J to the to the bin
     which covers the coordinates (X,Y). The bin is located using a
     binary search.  The search includes an optimization for histogram
     with uniform ranges, and will return the correct bin immediately
     in this case. If (x,y) is found then the function sets the indices
     (I,J) and returns `GSL_SUCCESS'.  If (x,y) lies outside the valid
     range of the histogram then the function returns `GSL_EDOM' and
     the error handler is invoked.


File: gsl-ref.info,  Node: 2D Histogram Statistics,  Next: 2D Histogram Operations,  Prev: Searching 2D histogram ranges,  Up: Histograms

2D Histogram Statistics
=======================

 - Function: double gsl_histogram2d_max_val (const gsl_histogram2d * H)
     This function returns the maximum value contained in the histogram
     bins.

 - Function: void gsl_histogram2d_max_bin (const gsl_histogram2d * H,
          size_t * I, size_t * J)
     This function returns the indices (I,J) of the bin containing the
     maximum value in the histogram H. In the case where several bins
     contain the same maximum value the first bin found is returned.

 - Function: double gsl_histogram2d_min_val (const gsl_histogram2d * H)
     This function returns the minimum value contained in the histogram
     bins.

 - Function: void gsl_histogram2d_min_bin (const gsl_histogram2d * H,
          size_t * I, size_t * J)
     This function returns the indices (I,J) of the bin containing the
     minimum value in the histogram H. In the case where several bins
     contain the same maximum value the first bin found is returned.

 - Function: double gsl_histogram2d_xmean (const gsl_histogram2d * H)
     This function returns the mean of the histogrammed x variable,
     where the histogram is regarded as a probability distribution.
     Negative bin values are ignored for the purposes of this
     calculation.

 - Function: double gsl_histogram2d_ymean (const gsl_histogram2d * H)
     This function returns the mean of the histogrammed y variable,
     where the histogram is regarded as a probability distribution.
     Negative bin values are ignored for the purposes of this
     calculation.

 - Function: double gsl_histogram2d_xsigma (const gsl_histogram2d * H)
     This function returns the standard deviation of the histogrammed x
     variable, where the histogram is regarded as a probability
     distribution. Negative bin values are ignored for the purposes of
     this calculation.

 - Function: double gsl_histogram2d_ysigma (const gsl_histogram2d * H)
     This function returns the standard deviation of the histogrammed y
     variable, where the histogram is regarded as a probability
     distribution. Negative bin values are ignored for the purposes of
     this calculation.

 - Function: double gsl_histogram2d_cov (const gsl_histogram2d * H)
     This function returns the covariance of the histogrammed x and y
     variables, where the histogram is regarded as a probability
     distribution. Negative bin values are ignored for the purposes of
     this calculation.

 - Function: double gsl_histogram2d_sum (const gsl_histogram2d * H)
     This function returns the sum of all bin values. Negative bin
     values are included in the sum.


File: gsl-ref.info,  Node: 2D Histogram Operations,  Next: Reading and writing 2D histograms,  Prev: 2D Histogram Statistics,  Up: Histograms

2D Histogram Operations
=======================

 - Function: int gsl_histogram2d_equal_bins_p (const gsl_histogram2d
          *H1, const gsl_histogram2d *H2)
     This function returns 1 if the all of the individual bin ranges of
     the two histograms are identical, and 0 otherwise.

 - Function: int gsl_histogram2d_add (gsl_histogram2d *H1, const
          gsl_histogram2d *H2)
     This function adds the contents of the bins in histogram H2 to the
     corresponding bins of histogram H1, i.e. h'_1(i,j) = h_1(i,j) +
     h_2(i,j).  The two histograms must have identical bin ranges.

 - Function: int gsl_histogram2d_sub (gsl_histogram2d *H1, const
          gsl_histogram2d *H2)
     This function subtracts the contents of the bins in histogram H2
     from the corresponding bins of histogram H1, i.e. h'_1(i,j) =
     h_1(i,j) - h_2(i,j).  The two histograms must have identical bin
     ranges.

 - Function: int gsl_histogram2d_mul (gsl_histogram2d *H1, const
          gsl_histogram2d *H2)
     This function multiplies the contents of the bins of histogram H1
     by the contents of the corresponding bins in histogram H2, i.e.
     h'_1(i,j) = h_1(i,j) * h_2(i,j).  The two histograms must have
     identical bin ranges.

 - Function: int gsl_histogram2d_div (gsl_histogram2d *H1, const
          gsl_histogram2d *H2)
     This function divides the contents of the bins of histogram H1 by
     the contents of the corresponding bins in histogram H2, i.e.
     h'_1(i,j) = h_1(i,j) / h_2(i,j).  The two histograms must have
     identical bin ranges.

 - Function: int gsl_histogram2d_scale (gsl_histogram2d *H, double
          SCALE)
     This function multiplies the contents of the bins of histogram H
     by the constant SCALE, i.e. h'_1(i,j) = h_1(i,j) scale.

 - Function: int gsl_histogram2d_shift (gsl_histogram2d *H, double
          OFFSET)
     This function shifts the contents of the bins of histogram H by
     the constant OFFSET, i.e. h'_1(i,j) = h_1(i,j) + offset.


File: gsl-ref.info,  Node: Reading and writing 2D histograms,  Next: Resampling from 2D histograms,  Prev: 2D Histogram Operations,  Up: Histograms

Reading and writing 2D histograms
=================================

   The library provides functions for reading and writing two
dimensional histograms to a file as binary data or formatted text.

 - Function: int gsl_histogram2d_fwrite (FILE * STREAM, const
          gsl_histogram2d * H)
     This function writes the ranges and bins of the histogram H to the
     stream STREAM in binary format.  The return value is 0 for success
     and `GSL_EFAILED' if there was a problem writing to the file.
     Since the data is written in the native binary format it may not
     be portable between different architectures.

 - Function: int gsl_histogram2d_fread (FILE * STREAM, gsl_histogram2d
          * H)
     This function reads into the histogram H from the stream STREAM in
     binary format.  The histogram H must be preallocated with the
     correct size since the function uses the number of x and y bins in
     H to determine how many bytes to read.  The return value is 0 for
     success and `GSL_EFAILED' if there was a problem reading from the
     file.  The data is assumed to have been written in the native
     binary format on the same architecture.

 - Function: int gsl_histogram2d_fprintf (FILE * STREAM, const
          gsl_histogram2d * H, const char * RANGE_FORMAT, const char *
          BIN_FORMAT)
     This function writes the ranges and bins of the histogram H
     line-by-line to the stream STREAM using the format specifiers
     RANGE_FORMAT and BIN_FORMAT.  These should be one of the `%g',
     `%e' or `%f' formats for floating point numbers.  The function
     returns 0 for success and `GSL_EFAILED' if there was a problem
     writing to the file.  The histogram output is formatted in five
     columns, and the columns are separated by spaces, like this,

          xrange[0] xrange[1] yrange[0] yrange[1] bin(0,0)
          xrange[0] xrange[1] yrange[1] yrange[2] bin(0,1)
          xrange[0] xrange[1] yrange[2] yrange[3] bin(0,2)
          ....
          xrange[0] xrange[1] yrange[ny-1] yrange[ny] bin(0,ny-1)
          
          xrange[1] xrange[2] yrange[0] yrange[1] bin(1,0)
          xrange[1] xrange[2] yrange[1] yrange[2] bin(1,1)
          xrange[1] xrange[2] yrange[1] yrange[2] bin(1,2)
          ....
          xrange[1] xrange[2] yrange[ny-1] yrange[ny] bin(1,ny-1)
          
          ....
          
          xrange[nx-1] xrange[nx] yrange[0] yrange[1] bin(nx-1,0)
          xrange[nx-1] xrange[nx] yrange[1] yrange[2] bin(nx-1,1)
          xrange[nx-1] xrange[nx] yrange[1] yrange[2] bin(nx-1,2)
          ....
          xrange[nx-1] xrange[nx] yrange[ny-1] yrange[ny] bin(nx-1,ny-1)

     Each line contains the lower and upper limits of the bin and the
     contents of the bin.  Since the upper limits of the each bin are
     the lower limits of the neighboring bins there is duplication of
     these values but this allows the histogram to be manipulated with
     line-oriented tools.

 - Function: int gsl_histogram2d_fscanf (FILE * STREAM, gsl_histogram2d
          * H)
     This function reads formatted data from the stream STREAM into the
     histogram H.  The data is assumed to be in the five-column format
     used by `gsl_histogram_fprintf'.  The histogram H must be
     preallocated with the correct lengths since the function uses the
     sizes of H to determine how many numbers to read.  The function
     returns 0 for success and `GSL_EFAILED' if there was a problem
     reading from the file.


File: gsl-ref.info,  Node: Resampling from 2D histograms,  Next: Example programs for 2D histograms,  Prev: Reading and writing 2D histograms,  Up: Histograms

Resampling from 2D histograms
=============================

   As in the one-dimensional case, a two-dimensional histogram made by
counting events can be regarded as a measurement of a probability
distribution.  Allowing for statistical error, the height of each bin
represents the probability of an event where (x,y) falls in the range
of that bin.  For a two-dimensional histogram the probability
distribution takes the form p(x,y) dx dy where,

     p(x,y) = n_{ij}/ (N A_{ij})

In this equation n_{ij} is the number of events in the bin which
contains (x,y), A_{ij} is the area of the bin and N is the total number
of events.  The distribution of events within each bin is assumed to be
uniform.

 - Data Type: gsl_histogram2d_pdf
    `size_t nx, ny'
          This is the number of histogram bins used to approximate the
          probability distribution function in the x and y directions.

    `double * xrange'
          The ranges of the bins in the x-direction are stored in an
          array of NX + 1 elements pointed to by XRANGE.

    `double * yrange'
          The ranges of the bins in the y-direction are stored in an
          array of NY + 1 pointed to by YRANGE.

    `double * sum'
          The cumulative probability for the bins is stored in an array
          of NX*NY elements pointed to by SUM.

The following functions allow you to create a `gsl_histogram2d_pdf'
struct which represents a two dimensional probability distribution and
generate random samples from it.

 - Function: gsl_histogram2d_pdf * gsl_histogram2d_pdf_alloc (size_t
          nx, size_t ny)
     This function allocates memory for a two-dimensional probability
     distribution of size NX-by-NY and returns a pointer to a newly
     initialized `gsl_histogram2d_pdf' struct. If insufficient memory
     is available a null pointer is returned and the error handler is
     invoked with an error code of `GSL_ENOMEM'.

 - Function: int gsl_histogram2d_pdf_init (gsl_histogram2d_pdf * P,
          const gsl_histogram2d * H)
     This function initializes the two-dimensional probability
     distribution calculated P from the histogram H.  If any of the
     bins of H are negative then the error handler is invoked with an
     error code of `GSL_EDOM' because a probability distribution cannot
     contain negative values.

 - Function: void gsl_histogram2d_pdf_free (gsl_histogram2d_pdf * P)
     This function frees the two-dimensional probability distribution
     function P and all of the memory associated with it.

 - Function: int gsl_histogram2d_pdf_sample (const gsl_histogram2d_pdf
          * P, double R1, double R2, double * X, double * Y)
     This function uses two uniform random numbers between zero and one,
     R1 and R2, to compute a single random sample from the
     two-dimensional probability distribution P.


File: gsl-ref.info,  Node: Example programs for 2D histograms,  Prev: Resampling from 2D histograms,  Up: Histograms

Example programs for 2D histograms
==================================

   This program demonstrates two features of two-dimensional histograms.
First a 10 by 10 2d-histogram is created with x and y running from 0 to
1.  Then a few sample points are added to the histogram, at (0.3,0.3)
with a height of 1, at (0.8,0.1) with a height of 5 and at (0.7,0.9)
with a height of 0.5.  This histogram with three events is used to
generate a random sample of 1000 simulated events, which are printed
out.

     #include <stdio.h>
     #include <gsl/gsl_rng.h>
     #include <gsl/gsl_histogram2d.h>
     
     int
     main (void)
     {
       const gsl_rng_type * T;
       gsl_rng * r;
     
       gsl_histogram2d * h = gsl_histogram2d_alloc (10, 10);
     
       gsl_histogram2d_set_ranges_uniform (h,
                                           0.0, 1.0,
                                           0.0, 1.0);
     
       gsl_histogram2d_accumulate (h, 0.3, 0.3, 1);
       gsl_histogram2d_accumulate (h, 0.8, 0.1, 5);
       gsl_histogram2d_accumulate (h, 0.7, 0.9, 0.5);
     
       gsl_rng_env_setup();
     
       T = gsl_rng_default;
       r = gsl_rng_alloc(T);
     
       {
         int i;
         gsl_histogram2d_pdf * p
           = gsl_histogram2d_pdf_alloc (h->nx, h->ny);
     
         gsl_histogram2d_pdf_init (p, h);
     
         for (i = 0; i < 1000; i++) {
           double x, y;
           double u = gsl_rng_uniform (r);
           double v = gsl_rng_uniform (r);
     
           int status
            = gsl_histogram2d_pdf_sample (p, u, v, &x, &y);
     
           printf("%g %g\n", x, y);
         }
       }
     
      return 0;
     }

The following plot shows the distribution of the simulated events.
Using a higher resolution grid we can see the original underlying
histogram and also the statistical fluctuations caused by the events
being uniformly distributed over the area of the original bins.


File: gsl-ref.info,  Node: N-tuples,  Next: Monte Carlo Integration,  Prev: Histograms,  Up: Top

N-tuples
********

   This chapter describes functions for creating and manipulating
"ntuples", sets of values associated with events.  The ntuples are
stored in files. Their values can be extracted in any combination and
"booked" in an histogram using a selection function.

   The values to be stored are held in a user-defined data structure,
and an ntuple is created associating this data structure with a file.
The values are then written to the file (normally inside a loop) using
the ntuple functions described below.

   A histogram can be created from ntuple data by providing a selection
function and a value function.  The selection function specifies whether
an event should be included in the subset to be analyzed or not. The
value function computes the entry to be added to the histogram entry
for each event.

   All the ntuple functions are defined in the header file
`gsl_ntuple.h'

* Menu:

* The ntuple struct::
* Creating ntuples::
* Opening an existing ntuple file::
* Writing ntuples::
* Reading ntuples ::
* Closing an ntuple file::
* Histogramming ntuple values::
* Example ntuple programs::
* Ntuple References and Further Reading::


File: gsl-ref.info,  Node: The ntuple struct,  Next: Creating ntuples,  Up: N-tuples

The ntuple struct
=================

   Ntuples are manipulated using the `gsl_ntuple' struct. This struct
contains information on the file where the ntuple data is stored, a
pointer to the current ntuple data row and the size of the user-defined
ntuple data struct.

     typedef struct {
         FILE * file;
         void * ntuple_data;
         size_t size;
     } gsl_ntuple;


File: gsl-ref.info,  Node: Creating ntuples,  Next: Opening an existing ntuple file,  Prev: The ntuple struct,  Up: N-tuples

Creating ntuples
================

 - Function: gsl_ntuple * gsl_ntuple_create (char * FILENAME, void *
          NTUPLE_DATA, size_t SIZE)
     This function creates a new write-only ntuple file FILENAME for
     ntuples of size SIZE and returns a pointer to the newly created
     ntuple struct.  Any existing file with the same name is truncated
     to zero length and overwritten.  A pointer to memory for the
     current ntuple row NTUPLE_DATA must be supplied - this is used to
     copy ntuples in and out of the file.


File: gsl-ref.info,  Node: Opening an existing ntuple file,  Next: Writing ntuples,  Prev: Creating ntuples,  Up: N-tuples

Opening an existing ntuple file
===============================

 - Function: gsl_ntuple * gsl_ntuple_open (char * FILENAME, void *
          NTUPLE_DATA, size_t SIZE)
     This function opens an existing ntuple file FILENAME for reading
     and returns a pointer to a corresponding ntuple struct. The
     ntuples in the file must have size SIZE.  A pointer to memory for
     the current ntuple row NTUPLE_DATA must be supplied - this is used
     to copy ntuples in and out of the file.


File: gsl-ref.info,  Node: Writing ntuples,  Next: Reading ntuples,  Prev: Opening an existing ntuple file,  Up: N-tuples

Writing ntuples
===============

 - Function: int gsl_ntuple_write (gsl_ntuple * NTUPLE)
     This function writes the current ntuple NTUPLE->NTUPLE_DATA of
     size NTUPLE->SIZE to the corresponding file.

 - Function: int gsl_ntuple_bookdata (gsl_ntuple * NTUPLE)
     This function is a synonym for `gsl_ntuple_write'


File: gsl-ref.info,  Node: Reading ntuples,  Next: Closing an ntuple file,  Prev: Writing ntuples,  Up: N-tuples

Reading ntuples
===============

 - Function: int gsl_ntuple_read (gsl_ntuple * NTUPLE)
     This function reads the current row of the ntuple file for NTUPLE
     and stores the values in NTUPLE->DATA


File: gsl-ref.info,  Node: Closing an ntuple file,  Next: Histogramming ntuple values,  Prev: Reading ntuples,  Up: N-tuples

Closing an ntuple file
======================

 - Function: int gsl_ntuple_close (gsl_ntuple * NTUPLE)
     This function closes the ntuple file NTUPLE and frees its
     associated allocated memory.


File: gsl-ref.info,  Node: Histogramming ntuple values,  Next: Example ntuple programs,  Prev: Closing an ntuple file,  Up: N-tuples

Histogramming ntuple values
===========================

   Once an ntuple has been created its contents can be histogrammed in
various ways using the function `gsl_ntuple_project'.  Two user-defined
functions must be provided, a function to select events and a function
to compute scalar values. The selection function and the value function
both accept the ntuple row as a first argument and other parameters as
a second argument.

   The "selection function" determines which ntuple rows are selected
for histogramming.  It is defined by the following struct,
     typedef struct {
       int (* function) (void * ntuple_data, void * params);
       void * params;
     } gsl_ntuple_select_fn;

The struct component FUNCTION should return a non-zero value for each
ntuple row that is to be included in the histogram.

   The "value function" computes scalar values for those ntuple rows
selected by the selection function,
     typedef struct {
       double (* function) (void * ntuple_data, void * params);
       void * params;
     } gsl_ntuple_value_fn;

In this case the struct component FUNCTION should return the value to
be added to the histogram for the ntuple row.

 - Function: int gsl_ntuple_project (gsl_histogram * H, gsl_ntuple *
          NTUPLE, gsl_ntuple_value_fn *VALUE_FUNC, gsl_ntuple_select_fn
          *SELECT_FUNC)
     This function updates the histogram H from the ntuple NTUPLE using
     the functions VALUE_FUNC and SELECT_FUNC. For each ntuple row
     where the selection function SELECT_FUNC is non-zero the
     corresponding value of that row is computed using the function
     VALUE_FUNC and added to the histogram.  Those ntuple rows where
     SELECT_FUNC returns zero are ignored.  New entries are added to
     the histogram, so subsequent calls can be used to accumulate
     further data in the same histogram.


File: gsl-ref.info,  Node: Example ntuple programs,  Next: Ntuple References and Further Reading,  Prev: Histogramming ntuple values,  Up: N-tuples

Example programs
================

   The following example programs demonstrate the use of ntuples in
managing a large dataset.  The first program creates a set of 100,000
simulated "events", each with 3 associated values (x,y,z).  These are
generated from a gaussian distribution with unit variance, for
demonstration purposes, and written to the ntuple file `test.dat'.

     #include <config.h>
     #include <gsl/gsl_ntuple.h>
     #include <gsl/gsl_rng.h>
     #include <gsl/gsl_randist.h>
     
     struct data
     {
       double x;
       double y;
       double z;
     };
     
     int
     main (void)
     {
       const gsl_rng_type * T;
       gsl_rng * r;
     
       struct data ntuple_row;
       int i;
     
       gsl_ntuple *ntuple
         = gsl_ntuple_create ("test.dat", &ntuple_row,
                              sizeof (ntuple_row));
     
       gsl_rng_env_setup();
     
       T = gsl_rng_default;
       r = gsl_rng_alloc (T);
     
       for (i = 0; i < 10000; i++)
         {
           ntuple_row.x = gsl_ran_ugaussian (r);
           ntuple_row.y = gsl_ran_ugaussian (r);
           ntuple_row.z = gsl_ran_ugaussian (r);
     
           gsl_ntuple_write (ntuple);
         }
     
       gsl_ntuple_close(ntuple);
       return 0;
     }

The next program analyses the ntuple data in the file `test.dat'.  The
analysis procedure is to compute the squared-magnitude of each event,
E^2=x^2+y^2+z^2, and select only those which exceed a lower limit of
1.5.  The selected events are then histogrammed using their E^2 values.

     #include <config.h>
     #include <math.h>
     #include <gsl/gsl_ntuple.h>
     #include <gsl/gsl_histogram.h>
     
     struct data
     {
       double x;
       double y;
       double z;
     };
     
     int sel_func (void *ntuple_data, void *params);
     double val_func (void *ntuple_data, void *params);
     
     int
     main (void)
     {
       struct data ntuple_row;
       int i;
     
       gsl_ntuple *ntuple
         = gsl_ntuple_open ("test.dat", &ntuple_row,
                            sizeof (ntuple_row));
       double lower = 1.5;
     
       gsl_ntuple_select_fn S;
       gsl_ntuple_value_fn V;
     
       gsl_histogram *h = gsl_histogram_alloc (100);
       gsl_histogram_set_ranges_uniform(h, 0.0, 10.0);
     
       S.function = &sel_func;
       S.params = &lower;
     
       V.function = &val_func;
       V.params = 0;
     
       gsl_ntuple_project (h, ntuple, &V, &S);
     
       gsl_histogram_fprintf (stdout, h, "%f", "%f");
     
       gsl_histogram_free (h);
     
       gsl_ntuple_close (ntuple);
       return 0;
     }
     
     int
     sel_func (void *ntuple_data, void *params)
     {
       double x, y, z, E, scale;
       scale = *(double *) params;
     
       x = ((struct data *) ntuple_data)->x;
       y = ((struct data *) ntuple_data)->y;
       z = ((struct data *) ntuple_data)->z;
     
       E2 = x * x + y * y + z * z;
     
       return E2 > scale;
     }
     
     double
     val_func (void *ntuple_data, void *params)
     {
       double x, y, z;
     
       x = ((struct data *) ntuple_data)->x;
       y = ((struct data *) ntuple_data)->y;
       z = ((struct data *) ntuple_data)->z;
     
       return x * x + y * y + z * z;
     }

   The following plot shows the distribution of the selected events.
Note the cut-off at the lower bound.


File: gsl-ref.info,  Node: Ntuple References and Further Reading,  Prev: Example ntuple programs,  Up: N-tuples

References and Further Reading
==============================

Further information on the use of ntuples can be found in the
documentation for the CERN packages PAW and HBOOK (available online).


File: gsl-ref.info,  Node: Monte Carlo Integration,  Next: Simulated Annealing,  Prev: N-tuples,  Up: Top

Monte Carlo Integration
***********************

   This chapter describes routines for multidimensional Monte Carlo
integration.  These include the traditional Monte Carlo method and
adaptive algorithms such as VEGAS and MISER which use importance
sampling and stratified sampling techniques. Each algorithm computes an
estimate of a multidimensional definite integral of the form,

     I = \int_xl^xu dx \int_yl^yu  dy ...  f(x, y, ...)

over a hypercubic region ((x_l,x_u), (y_l,y_u), ...) using a fixed
number of function calls.  The routines also provide a statistical
estimate of the error on the result.  This error estimate should be
taken as a guide rather than as a strict error bound -- random sampling
of the region may not uncover all the important features of the
function, resulting in an underestimate of the error.

   The functions are defined in separate header files for each routine,
`gsl_monte_plain.h', `gsl_monte_miser.h' and `gsl_monte_vegas.h'.

* Menu:

* Monte Carlo Interface::
* PLAIN Monte Carlo::
* MISER::
* VEGAS::
* Monte Carlo Examples::
* Monte Carlo Integration References and Further Reading::


File: gsl-ref.info,  Node: Monte Carlo Interface,  Next: PLAIN Monte Carlo,  Up: Monte Carlo Integration

Interface
=========

   All of the Monte Carlo integration routines use the same interface.
There is an allocator to allocate memory for control variables and
workspace, a routine to initialize those control variables, the
integrator itself, and a function to free the space when done.

   Each integration function requires a random number generator to be
supplied, and returns an estimate of the integral and its standard
deviation.  The accuracy of the result is determined by the number of
function calls specified by the user.  If a known level of accuracy is
required this can be achieved by calling the integrator several times
and averaging the individual results until the desired accuracy is
obtained.

   Random sample points used within the Monte Carlo routines are always
chosen strictly within the integration region, so that endpoint
singularities are automatically avoided.

   The function to be integrated has its own datatype, defined in the
header file `gsl_monte.h'.

 - Data Type: gsl_monte_function
     This data type defines a general function with parameters for Monte
     Carlo integration.

    `double (* F) (double * X, size_t DIM, void * PARAMS)'
          this function should return the value f(x,params) for
          argument X and parameters PARAMS, where X is an array of size
          DIM giving the coordinates of the point where the function is
          to be evaluated.

    `size_t DIM'
          the number of dimensions for X

    `void * PARAMS'
          a pointer to the parameters of the function

Here is an example for a quadratic function in two dimensions,

     f(x,y) = a x^2 + b x y + c y^2

with a = 3, b = 2, c = 1.  The following code defines a
`gsl_monte_function' `F' which you could pass to an integrator:

     struct my_f_params { double a; double b; double c; };
     
     double
     my_f (double x, size_t dim, void * p) {
        struct my_f_params * fp = (struct my_f_params *)p;
     
        if (dim != 2)
           {
             fprintf(stderr, "error: dim != 2");
             abort();
           }
     
        return  fp->a * x[0] * x[0]
                  + fp->b * x[0] * x[1]
                    + fp->c * x[1] * x[1];
     }
     
     gsl_monte_function F;
     struct my_f_params params = { 3.0, 2.0, 1.0 };
     
     F.function = &my_f;
     F.dim = 2;
     F.params = &params;

The function f(x) can be evaluated using the following macro,

     #define GSL_MONTE_FN_EVAL(F,x)
         (*((F)->function))(x,(F)->dim,(F)->params)


File: gsl-ref.info,  Node: PLAIN Monte Carlo,  Next: MISER,  Prev: Monte Carlo Interface,  Up: Monte Carlo Integration

PLAIN Monte Carlo
=================

   The plain Monte Carlo algorithm samples points randomly from the
integration region to estimate the integral and its error.  Using this
algorithm the estimate of the integral E(f; N) for N randomly
distributed points x_i is given by,

     E(f; N) = =  V <f> = (V / N) \sum_i^N f(x_i).

where V is the volume of the integration region.  The error on this
estimate \sigma(E;N) is calculated from the estimated variance of the
mean,

     \sigma^2 (E; N) = (V / N) \sum_i^N (f(x_i) -  <f>)^2

For large N this variance decreases asymptotically as var(f)/N, where
var(f) is the true variance of the function over the integration
region.  The error estimate itself should decrease as
\sigma(f)/\sqrt{N}.  The familiar law of errors decreasing as
1/\sqrt{N} applies -- to reduce the error by a factor of 10 requires a
100-fold increase in the number of sample points.

   The functions described in this section are declared in the header
file `gsl_monte_plain.h'.

 - Function: gsl_monte_plain_state * gsl_monte_plain_alloc (size_t DIM)
     This function allocates and initializes a workspace for Monte Carlo
     integration in DIM dimensions.

 - Function: int gsl_monte_plain_init (gsl_monte_plain_state* S)
     This function initializes a previously allocated integration state.
     This allows an existing workspace to be reused for different
     integrations.

 - Function: int gsl_monte_plain_integrate (gsl_monte_function * F,
          double * XL, double * XU, size_t DIM, size_t CALLS, gsl_rng *
          R, gsl_monte_plain_state * S, double * RESULT, double *
          ABSERR)
     This routines uses the plain Monte Carlo algorithm to integrate the
     function F over the DIM-dimensional hypercubic region defined by
     the lower and upper limits in the arrays XL and XU, each of size
     DIM.  The integration uses a fixed number of function calls CALLS,
     and obtains random sampling points using the random number
     generator R. A previously allocated workspace S must be supplied.
     The result of the integration is returned in RESULT, with an
     estimated absolute error ABSERR.

 - Function: void gsl_monte_plain_free (gsl_monte_plain_state* S),
     This function frees the memory associated with the integrator state
     S.


File: gsl-ref.info,  Node: MISER,  Next: VEGAS,  Prev: PLAIN Monte Carlo,  Up: Monte Carlo Integration

MISER
=====

   The MISER algorithm of Press and Farrar is based on recursive
stratified sampling.  This technique aims to reduce the overall
integration error by concentrating integration points in the regions of
highest variance.

   The idea of stratified sampling begins with the observation that for
two disjoint regions a and b with Monte Carlo estimates of the integral
E_a(f) and E_b(f) and variances \sigma_a^2(f) and \sigma_b^2(f), the
variance Var(f) of the combined estimate E(f) = (1/2) (E_a(f) + E_b(f))
is given by,

     Var(f) = (\sigma_a^2(f) / 4 N_a) + (\sigma_b^2(f) / 4 N_b)

It can be shown that this variance is minimized by distributing the
points such that,

     N_a / (N_a + N_b) = \sigma_a / (\sigma_a + \sigma_b)

Hence the smallest error estimate is obtained by allocating sample
points in proportion to the standard deviation of the function in each
sub-region.

   The MISER algorithm proceeds by bisecting the integration region
along one coordinate axis to give two sub-regions at each step.  The
direction is chosen by examining all d possible bisections and
selecting the one which will minimize the combined variance of the two
sub-regions.  The variance in the sub-regions is estimated by sampling
with a fraction of the total number of points available to the current
step.  The same procedure is then repeated recursively for each of the
two half-spaces from the best bisection. The remaining sample points are
allocated to the sub-regions using the formula for N_a and N_b.  This
recursive allocation of integration points continues down to a
user-specified depth where each sub-region is integrated using a plain
Monte Carlo estimate.  These individual values and their error
estimates are then combined upwards to give an overall result and an
estimate of its error.

   The functions described in this section are declared in the header
file `gsl_monte_miser.h'.

 - Function: gsl_monte_miser_state * gsl_monte_miser_alloc (size_t DIM)
     This function allocates and initializes a workspace for Monte Carlo
     integration in DIM dimensions.  The workspace is used to maintain
     the state of the integration.

 - Function: int gsl_monte_miser_init (gsl_monte_miser_state* S)
     This function initializes a previously allocated integration state.
     This allows an existing workspace to be reused for different
     integrations.

 - Function: int gsl_monte_miser_integrate (gsl_monte_function * F,
          double * XL, double * XU, size_t DIM, size_t CALLS, gsl_rng *
          R, gsl_monte_miser_state * S, double * RESULT, double *
          ABSERR)
     This routines uses the MISER Monte Carlo algorithm to integrate the
     function F over the DIM-dimensional hypercubic region defined by
     the lower and upper limits in the arrays XL and XU, each of size
     DIM.  The integration uses a fixed number of function calls CALLS,
     and obtains random sampling points using the random number
     generator R. A previously allocated workspace S must be supplied.
     The result of the integration is returned in RESULT, with an
     estimated absolute error ABSERR.

 - Function: void gsl_monte_miser_free (gsl_monte_miser_state* S),
     This function frees the memory associated with the integrator state
     S.

   The MISER algorithm has several configurable parameters. The
following variables can be accessed through the `gsl_monte_miser_state'
struct,

 - Variable: double estimate_frac
     This parameter specifies the fraction of the currently available
     number of function calls which are allocated to estimating the
     variance at each recursive step. The default value is 0.1.

 - Variable: size_t min_calls
     This parameter specifies the minimum number of function calls
     required for each estimate of the variance. If the number of
     function calls allocated to the estimate using ESTIMATE_FRAC falls
     below MIN_CALLS then MIN_CALLS are used instead.  This ensures
     that each estimate maintains a reasonable level of accuracy.  The
     default value of MIN_CALLS is `16 * dim'.

 - Variable: size_t min_calls_per_bisection
     This parameter specifies the minimum number of function calls
     required to proceed with a bisection step.  When a recursive step
     has fewer calls available than MIN_CALLS_PER_BISECTION it performs
     a plain Monte Carlo estimate of the current sub-region and
     terminates its branch of the recursion.  The default value of this
     parameter is `32 * min_calls'.

 - Variable: double alpha
     This parameter controls how the estimated variances for the two
     sub-regions of a bisection are combined when allocating points.
     With recursive sampling the overall variance should scale better
     than 1/N, since the values from the sub-regions will be obtained
     using a procedure which explicitly minimizes their variance.  To
     accommodate this behavior the MISER algorithm allows the total
     variance to depend on a scaling parameter \alpha,

          Var(f) = {\sigma_a \over N_a^\alpha} + {\sigma_b \over N_b^\alpha}

     The authors of the original paper describing MISER recommend the
     value \alpha = 2 as a good choice, obtained from numerical
     experiments, and this is used as the default value in this
     implementation.

 - Variable: double dither
     This parameter introduces a random fractional variation of size
     DITHER into each bisection, which can be used to break the
     symmetry of integrands which are concentrated near the exact
     center of the hypercubic integration region.  The default value of
     dither is zero, so no variation is introduced. If needed, a
     typical value of DITHER is around 0.1.


File: gsl-ref.info,  Node: VEGAS,  Next: Monte Carlo Examples,  Prev: MISER,  Up: Monte Carlo Integration

VEGAS
=====

   The VEGAS algorithm of Lepage is based on importance sampling.  It
samples points from the probability distribution described by the
function |f|, so that the points are concentrated in the regions that
make the largest contribution to the integral.

   In general, if the Monte Carlo integral of f is sampled with points
distributed according to a probability distribution described by the
function g, we obtain an estimate E_g(f; N),

     E_g(f; N) = E(f/g; N)

with a corresponding variance,

     Var_g(f; N) = Var(f/g; N)

If the probability distribution is chosen as g = |f|/I(|f|) then it can
be shown that the variance V_g(f; N) vanishes, and the error in the
estimate will be zero.  In practice it is not possible to sample from
the exact distribution g for an arbitrary function, so importance
sampling algorithms aim to produce efficient approximations to the
desired distribution.

   The VEGAS algorithm approximates the exact distribution by making a
number of passes over the integration region while histogramming the
function f. Each histogram is used to define a sampling distribution
for the next pass.  Asymptotically this procedure converges to the
desired distribution. In order to avoid the number of histogram bins
growing like K^d the probability distribution is approximated by a
separable function: g(x_1, x_2, ...) = g_1(x_1) g_2(x_2) ...  so that
the number of bins required is only Kd.  This is equivalent to locating
the peaks of the function from the projections of the integrand onto
the coordinate axes.  The efficiency of VEGAS depends on the validity
of this assumption.  It is most efficient when the peaks of the
integrand are well-localized.  If an integrand can be rewritten in a
form which is approximately separable this will increase the efficiency
of integration with VEGAS.

   VEGAS incorporates a number of additional features, and combines both
stratified sampling and importance sampling.  The integration region is
divided into a number of "boxes", with each box getting in fixed number
of points (the goal is 2).  Each box can then have a fractional number
of bins, but if bins/box is less than two, Vegas switches to a kind
variance reduction (rather than importance sampling).

 - Function: gsl_monte_vegas_state * gsl_monte_vegas_alloc (size_t DIM)
     This function allocates and initializes a workspace for Monte Carlo
     integration in DIM dimensions.  The workspace is used to maintain
     the state of the integration.

 - Function: int gsl_monte_vegas_init (gsl_monte_vegas_state* S)
     This function initializes a previously allocated integration state.
     This allows an existing workspace to be reused for different
     integrations.

 - Function: int gsl_monte_vegas_integrate (gsl_monte_function * F,
          double * XL, double * XU, size_t DIM, size_t CALLS, gsl_rng *
          R, gsl_monte_vegas_state * S, double * RESULT, double *
          ABSERR)
     This routines uses the VEGAS Monte Carlo algorithm to integrate the
     function F over the DIM-dimensional hypercubic region defined by
     the lower and upper limits in the arrays XL and XU, each of size
     DIM.  The integration uses a fixed number of function calls CALLS,
     and obtains random sampling points using the random number
     generator R. A previously allocated workspace S must be supplied.
     The result of the integration is returned in RESULT, with an
     estimated absolute error ABSERR.  The result and its error
     estimate are based on a weighted average of independent samples.
     The chi-squared per degree of freedom for the weighted average is
     returned via the state struct component, S->CHISQ, and must be
     consistent with 1 for the weighted average to be reliable.

 - Function: void gsl_monte_vegas_free (gsl_monte_vegas_state* S),
     This function frees the memory associated with the integrator state
     S.

   The VEGAS algorithm computes a number of independent estimates of the
integral internally, according to the `iterations' parameter described
below, and returns their weighted average.  Random sampling of the
integrand can occasionally produce an estimate where the error is zero,
particularly if the function is constant in some regions. An estimate
with zero error causes the weighted average to break down and must be
handled separately. In the original Fortran implementations of VEGAS
the error estimate is made non-zero by substituting a small value
(typically `1e-30').  The implementation in GSL differs from this and
avoids the use of an arbitrary constant - it either assigns the value a
weight which is the average weight of the preceding estimates or
discards it according to the following procedure,

current estimate has zero error, weighted average has finite error
     The current estimate is assigned a weight which is the average
     weight of the preceding estimates.

current estimate has finite error, previous estimates had zero error
     The previous estimates are discarded and the weighted averaging
     procedure begins with the current estimate.

current estimate has zero error, previous estimates had zero error
     The estimates are averaged using the arithmetic mean, but no error
     is computed.

   The VEGAS algorithm is highly configurable. The following variables
can be accessed through the `gsl_monte_vegas_state' struct,

 - Variable: double result
 - Variable: double sigma
     These parameters contain the raw value of the integral RESULT and
     its error SIGMA from the last iteration of the algorithm.

 - Variable: double chisq
     This parameter gives the chi-squared per degree of freedom for the
     weighted estimate of the integral.  The value of CHISQ should be
     close to 1.  A value of CHISQ which differs significantly from 1
     indicates that the values from different iterations are
     inconsistent.  In this case the weighted error will be
     under-estimated, and further iterations of the algorithm are
     needed to obtain reliable results.

 - Variable: double alpha
     The parameter `alpha' controls the stiffness of the rebinning
     algorithm.  It is typically set between one and two. A value of
     zero prevents rebinning of the grid.  The default value is 1.5.

 - Variable: size_t iterations
     The number of iterations to perform for each call to the routine.
     The default value is 5 iterations.

 - Variable: int stage
     Setting this determines the "stage" of the calculation.  Normally,
     `stage = 0' which begins with a new uniform grid and empty weighted
     average.  Calling vegas with `stage = 1' retains the grid from the
     previous run but discards the weighted average, so that one can
     "tune" the grid using a relatively small number of points and then
     do a large run with `stage = 1' on the optimized grid.  Setting
     `stage = 2' keeps the grid and the weighted average from the
     previous run, but may increase (or decrease) the number of
     histogram bins in the grid depending on the number of calls
     available.  Choosing `stage = 3' enters at the main loop, so that
     nothing is changed, and is equivalent to performing additional
     iterations in a previous call.

 - Variable: int mode
     The possible choices are `GSL_VEGAS_MODE_IMPORTANCE',
     `GSL_VEGAS_MODE_STRATIFIED', `GSL_VEGAS_MODE_IMPORTANCE_ONLY'.
     This determines whether VEGAS will use importance sampling or
     stratified sampling, or whether it can pick on its own.  In low
     dimensions VEGAS uses strict stratified sampling (more precisely,
     stratified sampling is chosen if there are fewer than 2 bins per
     box).

 - Variable: int verbose
 - Variable: FILE * ostream
     These parameters set the level of information printed by VEGAS. All
     information is written to the stream OSTREAM.  The default setting
     of VERBOSE is `-1', which turns off all output.  A VERBOSE value
     of `0' prints summary information about the weighted average and
     final result, while a value of `1' also displays the grid
     coordinates.  A value of `2' prints information from the rebinning
     procedure for each iteration.

