\documentclass{report}
\usepackage[dvips]{graphicx, color}
\oddsidemargin 0.5in \textwidth 5.5in \topmargin 0.0in \textheight 9.0in

\newcommand{\centertt}[1]{\begin{center}{\tt #1}\end{center}}
\newcommand{\fref}[1]{Figure~\ref{#1}}

\begin{document}
\begin{titlepage}
  \noindent
  {\Huge \textsf{Mie Scattering Utilities}}
  \hfill {\large Michael P. Schubmehl}
  \vspace{0.05in}
  \rule{5.5 in}{2 pt}
  \noindent {\large Version 1.00 \hfill \today}

  \begin{center}
  {\Huge User's Guide}

  \includegraphics{mielogo}
  \end{center}
\end{titlepage}

\tableofcontents

\chapter{Introduction}

The {\tt mietable}, {\tt fitdist}, {\tt snell}, and {\tt fitmie} programs
documented here were written for use in sizing droplets by Mie scattering
measurements. In particular, they are geared towards analyzing data from
experimental setups like the those in \fref{fig:apparatus}. To determine the
size of a cloud or suspension of droplets, scattered light is measured as a
function of angle, and the resulting data are fit to a theory curves generated
by the {\tt mietable} program. This fitting procedure is performed by one of
two programs: if the scatterers are all of a single size ({\em monodispersed}),
the {\tt fitmie} program can be used. If the scatterers are not monodispersed,
distributed fitting to a variety of distributions can be performed using the
{\tt fitdist} program. Finally, it may or may not be necessary to correct for
the presence of a cuvette full of some sort of solvent, depending on the exact
experimental configuration. This can be done with the {\tt snell} program,
which corrects Mie theory tables using Snell's law.

\begin{figure}[hbt]
  \begin{center}
  \includegraphics{apparatus}
  \end{center}
  \caption{Experimental setup for Mie scattering measurements.}
  \label{fig:apparatus}
\end{figure}

First, the {\tt mietable} program is used to generate theory tables of
scattered intensity as a function of angle for a given relative index of
refraction and a specific range of size parameters. The dimensionless {\em size
parameter} of a droplet is directly proportional to its diameter, and is
defined by
$$
                        x = \frac{\pi d n}{\lambda},
$$
where $n$ is the index of refraction of the medium surrounding the droplet, $d$
the diameter of the droplet, and $\lambda$ the wavelength of the light used for
the scattering in vacuum. These tables can be generated for any range of size
parameters and angles needed for analysis.

The tables generated by the {\tt mietable} program are not always directly
useful in analyzing experimental data, however, because they fail to account
for two important optical effects---the presence of a cuvette, and the fact
that the medium surrounding the droplets may not be the same one in which the
angle measurements are taking place. In other words, the tables need to be
adjusted using Snell's law, in the event a cuvette is present. To do this, the
tables are passed to the {\tt snell} program, which uses various aspects of the
experimental setup to numerically correct the tables for Snell's law effects.
In particular, the user must specify the distance $R$ of the detector from the
cuvette, the half-length of a cuvette side $L$, the relative index of
refraction of the medium surrounding the spheres to that in which the
measurements are taking place $n$, and the polarization of the incident light.
Options are also available to adjust the accuracy of the correction and specify
whether or not to correct for the light passing through the front and side
faces of the cuvette.

Once the tables have been adjusted, if necessary, to correspond to the
appropriate experimental setup, the experimental data can be fit to these
theory tables using either the {\tt fitmie} program or the {\tt fitdist}
program. Note that, in an experimental setup like the one shown above, there
may be other detectors used to normalize the intensity and reduce error. Any
corrections used for these effects should be applied to the data prior to
fitting. Once the data and theory tables are ready, both are passed to the
fitting routine of the user's choice.

The distributed fitting code, {\tt fitdist}, reads in experimental data and
theory tables, along with a fit file specifying the ranges of parameters to
test. It then uses one of two fitting methods---a simple exploration of
parameter space, or the more complicated, more efficient Levenberg-Marquardt
method---to determine which of the size distributions produces a Mie theory
composite that minimizes the chi-squared per degree of freedom. Detailed
results of the fit, including the data, parameter ranges, best fit, size
distribution, and Mie theory, can be output to file.

The {\tt fitmie} program, on the other hand, looks through the theory tables
and attempts to minimize one of several error quantities that can be specified.
The program can perform a least-squares fit with or without uncertainty
information, a divide-by-point fit as described in \cite{bohren}, or a simple
front-to-back fit of the ratio of forward- to backward-scattered intensity. The
user can also specify a fitting range, in order to exclude points that may
contain too much error to be useful. The output of the {\tt fitmie} program is
used to determine the size parameter of the droplets. By default, it returns
only the best fit and an estimate of the error in that fit. An option is
available, however, to output tables of chi-squared values for the data
relative to each theory table, in a form suitable for graphing. The user can
also output scaled theory tables at a particular size parameter, for use in
creating a data-theory overlay plot.

The remaining chapters of this document explain in detail how to set up and use
each of the programs, as well as how they work and how to modify them.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


\chapter{The {\tt mietable} Program}
\section{Getting Started}
The {\tt mietable} program generates tables of intensity as a function of angle
for three different polarizations of incident light---perpendicular to the
scattering plane, parallel to the scattering plane, and unpolarized. It outputs
tables for angles ranging from 0 degrees out to some user-specified maximum
angle, at all size parameters in a given interval. The user must specify the
index of refraction of the scatterers relative to the surrounding medium.

To install the program, just copy the file {\tt mietable.exe} to the desired
directory. It is recommended that the install directory be added to the
system's PATH, or that all data files are kept in the same directory as the
program. Consult your operating system's documentation for information on
adding directories to the path.

Once the program has been installed, it can be run from the command line. On a
PC running Microsoft Windows 9x, a command line can be accessed by running {\tt
command.com}. In Windows NT/2000/XP, run {\tt cmd.exe} instead. Change to the
directory where you placed the {\tt mietable} program and use the following
command to run the program:

\centertt{mietable xmin xmax xstep nr [maxangle] [anglestep] [> outputfile]}

The program's arguments are summarized in the following list.

\begin{center}
\begin{tabular}[t]{rp{4in}}
  {\tt xmin} & The smallest size parameter to include in the table. Must be a
               real value greater than zero, and in practice greater than around 0.1.\\
  {\tt xmax} & The largest size parameter to include in the table. Must be a
               real value greater than or equal to xmin, and
               in practice less than around 10,000. \\
  {\tt xstep}& Step size between consecutive size parameters in the table. Must
               be a positive real number.\\
  {\tt nr}   & Relative index of refraction of scatterers to
               surrounding medium. For example, latex spheres in water
               have $1.59/1.33 \approx 1.2$, and water droplets in air have
               $1.33/1.0 = 1.33$.\\
  {\tt [maxangle]} & Optional argument giving the maximum angle to
                     include in output. Default is 180 degrees. Must be in the
                     range 6 to 180 degrees.\\
  {\tt [anglestep]} & Optional argument giving spacing between angles. Must be
                      in the range $0.5$ to $5.0$ degrees.
\end{tabular}
\end{center}

The output of the program goes to standard output, and can thus be redirected
to an output file with the command {\tt> outputfile} in a UNIX, DOS, or Windows
environment. The format of the output is described in detail in the next
section.

Typical uses of {\tt mietable} might be

\centertt{mietable 8 14 0.1 1.33 > mietables.txt}

\centertt{mietable 1 40 0.2 1.33 70 0.5 > tables}

\noindent which generates a table of three intensities as a function of angle
(one for each polarization), for angles going from 0 to $180^\circ$ in the
first case, and from 0 to $70^\circ$ in steps of $0.5^\circ$ in the second
case. The first table would start at a size parameter of 8.0, then include size
parameters 8.1, 8.2, and so on up to a size parameter of 14.0. The second
tables would include size parameters 1, 1.2, and so forth. The index of
refraction is that of water relative to air, so these tables could both be used
to fit water droplets suspended in air. The redirect commands {\tt>
mietables.txt} and {\tt > tables} are {\em not} part of the program's syntax,
but rather Windows, DOS and UNIX commands to write the program's output into
the files {\tt mietables.txt} and {\tt tables}.

If the program encounters a problem processing the arguments, it will exit with
error status and print an abbreviated version of the argument list above.

\section{Reference} \label{sec:mietableReference}

Installation instructions and syntax for the {\tt mietable} program are
described in the Getting Started section above. This section describes the
program's output format and discusses some of its limitations.

The {\tt mietable} program's output is plain text containing the desired
intensity data. The specific format is geared towards correction by the {\tt
snell} program and/or fitting with the {\tt fitdist} and {\tt fitmie} program.
Output is produced in columns in the following format:

\begin{verbatim}
*    0.500
     0.00        0.0002690        0.0002690        0.0002690
     1.00        0.0002690        0.0002689        0.0002690
     2.00        0.0002690        0.0002687        0.0002688
    <angle>    <perp intens>    <par intens>     <unp intens>
       .             .                .                 .
       .             .                .                 .
       .             .                .                 .
    <maxangle>   0.0000000        0.0000000        0.0000000
* <size parameter>
      .             .                .                 .
      .             .                .                 .
      .             .                .                 .
\end{verbatim}

The intensities are in arbitrary units, and the angles are in degrees. The
asterisk sentinel flags where the table for a new size parameter begins. Note
that, in general, the perpendicular polarization intensity will decrease very
slowly as a function of angle and the parallel intensity will decrease very
rapidly, while the unpolarized intensity is the average of the other two.

The program's limitations are inherited fairly directly from Warren Wiscombe's
{\tt MIEV0} program, which does all of the underlying computation needed to
generate the tables. A detailed discussion of the limitations of the {\tt
MIEV0} code in different domains is given in \cite{wiscombe}. In practice, the
program's accuracy should be adequate in a reasonable range of size parameters
(say from around 0.5 to 1000). This range should be more than adequate to
perform particle sizing of micron-sized droplets.

\section{Implementation}

The {\tt mietable} program is written almost entirely in ANSI Fortran 77. Only
the {\tt INCLUDE} command used to import Wiscombe's {\tt miev0.f} and {\tt
ErrPack.f} code is non-standard. The main body of the program is simple; it
begins by processing its arguments and checking for errors. If any are found,
it write a usage message to standard output, then exits. Note that if there is
an error and the output has been redirected to a file, the usage message will
be redirected to this file and {\em not} printed to the screen.

After performing all necessary error checking, the program calculates a table
of cosines of angles to be passed to the {\tt MIEV0} subroutine. Then it steps
through the specified size parameters and passes the cosine table, size
parameter and index of refraction to the {\tt MIEV0} subroutine. The subroutine
returns a variety of pieces of information, including intensity as a function
of angle for the three polarizations. The {\tt mietable} program prints these
data to standard output in the format described above. After it has finished
the last size parameter, the program exits.

For details on the inner workings of the {\tt MIEV0} routines, see
\cite{wiscombe} and a good optics book with a discussion of Mie scattering.

\section{Modifying and Compiling the Code}

It would be fairly easy to modify the program to output other pieces of
information provided by the {\tt MIEV0} routines. In the output section of the
program, one would only need to change which variables are examined and how
they are printed out. It would be similarly easy to change the program's output
format, although caution should be exercised in doing so, because the {\tt
snell}, {\tt fitdist} and {\tt fitmie} programs expect the current format.

The easiest way to compile the code is with a freeware compiler like GNU's g77.
With g77, simply place the files {\tt mietable.f}, {\tt miev0.f}, and {\tt
ErrPack.f} in the same directory, and type

\centertt{g77 mietable.f -o mietable.exe}

\noindent to compile the program. This should generate no errors or warnings.
Note that some compilers may not support the use of the command {\tt INCLUDE},
which is used to incorporate Wiscombe's {\tt MIEV0} routines into the program.
If successful, this procedure will generate an executable called {\tt
mietable.exe}, which can be used as described above to generate tables of
intensity as a function of angle.




%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%




\chapter{The {\tt snell} Program}

\section{Getting Started}
The {\tt snell} program reads in tables of intensity as a function of angle for
three different polarizations of incident light, in the format produced by the
{\tt mietable} program, discussed in section 2.2. The user specifies a
polarization, and the program takes this information, as well as information
about the geometry of the setup and adjusts the theory tables for the specified
polarization for Snell's law and foreshortening effects. It outputs corrected
tables for angles ranging from 0 degrees to some user-specified maximum angle,
at all size parameters in the original tables. It outputs these new theory
values to the output file in the same format as the {\tt mietable} program,
with the two unused columns (polarizations) zeroed out. The user must specify
the index of refraction of the medium surrounding the scatterers relative to
the medium in which measurements are being made.

To install the program, copy {\tt snell.exe} to the desired directory. This can
be the same directory as any or all of the other Mie programs. It is
recommended that the install directory be added to the system's PATH, or that
all data files are kept in the same directory as the program. Consult your
operating system's documentation for information on adding directories to the
path.

Once the program has been installed, it can be run from the command line.
Change to the directory where you placed the {\tt snell} program and use the
following command to run the program:

\begin{verbatim}
           snell inputfile outputfile [-R int] [-L int] [-n double]
                 [-pol {1,2,3}] [-w double] [-N int] [-max double]
                 [-front {1,0}] [-side {1,0}] [-help | -?]
\end{verbatim}

The required arguments and optional switches are summarized in the following
list.

\begin{center}
\begin{tabular}{lp{4 in}}
{\tt inputfile}      & Uncorrected Mie tables in {\tt mietable} format.\\
{\tt outputfile}     & File to output corrected Mie tables to.\\
{\tt [-R int]}       & Radius from detector to cuvette in mm (default = 245).\\
{\tt [-L int]}       & Half the length of cuvette side in mm (default = 6).\\
{\tt [-n double]}    & Relative index of refraction of medium surrounding scatterers to medium in which measurements are being made (e.g., water to air = 1.33
                       when using particles suspended in water) (default = 1.33).\\
{\tt [-pol {1,2,3}]} & Polarization. 1 = perp, 2 = par, 3 = unp (default).\\
{\tt [-w double]}    & Angular resolution of detector, in degrees (default = 0.3).\\
{\tt [-N int]}       & Number of scatterers to use in correction (default = 20).\\
{\tt [-max double]}  & Maximum angle to output corrected data at (default = 70.0).\\
{\tt [-front {1,0}]} & Use 0 to disable front correction, 1 to enable (default).\\
{\tt [-side {1,0}]}  & Use 0 to disable side correction, 1 to enable (default).\\
{\tt [-help | -?]}   & Print this message.\\
\end{tabular}
\end{center}

The tables output by the program are written directly to the file specified by
the argument {\tt outputfile}, so there is no need to redirect output as there
is with the {\tt mietable} program. The only information printed to standard
output is a status indicator that shows the program's progress in correcting
the original tables.

A typical use of {\tt snell} might be

\centertt{snell mietables.txt snelltables.txt -pol 2 -n 1.33}

\noindent which corrects the parallel-polarized column of the file {\tt
mietables.txt} using a relative index of refraction of 1.33, which is
appropriate for an experiment where scatterers are suspended in water and
measurements take place in the surrounding air. The results are output in a
table where the first and third columns are zeroed out and the second column
contains the corrected parallel-polarized theory. The output produced on
standard output looks like:

\begin{verbatim}
C:\Mie>snell mietables.txt snelltables.txt
Performing correction on file 'mietables.txt': 60%
\end{verbatim}

If the program encounters a problem processing the arguments, it will exit with
error status and print an abbreviated version of the list above.

\section{Reference}

The output format of the program is identical to that of the {\tt mietable}
program, except that {\tt snell} truncates the tables at the angle specified by
the {\tt -max} switch. Although the user can specify an angle as high as 180,
the default of 70 sufficient for the setup shown in the introduction, since
data is usually not collected at higher angles.

Most of the optional parameters are fairly self-explanatory. The angular
resolution of the detector, specified by the {\tt -w} switch, is not central to
the computation, and can be a rough approximation. The {\tt -front} and {\tt
-side} correction switches are present to give experimenters the option of
blocking the side of the cuvette with an opaque material, then disabling the
side correction, for example.

\section{Implementation}

The {\tt snell} program is implemented in ANSI C++, and has been successfully
compiled using Microsoft Visual Studio 6.0. It relies on the dataSet class
defined in {\tt dataset.hh} and related files, which are included with the
source code for the program.

The Snell's law and foreshortening corrections are both performed numerically,
since closed-form solutions are difficult to work with. The program reads in
the tables from the input file sequentially, selects the appropriate
polarization, and stores the data to a dataSet object. It then approximates the
angle shifts upon leaving the front and side faces of the cuvette and corrects
for the intensity being significantly higher at small angles due to the
foreshortening effect described in \cite{weiner}. The interested reader is
directed to this paper as a reference for further details. The corrected tables
are then output in the same format they were read in, but with the unused
polarization columns zeroed out. The tables produced by the {\tt snell} program
are in a format suitable for use by the {\tt fitmie} program.

\section{Modifying and Compiling the Code}

Probably the most useful modification to the {\tt snell} program is changing
the default values to match a new experimental setup. This can be accomplished
with relative ease by modifying {\tt snell.cpp}, which is well-documented with
comments. Care should be taken to change the default values printed in the help
table if the actual defaults are to be modified.

As noted above, the program uses {\tt dataset.hh} for the dataSet class in
which the theory data is stored. The key issue in compiling the code is to
properly include this file and the {\tt polynomial.hh} file. This can be
accomplished through a makefile in a UNIX environment. To compile under Visual
Studio, carefully follow the How To Compile instructions included with the {\tt
snell} source code.





%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%




\chapter{The {\tt fitmie} Program}

\section{Getting Started}

The {\tt fitmie} program reads in two tables --- one containing experimental
data in the format described in the Reference section, and one containing Mie
theory tables in the format produced by the {\tt mietable} and {\tt snell}
programs. In the default fitting mode, it then examines the $\chi^2$ between
the data and the theory at each size parameter in the theory table. The theory
table is scaled by a constant multiplicative factor to account for the fact
that the units of the intensity data are arbitrary. This is called an $\alpha$
regression. The program can output the results of this fit in a simple form, or
dump the $\chi^2$ as a function of size parameter. It can also output the
scaled fit tables in a form suitable for graphing along with the original. The
program has an option to restrict the range of the fit and an option to
disregard uncertainty data in case some part of the experimental data is deemed
unreliable. The fit types supported by the program are:

\begin{enumerate}
\item An alpha regression. In this method, the theory curve is first scaled so
that it has the same amplitude as the data, taking into account the uncertainty
at each point in the data set. This new theory curve is then compared to the
data set by computing a $\chi^2$ (i.e., the sum of the squares of the residuals
at each point in the data set, divided by the number of points in the set.) A
lower $\chi^2$ indicates a better fit.

\item An alpha regression disregarding uncertainties. Same as above, but
without taking into account uncertainty. This could be useful for data without
uncertainties, or data with suspect uncertainty.

\item A divide-by-point normalization. This method, suggested by Bohren and
Huffman \cite{bohren}, uses a scaling factor for both the data and theory. Both
scaling factors are computed by dividing all of the intensities present by the
intensity at some chosen angle. A $\chi^2$ is then computed as above, taking
into account uncertainties.

\item A front-back fit. This fitting method takes the average of a given number
of points from the front and back of the fitting range in the data and in the
theory. It then compares the ratio of these to averages in the data and theory,
and uses the squared difference between the theory ratio and data ratio to
measure fit quality.
\end{enumerate}

Each of these fit methods can be selected on the command line, as described
below.

To install the program, copy {\tt fitmie.exe} to the desired directory. This
can be the same directory as any or all of the other Mie programs. It is
recommended that the install directory be added to the system's PATH, or that
all data files are kept in the same directory as the program.

Once the program has been installed, change to the directory where you placed
it and use the following command to run the program:

\begin{verbatim}
 fitmie datafile theoryfile [-pol {1,2,3}] [-nouncert]
        [-dividebypoint double] [-frontback int] [-dump {data, chi, double}]
        [-range double double] [-help | -?]
\end{verbatim}

The required arguments and optional switches are summarized in the following
list.

\begin{center}
\begin{tabular}{lp{3.2 in}}
 {\tt datafile}                  & Experimental data (angle-intensity-sigma table).\\
 {\tt theoryfile}                & Theoretical Mie tables in {\tt mietable} format.\\
 {\tt [-pol {1,2,3}]}            & Polarization. 1 = perp, 2 = par, 3 = unp.\\
 {\tt [-nouncert]}               & Fit by alpha regression without uncertainties.\\
 {\tt [-dividebypoint double]}   & Fit by Bohren and Huffman's divide by point
                                   method, using the specified angle.\\
 {\tt [-frontback int]}          & Fit by back-to-front ratio using averages of
                                   a number of points from front and back of data.\\
 {\tt [-dump {data,chi,double}]} & Dump input data, chi-square, or the fit curve
                                   at the size parameter nearest to the double.\\
 {\tt [-range double double]}    & Fit only data in the range from the first angle
                                   specified to the second angle specified.\\
 {\tt [-help | -?]}              & Print help message.\\
\end{tabular}
\end{center}

The output of the program goes to standard output, and can thus be redirected
to an output file with the command {\tt> outputfile} in a UNIX or DOS
environment. This is useful once a reasonably good fit has been obtained, and
the user wishes to output a scaled theory curve to overlay on the data. It is
also useful for producing tables of $\chi^2$ as a function of size parameter to
visually depict the quality of the fit. The format of this output is described
in the next section.

A typical use of {\tt fitmie} might be

\centertt{fitmie data.txt snelltables.txt -pol 2}

\noindent or, once a good fit has been found and the user wishes to produce a
$\chi^2$ table,

\centertt{fitmie data.txt snelltables.txt -pol 2 -range 12 48 -dump chi >
chidist.txt}

Both of these fit the data to parallel-polarized tables generated by the {\tt
snell} program (or tables produced directly by the {\tt mietable} program if no
snell correction is needed for some reason). Again, note that the redirect
command {\tt> chidist.txt} is {\em not} part of the program's syntax, but
rather a DOS and UNIX command to write the program's output (in this case a
table of $\chi^2$ values) to the file {\tt chidist.txt}.

If the program encounters any errors processing the arguments, it will exit
with error status and print an abbreviated version of the list above.

\section{Reference}

The program takes as input a data table in the format:

\begin{verbatim}
    4    24782.229965156796   1526.0627957332767
    6    4436.597110754414    575.72747321778
    8    1076.4872521246461   158.36175478043836
 <angle>     <intensity>        <uncertainty>
    .             .                    .
    .             .                    .
    .             .                    .
\end{verbatim}

\noindent where the intensity units are arbitrary, but the same as those of the
uncertainties. It also takes a theory table in the {\tt mietable} format
described in section 1.2. Note that if the tables have been corrected by the
{\tt snell} program, two of the three columns will be zeroed out.

\section{Implementation}

The {\tt fitmie} program is implemented in ANSI C++, and has been successfully
compiled using Microsoft Visual Studio 6.0. It relies on the dataSet class
defined in {\tt dataset.hh} and the polynomial class defined in
{\tt polynomial.hh}.

The program reads in the theory tables one at a time, computes the appropriate
scaling factor according to the fit method, and then computes a $\chi^2$ (or
other measure of fit quality). It keeps track of the minimum $\chi^2$
encountered, the size parameter that produced it, and the corresponding alpha
(scaling) factor. It then either prints the results of the fit, dumps the data,
dumps the $\chi^2$ at each point, or dumps the scaled theory at a particular
intensity, depending on the command line switches specified. For details on
each of the fitting methods, see \cite{weiner}.

\section{Modifying and Compiling the Code}

The most useful modification to this program would be to make it a stand-alone.
That is, allow the user to pass in a data file, and generate any needed theory
on the fly. Implemented like this, the program would be able to refine the
accuracy of the fit on the fly, producing better size parameter approximations.
Because of the uncertainty present in the data and the vastly greater development
time required to implement this method, the current system was more than
sufficient in the experiments performed.

To compile the code, keep in mind that the program uses {\tt dataset.hh} for the dataSet
class in which the theory data is stored. The key issue in compiling it is to
properly include this file and the {\tt polynomial.hh} file. This can be
accomplished through a makefile in a UNIX environment. To compile under Visual
Studio, carefully follow the How To Compile instructions included with the {\tt
fitmie} source code. Note that the program also requires the standard library
files stdlib.h, iostream.h, fstream.h, and string.h.





%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%




\chapter{The {\tt fitdist} Program}

\section{Getting Started}

The {\tt fitdist} program reads in three files: a file containing data and a
description of the experimental setup that produced it, a file containing the
parameters for the fit to be performed, and a file containing Mie scattering
tables of angle as a function of intensity for various size parameters. The
program proceeds by using one of two algorithms to fit the distribution
specified in the fitting file to the data. The default choice is to use the
Levenberg-Marquardt algorithm, which varies smoothly between a steepest-descent
and quadratic approximation method, and generally converges fairly quickly to
the best fit, given reasonable starting ranges for all parameters. The optional
override is to simply explore all of parameter space, spacing $m$ points evenly
in each of $n$ parameter ranges, then evaluating $\chi^2$ at each of the $m^n$
parameter combinations and returning the best combination. This is useful for a
rough fit, or to check the results of the Lev-Mar fit. The size distribution
functions supported by the program are:
\begin{enumerate}
  \item Delta functions. These functions have two parameters---a size $r$ and
  an amplitude $\alpha$. So a 50--50 mix of 1.0$\mu$m and 5.0$\mu$m droplets
  could be represented by two delta functions of equal magnitude at $r_1 = 1.0$
  and $r_2 = 5.0$.

  \item Gaussians. Standard three parameter distributions with a size $r$, a
  standard deviation (or width) $\sigma$, and a total area of $\alpha$. Useful
  for even distributions of particle sizes about a central maximum.

  \item Logonormal. If a random variable $X$ has the
  property that $\log X$ is normally distributed, then $X$ is said to have a
  logonormal (log-normal) distribution. Again, there are three parameters,
  representing a distribution center $r$, a width $\sigma$ and an area
  $\alpha$. This distribution is most consistent with most real distributions
  in aerosols, and has the appealing property that it goes to zero at a size of
  zero.
\end{enumerate}

All input and output to the program, with the exception of the Mie tables
themselves, is in terms of microns of radius (as opposed to the dimensionless
size parameter, or some units of diameter).

To install the program, copy the executable file {\tt fitdist.exe} and the
default tables {\tt fitdist.dat} to the desired directory. This can be the same
directory as any or all of the other Mie programs, for convenience. It is
recommended that the installation directory be added to the system's PATH (see
your operating system's documentation for details) or that all data files be
kept in the same directory as the program. This prevents the user from having
to specify a full path to one or both of the program and the data files.

Once the program has been installed, change to the install directory and run it
at the command line as follows:
\begin{verbatim}
  fitdist datafile fitfile [-tables tablefile] [-simple #]
\end{verbatim}
The required arguments and optional switches are summarized below.
\begin{center}
\begin{tabular}{lp{3.2 in}}
 {\tt datafile}                  & Experimental data (angle-intensity-sigma table),
                                   with polarization, index of refraction, and laser
                                   wavelength for this setup.\\
 {\tt fitfile}                   & A file specifying the types of functions to
                                   be fit, and the parameter ranges over which
                                   to fit them. \\
 {\tt [-tables tablefile]}       & Read theoretical Mie tables in {\tt mietable}
                                   format from the file {\tt tablefile}. The default
                                   tables are in {\tt fitdist.dat}. \\
 {\tt [-simple \#]}              & Fit by simple exploration of parameter space,
                                   dividing each parameter range into the given
                                   number of points.\\
\end{tabular}
\end{center}

The program gives its progress as it loads the Mie theory tables, then outputs
a warning if the tables provided may not be sufficient to cover the parameter
ranges in the fit file. In any case, the program outputs a simple progress or
working indicator, depending on the fit algorithm selected. It also reports
$\chi^2$ as it progresses, and then gives a summary of the fit results when it
finishes. The user is given a choice whether to output the full results to a
file (including the input files, summary, size distribution, and theory
distribution). The user is also given a chance to perform the fit again with a
different fit file, or possibly a tweaked version of the same fit file. Thus, a
typical run for the program might look like
\begin{verbatim}
  C:\Mie> fitdist data.txt logonormal.fit -tables big-tables.dat
  Loading: 100%  Range: x = 1 to 199.998.
  Warning: Mie tables may not cover range of sizes needed.
           95% of the 1st function lies in the range 0.49 to 152.02.
  Fitting: Done Best chi^2: 45.3119 Results:
    Logonormal: r =  1.61 alpha = 1.3e-006 sigma =   0.48
  Output full results to file? (y/n): y
  Filename (data-fit02.txt):
  Perform another fit? (y/n): n
\end{verbatim}
Note that the progress indicator has already reached {\tt Done} and only the
final, best $\chi^2$ is still visible. The user hit {\tt y} to output full
results, then accepted the default file name---a concatenation of the original
file name with a {\tt -fitXX} suffix---by pressing enter without giving a name.
Finally, the user chose not to perform another fit, and the program exited with
no error status.

If the program encounters any errors processing the user's arguments, or
parsing the files provided, it will output an error message explaining the
problem. For problems with arguments, it outputs an abbreviated version of the
table above, explaining usage.

\section{Reference}

The input formats for the data file is demonstrated below. Any number of lines
beginning with {\tt //} {\em at the beginning of the file} are treated as
comments. Note that these comments are assumed to conclude with the first line
that does not begin with {\tt //}, and the program will begin looking for the
experimental setup parameters. These are the polarization of the laser (either
{\tt parallel}, {\tt perpendicular} or {\tt unpolarized}, relative to the
scattering plane), the wavelength of the laser in nm, and the index of
refraction of the scatterers and the surrounding medium. For backward
compatibility, the user can also specify a relative index of refraction only
(the ratio of scatterer index to ambient index), in which case the ambient
medium is assumed to be air. In any event, the user should be certain that the
relative index (whether calculated or specified) matches that used to generate
the Mie tables. In other words, Mie tables for latex spheres in water will not
size water droplets in air properly. See the {\tt mietable} documentation for
details.

\begin{verbatim}
  // Atomizer:  Piezo Number 9
  // Frequency: 1.42 MHz
  // Fluid:     Water
  // Date:      July 9 2002
  // The laser intensity was raised twice during
  // this set in order to go to larger angles
  // high angles removed

  polarization   = parallel
  wavelength     = 488
  relativeIndex  = 1.33
  scattererIndex = 1.33
  ambientIndex   = 1.00

  6.     1.                      0.0013953130379604915
  7.     0.6176239671094887      0.001276931484944276
  8.     0.46843010015008074     0.0012771352397687443
  10.    0.31065743175092075     0.0012457671845418142
  12.    0.2588737136257524      0.000919790028615837
  14.    0.21711476342765942     0.001095029365399996
  16.    0.18429929505415218     0.0010675632150616383
  18.    0.16392055253010773     0.0009433135231007288
  20.    0.13989623887441352     0.0009092355287083671
  25.    0.09438723207068338     0.0008898075061952929
  30.    0.06398401706405905     0.0011504914286203298
\end{verbatim}

Finally, the user provides the actual data from the scattering measurements,
one data point per line, with angle in the first column (with the original beam
as 0 degrees), the measured intensity or relative intensity in the second
column, and the uncertainty in the measurement in the third column.

The format for the fitting files, illustrated below, is also fairly
straightforward. The function type is specified in square brackets, then ranges
for each parameter are given. The example below would fit to a Gaussian, two
delta functions, and a logonormal peak. Note that, in practice, this would be
far too many parameters for a good fit.

\begin{verbatim}
  [Gaussian]
  alpha = 0   1
  sigma = 0.5 3
  r     = 1   10

  [Delta]
  alpha = 0 1
  r     = 3 5

  [Delta]
  alpha = 0 1
  r     = 5 7

  [Logonormal]
  alpha = 0   1
  sigma = 0.5 3
  r     = 1   10
\end{verbatim}

Finally, the program requires Mie scattering tables; the appropriate format for
these tables is described in the {\tt mietable} documentation.

The program's output to file begins with a concatenation of the data and fit
files, then a statement about the range and spacing of the Mie tables, and the
summary of fit results also output to the screen. Next, the program produces a
table of relative abundance of each size of particle under the best-fit size
distribution. This eliminates any confusion over convention choices in
formulas, because the user can plot and examine the actual distribution.
Finally, the theoretical intensity profile resulting from the best size
distribution is output, with angle in the first column, and intensity (scaled
to best fit the data) in the second column.

This integration of all the information used to perform the fit with the fit
results makes it easy to redo a fit later, or to plot data and theory against
each other by reading in only one file.

\section{Implementation}

The {\tt fitdist} program is written in ANSI C++, and has been successfully
compiled using Microsoft Visual Studio 6.0. Some minor adjustments to file i/o
calls may be required to compile it on other platforms. It relies on the
fitting function class, defined in {\tt fitfunc.hh} and implemented in {\tt
fitfunc.cpp}. These classes make use of inheritance to define the specific
function types supported by the program as extensions of a more abstract
fitting function.

The program first processes and checks its arguments for errors. It then reads
in and parses the experimental data and moves on to load from the Mie tables
only those angles needed for the fit, in order to save memory and computation
time. The main body of the program is a loop, so that the user can perform as
many fits as needed without rereading the data or the Mie tables. The fit file
is read and parsed, then the fitting is performed by one of two fitting
routines (the Levenberg-Marquardt algorithm, or a simple exploration of
parameter space) and a summary of the results is output. The user is given the
option to write the full results of the fit to file, in which case the program
computes a suitable default filename, then prompts the user to specify an
alternate if desired. The file is then written, and the user is given the
option to continue performing fits (re-enter the loop), or quit. Assuming no
problems were encountered, the program exits with status 0, indicating no
error.

\section{Modifying and Compiling the Code}

The program is believed to be fairly complete and robust, but modifications to
improve its speed would certainly be welcome. Another useful feature would be
to replace one of the $\alpha$ scaling factors with an overall scaling factor
that could vary freely, thus turning the user's input into relative scaling
factors. A few variables and routines in the program have already been set up
to accommodate this change, but it is certainly not necessary.

The main issue in compiling the code is the proper inclusion of the {\tt
fitfunc.hh} file that describes the fitting function class. Using a tool like
{\tt gcc} for compilation, this can be most easily accomplished by writing a
makefile. To compile under Visual Studio, carefully follow the How To Compile
instructions included with the {\tt fitdist} source code. Note that the program
also requires stdlib.h, iostream.h, iomanip.h, fstream.h, string.h, ctype.h,
and math.h.



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%




\begin{thebibliography}{WWW}
 \bibitem[IW]{weiner} I. Weiner, M. Rust, and T.D. Donnelly. ``Particle Size
                      Determination: An Undergraduate Lab in Mie Scattering.''
                      {\em American Jornal of Physics} February 2001: 129-136.
 \bibitem[WW]{wiscombe} W. J. Wiscombe. ``Mie Scattering Calculations: Advances
                        in Technique and Fast, Vector-Speed Computer Codes.''
                        NCAR Tehcnical Note. June 1996.
 \bibitem[BH]{bohren} Craig F. Bohren and Donald R. Huffman.
                        {\em Absorption and Scattering of Light by Small
                        Particles}. New York: Wiley, 1983.
\end{thebibliography}

\end{document}
