=========================================================================
			Sort subroutines FAQ
=========================================================================

This file contains notes and help information on the sort subroutines.
Please see the NEWS and README files for latest information.
See CHANGES for updates to the sort-subs distribution.

Contents
========

1.	What are the sort subroutines?
	1.1.	Where can I get the latest version from?
	1.2.	Installation.
	1.3.	Organisation of the sort-subs distribution.
        1.4.    Executables

2.	Conventions.
	2.1.	Organisation of Sorting/Calibration Files.
	2.2.	Co-ordinate Convention.
	2.3.	Array Indexing.
	2.4.	Error Handling.
	2.5.	Sort code simulation call routines.
 
3.	Where can I find instructions on the subroutines?

4.	How do I start using the subroutines?
	4.1.	Quickstart procedure.

5.	Do I have to use C sort-files?

6.	So, what is this "Standard Event Structure"?
	6.1.	Example generation of particles in the ev array.
	6.2.	Where is the Reaction defined?

7.	The "next generation" code, a bit Star Trek?
	7.1.	What does it do?
	7.2.	Main Elements.
	7.3.	How do I use it?

8.	Simulation Code, now that sounds useful?

9.	Misc Calibration codes.
	9.1	Example calibration procedure.
 
10.	Bugs and New features.
	10.1.	List of known bugs.

11.	HELP!


1. What are the sort subroutines?
==================================

The sort subroutines provide for standardised analysis and
manipulation of data using the sunsort package. The routines centre on
the philosophy that standard codes reduce error and analysis time in
data sorting. The calibration of data is decoupled from the "data
sorting" by using a "standard event format". The standard format data
is then portable and can be analysed without particular reference to
detection systems or specific experiments.

The subroutines consist of kinematic analysis codes and a set of
procedures to both aid in the setting-up of more transparent
sort-codes and make analysis more efficient. This allows the
calibration code to be defined explicity in terms of the detection
elements of the experiment. Events can then be analysed according to
the detector elements that were hit by running the named calibration
code appropriate to that particular detector. These routines comprise
the "next generation code".

A Monte Carlo simulation is also provided. This can be used to
generate pseudo events in the standard format which plug data directly
into sunsort. This allows the operation of sort codes to be analysed
and the efficiency of detection systems to be tested. This simulation
is in fact completely integrated with sunsort such that the user can
switch between simulated and measured events at the push of a couple
of buttons!

The sort subroutines are distributed with sunsort. They have been
compiled into a library which is included during sunsort
"makesort". The complete subroutine source code can be found in
/wherever/sunsort/lives/sort-subs.  This can be used as inspiration to
create modified functions (or new ones) in the user's area for
specific analysis tasks that cannot be performed with the standard
code. Remember that only the subroutines useful to any particular
analysis task need be used. The routines are free to anyone interested
in using them. They should reduce analysis time and the drudgery of
code development. Most importantly the more code that can be
"standardised" and employed in a variety of situations the more
confident we can all be in the results of our data analysis!

1.1. Where can I get the latest version from?
----------------------------------------------

The sort subroutines are distributed with sunsort. However, they are
usually updated more frequently than the complete sunsort
distribution. The latest update patches can be found on the Charissa
fileserver at Daresbury.

1.2. Installation
------------------

Installation notes are given in the sort-subs README file.

1.3. Organisation of the sort-subs distribution
------------------------------------------------

The layout of directories is defined in the sort-subs README file.

1.4. Executables 
----------------- 

Links to all executable files in the subroutines distibution can be
found in sort-subs/bin. It is useful to add this to your path.


2. Conventions
===============

2.1. Organisation of Sorting/Calibration Files 
-----------------------------------------------

In order to decouple the data sorting from the experiment specific
calibrations, all calibration codes and calibration data files should
be stored in a directory "calib-inputs" in the user sort directory
(i.e. the user directory from where sunsort is run). The contents of
calib-inputs are then all that is required to generate standard
event format data from an experiment. Sort codes outside this
directory are then designed to operate only on the standard event
structure. In this convention each experiment has a unique
calib-inputs, but standard event data from different experiments may
be analysed with the same standard event sort code.

The following filename convention is used in calib-inputs:
Makefile   	Called automatically on makesort to compile calibration codes
cal.h      	Header file for calibrations
cal_init.c	Initialisation procedures for calibration and sort-subs
cal.c      	Event-by-Event calibration procedures
*.cal		Calibration data files
*.sim		Simulation input files

2.2. Coordinates 
----------------- 

The following lab co-ordinate convention is used in defining particle
trajectories and detector coverage...

laboratory co-ords defined as (x,y,z)=(horiz,vert,beam)
                                                  y   z
                                                  |  /
(angles defined in the positive range 0->360.)    | /
                                                  |/
                                           x<-----.

2.3. Array Indexing
--------------------

In general, where the user is likely to call for information from an
array by number, the fortan array indexing convention is followed. For
example the energy of particle 1 in the event array is stored as
ev[1].e.

2.4. Error Handling.
--------------------

In general, the sort subroutines return 0 for correct execution and
nonzero for failure.  One exception to the rule is the
detector_event() and detector_init() procedures. They return "DET_OK"
for correct operation and "DET_ABORTSORT" for complete failure!
Specific error and return flags are defined in the various header
files. (e.g. detector.h).


2.5. Sort code simulation call routines.
---------------------------------------- 

It is necessary to compile some additional commands to read events
into sunsort from the simulation. The convention is used that where
user sorts have this extra code in place it is surrounded by

#ifdef SIM
...../*extra bits of code needed by simulation*/ 
#endif"

#ifndef SIM
..../*bits of code not required by simulation*/
#endif

Compilation with no flag then allows the code to be used with the
normal data stream and with -DSIM for the sorting of pseudodata.



3. Where can I find instructions on the subroutines?
=====================================================

Only background information is given in this FAQ. A brief description
of new subroutines will be posted in the NEWS file. The available
subroutine functions can be determined by examining the subs.h and
associated files in the sort-subs directory. A description of each
subroutine is given in the relevant source code file. The best course
of action for the new user is to follow the code by the examples given
in the distribution. Try the "Quickstart" and "Calibration" procedures
(See FAQ 4.1 below).


4. How do I start using the subroutines?
========================================

1) See note on filename conventions FAQ 2.1.


4.1. Quickstart Procedure
--------------------------

1) A complete set of starter files can be found in
calib-routines/quickstart. Copy all files in this directory to your
usual sort_dir (i.e. the directory from where you run sunsort). 

Your sort_dir should now contain at least the following files:
quickstart-c.srt   starter sortcode
quickstart_proc    quickstart procedure
calib-inputs/
Makefile   	Called automatically on makesort to compile calibration codes
cal.h      	Header file for calibrations
cal_init.c	Initialisation procedures for calibration and sort-subs
cal.c      	Event-by-Event calibration procedures
expt.cal	Experiment definition used by next generation code
map.cal		ADC/TDC to detector signal map

2) Follow the Quickstart procedure quickstart_proc.

3) It may also be helpful to read the quick calibration procedure for
strip detectors "calib_proc" in the calib-routines directory. This
points to example sort, calibration and calibration input files in the
calib-routines and calib-routines/calib-inputs directories. These
files can be used as additional inspiration for your desired analysis
procedures.


5. Do I have to use C sort-files?
=================================

No! Compatability routines have been provided to allow calls to the
subroutines from Fortran sortcodes. However, to date, these routines
remain mostly untested and come with a health warning!


6. So, what is this "Standard Event Structure"?
===============================================

Following calibration events are written into a standard format event
array. This format contains a header describing parameters such as
channel and particle multiplicities and the number of particles in the
event. Each particle hit then follows defined in terms of kinematic
parameters. The standard format structure is defined in full in the
file event-struct/ev.h. The following is a brief summary of the
main parameters.

Header => evhead."parameter"
----------------------------
evhead.n[0]	Total number of particles defined in the event array
evhead.n[1]	Total number of singles hits
evhead.n[2]	Total number of reconstructed doubles hits
evhead.n[3]	Total number of reconstructed triples hits
evhead.n[n]	Total number of reconstructed nfold hits
evhead.pmult[0]	Total number of hits 0=>Total n=>in detector n
evhead.cmult[n] Channel multiplicity 0=>Total n=>in detector n
evhead.p[n];    Particle positions in the array for each fold n
evhead.etot	Total energy of singles hits
evhead.type     Flag for event type

Macros for reading info from the event array
--------------------------------------------
i = particle number (i.e. 1 to evhead.n[0])

ev_vx(ev+i)             velocity in x
ev_vy(ev+i)             velocity in y
ev_vz(ev+i)             velocity in z
ev_e(ev+i)		energy
ev_etot(ev+i)           running total of daughter energies
ev_t(ev+i);             time
ev_q(ev+i)              excitation q
ev_q2(ev+i)             two-body q
ev_m(ev+i)		mass
ev_z(ev+i)              charge
ev_fold(ev+i)           particle reconstructed from fold particles
ev_hi(ev+i)             heavy-ion daughter
ev_li(ev+i)             light-ion daughter
ev_det(ev+i)            detector hit
ev_seg(ev+i)            detector segment hit
ev_pvec(ev+i)		lab vec
ev_p_r(ev+i)		lab momentum
ev_p_x(ev+i)		lab momentum in x
ev_p_y(ev+i)		lab momentum in y
ev_p_z(ev+i)		lab momentum in z
ev_p_t(ev+i)		lab theta angle in radians
ev_p_p(ev+i)		lab phi angle in radians
ev_p_td(ev+i)		lab theta angle in degrees
ev_p_pd(ev+i)		lab phi angle in degrees
ev_p_r2(ev+i)		lab square of momentum
ev_pcmvec(ev+i)		cm vec
ev_pcm_r(ev+i)		cm momentum
ev_pcm_x(ev+i)		cm momentum in x
ev_pcm_y(ev+i)		cm momentum in y
ev_pcm_z(ev+i)		cm momentum in z
ev_pcm_t(ev+i)		cm theta angle in radians
ev_pcm_p(ev+i)		cm phi angle in radians
ev_pcm_td(ev+i)		cm theta angle in degrees
ev_pcm_pd(ev+i)		cm phi angle in degrees
ev_pcm_r2(ev+i)		cm square of momentum

To write new information into the event array replace ev_xxx(ev+i) in
the examples above with evs_xxx(ev+i).

Reconstructed particles are also written into the event array during
analysis. For example, missing hits (reconstructed from the missing
momentum) and resonant particles (a combination of two daughters) can
be written into the event array by hand or by calling library
code.

6.1. Example generation of particles in the ev array
------------------------------------------------------

For example, the library function "missing_p()" will generate the
parameters of a missing particle. This is written as a single but not
registered as a hit e.g. ev_fold(ev+i) = 1, ev_det(ev+i) = ev_seg(ev+i) = 0.

The parameters of a resonant particle d consisting of two hits i and j
can be put in slot d of the event array with the function
"rp(d,i,j)". This is stored as a double e.g. ev_fold(ev+d) = 2, ev_hi(ev+d)
= i, ev_li(ev+d) = j. A triple t consisting of a double plus a single
e.g. ev_fold(ev+3) = 3, ev_hi(ev+t) = d, ev_li(ev+t)=k can be generated with
"rp(t,d,k)". The convention is to label the higher fold daughter as hi
and the lower fold daughter as li. Note that for the triple the
calculation of some resonant particle parameters (angle, momentum,
energy and excitation) using the function "rp" is independent of the
grouping of daughters (i,j)k or i(j,k). The calculation of breakup
angles will however depend on the grouping.

6.2 Where is the Reaction defined?
-----------------------------------

The generation of many parameters in the ev array requires information
on the masses in the reaction and the beam energy. This is stored in
the "reac" structure (see "reac.h") and initialised to particular
values by a calibration file. Following initialisation these values
can be changed from the default in the user sort code as desired. An
initial guess as to the mass of each hit is defined in the reac
structure, so that hit parameters such as momenta etc can be
calculated even when the mass is not explicitly known. If the mass of
particle i is subsequently suspected to be different from the initial
assignment the hit parameters can be recalculated with the function
rhit(newmass,i). The function nrhit(newmass,i) recalculates all
particles in the ev array for all dependencies on the changed mass
i.e. recalculating resonant particle parameters too. A simple
procedure to assign particle masses by guesswork and recalculation can
be made by sorting on momentum gates.


7. The "next generation" code - a bit Star Trek? 
=================================================

7.1. What does it do? 
---------------------- 

The "next generation" routines define calibration procedures
explicitly in terms of the detection elements of the
experiment. Information on the experimental set-up is provided by the
user along with a set of procedure names associated with each detector
element. During initialisation the next generation code examines the
experiment definition and calls the initialisation procedures attached
by the user to each detector element name. During ebye sorting the
code automatically "marks" only those detector elements which have
fired and only runs the ebye procedures attached to those element
names. Since the procedure for calibrating data from a particular
detector is often independent of the experiment itself, code can be
shared between experiments. Information on the specific cabling of
signals into ADC/TDC's is stored separately as part of the calibration
information. The result is a more transparent calibration code written
in terms of specific operations rather than with hidden ADC
numbering. The gain in sorting efficiency provided by the "markhits"
routine allows the filling of the standard event structure with all
the necessary parameters in each event without a significant reduction
in the sorting rate. The prefiltering of raw data tapes into
calibrated tapes is thus unnecessary.

7.2 Main Elements
------------------

At the core of the next generation code is the "structure" of the
experiment. This is generated from a user experiment definition file
"expt.cal". The structure is a basic tree. At the top of the tree is
the "experiment". This consists of a number of children
i.e. detectors. Each detector has its own children i.e. subelements
and so on. At the bottom of the structure the elements are comprised
of signals. A user calibration file "map.cal" relates ADC/TDC numbers
to the signals defined in the experiment structure. Information is
hooked to the appropriate nodes in the structure. This information
includes some standard parameters (gain,offset,thresholds) and a hook
to attach additional user data. Function names defining specific
procedures to be performed are also attached to each node. The
procedures to be run on initialisation (such as loading calibration
files) and during event sorting (ebye calibrations) for each detector
element are defined with the following syntax:

setdetprocs("elname", proc_elname_preinit,  proc_elname_init,
                      proc_elname_preevent, proc_elname_event);

where elname is the element name as defined in the users
experiment.cal. These definitions are usually placed in the users file
"cal_init.c". NULL replaces the procedure name when no procedure is
required. When an element has no procedures at all no setdetprocs
call is required. Some standard (or example) procedures have been
defined in the sort-subs library (see "detprocs.h"). User specific
procedures should be placed in their own calib-inputs directory in
cal_init.c for init procedures and cal.c for ebye procedures. The name
convention user_elname_preinit etc is preferred. Library procedures
are named proc_elname_preinit etc.

These procedures are called during initialisation with the function:
detector_init(expt)

and during ebye sorting with:
detector_event(PROC_FLAG,expt).

where expt points to the experiment structure and PROC_FLAG allows for
event procedures to be called by flag.

The proc_elname_* routines are run for the constituent parts of each
element first. So the individual "signal" procs are executed first up
to "detector" procs then the "experiment" proc. The proc_elname_pre*
routine for each element is run before the procedures of its
constituents.


7.3. How do I use it?
----------------------
See "How I start using the subroutines?"


8. Simulation Code, now that sounds useful?
============================================

The Monte Carlo simulation code calculates the kinematics of particles
in breakup reactions and can be used to predict the angles/energies of
scattered fragments and hence determine the suitability of different
detection systems for particular measurements. Since it plugs directly
into sunsort and uses the standard event structure it may also be used
to generate randomised order pseudodata to provide a realistic test of
sort code operation.

See the simulation/README for further information.


9. Misc Calibration codes
==========================

Some calibration routines have been provided in the calib-routines directory.
See the calib-routines/README for further information.

9.1. Example calibration procedure
----------------------------------- 

A complete step by step calibration procedure "calib_proc" for strip
detectors can be found in the directory calib-routines. This points to
example sort, calibration and calibration input files relevant to
strip detector experiments but is also useful for hints on setting up
calibrations for other detector types.


10. Bugs and New features
===========================

Bug fixes will be posted in the CHANGES file.
Details of new features can be found in NEWS.

10.1. List of known bugs and problems.....
-------------------------------------------

1) Prototype fortran compatability routines remain untested!
2) Nothing else known... yet!

Please report problems and bugs to s.chappell1@physics.ox.ac.uk. 


11. HELP!
==========

If you run into trouble contact: s.chappell1@physics.ox.ac.uk


******************************************************************************
FAQ updated: 12/5/99 SPGC
