learn grb data analysis in 3 days - readthedocs.org

110
Learn GRB Data Analysis in 3 Days Release 0.9.9 (Y.Wang, M.Peresano, R.Moradi, S.Shakeri, Y.Aimuratov) April 09, 2016

Upload: others

Post on 15-Mar-2022

1 views

Category:

Documents


0 download

TRANSCRIPT

Learn GRB Data Analysis in 3 DaysRelease 0.9.9

(Y.Wang, M.Peresano, R.Moradi, S.Shakeri, Y.Aimuratov)

April 09, 2016

Contents

1 10 minutes tutorial 3

2 Software Installation 52.1 Swift - HEASoft . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.2 Fermi - Science Tools & rmfit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72.3 Local CALDB Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

3 Swift-BAT Data Analysis 9

4 Swift -XRT Data Analysis 114.1 Two Modes: Windows Timing & Photon Counting . . . . . . . . . . . . . . . . . . . . . . . . . . . 114.2 What kind of files do we need? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114.3 How to download data? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134.4 How to generate spectrum and light curve ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

5 Fermi-GBM Data Analysis 17

6 Fermi-LAT Data Analysis 19

7 Spectrum Fitting 21

8 Light-curve Fitting 23

9 Advanced Learning 25

10 Helpful Links 27

11 Scripts 2911.1 Perl Subroutines from HEASoft . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2911.2 findRMF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10111.3 dlXRT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10211.4 getpar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105

i

ii

Learn GRB Data Analysis in 3 Days, Release 0.9.9

Conservatively speaking, Gamma-ray burst (GRB) data analysis can be learned in 3 days, even it can be finished within3 hours if you have experience in programming or data analysis, just follow this guide.

This guide is practical, its purpose is to gain enough technique to start your work, also it provides some links fordeepening your knowledge.

Hope it acts as the entry of your GRB data world.

Contents 1

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2 Contents

CHAPTER 1

10 minutes tutorial

3

Learn GRB Data Analysis in 3 Days, Release 0.9.9

4 Chapter 1. 10 minutes tutorial

CHAPTER 2

Software Installation

• Swift - HEASoft• Fermi - Science Tools & rmfit• Local CALDB Setup

2.1 Swift - HEASoft

HEASoft developed by NASA is the major software for the Swift data reeducation, it provides several tools includingxselect for data selection and xspec for spectrum fitting.

This example is for MacOS.

• Install XQuartz for X window environment from xquartz.org.

• Install Xcode from App Store, then by typing:

xcode-select --install

in the terminal to install the Command Line Tools.

• Install gfortron from HPC.

• Download the compiled package of HEAsoft from NASA’s HEASARC, here shows an example for Mac OS10.11:

• Uncompress HEAsoft to your application folder, here I put it in /Applications/heasoft/, then go to/Applications/heasoft/x86_64-apple-darwin15.0.0/BUILD_DIR, and run:

./configure >& config.out &

• Create .bash_profile file in your home root folder /Users/Yourname/, add the content:

HEADAS=/Applications/heasoft/x86_64-apple-darwin15.0.0export HEADASsource $HEADAS/headas-init.sh

• Download DS9 for X Window from Smithsonian Astrophysical Observatory, Uncompress DS9 and ds9.zipto /Applications/heasoft/x86_64-apple-darwin15.0.0/bin.

• Done.

5

Learn GRB Data Analysis in 3 Days, Release 0.9.9

6 Chapter 2. Software Installation

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2.2 Fermi - Science Tools & rmfit

2.3 Local CALDB Setup

Calibration database (CALDB) system stores and indexes datasets associated with the calibration of satellites.

We are going to install the local CALDB in /Applications/heasoft/CALDB_LOCAL:

• Downloading CALDB setup files, and uncompress to /Applications/heasoft/CALDB_LOCAL.

• Downloading CALDB Calibration Data, and uncompress to /Applications/heasoft/CALDB_LOCAL.

The structure inside /Applications/heasoft/ will be like:

CALDB_LOCAL-- data| -- glast| | -- lat| | -- gbm| -- swift| -- bat| -- xrt| -- uvot| -- mis-- software

-- tools-- alias_config.fits-- caldb.config-- caldbinit.csh-- caldbinit.sh-- caldbinit.unix-- caldbinit.vms-- caldbinit_iraf.unix

• Add to ~/.bash_profile:

### LOCAL CALDB #########CALDB=/Applications/heasoft/CALDB_LOCALexport CALDBCALDBCONFIG=$CALDB/software/tools/caldb.configexport CALDBCONFIGCALDBALIAS=$CALDB/software/tools/alias_config.fitsexport CALDBALIASsource $CALDB/software/tools/caldbinit.sh

• Done. We can check if the local CALDB is corrected installed by running caldbinfo, open a new terminal:

caldbinfo INST SWIFT XRT

** caldbinfo 1.0.2... Local CALDB appears to be set-up & accessible

** caldbinfo 1.0.2 completed successfully

2.2. Fermi - Science Tools & rmfit 7

Learn GRB Data Analysis in 3 Days, Release 0.9.9

8 Chapter 2. Software Installation

CHAPTER 3

Swift-BAT Data Analysis

9

Learn GRB Data Analysis in 3 Days, Release 0.9.9

10 Chapter 3. Swift-BAT Data Analysis

CHAPTER 4

Swift -XRT Data Analysis

• Two Modes: Windows Timing & Photon Counting• What kind of files do we need?• How to download data?• How to generate spectrum and light curve ?

4.1 Two Modes: Windows Timing & Photon Counting

Swift-XRT has two modes, Windowed Timing (WT) and Photon Counting (PC).

The Windowed Timing data is obtained by binning 10 rows into a single row, and then reading out only the central200 columns of the CCD. The time resolution of this mode is 1.7 ms.

The Photon Counting data retains full imaging and spectroscopic resolution but the time resolution is limited to 2.5 s.

4.2 What kind of files do we need?

• Event File .evt, the most important one, which contains the observational data. Swift website providesscreened event file _cl.evt and unscreened event file _uf.evt.

• Redistribution Matrix File .rmf and Ancillary Response File .arf. The Redistribution Matrix gives theprobabilities of an incoming photon of energy E will be detected in several detector’s channels. The AncillaryResponse Matrix gives the “effective area”, the effective sensitivity area of the detector to photons of givenenergy” of the detector system, and usually includes such components as mirror vignetting, filters, etc.

Note: In some cases .arf and .rmf are supplemented, in the cases of BAT and UVOT, replaced by.rsp files. A detailed description is available: Definition of RMF and ARF file formats.

• Housekeeping File .hk, The Housekeeping file contains the information of satellite while observing the GRB,for instance, CCD temperature, voltage and etc.

• Attitude files .sat .pat .uat, The .sat file contains the attitude determined from the spacecraft startrackers. The .pat file is almost identical to the sat file, but the task attjumpcorr has been applied to it.From the point of view of XRT analysis, these files are indistinguishable. The attitude in the .uat file has beendetermined using the UVOT as a star tracker.

11

Learn GRB Data Analysis in 3 Days, Release 0.9.9

Fig. 4.1: Light curve of GRB 160227A taken from Swift UK data center, the blue part is from WT mode and the redpart is observed by PC mode.

12 Chapter 4. Swift -XRT Data Analysis

Learn GRB Data Analysis in 3 Days, Release 0.9.9

Fig. 4.2: Unscreened (left) and screened (right) images of GRB 160227A.

Fig. 4.3: XRT Effective area curves for WT mode grade 0-2 and PC mode grade 0-12.

4.3 How to download data?

1. Select the GRB from Swift Archive Download Portal, we choose 160227A for example.

2. Above figure show the download page with individual observations. If you want to download all the data forXRT analysis, select “xrt” and “auxil” on the top-left and click “download selected”, “xrt” has the XRT data and“auxil” contains the satellite information.

3. Here we only need some necessary file for the early afterglow analysis. Those files are included in obs ID:00676423000, which contains the data till 4532.6s data after the GRB trigger. Click on “00676423000”, a listof many files appear.

4. First we download the event file sw00676423000xpcw3po_cl.evt of PC mode andsw00676423000xwtw2po_cl.evt of WT mode, and the housekeeping file sw00676423000xhd.hk.

5. Determine the ATTFLAG of the event file in order to select the attitude file:

fkeyprint sw00676423000xpcw3po_cl.evt.gz ATTFLAG

# FILE: sw00676423000xpcw3po_cl.evt.gz# KEYNAME: ATTFLAG# EXTENSION: 0ATTFLAG = '110 ' / Attitude type flag# EXTENSION: 1ATTFLAG = '110 ' / Attitude type flag# EXTENSION: 2# EXTENSION: 3# EXTENSION: 4

fkeyprint is used to print the keywori stored in FITS file, it displys ATTFLAG = 110, which means theextension of attitude file is .pat, so we shall download sw00676423000pat.fits. The correspondence

4.3. How to download data? 13

Learn GRB Data Analysis in 3 Days, Release 0.9.9

Fig. 4.4: GRB 160227A Data Download Page

14 Chapter 4. Swift -XRT Data Analysis

Learn GRB Data Analysis in 3 Days, Release 0.9.9

is 100 = .sat file, 110 = .pat file, ‘111 = .uat file, and 101 = .uat file.

6. Response matrix files .rmf, .arf and .rsp are not in this page, we will download and produce them whendoing the spectrum analysis.

Hint: A perl script for downloading above files: dlXRT

4.4 How to generate spectrum and light curve ?

4.4. How to generate spectrum and light curve ? 15

Learn GRB Data Analysis in 3 Days, Release 0.9.9

16 Chapter 4. Swift -XRT Data Analysis

CHAPTER 5

Fermi-GBM Data Analysis

17

Learn GRB Data Analysis in 3 Days, Release 0.9.9

18 Chapter 5. Fermi-GBM Data Analysis

CHAPTER 6

Fermi-LAT Data Analysis

19

Learn GRB Data Analysis in 3 Days, Release 0.9.9

20 Chapter 6. Fermi-LAT Data Analysis

CHAPTER 7

Spectrum Fitting

21

Learn GRB Data Analysis in 3 Days, Release 0.9.9

22 Chapter 7. Spectrum Fitting

CHAPTER 8

Light-curve Fitting

23

Learn GRB Data Analysis in 3 Days, Release 0.9.9

24 Chapter 8. Light-curve Fitting

CHAPTER 9

Advanced Learning

25

Learn GRB Data Analysis in 3 Days, Release 0.9.9

26 Chapter 9. Advanced Learning

CHAPTER 10

Helpful Links

27

Learn GRB Data Analysis in 3 Days, Release 0.9.9

28 Chapter 10. Helpful Links

CHAPTER 11

Scripts

The best way of learning GRB data analysis to to read the source code of HEASoft and Science Tools, they are mainlywritten by C and Perl.

Here I provide several Perl and Python scripts, Perl tackles data reduction, it is especially easy to use for Swift, becauseHEASoft contains many libraries and commands written by Perl. Python is for fitting and plotting commonly.

11.1 Perl Subroutines from HEASoft

This page contains two files (libswxrt.pl, xrtproducts.pl).

These Perl libraries are from the source code of HEASoft, written by Italian Swift Archive Center (Frascati), Imodified some.

Most of the perl scripts provided here require these two libraries.

1 #!/usr/bin/perl2

3 ## This file combines libswxrtperl.pl and xrtproduct from HEASoft, with some changes.4 ## ----------------------------------------------------------------------------------5

6 #7 # Modul name: libswxrtperl.pl8 #9 #

10 # Description:11 # Library functions for Unit Tests12 #13 #14 # Author/Date: Italian Swift Archive Center (Frascati)15 #16 # History:17 #18 # 0.1.0 : FT 07/02/2003 - First Release19 # 0.1.1 : FT 14/05/2003 - check existence of 'fkeypar' (if LHEASOFT20 # has not been set the 'qx' does not return21 # error)22 # 0.1.2 : RP 22/07/2003 - Minor change to GetEventDataMode23 # 0.1.3 : FT 30/07/2003 - Changes to GetEventFilteredName function24 # 0.1.4 : FT 03/08/2003 - Changes to GetAttOrbFileName function;25 # muved subroutines: CrateDir, GetViewer,26 # PlotImage, FindExecFile, SetLev2EvtFileName,27 # and AddKeyword from xrtpipeline task

29

Learn GRB Data Analysis in 3 Days, Release 0.9.9

28 # 0.1.5 : FT 24/10/2003 - Added 'CallQuzcif' subroutine needed for29 # 'xrtscreen' task taken from 'xrtpipeline'30 # Minor changes CompUL subroutine31 # Added CheckXselectLog function32 # 0.1.6 : RP 13/11/2003 - Change CallQuzCif return two arrays outlist33 # and extlist34 # Added GetHduNum , GetNumExtName functoin35 # 0.1.7 : FT 14/11/2003 - Changes on GetHduNum and GetExtName subroutines36 # TableEmpty subroutine changes37 # 0.1.8 : FT 20/11/2003 - Changes on GetHduNum subroutine (problems with38 # the log file created by fstruct in the same39 # directory of the input file)40 # 0.1.9 : FT 20/11/2003 - Added RP subroutine 'LoadBinTable'41 # 0.2.0 : FT 25/11/2003 - Added SetGtiFileName subroutine42 # 0.2.1 : FT 26/11/2003 - Added ErasePath subroutine43 #44 # 0.2.2 : RP 12/12/2003 - Added GetPfilesName(), LoadParameter(), LoadParameterFromCmdLine(),45 # GetParameterList()46 # 0.2.3 : RP 19/01/2004 - Added getHistoryTime(), write_history(), write_parameter_list()47 # 0.2.4 : RP 16/03/2004 - Added funcion UpdateChecksum48 # 0.2.5 : FT 16/03/2004 - Minor Changes on GetPfilesName subroutine and comments49 # 0.2.6 : RP 16/03/2004 - Modify WriteParameterList50 # 0.2.7 : RP 18/03/2004 - write checksum when call WriteParameterList51 # 0.2.8 : RP 19/03/2004 - Added CheckRa,CheckDec,Ra2Deg,Dec2Deg,RaDec2XY52 # 0.2.9 : FT 26/03/2004 - 'GetInputParam' bug fixed parsing input parameters53 # - Minor changes on Info and Error messages54 # 0.2.10: RP 01/04/2004 - Modify LoadBinTable55 # Added function CheckCol, CheckColPtr56 # 0.2.11: RP 01/04/2004 - Added GetXspecChatter57 # 0.2.12: RP 07/04/2004 - Bug fixed58 # 0.2.13: RP 19/04/2004 - Change GetKeyword (used cfits library)59 # Added function GetFitsPointer60 # Remove GetHduNum61 # Changed parameter to TableEmpty (file,extension)62 # 0.2.14: RP 21/04/2004 - Change GetKeyword63 # 0.2.13: FT 27/04/2004 - Substituted "goto EXITWITHERROR" with return64 # 0.2.14: RP 29/04/2004 - Minor change65 # 0.2.15: RP 29/04/2004 - Bug fixed66 # 0.2.16: FT 05/05/2004 - Added 'GetEventStartDate' subroutine that returns67 # $date and $time for CALDB quzcif query68 # - New Naming Convention Handle (1 March 2004)69 # - Added 'RunCommandAndRedirectOutput' to run a command70 # without have output on the STDOUT but into a file. This71 # can be used with Xselect, Ximage, Lcurve to avoid72 # messages on screen73 # 0.2.17: FT 13/05/2004 - Changed GTI Default Name (SetGtiFileName function)74 # 0.2.18: FT 17/05/2004 - Added check on GetValPar function75 # 0.2.19: RP 19/07/2004 - Added check input value to CheckRa and CheckDec76 # 0.2.20: FT 22/07/2004 - Added Cleanup and RenameFile subroutines77 # - Added parameter to GetKeyword subroutine to do not78 # print error messages if the keyword does not exist79 # (needed to check the keyword existence without give an80 # error)81 # 0.2.21: RP 27/07/2004 - Bug fixed82 # 0.2.22: RP 29/07/2004 - Change function IsNumeric83 # 0.2.23: CS 02/08/2004 - Added ExecXimage subroutine to exec ximage and84 # perform a check on error85 # 0.2.24: FT 29/07/2004 - Added 'GetPntFromExt' and 'GetObjFromExt' functions

30 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

86 # 0.2.25: RP 03/08/2004 - Added function getArrayExtensionImage87 # 0.2.26: RP 04/08/2004 - Added function delFitsCol to delete a list of columns from fits file88 # Added parameter to getFitsPointer . $mode to open or READONLY or READWRITE mode89 # 0.2.27: FT 05/08/2004 - Bug fixed in SetLev2EvtFileName, added handle of input compressed files90 # 0.2.28: RP 06/08/2004 - Update checksum in function delFitsCol91 # 0.2.29: CS 10/08/2004 - Kill -9 ExecXimage (sun bug)92 # 0.2.30: CS 19/08/2004 - Kill ExecXimage patch for SunOS93 # 0.2.31: RP 29/09/2004 - Bug fixed GetFitsPointer subroutine (this should solve the94 # Solaris problem given by 'xrttdrss' and 'xrttam'95 # tasks during Build 9)96 # 0.2.31: RP 30/09/2004 - Modify CreateDir to create parents directory97 # Added check to CheckRa and CheckDec if is empty98 # 0.2.32: FT 30/09/2004 - Added GetRootStem function. It takes the99 # root of a filename erasing the given 'tailstem'

100 # 0.2.33: RP 04/10/2004 - Added function AddKeywordExt101 # 0.3.0: FT 07/10/2004 - Added initialization of $fptr and $status to 0,102 # this change has been suggested by Bob Wiegand103 # (undefined variables give warnings with104 # Astro::FITS::CFITSIO library)105 # - added undefined variables initialization when needed106 # 0.3.1: FT 10/12/2004 - Added CallScQuzcif function107 # 0.3.2: RP 10/12/2004 - Bug fixed on Ra2Deg and Dec2Deg for negative numbers108 # 0.3.3: RP 27/01/2005 - LoadFromCmdLine: Check on range value for parameters inserted on command line109 # Change CheckCol if parameter chkval is not defined check if value is different from 0 and TNULL value110 # 0.3.4: RP 23/02/2005 - Change function delFitsCol111 # 0.3.5: FT 21/03/2005 - Changed check on 'undefined' hask value in GetValPar subroutine.112 # 0.3.6: FT 23/03/2005 - Changes in the CheckCol subroutine. Now returns the $Task{status}113 # eq 1 if the colum is filled by zeros and eq 2 if the column114 # is filled by NULLs. This is to give in the xrtproducts task115 # a warning message if the column is filled by nulls116 # 0.3.7: BS 13/05/2005 - Bugs fixed117 # 0.3.8: FT 06/06/2005 - Added CheckRow funcion taken from 'xrtscreen' task118 # needed also to 'xrtpipeline'119 # - Added CleanTimeNulls function to run ftselect120 # on the input file and erase rows with TIME121 # equal to NULL122 # - Added SetFileName function123 # - Added AddStemBeforeExtension function124 # 0.3.9: FT 15/09/2005 - added fits_close_file when needed125 # 0.4.0: BS 13/03/2005 - Build standard sky instrument map file name126 # in SetExpoMapFileName routine127 # 0.4.1: NS 24/10/2006 - Added 'GetHdStartDate' subroutine that returns128 # $date and $time of hd file for CALDB quzcif query129 # - Added 'GetAttitudeATTFLAG' subroutine that returns130 # ATTFLAG keyword value in attitude file131 # - Added function AddKeywordExtNum132 # - Added GetImagesHduList133 # 0.4.2: NS 09/06/2007 - Change function IsNumeric134 # 0.4.3: 18/10/2007 - Bug fixed in IsNumeric function135 # 0.4.4: 18/12/2007 - Changed 'GetEventStartDate' function to read keywords from primary136 # hdu if 'EVENTS' extension not exists (i.e. in pc *sk.img files)137 # 0.4.5: 26/03/2008 - Changed 'SetExpoMapFileName' routine to build standard138 # raw instrument map file name139 # 0.4.6: 30/07/2009 - Modified IsNumeric function to accept '.xx' numeric format140 # 0.4.7: 14/10/2009 - Modified CallQuzCif function to set retrieve=yes in quzcif call141 # 0.4.8: NS 20/01/2015 - Added 'FindCaldbIndxFile' and 'GetCaldbVersion' routines142 #143 # Functions implemented in this file:

11.1. Perl Subroutines from HEASoft 31

Learn GRB Data Analysis in 3 Days, Release 0.9.9

144 # Cleanup(@filelist)145 # CompUL($string, $comp )146 # PrntChty($chatty, $message )147 # GetKeyword([$filename|undef],[$extname|undef],[$filepnt|undef],148 # $keyname,\$keywordval,$checkexist);149 # SetBool($boolval)150 # sub GetInputParam ($inspec)151 # GetSwXRTDefaultStem ($filename)152 # GetAttOrbFileName ($infile, $outdir, $default, $stem )153 # RunningTask()154 # RunningSub($task,$subrout)155 # SuccessSub($message)156 # Success($message)157 # Error($message)158 # RunningComm($task,$command)159 # ErrorComm($task,$subrout,$command)160 # GetPath($filename)161 # GetFileNameRoot($filename)162 # IsCompressed ($filename)163 # EraseLastExtension($filename)164 # GetEventDataMode($evtfile)165 # TableEmpty($filename,$extension)166 # CrateDir ($directory) - Creaes the directory if not found167 # GetViewer ( $plotdevice )168 # PlotImage($viewer, $ImageFile)169 # FindExecFile($file)170 # SetLev2EvtFileName($infile,$outdir)171 # AddKeyword ($fileandext, $keyname, $keyvalue, $comment)172 # CallQuzcif($Dataset, $Date, $Time, $Selectin )173 # CheckXselectLog()174 # GetNumExtName($filename,$extname)175 # LoadBinTable($filefits, $extname,$numext,@columns)176 # SetGtiFilName($evtfile,$outdir)177 # ErasePath($filename)178 # GetPfilesName()179 # LoadParameter()180 # LoadParameterFromCmdLine()181 # GetParameterList()182 # GetValPar($parname , $pos)183 # SetValPar($parname, $val, $col)184 # getHistoryTime()185 # write_history($filename,$hdunum,$hist)186 # WriteParameterList($filename,$hdunum,@list)187 # WriteParHistory($filefits,$head,$str,$status)188 # UpdateCheckSum($file)189 # CheckRa($type,$str)190 # CheckDec($type,$str)191 # Ra2Deg($str)192 # Dec2Deg($str)193 # RaDec2XY($file,$ra,$dec,$x,$y)194 # CheckCol($filename,$extname,$colname,$chkval,$maxval,$minval)195 # CheckColPtr($fptr,$colname,$chkval,$maxval,$minval)196 # GetXspecChatter($TaskChat)197 # GetFitsPointer($filename,$extname,$pointer,$mode) mode=READONLY or READWRITE198 # GetEventStartDate($filename,\$date,\$time)199 # GetHdStartDate($hdfilename,\$date,\$time)200 # RunCommandAndRedirectOutput($command,$outfile)201 # RenameFile ( $filename, $newfilename )

32 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

202 # ExecXimage ( $parameterlist )203 # GetPntFromExt($filename,[$extname|undef],[$extnum|undef],204 # \$ra_pnt,\$dec_pnt,[\$pa_pnt|undef]);205 # GetObjFromExt($filename,[$extname|undef],[$extnum|undef],206 # \$ra_obj,\$dec_obj);207 # getArrayExtensionImage($filefits)208 # AddKeywordExt ($filename,$extname,$datatype,$keyname,$value,$comment)209 # AddKeywordExtNum ($filename,$extnum,$datatype,$keyname,$value,$comment)210 # GrtRootStem($filename,$tailstem)211 # CallScQuzcif($Dataset, $Date, $Time, $Selectin )212 # CheckRow( $file, $ext, $gtifile, $gtiexpr, $gtiextname ) )213 # CleanTimeNulls ( $infile, $outfile, $extname )214 # AddStemBeforeExtension ($file, $stem )215 # GetAttitudeATTFLAG ($attfile, $attflag)216 # GetImagesHduList ($infile)217 #218 #219 # %Task = (220 # name => <task name>,221 # version => <task version>,222 # chatter => <numb>,223 # status => 0,224 # errmess => "",225 # stem => <task name and version>,226 # ....227 # )228 # %Default = (229 # KEYPAR_COMMAND,230 # ....231 # )232 #233 # HEADAS tasks needed:234 # ftselect235 # ftchecksum236 # ftstat237 #238 # LHEASOFT tasks needed:239 # fkeypar240 #241 #============================================================#242 #243 # Specific of the task244 #;245

246 # add subroutines from xrtproducts.pl247 require 'xrtproducts.pl';248

249 use strict;250 use vars qw( %Task %Default %Def);251 use base qw(Task::HEAdas);252 use Task qw(:codes);253

254 use Astro::FITS::CFITSIO qw(:longnames :constants);255 use File::Copy;256

257 use Math::Trig;258

259 %Def = (

11.1. Perl Subroutines from HEASoft 33

Learn GRB Data Analysis in 3 Days, Release 0.9.9

260 GTIFILESTEM => "gti",261 LEV2STEM => "cl",262 LEV2STEMLEN => 2,263 LEV2STARPOINT => 20,264 LEV2LEN => 22,265 );266

267

268 my $PI = 3.14159265358979323846;269 my $PIS = 3.141592653;270 my $EPSR4 = 1E-7;271 my $MAXR4 = 1E38;272 my $MAX_INTEG = 2147483647;273

274

275

276

277 sub Cleanup {278

279 # Remove a list of files giving a warning280 # if the file cannot be removed281

282 my ( @list ) = @_;283

284 use vars qw ( %Task );285 my $file;286

287 foreach $file ( @list ) {288 if ( -f $file ) {289 if ( !unlink ( $file ) ) {290 &PrntChty(2,"$Task{stem}: Warning: Cleanup: Unable to remove '$file' file. $!\n");291 }292 }293 }294

295 return 0;296

297 } # Cleanup298

299 sub CompUL {300 my ( $string1, $string2 ) = @_;301 # The subroutine performs a insensitive case302 # compare of two strings. It returns303 # 1 if the strings are equal or 0 if not304 if ( lc($string1) eq lc($string2) ) { return 1; }305 return 0;306 } # CompUL307

308 sub PrntChty {309 my ( $chatty, $message ) = @_;310 use vars qw ( %Task );311 if ( $chatty <= $Task{chatter} ) {312 print"$message";313 }314 return;315 } # PrntChty316

317 sub SetBool {

34 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

318

319 my ( $val ) = @_;320 my ( $ret );321 use vars qw ( %Task );322

323 if ( $val =~ /[yY]/ ) { $ret = 1; }324 elsif ( $val =~ /[nN]/ ) { $ret = 0; }325 else { $Task{status} = 1; }326

327 return $ret;328

329 } # SetBool330

331 sub GetInputParam {332

333 # This function parses the input parameter specification.334 # The $inspec must be of format: <parametername>=<parametervalue>335

336 my ( $inspec ) = @_;337 use vars qw ( %Task );338

339 if ( $Task{status} ) { return; }340

341 my ( $ind ) = index ( $inspec, '=' );342 my ( $inpar ) = substr($inspec,0,$ind-1);343 my ( $inval ) = substr($inspec,$ind+1);344

345 if ( $ind <= 0 || !$inpar || ( !$inval && $inval ne "0" )) {346 print"$Task{'stem'}: Error: Parsing input parameter: $inspec\n";347 print"$Task{'stem'}: Error: Please specify parameters with format: <parametername>=<parametervalue> without blanks\n";348 print"$Task{'stem'}: Error: Type 'fhelp $Task{name}' for more information on parameters\n";349 $Task{status} = 1;350 return;351 }352 return ($inval);353

354 } #GetInputParam355

356 sub GetAttOrbFileName {357

358 my ( $default, $stemout, $stemin ) = @_;359

360 use vars qw ( %Task %Default );361 my ( $AttOrb , $InStem );362

363 my ( $ATTORBEXTENSION ) = "s.attorb";364

365 # Define attorbfilename366

367 if ( &CompUL( $default, $Default{DEFAULT} ) && &CompUL( $stemout, $Default{DEFAULT} )) {368 $AttOrb = "$stemin$ATTORBEXTENSION";369 }370 elsif ( &CompUL( $default, $Default{DEFAULT} ) && !&CompUL( $stemout, $Default{DEFAULT} )) {371 # Use Input Stem372 $AttOrb = "$stemout$ATTORBEXTENSION";373 }374 else { $AttOrb = "$default"; }375

11.1. Perl Subroutines from HEASoft 35

Learn GRB Data Analysis in 3 Days, Release 0.9.9

376 &PrntChty(3,"$Task{stem}: Info: GetAttOrbFileName: Output Attitude Orbit File will be $AttOrb\n");377

378 return $AttOrb;379

380 } # GetAttOrbFileName381

382 sub GetSwXRTDefaultStem {383

384 my ( $infile ) = @_;385 use vars qw ( %Task );386

387 my ( $STDXPos ) = 13;388

389 my ( $infilenopath ) = substr($infile,rindex( $infile, '/' )+1);390 # take stem391 if ( substr( $infilenopath,0,2 ) !~ "sw" || rindex( $infilenopath , 'x' ) != $STDXPos )392 {393 &PrntChty(2,"$Task{stem}: Error: GetSwXRTDefaultStem: Input file name '$infile',\n");394 &PrntChty(2,"$Task{stem}: Error: GetSwXRTDefaultStem: does not match SWIFT/XRT standard naming conventions\n");395 $Task{errmess} = "Cannot define standard stem of files";396 $Task{status} = 1;397 return ;398 }399

400 my $OutStr = substr($infilenopath,0,$STDXPos);401 return ($OutStr);402

403 } # GetSwXRTtDefaultStem404

405 sub RunningTask {406 use vars qw (%Task);407

408 &PrntChty(2,"--------------------------------------------------------------\n");409 &PrntChty(2," Running ' $Task{name} version $Task{version} '\n");410 &PrntChty(2,"--------------------------------------------------------------\n");411

412 } # RunningTask413

414 sub RunningSub {415 use vars qw (%Task);416 my ($task,$subrout,$message) = @_;417 if ( !defined($message) ) { $message = ""; }418 &PrntChty(3,"$Task{stem}: Info: Running '$subrout' $message\n");419 } # RunningSub420

421 sub SuccessSub {422 use vars qw (%Task);423 my ($task,$subrout, $message) = @_;424 if ( !defined($message) ) { $message = ""; }425 &PrntChty(3,"$Task{stem}: Info: '$subrout' exit with success. $message\n");426 } # RunningSub427

428 sub Success {429 my ( $message ) = $_;430 use vars qw ( %Task );431 &PrntChty(2,"----------------------------------------------------------\n");432 if ( !defined($message) ) { $message = ""; }433 &PrntChty(2,"$Task{stem}: Exit with success $message\n");

36 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

434 &PrntChty(2,"------------------------------------------------------------\n");435 } # $Success436

437 sub Error {438 my ( $message ) = $_;439 use vars qw (%Task);440 &PrntChty(2,"-------------------- $Task{name} error -----------------------\n");441 if ( defined($message) ) {442 &PrntChty(2,"$Task{'stem'}: $message\n");443 }444 &PrntChty(2,"$Task{'stem'}: $Task{errmess}\n");445 &PrntChty(2,"--------------------------------------------------------------\n");446 } # Error447

448 sub RunningComm {449 use vars qw (%Task);450 my($task,$command) = @_;451 &PrntChty(4,"$Task{stem}: Command: $command\n");452 } # RunningComm453

454 sub ErrorComm {455 use vars qw (%Task);456 my($task,$subrout,$command) = @_;457 &PrntChty(3,"$Task{stem}: Error: running '$subrout'\n");458 &PrntChty(3,"$Task{stem}: Error: The run was: $command \n");459 } # ErrorComm460

461 sub GetPath {462 my ( $filename ) = @_;463 my ( $i, $path );464

465 $i = rindex( $filename, '/' );466 if ( $i == -1 ) { $path = "."; }467 else { $path = substr($filename,0,rindex( $filename, '/' )+1); }468 return $path;469 } # GetPath470

471 sub GetFileNameRoot {472 my ( $infile ) = @_;473 my $infilenopath = substr($infile,rindex( $infile, '/' )+1);474 if ( &IsCompressed($infilenopath) ) { $infilenopath = &EraseLastExtension($infilenopath); }475 $infilenopath = &EraseLastExtension($infilenopath);476 return $infilenopath;477 } # GetFileNameRoot478

479 sub IsCompressed {480 my ( $infile ) = @_;481 my ( @ZIPEXTENSIONS ) = (".gz",".Z");482 my $ext;483

484 foreach $ext ( @ZIPEXTENSIONS ) {485 if ( $infile =~ /$ext$/ ) { return 1; }486 }487 return 0;488 } # IsCompressed489

490 sub EraseLastExtension {491 my ( $infile ) = @_;

11.1. Perl Subroutines from HEASoft 37

Learn GRB Data Analysis in 3 Days, Release 0.9.9

492 my $infile2;493 my $i = rindex( $infile, '.' );494 if ( $i == -1 ) { $infile2 = $infile; }495 else { $infile2 = substr($infile,0,$i); }496 return $infile2;497 } # EraseLastExtension498

499 sub ErasePath {500 my ( $infile ) = @_;501 my $infile2;502 my $i = rindex( $infile, '/' ) + 1;503 if ( $i <= 0 ) { $infile2 = $infile; }504 else { $infile2 = substr($infile,$i); }505 return $infile2;506 } # ErasePath507

508 sub GetEventDataMode {509

510 my ( $file ) = @_;511 use vars qw (%Task %Default);512 my (%xrtmodes, $numext, $value, $comm);513

514 %xrtmodes = (515 PHOTON => "pc",516 LOWRATE => "lr",517 PILEDUP => "pu",518 WINDOWED => "wt",519 SHORTIMA => "im",520 LONGIMA => "im",521 );522

523 my ($fptr, $status) = (0, 0);524 fits_open_file($fptr,$file,READONLY,$status);525 if ($status) {526 $Task{status} = 1;527 $Task{errmess} = "Unable to open fits file : $file";528 return;529 }530

531 fits_get_num_hdus($fptr,$numext,$status);532 if ($status) {533 $Task{status} =1;534 $Task{errmess} = "Unable to get number of extensions from file : $file\n";535 fits_close_file($fptr,$status);536 return;537 }538

539 for (my $i = 1; $i <= $numext; $i++) {540

541 fits_movabs_hdu($fptr,$i,ANY_HDU,$status);542 if ($status) {543 $Task{errmess} = "Running movabs_hdu (num extension: $i) in $file";544 &PrntChty(2,"$Task{stem}: Error: GetEventDataMode: $Task{errmess}\n");545 $Task{status} = 1;546 return ;547 }548

549 fits_read_keyword($fptr,"DATAMODE",$value,$comm,$status);

38 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

550 if (!$status) {551 fits_close_file($fptr,$status);552

553 $value =~ s/ |\'//g;554

555 # Get datamode556 if ( !$xrtmodes{$value} ) {557 &PrntChty(2,"$Task{stem}: Error: GetEventDataMode: DATAMODE ($value) read from '$file'\n");558 &PrntChty(2,"$Task{stem}: Error: GetEventDataMode: is not a SWIFT/XRT valid datamode\n");559 $Task{errmess} = "Unable to define '$file' datamode";560 $Task{status} = 1;561 return ;562 }563

564 return $xrtmodes{$value};565 } else {$status = 0;}566

567 }568

569 fits_close_file($fptr,$status);570

571 $Task{status} = 1;572 $Task{errmess} = "Error: Reading datamode in $file";573 return;574

575

576 } # GetEventDataMode577

578 sub TableEmpty {579

580 # Input file name and extension: sring filename+extension581 # Return status:582 # 0: table not empty583 # 1: table empty or error584

585 my ($filename,$extension) = @_;586 use vars qw (%Task);587

588 # Get keyword589 my ($keyword);590 &GetKeyword($filename,$extension,undef,"NAXIS2",\$keyword);591 if ($Task{status}){return 1;}592 $keyword =~ s/ |\'//g;593

594 if ( $keyword == 0 ) { return 1; } # the table is empty595

596 return 0; # the table is not empty597

598 } # TableEmpty599

600

601 #sub CheckExec {602 #603 # my ( $exec ) = @_;604 # my ( $sdir );605 # my ( @searchp )=split(/:/,$ENV{'PATH'});606 #607 # foreach $sdir (@searchp) {

11.1. Perl Subroutines from HEASoft 39

Learn GRB Data Analysis in 3 Days, Release 0.9.9

608 # if ( -x "$sdir/$exec" ) { return 0; }609 # }610 #611 # return 1;612 #613 #} # CheckExec614

615 sub FindExecFile {616

617 my ( $file ) = @_;618 my ( @searchp )=split(/:/, $ENV{'PATH'});619 my ( $sdir );620

621 foreach $sdir (@searchp){622 if ( -x "$sdir/$file" ) { return 1; }623 }624

625 # Executable Not Found626 return 0;627

628 } # FindExecFile629

630 sub CreateDir {631

632 my ( $directory ) = @_;633 use vars qw (%Task);634

635 if ( !-d $directory ) {636 &PrntChty(4,"$Task{stem}: Info: CreateDir: Creating '$directory' directory\n");637 #if ( ! mkdir -p $directory, 0777) {638 if ( system("mkdir -p -m 0777 $directory")) {639 $Task{error} = "Creating Directory '$directory: $!'\n";640 $Task{status} = 1;641 return 1;642 }643 }644 return 0;645

646 } # CreateDir647

648 sub GetViewer {649

650 my ( $plotdevice ) = @_ ;651 my ( $task );652 use vars qw (%Task);653

654 my ( @PlotGifList ) = ("xv", "gqview","kview" );655 my ( @PlotPsList ) = ("gv", "ghostview");656

657 if ( $plotdevice =~ /gif/ ) {658 foreach $task (@PlotGifList) {659 if ( &FindExecFile($task) ) {660 return $task;661 last;662 }663 else {664 &PrntChty(4,"$Task{stem}: Error: GetViewer: .... $task not found\n");665 }

40 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

666 }667 } # Image into gif format668

669 elsif ($plotdevice =~ "ps" ) {670 foreach $task (@PlotPsList) {671 if ( &FindExecFile($task) ) {672 return $task;673 last;674 }675 else {676 &PrntChty(4,"$Task{stem}: Error: GetViewer: .... $task not found\n");677 }678 }679 }680

681 # No viewer found682 return 0;683 } #GetViewer684

685

686 sub PlotImage {687 #688 # Find the Image Viewer good for the Image File Format689 #690 my ( $viewer, $ImageFile) = @_ ;691 use vars qw (%Task);692

693 my ( $command ) = "$viewer $ImageFile &";694 if ( !-f $ImageFile ) {695 &PrntChty(1,"$Task{stem}: Error: PlotImage: cannot display '$ImageFile': file not found\n");696 return 1;697 }698 if ( system ( $command ) ) {699 &PrntChty(1,"$Task{stem}: Error: PlotImage: running '$viewer' Viewer\n");700 return 1;701 }702

703 return 0;704

705 } # Plot Image706

707

708 sub SetLev2EvtFileName {709

710 my ( $infile,$outdir ) = @_;711 use vars qw (%Task);712

713 my ( $stemlev2 ) = "cl";714 my ( $filenopath ) = substr($infile,rindex( $infile, '/' )+1);715

716 # Check if the event file is compressed717 my ( @splitfields ) = split ( /\./,$filenopath);718 if ( $splitfields[$#splitfields] eq "gz" || $splitfields[$#splitfields] eq "Z" ) {719 pop @splitfields; }720 my ( $filenozip ) = join '.', @splitfields;721

722 my ( $filenoext ) = substr($filenozip,0,rindex( $filenozip, '.' ));723 my ( $ext ) = substr($filenozip,rindex( $filenozip, '.' ));

11.1. Perl Subroutines from HEASoft 41

Learn GRB Data Analysis in 3 Days, Release 0.9.9

724

725 if ( $filenoext =~ /(l1a|ufre)/ ) { $filenoext =~ s/(l1a|ufre)/$stemlev2/; }726 elsif ( $filenoext =~ /(l1|uf)/ ) { $filenoext=~ s/(l1|uf)/$stemlev2/; }727 else { $filenoext .= $stemlev2; }728

729 my ( $lev2filename ) = "$outdir/$filenoext$ext";730 &PrntChty(3,"$Task{stem}: Info: SetLev2EvtFileName: Filtered Event File will be $lev2filename\n");731

732 return $lev2filename;733 } # SetLev2EvtFileName734

735 sub SetExpoMapFileName {736

737 my ( $infile,$outdir ) = @_;738 use vars qw (%Task);739

740 my ( $stemexpo ) = "ex.img";741 my ( $steminstr ) = "rawinstr.img";742 my ( $filenopath ) = substr($infile,rindex( $infile, '/' )+1);743

744 # Check if the event file is compressed745 my ( @splitfields ) = split ( /\./,$filenopath);746 if ( $splitfields[$#splitfields] eq "gz" || $splitfields[$#splitfields] eq "Z" ) {747 pop @splitfields; }748 my ( $filenozip ) = join '.', @splitfields;749

750 my ( $filenoext ) = substr($filenozip,0,rindex( $filenozip, '.' ));751

752 my ($instrnoext) = $filenoext;753

754 $filenoext=~ s/(cl)/$stemexpo/;755 $instrnoext =~ s/(cl)/$steminstr/;756 my ( $expofilename ) = "$outdir/$filenoext";757 my ( $instrfilename ) = "$outdir/$instrnoext";758

759 &PrntChty(3,"$Task{stem}: Info: SetExpoMapFileName: Exposure Map File will be $expofilename\n");760 &PrntChty(3,"$Task{stem}: Info: SetExpoMapFileName: Raw Instrument Map will be $instrfilename\n");761

762 return $expofilename, $instrfilename;763 } # SetExpoMapFileName764

765

766 sub AddKeyword {767

768 my ( $fileandext, $keyname, $keyvalue, $comment ) = @_ ;769

770 use vars qw ( %Task %Default);771

772 my ( $PARKEY_COMMAND ) = 'fparkey';773

774 if ( !&FindExecFile($PARKEY_COMMAND) ) {775

776 &PrntChty(2,"$Task{stem}: Error: AddKeyword: Executable '$PARKEY_COMMAND' not found in User Path\n");777 $Task{errmess} = "Error: Executable '$PARKEY_COMMAND' not found in User Path";778 $Task{status} = 1;779 return 1;780 }781

42 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

782 my $cmd = "$PARKEY_COMMAND $keyvalue $fileandext $keyname add=yes ";783

784

785 if (defined($comment)) {786 $cmd .= "comm='$comment'";787 }788

789 if ( my($FkeyRet) = qx($cmd) ) {790 &PrntChty(2,"$Task{stem}: Error: AddKeyword: Running $cmd \n");791 $Task{errmess} = "Error: Running '$PARKEY_COMMAND $fileandext $keyname'";792 $Task{status} = 1;793 return 1;794 }795

796 return 0;797

798 } # AddKeyword799

800 sub CallQuzcif {801

802

803 my ( $Dataset, $Date, $Time, $Selection , $expnumfile ) = @_;804 my ( $field,@dummy, @outlist , @extlist);805 use vars qw ( %Task );806

807 # The function performs a query to the CALDB database based808 # on $Dataset, $Date, $Time, $Selection parameters (see below809 # for the input parameter description.810 # The function return two array 'outlist' and 'extlist' with the result of the query.811 # The array is filled with filenames and extensions from the quzcif query812 # For example: if the 'quzcif' query gives only one match the array will813 # content : $outlist[0] = filename814 # $extlist[0] = extension815 # if the 'quzcif' query gives two matches the array will816 # content : $outlist[0] = filename1817 # $extlist[0] = extension1818 # $outlist[1] = filename2819 # $extlist[1] = extension2820 # etc ....821 # $Dataset - 'Calibration Dataset Codename'822 # $Date - 'Requested Date in yyyy-mm-dd format' or "NOW" for the must up to date dataset823 # $Time - 'Requested Time in hh:mm:ss format' or "-" if $date = "NOW"824 # $Selection - "Boolean selection expression for Boundary params" or "-" if not required825

826 # Check CALDB environment827

828 ## different from original one:829

830 if ( !$ENV{CALDB} ) {831 &PrntChty(2,"$Task{stem}: Error: CallQuzcif: CALDB environment not set\n");832 &PrntChty(2,"$Task{stem}: Error: CallQuzcif: Please set the CALDB environment or specify the input parameter for '$Dataset'\n");833 $Task{status} = 1;834 return (\@outlist,\@extlist);835 }836 #print "Dataset is $Dataset \n";837 my ( $command ) = "quzcif SWIFT XRT - - $Dataset $Date $Time \"$Selection\" retrieve+ clobber=yes";838 &PrntChty(2,"$Task{stem}: Info: CallQuzcif: Running $command\n");839 my ( @ret ) = qx($command);

11.1. Perl Subroutines from HEASoft 43

Learn GRB Data Analysis in 3 Days, Release 0.9.9

840 &PrntChty(2,"CallQuzcif: Info: Output 'quzcif' Command: \nCallQuzcif: Info:@ret");841

842 if ( $#ret == -1 ) {843 &PrntChty(2,"$Task{stem}: Error: CallQuzcif: No Calibration File Found for '$Dataset' dataset\n");844 &PrntChty(2,"$Task{stem}: Error: CallQuzcif: 'quzcif' command: \"$command\"\n");845 $Task{status} = 1;846 return (\@outlist,\@extlist);847 }848

849 if ( $#ret != $expnumfile-1) {850 my $n = $#ret +1;851 &PrntChty(2,"$Task{stem}: Error: CallQuzcif: Found " . $n . " calibration file(s) instead of $expnumfile file(s)\n");852 $Task{status} = 1;853 return (\@outlist,\@extlist);854 }855

856 foreach $field ( @ret ) {857

858 my ( $file, $ext );859

860 if ( $field =~ "ERROR" ) {861 &PrntChty(2,"$Task{stem}: Error: CallQuzcif: 'quzcif': @ret\n");862 $Task{status} = 1;863 return (\@outlist,\@extlist);864 }865

866 ($file, $ext ) = split /\s+/,$field;867 push @outlist, $file;868 push @extlist, $ext;869

870 }871

872 return (\@outlist,\@extlist);873

874 } # CallQuzcif875

876

877 sub CheckXselectLog {878

879 # No error code returned by xselect880 # check errors from 'xselect.log' found in881 # current directory882 my $ret = 0;883 my $XselectLog = "xselect.log";884 if ( !-f $XselectLog ) {885 PrntChty(3,"$Task{stem}: Warning: CheckXselectLog: '$XselectLog' not found\n");886 PrntChty(3,"$Task{stem}: Warning: CheckXselectLog: no checks on 'xselect' run performed\n");887 }888 else {889 if ( ! open ( XSELECTLOG, "<$XselectLog" )) {890 PrntChty(3,"$Task{stem}: Warning: CheckXselectLog: Cannot read '$XselectLog' file\n");891 PrntChty(3,"$Task{stem}: Warning: CheckXselectLog: no checks on 'xselect' run performed\n");892 }893 else {894 while ( <XSELECTLOG> ) {895 if ( $_ =~ /Error/ ) {896 chop;897 PrntChty(2,"$Task{stem}: Error: CheckXselectLog: following error message found for 'xselect' run:\n");

44 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

898 PrntChty(2,"$Task{stem}: Error: CheckXselectLog: '$_'\n");899 $ret = 1;900 }901 }902 close XSELECTLOG;903 }904 }905

906 return $ret;907

908 } # CheckXselectLog909

910

911 #Return number of extension with extname=parameter912 # if not found return -1913 sub GetNumExtName {914

915 my ($filename,$extname) = @_;916

917 my ($numext, $fptr, $status) = (0, 0, 0);918

919 fits_open_file($fptr,$filename,READONLY,$status);920 if ($status) {921 $Task{status} = 1;922 &PrntChty(2,"$Task{stem}: Error: GetNumExtName: Fitsio 'fits_open_file' error '$status' on '$filename' file\n");923 $Task{errmess} = "Unable to open fits file : $filename";924 return 5;925 }926 fits_movnam_hdu($fptr,ANY_HDU,$extname,0,$status);927 if ($status == BAD_HDU_NUM ) {928 &PrntChty(4,"$Task{stem}: Warning: GetNumExtName: not found '$extname' extension\n");929 &PrntChty(4,"$Task{stem}: Warning: GetNumExtName: in '$filename' file\n");930 fits_close_file($fptr,$status);931 return -1;932 } elsif ($status) {933 $Task{status} = 1;934 $Task{errmess} = "Unable to move to the extension '$extname' of '$filename'";935 fits_close_file($fptr,$status);936 return;937 }938

939 fits_get_hdu_num($fptr,$numext);940 fits_close_file($fptr,$status);941

942 return $numext-1;943

944 } # GetNumExtName945

946 sub LoadBinTable947 {948 my ($filefits, $extname,$numext,@columns) = @_;949 use vars qw ( %Task );950

951 my $status = 0;952 my $fits = Astro::FITS::CFITSIO::open_file($filefits, READONLY, $status);953 if (not $fits) {954 &PrntChty(2,"$Task{stem}: Error: LoadBinTable: CFITSIO::open_file: error on '$filefits' file\n");955 $Task{status} = 1;

11.1. Perl Subroutines from HEASoft 45

Learn GRB Data Analysis in 3 Days, Release 0.9.9

956 return;957 }958

959 if (defined($extname) && ($extname ne "")) {960 $fits->movnam_hdu(BINARY_TBL, $extname, 0, $status);961 if ( $status ) {962 &PrntChty(2,"$Task{stem}: Error: LoadBinTable: movnam_hdu: error on '$filefits' file\n");963 &PrntChty(2,"$Task{stem}: Error: LoadBinTable: unable to move to extname: $extname\n");964 $Task{status} = 1;965 return;966 }967 } else {968

969 $fits->movabs_hdu($numext+1,undef,$status);970 if ( $status ) {971 &PrntChty(2,"$Task{stem}: Error: LoadBinTable: movabs_hdu: error on '$filefits' file\n");972 &PrntChty(2,"$Task{stem}: Error: LoadBinTable: unable to move to ext num: $numext\n");973 $Task{status} = 1;974 return;975 }976 }977

978 my $count = -1;979 $fits->get_num_rows($count, $status);980 if ($status) {981 &PrntChty(2,"$Task{stem}: Error: LoadBinTable: get_num_rows: error on '$filefits' file\n");982 &PrntChty(2,"$Task{stem}: Error: LoadBinTable: unable to get the number of rows\n");983 $Task{status} = 1;984 return ;985

986 }987

988 foreach my $col (@columns) {989

990 $col->{data} = [ ];991

992 my $index = -1;993 my $null = -1;994 my $nulls = -1;995 my ( $type,$repeat,$width, $tzeroval,$comm );996

997 if ($fits->get_colnum(0, $col->{name}, $index, $status)) {998 &PrntChty(2,"$Task{stem}: Error: LoadBinTable: get_colnum: error on '$filefits' file\n");999 &PrntChty(2,"$Task{stem}: Error: LoadBinTable: unable to get colnum: '$col->{name}'\n");

1000 $Task{status} = 1;1001 return ;1002 }1003

1004 if ($fits->get_coltype($index,$type,$repeat,$width,$status)) {1005 &PrntChty(2,"$Task{stem}: Error: LoadBinTable: Unable to get column type ($col) file : $filefits\n");1006 $Task{status} = 1;1007 return ;1008 }1009

1010 $fits->read_key(TULONG,"TZERO$index",$tzeroval,$comm,$status);1011 if ($status == KEY_NO_EXIST ) {1012 $tzeroval = -1;1013 $status = 0;

46 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

1014 }1015

1016 my $tscal = 1;1017

1018 $fits->read_key(TINT,"TSCAL$index",$tscal,$comm,$status);1019 if ($status == KEY_NO_EXIST ) {1020 $tscal = 1;1021 $status = 0;1022 }1023

1024 if ($type == TINT) {1025 if (($tscal == 1) &&($tzeroval == 32768)) {1026 $type = TUINT;1027 }1028 }1029 if ($type == TLONG) {1030 if (($tscal == 1) &&($tzeroval == 2147483648 )) {1031 $type = TULONG;1032 }1033 }1034

1035 # print "Column name: $col->{name} index: $index type: $type (numero righe: $count)\n";1036 # print TDOUBLE . " " . TSHORT . "\n";1037 $fits->read_col($type,$index, 1, 1, $count, $null,$col->{data}, $nulls, $status);1038 if ($status) {1039 &PrntChty(2,"Task{stem}: Error: LoadBinTable: unable to read column: '$col->{name}'\n");1040 &PrntChty(2,"Task{stem}: Error: LoadBinTable: from file: $filefits\n");1041 $Task{status} = 1;1042 return ;1043 }1044

1045 }1046

1047 $fits->close_file($status);1048

1049 # convert from parallel arrays to array of keyed structs1050 my @table = ();1051 for (my $i = 0; $i < $count; ++$i) {1052 my %record;1053 foreach my $col (@columns) {1054 $record{$col->{name}} = $col->{data}[$i];1055 }1056

1057

1058 push(@table, \%record);1059 }1060

1061 return @table;1062

1063 } # LoadBinTable1064

1065 sub SetGtiFileName {1066

1067 # The subroutine returns the GTI file name following1068 # standard neming convention1069

1070 my ( $evtfile, $outdir ) = @_;1071 use vars qw ( %Task %Def );

11.1. Perl Subroutines from HEASoft 47

Learn GRB Data Analysis in 3 Days, Release 0.9.9

1072

1073 # Cut off event file extension and path1074 my ($InStem) = &GetFileNameRoot ( $evtfile );1075 if ( length($InStem) == $Def{LEV2LEN} ) {1076 $InStem = substr($InStem,0,$Def{LEV2STARPOINT});1077 }1078

1079 my ($gtifile) = "$outdir/$InStem$Def{GTIFILESTEM}.fits";1080

1081 return $gtifile;1082

1083 } # SetGtiFileName1084

1085 sub GetPfilesName {1086

1087 use vars qw ( %Task);1088

1089 my ($file1,$file2);1090 my $filename = $Task{name} . ".par";1091

1092 if ($ENV{PFILES} eq "") {1093 &PrntChty(2,"$Task{stem}: Error: GetPfilesName: PFILES environment variable not found\n");1094 $Task{errmess} ="PFILES environment variable not found";1095 $Task{status} = 1;1096 return;1097 }1098

1099 my @path = split(/[;:]/,$ENV{PFILES});1100

1101 $file1 = $path[0] . "/" . $filename;1102

1103 if (($#path>0) && ($ENV{PFCLOBBER}==1)) {1104 for (my $i = 1; $i <= $#path; $i++) {1105 $file2 = $path[$i] . "/" . $filename;1106 if ( -f $file2 ) {1107 if ((stat($file2))[10] > (stat($file1))[10]) {1108 if (!copy ($file2,$file1)) {1109 &PrntChty(2,"$Task{stem}: Error: GetPfilesName: Cannot copy parameter file $file2 into $file1\n");1110 $Task{errmess} ="Cannot copy parameter file $file2 into $file1";1111 $Task{status} = 1;1112 return;1113 }1114 }1115 }1116 }1117 }1118

1119

1120 if (! -f $file1) {1121 &PrntChty(2,"$Task{stem}: Error: GetPfilesName: Parameter file $file1 not found \n");1122 $Task{errmess} ="Parameter file '$file1' not found";1123 $Task{status} = 1;1124 return;1125 }1126

1127 return $file1;1128

1129 } # GetPfilesName

48 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

1130

1131

1132 sub GetParameterList {1133 use vars(%Task);1134

1135 my $pfile = &GetPfilesName();1136 if ($Task{status}) {1137 &PrntChty(2,"$Task{stem}: Error: GetParameterList: Cannot get parameter file name\n");1138 return;1139 }1140

1141 if (!open(FILEPAR,$pfile)) {1142 $Task{errmess} = "Cannot open input parameter file ($pfile)";1143 $Task{status} = 1;1144 return;1145 }1146

1147 my @arr_par;1148 my $i = 0;1149 my %keyind;1150 while (<FILEPAR>) {1151 chomp();1152

1153 if (! ($_ =~ /^#/)) {1154

1155 my ($name,$type,$mode,$defvalue,$minval,$maxval,$description) = split(",");1156

1157 my %hash;1158

1159 $defvalue =~ s/^\s+//; # remove leading spaces1160 $defvalue =~ s/\s+$//; # remove trailing spaces1161 $defvalue =~ s/^"//g;; #Remove apex1162 $defvalue =~ s/"$//g;; #Remove apex1163

1164

1165 $hash{name} = $name;1166 $hash{defval} = $defvalue;1167 #if ($type eq "h") {1168 $hash{val} = $defvalue;1169 # } else {1170 # $hash{val} = "DEFAULT";1171 # }1172 $hash{set} = 0;1173 $hash{type} = $type;1174 $hash{maxval} = $maxval;1175 $hash{minval} = $minval;1176

1177 #$arr_par[$i] = \%hash;1178

1179 push (@arr_par,\%hash);1180

1181 $keyind{$name} = $i;1182

1183 $i++;1184 }1185 }1186

1187 close FILEPAR;

11.1. Perl Subroutines from HEASoft 49

Learn GRB Data Analysis in 3 Days, Release 0.9.9

1188

1189 return (\%keyind , @arr_par);1190

1191 } # GetParameterList1192

1193

1194 sub LoadParameterFromCmdLine {1195

1196 my (@ARGV) = @_;1197

1198 use vars qw(@Par %Ind);1199

1200 my ( $name, $value, $p);1201

1202

1203 if ($#Par < 0) {1204 &PrntChty(2,"$Task{stem}: Error: LoadParameterFromCmdLine: List of input parameter is empty \n");1205 $Task{errmess} ="LoadParameterFromCmdLine the List of input parameters is empty";1206 $Task{status} = 0;1207 return 0;1208

1209 }1210

1211

1212 foreach $p (@ARGV) {1213

1214 ($name,$value) = split("=",$p);1215

1216 if (! exists($Ind{$name})) {1217 &PrntChty(2,"$Task{stem}: Error: parsing input parameter '$name'\n");1218 &PrntChty(2,"$Task{stem}: Error: Parameter name '$name' not found or sintax error\n");1219 &PrntChty(2,"$Task{stem}: Error: Please specify parameters with format: <parametername>=<parametervalue>\n");1220 &PrntChty(2,"$Task{stem}: Error: without blanks\n");1221 &PrntChty(2,"$Task{stem}: Error: Type 'fhelp $Task{name}' for more information on parameters\n");1222 return 0;1223 } else {1224

1225 my $v = GetInputParam ($p);1226

1227 if (($Par[$Ind{$name}]->{type} eq "r") || ($Par[$Ind{$name}]->{type} eq "i")) {1228 if (($Par[$Ind{$name}]->{minval} ne "") && ($Par[$Ind{$name}]->{maxval} ne "")) {1229

1230 if (($v < $Par[$Ind{$name}]->{minval}) || ($v > $Par[$Ind{$name}]->{maxval})) {1231 &PrntChty(2,"$Task{stem}: Error: parsing input parameter '$name'\n");1232 &PrntChty(2,"$Task{stem}: Error: Value is out of range minvalue=$Par[$Ind{$name}]->{minval} maxvalue=$Par[$Ind{$name}]->{maxval}\n");1233 $Task{errmess} = "LoadParameterFromCmdLine: Parameter $name value is out of range";1234 $Task{status} = 0;1235 return 0;1236 }1237 }1238 }1239

1240 $Par[$Ind{$name}]->{val} = $v;1241 if ($Task{status}) { return 0;}1242

1243 $Par[$Ind{$name}]->{set} = 1;1244 }1245

50 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

1246 }1247

1248 return 1;1249

1250 } # LoadParameterFromCmdLine1251

1252 sub LoadParameter {1253

1254

1255 use vars qw(@Par %Ind %Task);1256

1257 my ($val, $p);1258

1259 foreach $p (@Par ) {1260 if ( &RequestParameter($p->{name})) {1261 $val = "";1262 if ($p->{set} == 0) {1263 chop($val = `pquery2 $Task{name} $p->{name}`);1264 $p->{set} = 2;1265 #if ( !$val && $val != 0) {1266 if ($val eq "") {1267 &PrntChty(2,"$Task{stem}: Error: LoadParameter: Running 'pquery2 $Task{name} $p->{name}'\n");1268 $Task{errmess} ="Running 'pquery2 $Task{name} $p->{name}'";1269 $Task{status} = 1;1270 return 0;1271 }1272 else { $p->{val} = $val;}1273 }1274 }1275 }1276

1277 #Reset string of message populate from RequestParameter in case of error1278 $Task{errmess} = "";1279 return 1;1280

1281 } # LoadParameter1282

1283

1284 sub GetValPar {1285

1286 my ( $parname , $pos) = @_;1287

1288 use vars qw(@Par %Ind %Task);1289

1290 my $p;1291

1292 if ( !defined($pos) ) { $p = "val";}1293 else {$p = $pos;}1294

1295 if ( $p eq "val" && !defined($Ind{$parname}) ) {1296 $Task{status} = 1;1297 $Task{errmess} = "Parameter '$parname' not found in the input parameter file";1298 &PrntChty(2,"$Task{stem}: Error: GetValPar: $Task{errmess}\n");1299 return;1300 }1301

1302 return $Par[$Ind{$parname}]->{$p};1303

11.1. Perl Subroutines from HEASoft 51

Learn GRB Data Analysis in 3 Days, Release 0.9.9

1304 } # GetValPar1305

1306 sub SetValPar {1307

1308 my ( $parname , $val,$col) = @_;1309

1310 use vars qw(@Par %Ind %Task);1311

1312 my $pos;1313

1314 if ( !defined($col) ) { $pos = "val";}1315 else {$pos = $col;}1316

1317 my $name = exists($Ind{$parname});1318

1319 if ($name) {1320 $Par[$Ind{$parname}]->{$pos} = $val;1321 } else {1322 $Task{status} = 1;1323 $Task{errmess} = "Parameter $parname not found";1324 }1325 } # SetValPar1326

1327

1328 sub getHistoryTime {1329

1330 my @f = localtime();1331

1332 my $s = sprintf("%04d-%02d-%02dT%02d:%02d:%02d",$f[5]+1900,$f[4]+1,@f[3,2,1,0]);1333

1334 return $s;1335

1336 } # getHistoryTime1337

1338

1339 # Write History Parameter List1340 # hdunum < 0 to write in all extension1341

1342 sub write_history {1343

1344 my ($filename,$hdunum,$hist) = @_;1345

1346 use vars qw (%Task);1347

1348 my ($p,$start);1349

1350 if ( &GetValPar("history") =~ /no/i) {1351 return 0;1352 }1353

1354

1355 if (&IsCompressed($filename)) {1356 &PrntChty(2,"$Task{stem}: Error: write_history: Cannot write history into a compressed file (file : $filename)\n");1357 $Task{status} = 1;1358 return 1;1359 }1360

1361 my $status = 0;

52 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

1362 my $fits = Astro::FITS::CFITSIO::open_file($filename, READWRITE, $status);1363 if (not $fits) {1364 &PrntChty(2,"$Task{stem}: Error: write_history: Unable to open '$filename' file\n");1365 $Task{status} = 1;1366 return 1;1367 }1368

1369

1370 if ($hdunum < 0) {1371 $start = 1;1372 $fits->get_num_hdus($hdunum,$status);1373 if ( $status ) {1374 &PrntChty(2,"$Task{stem}: Error: write_history: unable to get the number of HDUs\n");1375 &PrntChty(2,"$Task{stem}: Error: write_history: of '$filename' file\n");1376 $Task{status} = 1;1377 $fits->close_file($status);1378 return 1;1379 }1380 } else {1381 $start = $hdunum;1382 }1383

1384

1385 for (my $ind = $start; $ind<=$hdunum; $ind++) {1386

1387 $fits->movabs_hdu($ind,undef,$status);1388 if ($status) {1389 $Task{errmess} = "Running movabs_hdu (num $ind) on $filename";1390 &PrntChty(2,"$Task{stem}: Error: write_history: $Task{errmess}\n");1391 return 1;1392 }1393

1394 $fits->write_history($hist,$status);1395 if ($status) {1396 $Task{errmess} = "Running write_history (num $ind) on $filename";1397 &PrntChty(2,"$Task{stem}: Error: write_history: $Task{errmess}\n");1398 return 1;1399 }1400

1401 $fits->write_chksum($status);1402 if ($status) {1403 $Task{errmess} = "Running write_chksum (num $ind) on $filename";1404 &PrntChty(2,"$Task{stem}: Error: write_history: $Task{errmess}\n");1405 $Task{status} = 1;1406 return 1;1407 }1408

1409 }1410

1411 $fits->close_file($status);1412

1413 return 0;1414

1415 } # write_history1416

1417

1418

1419 #Write History Parameter List

11.1. Perl Subroutines from HEASoft 53

Learn GRB Data Analysis in 3 Days, Release 0.9.9

1420 # hdunum < 0 to write in all extension1421

1422 sub WriteParameterList {1423 my ($filename,$hdunum,@list) = @_;1424

1425 use vars qw (%Task);1426

1427 my ($start);1428

1429

1430 if ( &GetValPar("history") =~ /no/i) {1431 return 0;1432 }1433

1434 if (&IsCompressed($filename)) {1435 &PrntChty(2,"$Task{stem}: Error: WriteParameterList: Cannot write history into a compressed file (file : $filename)\n");1436 $Task{status} = 1;1437 $Task{errmess} = "Cannot write history into a compressed file (file : $filename)";1438 return 1;1439 }1440

1441 my $status = 0;1442 my $fits = Astro::FITS::CFITSIO::open_file($filename, READWRITE, $status);1443 if (not $fits) {1444 &PrntChty(2,"$Task{stem}: Error: WriteParameterList: Unable to open '$filename' file\n");1445 $Task{status} = 1;1446 return 1;1447 }1448

1449

1450 if ($hdunum < 0) {1451 $start = 1;1452 $fits->get_num_hdus($hdunum,$status);1453 if ( $status ) {1454 &PrntChty(2,"$Task{stem}: Error: WriteParameterList: unable to get the number of HDUs\n");1455 &PrntChty(2,"$Task{stem}: Error: WriteParameterList: of '$filename' file\n");1456 $Task{status} = 1;1457 $fits->close_file($status);1458 return;1459 }1460 } else {1461 $start = $hdunum;1462 }1463

1464

1465 for (my $ind = $start; $ind<=$hdunum; $ind++) {1466

1467 $fits->movabs_hdu($ind,undef,$status);1468 if ($status) {1469 &PrntChty(2, "$Task{stem}: Error: WriteParameterList: Running 'fits->movabs_hdu' (num $ind) on $filename\n");1470 $Task{errmess} = "Running movabs_hdu (num $ind) on $filename";1471 $Task{status} = 1;1472 return 1;1473 }1474

1475 my $p;1476

1477 $fits->write_history(" ",$status);

54 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

1478 $fits->write_history("START PARAMETER list for $Task{stem} at " . &getHistoryTime(),$status);1479 $fits->write_history(" ",$status);1480

1481

1482

1483 my $numpar = 0;1484

1485 foreach $p (@list) {1486 $numpar++;1487 &WriteParHistory($fits,"P" . $numpar . " ",$p->{name} . " = " . $p->{val},\$status);1488 #$fits->write_history($p->{name} . " = " . $p->{val},$status);1489 if ($status) {1490 &PrntChty(2, "$Task{stem}: Error: Running: 'fits->write_history' on $filename\n");1491 $Task{errmess} ="Error running write_history on $filename";1492 $Task{status} = 1;1493 return 1;1494 }1495 }1496 $fits->write_history(" ",$status);1497

1498 $fits->write_history("END PARAMETER list for $Task{stem}",$status);1499

1500

1501

1502 $fits->write_chksum($status);1503 if ($status) {1504 $Task{errmess} = "Running write_chksum (num $ind) on $filename";1505 &PrntChty(2,"$Task{stem}: Error: $Task{errmess}\n");1506 $Task{status} = 1;1507 return 0;1508 }1509

1510

1511 }1512

1513 $fits->close_file($status);1514

1515 return 0;1516 } # WriteParameterList1517

1518

1519

1520 sub WriteParHistory {1521 my ($filefits,$head,$str,$status) = @_;1522

1523 my ($len,$part,$beg,$end,@liststr);1524

1525 my $const = "HISTORY ";1526

1527 $part = 80 - length($const) - length($head);1528 $beg = 0;1529 $end = $part;1530

1531 while ($beg < length($str)) {1532 push @liststr, substr($str,$beg,$end);1533 $beg +=$part;1534 }1535

11.1. Perl Subroutines from HEASoft 55

Learn GRB Data Analysis in 3 Days, Release 0.9.9

1536 for (my $i = 0; $i <= $#liststr; $i++) {1537 $filefits->write_history("$head" . "$liststr[$i]",$$status);1538 }1539

1540

1541 } # WriteParHistory1542

1543 sub UpdateCheckSum {1544

1545 my ($file) = @_;1546

1547 my $status = 0;1548 my $fits = Astro::FITS::CFITSIO::open_file($file, READWRITE, $status);1549

1550 my $hdunum;1551

1552 $fits->get_num_hdus($hdunum,$status);1553 if ( $status ) {1554 &PrntChty(2,"$Task{stem}: Error: UpdateCheckSum: unable to get the number of HDUs\n");1555 &PrntChty(2,"$Task{stem}: Error: UpdateCheckSum: of '$file' file\n");1556 $Task{status} = 1;1557 $fits->close_file($status);1558 return;1559 }1560

1561 for (my $ind = 1; $ind<=$hdunum; $ind++) {1562

1563 $fits->movabs_hdu($ind,undef,$status);1564 if ($status) {1565 $Task{errmess} = "Running movabs_hdu (num $ind) on $file";1566 &PrntChty(2,"$Task{stem}: Error: UpdateCheckSum: $Task{errmess}\n");1567 $Task{status} = 1;1568 return 0;1569 }1570

1571

1572 $fits->write_chksum($status);1573 if ($status) {1574 $Task{errmess} = "Running write_chksum (num $ind) on $file";1575 &PrntChty(2,"$Task{stem}: Error: UpdateCheckSum: $Task{errmess}\n");1576 $Task{status} = 1;1577 return 0;1578 }1579

1580 }1581

1582 $fits->close_file($status);1583 return 1;1584

1585 } # UpdateCheckSum1586

1587

1588 sub IsNumeric {1589 my $InputString = shift;1590

1591 if ($InputString !~ /^([-|+])?[0-9]*([.|,]([0-9]*))?((e|E)([-|+])?[0-9]+)?$/) {1592 return 0;1593 }

56 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

1594 else {1595 return 1;1596 }1597 }1598

1599

1600 sub CheckRa {1601

1602 my ($type,$str) = @_;1603

1604 use vars qw(%Task);1605

1606 my (@l, $hh, $mm, $ss, $rag) ;1607

1608 &PrntChty(3,"CheckRa : Info: CheckRa: Performing check on RA '$str' string\n");1609

1610

1611 (@l) = split(" ",$str);1612

1613 if (&trimValue($str) eq "") {1614 $Task{errmess} = "Invalid $type sintax. Please specify $type with format 'hh mm ss.s' or 'xx.xx'(deg)";1615 $Task{status} = 1;1616 return 0;1617 }1618

1619

1620 for (my $ind =0; $ind <=$#l; $ind++) {1621 if (! &IsNumeric($l[$ind])) {1622 $Task{errmess} = "Invalid $type sintax. Please specify $type with format 'hh mm ss.s' or 'xx.xx'(deg)";1623 $Task{status} = 1;1624 return 0;1625 }1626 }1627

1628 if ($#l == 0) {1629 $rag = $l[0];1630 }1631 else {1632 if ($#l >= 3) {1633 $Task{errmess} = "Invalid $type sintax. Please specify $type with format 'hh mm ss.s' or 'xx.xx'(deg)";1634 $Task{status} = 1;1635 return 0;1636 }1637

1638 $hh = $l[0];1639 $mm = $l[1]+0;1640 $ss = $l[2]+0;1641

1642 if (($hh < 0) || ($hh > 23)) {1643 $Task{errmess} = "Invalid $type range. Please check $type input";1644 $Task{status} = 1;1645 return 0;1646 }1647

1648

1649 if (($mm < 0) || ($mm > 59)) {1650 $Task{errmess} = "Invalid $type range. Please check $type input";1651 $Task{status} = 1;

11.1. Perl Subroutines from HEASoft 57

Learn GRB Data Analysis in 3 Days, Release 0.9.9

1652 return 0;1653 }1654

1655 if (($ss < 0) || ($ss > 59.9)) {1656 $Task{errmess} = "Invalid $type range. Please check $type input";1657 $Task{status} = 1;1658 return 0;1659 }1660

1661

1662 $rag = &Ra2Deg($str);1663

1664 }1665

1666 if (($rag < 0) || ($rag > 360)) {1667 $Task{errmess} = "Invalid $type range. Please check $type input";1668 $Task{status} = 1;1669 return 0;1670 }1671

1672 return 1;1673 } # CheckRa1674

1675 sub CheckDec {1676

1677 my ($type,$str) = @_;1678

1679 use vars qw(%Task);1680

1681 my ($dd,$mm,$ss,@l,$deg) ;1682

1683 &PrntChty(3,"CheckDec: Info: CheckDec: Performing check on DEC '$str' string\n");1684

1685 if (&trimValue($str) eq "") {1686 $Task{errmess} = "Invalid $type sintax. Please specify $type with format 'dd mm ss.s' or 'xx.xx'(deg)";1687 $Task{status} = 1;1688 return 0;1689 }1690

1691

1692 (@l) = split(" ",$str);1693

1694 for (my $ind =0; $ind <=$#l; $ind++) {1695 if (! &IsNumeric($l[$ind])) {1696 $Task{errmess} = "Invalid $type sintax. Please specify $type with format 'dd mm ss.s' or 'xx.xx'(deg)";1697 $Task{status} = 1;1698 return 0;1699 }1700 }1701

1702

1703 if ($#l == 0) {1704 $deg = $l[0];1705 }1706 else {1707 if ($#l >= 3) {1708 $Task{errmess} = "Invalid $type sintax. Please specify $type with format 'dd mm ss.s' or 'xx.xx'(deg)";1709 $Task{status} = 1;

58 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

1710 return 0;1711 }1712

1713 $dd = $l[0];1714 $mm = $l[1]+0;1715 $ss = $l[2]+0;1716

1717 my $neg = 0;1718

1719 if ($str =~ /^\-/) {1720 $neg = 1;1721 $dd = 0 - $dd;1722 }1723

1724 if (($dd < -90) || ($dd > 90)) {1725 $Task{errmess} = "Invalid $type range. Please check $type input";1726 $Task{status} = 1;1727 return 0;1728 }1729

1730

1731 if (($mm < 0) || ($mm > 59)) {1732 $Task{errmess} = "Invalid $type range. Please check $type input";1733 $Task{status} = 1;1734 return 0;1735 }1736

1737 if (($ss < 0) || ($ss > 59.9)) {1738 $Task{errmess} = "Invalid $type range. Please check $type input";1739 $Task{status} = 1;1740 return 0;1741 }1742

1743

1744 $deg = &Dec2Deg($str);1745 if ($neg) { $deg = 0 - $deg;}1746

1747 }1748 if (($deg < -90) || ($deg > 90)) {1749 $Task{errmess} = "Invalid $type range. Please check $type input";1750 $Task{status} = 1;1751 return 0;1752 }1753

1754 return 1;1755

1756 } # CheckDec1757

1758

1759 sub Ra2Deg {1760

1761 my ($str) = @_;1762

1763 use vars qw(%Task);1764

1765 my ($hh,$mm,$ss,@l,$result) ;1766

1767 (@l) = split(" ",$str);

11.1. Perl Subroutines from HEASoft 59

Learn GRB Data Analysis in 3 Days, Release 0.9.9

1768 if ($#l == 0) {1769 $result = $l[0];1770 }1771 else {1772

1773 $hh = $l[0];1774 $mm = $l[1]+0;1775 $ss = $l[2]+0;1776

1777 if ($hh =~ /^-/) { $mm *=-1;$ss*=-1;}1778

1779 $result = $hh*15 + ($mm*15/60) + ($ss*15/3600);1780 }1781

1782 return $result;1783

1784

1785 } # Ra2Deg1786

1787

1788

1789 sub Dec2Deg {1790

1791 my ($str) = @_;1792

1793 use vars qw(%Task);1794

1795 my ($dd,$mm,$ss,@l,$result) ;1796

1797

1798 ($dd,$mm,$ss) = split(" ",$str);1799

1800 (@l) = split(" ",$str);1801 if ($#l == 0) {1802 $result = $l[0];1803 }1804 else {1805

1806 $dd = $l[0];1807 $mm = $l[1]+0;1808 $ss = $l[2]+0;1809

1810 if ($dd =~ /^-/) { $mm *=-1;$ss*=-1;}1811

1812 $result = $dd + ($mm/60) + ($ss/3600);1813 }1814

1815 return $result;1816

1817

1818 } # Dec2Deg1819

1820 sub RaDec2XY {1821

1822 my ($file,$ra,$dec,$x,$y) = @_;1823

1824 use vars qw($PI $datamode);1825

60 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

1826 my ($xsize,$ysize,$radian,$roll2,$gamma1,$ximh,$yimh,$dera,$derar,$decr,$decnomr,$rar,$rarnomr,1827 $ralde,$ranom,$decnom,$ranomr,$aixnor,$aiynor,$pixelsize,$aix,$aiy,$numcolx,$numcoly, $roll);1828

1829

1830

1831 &PrntChty(3,"$Task{'stem'}: Info: RaDec2XY: Converting ra: $ra deg and dec: $dec deg into x,y pixel\n");1832

1833

1834 my ($fptr,$status,$comm) = (0, 0);1835 fits_open_file($fptr,$file,READONLY,$status);1836 if ($status) {1837 $Task{status} = 1;1838 $Task{errmess} = "Unable to open fits file : $file";1839 return 0;1840 }1841

1842 fits_movnam_hdu($fptr,ANY_HDU,"EVENTS",0,$status);1843 if ($status) {1844 $Task{status} = 1;1845 $Task{errmess} = "Cannot move into EVENTS extension in '$file' file";1846 fits_close_file($fptr,$status);1847 return 0;1848 }1849

1850 fits_get_colnum($fptr,0,"X",$numcolx,$status);1851 if ($status) {1852 $Task{status} = 1;1853 $Task{errmess} = "Column X not found in '$file' file";1854 fits_close_file($fptr,$status);1855 return 0;1856 }1857 fits_get_colnum($fptr,0,"Y",$numcoly,$status);1858 if ($status) {1859 $Task{status} = 1;1860 $Task{errmess} = "Column Y not found in '$file' file";1861 fits_close_file($fptr,$status);1862 return 0;1863 }1864

1865 fits_read_keyword($fptr,"TCRVL" . $numcolx,$ranom,$comm,$status);1866 if ( $status) {1867 $Task{status} = 1;1868 $Task{errmess} = "Keyword TCRVL$numcolx not found in '$file' file";1869 fits_close_file($fptr,$status);1870 return 0;1871 }1872 fits_read_keyword($fptr,"TCRVL" . $numcoly,$decnom,$comm,$status);1873 if ( $status) {1874 $Task{status} = 1;1875 $Task{errmess} = "Keyword TCRVL$numcolx not found in '$file' file";1876 fits_close_file($fptr,$status);1877 return 0;1878 }1879

1880 fits_read_keyword($fptr,"TCDLT" . $numcolx,$pixelsize,$comm,$status);1881 if ( $status) {1882 $Task{status} = 1;1883 $Task{errmess} = "Keyword TCRVL$numcolx not found in '$file' file";

11.1. Perl Subroutines from HEASoft 61

Learn GRB Data Analysis in 3 Days, Release 0.9.9

1884 fits_close_file($fptr,$status);1885 return 0;1886 }1887 fits_close_file($fptr,$status);1888

1889 $xsize = 1000;1890 $ysize = 1000;1891

1892 $radian = 180 / $PI;1893

1894 $roll = 270;1895

1896 $roll2 = -$roll + 270;1897 $gamma1 = -$roll2/$radian;1898

1899 $ximh = $xsize/2 + 0.5;1900 $yimh = $ysize/2 + 0.5;1901 $dera = $ranom - $ra;1902

1903 if ($dera < -300) {1904 $dera = $ranom + 360 - $ra;1905 }1906 $derar = $dera/$radian;1907 $decr = $dec/$radian;1908 $decnomr= $decnom/$radian;1909 $rar=$ra/$radian;1910 $ranomr=$ranom/$radian;1911

1912 $ralde=acos((sin($decr)*sin($decnomr))+(cos($decr)*cos($decnomr)*cos($derar)));1913

1914 $aixnor=0.0;1915 $aiynor=0.0;1916 if($ralde !=0) {1917 $aixnor = $ralde/sin($ralde)*$radian/-$pixelsize*cos($decr)*sin($derar);1918 $aiynor = $ralde/sin($ralde)*$radian/-$pixelsize*(sin($decr)*cos($decnomr)- cos($decr)*sin($decnomr)*cos($derar));1919 }1920

1921 $aix = $aixnor*cos($gamma1) - $aiynor*sin($gamma1) + $ximh;1922 $aiy = $aiynor*cos($gamma1) - $aixnor*sin($gamma1) + $yimh;1923

1924 $$x = $aix;1925 $$y = $aiy;1926

1927 &PrntChty(3,"$Task{'stem'}: Info: RaDec2XY: Calculated x: ${aix}pixel and y: ${aiy}pixel\n");1928

1929 if (($aix < 0) || ($aix > 1000)) {1930 $Task{errmess} = "Sky X coordinate out of range (0,1000)";1931 return 0;1932 }1933

1934 if (($aiy < 0) || ($aiy > 1000)) {1935 $Task{errmess} = "Sky Y coordinate out of range (0,1000)";1936 return 0;1937 }1938 return 1;1939 } # RaDec2XY1940

1941

62 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

1942

1943 #When chkval is not defined1944 #Check if value is different from 0 and TNULL value (if TNULL value is not exist1945 # default value is -1)1946

1947 sub CheckCol {1948

1949 my ($filename,$extname,$colname,$chkval,$maxval,$minval) = @_;1950

1951 use vars qw (%Task);1952

1953 my ($fptr,$status) = (0, 0);1954 fits_open_file($fptr,$filename,READONLY,$status);1955 if ($status) {1956 $Task{status} = 1;1957 &PrntChty(2,"$Task{stem}: Error: CheckCol: Cannot open file: $filename\n");1958 &PrntChty(2,"$Task{stem}: Error: CheckCol: CFITSIO error: $status\n");1959 $Task{errmess} = "Unable to open fits file : $filename";1960 return 0;1961 }1962 fits_movnam_hdu($fptr,ANY_HDU,$extname,0,$status);1963 if ($status) {1964 $Task{status} = 1;1965 &PrntChty(2,"$Task{stem}: Error: CheckCol: Cannot move to extension name $extname in file $filename\n");1966 &PrntChty(2,"$Task{stem}: Error: CheckCol: CFITSIO error: $status\n");1967 $Task{errmess} = "Error: Cannot move to extension name $extname in file $filename";1968 fits_close_file($fptr,$status);1969 return 0;1970 }1971

1972 my $chk = &CheckColPtr($fptr,$colname,$chkval,$maxval,$minval);1973

1974 fits_close_file($fptr,$status);1975

1976 return $chk;1977

1978 }#CheckCol1979

1980 sub CheckColPtr {1981

1982 my ($fptr,$colname,$chkval,$maxval,$minval) = @_;1983

1984 my ($numcol,$type,$repeat,$width,@column,$nulls,$tzeroval,$comm);1985

1986 use vars (%Task);1987

1988 $nulls = -1;1989

1990 my $max = -9999999;1991 my $min = 9999999;1992

1993

1994 my $count = -1;1995 my $status = 0;1996 fits_get_num_rows($fptr,$count, $status);1997 if ($status) {1998 &PrntChty(2,"$Task{stem}: Error: CheckColPtr: Cannot get the Fits File number of rows\n");1999 &PrntChty(2,"$Task{stem}: Error: CheckColPtr: CFITSIO error: $status\n");

11.1. Perl Subroutines from HEASoft 63

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2000 $Task{errmess} = "Getting number rows";2001 $Task{status} = 1;2002 return 0;2003 }2004

2005 fits_get_colnum($fptr,0,$colname,$numcol,$status);2006 if ($status) {2007 &PrntChty(2,"$Task{stem}: Error: CheckColPtr: Cannot get the '$colname' column number\n");2008 &PrntChty(2,"$Task{stem}: Error: CheckColPtr: CFITSIO error: $status\n");2009 $Task{status} = 1;2010 $Task{errmess} = "Column $colname not found";2011 return 0;2012 }2013

2014

2015 fits_read_key($fptr,TULONG,"TZERO$numcol",$tzeroval,$comm,$status);2016 if ($status == KEY_NO_EXIST ) {2017 $tzeroval = -1;2018 $status = 0;2019 } elsif ($status) {2020 $Task{status} = 1;2021 &PrntChty(2,"$Task{stem}: Error: CheckColPtr: Cannot read the 'TZERO$numcol' keyword\n");2022 &PrntChty(2,"$Task{stem}: Error: CheckColPtr: CFITSIO error: $status\n");2023 $Task{errmess} = "Error reading keyword TZERO$numcol unexpected error";2024 return 0;2025 }2026

2027

2028 my $tscal = 1;2029

2030 fits_get_coltype($fptr,$numcol,$type,$repeat,$width,$status);2031

2032 fits_read_key($fptr,TINT,"TSCAL$numcol",$tscal,$comm,$status);2033 if ($status == KEY_NO_EXIST ) {2034 $tscal = 1;2035 $status = 0;2036 } elsif ($status) {2037 $Task{status} = 1;2038 &PrntChty(2,"$Task{stem}: Error: CheckColPtr: Cannot read the 'TSCAL$numcol' keyword\n");2039 &PrntChty(2,"$Task{stem}: Error: CheckColPtr: CFITSIO error: $status\n");2040 $Task{errmess} = "Error reading keyword TSCAL$numcol unexpected error";2041 return 0;2042 }2043

2044

2045 my $nullval = 0;2046

2047 if (!defined($chkval)) {2048

2049 fits_read_key($fptr,TINT,"TNULL$numcol",$nullval,$comm,$status);2050 if ($status == KEY_NO_EXIST ) {2051 $nullval = -1;2052 $status = 0;2053 }2054

2055 }2056

2057 if ($type == TINT) {

64 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2058 if (($tscal == 1) &&($tzeroval == 32768)) {2059 $type = TUINT;2060 }2061 }2062 if ($type == TLONG) {2063 if (($tscal == 1) &&($tzeroval == 2147483648 )) {2064 $type = TULONG;2065 }2066 }2067 my @nulls;2068

2069 fits_read_col($fptr,$type,$numcol, 1, 1, $count, 0,\@column,$nulls, $status);2070

2071 if ($status) {2072 &PrntChty(2,"$Task{stem}: Error: CheckColPtr: Cannot read column '$colname'\n");2073 &PrntChty(2,"$Task{stem}: Error: CheckColPtr: CFITSIO error: $status\n");2074 $Task{errmess} = "reading column: $colname file";2075 $Task{status} = 1;2076 return 0;2077 }2078

2079

2080 my $err = 0;2081 my $isnullval = 1;2082 my $iszero = 1;2083

2084 for (my $ind =0; $ind <= $#column; $ind++) {2085 if (defined($chkval)) {2086 if ($column[$ind] != $chkval) {2087 $err =1;2088 }2089 } else {2090 if (($column[$ind] != 0)) {2091 $iszero=0;2092 $err =1;2093 }2094 if (($column[$ind] != $nullval)) {2095 $isnullval=0;2096 $err =1;2097 }2098

2099 }2100 if ($column[$ind] > $max) { $max = $column[$ind];}2101 if ($column[$ind] < $min) { $min = $column[$ind];}2102 }2103

2104 if (defined($maxval)) {2105 $$maxval = $max;2106 }2107

2108 if (defined($minval)) {2109 $$minval = $min;2110 }2111

2112 if ( !defined($chkval) ) {2113 if ($isnullval) { $Task{status} = 2; return 1;}2114 elsif ($iszero){ $Task{status} = 1; return 1;}2115 }

11.1. Perl Subroutines from HEASoft 65

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2116

2117 if ($err) { return 0;}2118 return 1;2119

2120

2121 }# CheckColPtr2122

2123

2124 sub GetXspecChatter {2125

2126 # xspec chatter ranges from 0 to 252127

2128 my ( $TaskChat ) = @_;2129

2130 if ( $TaskChat < 3 ) { return 0; }2131 elsif ( $TaskChat <= 4 ) { return 5; }2132 else { return 10; }2133

2134 } # GetXspecChatte2135

2136 sub GetFitsPointer {2137

2138 # This routines returns the pointer to the2139 # fits fileextension or $pointer if2140 # defined2141

2142 my ($filename,$extname,$pointer,$mode) = @_;2143

2144 use vars qw (%Task);2145

2146 if (! defined($mode)) { $mode = READONLY;}2147

2148 my ($fptr,$status) = (0, 0);2149

2150 if (defined($pointer)) { $fptr = $pointer;}2151 else {2152

2153 fits_open_file($fptr,$filename,$mode,$status);2154 if ($status) {2155 $Task{status} = 1;2156 &PrntChty(2,"$Task{stem}: Error: GetFitsPointer: Cannot open fits file: $filename\n");2157 &PrntChty(2,"$Task{stem}: Error: GetFitsPointer: CFITSIO error: $status\n");2158 $Task{errmess} = "Unable to open fits file: $filename";2159 return;2160 }2161 }2162

2163 if (defined($extname)) {2164 fits_movnam_hdu($fptr,ANY_HDU,$extname,0,$status);2165 if ($status) {2166 $Task{status} = 1;2167 &PrntChty(2,"$Task{stem}: Error: GetFitsPointer: Cannot move to extension '$extname' of file '$filename'\n");2168 &PrntChty(2,"$Task{stem}: Error: GetFitsPointer: CFITSIO error: $status\n");2169 $Task{errmess} = "Cannot move into extension '$extname' of file '$filename'";2170 return;2171 }2172 }2173

66 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2174 return $fptr;2175

2176

2177

2178 }#GetFitsPointer2179

2180

2181 sub GetKeyword {2182

2183 # This subroutine returns the value of the "keyname"2184 # taken from the heder extension "extname" of the2185 # input "filename" or from the extension where the2186 # fits file pointer "pointer" is set2187 # FT 23/07/2004 - added $checkexist parameter to2188 # do not print a message if the2189 # keyword does not exist. If the2190 # key does not exist the subroutine2191 # returns the KEY_NO_EXIST code2192

2193 my ( $filename, $extname, $pointer, $keyname, $keyvalue, $checkexist ) = @_ ;2194

2195 use vars (%Task);2196

2197 my $fptr = &GetFitsPointer($filename,$extname,$pointer);2198 if ($Task{status}) {2199 $Task{errmess} = "Unable to open '$filename' file";2200 $Task{status} = 1;2201 return 1;2202 }2203

2204 my ($comm,$value,$str);2205 my $status = 0;2206 fits_read_keyword($fptr,$keyname,$value,$comm,$status);2207 if ($status) {2208 $Task{status} = $status;2209 if ( !($checkexist && $status==KEY_NO_EXIST) ) {2210 if (defined($filename)) { $str = "Error reading keyword $keyname in file $filename";}2211 else {$str= "Error reading keyword $keyname";}2212 &PrntChty(2,"$Task{stem}: Error: GetKeyword: FITSIO error: $status\n");2213 $Task{errmess} = $str;2214 fits_get_errstatus($status,$str);2215 &PrntChty(2,"$Task{stem}: Error: GetKeyword: FITSIO error: $str\n");2216 }2217 fits_close_file($fptr,$status);2218 return 1;2219 }2220

2221 $value =~ s/^\s+//; # remove leading spaces2222 $value =~ s/\s+$//; # remove trailing spaces2223 $value =~ s/^'//g;; #Remove apex2224 $value =~ s/'$//g;; #Remove apex2225 $value =~ s/\s+$//g;; #Remove right space2226

2227 $$keyvalue= $value;2228

2229

2230 if (defined($filename)) {2231 fits_close_file($fptr,$status);

11.1. Perl Subroutines from HEASoft 67

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2232 if ($status) {2233 $Task{status} = $status;2234 fits_get_errstatus($status,$str);;2235 $Task{errmess} = $str;2236 return 1;2237 }2238 }2239

2240 return 0;2241

2242 } #GetKeyword2243

2244

2245 sub trim { # (string) -> trimmed string2246 my $s=shift;2247 chomp($s); # get rid of \n2248 $s =~ s/^\s+//; # remove leading spaces2249 $s =~ s/\s+$//; # remove trailing spaces2250 return $s;2251 } # /sub2252

2253 sub GetEventStartDate {2254

2255 # This subroutine returns the observation Date and Time2256 # with the format needed for CALDB query2257 # The Observation Start date is taken from EVENTS2258 # extension for PC, WT, and PD modes (if exists..) and from the2259 # primary extension for IM mode2260

2261 my ( $evtfile, $date, $time ) = @_;2262

2263 my $mode = &GetEventDataMode ( $evtfile );2264 if ( $Task{status} ) { return; }2265

2266 my ( $extension );2267

2268 if ( $mode eq "pc" || $mode eq "pu" || $mode eq "wt" || $mode eq "lr" ) {2269

2270 my $numext = &GetNumExtName( $evtfile, "EVENTS" );2271

2272 if($numext > -1){2273 $extension = "EVENTS";2274 }2275 else{2276 $extension = undef;2277 }2278 }2279 elsif ( $mode eq "im" ) { $extension = undef; }2280 else {2281 &PrntChty(2,"$Task{stem}: Error: GetEventStartDate: Event File: '$evtfile'\n");2282 &PrntChty(2,"$Task{stem}: Error: GetEventStartDate: Data Mode '$mode' not supported\n");2283 $Task{errmess} = "Data Mode '$mode' not supported";2284 $Task{status} = 1;2285 return 1;2286 }2287

2288 &GetKeyword($evtfile,$extension,undef,"DATE-OBS",\$$date);2289 if ( $Task{status} ) {return 1;}

68 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2290

2291 my $Tstr = substr($$date,10,1);2292

2293 if ( $Tstr eq "T" ) {2294 $$time = substr($$date,11);2295 $$date = substr($$date,0,10);2296 }2297 else {2298 &GetKeyword($evtfile,$extension,undef,"TIME-OBS",\$$time);2299 if ( $Task{status} ) {return 1;}2300 }2301

2302 &PrntChty(4,"$Task{stem}: Info: GetEventStartDate: Obsevation start date: $$date $$time,\n");2303 &PrntChty(4,"$Task{stem}: Info: GetEventStartDate: from event file: $evtfile\n");2304

2305 return 0;2306

2307 } # GetEventStartDate2308

2309

2310 sub GetHdStartDate {2311

2312 # This subroutine returns the observation Date and Time2313 # with the format needed for CALDB query2314 # The Observation Start date is taken from FRAME2315 # extension in hd file2316

2317 my ( $hdfile, $date, $time ) = @_;2318

2319 &GetKeyword($hdfile,"FRAME",undef,"DATE-OBS",\$$date);2320 if ( $Task{status} ) {return 1;}2321

2322 my $Tstr = substr($$date,10,1);2323

2324 if ( $Tstr eq "T" ) {2325 $$time = substr($$date,11);2326 $$date = substr($$date,0,10);2327 }2328 else {2329 &GetKeyword($hdfile,"FRAME",undef,"TIME-OBS",\$$time);2330 if ( $Task{status} ) {return 1;}2331 }2332

2333 &PrntChty(4,"$Task{stem}: Info: GetHdStartDate: Obsevation start date: $$date $$time,\n");2334 &PrntChty(4,"$Task{stem}: Info: GetHdStartDate: from hd file: $hdfile\n");2335

2336 return 0;2337

2338 } # GetHdStartDate2339

2340

2341 sub RunCommandAndRedirectOutput {2342

2343 # This subroutine before performing a call to the 'system' using2344 # input 'command' redirects standard output in the2345 # ouput file2346

2347 my ( $command, $outfile ) = @_;

11.1. Perl Subroutines from HEASoft 69

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2348

2349 # dup STDOUT2350

2351 if ( ! open ( OLDSTDOUT, ">&STDOUT" ) ) {2352 &PrntChty(2, "$Task{stem}: Error: RunCommandAndRedirectOutput: Couldn't dup STDOUT: $!\n");2353 $Task{status} = 1;2354 return 1;2355 }2356

2357 # re-direct STDOUT to outfile2358

2359 if ( !open (STDOUT, ">> $outfile") ) {2360 &PrntChty(2, "$Task{stem}: Error: RunCommandAndRedirectOutput: Can't open $outfile: $!\n");2361 $Task{status} = 1;2362 return 1;2363 }2364

2365 my ( $ret ) = 0;2366 $ret = system ( $command );2367

2368 close STDOUT;2369

2370 # restore original STDOUT2371

2372 if ( ! open (STDOUT, ">&OLDSTDOUT") ) {2373 &PrntChty(2,"$Task{stem}: Error:RunCommandAndRedirectOutput: Can't restore STDOUT: $!\n");2374 $Task{status} = 1;2375 return 1;2376 }2377

2378 close OLDSTDOUT;2379

2380 if ( $ret ) {2381 &PrntChty(2,"$Task{stem}: Error: RunCommandAndRedirectOutput: 'system' exit with error: $ret\n");2382 $Task{message} = "'system' command error: $ret\n";2383 $Task{status} = 1;2384 return 1;2385 }2386

2387 return 0;2388

2389 }2390

2391 sub RenameFile {2392

2393 # Copy the $file1 into $file2 and delate2394 # the $file1. The function returns an error if the2395 # $file2 cannot be created but gives only a warning message if2396 # the $file1 cannot be removed2397

2398

2399 my ( $file1, $file2 ) = @_;2400

2401 if (!copy($file1, $file2)) {2402 $Task{status} = 1;2403 $Task{errmess} = "Unable to copy file: '$file1' in '$file2'. $!";2404 return 1;2405 }

70 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2406

2407 else {2408 if ( !unlink($file1) ) {2409 &PrntChty(2,"$Task{stem}: Warning: RenameFile: Unable to remove '$file1' file. $!\n");2410 }2411 }2412

2413 return 0;2414

2415 } #RenameFile2416

2417 sub ExecXimage2418 {2419 my ($param) = @_;2420

2421 my $line = "";2422 my $err = 0;2423 my $cmd = "ximage \"$param\"";2424

2425 &RunningSub("ExecXimage","ximage");2426 &RunningComm("ExecXimage",$cmd);2427 my $p = open(FILEH, "$cmd |");2428 if ($p)2429 {2430 while(<FILEH>)2431 {2432 &PrntChty(3,"$Task{stem}: ExecXimage: $_");2433 if ($_ =~ /^ Failed to execute startup command/)2434 {2435 $err = 1;2436 last;2437 }2438 }2439 $_ = "";2440 if (`uname` =~ /SunOS/)2441 {2442 my @pid = `ps -af|grep "ximage $param"\$|grep -v grep`;2443 $p = $pid[1];2444 }2445 kill 15, $p;2446 close(FILEH);2447 }2448 return $err;2449 }2450

2451

2452 sub GetPntFromExt {2453

2454 my ($filename,$extname,$extnum,$ra_pnt,$dec_pnt,$pa_pnt) = @_;2455

2456 if ( $pa_pnt ) {2457 &PrntChty(4,"$Task{stem}: Info: GetPntFromExt: Reading RA_PNT, DEC_PNT and PA_PNT Keywords\n");2458 }2459 else {2460 &PrntChty(4,"$Task{stem}: Info: GetPntFromExt: Reading RA_PNT and DEC_PNT Keywords\n");2461 }2462 &PrntChty(4,"$Task{stem}: Info: GetPntFromExt: from '$filename' file\n");2463

11.1. Perl Subroutines from HEASoft 71

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2464 &GetKeyword($filename,$extname,$extnum,"RA_PNT",$ra_pnt);2465 if ( $Task{status} ) { return 1; }2466

2467 &GetKeyword($filename,$extname,$extnum,"DEC_PNT",$dec_pnt);2468 if ( $Task{status} ) { return 1; }2469

2470 if ( $pa_pnt ) {2471 &GetKeyword($filename,$extname,$extnum,"PA_PNT",$pa_pnt);2472 if ( $Task{status} ) { return 1; }2473 }2474

2475 } # GetPntFromExt2476

2477 sub GetObjFromExt {2478

2479 my ($filename,$extname,$extnum,$ra_obj,$dec_obj) = @_;2480

2481 &PrntChty(4,"$Task{stem}: Info: GetObjFromExt: Reading RA_OBJ, DEC_OBJ and PA_OBJ Keywords\n");2482 &PrntChty(4,"$Task{stem}: Info: GetObjFromExt: from '$filename' file\n");2483

2484 &GetKeyword($filename,$extname,$extnum,"RA_OBJ",$ra_obj);2485 if ( $Task{status} ) { return 1; }2486

2487 &GetKeyword($filename,$extname,$extnum,"DEC_OBJ",$dec_obj);2488 if ( $Task{status} ) { return 1; }2489

2490 } # GetObjFromExt2491

2492 #Return a array with list of extension number where type of relative header is IMAGE_HDU2493 # and check if CTYPE1 =="RA--TAN" and CTYPE2= "DEC--TAN"2494 sub getArrayExtensionImage() {2495 my ($filename) = @_;2496

2497

2498 my($numext,$hdutype,@list,$value1,$value2,$comm);2499 my($fptr,$status)=(0,0);2500 fits_open_file($fptr,$filename,READONLY,$status);2501 if ($status) {2502 $Task{status} = 1;2503 $Task{errmess} = "Unable to open fits file : $filename";2504 return;2505 }2506

2507 fits_get_num_hdus($fptr,$numext,$status);2508 if ($status) {2509 $Task{status} =1;2510 $Task{errmess} = "Unable to get number of extensions from file : $filename";2511 fits_close_file($fptr,$status);2512 return;2513 }2514

2515 for (my $i = 1; $i < $numext; $i++) {2516 fits_movabs_hdu($fptr,$i+1,ANY_HDU,$status);2517 if ($status) {2518 $Task{errmess} = "Running movabs_hdu (num extension: " . $i+1 . ") in $filename";2519 &PrntChty(2,"$Task{stem}: Error: getArrayExtensionImage: $Task{errmess}\n");2520 $Task{status} = 1;2521 fits_close_file($fptr,$status);

72 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2522 return ;2523 }2524 fits_get_hdu_type($fptr,$hdutype,$status);2525 if ($status) {2526 $Task{status} =1;2527 $Task{errmess} = "Unable to get number of extensions from file : $filename";2528 fits_close_file($fptr,$status);2529 return;2530 }2531

2532

2533 if ($hdutype == IMAGE_HDU) {2534 fits_read_keyword($fptr,"CTYPE1",$value1,$comm,$status);2535 if ($status) {2536 fits_close_file($fptr,$status);2537 $Task{errmess} = "Running read_keyword CTYPE1 (num extension: $i) in $filename";2538 &PrntChty(2,"$Task{stem}: Error: getArrayExtensionImage: $Task{errmess}\n");2539 $Task{status} = 1;2540 fits_close_file($fptr,$status);2541 return ;2542 }2543 fits_read_keyword($fptr,"CTYPE2",$value2,$comm,$status);2544 if ($status) {2545 fits_close_file($fptr,$status);2546 $Task{errmess} = "Running read_keyword CTYPE2 (num extension: $i) in $filename";2547 &PrntChty(2,"$Task{stem}: Error: getArrayExtensionImage: $Task{errmess}\n");2548 $Task{status} = 1;2549 fits_close_file($fptr,$status);2550 return ;2551 }2552 $value1 = &trimValue($value1);2553 $value2 = &trimValue($value2);2554 if ($value1 ne "RA---TAN") {2555 &PrntChty(2,"$Task{stem}: Warning: Keyword CTYPE1 is not equal to 'RA---TAN' ($value1) in $filename+$i\n");2556 } elsif ($value2 ne "DEC--TAN") {2557 &PrntChty(2,"$Task{stem}: Warning: Keyword CTYPE2 is not equal to 'DEC---TAN' ($value2) in $filename+$i\n");2558 } else {2559 push @list,$i;2560 }2561 }2562 }2563

2564

2565 fits_close_file($fptr,$status);2566

2567

2568 return @list;2569

2570

2571 } #getArrayExtensionImage2572

2573

2574 sub trimValue() {2575 my $value=shift;2576 $value =~ s/^\s+//; # remove leading spaces2577 $value =~ s/\s+$//; # remove trailing spaces2578 $value =~ s/^'//g;; #Remove apex2579 $value =~ s/'$//g;; #Remove apex

11.1. Perl Subroutines from HEASoft 73

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2580 $value =~ s/\s+$//g;; #Remove right space2581 return $value;2582

2583 }2584

2585

2586 # Delete a list of column name. Return 1 in case of error2587

2588 sub delFitsCol() {2589 my ($filename,$extname,@listCol) = @_;2590

2591 my ($colname,$index);2592

2593 my $status = 0;2594

2595 foreach $colname (@listCol) {2596 my $fptr = &GetFitsPointer($filename,$extname,undef,READWRITE);2597 if ($Task{status}) {2598 return 1;2599 }2600

2601 fits_get_colnum($fptr,0, $colname , $index, $status);2602 if ($status) {2603 &PrntChty(5,"$Task{stem}: Warning: Column '$colname' not found in $filename file\n");2604 } else {2605

2606

2607 &PrntChty(5,"$Task{stem}: Info: delFitsColumn: Delete column : '$colname' in $filename file\n");2608 fits_delete_col($fptr,$index,$status);2609 if ($status) {2610 &PrntChty(2,"$Task{stem}: Error: delFitsCol: Unable to delete colname: '$colname'\n");2611 $Task{errmess} = "Unable to delete column name $colname from $filename file";2612 $Task{status} = 1;2613 return 1;2614 }2615

2616 fits_write_chksum($fptr,$status);2617 if ($status) {2618 $Task{errmess} = "Error running write_chksum $filename file , $extname extension";2619 &PrntChty(2,"$Task{stem}: Error: delFitsCol - Running write_chksum on file $filename\n");2620 $Task{status} = 1;2621 return 0;2622 }2623 }2624 $status =0;2625

2626

2627

2628 fits_close_file($fptr,$status);2629 if ($status) {2630 $Task{errmess} = "delFitsCol: Unable to close file : $filename";2631 return 1;2632 }2633 }2634 return 0;2635 }2636

2637 sub GetRootStem {

74 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2638

2639 # It takes the root of a filename erasing the given 'tailstem'2640 # i.e: infile = /home/user/rootfiletest.txt2641 # tailstem = test.txt2642 # return (rootfile)2643

2644 my ( $infile , $tailstem) = @_;2645 use vars qw ( %Task );2646

2647 my ( $infilenopath ) = substr($infile,rindex( $infile, '/' )+1);2648

2649 # take the root stem2650

2651 if ( $infilenopath =~ /$tailstem$/ ) {$infilenopath =~ s/$tailstem//g;}2652 else { $Task{errmess} = "Cannot define standard stem of files";2653 $Task{status} = 1;2654 return; }2655

2656 return ($infilenopath);2657

2658 } # GetRootStem2659

2660

2661

2662 sub AddKeywordExt {2663

2664 my ($filename,$extname,$datatype,$keyname,$value,$comment) = @_;2665

2666 use vars qw (%Task);2667

2668 my ($fptr,$status) = (0,0);2669

2670 fits_open_file($fptr,$filename,READWRITE,$status);2671 if ($status) {2672 $Task{status} = 1;2673 &PrntChty(2,"$Task{stem}: Error: AddKeywordExt: Cannot open file: $filename\n");2674 &PrntChty(2,"$Task{stem}: Error: AddKeywordExt: CFITSIO error: $status\n");2675 $Task{errmess} = "Unable to open fits file : $filename";2676 return 0;2677 }2678 fits_movnam_hdu($fptr,ANY_HDU,$extname,0,$status);2679 if ($status) {2680 $Task{status} = 1;2681 &PrntChty(2,"$Task{stem}: Error: AddKeywordExt: Cannot move to extension name $extname in file $filename\n");2682 &PrntChty(2,"$Task{stem}: Error: AddKeywordExt: CFITSIO error: $status\n");2683 $Task{errmess} = "Error: AddKeywordExt: Cannot move to extension name $extname in file $filename";2684 fits_close_file($fptr,$status);2685 return 0;2686 }2687

2688 fits_update_key($fptr,$datatype, $keyname,$value,$comment,$status);2689 if ($status) {2690 $Task{status} = 1;2691 $Task{errmess} = "Error writing keyword $keyname to file $filename";2692 fits_close_file($fptr,$status);2693 return 0;2694 }2695 fits_write_chksum($fptr,$status);

11.1. Perl Subroutines from HEASoft 75

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2696 if ($status) {2697 $Task{status} = 1;2698 &PrntChty(2,"$Task{stem}: Error: AddKeywordExt: Cannot write checksum to extension name $extname in file $filename\n");2699 &PrntChty(2,"$Task{stem}: Error: AddKeywordExt: CFITSIO error: $status\n");2700 $Task{errmess} = "Error: Cannot write checksum dddd file $filename";2701 fits_close_file($fptr,$status);2702 return 0;2703 }2704

2705 fits_close_file($fptr,$status);2706

2707 return 1;2708 }2709

2710 sub AddKeywordExtNum {2711

2712 my ($filename,$extnum,$datatype,$keyname,$value,$comment) = @_;2713

2714 use vars qw (%Task);2715

2716 my ($fptr,$status,$exttype) = (0,0,0);2717

2718 fits_open_file($fptr,$filename,READWRITE,$status);2719 if ($status) {2720 $Task{status} = 1;2721 &PrntChty(2,"$Task{stem}: Error: AddKeywordExtNum: Cannot open file: $filename\n");2722 &PrntChty(2,"$Task{stem}: Error: AddKeywordExtNum: CFITSIO error: $status\n");2723 $Task{errmess} = "Unable to open fits file : $filename";2724 return 0;2725 }2726 fits_movabs_hdu($fptr,$extnum,$exttype,$status);2727 if ($status) {2728 $Task{status} = 1;2729 &PrntChty(2,"$Task{stem}: Error: AddKeywordExtNum: Cannot move to extension number $extnum in file $filename\n");2730 &PrntChty(2,"$Task{stem}: Error: AddKeywordExtNum: CFITSIO error: $status\n");2731 $Task{errmess} = "Error: AddKeywordExtNum: Cannot move to extension number $extnum in file $filename";2732 fits_close_file($fptr,$status);2733 return 0;2734 }2735

2736 fits_update_key($fptr,$datatype, $keyname,$value,$comment,$status);2737 if ($status) {2738 $Task{status} = 1;2739 $Task{errmess} = "Error writing keyword $keyname to file $filename";2740 fits_close_file($fptr,$status);2741 return 0;2742 }2743 fits_write_chksum($fptr,$status);2744 if ($status) {2745 $Task{status} = 1;2746 &PrntChty(2,"$Task{stem}: Error: AddKeywordExtNum: Cannot write checksum to extension number $extnum in file $filename\n");2747 &PrntChty(2,"$Task{stem}: Error: AddKeywordExtNum: CFITSIO error: $status\n");2748 $Task{errmess} = "Error: Cannot write checksum in file $filename";2749 fits_close_file($fptr,$status);2750 return 0;2751 }2752

2753 fits_close_file($fptr,$status);

76 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2754

2755 return 1;2756 }2757

2758

2759 sub CallScQuzcif {2760

2761

2762 my ( $Dataset, $Date, $Time, $Selection , $expnumfile ) = @_;2763 my ( $field,@dummy, @outlist , @extlist);2764 use vars qw ( %Task );2765

2766 # The function performs a query to the CALDB database based2767 # on $Dataset, $Date, $Time, $Selection parameters (see below2768 # for the input parameter description.2769 # The function return two array 'outlist' and 'extlist' with the result of the query.2770 # The array is filled with filenames and extensions from the quzcif query2771 # For example: if the 'quzcif' query gives only one match the array will2772 # content : $outlist[0] = filename2773 # $extlist[0] = extension2774 # if the 'quzcif' query gives two matches the array will2775 # content : $outlist[0] = filename12776 # $extlist[0] = extension12777 # $outlist[1] = filename22778 # $extlist[1] = extension22779 # etc ....2780 # $Dataset - 'Calibration Dataset Codename'2781 # $Date - 'Requested Date in yyyy-mm-dd format' or "NOW" for the must up to date dataset2782 # $Time - 'Requested Time in hh:mm:ss format' or "-" if $date = "NOW"2783 # $Selection - "Boolean selection expression for Boundary params" or "-" if not required2784

2785 # Check CALDB environment2786

2787 if ( !$ENV{CALDB} ) {2788 &PrntChty(2,"$Task{stem}: Error: CallScQuzcif: CALDB environment not set\n");2789 &PrntChty(2,"$Task{stem}: Error: CallScQuzcif: Please set the CALDB environment or specify the input parameter for '$Dataset'\n");2790 $Task{status} = 1;2791 return (\@outlist,\@extlist);2792 }2793

2794 my ( $command ) = "quzcif SWIFT SC - - $Dataset $Date $Time \"$Selection\" retrieve+ clobber=yes";2795 &PrntChty(5,"$Task{stem}: Info: CallScQuzcif: Running $command\n");2796 my ( @ret ) = qx($command);2797 &PrntChty(5,"CallScQuzcif: Info: Output 'quzcif' Command: \nCallScQuzcif: Info:@ret");2798

2799 if ( $#ret == -1 ) {2800 &PrntChty(2,"$Task{stem}: Error: CallScQuzcif: No Calibration File Found for '$Dataset' dataset\n");2801 &PrntChty(2,"$Task{stem}: Error: CallScQuzcif: 'quzcif' command: \"$command\"\n");2802 $Task{status} = 1;2803 return (\@outlist,\@extlist);2804 }2805

2806 if ( $#ret != $expnumfile-1) {2807 my $n = $#ret +1;2808 &PrntChty(2,"$Task{stem}: Error: CallScQuzcif: Found " . $n . " calibration file(s) instead of $expnumfile file(s)\n");2809 $Task{status} = 1;2810 return (\@outlist,\@extlist);2811 }

11.1. Perl Subroutines from HEASoft 77

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2812

2813 foreach $field ( @ret ) {2814

2815 my ( $file, $ext );2816

2817 if ( $field =~ "ERROR" ) {2818 &PrntChty(2,"$Task{stem}: Error: CallScQuzcif: 'quzcif': @ret\n");2819 $Task{status} = 1;2820 return (\@outlist,\@extlist);2821 }2822

2823 ($file, $ext ) = split /\s+/,$field;2824 push @outlist, $file;2825 push @extlist, $ext;2826

2827 }2828

2829 return (\@outlist,\@extlist);2830

2831 } # CallScQuzcif2832

2833

2834 sub CheckRow {2835

2836 use vars qw( %Task );2837

2838 my ( $file, $ext, $gtifile, $gtiexpr, $gtiextname ) = @_ ;2839

2840

2841 my ( @splitexpr, $ee ) ;2842 my ( @columns );2843

2844 @splitexpr = split ( /&&/,$gtiexpr );2845

2846 my ( @lt_col, @le_col, @e_col, @gt_col, @ge_col );2847 my ( @lt_val, @le_val, @e_val, @gt_val, @ge_val );2848

2849 foreach $ee ( @splitexpr ) {2850 if ( $ee =~ /(\w+)>=(.*)/ ) {2851 push @ge_col, $1;2852 push @ge_val, $2;2853 }2854 elsif ( $ee =~ /(\w+)>(.*)/ ) {2855 push @gt_col, $1;2856 push @gt_val, $2;2857 }2858 elsif ( $ee =~ /(\w+)==(.*)/ ) {2859 push @e_col, $1;2860 push @e_val, $2;2861 }2862 elsif ( $ee =~ /(\w+)<=(.*)/ ) {2863 push @le_col, $1;2864 push @le_val, $2;2865 }2866 elsif ( $ee =~ /(\w+)<(.*)/ ) {2867 push @lt_col, $1;2868 push @lt_val, $2;2869 }

78 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2870 else {2871 &PrntChty(2,"$Task{stem}: Error: Screening Expression '$ee' not allowed\n");2872 $Task{errmess} = "Cannot Pars screening expression";2873 $Task{status} = 1;2874 return 1;2875 }2876 push @columns, { name => $1 };2877 }2878

2879 push @columns, { name => "TIME" };2880 push @columns, { name => "ENDTIME" };2881

2882 my (@table) = &LoadBinTable($file,"",$ext,@columns);2883 if ( $Task{status} ) { return -1;}2884

2885 my ( $col, $ind );2886 my ( $ok ) = 1;2887

2888 $ind = -1;2889 foreach $col ( @lt_col ) {2890 $ind ++;2891 if ( !($table[0]->{$col} <= $lt_val[$ind]) ) {2892 $ok = 0;2893 &PrntChty(4,"$Task{stem}: Warning: found '$col' set to '$table[0]->{$col}' that is > '$lt_val[$ind]'\n");2894 goto end_check; }2895 }2896 $ind = -1;2897 foreach $col ( @le_col ) {2898 $ind ++;2899 if ( !($table[0]->{$col} < $le_val[$ind]) ) {2900 $ok = 0;2901 &PrntChty(4,"$Task{stem}: Warning: found '$col' set to '$table[0]->{$col}' that is >= '$le_val[$ind]'\n");2902 goto end_check; };2903 }2904 $ind = -1;2905 foreach $col ( @e_col ) {2906 $ind ++;2907 if ( !($table[0]->{$col} == $e_val[$ind]) ) {2908 $ok = 0;2909 &PrntChty(4,"$Task{stem}: Warning: found '$col' set to '$table[0]->{$col}' that is != '$e_val[$ind]'\n");2910 goto end_check; };2911 }2912 $ind = -1;2913 foreach $col ( @gt_col ) {2914 $ind ++;2915 if ( !($table[0]->{$col} > $gt_val[$ind]) ) {2916 $ok = 0;2917 &PrntChty(4,"$Task{stem}: Warning: found '$col' set to '$table[0]->{$col}' that is <= '$gt_val[$ind]'\n");2918 goto end_check; };2919 }2920 $ind = -1;2921 foreach $col ( @ge_col ) {2922 $ind ++;2923 if ( !($table[0]->{$col} >= $ge_val[$ind]) ) {2924 $ok = 0;2925 &PrntChty(4,"$Task{stem}: Warning: found '$col' set to '$table[0]->{$col}' that is < '$ge_val[$ind]'\n");2926 goto end_check; };2927 }

11.1. Perl Subroutines from HEASoft 79

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2928

2929 end_check:2930

2931 # Cheate the GTI file, if the row does not match the2932 # expression the GTI file will be empty2933

2934 my ($fptr,$status) = (0,0);2935

2936 &PrntChty(3,"$Task{stem}: Info: Creating '$gtifile' file\n");2937

2938 fits_create_file($fptr,$gtifile,$status);2939

2940 if ($status) {2941 $Task{status} = 1;2942 $Task{errmess} = "$Task{stem}: Error: cannot create $gtifile";2943 return 1;2944 }2945

2946 fits_write_imghdr($fptr,16,0,0,$status);2947 if ($status) {2948 $Task{status} = 1;2949 $Task{errmess} = "Cannot create $gtifile Primary Header";2950 return 1;2951 }2952

2953 my $tform = [ qw(1D 1D) ];2954 my $ttype = [ qw(START STOP) ];2955 my $tunit = [ ( 'sec', 'sec' ) ];2956

2957 my $nrows = 0;2958 my $tfields = 2;2959 my $pcount = 0;2960 my $binname = $gtiextname;2961

2962 fits_insert_btbl($fptr,$nrows,$tfields,$ttype,$tform,$tunit,$binname,0,$status);2963 if ($status) {2964 $Task{status} = 1;2965 $Task{errmess} = "Cannot create $gtifile '$gtiextname' extension";2966 return 1;2967 }2968

2969 if ( $ok ) {2970 &PrntChty(3,"$Task{stem}: Info: Output GTI file with START: $table[0]->{TIME} and STOP: $table[0]->{ENDTIME}\n");2971 fits_write_col($fptr,TDOUBLE,1,1,1,1, $table[0]->{TIME},$status);2972 if ($status) {2973 $Task{status} = 1;2974 $Task{errmess} = "Cannot write $gtifile 'START' value";2975 return 1;2976 }2977 fits_write_col($fptr,TDOUBLE,2,1,1,1, $table[0]->{ENDTIME},$status);2978 if ($status) {2979 $Task{status} = 1;2980 $Task{errmess} = "Cannot create $gtifile 'STOP' value";2981 return 1;2982 }2983 }2984 else {2985 &PrntChty(3,"$Task{stem}: Warning: The '$file' row does not match Timing conditions\n");

80 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

2986 &PrntChty(3,"$Task{stem}: Warning: Created Empty GTI '$gtifile'\n");2987 }2988

2989 fits_close_file($fptr,$status);2990 if ($status) {2991 &PrntChty(2,"$Task{stem}: Error: 'fits_close_file' error on '$gtifile'\n");2992 $Task{status} = 1;2993 $Task{errmess} = "cannot close '$gtifile' file";2994 return 1;2995 }2996

2997 return 0;2998

2999 } # CheckRow3000

3001 sub CleanTimeNulls {3002

3003 #3004 # The subroutine returns:3005 #3006 # - 1 if some NULLs have been found in the TIME column and3007 # the selection have been applied3008 # _or_3009 # if there is an error3010 #3011 # - 0 if no NULLs have been found so no selection needed3012 #3013 my ( $infile, $outfile, $extension ) = @_;3014

3015 my ( $ret, $par, $command, %ftselect );3016 my $expr = "\"\!isnull(TIME)&&TIME!=-1\"";3017 my $null = 0;3018 my $outdir = substr($outfile,0,rindex($outfile,"/"));3019

3020 #3021 # Check if the input file has NULLS in the TIME column3022 #3023 $null = &RunFtstat($infile,$extension,"TIME","null",$outdir);3024 if ( $Task{status} ) { return 1; }3025

3026 #3027 # If There are some NULLs in the TIME column runfselect3028 #3029

3030 if ( $null ) {3031

3032 &PrntChty(3,"$Task{stem}: Warning: CleanTimeNulls: Found some records in the\n");3033 &PrntChty(3,"$Task{stem}: Warning: CleanTimeNulls: '$infile' file with\n");3034 &PrntChty(3,"$Task{stem}: Warning: CleanTimeNulls: TIME value set to NULL\n");3035 &RunningSub("CleanTimeNulls","ftselect", " to select from '$infile' rows with expression '$expr'");3036

3037 #3038 # Build the command line to run 'ftselect'3039 #3040

3041 %ftselect = (3042 infile => $infile,3043 outfile => $outfile,

11.1. Perl Subroutines from HEASoft 81

Learn GRB Data Analysis in 3 Days, Release 0.9.9

3044 expression => $expr,3045 copyall => "yes",3046 clobber => "no",3047 chatter => $Task{chatter},3048 history => $Task{history},3049 );3050

3051 $command = "ftselect";3052 for $par ( keys %ftselect ) { $command .= " $par=$ftselect{$par}"; }3053

3054 &RunningComm("CleanTimeNulls",$command);3055

3056 $ret = 0;3057 $ret = system( $command );3058

3059 if ( $ret != 0 ) {3060 &ErrorComm("CleanTimeNulls","ftselect",$command);3061 $Task{errmess} = "Error: running 'ftselect'";3062 $Task{status} = 1;3063 return 1;3064 }3065

3066 # update checksum3067

3068 if ( system("ftchecksum $outfile update=yes chatter=0") ) {3069 &PrntChty(1,"$Task{stem}: Error: Error updating checksum\n");3070 $Task{errmess} = "Error: updating checksum";3071 $Task{status} = 1;3072 return 1;3073 }3074

3075 &SuccessSub("CleanTimeNulls","ftselect","'$infile' filtered");3076 return 1;3077 }3078 else {3079 &PrntChty(4,"$Task{stem}: Info: CleanTimeNulls: Clean of the '$infile' not needed\n");3080 return 0;3081 }3082

3083 } # CleanTimeNulls3084

3085

3086 sub RunFtstat {3087

3088 my ( $file, $ext, $col, $stat1, $outdir ) = @_;3089

3090 my ( $ret, $par, $command, %ftstat );3091

3092 my ($tmpoutfile) = $outdir.$$."ftstat.out";3093 unlink ( $tmpoutfile );3094

3095 #3096 # Build the command line to run 'ftselect'3097 #3098

3099 %ftstat = (3100 infile => "\'$file\[$ext\]\[col $col\]'",3101 outfile => "$tmpoutfile",

82 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

3102 centroid => "yes",3103 clip => "no",3104 nsigma => 3,3105 maxiter => 20,3106 );3107

3108 $command = "ftstat";3109

3110 for $par ( keys %ftstat ) { $command .= " $par=$ftstat{$par}"; }3111

3112 &RunningComm("RunFtstat",$command);3113

3114 $ret = 0;3115 $ret = system( $command );3116

3117 if ( $ret != 0 ) {3118 &ErrorComm("RunFtstat","ftstat",$command);3119 $Task{errmess} = "Error: running 'ftstat'";3120 $Task{status} = 1;3121 return 1;3122 }3123

3124 # Get the value of the ftstat parameter '$stat1'3125

3126 $command = "pget ftstat $stat1";3127

3128 &RunningComm("RunFtstat",$command);3129

3130 $ret = 0;3131 $ret = `$command`;3132 chop $ret;3133

3134 &PrntChty(4,"$Task{stem}: Info: RunFtstat: Read '$stat1' value = '$ret' for column '$col'\n");3135 &PrntChty(4,"$Task{stem}: Info: RunFtstat: in the '$file' file\n");3136

3137 unlink ( $tmpoutfile );3138

3139 return $ret;3140

3141 } # RunFtstat3142

3143 sub SetFileName {3144

3145 my ( $outfileparam, $stemout, $stemin, $defaultext, $dir ) = @_;3146

3147 use vars qw ( %Task %Default );3148 my ( $Filename );3149

3150 # Define attorbfilename3151

3152 if ( &CompUL( $outfileparam, $Default{DEFAULT} ) && &CompUL( $stemout, $Default{DEFAULT} )) {3153 $Filename = "$dir/$stemin$defaultext";3154 }3155 elsif ( &CompUL( $outfileparam, $Default{DEFAULT} ) && !&CompUL( $stemout, $Default{DEFAULT} )) {3156 # Use Input Stem3157 $Filename = "$dir/$stemout$defaultext";3158 }3159 else { $Filename = "$outfileparam"; }

11.1. Perl Subroutines from HEASoft 83

Learn GRB Data Analysis in 3 Days, Release 0.9.9

3160

3161 &PrntChty(4,"$Task{stem}: Info: SetFileName: The file name will be $Filename\n");3162

3163 return $Filename;3164

3165 } # SetFileName3166

3167 sub AddStemBeforeExtension {3168

3169 my ($file, $stem ) = @_;3170 my $ext = "";3171 my ($filenozip, $filenoext);3172

3173 if ( $file =~ /(.gz|.Z)$/ ) {3174 $filenozip = substr($file,0,rindex($file,'.'));3175 } else { $filenozip = $file; }3176

3177 if ( rindex($filenozip,'.') > 0 ) {3178 $filenoext = substr($file,0,rindex($filenozip,'.'));3179 $ext = substr($file,rindex($filenozip,'.'));3180 } else { $filenoext = $filenozip; }3181

3182 return "$filenoext$stem$ext";3183

3184 }3185

3186

3187 sub GetAttitudeATTFLAG {3188

3189 # This subroutine returns the ATTFLAG keyword value3190 # in the attitude file3191 # The ATTFLAG keyword is taken from ATTITUDE3192 # extension in attitude file3193 # If ATTFLAG key not exist (old attitude file)3194 # return the default value '100' for old files3195

3196 my ( $attfile, $attflag ) = @_;3197

3198 my ($fptrin, $status) = (0,0);3199

3200 fits_open_file($fptrin,$attfile,READONLY,$status);3201 if ($status) {3202 $Task{status} = 1;3203 $Task{errmess} = "Unable to open fits file : $attfile";3204 return 1;3205 }3206

3207 my ($attflag_value, $attflag_comm);3208

3209 fits_movnam_hdu($fptrin,ANY_HDU,"ATTITUDE",0,$status);3210 if ( $status ) {3211 $Task{errmess} ="Unable to move to extname 'ATTITUDE' in attitude file $attfile";3212 $Task{status} = 1;3213 return 1;3214 }3215

3216 fits_read_key_str($fptrin,"ATTFLAG",$attflag_value,$attflag_comm,$status);3217 if ($status == KEY_NO_EXIST ) {

84 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

3218 $attflag_value = "100";3219 &PrntChty(2,"$Task{stem}: Warning: GetAttitudeATTFLAG: 'ATTFLAG' keyword not found in $attfile\n");3220 &PrntChty(2,"$Task{stem}: Warning: GetAttitudeATTFLAG: using default value '100'\n");3221 $status = 0;3222 } elsif ($status) {3223 $Task{errmess} = "Error reading ATTFLAG keyword in file $attfile";3224 $Task{status} = 1;3225 return 1;3226 }3227

3228 $$attflag = $attflag_value;3229

3230 fits_close_file($fptrin,$status);3231

3232 return 0;3233

3234 }3235

3236 sub GetImagesHduList{3237

3238 my ($infile) = @_;3239 my $ffp;3240 my $count = 0;3241 my $status=0;3242 my @hdu_list ;3243 my $hdun = 1;3244 my $type;3245

3246

3247 fits_open_file($ffp,$infile,READONLY,$status);3248

3249 if ($status) {3250 $Task{status} = 1;3251 $Task{errmess} = "Unable to open fits file : $infile" ;3252 return;3253 }3254

3255 while (!fits_movabs_hdu($ffp, $hdun, $type, $status))3256 {3257 if ($type eq IMAGE_HDU)3258 {3259 $hdu_list[$count] = $hdun;3260 $count ++;3261 }3262 $hdun ++;3263 }3264

3265 $Task{status} = 0;3266 $Task{errmess} = " ";3267 return @hdu_list;3268

3269 } #GetImagesHduList3270

3271

3272 sub FindCaldbIndxFile {3273

3274 # This function find the calibration index file path3275

11.1. Perl Subroutines from HEASoft 85

Learn GRB Data Analysis in 3 Days, Release 0.9.9

3276 my ( $mission, $instrument, $caldbindxfile ) = @_;3277

3278 my $line;3279

3280 if (!open(FILECONFIG,"<$ENV{CALDBCONFIG}")) {3281 $Task{errmess} = "cannot open CALDB config file $ENV{CALDBCONFIG}.";3282 $Task{status} = 1;3283 #&PrntChty(2,"$Task{stem}: Error: FindCaldbIndxFile: $Task{errmess}\n");3284 return 1;3285 }3286

3287 while ( $line = <FILECONFIG>) {3288

3289 chop($line);3290

3291 if (!($line=~ /^\#/))3292 {3293 my ($lmission,$linstrument,$ldevice,$ldirectory,$lfileindx,$lp6,$lp7)= split(/\s+/, $line);3294

3295 if(($mission eq $lmission)&&($instrument eq $linstrument))3296 {3297 if ($ldevice eq "CALDB")3298 {3299 $ldevice=$ENV{CALDB};3300 }3301

3302 $$caldbindxfile = $ldevice ."/". $ldirectory ."/". $lfileindx;3303 return 0;3304 }3305 }3306 }3307

3308 $Task{errmess} = "caldb.indx file not found for mission='$mission' and instrument='$instrument'";3309 $Task{status} = 1;3310 #&PrntChty(2,"$Task{stem}: Error: FindCaldbIndxFile: $Task{errmess}\n");3311 return 1;3312

3313 } #FindCaldbIndxFile3314

3315

3316 sub GetCaldbVersion {3317

3318 my ( $caldbversion ) = @_;3319 my ( $caldbindxfile );3320 my ( $fptr, $status, $numext ) = ( 0, 0, 0 );3321 my ( $value, $comm, $i );3322

3323 use vars qw(%Task);3324

3325

3326 # Check the environment variables 'CALDB' e 'CALDBCONFIG'3327

3328 if ( !$ENV{CALDB} ) {3329 $Task{errmess} = "CALDB environment variable not found";3330 $Task{status} = 1;3331 #&PrntChty(2,"$Task{stem}: Error: GetCaldbVersion: $Task{errmess}\n");3332 return 1;3333 }

86 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

3334

3335 if ( !(-d $ENV{CALDB}) ) {3336 $Task{errmess} = "$ENV{CALDB} NOT a valid directory.";3337 $Task{status} = 1;3338 #&PrntChty(2,"$Task{stem}: Error: GetCaldbVersion: $Task{errmess}\n");3339 return 1;3340 }3341

3342 if ( !$ENV{CALDBCONFIG} ) {3343 $Task{errmess} = "CALDBCONFIG environment variable not found";3344 $Task{status} = 1;3345 #&PrntChty(2,"$Task{stem}: Error: GetCaldbVersion: $Task{errmess}\n");3346 return 1;3347 }3348

3349 if ( !(-f $ENV{CALDBCONFIG}) ) {3350 $Task{errmess} = "$ENV{CALDBCONFIG} NOT a valid file.";3351 $Task{status} = 1;3352 #&PrntChty(2,"$Task{stem}: Error: GetCaldbVersion: $Task{errmess}\n");3353 return 1;3354 }3355

3356

3357 # Find the calibration index file path3358

3359 &FindCaldbIndxFile("SWIFT","XRT",\$caldbindxfile);3360 if ( $Task{status} ) {3361 #&PrntChty(2,"$Task{stem}: Error: GetCaldbVersion: unable to find the calibration index file.\n");3362 return 1;3363 }3364

3365

3366 # Read the CALDB version from the calibration index file3367

3368 if(!(-f $caldbindxfile)){3369 $Task{errmess} = "'$caldbindxfile' calibration index file NOT found.";3370 $Task{status} = 1;3371 #&PrntChty(2,"$Task{stem}: Error: GetCaldbVersion: $Task{errmess}\n");3372 return 1;3373 }3374

3375 fits_open_file($fptr,$caldbindxfile,READONLY,$status);3376 if ($status) {3377 $Task{errmess} = "Unable to open fits file '$caldbindxfile'";3378 $Task{status} = 1;3379 #&PrntChty(2,"$Task{stem}: Error: GetCaldbVersion: $Task{errmess}\n");3380 return 1;3381 }3382

3383 fits_get_num_hdus($fptr,$numext,$status);3384 if ($status) {3385 $Task{errmess} = "Unable to get num hdu in file '$caldbindxfile'";3386 $Task{status} = 1;3387 #&PrntChty(2,"$Task{stem}: Error: GetCaldbVersion: $Task{errmess}\n");3388 return 1;3389 }3390

3391 for ( $i = 1; $i <= $numext; $i++) {

11.1. Perl Subroutines from HEASoft 87

Learn GRB Data Analysis in 3 Days, Release 0.9.9

3392

3393 $status=0;3394 fits_movabs_hdu($fptr,$i,ANY_HDU,$status);3395 if ($status) {3396 $Task{errmess} = "Unable to open HDU number $i-1 in file '$caldbindxfile'";3397 $Task{status} = 1;3398 #&PrntChty(2,"$Task{stem}: Error: GetCaldbVersion: $Task{errmess}\n");3399 return 1;3400 }3401

3402 fits_read_keyword($fptr,"CALDBVER",$value,$comm,$status);3403 if (!$status) {3404 fits_close_file($fptr,$status);3405 $$caldbversion = &trimValue($value);3406 return 0;3407 }3408 }3409

3410

3411 fits_close_file($fptr,$status);3412

3413

3414 $Task{errmess} = "Unable to find 'CALDBVER' in HDU of file '$caldbindxfile'";3415 $Task{status} = 1;3416 #&PrntChty(2,"$Task{stem}: Error: GetCaldbVersion: $Task{errmess}\n");3417 return 1;3418

3419 } # GetCaldbVersion3420

3421

3422 1;

1 #------------------------------------------------------------2 # subroutines copied from xrtproducts3 #-----------------------------------------------------------4

5 sub RunXimage(){6

7 my($filename) = @_;8

9 use vars qw($headfilename $datamode);10

11 my $ImgFile;12 if ($datamode =~ /pc/i) {13 $ImgFile = &GetValPar("outdir") . "/" . $headfilename . "_sk." . &GetValPar("plotdevice");14 } else {15 $ImgFile = &GetValPar("outdir") . "/" . $headfilename . "im." . &GetValPar("plotdevice");16 }17

18

19 if ( -f $ImgFile) {20 if (!$Task{clobber} ) {21 &PrntChty(2, "$Task{stem}: Error: the '$ImgFile' exists\n");22 &PrntChty(2, "$Task{stem}: Error: please delete '$ImgFile' or\n");23 &PrntChty(2, "$Task{stem}: Error: set the input parameter 'clobber' to 'yes'\n");24 $Task{errmess} = "Unable to overwrite '$ImgFile' file";25 $Task{status} = 1;26 goto EXITWITHERROR;

88 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

27 } else {28 &DeleteFile($ImgFile);29 }30 }31

32

33

34 my ($dev) = &GetValPar("plotdevice");35 if ( $dev eq "ps" ) { $dev = "cps"; }36

37 &RunningSub("$Task{stem}","ximage", " on '$filename'");38

39 # Open a temporary file with ximage commands;40 my ( $XimageFile ) = &GetValPar("outdir") . "/" . $headfilename . ".xco";41 unlink ( $XimageFile );42

43 if ( ! open ( XIMFILE, ">$XimageFile" )) {44 $Task{errmess} = "Unable to create '$XimageFile' file";45 $Task{status} = 1;46 goto EXITWITHERROR;47 }48

49 if ( &GetValPar("chatter") <= 4 ) {50 print XIMFILE "chat 0\n";51 }52 if ($datamode =~ /pc/i) {53 print XIMFILE "read/size=600/ecol=pi/emin=30/emax=1000 $filename\n";54 print XIMFILE "cey 2000\n";55 print XIMFILE "smo\n";56 print XIMFILE "cpd $ImgFile/$dev\n";57 print XIMFILE "disp;grid\n";58 print XIMFILE "cpd /xs\n";59 print XIMFILE "quit";60 }elsif ($datamode =~ /im/i) {61 my($fptr,$status,$numext,@listext);62

63 @listext = &getArrayExtensionImage($filename);64 if ($Task{status}) { goto EXITWITHERROR;}65

66 if ($#listext == -1) {67 $Task{errmess} = "The $filename file is in raw coordinates. Unable to produce a sky coordinate image";68 goto EXITWITHERROR;69 }70

71 if ($#listext >= 0) {72 print XIMFILE "read/size=600 $filename+$listext[0];save_ima\n";73 }74 for (my $i = 1; $i <= $#listext; $i++) {75 print XIMFILE "read/size=600 $filename+" . +$listext[$i] . ";sum_ima;save_ima\n"76 }77 print XIMFILE "cey 2000\n";78 print XIMFILE "smo\n";79 print XIMFILE "cpd $ImgFile/$dev\n";80 print XIMFILE "disp;grid\n";81 print XIMFILE "cpd /null\n";82 print XIMFILE "quit\n";83

84

11.1. Perl Subroutines from HEASoft 89

Learn GRB Data Analysis in 3 Days, Release 0.9.9

85 } else {86 print XIMFILE "read/size=600/xcol=detx/ycol=rawy/xpix=300/ypix=300 $filename\n";87 print XIMFILE "cpd $ImgFile/$dev\n";88 print XIMFILE "disp\n";89 print XIMFILE "vplabel/bottom/margin=2.5/color=0 \"X Pixels\"\n";90 print XIMFILE "vplabel/bottom/margin=2.5 \"DETX Pixels\"\n";91 print XIMFILE "vplabel/left/margin=0.7/color=0/lwidth=10/position=0.33 '200'\n";92 print XIMFILE "vplabel/left/margin=0.7/color=0/lwidth=10/position=0.67 '400'\n";93 print XIMFILE "vplabel/left/margin=0.7/color=0/lwidth=10/position=1 \"600\"\n";94 print XIMFILE "vplabel/left/margin=2.2/color=0 \"Y Pixels\"\n";95 print XIMFILE "vplabel/left/margin=2.2 \"Folded Time\"\n";96 print XIMFILE "cpd /xs\n";97 print XIMFILE "quit\n";98 }99

100 close ( XIMFILE );101

102 my ( $command ) = "ximage \@$XimageFile";103 &RunningComm("$Task{stem}",$command);104 if ( system( "ximage \@$XimageFile" ) ) {105 &ErrorComm("RunExtractor","ximage",$command);106 &PrntChty(2,"$Task{stem}: Error: running command: 'ximage \@$XimageFile'\n");107 $Task{errmess} = "Error Running 'ximage'";108 $Task{status} = 1;109 goto EXITWITHERROR;110 }111

112 if ( &CompUL( &GetValPar("cleanup"), "yes" ) ) {113 &DeleteFile($XimageFile);114 }115

116 if ( &GetValPar("display") ) {117 if (&PlotImage( $Task{viewer}, $ImgFile )) {118 &PrntChty(2,"$Task{stem}: Warning: cannot display '$ImgFile' image\n");119 }120 }121 &SuccessSub("$Task{stem}","ximage","Created '$ImgFile' image");122 return ;123 }124

125

126 sub GetInputParameters {127

128 use vars qw( %Task $datamode @Par %Ind);129

130 my ( $name, $indref, $p);131

132 ($indref,@Par) = &GetParameterList();133

134 $Task{chatter} = 3;135

136 if ($Task{status}) { goto EXITWITHERROR;}137

138

139 %Ind = %$indref;140

141 if (! &LoadParameterFromCmdLine(@ARGV)) {142 &PrntChty(2,"$Task{stem}: Error: $Task{errmess}\n");

90 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

143 return 1;144 }145

146

147 if (&GetValPar("infile","set") == 0 ) {148 my $Stringa = "";149 chop($Stringa = `pquery2 xrtproducts infile`);150 if ( !$Stringa) {151 &PrntChty(2,"$Task{stem}: Error: running: 'pquery2 xrtproducts infile'\n");152 return 1;153 }154 &SetValPar("infile",$Stringa);155 &SetValPar("infile",2,"set");156 }157

158

159

160 #Check if it is a list of files161

162

163 if (&GetValPar("infile") =~ /^@/) {164 my($fv) = substr(&GetValPar("infile"),1);165

166 if( ! -f $fv ) {167 $Task{status} = 0;168 $Task{errmess} = "Input Event File List: '$fv' not found";169 goto EXITWITHERROR;170 }171

172 if ( ! open(FILELIST,$fv ) ) {173 $Task{errmess} = "Cannot open '$fv' file";174 goto EXITWITHERROR;175 }176

177 while (<FILELIST>) {178 chop();179 push(@filelist,$_);180 if (! -f $_) {181 $Task{errmess} = "Input Event File: '$_' not found";182 goto EXITWITHERROR;183 }184 }185 close(FILELIST);186 }187 else {188 $filelist[0] = &GetValPar("infile");189 if( ! -f &GetValPar("infile") ) {190 $Task{errmess} = "Input Event File: '" . &GetValPar("infile") . "' not found";191 goto EXITWITHERROR;192 }193 }194

195 $datamode = &GetEventDataMode($filelist[0]);196 if ( $Task{status} ) {197 goto EXITWITHERROR;198 }199

200 if ($datamode !~ /(lr|pu|wt|pc|im)/) {

11.1. Perl Subroutines from HEASoft 91

Learn GRB Data Analysis in 3 Days, Release 0.9.9

201 $Task{errmess} = "Incorrect Data Mode: '$datamode' ; '$filelist[0]' event file";202 goto EXITWITHERROR;203 }204

205

206 if ($datamode !~ /(lr|pu|im)/) {207 if ( &GetValPar("regionfile","set") == 0 ) {208 my $Stringa = "";209 chop($Stringa = qx(pquery2 xrtproducts regionfile));210 if ( !$Stringa ) {211 print "ERROR: error running: 'pquery2 xrtproducts regionfile'\n";212 return 1;213 }214 &SetValPar("regionfile", $Stringa);215 &SetValPar("regionfile",2,"set");216 }217 }218

219 if ($datamode ne "im") {220

221 &GetKeyword($filelist[0], "EVENTS", undef, "OBS_MODE", \$obsmode);222 if ( $Task{status} ) {223 goto EXITWITHERROR;224 }225

226 if ( &GetValPar("phafile","set") == 0 ) {227 my $Stringa = "";228 chop($Stringa = qx(pquery2 xrtproducts phafile));229 if ( !$Stringa ) {230 &PrntChty(2,"$Task{stem}: Error: running: 'pquery2 xrtproducts phafile'\n");231 return 1;232 }233 &SetValPar("phafile", $Stringa);234 &SetValPar("phafile",2,"set");235 }236 }237

238 #filelc239 if ( &GetValPar("lcfile","set") == 0 ) {240 my $Stringa = "";241 chop($Stringa = qx(pquery2 xrtproducts lcfile));242 if ( !$Stringa ) {243 print "ERROR: error running: 'pquery2 xrtproducts lcfile'\n";244 return 1;245 }246 &SetValPar("lcfile", $Stringa);247 &SetValPar("lcfile",2,"set");248 }249

250 #expofile251 if ( &GetValPar("expofile","set") == 0 ) {252 my $Stringa = "";253 chop($Stringa = qx(pquery2 xrtproducts expofile));254 if ( !$Stringa ) {255 print "ERROR: error running: 'pquery2 xrtproducts expofile'\n";256 return 1;257 }258 &SetValPar("expofile", $Stringa);

92 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

259 &SetValPar("expofile",2,"set");260 }261

262 if ( &GetValPar("bkgextract","set") == 0 ) {263 my $Stringa = "";264 chop($Stringa = qx(pquery2 xrtproducts bkgextract));265 if ( !$Stringa ) {266 print "ERROR: error running: 'pquery2 xrtproducts bkgextract'\n";267 return 1;268 }269 &SetValPar("bkgextract", $Stringa);270 &SetValPar("bkgextract",2,"set");271 }272

273 if ( &GetValPar("correctlc","set") == 0 ) {274 my $Stringa = "";275 chop($Stringa = qx(pquery2 xrtproducts correctlc));276 if ( !$Stringa ) {277 print "ERROR: error running: 'pquery2 xrtproducts correctlc'\n";278 return 1;279 }280 &SetValPar("correctlc", $Stringa);281 &SetValPar("correctlc",2,"set");282 }283

284

285 foreach $p (@Par) {286 if (($p->{set} == 1) && (!&RequestParameter($p->{name}))) {287 &PrntChty(2,"$Task{stem}: Error: $Task{errmess}\n");288 return 1;289 }290 }291

292 $Task{errmess} = "";293 if (! &LoadParameter()) {294 &PrntChty(2,"$Task{stem}: Error: $Task{errmess}\n");295 return 1;296 }297

298 $Task{chatter} = &GetValPar("chatter");299

300 if (&GetValPar("ra","set") != 0 ) {301 if (!&CheckRa("RA",&GetValPar("ra"))) { goto EXITWITHERROR;}302 }303 if (&GetValPar("dec","set") != 0 ) {304 if (!&CheckDec("DEC",&GetValPar("dec"))) { goto EXITWITHERROR;}305

306 }307

308 if( (&GetValPar("lcfile") =~ /$Default{NONE}/i) && (&CompUL( &GetValPar("correctlc"),"yes")) ){309 &PrntChty(2,"$Task{stem}: Error: Parameter lcfile set to NONE, cannot correct source light-curve.\n");310 goto EXITWITHERROR;311 }312

313

314 return 0;315 } # GetInputParameters316

11.1. Perl Subroutines from HEASoft 93

Learn GRB Data Analysis in 3 Days, Release 0.9.9

317

318

319 sub RunXselect {320

321 my ($xcofile,$evtfile) = @_;322 use vars qw( %Task );323 my ( $command, $ret, $par, %extractor );324

325

326 &RunningSub("$Task{stem}","xselect", " on '$xcofile'");327

328 # set expression specific the the datamode329 #330 # Build the command line to run 'extractor'331 #332

333 $command = "xselect @" . $xcofile;334

335

336 &RunningComm("$Task{stem}",$command);337

338 $ret = 0;339 $ret = system( $command );340

341 if ( $ret != 0 ) {342 &ErrorComm("$Task{stem}","xselect",$command);343 $Task{errmess} = "Error running 'xselect'";344 $Task{status} = 1;345 goto EXITWITHERROR;346 }347

348 # check errors from 'xselect.log' file349 $ret = 0;350 $ret = &CheckXselectLog();351

352 if ( $ret != 0 ) {353 &ErrorComm("$Task{stem}","xselect",$command);354 $Task{errmess} = "Error running 'xselect'";355 $Task{status} = 1;356 return 1;357 }358

359 my $strmsg = "";360

361 if (&GetValPar("lcfile") !~ /$Default{NONE}/i) { $strmsg = "Light Curve ";}362 if (&GetValPar("phafile") !~ /$Default{NONE}/i) {$strmsg = $strmsg eq "" ? "Spectrum " : $strmsg . ",Spectrum ";}363

364

365 if ($datamode !~ /(lr|pu)/i) {366 if (&GetValPar("imagefile") !~ /$Default{NONE}/i) { $strmsg = $strmsg eq "" ? "Image" : $strmsg . "and Image ";}367 }368

369 &SuccessSub("$Task{stem}","xselect","$strmsg generated for '$evtfile'");370 return 0;371

372 } # RunExtractor373

374

94 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

375 #Return value of a specific extension376

377 sub GetValue(){378 my ($filename,$key,$extension) = @_;379 my ($row,$val);380

381 $row = `fkeyprint $filename+$extension $key | grep -i "$key\[ \]*="`;382 chop($row);383 my ($p,$comment) = split(/\//,$row);384 ($p,$val) = split(/=/,$p);385 $val = trim($val);386 chomp($val); # get rid of \n387 $val =~ s/^\s+//; # remove leading spaces388 $val =~ s/\s+$//; # remove trailing spaces389 $val =~ s/^'//g;; #Remove apex390 $val =~ s/'$//g;; #Remove apex391 $val =~ s/\s+$//g;; #Remove right space392 return $val;393 }394

395 #----------------------------------------------------------------------#396 # FUNCTION: hashValueAscendingNum #397 # #398 # PURPOSE: Help sort a hash by the hash 'value', not the 'key'. #399 # Values are returned in ascending numeric order (lowest #400 # to highest). #401 #----------------------------------------------------------------------#402

403

404 sub hashValueAscendingNum {405 use vars qw(%htstart);406 $htstart{$a} <=> $htstart{$b};407 }408

409 #Sort file for TSTART : parameter array of file410 sub SortArrayTStart {411

412 my (@file) = @_;413 my ($i,@f,$key,$tstart);414

415 for ($i=0; $i <= $#file ; $i++) {416 &GetKeyword($file[$i],"EVENTS",undef, "TSTART", \$tstart);417 if ( $Task{status} ) { goto EXITWITHERROR; }418 $htstart{$i} = $tstart;419 }420

421 $i = -1;422 foreach $key (sort hashValueAscendingNum (keys(%htstart))) {423 $i++;424 $f[$i] = $file[$key];425

426 }427

428 return @f;429

430 }431

432

11.1. Perl Subroutines from HEASoft 95

Learn GRB Data Analysis in 3 Days, Release 0.9.9

433 #Return name file without path434

435 sub getFileName() {436

437 my ($fn) = @_;438 my $pos = rindex($fn,"/");439 if ($pos == -1) {return $fn;}440 else {return substr($fn,$pos+1);}441 }442

443

444

445

446 sub RequestParameter(){447 use vars qw ($datamode %Default %Task);448 my ($par_name) = @_;449

450 $Task{errmess} = "Input parameters not compatible with datamode: $datamode";451

452 if ($datamode eq "im") {453 if ((uc(&GetValPar("gtifile")) ne "$Default{NONE}") && ($par_name eq "gtifile")) {454 $Task{errmess} = "Cannot insert $par_name when datamode=IMAGING";455 return 0;456 }457 if ((uc(&GetValPar("expofile")) ne "$Default{NONE}") && ($par_name eq "expofile")) {458 $Task{errmess} = "Cannot insert $par_name when datamode=IMAGING";459 return 0;460 }461 if (($par_name eq "pilow") || ($par_name eq "pihigh")) {462 $Task{errmess} = "Cannot insert $par_name when datamode=IMAGING";463 return 0;464 }465 if (($par_name eq "infile") || ($par_name eq "outdir") ||466 ($par_name eq "stemout") || ($par_name eq "display") || ($par_name eq "plotdevice") || ($par_name eq "chatter") ||467 ($par_name eq "history") || ($par_name eq "cleanup")|| ($par_name eq "clobber") || ($par_name eq "correctlc") || ($par_name eq "expofile") ){468 return 1;469 }470 else { return 0;}471 }472

473 if (($par_name eq "regionfile") && &CompUL(&GetValPar("regionfile"),$Default{NONE}) ) {474 &PrntChty(2,"$Task{stem}: Error: Cannot specify '$par_name=NONE'\n");475 &PrntChty(2,"$Task{stem}: Error: Please set '$par_name' to 'DEFAULT' or supply an extraction region file\n");476 $Task{errmess} = "Cannot insert $par_name=NONE";477 return 0;478 }479

480 if ( (($par_name eq "ra") || ($par_name eq "dec") || ($par_name eq "radius"))481 && ((&GetValPar("phafile") =~ /$Default{NONE}/i) && (&GetValPar("lcfile") =~ /$Default{NONE}/i)))482 {483 $Task{errmess} = "Cannot insert $par_name when phafile=NONE and lcfile=NONE";484 return 0;485 }486

487 if (($par_name eq "rmffile") || ($par_name eq "mirfile") || ($par_name eq "psfflag") ||488 ($par_name eq "fitsfile") || ($par_name eq "psffile") || ($par_name eq "vigfile") || ($par_name eq "inarffile") || ($par_name eq "expofile")) {489 if (&GetValPar("phafile") !~ /$Default{NONE}/i) {490 return 1;

96 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

491 } else {492 $Task{errmess} = "Cannot insert $par_name when phafile=NONE";493 return 0;494 }495 }496

497 if ((&GetValPar("lcfile") =~ /$Default{NONE}/i) && (($par_name eq "binsize") || ($par_name eq "pilow") || ($par_name eq "pihigh"))) {498 $Task{errmess} = "Cannot insert $par_name when lcfile=NONE";499 return 0;500 }501

502 if ( (&CompUL( &GetValPar("bkgextract"),"no")) && (($par_name eq "bkgregionfile") || ($par_name eq "bkglcfile") || ($par_name eq "bkgphafile"))) {503 $Task{errmess} = "Cannot insert $par_name when bkgextract=no";504 return 0;505 }506

507 if ( (&CompUL( &GetValPar("correctlc"),"no")) && (($par_name eq "attfile") || ($par_name eq "hdfile")) ) {508 $Task{errmess} = "Cannot insert $par_name when correctlc=no";509 return 0;510 }511

512 if ($datamode eq "pc") {513

514 if (($par_name eq "ra") && !&CompUL(&GetValPar("regionfile"),$Default{DEFAULT}) ) {515 $Task{errmess} = "Cannot insert $par_name when input region file name is specified";516 return 0;517 }518

519 if (($par_name eq "dec") && !&CompUL(&GetValPar("regionfile"),$Default{DEFAULT}) ) {520 $Task{errmess} = "Cannot insert $par_name when input region file name is specified";521 return 0;522 }523

524 if (($par_name eq "radius") && !&CompUL(&GetValPar("regionfile"),$Default{DEFAULT}) ) {525 $Task{errmess} = "Cannot insert $par_name when input region file name is specified";526 return 0;527 }528

529 return 1;530 }531

532 if ($datamode eq "wt") {533

534 if (($par_name eq "ra") && !&CompUL(&GetValPar("regionfile"),$Default{DEFAULT}) ) {535 $Task{errmess} = "Cannot insert $par_name when input region file name is specified";536 return 0;537 }538

539 if (($par_name eq "dec") && !&CompUL(&GetValPar("regionfile"),$Default{DEFAULT}) ) {540 $Task{errmess} = "Cannot insert $par_name when input region file name is specified";541 return 0;542 }543

544 if (($par_name eq "radius") && !&CompUL(&GetValPar("regionfile"),$Default{DEFAULT}) ) {545 $Task{errmess} = "Cannot insert $par_name when input region file name is specified";546 return 0;547 }548

11.1. Perl Subroutines from HEASoft 97

Learn GRB Data Analysis in 3 Days, Release 0.9.9

549 return 1;550 }551

552 if ($datamode =~ /(lr|pu)/i) {553 if (($par_name eq "radius") || ($par_name eq "regionfile") ||554 ($par_name eq "imagefile") || (($par_name eq "ra") || ($par_name eq "dec"))){555 return 0;556 }557 return 1;558 }559

560 $Task{errmess} = "";561 return 1;562 } # RequestParameter563

564

565 #Return filename of rmf file566 # return empty string if file not found or if there are more rmf file567 ## different from original: 1) comment and change "if ($Task{status} == KEY_NO_EXIST)"568 ## 2) add "$datamode = &GetEventDataMode($filename);"569 sub GetRmfFile(){570

571

572 my ($filename,$reffile,$refext,@rmffile,@extfile) = @_;573

574 use vars qw($datamode);575

576 my ($strmode,$grade,$rmffile);577 my ($StartDate, $StartTime, $xrtvsub);578

579

580 # Get Observation Start Date581 &GetEventStartDate($filename, \$StartDate, \$StartTime);582 if ( $Task{status} ) { return "";}583

584 # Get XRTVSUB585 &GetKeyword ($filename, "EVENTS", undef, "XRTVSUB", \$xrtvsub, 1);586 if ( $Task{status} ) {587 # if ($Task{status} == KEY_NO_EXIST){588 # $xrtvsub="0";589 # &PrntChty(2,"$Task{stem}: Warning: 'XRTVSUB' keyword not found in '$filename'\n");590 # &PrntChty(2,"$Task{stem}: Warning: using default value '0'\n");591 # $Task{status}=0;592 # }593 # else{594 &PrntChty(2,"$Task{stem}: Warning: cannot read 'XRTVSUB' keyword in file '$filename'\n");595 &PrntChty(2,"$Task{stem}: Warning: using default value '0'\n");596 $xrtvsub="0";597 $Task{status}=0;598 #return "";599 # }600 }601

602 # Get Grade603 $grade = &GetGrade($filename);604 if ($Task{status}) { return "";}605

606 # if ($grade <0) {return "";}

98 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

607 $datamode = &GetEventDataMode($filename);608 #print "datamode: $datamode \n";609

610 if ($datamode =~ /pc/i) {$strmode = "datamode.eq.photon"}611 elsif ($datamode =~ /wt/i) { $strmode = "datamode.eq.windowed";}612 else { $strmode = "datamode.eq.lowrate";}613

614 $strmode = $strmode . ".and.grade.eq.G$grade";615 $strmode = $strmode . ".and.XRTVSUB.eq.$xrtvsub";616

617 ($reffile,$refext) = &CallQuzcif ("matrix", $StartDate, $StartTime,"$strmode",1);618

619 @rmffile = @$reffile;620 @extfile = @$refext;621

622 if ($Task{status}) {623 $Task{errmess} = "Unable to get rmf file from CALDB";624 return "";625 } else {626 return $rmffile[0];627 }628 }629

630

631

632

633 #Return value of DSVALn keyword634 #return -1 in case of errors635 sub GetGrade() {636 my ($filename) = @_;637

638 my ($i,$numext,$val);639

640 #Get extension EVENTS641 $numext = &GetNumExtName($filename,"EVENTS");642 if ($numext < 0) {643 $Task{status} = 1;644 return -1;645 }646

647 for ($i = 1; $i <= 99; $i++) {648 &GetKeyword($filename,"EVENTS", undef,"DSTYP$i",\$val);649 &PrntChty(5,"$Task{stem}:Get keyword DSTYP$i ($numext) value: $val\n");650 if ( $Task{status} ) {return -1; }651

652

653 if ($val =~ /GRADE/i) {654 &GetKeyword($filename,"EVENTS", undef,"DSVAL$i",\$val);655 if ($Task{status}) { return -1;}656 return $val;657 }658 }659

660 $Task{status} = "Cannot find DSTYPm keyword in $filename";661 return -1;662 }663

664

11.1. Perl Subroutines from HEASoft 99

Learn GRB Data Analysis in 3 Days, Release 0.9.9

665 sub RunXrtLcCorr {666

667 my ( $lcfile, $infile, $stemout ) = @_;668

669 my ( $par, $ret );670 my ( $command, %xrtlccorr );671

672 my ( $outinstrfile, $corrfile, $outfile );673

674 use vars qw ( %Task %Default );675

676

677 # Set DEFAULT name of the output files678 if ( uc(&GetValPar("outinstrfile")) eq $Default{DEFAULT} ) {679 $outinstrfile = &GetValPar("outdir") ."/" . $stemout . "_srawinstr.img";680 }681 else {682 $outinstrfile = &GetValPar("outdir") ."/" . &GetValPar("outinstrfile");683 }684

685 if ( uc(&GetValPar("corrfile")) eq $Default{DEFAULT} ) {686 $corrfile = &GetValPar("outdir") ."/" . $stemout . "sr_corrfact.fits";687 }688 else {689 $corrfile = &GetValPar("outdir") ."/" . &GetValPar("corrfile");690 }691

692 if ( uc(&GetValPar("lccorrfile")) eq $Default{DEFAULT} ) {693 $outfile = &GetValPar("outdir") ."/" . $stemout . "sr_corr.lc";694 }695 else {696 $outfile = &GetValPar("outdir") ."/" . &GetValPar("lccorrfile");697 }698

699

700 %xrtlccorr = (701 lcfile => $lcfile,702 regionfile => "NONE",703 outfile => $outfile,704 corrfile => $corrfile,705 teldef => "CALDB",706 aberration => "no",707 attinterpol => "no",708 attfile => &GetValPar("attfile"),709 srcx => -1,710 srcy => -1,711 psffile => "CALDB",712 psfflag => "yes",713 energy => &GetValPar("lcenergy"),714 createinstrmap => "yes",715 outinstrfile => $outinstrfile,716 infile => $infile,717 hdfile => &GetValPar("hdfile"),718 fovfile => "CALDB",719 vigfile => "CALDB",720 wtnframe => &GetValPar("wtnframe"),721 pcnframe => &GetValPar("pcnframe"),722 chatter => &GetValPar("chatter"),

100 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

723 history => &GetValPar("history"),724 clobber => &GetValPar("clobber"),725 );726

727

728 $command = "xrtlccorr";729 for $par ( keys %xrtlccorr ) { $command .= " $par=$xrtlccorr{$par}"; }730

731

732 &RunningSub("RunXrtLcCorr","xrtlccorr"," on '$lcfile'");733 &RunningComm("RunXrtLcCorr",$command);734

735 $ret = 0;736 $ret = system( $command );737

738 if ( $ret != 0 ) {739 &ErrorComm("RunXrtLcCorr","xrtlccorr",$command);740 $Task{errmess} = "ERROR running 'xrtlccorr'";741 $Task{status} = 1;742 return 1;743 }744

745 &SuccessSub("RunXrtLcCorr","xrtlccorr");746 return 0;747

748 } # RunXrtLcCorr749 1;

11.2 findRMF

findRMF is used for finding the corresponding response matrix file from event file.

Input: .evt event file name

Output: .rmf response matrix file name

Example:

./findRMFPlease input the FITS filename:sw00271019000xpcw2po_cl.evt: Warning: cannot read 'XRTVSUB' keyword in file 'sw00271019000xpcw2po_cl.evt': Warning: using default value '0': Info: CallQuzcif: Running quzcif SWIFT XRT - - matrix 2007-03-18 07:37:09 "datamode.eq.photon.and.grade.eq.G0:12.and.XRTVSUB.eq.0" retrieve+ clobber=yesCallQuzcif: Info: Output 'quzcif' Command:CallQuzcif: Info:/Applications/heasoft/CALDB_LOCAL/data/swift/xrt/cpf/rmf/swxpc0to12s0_20070101v012.rmf 1

Source code:

1 #!/usr/bin/perl2

3 require "libswxrt.pl";4 use File::Copy;5

6 # Task info7

8 our %Task = (

11.2. findRMF 101

Learn GRB Data Analysis in 3 Days, Release 0.9.9

9 name => 'findRMF',10 version => '0.2',11 releasedate => "2016-03-13",12 chatter => 2,13 status => 0,14 errmess => '',15 stem => '',16 author => 'Y.Wang',17 );18

19 # Initial20

21 my $isCopy = 0; # 0 is no, 1 is yes.22

23 # Main #24

25 return 0 if $Task{status};26

27 ## read parameter28 my $filename = $ARGV[0] if ( $ARGV[0] );29

30 unless ( defined $filename ) {31 &PrntChty( 1, "Please input the FITS filename (eg. sw00271019000xwtw2po_cl.evt):\n" );32 chomp( $filename = <STDIN> );33 }34

35 ## get response matrix file36 &GetRmfFile($filename);37

38 &Error if $Task{status};39

40 ## copy rmf file to current folder41 $copied = copy( $rmfFilename, "./" ) if $rmfFilename and $isCopy;42 &PrntChty( 2, "\nRMF file has been copied to current folder.\n" ) if $copied;

11.3 dlXRT

dlXRT is used for download necessary files for Swift-XRT and Swift-BAT data analysis.

Input: observation ID and instrument name

Output: event file, housekeeping file and attitude file

Example:

./dlxrtPlease input the observation ID (eg.00554620000):00554620000Please input instrument xrt/bat (eg. xrt):xrt............Download finished.

Source code:

102 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

1 #!/usr/bin/perl2

3 require "./libswxrt.pl";4

5

6 # This script is for downloading data from Swift website7 our %Task = (8 name => 'dlxrt',9 version => '0.6',

10 releasedate => "2013-10-6",11 chatter => 2,12 status => 0,13 errmess => '',14 stem => '',15 author => 'Y.Wang',16 );17

18

19 ## Enter observational ID and Instrument20

21 my $obsID = $ARGV[0] if ($ARGV[0]);22 my $inst = $ARGV[1] if ($ARGV[1]);23 my $doXrt = "no"; #if download XRT data24 my $doBat = "no"; #if download Bat data25 #my $doUvot = "yes"; # if download UVOT data26

27 unless(defined $obsID){28 print "Please input the observation ID (eg.00554620000):\n";29 chomp($obsID = <STDIN>);30 }31

32 unless(defined $inst){33 print "Please input instrument xrt/bat (eg. xrt):\n";34 chomp($inst = <STDIN>);35 }36

37 $doXrt = "yes" if $inst eq "xrt" or $inst eq "XRT";38 $doBat = "yes" if $inst eq "bat" or $inst eq "BAT";39

40

41 my $trigger = substr($obsID,2,6);42 my $grbName;43

44 ### Download List45 #### XRT file list46 #my $sat_fits = "http://www.swift.ac.uk/archive/reproc/"."$obsID"."/auxil/sw"."$obsID"."sat.fits.gz";47 #my $sat_fits_pat = "http://www.swift.ac.uk/archive/reproc/"."$obsID"."/auxil/sw"."$obsID"."pat.fits.gz";48 #my $sat_fits_uat = "http://www.swift.ac.uk/archive/reproc/"."$obsID"."/auxil/sw"."$obsID"."uat.fits.gz";49 my $xhd_hk = "http://www.swift.ac.uk/archive/reproc/"."$obsID"."/xrt/hk/sw"."$obsID"."xhd.hk.gz";50 my $pcw3_cl_evt = "http://www.swift.ac.uk/archive/reproc/"."$obsID"."/xrt/event/sw"."$obsID"."xpcw3po_cl.evt.gz";51 my $wtw2_cl_evt = "http://www.swift.ac.uk/archive/reproc/"."$obsID"."/xrt/event/sw"."$obsID"."xwtw2po_cl.evt.gz";52 #my @downloadListXrt = ($sat_fits, $sat_fits_pat, $sat_fits_uat, $xhd_hk, $pcw3_cl_evt, $wtw2_cl_evt);53 my @downloadListXrt = ($xhd_hk, $pcw3_cl_evt, $wtw2_cl_evt);54

55

56 #### BAT file list57 my $bat_uf_evt = "http://www.swift.ac.uk/archive/reproc/"."$obsID"."/bat/event/sw"."$obsID"."bevshsp_uf.evt.gz";58 my $bdecb_hk = "http://www.swift.ac.uk/archive/reproc/"."$obsID"."/bat/hk/sw"."$obsID"."bdecb.hk.gz";

11.3. dlXRT 103

Learn GRB Data Analysis in 3 Days, Release 0.9.9

59 my $bdqcb_hk = "http://www.swift.ac.uk/archive/reproc/"."$obsID"."/bat/hk/sw"."$obsID"."bdqcb.hk.gz";60 my $fits_bevtr = "http://www.swift.ac.uk/archive/reproc/"."$obsID"."/bat/event/sw"."$obsID"."bevtr.fits.gz";61 #my @downloadListBat = ($sat_fits, $sat_fits_pat, $sat_fits_uat, $bat_uf_evt, $bdecb_hk, $bdqcb_hk, $fits_bevtr);62 my @downloadListBat = ($bat_uf_evt, $bdecb_hk, $bdqcb_hk, $fits_bevtr);63

64

65

66 ### Find Name and Make folder67 my $nameListWeb = "http://www.swift.ac.uk/grb_region/";68 my $grbName = $trigger;69 system 'curl',"$nameListWeb","-o","name.list";70 open my $nameList, '<', "name.list";71 while (<$nameList>) {72 if(/.*$trigger.*GRB\s(\w+)</){73 $grbName = $1 ;74 }75 }76

77 close $nameList;78 system 'rm -f name.list';79 print "Data are stored in the forder $grbName.\n";80 mkdir "$grbName" unless (-e "$grbName");81

82

83 chdir("$grbName");84 mkdir "$obsID" unless (-e "$obsID");85 chdir("$obsID");86

87

88

89 ### download XRT data90 if ($doXrt eq "yes"){91

92 mkdir "xrt" unless (-e "xrt");93 chdir("xrt");94 foreach $file (@downloadListXrt){95 system 'wget','--no-check-certificate','--no-clobber',"$file";96 }97 #system 'gzip --decompress --force --keep *.evt.gz';98 #system 'rm -r *.evt.gz';99

100 ## download attitude file101 my $attFlag, $attflagPC, $attflagWT, $attFile, $att_fits;102

103 my $pcEvent = "sw"."$obsID"."xpcw3po_cl.evt.gz";104 my $wtEvent = "sw"."$obsID"."xwtw2po_cl.evt.gz";105

106 &GetKeyword($pcEvent, 'EVENTS', undef, 'ATTFLAG', \$attflagPC, undef);107 $Task{status} = 0;108 &GetKeyword($wtEvent, 'EVENTS', undef, 'ATTFLAG', \$attflagWT, undef);109

110 $attFlag = $attflagPC if $attflagPC;111 $attFlag = $attflagWT if $attflagWT;112

113 &PrntChty(2, "ATTFLAG is $attFlag \n");114

115 #my $evtFilenameEvents="$evtFilename"."[Events]";116 #my $att = `ftlist $evtFilenameEvents k include=HISTORY`;

104 Chapter 11. Scripts

Learn GRB Data Analysis in 3 Days, Release 0.9.9

117 $attFile="sw"."$obsID"."pat.fits.gz" if $attFlag eq "110";118 $attFile="sw"."$obsID"."sat.fits.gz" if $attFlag eq "100";119 $attFile="sw"."$obsID"."uat.fits.gz" if ($attFlag eq "111" or $attFlag eq "101");120

121 $att_fits = "http://www.swift.ac.uk/archive/reproc/"."$obsID"."/auxil/"."$attFile";122 &PrntChty(2, "Attitude file is $att_fits \n");123

124 system 'wget','--no-check-certificate','--no-clobber',"$att_fits";125

126 chdir("..");127 }128

129 ### download bat data130 if ($doBat eq "yes"){131

132 mkdir "bat" unless (-e "bat");133 chdir("bat");134 foreach $file (@downloadListBat){135 system 'wget','--no-check-certificate','--no-clobber',"$file";136 }137 #system 'gzip --decompress --force --keep *.evt.gz';138 #system 'rm -r *.evt.gz';139

140 my $attFlag, $attflagPC, $attflagWT, $attFile, $att_fits;141

142 my $batEvent = "sw"."$obsID"."bevshsp_uf.evt.gz";143

144 &GetKeyword($batEvent, 'EVENTS', undef, 'ATTFLAG', \$attFlag, undef);145

146 &PrntChty(2, "ATTFLAG is $attFlag \n");147

148 #my $evtFilenameEvents="$evtFilename"."[Events]";149 #my $att = `ftlist $evtFilenameEvents k include=HISTORY`;150 $attFile="sw"."$obsID"."pat.fits.gz" if $attFlag eq "110";151 $attFile="sw"."$obsID"."sat.fits.gz" if $attFlag eq "100";152 $attFile="sw"."$obsID"."uat.fits.gz" if ($attFlag eq "111" or $attFlag eq "101");153

154 $att_fits = "http://www.swift.ac.uk/archive/reproc/"."$obsID"."/auxil/"."$attFile";155 &PrntChty(2, "Attitude file is $att_fits \n");156

157 system 'wget','--no-check-certificate','--no-clobber',"$att_fits";158

159 chdir("..");160

161 }162

163 &PrntChty(2, "Download finished. \n");

11.4 getpar

getpar is used for get observational parameters from event file.

Input: event file name

Output: observational parameters

Example:

11.4. getpar 105

Learn GRB Data Analysis in 3 Days, Release 0.9.9

getpar sw00585834000xwtw2po_cl.evtOBJECT = 'GRB140206a'OBS_ID = '00585834000'TSTART = 4.133639020059217E+08TSTOP = 4.134087866215617E+08RA_OBJ = 145.3342917DEC_OBJ = 66.7606944TRIGTIME = 413363851.776ATTFLAG = '110

getpar sw00585834000xwtw2po_cl.evt TRIGTIMETRIGTIME = 413363851.776

Source code:

1 #!/usr/bin/perl2

3 #warn "Input filename" if ($ARGV[1] eq "");4

5 my $evtFilename=$ARGV[0];6 my $evtFilenamePrimary="$evtFilename"."[primary]";7

8

9 unless ($ARGV[1]){10 $ARGV[1] = "OBJECT";11 $ARGV[2] = "OBS_ID";12 $ARGV[3] = "TSTART";13 $ARGV[4] = "TSTOP";14 $ARGV[5] = "RA_OBJ";15 $ARGV[6] = "DEC_OBJ";16 $ARGV[7] = "TRIGTIME";17 $ARGV[8] = "ATTFLAG";18 }19 foreach $argv (@ARGV){20 next if ($argv eq $ARGV[0]);21 my $par = `ftlist $evtFilenamePrimary hck`;22 $par =~ /\s{0,1}$argv\s*=\s+(.+?)\s+/;23 $par = $1;24 print "$argv = $par\n"25 }

Do you have questions? Please send an email to [email protected] or open an issue on Github.

106 Chapter 11. Scripts