    Class that implements Einasto (1969a,b) profile:

        rho(R,z) = rho_s exp{ - d(n) [ (r/r_s)^(1/n) - 1 ] }

    in a cylindrical frame (R,phi,z), where

        r = sqrt(R^2 + z^2)
        r_s: scale radius, at which d ln rho(r) / d ln(r) = -2
        n: Einasto shape index, the inverse of which, alpha=1/n, is also
            called the Einasto shape parameter
        d(n): geometric constant which makes that r_s to be a
            characteristic radius. (We usually use d(n)=2n,
            which makes r_s = r_-2, i.e., the radius at which
            d ln rho(r) / d ln(r) = -2.)
        rho_s: density at r=r_s  (Since r_s=r_-2, rho_s is also denoted
            as rho_-2.)

    See Retana-Montenegro+2012 for details.

    Syntax:

        halo = Einasto(M,c,alpha,Delta=200.,Om=0.3,h=0.7)

    where

        M: halo mass [M_sun], where halo is defined as spherical
            overdensity of Delta times critical density (float)
        c: concentration (float)
        alpha: shape (float)
        Delta: multiples of the critical density of the Universe (float)
            (default 200.)
        z: redshift (float) (default 0.)

    Attributes:

        .Mh: halo mass [M_sun]
        .ch: halo concentration (halo radius / scale radius)
        .alphah: halo shape
        .Deltah: spherical overdensity wrt instantaneous critical density
        .z: redshift
        .rhoc: critical density [M_sun kpc^-3]
        .rhoh: halo's average density [M_sun kpc^-3]
        .rh: halo radius [kpc], within which density is Deltah times rhoc
        .rs: scale radius [kpc], at which log density slope is -2
        .nh: inverse of shape paramter (1 / alphah)
        .hh: scale length [kpc], defined as rs / (2/alphah)^(1/alphah)
        .rho0: halo's central density [M_sun kpc^-3]
        .xmax: dimensionless rmax, defined as (rmax/hh)^alphah
        .rmax: radius [kpc] at which maximum circular velocity is reached
        .Vmax: maximum circular velocity [kpc/Gyr]
        .Mtot: total mass [M_sun] of the Einasto profile integrated to
            infinity
        .s001: logarithmic density slope at 0.01 halo radius
        .rhalf: half-mass radius [kpc]

    Methods:

        .rho(R,z=0.): density [M_sun kpc^-3] at radius r = sqrt(R^2 + z^2)
        .M(R,z=0.): mass [M_sun] within radius r = sqrt(R^2 + z^2)
        .rhobar(R,z=0.): mean density [M_sun kpc^-3] within radius
            r=sqrt(R^2+z^2)
        .tdyn(R,z=0.): dyn. time [Gyr] within radius r = sqrt(R^2 + z^2)
        .Phi(R,z=0.): potential [(kpc/Gyr)^2] at radius r=sqrt(R^2+z^2)
        .fgrav(R,z): grav. acceleration [(kpc/Gyr)^2 kpc^-1] at (R,z)
        .Vcirc(R,z=0.): circular velocity [kpc/Gyr] at radius r
        .sigma(R,z=0.): velocity dispersion [kpc/Gyr] at radius r=R

    HISTORY: Arthur Fangzhou Jiang (2016-11-08, HUJI)
             Arthur Fangzhou Jiang (2019-09-10, HUJI)


    Class that implements Miyamoto & Nagai (1975) disk profile:

        Phi(R,z) = - G M / sqrt{ R^2 + [ a + sqrt(z^2+b^2) ]^2 }

    in a cylindrical frame (R,phi,z), where

        M: disk mass
        a: scalelength
        b: scaleheight.

    Syntax:

        disk = MN(M,a,b)

    where

        M: disk mass [M_sun] (float)
        a: scalelength [kpc] (float)
        b: scaleheight [kpc] (float)

    Attributes:

        .Md: disk mass [M_sun]
        .Mh: the same as .Md, but for the purpose of keeping the notation
            for "host" mass consistent with the other profile classes
        .a: disk scalelength [kpc]
        .b: disk scaleheight [kpc]
        .rhalf: half-mass radius [kpc]

    Methods:

        .rho(R,z=0.): density [M_sun kpc^-3] at (R,z)
        .M(R,z=0.): mass [M_sun] within radius r=sqrt(R^2+z^2),
            defined as M(r) = r Vcirc(r,z=0)^2 / G
        .rhobar(R,z=0.): mean density [M_sun kpc^-3] within radius
            r=sqrt(R^2+z^2)
        .tdyn(R,z=0.): dyn. time [Gyr] within radius r = sqrt(R^2 + z^2)
        .Phi(R,z=0.): potential [(kpc/Gyr)^2] at (R,z)
        .fgrav(R,z): grav. acceleration [(kpc/Gyr)^2 kpc^-1] at (R,z)
        .Vcirc(R,z=0.): circ. vel. [kpc/Gyr] at (R,z=0), defined as
            sqrt(R d Phi(R,z=0.)/ d R)
        .sigma(R,z=0.): velocity dispersion [kpc/Gyr] at (R,z)

    HISTORY: Arthur Fangzhou Jiang (2016-11-03, HUJI)
             Arthur Fangzhou Jiang (2019-08-27, UCSC)


    Class that implements the Hernquist (1990) profile:

        rho(r) = M / (2 pi a^3) / [x (1+x)^3], x = r/a

    in a cylindrical frame (R,phi,z), where

        M: total mass
        a: scale radius

    Syntax:

        baryon = Hernquist(M,a)

    where

        M: baryon mass [M_sun] (float)
        a: scalelength [kpc] (float)

    Attributes:

        .Mb: baryon mass [M_sun]
        .Mh: the same as .Md, but for the purpose of keeping the notation
            for "host" mass consistent with the other profile classes
        .a: scalelength [kpc]
        .r0: the same as .a
        .rho0: characteristic density, M/(2 pi a^3) [M_sun/kpc^3]
        .rhalf: half-mass radius [kpc]

    Methods:

        .rho(R,z=0.): density [M_sun kpc^-3] at (R,z)
        .M(R,z=0.): mass [M_sun] within radius r=sqrt(R^2+z^2),
            defined as M(r) = r Vcirc(r,z=0)^2 / G
        .rhobar(R,z=0.): mean density [M_sun kpc^-3] within radius
            r=sqrt(R^2+z^2)
        .tdyn(R,z=0.): dyn. time [Gyr] within radius r = sqrt(R^2 + z^2)
        .Phi(R,z=0.): potential [(kpc/Gyr)^2] at (R,z)
        .fgrav(R,z): grav. acceleration [(kpc/Gyr)^2 kpc^-1] at (R,z)
        .Vcirc(R,z=0.): circ. vel. [kpc/Gyr] at (R,z=0), defined as
            sqrt(R d Phi(R,z=0.)/ d R)
        .sigma(R,z=0.): velocity dispersion [kpc/Gyr] at (R,z)

    HISTORY: Arthur Fangzhou Jiang (2020-09-09, Caltech)


    Class that implements the exponential disk profile:

        Sigma(r) = Sigma_0 exp(-x), x = r/a

    in a cylindrical frame (R,phi,z), where

        M: total mass
        a: scale radius

    Syntax:

        disk = exp(M,a)

    where

        M: baryon mass [M_sun] (float)
        a: scale radius [kpc] (float)

    Attributes:

        .Md: baryon mass [M_sun]
        .Mb: the same as .Md
        .Mh: the same as .Md, but for the purpose of keeping the notation
            for "host" mass consistent with the other profile classes
        .a: scalelength [kpc]
        .Rd: the same as .a
        .Sigma0: central surface density, M/(2 pi a^2) [M_sun/kpc^2]
        .rhalf: half-mass radius [kpc]

    Methods:

        .Sigma(R,z=0.): surface density [M_sun kpc^-2] at (R,z)
        .M(R,z=0.): mass [M_sun] within radius r=sqrt(R^2+z^2),
            defined as M(r) = r Vcirc(r,z=0)^2 / G

    Note: incomplete, other methods and attributes to be added...

    HISTORY: Arthur Fangzhou Jiang (2020-09-09, Caltech)


Class that calculates and keeps coeval maps, one z at a time.


    User parameters for Zeus21.

    Calling the class without specifying any parameter will set them to their default values, but they can also be directly set when creating the class:

    >>> zeus21.User_Parameters(precisionboost=0.5)

    Parameters can also be changed afterwards:
    >>> UserParams = zeus21.User_Parameters()
    >>> UserParams.precisionboost = 0.5

    Parameters
    ----------
    precisionboost: float
        Make integrals take more points for boost in precision, the baseline being 1.0.
    FLAG_FORCE_LINEAR_CF: int (0 or 1)
        0 to do standard calculation, 1 to force linearization of correlation function.
    MIN_R_NONLINEAR: float
        Minimum radius R/cMpc in which we start doing the nonlinear calculation.
        Below ~1 it will blow up because sigma > 1 eventually, and our exp(\delta) approximation breaks.
        Check if you play with it and if you change Window().
    MAX_R_NONLINEAR: float
        Maximum radius R/cMpc in which we start doing the nonlinear calculation (above this it is very linear)
    FLAG_DO_DENS_NL: bool
        Whether to do the nonlinear (ie lognormal) calculation for the density field itself and its cross correlations.
        Small (<3%) correction in dd, but non trivial (~10%) in d-xa and d-Tx
    FLAG_WF_ITERATIVE: bool
        Whether to iteratively do the WF correction as in Hirata2006.

    Attributes
    ----------
    C2_RENORMALIZATION_FLAG: int (0 or 1)
        Whether to renormalize the C2 oefficients (appendix in 2302.08506).


Class to pass the 6 LCDM parameters as input


Class that will keep the cosmo parameters throughout


Class to pass the astro parameters as input


Class that builds an interpolator of the HMF. Returns an interpolator


Class that calculates and keeps the correlation functions.


Get power spetrum from correlation functions and coefficients


Class containing the X-ray functions that we want to pass to main calculation


Test how command lines work.

    Usually considered bad practice, but in this
    case I need to test the full run of the codes, and files depend on each
    other.
    Inspired by https://stackoverflow.com/questions/5387299/python-unittest-testcase-execution-order

    When command line is missing, uses some function calls


Real unit tests.


    Base class for a composite material.
    The static phases can be minerals or materials,
    meaning composite can be nested arbitrarily.

    The fractions of the phases can be input
    as either 'molar' or 'mass' during instantiation,
    and modified (or initialised) after this point by
    using set_fractions.

    This class is available as ``burnman.Composite``.


    This is the base class for all minerals. States of the mineral
    can only be queried after setting the pressure and temperature
    using set_state(). The method for computing properties of
    the material is set using set_method(). This is done during
    initialisation if the param 'equation_of_state' has been defined.
    The method can be overridden later by the user.

    This class is available as ``burnman.Mineral``.

    If deriving from this class, set the properties in self.params
    to the desired values. For more complicated materials you
    can overwrite set_state(), change the params and then call
    set_state() from this class.

    All the material parameters are expected to be in plain SI units.  This
    means that the elastic moduli should be in Pascals and NOT Gigapascals,
    and the Debye temperature should be in K not C.  Additionally, the
    reference volume should be in m^3/(mol molecule) and not in unit cell
    volume and 'n' should be the number of atoms per molecule.  Frequently in
    the literature the reference volume is given in Angstrom^3 per unit cell.
    To convert this to m^3/(mol of molecule) you should multiply by 10^(-30) *
    N_a / Z, where N_a is Avogadro's number and Z is the number of formula units per
    unit cell. You can look up Z in many places, including www.mindat.org


    This is the base class for all solutions.
    Site occupancies, endmember activities and the constant
    and pressure and temperature dependencies of the excess
    properties can be queried after using set_composition().
    States of the solution can only be queried after setting
    the pressure, temperature and composition using set_state().

    This class is available as :class:`burnman.Solution`.
    It uses an instance of :class:`burnman.SolutionModel` to
    calculate interaction terms between endmembers.

    All the solution parameters are expected to be in SI units.  This
    means that the interaction parameters should be in J/mol, with the T
    and P derivatives in J/K/mol and m^3/mol.

    The parameters are relevant to all solution models. Please
    see the documentation for individual models for details about
    other parameters.

    Parameters
    ----------
    name : string
        Name of the solution
    solution_type : string
        String determining which SolutionModel to use. One of 'mechanical',
        'ideal', 'symmetric', 'asymmetric' or 'subregular'.
    endmembers : list of lists
        List of endmembers in this solution. The first item of each
        list should be a :class:`burnman.Mineral` object. The second item
        should be a string with the site formula of the endmember.
    molar_fractions : numpy array (optional)
        The molar fractions of each endmember in the solution.
        Can be reset using the set_composition() method.


    This is the base class for endmembers constructed from a
    linear combination of other minerals.

    Instances of this class should be initialised with a
    list of Mineral instances, a second list containing the
    number of moles of each mineral, and (optionally) a
    third list containing three floats describing a
    free energy adjustment which is linear in pressure and temperature
    (i.e. a constant energy [J/mol], entropy [J/K/mol]
    and volume adjustment [J/Pa/mol or m^3/mol]).

    For example, a crude approximation to a bridgmanite model might be
    bdg = CombinedMineral([per, stv], [1.0, 1.0], [-15.e3, 0., 0.])

    This class is available as :class:`burnman.CombinedMineral`.


    Base class for all materials. The main functionality is unroll() which
    returns a list of objects of type :class:`~burnman.Mineral` and their molar
    fractions. This class is available as ``burnman.Material``.

    The user needs to call set_method() (once in the beginning) and set_state()
    before querying the material with unroll() or density().


    Class for computing the upper Hashin-Shtrikman bound for elastic properties.
    This derives from :class:`burnman.averaging_schemes.averaging_scheme`, and implements
    the :func:`burnman.averaging_schemes.averaging_scheme.average_bulk_moduli`
    and :func:`burnman.averaging_schemes.averaging_scheme.average_shear_moduli` functions.
    Implements formulas from :cite:`Watt1976`.  The Hashin-Shtrikman bounds
    are tighter than the Voigt and Reuss bounds because they make the
    additional assumption that the orientation of the phases are statistically
    isotropic.  In some cases this may be a good assumption, and in others it
    may not be.


    Class for computing the lower Hashin-Shtrikman bound for elastic properties.
    This derives from :class:`burnman.averaging_schemes.averaging_scheme`, and implements
    the :func:`burnman.averaging_schemes.averaging_scheme.average_bulk_moduli`
    and :func:`burnman.averaging_schemes.averaging_scheme.average_shear_moduli` functions.
    Implements Formulas from :cite:`Watt1976`.  The Hashin-Shtrikman bounds
    are tighter than the Voigt and Reuss bounds because they make the
    additional assumption that the orientation of the phases are statistically
    isotropic.  In some cases this may be a good assumption, and in others it
    may not be.


    Class for computing arithmetic mean of the Hashin-Shtrikman bounds on elastic properties.
    This derives from :class:`burnman.averaging_schemes.averaging_scheme`, and implements
    the :func:`burnman.averaging_schemes.averaging_scheme.average_bulk_moduli`
    and :func:`burnman.averaging_schemes.averaging_scheme.average_shear_moduli` functions.


    A Helper that represents a Material that switches between different rocks based on a user specified
    select_rock() function based on current temperature and pressure. This class can be used in several
    ways:
    1. By creating an instance and setting select_rock to a lambda that returns a rock
    2. By deriving from this class and implementing select_rock.


A Helper that represents a Material that switches between two given rocks based on a given transition pressure.


    Helper class that makes a mineral that switches between two materials
    (for low and high spin) based on some transition pressure [Pa]


    This is the base class for a solution model,  intended for use
    in defining solutions and performing thermodynamic calculations
    on them.  All minerals of type :class:`burnman.Solution` use
    a solution model for defining how the endmembers in the solution
    interact.

    A user wanting a new solution model should define the functions included
    in the base class. All of the functions in the base class return zero,
    so if the user-defined solution model does not implement them,
    they essentially have no effect, and the Gibbs free energy and molar
    volume of a solution will be equal to the weighted arithmetic
    averages of the different endmember values.


    An extremely simple class representing a mechanical solution model.
    A mechanical solution experiences no interaction between endmembers.
    Therefore, unlike ideal solutions there is no entropy of mixing;
    the total gibbs free energy of the solution is equal to the
    dot product of the molar gibbs free energies and molar fractions
    of the constituent materials.


    A class representing an ideal solution model.
    Calculates the excess gibbs free energy and entropy due to configurational
    entropy. Excess internal energy and volume are equal to zero.

    The multiplicity of each type of site in the structure is allowed to
    change linearly as a function of endmember proportions. This class
    is therefore equivalent to the entropic part of
    a Temkin-type model :cite:`Temkin1945`.


    Solution model implementing the asymmetric regular solution model
    formulation as described in :cite:`HP2003`.

    The excess nonconfigurational Gibbs energy is given by the
    expression:

    .. math::
        \\mathcal{G}_{\\textrm{excess}} = \\alpha^T p (\\phi^T W \\phi)

    :math:`\\alpha` is a vector of van Laar parameters governing asymmetry
    in the excess properties.

    .. math::
        \\phi_i = \\frac{\\alpha_i p_i}{\\sum_{k=1}^{n} \\alpha_k p_k},
        W_{ij} = \\frac{2 w_{ij}}{\\alpha_i + \\alpha_j} \\textrm{for i<j}


    Solution model implementing the symmetric regular solution model.
    This is a special case of the
    :class:`burnman.solutionmodel.AsymmetricRegularSolution` class.


    Solution model implementing the subregular solution model formulation
    as described in :cite:`HW1989`. The excess conconfigurational
    Gibbs energy is given by the expression:

    .. math::
        \\mathcal{G}_{\\textrm{excess}} = \\sum_i \\sum_{j > i} (p_i p_j^2
        W_{ij} + p_j p_i^2 W_{ji} + \\sum_{k > j > i} p_i p_j p_k W_{ijk})

    Interaction parameters are inserted into a 3D interaction matrix during
    initialization to make use of numpy vector algebra.

    Parameters
    ----------
    endmembers : list of lists
        A list of all the independent endmembers in the solution.
        The first item of each list gives the Mineral object corresponding
        to the endmember. The second item gives the site-species formula.

    energy_interaction : list of list of lists
        The binary endmember interaction energies.
        Each interaction[i, j-i-1, 0] corresponds to W(i,j), while
        interaction[i, j-i-1, 1] corresponds to W(j,i).

    volume_interaction : list of list of lists
        The binary endmember interaction volumes.
        Each interaction[i, j-i-1, 0] corresponds to W(i,j), while
        interaction[i, j-i-1, 1] corresponds to W(j,i).

    entropy_interaction : list of list of lists
        The binary endmember interaction entropies.
        Each interaction[i, j-i-1, 0] corresponds to W(i,j), while
        interaction[i, j-i-1, 1] corresponds to W(j,i).

    energy_ternary_terms : list of lists
        The ternary interaction energies. Each list should contain
        four entries: the indices i, j, k and the value of the interaction.

    volume_ternary_terms : list of lists
        The ternary interaction volumes. Each list should contain
        four entries: the indices i, j, k and the value of the interaction.

    entropy_ternary_terms : list of lists
        The ternary interaction entropies. Each list should contain
        four entries: the indices i, j, k and the value of the interaction.


Counter that remembers the order elements are first encountered


BCC iron from :cite:`SE2015`.


FCC iron from :cite:`SE2015`.


HCP iron from :cite:`SE2015`.


Liquid iron from :cite:`SE2015`.


Murakami 2013 and references therein


Liquid iron equation of state from Anderson and Ahrens (1994)


Speziale et al. 2007, Mg#=83


Anderson & Ahrens, 1994 JGR


Dewaele et al., 2006, Physical Review Letters


    Class for the CoRK equation of state detailed in :cite:`HP1991`. The
    CoRK EoS is a simple virial-type extension to the modified Redlich-Kwong
    (MRK) equation of state. It was designed to compensate for the tendency of
    the MRK equation of state to overestimate volumes at high pressures and
    accommodate the volume behaviour of coexisting gas and liquid phases along
    the saturation curve.


    Base class for the finite strain liquid equation of state detailed
    in :cite:`deKoker2013` (supplementary materials).


    Base class for the isothermal Murnaghan equation of state,
    as described in :cite:`Murnaghan1944`.


    Class for the isothermal reciprocal K-prime equation of state
    detailed in :cite:`StaceyDavis2004`.  This equation of state is
    a development of work by :cite:`Keane1954` and :cite:`Stacey2000`,
    making use of the fact that :math:`K'` typically varies smoothly
    as a function of :math:`P/K`, and is thermodynamically required to
    exceed 5/3 at infinite pressure.

    It is worth noting that this equation of state rapidly becomes
    unstable at negative pressures, so should not be trusted to provide
    a good *HT-LP* equation of state using a thermal pressure
    formulation. The negative root of :math:`dP/dK`
    can be found at :math:`K/P = K'_{\infty} - K'_0`,
    which corresponds to a bulk modulus of
    :math:`K = K_0 ( 1 - K'_{\infty}/K'_0 )^{K'_0/K'_{\infty}}`
    and a volume of
    :math:`V = V_0 ( K'_0 / (K'_0 - K'_{\infty}) )^{K'_0/{K'}^2_{\infty}} \exp{(-1/K'_{\infty})}`.

    This equation of state has no temperature dependence.


    Class for the isothermal Morse Potential equation of state
    detailed in :cite:`Stacey1981`.
    This equation of state has no temperature dependence.


    Base class for the finite strain solid equation of state detailed
    in :cite:`deKoker2013` (supplementary materials).


    Class for the high pressure CALPHAD equation of state by
    :cite:`Brosh2007`.


    Base class for the isothermal Vinet equation of state.
    References for this equation of state are :cite:`vinet1986`
    and :cite:`vinet1987`. This equation of state actually
    predates Vinet by 55 years :cite:`Rydberg1932`,
    and was investigated further by :cite:`Stacey1981`.


    Class for the :math`E-V-S` liquid metal EOS detailed in :cite:`AA1994`.
    Internal energy (:math:`E`) is first calculated
    along a reference isentrope using a fourth order BM EoS
    (:math:`V_0`, :math:`KS`, :math:`KS'`, :math:`KS''`),
    which gives volume as a function of pressure,
    coupled with the thermodynamic identity:

    :math:`-\partial E/ \partial V |_S = P`.

    The temperature along the isentrope is calculated via

    :math:`\partial (\ln T)/\partial (\ln \\rho) |_S = \gamma`

    which gives:

    :math:`T_S/T_0 = \exp(\int( \gamma/\\rho ) d \\rho)`

    The thermal effect on internal energy is calculated at constant volume
    using expressions for the kinetic, electronic and potential contributions
    to the volumetric heat capacity, which can then be integrated with respect
    to temperature:

    :math:`\partial E/\partial T |_V = C_V`

    :math:`\partial E/\partial S |_V = T`

    We note that :cite:`AA1994` also include a detailed description
    of the Gruneisen parameter as a function of volume and energy (Equation 15),
    and use this to determine the temperature along the principal isentrope
    (Equations B1-B10) and the thermal pressure away from that isentrope
    (Equation 23). However, this expression is inconsistent with
    the equation of state away from the principal isentrope. Here we choose
    to calculate the thermal pressure and Grueneisen parameter thus:

    1) As energy and entropy are defined by the equation of state at any
    temperature and volume, pressure can be found by via the expression:

    :math:`\partial E/\partial V |_S = P`

    2) The Grueneisen parameter can now be determined as
    :math:`\gamma = V \partial P/\partial E |_V`

    To reiterate: away from the reference isentrope, the Grueneisen parameter
    calculated using these expressions is *not* equal to the
    (thermodynamically inconsistent) analytical expression given by :cite:`AA1994`.

    A final note: the expression for :math:`\Lambda` (Equation 17).
    does not reproduce Figure 5. We assume here that the figure matches the model
    actually used by :cite:`AA1994`, which has the form:
    :math:`F(-325.23 + 302.07 (\\rho/\\rho_0) + 30.45 (\\rho/\\rho_0)^{0.4})`.


    Base class for a generic finite-strain Mie-Grueneisen-Debye
    equation of state.  References for this can be found in many
    places, such as Shim, Duffy and Kenichi (2002) and Jackson and Rigden
    (1996).  Here we mostly follow the appendices of Matas et al (2007).
    Of particular note is the thermal correction to the shear modulus, which
    was developed by Hama and Suito (1998).


    Base class for the generic modified Tait equation of state.
    References for this can be found in :cite:`HC1974`
    and :cite:`HP2011` (followed here).

    An instance "m" of a Mineral can be assigned this
    equation of state with the command m.set_method('mt')
    (or by initialising the class with the param
    equation_of_state = 'mt').


    This class defines the interface for an equation of state
    that a mineral uses to determine its properties at a
    given :math:`P, T`.  In order define a new equation of state, you
    should define these functions.

    All functions should accept and return values in SI units.

    In general these functions are functions of pressure,
    temperature, and volume, as well as a "params" object,
    which is a Python dictionary that stores the material
    parameters of the mineral, such as reference volume,
    Debye temperature, reference moduli, etc.

    The functions for volume and density are just functions
    of temperature, pressure, and "params"; after all, it
    does not make sense for them to be functions of volume or density.


    Base class for the isothermal Birch Murnaghan equation of state.  This is fourth order in strain, and
    has no temperature dependence.


    Base class for the finite strain-Mie-Grueneiesen-Debye equation of state detailed
    in :cite:`Stixrude2005`.  For the most part the equations are
    all third order in strain, but see further the :class:`burnman.slb.SLB2` and
    :class:`burnman.slb.SLB3` classes.


    SLB equation of state with third order finite strain expansion for the
    shear modulus (this should be preferred, as it is more thermodynamically
    consistent.)


    SLB equation of state with second order finite strain expansion for the
    shear modulus.  In general, this should not be used, but sometimes
    shear modulus data is fit to a second order equation of state.  In that
    case, you should use this.  The moral is, be careful!


    Base class for the thermal equation of state based on
    the generic modified Tait equation of state (class MT),
    as described in :cite:`HP2011`.

    An instance "m" of a Mineral can be assigned this
    equation of state with the command m.set_method('hp_tmt')
    (or by initialising the class with the param
    equation_of_state = 'hp_tmt'


    Base class for the thermal equation of state
    described in :cite:`HP1998`, but with the Modified Tait as the static part,
    as described in :cite:`HP2011`.

    An instance "m" of a Mineral can be assigned this
    equation of state with the command m.set_method('hp_tmtL')
    (or by initialising the class with the param
    equation_of_state = 'hp_tmtL'


    Base class for the thermal equation of state
    described in :cite:`HP1998`.

    An instance "m" of a Mineral can be assigned this
    equation of state with the command m.set_method('hp98')
    (or by initialising the class with the param
    equation_of_state = 'hp98'


    Base class for the isothermal Birch Murnaghan equation of state.  This is third order in strain, and
    has no temperature dependence.  However, the shear modulus is sometimes fit to a second order
    function, so if this is the case, you should use that.  For more see :class:`burnman.birch_murnaghan.BM2` and :class:`burnman.birch_murnaghan.BM3`.


    Third order Birch Murnaghan isothermal equation of state.
    This uses the second order expansion for shear modulus.


Class to run SCMS on generic xy data


Variogram Class

    Calculates a variogram of the separating distances in the given
    coordinates and relates them to one of the semi-variance measures of
    the given dependent values.


DirectionalVariogram Class

    Calculates a variogram of the separating distances in the given
    coordinates and relates them to one of the semi-variance measures of the
    given dependent values.

    The directional version of a Variogram will only form paris of points
    that share a specified spatial relationship.


    A MetricSpace represents a point cloud together with a distance
    metric and possibly a maximum distance. It efficiently provides
    the distances between each point pair (when shorter than the
    maximum distance).

    Note: If a max_dist is specified a sparse matrix representation is
    used for the distances, which saves space and calculation time for
    large datasets, especially where max_dist << the size of the point
    cloud in space. However, it slows things down for small datasets.


    A MetricSpacePair represents a set of point clouds (MetricSpaces).
    It efficiently provides the distances between each point in one
    point cloud and each point in the other point cloud (when shorter
    than the maximum distance). The two point clouds are required to
    have the same distance metric as well as maximum distance.


Like MetricSpace but samples the distance pairs only returning a
    `samples` sized subset. `samples` can either be a fraction of
    the total number of pairs (float < 1), or an integer count.


Like ProbabilisticMetricSpace but only applies to Raster data (2D gridded data) and
    samples iteratively an `equidistant` subset within distances to a 'center' subset.
    Subsets can either be a fraction of the total number of pairs (float < 1), or an integer count.
    The 'center' subset corresponds to a disk centered on a point of the grid for which the location
    randomly varies and can be redrawn and aggregated for several runs. The corresponding 'equidistant'
    subset consists of a concatenation of subsets drawn from rings with radius gradually increasing
    until the maximum extent of the grid is reached.

    To define the subsampling, several parameters are available:
    - The raw number of samples corresponds to the samples that will be drawn in each central disk.
     Along with the ratio of samples drawn (see below), it will automatically define the radius
     of the disk and rings for subsampling.
     Note that the number of samples drawn will be repeatedly drawn for each equidistant rings
     at a given radius, resulting in a several-fold amount of total samples for the equidistant
     subset.
    - The ratio of subsample defines the density of point sampled within each subset. It
     defaults to 20%.
    - The number of runs corresponds to the number of random center points repeated during the
    subsampling. It defaults to a sampling of 1% of the grid with center subsets.

    Alternatively, one can supply:
    - The multiplicative factor to derive increasing rings radii, set as squareroot of 2 by
    default in order to conserve a similar area for each ring and verify the sampling ratio.
    Or directly:
    - The radius of the central disk subset.
    - A list of radii for the equidistant ring subsets.
    When providing those spatial parameters, all other sampling parameters will be ignored
    except for the raw number of samples to draw in each subset.


    The TestPerformance class is not a real unittest. It will always be true.
    It does apply some benchmarking, which could be included into the testing
    framework, as soon as the OrdinaryKriging class is finalized. From that
    point on, new code should not harm the performance significantly.


Record array containing a large amount of randomly generated binaries.

    For every binary defines the following field:
    - 'period': binary orbital period in years.
    - 'mass_ratio': ratio of the mass of the secondary to primary star. The primary star is the observed star (for which the velocity has been measured), the secondary star is its companion.
    - 'eccentricity': eccentricity of the binary orbit.
    - 'phase': phase of the orbit.
    - 'theta': angle between line connecting center of mass and periastron and the projection of the line of sight on the orbital plane (ignored when fitting single-epoch datasets).
    - 'inclination': angle between line of sight and the angular momentum of the binary (which is perpindicular to the orbital plane) (ignored when fitting single-epoch datasets).

    In addition some methods have been added:
    - `semi_major`: Returns an array containing the semi-major axis in AU for every binary.
    - `velocities`: Returns the radial velocity and proper motion offsets due to binary orbital motions for every binary.
    - `single_epoch`: Creates a callable object, which can be used to compute the log-likelihood of reproducing a single-epoch radial velocity dataset.
    - `multi_epoch`: Creates a callable object, which can be used to compute the log-likelihood of reproducing a multi-epoch radial velocity dataset.
    - `fake_dataset`: Creates a single- or multi-epoch fake radial velocity dataset for Monte Carlo simulations.


When called computes the log-likelihood of reproducing a set of observed radial velocities.

    The call takes 3 parameters, the mean velocity, velocity dispersion, and binary fraction of the cluster. These parameters can be varied to maximize the log-likelihood using any optmization routines (see scipy.optimize) or can be used in Markov Chain Monte Carlo Simulations (e.g. pymc, emcee).

    Properties (all of these are correctly set during initialization):
    - `velocity`: observed radial velocities in km/s (in the multi-epoch case contains the weighted means of the seemingly single stars).
    - `sigvel`: measurement uncertainties of the observed radial velocities in km/s (in the multi-epoch case this will be set to one, as the measurement uncertainties has already been taken into account in pbin).
    - `mass`: best mass estimate of the observed stars in solar masses (in the multi-epoch case this will be set to one, as the mass has already been taken into account in pbin).
    - `vbin`: velocity edges of the bins (in km/s) over which `pbin` was computed.
    - `pbin`: the probability distribution of the radial velocity offset due to binary orbital motions. The probability (defined per km/s) to have a velocity between vbin[i] and vbin[i + 1] is given by pbin[i]. In the single-epoch case this will be a single 1-dimensional array for a generic mass of 1 solar masses. In the multi-epoch case this will be a 2-dimensional array containing the probability distribution for every seemingly single star (given the observations of the star).
    - `pdet_single`: For all seemingly single stars: the probability that a binary would have been detected if the star is a binary (0 for the single-epoch case).
    - `pdet_rvvar`: For all stars with detected radial velocity variability: the probability that a binary would have been detected if the star is a binary (empy array for the single-epoch case).
    - `is_single`: Boolean array marking which stars are single.


Tranform a tensor or a list of matrix into a vector array of the
    selected moments of each band.


Tranform a tensor or a list of matrix into a vector array of the
    histogram of each band.


Compute the wet snow prediction using an learning adaptive threshold of type Nagler
    This is done by simply computing the mean of the ratio VV with a snow free reference


Classe for the calculation of covariance matrix from a dataset of variable size


Transform a tensor or a list of covariance matrix into a vector array.
    Each vector is the extraction of the triangular matrix of its associated matrix


Transform a tensor or a list of matrix into a vector array


Balanced Fold cross-validator, only valid for binary classification.

    Split dataset into k consecutive folds (without shuffling by default),
    ensuring that each fold has the same number of samples from each class.
    It allows to have B sub-datasets balanced, and have a complete view of the
    data.

    Parameters
    ----------
    shuffle : bool, default=False
        Whether to shuffle the data before splitting into batches.

    random_state : int, RandomState instance or None, default=None
        When shuffle=True, pseudo-random number generator state used for
        shuffling. If None, use default numpy RNG for shuffling.

    Attributes
    ----------
    n_splits : int
        Returns the number of splitting iterations in the cross-validator.


Class for managing the extraction of overlapping patches from an image
    and the reconstruction of the image from the patches.
    It is based on the scikit-learn class
    sklearn.feature_extraction.image.extract_patches_2d
    For the reconstruction, in case of odd window size, the center pixel
    of the patch is selected as the center pixel of the patch. In case of even
    window size, the upper left pixel in the center is selected as the center
    pixel of the patch.

    Attributes
    ----------
    window_size : int
        Size of the window (square)

    channel : list
        Channel to extract

    padding : bool
        Perform padding on the image before extracting patches

    positions_ : numpy array
        Array of positions corresponding to the extracted patches

    patches : numpy array
        Array of extracted patches

    image_size : tuple
        Size of the original image (Nx, Ny, C)


    Class to represent and operate on a repository description.

    For testing purpose, all system calls to svn should:

    * be isolated in separate functions with no application logic
      * of the form:
         - cmd = ['svn', ...]
         - value = execute_subprocess(cmd, output_to_caller={T|F},
                                      status_to_caller={T|F})
         - return value
      * be static methods (not rely on self)
      * name as _svn_subcommand_args(user_args)

    This convention allows easy unit testing of the repository logic
    by mocking the specific calls to return predefined results.


Class to represent and operate on a repository description.

    For testing purpose, all system calls to git should:

    * be isolated in separate functions with no application logic
      * of the form:
         - cmd = ['git', ...]
         - value = execute_subprocess(cmd, output_to_caller={T|F},
                                      status_to_caller={T|F})
         - return value
      * be static methods (not rely on self)
      * name as _git_subcommand_args(user_args)

    This convention allows easy unit testing of the repository logic
    by mocking the specific calls to return predefined results.


Class to represent and operate on a repository description.


Base externals description class that is independent of the user input
    format. Different input formats can all be converted to this
    representation to provide a consistent represtentation for the
    rest of the objects in the system.

    NOTE(bja, 2018-03): do NOT define _schema_major etc at the class
    level in the base class. The nested/recursive nature of externals
    means different schema versions may be present in a single run!

    All inheriting classes must overwrite:
        self._schema_major and self._input_major
        self._schema_minor and self._input_minor
        self._schema_patch and self._input_patch

    where _schema_x is the supported schema, _input_x is the user
    input value.


Create a externals description object from a dictionary using the API
    representations. Primarily used to simplify creating model
    description files for unit testing.


Create a externals description object from a config_parser object,
    schema version 1.


_External represents an external object inside a SourceTree


SourceTree represents a group of managed externals


Test the application logic of creat_externals_description


Test the create_repository functionality to ensure it returns the
    propper type of repository and errors for unknown repository
    types.


Test the externals description processing used to create the Repository
    base class shared by protocol specific repository classes.


Class to provide building blocks to create
    ExternalsDescriptionCfgV1 files.

    Includes predefined files used in tests.


Base class of reusable systems level test setup for
    checkout_externals


Run systems level tests of checkout_externals


Test the create_remote_name method on the GitRepository class


 This class contains methods to allow python to interact with the JSON file that
        defines the MARBL parameters and sets default values.

        This file also contains several subroutines that are not part of the class but are
        called by member functions in the class.


 This class contains methods to allow python to interact with the JSON file that
        defines the MARBL diagnostics and sets default values. It requires a
        MARBL_settings_class object upon construction because some diagnostics are only
        available with specific settings (for example, there are several carbon isotope
        diagnostics but MARBL will only compute them if ciso_on = .true.) and other
        diagnostics are defined on a per-tracer basis (MARBL_settings.tracer_dict.keys()
        is a list of all tracers active given MARBL_settings).


    This class contains all the Fortran consistency check tests.
    The logs dictionary contains a deque object with a list of all source lines
    that fail a particular test (given as the logs key)


Tests for the TestSuiteSpec class.


Tests for the suites_from_xml function.


Catch-all class for formatting output.

    Public routines:
    __init__ - Constructor.
    print - Print input arguments.
    comment - Print input arguments, as a comment.
    draw_rule - Print a separator.
    print_header - Print a section header.
    print_error - Print a string as an error message.


Specialized printer object for printing a script.

    Modified public routines:
    __init__ - Restricts constructor (no longer takes a "color" argument).
    print - Now does indentation.
    comment - Overrides parent routine: print a comment with a "#".
    print_header - Extends parent routine: prints a section header.

    Public data:
    indent_level - Current level of indentation. Must be nonnegative.


Specification for the location of a test suite.

    Public methods:
    __init__ - Constructor.
    __iter__ - Iterate over label/directory pairs.

    Public data:
    name - Name of the suite for logging output.
    labels - Labels for test suite directories.
    directories - Absolute paths to test suite directories.


A mock version of the Machines object to simplify testing.


Helper class for checking Makefile output.

    Public methods:
    __init__
    query_var
    assert_variable_equals
    assert_variable_matches


Helper class for checking CMake output.

    Public methods:
    __init__
    query_var
    assert_variable_equals
    assert_variable_matches


Basic infrastructure tests.

    This class contains tests that do not actually depend on the output of the
    macro file conversion. This includes basic smoke testing and tests of
    error-handling in the routine.


Makefile macros tests.

    This class contains tests of the Makefile output of Build.

    Aside from the usual setUp and test methods, this class has a utility method
    (xml_to_tester) that converts XML input directly to a MakefileTester object.


CMake macros tests.

    This class contains tests of the CMake output of Build.

    This class simply inherits all of the methods of TestMakeOutput, but changes
    the definition of xml_to_tester to create a CMakeTester instead.


Tests various scripts to manage and query xml files


Utility class for generating namelists for a given component.


    Simple struct for holding dates and the time of day and performing comparisons

    Difference in Hour, Minute, or Second
    >>> date(4, 5, 6, 9) == date(4, 5, 6, 8)
    False
    >>> date(4, 5, 6, 9) != date(4, 5, 6, 8)
    True
    >>> date(4, 5, 6, 9) < date(4, 5, 6, 8)
    False
    >>> date(4, 5, 6, 9) <= date(4, 5, 6, 8)
    False
    >>> date(4, 5, 6, 9) >= date(4, 5, 6, 8)
    True
    >>> date(4, 5, 6, 9) > date(4, 5, 6, 8)
    True

    >>> date(4, 5, 6, 4) == date(4, 5, 6, 8)
    False
    >>> date(4, 5, 6, 4) != date(4, 5, 6, 8)
    True
    >>> date(4, 5, 6, 4) < date(4, 5, 6, 8)
    True
    >>> date(4, 5, 6, 4) <= date(4, 5, 6, 8)
    True
    >>> date(4, 5, 6, 4) >= date(4, 5, 6, 8)
    False
    >>> date(4, 5, 6, 4) > date(4, 5, 6, 8)
    False

    Difference in Day
    >>> date(4, 5, 8, 8) == date(4, 5, 6, 8)
    False
    >>> date(4, 5, 8, 8) != date(4, 5, 6, 8)
    True
    >>> date(4, 5, 8, 8) < date(4, 5, 6, 8)
    False
    >>> date(4, 5, 8, 8) <= date(4, 5, 6, 8)
    False
    >>> date(4, 5, 8, 8) >= date(4, 5, 6, 8)
    True
    >>> date(4, 5, 8, 8) > date(4, 5, 6, 8)
    True

    >>> date(4, 5, 5, 8) == date(4, 5, 6, 8)
    False
    >>> date(4, 5, 5, 8) != date(4, 5, 6, 8)
    True
    >>> date(4, 5, 5, 8) < date(4, 5, 6, 8)
    True
    >>> date(4, 5, 5, 8) <= date(4, 5, 6, 8)
    True
    >>> date(4, 5, 5, 8) >= date(4, 5, 6, 8)
    False
    >>> date(4, 5, 5, 8) > date(4, 5, 6, 8)
    False

    Difference in Month
    >>> date(4, 6, 6, 8) == date(4, 5, 6, 8)
    False
    >>> date(4, 6, 6, 8) != date(4, 5, 6, 8)
    True
    >>> date(4, 6, 6, 8) < date(4, 5, 6, 8)
    False
    >>> date(4, 6, 6, 8) <= date(4, 5, 6, 8)
    False
    >>> date(4, 6, 6, 8) >= date(4, 5, 6, 8)
    True
    >>> date(4, 6, 6, 8) > date(4, 5, 6, 8)
    True

    >>> date(4, 4, 6, 8) == date(4, 5, 6, 8)
    False
    >>> date(4, 4, 6, 8) != date(4, 5, 6, 8)
    True
    >>> date(4, 4, 6, 8) < date(4, 5, 6, 8)
    True
    >>> date(4, 4, 6, 8) <= date(4, 5, 6, 8)
    True
    >>> date(4, 4, 6, 8) >= date(4, 5, 6, 8)
    False
    >>> date(4, 4, 6, 8) > date(4, 5, 6, 8)
    False

    Difference in Year
    >>> date(5, 5, 6, 8) == date(4, 5, 6, 8)
    False
    >>> date(5, 5, 6, 8) != date(4, 5, 6, 8)
    True
    >>> date(5, 5, 6, 8) < date(4, 5, 6, 8)
    False
    >>> date(5, 5, 6, 8) <= date(4, 5, 6, 8)
    False
    >>> date(5, 5, 6, 8) >= date(4, 5, 6, 8)
    True
    >>> date(5, 5, 6, 8) > date(4, 5, 6, 8)
    True

    >>> date(3, 5, 6, 8) == date(4, 5, 6, 8)
    False
    >>> date(3, 5, 6, 8) != date(4, 5, 6, 8)
    True
    >>> date(3, 5, 6, 8) < date(4, 5, 6, 8)
    True
    >>> date(3, 5, 6, 8) <= date(4, 5, 6, 8)
    True
    >>> date(3, 5, 6, 8) >= date(4, 5, 6, 8)
    False
    >>> date(3, 5, 6, 8) > date(4, 5, 6, 8)
    False


Class representing a Fortran namelist.

    Public methods:
    __init__
    delete_variable
    get_group_names
    get_value
    get_variable_names
    get_variable_value
    merge_nl
    set_variable_value
    write


Exception thrown for an unexpected end-of-file in a namelist.

    This is an internal helper class, and should never be raised in a context
    where it would be visible to a user. (Typically it should be caught and
    converted to some other error, or ignored.)


Exception thrown when namelist input has a syntax error.

    This is an internal helper class, and should never be raised in a context
    where it would be visible to a user. (Typically it should be caught and
    converted to some other error, or ignored.)


Class to validate and read from Fortran namelist input.

    This is intended to be an internal helper class and should not be used
    directly. Use the `parse` function in this module instead.


    Context manager for environment variables
    Usage:
        os.environ['MYVAR'] = 'oldvalue'
        with EnvironmentContex(MYVAR='myvalue', MYVAR2='myvalue2'):
            print os.getenv('MYVAR')    # Should print myvalue.
            print os.getenv('MYVAR2')    # Should print myvalue2.
        print os.getenv('MYVAR')        # Should print oldvalue.
        print os.getenv('MYVAR2')        # Should print None.

    CREDIT: https://github.com/sakurai-youhei/envcontext


Macro writer for the Makefile format.

    For details on the provided methods, see MacroWriterBase, which this
    class inherits from.


Tree containing the various possible settings of a specific macro.

    Unlike the PossibleValues class, this class assumes that we have
    finished determining which settings could apply on a given machine. It
    also sorts the settings based on the conditions under which they take
    effect, in preparation for writing out the Macros file itself.

    Public methods:
    merge
    write_out


Abstract base class for macro file writers.

    The methods here come in three flavors:
    1. indent_left/indent_right change the level of indent used internally by
       the class.
    2. The various methods ending in "_string" return strings relevant to the
       build system.
    3. The other methods write information to the file handle associated with
       an individual writer instance.

    Public attributes:
    indent_increment - Number of spaces to indent if blocks (does not apply
                       to format-specific indentation, e.g. cases where
                       Makefiles must use tabs).
    output - File-like object that output is written to.

    Public methods:
    indent_string
    indent_left
    indent_right
    write_line
    environment_variable_string
    shell_command_string
    variable_string
    set_variable
    append_variable
    start_ifeq
    end_ifeq


Holds a list of settings for a single "Macros" variable.

    This helper class takes in variable settings and, for each one, decides
    whether to throw it out, add it to the list of values, or replace the
    existing list of values with the new, more specific setting.

    This class also performs ambiguity checking; if it is possible at build
    time for more than one setting to match the same variable, this is
    considered an error.

    Public attributes:
    name - The name of the variable.
    settings - The current list of possible initial settings for the
               variable.
    append_settings - A dictionary of lists of possible appending settings
                      for the variable, with the specificity of each list
                      as the associated dictionary key.
    depends - The current list of variables that this variable depends on
              to get its value.

    Public methods:
    add_setting
    ambiguity_check
    to_cond_trees


Holds data about how a value can be assigned to a variable.

    Note that this class doesn't know or care *which* variable might be
    assigned in this way, only that there is a procedure to perform that
    operation

    Public attributes:
    value - The actual value that will be set.
    do_append - Boolean describing whether the value should be
                appended to the existing value of the variable rather
                than overwriting other settings.
    conditions - Dictionary containing the set of values that different
                 variables have to have to use this setting (e.g.
                 DEBUG="TRUE" might be a condition on a debug flag).
    set_up - List of any commands that have to be executed in the build
             system before this setting can occur.
    tear_down - List of any commands that should be executed to clean up
                after setting the variable.

    Public methods:
    is_ambiguous_with


Macro writer for the CMake format.

    For details on the provided methods, see MacroWriterBase, which this
    class inherits from.


    https://github.com/ESMCI/cime/wiki/Developers-Introduction
    The Case class is the heart of the CIME Case Control system.  All
    interactions with a Case take part through this class.  All of the
    variables used to create and manipulate a case are defined in xml
    files and for every xml file there is a python class to interact
    with that file.

    XML files which are part of the CIME distribution and are meant to
    be readonly with respect to a case are typically named
    config_something.xml and the corresponding python Class is
    Something and can be found in file CIME.XML.something.py.  I'll
    refer to these as the CIME config classes.

    XML files which are part of a case and thus are read/write to a
    case are typically named env_whatever.xml and the cooresponding
    python modules are CIME.XML.env_whatever.py and classes are
    EnvWhatever.  I'll refer to these as the Case env classes.

    The Case Class includes an array of the Case env classes, in the
    configure function and it's supporting functions defined below
    the case object creates and manipulates the Case env classes
    by reading and interpreting the CIME config classes.

    This class extends across multiple files, class members external to this file
    are listed in the following imports


Data used to translate a single <compiler> element.

    This is used during write_macros to traverse the XML and create a list
    of settings specified in the element.

    Public methods:
    add_settings_to_lists
    matches_machine


Class representing variable definitions for a namelist.
    This class inherits from `EntryID`, and supports most inherited methods;
    however, `set_value` is unsupported.

    Additional public methods:
    - dict_to_namelist.
    - is_valid_value
    - validate


    Implementation of the CIME data assimilation test:
    Compares standard run with a run broken into two data assimilation cycles.
    Runs a simple DA script on each cycle which performs checks but does not
    change any model state (restart files). Compares answers of two runs.
    Refers to a faux data assimilation script in the
    cime/scripts/data_assimilation directory


    Implementation of the CIME pause/resume test: Tests having driver
    'pause' (write cpl and/or other restart file(s)) and 'resume'
    (read cpl and/or other restart file(s)) possibly changing restart
    file. Compare to non-pause/resume run.


    Inheriters of the FakeTest Class are intended to test the code.

    All members of the FakeTest Class must
    have names beginnig with "TEST" this is so that the find_system_test
    in utils.py will work with these classes.


    You can generate a diff with this test as follows:
    1) Run the test and generate a baseline
    2) set TESTRUNDIFF_ALTERNATE environment variable to TRUE
    3) Re-run the same test from step 1 but do a baseline comparison instead of generation
      3.a) This should give you a DIFF


non-demoninational dictionary of node data:


Read in a domain node from Cime2 xml format


Read in a domain node from Cime5 xml format


Convert dictionary data entry into usable object


    Optimized the problem based on the Layout
              ____________________
             | ICE  |  LND  |     |
             |______|_______|     |
             |              | OCN |
             |    ATM       |     |
             |______________|_____|

      Min T
      s.t.  T[ice]      <= T1
            T[lnd]      <= T1
            T1 + T[atm] <= T
            T[ocn]      <= T

            NB[c]        >= 1 for c in [ice,lnd,ocn,atm]
            NB[ice] + NB[lnd] <= NB[atm]
            atm_blocksize*NB[atm] + ocn_blocksize*NB[ocn] <= TotalTasks
            (NB[*] is number of processor blocks)

            T[c]        >= C[c]_{i} - NB[c]_{i} *
                       (C[c]_{i+1} - C[c]_{i}) / (NB[c]_{i+1} - NB[c]_{i})
                       + NB[c] * (C[c]_{i+1} - C[c]_{i})
                                               / (NB[c]_{i+1} - NB[c]_{i}),
                        i=1..ord(NB), c in [ice,lnd,ocn,atm]

    These assumptions are checked when solver is initialized
      . Assuming cost is monotonic decreasing vs ntasks
      . Assuming perfect scalability for ntasks < tasks[0]
      . Assuming same scalability factor for ntasks > ntasks[last] as for
                              last two data points

    Returns state (STATE_SOLVED_OK, STATE_SOLVED_BAD, STATE_UNSOLVED)
    If solved, then solution will be stored in self.X dictionary, indexed
    by variable name. Suggested convention:
        'Tice', 'Tlnd', ... for cost per component
        'Nice', 'Nlnd', ... for ntasks per component
        'NBice', 'NBlnd', ... for number of blocks per component


    Optimized the problem based on the Layout
              __________________________
             | ICE  |  LND  | WAV |     |
             |______|_______|_____|     |
             |                    | OCN |
             |    ATM             |     |
             |____________________|_____|

      Min T
      s.t.  T[ice]      <= T1
            T[lnd]      <= T1
            T[wav]      <= T1
            T1 + T[atm] <= T
            T[ocn]      <= T

            NB[c]        >= 1 for c in [ice,lnd,wav,ocn,atm]
            NB[ice] + NB[lnd] + NB[wav] <= NB[atm]
            atm_blocksize*NB[atm] + ocn_blocksize*NB[ocn] <= TotalTasks
            (NB[*] is number of processor blocks)

            T[c]        >= C[c]_{i} - NB[c]_{i} *
                       (C[c]_{i+1} - C[c]_{i}) / (NB[c]_{i+1} - NB[c]_{i})
                       + NB[c] * (C[c]_{i+1} - C[c]_{i})
                                               / (NB[c]_{i+1} - NB[c]_{i}),
                        i=1..ord(NB), c in [ice,lnd,wav,ocn,atm]

    These assumptions are checked when solver is initialized
      . Assuming cost is monotonic decreasing vs ntasks
      . Assuming perfect scalability for ntasks < tasks[0]
      . Assuming same scalability factor for ntasks > ntasks[last] as for
                              last two data points
      . Assuming components are capable of running on ntasks

    Returns state (STATE_SOLVED_OK, STATE_SOLVED_BAD, STATE_UNSOLVED)
    If solved, then solution will be stored in self.X dictionary, indexed
    by variable name. Suggested convention:
        'Tice', 'Tlnd', ... for cost per component
        'Nice', 'Nlnd', ... for ntasks per component
        'NBice', 'NBlnd', ... for number of blocks per component


DB-API base exception


Stop the iteration of `next()` in pipeline tasks.

    Pipeline tasks should raise this excetions in the `next()` method to stop
    the iteration of the task and to proceed to `finish()`.

    Note that if `next()` recieves input data as an argument, it is not
    required to ever raise this exception.  The pipeline will proceed to
    `finish()` once the input data has run out.


    Abstract base class for DataProvider implementation. Subclasses have to
    overwrite the `_next_data` method that load the next data and label array.
    This implementation automatically clips the data with the given min/max and
    normalizes the values to (0,1]. To change this behavoir the `_process_data`
    method can be overwritten. To enable some post processing such as data
    augmentation the `_post_process` method can be overwritten.

    :param a_min: (optional) min value used for clipping
    :param a_max: (optional) max value used for clipping


    A simple data provider for numpy arrays.
    Assumes that the data and label are numpy array with the dimensions
    data `[n, X, Y, channels]`, label `[n, X, Y, classes]`. Where
    `n` is the number of images, `X`, `Y` the size of the image.

    :param data: data numpy array. Shape=[n, X, Y, channels]
    :param label: label numpy array. Shape=[n, X, Y, classes]
    :param a_min: (optional) min value used for clipping
    :param a_max: (optional) max value used for clipping


    Generic data provider for images, supports gray scale and colored images.
    Assumes that the data images and label images are stored in the same folder
    and that the labels have a different file suffix
    e.g. 'train/fish_1.tif' and 'train/fish_1_mask.tif'
    Number of pixels in x and y of the images and masks should be even.

    Usage:
    data_provider = ImageDataProvider("..fishes/train/*.tif")

    :param search_path: a glob search pattern to find all data and label images
    :param a_min: (optional) min value used for clipping
    :param a_max: (optional) max value used for clipping
    :param data_suffix: suffix pattern for the data images. Default '.tif'
    :param mask_suffix: suffix pattern for the label images. Default '_mask.tif'
    :param shuffle_data: if the order of the loaded file path should be randomized. Default 'True'


    A unet implementation

    :param channels: number of channels in the input image
    :param n_class: number of output labels
    :param cost: (optional) name of the cost function. Default is 'cross_entropy'
    :param cost_kwargs: (optional) kwargs passed to the cost function. See Unet._get_cost for more options


    Trains a unet instance

    :param net: the unet instance to train
    :param batch_size: size of training batch
    :param verification_batch_size: size of verification batch
    :param norm_grads: (optional) true if normalized gradients should be added to the summaries
    :param optimizer: (optional) name of the optimizer to use (momentum or adam)
    :param opt_kwargs: (optional) kwargs passed to the learning rate (momentum opt) and to the optimizer


    Extends the BaseDataProvider to randomly select the next
    chunk of the image and randomly applies transformations to the data


    Extends the default ImageDataProvider to randomly select the next
    image and ensures that only data sets are used where the mask is not empty.
    The data then gets mean and std adjusted


    Extends the BaseDataProvider to randomly select the next
    data chunk


Store all relevant data to communicate between the different modules.


Store the type of prior associated to a parameter


General class that all likelihoods will inherit from.


Hold all information for analyzing runs


    New class of file, to provide an equivalent of the tail command (on linux).

    It will be used when starting from an existing chain, and avoids circling
    through an immense file.


Likelihood for WiggleZ


    This likelihood is used to derive constraints on the ISW effect through
    crosscorrelation of the CMB with 5 galaxy surveys: 2MPZ, Wise x SuperCOSMOS,
    SDSS DR12 photometric, SDSS DR6 QSO, and NVSS. Each survey is divided into
    several redshift bins.

    The C_l of auto- and crosscorrelation are binned in l and fitted to the
    cosmological model. The minimum and maximum l and the number of bins is
    specified in the datafile of each survey and redshift bin.

    Fit parameters: ISW amplitude A_ISW, 15 bias parameters (one for each redshift bin of each catalog)


    def __load_legacy_nofz(self):

        # Create labels for loading of dn/dz-files:
        self.zbin_labels = []
        for idx in xrange(self.nzbins):
            self.zbin_labels += ['{:.1f}t{:.1f}'.format(self.z_bins_min[idx], self.z_bins_max[idx])]

        z_samples = []
        hist_samples = []
        for zbin in xrange(self.nzbins):
            window_file_path = os.path.join(
                self.data_directory, 'Nz_DIR/Nz_DIR_Mean/Nz_DIR_z{:}.asc'.format(self.zbin_labels[zbin]))
            if os.path.exists(window_file_path):
                zptemp, hist_pz = np.loadtxt(window_file_path, usecols=[0, 1], unpack=True)
                shift_to_midpoint = np.diff(zptemp)[0] / 2.
                if zbin > 0:
                    zpcheck = zptemp
                    if np.sum((zptemp - zpcheck)**2) > 1e-6:
                        raise io_mp.LikelihoodError('The redshift values for the window files at different bins do not match.')
                print('Loaded n(zbin{:}) from: \n'.format(zbin + 1), window_file_path)
                # we add a zero as first element because we want to integrate down to z = 0!
                z_samples += [np.concatenate((np.zeros(1), zptemp + shift_to_midpoint))]
                hist_samples += [np.concatenate((np.zeros(1), hist_pz))]
            else:
                raise io_mp.LikelihoodError("File not found:\n %s"%window_file_path)

        z_samples = np.asarray(z_samples)
        hist_samples = np.asarray(hist_samples)

        return z_samples, hist_samples


    # Test syncing a directory of configs with an empty S3 bucket.
    # Passes if the configs are all deleted from the directory.
    def test_sync_configs_delete_all(self):
        test_dir_name = "test_configs_delete"
        test_dir_path = os.path.join(os.getcwd(), TEST_FILES_DIR, test_dir_name)
        for filename in os.listdir(test_dir_path):
            shutil.copy2(os.path.join(test_dir_path, filename), self.sync_dir_path)
        cmd = "python3 /home/oe2/onearth/src/scripts/oe_sync_s3_configs.py -b {0} -d {1} -s {2}".format(TEST_BUCKET, self.sync_dir_path, MOCK_S3_URI)
        run_command(cmd)
        # check results
        success = True
        failure_msg = "\noe_sync_s3_configs.py failed to delete the following file(s) from {0} that weren't in the S3 bucket:".format(self.sync_dir_path)
        for _, _, files in os.walk(self.sync_dir_path):
            for name in files:
                success = False
                failure_msg += "\n- {0}".format(name)
        self.assertTrue(success, failure_msg)


    Example usage:

    >>> tree = ElementTree.parse('your_file.xml')
    >>> root = tree.getroot()
    >>> xmldict = XmlDictConfig(root)

    Or, if you want to use an XML string:

    >>> root = ElementTree.XML(xml_string)
    >>> xmldict = XmlDictConfig(root)

    And then use xmldict for what it is... a dict.


    This covers the following test cases:
        Test using tiled images with Z-level
        Test MRF generation with date and time


    # Tests creation of a shapefile from multiple GeoJSON inputs.
    # Alerts if output shapefile's number of features differs from the sum of the number of features in the input GeoJSONs.
    def test_shapefile_generation_multiple_geojson(self):
        # Process config file
        test_artifact_path = os.path.join(self.main_artifact_path, 'shapefiles_multiple_geojson')
        config = self.parse_vector_config(self.shapefile_mult_geojson_test_config, test_artifact_path)

        # Open input GeoJSON and get stats
        try:
            with fiona.open(config['input_files'][0]) as geojson1, fiona.open(config['input_files'][1]) as geojson2:
                origin_num_features = len(list(geojson1)) + len(list(geojson2))
        except fiona.errors.FionaValueError:
            self.fail("Can't open input geojson {0} or {1}. Make sure they're valid.".format(config['input_files'][0], config['input_files'][1]))

        # Run vectorgen
        prevdir = os.getcwd()
        os.chdir(test_artifact_path)
        cmd = 'oe_vectorgen -c ' + self.shapefile_mult_geojson_test_config
        run_command(cmd, ignore_warnings=True)
        os.chdir(prevdir)

        # Check the output
        output_file = os.path.join(config['output_dir'], config['prefix'] + '.shp')
        try:
            with fiona.open(output_file) as shapefile:
                self.assertEqual(origin_num_features, len(list(shapefile)),
                                 "Feature count between the sum of input GeoJSONs {0} and {1} differs from that of output shapefile {2}. There is a problem with the conversion process."
                                 .format(config['input_files'][0], config['input_files'][1], output_file))
        except IOError:
            self.fail("Expected output geojson file {0} doesn't appear to have been created.".format(output_file))
        except fiona.errors.FionaValueError:
            self.fail("Bad output geojson file {0}.".format(output_file))


Collection of ColorMaps


ColorMapEntry values within a ColorMap


LegendEntry values within a Legend


Environment information for layer(s)


RGBA values for VRT color table


Class for Catalog objects


Possible surveys: 2MASS, WISE, IRAS


    A custom server class for DSSServer
    Because of the diverse data source of DSS, this is an agglormerate of things that works on DSS.


RC3 Class is the core mosaicing class. Each RC3 galaxy is represented by an RC3 object.


Class for RC3 Catalog objects


manage a local git repository


    Class to construct data warehouses. A data warehouse is simple
    file directory with the following structure

    YEAR
        MONTH
            file.ext


    new style adapter
    be careful with super methods you use they may deprecate

    using decorators is the new model


    The DatabaseAdapter is a base class for interacting with a SQLAlchemy database.
    Two main subclasses are used by pychron, IsotopeAdapter and MassSpecDatabaseAdapter.

    This class provides attributes for describing the database url, i.e host, user, password etc,
    and methods for connecting and opening database sessions.

    It also provides some helper functions used extensively by the subclasses, e.g. ``_add_item``,
    ``_retrieve_items``


Teach SA how to literalize various things.


MeasurementPyScripts are used to collect isotopic data


    The ExtractionPyScript is used to program the extraction and gettering of
    sample gas.


Thin http client used to interact with Sparrow API


    1a. user move to center
     b. record position
    2a. user move to right
     b. record position
    3. traverse holes finding autocenter position


    1a. move to center position automatically
     b. autocenter
    2a. move to right position automatically
     b. autocenter


        adapted from
        https://stackoverflow.com/questions/3104781/inverse-distance-weighted-idw-interpolation-with-python

        inverse-distance-weighted interpolation using KDTree:
    invdisttree = Invdisttree( X, z )  -- data points, values
    interpol = invdisttree( q, nnear=3, eps=0, p=1, weights=None, stat=0 )
        interpolates z from the 3 points nearest each query point q;
        For example, interpol[ a query point q ]
        finds the 3 data points nearest q, at distances d1 d2 d3
        and returns the IDW average of the values z1 z2 z3
            (z1/d1 + z2/d2 + z3/d3)
            / (1/d1 + 1/d2 + 1/d3)
            = .55 z1 + .27 z2 + .18 z3  for distances 1 2 3

        q may be one point, or a batch of points.
        eps: approximate nearest, dist <= (1 + eps) * true nearest
        p: use 1 / distance**p
        weights: optional multipliers for 1 / distance**p, of the same shape as q
        stat: accumulate wsum, wn for average weights

    How many nearest neighbors should one take ?
    a) start with 8 11 14 .. 28 in 2d 3d 4d .. 10d; see Wendel's formula
    b) make 3 runs with nnear= e.g. 6 8 10, and look at the results --
        |interpol 6 - interpol 8| etc., or |f - interpol*| if you have f(q).
        I find that runtimes don't increase much at all with nnear -- ymmv.

    p=1, p=2 ?
        p=2 weights nearer points more, farther points less.
        In 2d, the circles around query points have areas ~ distance**2,
        so p=2 is inverse-area weighting. For example,
            (z1/area1 + z2/area2 + z3/area3)
            / (1/area1 + 1/area2 + 1/area3)
            = .74 z1 + .18 z2 + .08 z3  for distances 1 2 3
        Similarly, in 3d, p=3 is inverse-volume weighting.

    Scaling:
        if different X coordinates measure different things, Euclidean distance
        can be way off.  For example, if X0 is in the range 0 to 1
        but X1 0 to 1000, the X1 distances will swamp X0;
        rescale the data, i.e. make X0.std() ~= X1.std() .

    A nice property of IDW is that it's scale-free around query points:
    if I have values z1 z2 z3 from 3 points at distances d1 d2 d3,
    the IDW average
        (z1/d1 + z2/d2 + z3/d3)
        / (1/d1 + 1/d2 + 1/d3)
    is the same for distances 1 2 3, or 10 20 30 -- only the ratios matter.
    In contrast, the commonly-used Gaussian kernel exp( - (distance/h)**2 )
    is exceedingly sensitive to distance and to h.


    xs=[(x1,y1),(x2,y2),...,(xn,yn)]
    ys=[z1,z2,z3,...,zn]

    if you have a list of x's and y's
    X=array(zip(x,y))
    if you have a tuple of x,y pairs
    X=array(xy)


columns should be 2D


Editor factory for buttons.


An edge color factory


makes  message dialogs thread save.


    Uses a QPlainTextEdit instead of QTextEdit.

    doesn't use QTextTable.
    uses static column widths defined by the adapter


    fast text table editor may no longer be necessary
    texttableeditor sped up significantly using beginEditBlock/endEditBlock


A convenience class for rendering PlotComponents onto PDF


    affine transform

    cumulative transform using augmented matrix A


    video only needs to be an object the implements
    get_image_data([,size=(w,h)])
        returns  ndarray


    figure_events get handled by the Panel. The Panel then fires a new figure_event that is handled by the
    PipelineEngine


High level representation of the ArAr attributes of an analysis.


    ported from Renne_2011_noLSC.m (Leah Morgan USGS 2016)
    original source available in  docs/dev_guide


    use to revert data from Pychron to MassSpec.
    uses the MassSpecDatabasereverter to do the actual work.
    This class takes a list of run ids, extracts data from
    the pychron database, prepares data for use with MassSpecDatabasereverter,
    then writes to the MassSpec database


export irradiation from the pychron database to a mass spec database


class used to create/edit an irradiation


Used to import data from MassSpec database to a Pychron database


Test exporting irradiations from Pychron to MassSpec


    currently uses passive focus techniques
    see

    http://en.wikipedia.org/wiki/Autofocus


    mysql2sqlite
    https://gist.github.com/esperlu/943776

    update local database
    when pushing
    1. pull remote database file and merge with local
       a. pull remote to path.remote (rsync remote path.remote)
       b. create merged database at path.merge
       c. rsync path.merge path
    2. push local to remote
       a. rsync lpath remote


transfer analyses from an isotope_db database to a dvc database


main interface to DVC backend. Delegates responsibility to DVCDatabase and MetaRepo


    1. Select set of repositories
    2. clone repositories
    3. update the meta repo
    4. copy the central db to a sqlite db
    5. set DVC db preferences to sqlite


map a voltage to a mass


    Interface to a Thermo Scientific Argus Mass Spectrometer via Qtegra and RemoteControlServer.cs
    magnet control provided by ArgusMagnet
    source control provided by ArgusSource

    direct access to RemoteControlServer.cs API via microcontroller
    e.g. microcontroller.ask('GetIntegrationTime')


    Top level interface to an Thermo Scientific Argus Mass Spectrometer

    direct access provided by spectrometer_microcontroller; an instance
    of thermo.spectrometer.Spectrometer


    Magnet interface to Qtegra.

    uses MFTable object of mapping dac to mass


Abstraction for the MAP Magent


draws a horizontal or vertical line at the specified value


    a graph for displaying diffusion data

    contains upto 5 plots
    1. age-spectrum
    2.log r/ro
    3.arrhenius
    4.cooling histories
    5.unconstrained thermal histories


A tool that captures the color and underlying values of an image plot.


An overlay that displays a box containing values from an
    ImageInspectorTool instance.


abstract class for displaying hover data


    Scanner is a base class for displaying a scan of device data

    ScanableDevices has this ability built in but more complicated scans are
    best done here. ScanableDevice scan is best used from continuous long term recording
    of a single or multiple values


    A PychronLaserManager is used to control an instance of
    pychron remotely.

    Common laser functions such as enable_laser are converted to
    the RemoteHardwareServer equivalent and sent by the communicator

    e.g enable_laser ==> self.communicator.ask('Enable')

    The communicators connection arguments are set in initialization.xml

    use a communicator block
    <plugin enabled="true" fire_mode="client">FusionsDiode
        ...
        <communications>
          <host>129.138.12.153</host>
          <port>1069</port>
          <kind>UDP</kind>
        </communications>
    </plugin>


Base class for a GUI representation of a laser device


fusions co2 has a built in power meter that needs to be calibrated


    a pattern is only good for one execution.
    self.pattern needs to be reset after stop or finish using load_pattern(name_or_pickle)


class for accessing a streaming camera.


    a list of name, url (file:///abs/path or pvs://host[:port=8080]) tuples

    if file then should be a path to an image
    if pvs than should be address to a Pychron Video Server


Convenience class for including an Instance in a View


    modified TaskWIndowLaunchAction default behaviour

    .perform() previously created a new window on every event.

    now raise the window if its available else create it


        when a hole is selected npositions defines the number of
        total positions to apply the current information i.e identifier


    Used to add experiments and runs to the database.
    Used in conjunction with ExperimentPlugin


ExperimentExecutor coordinates execution of an experiment queue


used by ExperimentEditor when it validates its queue before saving


    Collector class for doing multi-collection, i.e. measuring multiple intensities simultaneously.

    ``MulticCollector`` and ``PeakHopCollector`` conceptually very similar and potentially could be merged and simplified.
    MultiCollection is a simple case of PeakHopCollection in which only one peak hop is made at the beginning.


Base class for ``Collector`` objects. Provides logic for iterative measurement.


    Collector class for doing a peak hop measurement. Measure one or more intensities at given mass for ncounts then
    jump magnet to next new mass.


    this class is used to as a simple container and factory for
    an AutomatedRun. the AutomatedRun does the actual work. ie extraction and measurement


    Save automated run data to file and database(s)

    #. save meta data to the local_lab database. This keeps a local record of all analyses run on the local system
    #. save data to an HDF5 file using a ``H5DataManager``
    #. use the ``Datahub`` to save data to databases


    The ``AutomatedRun`` object is used to execute automated analyses.

    It mostly delegates responisbility to other objects.
    It provides an interface for ``MeasurementPyscripts``.
    All measurement script commands have a corresponding function defined here.
    A commands corresponding function is defined as py_{function_name}

    for example ``position_magnet`` calls ``AutomatedRun.py_position_magnet``

    data collection is handled by either ``MultiCollector`` or ``PeakHopCollector``

    persistence (saving to file and database) is handled by ``AutomatedRunPersister``

    An automated run is executed in four steps by the ``ExperimentExecutor``.

    #. start
    #. extraction
    #. measurement

       a. equilibration
       b. post_equilibration

    #. post_measurement

    equilibration and post_equilibration are executed concurrently with the measurement script
    this way equilibration gas can be measured.

    four pyscripts (all optional) are used to program analysis execution

    1. extraction
    2. measurement
    3. post_equilibration
    4. post_measurement

    four types of conditionals are available

    1. termination_conditionals
    2. truncation_conditionals
    3. action_conditionals
    4. cancelation_conditionals


    stops the current measurement and continues to next step in pyscript.
    If more measure calls are made use abbreviated_count_ratio to reduce
    the number of counts. for example of abbreviated_count_ratio = 0.5 and
    the original baseline counts = 100, only 50 counts will be made for a truncated
    run.


    Stop the current analysis immediately. Don't save to database.
    Continue to next run in experiment queue


    Executes a specified action. The action string is executed as pyscript snippet. actions
    therefore may be any valid measuremnt pyscript code. for example::

        # call a gosub
        gosub("someGoSub")

        # open a valve
        open("V")


use to modify the queue. for example if blank to large run another blank.


    base class for mapping between two data sources
    use this to fix/change run info on import

    fix typos
    e.g change Mina Bluff > Minna Bluff


    this label repositions itself if doesn't fit within the
    its component bounds.


wxPython editor factory for Enable components.


    Base node for all nodes that need access to a DVC instance or BrowserModel for
    retrieving analyses


Manager to interface with the UHV and HV pneumatic valves


    Manager for interacting with the extraction line
    contains reference to valve manager, gauge manager and laser manager


the additional volume when a valve is open


    qtegra_monitor.cfg

    [General]
    name=Jan
    [Communications]
    type=ethernet
    host=localhost
    port=1069
    [Parameters]
    manometer=MKS 1000

    dashboard.yaml
    - name: JanMonitor
      enabled: True
      device: qtegra_monitor
      values:
        - name: JanTrapCurrent
          func: get_trap_current
          enabled: True
          period: on_change
        - name: JanEmission
          func: get_emission
          enabled: True
          period: on_change
        - name: JanDecabinTemp
          func: get_decabin_temperature
          enabled: True
          period: on_change


    http://www.omega.com/Manuals/manualpdf/M3861.pdf

    iServer MicroServer

    tested with iTHX-W


    list of coefficients. see numpy.poly1d to see exactly how coefficients used
    coefficient = 1,2,3
        ==> 1*x^2+2*x+3


    :hardware
    This is the main doc


    emissivity (Emi) = 100%;
    exposition time (t90) = min;
    clear time (tClear) = off;
    analog output (mA) = 0 ... 20 mA;
    sub range (from / to) same as temperature range
    address (Adr) = 00; baud rate (Baud) = 19200 Bd;
    temperature display (C / F) = C
    wait time (tw) at RS232 = 00;
    wait time (tw) at RS485 = 10;
    switch for serial interface (RS485 / RS232) = RS232


    def main():
        aqua = get_device('aqua_controller')
        aqua.trigger()
        waitfor(dev.is_ready)


abstract device the reads an input voltage and maps to an output value


    ADCThermocouple is a simple device that reads a voltage
    and maps it to a temperature


    a ValveFlag holds a list of valves keys (A, B, ...)

    if the flag is set then the these valves should be locked out
    from being actuated by ip addresses other than the owner of this
    flag

    valves should (can) not occur in multiple ValveFlags


    class for interfacing with an Agilent DMM - most likely a
    34401A. Since they use SCPI
    http://en.wikipedia.org/wiki/Standard_Commands_for_Programmable_Instruments
    model number is not very important?


    implement the actuator interface
    open_channel
    close_channel
    get_channel_state


Base class for motors controller by a kerr microcontroller board


    Provides access to a `Kerr Controller board <http://www.jrkerr.com/boards.html>`_.
    Used for controlling stepper motors and servos.


Base class for Kerr devices


    WatlowEZZone represents a WatlowEZZone PM PID controller.
    this class provides human readable methods for setting the modbus registers


    Abstract module for Arduino GP Actuator

    @todo: first command to arduino consistently times out

    compatible with valvebox3.pde/Messenger.h


    :::
    name: WiscAr CRio based GP Actuator
    description: Used to communicate with PyValve valves


Used to communicate with PyValve valves


Used to communicate with furnace switches


simple mapper of the Modbus commands


    this class should be used when working with multiple rs485 devices on the same port.

    it uses a simple lock and sleep cycle to avoid collision on the data lines

    when setting up the devices use device.set_scheduler to set the shared scheduler


    OPC (OLE for Process Control) communicator.
    http://openopc.sourceforge.net/


    modbus message syntax
    [Device address][function code][data][error check]


    Base Class for devices that communicate using a rs232 serial port.
    Using Keyspan serial converter is the best option for a Mac
    class is built on top of pyserial. Pyserial is used to create a handle and
    this class uses the handle to read and write.
    handles are created when a serial device is opened
    setup args are loaded using load(). this method should be overwritten to
    load specific items.


uses PyVisa as main interface to USB.


Base class for all communicators, e.g. SerialCommunicator, EthernetCommunicator


    uses PyVisa as main interface to GPIB. currently (8/27/14) need to use a 32bit python version.
    The NI488.2 framework does not work with a 64bit distribution


Communicator of UDP or TCP.


    configure DIO Mapping. need to map "power" to a channel e.g
    [DIOMapping]
    power=FIO3

    [AnalogMapping]
    intensity=0


    Series 2000 Communications Handbook
    http://buphy.bu.edu/~stein/etherm/2000cmms.pdf
    Part No HA026230

    See Modbus & EI Bisynch Addresses, Chapter 5.


needs to expose extraction line manager api to an el script


    WARNING
    the totals are not raw values and have been blank, discrimination and decay corrected already


iso = intercept - bkgrd


PyQt user interface panel for Traits-based user interfaces.


 A renderer which displays a checked-box for a True value and an
            unchecked box for a false value.


Meta class for setting flavor enums.

    Needed for calling __getitem__ on subclasses of Enum. See the discussion in
    https://github.com/SNEWS2/snewpy/pull/324#discussion_r1598833198


Configurable enumeration for different flavor schems (2, 3, 4, ... flavors).


Encapsulate flavor transformations for any FlavorScheme, enabling conversion between an input and output FlavorScheme.


Neutrino mass ordering: ``NORMAL`` or ``INVERTED``.


Mixing angles and mass differences, assuming three neutrino flavors.
    This class contains the default values used throughout SNEWPY, which are
    based on `NuFIT 6.0 <http://www.nu-fit.org>`_ results from September 2024,
    published in `JHEP 12 (2024) 216 <https://dx.doi.org/10.1007/JHEP12(2024)216>`_
    [`arXiv:2410.05380 <https://arxiv.org/abs/2410.05380>`_].


A class for four flavor neutrino mixing.
    ..Note: it is an extension of :class:`ThreeFlavorMixingParameters`, and can be constructed using it:

        >>> pars_3f = ThreeFlavorMixingParameters() #standard 3flavor mixing
        >>> pars_4f = FourFlavorMixingParameters(**pars_3f, theta14=90<<u.deg, dm41_2=1<<u.GeV**2)


A class describing energy smearing, i.e. matrix transforming flux from :math:`E_\nu` (true neutrino energy) to :math:`E_{det}` (observed or smeared energy) space


A wrapper around a given function of energy, for example interaction cross-section, or a detection efficiency.
    This helper class will perform a correct operation when multiplied to a :class:`Container` object - rate or flux.


Description of a single detection channel in the detector


A detector configuration for the rate calculation.


r"""Simple rate calculation interface.
        Computes expected rate for a detector using SNOwGLoBES data.

        Use :meth:`RateCalculator.run` method to run the simulation for specific detector and flux object.

        Input flux can either be energy differential flux :math:`F_\nu(E_i) = \frac{d N}{d_E}(E_i)` or integral flux in the energy bins :math:`N_{\nu}(E_i)`.

        If the `detector_effects=False` the result is the number of neutrino interactions :math:`N` - a product with with cross-section :math:`\sigma(E)` and the number of targets in the detector :math:`N_{tgt}`:

        .. math:: N (E_i) = N_{tgt} \cdot F_\nu(E_i)\cdot \sigma(E_i)

        If the detector effects are included, it is integrated within the energy bins and multiplied by the smearing matrix and detection efficiency to get number of interactions in energy bin:

        .. math::

            N_i = N_{tgt} \cdot \int\limits_{E_i}^{E_{i+1}}~F_\nu(E_i)~\sigma(E_i)~d E

        and this is convoluted with the detector smearing matrix :math:`M_{ij}` and efficiency :math:`\varepsilon(E)`:

        .. math::

            N^{rec}_i = \sum\limits_{j} M_{ij} \cdot N_j \cdot \varepsilon(E_i)


Enum to keep the number number of the array dimension for each axis


base class for internal use
    :noindex:


Raise an exception due to a mismatch in the MD5 checksum.


Object storing local path, remote URL (optional), and MD5 sum
    (optional) for a SNEWPY model file. If the requested file is already present
    locally, open it. Otherwise, download it from the remote URL to the desired
    local path.


Access model data. Configuration for each model is in a YAML file
    distributed with SNEWPY.


Subclass that reads models in the format used in the
    `Garching Supernova Archive <https://wwwmpa.mpa-garching.mpg.de/ccsnarchive/>`_.


Model based on the black hole formation simulation in `O'Connor & Ott (2013) <https://arxiv.org/abs/1207.1100>`_.


Model based on the black hole formation simulation in `O'Connor (2015) <https://arxiv.org/abs/1411.7058>`_.


Presupernova model based on
    `Kelly M. Patton et al. 2017 ApJ 851 6 <https://iopscience.iop.org/article/10.3847/1538-4357/aa95c4>`_

    Dataset available on Zenodo (`DOI:10.5281/zenodo.2626645 <http://doi.org/10.5281/zenodo.2626645>`_)


Presupernova model based on
    `Chinami Kato et al. 2017 ApJ 848 48 <https://iopscience.iop.org/article/10.3847/1538-4357/aa8b72>`_

    Dataset available on `Zenodo <https://zenodo.org/records/3768052>`__


Presupernova model based on
    `Yoshida et al. (2016), PRD 93, 123012 <https://doi.org/10.1103/PhysRevD.93.123012>`_

    Dataset available on `Zenodo <https://zenodo.org/records/3778014>`__


Model based on simulations from `Fischer et al. (2020) <https://arxiv.org/abs/1804.10890>`


Model based on simulations from Sukhbold et al., ApJ 821:38,2016. Models were shared privately by email.


Model based on 3D simulations from `Tamborra et al., PRD 90:045032, 2014 <https://arxiv.org/abs/1406.0006>`_.
    Data files are from the `Garching Supernova Archive`_.


Model based on simulations from `Bollig et al. (2016) <https://arxiv.org/abs/1508.00785>`_.
    Models were taken, with permission, from the `Garching Supernova Archive`_.


Model based on SASI-dominated simulations from `Walk et al.,
    PRD 98:123001, 2018 <https://arxiv.org/abs/1807.02366>`_. Data files are from
    the `Garching Supernova Archive`_.


Model based on SASI-dominated simulations from `Walk et al.,
    PRD 101:123013, 2019 <https://arxiv.org/abs/1910.12971>`_. Data files are
    from the `Garching Supernova Archive`_.


Model based on the hadron-quark phse transition models from `Zha et al. 2021 <https://arxiv.org/abs/2103.02268>`_.


Model based on simulations from Warren et al., ApJ 898:139, 2020.
    Neutrino fluxes available at https://doi.org/10.5281/zenodo.3667908.


Model based on simulations from `Kuroda et al. (2020) <https://arxiv.org/abs/2009.07733>`_.


Model based on 3D simulations from D. Vartanyan, A. Burrows, D. Radice, M.  A. Skinner and J. Dolence, MNRAS 482(1):351, 2019.
       Data available at https://www.astro.princeton.edu/~burrows/nu-emissions.3d/


Model based on 2D simulations of 100 progenitors from Tianshu Wang, David Vartanyan, Adam Burrows, and Matthew S.B. Coleman, MNRAS 517:543, 2022.
       Data available at https://www.astro.princeton.edu/~burrows/nu-emissions.2d.large/


Model based on 2D simulations with axionlike particles, K. Mori, T.  Takiwaki, K. Kotake and S. Horiuchi, Phys. Rev. D 108:063027, 2023. All models are based on the non-rotating 20 M_sun solar metallicity progenitor model from S.E. Woolsey and A. Heger, Phys. Rep. 442:269, 2007. Data from private communication.


A model that does not inherit from SupernovaModel (yet) and imports a group of SNOwGLoBES files.


An analytical model calculating spectra given total luminosity,
    average energy, and rms or pinch, for each species.


Set up a presupernova model, based on
    [A. Odrzywolek and A. Heger, Acta Phys. Polon. B 41 (2010) 1611.]


Set up a presupernova model based on
    [Kelly M. Patton et al 2017 ApJ 851 6,
     https://doi.org/10.5281/zenodo.2598709]


Set up a presupernova model based on
    [Chinami Kato et al 2017 ApJ 848 48]


Set up a presupernova model based on
    [Yoshida et al. (2016), PRD 93, 123012.]


Base class defining an interface to a supernova model.


Subclass that contains spectra/luminosity pinches


A class to describe the model parameter: it's range of allowed values, name, description etc.


A class to describe all possible combinations of parameter values


Class defining a supernova model with a cooling tail extension.


Base class for all transformations in SN


Adiabatic MSW effect.


The MSW effect using a density profile and electron
       fraction provided by the user. Uses the SNOSHEWS module.


A placeholder class for the density and electron fraction profiles. Currently SNOSHEWS
        reads the profiles from files but that might change in the future.


A four-neutrino mixing prescription. The assumptions used are that:

    1. the fourth neutrino mass is the heaviest but not so large
       that the electron-sterile resonances are inside the neutrinosphere;
    2. the outer electron-sterile MSW resonance is adiabatic;
    3. the inner electron-sterile MSW resonance (where the electron
       fraction = 1/3) is non-adiabatic.

    For further insight see, for example, Esmaili, Peres, and Serpico,
        Phys. Rev. D 90, 033013 (2014).


A four-neutrino mixing prescription. The assumptions used are that:

    1. the fourth neutrino mass is the heaviest but not so large
       that the electron-sterile resonances are inside the neutrinosphere;
    2. the outer electron-sterile MSW resonance is non-adiabatic;
    3. the inner electron-sterile MSW resonance (where the electron
       fraction = 1/3) is non-adiabatic.

    For further insight see, for example, Esmaili, Peres, and Serpico,
        Phys. Rev. D 90, 033013 (2014).


Survival probabilities for no oscillation case.


Survival probabilities for the case when the electron flavors
       are half exchanged with the mu flavors and the half with the tau flavors.


Equal mixing of all threen eutrino matter states and antineutrino matter states


Quantum Decoherence, where propagation in vacuum leads to equipartition
    of states. For a description and typical parameters, see M. V. dos Santos et al.,
    2023, arXiv:2306.17591.


Generic interface to compute neutrino and antineutrino survival probability.


r"""This class calculates the probability matrix :math:`P_{\beta\alpha}` of the :math:`\nu_\alpha\to\nu_\beta` flavor transition as multiplication of :math:`P^{SN}` transformation in SN, :math:`P^{Vac}` transformation in vacuum and :math:`P^{Earth}` transformation in Earth:

    .. math::

        P_{\beta\alpha} = \sum\limits_{i,j}P^{Earth}_{\beta j} \cdot P^{Vac}_{ji} \cdot P^{SN}_{i\alpha}


Base class for custom errors related to the running of Toyz


 Wraps an ``iterable`` to behave like ``Progressbar``, but without
    producing output.


Just what is says on the tin, a column of values.


    This class is used to expand loops.
    It creates a list of list in self.groups.


The TmpFile objets are designed to be used for temporary files.
    It ensures that the file is unlinked when the object is
    out-of-scope (with __del__).

    Parameters
    ----------
    path : str
        Actual path of the file.


    A context manager that temporarily sets environment variables.

    Usage:
    >>> import os
    >>> with TmpEnv(CLIMETLAB_TESTS_FOO='123', CLIMETLAB_TESTS_BAR='456'):
    ...     print(os.environ['CLIMETLAB_TESTS_FOO'])
    ...     print(os.environ['CLIMETLAB_TESTS_BAR'])
    123
    456
    >>> print(os.environ.get('CLIMETLAB_TESTS_FOO'))
    None


Mother class to create a dataset object.


Dataset class to defined datasets from a YAML file.

    When inheriting, self._src and self._args must be defined before calling __init__.
    This is performed in :py:class:`DatasetLoader`.


This source use a MARS request to get the data for accumulated fields
    following the same logic as what has been done when storing ERA5 in the
    Climate Data Store (CDS).
    The date+time provided to this source refers to the valid datetime of the data,
    these date+time are used to compute the date+time+step that are actually used to perform the mars request.

    Note 1 : as all these are lists, there are potentially to many fields requested to MARS.
          This is taken care by the final ".sel" .
    Note 2 : There are no overlap due to the way the date+time+step are computed


Abstract class, INDEX_CLASS must be implemented


A class so that ZipInfo has the same interface as TarInfo


This class delays parsing the directory for the list of files
    until the iterator is actually used (calling __iter__)


Class that wraps a xarray dataset to provide caching


    Lightweight wrapper class utilized in granule preprocessing to simply comparisons between
    different variables from different granule sets

    Attributes
    ----------
    name: str
        name of the variable
    dim_order: list
        list of dimension names in order
    datatype: numpy.dtype
        the numpy datatype for the data held in the variable
    group_path: str
        Unix-like group path to the variable
    fill_value: object
        Value used to fill missing/empty values in variable's data


Concise Exception class for custom error messages to see in harmony api calls.


    A harmony-service-lib wrapper around the Concise module. This wrapper does
    not support Harmony calls that do not have STAC catalogs as support for
    this behavior is being depreciated in harmony-service-lib


A base class for transforming between two sets of parameters.