source: Sophya/trunk/SophyaLib/Manual/sophya.tex@ 3034

Last change on this file since 3034 was 3034, checked in by ansari, 19 years ago

suite documentation SOPHYA overview - section FitsIOServer, Reza 17/7/2006

File size: 79.1 KB
Line 
1\documentclass[twoside,10pt]{article}
2% Package standard : Utilisation de caracteres accentues, mode francais et graphique
3\usepackage{url}
4\usepackage[latin1]{inputenc}
5\usepackage[T1]{fontenc}
6\usepackage[english]{babel}
7\usepackage{graphicx}
8% package a mettre pour faire du pdf
9\usepackage{palatino}
10
11% Extension de symboles mathematiques
12\usepackage{amssymb}
13
14% Definition pour Docs Sophya
15\usepackage{defsophya}
16
17% Constitution d'index
18\usepackage{makeidx}
19
20\usepackage[ps2pdf,bookmarks,bookmarksnumbered,%
21 urlcolor=blue,citecolor=blue,linkcolor=blue,%
22 pagecolor=blue,%hyperindex,%
23 colorlinks=true,hyperfigures=true,hyperindex=true
24 ]{hyperref}
25
26\makeindex % Constitution d'index
27
28\newcommand{\rond}{$\bullet \ $}
29\newcommand{\etoile}{$\star \ $}
30\newcommand{\cercle}{$\circ \ $}
31\newcommand{\carre}{$\Box \ $}
32
33
34\begin{document}
35
36\begin{titlepage}
37% The title page - top of the page with the title of the paper
38\titrehp{Sophya \\ An overview }
39% Authors list
40\auteurs{
41R. Ansari & ansari@lal.in2p3.fr \\
42E. Aubourg & aubourg@hep.saclay.cea.fr \\
43G. Le Meur & lemeur@lal.in2p3.fr \\
44C. Magneville & cmv@hep.saclay.cea.fr \\
45S. Henrot-Versille & versille@in2p3.fr
46}
47% \auteursall
48% The title page - bottom of the page with the paper number
49\vspace{1cm}
50\begin{center}
51{\bf \Large Sophya Version: 2.0 (V\_Jul2006) }
52% Document revision 1.0 }
53\end{center}
54\titrebp{1}
55\end{titlepage}
56
57\tableofcontents
58
59\newpage
60
61\section{Introduction}
62
63{\bf SOPHYA} ({\bf SO}ftware for {\bf PHY}sics {\bf A}nalysis)
64is a collection of C++ classes designed for numerical and
65physics analysis software development. Our goal is to provide
66easy to use, yet powerful classes which can be used by scientists.
67Although some of the SOPHYA modules (SkyMap, Samba, SkyT)
68have been designed with the specific goal CMB data analysis, most
69modules presented here have a much broader scope and can be
70used in scientific data analysis and modeling/simulation.
71Whenever possible, we use existing numerical packages and libraries,
72encapsulating them in classes in order to facilitate their usage.
73\par
74Our main requirements in designing SOPHYA classes can be summarized as
75follow:
76\begin{itemize}
77\item[\rond] Provide a comprehensive set of data containers, such as arrays and tables
78(tuple) covering the most common needs in scientific simulation and data analysis
79softwares.
80\item[\rond] Take advantage of the C++ language and define methods and operators
81for most basic operation, such as arithmetic operations, in a rather intuitive way, while
82maintaining performances comparable to low level coding in other languages
83(C, Fortran, F90 \ldots)
84\item[\rond] Simplify memory management for programmers using the class library.
85This has been a strong requirement for most SOPHYA classes. Automatic reference
86sharing and memory management is implemented in SOPHYA classes intended
87for large size objects. We recommend to allocate SOPHYA objects on the stack,
88including when objects are returned by methods or functions.
89See section \ref{memgt} for more information.
90\item[\rond] Archiving, importing (reading) and exporting (writing) data in a
91efficient and consistent way is a major concern in many scientific software
92and projects. SOPHYA provide a native data I/O or persistence system,
93(PPF, \ref{ppfdesc}) as well as import/export services for ASCII and FITS formats.
94\end{itemize}
95
96% \vspace*{2mm}
97This documents
98presents only a brief overview of the class library,
99mainly from the user's point of view. A more complete description
100can be found in the reference manual, available from the SOPHYA
101web site: % {\bf http://www.sophya.org}.
102\href{http://www.sophya.org}{http://www.sophya.org}.
103%%%
104%%%
105\subsection{SOPHYA modules}
106The source directory tree
107\footnote{ CVS: cvsserver.lal.in2p3.fr:/exp/eros/CVSSophya}
108is organised into a number of modules.
109
110\begin{itemize}
111\item[] {\bf BuildMgr/} Scripts for code management,
112makefile generation and software installation
113\item[] {\bf BaseTools/} General architecture support classes such
114as {\tt PPersist, NDataBlock<T>}, and few utility classes
115such as the dynamic variable list manager ({\tt DVList}) as well
116as the basic set of exception classes used in SOPHYA.
117\item[] {\bf TArray/} template numerical arrays, vectors and matrices \\
118({\tt TArray<T> TMatrix<T> TVector<T> } \ldots)
119\item[] {\bf NTools/} Some standard numerical analysis tools
120(linear, and non linear parameter fitting, FFT, \ldots)
121\item[] {\bf HiStats/} Histogram-ming and data set handling classes (tuples) \\
122({\tt Histo Histo2D NTuple DataTable} \ldots)
123\item[] {\bf SkyMap/} Local and full sky maps, and some 3D geometry
124handling utility classes. \\
125({\tt PixelMap<T>, LocalMap<T>, SphericalMap<T>, \ldots})
126\item[] {\bf SUtils/} This module contains few utility classes, such as the
127{\tt DataCard} class, as well as string manipulation functions in C and C++.
128\item[] {\bf SysTools/} This module contains classes implementing
129an interface to various OS specific services, such
130threads and dynamic link/shared library handling.
131
132\end{itemize}
133
134The modules listed below are more tightly related to the
135CMB (Cosmic Microwave Background) data analysis problem:
136\begin{itemize}
137\item[] {\bf SkyT/}
138classes for spectral emission and detector frequency response modelling \\
139({\tt SpectralResponse, RadSpectra, BlackBody} \ldots)
140\item[] {\bf Samba/} Spherical harmonic analysis, noise generators \ldots
141\end{itemize}
142
143The following modules contain the interface classes with
144external libraries:
145\begin{itemize}
146\item[] {\bf FitsIOServer/} Classes for handling file input-output
147in FITS format using the cfitsio library.
148FITS is maintained by NASA and SAO and is available from: \\
149\href{http://heasarc.gsfc.nasa.gov/docs/software/fitsio/fitsio.html}
150{http://heasarc.gsfc.nasa.gov/docs/software/fitsio/fitsio.html}
151\item[] {\bf LinAlg/} Interface with Lapack linear algebra package.
152Lapack is a linear algebra package and can be downloaded from: \\
153\href{http://www.netlib.org/lapack/}{http://www.netlib.org/lapack/}
154\item[] {\bf IFFTW/} Interface with FFTW package (libfftw.a).
155FFTW is a package for performing Fourier transforms, written in C.
156Documentation and source code can be found at: \\
157\href{http://www.fftw.org/}{http://www.fftw.org/}
158\item[] {\bf XAstroPack/} Interface to some common astronomical
159computation libraries. Presently, this module uses an external library
160extracted from the {\bf Xephem } source code. The corresponding source
161code is also available from SOPHYA cvs repository, module {\bf XephemAstroLib}.
162Information on Xephem can be found at : \\
163\href{http://www.clearskyinstitute.com/xephem/}{http://www.clearskyinstitute.com/xephem/}
164\item[] {\bf MinuitAdapt/} Wrapper classes to CERN minimization routines (Minuit).
165
166\end{itemize}
167
168The following modules contain each a set of related programs using the
169SOPHYA library.
170\begin{itemize}
171\item[] {\bf Tests/} Simple test programs
172\item[] {\bf PrgUtil/} Various utility programs (runcxx, scanppf, scanfits, \ldots)
173\item[] {\bf PrgMap/} Programs performing operations on skymaps: projections,
174power spectrum in harmonic space, \ldots
175\item[] {\bf PMixer/} skymixer and related programs
176\end{itemize}
177
178As a companion to SOPHYA, the {\bf (s)piapp} interactive data analysis
179program is built on top of SOPHYA and the {\bf PI} GUI class library
180and application framework. The {\bf PI} ({\bf P}eida {\bf Interactive})
181development started in 1995, in the EROS \footnote{EROS: {\bf E}xp\'erience
182de {\bf R}echerche d'{\bf O}bjets {\bf S}ombres - http://eros.in2p3.fr}
183microlensing search collaboration, with PEIDA++ \footnote {PEIDA++:
184The EROS data analysis class library -
185http://www.lal.in2p3.fr/recherche/eros/PeidaDoc/}.
186The {\bf PI} documentation and the {\bf piapp} user's guide are available
187from \href{http://www.sophya.org}{http://www.sophya.org}.
188%\href{http://www.sophya.org}{http://www.sophya.org}.
189The {\bf PI} is organized as the following modules:
190\begin{itemize}
191\item[] {\bf PI/} Portable GUI class library and application development
192framework kernel.
193\item[] {\bf PIGcont/} Contour-plot drawing classes.
194\item[] {\bf PIext/} Specific drawers and adapters for SOPHYA objects,
195and the {\bf piapp} interactive data analysis framework.
196\item[] {\bf ProgPI/} interactive analysis tool main program and pre-loaded
197modules.
198\end{itemize}
199
200Modules containing examples and demo programs and scripts:
201\begin{itemize}
202\item[] {\bf Examples/} Sample SOPHYA codes and example programs and
203makefiles.
204\item[] {\bf DemoPIApp/} Sample scripts and programs for (s)piapp
205interactive analysis tools.
206\end{itemize}
207\newpage
208
209\section{Using Sophya}
210The organisation of SOPHYA directories and some of the associated
211utility programs are described in this section.
212Basic usage of Sophya classes are described in in the following sections.
213Complete Sophya documentation can be found at our web site
214{\bf http://www.sophya.org}.
215
216\subsection{Directories, environment variables, configuration files}
217\label{directories}
218The environment variable {\bf SOPHYABASE} is used
219to define the path where the Sophya libraries and binaries are installed.
220\begin{itemize}
221\item \$SOPHYABASE/include : Include (.h) files
222\item \$SOPHYABASE/lib : Path for the archive libraries (.a)
223\item \$SOPHYABASE/slb: Shared library path (.so or .dylib on Darwin/MacOS)
224\item \$SOPHYABASE/exe : Path for binary program files
225\end{itemize}
226
227The directory { \tt \$SOPHYABASE/include/SophyaConfInfo/ } contains files
228describing the installed configuration of SOPHYA software.
229
230The file { \tt \$SOPHYABASE/include/machdefs.h } contains definitions
231(flags, typedef) used in SOPHYA, while some more specific flags,
232are found in { \tt \$SOPHYABASE/include/sspvflags.h }
233
234The file { \tt \$SOPHYABASE/include/sophyamake.inc } contains the
235compilation commands and flags used for building the software.
236Users can use most of compilation and link commands defined in this file:
237 {\tt \$CCOMPILE , \$CXXCOMPILE . \$CXXLINK \ldots}.
238 (See module Example).
239
240The configure script (BuildMgr/configure) creates the directory tree and the
241above files. It also copy (or create symbolic link) for all SOPHYA include
242files as well as symbolic links for external libraries
243include files path in {\tt \$SOPHYABASE/include} (FitsIO, FFTW, XAstro \ldots).
244
245Object files for each module are grouped in a static archive library
246by the build procedure (libXXX.a for module
247XXX, with XXX = BaseTools, TArray, HiStats, FitsIOServer \ldots).
248
249When shared libraries are build, all stand alone SOPHYA modules
250are grouped in {\tt libsophya.so}, {\tt libextsophya.so} contains
251the interface modules with external libraries {\bf (FitsIOServer, LinAlg \ldots)},
252while {\bf PI, PIext, PIGcont} modules are grouped in {\tt libPI.so}.
253Alternatively, it is possible to group all modules in a single shared
254library {\tt libAsophyaextPI.so} (See \ref{build})
255
256In order to use the shared libraries, the {\bf LD\_LIBRARY\_PATH} variable
257should contain the Sophya shared library path
258({\tt \$SOPHYABASE/slb}).
259On Silicon Graphics machines with IRIX64 operating system,
260the default SOPHYA configuration correspond to the 64 bit architecture.
261The environment variable { \bf LD\_LIBRARY64\_PATH } replace in
262this case the usual {\bf LD\_LIBRARY\_PATH} variable.
263On IBM machines with AIX, the {\bf LIBPATH} environment variables
264contains the shared libraries search path.
265
266When using the dynamic load services in SOPHYA ({\tt PDynLinkMgr}
267class), in runcxx or (s)piapp applications for example, the shared
268library search path must contain the current working directory (
269dot . in unix).
270
271\subsection{the runcxx program}
272\index{runcxx}
273{\bf runcxx} is a simple program which can be used to compile, link
274and run simple C++ programs. It handles the creation of a
275complete program file, containing the basic set C++ include files,
276the necessary include files for SOPHYA SysTools, TArray, HiStats
277and NTools modules, and the main program with exception handling.
278Other Sophya modules can be included using the {\tt -import} flag.
279Use of additional include files can be specified using the
280{\tt -inc} flag.
281\begin{verbatim}
282csh> runcxx -h
283 PIOPersist::Initialize() Starting Sophya Persistence management service
284SOPHYA Version 1.9 Revision 0 (V_Mai2005) -- May 31 2005 15:11:32 cxx
285 runcxx : compiling and running of a piece of C++ code
286 Usage: runcxx [-compopt CompileOptions] [-linkopt LinkOptions]
287 [-tmpdir TmpDirectory] [-f C++CodeFileName]
288 [-inc includefile] [-inc includefile ...]
289 [-import modulename] [-import modulename ...]
290 [-uarg UserArg1 UserArg2 ...]
291 if no file name is specified, read from standard input
292 modulenames: SkyMap, Samba, SkyT, FitsIOServer,
293 LinAlg, IFFTW, XAstroPack
294\end{verbatim}
295Most examples in this manual can be tested using runcxx. The
296example below shows how to compile, link and run a sample
297code.
298\begin{verbatim}
299// File example.icc
300Matrix a(3,3);
301a = IdentityMatrix(1.);
302cout << a ;
303// Executing this sample code
304csh> runcxx -f example.icc
305\end{verbatim}
306
307\subsection{the scanppf program}
308{\bf scanppf} is a simple SOPHYA application which can be used to check
309PPF files and list their contents. It can also provide the list of all registered
310PPF handlers.
311\begin{verbatim}
312csh> scanppf -h
313 PIOPersist::Initialize() Starting Sophya Persistence management service
314SOPHYA Version 2.0 Revision 0 (V_Jul2006) -- Jul 17 2006 14:13:27 cxx
315 Usage: scanppf [flags] filename
316 flags = -s -n -a0 -a1 -a2 -a3 -lh -lho -lmod
317 -s[=default} : Sequential reading of objects
318 -n : Object reading at NameTags
319 -a0...a3 : Tag List with PInPersist.AnalyseTags(0...3)
320 -lh : List PPersist handler classes
321 -lho : List PPersist handler and dataobj classes
322 -lmod : List initialized/registered modules
323\end{verbatim}
324
325\subsection{the scanppf program}
326{\bf scanfits} is a SOPHYA program using the FitsIOServer
327\footnote{FitsIOServer module uses the cfitsio library. scanfits has to be linked with
328with FitsIOServer module and cfitsio libraries, or libextsophya.so}
329module which can be used
330to analyse the content of FITS files. It can list the FITS headers, the appropriate
331SOPHYA-FITS handler (implementing {\tt FitsHandlerInterface}) class, and the list of
332all registered FITS handlers.
333\begin{verbatim}
334csh> scanfits -h
335 SophyaInitiator::SophyaInitiator() BaseTools Init
336 PIOPersist::Initialize() Starting Sophya Persistence management service
337SOPHYA Version 1.9 Revision 33 (V_Mar2006) -- Apr 3 2006 14:04:07 gcc 3.3 20030304 (Apple Computer, Inc. build 1495)
338 Usage: scanfits [flags] filename
339 flags = -V1 -lh -rd -header
340 -V1 : Scan using old (V1) code version
341 -lh : Print the list of registered handlers (FitsHandlerInterface)
342 -rd : try to read each HDU data using appropriate handler
343 -header : List header information
344\end{verbatim}
345
346\newpage
347
348\section{Copy constructor and assignment operator}
349\label{memgt}
350In C++, objects can be copied by assignment or by initialisation.
351Copying by initialisation corresponds to creating an object and
352initialising its value through the copy constructor.
353The copy constructor has its first argument as a reference, or
354const reference to the object's class type. It can have
355more arguments, if default values are provided.
356Copying by assignment applies to an existing object and
357is performed through the assignment operator (=).
358The copy constructor implements this for identical type objects:
359\begin{verbatim}
360class MyObject {
361public:
362 MyObject(); // Default constructor
363 MyObject(MyObject const & a); // Copy constructor
364 MyObject & operator = (MyObject const & a) // Assignment operator
365}
366\end{verbatim}
367The copy constructors play an important role, as they are
368called when class objects are passed by value,
369returned by value, or thrown as an exception.
370\begin{verbatim}
371// A function declaration with an argument of type MyObject,
372// passed by value, and returning a MyObject
373MyObject f(MyObject x)
374{
375 MyObject r;
376 ...
377 return(r); // Copy constructor is called here
378}
379// Calling the function :
380MyObject a;
381f(a); // Copy constructor called for a
382\end{verbatim}
383It should be noted that the C++ syntax is ambiguous for the
384assignment operator. {\tt MyObject x; x=y; } and
385{\tt MyObject x=y;} have different meaning.
386\begin{verbatim}
387MyObject a; // default constructor call
388MyObject b(a); // copy constructor call
389MyObject bb = a; // identical to bb(a) : copy constructor call
390MyObject c; // default constructor call
391c = a; // assignment operator call
392\end{verbatim}
393
394As a general rule in SOPHYA, objects which implements
395reference sharing on their data members have a copy constructor
396which shares the data, while the assignment operator copies or
397duplicate the data.
398
399\newpage
400\section{Module BaseTools}
401
402{\bf BaseTools} contains utility classes such as
403{\tt DVlist}, an hierarchy of exception classes for Sophya, a template
404class {\tcls{NDataBlock}} for handling reference counting on numerical
405arrays, as well as classes providing the services for implementing simple
406serialisation.
407\vspace*{5mm}
408
409\subsection{Initialisation}
410\index{SophyaInitiator}
411A number of actions have to be taken before
412some of the services provided by SOPHYA become operational. This is the case
413of SOPHYA persistence, as well as FITS I/O facilities.
414Initialisation of many SOPHYA modules is performed through an initialiser class,
415which inherits from {\bf SophyaInitiator}. Static instance of each
416initialiser class exist in the library and the various SOPHYA services
417should be operational when the user code ({\tt main()}) starts.
418However, in some cases the run time loader may not perform correctly the static
419object initialisation. You may thus need to instanciate the initialiser class
420for the modules you use in the beginning of your main program: \\
421{\tt TArrayInitiator , HiStatsInitiator , SkyMapInitiator \ldots }
422%%%
423\subsection{SOPHYA persistence}
424\label{ppfdesc}
425\index{PPersist} \index{PInPersist} \index{POutPersist}
426\begin{figure}[hbt]
427\dclsa{PPersist}
428\dclsccc{PPFBinarIOStream}{PPFBinaryInputStream}{PInPersist}
429\dclscc{PPFBinaryOutputStream}{POutPersist}
430\caption{partial class diagram for classes handling persistence in Sophya}
431\end{figure}
432A simple persistence mechanism is defined in SOPHYA. Its main
433features are:
434\begin{itemize}
435\item[] Portable file format, containing the description of the data structures
436and object hierarchy. \\
437{\bf PPF} {\bf P}ortable {\bf P}ersistence file {\bf F}ormat.
438\index{PPF}
439\item[] Handling of read/write for multiply referenced objects.
440\item[] All write operations are carried using sequential access only. This
441holds also for read operations, unless positional tags are used.
442SOPHYA persistence services can thus be used to transfer objects
443through network links.
444\item[] The serialisation (reading/writing) for objects for a given class
445is implemented through a handler object. The handler class inherits
446from {\tt PPersist} class.
447\item[] A run time registration mechanism is used in conjunction with
448RTTI (Run Time Type Identification) for identifying handler classes
449when reading {\bf PInPersist} streams, or for associating handlers
450with data objects {\bf AnyDataObject} for write operations.
451\end{itemize}
452A complete description of SOPHYA persistence mechanism and guidelines
453for writing delegate classes for handling object persistence is beyond
454the scope of this document. The most useful methods for using Sophya
455persistence are listed below:
456\begin{itemize}
457\item[] {\tt POutPersist::PutObject(AnyDataObj \& o)} \\
458Writes the data object {\bf o} to the output stream.
459\item[] {\tt POutPersist::PutObject(AnyDataObj \& o, string tagname)} \\
460Writes the data object {\bf o} to the output stream, associated with an
461identification tag {\bf tagname}.
462\item[] {\tt PInPersist::GetObject(AnyDataObj \& o)} \\
463Reads the next object in stream into {\bf o}. An exception is
464generated for incompatible object types.
465\item[] {\tt PInPersist::GetObject(AnyDataObj \& o, string tagname)} \\
466Reads the object associated with the tag {\bf tagname} into {\bf o}.
467An exception is generated for incompatible object types.
468\end{itemize}
469The operators {\tt operator << (POutPersist ...) } and
470{\tt operator >> (PInPersist ...) } are often overloaded
471to perform {\tt PutObject()} and {\tt GetObject()} operations.
472the {\bf PPFNameTag} (ppfnametag.h) class can be used in conjunction with
473{\tt << >> } operators to write objects with a name tag or to retrieve
474an object identified with a name tag. The example below shows the
475usage of these operators:
476\begin{verbatim}
477// Creating and filling a histogram
478Histo hw(0.,10.,100);
479...
480// Writing histogram to a PPF stream
481POutPersist os("hw.ppf");
482os << PPFNameTag("myhisto") << hw;
483
484// Reading a histogram from a PPF stream
485PInPersist is("hr.ppf");
486is >> PPFNameTag("myhisto") >> hr;
487\end{verbatim}
488
489The {\bf scanppf} program can be used to list the content of a PPF file.
490
491\subsection{\tcls{NDataBlock}}
492\index{\tcls{NDataBlock}}
493\begin{figure}[hbt]
494\dclsbb{AnyDataObj}{\tcls{NDataBlock}}
495\dclsbb{PPersist}{\tcls{FIO\_NDataBlock}}
496\end{figure}
497The {\bf \tcls{NDataBlock}} is designed to handle reference counting
498and sharing of memory blocs (contiguous arrays) for numerical data
499types. Initialisation, resizing, basic arithmetic operations, as
500well as persistence handling services are provided.
501The persistence handler class ({\tt \tcls{FIO\_NDataBlock}}) insures
502that a single copy of data is written for multiply referenced objects,
503and the data is shared among objects when reading.
504\par
505The example below shows writing of NDataBlock objects through the
506use of overloaded operator $ << $ :
507\begin{verbatim}
508#include "fiondblock.h"
509// ...
510POutPersist pos("aa.ppf");
511NDataBlock<r_4> rdb(40);
512rdb = 567.89;
513pos << rdb;
514// We can also use the PutObject method
515NDataBlock<int_4> idb(20);
516idb = 123;
517pos.PutObject(idb);
518\end{verbatim}
519The following sample programs show the reading of the created PPF file :
520\begin{verbatim}
521PInPersist pis("aa.ppf");
522NDataBlock<r_4> rdb;
523pis >> rdb;
524cout << rdb;
525NDataBlock<int_4> idb;
526cout << idb;
527\end{verbatim}
528
529\subsection{DVList, MuTyV and TimeStamp classes}
530\index{DVList} \index{MuTyV} \index{TimeStamp}
531\begin{figure}[hbt]
532\dclsa{MuTyV}
533\dclsbb{AnyDataObj}{DVList}
534\dclsbb{PPersist}{\tclsc{ObjFileIO}{DVList}}
535\end{figure}
536The {\bf DVList} class objects can be used to create and manage list
537of values, associated with names. A list of pairs of (MuTyV, name(string))
538is maintained by DVList objects. {\bf MuTyV} is a simple class
539capable of holding string, integer, float or complex values,
540providing easy conversion methods between these objects.
541{\bf MuTyV} objects can also hold {\bf TimeStamp } objects.
542\begin{verbatim}
543// Using MuTyV objects
544MuTyV s("hello"); // string type value
545MuTyV x;
546x = "3.14159626"; // string type value, ASCII representation for Pi
547double d = x; // x converted to double = 3.141596
548x = 314; // x contains the integer value = 314
549// Using DVList
550DVList dvl;
551dvl("Pi") = 3.14159626; // float value, named Pi
552dvl("Log2") = 0.30102999; // float value, named Log2
553dvl("FileName") = "myfile.fits"; // string value, named myfile.fits
554// Printing DVList object
555cout << dvl;
556\end{verbatim}
557
558\begin{figure}[hbt]
559\dclsbb{AnyDataObj}{TimeStamp}
560\end{figure}
561%
562The {\bf TimeStamp} class represent date and time and provides
563many standard operations, such as Initialisation from strings,
564conversion to strings and time interval computations. \\
565Usage example:
566\begin{verbatim}
567// Create a object with the current date and time and prints it to cout
568TimeStamp ts;
569cout << ts << endl;
570// Create an object with a specified date and time
571TimeStamp ts2("01/01/1905","00:00:00");
572// Get the number of days since 0 Jan 1901
573cout << ts2.ToDays() << endl;
574
575// Combined use of TimeStamp and MuTyV
576string s;
577TimeStamp ts; // Current date/time
578MuTyV mvt = ts;
579s = mvt; // s contains the current date in string format
580cout << s << endl;
581\end{verbatim}
582
583\subsection{\tcls{SegDataBlock} , \tcls{SwSegDataBlock}}
584\begin{figure}[hbt]
585\dclsccc{AnyDataObj}{\tcls{SegDBInterface}}{ \tcls{SegDataBlock} }
586\dclscc{\tcls{SegDBInterface}}{ \tcls{SwSegDataBlock} }
587\end{figure}
588\begin{itemize}
589\item[] \tcls{SegDataBlock} handles arrays of object of
590type {\bf T} with reference sharing in memory. The array can be extended
591(increase in array size) with fixed segment size. It implements the interface
592defined by \tcls{SegDBInterface}.
593\item[] \tcls{SwSegDataBlock} Implements the same \tcls{SegDBInterface}
594using a data swapper object. Data swappers implement the interface defined in
595(\tcls{DataSwapperInterface} class. \tcls{SwSegDataBlock} can
596thus be used to handle arrays with very large number of objects.
597These classes handles reference sharing.
598\end{itemize}
599
600\newpage
601\section{Module TArray}
602\index{\tcls{TArray}}
603{\bf TArray} module contains template classes for handling standard
604operations on numerical arrays. Using the class {\tt \tcls{TArray} },
605it is possible to create and manipulate up to 5-dimension numerical
606arrays {\tt (int, float, double, complex, \ldots)}. The include
607file {\tt array.h} declares all the classes and definitions
608in module TArray. {\bf Array} is a typedef for arrays
609with double precision floating value elements. \\
610{\tt typedef TArray$<$r\_8$>$ Array ; }
611
612\begin{figure}[hbt]
613\dclsccc{AnyDataObj}{BaseArray}{\tcls{TArray}}
614\dclsbb{PPersist}{\tcls{FIO\_TArray}}
615\end{figure}
616
617The development of this module started around 1999-2000,
618after evaluation of a number of publicly available
619C++ array hadling packages, including TNT, Lapack++, Blitz++,
620as well as commercial packages from RogueWave (math.h++ \ldots).
621Most of these packages provide interesting functionalities, however,
622not any one package seemed to fulfill most of our requirements.
623\begin{itemize}
624\item Capability to handle {\bf large - multidimensional - dense}
625arrays, for numerical data types. Although we have used templates, for
626data type specialisation, the actual code, apart inline functions is
627not in header files. Instead, we use explicit instanciation, and the
628compiled code for the various numerical types of arrays is the
629library .
630\item The shape and size of the arrays can be defined and changed
631at run time. The classes ensure the memory management of the
632created objets, with reference sharing for the array data.
633The default behaviour of the copy constructor is to share the data,
634avoiding expensive memory copies.
635\item The package provides transparent management of sub-arrays
636and slices, in an intuitive way, somehow similar to what is
637available in Mathlab or Scilab.
638\item The memory organisation for arrays, specially matrices
639(row-major or column major) can be
640controled. This provide compatibility when using existing C or
641Fortran coded numerical libraries.
642\item The classes provide efficient methods to perform basic arithmetic
643and mathematical operations on arrays. In addition, operator overload
644provides intuitive programming for element acces and most basic
645arithmetic operations.
646\item Conversion can be performed between arrays with different
647data types. Copy and arithmetic operations can be done transparently
648between arrays with different memory organisation patterns.
649\item This module does not provide more complex operations
650such as FFT or linear algebra. Additional libraries are used, with interface
651classes for these operations.
652\item ASCII formatted I/O, for printing and read/write operations to/from text files.
653\item Efficient binary I/O for object persistence (PPF format), or import/export
654to other data formats, such as FITS are provided by helper or handler classes.
655\end{itemize}
656
657\subsection{Using arrays}
658\index{Sequence} \index{RandomSequence} \index{RegularSequence}
659\index{EnumeratedSequence}
660The example below shows basic usage of arrays, creation, initialisation
661and arithmetic operations. Different kind of {\bf Sequence} objects
662can be used for initialising arrays.
663
664\begin{figure}[hbt]
665\dclsbb{Sequence}{RandomSequence}
666\dclsb{RegularSequence}
667\dclsb{EnumeratedSequence}
668\end{figure}
669
670The example below shows basic usage of arrays:
671\index{\tcls{TArray}}
672\begin{verbatim}
673// Creating and initialising a 1-D array of integers
674TArray<int> ia(5);
675EnumeratedSequence es;
676es = 24, 35, 46, 57, 68;
677ia = es;
678cout << "Array<int> ia = " << ia;
679// 2-D array of floats
680TArray<r_4> b(6,4), c(6,4);
681// Initializing b with a constant
682b = 2.71828;
683// Filling c with random numbers
684c = RandomSequence();
685// Arithmetic operations
686TArray<r_4> d = b+0.3f*c;
687cout << "Array<float> d = " << d;
688\end{verbatim}
689
690The copy constructor shares the array data, while the assignment operator
691copies the array elements, as illustrated in the following example:
692\begin{verbatim}
693TArray<int> a1(4,3);
694a1 = RegularSequence(0,2);
695// Array a2 and a1 shares their data
696TArray<int> a2(a1);
697// a3 and a1 have the same size and identical elements
698TArray<int> a3;
699a3 = a1;
700// Changing one of the a2 elements
701a2(1,1,0) = 555;
702// a1(1,1) is also changed to 555, but not a3(1,1)
703cout << "Array<int> a1 = " << a1;
704cout << "Array<int> a3 = " << a3;
705\end{verbatim}
706
707\subsection{Matrices and vectors}
708\index{\tcls{TMatrix}} \index{\tcls{TVector}}
709\begin{figure}[hbt]
710\dclsccc{\tcls{TArray}}{\tcls{TMatrix}}{\tcls{TVector}}
711\end{figure}
712Vectors and matrices are 2 dimensional arrays. The array size
713along one dimension is equal 1 for vectors. Column vectors
714have {\tt NCols() = 1} and row vectors have {\tt NRows() = 1}.
715Mathematical expressions involving matrices and vectors can easily
716be translated into C++ code using {\tt TMatrix} and
717{\tt TVector} objects. {\bf Matrix} and {\bf Vector} are
718typedefs for double precision float matrices and vectors.
719The operator {\bf *} beteween matrices is redefined to
720perform matrix multiplication. One can then write: \\
721\begin{verbatim}
722 // We create a row vector
723 Vector v(1000, BaseArray::RowVector);
724 // Initialize values with a random sequence
725 v = RandomSequence();
726 // Compute the vector length (norm)
727 double norm = (v*v.Transpose()).toScalar();
728 cout << "Norm(v) = " << norm << endl;
729\end{verbatim}
730
731This module contains basic array and matrix operations
732such as the Gauss matrix inversion algorithm
733which can be used to solve linear systems, as illustrated by the
734example below:
735\begin{verbatim}
736#include "sopemtx.h"
737// ...
738// Creation of a random 5x5 matrix
739Matrix A(5,5);
740A = RandomSequence(RandomSequence::Flat);
741Vector X0(5);
742X0 = RandomSequence(RandomSequence::Gaussian);
743// Computing B = A*X0
744Vector B = A*X0;
745// Solving the system A*X = B
746Vector X;
747LinSolve(A, B, X);
748// Checking the result
749Vector diff = X-X0;
750cout << "X-X0= " << diff ;
751double min,max;
752diff.MinMax(min, max);
753cout << " Min(X-X0) = " << min << " Max(X-X0) = " << max << endl;
754\end{verbatim}
755
756{\bf Warning: } The operations defined in {\tt sopemtx.h}, such as
757matrix inversion and linear system solver use a basic Gauss pivot
758algorithm which are not adapted for large matrices ($>\sim 100x100$).
759The services provided in other modules, such as {\bf LinAlg} should
760be preferred in such cases.
761
762\subsection{Working with sub-arrays and Ranges}
763\index{Range}
764A powerful mechanism is included in array classes for working with
765sub-arrays. The class {\bf Range} can be used to specify range of array
766indexes in any of the array dimensions. Any regularly spaced index
767range can be specified, using the {\tt start} and {\tt end} index
768and an optional step (or stride). It is also possible to specify
769the {\tt start} index and the number of elements.
770\begin{itemize}
771\item {\bf Range::all()} {\tt = Range(Range::firstIndex(), Range::lastIndex())} \\
772return a Range objects representing all valid indexes along the
773corresponding axe.
774\item {\bf Range::first()} {\tt = Range(Range::firstIndex())} \\
775return a Range object representing the first valid index
776\item {\bf Range::last()} {\tt = Range(Range::lastIndex())}
777return a Range object representing the last valid index
778\item {\bf Range(idx)} represents a single index ({\bf = idx})
779\item {\bf Range(first, last)} represents the range of indices
780{\bf first} $\leq$ index $\leq$ {\bf last}.
781The static method {\tt Range::lastIndex()} can be used
782to specify the last valid index.
783\item {\bf Range(first, last, step)} represents the range of index
784which is equivalent to \\ {\tt for(index=first; index <= last; index += step) }
785\item { \bf Range (first, last, size, step) } the general form can be used
786to specify an index range, using the number of elements.
787It is possible to specify a range of index, ending with the last valid index.
788For example \\
789\hspace*{5mm}
790{\tt Range(Range::lastIndex(), Range::lastIndex(), 3, 2) } \\
791defines the index range: \hspace*{5mm} last-4, last-2, last.
792
793\begin{center}
794\begin{tabular}{ll}
795\hline \\
796\multicolumn{2}{c}{ {\bf Range} {\tt (start, end, size, step) } } \\[2mm]
797\hline \\
798{\bf Range} {\tt r(7); } & index range: \hspace{2mm} 7 \\
799{\bf Range} {\tt r(3,6); } & index range: \hspace{2mm} 3,4,5,6 \\
800{\bf Range} {\tt r(3,7,2); } & index range: \hspace{2mm} 3,5,7 \\
801{\bf Range} {\tt r(7,0,3,1); } & index range: \hspace{2mm} 7,8,9 \\
802{\bf Range} {\tt r(10,0,5,2); } & index range: \hspace{2mm} 10,12,14,16,18 \\[2mm]
803\hline
804\end{tabular}
805\end{center}
806\end{itemize}
807
808The method {\tt TArray<T>SubArray(Range ...)} can be used
809to extract subarrays and slices. The operator {\tt operator() (Range rx, Range ry ...)}
810is also overloaded for sub-array extraction.
811For matrices, {\tt TMatrix<T>::Row()} and {\tt TMatrix<T>::Column()}
812extract selected matrix rows and columns.
813
814The example illustrates the sub-array extraction using Range objects:
815\begin{verbatim}
816 // Creating and initialising a 2-D (6 x 4) array of integers
817 TArray<int> iaa(6, 4);
818 iaa = RegularSequence(1,2);
819 cout << "Array<int> iaa = \n" << iaa;
820 // We extract a sub-array - data is shared with iaa
821 TArray<int> iae = iaa(Range(1, Range::lastIndex(), 3) ,
822 Range::all(), Range::first() );
823 cout << "Array<int> iae=subarray(iaa) = \n" << iae;
824 // Changing iae elements changes corresponding iaa elements
825 iae = 0;
826 cout << "Array<int> iae=0 --> iaa = \n" << iaa;
827
828\end{verbatim}
829
830In the following example, a simple low-pass filter, on a one
831dimensional stream (Vector) has been written using sub-arrays:
832
833\begin{verbatim}
834// Input Vector containing a noisy periodic signal
835 Vector in(1024), out(1024);
836 in = RandomSequence(RandomSequence::Gaussian, 0., 1.);
837 for(int kk=0; kk<in.Size(); kk++)
838 in(kk) += 2*sin(kk*0.05);
839// Compute the output vector by a simple low pass filter
840 Vector out(1024);
841 int w = 2;
842 for(int k=w; k<in.Size()-w; k++)
843 out(k) = in(Range(k-w, k+w).Sum()/(2.*w+1.);
844\end{verbatim}
845
846\subsection{Input, Output}
847Arrays can easily be saved to, or restored from files in different formats.
848SOPHYA library can handle array I/O to ASCII formatted files, to PPF streams,
849as well as to files in FITS format.
850FITS format input/output is provided through the classes in
851{\bf FitsIOServer} module. Onnly arrays with data types
852supported by the FITS standard can be handled during
853I/O operations to and from FITS streams (See the FitsIOServer section
854for additional details).
855
856\subsubsection{PPF streams}
857
858SOPHYA persistence (PPF streams) handles reference sharing, and multiply
859referenced objects are only written once. A hierarchy of arrays and sub-arrays
860written to a PPF stream is thus completely recovered, when the stream is read.
861The following example illustrates this point:
862\begin{verbatim}
863{
864// Saving an array with a sub-array into a POutPersist file
865Matrix A(3,4);
866A = RegularSequence(10,5);
867// Create a sub-array of A
868Matrix AS = A(Range(1,2), Range(2,3));
869// Save the two arrays to a PPF stream
870POutPersist pos("aas.ppf");
871pos << A << AS;
872}
873{
874// Reading arrays from the previously created PPF file aas.ppf
875PInPersist pis("aas.ppf");
876Matrix B,BS;
877pis >> B >> BS;
878// BS is a sub-array of B, modifying BS changes also B
879BS(1,1) = 98765.;
880cout << " B , BS after BS(1,1) = 98765. "
881 << B << BS << endl;
882}
883\end{verbatim}
884The execution of this sample code creates the file {\tt aas.ppf} and
885its output is reproduced here. Notice that the array hierarchy is
886recovered. BS is a sub-array of B, and modifying BS changes also
887the corresponding element in B.
888\begin{verbatim}
889 B , BS after BS(1,1) = 98765.
890
891--- TMatrix<double>(NRows=3, NCols=4) ND=2 SizeX*Y*...= 4x3 ---
89210 15 20 25
89330 35 40 45
89450 55 60 98765
895
896--- TMatrix<double>(NRows=2, NCols=2) ND=2 SizeX*Y*...= 2x2 ---
89740 45
89860 98765
899\end{verbatim}
900
901\centerline{\bf Warning: }
902
903There is a drawback in this behaviour: only a single
904copy of an array is written to a file, even if the array is modified,
905without being resized and written to a PPF stream.
906\begin{verbatim}
907{
908POutPersist pos("mca.ppf");
909TArray<int_4> ia(5,3);
910ia = 8;
911pos << ia;
912ia = 16;
913pos << ia;
914ia = 32;
915pos << ia;
916}
917\end{verbatim}
918
919Only a single copy of the data is effectively written to the output
920PPF file, corresponding to the value 8 for array elements. When we
921read the three array from the file mca.ppf, the same array elements
922are obtained three times (all elements equal to 8):
923\begin{verbatim}
924{
925PInPersist pis("mca.ppf");
926TArray<int_4> ib;
927pis >> ib;
928cout << " First array read from mca.ppf : " << ib;
929pis >> ib;
930cout << " Second array read from mca.ppf : " << ib;
931pis >> ib;
932cout << " Third array read from mca.ppf : " << ib;
933}
934\end{verbatim}
935
936\subsubsection{ASCII streams}
937
938The {\bf WriteASCII} method can be used to dump an array to an ASCII
939formatted file, while the {\bf ReadASCII} method can be used to decode
940ASCII formatted files. Space or tabs are the possible separators.
941Complex numbers should be specified as a pair of comma separated
942real and imaginary parts, enclosed in parenthesis.
943
944\begin{verbatim}
945{
946// Creating array A and writing it to an ASCII file (aaa.txt)
947Array A(4,6);
948A = RegularSequence(0.5, 0.2);
949ofstream ofs("aaa.txt");
950A.WriteASCII(ofs);
951}
952{
953// Decoding the ASCII file aaa.txt
954ifstream ifs("aaa.txt");
955Array B;
956sa_size_t nr, nc;
957B.ReadASCII(ifs,nr,nc);
958cout << " Array B; B.ReadASCII() from file " << endl;
959cout << B ;
960}
961\end{verbatim}
962
963
964\subsection{Complex arrays}
965The {\bf TArray} module provides few functions for manipulating
966arrays of complex numbers (single and double precision).
967These functions are declared in {\tt matharr.h}.
968\begin{itemize}
969\item[\bul] Creating a complex array through the specification of the
970real and imaginary parts.
971\item[\bul] Functions returning arrays corresponding to real and imaginary
972parts of a complex array: {\tt real(za) , imag(za) }
973({\bf Warning:} Note that the present implementation does not provide
974shared memory access to real and imaginary parts.)
975\item[\bul] Functions returning arrays corresponding to the module,
976phase, and module squared of a complex array:
977 {\tt phase(za) , module(za) , module2(za) }
978\end{itemize}
979
980\begin{verbatim}
981 TVector<r_4> p_real(10, BaseArray::RowVector);
982 TVector<r_4> p_imag(10, BaseArray::RowVector);
983 p_real = RegularSequence(0., 0.5);
984 p_imag = RegularSequence(0., 0.25);
985 TVector< complex<r_4> > zvec = ComplexArray(p_real, p_imag);
986 cout << " :: zvec= " << zvec;
987 cout << " :: real(zvec) = " << real(zvec) ;
988 cout << " :::: imag(zvec) = " << imag(zvec) ;
989 cout << " :::: module2(zvec) = " << module2(zvec) ;
990 cout << " :::: module(zvec) = " << module(zvec) ;
991 cout << " :::: phase(zvec) = " << phase(zvec) ;
992\end{verbatim}
993
994The decoding of complex numbers from an ASCII formatted stream
995is illustrated by the next example. As mentionned already,
996complex numbers should be specified as a pair of comma separated
997real and imaginary parts, enclosed in parenthesis.
998
999\begin{verbatim}
1000csh> cat zzz.txt
1001(1.,-1) (2., 2.5) -3. 12.
1002-24. (-6.,7.) 14.2 (8.,64.)
1003
1004// Decoding of complex numbers from an ASCII file
1005// Notice that the << operator can be used instead of ReadASCII
1006TArray< complex<r_4> > Z;
1007ifstream ifs("zzz.txt");
1008ifs >> Z;
1009cout << " TArray< complex<r_4> > Z from file zzz.txt " << Z ;
1010\end{verbatim}
1011
1012
1013\subsection{Memory organisation}
1014{\tt \tcls{TArray} } can handle numerical arrays with various memory
1015organisation, as long as the spacing (steps) along each axis is
1016regular. The five axis are labeled X,Y,Z,T,U. The examples below
1017illustrates the memory location for a 2-dimensional, $N_x=4 \times N_y=3$.
1018The first index is along the X axis and the second index along the Y axis.
1019\begin{verbatim}
1020 | (0,0) (0,1) (0,2) (0,3) |
1021 | (1,0) (1,1) (1,2) (1,3) |
1022 | (2,0) (2,1) (2,2) (2,3) |
1023\end{verbatim}
1024In the first case, the array is completely packed
1025($Step_X=1, Step_Y=N_X=4$), with zero offset,
1026while in the second case, $Step_X=2, Step_Y=10, Offset=10$:
1027\begin{verbatim}
1028 | 0 1 2 3 | | 10 12 14 16 |
1029Ex1 | 4 5 6 7 | Ex2 | 20 22 24 26 |
1030 | 8 9 10 11 | | 30 32 34 36 |
1031\end{verbatim}
1032
1033For matrices and vectors, an optional argument ({\tt MemoryMapping})
1034can be used to select the memory mapping, where two basic schemes
1035are available: \\
1036{\tt CMemoryMapping} and {\tt FortranMemoryMapping}. \\
1037In the case where {\tt CMemoryMapping} is used, a given matrix line
1038is packed in memory, while the columns are packed when
1039{\tt FortranMemoryMapping} is used. The first index when addressing
1040the matrix elements (line number index) runs along
1041the Y-axis if {\tt CMemoryMapping} is used, and along the X-axis
1042in the case of {\tt FortranMemoryMapping}.
1043Arithmetic operations between matrices
1044with different memory organisation is allowed as long as
1045the two matrices have the same sizes (Number of rows and columns).
1046The following code example and the corresponding output illustrates
1047these two memory mappings. The {\tt \tcls{TMatrix}::TransposeSelf() }
1048method changes effectively the matrix memory mapping, which is also
1049the case of {\tt \tcls{TMatrix}::Transpose() } method without argument.
1050
1051\begin{verbatim}
1052TArray<r_4> X(4,2);
1053X = RegularSequence(1,1);
1054cout << "Array X= " << X << endl;
1055TMatrix<r_4> X_C(X, true, BaseArray::CMemoryMapping);
1056cout << "Matrix X_C (CMemoryMapping) = " << X_C << endl;
1057TMatrix<r_4> X_F(X, true, BaseArray::FortranMemoryMapping);
1058cout << "Matrix X_F (FortranMemoryMapping) = " << X_F << endl;
1059\end{verbatim}
1060This code would produce the following output (X\_F = Transpose(X\_C)) :
1061\begin{verbatim}
1062Array X=
1063--- TArray<f> ND=2 SizeX*Y*...= 4x2 ---
10641, 2, 3, 4
10655, 6, 7, 8
1066
1067Matrix X_C (CMemoryMapping) =
1068--- TMatrix<f>(NRows=2, NCols=4) ND=2 SizeX*Y*...= 4x2 ---
10691, 2, 3, 4
10705, 6, 7, 8
1071
1072Matrix X_F (FortranMemoryMapping) =
1073--- TMatrix<f>(NRows=4, NCols=2) ND=2 SizeX*Y*...= 4x2 ---
10741, 5
10752, 6
10763, 7
10774, 8
1078\end{verbatim}
1079
1080\newpage
1081
1082\section{Module HiStats}
1083\begin{figure}[hbt]
1084\dclsbb{AnyDataObj}{Histo}
1085\dclscc{Histo}{HProf}
1086\dclscc{Histo}{HistoErr}
1087\dclsbb{AnyDataObj}{Histo2D}
1088\caption{partial class diagram for histograms and ntuples}
1089\end{figure}
1090
1091{\bf HiStats} contains classes for creating, filling, printing and
1092doing various operations on one or two dimensional histograms
1093{\tt Histo} and {\tt Histo2D} as well as profile histograms {\tt HProf}. \\
1094This module also contains {\tt NTuple} and {\tt DataTable} which are
1095more or less the same as the binary or ascii FITS tables.
1096
1097\subsection{Histograms}
1098\subsubsection{1D Histograms}
1099\index{Histo}
1100For 1D histograms, various numerical methods are provided such as
1101computing means and sigmas, finding maxima, fitting, rebinning,
1102integrating \dots \\
1103The example below shows creating and filling a one dimensional histogram
1104of 100 bins from $-5.$ to $+5.$ to create a Gaussian normal distribution
1105with errors~:
1106\begin{verbatim}
1107#include "histos.h"
1108// ...
1109Histo H(-0.5,0.5,100);
1110H.Errors();
1111for(int i=0;i<25000;i++) {
1112 double x = NorRand();
1113 H.Add(x);
1114}
1115H.Print(80);
1116\end{verbatim}
1117
1118\subsubsection{2D Histograms}
1119\index{Histo2D}
1120Much of these operations are also valid for 2D histograms. 1D projection
1121or slices can be set~:
1122\begin{verbatim}
1123#include "histos2.h"
1124// ...
1125Histo2D H2(-1.,1.,100,0.,60.,50);
1126H2.SetProjX(); // create the 1D histo for X projection
1127H2.SetBandX(25.,35.); // create 1D histo projection for 25.<y<35.
1128H2.SetBandX(35.,45.); // create 1D histo projection for 35.<y<45.
1129H2.SetBandX(40.,55.); // create 1D histo projection for 40.<y<55.
1130//... fill H2 with what ever you want
1131H2.Print();
1132Histo *hx = H2.HProjX();
1133 hx->Print(80);
1134Histo *hbx2 = HBandX(1); // Get the second X band (35.<y<45.)
1135 hbx2->Print(80);
1136\end{verbatim}
1137
1138\subsubsection{Profile Histograms}
1139\index{HProf}
1140Profiles histograms {\bf HProf} contains the mean and the
1141sigma of the distribution
1142of the values filled in each bin. The sigma can be changed to
1143the error on the mean. When filled, the profile histogram looks
1144like a 1D histogram and much of the operations that can be done on 1D histo
1145may be applied onto profile histograms.
1146
1147\subsection{Data tables (tuples)}
1148\begin{figure}[hbt]
1149\dclsbb{AnyDataObj}{NTuple}
1150\dclsccc{AnyDataObj}{BaseDataTable}{DataTable}
1151\dclscc{BaseDataTable}{SwPPFDataTable}
1152\end{figure}
1153
1154\subsubsection{NTuple}
1155\index{NTuple}
1156NTuple are memory resident tables of 32 or 64 bits floating values
1157(float/double).They are arranged in columns. Each line is often called an event.
1158These objects are frequently used to analyze data.
1159The piapp graphicals tools can plot a column against an other one
1160with respect to various selection cuts. \\
1161Here is an example of creation and filling~:
1162\begin{verbatim}
1163#include "ntuple.h"
1164#include "srandgen.h"
1165// ...
1166char* nament[4] = {"i","x","y","ey"};
1167r_4 xnt[4];
1168NTuple NT(4,nament);
1169for(i=0;i<5000;i++) {
1170 xnt[0] = i+1;
1171 xnt[1] = 5.*drandpm1(); // a random value between -5 and +5
1172 xnt[2] = 100.*exp(-0.5*xnt[1]*xnt[1]) + 1.;
1173 xnt[3] = sqrt(xnt[2]);
1174 xnt[2] += xnt[3] * NorRand(); // add a random gaussian error
1175 NT.Fill(xnt);
1176}
1177\end{verbatim}
1178
1179XNTuple provide additional functionalities, compared to NTuple.
1180They are deprecated and are only kept for backward compatibility
1181and should not be used anymore. Use DataTable and
1182SwPPFDataTable instead.
1183Object of type XNTuple handle various types
1184of column values (double,float,int,string,...) and can handle
1185very large data sets, through swap space on disk.
1186
1187\subsubsection{DataTables}
1188\label{datatables}
1189\index{DataTable}
1190The class {\bf DataTable} extends significantly the functionalities provided by
1191NTuple. DataTable is a memory resident implementation of the interface
1192{\bf BaseDataTable } which organizes the data as a 2-D table. User can define
1193the name and data type of each column. Data is added to the table as rows.
1194The table is extended as necessary when adding rows.
1195The sample code below shows an example of DataTable usage :
1196\begin{verbatim}
1197 #include "datatable.h"
1198 // ...
1199 DataTable dt(64);
1200 dt.AddFloatColumn("X0_f");
1201 dt.AddFloatColumn("X1_f");
1202 dt.AddDoubleColumn("X0X0pX1X1_d");
1203 double x[5];
1204 for(int i=0; i<63; i++) {
1205 x[0] = (i/9)-4.; x[1] = (i/9)-3.; x[2] = x[0]*x[0]+x[1]*x[1];
1206 dt.AddLine(x);
1207 }
1208 // Printing table info
1209 cout << dt ;
1210 // Saving object into a PPF file
1211 POutPersist po("dtable.ppf");
1212 po << dt ;
1213
1214\end{verbatim}
1215
1216
1217\index{SwPPFDataTable}
1218The class {\bf SwPPFDataTable} implements the BaseDataTable interface
1219using segmented data blocks with swap on PPF streams. Very large data sets
1220can be created and manipulated through tis class
1221
1222\index{DataTableRow}
1223The class {\bf DataTableRow } is an auxiliary class which simplifies the manipulation
1224of BaseDataTable object rows.
1225The example below show how to create and filling a table, using a PPF stream as
1226swap space. In addition, we have used a {\tt DataTableRow} to prepare data
1227for each table line.
1228\begin{verbatim}
1229 #include "swppfdtable.h"
1230 // ...
1231 {
1232 // ---------- Create an output PPF stream (file)
1233 POutPersist po("swdtable.ppf");
1234 // ------------------
1235 // Create a table with 3 columns, using the above stream as swap space
1236 SwPPFDataTable dtrow(po, 64);
1237 dtrow.AddStringColumn("sline");
1238 dtrow.AddIntegerColumn("line");
1239 dtrow.AddDateTimeColumn("datime");
1240 //
1241 TimeStamp ts, ts2; // Initialize current date and time
1242 string sline;
1243 //---- Create a table row with the required structure
1244 DataTableRow row = dtrow.EmptyRow();
1245 // ----- Fill the table
1246 for(int k = 0; k<2500; k++) {
1247 sline = "L-";
1248 sline += (string)MuTyV(k);
1249 row["sline"] = sline;
1250 row[1] = k;
1251 ts2.Set(ts.ToDays()+(double)k);
1252 row["datime"] = ts2;
1253 dtrow.AddRow(row);
1254 }
1255 //------ Write the table itself to the stream, before closing the file
1256 po << PPFNameTag("SwTable") << dtrow;
1257 }
1258\end{verbatim}
1259%%
1260The previously created table can easily be read in, as shown below:
1261%%
1262\begin{verbatim}
1263 #include "swppfdtable.h"
1264 // ...
1265 {
1266 // ------ Create the input PPF stream (file)
1267 PInPersist pin("swdtable.ppf");
1268 // ------ Read in the SwPPFDataTable object
1269 SwPPFDataTable dtr;
1270 pin >> PPFNameTag("SwTable") >> dtr;
1271 // ---- Create a table row with the required structure
1272 DataTableRow row = dtr.EmptyRow();
1273 // ---- Acces and print two of the table rows :
1274 cout << dtr.GetRow(6, row) << endl;
1275 cout << dtr.GetRow(17, row) << endl;
1276 }
1277\end{verbatim}
1278
1279\subsection{Writing, viewing \dots }
1280
1281All these objects have been design to be written to or read from a persistent file.
1282The following example shows how to write the previously created objects
1283into such a file~:
1284\begin{verbatim}
1285//-- Writing
1286{
1287char *fileout = "myfile.ppf";
1288string tag;
1289POutPersist outppf(fileout);
1290tag = "H"; outppf.PutObject(H,tag);
1291tag = "H2"; outppf.PutObject(H2,tag);
1292tag = "NT"; outppf.PutObject(NT,tag);
1293} // closing ``}'' destroy ``outppf'' and automatically close the file !
1294\end{verbatim}
1295
1296Sophya graphical tools (spiapp) can automatically display and operate
1297all these objects.
1298
1299\newpage
1300\section{Module NTools}
1301
1302This module provides elementary numerical tools for numerical integration,
1303fitting, sorting and ODE solving. FFTs are also provided (Mayer,FFTPack).
1304
1305\subsection{Fitting}
1306\index{Fitting} \index{Minimisation}
1307Fitting is done with two classes {\tt GeneralFit} and {\tt GeneralFitData}
1308and is based on the Levenberg-Marquardt method.
1309\index{GeneralFit} \index{GeneralFitData}
1310GeneralFitData is a class which provide a description of the data
1311to be fitted. GeneralFit is the fitter class. Parametrized functions
1312can be given as classes which inherit {\tt GeneralFunction}
1313or as simple C functions. Classes of pre-defined functions are provided
1314(see files fct1dfit.h and fct2dfit.h). The user interface is very close
1315from that of the CERN {\tt Minuit} fitter.
1316Number of objects (Histo, HProf \dots ) are interfaced with GeneralFit
1317and can be easily fitted. \\
1318Here is a very simple example for fitting the previously created NTuple
1319with a Gaussian~:
1320\begin{verbatim}
1321#include "fct1dfit.h"
1322// ...
1323
1324// Read from ppf file
1325NTuple nt;
1326{
1327PInPersist pis("myfile.ppf");
1328string tag = "NT"; pis.GetObject(nt,tag);
1329}
1330
1331// Fill GeneralData
1332GeneralData mGdata(nt.NEntry());
1333for(int i=0; i<nt.NEntry(); i++)
1334 mGdata.AddData1(xnt[1],xnt[2],xnt[3]); // Fill x, y and error on y
1335mGData.PrintStatus();
1336
1337// Function for fitting : y = f(x) + noise
1338Gauss1DPol mFunction; // gaussian + constant
1339
1340// Prepare for fit
1341GeneralFit mFit(&mFunction); // create a fitter for the choosen function
1342mFit.SetData(&mGData); // connect data to the fitter
1343
1344// Set and initialise the parameters (that's non-linear fitting!)
1345// (num par, name, guess start, step, [limits min and max])
1346mFit.SetParam(0,"high",90.,1..);
1347mFit.SetParam(1,"xcenter",0.05,0.01);
1348mFit.SetParam(2,"sigma",sig,0.05,0.01,10.);
1349 // Give limits to avoid division by zero
1350mFit.SetParam(3,"constant",0.,1.);
1351
1352// Fit and print result
1353int rcfit = mFit.Fit();
1354mFit.PrintFit();
1355if(rcfit>0) {)
1356 cout<<"Reduce_Chisquare = "<<mFit.GetChi2Red()
1357 <<" nstep="<<mFit.GetNStep()<<" rc="<<rcfit<<endl;
1358} else {
1359 cout<<"Fit_Error, rc = "<<rcfit<<" nstep="<<mFit.GetNStep()<<endl;
1360 mFit.PrintFitErr(rcfit);
1361}
1362
1363// Get the result for further use
1364TVector<r_8> ParResult = mFit.GetParm();
1365cout<<ParResult;
1366\end{verbatim}
1367
1368Much more usefull possibilities and detailed informations might be found
1369in the HTML pages of the Sophya manual.
1370
1371\subsection{Polynomial}
1372\index{Polynomial} \index{Poly} \index{Poly2}
1373Polynomials of 1 or 2 variables are supported ({\tt Poly} and {\tt Poly2}).
1374Various operations are supported~:
1375\begin{itemize}
1376\item elementary operations between polynomials $(+,-,*,/) $
1377\item setting or getting coefficients
1378\item computing the value of the polynomial for a given value
1379 of the variable(s),
1380\item derivating
1381\item computing roots (degre 1 or 2)
1382\item fitting the polynomial to vectors of data.
1383\end{itemize}
1384Here is an example of polynomial fitting~:
1385\begin{verbatim}
1386#include "poly.h"
1387// ...
1388Poly pol(2);
1389pol[0] = 100.; pol[1] = 0.; pol[2] = 0.01; // Setting coefficients
1390TVector<r_8> x(100);
1391TVector<r_8> y(100);
1392TVector<r_8> ey(100);
1393for(int i=0;i<100;i++) {
1394 x(i) = i;
1395 ey(i) = 10.;
1396 y(i) = pol((double) i) + ey(i)*NorRand();
1397 ey(i) *= ey(i)
1398}
1399
1400TVector<r_8> errcoef;
1401Poly polfit;
1402polfit.Fit(x,y,ey,2,errcoef);
1403
1404cout<<"Fit Result"<<polfit<<endl;
1405cout<<"Errors :"<<errcoef;
1406\end{verbatim}
1407
1408Similar operations can be done on polynomials with 2 variables.
1409
1410\subsection{Integration, Differential equations}
1411\index{Integration}
1412The NTools module provide also simple classes for numerical integration
1413of functions and differential equations.
1414\begin{figure}[hbt]
1415\dclsbb{Integrator}{GLInteg}
1416\dclsb{TrpzInteg}
1417\end{figure}
1418
1419\index{GLInteg} \index{TrpzInteg}
1420{\bf GLInteg} implements the integration through Gauss-Legendre method
1421and {\bf TrpzInteg} implements trapeze integration. For {\bf TrpzInteg},
1422number of steps specify the number of trapeze, and integration step,
1423their width.
1424The sample code below illustrates the use of TrpzInteg class:
1425\begin{verbatim}
1426#include "integ.h"
1427// ......................................................
1428// Function to be integrated
1429double myf(double x)
1430{
1431// Simple a x + b x^2 (a=2 b=3)
1432return (x*(2.+3.*x));
1433}
1434// ......................................................
1435
1436// Compute Integral(myf, 2., 5.) between xmin=2., xmax=5.
1437TrpzInteg trpz(myf, 2., 5.);
1438// We specify an integration step
1439trpz.DX(0.01);
1440// The integral can be computed as trpz.Value()
1441double myf_integral = trpz.Value();
1442// We could have used the cast operator :
1443cout << "Integral[myf, 2., 5.]= " << (double)trpz << endl;
1444// Limits can be specified through ValueBetween() method
1445cout << "Integral[myf, 0., 4.]= " << trpz.ValueBetween(0.,4.) << endl;
1446\end{verbatim}
1447
1448\subsection{Fourier transform (FFT)}
1449\index{FFT} \index{FFTPackServer}
1450An abstract interface for performing FFT operations is defined by the
1451{\bf FFTServerInterface} class. The {\bf FFTPackSever} class implements
1452one dimensional FFT, on real and complex data. FFTPackServer uses an
1453adapted and extended version of FFTPack (available from netlib),
1454translated in C, and can operate on single and double precision
1455({\tt float, double}) data.
1456
1457The sample code below illustrates the use of FFTServers:
1458\begin{verbatim}
1459#include "fftpserver.h"
1460 // ...
1461TVector<r_8> in(32);
1462TVector< complex<r_8> > out;
1463in = RandomSequence();
1464FFTPackServer ffts;
1465ffts.setNormalize(true); // To have normalized transforms
1466cout << " FFTServer info string= " << ffts.getInfo() << endl;
1467cout << "in= " << in << endl;
1468cout << " Calling ffts.FFTForward(in, out) : " << endl;
1469ffts.FFTForward(in, out);
1470cout << "out= " << out << endl;
1471\end{verbatim}
1472
1473% \newpage
1474\section{Module SUtils}
1475Some utility classes and C/C++ string manipulation functions are gathered
1476in {\bf SUtils} module.
1477\subsection{Using DataCards}
1478\index{DataCards}
1479The {\bf DataCards} class can be used to read parameters from a file.
1480Each line in the file starting with \@ defines a set of values
1481associated with a keyword. In the example below, we read the
1482parameters corresponding with the keyword {\tt SIZE} from the
1483file {\tt ex.d}. We suppose that {\tt ex.d} contains the line: \\
1484{\tt @SIZE 400 250} \\
1485\begin{verbatim}
1486#include "datacards.h"
1487// ...
1488// Initialising DataCards object dc from file ex.d
1489DataCards dc( "ex.d" );
1490// Getting the first and second parameters for keyword size
1491// We define a default value 100
1492int size_x = dc.IParam("SIZE", 0, 100);
1493int size_y = dc.IParam("SIZE", 1, 100);
1494cout << " size_x= " << size_x << " size_y= " << size_y << endl;
1495\end{verbatim}
1496
1497\section{Module SysTools}
1498The {\bf SysTools} module contains classes implementing interface to some
1499OS specific services, such as thread creation and management, dynamic loading and
1500resource usage information. For example, yhe class {\bf Periodic} provides the
1501necessary services needed to implement the execution of a periodic action.
1502
1503\subsection{Resource usage (CPU, memory \ldots) }
1504 The class {\bf ResourceUsage} \index{ResourceUsage}
1505and {\bf Timer} {\index{Timer} provides access to information
1506about various resource usage (memory, CPU, ...).
1507The class {\bf Timer} {\index{time (CPU, elapsed)} and c-functions
1508{\tt InitTim() , PrtTim(const char * Comm) } can be used to print
1509the amount of CPU and elapsed time in programs.
1510
1511The following sample code illustrates the use of {\bf ResourceUsage} :
1512\begin{verbatim}
1513 // How to check resource usage for a given part of the program
1514 ResourceUsage res;
1515 // --- Part of the program to be checked : Start
1516 // ...
1517 res.Update();
1518 cout << " Memory size increase (KB):" << res.getDeltaMemorySize() << endl;
1519 cout << " Resource usage info : \n" << res << endl;
1520\end{verbatim}
1521
1522\subsection{Thread management classes}
1523A basic interface to POSIX threads \index{thread} is also provided
1524through the \index{threads} {\bf ZThread}, {\bf ZMutex} and {\bf ZSync}
1525classes. The best way to use thread management classes is by inheriting
1526from {\bf ZThread} and redefining the {\tt run() } method.
1527It is also possible to use the default {\tt run() } implementation and associate
1528a function to perform the action, as in the example below :
1529\begin{verbatim}
1530 // The functions to perform computing
1531 void fun1(void *arg) { }
1532 void fun2(void *arg) { }
1533 // ...
1534 ZThread zt1;
1535 zt1.setAction(fun1, arg[1]);
1536 ZThread zt2;
1537 zt2.setAction(fun2, arg[1]);
1538 cout << " Starting threads ... " << endl;
1539 zt1.start();
1540 zt2.start();
1541 cout << " Waiting for threads to end ... " << endl;
1542 zt1.join();
1543 zt2.join();
1544\end{verbatim}
1545The classes {\bf ZMutex} \index{mutex} and {\bf ZSync} can be used
1546to perform synchronisation and signaling between threads.
1547
1548\subsection{Dynamic linker and C++ compiler classes}
1549\index{PDynLinkMgr}
1550The class {\bf PDynLinkMgr} can be used for managing shared libraries
1551at run time. The example below shows the run time linking of a function:\\
1552{\tt extern "C" { void myfunc(); } } \\
1553\begin{verbatim}
1554#include "pdlmgr.h"
1555// ...
1556string soname = "mylib.so";
1557string funcname = "myfunc";
1558PDynLinkMgr dyl(soname);
1559DlFunction f = dyl.GetFunction(funcname);
1560if (f != NULL) {
1561// Calling the function
1562 f();
1563}
1564\end{verbatim}
1565
1566\index{CxxCompilerLinker}
1567The {\bf CxxCompilerLinker} class provides the services to compile C++ code and building
1568shared libraries, using the same compiler and options which have
1569been used to create the SOPHYA shared library.
1570The sample program below illustrates using this class to build
1571the shared library (myfunc.so) from the source file myfunc.cc :
1572\begin{verbatim}
1573#include "cxxcmplnk.h"
1574// ...
1575string flnm = "myfunc.cc";
1576string oname, soname;
1577int rc;
1578CxxCompilerLinker cxx;
1579// The Compile method provides a default object file name
1580rc = cxx.Compile(flnm, oname);
1581if (rc != 0 ) { // Error when compiling ... }
1582// The BuildSO method provides a default shared object file name
1583rc = cxx.BuildSO(oname, soname);
1584if (rc != 0 ) { // Error when creating shared object ... }
1585\end{verbatim}
1586
1587\subsection{Command interpreter}
1588The class {\bf Commander} can be used in interactive programs to provide
1589c-shell like command interpreter and scripting capabilties.
1590Arithmetic expression evaluation is implemented through the {\bf CExpressionEvaluator}
1591and {\bf RPNExpressionEvaluator} classes.
1592The command language provides variable manipulation through the usual
1593{\tt \$varname} vector variable and arithmetic expression extensions, as well
1594as the control and test blocs.
1595\begin{verbatim}
1596#include "commander.h"
1597...
1598Commander cmd;
1599char* ss[3] = {"foreach f ( AA bbb CCCC ddddd )", "echo $f" , "end"};
1600for(int k=0; k<3; k++) {
1601 string line = ss[k];
1602 cmd.Interpret(line);
1603}
1604\end{verbatim}
1605
1606\newpage
1607\section{Module SkyMap}
1608\begin{figure}[hbt]
1609\dclsbb{AnyDataObj}{PixelMap}
1610\dclsccc{PixelMap}{Sphericalmap}{SphereHEALPix}
1611\dclsc{SphereThetaPhi}
1612\dclsc{SphereECP}
1613\dclsb{LocalMap}
1614\caption{partial class diagram for spherical map classes in Sophya}
1615\end{figure}
1616The {\bf SkyMap} module provides classes for creating, filling, reading pixelized spherical and 2D-maps. The types of values stored in pixels can be int, float, double , complex etc. according to the specialization of the template type.
1617\subsection {Spherical maps}
1618SkyMap module provides three kinds of complete ($4 \pi$) spherical maps according to the
1619pixelization scheme.
1620SphereHEALPix represents spheres pixelized following the HEALPIix algorithm (E. Hivon, K. Gorski)
1621\footnote{see the HEALPix Homepage: http://www.eso.org/kgorski/healpix/ }
1622, SphereThetaPhi represents spheres pixelized following an algorithm developed at LAL-ORSAY. The example below shows creating and filling of a SphereHEALPix with nside = 8 (it will be 12*8*8= 768 pixels) :
1623\index{\tcls{SphereHEALPix}}
1624
1625\begin{verbatim}
1626#include "spherehealpix.h"
1627// ...
1628SphereHEALPix<double> sph(8);
1629for (int k=0; k< sph.NbPixels(); k++) sph(k) = (double)(10*k);
1630\end{verbatim}
1631
1632SphereThetaPhi is used in a similar way with an argument representing number of slices in theta (Euler angle) for an hemisphere.
1633\index{\tcls{SphereThetaPhi}}
1634The SphereECP class correspond to the cylindrical projection and can be used for representing
1635partial or full spherical maps. However, it has the disadvantage of having non uniform pixel
1636size.
1637\index{\tcls{SphereECP}}
1638
1639\subsection {Local maps}
1640\index{\tcls{LocalMap}}
1641A local map is a 2 dimensional array, with i as column index and j as row index. The map is supposed to lie on a plan tangent to the celestial sphere in a point whose coordinates are (x0,y0) on the local map and (theta0, phi0) on the sphere. The range of the map is defined by two values of angles covered respectively by all the pixels in x direction and all the pixels in y direction (SetSize()). Default value of (x0, y0) is middle of the map, center of pixel(nx/2, ny/2).
1642
1643Internally, a map is first defined within this reference plane and tranported until the point (theta0, phi0) in such a way that both axes are kept parallel to meridian and parallel lines of the sphere. The user can define its own map with axes rotated with respect to reference axes (this rotation is characterized by angle between the local parallel line and the wanted x-axis-- method SetOrigin(...))
1644
1645The example below shows creating and filling of a LocalMap with 4 columns and 5 rows. The origin is set to default. The map covers a sphere portion defined by two angles of 30. degrees (methods \textit{SetOrigin()} and \textit{SetSize()} must be called in order to completely define the map).
1646\begin{verbatim}
1647#include "localmap.h"
1648//..............
1649 LocalMap<r_4> locmap(4,5);
1650 for (int k=0; k<locmap.NbPixels();k++) locmap(k)=10.*k;
1651 locmap.SetOrigin();
1652 locmap.SetSize(30.,30.);
1653\end{verbatim}
1654
1655\subsection{Writing, viewing \dots }
1656
1657All these objects have been design to be written to or read from a persistant file.
1658The following example shows how to write the previously created objects
1659into such a file~:
1660\begin{verbatim}
1661//-- Writing
1662
1663#include "fiospherehealpix.h"
1664//................
1665
1666char *fileout = "myfile.ppf";
1667POutPersist outppf(fileout);
1668FIO_SphereHEALPix<r_8> outsph(sph);
1669outsph.Write(outppf);
1670FIO_LocalMap<r_8> outloc(locmap);
1671outloc.Write(outppf);
1672// It is also possible to use the << operator
1673POutPersist os("sph.ppf");
1674os << outsph;
1675os << outloc;
1676\end{verbatim}
1677
1678Sophya graphical tools (spiapp) can automatically display and operate
1679all these objects.
1680
1681\newpage
1682\section{Samba and SkyT}
1683\subsection{Samba}
1684\index{Spherical Harmonics}
1685\index{SphericalTransformServer}
1686The module provides several classes for spherical harmonic analysis. The main class is \textit{SphericalTranformServer}. It contains methods for analysis and synthesis of spherical maps. The following example fills a vector of Cl's, generate a spherical map from these Cl's. This map is analysed back to Cl's...
1687\begin{verbatim}
1688#include "skymap.h"
1689#include "samba.h"
1690....................
1691
1692// Generate input spectra a + b* l + c * gaussienne(l, 50, 20)
1693int lmax = 92;
1694Vector clin(lmax);
1695for(int l=0; l<lmax; l++) {
1696 double xx = (l-50.)/10.;
1697 clin(l) = 1.e-2 -1.e-4*l + 0.1*exp(-xx*xx);
1698}
1699
1700// Compute map from spectra
1701SphericalTransformServer<r_8> ylmserver;
1702int m = 128; // HealPix pixelisation parameter
1703SphereHEALPix<r_8> map(m);
1704ylmserver.GenerateFromCl(map, m, clin, 0.);
1705// Compute power spectrum from map
1706Vector clout = ylmserver.DecomposeToCl(map, lmax, 0.);
1707\end{verbatim}
1708
1709\subsection{Module SkyT}
1710\index{RadSpectra} \index{SpectralResponse} \index
1711The SkyT module is composed of two types of classes:
1712\begin{itemize}
1713\item{} one which corresponds to an emission spectrum of
1714radiation, which is called RadSpectra
1715\item{} one which corresponds to the spectral response
1716of a given detector (i.e. corresponding to a detector
1717filter in a given frequency domain), which is called
1718SpectralResponse.
1719\end{itemize}
1720\begin{figure}[hbt]
1721\dclsbb{RadSpectra}{RadSpectraVec}
1722\dclsb{BlackBody}
1723\dclsccc{AnyDataObj}{SpectralResponse}{SpecRespVec}
1724\dclsc{GaussianFilter}
1725\caption{partial class for SkyT module}
1726\end{figure}
1727
1728\begin{verbatim}
1729#include "skyt.h"
1730// ....
1731// Compute the flux from a blackbody at 2.73 K through a square filter
1732BlackBody myBB(2.73);
1733// We define a square filter from 100 - 200 GHz
1734SquareFilter mySF(100,200);
1735// Compute the filtered integrated flux :
1736double flux = myBB.filteredIntegratedFlux(mySF);
1737\end{verbatim}
1738
1739A more detailed description of SkyT module can be found in:
1740{\it The SkyMixer (SkyT and PMixer modules) - Sophya Note No 2. }
1741available also from Sophya Web site.
1742
1743\newpage
1744\section{Module FitsIOServer}
1745\subsection{FITS streams}
1746\index{FITS} \index{FitsInFile} \index{FitsOutFile}
1747This module provides classes for handling file input-output in FITS format using the cfitsio library. Its
1748design is similar to the SOPHYA persistence (see Module BaseTools).
1749Delegate classes or handlers perform the actual read/write from/to fits files.
1750Compared to the SOPHYA native persistence (PPF format),
1751FITS format has the advantage of being used extensively, and handled
1752by a many different software tools. It is a de facto standard in
1753astronomy and astrophysics.
1754However, FITS lacks some of the features present in SOPHYA PPF, and although
1755many SOPHYA objects can be saved in FITS files, FITS persistence has
1756some limitations. For example, FITS does not currently handle complex arrays.
1757\par
1758The class {\bf FitsInOutFile} can be seen as a wrapper class for the cfitsio library functions.
1759This class has been introduced in 2005 (V=1.9), when the module has been
1760extensively changed. In order to keep backward compatibility, the old fits wrapper
1761classes ({\bf FitsFile, FitsInFile, FitsOutFile} has been changed to inherit from
1762 {\bf FitsInOutFile}. The use of class FitsFile and specific services of these old classes
1763 should be avoided, but FitsInFile, FitsOutFile can be safely considered a specialisation
1764 of FitsInOutFile for read/input and write/output operations respectively.
1765 The diagram below shows the class hierarchy for cfitsio wrapper classes.
1766\begin{figure}[hbt]
1767\dclsa{FitsInOutFile}
1768\dclscc{FitsFile}{FitsInFile}
1769\dclscc{FitsFile}{FitsOutFile}
1770\end{figure}
1771%%%%
1772\subsection{FITS handlers}
1773Handlers classes inheriting from {\bf FitsHandlerInterface} perform write/read operations
1774for AnyDataObj objects to/from FitsInOutFile streams. The {\bf FitsManager} class provides
1775top level services for object read/write in FITS files.
1776In most cases, \\
1777{\tt FitsInOutFile\& $<<$ } and {\tt FitsInOutFile\& $>>$ } or \\
1778 {\tt FitsOutFile\& $<<$ } and {\tt FitsInFile\& $>>$ } \\
1779 operators can be used
1780write and read objects. The two main types of fits data structures, images and tables
1781{\tt (IMAGE\_HDU , BINARY\_TBL , ASCII\_TBL)} are handled by the generic handlers: \\
1782{\bf \tcls{FitsArrayHandler}} and {\bf FitsHandler$<$BaseDataTable$>$}. \\
1783A number of more specific handlers are also available, in particular for NTuple,
1784\tcls{SphereHealPix} and \tcls{SphereThetaPhi}. \\[2mm]
1785{\bf Warning:} Some handlers were written with the old FitsIOServer classes and
1786inherit from the intermediate class {\bf FitsIOHandler}. They
1787have been adapted to the new scheme, but may not perform correctly if not used
1788through the {\bf FitsManager} class. \\[2mm]
1789%%%
1790The examples below illustrates the usage of FitsIOServer classes.
1791\begin{enumerate}
1792\item Saving an array and a HealPix map to a Fits file
1793\begin{verbatim}
1794#include "fitsioserver.h"
1795#include "fiosinit.h"
1796
1797// ....
1798{
1799// Make sure FitsIOServer module is initialised :
1800FitsIOServerInit();
1801// Create and open a fits file named myfile.fits
1802FitsInOutFile fos("myfile.fits", FitsInOutFile ::Fits_Create);
1803// Create and save a 15x11 matrix of integers
1804TMatrix<int_4> mxi(15, 11);
1805mxi = RegularSequence(10.,10.);
1806fos << mxi;
1807// Save a HEALPix spherical map using FitsManager services
1808SphereHEALPix<r_8> sph(16);
1809sph = 48.3;
1810FitsManager::Write(fos, sph);
1811}
1812\end{verbatim}
1813%%%%
1814%%%%
1815\item Reading objects and the header from the previously created fits file:
1816\begin{verbatim}
1817{
1818FitsIOServerInit(); // Initialisation
1819// ---- Open the fits file named myfile.fits
1820FitsInFile fis("myfile.fits");
1821//---- print file information on cout
1822cout << fis << endl;
1823//--- Read in the array
1824TArray<int_4> arr;
1825fis >> arr;
1826arr.Show();
1827//--- Position on second HDU
1828fis.MoveAbsToHDU(2);
1829//--- read and display header information
1830DVList hdu2;
1831fis.GetHeaderRecords(hdu2, true, true);
1832cout << hdu2;
1833//--- read in the HEALPix map
1834SphereHEALPix<r_8> sph;
1835FitsManager::Read(fis, sph);
1836fis.MoveAbsToHDU(2);
1837sph.Show();
1838}
1839\end{verbatim}
1840%%%%%%%
1841%%%
1842\item DataTable objects can be read from and written to FITS files as ASCII or
1843binary tables. The example belo show reading the DataTable created in the example
1844in section \ref{datatables} from a PPF file and saving it to a fits file;
1845\begin{verbatim}
1846{
1847FitsIOServerInit(); // Initialisation
1848FitsInOutFile fos("dtable.fits", FitsInOutFile ::Fits_Create);
1849}
1850\end{verbatim}
1851%%%%
1852\end{enumerate}
1853
1854
1855A partial class diagram of FITS persistence handling classes is shown below. The
1856class {\tt FitsIOhandler} conforms to the old FitsIOServer module design and
1857should not be used anymore.
1858\begin{figure}[hbt]
1859\dclsbb{FitsHandlerInterface}{FitsArrayHandler$<$T$>$}
1860\dclsb{\tcls{FitsHandler}}
1861\dclscc{FitsIOhandler}{FITS\_NTuple}
1862\dclsc{FITS\_SphereHEALPix}
1863% \dclsb{FITS\_LocalMap}
1864\end{figure}
1865
1866\subsection{SwFitsDataTable and other classes}
1867
1868\subsection{scanfits}
1869
1870\newpage
1871\section{LinAlg and IFFTW modules}
1872An interface to use LAPACK library (available from {\tt http://www.netlib.org})
1873is implemented by the {\bf LapackServer} class, in module LinAlg.
1874\index{LapackServer}.
1875The sample code below shows how to use SVD (Singular Value Decomposition)
1876through LapackServer:
1877\begin{verbatim}
1878#include "intflapack.h"
1879// ...
1880// Use FortranMemoryMapping as default
1881BaseArray::SetDefaultMemoryMapping(BaseArray::FortranMemoryMapping);
1882// Create an fill the arrays A and its copy AA
1883int n = 20;
1884Matrix A(n , n), AA;
1885A = RandomSequence(RandomSequence::Gaussian, 0., 4.);
1886AA = A; // AA is a copy of A
1887// Compute the SVD decomposition
1888Vector S; // Vector of singular values
1889Matrix U, VT;
1890LapackServer<r_8> lpks;
1891lpks.SVD(AA, S, U, VT);
1892// We create a diagonal matrix using S
1893Matrix SM(n, n);
1894for(int k=0; k<n; k++) SM(k,k) = S(k);
1895// Check the result : A = U*SM*VT
1896Matrix diff = U*(SM*VT) - A;
1897double min, max;
1898diff.MinMax(min, max);
1899cout << " Min/Max difference Matrix (?=0) , Min= " << min
1900 << " Max= " << max << endl;
1901\end{verbatim}
1902
1903\index{FFTWServer}
1904The {\bf FFTWServer} class (in module FFTW) implements FFTServerInterface class
1905methods, for one dimensional and multi-dimensional Fourier
1906transforms on double precision data using the FFTW package
1907(available from {\tt http://www.fftw.org}).
1908
1909\newpage
1910\section{Building and installing Sophya}
1911\subsection{supported platforms}
1912Presently, the Sophya library has been tested with the following
1913compiler/platform pairs:
1914
1915\begin{center}
1916\begin{tabular}{|l|l|}
1917\hline
1918OS & compiler \\
1919\hline
1920Linux (RH) & g++ (3.2) \\
1921Linux (SCL) & icc (8.1) (Intel compiler) \\
1922MacOSX/Darwin 10.3 & g++ 3.3 \\
1923HP/Compaq/DEC Tru64 ( OSF1) & cxx (6.1 , 6.3) \\
1924SGI IRIX64 & CC (7.3) \\
1925IBM AIX & xlC (7.x) \\
1926\hline
1927\end{tabular}
1928\end{center}
1929
1930Some of the modules in the Sophya package uses external libraries. The
1931{\bf FitsIOServer} is the example of such a module, where the {\tt libcfitsio.a}
1932is used.
1933par
1934The object files from a given Sophya module are grouped in an archive library
1935with the module's name ({\tt libmodulename.a}). All Sophya modules
1936 are grouped in a single shared library ({\tt libsophya.so}), while the
1937modules with reference to external libraries are grouped in
1938({\tt libextsophya.so}). The {\bf PI} and {\bf PIext} modules are
1939grouped in ({\tt libPI.so}).
1940Alternatively, it is possible to group all modules in a single shared
1941library {\tt libAsophyaextPI.so}.
1942
1943\subsection{Installation}
1944\label{build}
1945The build procedure has two main steps:
1946\begin{enumerate}
1947\item The configure step (BuildMgr/configure) setup the directory structure and
1948the necessary configuration file. Refer to section \ref{directories} for
1949the description of SOPHYA directory tree and files.
1950\item The make step compiles the different sources files, create the library and optionaly
1951builds all or some of the associated executables.
1952\end{enumerate}
1953
1954{\tt BuildMgr/configure } is a c-shell script with a number of arguments:
1955\begin{verbatim}
1956csh> ./configure -h
1957configure [-sbase SOPHYABASE] [-scxx SOPHYACXX] [-incln]
1958 [-minc mymake.inc]
1959 [-extp dir1 -extp dir2 ...] [-extip dir1 -extip dir2 ... ]
1960 [-extlp dir1 -extlp dir2 ... ]
1961 [-noextlib -noext fits -noext fftw -noext lapack ]
1962 [-noext astro -noext minuit]
1963 [-usefftw2 -uselapack2] [-singleslb]
1964\end{verbatim}
1965\begin{itemize}
1966\item[] -sbase : define SOPHYA installation base directory. \$SOPHYABASE is used
1967if not specified.
1968\item[] -scxx : selects the C++ compiler. \$SOPHYACXX s used
1969if not specified.
1970\item[] -incln : creates symbolic link for include files, instead of copying them.
1971\item[] -minc : give an explicit name for the file used to generate
1972\$SOPHYABASE/include/sophyamake.inc.
1973\item[] -extp : Adds the specied path to the search path of the external libraries
1974include files and archive library.
1975\item[] -extip : Adds the specied path to the search path of the external libraries
1976include files.
1977\item[] -extp : Adds the specied path to the search path of the external libraries
1978archive (libxxx.a).
1979\item[] -noextlib : Disable compiling of modules referencing external libraries.
1980\item[] -noext : Disable compiling of the specified module (with reference to external
1981library.
1982\item[] -usefftw2: FFTW V2 is being used (default FFTW V3) - A compilation flag
1983will be defined in sspvflags.h
1984\item[] -uselapack2: Lapack V2 is being used (defaulr V3) - A compilation flag
1985will be defined in sspvflags.h
1986\item[] -singleslb: A single shared library for all SOPHYA, PI and external library interface
1987modules will be build. A compilation flag
1988will be defined in sspvflags.h . `See also target {\tt slballinone} below.
1989\end{itemize}
1990
1991In the example below, we assume that we want to install Sophya from a
1992released (tagged) version in the source directory {\tt \$SRC} in the
1993{\tt /usr/local/Sophya} directory, using {\tt g++}. We assume that
1994the external libraries can be found in {\tt /usr/local/ExtLibs/}.
1995We disable the compilation of the MinuitAdapt and XAstrPack packages.
1996
1997\vspace*{3mm}
1998\begin{verbatim}
1999# Create the top level directory
2000csh> mkdir /usr/local/Sophya/
2001csh> cd $SRC/BuildMgr
2002# Step 1.a : Run the configuration script
2003csh> ./configure -sbase /usr/local/Sophya -scxx g++ -extp /usr/local/ExtLibs/ \
2004-noext astro -noext minuit
2005# Step 1.b : Check the generated file $SOPHYABASE/include/sophyamake.inc
2006csh> ls -lt *.inc
2007csh> more sophyamake.inc
2008\end{verbatim}
2009If necessary, edit the generated file {\tt sophyamake.inc } in order to modify
2010compilation flags, library list. The file is rather short and self documented.
2011\begin{verbatim}
2012# Step 2.a: Compile the modules without external library reference
2013csh> make libs
2014# Step 2.b: Compile the modules WITH external library reference (optional)
2015csh> make extlibs
2016# Step 2.c: Build libsophya.so
2017csh> make slb
2018# Step 2.d: Build libextsophya.so (optional)
2019csh> make slbext
2020# Step 2.e: Compile the PI and PIext modules (optional)
2021csh> make PI
2022# Step 2.f: Build the corresponding shared library libPI.so (optional)
2023csh> make slbpi
2024\end{verbatim}
2025
2026To compile all modules and build the shared libraries, it is possible
2027to perform the steps 2.a to 2.f using the targets {\tt all} and {\tt slball}
2028defined in the Makefile
2029\begin{verbatim}
2030# Step 2.a ... 2.f
2031csh> make all slball
2032\end{verbatim}
2033
2034It is also possible to group all modules in a single shared library using
2035the target {\tt slballinone}.
2036\begin{verbatim}
2037# Step 2.a ... 2.f
2038csh> make all slballinone
2039\end{verbatim}
2040
2041At this step, all libraries should have been made. Programs using
2042Sophya libraries can now be built:
2043\begin{verbatim}
2044# To compile some of the test programs
2045csh> make basetests
2046# To compile runcxx , scanppf , scanfits
2047csh> make prgutil
2048# To build (s)piapp (libPI.so is needed)
2049csh> make piapp
2050\end{verbatim}
2051
2052\subsection{Platform specific notes }
2053\begin{itemize}
2054\item[{\bf AIX}] There seem to be a problem on AIX when several shared
2055libraries are used. We have been able to run SOPHYA programs either
2056using static libraries, or a single shared library (libAsophyaextPI.so)
2057if extlibs and PI are needed, in addition to stand alone SOPHYA modules.
2058\end{itemize}
2059
2060\subsection{Files and scripts in BuildMgr/ }
2061\begin{itemize}
2062\item[] {\bf Makefile:} Top level Makefile for building SOPHYA.
2063{\tt smakefile} is similar to Makefile, except that it uses
2064the smakefiles in each module.
2065\item[] {\bf mkmflib:} c-shell script for creation of library module
2066Makefile / smakefile.
2067{\tt ./mkmflib -sbase /tmp/sbase SUtils }
2068\item[] {\b mkmfprog:}
2069{\tt c-shell script for creation of programs module
2070Makefile / smakefile \\
2071{\tt ./mkmfprog -sbase /tmp/sbase ProgPI }
2072\item[] {\bf domkmf:} c-shell script - calls mkmflib for all modules \\
2073{\tt ./domkmf -sbase /tmp/sbase}
2074\item[] Configuration files for different compilers and OS
2075(\tt Linux\_g++\_make.inc , OSF1\_cxx\_make.inc \ldots }.
2076These files are used to generate {\tt sophyamake.inc}
2077\end{itemize}
2078
2079\noindent {\large \bf NOTE} \hspace{5mm}
2080The {\bf Mgr} module contains makefiles and build scripts
2081whih were used in SOPHYA up to version 1.7 (2004).
2082It should not be used anymore.
2083
2084
2085\newpage
2086\appendix
2087\section{SOPHYA Exceptions}
2088\index{Exception classes} \index{PThrowable} \index{PError} \index{PException}
2089SOPHYA library defines a set of exceptions which are used
2090for signalling error conditions. The figure below shows a partial
2091class diagram for exception classes in SOPHYA.
2092\begin{figure}[hbt]
2093\dclsbb{PThrowable}{PError}
2094\dclscc{PError}{AllocationError}
2095\dclscc{PError}{NullPtrError}
2096\dclscc{PError}{ForbiddenError}
2097\dclscc{PError}{AssertionFailedError}
2098\dclsbb{PThrowable}{PException}
2099\dclscc{PException}{IOExc}
2100\dclscc{PException}{SzMismatchError}
2101\dclscc{PException}{RangeCheckError}
2102\dclscc{PException}{ParmError}
2103\dclscc{PException}{TypeMismatchExc}
2104\dclscc{PException}{MathExc}
2105\dclscc{PException}{CaughtSignalExc}
2106\caption{partial class diagram for exception handling in Sophya}
2107\end{figure}
2108
2109For simple programs, it is a good practice to handle
2110the exceptions at least at high level, in the {\tt main()} function.
2111The example below shows the exception handling and the usage
2112of Sophya persistence.
2113
2114\input{ex1.inc}
2115
2116
2117\newpage
2118\addcontentsline{toc}{section}{Index}
2119\printindex
2120\end{document}
2121
Note: See TracBrowser for help on using the repository browser.