API reference — satlas2 0.1.6 documentation

Toggle navigation sidebar
Toggle in-page Table of Contents

# API reference

## Subpackages

- satlas2.models package
  - Submodules
  - satlas2.models.hfsModel module
  - satlas2.models.models module
  - Module contents

## Submodules

## satlas2.core module

Implementation of the base Fitter, Source, Model and Parameter classes

class satlas2.core.Fitter

  Bases: `object`

  Main class for performing fits and organising data

  addSource(source: Source) → None

    Add a datasource to the Fitter structure

    Parameters

      source (Source) – Source to be added to the fitter

  createMetadataDataframe() → DataFrame

    Generates a dataframe containing the fitting information and statistics.

    Return type

      pd.DataFrame

  createResultDataframe() → DataFrame

    Generates a dataframe containing all information about the parameters after a fit.

    Return type

      pd.DataFrame

  evaluateOverWalk(filename: str, burnin: int = 0, x: ArrayLike = None, evals: int = 0) → Tuple[list, list]

    The parameters saved in the h5 file are evaluated in the models a specific number of times. From these evaluations, the 16, 50 and 84 percentiles (corresponding to the 1-sigma band) are calculated.

    Parameters

      - filename (str) – Filename of the random walk results.

      - burnin (int, optional) – Amount of steps to skip, by default 0

      - x (ArrayLike, optional) – Evaluation points for the model, defaults to the datapoints in Source

      - evals (int, optional) – Number of selected parameter values, defaults to using all values

    Returns

      A tuple with, as the first element, a list of arrays x-values for which the band has been evaluated. Each source contributes an array. The second element is a list of 2D arrays, one for each source. The first row is the sigma- boundary, the second row is the median value and the third row is the sigm+ boundary.

    Return type

      Tuple of lists

  fit(llh: bool = False, llh_method: str = 'gaussian', method: str = 'leastsq', mcmc_kwargs: dict = {}, sampler_kwargs: dict = {}, filename: Optional[str] = None, steps: int = 1000, nwalkers: int = 50, scale_covar: bool = True, iter_cb: Optional[callable] = None) → None

    Perform a fit of the models (added to the sources) to the data in the sources. Models in the same source are summed together, models in different sources can be linked through their parameters.

    Parameters

      - llh (bool, optional) – Selects if a chisquare (False) or likelihood fit is performed, by default False.

      - llh_method (str, optional) – Selects which likelihood calculation is used, by default ‘gaussian’.

      - method (str, optional) – Selects the method used by the `lmfit.minimizer()`, by default ‘leastsq’. Set to ‘emcee’ for random walk.

      - mcmc_kwargs (dict, optional) – Dictionary of keyword arguments to be supplied to the MCMC routine (see `emcee.EnsembleSampler.sample()`), by default {}

      - sampler_kwargs (dict, optional) – Dictionary of keyword arguments to be supplied to the `emcee.EnsembleSampler()` , by default {}

      - filename (str, optional) – Filename in which the random walk should be saved, by default None

      - steps (int, optional) – Number of steps the random walk should, by default 1000

      - nwalkers (int, optional) – Number of walkers to be used in the random walk, by default 50

      - scale_covar (bool, optional) – Scale the calculated uncertainties by the root of the reduced chisquare, by default True. Set to False when llh is True, since the reduced chisquare calculated in this case is not applicable.

  readWalk(filename: str, burnin: int = 0)

    Read and process the h5 file containing the results of a random walk. The parameter values and uncertainties are extracted from the walk.

    Parameters

      filename (str) – Filename of the random walk results.

  removeParamPrior(source: str, model: str, parameter_name: str) → None

    Removes a prior set on a parameter.

    Parameters

      - source (str) – Name of the datasource in which the parameter is present.

      - model (str) – Name of the model in which the parameter is present.

      - parameter_name (str) – Name of the parameter.

  reportFit(modelpars: Optional[Parameters] = None, show_correl: bool = False, min_correl: float = 0.1, sort_pars: Union[bool, callable] = False) → str

    Generate a report of the fitting results.

    The report contains the best-fit values for the parameters and their uncertainties and correlations.

    Parameters

      - modelpars (lmfit.Parameters, optional) – Known Model Parameters

      - show_correl (bool, optional) – Whether to show a list of sorted correlations, by default False

      - min_correl (float, optional) – Smallest correlation in absolute value to show, by default 0.1

      - sort_pars (bool or callable, optional) – Whether to show parameter names sorted in alphanumerical order. If False (default), then the parameters will be listed in the order they were added to the Parameters dictionary. If callable, then this (one argument) function is used to extract a comparison key from each list element.

    Returns

      Multi-line text of fit report.

    Return type

      str

  revertFit()

    Reverts the parameter values to the original values.

  setExpr(parameter_name: Union[list, str], parameter_expression: Union[list, str]) → None

    Set the expression to be used for the given parameters. The given parameter names should be the full description i.e. containing the source and model name.

    Note

    The priority order on expressions is

      1. Expressions given by `setExpr()`

      2. Sharing of parameters through `shareParams()`

      3. Sharing of parameters through `shareModelParams()`

    Parameters

      - parameter_name (list or str) – Either a single parameter name or a list of them.

      - parameter_expression (list or str) – The parameter expression to be associated with parameter_name.

  setParamPrior(source: str, model: str, parameter_name: str, value: float, uncertainty: float) → None

    Set a Gaussian prior on a parameter, mainly intended to represent literature values.

    Parameters

      - source (str) – Name of the datasource in which the parameter is present.

      - model (str) – Name of the model in which the parameter is present.

      - parameter_name (str) – Name of the parameter.

      - value (float) – Central value of the Gaussian

      - uncertainty (float) – Standard deviation associated with the value.

  shareModelParams(parameter_name: Union[list, str]) → None

    Add parameters to the list of shared parameters across all models with the same name.

    Note

    The priority order on expressions is

      1. Expressions given by `setExpr()`

      2. Sharing of parameters through `shareParams()`

      3. Sharing of parameters through `shareModelParams()`

    Parameters

      parameter_name (list or str) – List of parameters or single parameter name.

  shareParams(parameter_name: Union[list, str]) → None

    Add parameters to the list of shared parameters.

    Note

    The full parameter name should be given.

    Note

    The priority order on expressions is

      1. Expressions given by `setExpr()`

      2. Sharing of parameters through `shareParams()`

      3. Sharing of parameters through `shareModelParams()`

    Parameters

      parameter_name (list or str) – List of parameters or single parameter name.

class satlas2.core.Model(name: str, prefunc: Optional[callable] = None)

  Bases: `object`

  f(x) → float
  setTransform(func: callable)

    Set the transformation for the pre-evaluation.

    Parameters

      func (callable) –

class satlas2.core.Source(x: ArrayLike, y: ArrayLike, yerr: Union[ArrayLike, callable], name: str, xerr: ArrayLike = None)

  Bases: `object`

  addModel(model: Model)

    Add a model to the Source

    Parameters

      model (Model) – The Model to be added to the source. Multiple models give, as a result, the sum of the individual models

  evaluate(x: ArrayLike) → ArrayLike

    Evaluates all models in the given points and returns the sum.

    Parameters

      x (ArrayLike) – Points in which the models have to be evaluated

    Return type

      ArrayLike

  f() → ArrayLike

    Returns the sum of the evaluation of all models in the x-coordinates defined in the source.

    Return type

      ArrayLike

## satlas2.interface module

Implementation of the base HFSModel and SumModel classes, based on the syntax used in the original satlas

NOTE: THIS IS NOT FULLY BENCHMARKED/DEVELOPED SO BUGS MIGHT BE PRESENT, AND NOT ALL FUNCTIONALITIES OF THE ORIGINAL SATLAS ARE IMPLEMENTED

class satlas2.interface.HFSModel(I: float, J: ArrayLike[float, float], ABC: ArrayLike[float, float, float, float, float, float], centroid: float = 0, fwhm: ArrayLike[float, float] = [50.0, 50.0], scale: float = 1.0, background_params: ArrayLike = [0.001], shape: str = 'voigt', use_racah: bool = True, use_saturation: bool = False, saturation: float = 0.001, sidepeak_params: dict = {'N': None, 'Offset': 0, 'Poisson': 0}, crystalballparams=None, pseudovoigtparams=None, asymmetryparams=None, name: str = 'HFModel__')

  Bases: `object`

  Initializes a hyperfine spectrum Model with the given hyperfine parameters.

  Parameters

    - I (float) – Integer or half-integer value of the nuclear spin

    - J (ArrayLike) – A sequence of 2 spins, respectively the J value of the lower state and the J value of the higher state

    - ABC (ArrayLike) – A sequence of 2 A, 2 B and 2 C values, respectively for the lower and the higher state

    - centroid (float, optional) – The centroid of the spectrum, by default 0

    - fwhm (ArrayLike, length = 2, optional) – First element: The Gaussian FWHM of the Voigt profile, by default 50 Second element: The Lorentzian FWHM of the Voigt profile, by default 50

    - scale (float, optional) – The amplitude of the entire spectrum, by default 1.0

    - background_params (ArrayLike, optional) – The coefficients of the polynomial background, by default [0.001]

    - shape (str, optional) – Voigt only

    - use_racah (bool, optional) – Use individual amplitudes are setting the Racah intensities, by default True

    - use_saturation (bool, optional) – False only

    - saturation (float, optional) – No saturation

    - sidepeak_params (dict, optional) – keys:

    - N (int, optional) – Number of sidepeaks to be generated, by default None

    - Poisson (float, optional) – The poisson factor for the sidepeaks, by default 0

    - Offset (float, optional) – Offset in units of x for the sidepeak, by default 0

    - prefunc (callable, optional) – Transformation to be applied on the input before evaluation, by default None

  chisquare_fit(x: ArrayLike, y: ArrayLike, yerr: Union[ArrayLike, callable] = None, xerr: ArrayLike = None, func: callable = None, verbose: bool = False, hessian: bool = False, method: str = 'leastsq', show_correl: bool = True) → Tuple[bool, str]

    Perform a fit of this model to the data provided in this function.

    Parameters

      - x (ArrayLike) – x-values of the data points

      - y (ArrayLike) – y-values of the data-points

      - yerr (Union[ArrayLike, callable], optional) – 1-sigma error on the y-values, values or function to be used on f(x), by default None=sqrt(f(x))

      - xerr (ArrayLike, optional) – 1-sigma error on the x-values, by default None

      - func (callable, optional) – Not implemented

      - verbose (bool, optional) – Not implemented, by default False

      - hessian (bool, optional) – Not implemented, by default False

      - method (str, optional) – Selects the method used by the `lmfit.minimizer()`, by default ‘leastsq’

    Returns

      Returns a boolean indicating the success of the fit, and the message accompanying it.

    Return type

      Tuple[bool, str]

    Raises

      NotImplementedError – When the chosen options for func, verbose and Hessian result is not implemented.

  display_chisquare_fit(scaled: bool = True, **kwargs)

    Generate a report of the fitting results.

    The report contains the best-fit values for the parameters and their uncertainties and correlations.

    Parameters

      - scaled (bool, optional) – Whether the errors are scaled with reduced chisquared, by default True, and only True

      - show_correl (bool, optional) – Whether to show a list of sorted correlations, by default False

      - min_correl (float, optional) – Smallest correlation in absolute value to show, by default 0.1

    Returns

      Multi-line text of fit report.

    Return type

      str

  f(x: ArrayLike) → ArrayLike

    Calculate the response for an unshifted spectrum with background

    Parameters

      x (ArrayLike) –

    Return type

      ArrayLike

  fix_ratio(value, target='upper', parameter='A')
  get_result(selection: str = 'chisquare') → Tuple[list, list, list]

    Return the variable names, values and estimated error bars for the parameters as seperate lists.

    Parameters

      selection (string, optional) – Selects if the chisquare (‘chisquare’ or ‘any’) or MLE values are used. Defaults to ‘chisquare’, and chisquare only

    Returns

      names, values, uncertainties – Returns a 3-tuple of lists containing the names of the parameters, the values and the estimated uncertainties, scaled with the reduced chisquared.

    Return type

      tuple of lists

  get_result_dict(method: str = 'chisquare', scaled: bool = True) → dict

    Returns the fitted parameters in a dictionary of the form {name: [value, uncertainty]}.

    Parameters

      - method ({'chisquare', 'mle'}) – Selects which parameters have to be returned, by default ‘chisquare’, and only ‘chisquare’

      - scaled (boolean) – Selects if, in case of chisquare parameters, the uncertainty has to be scaled by sqrt(reduced_chisquare). Defaults to True, and only True

    Returns

      Dictionary of the form described above.

    Return type

      dict

  get_result_frame(method: str = 'chisquare', selected: bool = False, bounds: bool = False, vary: bool = False, scaled: bool = True) → DataFrame

    Returns the data from the fit in a pandas DataFrame.

    Parameters

      - method (str, optional) – Selects which fitresults have to be loaded. Can be ‘chisquare’ or ‘mle’. Defaults to ‘chisquare’, and only ‘chisquare’.

      - selected (list of strings, optional) – Selects the parameters that have any string in the list as a substring in their name. Set to None to select all parameters. Defaults to None, and only None.

      - bounds (boolean, optional) – Selects if the boundary also has to be given. Defaults to False, and onlyb False.

      - vary (boolean, optional) – Selects if only the parameters that have been varied have to be supplied. Defaults to False, and only False.

      - scaled (boolean, optional) – Sets the uncertainty scaling with the reduced chisquare value. Default to True, and only True

    Returns

      resultframe – Dateframe with MultiIndex, using the variable names as main column names and the two rows under for the value and the uncertainty

    Return type

      DataFrame

  set_expr(constraints: dict) → None

    Set the expression to be used for the given parameters. The constraint should be a dict with following structure:

    key: string

      Parameter to constrain

    value: ArrayLike, length = 2

      First element: Factor to multiply Second element: Parameter that the key should be constrained to. {‘Au’:[‘0.5’,’Al’]} results in Au = 0.5*Al

  set_variation(varyDict: dict) → None

    Sets the variation of the fitparameters as supplied in the dictionary.

    Parameters

      varyDict (dictionary) – A dictionary containing ‘key: True/False’ mappings with the parameter names as keys.

class satlas2.interface.SumModel(models: list, background_params: list, name: str = 'sum', source_name: str = 'source')

  Bases: `object`

  Initializes a hyperfine spectrum for the sum of multiple Models with the given models and a step background.

  Parameters

    - models (ArrayLike, with instances of HFSModel as elements) – The models that should be summed

    - background_params (Dict with keys: 'values' and 'bounds' and values ArrayLike) – The bounds where the background changes stepwise in key ‘bounds’ The background values between the bounds i.e. {‘values’: [2,5], ‘bounds’:[-10]} means a background of 2 from -inf to -10, and a background of 5 from -10 to +inf

    - name (string, optional) – Name of this summodel

    - source_name (string, optional) – Name of the DataSource instance (from satlas2)

  chisquare_fit(x: ArrayLike, y: ArrayLike, yerr: Union[ArrayLike, callable] = None, xerr: ArrayLike = None, func: callable = None, verbose: bool = False, hessian: bool = False, method: str = 'leastsq') → Tuple[bool, str]

    Perform a fit of this model to the data provided in this function.

    Parameters

      - x (ArrayLike) – x-values of the data points

      - y (ArrayLike) – y-values of the data-points

      - yerr (Union[ArrayLike, callable], optional) – 1-sigma error on the y-values, values or function to be used on f(x), by default None=sqrt(f(x))

      - xerr (ArrayLike, optional) – 1-sigma error on the x-values, by default None

      - func (callable, optional) – Not implemented

      - verbose (bool, optional) – Not implemented, by default False

      - hessian (bool, optional) – Not implemented, by default False

      - method (str, optional) – Selects the method used by the `lmfit.minimizer()`, by default ‘leastsq’

    Returns

      Returns a boolean indicating the success of the fit, and the message accompanying it.

    Return type

      Tuple[bool, str]

    Raises

      NotImplementedError – When the chosen options for func, verbose and Hessian result is not implemented.

  display_chisquare_fit(scaled: bool = True, **kwargs) → str

    Generate a report of the fitting results.

    The report contains the best-fit values for the parameters and their uncertainties and correlations.

    Parameters

      - scaled (bool, optional) – Whether the errors are scaled with reduced chisquared, by default True, and only True

      - show_correl (bool, optional) – Whether to show a list of sorted correlations, by default False

      - min_correl (float, optional) – Smallest correlation in absolute value to show, by default 0.1

    Returns

      Multi-line text of fit report.

    Return type

      str

  f(x: ArrayLike) → ArrayLike

    Calculate the response for a spectrum

    Parameters

      x (ArrayLike) –

    Return type

      ArrayLike

  get_result(selection: str = 'chisquare') → Tuple[list, list, list]

    Return the variable names, values and estimated error bars for the parameters as seperate lists.

    Parameters

      selection (string, optional) – Selects if the chisquare (‘chisquare’ or ‘any’) or MLE values are used. Defaults to ‘chisquare’, and chisquare only

    Returns

      names, values, uncertainties – Returns a 3-tuple of lists containing the names of the parameters. The first list each tuple element contains the names/values/uncertainties of the first model added to the summodel, etc. The last list in each tuple element contains the names/values/uncertainties for the step background The values and the estimated uncertainties are always scaled with the reduced chisquared.

    Return type

      tuple of lists

  get_result_dict(method: str = 'chisquare', scaled: bool = True) → dict

    Returns the fitted parameters in a dictionary of the form {name of model in summodel : {name: [value, uncertainty]}}. Background values are under key ‘bkg’ in dictionary.

    Parameters

      - method ({'chisquare', 'mle'}) – Selects which parameters have to be returned, by default ‘chisquare’, and only ‘chisquare’

      - scaled (boolean) – Selects if, in case of chisquare parameters, the uncertainty has to be scaled by sqrt(reduced_chisquare). Defaults to True, and only True

    Returns

      Dictionary of the form described above.

    Return type

      dict

  get_result_frame(method: str = 'chisquare', selected: bool = False, bounds: bool = False, vary: bool = False, scaled: bool = True) → DataFrame

    Returns the data from the fit in a pandas DataFrame.

    Parameters

      - method (str, optional) – Selects which fitresults have to be loaded. Can be ‘chisquare’ or ‘mle’. Defaults to ‘chisquare’, and only ‘chisquare’.

      - selected (list of strings, optional) – Selects the parameters that have any string in the list as a substring in their name. Set to None to select all parameters. Defaults to None, and only None.

      - bounds (boolean, optional) – Selects if the boundary also has to be given. Defaults to False, and onlyb False.

      - vary (boolean, optional) – Selects if only the parameters that have been varied have to be supplied. Defaults to False, and only False.

      - scaled (boolean, optional) – Sets the uncertainty scaling with the reduced chisquare value. Default to True, and only True

    Returns

      resultframe – Dateframe with MultiIndex, using the model name + variable names as main column names and the two rows under for the value and the uncertainty

    Return type

      DataFrame

  set_variation(varyDict: dict)

satlas2.interface.chisquare_fit(model: Union['HFSModel', 'SumModel'], x: ArrayLike, y: ArrayLike, yerr: Union[ArrayLike, callable], xerr: ArrayLike = None, method: str = 'leastsq')

  Perform a fit of the provided model to the data provided in this function.

  Parameters

    - model –

    - x (ArrayLike) – x-values of the data points

    - y (ArrayLike) – y-values of the data points

    - yerr (ArrayLike) – 1-sigma error on the y-values

    - xerr (ArrayLike, optional) – 1-sigma error on the x-values

    - method (str, optional) – Selects the method used by the `lmfit.minimizer()`, by default ‘leastsq’.

    - show_correl (bool, optional) – Show correlations between fitted parameters in fit message, by default True

  Return type

    Instance of Fitter

## satlas2.plotting module

Functions for the generation of plots related to the fitting results.

satlas2.plotting.generateChisquareMap(fitter, filter=None, method='chisquare', resolution_diag=15, resolution_map=15, fit_kws={}, source=False, model=True)

  Generates a correlation map for either the chisquare or the MLE method. On the diagonal, the chisquare or loglikelihood is drawn as a function of one fixed parameter. Refitting to the data each time gives the points on the line. A dashed line is drawn on these plots, with the intersection with the plots giving the correct confidence interval for the parameter. In solid lines, the interval estimated by the fitting routine is drawn. On the offdiagonal, two parameters are fixed and the model is again fitted to the data. The change in chisquare/loglikelihood is mapped to 1, 2 and 3 sigma contourmaps.

  Parameters

    - fitter (`Fitter`) – Fitter instance for which the chisquare map must be created.

    - filter (list of strings) – Only the parameters matching the names given in this list will be used to generate the maps.

    - resolution_diag (int) – Number of points for the line plot on each diagonal.

    - resolution_map (int) – Number of points along each dimension for the meshgrids.

    - fit_kws (dictionary) – Dictionary of keywords to pass on to the fitting routine.

    - npar (int) – Number of parameters for which simultaneous predictions need to be made. Influences the uncertainty estimates from the parabola.

satlas2.plotting.generateCorrelationPlot(filename, filter=None, bins=None, burnin=0, source=True, binreduction=1, bin2dreduction=1, model=True)

  Given the random walk data, creates a triangle plot: distribution of a single parameter on the diagonal axes, 2D contour plots with 1, 2 and 3 sigma contours on the off-diagonal. The 1-sigma limits based on the percentile method are also indicated, as well as added to the title.

  Parameters

    - filename (string) – Filename for the h5 file containing the data from the walk.

    - filter (list of str, optional) – If supplied, only this list of columns is used for the plot.

    - bins (int or list of int, optional) – If supplied, use this number of bins for the plotting.

  Returns

    Returns the MatPlotLib figure created.

  Return type

    figure

satlas2.plotting.generateWalkPlot(filename, filter=None, burnin=0, source=False, model=True)

  Given the random walk data, the random walk for the selected parameters is plotted.

  Parameters

    - filename (string) – Filename for the h5 file containing the data from the walk.

    - filter (list of str, optional) – If supplied, only this list of parameters is used for the plot.

  Returns

    Returns the MatPlotLib figure created.

  Return type

    figure