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

Last change on this file since 3723 was 3723, checked in by ansari, 16 years ago

mise a jour tres partielle du fichier modifs.tex et sophya.tex , Reza 29/12/2009

File size: 108.1 KB
RevLine 
[3015]1\documentclass[twoside,10pt]{article}
[887]2% Package standard : Utilisation de caracteres accentues, mode francais et graphique
[988]3\usepackage{url}
[887]4\usepackage[latin1]{inputenc}
5\usepackage[T1]{fontenc}
6\usepackage[english]{babel}
7\usepackage{graphicx}
8% package a mettre pour faire du pdf
[978]9\usepackage{palatino}
[887]10
11% Extension de symboles mathematiques
12\usepackage{amssymb}
13
[988]14% Definition pour Docs Sophya
[974]15\usepackage{defsophya}
16
[1362]17% Constitution d'index
18\usepackage{makeidx}
[2280]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}
[887]25
[2280]26\makeindex % Constitution d'index
27
[3006]28\newcommand{\rond}{$\bullet \ $}
29\newcommand{\etoile}{$\star \ $}
30\newcommand{\cercle}{$\circ \ $}
31\newcommand{\carre}{$\Box \ $}
32
33
[887]34\begin{document}
35
36\begin{titlepage}
[988]37% The title page - top of the page with the title of the paper
[978]38\titrehp{Sophya \\ An overview }
[988]39% Authors list
[978]40\auteurs{
[988]41R. Ansari & ansari@lal.in2p3.fr \\
[1340]42E. Aubourg & aubourg@hep.saclay.cea.fr \\
[988]43G. Le Meur & lemeur@lal.in2p3.fr \\
44C. Magneville & cmv@hep.saclay.cea.fr \\
[887]45}
[978]46% \auteursall
[988]47% The title page - bottom of the page with the paper number
[1362]48\vspace{1cm}
49\begin{center}
[3723]50{\bf \Large Sophya Version: 2.2 (V\_Jan2010) }
[1362]51\end{center}
[988]52\titrebp{1}
[887]53\end{titlepage}
54
55\tableofcontents
56
57\newpage
58
59\section{Introduction}
60
[1362]61{\bf SOPHYA} ({\bf SO}ftware for {\bf PHY}sics {\bf A}nalysis)
[887]62is a collection of C++ classes designed for numerical and
63physics analysis software development. Our goal is to provide
64easy to use, yet powerful classes which can be used by scientists.
[2790]65Although some of the SOPHYA modules (SkyMap, Samba, SkyT)
[3045]66have been designed with the specific goal of CMB data analysis, most
[2790]67modules presented here have a much broader scope and can be
68used in scientific data analysis and modeling/simulation.
[3006]69Whenever possible, we use existing numerical packages and libraries,
70encapsulating them in classes in order to facilitate their usage.
[1435]71\par
[3006]72Our main requirements in designing SOPHYA classes can be summarized as
73follow:
74\begin{itemize}
75\item[\rond] Provide a comprehensive set of data containers, such as arrays and tables
76(tuple) covering the most common needs in scientific simulation and data analysis
77softwares.
78\item[\rond] Take advantage of the C++ language and define methods and operators
79for most basic operation, such as arithmetic operations, in a rather intuitive way, while
80maintaining performances comparable to low level coding in other languages
81(C, Fortran, F90 \ldots)
82\item[\rond] Simplify memory management for programmers using the class library.
83This has been a strong requirement for most SOPHYA classes. Automatic reference
84sharing and memory management is implemented in SOPHYA classes intended
85for large size objects. We recommend to allocate SOPHYA objects on the stack,
86including when objects are returned by methods or functions.
87See section \ref{memgt} for more information.
88\item[\rond] Archiving, importing (reading) and exporting (writing) data in a
89efficient and consistent way is a major concern in many scientific software
90and projects. SOPHYA provide a native data I/O or persistence system,
91(PPF, \ref{ppfdesc}) as well as import/export services for ASCII and FITS formats.
92\end{itemize}
93
94% \vspace*{2mm}
[1435]95This documents
[1434]96presents only a brief overview of the class library,
97mainly from the user's point of view. A more complete description
[2278]98can be found in the reference manual, available from the SOPHYA
[2280]99web site: % {\bf http://www.sophya.org}.
100\href{http://www.sophya.org}{http://www.sophya.org}.
[3006]101%%%
102%%%
[3438]103\subsection{Acknowlegments}
104Many people have contributed to the development SOPHYA and/or the PI library
105and (s)piapp interactive analysis tool.
106we are grateful to the following people:
107
108\begin{tabular}{lcl}
109Reza Ansari & \hspace{5mm} & (LAL-Univ.Paris Sud, Orsay) \\
110Eric Aubourg & & (DAPNIA-CEA/APC, Saclay) \\
111Sophie Henrot-Versille & & (LAL-IN2P3/CNRS, Orsay) \\
112Alex Kim & & (LBL, Berkeley) \\
113Guy Le Meur & & (LAL-IN2P3/CNRS, Orsay) \\
114Eric Lesquoy & & (DAPNIA-CEA, Saclay) \\
115Christophe Magneville & & (DAPNIA-CEA, Saclay) \\
116Bruno Mansoux & & (LAL-IN2P3/CNRS, Orsay) \\
117Olivier Perdereau & & (LAL-IN2P3/CNRS, Orsay) \\
118Nicolas Regnault & & (LPNHE-IN2P3/CNRS, Paris) \\
119Benoit Revenu & & (APC/Univ.Paris 7, Paris) \\
120Francois Touze & & (LAL-IN2P3/CNRS, Orsay) \\
121\end{tabular}
122
123We thank also the persons who have helped us by useful suggestions, among others : \\
[3441]124S. Bargot, S. Plasczczynski, C. Renault and D. Yvon.
[3438]125
[3006]126\subsection{SOPHYA modules}
[3045]127\label{sopmodules}
[1434]128The source directory tree
[2790]129\footnote{ CVS: cvsserver.lal.in2p3.fr:/exp/eros/CVSSophya}
[887]130is organised into a number of modules.
131
132\begin{itemize}
[2790]133\item[] {\bf BuildMgr/} Scripts for code management,
[887]134makefile generation and software installation
[2278]135\item[] {\bf BaseTools/} General architecture support classes such
[887]136as {\tt PPersist, NDataBlock<T>}, and few utility classes
[2278]137such as the dynamic variable list manager ({\tt DVList}) as well
138as the basic set of exception classes used in SOPHYA.
[1340]139\item[] {\bf TArray/} template numerical arrays, vectors and matrices \\
[1648]140({\tt TArray<T> TMatrix<T> TVector<T> } \ldots)
[887]141\item[] {\bf NTools/} Some standard numerical analysis tools
142(linear, and non linear parameter fitting, FFT, \ldots)
[1648]143\item[] {\bf HiStats/} Histogram-ming and data set handling classes (tuples) \\
[2790]144({\tt Histo Histo2D NTuple DataTable} \ldots)
145\item[] {\bf SkyMap/} Local and full sky maps, and some 3D geometry
[1648]146handling utility classes. \\
147({\tt PixelMap<T>, LocalMap<T>, SphericalMap<T>, \ldots})
[2790]148\item[] {\bf SUtils/} This module contains few utility classes, such as the
[2278]149{\tt DataCard} class, as well as string manipulation functions in C and C++.
150\item[] {\bf SysTools/} This module contains classes implementing
151an interface to various OS specific services, such
[2790]152threads and dynamic link/shared library handling.
[2278]153
[887]154\end{itemize}
155
[978]156The modules listed below are more tightly related to the
157CMB (Cosmic Microwave Background) data analysis problem:
[887]158\begin{itemize}
159\item[] {\bf SkyT/}
160classes for spectral emission and detector frequency response modelling \\
161({\tt SpectralResponse, RadSpectra, BlackBody} \ldots)
[1436]162\item[] {\bf Samba/} Spherical harmonic analysis, noise generators \ldots
[887]163\end{itemize}
164
[978]165The following modules contain the interface classes with
166external libraries:
[887]167\begin{itemize}
[988]168\item[] {\bf FitsIOServer/} Classes for handling file input-output
[3006]169in FITS format using the cfitsio library.
170FITS is maintained by NASA and SAO and is available from: \\
171\href{http://heasarc.gsfc.nasa.gov/docs/software/fitsio/fitsio.html}
172{http://heasarc.gsfc.nasa.gov/docs/software/fitsio/fitsio.html}
173\item[] {\bf LinAlg/} Interface with Lapack linear algebra package.
174Lapack is a linear algebra package and can be downloaded from: \\
175\href{http://www.netlib.org/lapack/}{http://www.netlib.org/lapack/}
176\item[] {\bf IFFTW/} Interface with FFTW package (libfftw.a).
177FFTW is a package for performing Fourier transforms, written in C.
178Documentation and source code can be found at: \\
179\href{http://www.fftw.org/}{http://www.fftw.org/}
[1648]180\item[] {\bf XAstroPack/} Interface to some common astronomical
181computation libraries. Presently, this module uses an external library
182extracted from the {\bf Xephem } source code. The corresponding source
183code is also available from SOPHYA cvs repository, module {\bf XephemAstroLib}.
[3006]184Information on Xephem can be found at : \\
185\href{http://www.clearskyinstitute.com/xephem/}{http://www.clearskyinstitute.com/xephem/}
[2790]186
[887]187\end{itemize}
188
[2278]189The following modules contain each a set of related programs using the
190SOPHYA library.
[887]191\begin{itemize}
[3415]192\item[] {\bf Tests/} Simple test programs. Many of these test programs can be also used
193as examples for using SOPHYA.
[1340]194\item[] {\bf PrgUtil/} Various utility programs (runcxx, scanppf, scanfits, \ldots)
[2278]195\item[] {\bf PrgMap/} Programs performing operations on skymaps: projections,
196power spectrum in harmonic space, \ldots
197\end{itemize}
198
199As a companion to SOPHYA, the {\bf (s)piapp} interactive data analysis
200program is built on top of SOPHYA and the {\bf PI} GUI class library
201and application framework. The {\bf PI} ({\bf P}eida {\bf Interactive})
202development started in 1995, in the EROS \footnote{EROS: {\bf E}xp\'erience
203de {\bf R}echerche d'{\bf O}bjets {\bf S}ombres - http://eros.in2p3.fr}
204microlensing search collaboration, with PEIDA++ \footnote {PEIDA++:
205The EROS data analysis class library -
206http://www.lal.in2p3.fr/recherche/eros/PeidaDoc/}.
207The {\bf PI} documentation and the {\bf piapp} user's guide are available
[2280]208from \href{http://www.sophya.org}{http://www.sophya.org}.
[2278]209%\href{http://www.sophya.org}{http://www.sophya.org}.
210The {\bf PI} is organized as the following modules:
211\begin{itemize}
[2280]212\item[] {\bf PI/} Portable GUI class library and application development
[2278]213framework kernel.
[2280]214\item[] {\bf PIGcont/} Contour-plot drawing classes.
215\item[] {\bf PIext/} Specific drawers and adapters for SOPHYA objects,
[2278]216and the {\bf piapp} interactive data analysis framework.
217\item[] {\bf ProgPI/} interactive analysis tool main program and pre-loaded
218modules.
[887]219\end{itemize}
220
[3006]221Modules containing examples and demo programs and scripts:
[1434]222\begin{itemize}
223\item[] {\bf Examples/} Sample SOPHYA codes and example programs and
[2790]224makefiles.
225\item[] {\bf DemoPIApp/} Sample scripts and programs for (s)piapp
[1434]226interactive analysis tools.
227\end{itemize}
[3415]228
229The following modules contains additional programs or libraries, based on SOPHYA :
230\begin{itemize}
231\item[] {\bf AnaLC} contains program files extracted from the EROS/PEIDA software
232and adapted to be compiled with SOPHYA. It can be used in particular to read and analyse
233EROS light curve data files.
234\item[] {\bf LUC} {\bf L}ittle {\bf U}niverse {\bf C}alculator is a module containing classes to
235perform basic computation related to the universe geometry (FRW metric).
236\item[] {\bf PMixer/} skymixer and related programs
237\end{itemize}
238
[988]239\newpage
240
[978]241\section{Using Sophya}
[2996]242The organisation of SOPHYA directories and some of the associated
243utility programs are described in this section.
[3045]244Basic usage of Sophya classes is described in the following sections.
[2278]245Complete Sophya documentation can be found at our web site
[1434]246{\bf http://www.sophya.org}.
[1362]247
[2790]248\subsection{Directories, environment variables, configuration files}
[3015]249\label{directories}
[2790]250The environment variable {\bf SOPHYABASE} is used
[3006]251to define the path where the Sophya libraries and binaries are installed.
[978]252\begin{itemize}
[2790]253\item \$SOPHYABASE/include : Include (.h) files
254\item \$SOPHYABASE/lib : Path for the archive libraries (.a)
[3015]255\item \$SOPHYABASE/slb: Shared library path (.so or .dylib on Darwin/MacOS)
[3006]256\item \$SOPHYABASE/exe : Path for binary program files
[978]257\end{itemize}
258
[2790]259The directory { \tt \$SOPHYABASE/include/SophyaConfInfo/ } contains files
260describing the installed configuration of SOPHYA software.
[978]261
[2790]262The file { \tt \$SOPHYABASE/include/machdefs.h } contains definitions
[3015]263(flags, typedef) used in SOPHYA, while some more specific flags,
264are found in { \tt \$SOPHYABASE/include/sspvflags.h }
[2790]265
266The file { \tt \$SOPHYABASE/include/sophyamake.inc } contains the
267compilation commands and flags used for building the software.
268Users can use most of compilation and link commands defined in this file:
269 {\tt \$CCOMPILE , \$CXXCOMPILE . \$CXXLINK \ldots}.
270 (See module Example).
271
272The configure script (BuildMgr/configure) creates the directory tree and the
[3015]273above files. It also copy (or create symbolic link) for all SOPHYA include
274files as well as symbolic links for external libraries
275include files path in {\tt \$SOPHYABASE/include} (FitsIO, FFTW, XAstro \ldots).
[2790]276
[3015]277Object files for each module are grouped in a static archive library
278by the build procedure (libXXX.a for module
279XXX, with XXX = BaseTools, TArray, HiStats, FitsIOServer \ldots).
280
281When shared libraries are build, all stand alone SOPHYA modules
282are grouped in {\tt libsophya.so}, {\tt libextsophya.so} contains
283the interface modules with external libraries {\bf (FitsIOServer, LinAlg \ldots)},
284while {\bf PI, PIext, PIGcont} modules are grouped in {\tt libPI.so}.
285Alternatively, it is possible to group all modules in a single shared
286library {\tt libAsophyaextPI.so} (See \ref{build})
287
288In order to use the shared libraries, the {\bf LD\_LIBRARY\_PATH} variable
289should contain the Sophya shared library path
290({\tt \$SOPHYABASE/slb}).
291On Silicon Graphics machines with IRIX64 operating system,
292the default SOPHYA configuration correspond to the 64 bit architecture.
293The environment variable { \bf LD\_LIBRARY64\_PATH } replace in
294this case the usual {\bf LD\_LIBRARY\_PATH} variable.
295On IBM machines with AIX, the {\bf LIBPATH} environment variables
296contains the shared libraries search path.
297
298When using the dynamic load services in SOPHYA ({\tt PDynLinkMgr}
299class), in runcxx or (s)piapp applications for example, the shared
300library search path must contain the current working directory (
301dot . in unix).
302
[3419]303\subsection{Copy constructor and assignment operator}
304\label{memgt}
305In C++, objects can be copied by assignment or by initialisation.
306Copying by initialisation corresponds to creating an object and
307initialising its value through the copy constructor.
308The copy constructor has its first argument as a reference, or
309const reference to the object's class type. It can have
310more arguments, if default values are provided.
311Copying by assignment applies to an existing object and
312is performed through the assignment operator (=).
313The copy constructor implements this for identical type objects:
314\begin{verbatim}
315class MyObject {
316public:
317 MyObject(); // Default constructor
318 MyObject(MyObject const & a); // Copy constructor
319 MyObject & operator = (MyObject const & a) // Assignment operator
320}
321\end{verbatim}
322The copy constructors play an important role, as they are
323called when class objects are passed by value,
324returned by value, or thrown as an exception.
325\begin{verbatim}
326// A function declaration with an argument of type MyObject,
327// passed by value, and returning a MyObject
328MyObject f(MyObject x)
329{
330 MyObject r;
331 ...
332 return(r); // Copy constructor is called here
333}
334// Calling the function :
335MyObject a;
336f(a); // Copy constructor called for a
337\end{verbatim}
338It should be noted that the C++ syntax is ambiguous for the
339assignment operator. {\tt MyObject x; x=y; } and
340{\tt MyObject x=y;} have different meaning.
341\begin{verbatim}
342MyObject a; // default constructor call
343MyObject b(a); // copy constructor call
344MyObject bb = a; // identical to bb(a) : copy constructor call
345MyObject c; // default constructor call
346c = a; // assignment operator call
347\end{verbatim}
348
349As a general rule in SOPHYA, objects which implements
350reference sharing on their data members have a copy constructor
351which shares the data, while the assignment operator copies or
352duplicate the data.
353
354\subsection{Multi-thread programming with SOPHYA}
355Multi-thread programming is usually safe as long as different threads DO NOT access
356the same memory locations. SOPHYA is mainly organized as classes having only
357data members, with very few cases having static data members (memory locations
358common to all instances of a class), or seldom, global variables. \\
359Using different instances of a class in different threads is thus safe for most
360classes / methods in SOPHYA. \\
361A major exception is the reference sharing mechanism, where different instances
362of a class may shared memory locations. This reference sharing mechanism has been
363made thread-safe in SOPHYA, from version V=2.1. \\
364As a consequence, different execution threads can access non overlapping sub-arrays
365and access (read/write) the corresponding elements without the need of
366mutex and thread synchonisation. Moreover, thread safe filling of
367NTuple and DataTable objects can be activated, on an object per object basis. \\
368The {\tt ZThread, ZMutex \ldots} classes in the {\bf SysTools } module offer a relatively
369easy way of writing multi-threaded programs.
370
[1362]371\subsection{the runcxx program}
[3037]372\index{runcxx} \label{runcxx}
[1362]373{\bf runcxx} is a simple program which can be used to compile, link
374and run simple C++ programs. It handles the creation of a
375complete program file, containing the basic set C++ include files,
376the necessary include files for SOPHYA SysTools, TArray, HiStats
377and NTools modules, and the main program with exception handling.
378Other Sophya modules can be included using the {\tt -import} flag.
[1435]379Use of additional include files can be specified using the
380{\tt -inc} flag.
[1362]381\begin{verbatim}
382csh> runcxx -h
[2790]383 PIOPersist::Initialize() Starting Sophya Persistence management service
384SOPHYA Version 1.9 Revision 0 (V_Mai2005) -- May 31 2005 15:11:32 cxx
385 runcxx : compiling and running of a piece of C++ code
386 Usage: runcxx [-compopt CompileOptions] [-linkopt LinkOptions]
387 [-tmpdir TmpDirectory] [-f C++CodeFileName]
388 [-inc includefile] [-inc includefile ...]
389 [-import modulename] [-import modulename ...]
390 [-uarg UserArg1 UserArg2 ...]
391 if no file name is specified, read from standard input
392 modulenames: SkyMap, Samba, SkyT, FitsIOServer,
393 LinAlg, IFFTW, XAstroPack
[1362]394\end{verbatim}
[3419]395Most examples in this manual can be tested using runcxx.
396The preprocessor macro {\tt KeepObj()} is defined by runcxx and let the user
397to save an objet to an PPF file, with the same name as the corresponding variable.
398The example below shows how to compile, link and run a sample
[1362]399code.
400\begin{verbatim}
[3419]401## File example.icc :
402
403Matrix mxa(3,3);
404mxa = IdentityMatrix(1.);
405cout << mxa ;
406// Save the object mxa in a PPF file named mxa
407KeepObj(mxa);
408
409## Executing this sample code
[1362]410csh> runcxx -f example.icc
411\end{verbatim}
[2278]412
413\subsection{the scanppf program}
[3037]414\index{scanppf} \label{scanppf}
[2278]415{\bf scanppf} is a simple SOPHYA application which can be used to check
[2790]416PPF files and list their contents. It can also provide the list of all registered
417PPF handlers.
[2278]418\begin{verbatim}
419csh> scanppf -h
[2790]420 PIOPersist::Initialize() Starting Sophya Persistence management service
[3034]421SOPHYA Version 2.0 Revision 0 (V_Jul2006) -- Jul 17 2006 14:13:27 cxx
[2790]422 Usage: scanppf [flags] filename
[3034]423 flags = -s -n -a0 -a1 -a2 -a3 -lh -lho -lmod
[2790]424 -s[=default} : Sequential reading of objects
425 -n : Object reading at NameTags
426 -a0...a3 : Tag List with PInPersist.AnalyseTags(0...3)
427 -lh : List PPersist handler classes
428 -lho : List PPersist handler and dataobj classes
[3034]429 -lmod : List initialized/registered modules
[2278]430\end{verbatim}
431
[3037]432\subsection{the scanfits program}
433\index{scanfits} \label{scanfits}
[2996]434{\bf scanfits} is a SOPHYA program using the FitsIOServer
435\footnote{FitsIOServer module uses the cfitsio library. scanfits has to be linked with
436with FitsIOServer module and cfitsio libraries, or libextsophya.so}
437module which can be used
438to analyse the content of FITS files. It can list the FITS headers, the appropriate
439SOPHYA-FITS handler (implementing {\tt FitsHandlerInterface}) class, and the list of
440all registered FITS handlers.
441\begin{verbatim}
442csh> scanfits -h
443 PIOPersist::Initialize() Starting Sophya Persistence management service
[3037]444SOPHYA Version 2.0 Revision 0 (V_Jul2006) -- Jul 17 2006 14:13:27 cxx
[2996]445 Usage: scanfits [flags] filename
446 flags = -V1 -lh -rd -header
447 -V1 : Scan using old (V1) code version
448 -lh : Print the list of registered handlers (FitsHandlerInterface)
449 -rd : try to read each HDU data using appropriate handler
450 -header : List header information
451\end{verbatim}
[2278]452
[3415]453\subsection{the spiapp program}
454\index{spiapp} \label{spiapp}
455{\bf spiapp} is an interactive data analysis program, built on top of the SOPHYA
456library, , the PI GUI library. The interactive data analysis framework is defined
457by the classes in the {\bf PIext} module. spiapp has a c-shell like
458command interpreter and can be used to manipulate SOPHYA and display
459objects. Refer to the piapp user manual for more information.
460\begin{verbatim}
461csh> spiapp -h
462 SophyaInitiator::SophyaInitiator() BaseTools Init
463 PIOPersist::Initialize() Starting Sophya Persistence management service
464SOPHYA Version 2.1 Revision 0 (V_Nov2007) -- Nov 24 2007 13:08:58 gcc 3.3 20030304 (Apple Computer, Inc. build 1495)
465
466 piapp: Interactive data analysis and visualisation program
467 Usage: piapp [-nored] [-doublered] [-termread] [-term]
468 [-hidezswin] [-small] [-nosig] [-nosigfpe] [-nosigsegv]
469 [-tmpdir TmpDirectory] [-help2tex] [-exec file [args]]
470 -nored : Don't redirect stdout/stderr to piapp console
471 -doublered : Redirect stdout/stderr to piapp console AND the terminal
472 -termread : Read commands on terminal (stdin)
473 -term : equivalent to -nored -termread -small
474 -hidezswin : Hide Zoom/Stat/ColMap window
475 -small : Create small size main piapp window
476 -nosig : Don't catch SigFPE, SigSEGV
477 -nosigfpe -nosigsegv: Don t catch SigFPE / SigSEGV
478 -tmpdir TmpDirectory: defines TMDIR for temporary files
479 -help2tex: Create a LaTeX help file (piahelp.tex)
480 -exec file [args] : Execute command file (last option)
481
482\end{verbatim}
[978]483
[1299]484
[1435]485\newpage
[2278]486\section{Module BaseTools}
[1299]487
[2278]488{\bf BaseTools} contains utility classes such as
[1299]489{\tt DVlist}, an hierarchy of exception classes for Sophya, a template
490class {\tcls{NDataBlock}} for handling reference counting on numerical
491arrays, as well as classes providing the services for implementing simple
[3419]492serialisation (object persistence services).
[1299]493\vspace*{5mm}
494
[3034]495\subsection{Initialisation}
496\index{SophyaInitiator}
497A number of actions have to be taken before
498some of the services provided by SOPHYA become operational. This is the case
499of SOPHYA persistence, as well as FITS I/O facilities.
500Initialisation of many SOPHYA modules is performed through an initialiser class,
[3040]501which inherits from {\bf SophyaInitiator}.
502\par
503Static instance of each initialiser class exist in the library and the various SOPHYA services
504should be operational when the user code ({\tt main()}) starts, except for
505modules in the second or third shared libraries
506({\tt libextsophya.so libPI.so}). Indeed, a problem related
507to the initialisation of shared libraries arises on some systems
508(Darwin/Mac OS X in particular) causing program crash at start-up,
509if static instance of initialiser class is present in the second shared library.
510The FitsIOServer module should thus be explicitly initialised in the user
511program.
512\par
513In cases where the run time loader does not perform correctly the static
514object initialisation, the initialiser class for the modules used in the
515program must be instanciated in the beginning of your main program: \\
516{\tt TArrayInitiator , HiStatsInitiator , SkyMapInitiator , FitsIOServer \ldots}
[3034]517%%%
[1340]518\subsection{SOPHYA persistence}
[3006]519\label{ppfdesc}
[1362]520\index{PPersist} \index{PInPersist} \index{POutPersist}
[1299]521\begin{figure}[hbt]
522\dclsa{PPersist}
[2790]523\dclsccc{PPFBinarIOStream}{PPFBinaryInputStream}{PInPersist}
524\dclscc{PPFBinaryOutputStream}{POutPersist}
[1299]525\caption{partial class diagram for classes handling persistence in Sophya}
526\end{figure}
[1340]527A simple persistence mechanism is defined in SOPHYA. Its main
528features are:
529\begin{itemize}
530\item[] Portable file format, containing the description of the data structures
531and object hierarchy. \\
532{\bf PPF} {\bf P}ortable {\bf P}ersistence file {\bf F}ormat.
[1648]533\index{PPF}
[1435]534\item[] Handling of read/write for multiply referenced objects.
[1340]535\item[] All write operations are carried using sequential access only. This
536holds also for read operations, unless positional tags are used.
537SOPHYA persistence services can thus be used to transfer objects
538through network links.
[1360]539\item[] The serialisation (reading/writing) for objects for a given class
[1435]540is implemented through a handler object. The handler class inherits
[1360]541from {\tt PPersist} class.
[1435]542\item[] A run time registration mechanism is used in conjunction with
543RTTI (Run Time Type Identification) for identifying handler classes
544when reading {\bf PInPersist} streams, or for associating handlers
545with data objects {\bf AnyDataObject} for write operations.
[1340]546\end{itemize}
[3419]547The most useful methods for using Sophya
548persistence are listed below. A brief description of the PPF file format
549and some guidelines for writing writing delegate classes for handling
550object persistence can be found in the following paragraphs.
[1435]551\begin{itemize}
552\item[] {\tt POutPersist::PutObject(AnyDataObj \& o)} \\
553Writes the data object {\bf o} to the output stream.
554\item[] {\tt POutPersist::PutObject(AnyDataObj \& o, string tagname)} \\
555Writes the data object {\bf o} to the output stream, associated with an
556identification tag {\bf tagname}.
557\item[] {\tt PInPersist::GetObject(AnyDataObj \& o)} \\
558Reads the next object in stream into {\bf o}. An exception is
559generated for incompatible object types.
560\item[] {\tt PInPersist::GetObject(AnyDataObj \& o, string tagname)} \\
561Reads the object associated with the tag {\bf tagname} into {\bf o}.
562An exception is generated for incompatible object types.
563\end{itemize}
564The operators {\tt operator << (POutPersist ...) } and
565{\tt operator >> (PInPersist ...) } are often overloaded
[2790]566to perform {\tt PutObject()} and {\tt GetObject()} operations.
567the {\bf PPFNameTag} (ppfnametag.h) class can be used in conjunction with
568{\tt << >> } operators to write objects with a name tag or to retrieve
569an object identified with a name tag. The example below shows the
570usage of these operators:
[1435]571\begin{verbatim}
572// Creating and filling a histogram
573Histo hw(0.,10.,100);
574...
575// Writing histogram to a PPF stream
576POutPersist os("hw.ppf");
[2790]577os << PPFNameTag("myhisto") << hw;
578
[1435]579// Reading a histogram from a PPF stream
580PInPersist is("hr.ppf");
[2790]581is >> PPFNameTag("myhisto") >> hr;
[1435]582\end{verbatim}
[1360]583
[1435]584The {\bf scanppf} program can be used to list the content of a PPF file.
585
[3419]586\subsubsection{PPF file format}
587The PPF file consist of :
588\begin{itemize}
589\item[\rond] A file header (3x32=96 bytes) , containing an identification string,
590PPF format version (currently V3), the file endiannes {\tt (BIG-ENDIAN , LITTLE-ENDIAN)}
591and the file creation date and time. It should be noted that the present SOPHYA version
592(V=2.1) does not allow updating an existing PPF file.
593\item[\rond] A collection of tagged data items and data structuring tags.
594the PPF tags are one byte (8 bits) long and may be followed by a length information
595for arrays, or strings. The length information might be 4 bytes or 8 bytes long.
596Characters, various length (1,2,4,8 bytes long) signed and unsigned integers,
597simple or double precision (4/8) bytes floating point and complex numbers are
598the basic data types handled by PPF streams.
599\begin{verbatim}
600tag=PPS_SIMPLE_Integer4 + data (4 bytes)
601tag=PPS_SIMPLE_Float4 + data (4 bytes)
602tag=PPS_SIMPLE_Complex8 + data (2x8=16 bytes)
603tag=PPS_STRING + Length (4 bytes) + data (Length bytes)
604tag=PPS_SIMPLE_ARRAY4_UInt2 + Length (4 bytes) + data (2xLength bytes)
605\end{verbatim}
606The two tags {\tt PPS\_OBJECT} and {\tt PPS\_ENDOBJECT} are used for identifying
607objects.
608\item[\rond] The file trailer contains some global statistics such as the total number
609of objects in file, the list of name tags, with their corresponding positions.
610These informations are grouped under the identifier tag {\tt PPS\_NAMETAG\_TABLE }.
611The last byte in file contains the value {\tt PPS\_EOF}
612\end{itemize}
613We show below the result of the analysis of a PPF file using
614 {\tt PPFBinaryInputStream::AnalyseTags()}. This can easily be done using the
615 {\bf runcxx} program.
616The PPF file contains four objects:
617a {\tt TimeStamp} object, two {\tt NDataBlock} objects, the second one sharing its data with
618the first one. The second NDataBlock is only written as a reference to the first object. The fourth
619object is a {\tt RandomGenerator} which has an {\tt NDataBlock} object as data member.
620Notice the corresponding nested structure of object marker tags.
621The first object and the last objects in the file are written associated with a {\bf NameTag}.
622{\small
623\begin{verbatim}
624 ----------------------------------------------------------
625 PPFBinaryInputStream::AnalyseTags(Level= 49)
626 FileName= toto.ppf
627 Version= 3 FileSize= 8884 Creation Date= Fri Dec 7 15:30:58 2007
628
629 NbPosTag=0 NbNameTag=2 NbObjs=4 NbTopLevObjs=3 NbRefs=1 MaxNest=2
630
631<PPS_NAMETAG_MARK> tag at position 60
632<PPS_OBJECT> tag at position 61 ClassId= c09dfe032b341cee ObjectId= 10
633 <PPS_SIMPLE> tag at position 72 DataType=INTEGER x4
634 <PPS_SIMPLE> tag at position 77 DataType=INTEGER x8
635 <PPS_SIMPLE> tag at position 80 DataType=FLOAT x8
636<PPS_ENDOBJECT> tag at position 89 ObjectId= 10
637<PPS_OBJECT> tag at position 92 ClassId= e670300b367585d1 ObjectId= 21
638 <PPS_SIMPLE_ARRAY4> tag at position a3 DataType=UNSIGNED x8 NElts= 3
639 <PPS_SIMPLE_ARRAY4> tag at position c0 DataType=INTEGER x4 NElts= 50
640<PPS_ENDOBJECT> tag at position 18d ObjectId= 21
641<PPS_REFERENCE> tag at position 196 ObjectId= 21 OrigPos=92
642<PPS_NAMETAG_MARK> tag at position 1a7
643<PPS_OBJECT> tag at position 1a8 ClassId= eb6c427a5a30caed ObjectId= 30
644 <PPS_SIMPLE_ARRAY4> tag at position 1b9 DataType=UNSIGNED x4 NElts= 6
645 <PPS_SIMPLE> tag at position 1d6 DataType=UNSIGNED x8
646 <PPS_SIMPLE> tag at position 1df DataType=UNSIGNED x8
647 <PPS_OBJECT> tag at position 1e8 ClassId= 6531a8f47336d4aa ObjectId= 41
648 <PPS_SIMPLE_ARRAY4> tag at position 1f9 DataType=UNSIGNED x8 NElts= 3
649 <PPS_SIMPLE_ARRAY4> tag at position 216 DataType=FLOAT x8 NElts= 1024
650 <PPS_ENDOBJECT> tag at position 221b ObjectId= 41
651<PPS_ENDOBJECT> tag at position 2224 ObjectId= 30
652<PPS_NAMETAG_TABLE> tag at position 222d
653<PPS_NAMETAG_ENTRY> NameTag=rg-randgen NameTagMark Position=1a7
654<PPS_NAMETAG_ENTRY> NameTag=ts-timestamp NameTagMark Position=60
655<PPS_EOF> tag at position 22b3 TagPos=222d
656 PPFBinaryInputStream::AnalyseTags() - End - Total Number of Tags= 23
657 ----------------------------------------------------------
658\end{verbatim}
659} % fin de small
660
661\subsubsection{Writing PPF handlers}
662Here are some guidelines for creating PPF handler classes to make
663a class persistent through the SOPHYA PPersist mechanism. The example
664discussed here can be found in the {\bf Examples} module, in the directory
665{\bf MyPPF}.
666\begin{enumerate}
667\item The class should inherit from the {\bf SOPHYA::AnyDataObj} class.
668 In the example here, we want to make the class {\bf Vfs} persistent
669\begin{verbatim}
670class Vfs : public SOPHYA::AnyDataObj {
671 ...
672}
673\end{verbatim}
674%%%%
675\item The PPF handler class
676should inherit from {\bf SOPHYA::PPersist} . The pure virtual methods
677of PPersist class (DataObj() , SetDataObj() , ReadSelf(), WriteSelf()
678must be implemented.
679\begin{verbatim}
680class PPFHandlerVfs : public SOPHYA::PPersist {
681public:
682 virtual SOPHYA::AnyDataObj* DataObj();
683 virtual void SetDataObj(SOPHYA::AnyDataObj &);
684protected:
685 virtual void ReadSelf(SOPHYA::PInPersist&);
686 virtual void WriteSelf(SOPHYA::POutPersist&) const;
687}
688\end{verbatim}
689%%%
690It is possible to use the template class {\tt SOPHYA::ObjFileIO<T>}, and
691specialize it for the tharget class (here {\tt SOPHYA::ObjFileIO<Vfs>}),
692by defining the two methods : \\
693\hspace*{5mm} {\tt SOPHYA::ObjFileIO<Vfs>::ReadSelf(SOPHYA::PInPersist\&) } \\
694\hspace*{5mm} {\tt SOPHYA::ObjFileIO<Vfs>::WriteSelf(SOPHYA::POutPersist\&) const }
695%%%%
696\item If it is NOT possible to have the target class inherit from {\bf AnyDataObj},
697a wrapper class should be used. The same class can play the role of wrapper
698AND the PPF handler. See the PPF handler / wrapper class for STL vectors : \\
699\hspace*{5mm} {\tt SOPHYA::PPFWrapperSTLVector<T>} in file BaseTools/ppfwrapstlv.h
700%%%
701\item Implement the ReadSelf() and WriteSelf() methods of the PPF handler.
702All the I/O services from the following classes can be used :
703\begin{itemize}
704\item PPFBinaryIOStrem , PPFBinaryInputStream , PInPersist
705\item PPFBinaryIOStrem , PPFBinaryOutputStream , POutPersist
706\end{itemize}
707Writing and reading of the embeded objects for which a handler has been register
708ed can simply be performed by : \\
709\hspace*{5mm} {\tt POutPersist::PutObject() } \\
710\hspace*{5mm} {\tt PInPersist::GetObject() }
711
712{\bf Warning:} The services associated with nametags : \\
713\hspace*{5mm} {\tt PPFBinaryOutputStream::WriteNameTag() } \\
714\hspace*{5mm} {\tt PPFBinaryInputStream::GotoNameTag() } \\
715are {\bf NOT} intented to be used in WriteSelf() , ReadSelf()
716%%%%%
717\item The new PPF handler, as well as the list of classes it can handle has to be
718registered prior to use PPF read/write for the target classes. This must be
719performed during the initialization phase, for example at the beginning of the
720main() program. Another possibility is to use a module initializer
721(See {\bf SophyaInitiator} class in file BaseTools/sophyainit.h )
722and declare a static instance of the class. Notice that this works only if
723the system loader handles correcly the call of constructor
724for the statically declared objects.
725
726The registration can be performed using the CPP macros defined in
727BaseTools/ppersist.h
728\begin{verbatim}
729 // First, register the PPF handler ObjFileIO<Vfs>
730 PPRegister(ObjFileIO<Vfs>);
731 // Register the list of classes which can be handled by ObjFileIO<Vfs>
732 DObjRegister(ObjFileIO<Vfs>, Vfs);
733\end{verbatim}
734%%%%%%%%%%%%%%%%
735\end{enumerate}
736
737%%%%%%%%%%%%
[1360]738\subsection{\tcls{NDataBlock}}
[1362]739\index{\tcls{NDataBlock}}
740\begin{figure}[hbt]
741\dclsbb{AnyDataObj}{\tcls{NDataBlock}}
742\dclsbb{PPersist}{\tcls{FIO\_NDataBlock}}
743\end{figure}
[1360]744The {\bf \tcls{NDataBlock}} is designed to handle reference counting
745and sharing of memory blocs (contiguous arrays) for numerical data
746types. Initialisation, resizing, basic arithmetic operations, as
747well as persistence handling services are provided.
748The persistence handler class ({\tt \tcls{FIO\_NDataBlock}}) insures
749that a single copy of data is written for multiply referenced objects,
750and the data is shared among objects when reading.
751\par
752The example below shows writing of NDataBlock objects through the
753use of overloaded operator $ << $ :
[1340]754\begin{verbatim}
755#include "fiondblock.h"
756// ...
757POutPersist pos("aa.ppf");
758NDataBlock<r_4> rdb(40);
759rdb = 567.89;
760pos << rdb;
761// We can also use the PutObject method
762NDataBlock<int_4> idb(20);
763idb = 123;
764pos.PutObject(idb);
765\end{verbatim}
766The following sample programs show the reading of the created PPF file :
767\begin{verbatim}
768PInPersist pis("aa.ppf");
769NDataBlock<r_4> rdb;
770pis >> rdb;
771cout << rdb;
772NDataBlock<int_4> idb;
773cout << idb;
774\end{verbatim}
[1299]775
[2996]776\subsection{DVList, MuTyV and TimeStamp classes}
777\index{DVList} \index{MuTyV} \index{TimeStamp}
[1362]778\begin{figure}[hbt]
[2996]779\dclsa{MuTyV}
[1362]780\dclsbb{AnyDataObj}{DVList}
781\dclsbb{PPersist}{\tclsc{ObjFileIO}{DVList}}
782\end{figure}
783The {\bf DVList} class objects can be used to create and manage list
784of values, associated with names. A list of pairs of (MuTyV, name(string))
785is maintained by DVList objects. {\bf MuTyV} is a simple class
786capable of holding string, integer, float or complex values,
787providing easy conversion methods between these objects.
[2996]788{\bf MuTyV} objects can also hold {\bf TimeStamp } objects.
[1362]789\begin{verbatim}
790// Using MuTyV objects
791MuTyV s("hello"); // string type value
792MuTyV x;
[1435]793x = "3.14159626"; // string type value, ASCII representation for Pi
[1362]794double d = x; // x converted to double = 3.141596
795x = 314; // x contains the integer value = 314
796// Using DVList
797DVList dvl;
798dvl("Pi") = 3.14159626; // float value, named Pi
799dvl("Log2") = 0.30102999; // float value, named Log2
800dvl("FileName") = "myfile.fits"; // string value, named myfile.fits
801// Printing DVList object
802cout << dvl;
803\end{verbatim}
804
[2996]805\begin{figure}[hbt]
806\dclsbb{AnyDataObj}{TimeStamp}
807\end{figure}
808%
809The {\bf TimeStamp} class represent date and time and provides
810many standard operations, such as Initialisation from strings,
811conversion to strings and time interval computations. \\
812Usage example:
813\begin{verbatim}
814// Create a object with the current date and time and prints it to cout
815TimeStamp ts;
816cout << ts << endl;
817// Create an object with a specified date and time
818TimeStamp ts2("01/01/1905","00:00:00");
819// Get the number of days since 0 Jan 1901
820cout << ts2.ToDays() << endl;
821
822// Combined use of TimeStamp and MuTyV
823string s;
824TimeStamp ts; // Current date/time
825MuTyV mvt = ts;
826s = mvt; // s contains the current date in string format
827cout << s << endl;
828\end{verbatim}
829
[2790]830\subsection{\tcls{SegDataBlock} , \tcls{SwSegDataBlock}}
[3037]831\index{\tcls{SegDataBlock}} \index{\tcls{SwSegDataBlock}}
832%%
[2790]833\begin{figure}[hbt]
834\dclsccc{AnyDataObj}{\tcls{SegDBInterface}}{ \tcls{SegDataBlock} }
835\dclscc{\tcls{SegDBInterface}}{ \tcls{SwSegDataBlock} }
836\end{figure}
837\begin{itemize}
[3415]838\item[\rond] \tcls{SegDataBlock} handles arrays of object of
[2790]839type {\bf T} with reference sharing in memory. The array can be extended
840(increase in array size) with fixed segment size. It implements the interface
[2996]841defined by \tcls{SegDBInterface}.
[3415]842\item[\rond] \tcls{SwSegDataBlock} Implements the same \tcls{SegDBInterface}
[2996]843using a data swapper object. Data swappers implement the interface defined in
844(\tcls{DataSwapperInterface} class. \tcls{SwSegDataBlock} can
845thus be used to handle arrays with very large number of objects.
846These classes handles reference sharing.
[2790]847\end{itemize}
848
[3419]849 \subsection{Random numbers}
850 \index{RandomGenerator}
[3723]851\begin{figure}[hbt]
852\dclsbb{ AnyDataObj }{ RandomGeneratorInterface }
853\vspace*{5mm}
854\dclsccc{RandomGeneratorInterface}{DR48RandGen}{ ThSDR48RandGen }
855\dclsbb{ RandomGeneratorInterface }{ FMTRandGen }
856\end{figure}
857%% CHECK
858{\bf \large SECTION A METTRE A JOUR } \\
[3419]859 The C-functions defined in the file BaseTools/srandgen.h can be used
860 for generating sequence of random numbers with different PDF (probability
861 distribution functions : flat, gaussian, poisson \ldots.
862 However, we advise to use the {\bf RandomGenerator} class which provides
863can be used in multi-threaded programs. In this case, a different instance of
864the RandomGenerator class should be created in each thread running in parallel.
865In addition, this class has a PPF handler which saves the complete state of the class and
866the underlying generatoir to the PPF stream. This can be used to generate very long sequence
867of random numbers, distributed over several runs.
868\begin{verbatim}
869sa_size_t N = 1000;
870Vector vf(2*N), vg(2*N);
871{
872// Instanciate the random generator
873RandomGenerator rg;
874// Generate some sequence of random numbers
875for(sa_size_t i=0; i<N; i++) {
876 vf(i) = rg.Flat01();
877 vg(i) = rg.Gaussian();
878 }
879// Save the generator to file rg.ppf
880POutPersist po("rg.ppf");
881po << rg;
882}
883// ....
884{
885// Create and read the generator from file rg.ppf
886RandomGenerator rg;
887PInPersist pi("rg.ppf");
888pi >> rg;
889// Continue the generation sequence
890for(sa_size_t i=N; i<2*N; i++) {
891 vf(i) = rg.Flat01();
892 vg(i) = rg.Gaussian();
893 }
894}
895\end{verbatim}
896
897%%%%%%%%%%%%
[1435]898\newpage
[1299]899\section{Module TArray}
[1362]900\index{\tcls{TArray}}
[1299]901{\bf TArray} module contains template classes for handling standard
902operations on numerical arrays. Using the class {\tt \tcls{TArray} },
903it is possible to create and manipulate up to 5-dimension numerical
[1362]904arrays {\tt (int, float, double, complex, \ldots)}. The include
905file {\tt array.h} declares all the classes and definitions
[1435]906in module TArray. {\bf Array} is a typedef for arrays
[1411]907with double precision floating value elements. \\
908{\tt typedef TArray$<$r\_8$>$ Array ; }
[1299]909
910\begin{figure}[hbt]
911\dclsccc{AnyDataObj}{BaseArray}{\tcls{TArray}}
[1362]912\dclsbb{PPersist}{\tcls{FIO\_TArray}}
[1299]913\end{figure}
914
[2919]915The development of this module started around 1999-2000,
916after evaluation of a number of publicly available
917C++ array hadling packages, including TNT, Lapack++, Blitz++,
918as well as commercial packages from RogueWave (math.h++ \ldots).
919Most of these packages provide interesting functionalities, however,
920not any one package seemed to fulfill most of our requirements.
921\begin{itemize}
922\item Capability to handle {\bf large - multidimensional - dense}
923arrays, for numerical data types. Although we have used templates, for
924data type specialisation, the actual code, apart inline functions is
925not in header files. Instead, we use explicit instanciation, and the
926compiled code for the various numerical types of arrays is the
927library .
928\item The shape and size of the arrays can be defined and changed
929at run time. The classes ensure the memory management of the
930created objets, with reference sharing for the array data.
931The default behaviour of the copy constructor is to share the data,
932avoiding expensive memory copies.
933\item The package provides transparent management of sub-arrays
934and slices, in an intuitive way, somehow similar to what is
935available in Mathlab or Scilab.
936\item The memory organisation for arrays, specially matrices
937(row-major or column major) can be
938controled. This provide compatibility when using existing C or
939Fortran coded numerical libraries.
940\item The classes provide efficient methods to perform basic arithmetic
941and mathematical operations on arrays. In addition, operator overload
942provides intuitive programming for element acces and most basic
943arithmetic operations.
944\item Conversion can be performed between arrays with different
945data types. Copy and arithmetic operations can be done transparently
946between arrays with different memory organisation patterns.
947\item This module does not provide more complex operations
948such as FFT or linear algebra. Additional libraries are used, with interface
949classes for these operations.
950\item ASCII formatted I/O, for printing and read/write operations to/from text files.
951\item Efficient binary I/O for object persistence (PPF format), or import/export
952to other data formats, such as FITS are provided by helper or handler classes.
953\end{itemize}
[1360]954
[1299]955\subsection{Using arrays}
[1362]956\index{Sequence} \index{RandomSequence} \index{RegularSequence}
957\index{EnumeratedSequence}
[1435]958The example below shows basic usage of arrays, creation, initialisation
[1362]959and arithmetic operations. Different kind of {\bf Sequence} objects
[1435]960can be used for initialising arrays.
[1411]961
[1362]962\begin{figure}[hbt]
963\dclsbb{Sequence}{RandomSequence}
964\dclsb{RegularSequence}
965\dclsb{EnumeratedSequence}
966\end{figure}
[1299]967
[1340]968The example below shows basic usage of arrays:
[1414]969\index{\tcls{TArray}}
[1340]970\begin{verbatim}
[1435]971// Creating and initialising a 1-D array of integers
[1362]972TArray<int> ia(5);
973EnumeratedSequence es;
974es = 24, 35, 46, 57, 68;
975ia = es;
976cout << "Array<int> ia = " << ia;
977// 2-D array of floats
978TArray<r_4> b(6,4), c(6,4);
979// Initializing b with a constant
980b = 2.71828;
981// Filling c with random numbers
982c = RandomSequence();
983// Arithmetic operations
984TArray<r_4> d = b+0.3f*c;
985cout << "Array<float> d = " << d;
[1340]986\end{verbatim}
987
[1362]988The copy constructor shares the array data, while the assignment operator
989copies the array elements, as illustrated in the following example:
990\begin{verbatim}
991TArray<int> a1(4,3);
992a1 = RegularSequence(0,2);
993// Array a2 and a1 shares their data
994TArray<int> a2(a1);
995// a3 and a1 have the same size and identical elements
996TArray<int> a3;
997a3 = a1;
998// Changing one of the a2 elements
999a2(1,1,0) = 555;
1000// a1(1,1) is also changed to 555, but not a3(1,1)
1001cout << "Array<int> a1 = " << a1;
1002cout << "Array<int> a3 = " << a3;
1003\end{verbatim}
1004
[3037]1005\subsection{Arithmetic operations}
1006The four usual arithmetic operators ({\bf + \, - \, * \, / }) are defined
1007to perform constant addition, subtraction, multiplication and division.
1008The three operators ({\bf + \, - \, / }) between two arrays of the same type
1009are defined to perform element by element addition, subtraction
1010and division. In order to avoid confusion with matrix multiplication,
1011element by element multiplication is defined by overloading the
1012operator {\bf \, \&\& \, }, as shown in the example below:
1013\begin{verbatim}
1014TArray<int_4> a(4,3), b(4,3), c , d, e;
1015a = RegularSequence(1.,1.);
1016b = RegularSequence(10.,10.);
1017cout << a << b ;
1018c = a && b;
1019d = c / a;
1020e = (c / b) - a;
1021cout << c << d << e;
1022\end{verbatim}
1023
[1362]1024\subsection{Matrices and vectors}
1025\index{\tcls{TMatrix}} \index{\tcls{TVector}}
1026\begin{figure}[hbt]
1027\dclsccc{\tcls{TArray}}{\tcls{TMatrix}}{\tcls{TVector}}
1028\end{figure}
1029Vectors and matrices are 2 dimensional arrays. The array size
1030along one dimension is equal 1 for vectors. Column vectors
1031have {\tt NCols() = 1} and row vectors have {\tt NRows() = 1}.
[1411]1032Mathematical expressions involving matrices and vectors can easily
1033be translated into C++ code using {\tt TMatrix} and
1034{\tt TVector} objects. {\bf Matrix} and {\bf Vector} are
1035typedefs for double precision float matrices and vectors.
1036The operator {\bf *} beteween matrices is redefined to
1037perform matrix multiplication. One can then write: \\
1038\begin{verbatim}
1039 // We create a row vector
1040 Vector v(1000, BaseArray::RowVector);
1041 // Initialize values with a random sequence
1042 v = RandomSequence();
1043 // Compute the vector length (norm)
1044 double norm = (v*v.Transpose()).toScalar();
1045 cout << "Norm(v) = " << norm << endl;
1046\end{verbatim}
[1362]1047
[1414]1048This module contains basic array and matrix operations
1049such as the Gauss matrix inversion algorithm
[1411]1050which can be used to solve linear systems, as illustrated by the
1051example below:
[1340]1052\begin{verbatim}
[1411]1053#include "sopemtx.h"
1054// ...
1055// Creation of a random 5x5 matrix
1056Matrix A(5,5);
1057A = RandomSequence(RandomSequence::Flat);
1058Vector X0(5);
1059X0 = RandomSequence(RandomSequence::Gaussian);
1060// Computing B = A*X0
1061Vector B = A*X0;
1062// Solving the system A*X = B
1063Vector X;
1064LinSolve(A, B, X);
1065// Checking the result
1066Vector diff = X-X0;
1067cout << "X-X0= " << diff ;
1068double min,max;
1069diff.MinMax(min, max);
1070cout << " Min(X-X0) = " << min << " Max(X-X0) = " << max << endl;
1071\end{verbatim}
1072
[2919]1073{\bf Warning: } The operations defined in {\tt sopemtx.h}, such as
1074matrix inversion and linear system solver use a basic Gauss pivot
1075algorithm which are not adapted for large matrices ($>\sim 100x100$).
1076The services provided in other modules, such as {\bf LinAlg} should
1077be preferred in such cases.
1078
[1411]1079\subsection{Working with sub-arrays and Ranges}
[1414]1080\index{Range}
[1411]1081A powerful mechanism is included in array classes for working with
1082sub-arrays. The class {\bf Range} can be used to specify range of array
1083indexes in any of the array dimensions. Any regularly spaced index
1084range can be specified, using the {\tt start} and {\tt end} index
1085and an optional step (or stride). It is also possible to specify
[2919]1086the {\tt start} index and the number of elements.
1087\begin{itemize}
1088\item {\bf Range::all()} {\tt = Range(Range::firstIndex(), Range::lastIndex())} \\
1089return a Range objects representing all valid indexes along the
1090corresponding axe.
1091\item {\bf Range::first()} {\tt = Range(Range::firstIndex())} \\
1092return a Range object representing the first valid index
1093\item {\bf Range::last()} {\tt = Range(Range::lastIndex())}
1094return a Range object representing the last valid index
1095\item {\bf Range(idx)} represents a single index ({\bf = idx})
1096\item {\bf Range(first, last)} represents the range of indices
[3415]1097{\bf first} $\leq$ index $\leq$ {\bf last}.\\
[2919]1098The static method {\tt Range::lastIndex()} can be used
1099to specify the last valid index.
1100\item {\bf Range(first, last, step)} represents the range of index
1101which is equivalent to \\ {\tt for(index=first; index <= last; index += step) }
1102\item { \bf Range (first, last, size, step) } the general form can be used
1103to specify an index range, using the number of elements.
1104It is possible to specify a range of index, ending with the last valid index.
1105For example \\
1106\hspace*{5mm}
1107{\tt Range(Range::lastIndex(), Range::lastIndex(), 3, 2) } \\
1108defines the index range: \hspace*{5mm} last-4, last-2, last.
1109
[1648]1110\begin{center}
1111\begin{tabular}{ll}
[3034]1112\hline \\
[2919]1113\multicolumn{2}{c}{ {\bf Range} {\tt (start, end, size, step) } } \\[2mm]
[1648]1114\hline \\
[3034]1115{\bf Range} {\tt r(7); } & index range: \hspace{2mm} 7 \\
[2919]1116{\bf Range} {\tt r(3,6); } & index range: \hspace{2mm} 3,4,5,6 \\
[3034]1117{\bf Range} {\tt r(3,7,2); } & index range: \hspace{2mm} 3,5,7 \\
[2919]1118{\bf Range} {\tt r(7,0,3,1); } & index range: \hspace{2mm} 7,8,9 \\
[3034]1119{\bf Range} {\tt r(10,0,5,2); } & index range: \hspace{2mm} 10,12,14,16,18 \\[2mm]
1120\hline
[1648]1121\end{tabular}
1122\end{center}
[2919]1123\end{itemize}
[1648]1124
[2919]1125The method {\tt TArray<T>SubArray(Range ...)} can be used
1126to extract subarrays and slices. The operator {\tt operator() (Range rx, Range ry ...)}
1127is also overloaded for sub-array extraction.
1128For matrices, {\tt TMatrix<T>::Row()} and {\tt TMatrix<T>::Column()}
1129extract selected matrix rows and columns.
1130
1131The example illustrates the sub-array extraction using Range objects:
1132\begin{verbatim}
1133 // Creating and initialising a 2-D (6 x 4) array of integers
1134 TArray<int> iaa(6, 4);
1135 iaa = RegularSequence(1,2);
1136 cout << "Array<int> iaa = \n" << iaa;
1137 // We extract a sub-array - data is shared with iaa
1138 TArray<int> iae = iaa(Range(1, Range::lastIndex(), 3) ,
1139 Range::all(), Range::first() );
1140 cout << "Array<int> iae=subarray(iaa) = \n" << iae;
1141 // Changing iae elements changes corresponding iaa elements
1142 iae = 0;
1143 cout << "Array<int> iae=0 --> iaa = \n" << iaa;
1144
1145\end{verbatim}
1146
[1648]1147In the following example, a simple low-pass filter, on a one
[1411]1148dimensional stream (Vector) has been written using sub-arrays:
1149
1150\begin{verbatim}
[1340]1151// Input Vector containing a noisy periodic signal
1152 Vector in(1024), out(1024);
1153 in = RandomSequence(RandomSequence::Gaussian, 0., 1.);
1154 for(int kk=0; kk<in.Size(); kk++)
1155 in(kk) += 2*sin(kk*0.05);
1156// Compute the output vector by a simple low pass filter
1157 Vector out(1024);
1158 int w = 2;
1159 for(int k=w; k<in.Size()-w; k++)
1160 out(k) = in(Range(k-w, k+w).Sum()/(2.*w+1.);
1161\end{verbatim}
1162
[1648]1163\subsection{Input, Output}
1164Arrays can easily be saved to, or restored from files in different formats.
1165SOPHYA library can handle array I/O to ASCII formatted files, to PPF streams,
1166as well as to files in FITS format.
1167FITS format input/output is provided through the classes in
[3037]1168{\bf FitsIOServer} module. Only arrays with data types
[1648]1169supported by the FITS standard can be handled during
1170I/O operations to and from FITS streams (See the FitsIOServer section
1171for additional details).
1172
1173\subsubsection{PPF streams}
1174
1175SOPHYA persistence (PPF streams) handles reference sharing, and multiply
1176referenced objects are only written once. A hierarchy of arrays and sub-arrays
1177written to a PPF stream is thus completely recovered, when the stream is read.
1178The following example illustrates this point:
1179\begin{verbatim}
1180{
1181// Saving an array with a sub-array into a POutPersist file
1182Matrix A(3,4);
1183A = RegularSequence(10,5);
1184// Create a sub-array of A
1185Matrix AS = A(Range(1,2), Range(2,3));
1186// Save the two arrays to a PPF stream
1187POutPersist pos("aas.ppf");
1188pos << A << AS;
1189}
1190{
1191// Reading arrays from the previously created PPF file aas.ppf
1192PInPersist pis("aas.ppf");
1193Matrix B,BS;
1194pis >> B >> BS;
1195// BS is a sub-array of B, modifying BS changes also B
1196BS(1,1) = 98765.;
1197cout << " B , BS after BS(1,1) = 98765. "
1198 << B << BS << endl;
1199}
1200\end{verbatim}
1201The execution of this sample code creates the file {\tt aas.ppf} and
[2919]1202its output is reproduced here. Notice that the array hierarchy is
[1648]1203recovered. BS is a sub-array of B, and modifying BS changes also
1204the corresponding element in B.
1205\begin{verbatim}
1206 B , BS after BS(1,1) = 98765.
1207
1208--- TMatrix<double>(NRows=3, NCols=4) ND=2 SizeX*Y*...= 4x3 ---
120910 15 20 25
121030 35 40 45
121150 55 60 98765
1212
1213--- TMatrix<double>(NRows=2, NCols=2) ND=2 SizeX*Y*...= 2x2 ---
121440 45
121560 98765
1216\end{verbatim}
1217
[3417]1218{\bf Warning: }
[1648]1219There is a drawback in this behaviour: only a single
1220copy of an array is written to a file, even if the array is modified,
[3417]1221without being resized and written (dumped) again to the same PPF stream.
1222However, this behavior can be changed using the {\tt RenewObjId()} method,
1223as illustrated below.
[1648]1224\begin{verbatim}
1225{
1226POutPersist pos("mca.ppf");
1227TArray<int_4> ia(5,3);
1228ia = 8;
[3419]1229pos << ia; // (1)
[1648]1230ia = 16;
[3419]1231pos << ia; // (2) Only a reference to the previously ia array is written
[1648]1232ia = 32;
[3417]1233ia.RenewObjId(); // We change the object Id
[3419]1234pos << ia; // (3) The complete array is dumped again
[1648]1235}
1236\end{verbatim}
1237
1238Only a single copy of the data is effectively written to the output
[3417]1239PPF file, corresponding to the value 8 for array elements, for the first two
1240write operations. When we
[1648]1241read the three array from the file mca.ppf, the same array elements
[3417]1242are obtained two times (all elements equal to 8), and a different array is obtained
1243the third time
[1648]1244\begin{verbatim}
1245{
1246PInPersist pis("mca.ppf");
1247TArray<int_4> ib;
1248pis >> ib;
1249cout << " First array read from mca.ppf : " << ib;
1250pis >> ib;
1251cout << " Second array read from mca.ppf : " << ib;
1252pis >> ib;
1253cout << " Third array read from mca.ppf : " << ib;
1254}
1255\end{verbatim}
1256
1257\subsubsection{ASCII streams}
1258
1259The {\bf WriteASCII} method can be used to dump an array to an ASCII
1260formatted file, while the {\bf ReadASCII} method can be used to decode
1261ASCII formatted files. Space or tabs are the possible separators.
1262Complex numbers should be specified as a pair of comma separated
1263real and imaginary parts, enclosed in parenthesis.
1264
1265\begin{verbatim}
1266{
1267// Creating array A and writing it to an ASCII file (aaa.txt)
1268Array A(4,6);
1269A = RegularSequence(0.5, 0.2);
1270ofstream ofs("aaa.txt");
1271A.WriteASCII(ofs);
1272}
1273{
1274// Decoding the ASCII file aaa.txt
1275ifstream ifs("aaa.txt");
1276Array B;
1277sa_size_t nr, nc;
1278B.ReadASCII(ifs,nr,nc);
1279cout << " Array B; B.ReadASCII() from file " << endl;
1280cout << B ;
1281}
1282\end{verbatim}
1283
[3417]1284\subsection{Cast without conversion}
1285Data conversion between arrays with different data type is handled transparently,
1286through the copy constructor or the assignment (=) operator . However, in rare cases,
1287one wants to access the same memory locations, without data type conversion.
1288The template functions defined in {\tt arrctcast.h} can be used to access the same
1289memory locations, by arrays with different data types. The SOPHYA/NDataBlock
1290reference sharing mechanism is effective When using these functions.
1291Notice that the array size or stride may change during these cast operations. \\
1292 {\tt arrctcast.h} has been introduced in version V=2.1 (Nov 2007), and has not been
1293 fully tested for non packed arrays.
1294\begin{verbatim}
1295// We define and initialize a real array :
1296TArray<r_4> fa(5);
1297fa = RegularSequence(1.25,0.5);
1298cout << " fa= " << fa;
1299// We construct an integer array from fa, where the floating point values
1300// are converted to integer values
1301TArray<uint_2> ia(fa);
1302cout << " ia= " << ia;
1303cout << " ia (in hex)= " << hex << ia << dec;
1304// We can also access the fa memory locations interpreted as short integers
1305uint_2 ui2;
1306// Note that sfia size is double the fa size
1307TArray<uint_2> sfia = ArrayCast(fa, ui2);
1308cout << " sfia= " << sfia;
1309cout << " sfia (in hex)= " << hex << sfia << dec;
1310\end{verbatim}
1311One of the most useful case of these array type cast without conversion
1312correspond to accessing the real or imaginary part of a complex array.
1313Two specific template functions {\tt SDRealPart()} and {\tt SDImagPart()}
1314are also defined in {\tt arrctcast.h}. Two other functions {\tt ArrCastR2C()}
1315and {\tt ArrCastC2R() } are also defined for real to complex, and
1316complex to real cast.
1317Their usage is shown in the next paragraph on complex arrays.
[1648]1318
1319\subsection{Complex arrays}
1320The {\bf TArray} module provides few functions for manipulating
1321arrays of complex numbers (single and double precision).
1322These functions are declared in {\tt matharr.h}.
1323\begin{itemize}
1324\item[\bul] Creating a complex array through the specification of the
1325real and imaginary parts.
1326\item[\bul] Functions returning arrays corresponding to real and imaginary
1327parts of a complex array: {\tt real(za) , imag(za) }
[3419]1328({\bf Warning:} Note that the these functions create an array and copies
1329the data from the original complex array. They do not provide
1330shared memory access to real and imaginary parts.
1331For shared memory access, use functions {\tt SDRealPart()} and
1332{\tt SDImagPart() } (see below).
[1648]1333\item[\bul] Functions returning arrays corresponding to the module,
1334phase, and module squared of a complex array:
1335 {\tt phase(za) , module(za) , module2(za) }
1336\end{itemize}
1337
1338\begin{verbatim}
1339 TVector<r_4> p_real(10, BaseArray::RowVector);
1340 TVector<r_4> p_imag(10, BaseArray::RowVector);
1341 p_real = RegularSequence(0., 0.5);
1342 p_imag = RegularSequence(0., 0.25);
1343 TVector< complex<r_4> > zvec = ComplexArray(p_real, p_imag);
1344 cout << " :: zvec= " << zvec;
1345 cout << " :: real(zvec) = " << real(zvec) ;
1346 cout << " :::: imag(zvec) = " << imag(zvec) ;
1347 cout << " :::: module2(zvec) = " << module2(zvec) ;
1348 cout << " :::: module(zvec) = " << module(zvec) ;
1349 cout << " :::: phase(zvec) = " << phase(zvec) ;
1350\end{verbatim}
1351
1352The decoding of complex numbers from an ASCII formatted stream
1353is illustrated by the next example. As mentionned already,
1354complex numbers should be specified as a pair of comma separated
1355real and imaginary parts, enclosed in parenthesis.
1356
1357\begin{verbatim}
1358csh> cat zzz.txt
1359(1.,-1) (2., 2.5) -3. 12.
1360-24. (-6.,7.) 14.2 (8.,64.)
1361
1362// Decoding of complex numbers from an ASCII file
1363// Notice that the << operator can be used instead of ReadASCII
1364TArray< complex<r_4> > Z;
1365ifstream ifs("zzz.txt");
1366ifs >> Z;
1367cout << " TArray< complex<r_4> > Z from file zzz.txt " << Z ;
1368\end{verbatim}
1369
[3417]1370\noindent {\bf Shared data access :} It is possible to access a complex array
1371elements (real and imaginary parts) through the template functions defined
1372in {\tt arrctcast.h} and discussed above. The example below shows how to use
1373these functions.
[1648]1374
[3417]1375\begin{verbatim}
1376// We define a complex array
1377TArray< complex<r_4> > za(5);
1378cout << " za= " << za;
1379// And two real arrays, corresponding to the real and imaginary parts
1380TArray<r_4> rza = SDRealPart(za);
1381TArray<r_4> iza = SDImagPart(za);
1382// We initialize the real and imaginary parts of the complex array
1383rza = RegularSequence(10.,2.);
1384iza = RegularSequence(5.,0.75);
1385cout << " rza=..., iza=... ----> za = " << za;
1386// The complex array seen as a real array (double size)
1387TArray<r_4> aza = ArrCastC2R(za);
1388cout << " za --> aza= " << aza;
[3419]1389TArray< complex<r_4> > zb;
1390zb = ArrCastR2C(aza);
1391KeepObj(zb);
[3417]1392\end{verbatim}
1393
[1360]1394\subsection{Memory organisation}
1395{\tt \tcls{TArray} } can handle numerical arrays with various memory
1396organisation, as long as the spacing (steps) along each axis is
1397regular. The five axis are labeled X,Y,Z,T,U. The examples below
1398illustrates the memory location for a 2-dimensional, $N_x=4 \times N_y=3$.
1399The first index is along the X axis and the second index along the Y axis.
1400\begin{verbatim}
[3419]1401 | (0,0) (1,0) (2,0) (3,0) |
1402 | (0,1) (1,1) (2,1) (3,1) |
1403 | (0,2) (1,2) (2,2) (3,2) |
[1360]1404\end{verbatim}
1405In the first case, the array is completely packed
1406($Step_X=1, Step_Y=N_X=4$), with zero offset,
1407while in the second case, $Step_X=2, Step_Y=10, Offset=10$:
1408\begin{verbatim}
1409 | 0 1 2 3 | | 10 12 14 16 |
1410Ex1 | 4 5 6 7 | Ex2 | 20 22 24 26 |
1411 | 8 9 10 11 | | 30 32 34 36 |
1412\end{verbatim}
1413
1414For matrices and vectors, an optional argument ({\tt MemoryMapping})
1415can be used to select the memory mapping, where two basic schemes
1416are available: \\
1417{\tt CMemoryMapping} and {\tt FortranMemoryMapping}. \\
1418In the case where {\tt CMemoryMapping} is used, a given matrix line
1419is packed in memory, while the columns are packed when
1420{\tt FortranMemoryMapping} is used. The first index when addressing
1421the matrix elements (line number index) runs along
1422the Y-axis if {\tt CMemoryMapping} is used, and along the X-axis
1423in the case of {\tt FortranMemoryMapping}.
1424Arithmetic operations between matrices
1425with different memory organisation is allowed as long as
1426the two matrices have the same sizes (Number of rows and columns).
1427The following code example and the corresponding output illustrates
[1414]1428these two memory mappings. The {\tt \tcls{TMatrix}::TransposeSelf() }
1429method changes effectively the matrix memory mapping, which is also
1430the case of {\tt \tcls{TMatrix}::Transpose() } method without argument.
1431
[1360]1432\begin{verbatim}
[3419]1433BaseArray::SetDefaultMemoryMapping(BaseArray::CMemoryMapping);
[1360]1434TArray<r_4> X(4,2);
1435X = RegularSequence(1,1);
1436cout << "Array X= " << X << endl;
[3419]1437TMatrix<r_4> X_C(X, true);
[1360]1438cout << "Matrix X_C (CMemoryMapping) = " << X_C << endl;
[3419]1439TMatrix<r_4> X_F(X_C, true);
1440X_F.TransposeSelf(); // we make it a FortranMemoryMapping matrix
[1360]1441cout << "Matrix X_F (FortranMemoryMapping) = " << X_F << endl;
1442\end{verbatim}
1443This code would produce the following output (X\_F = Transpose(X\_C)) :
1444\begin{verbatim}
1445Array X=
1446--- TArray<f> ND=2 SizeX*Y*...= 4x2 ---
14471, 2, 3, 4
14485, 6, 7, 8
1449
1450Matrix X_C (CMemoryMapping) =
1451--- TMatrix<f>(NRows=2, NCols=4) ND=2 SizeX*Y*...= 4x2 ---
14521, 2, 3, 4
14535, 6, 7, 8
1454
1455Matrix X_F (FortranMemoryMapping) =
1456--- TMatrix<f>(NRows=4, NCols=2) ND=2 SizeX*Y*...= 4x2 ---
14571, 5
14582, 6
14593, 7
14604, 8
1461\end{verbatim}
1462
[3419]1463{\bf Note:} Only the {\tt TMatrix} class is sensitive to the memory organisation. It should also
1464be noted that the first index for a matrix is the row index. For a {\tt TArray} object, the first
1465index correspond always to the X axis. For a matrix in the {\tt CMemoryMapping}, the row
1466index is the Y index of the corresponding array, while for a matrix
1467with {\tt FortranMemoryMapping}, the row index is the X index.
1468\begin{verbatim}
1469# 2D array arr , matrix mx
1470TArray<r_4> arr;
1471...
1472TMatrix<r_4> mx(arr);
1473...
1474### CMemoryMapping :
1475mx( row , col ) -> arr( ix=col, jy= row )
1476### FortranMemoryMapping :
1477mx( row , col ) -> arr( ix=row, jy= col )
1478\end{verbatim}
1479The following code fragment shows the difference between element access
1480index order for the different memory organisation:
1481\begin{verbatim}
1482 TArray<int_4> a(5,3);
1483 a = RegularSequence(10,2);
1484 cout << "Array a = " << a << endl;
1485 TMatrix<r_4> mac(a);
1486 cout << "Matrix mac (CMemoryMapping) = " << mac << endl;
1487 TMatrix<r_4> maf(mac);
1488 maf.TransposeSelf(); // we make it a FortranMemoryMapping matrix
1489 cout << "Matrix maf (FortranMemoryMapping) = " << maf << endl;
1490 // ---- element access
1491 cout << " Array(ix,jy) : a(2,0)= " << a(2,0) << " a(1,2)= " << a(1,2)
1492 << " a(0,2)= " << a(0,2) << endl;
1493 cout << " mac(row,col) : mac(2,0)= " << mac(2,0) << " mac(1,2)= " << mac(1,2)
1494 << " mac(0,2)= " << mac(0,2) << endl;
1495 cout << " maf(row,col) : maf(2,0)= " << maf(2,0) << " maf(1,2)= " << maf(1,2)
1496 << " maf(0,2)= " << maf(0,2) << endl;
1497\end{verbatim}
1498
1499
[988]1500\newpage
1501
[1299]1502\section{Module HiStats}
1503\begin{figure}[hbt]
[2996]1504\dclsbb{AnyDataObj}{Histo}
1505\dclscc{Histo}{HProf}
[1299]1506\dclsbb{AnyDataObj}{Histo2D}
[3137]1507\dclsbb{AnyDataObj}{HistoErr}
1508\dclsbb{AnyDataObj}{Histo2DErr}
[1299]1509\caption{partial class diagram for histograms and ntuples}
1510\end{figure}
1511
[1347]1512{\bf HiStats} contains classes for creating, filling, printing and
1513doing various operations on one or two dimensional histograms
1514{\tt Histo} and {\tt Histo2D} as well as profile histograms {\tt HProf}. \\
[3006]1515This module also contains {\tt NTuple} and {\tt DataTable} which are
1516more or less the same as the binary or ascii FITS tables.
[1347]1517
[3006]1518\subsection{Histograms}
1519\subsubsection{1D Histograms}
[1414]1520\index{Histo}
[1347]1521For 1D histograms, various numerical methods are provided such as
1522computing means and sigmas, finding maxima, fitting, rebinning,
1523integrating \dots \\
[1435]1524The example below shows creating and filling a one dimensional histogram
1525of 100 bins from $-5.$ to $+5.$ to create a Gaussian normal distribution
[1347]1526with errors~:
1527\begin{verbatim}
1528#include "histos.h"
1529// ...
1530Histo H(-0.5,0.5,100);
1531H.Errors();
1532for(int i=0;i<25000;i++) {
1533 double x = NorRand();
1534 H.Add(x);
1535}
1536H.Print(80);
1537\end{verbatim}
1538
[3006]1539\subsubsection{2D Histograms}
[1414]1540\index{Histo2D}
[1347]1541Much of these operations are also valid for 2D histograms. 1D projection
1542or slices can be set~:
1543\begin{verbatim}
1544#include "histos2.h"
1545// ...
[1414]1546Histo2D H2(-1.,1.,100,0.,60.,50);
[1347]1547H2.SetProjX(); // create the 1D histo for X projection
1548H2.SetBandX(25.,35.); // create 1D histo projection for 25.<y<35.
1549H2.SetBandX(35.,45.); // create 1D histo projection for 35.<y<45.
1550H2.SetBandX(40.,55.); // create 1D histo projection for 40.<y<55.
1551//... fill H2 with what ever you want
1552H2.Print();
1553Histo *hx = H2.HProjX();
1554 hx->Print(80);
1555Histo *hbx2 = HBandX(1); // Get the second X band (35.<y<45.)
1556 hbx2->Print(80);
1557\end{verbatim}
1558
[3006]1559\subsubsection{Profile Histograms}
[1414]1560\index{HProf}
1561Profiles histograms {\bf HProf} contains the mean and the
1562sigma of the distribution
[1347]1563of the values filled in each bin. The sigma can be changed to
1564the error on the mean. When filled, the profile histogram looks
1565like a 1D histogram and much of the operations that can be done on 1D histo
1566may be applied onto profile histograms.
1567
[3137]1568\subsubsection{Histograms HistoErr and Histo2DErr}
[3061]1569\index{HistoErr}
[3137]1570The {\bf HistoErr} are basic histograms where the number of entries for each bin is kept.
1571Methods to compute of the mean and the variance in each bin are provided.
1572The {\bf Histo2DErr} is the same for $2$ dimensions.
[3061]1573
[1435]1574\subsection{Data tables (tuples)}
[3006]1575\begin{figure}[hbt]
1576\dclsbb{AnyDataObj}{NTuple}
1577\dclsccc{AnyDataObj}{BaseDataTable}{DataTable}
1578\dclscc{BaseDataTable}{SwPPFDataTable}
1579\end{figure}
1580
1581\subsubsection{NTuple}
[1414]1582\index{NTuple}
[3048]1583{\bf NTuple} are memory resident tables of 32 or 64 bits floating values
[2790]1584(float/double).They are arranged in columns. Each line is often called an event.
[1347]1585These objects are frequently used to analyze data.
[2790]1586The piapp graphicals tools can plot a column against an other one
[1347]1587with respect to various selection cuts. \\
1588Here is an example of creation and filling~:
1589\begin{verbatim}
1590#include "ntuple.h"
1591#include "srandgen.h"
1592// ...
1593char* nament[4] = {"i","x","y","ey"};
1594r_4 xnt[4];
1595NTuple NT(4,nament);
1596for(i=0;i<5000;i++) {
1597 xnt[0] = i+1;
1598 xnt[1] = 5.*drandpm1(); // a random value between -5 and +5
1599 xnt[2] = 100.*exp(-0.5*xnt[1]*xnt[1]) + 1.;
1600 xnt[3] = sqrt(xnt[2]);
1601 xnt[2] += xnt[3] * NorRand(); // add a random gaussian error
1602 NT.Fill(xnt);
1603}
1604\end{verbatim}
1605
[3048]1606{\bf XNTuple} provide additional functionalities, compared to NTuple. However,
1607this class is deprecated and superseded by classes inheriting from BaseDataTable.
1608It is only kept for backward compatibility and should not be used anymore.
1609Use DataTable and SwPPFDataTable instead.
[2790]1610Object of type XNTuple handle various types
[1414]1611of column values (double,float,int,string,...) and can handle
1612very large data sets, through swap space on disk.
[2790]1613
[3006]1614\subsubsection{DataTables}
[3034]1615\label{datatables}
[2790]1616\index{DataTable}
1617The class {\bf DataTable} extends significantly the functionalities provided by
1618NTuple. DataTable is a memory resident implementation of the interface
1619{\bf BaseDataTable } which organizes the data as a 2-D table. User can define
1620the name and data type of each column. Data is added to the table as rows.
1621The table is extended as necessary when adding rows.
1622The sample code below shows an example of DataTable usage :
[1414]1623\begin{verbatim}
[2790]1624 #include "datatable.h"
1625 // ...
[3037]1626 {
[2790]1627 DataTable dt(64);
1628 dt.AddFloatColumn("X0_f");
1629 dt.AddFloatColumn("X1_f");
1630 dt.AddDoubleColumn("X0X0pX1X1_d");
1631 double x[5];
1632 for(int i=0; i<63; i++) {
1633 x[0] = (i/9)-4.; x[1] = (i/9)-3.; x[2] = x[0]*x[0]+x[1]*x[1];
1634 dt.AddLine(x);
1635 }
1636 // Printing table info
1637 cout << dt ;
1638 // Saving object into a PPF file
1639 POutPersist po("dtable.ppf");
1640 po << dt ;
[3037]1641 }
[1414]1642\end{verbatim}
[1347]1643
[2790]1644
1645\index{SwPPFDataTable}
1646The class {\bf SwPPFDataTable} implements the BaseDataTable interface
1647using segmented data blocks with swap on PPF streams. Very large data sets
[3048]1648can be created and manipulated through this class. A similar class
1649SwFitsDataTable (\ref{SwFitsDataTable}), using
1650FITS files as swap space is also provided in the FitsIOServer module.
[2790]1651
[3006]1652\index{DataTableRow}
1653The class {\bf DataTableRow } is an auxiliary class which simplifies the manipulation
1654of BaseDataTable object rows.
[3034]1655The example below show how to create and filling a table, using a PPF stream as
1656swap space. In addition, we have used a {\tt DataTableRow} to prepare data
1657for each table line.
[3006]1658\begin{verbatim}
[3034]1659 #include "swppfdtable.h"
[3006]1660 // ...
[3034]1661 {
1662 // ---------- Create an output PPF stream (file)
1663 POutPersist po("swdtable.ppf");
1664 // ------------------
1665 // Create a table with 3 columns, using the above stream as swap space
1666 SwPPFDataTable dtrow(po, 64);
[3006]1667 dtrow.AddStringColumn("sline");
1668 dtrow.AddIntegerColumn("line");
[3034]1669 dtrow.AddDateTimeColumn("datime");
1670 //
[3006]1671 TimeStamp ts, ts2; // Initialize current date and time
1672 string sline;
[3034]1673 //---- Create a table row with the required structure
[3006]1674 DataTableRow row = dtrow.EmptyRow();
[3034]1675 // ----- Fill the table
1676 for(int k = 0; k<2500; k++) {
[3006]1677 sline = "L-";
1678 sline += (string)MuTyV(k);
1679 row["sline"] = sline;
1680 row[1] = k;
1681 ts2.Set(ts.ToDays()+(double)k);
1682 row["datime"] = ts2;
1683 dtrow.AddRow(row);
1684 }
[3034]1685 //------ Write the table itself to the stream, before closing the file
1686 po << PPFNameTag("SwTable") << dtrow;
1687 }
[3006]1688\end{verbatim}
[3034]1689%%
1690The previously created table can easily be read in, as shown below:
1691%%
1692\begin{verbatim}
1693 #include "swppfdtable.h"
1694 // ...
1695 {
1696 // ------ Create the input PPF stream (file)
1697 PInPersist pin("swdtable.ppf");
1698 // ------ Read in the SwPPFDataTable object
1699 SwPPFDataTable dtr;
1700 pin >> PPFNameTag("SwTable") >> dtr;
1701 // ---- Create a table row with the required structure
1702 DataTableRow row = dtr.EmptyRow();
1703 // ---- Acces and print two of the table rows :
1704 cout << dtr.GetRow(6, row) << endl;
1705 cout << dtr.GetRow(17, row) << endl;
1706 }
1707\end{verbatim}
1708
[1362]1709\subsection{Writing, viewing \dots }
[3419]1710%%
1711Histogram and NTuple/DataTable objects have PPF handlers and
1712can be written to or read from PPF files. Sophya graphical tool (spiapp) can
1713automatically display and operate on all these objects.
[1347]1714The following example shows how to write the previously created objects
1715into such a file~:
1716\begin{verbatim}
1717{
1718char *fileout = "myfile.ppf";
1719string tag;
1720POutPersist outppf(fileout);
1721tag = "H"; outppf.PutObject(H,tag);
1722tag = "H2"; outppf.PutObject(H2,tag);
1723tag = "NT"; outppf.PutObject(NT,tag);
1724} // closing ``}'' destroy ``outppf'' and automatically close the file !
1725\end{verbatim}
1726
[1414]1727\newpage
[1299]1728\section{Module NTools}
1729
[1347]1730This module provides elementary numerical tools for numerical integration,
1731fitting, sorting and ODE solving. FFTs are also provided (Mayer,FFTPack).
1732
1733\subsection{Fitting}
[1435]1734\index{Fitting} \index{Minimisation}
[1347]1735Fitting is done with two classes {\tt GeneralFit} and {\tt GeneralFitData}
1736and is based on the Levenberg-Marquardt method.
[1414]1737\index{GeneralFit} \index{GeneralFitData}
[1347]1738GeneralFitData is a class which provide a description of the data
1739to be fitted. GeneralFit is the fitter class. Parametrized functions
1740can be given as classes which inherit {\tt GeneralFunction}
1741or as simple C functions. Classes of pre-defined functions are provided
1742(see files fct1dfit.h and fct2dfit.h). The user interface is very close
1743from that of the CERN {\tt Minuit} fitter.
1744Number of objects (Histo, HProf \dots ) are interfaced with GeneralFit
1745and can be easily fitted. \\
1746Here is a very simple example for fitting the previously created NTuple
[1435]1747with a Gaussian~:
[1347]1748\begin{verbatim}
1749#include "fct1dfit.h"
1750// ...
1751
1752// Read from ppf file
1753NTuple nt;
1754{
1755PInPersist pis("myfile.ppf");
1756string tag = "NT"; pis.GetObject(nt,tag);
1757}
1758
1759// Fill GeneralData
1760GeneralData mGdata(nt.NEntry());
1761for(int i=0; i<nt.NEntry(); i++)
1762 mGdata.AddData1(xnt[1],xnt[2],xnt[3]); // Fill x, y and error on y
1763mGData.PrintStatus();
1764
1765// Function for fitting : y = f(x) + noise
1766Gauss1DPol mFunction; // gaussian + constant
1767
1768// Prepare for fit
1769GeneralFit mFit(&mFunction); // create a fitter for the choosen function
1770mFit.SetData(&mGData); // connect data to the fitter
1771
[1435]1772// Set and initialise the parameters (that's non-linear fitting!)
[1347]1773// (num par, name, guess start, step, [limits min and max])
1774mFit.SetParam(0,"high",90.,1..);
1775mFit.SetParam(1,"xcenter",0.05,0.01);
1776mFit.SetParam(2,"sigma",sig,0.05,0.01,10.);
1777 // Give limits to avoid division by zero
1778mFit.SetParam(3,"constant",0.,1.);
1779
1780// Fit and print result
1781int rcfit = mFit.Fit();
1782mFit.PrintFit();
1783if(rcfit>0) {)
1784 cout<<"Reduce_Chisquare = "<<mFit.GetChi2Red()
1785 <<" nstep="<<mFit.GetNStep()<<" rc="<<rcfit<<endl;
1786} else {
1787 cout<<"Fit_Error, rc = "<<rcfit<<" nstep="<<mFit.GetNStep()<<endl;
1788 mFit.PrintFitErr(rcfit);
1789}
1790
1791// Get the result for further use
1792TVector<r_8> ParResult = mFit.GetParm();
1793cout<<ParResult;
1794\end{verbatim}
1795
1796Much more usefull possibilities and detailed informations might be found
1797in the HTML pages of the Sophya manual.
1798
[3438]1799\subsection{Simplex method}
1800The class {\bf MinZSimplex} implements the simplex method for non linear
1801optimization / minimization. See the SOPHYA manual for more information.
1802
[1350]1803\subsection{Polynomial}
[1414]1804\index{Polynomial} \index{Poly} \index{Poly2}
[1350]1805Polynomials of 1 or 2 variables are supported ({\tt Poly} and {\tt Poly2}).
1806Various operations are supported~:
1807\begin{itemize}
1808\item elementary operations between polynomials $(+,-,*,/) $
1809\item setting or getting coefficients
1810\item computing the value of the polynomial for a given value
1811 of the variable(s),
1812\item derivating
1813\item computing roots (degre 1 or 2)
1814\item fitting the polynomial to vectors of data.
1815\end{itemize}
1816Here is an example of polynomial fitting~:
1817\begin{verbatim}
1818#include "poly.h"
1819// ...
1820Poly pol(2);
1821pol[0] = 100.; pol[1] = 0.; pol[2] = 0.01; // Setting coefficients
1822TVector<r_8> x(100);
1823TVector<r_8> y(100);
1824TVector<r_8> ey(100);
1825for(int i=0;i<100;i++) {
1826 x(i) = i;
1827 ey(i) = 10.;
1828 y(i) = pol((double) i) + ey(i)*NorRand();
1829 ey(i) *= ey(i)
1830}
1831
1832TVector<r_8> errcoef;
1833Poly polfit;
1834polfit.Fit(x,y,ey,2,errcoef);
1835
1836cout<<"Fit Result"<<polfit<<endl;
1837cout<<"Errors :"<<errcoef;
1838\end{verbatim}
1839
1840Similar operations can be done on polynomials with 2 variables.
1841
[1435]1842\subsection{Integration, Differential equations}
1843\index{Integration}
1844The NTools module provide also simple classes for numerical integration
1845of functions and differential equations.
1846\begin{figure}[hbt]
1847\dclsbb{Integrator}{GLInteg}
1848\dclsb{TrpzInteg}
1849\end{figure}
1850
1851\index{GLInteg} \index{TrpzInteg}
1852{\bf GLInteg} implements the integration through Gauss-Legendre method
1853and {\bf TrpzInteg} implements trapeze integration. For {\bf TrpzInteg},
1854number of steps specify the number of trapeze, and integration step,
1855their width.
1856The sample code below illustrates the use of TrpzInteg class:
1857\begin{verbatim}
1858#include "integ.h"
1859// ......................................................
1860// Function to be integrated
1861double myf(double x)
1862{
1863// Simple a x + b x^2 (a=2 b=3)
1864return (x*(2.+3.*x));
1865}
1866// ......................................................
1867
1868// Compute Integral(myf, 2., 5.) between xmin=2., xmax=5.
1869TrpzInteg trpz(myf, 2., 5.);
1870// We specify an integration step
1871trpz.DX(0.01);
1872// The integral can be computed as trpz.Value()
1873double myf_integral = trpz.Value();
1874// We could have used the cast operator :
1875cout << "Integral[myf, 2., 5.]= " << (double)trpz << endl;
1876// Limits can be specified through ValueBetween() method
1877cout << "Integral[myf, 0., 4.]= " << trpz.ValueBetween(0.,4.) << endl;
1878\end{verbatim}
1879
1880\subsection{Fourier transform (FFT)}
1881\index{FFT} \index{FFTPackServer}
1882An abstract interface for performing FFT operations is defined by the
1883{\bf FFTServerInterface} class. The {\bf FFTPackSever} class implements
1884one dimensional FFT, on real and complex data. FFTPackServer uses an
1885adapted and extended version of FFTPack (available from netlib),
1886translated in C, and can operate on single and double precision
1887({\tt float, double}) data.
1888
1889The sample code below illustrates the use of FFTServers:
1890\begin{verbatim}
1891#include "fftpserver.h"
1892 // ...
1893TVector<r_8> in(32);
1894TVector< complex<r_8> > out;
1895in = RandomSequence();
1896FFTPackServer ffts;
1897ffts.setNormalize(true); // To have normalized transforms
1898cout << " FFTServer info string= " << ffts.getInfo() << endl;
1899cout << "in= " << in << endl;
1900cout << " Calling ffts.FFTForward(in, out) : " << endl;
1901ffts.FFTForward(in, out);
1902cout << "out= " << out << endl;
1903\end{verbatim}
1904
[2278]1905% \newpage
1906\section{Module SUtils}
1907Some utility classes and C/C++ string manipulation functions are gathered
1908in {\bf SUtils} module.
1909\subsection{Using DataCards}
1910\index{DataCards}
1911The {\bf DataCards} class can be used to read parameters from a file.
1912Each line in the file starting with \@ defines a set of values
1913associated with a keyword. In the example below, we read the
1914parameters corresponding with the keyword {\tt SIZE} from the
1915file {\tt ex.d}. We suppose that {\tt ex.d} contains the line: \\
1916{\tt @SIZE 400 250} \\
1917\begin{verbatim}
1918#include "datacards.h"
1919// ...
1920// Initialising DataCards object dc from file ex.d
1921DataCards dc( "ex.d" );
1922// Getting the first and second parameters for keyword size
1923// We define a default value 100
1924int size_x = dc.IParam("SIZE", 0, 100);
1925int size_y = dc.IParam("SIZE", 1, 100);
1926cout << " size_x= " << size_x << " size_y= " << size_y << endl;
1927\end{verbatim}
1928
1929\section{Module SysTools}
1930The {\bf SysTools} module contains classes implementing interface to some
[3015]1931OS specific services, such as thread creation and management, dynamic loading and
1932resource usage information. For example, yhe class {\bf Periodic} provides the
1933necessary services needed to implement the execution of a periodic action.
1934
1935\subsection{Resource usage (CPU, memory \ldots) }
1936 The class {\bf ResourceUsage} \index{ResourceUsage}
[3037]1937and {\bf Timer} \index{Timer} provides access to information
[2304]1938about various resource usage (memory, CPU, ...).
[3037]1939The class {\bf Timer} \index{time (CPU, elapsed)} and c-functions
[3015]1940{\tt InitTim() , PrtTim(const char * Comm) } can be used to print
1941the amount of CPU and elapsed time in programs.
[2790]1942
[3015]1943The following sample code illustrates the use of {\bf ResourceUsage} :
1944\begin{verbatim}
1945 // How to check resource usage for a given part of the program
1946 ResourceUsage res;
1947 // --- Part of the program to be checked : Start
1948 // ...
1949 res.Update();
1950 cout << " Memory size increase (KB):" << res.getDeltaMemorySize() << endl;
1951 cout << " Resource usage info : \n" << res << endl;
1952\end{verbatim}
1953
[2790]1954\subsection{Thread management classes}
[3037]1955\index{ZThread} \index{ZMutex}
1956A basic interface to POSIX threads is also provided
[3015]1957through the \index{threads} {\bf ZThread}, {\bf ZMutex} and {\bf ZSync}
1958classes. The best way to use thread management classes is by inheriting
1959from {\bf ZThread} and redefining the {\tt run() } method.
1960It is also possible to use the default {\tt run() } implementation and associate
1961a function to perform the action, as in the example below :
1962\begin{verbatim}
1963 // The functions to perform computing
1964 void fun1(void *arg) { }
1965 void fun2(void *arg) { }
1966 // ...
1967 ZThread zt1;
1968 zt1.setAction(fun1, arg[1]);
1969 ZThread zt2;
1970 zt2.setAction(fun2, arg[1]);
1971 cout << " Starting threads ... " << endl;
1972 zt1.start();
1973 zt2.start();
1974 cout << " Waiting for threads to end ... " << endl;
1975 zt1.join();
1976 zt2.join();
1977\end{verbatim}
1978The classes {\bf ZMutex} \index{mutex} and {\bf ZSync} can be used
1979to perform synchronisation and signaling between threads.
[3419]1980Example multithread programs using these classes can be found in
1981the {\bf Tests} module : \\
1982\hspace{10mm} {\tt zthr.cc , tmtdt.cc , tmtrnd.cc }
1983
[3723]1984\begin{figure}[hbt]
1985\dclsbb{ZThread}{ParalExThread}
1986\dclsa{ParallelExecutor}
1987\end{figure}
1988%% CHECK
1989{\bf \large DECRIRE l'utilisation des nouvelles classes ParallelExecutor ... }
1990
[2790]1991\subsection{Dynamic linker and C++ compiler classes}
[2278]1992\index{PDynLinkMgr}
1993The class {\bf PDynLinkMgr} can be used for managing shared libraries
1994at run time. The example below shows the run time linking of a function:\\
1995{\tt extern "C" { void myfunc(); } } \\
1996\begin{verbatim}
1997#include "pdlmgr.h"
1998// ...
1999string soname = "mylib.so";
2000string funcname = "myfunc";
2001PDynLinkMgr dyl(soname);
2002DlFunction f = dyl.GetFunction(funcname);
2003if (f != NULL) {
2004// Calling the function
2005 f();
2006}
2007\end{verbatim}
2008
2009\index{CxxCompilerLinker}
[2790]2010The {\bf CxxCompilerLinker} class provides the services to compile C++ code and building
[2278]2011shared libraries, using the same compiler and options which have
2012been used to create the SOPHYA shared library.
2013The sample program below illustrates using this class to build
2014the shared library (myfunc.so) from the source file myfunc.cc :
2015\begin{verbatim}
2016#include "cxxcmplnk.h"
2017// ...
2018string flnm = "myfunc.cc";
2019string oname, soname;
2020int rc;
2021CxxCompilerLinker cxx;
2022// The Compile method provides a default object file name
2023rc = cxx.Compile(flnm, oname);
2024if (rc != 0 ) { // Error when compiling ... }
2025// The BuildSO method provides a default shared object file name
2026rc = cxx.BuildSO(oname, soname);
2027if (rc != 0 ) { // Error when creating shared object ... }
2028\end{verbatim}
2029
[2790]2030\subsection{Command interpreter}
[3419]2031\index{Commander}
2032\index{Expression evaluation}
[2790]2033The class {\bf Commander} can be used in interactive programs to provide
2034c-shell like command interpreter and scripting capabilties.
2035Arithmetic expression evaluation is implemented through the {\bf CExpressionEvaluator}
[3419]2036and {\bf RPNExpressionEvaluator} classes. The latter can be used to perform evaluation
2037in reverse polish notation (old HP calculators),
2038while the former uses the usual algebraic (c-language like) expressions.
[3015]2039The command language provides variable manipulation through the usual
2040{\tt \$varname} vector variable and arithmetic expression extensions, as well
2041as the control and test blocs.
2042\begin{verbatim}
2043#include "commander.h"
2044...
2045Commander cmd;
2046char* ss[3] = {"foreach f ( AA bbb CCCC ddddd )", "echo $f" , "end"};
2047for(int k=0; k<3; k++) {
2048 string line = ss[k];
2049 cmd.Interpret(line);
2050}
2051\end{verbatim}
[2790]2052
[1435]2053\newpage
2054\section{Module SkyMap}
2055\begin{figure}[hbt]
2056\dclsbb{AnyDataObj}{PixelMap}
2057\dclsccc{PixelMap}{Sphericalmap}{SphereHEALPix}
2058\dclsc{SphereThetaPhi}
[3006]2059\dclsc{SphereECP}
[1435]2060\dclsb{LocalMap}
[3006]2061\caption{partial class diagram for spherical map classes in Sophya}
[1435]2062\end{figure}
2063The {\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.
[3419]2064\subsection{3D geometry}
2065Some of the classes in this module simplify the angle manipulation, or the 3D geometry
2066and rotation calculations, such as the {\bf Vector3d} and {\bf UnitVector} classes.
2067\index{Vector3d}
2068The classes {\bf Vector3d} and {\bf UnitVector} are useful for angle conversions.
2069\index{Angle}
2070{\bf LongLat} class and {\bf Angle} class (defined in file vector3d.h) can be used for
2071angle conversions :
2072\begin{verbatim}
2073 // Example to convert 0.035 radians to arcsec
2074 double vr = 0.035;
2075 cout << "Angle rad= " << vr << " ->arcsec= " << Angle(vr).ToArcSec() << endl;
2076 // Example to convert 2.3 arcmin to radian - we use the conversion operator
2077 double vam = 2.3;
2078 cout << "Angle arcmin= " << vam << " ->rad= "
2079 << (double)Angle(vam, Angle::ArcMin) << endl;
2080\end{verbatim}
2081%%%
[1435]2082\subsection {Spherical maps}
[3438]2083SkyMap module provides three classes for representing data with pixels distributed over complete ($4 \pi$ steradians) spheres. These classes implements the common interface defined
2084in the base class \tcls{SphericalMap} with three different algorithms or
[3006]2085pixelization scheme.
[3438]2086The spherical maps can be instanciated for the followind data types: \\
2087\hspace*{5mm} int\_4 , r\_4 (float) , r\_8 (double) , complex$<$r\_4$>$ , complex$<$r\_8$>$. \\
2088The SphereHEALPix can in addition be instanciated for T=uint\_2.
[1435]2089
[3438]2090\begin{enumerate}
2091\item \index{\tcls{SphereHEALPix}}
2092{\bf \tcls{SphereHEALPix}} implements the HEALPix
2093({\bf H}ierarchical {\bf E}qual {\bf A}rea iso{\bf L}atitude {\bf Pix}elization) scheme,
2094developped originaly by K. Gorski \& E. Hivon. Refer to
2095\href{http://healpix.jpl.nasa.gov/}{HEALPix home page} for
2096detailed information about this pixelisation scheme and related software
2097\footnote{HEALPix home page: http://healpix.jpl.nasa.gov/ }.
2098FITS read/write for SphereHEALPix objects is handled by the \tcls{FITS\_SphereHEALPix}
2099class in module FitsIOServer.
2100\item \index{\tcls{SphereThetaPhi}}
2101{\bf \tcls{SphereThetaPhi}} represents spheres pixelized following an algorithm
2102developed at LAL-ORSAY, for SOPHYA.
2103The sphere is divided into a number of rings or slices
2104along the parallels, corresponding to different values of the angle $\theta$.
2105Each slice is then divided into a number of pixels, with an aspect ratio close
2106to one (square pixels). Pixels are exactly iso-latitude and very uniform in surface,
2107over the sphere.
2108
2109\item \index{\tcls{SphereECP}}
2110
2111The {\bf \tcls{SphereECP}} class correspond to the cylindrical projection.
2112Like SphereThetaPhi class, the sphere is divided into a number of rings
2113or slices, and each ring is divided into a constant number of pixels
2114along the $\varphi$ direction. Although the \tcls{SphereECP} does not have
2115equal area pixels when used for complete spheres, it can be used for
2116representing partial or full spherical maps.
2117\end{enumerate}
2118
2119The example below shows creating and filling of a
2120SphereHEALPix with nside = 8
2121(The sphere will have $12 \times 8 \times 8= 768$ pixels) :
2122
[1435]2123\begin{verbatim}
2124#include "spherehealpix.h"
2125// ...
2126SphereHEALPix<double> sph(8);
2127for (int k=0; k< sph.NbPixels(); k++) sph(k) = (double)(10*k);
2128\end{verbatim}
2129
[3438]2130Pixels at an angular posistion can be directly accessed through the operator \\
2131\hspace*{15mm} T \tcls{SphericalMap}::operator()($\theta, \varphi$) :
2132\begin{verbatim}
2133#include "vector3d.h"
2134#include "spherethetaphi.h"
2135...
2136// Create a sphere with 40 arcmin resolution
2137int M = SphereThetaPhi<r_4>::ResolToSizeIndex(
2138 Angle(40., Angle::ArcMin).ToRadian() );
2139SphereThetaPhi<r_4> sphtp(M);
2140double tet, phi;
2141for (int k=0; k< sphtp.NbPixels(); k++) {
2142 sphtp.PixThetaPhi(k, tet, phi);
2143 sphtp(k) = cos(5.*tet)*sin(7.*phi);
2144}
2145cout << sphtp;
2146// To save sphtp to file sphtp (if executed through runcxx)
2147KeepObj(sphtp);
2148\end{verbatim}
2149
[1435]2150\index{\tcls{SphereThetaPhi}}
2151
2152\subsection {Local maps}
2153\index{\tcls{LocalMap}}
2154A 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).
2155
2156Internally, 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(...))
2157
2158The 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).
2159\begin{verbatim}
2160#include "localmap.h"
2161//..............
2162 LocalMap<r_4> locmap(4,5);
2163 for (int k=0; k<locmap.NbPixels();k++) locmap(k)=10.*k;
2164 locmap.SetOrigin();
2165 locmap.SetSize(30.,30.);
2166\end{verbatim}
2167
2168\subsection{Writing, viewing \dots }
2169
2170All these objects have been design to be written to or read from a persistant file.
2171The following example shows how to write the previously created objects
2172into such a file~:
2173\begin{verbatim}
2174//-- Writing
2175
2176#include "fiospherehealpix.h"
2177//................
2178
2179char *fileout = "myfile.ppf";
2180POutPersist outppf(fileout);
2181FIO_SphereHEALPix<r_8> outsph(sph);
2182outsph.Write(outppf);
2183FIO_LocalMap<r_8> outloc(locmap);
2184outloc.Write(outppf);
2185// It is also possible to use the << operator
2186POutPersist os("sph.ppf");
2187os << outsph;
2188os << outloc;
2189\end{verbatim}
2190
2191Sophya graphical tools (spiapp) can automatically display and operate
2192all these objects.
2193
2194\newpage
[3015]2195\section{Samba and SkyT}
2196\subsection{Samba}
[1414]2197\index{Spherical Harmonics}
2198\index{SphericalTransformServer}
[1435]2199The 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...
[1387]2200\begin{verbatim}
2201#include "skymap.h"
2202#include "samba.h"
2203....................
2204
2205// Generate input spectra a + b* l + c * gaussienne(l, 50, 20)
2206int lmax = 92;
2207Vector clin(lmax);
2208for(int l=0; l<lmax; l++) {
2209 double xx = (l-50.)/10.;
2210 clin(l) = 1.e-2 -1.e-4*l + 0.1*exp(-xx*xx);
2211}
2212
2213// Compute map from spectra
2214SphericalTransformServer<r_8> ylmserver;
2215int m = 128; // HealPix pixelisation parameter
2216SphereHEALPix<r_8> map(m);
2217ylmserver.GenerateFromCl(map, m, clin, 0.);
2218// Compute power spectrum from map
2219Vector clout = ylmserver.DecomposeToCl(map, lmax, 0.);
2220\end{verbatim}
2221
[3015]2222\subsection{Module SkyT}
[3037]2223\index{RadSpectra} \index{SpectralResponse}
[1435]2224The SkyT module is composed of two types of classes:
2225\begin{itemize}
2226\item{} one which corresponds to an emission spectrum of
2227radiation, which is called RadSpectra
2228\item{} one which corresponds to the spectral response
2229of a given detector (i.e. corresponding to a detector
2230filter in a given frequency domain), which is called
2231SpectralResponse.
2232\end{itemize}
2233\begin{figure}[hbt]
2234\dclsbb{RadSpectra}{RadSpectraVec}
2235\dclsb{BlackBody}
2236\dclsccc{AnyDataObj}{SpectralResponse}{SpecRespVec}
2237\dclsc{GaussianFilter}
2238\caption{partial class for SkyT module}
2239\end{figure}
[1299]2240
[1435]2241\begin{verbatim}
2242#include "skyt.h"
2243// ....
2244// Compute the flux from a blackbody at 2.73 K through a square filter
2245BlackBody myBB(2.73);
2246// We define a square filter from 100 - 200 GHz
2247SquareFilter mySF(100,200);
2248// Compute the filtered integrated flux :
2249double flux = myBB.filteredIntegratedFlux(mySF);
2250\end{verbatim}
2251
2252A more detailed description of SkyT module can be found in:
2253{\it The SkyMixer (SkyT and PMixer modules) - Sophya Note No 2. }
2254available also from Sophya Web site.
2255
2256\newpage
[1387]2257\section{Module FitsIOServer}
[3037]2258This module provides classes for handling file input-output in FITS
2259\footnote{http://heasarc.gsfc.nasa.gov/docs/software/fitsio/fitsio.html}
2260format using the cfitsio library. Its
[3015]2261design is similar to the SOPHYA persistence (see Module BaseTools).
2262Delegate classes or handlers perform the actual read/write from/to fits files.
[3037]2263\par
[3015]2264Compared to the SOPHYA native persistence (PPF format),
2265FITS format has the advantage of being used extensively, and handled
2266by a many different software tools. It is a de facto standard in
2267astronomy and astrophysics.
2268However, FITS lacks some of the features present in SOPHYA PPF, and although
2269many SOPHYA objects can be saved in FITS files, FITS persistence has
2270some limitations. For example, FITS does not currently handle complex arrays.
[3037]2271\subsection{FITS streams}
2272\index{FITS} \index{FitsInOutFile}
2273%%
[3015]2274The class {\bf FitsInOutFile} can be seen as a wrapper class for the cfitsio library functions.
2275This class has been introduced in 2005 (V=1.9), when the module has been
2276extensively changed. In order to keep backward compatibility, the old fits wrapper
[3037]2277classes ({\bf FitsFile, FitsInFile, FitsOutFile}) has been changed to inherit from
[3015]2278 {\bf FitsInOutFile}. The use of class FitsFile and specific services of these old classes
2279 should be avoided, but FitsInFile, FitsOutFile can be safely considered a specialisation
2280 of FitsInOutFile for read/input and write/output operations respectively.
[3037]2281 Most c-fitsio errors are converted to an exception: {\bf FitsIOException}.
2282 \par
2283 File names are passed to cfitsio library. It is thus possible to use cfitsio file name conventions,
2284 such as {\bf ! } as the first character, for overwriting existing files (when creating files).
[3015]2285 The diagram below shows the class hierarchy for cfitsio wrapper classes.
[1387]2286\begin{figure}[hbt]
[3015]2287\dclsa{FitsInOutFile}
2288\dclscc{FitsFile}{FitsInFile}
2289\dclscc{FitsFile}{FitsOutFile}
[1387]2290\end{figure}
[3015]2291%%%%
[3048]2292\subsection{FITS handlers and I/O operators}
[3037]2293\index{FitsManager}
[3015]2294Handlers classes inheriting from {\bf FitsHandlerInterface} perform write/read operations
2295for AnyDataObj objects to/from FitsInOutFile streams. The {\bf FitsManager} class provides
2296top level services for object read/write in FITS files.
[3037]2297\par In most cases,
2298\hspace{5mm} {\tt FitsInOutFile\& $<<$ } \, and \, {\tt FitsInOutFile\& $>>$ } \hspace{5mm}
2299operators can be used to write and read objects.
[3048]2300When reading objects from a fits file using the {\tt FitsInOutFile\& $>>$ } operator,
2301the fits file is positioned on the next HDU, after reading. Also, if the {\bf FitsInOutFile}
2302object is positioned on a first empty HDU (without data, naxis=0), reading in objects
2303corresponding to a binary or ascii table using the operator $>>$ will skip automatically
2304the empty HDU and position the fits file on the second HDU, before trying to read in
2305the object.
[3037]2306\par
2307The two main types of fits data structures, images and tables
[3015]2308{\tt (IMAGE\_HDU , BINARY\_TBL , ASCII\_TBL)} are handled by the generic handlers: \\
[3037]2309{\bf \tcls{FitsArrayHandler}} and {\bf FitsHandler$<$BaseDataTable$>$}.
2310\par
[3015]2311A number of more specific handlers are also available, in particular for NTuple,
[3034]2312\tcls{SphereHealPix} and \tcls{SphereThetaPhi}. \\[2mm]
[3048]2313{\bf Warning:} Some handlers were written with the old FitsIOServer classes.
2314They inherit from the intermediate class {\bf FitsIOHandler} and
2315have been adapted to the new scheme. \\[2mm]
[3015]2316%%%
[3037]2317The examples below illustrates the usage of FitsIOServer classes. They can be compiled
2318and executed using runcxx, without the {\tt include} lines: \\[1mm]
2319\hspace*{5mm} {\tt csh> runcxx -import SkyMap -import FitsIOServer -inc fiosinit.h }
2320%%%
[3015]2321\begin{enumerate}
2322\item Saving an array and a HealPix map to a Fits file
[1387]2323\begin{verbatim}
[3026]2324#include "fitsioserver.h"
[3034]2325#include "fiosinit.h"
[3015]2326// ....
2327{
[3034]2328// Make sure FitsIOServer module is initialised :
[3015]2329FitsIOServerInit();
2330// Create and open a fits file named myfile.fits
2331FitsInOutFile fos("myfile.fits", FitsInOutFile ::Fits_Create);
2332// Create and save a 15x11 matrix of integers
2333TMatrix<int_4> mxi(15, 11);
2334mxi = RegularSequence(10.,10.);
2335fos << mxi;
2336// Save a HEALPix spherical map using FitsManager services
2337SphereHEALPix<r_8> sph(16);
2338sph = 48.3;
2339FitsManager::Write(fos, sph);
[3037]2340// --- The << operator could have been used instead : fos << sph;
[3015]2341}
2342\end{verbatim}
[3034]2343%%%%
2344%%%%
2345\item Reading objects and the header from the previously created fits file:
[3015]2346\begin{verbatim}
[3034]2347{
2348FitsIOServerInit(); // Initialisation
2349// ---- Open the fits file named myfile.fits
2350FitsInFile fis("myfile.fits");
2351//---- print file information on cout
2352cout << fis << endl;
2353//--- Read in the array
2354TArray<int_4> arr;
2355fis >> arr;
2356arr.Show();
2357//--- Position on second HDU
2358fis.MoveAbsToHDU(2);
2359//--- read and display header information
2360DVList hdu2;
2361fis.GetHeaderRecords(hdu2, true, true);
2362cout << hdu2;
2363//--- read in the HEALPix map
2364SphereHEALPix<r_8> sph;
2365FitsManager::Read(fis, sph);
[3037]2366// --- The >> operator could have been used instead : fis >> sph;
[3034]2367sph.Show();
2368}
[1387]2369\end{verbatim}
[3034]2370%%%%%%%
2371%%%
2372\item DataTable objects can be read from and written to FITS files as ASCII or
2373binary tables. The example belo show reading the DataTable created in the example
[3037]2374in section \ref{datatables} from a PPF file and saving it to a fits file.
[1435]2375\begin{verbatim}
[3037]2376#include "swfitsdtable.h"
2377// ....
[3034]2378{
[3037]2379FitsIOServerInit(); // FitsIOServer Initialisation
2380//--- Reading in DataTable object from PPF file
2381PInPersist pin("dtable.ppf");
2382DataTable dt;
2383pin >> dt;
2384dt.Show();
2385//--- Saving table to FITS
2386FitsInOutFile fos("!dtable.fits", FitsInOutFile ::Fits_Create);
2387fos << dt;
[3034]2388}
[1435]2389\end{verbatim}
[3034]2390%%%%
2391\end{enumerate}
[3037]2392%%%
[3015]2393A partial class diagram of FITS persistence handling classes is shown below. The
2394class {\tt FitsIOhandler} conforms to the old FitsIOServer module design and
2395should not be used anymore.
[1648]2396\begin{figure}[hbt]
[3015]2397\dclsbb{FitsHandlerInterface}{FitsArrayHandler$<$T$>$}
2398\dclsb{\tcls{FitsHandler}}
2399\dclscc{FitsIOhandler}{FITS\_NTuple}
2400\dclsc{FITS\_SphereHEALPix}
[1648]2401% \dclsb{FITS\_LocalMap}
2402\end{figure}
[1387]2403
[3034]2404\subsection{SwFitsDataTable and other classes}
[3048]2405\label{SwFitsDataTable}
[3037]2406\index{SwFitsDataTable}
2407The {\bf SwFitsDataTable} class implements the BaseDataTable interface
2408using a FITS file as swap space. Compared to SwPPFDataTable, they can be
2409used in R/W mode (reading from the table, when it is being created / filled).
2410They can be used in a way similar to DataTable and SwPPFDataTable.
2411When creating the table, a {\tt FitsInOutFile } stream, opened for writing has
2412to be passed to the creator. No further operation is needed.
2413\begin{verbatim}
2414// ....
2415FitsInOutFile so("!myswtable.fits", FitsInOutFile::Fits_Create);
2416SwFitsDataTable dt(so, 16);
2417// define table columns
2418dt.AddIntegerColumn("X0_i");
2419dt.AddFloatColumn("X1_f");
2420// ... Fill the table
2421r_8 x[5];
2422for(int i=0; i<63; i++) {
2423 x[0] = (i%9)-4.; x[1] = (i/9)-3.;
2424 dt.AddLine(x);
2425}
2426\end{verbatim}
2427The class {\bf FitsBTNtuIntf } provide an alternative tool to read FITS tables.
2428{\bf FitsABTColRd} , {\bf FitsABTWriter } and {\bf FitsImg2DWriter } can also
2429be used to manipulate FITS files.
2430\par
2431The {\bf scanfits} program can be used to check FITS files and analyse their
2432content (See \ref{scanfits}).
[3034]2433
[3037]2434%%%%
[1340]2435\newpage
[1435]2436\section{LinAlg and IFFTW modules}
2437An interface to use LAPACK library (available from {\tt http://www.netlib.org})
2438is implemented by the {\bf LapackServer} class, in module LinAlg.
2439\index{LapackServer}.
2440The sample code below shows how to use SVD (Singular Value Decomposition)
2441through LapackServer:
2442\begin{verbatim}
2443#include "intflapack.h"
2444// ...
2445// Use FortranMemoryMapping as default
2446BaseArray::SetDefaultMemoryMapping(BaseArray::FortranMemoryMapping);
2447// Create an fill the arrays A and its copy AA
2448int n = 20;
2449Matrix A(n , n), AA;
2450A = RandomSequence(RandomSequence::Gaussian, 0., 4.);
2451AA = A; // AA is a copy of A
2452// Compute the SVD decomposition
2453Vector S; // Vector of singular values
2454Matrix U, VT;
2455LapackServer<r_8> lpks;
2456lpks.SVD(AA, S, U, VT);
2457// We create a diagonal matrix using S
2458Matrix SM(n, n);
2459for(int k=0; k<n; k++) SM(k,k) = S(k);
2460// Check the result : A = U*SM*VT
2461Matrix diff = U*(SM*VT) - A;
2462double min, max;
2463diff.MinMax(min, max);
2464cout << " Min/Max difference Matrix (?=0) , Min= " << min
2465 << " Max= " << max << endl;
2466\end{verbatim}
2467
2468\index{FFTWServer}
2469The {\bf FFTWServer} class (in module FFTW) implements FFTServerInterface class
2470methods, for one dimensional and multi-dimensional Fourier
[3419]2471transforms using the FFTW package (available from {\tt http://www.fftw.org}).
2472Depending on the configuration options during library build, only
2473transforms on double precision data might be available.
[1435]2474
2475\newpage
[978]2476\section{Building and installing Sophya}
[3045]2477\subsection{Supported platforms}
[1436]2478Presently, the Sophya library has been tested with the following
[978]2479compiler/platform pairs:
2480
2481\begin{center}
[2790]2482\begin{tabular}{|l|l|}
2483\hline
2484OS & compiler \\
2485\hline
[3415]2486Linux (32 bits) & g++ (3.x \, 4.0) \\
2487Linux (SCL, 32) & icc - Intel compiler (9.0) \\
2488Linux (SCL, 64) & g++ 3.3 \, 3.4 \\
[3092]2489MacOSX/Darwin (PowerPC) 10.3 \, 10.4 & g++ (3.3 \, 4.0)\\
2490MacOSX/Darwin (Intel) 10.4 & g++ (4.0)\\
[3045]2491HP/Compaq/DEC Tru64 ( OSF1) & cxx (6.1 6.3) \\
[1436]2492SGI IRIX64 & CC (7.3) \\
[3415]2493IBM AIX (5.3) & xlC (8.0) \\
[2790]2494\hline
[978]2495\end{tabular}
2496\end{center}
2497
[3045]2498\subsection{Library and makefile structure}
2499%
[978]2500The object files from a given Sophya module are grouped in an archive library
2501with the module's name ({\tt libmodulename.a}). All Sophya modules
2502 are grouped in a single shared library ({\tt libsophya.so}), while the
2503modules with reference to external libraries are grouped in
2504({\tt libextsophya.so}). The {\bf PI} and {\bf PIext} modules are
2505grouped in ({\tt libPI.so}).
[3015]2506Alternatively, it is possible to group all modules in a single shared
2507library {\tt libAsophyaextPI.so}.
[3037]2508\par
2509Each library module has a {\tt Makefile} which compiles the source files
2510and build the correspond static (archive) library using the compilation
[3045]2511rules and flags defined in \\
2512\hspace*{5mm} {\tt \$SOPHYABASE/include/sophyamake.inc}. \\
[3037]2513Each program module has a {\tt Makefile} which compiles and link the
2514corresponding programs using the compilation rules and libraries
2515defined in {\$SOPHYABASE/include/sophyamake.inc}.
2516The top level Makefile in BuildMgr/ compiles each library modules
2517and builds shared libraries.
[3045]2518\par
2519Some of the modules in the Sophya package uses external libraries. The
2520{\bf FitsIOServer} is an example of such a module, where the {\tt libcfitsio.a}
2521is used. The list of all Sophya modules using external libraries is
2522presented in section \ref{sopmodules}.
2523The external libraries should be installed before the configure step
2524(see below) and the compilation of the corresponding Sophya modules.
[3037]2525\par
2526The series of Makefiles use the link to {\tt sophyamake.inc} in BuildMgr.
2527There are also the {\tt smakefile} series which uses the explicit path, using
2528{\tt \$SOPHYABASE} environment variable.
[978]2529
[3045]2530\subsection{Build instructions}
[3015]2531\label{build}
2532The build procedure has two main steps:
2533\begin{enumerate}
2534\item The configure step (BuildMgr/configure) setup the directory structure and
2535the necessary configuration file. Refer to section \ref{directories} for
2536the description of SOPHYA directory tree and files.
2537\item The make step compiles the different sources files, create the library and optionaly
[2790]2538builds all or some of the associated executables.
[3015]2539\end{enumerate}
[2790]2540
2541{\tt BuildMgr/configure } is a c-shell script with a number of arguments:
2542\begin{verbatim}
2543csh> ./configure -h
2544configure [-sbase SOPHYABASE] [-scxx SOPHYACXX] [-incln]
[3415]2545 [-minc mymake.inc] [-compopt 'cc/cxxOptions']
2546 [-arch64] [-sasz64] [-nofpic] [-nothsafe] [-boundcheck] [-sodebug]
2547 [-extp dir1 -extp dir2 ...] [-extip dir1 -extip dir2 ... ] [-extlp dir1 -extlp dir2 ... ]
2548 [-noextlib] [-noext fits] [-noext fftw] [-noext lapack] [-noext astro]
2549 [-noPI] [-slballinone]
2550 [-alsofftwfloat] [-usefftw2] [-uselapack2]
2551 (See SOPHYA manual/web pages for a detailed description of configure options)
[2790]2552\end{verbatim}
2553\begin{itemize}
2554\item[] -sbase : define SOPHYA installation base directory. \$SOPHYABASE is used
2555if not specified.
2556\item[] -scxx : selects the C++ compiler. \$SOPHYACXX s used
2557if not specified.
2558\item[] -incln : creates symbolic link for include files, instead of copying them.
2559\item[] -minc : give an explicit name for the file used to generate
[3415]2560\$SOPHYABASE/include/sophyamake.inc. If {\tt -minc} is not specified, one of
2561the files in BuildMgr/ directory is selected, based on the system name and the
2562compiler {\tt Linux\_g++\_make.inc , OSF1\_cxx\_make.inc , AIX\_xlC\_make.inc \ldots}
[2790]2563\item[] -extp : Adds the specied path to the search path of the external libraries
2564include files and archive library.
2565\item[] -extip : Adds the specied path to the search path of the external libraries
2566include files.
2567\item[] -extp : Adds the specied path to the search path of the external libraries
2568archive (libxxx.a).
2569\item[] -noextlib : Disable compiling of modules referencing external libraries.
2570\item[] -noext : Disable compiling of the specified module (with reference to external
[3415]2571library : {\tt -noext fits , -noext fftw \ldots }
2572\item[] -usefftw2: Use FFTW V2 instead of the default FFTW V3 - A preprocessor
2573flag will be defined in sspvflags.h
2574\item[] -uselapack2: Lapack V2 is being used (defaulr V3) - A preprocessor
2575flag will be defined in sspvflags.h
2576\item[] -alsofftwfloat : compile single precision (float) version of the Fourier
2577transform methods (module IFFTW, class FFTWServer). A preprocessor
2578flag will be defined in sspvflags.h and float version of the FFTW library
2579(libfftw3f.a) will be linked with SOPHYA, in addition to the default double
2580precision library (libfftw3.a).
2581\item[] -noPI : has currently no effect
2582\item[] -slballinone: A single shared library for all SOPHYA, PI and external library interface
[3015]2583modules will be build. A compilation flag
[3415]2584will be defined in sspvflags.h . \\ See also target {\tt slballinone} below.
[2790]2585\end{itemize}
2586
[3415]2587{\large \bf configure steps } \\[1mm]
2588The configure script performs the following actions :
2589\begin{enumerate}
2590\item Creating directory tree under {\tt \$SOPHYABASE }
2591\item Cpoying include files (or creating symbolic) in {\tt \$SOPHYABASE/include/ }
2592\item Search for external libraries include files and create the necessary links
2593in {\tt \$SOPHYABASE/include}
2594\item Search for external libraries (-lfits \ldots) and add the corresponding
2595directories to the library search path, in {\tt sophyamake.inc}
2596\item Creates the file { \tt \$SOPHYABASE/include/sophyamake.inc }
2597\item Creates the file {\tt machdefs.h} from { BaseTools/machdefs\_mkmf.h } and
2598{\tt sspvflags.h }
2599\item Creates the object list files for shared library creation
2600\end{enumerate}
2601
2602{\large \bf Example } \\[1mm]
2603
[978]2604In the example below, we assume that we want to install Sophya from a
2605released (tagged) version in the source directory {\tt \$SRC} in the
[2790]2606{\tt /usr/local/Sophya} directory, using {\tt g++}. We assume that
2607the external libraries can be found in {\tt /usr/local/ExtLibs/}.
[3180]2608We disable the compilation of the XAstroPack package.
[2790]2609
[978]2610\vspace*{3mm}
2611\begin{verbatim}
[2790]2612# Create the top level directory
[978]2613csh> mkdir /usr/local/Sophya/
[2790]2614csh> cd $SRC/BuildMgr
2615# Step 1.a : Run the configuration script
2616csh> ./configure -sbase /usr/local/Sophya -scxx g++ -extp /usr/local/ExtLibs/ \
[3180]2617-noext astro
[3015]2618# Step 1.b : Check the generated file $SOPHYABASE/include/sophyamake.inc
2619csh> ls -lt *.inc
2620csh> more sophyamake.inc
2621\end{verbatim}
2622If necessary, edit the generated file {\tt sophyamake.inc } in order to modify
2623compilation flags, library list. The file is rather short and self documented.
2624\begin{verbatim}
[2790]2625# Step 2.a: Compile the modules without external library reference
[978]2626csh> make libs
[2790]2627# Step 2.b: Compile the modules WITH external library reference (optional)
[978]2628csh> make extlibs
[2790]2629# Step 2.c: Build libsophya.so
[978]2630csh> make slb
[2790]2631# Step 2.d: Build libextsophya.so (optional)
[978]2632csh> make slbext
[2790]2633# Step 2.e: Compile the PI and PIext modules (optional)
[978]2634csh> make PI
[2790]2635# Step 2.f: Build the corresponding shared library libPI.so (optional)
[978]2636csh> make slbpi
2637\end{verbatim}
2638
2639To compile all modules and build the shared libraries, it is possible
[3015]2640to perform the steps 2.a to 2.f using the targets {\tt all} and {\tt slball}
2641defined in the Makefile
[978]2642\begin{verbatim}
[2790]2643# Step 2.a ... 2.f
[3015]2644csh> make all slball
[978]2645\end{verbatim}
2646
[3015]2647It is also possible to group all modules in a single shared library using
2648the target {\tt slballinone}.
2649\begin{verbatim}
2650# Step 2.a ... 2.f
2651csh> make all slballinone
2652\end{verbatim}
2653
[1435]2654At this step, all libraries should have been made. Programs using
[978]2655Sophya libraries can now be built:
2656\begin{verbatim}
[3015]2657# To compile some of the test programs
2658csh> make basetests
2659# To compile runcxx , scanppf , scanfits
2660csh> make prgutil
[978]2661# To build (s)piapp (libPI.so is needed)
[3015]2662csh> make piapp
[978]2663\end{verbatim}
2664
[3037]2665If no further modification or update of source files is foreseen, it is possible
2666to remove all .o files:
2667\begin{verbatim}
2668# To clean $SOPHYABASE/obj directory :
2669csh> make cleanobj
2670\end{verbatim}
2671
2672
2673\subsection{Notes}
[988]2674\begin{itemize}
[3037]2675\item[{\bf Makefile}] List of top level Makefile build targets
2676\begin{verbatim}
2677> libs extlibs PI = all
2678> slb slbext slbpi = slball (OR = slballinone)
2679> clean cleanobj
2680> tests prgutil prgmap progpi = prgall
2681> basetests piapp (ou progpi) pmixer
2682\end{verbatim}
2683\item[{\bf MacOS X}] A high performance mathematic and signal processing
2684library, including LAPACK and BLAS is packaged in Darwin/MacOS X (10.3, 10.4) : \\
2685\hspace*{5mm} {\bf -framework Accelerate}
2686\item[{\bf Tru64/OSF}] An optimised math library with LAPACK and BLAS might
2687optionaly be installed {\bf (-lcxlm) }. On our system, this libray contained Lapack V2.
2688So we used the LAPACK, as compiled from the public sources, and linked with
2689the Tru64 native BLAS.
2690\item[{\bf IRIX64}] We used the math library with LAPACK V2 and BLAS
2691from SGI : {\bf -lcomplib.sgimath}
[3015]2692\item[{\bf AIX}] There seem to be a problem on AIX when several shared
2693libraries are used. We have been able to run SOPHYA programs either
2694using static libraries, or a single shared library (libAsophyaextPI.so)
2695if extlibs and PI are needed, in addition to stand alone SOPHYA modules.
[3037]2696It has not been possible to link SOPHYA with fortran libraries
2697\item[{\bf Mgr}] This module contains makefiles and build scripts
2698that were used in SOPHYA up to version 1.7 (2004) : OBSOLETE.
[3015]2699\end{itemize}
[887]2700
[3015]2701\subsection{Files and scripts in BuildMgr/ }
2702\begin{itemize}
2703\item[] {\bf Makefile:} Top level Makefile for building SOPHYA.
2704{\tt smakefile} is similar to Makefile, except that it uses
2705the smakefiles in each module.
2706\item[] {\bf mkmflib:} c-shell script for creation of library module
[3045]2707Makefile / smakefile. \\
2708\hspace*{5mm} {\tt ./mkmflib -sbase /tmp/sbase SUtils }
[3015]2709\item[] {\b mkmfprog:}
[3045]2710c-shell script for creation of programs module Makefile / smakefile \\
2711\hspace*{5mm} {\tt ./mkmfprog -sbase /tmp/sbase ProgPI }
[3015]2712\item[] {\bf domkmf:} c-shell script - calls mkmflib for all modules \\
[3045]2713\hspace*{5mm} {\tt ./domkmf -sbase /tmp/sbase}
2714\item[] {\bf xxx\_make.inc:} Configuration files for different compilers and OS
2715{\tt ( Linux\_g++\_make.inc , OSF1\_cxx\_make.inc \ldots )}.
[3015]2716These files are used to generate {\tt sophyamake.inc}
[988]2717\end{itemize}
[3015]2718
2719
2720
[988]2721\newpage
[1299]2722\appendix
[1362]2723\section{SOPHYA Exceptions}
2724\index{Exception classes} \index{PThrowable} \index{PError} \index{PException}
2725SOPHYA library defines a set of exceptions which are used
[1435]2726for signalling error conditions. The figure below shows a partial
[1362]2727class diagram for exception classes in SOPHYA.
2728\begin{figure}[hbt]
2729\dclsbb{PThrowable}{PError}
2730\dclscc{PError}{AllocationError}
2731\dclscc{PError}{NullPtrError}
2732\dclscc{PError}{ForbiddenError}
2733\dclscc{PError}{AssertionFailedError}
2734\dclsbb{PThrowable}{PException}
2735\dclscc{PException}{IOExc}
2736\dclscc{PException}{SzMismatchError}
2737\dclscc{PException}{RangeCheckError}
2738\dclscc{PException}{ParmError}
2739\dclscc{PException}{TypeMismatchExc}
2740\dclscc{PException}{MathExc}
2741\dclscc{PException}{CaughtSignalExc}
2742\caption{partial class diagram for exception handling in Sophya}
2743\end{figure}
2744
[1299]2745For simple programs, it is a good practice to handle
[988]2746the exceptions at least at high level, in the {\tt main()} function.
2747The example below shows the exception handling and the usage
2748of Sophya persistence.
[1299]2749
[988]2750\input{ex1.inc}
[887]2751
[1362]2752\newpage
2753\addcontentsline{toc}{section}{Index}
2754\printindex
[1299]2755\end{document}
[1362]2756
Note: See TracBrowser for help on using the repository browser.