BurstCube Documentation Documentation

68
BurstCube Documentation Documentation Release 1.0.0 Noah Kasmanoff Jan 21, 2022

Transcript of BurstCube Documentation Documentation

Page 1: BurstCube Documentation Documentation

BurstCube DocumentationDocumentation

Release 1.0.0

Noah Kasmanoff

Jan 21, 2022

Page 2: BurstCube Documentation Documentation
Page 3: BurstCube Documentation Documentation

Contents

1 Introduction 11.1 Getting Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Documentation Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Python Module Index 57

Index 59

i

Page 4: BurstCube Documentation Documentation

ii

Page 5: BurstCube Documentation Documentation

CHAPTER 1

Introduction

This is the BurstCube’s documentation page. For more information about the misson, please refer to the BurstCubeWebsite.

BurstCube’s documentation is built with a series of different functions and modules that allow the following:

• Creating different geometry files to allow for new arrangements of BurstCube to be subject to testing.

• Creating source files of ranging sky locations and energies.

• Quick manipulation of the MEGAlib Cosima function to permit quick simulations.

• Packages such as bcSim and plotSim that grant fast and effective data processing.

BurstCube uses a configuration-file driven workflow in which the analysis parameters (data selection, IRFs, and ROImodel) are defined in a YAML configuration file. Analysis is executed through a python script.

1.1 Getting Help

If you have questions about using this please open a GitLab Issue

1.2 Documentation Contents

1.2.1 Installation

Install the code via

$ python setup.py install --user

1

Page 6: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

Requirements

• MEGAlib

• gbm-data-tools (not yet public, will be released soon)

• ephem

• numpy

• pytest

• PyYAML

See ci.Dockerfile for an example on how to install them.

Docker

Docker containers are available at https://hub.docker.com/u/burstcube

1.2.2 Tutorials

Tutorial for various components of the bc-tools library. These are Python notebooks that you can execute interactively.

Create and inspect a detector response for one burst

A detector response matrix codifies two sets of quantities:

1. The effective area as a function of energy. That is, the equivalent collection area a perfect detector would havethat will result in the same number of counts for a given flux.

2. The probability of a photon of energy 𝐸 to be assigned to a channel energy 𝐸′

These allow us to reconstruct physical quantities —e.g. spectrum and localization— out of simple counts.

The detector response matrix is then a 2D matrix of “real” photon energy versus assigned channel energy. Each entryis the effective area of the corresponding photon energy bin, times the fraction of events in the photon energy bin thatland in the corresponding channel energy.

This matrix is generated based on particle-by-particle simulations using the app bc-rsp. The basic usage is

$ bc-rsp config_file working_dir --ntriggers NTRIGGERS --direction ZENITH AZIMUTH

You can see other optional arguments by using the --help flag or by looking at the “Scripts” documentation.

The config_file argument is the path to the YAML configuration file. An example is provided with this library.You can find the path to it either using the following command line executable:

$ bc-config-example-path

or using the API:

[1]: from BurstCube.config import Configurator

Configurator.config_example_path()

[1]: PosixPath('/Users/imartin5/BurstCube/software/bc-tools/BurstCube/config/bc_config.yaml→˓')

2 Chapter 1. Introduction

Page 7: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

bc-rsp uses the parameters in the simulations and detector section of the config file. Worth mentioning arethe parameters from simulations:detector_effects. These codify the results from calibration and indicateshow to simulate effects from a realistic detector, such as energy resolution and efficiency.

The final output of bc-rsp is a GBM RSP file for each detector. There are also complementary files with the suffix_peak.rsp, which corresponse to the detector response including only events from the photopeak, that is, thosephotons which deposited all of their energy in a given detector.

You can open these files directly using the gbm library, e.g.

[2]: from gbm.data import RSP

# Test dataimport BurstCube.data as data

# Response from zenith (of the whole instrument, not a single detector)rsp = RSP.open(data.path / "sims/SQD0_zenith.rsp")rsp_peak = RSP.open(data.path / "sims/SQD0_zenith_peak.rsp")

you can then plot it

[3]: from gbm.plot import ResponseMatrix

rsp_plot = ResponseMatrix()rsp_plot.set_response(rsp, color="plasma")

The projection onto the x-axis is the effective area

[4]: from gbm.plot import PhotonEffectiveArea

import matplotlib.pyplot as plt

(continues on next page)

1.2. Documentation Contents 3

Page 8: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

(continued from previous page)

fig,ax = plt.subplots(dpi=150)

effarea_energy = PhotonEffectiveArea(data=rsp, axis=ax)effarea_energy._data.color = 'orange' #Workaround

effarea_energy_peak = PhotonEffectiveArea(data=rsp_peak, axis=ax)

ax.legend([effarea_energy._data._artists[0],effarea_energy_peak._data._artists[0]],[→˓"Total", "Photopeak"]); #Workaround

<Figure size 770x470 with 0 Axes>

<Figure size 770x470 with 0 Axes>

This is the typical reponse for a gamma-ray detector using scintillator, such as BurstCube, GBM or BATSE. At lowenergies there is a cutoff since the photons are not energetic enough to reach the scintillator and get a measurement.At high energies, pair-production dominates the total effective area. Although the gamma-rays do interact with thedetector and produce a count, only a small fraction of the energiy is deposited. This cutoff can be seen in photopeakresponse, where we only considered those events that were fully absorbed due to either the photoelectric effect or incombination with other effects such as Compton scattering.

Having the full detector response allows us to account for the energy resolution and contamination by these partially-absorbed events. In practice, GRBs and other sources typically have a falling spectrum with an index of & −1.5, sosimulating up to ~10 MeV is sufficient.

You can also open an .rsp file directly using the bc-tools library:

[5]: from BurstCube.sims import DRM

drm = DRM.from_gbm_rsp_file(data.path / "sims/SQD0_zenith.rsp")

4 Chapter 1. Introduction

Page 9: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

[6]: import matplotlib.pyplot as plt

Note that you can go back and forth between GBM’s RSP and the native DRM with DRM.from_rsp() and DRM.to_rsp().

As an example on how to use a DRM let’s plot the expected measured counts per second from a monoenergetic source.Say our source is 137Cs (peak energy at 662 keV), has an activity of 1 𝜇Ci and is located at 1 m from the center of thedetector.

[7]: # We used the BurstCube's units module to keep track of units.# These are just constants, with the value of 1 assigned to base units (keV, s, cm).from BurstCube.util import units as u

energy = 662 * u.keVactivity = 3.7e4 / u.s # 1 uCidistance = 1 * u.meterflux = activity / (4*u.pi*distance**2) # Photons per area

# drm.energy_channels gives you an Axis object describing the binning of the energy→˓channels# from which you can get the centers, edges, lower_bounds, upper_bounds, or the→˓number of channels (nbins)energy_channels = drm.energy_channels

# We can get the total expected counts using:tot_rate = flux * drm.effective_area(energy)

print("Total rate = {:.2} Hz".format(tot_rate * u.s))

# However, due to a finite energy resolution and other instrumental effects, there is→˓an energy spreadchannel_rate = flux * drm.channel_effective_area(energy, range(energy_channels.nbins))

# Plot itfig,ax = plt.subplots(dpi=150)

ax.plot(energy_channels.lower_bounds,channel_rate,drawstyle = 'steps-post')

ax.set_xscale('log')

ax.set_ylabel("Expected count rates [Hz]")ax.set_xlabel("Channel energy [MeV]");

Total rate = 9.2 Hz

1.2. Documentation Contents 5

Page 10: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

In this case we assumed that the source is sufficiently far away to model it with a detector response with a sourceat infinity (the default). Furthermore, this assumes that there are no nearby sources of scattering or attenuation.An improvement of this would be to generate a detector response with the command line option --distance inbc-rsp. This would mimic more accurately, for example, what happens during calibration.

Working with a full instrument response

In the last tutorial we saw how to use an RSP file, which contains the response for a single detector and a singlecoordinate. If you don’t provide bc-rsp with the --direction flag, it will generate an HDF5 file containningthe detector response matrices (DRMs) for all detectors and multiple directions covering the full sky (in a HEALPixgrid). If you want to use the GBM software, a convenient way to get an RSP file from a full DRM is to use the scriptbc-rsp-extractor.

You can also get information directy from the DRM. The class to access this file is BurstCube.io.DRM. For exam-ple, let’s get the effective area at 100 keV as a function of the angle with respect to to the normal of the first SingleQuarter Detector:

[1]: import BurstCube.data as datafrom BurstCube.io import InstrumentResponsefrom BurstCube.util.coords import SpacecraftCoordsimport BurstCube.util.units as u

import matplotlib.pyplot as pltimport numpy as np

theta = np.linspace(0,360, 360)*u.deg(continues on next page)

6 Chapter 1. Introduction

Page 11: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

(continued from previous page)

energy = 100 * u.keV

# The best way to work with them is to use them as context manager# The alternative to using context manager is to remember to call close() when you→˓are done with the file.with InstrumentResponse(data.path/'sims/drm.h5') as irf:

# You can get a list of the detector IDsprint("Detectors: {}".format(irf.detectors))

# SQD0 zenith is pointing at 45d,45d in the spacecraft coordinateseff_area = []

for angle in theta:

coords = SpacecraftCoords(45*u.deg + angle, 45*u.deg)

drm = irf.get_drm("SQD0", coords = coords)

eff_area += [drm.effective_area(energy)]

fig,ax = plt.subplots()

ax.plot(theta/u.deg, eff_area);

ax.set_xlim(0,360)

ax.set_xlabel("SQD0 zenith angle [deg]")ax.set_ylabel("Effective area [cm$^2$]");

Detectors: ['SQD0', 'SQD1', 'SQD2', 'SQD3']

The effective area is not symmetric around 180∘ because the shadowing effect from the other simulated componentsis taken into account.

This plot is not very smooth because the underlying DRM used for this example has low resolution. You can see thiswith

1.2. Documentation Contents 7

Page 12: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

[2]: with InstrumentResponse(data.path/'sims/drm.h5') as irf:

nside = irf.nside

print("Underlying HEALPix NSIDE = {}".format(nside))print("This means only {} directions were simulated".format(12*nside*nside))

Underlying HEALPix NSIDE = 2This means only 48 directions were simulated

Localization

In this tutorial we’ll estimate the localization of a source based on a classical maximum likelihood estimate (MLE)method.

The key class is TSMap which generates a test statistics map based on one or more objects of the LocLike class.All derived classes of LocLike provide the likelihood for a given coordinate through the get_log_like method.This allows multiple instruments to participate in a joint fit by creating an appropiate LocLike subclass.

For this example we’ll use the simple NormLocLike subclass, which defines the Poisson likelihood for a photon-counting experiment as

logℒ(𝑁) =∑︁𝑖

log𝑃 (𝜆 = 𝑏𝑖 + 𝑁𝑒𝑖; 𝑑𝑖) =∑︁𝑖

log𝜆𝑑𝑖𝑒𝜆

𝑑𝑖!,

where

• 𝑑𝑖 are the set of counts detected by each detector

• 𝑏𝑖 are the estimated background counts

• 𝑒𝑖 are the estimated excess counts for a given hypothesis

• 𝑁 , the only free parameter, is the overall normalization.

We proceed to use a full instrument response file to compute the estimated excess counts e_i based on a fiducial 1sburst with an index -2 power law spectrum:

[3]: import BurstCube.data as datafrom BurstCube.io import InstrumentResponsefrom BurstCube.loc import LocalLocTablefrom BurstCube.spectra.spectrum import PowerLaw

# Convolve an full instrument response with a hypothetical spectrumirf_path = data.path/'sims/drm.h5'

with InstrumentResponse(irf_path) as irf:

# Hypothetical spectrum# This normalization corresponds to 1 ph/cm2/s between 50-300 keVspectrum = PowerLaw(60, 2)

# In this case we integrate the rate from all energy channels.# You can subdivide the data into multiple energy channel groupslocal_loctable = LocalLocTable.from_irf(irf, spectrum)

# The local_loctable contains the expected rates in spacecraft coordinates# We now need to use this to estimate the total expected counts in sky coordinate for

(continues on next page)

8 Chapter 1. Introduction

Page 13: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

(continued from previous page)

# the full duration of an event.# In this case we simply have a 1 second event and specifying the attitude by a→˓quaternion# ([0,0,0,1] corresponds to the identity rotation). You can have multiple attitude-→˓duration# pairs to correctly model long duration events.sky_loctable = local_loctable.to_skyloctable(attitude = [0,0,0,1], duration = 1)

Here’s how the look-up tables in norm_likelihood look. Note that we’re using a low-resolution instrument re-sponse. Although these tables are bilinearly interpolated, you typically need a resolution comparable to the localizationuncertainty you expect.

[2]: print(f"Look-up tables: {sky_loctable.labels}")

sky_loctable.get_expectation_map('SQD0').plot();

Look-up tables: ['SQD0' 'SQD1' 'SQD2' 'SQD3']

Now that we have the expected excessthe remaining ingredients are the actual measured counts and their correspondingestimated background counts. For real event these come from data. In this case we’ll simulate a background rate of 1kHz per detector and a source of 2 ph/cm2/s at (RA = 60deg, Dec = 45deg)

[4]: from astropy.coordinates import SkyCoordimport astropy.units as u

# 1 kHz per detector (we're simulating a 1s burst)bkg = [1000, 1000, 1000, 1000]sky_loctable.set_background(bkg)

(continues on next page)

1.2. Documentation Contents 9

Page 14: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

(continued from previous page)

# Injected source locationcoord = SkyCoord(ra = 60*u.deg, dec = 45*u.deg)

# 2 ph/cm2/s between 50-300 keV (our hypothetital source was 1 ph/cm2/s)signal = 2*sky_loctable.get_expectation(coord)

sky_loctable.set_data(bkg + signal)

With all the ingredients in place, we can now compute a test-statistics map:

[5]: from BurstCube.loc import TSMap, NormLocLike

# NormLocLike is a subclass of LocLike and computes# a Poisson likelihood for counting instruments. The# overall normalization is the only free parameternorm_likelihood = NormLocLike(sky_loctable)

# Define a map of nside = 32. Note that this is a finer resolution# that the underlying look-up table, which will be interpolatedts = TSMap(nside = 32)

# Compute the TS map from one or more LocLikelihoodts.compute(norm_likelihood)

These are the results:

[6]: import numpy as npprint(f"Maximum sqrt(TS) = {np.sqrt(np.max(ts)):.2f}")print(f"Best estimate: RA = {ts.best_loc().ra:.2f} Dec= {ts.best_loc().dec:.2f}")print(f"Error area (90% cont.): {ts.error_area(cont = .9).to(u.deg**2):.2f}")print(f"Equivalent error radius (90% cont.): {np.sqrt(ts.error_area(cont = .9)/np.pi).→˓to(u.deg):.2f}")

img,ax = ts.plot()ax.grid(alpha = .5)

# Actual location of simulated sourceax.scatter(coord.ra.to(u.deg).value, coord.dec.to(u.deg).value,

color = 'red', transform = ax.get_transform('world'), s = 2);

Maximum sqrt(TS) = 12.55Best estimate: RA = 61.50 deg Dec= 44.99 degError area (90% cont.): 1937.09 deg2Equivalent error radius (90% cont.): 24.83 deg

10 Chapter 1. Introduction

Page 15: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

[ ]:

1.2.3 Scripts

The scripts are easy ways to call certain functions of the library from the command line. While you could perform thesame tasks using Python code, it is usually easier to just call an executable that is in your path.

Most of the parameters needed by the scripts are defined in a yaml configuration file. An exam-ple of this file comes with bc-tools, within the config module. You can get the path to it either us-ing BurstCube.config.Configurator.config_example_path() or from the command line callingbc-config-example-path. Sometime though it is impractical to change the configuration file for every run.In these situations you can override any parameter using the --override command-line option, which accepts pairskeys and values, separated by ‘=’. For example:

$ bc-script --override parameter1=5 'group:subgroup:parameter2 = ["example", 5, True]'

is equivalent to have a configuration file with:

parameter1: 5

group:subgroup:parameter2: ["example", 5, True]

Note that the groups/subgroups are separated by :, and that you need to use quotes such that each overriding statementis passed as single argument to the exceutable (spaces are trimmed). The value will by parsed by yaml in the samewas as if it were in the configuration file.

1.2. Documentation Contents 11

Page 16: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

The following is an overview of the available scripts. Use -h/--help for more details and other options.

bc-config-example-path

Prints the path in your system to the BurstCube configuration file example. e.g.:

$ bc-config-example-path/path/to/bc-tools/BurstCube/config/bc_config.yaml

This is an entry point for BurstCube.config.Configurator.config_example_path()

bc-rsp

Generate BurstCube detector reponse files.

Basic usage:

bc-rsp config_file working_dir --ntriggers NTRIGGERS

where NTRIGGERS is the stopping conditions, the number of thrown events that resulted in an interaction with asensitive component (per simulated direction).

By default, it generates an HDF5 file containing the detector response matrices for multiple directions, specifically thecenter of the pixels in a HEALPix grid (the pixelization is controlled by simulations:nside). This can then be openedby BurstCube.io.DRM which can interpolate in between to obtain a full 4pi response. The user can specify a specificdirection to simulate with –direction, in which case a GBM RSP will be output for each detector.

The program performs the following steps for each simulated directions:

1. Creates a working directory.

2. Generates a Cosima .source file.

3. Runs Cosima, resulting in a .sim file.

4. Using this output, it generates a detector response matrix which is saved as GBM RSP files. There is one foreach detector labeled detector_id.rsp. The file called detector_id_photopeak.rsp includes onlythe events corresponding to the photopeak.

If --direction was not set, then at the end all detector response matrices are combined in working_dir/drm[_peak].h5.

If the program detects that the subproduct of any of these steps already exists in the working directory, the step isskipped.

Warning: If a subproduct is already available, the configurations parameters or command-line arguments neededfor the step will be ignored. For example, if the Cosima mc.source file already exists, it will be used withoutchecking that the spectrum corresponds to the one input by the user during the current run.

Generating a full detector response can be CPU intensive. There are two ways to parallelize and speed this process:

1. Using --nthreads N: the program launches a subprocess for each pixel, where N is the maximum subpro-cesses running at a given time

2. Using --part PART NPARTS: in this case, the program will divide the number of pixels into NPARTSnumber of jobs, and will only run number PART (zero indexed). Note that in this case the DRMs will not becombined into a single HDF5 at the end. A separate job without this flag needs to be run at the end.

12 Chapter 1. Introduction

Page 17: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

Both ways can be combined.

Note: You need to have MEGAlib installed and loaded.

This is an entry point for the BurstCube.sims.rsp_gen module.

bc-rsp-extractor

For convenience, when you generate a full detector response with bc-rsp, you can extract a particular direction withbc-rsp-extractor.

Basic usage:

bc-rsp-extractor input_hdf5 --spacecraft_coords RA(deg) DEC(deg)

This will output a .rsp file per detector, prefixed with the detector name.

1.2.4 API

Input/Output

Cosima

CosimaSim

class BurstCube.io.CosimaSimBases: object

Contains info associated with a Cosima output file (.sim)

Attributes

• tstart (float) – Start of simulated time

• tstop (float) – Stop of simulated time

• nthrown (int) – Total number of simulated particles

• ntriggers (int) – Total number of triggered events

• events (list of SimEvent) – Collection of all events, which contain hits. These might notbe loaded

static event_iter(filename, detector)Loops through the event section in a .sim file and yields a SimEvent object for each one. This avoidsloading a large file into memory. e.g.:

for hit in CosimaSim.event_iter("/path/to/file.sim", detector):

do_something(hit)

Parameters

• filename (Path) – Path to .sim file.

• detector (BurstCube.containers.Detector) – Detector locations/names

1.2. Documentation Contents 13

Page 18: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

Returns Yields SimEvent objects

merge(sim2, shift=0)Combine CosimaSim object with a shift. Hits will be time sorted

Parameters

• sim2 (CosimaSim) – Hits to be merged

• shift (float, optional) – Apply a time shift to obj2

classmethod open(filename, detector=None, load_events=True)

Parameters

• filename (Path) – Path to .sim file.

• detector_dict (dict) – Convert from a string of x,y location to a given detector ID.Use x and y value exactly as they appear in the input file

• detector (BurstCube.containers.Detector) – Detector with loca-tions/names. Only needed if loading events

• load_events (bool) – If false, only load the header information of the file but do notstore the events

Returns CosimaSim object

Warning: Concatenating files with NF and IN keywords is not supported

time_shift(shift)Shift time of events

Parameters shift (float) – duration of shift

to_TTE(energy_channel_edges, *args, **kwargs)Convert the hits into a mocked Time-Tagged Event object

Parameters

• energy_channel_edges (list) – Energy channel definition for discreatization

• *args – passed to TTE.from_data()

• **kwargs – passed to TTE.from_data()

Returns One TTE for each detector

Return type list of gbm.data.phaii.TTE

CosimaSource

class BurstCube.io.CosimaSource(geometry=None, ntriggers=None)Bases: object

Class to read/write .source Cosima files

Parameters

• geometry (Path) – Path to Geomega geometry file

• ntriggers (int) – Stop simulation when this number of triggers was reached

14 Chapter 1. Introduction

Page 19: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

Note: Besides the parameters initialized during consutruction, note that ou still need to call set_point_source

Attributes

• avail_spec_help (str) – List of available spectral shapes

• spectrum (Spectrum) – Parsed Cosima spectrum and flux

• geometry (Path) – Path to Geomega geometry file

• ntriggers (str) – Stop simulation when this number of triggers was reached

• location (SpacecraftCoords) – Source location. Distance might be infinity

• source_path (Path) – Path to .source Cosima file

• sim_path (Path) – Path to Cosima’s results .sim file

Warning: Reading general .source files not written by this class is not guaranteed to work

classmethod open(source_path)Read file from disk

Parameters source_path (Path) – Path to .source file

Warning: Reading general .source files not written by this class is not guaranteed to work

run(log_path=None, seed=None)Run the simulations

Parameters

• log_path (Path) – Path to output Cosima log. To stdout by default.

• seed (int or None) – Random seed for Cosima (must be > 0). Use None

• a "random" random seed. (for) –

set_point_source(spectrum, location)Indicate that a point source will be simulated

Parameters

• spectrum (Spectrum) – Spectrum to simulate

• location (SpacecraftCoords) – Source location

write(source_path, sim_path)Write file

Parameters

• source_path (Path) – .source file output path

• sim_path (Path) – .sim file output path prefix when this .source file is run..inc1.id1.sim will be appended, .inc2.id1.sim if it already exists, and so on.

1.2. Documentation Contents 15

Page 20: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

Note: sim_path is relative to the current directory, not to source_path

Instrument Response File

class BurstCube.io.InstrumentResponse(filename, nside=None, scheme=’ring’)Bases: mhealpy.containers.healpix_base.HealpixBase

Input/output access of HDF5 files containing Detector Response Matrices (DRMs) for all detectors and multiplepoints in the sky.

There is one DRM (photon energy vs energy channel) per detector per pixel in a HEALPix grid.

Please be aware that you need to call close() when you are done. Or even better, use it as a context manager,e.g.:

with InstrumentResponse("irf.h5") as irf:

coord = SpacecraftCoords(0, 0)

drm = irf.get_drm("detector1", coords = coord)

# Do something with drm

This automatically closes the file, even if an exception occurred.

Parameters

• filename (Path) – Path to HDF5 containing DRMs

• nside (int or None) – It not None, a new file will be created with this Healpix nside.

• scheme (str) – RING or NESTED Healpix ordering scheme

classmethod adaptive_moc_mesh(max_nside, split_fun)Return a MOC mesh with an adaptive resolution determined by an arbitrary function.

Parameters

• max_nside (int) – Maximum HEALPix nside to consider

• split_fun (function) – This method should return True if a pixel

• be split into pixel of a higher order, and False otherwise.(should) –

• takes two integers, start (It) –

• correspond to a single pixel in nested rangeset format fora (which) –

• of nside max_nside. (map) –

Returns HealpixBase

ang2pix(theta, phi)Get the pixel (as used in []) that contains a given coordinate

Parameters

• theta (float or array) – Zenith angle

• phi (float or arrray) – Azimuth angle

16 Chapter 1. Introduction

Page 21: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

Returns int or array

boundaries(pix, step=1)Returns an array containing vectors to the boundary of the nominated pixel.

The returned array has shape (3, 4*step), the elements of which are the x,y,z positions on the unit sphereof the pixel boundary. In order to get vector positions for just the corners, specify step=1.

close()Close the HDF5 file containing the DRMs

conformable(other)For single-resolution maps, return True if both maps have the same nside and scheme.

For MOC maps, return True if both maps have the same list of UNIQ pixels (including the ordering)

detectorsList of detector IDs

energy_channels(detector)Returns the axis corresponding to the energy channels

Parameters detector (str) – Detector ID

Returns Labeled ‘channels’

Return type Axis

filenamePath to on-disk file containing DRMs

Returns Path

classmethod from_rsps(rsp_dict, filename, scheme=’ring’)Create an InstrumentResponse from a list of GBM RSP files

Parameters

• rsp_dict (dict of list of RSP) – Lists of .rsp files, one list per detector. Usedetector name as dict key. The lists contain one entry per pixel in a HEALPix grid.

• filename (Path) – Path to HDF5 output file to store the DRM

• nest (bool) – True for NESTED scheme. False for RING

get_all_neighbours(theta, phi=None)Return the 8 nearest pixels. For MOC maps, these might repeat, as this is equivalent to raterizing the mapsto the highest order, getting the neighbohrs, and then finding the pixels tha contain them.

Parameters

• theta (float or int or array) – Zenith angle (rad). If phi is None, these areassummed to be pixels numbers. For MOC maps, these are assumed to be pixel numbersin NESTED scheme for the equivalent single-resolution map of the highest order.

• phi (float or array or None) – Azimuth angle (rad)

Returns

pixel number of the SW, W, NW, N, NE, E, SE and S neighbours, shape is (8,) if input isscalar, otherwise shape is (8, N) if input is of length N. If a neighbor does not exist (it canbe the case for W, N, E and S) the corresponding pixel number will be -1.

Return type array

1.2. Documentation Contents 17

Page 22: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

get_drm(detector, pix=None, coords=None, interp=True)Return a single DRM (2D) corresponding to the input pixel or coordinate.

If interp is true, the output will be a bilinear interpolation from the 4 closest pixels to the coordinate.Otherwise, the center of the pixel the input coordinate corresponds to will be used.

Parameters

• detector (str) – Detector ID

• pix (int) – HEALPix pixel

• coords (SpacecraftCoords) – Local coordinate

• interp (bool) – whether or not to interpolate

Returns

Photon energies axis is called “energy”, energy channels axis is called “channels”

Return type Histogram

get_interp_weights(theta, phi)Return the 4 closest pixels on the two rings above and below the location and corresponding weights.Weights are provided for bilinear interpolation along latitude and longitude

Parameters

• theta (float or array) – Zenith angle (rad)

• phi (float or array) – Azimuth angle (rad)

Returns

(pixels, weights), each with of (4,) if the input is scalar, if (4,N) where N is size of thetaand phi. For MOC maps, these pixel numbers might repeate.

Return type tuple

is_mesh_valid()Return True is the map pixelization is valid. For single resolution this simply checks that the size is avalid NSIDE value. For MOC maps, it checks that every point in the sphere is covered by one and onlyone pixel.

Returns True

is_mocReturn true if this is a Multi-Dimensional Coverage (MOC) map (multi-resolution)

Returns bool

is_nestedReturn true if scheme is NESTED or NUNIQ

Return bool

is_ringReturn true if scheme is RING

Return bool

classmethod moc_from_pixels(nside, pixels, nest=False)Return a MOC mesh where a list of pixels are kept at a given nside, and every other pixel is appropiatelydownsampled.

Also see the more generic adaptive_moc() and adaptive_moc_mesh().

18 Chapter 1. Introduction

Page 23: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

Parameters

• nside (int) – Maximum healpix NSIDE (that is, the NSIDE for the pixel list)

• pixels (array) – Pixels that must be kept at the finest pixelation

• nest (bool) – Whether the pixels are a ‘NESTED’ or ‘RING’ scheme

moc_sort()Sort the uniq pixels composing a MOC map based on its rangeset representation

nest2pix(pix)Get the corresponding pixel in the current grid for a pixel in NESTED scheme. For MOC map, return thepixel that contains it.

Parameters pix (int or array) – Pixel number in NESTED scheme. Must correspond toa map of the same order as the current.

Returns int or array

npixGet number of pixels.

For multi-resolutions maps, this corresponds to the number of utilized UNIQ pixels.

Returns int

nsideGet map NSIDE

Returns int

orderGet map order

Returns int

photon_energies(detector)Returns the axis corresponding to the MC truth photon energies.

Parameters detector (str) – Detector ID

Returns Labeled ‘energy’

Return type Axis

pix2ang(pix)Return the coordinates of the center of a pixel

Parameters pix (int or array) –

Returns (float or array, float or array)

pix2range(nside, pix)Get the equivalent range of child pixels in nested scheme for a map of equal or higher nside

Parameters

• nside (int) – Nside of output range sets

• pix (int or array) – Pixel numbers

Returns

Start pixel (inclusive) and stop pixel (exclusive)

Return type (int or array, int or array)

1.2. Documentation Contents 19

Page 24: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

pix2uniq(pix)Get the UNIQ representation of a given pixel index.

Parameters pix (int) – Pixel number in the current scheme (as used for [])

pix2vec(pix)Return a vector corresponding to the center of a pixel

Parameters pix (int or array) –

Returns Size (3,N)

Return type array

pix_order_list()Get a list of lists containing all pixels sorted by order

Returns

(pix_per_order, nest_pix_per_order) Each list has a size equal to the map order.Each element is a list of all pixels whose order matches the index of the list position. Thefirst output contains the index of the pixels, while the second contains their corespondingpixel number in a nested scheme.

Return type (list, list)

pix_rangesets(nside=None)Get the equivalent range of child pixels in nested scheme for a map of equal or higher nside

Parameters nside (int or None) – Nside of output range sets. If None, the map nside willbe used

Returns

With columns named ‘start’ (inclusive) and ’stop’ (exclusive)

Return type recarray

pixarea(pix=0)Return area of pixel in steradians

Parameters pix (int or array) – Pixel number. Only relevant for MOC maps

Returns float or array

plot_grid(ax=’mollview’, ax_kw={}, step=32, coord=’C’, **kwargs)Plot the pixel boundaries of a Healpix grid

Parameters

• ax (WCSAxes or str) – Astropy’s WCSAxes to plot the map. Either an existing in-stance or the name of a registered projection.

• ax_kw (dict) – Extra arguments if a new axes needs to be created.

• step (int) – How many points per pixel side

• coord (str) – Instrinsic coordinates of the map. Either ‘G’ (Galactic), ‘E’ (Ecliptic) ,‘C’ (Celestial = Equatorial) or any other coordinate frame recognized by astropy.

• **kwargs – Passed to matplotlib.pyplot.plot()

Returns

The first return value corresponds to the output pyplot.plot() for one of the pixels.The second is the astropy WCSAxes object used.

20 Chapter 1. Introduction

Page 25: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

Return type matplotlib.lines.Line2D list, WCSAxes

query_disc(vec, radius, inclusive=False, fact=4)

Parameters

• vec (float, sequence of 3 elements) – The coordinates of unit vector defin-ing the disk center.

• radius (float) – The radius (in radians) of the disk

• inclusive (bool) – f False, return the exact set of pixels whose pixels centers liewithin the region; if True, return all pixels that overlap with the region.

• fact (int) – Only used when inclusive=True. The overlapping test will be done at theresolution fact*nside. For NESTED ordering, fact must be a power of 2, less than 2**30,else it can be any positive integer. Default: 4.

Returns The pixels which lie within the given disc.

Return type int array

query_polygon(vertices, inclusive=False, fact=4)Returns the pixels whose centers lie within the convex polygon defined by the vertices array (if inclusiveis False), or which overlap with this polygon (if inclusive is True).

Parameters

• vertices (float) – Vertex array containing the vertices of the polygon, shape (N, 3).

• inclusive (bool) – f False, return the exact set of pixels whose pixels centers liewithin the region; if True, return all pixels that overlap with the region.

• fact (int) – Only used when inclusive=True. The overlapping test will be done at theresolution fact*nside. For NESTED ordering, fact must be a power of 2, less than 2**30,else it can be any positive integer. Default: 4.

Returns The pixels which lie within the given polygon.

Return type int array

query_strip(theta1, theta2, inclusive=False)Returns pixels whose centers lie within the colatitude range defined by theta1 and theta2 (if inclusive isFalse), or which overlap with this region (if inclusive is True). If theta1<theta2, the region between bothangles is considered, otherwise the regions 0<theta<theta2 and theta1<theta<pi.

Parameters

• theta (float) – First colatitude (radians)

• phi (float) – Second colatitude (radians)

• inclusive (bool) – f False, return the exact set of pixels whose pixels centers liewithin the region; if True, return all pixels that overlap with the region.

Returns The pixels which lie within the given strip.

Return type int array

schemeReturn HEALPix scheme

Returns Either ‘NESTED’, ‘RING’ or ‘NUNIQ’

Return type str

1.2. Documentation Contents 21

Page 26: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

uniqGet an array with the NUNIQ numbers for all pixels

vec2pix(x, y, z)Get the pixel (as used in []) that contains a given coordinate

Parameters

• theta (float or array) – Zenith angle

• phi (float or arrray) – Azimuth angle

Returns int or array

Containers

Simulations

Hit

class BurstCube.containers.Hit(detector, time, energy)Bases: object

Single interaction with a SiPM

Attributes

• time (float) – Time of the hits

• detector (str) – Detector ID

• energy (float) – Deposited energy

SimEvent

class BurstCube.containers.SimEvent(particle, direction, energy, energy_escaped, en-ergy_absorbed, time, hits=[])

Bases: object

Simulation event, with MC truth and possibly some triggered hits

Parameters

• particle (int) – Incoming particle type ID (see Cosima manual)

• direction (list of float) – [x,y,z] direction of incoming particle

• energy (float) – kinetic energy of incoming partigle

• time (float) – Time of the event. Hit times are relative to this

• hits (list of Hit) – Triggered hits.

Attributes

• particle (int) – Incoming particle type ID (see Cosima manual)

• direction (list of float) – [x,y,z] direction of incoming particle

• energy (float) – kinetic energy of incoming partigle

• time (float) – Time of the event. Hit times are relative to this

22 Chapter 1. Introduction

Page 27: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

• hits (list of Hit) – Triggered hits.

add_hit(hit)Add a hit to the event

Parameters hit (Hit) – triggered hit (detector, time and energy)

is_fully_defined()Returns True if no attribute is None

Returns bool

Detector

Detector

class BurstCube.containers.Detector(config)Bases: object

Contains the detector configuration

Parameters config (Configurator) – Configurator with detector characteristics

Attributes

• energy_channel_edges (array) – Definition of energy channels

• detectors (list) – Detector IDs

detectorsDetector list

max_energyUpper bound of last energy channepl

min_energyLower bound of first energy channel

sim_loc_to_detector(x, y, z)Get the detector ID from the position of the hit reported by Cosima

Parameters

• x (str) – x position

• y (str) – y position

• z (str) – z position

Returns Detector ID

Return type str

Histogram

Histogram

class BurstCube.containers.Histogram(edges, contents=None, sumw2=None, labels=None,scale=None)

Bases: object

This is a wrapper of a numpy array with axes and a fill method.

1.2. Documentation Contents 23

Page 28: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

Like an array, the histogram can have an arbitrary number of dimensions.

Standard numpy array indexing is supported to get the contents –i.e. h[:], h[4], h[[1,3,4]], h[:,5:50:2]], etc.–. However, the meaning of the -1 index is different. Instead of counting from the end, -1corresponds to the underflow bin. Similarly, an index equal to the number of bins corresponds to the overflowbin.

You can however give relative position with respect to h.NBINS –e.g. h[0:h.NBINS] result in all regularbins, h[-1:h.NBINS+1] includes also the underflow/overflow bins and h[h.NBINS] gives you the contentsof the overflow bin.

You can also use an Ellipsis object (. . . ) at the end to specify that the contents from the rest of the dimensionare to have the under and overflow bins included. e.g. for a 3D histogram h[1,-1:h.NBINS+1,-1:h.NBINS+1] = h[1,...]. h[:] returns all contents without under/overflow bins and h[. . . ] returns everything,including those special bins.

Additionally, you can specify with a dictionary the indices for specific axes, with all the rest being the default.e.g. h[:,:,1:,:,6] <==> h[{2:slice(1,None), 4:6}]. If you also use the axes id if you labeledthem, e.g. h[{'x':slice(0,h.NBINS+1)}]

If sumw2 is not None, then the histogram will keep track of the sum of the weights squared –i.e. you better usethis if you are using weighted data and are concern about error bars–

You can use the *= operator to weight by a number or an array of weights with the shape of h.nbins+2 (toinclude under/overflow bins).

The operators +, -, += and -= are available. Both operands need to be histograms. An exception will be raisedif the axes are not the same. Note that h += h0 is more efficient than h = h + h0 since latter involves theinstantiation of a new histogram.

Parameters

• edges (Axes or array) – Definition of bin edges, Anything that can be processes byAxes. Lower edge value is included in the bin, upper edge value is excluded.

• contents (array) – Initialization of histogram contents. Might or might not includeunder/overflow bins. Initialize to 0 by default.

• sumw2 (None, bool or array) – If True, it will keep track of the sum of the weightssquared. You can also initialize them with an array

• labels (array of str) – Optionally label the axes for easier indexing

• scale (str or array) – Bin center mode e.g. “linear” or “log”. See Axis.scale(). Not to be confused with the Histogram`'s `method ``scale(),which scales the bin contents, rather than defining what the scale mode of an axis is.

Attributes sumw2 (Histogram) – An auxiliary histogram whose contents are the sum of the squareof the weight that were used to fill this histogram

axesUnderlaying axes object

axisEquivalent to self.axes[0], but fails if ndim > 1

clear()Set all counts to 0

classmethod concatenate(edges, histograms, label=None)Generate a Histogram from a list os histograms. The axes of all input histograms must be equal, and thenew histogram will have one more dimension than the input. The new axis has index 0.

24 Chapter 1. Introduction

Page 29: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

Parameters

• edges (Axes or array) – Definition of bin edges of the new dimension

• histograms (list of Histogram) – List of histogram to fill contents. Might ormight not include under/overflow bins.

• labels (str) – Label the new dimension

Returns Histogram

fill(*values, weight=1)And an entry to the histogram. Can be weighted.

Follow same convention as find_bin()

Parameters

• values (float or array) – Value of entry

• weight (float) – Value weight in histogram.

Note: Note that weight needs to be specified explicitely by key, otherwise it will be considered a value ana IndexError will be thrown.

find_bin(*values, axis=None)Return one or more indices corresponding to the bin this value or set of values correspond to.

You can pass either an array, or specified the values as different arguments. i.e. h.find_bin(x,y,z)= h.find_bin([x,y,z])

Parameters

• values (float or array) – Vaule or list of values

• axis (int or str or list) – If set, values correspond to the subset of axes listedhere

Returns Bin index

Return type int or tuple

interp(*values)Get a linearly interpolated content for a given set of values along each axes. The bin contents are assignedto the center of the bin.

Parameters values (float or array) – Coordinates within the axes to interpolate. Musthave the same size as ndims. Input values as (1,2,3) or ([1,2,3])

Returns float

project(*axis)Return a histogram consisting on a projection of the current one

Parameters axis (int or str or list) – axis or axes onto which the histogram will beprojected –i.e. will sum up over the other dimensiones–. The axes of the new histogram willhave the same order –i.e. you can transpose axes–

Returns Projected histogram

Return type Histogram

1.2. Documentation Contents 25

Page 30: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

scale(weight, indices=Ellipsis, axis=None)Scale the histogram contents.

By default, h.scale(weight) <==> h *= weight

The parameter indices can be used to specify the slice that will be multiplied by the weights. Followthe same index convention as in [].

If axis is specified, then weights and indices correspond to a single axis.

Parameters

• weights (array-like) – Weights

• indices (int or tuple) – Bin indices

• axis (int or str) – Axis index

shapeTuple with number of bins along each dimensions

slice(axis, start=None, stop=None, underflow=True, overflow=True)Return a histogram which is a slice of the current one, along a given dimension.

Follows same indexing convention as [] operator

Parameters

• axis (int or str) – Dimension that will be sliced

• start (None or int) – Start bin (inclusive)

• stop (None or int) – Stop bin (exclusive). Must be greater than start

• underflow (bool) – If True, the contents before the start bin will be summed up andkept in the underflow bins, otherwise they’ll be discarded

• overflow (overflow) – same as underflow

Returns Sliced histogram

Return type Histogram

Axis

class BurstCube.containers.histogram.Axis(edges, label=None, scale=None)Bases: object

Bin edges. Optionally labeled

Parameters

• edges (array-like) – Bin edges

• label (str) – Label for axis. If edges is an Axis object, this will override its label

• scale (str) – Bin center mode e.g. “linear” or “log”. See scale(). If edges is an Axisobject, this will override its mode

Attributes

• edges (array-like) – Bin edges

• label (str) – Label for axis

26 Chapter 1. Introduction

Page 31: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

boundsStart of [lower_bound, upper_bound] values for each bin.

centersCenter of each bin.

find_bin(value)Return the bin value corresponds to.

Returns Bin number. -1 for underflow, nbins for overflow

Return type int

interp_weights(value)Get the two closest bins to value, together with the weights to linearly interpolate between them. The bincontents are assigned to the center of the bin.

Values in the edges beyond the center of the first/last bin will result in no interpolation.

Returns Bins [float, float]: Weights

Return type [int, int]

lower_boundsLower bound of each bin

maxOverall upper bound of histogram

minOverall lower bound

nbinsNumber of elements along each axis. Either an int (1D histogram) or an array

scale(mode=None)Control what is considered the center of the bin. This affects centers() and interpolations.

Parameters mode (str or None) –

• linear (default): The center is the midpoint between the bin edges

• symmetric: same as linear, except for the first center, which will correspond to the loweredge. This is, for example, useful when the histogram is filled with the absolute value of avariable.

• log: The center is the logarithmic (or geometrical) midpoint between the bin edges.

Returns The new mode (or current if mode is None).

Return type str

upper_boundsUpper bound of each bin

widthsWidth each bin.

Axes

class BurstCube.containers.histogram.Axes(edges, labels=None, scale=None)Bases: object

Holds a list of axes.

1.2. Documentation Contents 27

Page 32: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

The operator Axes[key] return a subset of these. Key can be either the index or the label. If the key is a singleindex, a single Axis object will be returned

Parameters

• edges (array or list of arrays or Axis) – Definition of bin edges.

• labels (array of str) – Optionally label the axes for easier indexing. Will overridethe labels of edges, if they are Axis objects

• scale (str or array) – Bin center mode e.g. “linear” or “log”. See Axis.scale. Ifnot an array, all axes will have this mode.

interp_weights(*values)Get the bins and weights to linearly interpolate between bins. The bin contents are assigned to the centerof the bin.

Parameters values (float or array) – Coordinates within the axes to interpolate. Musthave the same size as ndims. Input values as (1,2,3) or ([1,2,3]).

Returns Bins and weights to use. Size=2^ndim. Each bin is specified by a tuple containing ndimintegers

Return type array of tuples of int, array of floats

key_to_index(key)Turn a key or list of keys, either indices or labels, into indices

Parameters key (int or str) – Index or label

Returns Index

Return type int

labelsLabel of axes.

Returns Either a string or a tuple of string. None if they are not defined

ndimNumber of axes

Spectra

Spectrum

A collection of spectrum functions.

Translate from/to MEGAlib’s format

class BurstCube.spectra.spectrum.Mono(flux, energy)Mono energetic beam

Parameters

• flux (float) – Flux

• energy (float) – Energy

eval(energy)Evaluate the spectrum F(E)

Parameters energy (iterable) – energy 𝐸 values

28 Chapter 1. Introduction

Page 33: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

Returns flux 𝐹 values

Return type array

integrate(bounds)Evaluate the integral between two energy bounds

Parameters bound (array) – Energy bounds. Either an array with 2 elements or 2D arraywith 2 columns

Returns Integral flux between bounds

Return type float or array

normalize(flux)Update the flux

Parameters flux (float) – new flux

to_megalib()Return equivalent parameters of MEGAlib’s Source.Spectrum and Source.Flux

Returns Spectrum type and parameteters for Source.Spectrum (i.e. PowerLaw min_energymax_energy photon_index) str: Parameter for Source.Flux

Return type list of str

class BurstCube.spectra.spectrum.PowerLaw(norm, index)𝐹 (𝐸) = 𝐴

(︀𝐸

1keV

)︀−𝛼

Parameters

• norm (float) – normalization 𝐴

• index (float) – spectral index 𝛼

Attributes

• norm (float) – normalization 𝐴

• index (float) – spectral index 𝛼

• min_energy (float) – 𝐹 = 0 if 𝐸 < min_energy

• max_energy (float) – 𝐹 = 0 if 𝐸 > max_energy

eval(energy)Evaluate the spectrum F(E)

Parameters energy (iterable) – energy 𝐸 values

Returns flux 𝐹 values. F = 0 outside of the min/max_energy bounds

Return type array

fluxTotal integrated flux between energy bounds

integrate(bounds)Evaluate the integral between two energy bounds.

Note that the spectrum evaluates to 0 out of the overall min/max_energy bounds.

Parameters bound (array) – Energy bounds. Either an array with 2 elements or 2D arraywith 2 columns

Returns Integral flux between bounds

1.2. Documentation Contents 29

Page 34: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

Return type float or array

normalize(flux, min_energy=None, max_energy=None)Change norm based on the total emission between min_enegy and max_energy

Parameters

• flux (float) – new integral flux between min_energy and max_energy

• min_energy (float) – Lower integration bound. Defaults to self.min_energy

• max_energy (float) – Upper integration bound. Defaults to self.max_energy

to_megalib()Return equivalent parameters of MEGAlib’s Source.Spectrum and Source.Flux

Returns Spectrum type and parameteters for Source.Spectrum (i.e. PowerLaw min_energymax_energy photon_index) str: Parameter for Source.Flux

Return type list of str

class BurstCube.spectra.spectrum.SpectrumAbstract class representing an spectral model

Child classes need to implement eval(), integrate(), _from_megalib(), to_megalib(), __str__(), __eq__() andnormalize() and property flux

eval(energy)Evaluate the spectrum F(E)

Parameters energy (iterable) – energy 𝐸 values

Returns flux 𝐹 values

Return type array

fluxTotal integrated flux between energy bounds

classmethod from_megalib(params, flux)Get object from MEGAlibs format.

Parameters

• params (list) – List of paramters. See str_megalib_format

• flux (str) – Flux value (In MEGAlib the spectrum refers only to the shape)

classmethod from_name(name, *args, **kwargs)Instantiate a spectrum from the subclass name. e.g.: Spectrum.from_name('PowerLaw',

*args, **kwargs) <==> PowerLaw(*args, **kwargs)

integrate(bounds)Evaluate the integral between two energy bounds

Parameters bound (array) – Energy bounds. Either an array with 2 elements or 2D arraywith 2 columns

Returns Integral flux between bounds

Return type float or array

normalize(flux, *args, **kwargs)Change normalization parameters based on an integrated flux.

30 Chapter 1. Introduction

Page 35: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

set_elims(min_energy=None, max_energy=None)Set energy limits. Function evaluates to 0 outside of these bounds

Limits stay the same if not specified

Parameters

• min_energy (float) – lower energy bound

• max_energy (float) – uppper energy bound

to_megalib()Return equivalent parameters of MEGAlib’s Source.Spectrum and Source.Flux

Returns Spectrum type and parameteters for Source.Spectrum str: Parameter for Source.Flux

Return type list of str

Fitting

Fast Norm Fit

class BurstCube.fitting.FastNormFit(max_iter=1000, conv_frac_tol=0.001, zero_ts_tol=1e-05, allow_negative=False)

Bases: object

Perform a fast poisson maximum likelihood ratio fit of the normalization of a source over background.

The likelihood ratio as a function of the norm is computed as follow

𝑇𝑆(𝑁) = 2∑︁𝑖

(︂log𝑃 (𝑑𝑖; 𝑏𝑖 + 𝑁𝑒𝑖)

log𝑃 (𝑑𝑖; 𝑏𝑖)

)︂where 𝑃 (𝑑;𝜆) is the Poisson probability of obtaining 𝑑 count where 𝜆 is expected on average; 𝑏 is the esti-mated number of background counts; 𝑁 is the normalization; and 𝑒 is the expected excess -i.e. signal- pernormalization unit -i.e. the number of excess counts equals 𝑁 .

It can be shown that 𝑇𝑆(𝑁) has analytic derivative of arbitrary order and that the Newton’s method is guaranteedto converge if initialized at 𝑁 = 0.

Note: The background is not allowed to float. It is assumed the error on the estimation of the background issmall compared to the fluctuation of the background itself (i.e. 𝑁𝐵/𝑁𝑜𝑓𝑓 ≪ 1).

Note: Because of the Poisson probability, 𝑇𝑆(𝑁) is only well-defined for 𝑁 ≥ 1. By default, underfluctuationsare set to 𝑇𝑆(𝑁 = 0) = 0. For cases when there is benefit in letting the normalization float to negative values,you can use allow_negative, but in that case the results are only valid in the Gaussian regime.

Parameters

• max_iter (int) – Maximum number of iteration

• conv_frac_tol (float) – Convergence stopping condition, expressed as the ratio be-tween the size of the last step and the current norm value.

• zero_ts_tol (float) – If zero_ts_tol < TS < 0, then TS is set to 0 without failed flagstatus (analytically, TS < 0 should never happen)

1.2. Documentation Contents 31

Page 36: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

• allow_negative (bool) – Allow the normalization to float toward negative values

static dts(data, bkg, unit_excess, norm, order=1)Get the derivative of TS with respecto to the normalization, at given normalization.

Parameters

• data (array) – Observed counts

• bkg (array) – Background estimation. Same size as data. Every element should be >0

• unit_excess (array) – Expected excess per normalization unit. Same size as data.

• norm (float or array) – Normalization value

• order (int) – Derivative order

Returns d^n TS / dN^n, same shape as norm

Return type float or array

solve(data, bkg, unit_excess)Get the maximum TS, fitted normalization and normalization error (∆𝑇𝑆 = 1)

Note: The normalization error is obtained from approximating the TS function as as parabola (i.e. validin the Gaussian regime). TS and norm are indeed valid in the Poisson regime.

Parameters

• data (array) – Observed counts

• bkg (array) – Background estimation. Same size as data. Every element should be >0

• unit_excess (array) – Expected excess per normalization unit. Same size as data.

Returns ts, norm, norm error and status (0 = good)

Return type (float, float, float, bool)

static ts(data, bkg, unit_excess, norm)Get TS for a given normalization.

Parameters

• data (array) – Observed counts

• bkg (array) – Background estimation. Same size as data. Every element should be >0

• unit_excess (array) – Expected excess per normalization unit. Same size as data.

• norm (float or array) – Normalization value

Returns TS, same shape as norm

Return type float or array

Simulations

Detector effects

Classes that modify a hit in order to reproduce detector effects seen in calibration

32 Chapter 1. Introduction

Page 37: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

class BurstCube.sims.detector_effects.SimDetectorEffectAbstract detector effect class. Derived classes must implement the apply() method, which modify a Hit object

apply(hit)Take a Hit output a new Hit that takes into account a detector effect

Parameters hit (Hit or None) – Hit input object

Returns Hit or None

classmethod from_config(config)Return a detector effects object that will apply all effects in ‘simulations:detector_effects’

Parameters config (Configurator) – Configurator object

Returns SimDetectorEffect

classmethod from_name(name, *args, **kwargs)Instantiate a detector effect from the subclass name. e.g.: SimDetectorEffect.from_name('SimEnergyResolutionFromFit', *args, **kwargs) is equivalent toSimEnergyResolutionFromFit(*args, **kwargs)

class BurstCube.sims.detector_effects.SimDetectorEffects(detector_effects)Apply a collection of detector effects

Parameters detector_effects (list of SimDetectorEffect) – Detector effecto tobe applied, in order

apply(hit)Apply all detector effects

Parameters hit (Hit or None) – Input hit

Returns Output hit

Return type Hit or None

class BurstCube.sims.detector_effects.SimEfficiencyFromPoints(energy, effi-ciency)

Randomly drop a hit based on a arbitrary efficiency vs. energy.

The class takes a set points and interpolates between them. The efficiency of an energy before/after the first/lastpoint will be the eficciency of the first/last point.

Parameters

• energy (array) – List of energy point

• efficiency (array) – efficiency at each of the energy points

apply(hit)Returns None is the hit is dropped, and the same input hits otherwise. On average, it’ll let pass a fractionof hits equal to the efficiency

Parameters hit (Hit or None) – Input hit

Returns None or same as hit

class BurstCube.sims.detector_effects.SimEnergyResolutionFromFit(coeffs)Simulates the energy resolution of the instrument from a fit to various calibrating sources.

This detector effect replaces the energy of the hist with a random value obtained from for the energy from anormal distribution centered at the input energy and a width equal to ∆𝐸/2.35482 where ∆𝐸 is the full widthat half maximum.

1.2. Documentation Contents 33

Page 38: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

The value of ∆𝐸 depends on energy, and comes from a fit of the form

∆𝐸

𝐸=

√︁𝑐20 + 𝑐21(𝐸/keV)−1 + 𝑐22(𝐸/keV)−2 + ...

Note that ∆𝐸/𝐸 ∼ 1/√𝐸 if the energy resolution is only determined by the statistical error on the number of

photoelectrons produces.

Parameters coeffs (array, dict) – List with coefficients [𝑐0, 𝑐1, 𝑐2, . . . ]. Higher ordercoefficients are assummed zero. If a dictionary, the keys correspond to the detectos IDs.

apply(hit)Replaces hit energy

Parameters hit (Hit or list) – Hit to be modified

Response generator

Code for bc-rsp app.

See also: BurstCube.io.CosimaSource and BurstCube.io.CosimaSim

BurstCube.sims.rsp_gen.counts_to_rsp(hist, source, sim, filename)Scale a counts to create a detector response matrix and save it as a GBM RSP file

Parameters

• hist (Histogram) – Histogram with counts (must have an axis labeled “energy”)

• source (CosimaSource) – Cosima source object containing the spectrum and beaminformation

• sim (CosimaSim) – Cosima sim object containing the total duration of the simulation.

• filename (Path) – Location in disk to save the RSP file

BurstCube.sims.rsp_gen.main(argv=None)This method will become the entry point (e.g. executable) for user to generate a response file from the comman-dline

BurstCube.sims.rsp_gen.rsp_gen(working_dir, config, ntriggers=None, nthreads=1, nparts=1,part=1, distance=inf)

Generate an all-sky detector response.

rsp_gen_direction() is called for each of the directions in a HEALPix grid.

Parameters

• working_dir (Path) – Path to working directory

• config (Configurator) – Global configuration object

• ntriggers (int) – Stopping condition

• location (SpacecraftCoords) – Locations of the source

• nthreads (int) – Number of threads. One thread handles one direction at a time

• distance (float) – Distance to source. Far field by default

BurstCube.sims.rsp_gen.rsp_gen_direction(working_dir, config, ntriggers=None, loca-tion=None)

Generate a detector response for a single direction.

If the product from a given step is already available in the working dir, that step will be skept. This is why mostparameters are optional.

34 Chapter 1. Introduction

Page 39: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

Parameters

• working_dir (Path) – Path to working directory

• config (Configurator) – Global configuration object

• ntriggers (int) – Stopping condition

• location (SpacecraftCoords) – Locations of the source

Detector response matrix

class BurstCube.sims.DRM(photon_energies, energy_channels, matrix)Bases: object

Holds a 2D matrix of photon energy (MC truth) vs energy channels (estimated energy).

Parameters

• photon_energies (array or Axis) – MC truth energy edges

• energy_channels (array or Axis) – Estimated energy edges (last bin is overflow)

• matrix (array) – Axis 0 corresponds to photon energy, axis 1 to energy channels

axesReturn photon energy and energy channels axes

Returns Axes

channel_effective_area(energy, channel)Get the effective area at a given photon energy taking into account only the events assigned to a givenenergy channel.

Parameters

• energy (float or array) – Photon energy

• channel (int or array) – Energy channel

Returns float or array

effective_area(energy)Get the total (interpolated) effective energy for a given energy

Parameters energy (float or array) – Photon energy

Returns float or array

energy_channelsReturns the axis corresponding to the measured energy channels

Returns Labeled ‘channels’

Return type Axis

fold_spectrum(spectrum)Return the expected count rate for a given spectrum for each energy channel

Parameters spectrum (Spectrum) – Flux (keV^-1 cm^-2 s^-1)

Returns Counts per second for each energy channel

Return type array

1.2. Documentation Contents 35

Page 40: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

classmethod from_gbm_rsp(rsp, index=0)Create a detector response matrix using the contents of a gbm.data.RSP

Parameters

• rsp (gbm.data.RSP) – GBM RSP object

• index (int) – The DRM index if the RSP contained matrices for multiple times

Returns DRM

classmethod from_gbm_rsp_file(filename, index=0)Equivalent to from_gbm_rsp(RSP.open(filename), index)

Parameters

• filename (Path) – Path to .rsp(2) file

• index (int) – The DRM index if the RSP contains matrices for multiple times

photon_energiesReturns the axis corresponding to the MC truth photon energies.

Returns Labeled ‘energy’

Return type Axis

to_gbm_rsp()Convert to GBM RSP object

Returns gbm.data.RSP

to_gbm_rsp_file(filename)Save to GBM RSP format

Parameters filename (Path) – Output path

Localization

Localization tables

LocTable

class BurstCube.loc.LocTableBases: abc.ABC

Class prototype to store the neccessary numbers to estimate the localization from a series of counting detectors

get_background()Get estimated background counts. One per measurement

Returns array

get_data()Get measured data.

Returns array

get_expectation(coord)The expected exccess given a normalized spectral hypothesis

Parameters coord (SkyCoord) – Sky coordinate

Returns One per labeled measurement

36 Chapter 1. Introduction

Page 41: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

Return type array

labelsLabels for each measurement. e.g. detector number or name

Returns array

nmeasurementsTotal number of measurements

HealpixLocTable

class BurstCube.loc.HealpixLocTable(base, labels, expectation, data=None, back-ground=None, frame=’icrs’)

Bases: BurstCube.loc.loctable.LocTable, mhealpy.containers.healpix_base.HealpixBase

Localization table based on a HEALPix grid. Can be stored in HDF5 format.

Parameters

• base (HealpixBase) – Defines the healpix geometry

• labels (array) – Label each measurements

• expectation (array) – Expected excess for a normalized spectral hypothesis

• data (array) – Measured counts. Optional.

• background (array) – Estimated background the data. Optional.

• frame (BaseCoordinateFrame or str) – Coordinate frame object or name.NOTE: use only names of built in frames if you need to save the table to disc.

frameCoordinate frame

Returns BaseCoordinateFrame or str

get_background()Get estimated background counts. One per measurement

Returns array

get_data()Set measured counts.

Returns array

get_expectation(coords)The expected exccess given a normalized spectral hypothesis

Parameters coord (SkyCoord) – Sky coordinate

Returns One per labeled measurement

Return type array

labelsLabels for each measurement. e.g. detector number or name

Returns array

classmethod open(filename, name=’LocTable’)Load table from HDF5 file.

1.2. Documentation Contents 37

Page 42: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

Parameters

• filename (str) – Path to file

• name (str) – Group name inside file

set_background(background)Set estimated background counts. One per measurement

Returns array

set_data(data)Set measured counts.

Returns array

write(filename, name=’LocTable’, overwrite=False)Write table to HDF5 file.

Parameters

• filename (str) – Path to file

• name (str) – Group name inside file

• overwrite (bool) – Overwrite group is already exists

Localization likelihood

LocLike

class BurstCube.loc.LocLikeBases: abc.ABC

get_log_like(coords)Return the log-likelihood for a given coordinate under the source hypothesis

Returns float or array

get_null_log_like(coords)Return the lg-likelihood for a given coordinate under a background-only hypothesis

Returns float or array

NormLocLike

class BurstCube.loc.NormLocLike(*loctable)Bases: BurstCube.loc.loclike.LocLike

Compute the likelihood from a series of observed counts (𝑑𝑖), the estimated background counts (𝑏𝑖) and theexpected excess (𝑒𝑖) given a model hypothesis:

logℒ(𝑁) =∑︁𝑖

log𝑃 (𝜆 = 𝑏𝑖 + 𝑁𝑒𝑖; 𝑑𝑖)

𝑃 (𝜆; 𝑑) = log𝜆𝑑𝑒𝜆

𝑑

The likelihood is maximized against the normalization (𝑁 ). It is the only free (nuisance) parameter.

Parameters loctable (LocTable) – One or more localization tables

38 Chapter 1. Introduction

Page 43: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

get_background()List of background counts estimate for each measurement.

Returns array

get_data()List of measured counts

Returns array

get_expectation(coords)List of expected excess.

Returns array

get_log_like(coords)Return the log-likelihood for a given sky coordinate. The likelihood is maximize against the normalization.

Parameters coords (SkyCoord) – Sky coordinates

Returns array

get_null_log_like(coords)Get the log likelihood for N=0. This is a constant, there are no free parameters

Parameters coords (SkyCoord) – Sky coordinates

labelsLabel for each measurement entry.

Returns array

Maps

TSMap

class BurstCube.loc.TSMap(*args, frame=’icrs’, **kwargs)Bases: mhealpy.containers.healpix_map.HealpixMap

Test statistic map.

Parameters

• frame (str) – Name of astropy coordinate frame of the map

• **kwargs (*args,) – Passed to mhealpy.HealpixMap

best_loc()Coordinate of best estimate

Returns SkyCoord

compute(*loclikes)Compute the TS at each pixel based on a series of LocLike plugins.

error_area(cont=0.9)Area of the confidence region at a given confidence level.

Parameters cont (float) – Containment fraction

Returns astropy.Quantity

frameAstropy coordinate frame

1.2. Documentation Contents 39

Page 44: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

plot(*args, cont=0.9, **kwargs)Plot map.

Parameters

• cont (float) – Set the minimum of the colorbar to show only this fraction containments.Will be overridden by vmin

• **kwargs (*args,) – Passed to mhealpy.HealpixMap

Returns Same as mhealpy.HealpixMap

Utilities

Coordinates

Classes to interact with gbm.coords

class BurstCube.util.coords.Attitude(quat)Spacecract attitude

Parameters quat (array) – Quaternion. Array with 4 elements

quaternionGet attitude in the form of a quaternion (4 element array)

Returns 4 elements

Return type array

class BurstCube.util.coords.CartesianCoords(x, y, z)Cartesian coordinates

Attribute: x (float): Distance along x-axis y (float): Distance along y-axis z (float): Distance along z-axis

spherical

class BurstCube.util.coords.SkyCoords(ra, dec, distance=1)Celestial coordinates.

J2000 unless otherwise noticed.

decDeclination

distance

raRight ascension

to_spacecraftcoords(attitude)Convert to local coordinates

Note: The output distance is the same, only the direction is converted. This is planned to change in thefuture.

Parameters attitude (Attitude) – Spacecraft attitude

Returns SpacecraftCoords

40 Chapter 1. Introduction

Page 45: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

class BurstCube.util.coords.SpacecraftCoords(zenith, azimuth, distance=1)Local spacecraft coordinates

Arg: zenith (float): Zenith angle. azimuth (float): Azimuth angle. Anti-clockwise from x-axis distance (float):Distance to point

azimuth

distance

classmethod from_megalib(params)Construct location from a source.Beam argument in a MEGAlib source file

Parameters params (list) – List of parameter. Either [‘FarFieldPointSource’, zenith, az-imuth] or [‘(Restricted)PointSource’, x, y, z]

to_megalib()Return the location in a format that can be use in MEGAlib in the source.Beam argument of a source file

Returns

Paramters for either a FarFieldPointSource or a RestrictedPointSource

Return type list

to_skycoords(attitude)Convert from local to celestial coordinates.

Note: The output distance is the same, only the direction is converted. This is planned to change in thefuture.

Parameters attitude (Attitude) – Spacecraft attitude

Returns Skycoords

zenith

class BurstCube.util.coords.SphericalCoords(theta, phi, radius)Spherical polar coordinate using Physics convention

Arg: theta (float): Zenith angle phi (float): Azimuth angle. Anti-clockwise from x-axis radius (float): Distanceto point

Attributes

• theta (float) – Zenith angle

• phi (float) – Azimuth angle. Anti-clockwise from x-axis

• radius (float) – Distance to point

cartesianConvert to cartesian coordinates

Units

Base and auxiliary units and constants used througout the library

This help keep track of the units we are usings and makes it easier to interact with other libraries or with the user (readin and display).

1.2. Documentation Contents 41

Page 46: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

Usage example:

>>> from BurstCube.util import units as u>>> energy = 500 * u.keV>>> print("{} MeV".format(energy/u.MeV))0.5 MeV

BurstCube.util.units.GeV = 1000000.0

BurstCube.util.units.MeV = 1000.0

BurstCube.util.units.TeV = 1000000000.0

BurstCube.util.units.cm = 1Base distance unit

BurstCube.util.units.cm2 = 1

BurstCube.util.units.deg = 0.017453292519943295

BurstCube.util.units.eV = 0.001

BurstCube.util.units.halfpi = 1.5707963267948966

BurstCube.util.units.inf = inf

BurstCube.util.units.keV = 1Base energy units

BurstCube.util.units.m = 100

BurstCube.util.units.meter = 100

BurstCube.util.units.pi = 3.141592653589793

BurstCube.util.units.rad = 1

BurstCube.util.units.radian = 1Base angle unit

BurstCube.util.units.s = 1

BurstCube.util.units.second = 1Base time unit

BurstCube.util.units.twopi = 6.283185307179586

Configuration

This defines the properties of the detector. An example configuration file is provided with the library.

Configurator

class BurstCube.config.Configurator(config_path)Bases: object

Access to configuration parameters.

The parameters are organized in nested dictionarys. They set values can be a number, a string or a list. They canbe accessed as e.g. config['group:subgroup:subsubgroup:parameter']

Parameters config_path (Path) – Path to yaml configuration file.

42 Chapter 1. Introduction

Page 47: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

absolute_path(path)Turn a path relative to the location of the config file absolute

Parameters path (Path) – relative path

Returns absolute path

Return type Path

static config_example_path()Get path to the example configuration file

dump(*args, **kwargs)Dump the configuration contents to a file or a string.

All arguments are passed to yaml.dump(). By default it returns as string. You can specify a file or streamto dump it into in the first argument.

override(*args)Override one or more parameter by parsings strings of the form 'group:subgroup:parameter =value'. Value is parsed the same way as yaml would do it, so if it is a string use quotes.

The foreseen use case scenario is to let the uses override parameters from command line e.g.--override "group:parameter = new_value". Note that the values can be override directlyin code by using config['group:parameter'] = new_value".

Parameters args (string or array) – String to parse and override parameters.

static print_config_example_path(argv=None)Get path to the example configuration file

Miscellaneous

Exceptions

Custom exceptions

exception BurstCube.exceptions.CommandLineErrorRaise for a missing or incompatible commanline argument. This is usually caught by the main function and useas input for ArgParser.error()

exception BurstCube.exceptions.ConfigErrorRaise when there is a problem with the configuration

exception BurstCube.exceptions.InternalLogicErrorRaise when the program wanders into an option if shouldn’t.

exception BurstCube.exceptions.NotSupportedUse when the user tries to access a functionality that is not implemented. Unlike NotYetImplemented, thisindicates a feature that is not planned to be implemented in the near future.

exception BurstCube.exceptions.NotYetImplementedRaise to indicate that a given feature has not been implemented yet. Only use as a temporary placeholder.

exception BurstCube.exceptions.ParsingErrorRaise when there as a problem parsing a file

exception BurstCube.exceptions.UserErrorRaise to blame the user!

1.2. Documentation Contents 43

Page 48: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

1.2.5 v0 Documentation

This is the documentation for a the initial Simulations software.

We plan to replace these by a library fully compatible with the new version of gbm-data-tool.

This will be documented here while we make sure all the features are ported

Tutorial

The steps to quickly and efficiently generate source files that are used to simulate a GRB on a given BurstCubearrangement with a given strength and sky position are split into the following steps:

1. Creating source files

config.yaml allows you to select the desired geometry, desired energy range, and desired source position respectively.

Using python, this yaml file is read in using the configurator, which is contained in the simGenerator module. Formore information about each module, please see the code section.

The simGenerator module, along with the rest of the modules required for this process are located within the bin. If itis the case where these functions need to be done in a new or different directory, make sure to export them.

Next, create an object with the configurator by pointing to the yaml file like this:

conf = configurator(‘~/config.yaml’)

and now with this object, run the function conf.createSourceFiles(), which outputs all of the source files into thedesired directory.

2. Running simulations

runSims.py is a function which runs the source files and outputs the .sim files to be further analyzed.

In order to activate runSim.py, simply type into your path

python <location>/runsims.py –runCosima TRUE –sourcepath ./ x where x is the desired amount of source files to runin parallel.

After runSims has completed its operation, the sim files will be outputted in the designated directory for furtheranalysis.

3. Analyzing results

With the sim files generated, these can be plotted using python.

Once uploading the sim files to python, they can be plotted using the module plotSim, which provides many optionsas to how the various simulated detector responses can be analyzed.

BurstCube

simGenerator module

class BurstCube.simGenerator.configurator(*args)

44 Chapter 1. Introduction

Page 49: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

azbinsCreates increments of azimuth angle to be sampled by individual source files.

createSourceFiles(dir=”)Creates a source file from a configurator object with a specific angle and energy

Parameters

• dir (string) –

• desired directory of the output (the) –

Returns

• In your directory all of the source files with specific angles

• and energies.

ebinsCreates increments of energy (keV) to be sampled by individual source files.

loadConfig(path)

saveConfig(path)

zebinsCreates increments of zenith angle to be sampled by individual source files.

BurstCube.simGenerator.createSourceString(config, energy, ze, az)Creates a source file from a configurator object with a specific angle and energy

Parameters config (string) – The .yaml file the imposes the conditions for the source filesdesired.

Returns srcstr – A sring which can be used to create a source file for cosima.

Return type string

bcSim module

class BurstCube.bcSim.simFile(simFile, sourceFile, logFile=”)

ED_res

azimuth

calculateAeff(useEres=False, width=0.0)Calculates effective area of sim file.

Parameters

• useEres (Boolean) – Switch to either use the energy resolution in the calculation ornot. If you don’t use this it assumes all of the events are good.

• width (Float) – The energy width that is used to reject events in the selection.

Returns Aeff – The effective area.

Return type Float

energy

fileToDict(filename, commentString=’#’, termString=None)

getEresFromFile(filename, commentString=’//’)

1.2. Documentation Contents 45

Page 50: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

getHits(detID=4)Get the hit details of all of the events in the sim file. Ignores the a,b,and c details.

Parameters detID (int) – Detector ID (usually 4)

Returns hits – Five column Structured array. Columns are all floats and are x_pos, y_pos, z_pos,E, and tobs.

Return type numpy structured array

getTriggerProbability(num_det=4, test=False)Takes a single simFile (from bcSim.simFiles(config.yaml)) and returns the probability of hitting in eachdetector

Parameters

• num_det (integer) – Number of detectors to get triggers for.

• test (boolean) – Run a quick test over a limited number of events (20)

Returns prob_det_info – Array is (energy, az, ze, error, prob1, prob2, . . . )

Return type numpy array

logToDict(filename)Reads a gzipped log file and populates a dictionary with information about the events. Returns this dictio-nary.

Parameters filename (string or byte like object) – Name of log file to read.

Returns

• eventDict (dictionary)

• Dictionary with the key being the trigger number (int). Each

• value is a tuple of the event number (int) and the detector

• (str) that was hit.

passEres(alpha=2.57, escape=30.0)Calculates the fraction of events that are good (fully absorbed) and those that escape. The default escapephoton energy is for CsI (30.0 keV). An alpha of 2.57 is based on 10% energy resolution at 662 keV with1/sqrt(E) scaling. Sigma is calculated as the FWHM or eres diveded by 2.35.

Returns

• frac (float)

• mod_frac (float)

printDetails()Prints the general information about specific sim files.

zenith

class BurstCube.bcSim.simFiles(config_file)

applyEres()Applies the energy resolution to the deposited energy in each sim file and returns a flattened array forplotting.

Returns

• null (numpy array)

46 Chapter 1. Introduction

Page 51: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

• numpy array that contains all of the events with eres applied.

calculateAeff(useEres=False, sigma=2.0)Calculates effective area from the information contained within the .sim files.

Parameters

• self (null) –

• useEres (boolean) – Switch to use the energy resolution in the calculation.

• sigma (float) – Width of energy cut in sigma. Default is 2.0.

Returns aeffs – Numpy array containing effective area of detector.

Return type array

getAllTriggerProbability(num_detectors=4, test=False)Returns the probabability of hitting each detector in each simulation.

Parameters

• num_detectors (int) – Number of detectors in the simulation

• test (boolean) – run a quick test over a limited number of files (20)

Returns det_prob – Contains information from all the files about the energy, angles and proba-bility of hitting a given detector

Return type numpy array

loadFiles()

Parameters self (null) –

Returns sfs – numpy array containing information about each sim file.

Return type array

plotSim module

BurstCube.plotSim.getGBMdata(gbmfile=”)Reads the GBM NaI effective area file and returns a numpy array with two columns energy and aeff.

Parameters gbmfile (string) – Name of file that contains the GBM data. If not given, willlook in the installed location.

Returns

• gbmdata (array)

• numpy array with two columns energy and aeff

BurstCube.plotSim.plotAeff(simFiles, useEres=False, plotGBM=False)Plots the GBM NaI effective area against the changing parts of the simulation

Parameters simFiles (list) – Simulation files generated by MEGAlib.

Returns

Return type a bunch of plots!

BurstCube.plotSim.plotAeffComparison(sims, names, useEres=False, compareTo=’GBM’,axis=’ze’, elim=(1, 100000.0))

Makes Aeff comparison plots of two or more simulations.

Parameters

1.2. Documentation Contents 47

Page 52: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

• sims (list) – List of simulation objects that need to be compared.

• names (list) – List of strings used to label the plots. Should be the same length as thesims list.

• compareTo (string) – The curve to make the comparison to in the percent difference.Default is GBM. You can pick any of the other curves in the names list.

• axis (string) – Either ze or az for the angle axis to plot against.

Returns

Return type Nothing

BurstCube.plotSim.plotAeffvsEnergy(energy, aeff, aeff_eres, aeff_eres_modfrac, az=0, ze=0,plotGBM=False)

Plots the GBM NaI effective area against the energy of that source.

Parameters

• energy (array) – numpy array of energy in units of keV of the sources.

• aeff (array) – numpy array with GBM NaI effective area.

• aeff_eres (array) – I’ll look up energy resulution later

• aeff_eres_modfrac (array) – plus escape?

Returns

Return type a plot of the effective area vs. energy.

BurstCube.plotSim.plotAeffvsPhi(azimuth, aeff, aeff_eres, aeff_eres_modfrac)Plots the GBM NaI effective area against the polar angle phi used to generate that source.

Parameters

• azimuth (array) – numpy array of the angle in deg of the source.

• aeff (array) – numpy array with GBM NaI effective area.

• aeff_eres (array) – I’ll look up energy resulution later

• aeff_eres_modfrac (array) – plus escape?

Returns

Return type a plot!

BurstCube.plotSim.plotAeffvsTheta(theta, aeff, aeff_eres, aeff_eres_modfrac, energy=100.0,paren=”)

Plots the GBM NaI effective area against the polar angle theta used to generate that source.

Parameters

• theta (array) – numpy array of the angle in deg of the source.

• aeff (array) – numpy array with GBM NaI effective area.

• aeff_eres (array) – I’ll look up energy resulution later

• aeff_eres_modfrac (array) – plus escape?

Returns

Return type a plot!

48 Chapter 1. Introduction

Page 53: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

BurstCube.plotSim.plotAngleComparison(sims, names, axis=’ze’, compareTo=”,useEres=False, energyRange=(99, 101), an-gleRange=(0, 360))

Makes Theta comparison plots of two or more simulations.

Parameters

• sims (list) – List of simulation objects that need to be compared.

• names (list) – List of strings used to label the plots. Should be the same length as thesims list.

• axis (string ('ze' or 'az')) – Axis to plot (either ‘ze’ for zenith or ‘az’ forazimuth.

• compareTo (string) – The curve to make the comparison to in the percent difference.Default is the first in the list. You can pick any of the other curves in the names list.

• usEres (bool) – Use the energy resolution in the effective area calculation.

• energyRang (list) – The energy range (in keV) to plot as (emin, emax).

• angleRange (list) – The angular range (in keV) to plot as (degmin, degmax). This willonly plot curves that fall into this range for the axis that you are not plotting against (i.e. it’llbe ‘az’ if you selected ‘ze’ for axis above.

Returns

Return type Nothing

utils module

BurstCube.utils.getAllTriggerProbability(filelist, num_detectors=4, test=False)Takes a bunch of simFiles (from bcSim.simFiles(config.yaml)) and returns the probability of hitting in eachdetector

Parameters

• self (simFiles) –

• test (run a quick test over a limited number of files (20)) –

Returns det_prob – Contains information from all the files about the energy, angles and probabilityof hitting a given detector

Return type numpy array

BurstCube.utils.getDetailsFromFilename(filename)Function to get the energy and angle from a filename. Really should be meta data.

This function will be deprecated at some point since the energy and angle are in the simFile object now.

BurstCube.utils.getFilenameFromDetails(details)Takes a dictionary of details and makes a machine readible filename out of it. Angle comes in radians.

BurstCube.utils.getTriggerProbability(htsimfile, num_det=4, test=False)Takes a single simFile (from bcSim.simFiles(config.yaml)) and returns the probability of hitting in each detector

Parameters

• self (simFile) –

• test (run a quick test over a limited number of events (20)) –

Returns

1.2. Documentation Contents 49

Page 54: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

• prob_det_info (1x6 numpy array containing information about the)

• energy, angles and probability of hitting a given detector

BurstCube.utils.setPath(desiredPath=”, desiredPathName=’BURSTCUBE’)Checks for desiredPathName path. Returns 0 if ok, 1 if bad.

LocSim

Detector module

class BurstCube.LocSim.Detector.Detector(name=’det’, azimuth_angle=’0:0:0’,zenith_angle=’0:0:0’, noise=True,background_rate=10.0, window=2.0,lat=’37:56:24.7’, lon=’75:27:59’,elev=550000.0)

altitude

cart2polar(x, y, z)

exposure(ra, dec, FoV=False, alt=-10.0, index=0.77, horizon=90.0)This function takes an ra and a dec and reports the exposure at that point. If you declare FoV to be true,it’ll assume the exposure is uniform across the field of view. Otherwise, it will return an effective areasscaled by a cosine dependance up to the horizon.

Parameters

• ra (the right ascension of the test point) –

• dec (the declination of the test point) –

• FoV (If True, assumes a flat exposure. If false, assumes acosine dependance.) –

• alt (The location of the Earth's limb. No exposure belowthis point (degrees)) –

• index (the scaling of the cosine dependance.) –

• horizon (A cut on the field of view of a detector. Noexposure below this point (degrees)) –

Returns float

Return type the exposure at the test point

get_separation(grb)

polar2cart(theta, phi)

sign_time

sign_times

throw_grb(grb)

trigger_time

triggered_counts

triggered_counts_error

50 Chapter 1. Introduction

Page 55: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

GRB module

class BurstCube.LocSim.GRB.GRB(ra, dec, amplitude=10000.0, decay=2.0, T0=0.0, binz=1.0,real=False, filename=”)

loadFRED()

loadReal(filename, nbins=20000.0, sub=True)

Spacecraft module

class BurstCube.LocSim.Spacecraft.Spacecraft(pointings={’01’: (’0:0:0’, ’5:0:0’), ’02’:(’30:0:0’, ’20:0:0’), ’03’: (’60:0:0’,’35:0:0’), ’04’: (’90:0:0’, ’10:0:0’), ’05’:(’120:0:0’, ’25:0:0’), ’06’: (’150:0:0’,’40:0:0’), ’07’: (’180:0:0’, ’15:0:0’),’08’: (’210:0:0’, ’30:0:0’), ’09’:(’240:0:0’, ’45:0:0’), ’10’: (’270:0:0’,’20:0:0’), ’11’: (’300:0:0’, ’35:0:0’), ’12’:(’330:0:0’, ’50:0:0’)}, lat=’37:56:24.7’,lon=’75:27:59’, elev=550000.0, win-dow=4.0, background_rate=10.0,noise=True)

The pointings are just key,item pairs of the pointing directions of the detectors on the spacecraft (respect to 0,0at zenith). The default are 12 detectors pointing every 30 degrees in azimuth and 15 degrees in zenith (offset abit).

detnum

throw_grb(grb)

throw_grbs(grbs, scaled=False, save=False, filename=’grbs.pkl’)

Stats module

BurstCube.LocSim.Stats.addErrors(real_counts, training_counts)Adds all of the errors together in quadrature

Parameters

• real_counts (the array of real grb counts in each detector) –

• training_counts (the arrary of traning counts in eachdetector) –

Returns null – numpy array of the errors

Return type array

BurstCube.LocSim.Stats.calcNorms(real_counts, training_counts)Calculates the norm between the vectors in two numpy arrays.

Parameters

• real_counts (the array of real grb counts in each detector) –

• training_counts (the arrary of traning counts in eachdetector) –

1.2. Documentation Contents 51

Page 56: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

Returns null – numpy array of the norm between all of the vectors

Return type array

BurstCube.LocSim.Stats.calcNormsWithError(real_counts, training_counts,real_counts_with_error)

Utils module

BurstCube.LocSim.Utils.deg2DMS(DEC)Borrowed from Sylvain Baumont http://supernovae.in2p3.fr/~baumont/

BurstCube.LocSim.Utils.deg2HMS(RA)Borrowed from Sylvain Baumont http://supernovae.in2p3.fr/~baumont/

NoahSim

GRBgenerator module

class BurstCube.NoahSim.GRBgenerator.Sky(NSIDE, strength)Generates an array of GRB’s given certains strength at different sky positions.

Output should be an array.

fastcube module

The following cell contains the “FastCube” class. This is the simulation I hope to use emulate the results of state ofthe art simulations on GRB localization, and use these results to characterize the burstcube spacecraft.

For questions/comments please contact me, Noah Kasmanoff, at [email protected] or https://github.com/nkasmanoff

class BurstCube.NoahSim.fastcube.FastCube(background, dettilt, alternating=False)

detABurstCube is composed of 4 separate scintillators to detect and localize events. In this software package,they are labelled A through D.

detBBurstCube is composed of 4 separate scintillators to detect and localize events. In this software package,they are labelled A through D.

detCBurstCube is composed of 4 separate scintillators to detect and localize events. In this software package,they are labelled A through D.

detDBurstCube is composed of 4 separate scintillators to detect and localize events. In this software package,they are labelled A through D.

dets

normA

normB

normC

52 Chapter 1. Introduction

Page 57: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

normD

response2GRB(GRB, samples, test=True, talk=False)Using x, respond2GRB will determine the sky position of an array of GRB sources assuming some inherentbackground noise within detectors, along with fluctuations of either Gaussian or Poissonian nature.

Parameters

• GRB (object) – An instance of the separately defined “GRBs” class that contains anumber of evenly spaced sky positions of a given strength.

• test (boolean) – For sanity purposes, if the simulation seems to give unrealistic re-sults, switching to test mode allows for much quicker sampling, allowing it easier to spotpotential errors.

talk [boolean] If desired, prints position by position results.

Returns

• localizationerrors (array) – numpy array that contains the average localization uncer-tainty at each sky position.

• Additionally, response2GRB will print the sky position it is currently sampling, along withthe average offset of localizations at that spot.

response2oneGRB(sourcetheta, sourcephi, sourcestrength)If you wish, will allow you to examine the localization uncertainty of one sampled GRB of somegiven strenth at some point in the sky. For a full/complete simulation just use the function below, “re-sponse2GRB”.

Parameters

• sourcetheta (float) – The displacement in degrees in the zenithal direction.

• sourcephi (float) – The displacement in degrees in the azimuthal direction.

• sourcestrength (float) – The stength in counts of the simulated GRB.

Returns recpos – The reconstructed position of the GRB based on the detectors’ response.

Return type float

burstutils module

BurstCube.NoahSim.burstutils.angle(v1, v2)” Finds the angle between 2 vectors

Parameters

• v1 (array) –

• v2 (array) – The arrays representing the vectors who’s angle is to be calculated.

Returns ang – Angle between the 2 vectors.

Return type float

BurstCube.NoahSim.burstutils.chiresponse(A, x)Deprecated, just use normal “response” function above!

The response function used in the chi squared fitting portion of the simulation. Meant to imitate the actualresponse of a scintillator. Inputs 2 vectors, and responds with a cos^x dependence.

1.2. Documentation Contents 53

Page 58: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

Parameters A (float) – The angle between the two vectors who’s response is meant to be imitated.

Returns A – The cosine dependence based on the angle, includes a mask so that terms correspondingto angular separations beyond pi/2 are 0, imitating what would happen if a GRB didn’t strikethe face of a detector. Further simulations of this effect are neccessary in a different softwarepackage to confirm this assumption, but its okay for now.

Return type float

BurstCube.NoahSim.burstutils.findAngles(v1s, v2s)

BurstCube.NoahSim.burstutils.indexer(chisquareds, bottheta, toptheta, botphi, topphi, botA,topA, ntheta, nphi, nA)

After obtaining an array of all the possible chi squared values, this uses an equation I tediously discovered whichcan backtrack to what term in each array corresponds to the minimim chi squared.

Parameters

• chisquareds (array) – numpy array of all possible chi squared values

• bottheta (float) – Minimum polar angle to be tested.

• toptheta (float) – Maximum polar angle to be tested.

• botphi (float) – Minimum azimuthal angle to be tested.

• topphi (float) – Maximum azimuthal angle to be tested.

• botA (float) – Minimum signal strength to be tested.

• topA (float) – Maximum signal strength to be tested.

• ntheta (int) – Number of sample points between bottheta and toptheta.

• nphi (int) – Number of sample points between botphi and topphi.

• nA (int) – Number of sample points between botA and topA.

Returns

• thetaloc (float) – The reconstructed polar angle of the source.

• philoc (float) – The reconstructeed azimuthal angle of the source.

• Aoguess (float) – The reconstructed strength of the source.

BurstCube.NoahSim.burstutils.length(v)Finds the length of a vector

Parameters v (array) – numpy array representative of the vector you want to find the magnitudeof.

Returns magv – magnitude of v.

Return type float

BurstCube.NoahSim.burstutils.look_up_A(detnorm, source, array=False)The look up table for detector A. Currently for all these functions the coordinates are relative to the top of thespacecraft, not indivudial detectors. To tranform just rotate by this specific detnorm.

Parameters

• detnorm (array) – The vector normal to detector A.

• source (array) – The vector pointing to where in the sky the GRB came from.

Returns x – The exponent of dependence for the detector’s response.

Return type float

54 Chapter 1. Introduction

Page 59: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

BurstCube.NoahSim.burstutils.look_up_B(detnorm, source, array=False)The look up table for detector B. Currently for all these functions the coordinates are relative to the top of thespacecraft, not indivudial detectors. To tranform just rotate by this specific detnorm.

Parameters

• detnorm (array) – The vector normal to detector B.

• source (array) – The vector pointing to where in the sky the GRB came from.

Returns x – The exponent of dependence for the detector’s response.

Return type float

BurstCube.NoahSim.burstutils.look_up_C(detnorm, source, array=False)The look up table for detector C.

Parameters

• detnorm (array) – The vector normal to detector C.

• source (array) – The vector pointing to where in the sky the GRB came from.

Returns

• x (float) – The exponent of dependence for the detector’s response.

• Example

• Let’s say for this detector, past 30 degrees and for azimuths of

• 60 - 180, it’s blocked. This is what it would look like

• R = 0.76*np.ones(shape=np.shape(X)) – R[30:,60:180] = 0

BurstCube.NoahSim.burstutils.look_up_D(detnorm, source, array=False)The look up table for detector D.

Parameters

• detnorm (array) – The vector normal to detector D.

• source (array) – The vector pointing to where in the sky the GRB came from.

Returns x – The exponent of dependence for the detector’s response.

Return type float

BurstCube.NoahSim.burstutils.quad_solver(detval, detnorm, bottheta, toptheta, botphi, top-phi, botA, topA, ntheta, nphi, nA, background,A=False, B=False, C=False, D=False)

Generates an array of all possible chi terms for a given detector and the number of counts induced in it by somesource. Named quad since BurstCube is composed of 4 detectors, and this generates 1/4 of the terms.

Parameters

• detsvals (array) – Numpy array containing the relative counts in a BurstCube detector.

• detnorms (array) – Numpy array containing the normal vector of a BurstCube detector.

• bottheta (float) – Minimum polar angle to be tested.

• toptheta (float) – Maximum polar angle to be tested.

• botphi (float) – Minimum azimuthal angle to be tested.

• topphi (float) – Maximum azimuthal angle to be tested.

• botA (float) – Minimum signal strength to be tested.

1.2. Documentation Contents 55

Page 60: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

• topA (float) – Maximum signal strength to be tested.

• ntheta (int) – Number of sample points between bottheta and toptheta.

• nphi (int) – Number of sample points between botphi and topphi.

• bgrd (float) – # of background counts inherent to each detector.

• nA (int) – Number of sample points between botA and topA.

Returns chiterm – Numpy array containing all the chisquared terms for one BurstCube detector.

Return type array

BurstCube.NoahSim.burstutils.response(A, x)Meant to imitate the actual response of a scintillator. Inputs 2 vectors, and responds with a cos^x dependence.

Parameters

• A (float) – The angular separation in radians between the normal vector of the detector,and the position in the sky of the simulated GRB.

• x (float) – The dependence

Returns R – The response function of how the scintillator will respond to a source at angle A.

Return type float

56 Chapter 1. Introduction

Page 61: BurstCube Documentation Documentation

Python Module Index

bBurstCube.bcSim, 45BurstCube.exceptions, 43BurstCube.LocSim.Detector, 50BurstCube.LocSim.GRB, 51BurstCube.LocSim.Spacecraft, 51BurstCube.LocSim.Stats, 51BurstCube.LocSim.Utils, 52BurstCube.NoahSim.burstutils, 53BurstCube.NoahSim.fastcube, 52BurstCube.NoahSim.GRBgenerator, 52BurstCube.plotSim, 47BurstCube.simGenerator, 44BurstCube.sims.detector_effects, 32BurstCube.sims.rsp_gen, 34BurstCube.spectra.spectrum, 28BurstCube.util.coords, 40BurstCube.util.units, 41BurstCube.utils, 49

57

Page 62: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

58 Python Module Index

Page 63: BurstCube Documentation Documentation

Index

Aabsolute_path() (BurstCube.config.Configurator

method), 42adaptive_moc_mesh()

(BurstCube.io.InstrumentResponse classmethod), 16

add_hit() (BurstCube.containers.SimEvent method),23

addErrors() (in module BurstCube.LocSim.Stats), 51altitude (BurstCube.LocSim.Detector.Detector

attribute), 50ang2pix() (BurstCube.io.InstrumentResponse

method), 16angle() (in module BurstCube.NoahSim.burstutils), 53apply() (BurstCube.sims.detector_effects.SimDetectorEffect

method), 33apply() (BurstCube.sims.detector_effects.SimDetectorEffects

method), 33apply() (BurstCube.sims.detector_effects.SimEfficiencyFromPoints

method), 33apply() (BurstCube.sims.detector_effects.SimEnergyResolutionFromFit

method), 34applyEres() (BurstCube.bcSim.simFiles method), 46Attitude (class in BurstCube.util.coords), 40axes (BurstCube.containers.Histogram attribute), 24axes (BurstCube.sims.DRM attribute), 35Axes (class in BurstCube.containers.histogram), 27axis (BurstCube.containers.Histogram attribute), 24Axis (class in BurstCube.containers.histogram), 26azbins (BurstCube.simGenerator.configurator at-

tribute), 44azimuth (BurstCube.bcSim.simFile attribute), 45azimuth (BurstCube.util.coords.SpacecraftCoords at-

tribute), 41

Bbest_loc() (BurstCube.loc.TSMap method), 39boundaries() (BurstCube.io.InstrumentResponse

method), 17

bounds (BurstCube.containers.histogram.Axis at-tribute), 26

BurstCube.bcSim (module), 45BurstCube.exceptions (module), 43BurstCube.LocSim.Detector (module), 50BurstCube.LocSim.GRB (module), 51BurstCube.LocSim.Spacecraft (module), 51BurstCube.LocSim.Stats (module), 51BurstCube.LocSim.Utils (module), 52BurstCube.NoahSim.burstutils (module), 53BurstCube.NoahSim.fastcube (module), 52BurstCube.NoahSim.GRBgenerator (module),

52BurstCube.plotSim (module), 47BurstCube.simGenerator (module), 44BurstCube.sims.detector_effects (module),

32BurstCube.sims.rsp_gen (module), 34BurstCube.spectra.spectrum (module), 28BurstCube.util.coords (module), 40BurstCube.util.units (module), 41BurstCube.utils (module), 49

CcalcNorms() (in module BurstCube.LocSim.Stats), 51calcNormsWithError() (in module

BurstCube.LocSim.Stats), 52calculateAeff() (BurstCube.bcSim.simFile

method), 45calculateAeff() (BurstCube.bcSim.simFiles

method), 47cart2polar() (BurstCube.LocSim.Detector.Detector

method), 50cartesian (BurstCube.util.coords.SphericalCoords at-

tribute), 41CartesianCoords (class in BurstCube.util.coords),

40centers (BurstCube.containers.histogram.Axis at-

tribute), 27

59

Page 64: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

channel_effective_area()(BurstCube.sims.DRM method), 35

chiresponse() (in moduleBurstCube.NoahSim.burstutils), 53

clear() (BurstCube.containers.Histogram method), 24close() (BurstCube.io.InstrumentResponse method),

17cm (in module BurstCube.util.units), 42cm2 (in module BurstCube.util.units), 42CommandLineError, 43compute() (BurstCube.loc.TSMap method), 39concatenate() (BurstCube.containers.Histogram

class method), 24config_example_path()

(BurstCube.config.Configurator static method),43

ConfigError, 43Configurator (class in BurstCube.config), 42configurator (class in BurstCube.simGenerator), 44conformable() (BurstCube.io.InstrumentResponse

method), 17CosimaSim (class in BurstCube.io), 13CosimaSource (class in BurstCube.io), 14counts_to_rsp() (in module

BurstCube.sims.rsp_gen), 34createSourceFiles()

(BurstCube.simGenerator.configuratormethod), 45

createSourceString() (in moduleBurstCube.simGenerator), 45

Ddec (BurstCube.util.coords.SkyCoords attribute), 40deg (in module BurstCube.util.units), 42deg2DMS() (in module BurstCube.LocSim.Utils), 52deg2HMS() (in module BurstCube.LocSim.Utils), 52detA (BurstCube.NoahSim.fastcube.FastCube attribute),

52detB (BurstCube.NoahSim.fastcube.FastCube attribute),

52detC (BurstCube.NoahSim.fastcube.FastCube attribute),

52detD (BurstCube.NoahSim.fastcube.FastCube attribute),

52Detector (class in BurstCube.containers), 23Detector (class in BurstCube.LocSim.Detector), 50detectors (BurstCube.containers.Detector attribute),

23detectors (BurstCube.io.InstrumentResponse at-

tribute), 17detnum (BurstCube.LocSim.Spacecraft.Spacecraft at-

tribute), 51dets (BurstCube.NoahSim.fastcube.FastCube attribute),

52

distance (BurstCube.util.coords.SkyCoords attribute),40

distance (BurstCube.util.coords.SpacecraftCoords at-tribute), 41

DRM (class in BurstCube.sims), 35dts() (BurstCube.fitting.FastNormFit static method),

32dump() (BurstCube.config.Configurator method), 43

Eebins (BurstCube.simGenerator.configurator attribute),

45ED_res (BurstCube.bcSim.simFile attribute), 45effective_area() (BurstCube.sims.DRM method),

35energy (BurstCube.bcSim.simFile attribute), 45energy_channels (BurstCube.sims.DRM attribute),

35energy_channels()

(BurstCube.io.InstrumentResponse method), 17error_area() (BurstCube.loc.TSMap method), 39eV (in module BurstCube.util.units), 42eval() (BurstCube.spectra.spectrum.Mono method),

28eval() (BurstCube.spectra.spectrum.PowerLaw

method), 29eval() (BurstCube.spectra.spectrum.Spectrum

method), 30event_iter() (BurstCube.io.CosimaSim static

method), 13exposure() (BurstCube.LocSim.Detector.Detector

method), 50

FFastCube (class in BurstCube.NoahSim.fastcube), 52FastNormFit (class in BurstCube.fitting), 31filename (BurstCube.io.InstrumentResponse at-

tribute), 17fileToDict() (BurstCube.bcSim.simFile method), 45fill() (BurstCube.containers.Histogram method), 25find_bin() (BurstCube.containers.Histogram

method), 25find_bin() (BurstCube.containers.histogram.Axis

method), 27findAngles() (in module

BurstCube.NoahSim.burstutils), 54flux (BurstCube.spectra.spectrum.PowerLaw attribute),

29flux (BurstCube.spectra.spectrum.Spectrum attribute),

30fold_spectrum() (BurstCube.sims.DRM method),

35frame (BurstCube.loc.HealpixLocTable attribute), 37frame (BurstCube.loc.TSMap attribute), 39

60 Index

Page 65: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

from_config() (BurstCube.sims.detector_effects.SimDetectorEffectclass method), 33

from_gbm_rsp() (BurstCube.sims.DRM classmethod), 35

from_gbm_rsp_file() (BurstCube.sims.DRM classmethod), 36

from_megalib() (BurstCube.spectra.spectrum.Spectrumclass method), 30

from_megalib() (BurstCube.util.coords.SpacecraftCoordsclass method), 41

from_name() (BurstCube.sims.detector_effects.SimDetectorEffectclass method), 33

from_name() (BurstCube.spectra.spectrum.Spectrumclass method), 30

from_rsps() (BurstCube.io.InstrumentResponse classmethod), 17

Gget_all_neighbours()

(BurstCube.io.InstrumentResponse method), 17get_background() (BurstCube.loc.HealpixLocTable

method), 37get_background() (BurstCube.loc.LocTable

method), 36get_background() (BurstCube.loc.NormLocLike

method), 38get_data() (BurstCube.loc.HealpixLocTable

method), 37get_data() (BurstCube.loc.LocTable method), 36get_data() (BurstCube.loc.NormLocLike method), 39get_drm() (BurstCube.io.InstrumentResponse

method), 17get_expectation()

(BurstCube.loc.HealpixLocTable method),37

get_expectation() (BurstCube.loc.LocTablemethod), 36

get_expectation() (BurstCube.loc.NormLocLikemethod), 39

get_interp_weights()(BurstCube.io.InstrumentResponse method), 18

get_log_like() (BurstCube.loc.LocLike method),38

get_log_like() (BurstCube.loc.NormLocLikemethod), 39

get_null_log_like() (BurstCube.loc.LocLikemethod), 38

get_null_log_like()(BurstCube.loc.NormLocLike method), 39

get_separation() (BurstCube.LocSim.Detector.Detectormethod), 50

getAllTriggerProbability()(BurstCube.bcSim.simFiles method), 47

getAllTriggerProbability() (in moduleBurstCube.utils), 49

getDetailsFromFilename() (in moduleBurstCube.utils), 49

getEresFromFile() (BurstCube.bcSim.simFilemethod), 45

getFilenameFromDetails() (in moduleBurstCube.utils), 49

getGBMdata() (in module BurstCube.plotSim), 47getHits() (BurstCube.bcSim.simFile method), 45getTriggerProbability()

(BurstCube.bcSim.simFile method), 46getTriggerProbability() (in module

BurstCube.utils), 49GeV (in module BurstCube.util.units), 42GRB (class in BurstCube.LocSim.GRB), 51

Hhalfpi (in module BurstCube.util.units), 42HealpixLocTable (class in BurstCube.loc), 37Histogram (class in BurstCube.containers), 23Hit (class in BurstCube.containers), 22

Iindexer() (in module BurstCube.NoahSim.burstutils),

54inf (in module BurstCube.util.units), 42InstrumentResponse (class in BurstCube.io), 16integrate() (BurstCube.spectra.spectrum.Mono

method), 29integrate() (BurstCube.spectra.spectrum.PowerLaw

method), 29integrate() (BurstCube.spectra.spectrum.Spectrum

method), 30InternalLogicError, 43interp() (BurstCube.containers.Histogram method),

25interp_weights() (BurstCube.containers.histogram.Axes

method), 28interp_weights() (BurstCube.containers.histogram.Axis

method), 27is_fully_defined()

(BurstCube.containers.SimEvent method),23

is_mesh_valid() (BurstCube.io.InstrumentResponsemethod), 18

is_moc (BurstCube.io.InstrumentResponse attribute),18

is_nested (BurstCube.io.InstrumentResponse at-tribute), 18

is_ring (BurstCube.io.InstrumentResponse attribute),18

Index 61

Page 66: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

KkeV (in module BurstCube.util.units), 42key_to_index() (BurstCube.containers.histogram.Axes

method), 28

Llabels (BurstCube.containers.histogram.Axes at-

tribute), 28labels (BurstCube.loc.HealpixLocTable attribute), 37labels (BurstCube.loc.LocTable attribute), 37labels (BurstCube.loc.NormLocLike attribute), 39length() (in module BurstCube.NoahSim.burstutils),

54loadConfig() (BurstCube.simGenerator.configurator

method), 45loadFiles() (BurstCube.bcSim.simFiles method), 47loadFRED() (BurstCube.LocSim.GRB.GRB method),

51loadReal() (BurstCube.LocSim.GRB.GRB method),

51LocLike (class in BurstCube.loc), 38LocTable (class in BurstCube.loc), 36logToDict() (BurstCube.bcSim.simFile method), 46look_up_A() (in module

BurstCube.NoahSim.burstutils), 54look_up_B() (in module

BurstCube.NoahSim.burstutils), 55look_up_C() (in module

BurstCube.NoahSim.burstutils), 55look_up_D() (in module

BurstCube.NoahSim.burstutils), 55lower_bounds (BurstCube.containers.histogram.Axis

attribute), 27

Mm (in module BurstCube.util.units), 42main() (in module BurstCube.sims.rsp_gen), 34max (BurstCube.containers.histogram.Axis attribute), 27max_energy (BurstCube.containers.Detector at-

tribute), 23merge() (BurstCube.io.CosimaSim method), 14meter (in module BurstCube.util.units), 42MeV (in module BurstCube.util.units), 42min (BurstCube.containers.histogram.Axis attribute), 27min_energy (BurstCube.containers.Detector at-

tribute), 23moc_from_pixels()

(BurstCube.io.InstrumentResponse classmethod), 18

moc_sort() (BurstCube.io.InstrumentResponsemethod), 19

Mono (class in BurstCube.spectra.spectrum), 28

Nnbins (BurstCube.containers.histogram.Axis attribute),

27ndim (BurstCube.containers.histogram.Axes attribute),

28nest2pix() (BurstCube.io.InstrumentResponse

method), 19nmeasurements (BurstCube.loc.LocTable attribute),

37normA (BurstCube.NoahSim.fastcube.FastCube at-

tribute), 52normalize() (BurstCube.spectra.spectrum.Mono

method), 29normalize() (BurstCube.spectra.spectrum.PowerLaw

method), 30normalize() (BurstCube.spectra.spectrum.Spectrum

method), 30normB (BurstCube.NoahSim.fastcube.FastCube at-

tribute), 52normC (BurstCube.NoahSim.fastcube.FastCube at-

tribute), 52normD (BurstCube.NoahSim.fastcube.FastCube at-

tribute), 52NormLocLike (class in BurstCube.loc), 38NotSupported, 43NotYetImplemented, 43npix (BurstCube.io.InstrumentResponse attribute), 19nside (BurstCube.io.InstrumentResponse attribute), 19

Oopen() (BurstCube.io.CosimaSim class method), 14open() (BurstCube.io.CosimaSource class method), 15open() (BurstCube.loc.HealpixLocTable class method),

37order (BurstCube.io.InstrumentResponse attribute), 19override() (BurstCube.config.Configurator method),

43

PParsingError, 43passEres() (BurstCube.bcSim.simFile method), 46photon_energies (BurstCube.sims.DRM attribute),

36photon_energies()

(BurstCube.io.InstrumentResponse method), 19pi (in module BurstCube.util.units), 42pix2ang() (BurstCube.io.InstrumentResponse

method), 19pix2range() (BurstCube.io.InstrumentResponse

method), 19pix2uniq() (BurstCube.io.InstrumentResponse

method), 19pix2vec() (BurstCube.io.InstrumentResponse

method), 20

62 Index

Page 67: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

pix_order_list() (BurstCube.io.InstrumentResponsemethod), 20

pix_rangesets() (BurstCube.io.InstrumentResponsemethod), 20

pixarea() (BurstCube.io.InstrumentResponsemethod), 20

plot() (BurstCube.loc.TSMap method), 39plot_grid() (BurstCube.io.InstrumentResponse

method), 20plotAeff() (in module BurstCube.plotSim), 47plotAeffComparison() (in module

BurstCube.plotSim), 47plotAeffvsEnergy() (in module

BurstCube.plotSim), 48plotAeffvsPhi() (in module BurstCube.plotSim), 48plotAeffvsTheta() (in module BurstCube.plotSim),

48plotAngleComparison() (in module

BurstCube.plotSim), 48polar2cart() (BurstCube.LocSim.Detector.Detector

method), 50PowerLaw (class in BurstCube.spectra.spectrum), 29print_config_example_path()

(BurstCube.config.Configurator static method),43

printDetails() (BurstCube.bcSim.simFile method),46

project() (BurstCube.containers.Histogram method),25

Qquad_solver() (in module

BurstCube.NoahSim.burstutils), 55quaternion (BurstCube.util.coords.Attitude attribute),

40query_disc() (BurstCube.io.InstrumentResponse

method), 21query_polygon() (BurstCube.io.InstrumentResponse

method), 21query_strip() (BurstCube.io.InstrumentResponse

method), 21

Rra (BurstCube.util.coords.SkyCoords attribute), 40rad (in module BurstCube.util.units), 42radian (in module BurstCube.util.units), 42response() (in module

BurstCube.NoahSim.burstutils), 56response2GRB() (BurstCube.NoahSim.fastcube.FastCube

method), 53response2oneGRB()

(BurstCube.NoahSim.fastcube.FastCubemethod), 53

rsp_gen() (in module BurstCube.sims.rsp_gen), 34

rsp_gen_direction() (in moduleBurstCube.sims.rsp_gen), 34

run() (BurstCube.io.CosimaSource method), 15

Ss (in module BurstCube.util.units), 42saveConfig() (BurstCube.simGenerator.configurator

method), 45scale() (BurstCube.containers.Histogram method), 25scale() (BurstCube.containers.histogram.Axis

method), 27scheme (BurstCube.io.InstrumentResponse attribute),

21second (in module BurstCube.util.units), 42set_background() (BurstCube.loc.HealpixLocTable

method), 38set_data() (BurstCube.loc.HealpixLocTable

method), 38set_elims() (BurstCube.spectra.spectrum.Spectrum

method), 30set_point_source() (BurstCube.io.CosimaSource

method), 15setPath() (in module BurstCube.utils), 50shape (BurstCube.containers.Histogram attribute), 26sign_time (BurstCube.LocSim.Detector.Detector at-

tribute), 50sign_times (BurstCube.LocSim.Detector.Detector at-

tribute), 50sim_loc_to_detector()

(BurstCube.containers.Detector method),23

SimDetectorEffect (class inBurstCube.sims.detector_effects), 32

SimDetectorEffects (class inBurstCube.sims.detector_effects), 33

SimEfficiencyFromPoints (class inBurstCube.sims.detector_effects), 33

SimEnergyResolutionFromFit (class inBurstCube.sims.detector_effects), 33

SimEvent (class in BurstCube.containers), 22simFile (class in BurstCube.bcSim), 45simFiles (class in BurstCube.bcSim), 46Sky (class in BurstCube.NoahSim.GRBgenerator), 52SkyCoords (class in BurstCube.util.coords), 40slice() (BurstCube.containers.Histogram method), 26solve() (BurstCube.fitting.FastNormFit method), 32Spacecraft (class in BurstCube.LocSim.Spacecraft),

51SpacecraftCoords (class in BurstCube.util.coords),

40Spectrum (class in BurstCube.spectra.spectrum), 30spherical (BurstCube.util.coords.CartesianCoords

attribute), 40

Index 63

Page 68: BurstCube Documentation Documentation

BurstCube Documentation Documentation, Release 1.0.0

SphericalCoords (class in BurstCube.util.coords),41

TTeV (in module BurstCube.util.units), 42throw_grb() (BurstCube.LocSim.Detector.Detector

method), 50throw_grb() (BurstCube.LocSim.Spacecraft.Spacecraft

method), 51throw_grbs() (BurstCube.LocSim.Spacecraft.Spacecraft

method), 51time_shift() (BurstCube.io.CosimaSim method), 14to_gbm_rsp() (BurstCube.sims.DRM method), 36to_gbm_rsp_file() (BurstCube.sims.DRM

method), 36to_megalib() (BurstCube.spectra.spectrum.Mono

method), 29to_megalib() (BurstCube.spectra.spectrum.PowerLaw

method), 30to_megalib() (BurstCube.spectra.spectrum.Spectrum

method), 31to_megalib() (BurstCube.util.coords.SpacecraftCoords

method), 41to_skycoords() (BurstCube.util.coords.SpacecraftCoords

method), 41to_spacecraftcoords()

(BurstCube.util.coords.SkyCoords method), 40to_TTE() (BurstCube.io.CosimaSim method), 14trigger_time (BurstCube.LocSim.Detector.Detector

attribute), 50triggered_counts (BurstCube.LocSim.Detector.Detector

attribute), 50triggered_counts_error

(BurstCube.LocSim.Detector.Detector at-tribute), 50

ts() (BurstCube.fitting.FastNormFit static method), 32TSMap (class in BurstCube.loc), 39twopi (in module BurstCube.util.units), 42

Uuniq (BurstCube.io.InstrumentResponse attribute), 21upper_bounds (BurstCube.containers.histogram.Axis

attribute), 27UserError, 43

Vvec2pix() (BurstCube.io.InstrumentResponse

method), 22

Wwidths (BurstCube.containers.histogram.Axis at-

tribute), 27write() (BurstCube.io.CosimaSource method), 15write() (BurstCube.loc.HealpixLocTable method), 38

Zzebins (BurstCube.simGenerator.configurator at-

tribute), 45zenith (BurstCube.bcSim.simFile attribute), 46zenith (BurstCube.util.coords.SpacecraftCoords at-

tribute), 41

64 Index