Analysis API

AGBaseAnalysis

class core.AGBaseAnalysis.AGBaseAnalysis(configurationFilePath)[source]
__init__(configurationFilePath)[source]
getAnalysisDir()[source]

It returns the path of the output directory

Returns:

the path of the output directory

Return type:

path (str)

deleteAnalysisDir()[source]

It deletes the output directory where all the products of the analysis are written.

Args:

Returns:

True if the directory is succesfully deleted, False otherwise.

setOptions(**kwargs)[source]

It updates configuration options specifying one or more key=value pairs at once.

Parameters:

kwargs – key-values pairs, separated by a comma.

Returns:

None

Raises:
  • ConfigFileOptionTypeError – if the type of the option value is not wrong.

  • ConfigurationsNotValidError – if the values are not coherent with the configuration.

  • CannotSetHiddenOptionError – if the option is hidden.

  • OptionNotFoundInConfigFileError – if the option is not found.

Note

The config attribute is initialized by reading the corresponding yaml configuration file, loading its contents in memory. Updating the values held by this object will not affect the original values written on disk.

Example

>>> aganalysis.setOptions(mapsize=60, binsize=0.5)
True
getOption(optionName)[source]

It reads an option value from the configuration.

Parameters:

optionName (str) – the name of the option.

Returns:

The option value

Raises:

OptionNotFoundInConfigFileError – if the optionName is not found in the configuration.

printOptions(section=None)[source]

It prints the configuration options in the console.

Parameters:

section (str) – you can specify a configuration file section to be printed out.

Returns:

None

AGAnalysis

class api.AGAnalysis.AGAnalysis(configurationFilePath, sourcesFilePath=None)[source]

This class contains the high-level API to run scientific analysis, data visualization and some utility methods.

This constructor of this class requires a yaml configuration file.

__init__(configurationFilePath, sourcesFilePath=None)[source]

AGAnalysis constructor.

Parameters:
  • configurationFilePath (str) – a relative or absolute path to the yaml configuration file.

  • sourcesFilePath (str, optional) – a relative or absolute path to a file containing the description of the sources. Defaults to None. Three different types of formats are supported: AGILE format (.txt), XML format (.xml) and AGILE catalog files (.multi).

Raises:
  • AGILENotFoundError – if the AGILE environment variable is not set.

  • PFILESNotFoundError – if the PFILES environment variable is not set.

Example

>>> from agilepy.api import AGAnalysis
>>> aganalysis = AGAnalysis('agconfig.yaml', sourcesFilePath='sources.xml')
destroy()[source]

It clears the list of sources and the current maplist file.

static getConfiguration(confFilePath, userName, sourceName, tmin, tmax, timetype, glon, glat, outputDir, verboselvl, evtfile='/AGILE_PROC3/FM3.119_ASDC2/INDEX/EVT.index', logfile='/AGILE_PROC3/DATA_ASDC2/INDEX/LOG.log.index', userestapi=True, datapath=None)[source]

Utility method to create a configuration file.

Parameters:
  • confFilePath (str) – the path and filename of the configuration file that is going to be created.

  • userName (str) – the username of who is running the software.

  • sourceName (str) – the name of the source.

  • tmin (float) – the start time of the analysis.

  • tmax (float) – the stop time of the analysis.

  • timetype (str) – timetype format possible values: “TT” or “MJD”

  • glon (float) – the galactic longitude (L) of the analysis.

  • glat (float) – the galactic latitude (B) of the analysis.

  • outputDir (str) – the path to the output directory. The output directory will be created using the following format: ‘userName_sourceName_todaydate’

  • verboselvl (int) – the verbosity level of the console output. Message types: level 0 => critical, warning, level 1 => critical, warning, info, level 2 => critical, warning, info, debug

  • evtfile (str, optional [default=/AGILE_PROC3/FM3.119_ASDC2/INDEX/EVT.index]) – the index file to be used for event data if userestapi is set to False. The time range starts from 107092735 TT, 54244.49924768 MJD, 2007-05-24 11:58:55 UTC

  • logfile (str, optional [default=/AGILE_PROC3/DATA_ASDC2/INDEX/LOG.log.index]) – the index file to be used for log data if userestapi is set to False. The time range starts from 107092735 TT, 54244.49924768 MJD, 2007-05-24 11:58:55 UTC

  • userestapi (bool, optional [default=True]) – If True, the SSDC REST API will be used to download missing data.

  • datapath (str, optional [default=None]) – Datapath to download AGILE data if userestapi is set to True. Index files will be generated into this path.

Returns:

None

loadSourcesFromCatalog(catalogName, rangeDist=(0, inf), show=False)[source]

It loads the sources from a catalog.

You can also specify a rangeDist argument to filter out the sources which distance from (glon, glat) is not in the rangeDist interval.

If the catalog is 2AGL and if the energy range (emin, emax) specified by the user in the configuration file (energybins parameter) is different from the catalog’s energy range, the flux of every source will be scaled.

Parameters:
  • catalogName (str) – the catalog name (2AGL, 4FGL).

  • rangeDist (tuple, optional) – a interval (min, max) of distances (degree). It defaults to (0, +inf).

Raises:
  • FileNotFoundError – if the catalog is not supported.

  • SourceModelFormatNotSupported – if the input file format is not supported.

  • SourcesFileLoadingError – if any error occurs during the parsing of the sources file.

Returns:

The List of sources that have been succesfully loaded into the SourcesLibrary.

loadSourcesFromFile(sourcesFilepath, rangeDist=(0, inf), show=False)[source]

It loads the sources, reading them from a file. Three different types of format are supported: AGILE format (.txt), XML format (.xml) and AGILE catalog files (.multi).

You can also specify a rangeDist argument to filter out the sources which distance from (glon, glat) is not in the rangeDist interval.

Parameters:

sourcesFilePath (str) – a relative or absolute path to a file containing the description of the sources. rangeDist (tuple): a interval (min, max) of distances (degree)

Raises:
  • SourceModelFormatNotSupported – if the input file format is not supported.

  • SourcesFileLoadingError – if any error occurs during the parsing of the sources file.

Returns:

The List of sources that have been succesfully loaded into the SourcesLibrary.

selectSources(selection, show=False)[source]

It returns the sources matching the selection criteria from the sourcesLibrary.

The sources can be selected with the selection argument, supporting either lambda functions and boolean expression strings.

The selection criteria can be expressed using the following Source class’s parameters:

  • name: the unique code identifying the source.

  • dist: the distance of the source from the center of the maps.

  • flux: the flux value.

  • sqrtts: the radix square of the ts.

Warning

The sqrtts parameter is available only after the maximum likelihood estimation analysis is performed.

Parameters:
  • selection (lambda or str) – a lambda function or a boolean expression string specifying the selection criteria.

  • quiet (boolean) (optional default=False) – if quiet is True, the method will not console log the selected sources.

Returns:

List of sources.

freeSources(selection, parameterName, free, show=False)[source]

It can set to True or False a parameter’s free attribute of one or more source.

Example of source model:

<source name="2AGLJ2021+4029" type="PointSource">
    <spectrum type="PLExpCutoff">
      <parameter name="flux" free="1"  value="119.3e-08"/>
      <parameter name="index" free="0" scale="-1.0" value="1.75" min="0.5" max="5"/>
      <parameter name="cutoffEnergy" free="0" value="3307.63" min="20" max="10000"/>
    </spectrum>
    <spatialModel type="PointSource" location_limit="0">
      <parameter name="pos" value="(78.2375, 2.12298)" free="0" />
    </spatialModel>
</source>

The supported parameterName are:

  • flux

  • index

  • index1

  • index2

  • cutoffEnergy

  • pivotEnergy

  • curvature

  • index2

  • pos

Parameters:
  • selection (lambda or str) – a lambda function or a boolean expression string specifying the selection criteria.

  • parameterName (str) – the free attribute of this parameter will be updated.

  • free (bool) – the boolean value used.

Returns:

The list of the sources matching the selection criteria.

Note

The sourcesLibrary attribute is initialized by reading the corresponding xml descriptor file, loading its contents in memory. Updating the values held by this object will not affect the original values written on disk.

Example

The following calls are equivalent and they set to True the free attribute of the “Flux” parameter for all the sources named “2AGLJ2021+4029” which distance from the map center is greater than zero and which flux value is greater than zero.

>>> aganalysis.freeSources(lambda name, dist, flux : Name == "2AGLJ2021+4029" AND dist > 0 AND flux > 0, "flux", True)
[..]
>>> aganalysis.freeSources('name == "2AGLJ2021+4029" AND dist > 0 AND flux > 0', "flux", True)
[..]
fixSource(source)[source]

Set to False all freeable params of a source.

Parameters:

sourceName (Source) – the source object.

Returns:

True if at least one parameter of the source changes, False otherwise.

addSource(sourceName, sourceDict)[source]

It adds a new source in the Sources Library. You can add a source, passing a dictionary containing the source’s data. Some keys are required, other are optional. Here’s an example:

newSourceDict = {
    "glon" : 6.16978,
    "glat": -0.0676943,
    "spectrumType" : "LogParabola",
    "flux": 35.79e-08,
    "curvature": 0.682363
}
newSource = aganalysis.addSource("2AGLJ1801-2334", newSourceDict)
Parameters:
  • sourceName (str) – the name of the source

  • sourceDict (dict) – a dictionary containing the source’s data.

Raises:

SourceParamNotFoundError – if sourceName is None or empty, OR the sourceDict input dictionary does not contain at least one of the following keys: [“glon”, “glat”,”spectrumType”].

Returns:

The source object if it is been loaded. None, otherwise.

deleteSources(selection, show=False)[source]

It deletes the sources matching the selection criteria from the sourcesLibrary.

Parameters:

selection (lambda or str) – a lambda function or a boolean expression string specifying the selection criteria.

Returns:

The list containing the deleted sources.

getSources()[source]

It returns all the sources. :returns: List of sources.

updateSourcePosition(sourceName, glon, glat)[source]

It updates a source (l,b) position parameters. The ‘dist’ value will also be updated.

Parameters:
  • sourceName (str) – the name of the source

  • glon (float) – galactic longitude.

  • glat (float) – galactic latitude.

Raises:
  • SourceNotFound – if the source has not been loaded into the SourcesLibrary.

  • ValueError – if glon or glat values are out of range.

Returns:

True if the position changes, False otherwise.

writeSourcesOnFile(outfileNamePrefix, fileFormat, sources=None)[source]

It writes on file the list of sources loaded into the SourceLibrary. The supported formats (‘txt’ AND ‘xml’) are described here: Sources file.

Parameters:
  • outfileNamePrefix (str) – the name of the output file (without the extension).

  • fileFormat (str) – Possible values: [‘txt’, ‘xml’, ‘reg’].

  • sources (List<Source>) – a list of Source objects. If is is None, every loaded source will be written on file.

Raises:

SourceModelFormatNotSupported – if the file format is not supported.

Returns:

Path to the file

setOptionTimeMJD(tmin, tmax)[source]

It performs a time conversion MJD -> TT and set new values using setOptions functions

Parameters:
  • tmin (float) – tmin in MJD

  • tmax (float) – tmax in MJD

setOptionEnergybin(value)[source]

An useful utility method that maps a value in a specific energybin and it calls the setOptions function.

Parameters:

Value (int) –

A value between 0 and 5

  • 0: [[100, 10000]]

  • 1: [[100, 50000]]

  • 2: [[100, 300], [300, 1000], [1000, 3000], [3000, 10000]]

  • 3: [[100, 300], [300, 1000], [1000, 3000], [3000, 10000], [10000, 50000]]

  • 4: [[50, 100], [100, 300], [300, 1000], [1000, 3000], [3000, 10000]]

  • 5: [[50, 100], [100, 300], [300, 1000], [1000, 3000], [3000, 10000], [10000, 50000]]

Raises:

ValueOutOfRange – if the value is not between 0 and 5.

generateMaps(config=None, maplistObj=None, tqdmOff=False)[source]

It generates (one or more) counts, exposure, gas and int maps and a maplist file.

The method’s behaviour varies according to several configuration options (see docs Configuration file).

Note

It resets the configuration options to their original values before exiting.

Returns:

The absolute path to the generated maplist file.

Raises:

ScienceToolInputArgMissing – if not all the required configuration options have been set.

Example

>>> aganalysis.generateMaps()
/home/rt/agilepy/output/testcase.maplist4
calcBkg(sourceName, galcoeff=None, pastTimeWindow=14.0, excludeTmaxTmin=False)[source]

It estimates the isotropic and galactic background coefficients.

Note

The current value of the isotropic and galactic bkg coeffs will be set to -1 in order to be free to vary during the fit. It automatically updates the configuration.

Parameters:
  • sourceName (str) – the name of the source under analysis.

  • galcoeff (List, optional) – the galactic background coefficients (one for each map).

  • pastTimeWindow (float, optional) – the number of days previous tmin. It defaults to 14. If it’s 0, the background coefficients will be estimated within the [tmin, tmax] interval.

  • excludeTmaxTmin (bool, optional) – if this value is True (defalut=False) and pasttimewindow > 0 the calcbkg method computes coeffs between [tmin-pastTimeWindow, tmin] instead of [tmin-pastTimeWindow, tmax]

Returns:

the estimates of the background coefficients and the path to the updated maplist file.

Return type:

galactic coefficients, isotropic coefficients, maplist file (List, List, str)

mle(maplistFilePath=None, config=None, updateSourceLibrary=True, position='ellipse')[source]

It performs a maximum likelihood estimation analysis on every source withing the sourceLibrary, producing one output file per source.

The method’s behaviour varies according to several configuration options (see docs Configuration file).

The outputfiles have the .source extension.

The method’s behaviour varies according to several configuration options (see docs here).

Note

It resets the configuration options to their original values before exiting.

Parameters:

maplistFilePath (str) – if not provided, the mle() analysis will use the last generated mapfile produced by generateMaps().

Returns:

A list of absolute paths to the output .source files.

Raises:

MaplistIsNone – is the input argument is None.

Example

>>> maplistFilePath = aganalysis.generateMaps()
>>> aganalysis.mle(maplistFilePath)
[/home/rt/agilepy/output/testcase0001_2AGLJ2021+4029.source /home/rt/agilepy/output/testcase0001_2AGLJ2021+3654.source]
lightCurveMLE(sourceName, tmin=None, tmax=None, timetype=None, binsize=86400, position='ellipse')[source]

It generates a cvs file containing the data for a light curve plot.

Parameters:
  • sourceName (str) – the name of the source under analysis.

  • tmin (float, optional) – starting point of the light curve. It defaults to None. If None the ‘tmin’ value of the configuration file will be used.

  • tmax (float, optional) – ending point of the light curve. It defaults to None. If None the ‘tmax’ value of the configuration file will be used.

  • timetype (str, optional) – the time format (‘MJD’ or ‘TT’). It defaults to None. If None the ‘timetype’ value of the configuration file will be used.

  • binsize (int, optional) – temporal bin size. It defaults to 86400.

  • position (str, optional) – the position of the source: {“ellipse”, “peak”, “initial”}

Returns:

The absolute path to the light curve data output file.

aperturePhotometry()[source]

It generates a cvs file containing the data for a light curve plot. The method’s behaviour varies according to several configuration options (see docs Configuration file).

Returns:

The absolute path to the light curve data output file.

Raises:

ScienceToolInputArgMissing – if not all the required configuration options have been set.

displayCtsSkyMaps(maplistFile=None, singleMode=True, smooth=4.0, saveImage=False, fileFormat='.png', title=None, cmap='CMRmap', regFiles=None, regFileColors=[], catalogRegions=None, catalogRegionsColor='red', normType='linear')[source]

It displays the last generated cts skymaps.

Parameters:
  • maplistFile (str, optional) – the path to the .maplist file. If not specified, the last generated maplist file will be used. It defaults to None.

  • singleMode (bool, optional) – if set to true, all maps will be displayed as subplots on a single figure. It defaults to True.

  • smooth (float, optional) – the sigma value of the gaussian smoothing. It defaults to 4.0.

  • saveImage (bool, optional) – if set to true, saves the image into the output directory. It defaults to False.

  • fileFormat (str, optional) – the extension of the output image. It defaults to ‘.png’ .

  • title (str, optional) – the title of the image. It defaults to None.

  • cmap (str, optional) – Matplotlib colormap. It defaults to ‘CMRmap’. Colormaps: https://matplotlib.org/tutorials/colors/colormaps.html

  • regFiles (list, optional) – A list containing region file(s) absolute path.

  • regFileColors (list, optional) – A list with a color for each region file, the length must be the same of regFiles.

  • catalogRegions (str, optional) – a catalog name. The regions that belongs to the catalog will be loaded. It defaults to None.

  • catalogRegionsColor (str, optional) – the color of the regions loaded from the catalog.

  • normType (str, optional) – It selects a normalization function for the data, possible valuses {‘linear’, ‘sqrt’, ‘power’, log’, ‘asinh’}, default ‘linear’.

Returns:

It returns the paths to the image files written on disk.

displayExpSkyMaps(maplistFile=None, singleMode=True, smooth=False, sigma=4.0, saveImage=False, fileFormat='.png', title=None, cmap='CMRmap', regFiles=None, regFileColors=[], catalogRegions=None, catalogRegionsColor='red', normType='linear')[source]

It displays the last generated exp skymaps.

Parameters:
  • maplistFile (str, optional) – the path to the .maplist file. If not specified, the last generated maplist file will be used. It defaults to None.

  • singleMode (bool, optional) – if set to true, all maps will be displayed as subplots on a single figure. It defaults to True.

  • smooth (float, optional) – the sigma value of the gaussian smoothing. It defaults to 4.0.

  • saveImage (bool, optional) – if set to true, saves the image into the output directory. It defaults to False.

  • fileFormat (str, optional) – the extension of the output image. It defaults to ‘.png’ .

  • title (str, optional) – the title of the image. It defaults to None.

  • cmap (str, optional) – Matplotlib colormap. It defaults to ‘CMRmap’. Colormaps: https://matplotlib.org/tutorials/colors/colormaps.html

  • regFiles (list, optional) – A list containing region file(s) absolute path

  • regFileColors (list, optional) – A list with a color for each region file, the length must be the same of regFiles

  • catalogRegions (str, optional) – a catalog name. The regions that belongs to the catalog will be loaded. It defaults to None.

  • catalogRegionsColor (str, optional) – the color of the regions loaded from the catalog.

  • normType (str, optional) – It selects a normalization function for the data, possible valuses {‘linear’, ‘sqrt’, ‘power’, log’, ‘asinh’}, default ‘linear’.

Returns:

It returns the paths to the image files written on disk.

displayGasSkyMaps(maplistFile=None, singleMode=True, smooth=False, sigma=4.0, saveImage=False, fileFormat='.png', title=None, cmap='CMRmap', regFiles=None, regFileColors=[], catalogRegions=None, catalogRegionsColor='red', normType='linear')[source]

It displays the last generated gas skymaps.

Parameters:
  • maplistFile (str, optional) – the path to the .maplist file. If not specified, the last generated maplist file will be used. It defaults to None.

  • singleMode (bool, optional) – if set to true, all maps will be displayed as subplots on a single figure. It defaults to True.

  • smooth (float, optional) – the sigma value of the gaussian smoothing. It defaults to 4.0.

  • saveImage (bool, optional) – if set to true, saves the image into the output directory. It defaults to False.

  • fileFormat (str, optional) – the extension of the output image. It defaults to ‘.png’ .

  • title (str, optional) – the title of the image. It defaults to None.

  • cmap (str, optional) – Matplotlib colormap. It defaults to ‘CMRmap’. Colormaps: https://matplotlib.org/tutorials/colors/colormaps.html

  • regFiles (list, optional) – A list containing region file(s) absolute path

  • regFileColors (list, optional) – A list with a color for each region file, the length must be the same of regFiles

  • catalogRegions (str, optional) – a catalog name. The regions that belongs to the catalog will be loaded. It defaults to None.

  • catalogRegionsColor (str, optional) – the color of the regions loaded from the catalog.

  • normType (str, optional) – It selects a normalization function for the data, possible valuses {‘linear’, ‘sqrt’, ‘power’, log’, ‘asinh’}, default ‘linear’.

Returns:

It returns the paths to the image files written on disk.

displayIntSkyMaps(maplistFile=None, singleMode=True, smooth=False, sigma=4.0, saveImage=False, fileFormat='.png', title=None, cmap='CMRmap', regFiles=None, regFileColors=[], catalogRegions=None, catalogRegionsColor='red', normType='linear')[source]

It displays the last generated int skymaps.

Parameters:
  • maplistFile (str, optional) – the path to the .maplist file. If not specified, the last generated maplist file will be used. It defaults to None.

  • singleMode (bool, optional) – if set to true, all maps will be displayed as subplots on a single figure. It defaults to True.

  • smooth (float, optional) – the sigma value of the gaussian smoothing. It defaults to 4.0.

  • saveImage (bool, optional) – if set to true, saves the image into the output directory. It defaults to False.

  • fileFormat (str, optional) – the extension of the output image. It defaults to ‘.png’ .

  • title (str, optional) – the title of the image. It defaults to None.

  • cmap (str, optional) – Matplotlib colormap. It defaults to ‘CMRmap’. Colormaps: https://matplotlib.org/tutorials/colors/colormaps.html

  • regFiles (list, optional) – A list containing region file(s) absolute path

  • regFileColors (list, optional) – A list with a color for each region file, the length must be the same of regFiles

  • catalogRegions (str, optional) – a catalog name. The regions that belongs to the catalog will be loaded. It defaults to None.

  • catalogRegionsColor (str, optional) – the color of the regions loaded from the catalog.

  • normType (str, optional) – It selects a normalization function for the data, possible valuses {‘linear’, ‘sqrt’, ‘power’, log’, ‘asinh’}, default ‘linear’.

Returns:

It returns the paths to the image files written on disk.

displayLightCurve(analysisName, filename=None, lineValue=None, lineError=None, saveImage=False, fermiLC=None)[source]

It displays the light curve plot. You can call this method after lightCurveMLE() or aperturePhotometry(). If you pass a filename containing the light curve data, this file will be used instead of using the data generated by the mentioned methods.

Parameters:
  • analysisName (str, required) – the analysis used to generate the light curve data: choose between ‘mle’ or ‘ap’.

  • filename (str, optional) – the path of the Lightcurve text data file. It defaults to None. If None the last generated file will be used.

  • lineValue (int, optional) – mean flux value. It defaults to None.

  • lineError (int, optional) – mean flux error lines. It defaults to None.

  • saveImage (bool, optional) – if set to true, saves the image into the output directory. It defaults to False.

  • fermiLC (str, optional) – the path of FERMI lightcurve data

Returns:

It returns the lightcurve plot

displayGenericColumns(filename, columns, um=None, saveImage=False)[source]

An utility method for viewing a generic column from the lightcurvedata

Parameters:
  • filename (str) – the path of the Lightcurve text data file. It defaults to None. If None the last generated file will be used.

  • columns (array of str) – the name of the columns to display(first display is always LC), possible values: (time_start_mjd | time_end_mjd | sqrt(ts) | flux | flux_err | flux_ul | gal | gal_error | iso | iso_error | l_peak | b_peak | dist_peak | l | b | r | ell_dist | a | b | phi | exposure | ExpRatio | counts | counts_err | Index | Index_Err | Par2 | Par2_Err | Par3 | Par3_Err | Erglog | Erglog_Err | Erglog_UL | time_start_utc | time_end_utc | time_start_tt | time_end_tt | Fix | index | ULConfidenceLevel | SrcLocConfLevel | start_l | start_b | start_flux | typefun | par2 | par3 | galmode2 | galmode2fit | isomode2 | isomode2fit | edpcor | fluxcor | integratortype | expratioEval | expratio_minthr | expratio_maxthr | expratio_size | Emin | emax | fovmin | fovmax | albedo | binsize | expstep | phasecode | fit_cts | fit_fitstatus0 | fit_fcn0 | fit_edm0 | fit_nvpar0 | fit_nparx0 | fit_iter0 | fit_fitstatus1 | fit_fcn1 | fit_edm1 | fit_nvpar1 | fit_nparx1 | fit_iter1 | fit_Likelihood1)

  • um (array of str) – unit of measurement, same length of columns

  • saveImage (bool) – if set to true, saves the image into the output directory. It defaults to False.

Returns:

If saveImage is true tha path of the image otherwise the plot

convertCatalogToXml(catalogFilepath)[source]

It takes a catalog file in AGILE (.txt) format as input and converts it in the xml format.

Parameters:

catalogFilepath (str) – a relative or absolute path to the catalog file in AGILE (.txt) format.

Raises:

SourceModelFormatNotSupported – if the input file format is not supported.

Returns:

A string rapresenting the path to the output file.

parseMaplistFile(maplistFilePath=None)[source]

It parses the maplistfile in order to return sky map files paths.

Parameters:
  • maplistFilePath (str) – if you don’t specify the maplistfile path, the

  • one (last generated) –

Returns:

A matrix where each row contains a cts, ext and gas map.

Raises:

MaplistIsNone – if no maplist file is passed and no maplist file have been generated yet.

AGAnalysisWavelet

class api.AGAnalysisWavelet.AGAnalysisWavelet(configurationFilePath, sourcesFilePath=None)[source]

This class contains the high-level API methods you can use to run wavelet analysis.

This class requires you to setup a yaml configuration file to specify the software’s behaviour.

WARNING: This class is deprecated due to the new Python wavelet tool in development

__init__(configurationFilePath, sourcesFilePath=None)[source]

AGAnalysis constructor.

Parameters:
  • configurationFilePath (str) – a relative or absolute path to the yaml configuration file.

  • sourcesFilePath (str, optional) – a relative or absolute path to a file containing the description of the sources. Defaults to None. Three different types of format are supported: AGILE format (.txt), XML format (.xml) and AGILE catalog files (.multi).

static getConfiguration(confFilePath, userName, outputDir, verboselvl, ctsmap, scaletype, scalemin, scalemax, scalenum, methistsize, cclsizemin, cclsizemax, cclradmin, cclradmax, cclscalemin, cclscalemax)[source]

Utility method to create a configuration file.

Parameters:
  • confFilePath (str) – the path and filename of the configuration file that is going to be created.

  • userName (str) – the username of who is running the software.

  • outputDir (str) – the path to the output directory. The output directory will be created using the following format: ‘userName_sourceName_todaydate’

  • verboselvl (int) – the verbosity level of the console output. Message types: level 0 => critical, warning, level 1 => critical, warning, info, level 2 => critical, warning, info, debug

  • ctsmap (str) – the path of cts map generated by AGAnalys class

  • scaletype (str) –

  • scalemin (float) –

  • scalemax (float) –

  • scalenum (int) –

  • methistsize (float) –

  • cclsizemin (float) –

  • cclsizemax (float) –

  • cclradmin (float) –

  • cclradmax (float) –

  • cclscalemin (float) –

  • cclscalemax (float) –

Returns:

None

waveletAnalysis()[source]

It runs the three science tools required to perform wavelet analysis, and it creates three directories respectively for any tool

waveletDisplay(fitsfile, saveImage=False, multiImage=False)[source]

It displays the wevelets generated by waveletAnalysis.

Parameters:
  • fitsfile (str) – fits filepath

  • saveImage (bool, optional) – if set to true, saves the image into the output directory. It defaults to False.

  • multiImage (bool) – if set to true plots an image for each wavelet

Returns:

It returns the paths to the image files written on disk.

AGBayesianBlocks

class api.AGBayesianBlocks.AGBayesianBlocks(configurationFilePath)[source]

Wrapper for the Bayesian Blocks Real-Time Analysis (RTA) module. Provides an interface to process data using Bayesian Blocks segmentation.

__init__(configurationFilePath)[source]

Initialize the AGBayesianBlocks class.

Parameters:

configurationFilePath (str) – a relative or absolute path to the yaml configuration file.

Raises:
  • AGILENotFoundError – if the AGILE environment variable is not set.

  • PFILESNotFoundError – if the PFILES environment variable is not set.

Example

>>> from agilepy.api import AGBayesianBlocks
>>> agilebb = AGBayesianBlocks('agconfig.yaml')
static getConfiguration(confFilePath, outputDir, filePath, userName='my_name', sourceName='bb-source', verboselvl=0, fileMode='AGILE_AP', rateCorrection=0, tstart='null', tstop='null', fitness='events', p0='null', gamma=0.35, useerror='true')[source]

Utility method to create a configuration file.

Parameters:
  • confFilePath (str) – the path and filename of the configuration file that is going to be created.

  • outputDir (str) – the path to the output directory. The output directory will be created using the following format: ‘userName_sourceName_todaydate’

  • userName (str) – the username of who is running the software.

  • sourceName (str) – the name of the source.

  • verboselvl (int) – the verbosity level of the console output. Message types: level 0 => critical, warning, level 1 => critical, warning, info, level 2 => critical, warning, info, debug

  • filePath (str) – The path to the data file.

  • fileMode (str or int) – it defines the format of the data. Allowed data formats: - UNBINNED data: AGILE_PH (1) - BINNED data: AGILE_AP (2), AGILE_MLE (3), CUSTOM_LC (4)

  • tstart (float) – Time start, stop in MJD to select events. If None, no selection is applied.

  • tstop (float) – Time start, stop in MJD to select events. If None, no selection is applied.

  • rateCorrection (None or 0 or float) – Multiplication factor to convert rates (cts/exp) into integers. - Set to None to not use. - Set to 0 to use the mean exposure (effective area * dt). - Set to a float value to use it directly.

  • fitness (str) – The fitness function to use.

  • p0 (float) – Prior on the number of blocks (optional). Calculated with eq. 21 in Scargle (2013)

  • gamma (float) – Regularization parameter (optional).

  • useerror – Flag for using error for computing blocks or not.

Returns:

None

selectEvents(file_path=None, file_mode=None, tstart=None, tstop=None, ratecorrection=None)[source]

Select an event by specifying its ID and data paths. If None, they are selected from the configuration.

Parameters:

file_pathstr

The path to the data file.

file_modestr, int or FileMode

FileMode to set read function and DataMode. Allowed data formats: - UNBINNED data: AGILE_PH (1) - BINNED data: AGILE_AP (2), AGILE_MLE (3), CUSTOM_LC (4)

tstart, tstopfloat

Time start, stop in MJD to select events. If None, no selection is applied.

ratecorrection: None or 0 or float

Multiplication factor to convert rates (cts/exp) into integers. - Set to None to not use. - Set to 0 to use the mean exposure (effective area * dt), typical value 1e7. - Set to a float value to use it directly.

headDetections(n=5)[source]

Return the first n rows of the detections DataFrame.

headEvents(n=5)[source]

Return the first n rows of the event DataFrame.

getDataOut()[source]

Return Output Data.

getDataIn()[source]

Return Input Data.

bayesianBlocks(fitness=None, p0=None, gamma=None, useerror=None)[source]

Compute the Bayesian blocks using the given parameters and plot the result.

Parameters:

fitnessstr

The fitness function to use (‘events’ by default).

p0float

Prior on the number of blocks (optional). Calculated with eq. 21 in Scargle (2013)

gammafloat

Regularization parameter (optional).

useerrorBool

Flag for using error for computing blocks or not.

plotBayesianBlocks(plotYErr=True, saveImage=False, plotBayesianBlocks=True, plotRate=False, plotDataCells=False, plotSumBlocks=False)[source]

Plot the data and the results of the Bayesian Blocks analysis.

Parameters:

plotYErrbool

Plot errors on Y data or not.

plotBayesianBlocksbool

Plot The Bayesian blocks over the data if they were computed.

plotRatebool

Add a second panel with the plot of the rate.

plotDataCellsbool

If True, plot the Data Cells vertical lines.

saveImagebool

Write a copy of the image if True.

plotSumBlocks :

Plot the Sum of the events in the Block if True.

AGRatemeters

class api.AGRatemeters.AGRatemeters(configurationFilePath)[source]

This class contains the high-level API to run analysis of the AGILE Ratemeters.

The constructor of this class requires a yaml configuration file.

__init__(configurationFilePath)[source]

AGRatemeters constructor.

Parameters:

configurationFilePath (str) – a relative or absolute path to the yaml configuration file.

Raises:
  • AGILENotFoundError – if the AGILE environment variable is not set.

  • PFILESNotFoundError – if the PFILES environment variable is not set.

Example

>>> from agilepy.api import AGRatemeters
>>> agratemeters = AGratemeters('agconfig.yaml')
static getConfiguration(confFilePath, outputDir, filePath, timetype, T0, background_tmin='null', background_tmax='null', signal_tmin='null', signal_tmax='null', userName='my_name', sourceName='rm-source', verboselvl=0)[source]

Utility method to create a configuration file.

Parameters:
  • confFilePath (str) – the path and filename of the configuration file that is going to be created.

  • outputDir (str) – the path to the output directory. The output directory will be created using the following format: ‘userName_sourceName_todaydate’

  • filePath (str) – The path to the data file.

  • timetype (str) – Format of the Burst Reference Time T0.

  • T0 (float or str) – Value of the Burst Reference Time T0.

  • background_tmin (float) – Min Time for Background computation.

  • background_tmax (float) – Max Time for Background computation.

  • signal_tmin (float) – Min Time for Signal computation.

  • signal_tmax (float) – Max Time for Signal computation.

  • userName (str) – the username of who is running the software.

  • sourceName (str) – the name of the source.

  • verboselvl (int) – the verbosity level of the console output. Message types: level 0 => critical, warning, level 1 => critical, warning, info, level 2 => critical, warning, info, debug

Returns:

None

readRatemeters(filePath=None, writeFiles=True)[source]

Read a file with ratemeters data and store it in a table. The table contains three columns: OBT Time (AGILE TT), Measured Counts, Detrended Counts. The detrending algorithm uses Fast Fourier Transforms.

Parameters:
  • (str) (filePath) –

  • (bool) (writeFiles) –

Returns:

ratemeters_table (dict of astropy.Table.table)

Return type:

each Table contains OBT time (AGILE TT), Counts, Detrended Counts.

plotRatemeters(plotInstruments=['3RM'], plotRange=(-100, 100), useDetrendedData=True)[source]

Plot Ratemeters Light Curves.

Parameters:
  • plotInstruments (list of str) – Keys of the instruments to plot (including “2RM”, “3RM”, “8RM”). Defaults to [“3RM”].

  • plotRange (tuple(float, float)) – Time limits of the plots, in seconds relative to T0.

  • useDetrendedData (bool) – If True, plot detrended counts, otherwise plot raw counts. Defaults to True.

Returns:

Plot output paths.

Return type:

plots (list(str) or None)

analyseSignal(backgroundRange=(None, None), signalRange=(None, None), useDetrendedData=True)[source]

Analyse the Burst in all tables.

Parameters:
  • backgroundRange (tuple(float, float)) – Time range for background selection, in seconds relative to T0.

  • signalRange (tuple(float, float)) – Time range for signal selection, in seconds relative to T0.

  • useDetrendedData (bool) – If True, use detrended data.

Returns:

Results table with Aperture Photometry Information.

Return type:

results (astropy.table.Table)

estimateDuration(dataRange, backgroundRange=(None, None), signalRange=(None, None), useDetrendedData=True, plotDuration=True)[source]

Estimate the Duration of the Burst with Cumulative Light Curves.

Parameters:
  • dataRange (tuple(float, float)) – Time range for the plot.

  • backgroundRange (tuple(float, float)) – Time range for background selection, in seconds relative to T0.

  • signalRange (tuple(float, float)) – Time range for signal selection, in seconds relative to T0.

  • useDetrendedData (bool) – If True, use detrended data.

  • plotDuration (bool) – if True, plot the Cumulative Light Curves.

Raises:

ValueError – if dataRange does not contain the Background or Signal Range.

Returns:

Dictionary of results. plot (str or None): Plot output path.

Return type:

data_dict (dict)

AGVisibility

class api.AGVisibility.AGVisibility(configurationFilePath)[source]

This class contains the high-level API methods you can use to run the visibility analysis.

This class requires you to setup a yaml configuration file to specify the software’s behaviour.

Class attributes:

config

it is used to read/update configuration values.

Type:

AgilepyConfig

logger

it is used to log messages with different importance levels.

Type:

AgilepyLogger

__init__(configurationFilePath)[source]

AGVisibility constructor.

Parameters:

configurationFilePath (str) – the relative or absolute path to the yaml configuration file.

Example

>>> from agilepy.api import AGVisibility
>>> ageng = AGVisibility('agconfig.yaml')
static getConfiguration(confFilePath, outputDir, logFile, step=30, timeType='tt', tmin='null', tmax='null', fermiSpacecraftFile=None, coord1='null', coord2='null', frame='icrs', userName='my_name', sourceName='vis-source', verboselvl=0)[source]

Utility method to create a configuration file.

Parameters:
  • confFilePath (str) – the path and filename of the configuration file that is going to be created.

  • outputDir (str) – the path to the output directory. The output directory will be created using the following format: ‘userName_sourceName_todaydate’.

  • logFile (str) – the path to the AGILE logfile containing spacecraft information.

  • fermiSpacecraftFile (str) – the path to the Fermi spacecraft file. Optional.

  • step (float) – time interval in seconds between 2 consecutive points in the resulting table. Minimum accepted value: 0.1. Default is 30.

  • timeType (str) – the time format of tmin and tmax.

  • tmin (float) – inferior, superior observation time limit to analize.

  • tmax (float) – inferior, superior observation time limit to analize.

  • coord1 (float) – the coordinates of the source used to compute the offaxis angle.

  • coord2 (float) – the coordinates of the source used to compute the offaxis angle.

  • frame (str) – the reference frame of the coordinates.

  • userName (str) – the username of who is running the software.

  • sourceName (str) – the name of the source.

  • verboselvl (int) – the verbosity level of the console output. Message types: level 0 => critical, warning, level 1 => critical, warning, info, level 2 => critical, warning, info, debug.

Returns:

None

computePointingDirection(logfilesIndex=None, tmin=None, tmax=None, timetype=None, step=None, src_x=None, src_y=None, frame=None, writeFiles=True)[source]

Compute the AGILE pointing direction and angular separation from a source in the sky. Values which are None are retreived from the configuration file. The pointing direction is extracted from the ATTITUDE_RA_Y and ATTITUDE_DEC_Y columns of the log files.

Parameters:
  • logfilesIndex (str) – the index file for the logfiles wiith spacecraft information.

  • tmin (float) – inferior, superior observation time limit to analize.

  • tmax (float) – inferior, superior observation time limit to analize.

  • timetype (str) – the time format of tmin and tmax.

  • step (integer) – time interval in seconds between 2 consecutive points the table. Minimum accepted value: 0.1.

  • src_x (float) – the coordinates of the source used to compute the offaxis angle, in degrees.

  • src_y (float) – the coordinates of the source used to compute the offaxis angle, in degrees.

  • frame (str) – the reference frame of the coordinates.

  • writeFiles (bool) – if True, write the visibility table.

Returns:

the table with the AGILE pointing direction and source separation in degrees.

Return type:

visibility_tab (astropy.table.Table)

getFermiPointing(fermiSpacecraftFile=None, tmin=None, tmax=None, timetype=None, src_x=None, src_y=None, frame=None, writeFiles=True)[source]

Compute the Fermi pointing direction and angular separation from a source in the sky. Values which are None are retreived from the configuration file. The pointing direction is extracted from the RA_SCZ and DEC_SCZ columns of the spacecraft file.

Parameters:
  • fermiSpacecraftFile (str) – the path to the Fermi spacecraft file. If None, it is retrieved from the configuration file.

  • tmin (float) – inferior, superior observation time limit to analize.

  • tmax (float) – inferior, superior observation time limit to analize.

  • timetype (str) – the time format of tmin and tmax.

  • src_x (float) – the coordinates of the source used to compute the offaxis angle, in degrees.

  • src_y (float) – the coordinates of the source used to compute the offaxis angle, in degrees.

  • frame (str) – the reference frame of the coordinates.

  • writeFiles (bool) – if True, write the visibility table.

Returns:

the table with the Fermi pointing direction and source separation in degrees.

Return type:

visibility_tab (astropy.table.Table)

plotVisibility(sourceCoordinates=None, maxOffaxis=None, mjd_limits=None, plotFermi=True, showPositionPanels=False, plotHistogram=True, saveImages=True)[source]

Plot the offaxis angle of a source from the AGILE and Fermi pointing directions as a function of time, and the histogram of the offaxis angles.

Parameters:
  • sourceCoordinates (astropy.coordinates.SkyCoord) – the coordinates of the source used to compute the offaxis angle, If None, the offaxis angle must already be computed in the visibility table.

  • maxOffaxis (float) – maximum offaxis angle in degrees to be shown in the visibility plot.

  • mjd_limits (tuple(float,float), optional) – Plot limits in MJD.

  • plotFermi (bool) – if True, plot the Fermi offaxis angle distribution.

  • plotHistogram (bool) – if True, plot the histogram of the offaxis angles.

  • saveImage (bool) – if True, save the images in the output directory.

  • showPositionPanels (bool) – if True, show satellite Direction.

Returns:

Plot output paths.

Return type:

plots (list(str) or None)