    Class: madys.FitParams

    Class that contains the results of an analysis performed upon a SampleObject instance.
    Created when get_params() is executed upon a sample object.
    It can be accessed like a dictionary.

    Attributes:
        - age: numpy array. Final age estimates [Myr].
        - age_min: numpy array. Minimum age (given by the user or derived) [Myr].
        - age_max: numpy array. Maximum age (given by the user or derived) [Myr].
        - mass: numpy array. Final mass estimates [M_sun or M_jup].
        - mass_min: numpy array. Minimum mass estimates [M_sun or M_jup].
        - mass_max: numpy array. Maximum mass estimates [M_sun or M_jup].
        - ebv: numpy array. Adopted/computed E(B-V), one element per star [mag].
        - ebv_err: numpy array. Error on adopted/computed E(B-V), one element per star [mag].
        - chi2_min: numpy array. Reduced chi2 of best-fit solutions.
        - radius: numpy array. Final radius estimates [R_sun or R_jup]. Only returned if phys_param=True.
        - radius_min: numpy array. Minimum radius estimates [R_sun or R_jup]. Only returned if phys_param=True.
        - radius_max: numpy array. Maximum radius estimates [R_sun or R_jup]. Only returned if phys_param=True.
        - logg: numpy array. Final surface gravity estimates [log10([cm s-2])]. Only returned if phys_param=True.
        - logg_min: numpy array. Minimum surface gravity estimates [log10([cm s-2])]. Only returned if phys_param=True.
        - logg_max: numpy array. Maximum surface gravity estimates [log10([cm s-2])]. Only returned if phys_param=True.
        - logL: numpy array. Final luminosity estimates [log10([L_sun])]. Only returned if phys_param=True.
        - logL_min: numpy array. Minimum luminosity estimates [log10([L_sun])]. Only returned if phys_param=True.
        - logL_max: numpy array. Maximum luminosity estimates [log10([L_sun])]. Only returned if phys_param=True.
        - Teff: numpy array. Final effective temperature estimates [K]. Only returned if phys_param=True.
        - Teff_min: numpy array. Minimum effective temperature estimates [K]. Only returned if phys_param=True.
        - Teff_max: numpy array. Maximum effective temperature estimates [K]. Only returned if phys_param=True.
        - fit_status: numpy array. Flag for the outcome of the fitting process, one element per star.
            0 - Successful fit.
            1 - All magnitudes for the star have an error beyond the maximum allowed threshold: age and mass determinations was not possible.
            2 - All magnitudes for the star are more than 0.2 mag away from their best theoretical match. Check age and mass range of the theoretical grid, or change the model if the current one does not cover the expected age/mass range for this star.
            3 - No point with chi2<1000 was found for the star.
            4 - The third closest filter in the best-fit solution is more than 3 sigma away from its theoretical match, and the third closest magnitude to its theoretical match is more than 0.1 mag away.
            5 - Undefined error.
        - chi2_maps: list. Only present if save_maps=True in the parent analysis. Contains one 2D numpy array per star; matrix elements are reduced chi2 estimates for grid points, using nominal data.
        - weight_maps: list. Only present if save_maps=True in the parent analysis. Contains one 2D numpy array per star; matrix elements are the weight of grid points, as used to obtain the final family of solutions.
        - all_solutions: list. Contains a dictionary per star, with all possible solutions providing an accettable fit to data.
        - feh: float. [Fe/H] of the grid.
        - he: float. Helium content of the grid.
        - afe: float. Alpha enhancement [a/Fe] of the grid.
        - v_vcrit: float. Rotational velocity of the grid.
        - fspot: float. Fraction of stellar surface covered by star spots.
        - B: int. Whether magnetic fields are included (1) or not (0) in the grid.
        - sample_name: string. Only returned if verbose>0. Name of the sample file, without extension.
        - path: string. Only returned if verbose>0. Full path to the sample file, without extension.
        - objects: numpy array. Names of analyzed objects. Corresponds to self.Gaia_ID of the parent SampleObject instance.
        - original_IDs: numpy array. Original IDs of analyzed objects. Corresponds to self.ID of the parent SampleObject instance.
        - exec_command: numpy array. Each entry is the __repr__ of the IsochroneGrid object used within SampleObject.get_params.
        - fitting_mode: int. Fitting mode of the parent get_params process. It can be either:
            1: the age was set a priori to a single value, or the selected model_version only has one age; corresponding to case 2) for the keyword 'age_range' from SampleObject.get_params.
            2: the age was to be found within the specified interval; corresponding to case 1) or 3) for the keyword 'age_range' from SampleObject.get_params.
            3: the age was fixed, and age_min and age_max were used to compute errors; corresponding to case 4) for the keyword 'age_range' from SampleObject.get_params.
            4: the program was left completely free to explore the entire age range.
        - model_grid: numpy array. Each entry is the model_version used to fit the corresponding star with SampleObject.get_params.
        - is_true_fit: bool. Whether the instance comes directly from a fit, or if it's an average of different model estimates.
        - units: dict. Physical units of mass, radius and Teff.
        - input_parameters: dict. Input parameters used to initialize the parent SampleObject.get_params() process.
        - a triple of numpy arrays (value, value_min, value_max) for every additional quantity specified through the 'additional_columns' keyword in the parent SampleObject.get_params() process.

    Built-in methods:

    1) __getitem__
    FitParam instances can be indexed like pandas dataframes, i.e. with a numpy array/list/int or with a string containing the column name.
    In the former case, the sample is cut according to the selected indices.
    In the latter case, the corresponding key is returned.
    See documentation for additional details.

    2) __setitem__
    FitParam instances support item assignment.
    Check the documentation for additional details.

    3) __len__
    The len of a FitParams instance is equal to the number of objects in the original list.

    4) __repr__
    Verbose reproduction of the execution command ran by the user. If coming from an average of different
    FitParams instance, it lists all of them.

    5) __eq__
    Two FitParams instances are defined to be equal if their object list and their attributes 'objects' and 'exec_command' are equal.

    Methods (use help() to have more detailed info):

    1) empty_like
    Starting from an existing instance, creates an empty FitParams instance with a given dimension.

    2) to_file
    Saves the instance in a .csv file.

    3) to_table
    Turns the main attributes of a FitParams instance into columns of an astropy Table.

    4) pprint
    Enables fancy print of a FitParams instance.

    5) plot_maps
    Plots (reduced chi2 / weight) maps of one or more stars as a f(mass,age) color map.

    6) average_results
    Averages the results of two or more FitParams instances coming from the same list of objects.

    7) export_to_file
    Exports the instance to a .h5 file. Complementary to import_from_file(), which performs the opposite operation.

    8) import_from_file
    Alternative initializer for the class. It imports the instance from a .h5 file. Complementary to export_to_file(), which performs the opposite operation.


    Class: madys.CurveObject

    Class that turns a contrast/flux limit curve from a direct imaging survey into a mass limit curve.
    Check the documentation for additional details on general functioning, customizable settings and various examples.

    New in version v1.1.0.

    Input:
    - file: string, required. Full path to the .fits file containing the input curve;
    - file_type: string, required. It can be either:
        - 'contrast_separation', if a 1D curve(separation) with shape (n_points, 2) is provided; the first column is assumed to
          correspond to contrasts, the second one to separations;
        - 'contrast_map', if a 2D curve(x, y) is provided. A 3D map (lambda, x, y) is accepted too.
    - stellar_parameters: dict, required. A dictionary containing information for the star under consideration. The following keywords must be present:
        - 'parallax': float. Stellar parallax [mas];
        - 'parallax_error': float. Uncertainty on stellar parallax [mas];
        - 'app_mag': float. Apparent magnitude of the star in the 'band' band [mag];
        - 'app_mag_error': float. Uncertainty on 'app_mag' [mag];
        - 'band': string. Filter which the map refers to. It should be a valid filter name for MADYS;
        - 'age': float. Stellar age [Myr];
        - 'age_error': float. Uncertainty on stellar age [Myr].
        For extinction, two possibility exist. Either it is set explicitly through the following doublet of keywords:
        - 'ebv': float. E(B-V) reddening for the star [mag];
        - 'ebv_error': float. Uncertainty on E(B-V) [mag];
        or coordinates must be specified to allow the program to estimate E(B-V):
        - 'ra': float. Right ascension of the star [deg];
        - 'dec': float. Declination of the star [deg].
        - 'ext_map': string, optional. 3D extinction map used for the computation. Possible values: 'leike', 'stilism'. Default: 'leike'.
        In the latter case, the error on ebv is always set to 0.
    - data_unit: string, optional. Choose 'magnitude' if the map is expressed in magnitudes, 'flux' if in flux contrast. Default: 'flux'.
    - rescale_flux = float, optional. Renormalization constant the flux is to be multiplied by. Default: 1.

    Attributes:
    - file: string. Corresponding to input 'file'.
    - file_type: string. Corresponding to input 'file_type'.
    - stellar_parameters: dict. Corresponding to input 'stellar_parameters'.
    - data_unit: string. Corresponding to input 'data_unit'.
    - rescale_flux: float. Corresponding to input 'rescale_flux'.
    - contrasts: numpy array. Renormalized contrast curve (flux ratio).
    - contrasts_mag: numpy array. Renormalized contrast curve (magnitude contrast).
    - abs_phot: numpy array. Absolute magnitudes in the required filters.
    - abs_phot_err: numpy array. Uncertainties on absolute magnitudes in the required filters.
    - abs_phot: numpy array. Apparent magnitudes in the required filters.
    - abs_phot_err: numpy array. Uncertainties on apparent magnitudes in the required filters.
    - mag_limits: numpy array. Limit absolute magnitudes corresponding to input curve.
    - mag_limits_err: numpy array. Uncertainties on limit absolute magnitudes.
    - mag_limits_app: numpy array. Limit apparent magnitudes corresponding to input curve.
    - mag_limits_app_err: numpy array. Uncertainties on limit apparent magnitudes.
    - separations: numpy array. Input separations, if 'file_type'='contrast_separation'; zero-filled array otherwise.
    - band: string. Input stellar_parameters['band'].

    Built-in methods:

    1) __len__
    The len of a CurveObject instance is equal to the number of unique values of contrasts_mag (rounded to 2 digits).

    Methods (use help() to have more detailed info):

    1) compute_mass_limits
    Converts the magnitude limit map stored in a CurveObject instance into a mass limit map.

    2) collapse_2D_map_to_1D
    Collapses a 2D (x, y) / 3D (lambda, x, y) mass limit map into an azimuthally averaged 1D (sep) / 2D (lambda, sep) curve, respectively.


    This will be the class to retrieve correlated-k tables from the database.
    Right now this is in beta mode and is retrieving the direct heritage
    196 grid files.
    Parameters
    ----------
    ck_dir : str
        Directory of the pre-mixed correlated k table data. Check that you are pointing to a
        directory with the files "ascii_data" and "full_abunds".
    cont_dir : str
        This should be in the references directory on Github. This has all the continuum opacity
        that you need (e.g. H2H2). It also has some extra cross sections that you may want to add
        in like Karkoschka methane and the optical ozone band.
    wave_range : list
        NOT FUNCTIONAL YET.
        Wavelength range to compuate in the format [min micron, max micron]


    This will be the class that will retrieve the opacities from the sqlite3 database. Right
    now we are just employing nearest neighbors to grab the respective opacities.

    Parameters
    ----------
    db_filename : str
        Opacity file name
    raman_data : str
        file name of the raman cross section data
    wave_range : list of float
        Wavelength range (in microns) to run.
        Default None grabs all the full wavelength range available
    location : str
        Default = local. This is the only option currently available since
        we dont have AWS or other services enabled.
    resample : int
        Default =1 (no resampling)
    Attributes
    ----------
    raman_db : pandas.DataFrame
        Database of Raman cross sections
    wno : array
        Wavenumber grid from opacity database (CGS cm-1)
    wave : array
        Wavelength grid from opacity database (micron)
    nwno : int
        Number of wavenumber points in the grid
    cia_temps : array
        CIA temps available from database
    molecules : array
        Molecules availalbe from database
    pt_pairs : array
        pressure-temperature pairs available from grid (our grid is usually
        computed on a fixed 1060 PT grid)
    molecular_opa : dict
        Molecular Opacity dictionary that contains all the queried information necessary
        to do calculation
    continuum_opa : dict
        Continuum opacity dictionary that contains all the queried information
        necessary for the calculation
    rayleigh_opa : dict
        Rayleigh opacity dictionary for all the sources we have. This is computed as
        cm^2/species when the users runs `opannection`. We technically could just
        store this in the DB as well. However, because its so fast, it doesn't take
        a lot of time, and because its non-temperature dependent, we only have to do
        it once.
    Methods
    -------
    db_connect
        Inherents functionality of `open_local`. Eventually it will
        inherent functionality of "open_non_locals" (e.g. cloud or other sources)
    open_local
        Opens sqlite3 connection and enables array interpretation from bytes
    get_available_data
        Gets opacity database attributes such as available T-Ps , availalbe molecules. etc.
    get_available_rayleigh
        Gets rayleigh cross sections when opannection is opened.
    get_opacities
        Gets opacities after user specifies atmospheric profile (e.g. full PT and Composition)


    This will be the class to retrieve correlated-k tables from the database.
    Right now this is in beta mode and is retrieving the direct heritage
    196 grid files.

    Parameters
    ----------
    ck_dir : str
        Directory of the pre-mixed correlated k table data. Check that you are pointing to a
        directory with the files "ascii_data" and "full_abunds".
    cont_dir : str
        This should be in the references directory on Github. This has all the continuum opacity
        that you need (e.g. H2H2). It also has some extra cross sections that you may want to add
        in like Karkoschka methane and the optical ozone band.
    wave_range : list
        NOT FUNCTIONAL YET.
        Wavelength range to compuate in the format [min micron, max micron]


Lazy object attribute whose value is computed on first access.


Chemical element.

    Attributes
    ----------
    number : int
        Atomic number
    symbol : str of length 1 or 2
        Chemical symbol
    name : str
        Name in english
    group : int
        Group in periodic table
    period : int
        Period in periodic table
    block : int
        Block in periodic table
    series : int
        Index to chemical series
    protons : int
        Number of protons
    neutrons : int
        Number of neutrons in the most abundant naturally occurring stable
        isotope
    nominalmass : int
        Mass number of the most abundant naturally occurring stable isotope
    electrons : int
        Number of electrons
    mass : float
        Relative atomic mass. Ratio of the average mass of atoms
        of the element to 1/12 of the mass of an atom of 12C
    exactmass : float
        Relative atomic mass calculated from the isotopic composition
    eleneg : float
        Electronegativity (Pauling scale)
    covrad : float
        Covalent radius in Angstrom
    atmrad :
        Atomic radius in Angstrom
    vdwrad : float
        Van der Waals radius in Angstrom
    tboil : float
        Boiling temperature in K
    tmelt : float
        Melting temperature in K
    density : float
        Density at 295K in g/cm3 respectively g/L
    oxistates : str
        Oxidation states
    eleaffin : float
        Electron affinity in eV
    eleconfig : str
        Ground state electron configuration
    eleconfig_dict : dict
        Ground state electron configuration (shell, subshell): electrons
    eleshells : int
        Number of electrons per shell
    ionenergy : tuple
        Ionization energies in eV
    isotopes : dict
        Isotopic composition.
        keys: isotope mass number
        values: Isotope(relative atomic mass, abundance)


Isotope massnumber, relative atomic mass, and abundance.


Ordered dict of Elements with lookup by number, symbol, and name.


Class to setup planet to run

    Parameters
    ----------
    calculation: str
        (Optional) Controls planet or brown dwarf calculation. Default = 'planet'. Other option is "browndwarf".
    climate : bool
        (Optional) If true, this do a thorough iterative calculation to compute
        a temperature pressure profile.

    Attributes
    ----------
    phase_angle() : set phase angle
    gravity() : set gravity
    star() : set stellar spec
    atmosphere() : set atmosphere composition and PT
    clouds() : set cloud profile
    approx()  : set approximation
    spectrum() : create spectrum


    Reads in default source configuration from JSON and creates a full atmosphere class.

    - Gets PT profile
    - Computes mean molecular weight, density, column density, mixing ratios
    - Gets cloud profile
    - Gets stellar profile


    Top level grid fitter

    Currently our GridFitter has these requirements for xarray models:

    Required `coords`:
    - wavelength
    - pressure

    Required `data_vars`:
    - transit_depth

    Parameters
    ----------
    grid_name : str
        Grid name so that users can keep track of inputs

    model_dir : str
        Location of model grid. Should be a directory that points to
        several files in the PICASO xarray format.
        Only keep as None if user chooses 'init' as type
    model_type : str , ('xarrays','user')
        Default = xarray which points to a directly full of xarrays in picaso format
        Otherwise can input "user" which initializes the grid fitter without
        reading anything in. "user" gives users the flexibility to add
        in their own input
    to_fit : str
        parameter to fit, default is transit_depth. other common is flux


Class structure to get references from PICASO


Contains functionality to compute Rayleigh cross sections.

    This module is adapted from code
    provided by Ryan MacDonald (rmacdonald@astro.cornell.edu). It contains
    several hard coded values that were taken from the references shown in each method.

    Attributes
    ----------
    wno : array
        Wavenumber in inverse cm
    wavelength : array
        Wavelength array in microns
    n_ref : float
        Number density at reference conditions of refractive index measurements
        Number density (cm^-3) at 0 C and 1 atm (1.01325 bar)
        http://refractiveindex.info
    polarisabilities : dict
        Dictionary of polarisabilities for each molecule (CGS units, cm^3).
        Mostly taken from CRC handbook. If a molecule doesn't exist in this
        dictionary we are not including it in as a Rayleigh scatterer.
    king_correction_no_wave : dict
        King correction factor for depolarisation. Usually this is a wavelength
        dependent quantity. When we don't have the full wavelength dependent
        information, we use a mean value.
    rayleigh_molecules : list
        Essentially just `polarisabilities.keys()`. All species where we are
        specifically computing cross sections for. Everything else will
        return an artifficially small value for the cross section ~ 1e-40

    Methods
    -------
    compute_sigma
        Returns cross sections in CGS (cm2/molecule)
    CH4
        Returns polarisability and King correction factor
    CO2
        Returns polarisability and King correction factor
    H2
        Returns polarisability and King correction factor
    H2O
        Returns polarisability and King correction factor
    He
        Returns polarisability and King correction factor
    N2
        Returns polarisability and King correction factor
    N2O
        Returns polarisability and King correction factor
    NH3
        Returns polarisability and King correction factor
    O2
        Returns polarisability and King correction factor
    get_polarizability
    get_anisotropy
    get_Lorentz_Lorenz
    get_king_correction
    generic


        Extended list to contain list of coordinates.

        Requires an image list in case of pixel coordinates to work properly.

        Parameters
        ---------
        imagenames
            A list of image names, requiered for pixle coordinates to work properly.
        coord_type
            **'physical'** or **'pixel'**. **'physical'** coordinates should be converted to pixels using **LineStacker.getPixelCoords** before stacking.
        unit
            can be **'rad'**, **'deg'** or **'pix'**.


        Describes a stacking position on an image.

        Class used internally to represent coordinates. May describe a
        physical coordinate or a pixel coordinate.

        Init: Creates a coordinate. A pixel coordinate should always specify
        to which image it belongs. Physical coordinates should be in
        J2000 radians.

        Parameters
        ---------
        x
            x coordinate of stacking target
        y
            y coordinate of stacking target
        z
            redshift of stacking target
        obsSpecArg
            argument of spectral bin on which to center the stack, will be computed from **z** and **fEm** if not specified
        weight
            Weight of the. source in case of mean stacking.
            Default is 1.
        image
            Index of the image associated to the source.
            Automatically set with **LineStacker.readCoords**.


A (multi-)interval on the extended real set.

    An interval is an immutable object that is created by specifying
    the end-points of its connected components:

        >>> interval([0, 1], [2, 3], [10, 15])
        interval([0.0, 1.0], [2.0, 3.0], [10.0, 15.0])

    constructs an interval whose arbitrary element x must satisfy 0 <=
    x <= 1 or 2 <= x <= 3 or 10 <= x <= 15. Several shortcuts are
    available:

        >>> interval(1, [2, 3])
        interval([1.0], [2.0, 3.0])

        >>> interval[1, 2]
        interval([1.0, 2.0])

        >>> interval[1]
        interval([1.0])

    Intervals are closed with respect to all arithmetic operations,
    integer power, union, and intersection. Casting is provided for
    scalars in the real set.

        >>> (1 + interval[3, 4] / interval[-1, 2]) & interval[-5, 5]
        interval([-5.0, -2.0], [2.5, 5.0])


    Base class for all primary beam models.
    Can be instanciated to get a constant beam model,
    i.e., set to 1 for all coordinates.


Primary beam model based on dish diameter


Primary beam model based on casa image.


        Image class, each object is a spectrum to stack,
        containing all necessary information to be stacked
        they can consist simply of a the flux array,
        or flux and corresponding spectral values

        Parameters
        ---------
        coords
            A coordList object of all target coordinates.
        spectrum
            Spectrum should be of the shape [N,2] or [2,N],
            where N is the number of spectral bins.
            The second dimension being the flux
            and the first the spectral values.
        amp
            Instead of defining spectrum one can define only the amplitude (flux).
        velocities=[]
            In the case where amp is defined
            it is still possible to define the velocites
        frequencies=[]
            In the case where amp is defined
            it is still possible to define the frequencies
        z
            Redshift, one of the possible way to define central frequency.
            If using redshift **fEmLine** (emission frequency of the line) should be defined.
            In addition the Image spectra should consist of BOTH amplitudes and spectral information (frequencies or velocites), and not amplitude alone.
        fEmLine
            Emission frequency of the line, needed if redshift argument is used.
        centerIndex
            channel index of the line center, an other possible way to define line center.
        centralFrequency
            (observed) Frequency of the line center, an other possible way to define line center.
        centralVelocity
            Observed velocity of the line center, an other possible way to define line center.
        weights
            The weighting scheme to use.\n
            Can be set to **'1/A'** or **'sigma2'**.
            If **sigma2** is used std of the entire spectra is used UNLESS, **fit** is set to **True**, in which case the central part around the line is excluded from std calculation (central here means one FWHM on each side of the center of the line).\n
            Alternativelly user input can be used, float or list (or array)
        name
            name of the image, can allow easier identification
        fit
            If fit is set to **True**, the spectrum will be fitted with a gaussian to try and identify the line center (as well as amplitude if weight is set to 1/A)
        velOrFreq
            Defining if spectral dimension is velocity or frequency.


class to generate the tree

    Args:
        bounds: boundaries in bin coordinates
        spec_chunk: spectral reflectivity within this node
        noise_thres: noise threshold hat separated this peak
        prom_thres: prominence threshold in linear units
        root: flag indicating if root node
        parent_lvl: level of the parent node


trees for a time-height chunk

    Args:
        config_file (string, optional): path to the instrument config file (.toml)
        system (string, optional): specify the system/campaign

    The attribute setting may contain

    ==================== ========================================================
     Key                  Description
    ==================== ========================================================
    ``decoupling``        decoupling of the crosschannel
    ``smooth``            flag if smoothing should be applied
    ``grid_time``         time in seconds to average the spectra
    ``max_no_nodes``      number of nodes to save
    ``thres_factor_co``   factor between noise_lvl and noise thres in co channel
    ``thres_factor_cx``   factor between noise_lvl and noise thres in cross ch.
    ``station_altitude``  height of station above msl
    ==================== ========================================================


    A signal is constituted by some X-ray dataset, a model instrument
    with which that data was acquired, a model background, and an object for
    modelling interstellar processes.

    The methods in this class must transform incident specific flux signals
    into a structure congruent to that of the data for the purpose of
    evaluation of the custom likelihood implemented via subclassing.

    :param obj data:
        An instance of :class:`~.Data.Data`.

    :param obj instrument:
        An instance of :class:`~.Instrument.Instrument`.

    :param obj background:
        If not ``None``, an instance of :class:`~.Background.Background`.
        It is assumed if one constructs a model using instances of
        :class:`~.Background.Background` that the background needs to be
        registered by a model instrument. If ``None``, it is still possible
        for one to define and use background parameters in a custom subclass
        of :class:`~.Signal`. In particular, background parameters for some
        model which directly specifies background contribution in units of
        count/s per *output* channels. These background parameters can even
        *be* the counts/s in output channels.

    :param obj interstellar:
        If not ``None``, an instance of :class:`~.Interstellar.Interstellar`.
        To be applied to the incident signal as a callable that modifies the
        signal in place.

    :param str photosphere_prefix:
        The ``str`` prefix of the photosphere object with which this signal
        object is associated.

    :param bool cache:
        Cache intermediary signals during likelihood evalation? When performing
        post-processing, this needs to be activated for full functionality of
        the :mod:`~.xpsi.PostProcessing` module. For likelihood function
        evaluation during sampling, caching should be deactivated because it is
        not used. It might be useful to activate caching also when preparing a
        model for a sampling application, to check the likelihood function
        works as intended.

    :param bool store:
        Deprecated. You can use this or ``cache``, which has the same effect.

    :param str stokes:
        Define the type of the signal. Options are Stokes "I" (default), "Q",
        "U", "Qn" (Q/I), and "Un" (U/I).


r""" Base class for astronomical X-ray instruments on-board space telescopes.

    The body of the initialiser must not be changed to ensure inter-module
    compatibility, but can be extended if appropriate using a call to
    ``super().__init__``. Specialist constructors can be defined in a subclass
    using the ``@classmethod`` decorator.

    :param ndarray[p,q] matrix:
        A :math:`p \\times q` matrix which is the product of a redistribution
        matrix and effective area vector. The input energy intervals must
        increase along the columns of :attr:`matrix`, and the output channels
        must increase along the rows of :attr:`matrix`. The *units* of the
        elements must be that of an *effective* area (:math:`cm^2`). Generally
        there will be some available calibration product, and deviations from
        this nominal response model will be parametrised. So here load some
        nominal response matrix.

    :param ndarray[q+1] energy_edges:
        Energy edges in keV of the instrument energy intervals which must be
        congruent to the first dimension of the :attr:`matrix`: the number of
        edges must be :math:`q + 1`. The edges must be monotonically increasing.
        These edges will correspond to the nominal response matrix and any
        deviation from this matrix (see above).

    :param ndarray[p] channels:
        Instrument channel numbers which must be equal in number to the number
        of rows of the :attr:`matrix`. The number of channels must therefore be
        :math:`p`. These channels will correspond to the nominal response
        matrix and any deviation from this matrix (see above). In common usage
        patterns, the channel numbers will increase monotonically with row
        number, and usually increment by one (but this is not necessary).

    .. note::

        That these channel numbers are not used to index the loaded instrument
        (sub)matrix. The :attr:`xpsi.Data.index_range` property returns
        bounding row numbers that index the loaded instrument response
        (sub)matrix in order to operate on an incident signal flux. The
        channel array contained in :attr:`xpsi.Data.channels` must be a
        contiguous (ordered) subset of the channel array loaded here.

    .. note::

        The dimensions of the response matrix need not be equal, but it is
        required that the number of input intervals be greater than or equal to
        the number of output channels -- i.e., :math:`p \leq q`. If :math:`p <
        q` then it is implied that subsets of adjacent output channels are
        effectively grouped together.

    :param ndarray[p+1] channel_edges:
        The channel (energy) edges of the instrument, in keV. The array must
        be congruent to the zeroth dimension of the :attr:`matrix`: the number
        of edges must be :math:`p + 1`. The edges must be monotonically
        increasing. These edges will correspond to the nominal response matrix
        and any deviation from this matrix (see above).

    :param tuple args:
        Container of parameter instances.

    :param dict kwargs:
        If you want to prefix parameters of an instance of this instrument
        subspace with an identifier, pass it as keyword argument and it will
        find its way to the base class.


Instrument with pile-up computation


r""" The photospheric radiation field represented by a global mesh.

    An instance of this class *cannot* be used in conjuction with hot region
    objects nor with an elsewhere instance.

    The local comoving radiation field properties are *not* assumed to be
    azimuthally invariant, so a time-dependent signal can be generated upon
    integration over the image.

    However, if you want to generate a time-dependent signal, you need
    to customise the parameters that control the radiation field w.r.t. surface
    local comoving frames. By default a single temperature parameter is
    defined which is globally invariant and thus the radiation field is
    azimuthally invariant and the image subtended on a distant observer's sky
    is phase-invariant.

    :param bool time_invariant:
        See above. Is the radiation field azimuthally invariant, thus
        generating a phase-invariant signal? Although the default configuration
        is simple and azimuthally invariant, we do not provide a default
        value for this argument to force the user to verify their intentions.

    :param dict bounds:
        If ``custom is None``, these bounds are supplied for instantiation
        of a temperature parameter. The parameter name
        ``'temperature'`` must be a key in the dictionary unless the
        parameter is *fixed* or *derived*. If a bound is ``None`` that bound
        is set equal to a strict hard-coded bound. We note that the bounds for
        parameters used in the atmosphere model should be restricted (by the user)
        to be within the tabulated values, in case a numerical atmosphere extension is used.

    :param dict values:
        Either the fixed value of the temperature, a callable if the
        temperature is *derived*, or a value upon initialisation if the
        temperature is free. The dictionary must have a key with name
        ``'temperature'`` if it is *fixed* or *derived*.

    :param int sqrt_num_cells:
        Number of cells in both colatitude and azimuth which form a regular
        mesh on the surface. Must be an even number such that half of the cells
        are exactly in one hemisphere. The total number of cells is the square
        of this argument value. The mesh suffers from squeezing in the polar
        regions, leading to a high degree of non-congruence in cell shape over
        the surface.

    :param int num_rays:
        Number of rays to trace (integrate) at each colatitude, distributed
        in angle subtended between ray tangent 4-vector and radial outward unit
        vector w.r.t a local orthonormal tetrad.

    :param int num_leaves:
        Number of stellar rotation phases to rotate a moving mesh through
        during signal integration.

    :param int num_phases:
        Number of phases to resolve the signal at if the signal is time-
        dependent.

    :param ndarray[m]:
        Array of phases to resolve a time-dependent signal at.

    :param str atm_ext:
        Used to determine which atmospheric extension to use.
        Options at the moment:
        "BB": Analytical blackbody (default),
        "Num4D": Numerical atmosphere using 4D-interpolation from the provided
        atmosphere data,
        "user": A user-provided extension which can be set up by replacing the contents of
        the file hot_user.pyx (and elsewhere_user.pyx if needed) and re-installing X-PSI
        (if not changed, "user" is the same as "BB").

    :param int beam_opt:
        Used to determine which atmospheric beaming modification model to use.
        Options at the moment:
        0: No modification (default),
        1: Original*beaming_correction without re-normalization,
        2: Original*beaming_correction with analytical re-normalization estimate,
        3: Original*beaming_correction with numerical re-normalization.

    :param iterable custom:
        Iterable over :class:`~.Parameter.Parameter` instances. If you
        supply custom parameter definitions, you need to overwrite the
        :func:`~.Everywhere.Everwhere._compute_cellParamVecs` method to
        implement your custom behaviour.

    :param int image_order_limit:
        The highest-order image to sum over. A value of *one* means primary
        images only (deflections :math:`<\pi`) whilst a value of *two* means
        primary and secondary images (deflections :math:`<2pi`) where visible,
        and so on. If ``None`` (the default), there is no hard limit. In this
        case the limit is determined quasi-naturally for each mesh element,
        meaning that images will be summed over until higher order images are
        not visible or the visibility limit is truncated due to lack of
        numerical precision (e.g. for rays that orbit very close to the
        Schwarzschild photon sphere three times or more).  Higher-order images
        generally contribute less and less due to geometric projection effects
        (higher-order images become more tangential), and the images of
        elements get squeezed in solid angle at the stellar limb. In principle,
        effects such as relativistic beaming can counter this effect to a
        degree for certain source-receiver configurations, by increasing
        brightness whilst solid angle decreases, and thus the flux contribution
        relative to that from a primary image can be greater than suggested
        simply by geometric project effects. Nevertheless, inclusion of these
        images is more computationally expensive. If, when iterating through
        image orders, an image is not visible because the deflection required
        is greater than the highest deflection permitted at a given colatitude
        on a surface (accounting for the surface tilt due to rotation), then
        the iteration over image orders terminates.

    :param bool _integrator_toggle:
        For testing purposes, toggle the integrator for time-dependent signals.
        If left as the default (``False``) the general-purpose integrator is
        called. If toggled, an integrator is called that assumes the surface
        radiation field is azimuthally invariant, which combined with the
        default global mesh (i.e., no subclassing) results in a time-invariant
        signal.


 Derives from `emcee`_'s :class:`~emcee.EnsembleSampler`.

    .. _emcee: http://emcee.readthedocs.io/en/latest/

    :param callable posterior:
        The posterior function for MPI pickling.

    :param int ndims:
        Number of model parameters.

    :param bool resume:
        Resume a sampling run from file?

    :param int nwalkers:
        Number of ensemble walkers.

    :param nsteps:
        Number of iterations to perform.

    :param pool:
        Instance of :class:`schwimmbad.MPIPool`.

    :param str root_dir:
        Path to a directory containing a ``samples.h5`` to resume from;
        also the directory to be written to.

    :param list walker_dist_moments:
        Optional set of tuples of means and standard deviations.
        One per parameter.

    :param obj _posterior:
        Reserved for internal usage when invoking MPI.


A photosphere plotter to do all sorts of cool images.


Base class for model interstellar X-ray processes (e.g., attenuation).


 Extended MultiNest wrapper.

    :param int ndims: Number of parameters.

    :param likelihood: An instance of :class:`~.Likelihood.Likelihood`.

    :param prior: An instance of :class:`~.Prior.Prior`.

    :param kwargs: A dictionary of MultiNest runtime settings, to be
                   handled via the PyMultiNest wrapper.


A custom implementation of argparse.ArgumentParser for handling arguments specified in a configuration file.


 Class that generates a configuration file based on the arguments provided to argparse.

    The class inherits from argparse.Action and overrides the __init__ and __call__ methods to
    implement the configuration file generation.


 The ambient Schwarzschild spacetime and Earth coordinates.

    :param dict bounds:
        Tuples of hard bounds on parameters with keys matching the names
        in the initialiser body. A ``None`` bound will be interpreted as
        fixed variable, in which case a value must be supplied in the
        corresponding dictionary. If there is no entry for a default
        parameter, it will be assumed to be fixed, but an exception
        will be raised if there is no associated value.

    :param dict values:
        Values of fixed parameters or initial values for free parameters,
        with keys matching the names in the initialiser body. If there is
        no entry for a default parameter, no initial value will be specified,
        but an exception will be raised if there is also no bound specified.

    :param string star_shape:
        A string specifying the assumed shape of the star. Options 'AGM_14'
        (an oblate spheroid from Algendy & Morsink 2014) or 'sphere' are
        currently allowed.

    We define a property for parameters and combinations of parameters to
    shortcut access, given that this subspace is passed to other subspaces
    for model computation. We would like to access the values with fewer
    characters than ``self[<name>]``.


 Ordered parameter subspace.

    :param str prefix:
        In common modelling patterns there are multiple instances
        of a particular subspace, so provide a unique naming prefix. The prefix
        will be suffixed with a double-underscore. Note that this prefix will
        prepend prefixes for encapsulated parameters lower in the hierarchy
        which themselves have identification prefixes.

    :param args:
        Instances of :class:`~.Parameter.Parameter`, or iterables over
        instances of :class:`~.Parameter.Parameter` or
        :class:`~.ParameterSubspace.ParameterSubspace`. All parameters
        and subspaces will be merged into this new subspace.


 The joint prior distribution of parameters (including hyperparameters).

    Methods to both evaluate the distribution (required by MCMC) and
    draw uniformly from the distribution (required for nested sampling, and
    by default is used to initialise an ensemble of MCMC chains).

    The distribution must be integrable (proper) and is thus
    *usually* bounded (compactly supported on a space).

    In the ``__call__()`` method the parameter values are checked against the
    hard parameter bounds of the prior support.

    .. note::

        If you wish to check bounds manually, implement the ``__init__()`` and
        ``__call__()`` methods, and do not access the default code (e.g., via
        ``super()``) or only use the default code for some parameters.

    :param obj parameters:
        An optional instance of :class:`~.ParameterSubspace.ParameterSubspace`.

    :param obj hyperparameters:
        Positional arguments that are hyperparameters (parameters of the prior
        distribution), or iterables of hyperparameters.


r""" A container for event data.

    The working assumption is that the sampling distribution of this event data
    can be written in terms of a set of channel-by-channel *count*\ -rate
    signals. The instrument associated with this data in an instance of
    :class:`~.Signal.Signal` must transform incident signals into a structure
    congruent to that of the event data. The attributes and methods of this
    class and any derived classes must therefore store information required for
    this operation.

    The initialiser assigns observation settings to attributes which are
    required for the treating the incident specific flux signals using the
    model instrument. The body of the initialiser may be changed, but to ensure
    inter-module compatibility, only the phase handling should really be
    modified, for instance if you want to implement an unbinned likelihood
    function with respect to phase; the phase bins defined in this concrete
    implementation are only used by a custom implementation of the
    likelihood function (i.e., by a subclass of :class:`xpsi.Signal`), and
    not by the other concrete classes used to construct the likelihood
    callable. The initialiser can also be extended if appropriate using a call
    to ``super().__init__``. Specialist constructors can be defined in a
    subclass using the ``@classmethod`` decorator, for instance to load event
    data from disk into a compatible data structure in memory; an example of
    this may be found below.

    .. note::

        You can subclass in order to tailor the handling of the event data, for
        instance to implement a likelihood functions for unbinned event data.

    :param ndarray[n,m] counts:
        A :class:`~numpy.ndarray` of count numbers. The columns must map to
        the phase intervals given by :obj:`phases`. The rows of the array map
        to some subset of instrument channels.

    :param ndarray[n] channels:
        Instrument channel numbers which must be equal in number to the first
        dimension of the :attr:`matrix`: the number of channels must be
        :math:`p`. These channels will correspond to the nominal response
        matrix and any deviation from this matrix (see above). In common usage
        patterns, the channel numbers will increase monotonically with row
        number, and usually increment by one (but this is not necessary). It is
        advisable that these numbers are the actual instrument channel numbers
        so that plots generated by the post-processing module using these
        labels are clear.

    :param ndarray[m+1] phases:
        A :class:`~numpy.ndarray` of phase interval edges, where events are
        binned into these same intervals in each instrument channel.

    :param int first:
        The index of the first row of the loaded response matrix containing
        events (see note below).

    :param int last:
        The index of the last row of the loaded response matrix containing
        events (see note below).

    .. note::

        The :obj:`counts` matrix rows  *must* span a contiguous subset of the
        rows of the loaded response matrix, but in general can span an
        arbitrary subset and order of instrument channels. Note that the
        :obj:`first` and :obj:`last+1` numbers are used to index the loaded
        instrument response matrix.  Therefore, if you load only a submatrix of
        the full instrument response matrix, these indices must be appropriate
        for the loaded submatrix, and must not be the true channel numbers
        (this information is instead loaded in the :class:`xpsi.Instrument`).
        Of course, in all sensible usage patterns the order of the instrument
        channels, when mapped to matrix rows, will be such that channel number
        increases with matrix row number monotonically because, then the
        nominal event energy increases monotonically with row number, which is
        important for visualisation of data and model (because spatial order
        matches energy order and correlations in space can be discerned easily).
        However, there could in principle be channel cuts that mean an increment
        of more than one channel between matrix adjacent rows, and the
        response matrix needs to be manipulated before or during a custom
        loading phase such that its rows match the channel numbers assigned to
        the :obj:`counts` matrix rows.

    :param float exposure_time:
        The exposure time, in seconds, to acquire this set of event data.


 A container for all objects related to likelihood evaluation.

    A collective for objects pertaining to a statistical analysis of
    X-ray signals. These objects include X-ray data (sub)sets, the model
    instruments used to acquire these data sets, and the model star and
    model backgrounds.

    :param obj star:
        An instance of :class:`~.Star.Star`. This instance is the model star.

    :param list signals:
        Either:

            * a single :class:`~.Signal.Signal` instance
            * a list of :class:`~.Signal.Signal` instances
            * a list of lists of :class:`~.Signal.Signal` instances

    :param float num_energies:
        Number of energies to compute specific photon flux signals at for
        likelihood evaluation. These energies will be distributed linearly
        in logarithmic space within the union of waveband coverages
        achieved by some set of instruments. Gaps in waveband coverage will
        be skipped.

    :param float fast_rel_num_energies:
        Fraction of the normal number of energies to use in *fast* mode.

    :param int threads:
        The number of ``OpenMP`` threads to spawn for integration. The default
        number of threads used by low-level integration routines is ``1``. The
        number can be increased if the parallelisation paradigm on a cluster
        is changed such that, e.g., per node there is one thread per CPU,
        instead of one ``OpenMPI`` process. It is recommended that
        :obj:`threads` is ``1``; more threads are useful when performing
        integrals at high resolution, but not necessarily when integrating
        *many* times as when sampling, because the MPI parallelisation
        paradigm is invoked.

    :param float llzero:
        The minimum log-likelihood setting for MultiNest. Points whose
        log-likelihood is lower than this value are ignored, which is useful
        for defining complicated priors.

    :param bool externally_updated:
        Update the parameter values upon call to the likelihood object?
        If so, then pass ``False``. A parameter vector then needs to be passed
        to the likelihood object. Otherwise, safely assume that the
        new parameter values are set externally, e.g., in a prior object
        when inverse sampling the prior for nested sampling.

    :param obj prior:
        Instance of subclass of :class:`~.Prior.Prior`.

    :param float max_energy:
        Optional maximum of energy set for signal computation. If no maximum
        is requested (the default), then the maximum is equal to the maximum
        energy from the loaded instrument response models.


r""" The photospheric radiation field *elsewhere*.

    This means the radiation field exterior to the hot regions. The local
    comoving radiation field properties are *assumed* (for now) to be
    azimuthally invariant but can in principle vary colatitudinally.

    :param int sqrt_num_cells:
        Number of cells in both colatitude and azimuth which form a regular
        mesh on the surface. Must be an even number such that half of the cells
        are exactly in one hemisphere. The total number of cells is the square
        argument value. The mesh suffers from squeezing in the polar regions,
        leading to a high degree of non-congruence in cell shape over the
        surface.

    :param int num_rays:
        Number of rays to trace (integrate) at each colatitude, distributed
        in angle subtended between ray tangent 4-vector and radial outward unit
        vector w.r.t a local orthonormal tetrad.

    :param dict bounds:
        If ``custom is None``, these bounds are supplied for instantiation
        of a temperature parameter. The parameter name
        ``'elsewhere_temperature'`` must be a key in the dictionary unless the
        parameter is *fixed* or *derived*. If a bound is ``None`` that bound
        is set equal to a strict hard-coded bound. We note that the bounds for
        parameters used in the atmosphere model should be restricted (by the user)
        to be within the tabulated values, in case a numerical atmosphere extension is used.

    :param dict values:
        Either the fixed value of the temperature elsewhere, a callable if the
        temperature is *derived*, or a value upon initialisation if the
        temperature is free. The dictionary must have a key with name
        ``'elsewhere_temperature'`` if it is *fixed* or *derived*.

    :param str atm_ext:
        Used to determine which atmospheric extension to use.
        Options at the moment:
        "BB": Analytical blackbody (default),
        "Num4D": Numerical atmosphere using 4D-interpolation from the provided
        atmosphere data,
        "user": A user-provided extension which can be set up by replacing the contents of
        the file hot_user.pyx (and elsewhere_user.pyx if needed) and re-installing X-PSI
        (if not changed, "user" is the same as "BB").

    :param iterable custom:
        Iterable over :class:`~.Parameter.Parameter` instances. If you
        supply custom parameter definitions, you need to overwrite the
        :func:`~.Elsewhere.Elsewhere._compute_cellParamVecs` method to
        handle your custom behaviour.

    :param int image_order_limit:
        The highest-order image to sum over. A value of *one* means primary
        images only (deflections :math:`<\pi`) whilst a value of *two* means
        primary and secondary images (deflections :math:`<2pi`) where visible,
        and so on. If ``None`` (the default), there is no hard limit. In this
        case the limit is determined quasi-naturally for each mesh element,
        meaning that images will be summed over until higher order images are
        not visible or the visibility limit is truncated due to lack of
        numerical precision (e.g. for rays that orbit very close to the
        Schwarzschild photon sphere three times or more).  Higher-order images
        generally contribute less and less due to geometric projection effects
        (higher-order images become more tangential), and the images of
        elements get squeezed in solid angle at the stellar limb. In principle,
        effects such as relativistic beaming can counter this effect to a
        degree for certain source-receiver configurations, by increasing
        brightness whilst solid angle decreases, and thus the flux contribution
        relative to that from a primary image can be greater than suggested
        simply by geometric project effects. Nevertheless, inclusion of these
        images is more computationally expensive. If, when iterating through
        image orders, an image is not visible because the deflection required
        is greater than the highest deflection permitted at a given colatitude
        on a surface (accounting for the surface tilt due to rotation), then
        the iteration over image orders terminates.


Base class for astronomical photon X-ray background.


r""" A photospheric hot region that is contiguously radiating.

    Instances of this class can take the following forms:

        * a circular, simply-connected region;
        * a ceding region with a non-radiating superseding region;
        * a ceding region with a radiating superseding region.

    For the first option, set ``omit=False`` and ``cede=False``.
    For the third option, set ``omit=False`` and ``cede=True``.

    For the second option, set ``omit=True`` and ``cede=False``. Yes, this is
    counter-intuitive. These settings produce a superseding region with a
    non-radiating omission region, which is *equivalent* to a ceding region with
    a non-radiating superseding region. The *omission* region may not strictly
    always be a hole, because it behaves as a superseding region that does
    not radiate. A superseding region can exist partially outside its relative
    ceding region, so the non-superseded subset of the ceding region is
    then simply-connected (i.e., does not have a hole).

    .. note::

        Setting ``omit=True`` and ``cede=True`` ignores the omission setting.

    The ``concentric`` setting defines whether the superseding region is
    concentric with the ceding region or a omission region, supposing either
    ``omit=True`` or ``cede=True``.

    These helper settings simply set up the *optional* parameter definitions
    so you do not have to do so more manually by providing keys-value pairs
    in the ``bounds`` and ``values`` dictionaries (see below).

    :param dict bounds:
        Hard prior parameter bounds for the free parameters. The dictionary
        keys must match the required parameter names, at least. If a required
        name is omitted as a key, the parameter is interpreted as *fixed* or
        *derived*. A key-value pair can take the following forms:

            * ``'name': None``
            * ``'name': (None, None)``, ``(None, x)``, ``(x, None)``
            * ``'name': (x, y)``

        where if a bound is ``None`` that bound is set equal to a strict
        hard-coded bound. We note that the bounds for parameters used in the
        atmosphere model should be restricted (by the user) to be within the
        tabulated values, in case a numerical atmosphere extension is used.

    :param dict values:
        Initial values of *free* parameters, fixed values of *fixed* parameters,
        and callables for *derived* parameters. If a key is omitted for a free
        parameter, the initial value is ``None`` by default. A key cannot be
        omitted for a required name that appears in the ``bounds`` dictionary
        with value ``None``, or a required name that is omitted from the bounds
        dictionary.

    :param bool split:
        If True, a ``CellMesh`` integrator compatible with 3+2 dimensional atmosphere
        interpolation is deployed. This option is currently only effective if
        setting symmetry=True. When used, it also ignores the atmosphere choices
        made using the atm_ext and beam_opt arguments.

    :param bool symmetry:
        Is the radiation field axisymmetric (w.r.t the stellar rotation
        axis) within superseding (and ceding) member regions? This determines
        which ``CellMesh`` integrator to deploy based on this safety check.

    :param int sqrt_num_cells:
        Number of cells in both colatitude and azimuth which form a regular
        mesh over a subset of the surface spanning a hot region. This is the
        square-root of the approximate number of cells whose centres should
        lie within a hot region. The total number of cells is approximately
        the square of this argument value. The mesh suffers from squeezing in
        the polar regions, leading to a high degree of non-congruence in cell
        shape for meshes that extend from a polar region to the equatorial
        region.

    :param min_sqrt_num_cells:
        Sets the minimum number of cells per *subregion*, discretised to
        the same degree in colatitude and azimuth. This setting has an
        effect only when the hot region has two temperature components, in
        the form of a superseding region and a ceding region.

    :param max_sqrt_num_cells:
        Sets the maximum number of cells per *subregion*, discretised to
        the same degree in colatitude and azimuth. This setting has an
        effect even when there is only one temperature component.

    :param num_rays:
        Number of rays to trace (integrate) at each colatitude,
        distributed in angle subtended between ray tangent
        4-vector and radial outward unit vector w.r.t a local
        orthonormal tetrad.

    :param int num_leaves:
        Number of leaves mesh motion is discretised into.

    :param int num_phases:
        Number of phases in a discrete representation of the specific flux
        pulses on the interval :math:`[0,1]`.

    :param phases:
        If not ``None``, a :class:`numpy.ndarray` of phases
        for a discrete representation of the specific flux
        pulses on the interval :math:`[0,1]`. If ``None``
        (default), the :obj:`num_phases` argument is utilised.

    :param bool do_fast:
        Activate fast precomputation to guide cell distribution between
        two radiating regions at distinct temperatures.

    .. note:: For each of the resolution parameters listed above, there is
              a corresponding parameter whose value is respected if the
              fast precomputation mode is activated.

    :param bool is_antiphased:
        If ``True``, shifts the cell mesh by :math:`\pi` radians about
        the stellar rotation axis for pulse integration. This is merely
        a choice that can be made, and is not crucial. Note that the
        (fast) phase-shifting applied near the end of the likelihood
        evaluation is related to this choice and thus phase-shift parameter
        prior support can be chosen accordingly. If ``False``, the hot region
        at phase zero is aligned with the observer meridian. If ``True``, the
        hot region at phase zero is aligned with the meridian on which
        the observer's antipode lies. Alignment also depends on the structure
        of the hot region. As a rule, if the hot region has a superseding
        region (``super`` region or an ``omit`` region) then the centre
        of that region is the point that is *aligned* to a meridian.

    .. note::

        The parameters are as follows:

            + super colatitude
            + super angular radius
            + cede *or* omit colatitude
            + cede *or* omit angular radius
            + cede *or* omit relative azimuth
            + parameters controlling the local comoving radiation field over
              the photospheric 2-surface (entirely the user's responsibility
              unless defaulting with ``custom is None``.

        If the ceding region or the omission region are concentric with the
        superseding region, the colatitude and relative azimuth of the
        ceding region or omission region are not parameters.

        These bounds might not be actually used, depending the user's
        implementation of the joint prior, and the user can in that case
        specify ``(None,None)`` for bounds pertaining to the ceding region
        or the omission region. These bounds will be set to strict bounds,
        and the user can implement more complicated prior support boundaries
        in a :class:`~.Prior.Prior` subclass instance.

    :param str atm_ext:
        Used to determine which atmospheric extension to use.
        Options at the moment:
        "BB": Analytical blackbody (default),
        "Num4D": Numerical atmosphere using 4D-interpolation from the provided
        atmosphere data,
        "Pol_BB_burst": Polarized analytical blackbody+burst approximation,
        "Pol_Num2D": Polarized numerical atmosphere using 2D-interpolation from the provided
        atmosphere data,
        "user": A user-provided extension which can be set up by replacing the contents of
        the file hot_user.pyx (and elsewhere_user.pyx if needed) and re-installing X-PSI
        (if not changed, "user" is the same as "BB").

    :param int beam_opt:
        Used to determine which atmospheric beaming modification model to use.
        Options at the moment:
        0: No modification (default),
        1: Original*beaming_correction without re-normalization,
        2: Original*beaming_correction with analytical re-normalization estimate,
        3: Original*beaming_correction with numerical re-normalization.

    :param iterable custom:
        Iterable over :class:`~.Parameter.Parameter` instances. If you
        supply custom parameter definitions, you need to overwrite the
        :func:`~.HotRegion.HotRegion.__compute_cellParamVecs` method to
        handle your custom behaviour. This custom behaviour can only
        target the radiation field within the hot regions as defined
        above.

    :param int image_order_limit:
        The highest-order image to sum over. A value of *one* means primary
        images only (deflections :math:`<\pi`) whilst a value of *two* means
        primary and secondary images (deflections :math:`<2pi`) where visible,
        and so on. If ``None`` (the default), there is no hard limit. In this
        case the limit is determined quasi-naturally for each mesh element,
        meaning that images will be summed over until higher order images are
        not visible or the visibility limit is truncated due to lack of
        numerical precision (e.g. for rays that orbit very close to the
        Schwarzschild photon sphere three times or more).  Higher-order images
        generally contribute less and less due to geometric projection effects
        (higher-order images become more tangential), and the images of
        elements get squeezed in solid angle at the stellar limb. In principle,
        effects such as relativistic beaming can counter this effect to a
        degree for certain source-receiver configurations, by increasing
        brightness whilst solid angle decreases, and thus the flux contribution
        relative to that from a primary image can be greater than suggested
        simply by geometric project effects. Nevertheless, inclusion of these
        images is more computationally expensive. If, when iterating through
        image orders, an image is not visible because the deflection required
        is greater than the highest deflection permitted at a given colatitude
        on a surface (accounting for the surface tilt due to rotation), then
        the iteration over image orders terminates.


 Helper class to bind to parameter instances as a method.

    This is a powerful abstract base class for customisting how derived
    parameters are evaluated from references to existing parameter objects.

    :param obj refs:
        Some references to parameter objects or subspace objects that
        need to be stored for deriving variable values. For example,
        a dictionary with key-ref pairs.

    .. note::

        In principle, it might be the case that the calling parameter
        subspace does not have references to other parameter objects
        required, *and* that distinct subspaces require mutual references
        to each other. An example would be two hot regions, each of which
        has one or more parameters that are derived in part from parameters
        of the other hot region. In this case you need to instantiate
        the subspaces first by binding instances of this present
        class to parameters. However, you then need to complete these instances
        of this present class (or more precisely instances of subclasses) with
        the required references. As an example, consider the following:

    .. highlight:: python
    .. code-block:: python

        bounds = dict(super_colatitude = (None, None),
                      super_radius = (None, None),
                      super_temperature = (None, None))

        class derive(xpsi.Derive):
            def __init__(self):
                pass

            def __call__(self, boundto, caller = None):
                # ref is a reference to another hot region object
                return self.ref['phase_shift'] - 0.5

        ref_1 = derive()

        # a simple circular, simply-connected spot
        primary = xpsi.HotRegion(bounds=bounds,
                                    values={'phase_shift': ref_1},
                                    symmetry=True,
                                    omit=False,
                                    cede=False,
                                    concentric=False,
                                    sqrt_num_cells=32,
                                    min_sqrt_num_cells=10,
                                    max_sqrt_num_cells=64,
                                    num_leaves=100,
                                    num_rays=200,
                                    do_fast=False,
                                    prefix='p')

        bounds = dict(omit_colatitude = (None, None),
                      super_radius = (None, None),
                      phase_shift = (None, None),
                      super_temperature = (None, None),
                      omit_radius = (None, None),
                      omit_azimuth = (None, None))

        class derive(xpsi.Derive):
            def __init__(self):
                pass

            def __call__(self, boundto, caller = None):
                return math.pi - self.ref['super_colatitude']

        ref_2 = derive()

        # overlap of an omission region and
        # and a radiating super region
        secondary = xpsi.HotRegion(bounds=bounds,
                                      values={'super_colatitude': ref_2},
                                      symmetry=True,
                                      omit=True,
                                      cede=False,
                                      concentric=False,
                                      sqrt_num_cells=32,
                                      min_sqrt_num_cells=10,
                                      max_sqrt_num_cells=100,
                                      num_leaves=100,
                                      num_rays=200,
                                      do_fast=False,
                                      is_antiphased=True,
                                      prefix='s')

        from xpsi import HotRegions

        hot = HotRegions((primary, secondary))

        # the crux: resolve the mutual refs
        ref_1.ref = secondary
        ref_2.ref = primary


 A parameter.

    :param str name:
        A unique parameter name for identification in attribute lookup.

    :param tuple strict_bounds:
        One 2-tuple of hard bounds per parameter. Can be unbounded
        *in principle*, but read the documentation for the
        :class:`~.Prior.Prior` class first.

    :param tuple bounds:
        One 2-tuple of hard bounds per parameter. Can be unbounded
        *in principle*, but read the documentation for the
        :class:`~.Prior.Prior` class first.

    :param bool permit_prepend:
        Allow encapsulating subspaces to prepend the parameter name with
        a prefix? Note that this gives permission recursively to all
        encapsulating subspaces higher in the hierarchy.

    :param bool is_hyperparameter:
        A boolean declaring whether the parameter is a hyperparameter.


 Instances of :class:`Star` represent model stars.

    Each model star is abstractly constructed from an ambient spacetime,
    :class:`Spacetime`, and a collection of photosphere objects which are each
    embedded in that ambient spacetime for disjoint intervals of coordinate
    time.

    :param obj spacetime: An instance of :class:`~.Spacetime.Spacetime`.

    :param list photospheres: Each element must be an instance of
                              :class:`~.Photosphere`.


 Wrapper for the UltraNest (https://johannesbuchner.github.io/UltraNest/) package (Buchner 2021).

    :param likelihood: An instance of :class:`~.Likelihood.Likelihood`.

    :param prior: An instance of :class:`~.Prior.Prior`.

    :param sampler_params: A dictionary of the keyword arguments passed to the instance of :class:`ultranest.ReactiveNestedSampler`.

    :param use_stepsampler: Boolean indicating if the step sampler is used. In this case the :class:`ultranest.stepsampler.SliceSampler` is used.

    :param stepsampler_params: A dictionary of the keyword arguments passed to the step sampler :class:`ultranest.stepsampler.SliceSampler`.


    Custom likelihood function for use with SBI.

    Modifies the `_driver` and `synthesise` methods from the base class
    to return `model_flux` that is the synthesised signal.


 Custom data container to enable synthesis.

    :param ndarray channels:
        Instrument channel numbers which must be equal in number to the first
        dimension of the count matrix.

    :param ndarray phases:
        Phases of the phase bins which must be equal in number to the second
        dimension of the count matrix.

    :param int first:
        First channel index number to include in the synthesised data.

    :param int last:
        Last channel index number to include in the synthesised data.


    Class that wraps the xpsi likelihood and prior into a SBI compatible interface.

    :param xpsi.Prior prior:
        xpsi.Prior instance.
    :param xpsi.Likelihood likelihood:
        xpsi.Likelihood instance.
    :param dict instr_kwargs:
        Instrument keyword arguments for the likelihood synthesise method.
    :param optional[bool] train_using_CNNs:
        Whether to use CNNs for training. Defaults to True.


Context manager for verbosity.


 A solution straight from Stack Overflow.

    Reference: questions/11195140/break-or-exit-out-of-with-statement


 A photosphere embedded in an ambient Schwarzschild spacetime.

    :param obj hot:
        An instance of :class:`~.HotRegion.HotRegion` (or a derived class).
        This objects represents the hot regions of the surface that in most
        use-cases will be assumed to contain radiating material that is hotter
        than that *elsewhere*.

    :param obj elsewhere:
        An instance of :class:`~.Elsewhere.Elsewhere` (or a derived class).

    :param obj everywhere:
        An instance of :class:`~.Everywhere.Everywhere` (or a derived class).

    .. note::

        You cannot specify the surface radiation field *everywhere* if you
        use hot regions (the latter usage may also include specification of
        the radiation field *elsewhere*).

    :param dict bounds:
        Bounds are supplied for instantiation of a frequency parameter.
        The parameter name ``'mode_frequency'`` must be a key in the
        dictionary unless the parameter is *fixed* or *derived*. If a bound
        is ``None`` that bound is set equal to a strict hard-coded bound.
        If ``None``, lock the coordinate rotation frequency of a mode of
        asymmetry in the photosphere to a fixed frequency, e.g., the stellar
        rotation frequency. If bounds are passed, the frequency is interpreted
        as a free parameter.

    :param dict values:
        Either the fixed value of the mode frequency, a callable if the
        frequency is *derived*, or a value upon initialisation if the
        frequency is free. The dictionary must have a key with name
        ``'mode_frequency'`` if it is *fixed* or *derived*.
        If the asymmetry is locked to the stellar spin, then you need to pass
        the spin frequency. If fixed but different to the spin frequency, this
        value needs to be passed instead. In the hot region base class this
        mode frequency is applied to normalise the ray lags instead of the
        stellar rotation frequency.

    :param boolean stokes:
        A Boolean that determines whether the signals for all the Stokes I, Q,
        and U parameters are calculated. If False, only Stokes I is calculated.

    :param iterable custom:
        A :class:`~.Parameter.Parameter` instance or iterable over such
        instances. Might be useful for calling image plane extensions and
        passing global variables, without having to instantiate
        surface-discretisation classes and without having to handle global
        variable values at compile time or from disk for runtime access.

    .. note::

        In basic modelling patterns the frequency is the spin frequency,
        and thus you only need to explicitly pass the spin as ``value`` whilst
        leaving ``bounds`` to default. If the spin frequency happens to be a
        free parameter (perhaps with informative prior information), then
        pass a callable instead that can be used to get the spin frequency
        dynamically when the derived mode frequency variable is called for.


 Two or more photospheric hot regions, where the hot regions are objects.

    The hot regions can be equal or different in parametrisation complexity.

    In principle you can construct multiple hot regions, but the computational
    expense scales ~linearly with number. Applications thus far have used two
    distinct hot regions with equal and unequal complexities.

    :param tuple hotregions:
        Iterable container of :class:`.HotRegion.HotRegion` instances.


 The (joint) posterior distribution.

    A callable instance is required by `emcee <http://dfm.io/emcee/current/>`_
    (but is not required for nested sampling).

    :param likelihood:
        An instance of :class:`~.Likelihood.Likelihood`.

    :param prior:
        An instance of :class:`~.Prior.Prior`.


    Two convolutional layers followed by one pooling layer and one fully connected layer.

    Args
    ----
    nchannels : int
        Number of energy bins.
    nphases : int
        Number of phase bins.
    out_channels : int, optional
        Number of channels in the first convolutional layer. Default is 16.
    kernel_size : int, optional
        Kernel size of the convolutional layers. Default is 3.
    pool_kernel_size : int, optional
        Kernel size of the pooling layer. Default is 2.
    pool_stride : int, optional
        Stride of the pooling layer. Default is 2.
    fc_out_features : int, optional
        Number of features in the output of the fully connected layer. Default is 10.

    Attributes
    ----------
    conv1 : torch.nn.LazyConv2d
        First convolutional layer.
    conv2 : torch.nn.LazyConv2d
        Second convolutional layer.
    pool : torch.nn.MaxPool2d
        Pooling layer.
    fc : torch.nn.LazyLinear
        Fully connected layer.


    Two convolutional layers followed by one pooling layer, followed by one convolutional layer,
    followed by one pooling layer, and one fully connected layer.

    Args
    ----
    nchannels : int
        Number of energy bins.
    nphases : int
        Number of phase bins.
    out_channels : int, optional
        Number of channels in the first convolutional layer. Default is 16.
    kernel_size : int, optional
        Kernel size of the convolutional layers. Default is 3.
    pool_kernel_size : int, optional
        Kernel size of the pooling layers. Default is 2.
    pool_stride : int, optional
        Stride of the pooling layers. Default is 2.
    fc_out_features : int, optional
        Number of features in the output of the fully connected layer. Default is 10.

    Attributes
    ----------
    conv1 : torch.nn.LazyConv2d
        First convolutional layer.
    conv2 : torch.nn.LazyConv2d
        Second convolutional layer.
    pool1 : torch.nn.MaxPool2d
        First pooling layer.
    conv3 : torch.nn.LazyConv2d
        Third convolutional layer.
    pool2 : torch.nn.MaxPool2d
        Second pooling layer.
    fc : torch.nn.LazyLinear
        Fully connected layer.


    A class that wraps a pre-trained `ResNet/ResNeXt model <https://pytorch.org/vision/stable/models.html#general-information-on-pre-trained-weights>`
    and unfreezes the last backbone and linear layers for fine-tuning.

    Args
    ----
    resnet_version (str): The version of ResNet/ResNeXt to use
        (one of 'resnet18', 'resnet34', 'resnet50',
        'resnet101', 'resnet152', 'resnext50',
        'resnext101', 'resnext101_64x4d').

    Attributes
    ----------
    resnet: The pre-trained ResNet/ResNeXt model
    fc: The linear layer at the end of the model


    Exit Exception for IPython.
    Exception temporarily redirects stderr to buffer.


 Base class for a signal plot.

    Interact with a single :class:`~xpsi.Signal.Signal` instance to plot
    signals.

    :param str fig_dir:
        Directory to write to.

    :param str root_filename:
        Prepended to filename automatically generated figure filename.

    :param str cmap:
         Colormap name from :mod:`matplotlib` to use for :mod:`fgivenx`
         contours. It is advisable to choose a colormap that is darker
         at lower values (in tails of conditional posterior distribution) and
         lighter at higher values (at higher densities in conditional posterior
         distribution).


Plot marginal posterior densities and estimators.


Information about parameters shared by runs for plotting.


 Post-process samples for inference and posterior checking.

    Base class that functions as a container for nested sampling run objects
    representing some set of posterior distributions that share some subset of
    parameters of interest that are to be plotted. The parameters can be
    shared in the sense that their relationship is the identity relation, or
    multiple physical objects in a population context each have an instance
    of a parameter type. An example of the former is the mass of a star, for
    which there are two or more distinct posterior distributions, due, e.g.:

        * to sequential inference conditional on independent data sets, where
          each posterior is an updated of the previous in the sequence;
        * inference conditional on independent data sets, where the different
          analyses invoked same [different] prior models and one simply wants
          to overlay the posteriors e.g., to gauge the synergy of different
          experiments [and argue the priors are weakly informative/
          diffuse in the context of the likelihood functions];
        * to analysis of a single data set but the effective existence of
          discrete hyperparameter resulting in posteriors conditional on
          the discrete label over population-level prior distributions that
          has not been marginalized over (i.e., the problem of choosing an
          appropriate the hierarchical prior model);
        * to competing models, where models can differ in the likelihood
          function, prior density, or both.

    An example of the latter is two more (neutron) stars, each with a mass;
    these masses collectively encode interesting population-level information.

    Subclasses will calculate inferences, usually in the form of approximate
    integrals over the posterior distribution. They will also provide tools
    for visualisation of posterior information and derived quantities, which
    is useful for basic posterior predictive checking.

    :param iterable posteriors:
        An iterable of instances of :class:`~.Runs`.


 Plot posterior-averaged channel-summed count-rate pulse profiles.

    The figure contains four panels which share phase as an x-axis:

        * the first (topmost) panel displays the posterior expectation of
          the specific photon flux signal from the source, jointly resolved in
          energy and phase;
        * the second panel displays the energy-integrated photon specific flux
          signal as function of phase for a subset of samples, optionally using
          :mod:`fgivenx`;
        * the third panel displays the posterior expectation of the count-rate
          signal as a function of channel and phase;
        * the last (bottommost) panel displays the channel-summed pulse as
          a function of phase for a subset of samples, optionally using
          :mod:`fgivenx`.

    The second and last panels aim to render the conditional posterior
    distribution of the associated signal as a function phase, ideally with
    contours to map out the conditional posterior mass. These panels have space
    to optionally display other elements such as: the posterior-expected total
    signal; the posterior-expected component signals; and the true total and
    component signals if the ground truth (the injected signal correpsonding
    to some model parameter vector) is known.

    The following example is from `Riley et al. 2019 <https://ui.adsabs.harvard.edu/abs/2019ApJ...887L..21R/abstract>`_:

    .. image:: _static/_pulseplot.png

    :param int num_phases:
        The number of phases to interpolate the pulse-profile signals at.

    :param str incident_cmap:
         Colormap name from :mod:`matplotlib` to use for the posterior-expected
         incident signal as a function of energy and phase (top panel).

    :param str registered_cmap:
         Colormap name from :mod:`matplotlib` to use for the posterior-expected
         registered signal as a function of channel and phase (third panel).

    :param bool show_components:
        If the :class:`~.Signal.Signal` instance has multiple components,
        display the posterior expectations of those components as a
        function of phase (second and last panels).

    :param dict expectation_line_kwargs:
        Keyword arguments for plotting the posterior-expected signal lines (in
        the second and last panels).

    :param bool use_fgivenx:
        Use :mod:`fgivenx` to plot conditional posterior contours in the
        second and last panels?

    :param dict incident_contour_kwargs:
        Keyword arguments for :mod:`fgivenx` incident signal contours (second
        panel) that will take precedence over the corresponding class
        attributes. (See the :class:`~.SignalPlot` class if you choose
        not to modify these attributes on this present subclass.)

    :param dict registered_contour_kwargs:
        Keyword arguments for :mod:`fgivenx` registered signal contours (last
        panel) that will take precedence over the corresponding class
        attributes. (See the :class:`~.SignalPlot` class if you choose
        not to modify these attributes on this present subclass.)

    :param plot_truth:
        Plot the ground truth (injected) signal, if known and available, in
        the second and last panels.

    :param truth_line_kwargs:
        Keyword arguments for plotting the ground truth signal lines (second
        and last panels).


 Container for nested sampling runs on a shared posterior.

    :param likelihood:
        The instance of :class:`~.Likelihood` used for sampling, or a clone of
        that instance. Defaults to ``None``. If multiple likelihood functions
        are associated with the runs due to discreteness in the model space,
        one can pass a dictionary with keys matching the IDs of the runs.


 Base class to record basic information about sampling runs.

    :param str ID:
        For identification of the object.

    :param list names:
        An ordered list of ``str`` parameter names. The ordering must match
        the parameter vector ordering defined in sample backend objects.

    :param dict bounds:
        A dictionary of one-dimensional *hard* parameter bounds. See
        :class:`getdist.mcsamples.MCSamples`; the keys must match the
        :obj:`names` list. For the purpose of density estimation plots these
        bounds can be viewing bounds.

    :param list labels:
        An ordered list of (LaTeX compatible) ``str`` literal parameter labels.

    :param str implementation:
        Sampling software applied to generate the samples. Known options are
        ``['multinest', 'polychord', 'emcee']``.

    :param dict kde_settings:
        Settings for instantiation of :class:`getdist.mcsamples.MCSamples`.

    :param dict truths:
        Optional dictionary of parameter truths, if *known*; if *unknown*
        leave as ``None``. The keys must be names which match those in
        :obj:`names`.


 Plot the count data, the posterior-expected count signal, residuals, clusters and their related distributions.

    The figure contains three upper panels which share phase as an x-axis:

        * the top panel displays the data count numbers in joint channel-phase
          intervals, identically split over two rotational phase cycles;
        * the center panel displays the posterior-expected count signal
          over joint channel-phase intervals;
        * the bottom panel displays the standardised residuals between the
          data and posterior-expected count signal over joint channel-phase
          intervals.

    If requested by plot_clusters, the figure also contains 2 lower panels
        * the first panel displays two figures: the one on the left shows the
          standardised residuals for which their absolute values overpass a chosen
          threshold, and the one on the right present the estimated cluster sizes from
          these residuals.
        * the second panel displays two figures: the one on the left is the residual distribution
          compared with an optimal gaussian one, and the one on the right shows a distribution of
          cluster sizes from residuals which have absolute values above the chosen threshold

    The following example is (improved) from `Riley et al. 2019 <https://ui.adsabs.harvard.edu/abs/2019ApJ...887L..21R/abstract>`_:

    .. image:: _static/_residualplot.png

    :param str data_cmap:
         Colormap name from :mod:`matplotlib` to use for the data count numbers
         over joint channel-phase intervals.

    :param str model_cmap:
         Colormap name from :mod:`matplotlib` to use for the posterior-expected
         count numbers over joint channel-phase intervals.

    :param str residual_cmap:
         Colormap name from :mod:`matplotlib` to use for the residuals between
         the data and posterior-expected count numbers over joint
         channel-phase intervals. A diverging colormap is recommended.


    Container for nested samples generated by a single run, and backends
    for analysis of the run.

    The other keyword arguments are generic properties passed to the parent
    class, such as the identification (ID) string of the run.

    :param str root:
        The root filename of the sample file collection.

    :param str base_dir:
        The directly containing the sample file collection.

    :param bool use_nestcheck:
        Invoke :mod:`nestcheck` for nested sampling error analysis?

    :param callable transform:
        A function to transform the parameter vector to another space.


 Plot posterior-averaged channel count-rate spectra.

    The figure contains three panels which share phase as an x-axis:

        * the top panel displays the specific photon flux signal
          from the source, resolved as a function of energy, optionally showing
          both unattenuated and attenuated incident spectra and optionally
          using :mod:`fgivenx`;
        * the center panel displays the posterior expectation of the count-rate
          signal as a function of channel and phase, optionally including an
          expected background signal;
        * the bottom panel displays the phase-integrated (averaged) count-rate
          spectum as a function of channel number, optionally including an
          expected background signal and optionally using :mod:`fgivenx`.

    The top and bottom panels aim to render the conditional posterior
    distribution of the associated signal as a function an energy (proxy)
    variable, ideally with contours to map out the conditional posterior mass.
    These panels have space to optionally display other elements such as:
    the posterior-expected total signal; the posterior-expected component
    signals; the true total and component signals if the ground truth (the
    injected signal correpsonding to some model parameter vector) is known;
    attenuated incident spectra; and the summation of posterior-expected
    total (component-summed) source count-rate signals with posterior-expected
    background count-rate signals.

    The following example is (improved) from `Riley et al. 2019 <https://ui.adsabs.harvard.edu/abs/2019ApJ...887L..21R/abstract>`_:

    .. image:: _static/_spectrumplot.png

    :param float rel_num_energies:
        The number of energies desired for interpolation as a fraction of the
        number of energies implemented for the original incident signal
        integration. The energy set will be appropriately spaced and bounded.

    :param int num_phases:
        The number of phases to interpolate the pulse-profile signals at for
        the center panel.

    :param str registered_cmap:
         Colormap name from :mod:`matplotlib` to use for the posterior-expected
         registered signal as a function of channel and phase (center panel).

    :param bool show_components:
        If the :class:`~.Signal.Signal` instance has multiple components (hot
        region signals), display the posterior expectations of those components
        as a function of energy (top panel) and channel (bottom panel).

    :param bool show_attenuated:
        If the source signal is attenuated by the interstellar absorption
        processes, display the posterior-expected attenuated incident specific
        photon flux spectra? This switch also instructs :mod:`fgivenx`, if
        enabled, to generate conditional posterior contours for the attenuated
        spectrum instead of the unattenuated spectrum (top panel). If
        :mod:`fgivenx` is not invoked, this switch instructs the plotting
        of sample-by-sample attenuated total (component-summed) spectra to
        delineate the distribution of conditional posterior mass (top panel).

    :param dict expectation_line_kwargs:
        Keyword arguments for plotting the posterior-expected signal lines (in
        the top and bottom panels).

    :param bool add_background:
        Add an posterior-expected background count-rate signal to the total
        (component-summed) expected source count-rate signals in the center
        and bottom panels?

    :param dict background_line_kwargs:
        Keyword arguments for plotting the posterior-expected spectrum in the
        bottom panel that includes the background signal.

    :param bool use_fgivenx:
        Use :mod:`fgivenx` to plot conditional posterior contours in the
        top and bottom panels?

    :param dict incident_contour_kwargs:
        Keyword arguments for :mod:`fgivenx` incident signal contours (top
        panel) that will take precedence over the corresponding class
        attributes. (See the :class:`~.SignalPlot` class if you choose
        not to modify these attributes on this present subclass.)

    :param dict registered_contour_kwargs:
        Keyword arguments for :mod:`fgivenx` registered signal contours (bottom
        panel) that will take precedence over the corresponding class
        attributes. (See the :class:`~.SignalPlot` class if you choose
        not to modify these attributes on this present subclass.)

    :param plot_truth:
        Plot the ground truth (injected) signal, if known and available, in
        the top and bottom panels.

    :param truth_line_kwargs:
        Keyword arguments for plotting the ground truth signal lines (top and
        bottom panels).

    :param comp_truth_line_kwargs:
        Keyword arguments for plotting the component ground truth signal lines
        (top and bottom panels).


 Plot conditional posterior distributions of thematic X-ray signals.

    Methods to plot the data and model for posterior checking.

    Plots are generated for each posterior selected using the associated
    likelihood object.

    For a given model, there may be multiple :class:`~xpsi.Signal.Signal`
    instances per likelihood object. If this is the case, you need to
    reduce the model down to only the objects needed for functioning of
    the :class:`~xpsi.Signal.Signal` object to be handled. To do this, simply
    remove supply to your likelihood object the references to this minimal
    set of objects. This minimises computation time and ensures explicit
    declaration of the signals to be plotted.

    .. note::

        If a model has multiple instruments, then the energy set for signal
        integration is calculated based on waveband coverage union.
        If instruments are omitted from the likelihood object in order
        to execute posterior signal plotting, the number of energies
        that span the waveband of the remaining instrument waveband should
        be set to match the number in the full model (with all instruments)
        if the likelihood factor for the remaining instrument is to be
        exactly the same.


 Plot the count data, the posterior-expected count signal, and residuals.

    The figure contain one panel :

        * histogram of the standardised residuals between the
          data and posterior-expected count signal over joint channel-phase
          intervals.

    The following example is (improved) from `Riley et al. 2019 <https://ui.adsabs.harvard.edu/abs/2019ApJ...887L..21R/abstract>`_:

    .. image:: _static/_1d_residualplot.png

    :param ... Todo


Base class for a sample container.


 Cache numerical model objects computed during likelihood evaluation.

    :param str filename:
        Filename of cache.

    :param str cache_dir:
        Directory to write cache to.

    :param bool read_only:
        Do not write to cache file?

    :param bool archive:
        If not read-only, then archive an existing cache file found at the
        same path?


A model of the NICER telescope response.


A photosphere extension to preload the numerical atmosphere NSX.


 A custom calculation of the logarithm of the likelihood.

    We extend the :class:`xpsi.Signal.Signal` class to make it callable.

    We overwrite the body of the __call__ method. The docstring for the
    abstract method is copied.


 A custom (joint) prior distribution.

    Source: Fictitious
    Model variant: ST-U
        Two single-temperature, simply-connected circular hot regions with
        unshared parameters.


Implement method for imaging.


    A custom calculation of the logarithm of the likelihood.
    We extend the :class:`~xpsi.Signal.Signal` class to make it callable.
    We overwrite the body of the __call__ method. The docstring for the
    abstract method is copied.


Custom implementation of HotRegion. Accreting Atmosphere model by
    Anna Bobrikova. The parameters are ordered I(E < mu < tau < tbb < te).

    E is energy.
    mu is cos of zenith angle.
    tau is the optical depth of the comptom slab.
    tbb is the black body temperature.
    te is temperature of the electron gas.


A photosphere extension to preload the numerical 5D accretion atmosphere.


A custom (joint) prior distribution.


The background injected to generate synthetic data.