flamedisx package

Subpackages

Submodules

flamedisx.block_source module

class flamedisx.block_source.Block(source)[source]

Bases: object

One part of a BlockSource model.

For example, P(electrons_detected | electrons_produced).

_annotate(d)[source]

Add _min and _max for each dimension to d in-place

_calculate_dimsizes_special()[source]

Re-calculate dimension size and steps differently for any dimensions; will need to override _calculate_dimsizes_special() within a block

_compute(data_tensor, ptensor, **kwargs)[source]

Return (n_batch_events, …dimensions…) tensor

_domain_dict_bonus(d)[source]

Calculate any additional intenal tensors arising from the use of bonus_dimensions in a block. Override within block

_simulate(d)[source]

Simulate extra columns in place.

Use the p_accepted column to modify acceptances; do not remove events here.

annotate(d: pandas.core.frame.DataFrame)[source]

Add _min and _max for each dimension to d in-place

array_columns: Tuple[str] = ()

Names of columns this block expects to be array-valued

check_data()[source]
compute(data_tensor, ptensor, **kwargs)[source]
depends_on: Tuple[Tuple[Tuple[str], str]] = ()

Blocks whose result this block expects as an extra keyword argument to compute. Specify as ((block_dims, argument_name), …), where block_dims is the dimensions-tuple of the block, and argument_name the expected name of the compute keyword argument.

dimensions: Tuple[str]

Names of dimensions of the block’s compute result

extra_dimensions: Tuple[Tuple[str, bool]]

Additional dimensions used in the block computation. Label True if they represent an internally contracted hidden variable; these will be added to inner_dimensions so domain tensors are calculated automatically. Label False otherwise; these will be added to bonus_dimensions. Thus, any additional domain tensors utilising them will need calculating via the block overriding _domain_dict_bonus())

frozen_model_functions: Tuple[str] = ()

Frozen model functions defined in this block

gimme(*args, **kwargs)[source]

Shorthand for self.source.gimme, see docs there

gimme_numpy(*args, **kwargs)[source]

Shorthand for self.source.gimme_numpy

model_attributes: Tuple[str] = ()

Additional attributes this Block will furnish the source with. These can be overriden by Source attributes, just like model functions.

model_functions: Tuple[str] = ()

Names of model functions defined in this block

setup()[source]

Do any necessary initialization.

Called after the block’s attributes have been properly overriden by source attributes, if specified.

simulate(d: pandas.core.frame.DataFrame)[source]
source: flamedisx.source.Source = None

Source the block belongs to

special_model_functions: Tuple[str] = ()

Names of model functions that take an additional first argument (‘bonus arg’) defined in this block; must be a subset of model_functions

class flamedisx.block_source.BlockModelSource(*args, **kwargs)[source]

Bases: flamedisx.source.Source

Source whose model is split over different Blocks

_annotate(_skip_bounds_computation=False)[source]

Add columns needed in inference to self.data

_check_data()[source]

Do any final checks on the self.data dataframe, before passing it on to the tensorflow layer.

_differential_rate(data_tensor, ptensor)[source]
_domain_dict(dimensions, data_tensor)[source]
static _find_block(blocks, has_dim: Union[list, tuple, set], exclude: Optional[flamedisx.block_source.Block] = None)[source]

Find a block with a dimension in has_dim, other than the block in exclude. Return (dimensions, b), or raises BlockNotFoundError.

_simulate_response()[source]

Do a forward simulation of the detector response, using self.data

add_derived_observables(d)[source]
calculate_dimsizes_special()[source]

Custom calulcation of any dimension sizes and steps; override _calculate_dimsizes_special within block

domain(x, data_tensor=None)[source]

Return (n_events, n_x) matrix containing all possible integer values of x for each event.

If x is a final dimension (e.g. s1, s2), we return an (n_events, 1) tensor with observed values – NOT a (n_events,) array!

draw_positions(*args, **kwargs)[source]
extra_dimensions = ()

Additional dimensions used in the block computation; see Block.extra_dimensions for info

initial_dimensions: tuple

Dimensions provided by the first block

model_blocks: tuple

Blocks the source is built from. simulate will be called from first to last, annotate from last to first.

mu_before_efficiencies(**params)[source]

Return mean expected number of events BEFORE efficiencies/response using data for the evaluation of the energy spectra

multiply_block_results(b_dims, b2_dims, r, r2)[source]

Return result of matrix-multiplying two block results :param b_dims: tuple, dimension specification of r :param b2_dims: tuple, dimension specification of r2 :param r: tensor , first block result to be multiplier :param r2: tensor, second block result to be multiplied :return: (dimension specification, tensor) of results

random_truth(n_events, fix_truth=None, **params)[source]

Draw random “deep truth” variables (energy, position)

validate_fix_truth(fix_truth)[source]

Return checked fix truth, with extra derived variables if needed

class flamedisx.block_source.FirstBlock(source)[source]

Bases: flamedisx.block_source.Block

The first Block of a source. This is usually an energy spectrum

_annotate(d)[source]

Add _min and _max for each dimension to d in-place

_simulate(d)[source]

Simulate extra columns in place.

Use the p_accepted column to modify acceptances; do not remove events here.

dimensions: Tuple[str]

Names of dimensions of the block’s compute result

domain(data_tensor)[source]

Return dictionary mapping dimension -> domain

extra_dimensions: Tuple[Tuple[str, bool]]

Additional dimensions used in the block computation. Label True if they represent an internally contracted hidden variable; these will be added to inner_dimensions so domain tensors are calculated automatically. Label False otherwise; these will be added to bonus_dimensions. Thus, any additional domain tensors utilising them will need calculating via the block overriding _domain_dict_bonus())

mu_before_efficiencies(**params)[source]
random_truth(n_events, fix_truth=None, **params)[source]
validate_fix_truth(d)[source]

flamedisx.inference module

flamedisx.likelihood module

class flamedisx.likelihood.LogLikelihood(sources: Union[Dict[str, type], Dict[str, Dict[str, type]]], data: Union[None, pandas.core.frame.DataFrame, Dict[str, pandas.core.frame.DataFrame]] = None, free_rates=None, batch_size=10, max_sigma=None, max_dim_size=120, n_trials=100000, log_constraint=None, bounds_specified=True, progress=True, defaults=None, **common_param_specs)[source]

Bases: object

_filter_source_kwargs(kwargs, source_name)[source]

Return {param: value} dictionary with keyword arguments for source, with values extracted from kwargs

_get_rate_mult(sname, kwargs)[source]
_log_likelihood(i_batch, dsetname, data_tensor, batch_info, omit_grads=(), second_order=False, **params)[source]
_log_likelihood_inner(i_batch, params, dsetname, data_tensor, batch_info)[source]

Return log likelihood contribution of one batch in a dataset

This loops over sources in the dataset and events in the batch, but not not over datasets or batches.

_param_i(pname)[source]

Return index of parameter pname

_source_kwargnames(source_name)[source]

Return parameter names that apply to source

batch_info: tensorflow.python.framework.ops.Tensor
bestfit(guess=None, fix=None, bounds=None, optimizer='scipy', get_lowlevel_result=False, get_history=False, use_hessian=True, return_errors=False, nan_val=inf, optimizer_kwargs=None, allow_failure=False)[source]

Return best-fit parameter dict

Parameters
  • guess – Guess parameters: dict {param: guess} of guesses to use. Any omitted parameters will be guessed at LogLikelihood.defaults()

  • fix – dict {param: value} of parameters to keep fixed during the minimzation.

  • optimizer – ‘tf’, ‘minuit’ or ‘scipy’

  • get_lowlevel_result – Returns the full optimizer result instead of the best fit parameters. Bool.

  • get_history – Returns the history of optimizer calls instead of the best fit parameters. Bool.

  • use_hessian – If True, uses flamedisxs’ exact Hessian in the optimizer. Otherwise, most optimizers estimate it by finite- difference calculations.

  • return_errors – If using the minuit minimizer, instead return a 2-tuple of (bestfit dict, error dict). If the optimizer is minuit, you can also pass ‘hesse’ or ‘minos’.

  • allow_failure – If True, raise a warning instead of an exception if there is an optimizer failure.

column_indices: Dict[str, numpy.ndarray]
data_tensors: Dict[str, tensorflow.python.framework.ops.Tensor]
dset_for_source

alias of Dict[str, str]

dsetnames: List
guess() Dict[str, float][source]

Return dictionary of parameter guesses

interval(parameter, **kwargs)[source]

Return central confidence interval on parameter. Options are the same as for limit.

inverse_hessian(params, omit_grads=())[source]

Return inverse hessian (square tensor) of -2 log_likelihood at params

limit(parameter, bestfit=None, guess=None, fix=None, bounds=None, confidence_level=0.9, kind='upper', sigma_guess=None, t_ppf=None, t_ppf_grad=None, t_ppf_hess=None, optimizer='scipy', get_history=False, get_lowlevel_result=False, tilt_overshoot=0.037, optimizer_kwargs=None, use_hessian=True, allow_failure=False)[source]

Return frequentist limit or confidence interval.

Returns a float (for upper or lower limits) or a 2-tuple of floats (for a central interval)

Parameters
  • parameter – string, the parameter to set the interval on

  • bestfit – {parameter: value} dictionary, global best-fit. If omitted, will compute it using bestfit.

  • guess – {param: value} guess of the result, or None. If omitted, nuisance parameters will be guessed equal to bestfit. If omitted, guess for target parameters will be based on asymptotic parabolic computation.

  • fix – {param: value} to fix during interval computation. Result is only valid if same parameters were fixed for bestfit.

  • confidence_level – Requried confidence level of the interval

  • kind – Type of interval, ‘upper’, ‘lower’ or ‘central’

  • sigma_guess – Guess for one sigma uncertainty on the target parameter. If not provided, will be computed from Hessian.

  • t_ppf – returns critical value as function of parameter Use Wilks’ theorem if omitted.

  • t_ppf_grad – return derivative of t_ppf

  • t_ppf_hess – return second derivative of t_ppf

  • tilt_overshoot – Set tilt so the limit’s log likelihood will overshoot the target value by roughly this much.

  • optimizer_kwargs – dict of additional arguments for optimizer

  • allow_failure – If True, raise a warning instead of an exception if there is an optimizer failure.

  • use_hessian – If True, uses flamedisxs’ exact Hessian in the optimizer. Otherwise, most optimizers estimate it by finite- difference calculations.

log_likelihood(second_order=False, omit_grads=(), **kwargs)[source]
minus2_ll(*, omit_grads=(), **kwargs)[source]
mu(*, source_name=None, dataset_name=None, **kwargs)[source]

Return expected number of events :param dataset_name: … for just this dataset :param source_name: … for just this source. You must provide either dsetname or source, since it makes no sense to add events from multiple datasets

param_defaults: Dict[str, tensorflow.python.framework.ops.Tensor]
params_to_dict(values)[source]

Return parameter {name: value} dictionary

prepare_params(kwargs, free_all_rates=False)[source]
set_data(data: Union[pandas.core.frame.DataFrame, Dict[str, pandas.core.frame.DataFrame]])[source]

set new data for sources in the likelihood. Data is passed in the same format as for __init__ Data can contain any subset of the original data keys to only update specific datasets.

simulate(fix_truth=None, **params)[source]

Simulate events from sources.

sources: Dict[str, flamedisx.source.Source]
sources_in_dset

alias of Dict[str, str]

summary(bestfit=None, fix=None, guess=None, inverse_hessian=None, precision=3)[source]

Print summary information about best fit

flamedisx.likelihood.cov_to_std(cov)[source]

Return (std errors, correlation coefficent matrix) given covariance matrix cov

flamedisx.lxe_sources module

class flamedisx.lxe_sources.ERSource(*args, **kwargs)[source]

Bases: flamedisx.block_source.BlockModelSource

final_dimensions: ty.Tuple[str] = ('s1', 's2')

Names of final observable dimensions (e.g. s1, s2) for use in domain / cross-domain

initial_dimensions: tuple

Dimensions provided by the first block

model_blocks: tuple = (<class 'flamedisx.lxe_blocks.energy_spectrum.FixedShapeEnergySpectrum'>, <class 'flamedisx.lxe_blocks.quanta_generation.MakeERQuanta'>, <class 'flamedisx.lxe_blocks.quanta_splitting.MakePhotonsElectronsBetaBinomial'>, <class 'flamedisx.lxe_blocks.detection.DetectPhotons'>, <class 'flamedisx.lxe_blocks.double_pe.MakeS1Photoelectrons'>, <class 'flamedisx.lxe_blocks.final_signals.MakeS1'>, <class 'flamedisx.lxe_blocks.detection.DetectElectrons'>, <class 'flamedisx.lxe_blocks.final_signals.MakeS2'>)

Blocks the source is built from. simulate will be called from first to last, annotate from last to first.

no_step_dimensions: ty.Tuple[str] = ()

inner_dimensions excluded from variable stepping logic, i.e. for which the domain is always a single interval of integers

static p_electron(nq, *, er_pel_a=15, er_pel_b=- 27.7, er_pel_c=32.5, er_pel_e0=5.0)[source]

Fraction of ER quanta that become electrons Simplified form from Jelle’s thesis

class flamedisx.lxe_sources.NRSource(*args, **kwargs)[source]

Bases: flamedisx.block_source.BlockModelSource

energies = <tf.Tensor: shape=(100,), dtype=float32, numpy= array([  0.7      ,   2.2080808,   3.7161617,   5.224242 ,   6.732323 ,          8.240404 ,   9.748485 ,  11.256566 ,  12.764647 ,  14.272727 ,         15.780808 ,  17.28889  ,  18.79697  ,  20.305052 ,  21.813133 ,         23.321213 ,  24.829294 ,  26.337376 ,  27.845455 ,  29.353537 ,         30.861618 ,  32.369698 ,  33.87778  ,  35.38586  ,  36.89394  ,         38.402023 ,  39.910103 ,  41.418182 ,  42.926266 ,  44.434345 ,         45.942425 ,  47.45051  ,  48.958588 ,  50.466667 ,  51.97475  ,         53.48283  ,  54.99091  ,  56.498993 ,  58.007072 ,  59.515152 ,         61.023235 ,  62.531315 ,  64.03939  ,  65.54747  ,  67.05556  ,         68.56364  ,  70.07172  ,  71.579796 ,  73.087875 ,  74.595955 ,         76.10404  ,  77.61212  ,  79.1202   ,  80.62828  ,  82.13636  ,         83.64444  ,  85.15253  ,  86.66061  ,  88.168686 ,  89.676765 ,         91.184845 ,  92.692924 ,  94.20101  ,  95.70909  ,  97.21717  ,         98.72525  , 100.23333  , 101.74142  , 103.2495   , 104.757576 ,        106.265656 , 107.773735 , 109.281815 , 110.7899   , 112.29798  ,        113.80606  , 115.31414  , 116.82222  , 118.3303   , 119.83839  ,        121.346466 , 122.854546 , 124.362625 , 125.870705 , 127.378784 ,        128.88687  , 130.39494  , 131.90303  , 133.41112  , 134.91919  ,        136.42728  , 137.93535  , 139.44344  , 140.9515   , 142.4596   ,        143.96768  , 145.47575  , 146.98384  , 148.49191  , 150.       ],       dtype=float32)>
final_dimensions: ty.Tuple[str] = ('s1', 's2')

Names of final observable dimensions (e.g. s1, s2) for use in domain / cross-domain

initial_dimensions: tuple

Dimensions provided by the first block

model_blocks: tuple = (<class 'flamedisx.lxe_blocks.energy_spectrum.FixedShapeEnergySpectrum'>, <class 'flamedisx.lxe_blocks.quanta_generation.MakeNRQuanta'>, <class 'flamedisx.lxe_blocks.quanta_splitting.MakePhotonsElectronsBinomial'>, <class 'flamedisx.lxe_blocks.detection.DetectPhotons'>, <class 'flamedisx.lxe_blocks.double_pe.MakeS1Photoelectrons'>, <class 'flamedisx.lxe_blocks.final_signals.MakeS1'>, <class 'flamedisx.lxe_blocks.detection.DetectElectrons'>, <class 'flamedisx.lxe_blocks.final_signals.MakeS2'>)

Blocks the source is built from. simulate will be called from first to last, annotate from last to first.

no_step_dimensions: ty.Tuple[str] = ()

inner_dimensions excluded from variable stepping logic, i.e. for which the domain is always a single interval of integers

static p_electron(nq, *, alpha=1.28, zeta=0.045, beta=0.02457, gamma=0.0141, delta=0.062, drift_field=120)[source]

Fraction of detectable NR quanta that become electrons, slightly adjusted from Lenardo et al.’s global fit (https://arxiv.org/abs/1412.4417). Penning quenching is accounted in the photon detection efficiency.

rates_vs_energy = <tf.Tensor: shape=(100,), dtype=float32, numpy= array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],       dtype=float32)>
class flamedisx.lxe_sources.SpatialRateERSource(*args, **kwargs)[source]

Bases: flamedisx.lxe_sources.ERSource

initial_dimensions: tuple

Dimensions provided by the first block

model_blocks: tuple = (<class 'flamedisx.lxe_blocks.energy_spectrum.SpatialRateEnergySpectrum'>, <class 'flamedisx.lxe_blocks.quanta_generation.MakeERQuanta'>, <class 'flamedisx.lxe_blocks.quanta_splitting.MakePhotonsElectronsBetaBinomial'>, <class 'flamedisx.lxe_blocks.detection.DetectPhotons'>, <class 'flamedisx.lxe_blocks.double_pe.MakeS1Photoelectrons'>, <class 'flamedisx.lxe_blocks.final_signals.MakeS1'>, <class 'flamedisx.lxe_blocks.detection.DetectElectrons'>, <class 'flamedisx.lxe_blocks.final_signals.MakeS2'>)

Blocks the source is built from. simulate will be called from first to last, annotate from last to first.

class flamedisx.lxe_sources.SpatialRateNRSource(*args, **kwargs)[source]

Bases: flamedisx.lxe_sources.NRSource

initial_dimensions: tuple

Dimensions provided by the first block

model_blocks: tuple = (<class 'flamedisx.lxe_blocks.energy_spectrum.SpatialRateEnergySpectrum'>, <class 'flamedisx.lxe_blocks.quanta_generation.MakeNRQuanta'>, <class 'flamedisx.lxe_blocks.quanta_splitting.MakePhotonsElectronsBinomial'>, <class 'flamedisx.lxe_blocks.detection.DetectPhotons'>, <class 'flamedisx.lxe_blocks.double_pe.MakeS1Photoelectrons'>, <class 'flamedisx.lxe_blocks.final_signals.MakeS1'>, <class 'flamedisx.lxe_blocks.detection.DetectElectrons'>, <class 'flamedisx.lxe_blocks.final_signals.MakeS2'>)

Blocks the source is built from. simulate will be called from first to last, annotate from last to first.

class flamedisx.lxe_sources.WIMPSource(*args, **kwargs)[source]

Bases: flamedisx.lxe_sources.NRSource

initial_dimensions: tuple

Dimensions provided by the first block

model_blocks: tuple = (<class 'flamedisx.lxe_blocks.energy_spectrum.WIMPEnergySpectrum'>, <class 'flamedisx.lxe_blocks.quanta_generation.MakeNRQuanta'>, <class 'flamedisx.lxe_blocks.quanta_splitting.MakePhotonsElectronsBinomial'>, <class 'flamedisx.lxe_blocks.detection.DetectPhotons'>, <class 'flamedisx.lxe_blocks.double_pe.MakeS1Photoelectrons'>, <class 'flamedisx.lxe_blocks.final_signals.MakeS1'>, <class 'flamedisx.lxe_blocks.detection.DetectElectrons'>, <class 'flamedisx.lxe_blocks.final_signals.MakeS2'>)

Blocks the source is built from. simulate will be called from first to last, annotate from last to first.

flamedisx.source module

class flamedisx.source.ColumnSource(data=None, batch_size=10, max_sigma=None, max_dim_size=120, data_is_annotated=False, _skip_tf_init=False, _skip_bounds_computation=False, fit_params=None, progress=False, **params)[source]

Bases: flamedisx.source.Source

Source that expects precomputed differential rate in a column, and precomputed mu in an attribute

_differential_rate(data_tensor, ptensor)[source]
calculate_dimsizes_special()[source]
column = 'rename_me!'

Name of the data column containing the precomputed differential rate

estimate_mu(n_trials=None, **params)[source]

Return estimate of total expected number of events :param n_trials: Number of events to simulate for estimate

extra_needed_columns()[source]
mu = 42.0

Expected events for this source

mu_before_efficiencies(**params)[source]

Return mean expected number of events BEFORE efficiencies/response using data for the evaluation of the energy spectra

random_truth(n_events, fix_truth=None, **params)[source]

Draw random “deep truth” variables (energy, position)

class flamedisx.source.Source(data=None, batch_size=10, max_sigma=None, max_dim_size=120, data_is_annotated=False, _skip_tf_init=False, _skip_bounds_computation=False, fit_params=None, progress=False, **params)[source]

Bases: object

_annotate()[source]

Add columns needed in inference to self.data

_batch_data_tensor_shape()[source]
_calculate_dimsizes(max_dim_size)[source]
_check_data()[source]

Do any final checks on the self.data dataframe, before passing it on to the tensorflow layer.

_differential_rate(data_tensor, ptensor)[source]
_fetch(x, data_tensor=None)[source]

Return a tensor column from the original dataframe (self.data) :param x: column name :param data_tensor: Data tensor, columns as in self.column_index

_fetch_param(param, ptensor)[source]
static _overwrite_fixed_truths(data, fix_truth, n_events)[source]

Replaces all columns in data with fix_truth.

Careful: ensure mutual constraints are accounted for first! (e.g. fixing energy for a modulating WIMP has consequences for the time distribution.)

_populate_tensor_cache()[source]

Set self.data_tensor to a big tensor of shape: (n_batches, events_per_batch, n_columns_in_data_tensor)

_set_temporarily(data, **kwargs)[source]

Set data and/or defaults temporarily, without affecting the data tensor state

_simulate_response()[source]

Do a forward simulation of the detector response, using self.data

add_extra_columns(data)[source]

Add additional columns to data

Parameters

data – pandas DataFrame

annotate_data(data, **params)[source]

Add columns to data with inference information

array_columns: Tuple[str] = ()

Names of array-valued data columns

batched_differential_rate(progress=True, **params)[source]

Return numpy array with differential rate for all events.

bonus_dimensions: Tuple[str] = ()

Names of dimensions of hidden variables for which dimsize calculations are NOT done here (but in user-defined code) but for which we DO track _min and _dimsizes

cap_dimsizes(dim, cap)[source]
cross_domains(x, y, data_tensor)[source]

Return (x, y) two-tuple of (n_events, n_x, n_y) tensors containing possible integer values of x and y, respectively.

data: pandas.core.frame.DataFrame = None

The fully annotated event data

default_max_sigma = 3
differential_rate(data_tensor=None, autograph=True, **kwargs)[source]
domain(x, data_tensor=None)[source]

Return (n_events, n_x) matrix containing all possible integer values of x for each event.

If x is a final dimension (e.g. s1, s2), we return an (n_events, 1) tensor with observed values – NOT a (n_events,) array!

estimate_mu(n_trials=100000, **params)[source]

Return estimate of total expected number of events :param n_trials: Number of events to simulate for estimate

extra_needed_columns()[source]
final_dimensions: Tuple[str] = ()

Names of final observable dimensions (e.g. s1, s2) for use in domain / cross-domain

frozen_model_functions: Tuple[str] = ()

Model functions whose results should be evaluated once per event, then stored with the data. For example, non-tensorflow functions. Note these cannot have any fittable parameters.

gimme(fname, *, data_tensor=None, ptensor=None, bonus_arg=None, numpy_out=False)[source]

Evaluate the model function fname with all required arguments

Parameters
  • fname – Name of the model function to compute

  • bonus_arg – If fname takes a bonus argument, the data for it

  • numpy_out – If True, return (tuple of) numpy arrays, otherwise (tuple of) tensors.

  • data_tensor – Data tensor, columns as self.column_index If not given, use self.data (used in annotate)

  • ptensor – Parameter tensor, columns as self.param_id If not given, use defaults dictionary (used in annotate) Before using gimme, you must use set_data to populate the internal caches.

gimme_numpy(fname, bonus_arg=None)[source]

Evaluate the model function fname with all required arguments

Parameters
  • fname – Name of the model function to compute

  • bonus_arg – If fname takes a bonus argument, the data for it

  • numpy_out – If True, return (tuple of) numpy arrays, otherwise (tuple of) tensors.

  • data_tensor – Data tensor, columns as self.column_index If not given, use self.data (used in annotate)

  • ptensor – Parameter tensor, columns as self.param_id If not given, use defaults dictionary (used in annotate) Before using gimme, you must use set_data to populate the internal caches.

inner_dimensions: Tuple[str] = ()

Names of dimensions of hidden variables (e.g. produced electrons) for which domain computations and dimsize calculations are to be done

model_attributes = ()

Any additional source attributes that should be configurable.

model_functions: Tuple[str] = ()

Names of model functions

mu_before_efficiencies(**params)[source]

Return mean expected number of events BEFORE efficiencies/response using data for the evaluation of the energy spectra

mu_function(interpolation_method='star', n_trials=100000, progress=True, **param_specs)[source]

Return interpolator for number of expected events Parameters must be specified as kwarg=(start, stop, n_anchors)

n_batches = None

Number of event batches to use in differential rate computations

n_padding = None

Number of fake events that were padded to the final batch to make it match the batch size

no_step_dimensions: Tuple[str] = ()

inner_dimensions excluded from variable stepping logic, i.e. for which the domain is always a single interval of integers

print_config(format='table', column_widths=(40, 20), omit=())[source]

Print the defaults of all parameters (from Source.defaults), and of model functions that have been set to constants (from Source.f_dims)

Parameters
  • format – ‘table’ to print a fixed-width table, ‘config’ to print as a configuration file

  • column_widths – 2-tuple of column widths to use for table format

  • omit – settings to omit from printout. Useful for format=’config’, since some things (like arrays and tensors) cannot be evaluated from their string representation.

ptensor_from_kwargs(**kwargs)[source]
random_truth(n_events, fix_truth=None, **params)[source]

Draw random “deep truth” variables (energy, position)

scan_model_functions()[source]

Discover which functions need which arguments / dimensions Discover possible parameters. Returns f_dims, f_params and defaults.

set_data(data=None, data_is_annotated=False, _skip_tf_init=False, _skip_bounds_computation=False, **params)[source]
set_defaults(*, config=None, **params)[source]
simulate(n_events, fix_truth=None, full_annotate=False, **params)[source]

Simulate n events.

Will omit events lost due to selection/detection efficiencies

special_model_functions: Tuple[str] = ()

Names of model functions that take an additional first argument (‘bonus arg’). This must be a subset of model_functions.

trace_differential_rate()[source]

Compile the differential rate computation to a tensorflow graph

trace_difrate = True

Whether to trace (compile into a tensorflow graph) the differential rate computation

validate_fix_truth(fix_truth)[source]

Return checked fix truth, with extra derived variables if needed

flamedisx.utils module

flamedisx.utils.beta_binom_pmf(x, n, p_mean, p_sigma)[source]

Return probability mass function of beta-binomial distribution.

That is, give the probability of obtaining x successes in n trials, if the success probability p is drawn from a beta distribution with mean p_mean and standard deviation p_sigma.

flamedisx.utils.beta_params(mean, sigma, force_valid=True)[source]

Convert (p_mean, p_sigma) to (alpha, beta) params of beta distribution

Parameters

force_valid – If true, adjust values to give valid, stable, and unimodal beta distributions. See issues #36 and #83

flamedisx.utils.cart_to_pol(x, y)[source]
flamedisx.utils.exporter()[source]

Export utility modified from https://stackoverflow.com/a/41895194 Returns export decorator, __all__ list

flamedisx.utils.float_type()[source]
flamedisx.utils.index_lookup_dict(names, column_widths=None)[source]
Return dictionary mapping names to successive tensor indices

(tf.constant integers.)

Parameters

column_widths – dictionary mapping names to column width. For columns with width > 1, the result contains a tensor slice.

flamedisx.utils.int_type()[source]
flamedisx.utils.is_numpy_number(x)[source]
flamedisx.utils.j2000_to_event_time(dates)[source]

Convert a numpy array of j2000 timestamps to event_times which are ns unix timestamps. This is the reverse of wimprates.j2000

flamedisx.utils.load_config(config_files=None)[source]

Return dictionary of configuration options from (a) python file(s)

flamedisx.utils.lookup_axis1(x, indices, fill_value=0)[source]

Return values of x at indices along axis 1, returning fill_value for out-of-range indices.

flamedisx.utils.np_to_tf(x)[source]

Convert (list/tuple of) arrays x to tensorflow

flamedisx.utils.pol_to_cart(r, theta)[source]
flamedisx.utils.run_command(command)[source]

Run command and show its output in STDOUT

flamedisx.utils.safe_p(ps)[source]

Clip probabilities to be in [1e-5, 1 - 1e-5] NaNs are replaced by 1e-5.

flamedisx.utils.symmetrize_matrix(x)[source]
flamedisx.utils.tf_log10(x)[source]
flamedisx.utils.tf_to_np(x)[source]

Convert (list/tuple of) tensors x to numpy

flamedisx.utils.values_to_constants(kwargs)[source]

Return dictionary with python/numpy values replaced by tf.constant

flamedisx.utils.wilks_crit(confidence_level)[source]

Return critical value from Wilks’ theorem for upper limits

Module contents