Utilities

Several useful utilities used throughout the various Data Tools modules

Coordinate/Geometry

The following functions in gbm.coords are used in various coordinate transforms and geometry calculations.

gbm.coords.azzen_to_cartesian(az, zen, deg=True)[source]

Convert spacecraft azimuth/zenith to Cartesian coordinates

Parameters
  • az (float or np.array) – Spacecraft azimuth

  • zen (float or np.array) – Spacecraft zenith

  • deg (bool, optional) – True (default) if input is in degrees, otherwise input is radians

Returns

np.array – 3-element Cartesian coordinate

gbm.coords.calc_mcilwain_l(latitude, longitude)[source]

Estimate the McIlwain L value given the latitude (-30, +30) and East Longitude. This uses a cubic polynomial approximation to the full calculation and is similar to the approach used by the GBM FSW.

Parameters
  • latitude (np.array) – Latitude in degrees from -180 to 180

  • longitude (np.array) – East longitude in degrees from 0 to 360

Returns

np.array – McIlwain L value

gbm.coords.geocenter_direction_cosines(gz, az, zen, deg=True)[source]

Create n geocenter direction cosine matrix(es) for a position or positions in spacecraft coordinates

Parameters
  • gz (np.array) – Geocenter vector in spacecraft Cartesian coordinates

  • az (float or np.array) – The azimuth location of positions in spacecraft coordinates

  • zen (float or np.array) – The zenith location of positions in spacecraft coordinates

  • deg (bool, optional) – If True, the input is in degrees. Default is True.

Returns

np.array – (3,3, n) array containing the geocenter direction cosines for each point

gbm.coords.geocenter_in_radec(coord)[source]

Calculate the location of the Earth center RA and Dec

Parameters

coord (np.array) – (3, n) array containing Geocentric cartesian coordinates in meters

Returns

(np.array, np.array) – RA and Dec of Earth center as viewed by Fermi in degrees

gbm.coords.geocenter_to_spacecraft(phi, theta, geo_cosines)[source]

Convert n points from geocenter frame to spacecraft frame

Parameters
  • phi (float or np.array) – The azimuthal location of positions in geocentric coordinates

  • theta (float or np.array) – The polar location of positions in geocentric coordinates

  • geo_cosines (np.array) – (3,3) array containing the direction cosines

Returns

(np.array, np.array) – Azimuth and zenith positions in the spacecraft frame

gbm.coords.get_sun_loc(met)[source]

Calculate sun location in RA/Dec for a given MET.

Parameters

met (float) – The MET time(s)

Returns

(float, float) – RA and Dec of the sun

gbm.coords.haversine(lon1, lat1, lon2, lat2, deg=True)[source]

Calculates the angular separation between two points using the haversine equation. If degrees are passed, degrees are returned. else the input/output is assumed to be radians. lon -> azimuth lat -> zenith

Parameters
  • lon1 (float) – lon/az of first point

  • lat1 (float) – lat/zen of first point

  • lon2 (float) – lon/az of second point

  • lat2 (float) – lat/zen of second point

  • deg (bool, optional) – True if input/output in degrees.

Returns

float – Angular separation between points

gbm.coords.latitude_from_geocentric_coords_complex(coord)[source]

Calculate latitude from Geocentric Cartesian coordinates. Uses the WGS 1984 model of the shape of the Earth. Also returns altitude.

Parameters

coord (np.array) – (3, n) array containing Geocentric cartesian coordinates in meters

Returns

(np.array, np.array) – Position of Fermi in Earth Latitude and altitude in meters

gbm.coords.latitude_from_geocentric_coords_simple(coord)[source]

Calculate latitude from Geocentric Cartesian coordinates. Assumes the Earth is a simple sphere. Also returns altitude.

Parameters

coord (np.array) – (3, n) array containing Geocentric cartesian coordinates in meters

Returns

(np.array, np.array) – Position of Fermi in Earth Latitude and altitude in meters

gbm.coords.longitude_from_geocentric_coords(coord, met, ut1=False)[source]

Calculate the East longitude from Geocentric coordinates. Requires the conversion of Fermi MET to sidereal time to rotate the Earth under the spacecraft. The conversion can either be performed using UTC (less accurate) or UT1 (more accurate) which uses IERS tables to correct for variations in Earth rotation velocity

Parameters
  • coord (np.array) – (3, n) array containing Geocentric cartesian coordinates in meters

  • met – (float or np.array): The MET time(s)

  • ut1 (bool, optional) – If True, use UT1 instead of UTC to calculate sidereal time. Default is False

Returns

np.array or float – Position of Fermi in East Longitude

gbm.coords.quaternion_conj(quat)[source]

Calculate conjugate of quaternion

Note

GBM quaternions are defined with the last element as the scalar value

Parameters

quat (np.array) – 4-element quaternion

Returns

np.array – quaternion conjugate

gbm.coords.quaternion_inv(quat)[source]

Calculate inverse of quaternion

Note

GBM quaternions are defined with the last element as the scalar value

Parameters

quat (np.array) – 4-element quaternion

Returns

np.array – quaternion inverse

gbm.coords.quaternion_prod(quat1, quat2)[source]

Calculate product of two quaternions

Note

GBM quaternions are defined with the last element as the scalar value

Parameters
  • quat1 (np.array) – 4-element quaternion

  • quat2 (np.array) – 4-element quaternion

Returns

np.array – product of the quaternions

gbm.coords.radec_to_cartesian(ra, dec, deg=True)[source]

Convert RA/Dec to Cartesian coordinates

Parameters
  • ra (float or np.array) – Right Ascension

  • dec (float or np.array) – Declination

  • deg (bool, optional) – True (default) if input is in degrees, otherwise input is radians

Returns

np.array – 3-element Cartesian coordinate

gbm.coords.radec_to_spacecraft(ra, dec, quat, deg=True)[source]

Convert a position in J2000 RA/Dec to spacecraft coordinates (Az/Zen). The options for input for this function are as follows:

  • a single RA/Dec position and multiple attitude transforms

  • multiple RA/Dec positions and a single attitude transform

  • multiple RA/Dec positions each with a corresponding attitude transform

Parameters
  • ra (float or np.array) – Right Ascension

  • dec (float or np.array) – Declination

  • quat (np.array) – (4, n) spacecraft attitude quaternion array

  • deg (bool, optional) – True if input/output in degrees.

Returns

(np.array, np.array) – Spacecraft azimuth and zenith of the transformed position

gbm.coords.saa_boundary()[source]

The coordinates of the SAA boundary in latitude and East longitude

Returns

(np.array, np.array) – The latitude and East longitude values

gbm.coords.spacecraft_direction_cosines(quat)[source]

Convert n spacecraft quaternions to direction cosine matrix

Parameters

quat (np.array) – (4, n) element array of quaternions

Returns

np.array – (3,3, n) array containing the spacecraft direction cosines

gbm.coords.spacecraft_to_radec(az, zen, quat, deg=True)[source]

Convert a position in spacecraft coordinates (Az/Zen) to J2000 RA/Dec The options for input for this function are as follows:

  • a single Az/Zen position and multiple attitude transforms

  • multiple Az/Zen positions and a single attitude transform

  • multiple Az/Zen positions each with a corresponding attitude transform

Parameters
  • az (float or np.array) – Spacecraft azimuth

  • zen (float or np.array) – Spacecraft zenith

  • quat (np.array) – (4, n) spacecraft attitude quaternion array

  • deg (bool, optional) – True if input/output in degrees.

Returns

(np.array, np.array) – RA and Dec of the transformed position


Detector Definitions

The class in gbm.detector contains the GBM Detector parameters.

class gbm.detectors.Detector(value)[source]

Bases: enum.Enum

The GBM detector names and pointings.

Attributes
  • pointing (float, float) – The spacecraft Azimuth/Zenith pointing

  • short_name (str) – The short name of the detector (e.g. NaI 0 -> ‘n0’)

classmethod bgo()[source]

Get all detectors that are BGOs

Returns

list of Detector – The BGO detectors

classmethod from_num(num)[source]

Create a Detector from an index number

Parameters

num (int) – The index number

Returns

Detector – The detector enum

classmethod from_str(value)[source]

Create a Detector from a short string name (e.g. ‘n0’)

Parameters

value (str) – The short name

Returns

Detector – The detector enum

is_bgo()[source]

Check if detector is a BGO

Returns

bool – True if detector is BGO, False otherwise.

is_nai()[source]

Check if detector is an NaI

Returns

bool – True if detector is NaI, False otherwise.

classmethod nai()[source]

Get all detectors that are NaIs

Returns

list of Detector – The NaI detectors


Filenaming

The class in gbm.file contains the standardized definitions for the GBM file naming scheme and other associated utilities

class gbm.file.GbmFile[source]

Parse or construct a GBM standardized filename.

Attributes
  • data_type (str) – The datatype of the file

  • detector (str) – The detector with which the file is associated

  • directory (str) – The directory hosting the file

  • extension (str) – The filename extension

  • meta (str) – Additional metadata in the filename

  • trigger (bool) – True if the file is from a trigger. False otherwise

  • uid (str) – The unique id of the file

  • version (int) – The version number of the file

basename()[source]

The file basename

Returns

str – The file basename

classmethod create(**kwargs)[source]

Create a GbmFile from keywords

Parameters

**kwargs – The properties of a GbmFile

Returns

GbmFile – The new filename object

detector_list()[source]

Generate a list of GbmFile objects, one for each GBM detector

Returns

list of GbmFile – The new filename objects

classmethod from_path(path)[source]

Create a GbmFile from parsing a filename

Parameters

path (str) – A filename path

Returns

GbmFile – The new filename object

classmethod list_from_paths(path_list, unknown=None)[source]

Create a many GbmFiles from a list of filepaths

Parameters

path_list (list of str) – List of filepaths

Returns

list of GbmFile – The new filename object(s)

path()[source]

The file path

Returns

str – The path

version_str()[source]

Return the file version number as a string

Returns

str – The file version

gbm.file.all_exists(file_list, parent_dir=None)[source]

Do all the files in the list exist in the filesystem?

Parameters
  • file_list (list of str) – List of file names to check

  • parent_dir (str, optional) – parent directory

Returns

bool – True if all files exist

gbm.file.has_detector(file_list, detector)[source]

Does the file list contain a file for the given detector?

Parameters
  • file_list (list of str) – List of file names

  • detector (str) – Detector being searched

Returns

bool – True if the list of file names includes the given detector

gbm.file.is_complete(file_list)[source]

Does the file list contain a file for every detector?

Parameters

file_list (list of str) – List of files that represent a detector set

Returns

bool – True if the file list contains a file for every detector

gbm.file.max_version(file_list)[source]

Returns the maximum _version of file name in the given list

Parameters

file_list (list of str) – list of file names

Returns

int – Largest _version number in the list

gbm.file.min_version(file_list)[source]

Returns the minimum _version of file name in the given list

Parameters

file_list (list of str) – list of file names

Returns

int – Smallest _version number in the list

gbm.file.scan_dir(path, hidden=False, recursive=False, absolute=False, regex=None)[source]

Scans the given directory for files.

Parameters
  • path (str) – The root directory to scan.

  • hidden (bool, optional) – Set True if you want to include hidden files.

  • recursive (bool, optional) – Set True if you want to scan subdirectories within the given path.

  • absolute (bool, optional) – Set true if you want the absolute path of each file returned.

  • regex (str) – Set if you want to only return files matching the given regular expression.

Yields

str – Full path to a file for each iteration.


Time Conversions

The class in gbm.time contains Fermi MET time definition, a class for time conversions to and from Fermi MET and other time utilities.

class gbm.time.Met(secs)[source]

Bases: object

Class representing the Fermi MET Epoch and allowing time conversions to and from it.

Parameters

secs (float) – The MET

Attributes
  • bn (str) – The MET converted to bust number format: ‘YYMMDDfff’

  • datetime (datetime.datetime) – A datetime object for the MET

  • gps (float) – The number of seconds since Jan 6, 1980 00:00:00 (leap seconds are removed)

  • jd (float) – The Julian Date associated with the MET

  • met (float) – The MET

  • mjd (float) – The modified Julian Date associated with the MET

  • time (astropy.time.Time) – The astropy time object for the MET

  • unix (float) – The number of seconds since Jan 1, 1970 00:00:00 with the leap seconds removed

  • ymd (str) – The MET converted to the form YYMMDD in UTC

  • ymd_h (str) – The MET converted to the form of YYMMDD_HHz in UTC

add(x)[source]

Returns an Met object with its value set to this object’s value with x seconds added to it. Can also use the + operator.

Parameters

x (float) – seconds to add

Returns

Met – The Met object

classmethod from_bn(bn)[source]

Creates a new Met object from a ‘YYMMDDfff’ string

Parameters

bn (str) – A burst number string

Returns

Met – The Met object

classmethod from_datetime(dt)[source]

Creates a new Met object from a datetime.datetime object

Parameters

dt (datetime.datetime) – The datetime object

Returns

Met – The Met object

classmethod from_gps(gps)[source]

Creates a new Met object from a GPS timestamp

Parameters

gsp (float) – A GPS time

Returns

Met – The Met object

classmethod from_iso(str_time)[source]

Create a new Met object from an ISO-format UTC string

Parameters

str_time (str) – The ISO string

Returns

Met – The Met object

classmethod from_jd(jd)[source]

Creates a new Met object from a Julian Date

Parameters

jd (float) – A Julian Date

Returns

Met – The Met object

classmethod from_mjd(mjd)[source]

Creates a new Met object from a Modified Julian Date

Parameters

mjd (float) – A Modified Julian Date

Returns

Met – The Met object

classmethod from_time(atime)[source]

Creates a new Met object from an astropy.Time object

Parameters

atime (astropy.time.Time) – The astropy time object

Returns

Met – The Met object

classmethod from_unix(unix)[source]

Creates a new Met object from a Unix timestamp

Parameters

unix (float) – A Unix time

Returns

Met – The Met object

classmethod from_ymd(ymd)[source]

Creates a new Met object from a ‘YYMMDD’ string

Parameters

ymd (str) – A YYMMDD string

Returns

Met – The Met object

classmethod from_ymd_h(ymd)[source]

Creates a new Met object from a ‘YYMMDD_HHz’ string

Parameters

ymd (str) – A YYMMDD_HHz string

Returns

Met – The Met object

iso()[source]

Returns the MET value as a string in the form of yyyy-mm-ddTHH:MM:SS in UT

Returns

str: the ISO string

classmethod now()[source]

Creates a new Met object from the current time

Returns

Met – The Met object

sub(x)[source]

Returns an Met object with its value set to this object’s value with x seconds subtracted from it. Can also use the - operator.

Parameters

x (float) – seconds to subtract

Returns

Met – The Met object

class gbm.time.TimeFermiSec(val1, val2, scale, precision, in_subfmt, out_subfmt, from_jd=False)[source]

Bases: astropy.time.formats.TimeFromEpoch

Represents the number of seconds elapsed since Jan 1, 2001 00:00:00 UTC including leap seconds

property cache

Return the cache associated with this instance.

property epoch

Reference epoch time from which the time interval is measured

property scale

Time scale

set_jds(val1, val2)

Initialize the internal jd1 and jd2 attributes given val1 and val2. For an TimeFromEpoch subclass like TimeUnix these will be floats giving the effective seconds since an epoch time (e.g. 1970-01-01 00:00:00).

to_value(parent=None, **kwargs)

Return time representation from internal jd1 and jd2. Subclasses that require parent or to adjust the jds should override this method.

property value

Return time representation from internal jd1 and jd2. Subclasses that require parent or to adjust the jds should override this method.

gbm.time.dates_from_hours(hours)[source]

Converts a list of hours to a list of days spanned

Parameters

hours (list of datetime.date) – List of hours

Returns

list – The list of dates

gbm.time.dates_range_from(num_days, dt=datetime.date(2022, 5, 10))[source]

Creates a list of dates within the given range

Parameters
  • num_days (int) – Number of days to include in the list

  • dt (datetime.date, optional) – The last date to be included in the list. Default is current date.

Returns

list – List of date values representing hours.

gbm.time.fraction_of_day_to_hms(value)[source]

The hour, minute, second for a given fraction of day

Parameters

value (float) – The fraction of day

Returns

(int, int, int) – Hour, minute, second

gbm.time.hms_to_fraction_of_day(value)[source]

The fraction of day as computed by the original ops code.

Parameters

value (datetime.datetime) – The date/time

Returns

float – The fraction of day

gbm.time.hours_range_from(num_hours, dt=datetime.datetime(2022, 5, 10, 18, 33, 40, 896597))[source]

Creates a list of datetimes within the given range

Parameters
  • num_hours (int) – Number of hours to include in the list

  • dt (datetime.datetime, optional) – The last hour to be included in the list (datetime will be truncated to hour value). Default is current hour.

Returns

list – List of datetime values representing hours.

gbm.time.inclusive_date_range(start, stop, step=datetime.timedelta(days=1))[source]

Creates a list of Met from start to stop times

Parameters
  • start (Met) – The start MET

  • stop (Met) – The end MET

  • ( (step) – class:`datetime.timedelta, optional): The step size. Default is 1 day.

Returns

list of Met – The list of Met objects