metrolopy package¶
Subpackages¶
Submodules¶
metrolopy.budget module¶
This module defines the Budget object which displays a table listing the uncertainty contributions to a gummy.
- class metrolopy.budget.Budget(y, xlist, uunit=None, units_on_values=None, sort=True, solidus=None, mulsep=None, slashaxis=None, columns=None, column_names=None, xnames=None, yname=None, show_subtotals=True, show_expanded_u=None, description=None, description_math_mode=False, custom=None, custom_heading=None, custom_math_mode=False, show_s=None, show_d=None, show_c=None, css=None, k=None, p=None, sim=False)¶
Bases:
metrolopy.printing.PrettyPrinter
A class that facilitates the creation of uncertainty budget tables.
To display the table use the Budget.html or Budget.latex methods in a console or notebook that supports this type of output or the python built-in function to get a unicode table.
The Budget.tohtml and Budget.tolatex methods can be used to get strings with the html or latex code.
The Budget.df property can be used to retrieve a pandas DataFrame with the table. Also Budget.df_str, Budget.df_html and Budget.df_latex return DataFrames with formatted strings as entries rather than numerical values.
- Parameters
y (gummy) – the dependant variable
xlist (array_like of gummy) – The independent variables. Warnings will be generated if the gummys in this list over determine y (that is if not all variables in this list can be treated as independent variables) or under determine y (that is if some variables contributing to the uncertainty in y are missing).
uunit (str or Unit, optional) – Unit to use to express the uncertainties. This useful if you wish to express all uncertainties as relative uncertainty unit (e.g. %).
k, p (float, optional) – k or p values for the expanded uncertainty; do not specify both k and p; if neither are specified the the k and p values of y are used
sort (bool, optional) – Whether or not to sort the gummys in xlist by significance.
columns (list of str or None, optional) – Allows the user to select the columns (and ordering of the columns) for display. The available columns are:
“component” or “name”: the names of the gummy, displayed by default
- “description”: description given in the description parameter list,
displayed by default if the description parameter is not None
“unit”: the unit of the gummy, displayed by default
“value”: the x value of the gummy, displayed by default
- “u” or “uncertainty”: The uncertainty of the gummy. This is the
standard uncertainty except possible in the last row where an expanded uncertainty is displayed. This column is displayed by default.
- “dof”: the degrees of freedom for the uncertainty, displayed by default
if any uncertainty has finite degrees of freedom
- “type”: the uncertainty type, displayed by default if any gummy has
a type defined
- “s” or “significance”: the sensitivity coefficient (below) multiplied
by the standard uncertainty, displayed by default
- “d”, “derivative” or “partial”: the partial derivative of the y gummy
with resect to the gummy in that row
“c” or “sensitivity coefficient”: the absolute value of “d”
- “custom”: value given in the custom parameter list, displayed by default
if the custom parameter is not None
The columns displayed can also be set with the columns property.
column_names (dict or None, optional) – Names to display as column headers, if this is None then the default names are used. The dictionary should use as keys any of the column names listed above in the columns parameter description and as values the desired heading for this column. The column names can also be set with the column_names property.
show_subtotals (bool, optional) – If any uncertainty types are defined, the combined standard uncertainty for each type is displayed in the table. This can also be changed by setting the show_subtotals attribute. The default is True.
show_expanded_u (bool or None, optional) – Whether or not to display the expanded uncertainty in the last row. If this is None, then the expanded uncertainty is displayed if
y.k != 1
. This can also be changed by setting the show_expanded_u attribute.show_s (bool, optional) – Whether or not to show the significance column. This is ignored if the columns parameter is not None. The default can be changed by setting the attribute class attribute Budget.show_s. The default value is True.
show_d (bool, optional) – Whether or not to show the partial derivatives column. This is ignored if columns is not None. The default can be changed by setting the attribute class attribute Budget.show_d. The default is True.
show_c (bool, optional) – Whether or not to show the sensitivity coefficient column. This is ignored if columns is not None. The default can be changed by setting the attribute class attribute Budget.show_c. Teh default value is False
units_on_values (bool or None) –
- If this is True, units are shown in the value and u columns and if False
the units are in a separate column. If None then the units are in a separate column unless any gummy in xlist or y has a uunit defined.
sim (bool, optional) – If True, the combined uncertainty and partial derivatives will be calculated using Monte-Carlo data. The default is False
css (str or None, optional) – A css header to be used when displaying the table in HTML format. If this is None then Budget.default_css will be used.
description (list of str or None, optional) – An optional column of descriptions to be printed in the table. This should be a description for y then for each x, and followed, optionally, by subtotal and expanded uncertainty descriptions.
description_math_mode (bool, optional) – If this is False, then when using a LaTeX format, the description is put in normal text mode rather than math mode. The default is False
custom (list of str or None, optional) – An optional column of additional information to be printed in the table. This should be a value for y then for each x, and followed, optionally, by subtotal and expanded uncertainty values.
custom_heading (str or None, optional) – A heading for the custom column.
custom_math_mode (bool) – If this is False, then when using a LaTeX format, the custom value is put in normal text mode rather than math mode. The default value is False.
solidus, mulsep, slashaxis – see gummy.solidus, gummy.mulsep and gummy.slashaxis
- property column_names¶
dict
Names to display as column headers. The dictionary should use as keys any of the column names listed above in the columns parameter description and as values the desired heading for this column.
- property columns¶
list of str or None
Allows the user to select the columns (and ordering of the columns) for display. The available columns are:
“component” or “name”: the names of the gummy, displayed by default
- “description”: description given in the description parameter list,
displayed by default if the description parameter is not None
“unit”: the unit of the gummy, displayed by default
“value”: the x value of the gummy, displayed by default
- “u” or “uncertainty”: The uncertainty of the gummy. This is the
standard uncertainty except possible in the last row where an expanded uncertainty is displayed. This column is displayed by default.
- “dof”: the degrees of freedom for the uncertainty, displayed by default
if any uncertainty has finite degrees of freedom
- “type”: the uncertainty type, displayed by default if any gummy has
a type defined
- “s” or “significance”: the sensitivity coefficient (below) multiplied
by the standard uncertainty, displayed by default
- “d”, “derivative” or “partial”: the partial derivative of the y gummy
with resect to the gummy in that row
“c” or “sensitivity coefficient”: the absolute value of “d”
- “custom”: value given in the custom parameter list, displayed by default
if the custom parameter is not None
- default_column_names = None¶
- default_columns = None¶
- default_css = '\n.budget_table {\n display: table;\n}\n \n.budget_row {\n display: table-row;\n}\n\n.budget_header_row {\n display: table-row;\n font-weight: bold;\n}\n\n.budget_first_col_header_cell\n{\n display: table-cell;\n text-align: center;\n border-bottom: solid;\n border-width: thin;\n padding-left: 5px;\n padding-right: 5px;\n}\n\n.budget_header_cell {\n display: table-cell;\n text-align: center;\n border-bottom: solid;\n border-width: thin;\n padding-left: 5px;\n padding-right: 5px;\n \n}\n\n.budget_first_col_x_cell {\n display: table-cell;\n text-align: center;\n padding-left: 5px;\n padding-right: 5px;\n min-width: 8ex;\n}\n\n.budget_x_cell {\n display: table-cell;\n text-align: center;\n padding-left: 5px;\n padding-right: 5px;\n min-width: 8ex;\n}\n'¶
- property df¶
read-only
Returns a Panda’s DataFrame with the the budget table.
- property df_html¶
read-only
Returns a Panda’s DataFrame with the the budget table, with entries displayed using HTML.
- property df_latex¶
read-only
Returns a Panda’s DataFrame with the the budget table, with all entries displayed using LaTeX.
- property df_str¶
read-only
Returns a Panda’s DataFrame with the the budget table, with all values displayed as strings.
- property k¶
Gets or sets the k value for the expanded uncertainty of y.
- property p¶
Gets or sets the p value for the expanded uncertainty of y.
- show_c = True¶
- show_d = False¶
- show_s = True¶
- tostring(fmt='unicode')¶
Returns a string representation of the budget table
- Parameters
fmt ({‘unicode’,’html’,’latex’,’ascii’}, optional) – encoding for the output. The default is ‘unicode’.
- units_on_values = None¶
metrolopy.dfunc module¶
Class Dfunc is an abstract base class inherited by ummy and immy to provide support for numpy ufunc functions.
- class metrolopy.dfunc.Dfunc¶
Bases:
object
Class Dfunc is an abstract base class that provides some support for numpy broadcasting for functions and operators. An inheriting class must implement the _apply(self,function,derivative,*args), _napply(self,function,*args), and tofloat(self) methods, as well as _add(x), _radd(x), _sub(x), …
- classmethod apply(function, derivative, *args)¶
A classmethod that applies a function to one or more gummy or jummy objects propagating the uncertainty.
- Parameters
function (function) – The the function to be applied. For gummy.apply, ‘function’ should take one or more float arguments and return a float value or float array. For jummy.apply, ‘function’ may also take and return complex values.
- derivative (function) – The name of a second function that gives the derivatives
with respect to the arguments of function. derivative should take an equal number of arguments as function. If function takes one argument derivative should return a float and if function takes more than one argument then derivative should return a tuple, list or array of floats that contains the derivatives with respect to each argument. In the case of jummy.apply, the derivatives with respect to each argument may be real or complex values, in which case function is assumed to be holomorphic. Or the derivative may be a 2 x 2 matrix of the form:
- [[ du/dx, du/dy ],
[ dv/dx, dv/dy ]]
where function(x + j*y) = u + j*v.
*args (gummy, jummy, or float) – One or more arguments to which function will be applied. These arguments need not all be Dfunc objects; arguments such as floats will be taken to be constants with no uncertainty. They may also be numpy ndarrays in which case the usual numpy broadcasting rules apply.
- Returns
If none of the arguments are gummy or jummy then the return value is the same type as the return value of function. Otherwise gummy.apply returns a gummy and jummy.apply returns either a gummy or a jummy depending on whether function has a float or a complex return value.
- Return type
gummy, jummy
Examples
>>> import numpy as np >>> x = gummy(0.678,u=0.077) >>> gummy.apply(np.sin,np.cos,x) 0.627 +/- 0.060
>>> x = gummy(1.22,u=0.44) >>> y = gummy(3.44,u=0.67) >>> def dhypot(x,y): ... return (x1/sqrt(x1**2 + x2**2),x2/np.sqrt(x1**2 + x2**2)) >>> gummy.apply(np.hypot,dhypot,x,y) 3.65 +/- 0.65
- classmethod napply(function, *args)¶
gummy.napply(function, arg1, arg2, …) and jummy.napply(function, arg1, arg2, …)
A classmethod that applies a function to one or more gummy or jummy objects propagating the uncertainty. This method is similar to apply except that the derivatives are computed numerically so a derivative function does not need to be supplied.
- Parameters
function (function) – The the function to be applied. For gummy.apply, ‘function’ should take one or more float arguments and return a float value r float array. For jummy.apply, ‘function’ may also take and return complex values.
*args (gummy, jummy, or float) – One or more arguments to which function will be applied. These arguments need not all be Dfunc objects; arguments such as floats will be taken to be constants with no uncertainty. They may also be numpy ndarrays in which case the usual numpy broadcasting rules apply.
- Returns
If none of the arguments are gummy or jummy then the return value is the same type as the return value of function. Otherwise gummy.apply returns a gummy and jummy.apply returns either a gummy or a jummy depending on whether function has a float or a complex return value.
- Return type
gummy, jummy
Examples
>>> import numpy as np >>> x = gummy(0.678,u=0.077) >>> gummy.napply(np.sin,x) 0.627 +/- 0.060
>>> x = gummy(1.22,u=0.44) >>> y = gummy(3.44,u=0.67) >>> gummy.napply(np.hypot,x,y) 3.65 +/- 0.65
- tofloat()¶
metrolopy.distributions module¶
This module contains the classed that represent distributions for Monte Carlo calculations.
- class metrolopy.distributions.ArcSinDist(center=None, half_width=None, lower_limit=None, upper_limit=None)¶
Bases:
metrolopy.distributions.Distribution
- random(n=None)¶
Override this method in a derived class
Return a numpy array of n values drawn from the distribution. If n is None then a single scalar value should be returned.
- u()¶
Override this method in a derived class
- Return a scalar “standard uncertainty” of the distribution (usually
the standard deviation). This is used to get the u value of a gummy defined with the distribution.
- x()¶
Override this method in a derived class
Return a scalar “center” of the distribution. This is used to get the x value of a gummy defined with the distribution.
- class metrolopy.distributions.BinomialDist(n, p)¶
Bases:
metrolopy.distributions.Distribution
- random(n=None)¶
Override this method in a derived class
Return a numpy array of n values drawn from the distribution. If n is None then a single scalar value should be returned.
- u()¶
Override this method in a derived class
- Return a scalar “standard uncertainty” of the distribution (usually
the standard deviation). This is used to get the u value of a gummy defined with the distribution.
- x()¶
Override this method in a derived class
Return a scalar “center” of the distribution. This is used to get the x value of a gummy defined with the distribution.
- class metrolopy.distributions.Convolution(func, *args)¶
Bases:
metrolopy.distributions.Distribution
- isindependent = False¶
- random(n=None)¶
Override this method in a derived class
Return a numpy array of n values drawn from the distribution. If n is None then a single scalar value should be returned.
- x()¶
Override this method in a derived class
Return a scalar “center” of the distribution. This is used to get the x value of a gummy defined with the distribution.
- class metrolopy.distributions.CurvlinearTrapDist(center=None, half_width=None, limit_half_range=None, lower_limit=None, upper_limit=None)¶
Bases:
metrolopy.distributions.Distribution
- random(n=None)¶
Override this method in a derived class
Return a numpy array of n values drawn from the distribution. If n is None then a single scalar value should be returned.
- u()¶
Override this method in a derived class
- Return a scalar “standard uncertainty” of the distribution (usually
the standard deviation). This is used to get the u value of a gummy defined with the distribution.
- x()¶
Override this method in a derived class
Return a scalar “center” of the distribution. This is used to get the x value of a gummy defined with the distribution.
- class metrolopy.distributions.Distribution¶
Bases:
object
Abstract base class for distributions used for Monte-Carlo uncertainty propagation.
In a derived class define the following methods:
- random(n=None): Return a numpy array of n values drawn from the distribution.
If n is None then a single scalar value should be returned. Preferably use, as a random number generator, the numpy.RandomState object accessed with the Distribution.random_state static method.
- x(): A scalar “center” of the distribution. This is used to get the x value
of a gummy defined with the distribution.
- u(): A scalar “standard uncertainty” of the distribution (usually the standard
deviation). This is used to get the u value of a gummy defined with the distribution.
- simdata¶
Simulated data following a call from the simulate static method.
- Type
numpy.ndarray or None
- isindependent¶
False if the class is a Convolution, True otherwise
- Type
bool
Example
>>> class ChiSquaredDist(Distribution): ... def __init__(self,dof): ... self.dof = dof ... ... def random(self,n=None): ... return Distribution.random_state().chisquare(self.dof,n) ... ... def x(self): ... return self.dof ... ... def u(self): ... return 2*self.dof
- static apply(f, *d)¶
Applies a function f to distribution(s) d1, d2, …, f`(`d1,`d2`,…) and returns a distribution resulting from the convolution.
- Parameters
f (function) – Any function that takes an appropriate number of scalar values and returns a scalar.
d1, d2, … (Distribution or scalar) – the distributions to be used as arguments to f. Fixed values (e.g. float) can also be used for some or all arguments.
- Returns
if any of d1, d2, … is a Distribution, f(d1,d2,…) otherwise
- Return type
Convolution or float
- ci(p)¶
Returns the shortest interval that contains the fraction p of the simulated data values.
- Returns
a tuple containing the lower and upper limits of the interval
- Return type
tuple of float
- Raises
NoSimulatedDataError – if no simulated data is available from a call to Distribution.simulate.
See also
- cisym(p)¶
Returns the interval that contains the fraction p of the simulated data values and with an equal number of values below the lower limit of the interval and above the upper limit of the interval.
- Returns
a tuple containing the lower and upper limits of the interval
- Return type
tuple of float
- Raises
NoSimulatedDataError – if no simulated data is available from a call to Distribution.simulate.
See also
- clear()¶
Clears the simulated data.
- static covplot(x, y, fmt='ko', xlabel=None, ylabel=None, title=None, hold=False, **kwds)¶
Plots the Distribution x versus the Distribution y
- Parameters
x, y (Distribution) – the distributions to be plotted
fmt (str, optional) – Format parameter passed to pyplot.plot(), the default is ‘ko’
xlabel (str or None) – a label for the plot x-axis, the default is None
ylabel (str or None) – a label for the plot y-axis, the default is None
title (str or None) – a title for the histogram, the default is None
hold (bool i) – If this is False, pyplot.show() will be called before the method exits. The default is False
kwds – additional key words that will be passed to pyplot.plot()
- Raises
NoSimulatedDataError – if no simulated data is available from a call to Distribution.simulate for x and y.
- covsim(d)¶
Returns the covariance between this Distribution instance and another Distribution d.
- Raises
NoSimulatedDataError – if no simulated data is available from a call to Distribution.simulate for both self and d.
- static covsim_matrix(*d)¶
Returns the variance-covariance matrix of the Distributions d1, d2, …
- Raises
NoSimulatedDataError – if no simulated data is available from a call to Distribution.simulate for any of d1, d2, …
- hist(hold=False, xlabel=None, ylabel='$ \\mathrm{probability\\:density} $', title=None, **kwds)¶
Generates a histogram from the simulated data.
- Parameters
hold (bool, optional) – If this is False, pyplot.show() will be called before the method exits. The default is False
xlabel (str or None, optional) – a label for the histogram horizontal axis, the default is None
ylabel (str or None, optional) – a label for the histogram vertical axis, the default is ‘probability density’
title (str or None) – a title for the histogram, the default is None
kwds – additional key words that will be passed to the pyplot.hist method that actually created the histogram
- Raises
NoSimulatedDataError – if no simulated data is available from a call to Distribution.simulate.
- isindependent = True¶
- property mean¶
Returns the mean of the simulated data.
- Raises
A NoSimulatedDataError will be raised if no simulated data is available –
from a call to Distribution.simulate(). –
- random(n=None)¶
Override this method in a derived class
Return a numpy array of n values drawn from the distribution. If n is None then a single scalar value should be returned.
- static random_state()¶
Returns the numpy.random.RandomState object shared by all distributions.
- static set_seed(seed)¶
Sets the seed of the numpy.random.RandomState object shared by all distributions.
- simdata = None¶
- property simsorted¶
numpy.ndarray, read-only
Returns a sorted numpy array containing the simulated data values.
- Raises
A NoSimulatedDataError will be raised if no simulated data is available –
from a call to Distribution.simulate(). –
- static simulate(distributions, n=100000, ufrom=None)¶
Generates simulated data for the desired distributions.
- Parameters
distributions (list of Distribution) – Each Distribution in the list will have the simulated data available in the simdata attribute. Data will be cleared from all Distribution instances not in the list.
n (int > 0, optional) – The number of samples to generate for each distribution. The default is 100000
ufrom (list of Distributions or None) – If this parameter is not None, then only variables represented by distributions in this list will be allowed to vary. All other variables will be held fixed at the distribution x value.
- property stdev¶
Returns the standard deviation of the simulated data.
- Raises
A NoSimulatedDataError will be raised if no simulated data is available –
from a call to Distribution.simulate(). –
- u()¶
Override this method in a derived class
- Return a scalar “standard uncertainty” of the distribution (usually
the standard deviation). This is used to get the u value of a gummy defined with the distribution.
- x()¶
Override this method in a derived class
Return a scalar “center” of the distribution. This is used to get the x value of a gummy defined with the distribution.
- class metrolopy.distributions.ExponentialDist(scale=None, rate=None)¶
Bases:
metrolopy.distributions.Distribution
- random(n=None)¶
Override this method in a derived class
Return a numpy array of n values drawn from the distribution. If n is None then a single scalar value should be returned.
- u()¶
Override this method in a derived class
- Return a scalar “standard uncertainty” of the distribution (usually
the standard deviation). This is used to get the u value of a gummy defined with the distribution.
- x()¶
Override this method in a derived class
Return a scalar “center” of the distribution. This is used to get the x value of a gummy defined with the distribution.
- class metrolopy.distributions.GammaDist(shape, scale)¶
Bases:
metrolopy.distributions.Distribution
- random(n=None)¶
Override this method in a derived class
Return a numpy array of n values drawn from the distribution. If n is None then a single scalar value should be returned.
- u()¶
Override this method in a derived class
- Return a scalar “standard uncertainty” of the distribution (usually
the standard deviation). This is used to get the u value of a gummy defined with the distribution.
- x()¶
Override this method in a derived class
Return a scalar “center” of the distribution. This is used to get the x value of a gummy defined with the distribution.
- class metrolopy.distributions.LaplaceDist(x, scale)¶
Bases:
metrolopy.distributions.Distribution
- random(n=None)¶
Override this method in a derived class
Return a numpy array of n values drawn from the distribution. If n is None then a single scalar value should be returned.
- u()¶
Override this method in a derived class
- Return a scalar “standard uncertainty” of the distribution (usually
the standard deviation). This is used to get the u value of a gummy defined with the distribution.
- x()¶
Override this method in a derived class
Return a scalar “center” of the distribution. This is used to get the x value of a gummy defined with the distribution.
- class metrolopy.distributions.LogNormalDist(mu, sigma)¶
Bases:
metrolopy.distributions.Distribution
- random(n=None)¶
Override this method in a derived class
Return a numpy array of n values drawn from the distribution. If n is None then a single scalar value should be returned.
- u()¶
Override this method in a derived class
- Return a scalar “standard uncertainty” of the distribution (usually
the standard deviation). This is used to get the u value of a gummy defined with the distribution.
- x()¶
Override this method in a derived class
Return a scalar “center” of the distribution. This is used to get the x value of a gummy defined with the distribution.
- class metrolopy.distributions.MultiNormalDist(mean, cov)¶
Bases:
metrolopy.distributions.MultivariateDistribution
- property cov¶
- u()¶
- x()¶
- class metrolopy.distributions.MultiTDist(mean, cov, dof)¶
Bases:
metrolopy.distributions.MultivariateDistribution
- property cov¶
- u()¶
- x()¶
- class metrolopy.distributions.MultiTElement(parent, index, dof)¶
- class metrolopy.distributions.MultivariateDistribution(nd)¶
Bases:
object
- clear()¶
- property cov¶
- u()¶
- x()¶
- class metrolopy.distributions.MultivariateElement(parent, index)¶
Bases:
metrolopy.distributions.Distribution
- clear()¶
Clears the simulated data.
- cov(d)¶
- random(n=None)¶
Override this method in a derived class
Return a numpy array of n values drawn from the distribution. If n is None then a single scalar value should be returned.
- u()¶
Override this method in a derived class
- Return a scalar “standard uncertainty” of the distribution (usually
the standard deviation). This is used to get the u value of a gummy defined with the distribution.
- x()¶
Override this method in a derived class
Return a scalar “center” of the distribution. This is used to get the x value of a gummy defined with the distribution.
- class metrolopy.distributions.NormalDist(x, s)¶
Bases:
metrolopy.distributions.Distribution
- random(n=None)¶
Override this method in a derived class
Return a numpy array of n values drawn from the distribution. If n is None then a single scalar value should be returned.
- u()¶
Override this method in a derived class
- Return a scalar “standard uncertainty” of the distribution (usually
the standard deviation). This is used to get the u value of a gummy defined with the distribution.
- x()¶
Override this method in a derived class
Return a scalar “center” of the distribution. This is used to get the x value of a gummy defined with the distribution.
- class metrolopy.distributions.PoissonDist(lam)¶
Bases:
metrolopy.distributions.Distribution
- random(n=None)¶
Override this method in a derived class
Return a numpy array of n values drawn from the distribution. If n is None then a single scalar value should be returned.
- u()¶
Override this method in a derived class
- Return a scalar “standard uncertainty” of the distribution (usually
the standard deviation). This is used to get the u value of a gummy defined with the distribution.
- x()¶
Override this method in a derived class
Return a scalar “center” of the distribution. This is used to get the x value of a gummy defined with the distribution.
- class metrolopy.distributions.TDist(x, s, dof)¶
Bases:
metrolopy.distributions.Distribution
- bayesian_default = False¶
- random(n=None)¶
Override this method in a derived class
Return a numpy array of n values drawn from the distribution. If n is None then a single scalar value should be returned.
- u()¶
Override this method in a derived class
- Return a scalar “standard uncertainty” of the distribution (usually
the standard deviation). This is used to get the u value of a gummy defined with the distribution.
- x()¶
Override this method in a derived class
Return a scalar “center” of the distribution. This is used to get the x value of a gummy defined with the distribution.
- class metrolopy.distributions.TrapezoidalDist(lower_limit, upper_limit, top_to_base_ratio)¶
Bases:
metrolopy.distributions.Distribution
- random(n=None)¶
Override this method in a derived class
Return a numpy array of n values drawn from the distribution. If n is None then a single scalar value should be returned.
- u()¶
Override this method in a derived class
- Return a scalar “standard uncertainty” of the distribution (usually
the standard deviation). This is used to get the u value of a gummy defined with the distribution.
- x()¶
Override this method in a derived class
Return a scalar “center” of the distribution. This is used to get the x value of a gummy defined with the distribution.
- class metrolopy.distributions.TriangularDist(mode, half_width=None, left_width=None, right_width=None, lower_limit=None, upper_limit=None)¶
Bases:
metrolopy.distributions.Distribution
- random(n=None)¶
Override this method in a derived class
Return a numpy array of n values drawn from the distribution. If n is None then a single scalar value should be returned.
- u()¶
Override this method in a derived class
- Return a scalar “standard uncertainty” of the distribution (usually
the standard deviation). This is used to get the u value of a gummy defined with the distribution.
- x()¶
Override this method in a derived class
Return a scalar “center” of the distribution. This is used to get the x value of a gummy defined with the distribution.
- class metrolopy.distributions.UniformDist(center=None, half_width=None, lower_limit=None, upper_limit=None)¶
Bases:
metrolopy.distributions.Distribution
- random(n=None)¶
Override this method in a derived class
Return a numpy array of n values drawn from the distribution. If n is None then a single scalar value should be returned.
- u()¶
Override this method in a derived class
- Return a scalar “standard uncertainty” of the distribution (usually
the standard deviation). This is used to get the u value of a gummy defined with the distribution.
- x()¶
Override this method in a derived class
Return a scalar “center” of the distribution. This is used to get the x value of a gummy defined with the distribution.
- class metrolopy.distributions.WeibullDist(shape, scale)¶
Bases:
metrolopy.distributions.Distribution
- random(n=None)¶
Override this method in a derived class
Return a numpy array of n values drawn from the distribution. If n is None then a single scalar value should be returned.
- u()¶
Override this method in a derived class
- Return a scalar “standard uncertainty” of the distribution (usually
the standard deviation). This is used to get the u value of a gummy defined with the distribution.
- x()¶
Override this method in a derived class
Return a scalar “center” of the distribution. This is used to get the x value of a gummy defined with the distribution.
metrolopy.exceptions module¶
- exception metrolopy.exceptions.BudgetWarning¶
Bases:
Warning
- exception metrolopy.exceptions.CircularUnitConversionError¶
- exception metrolopy.exceptions.ConstantNotFoundError¶
Bases:
ValueError
- exception metrolopy.exceptions.FitWarning¶
Bases:
Warning
- exception metrolopy.exceptions.GummyWarning¶
Bases:
Warning
- exception metrolopy.exceptions.IncompatibleUnitsError¶
Bases:
ValueError
This exception is raised when an operation is attempted with gummys that have units that are incompatible for that operation.
- exception metrolopy.exceptions.NoSimulatedDataError¶
Bases:
Exception
- exception metrolopy.exceptions.NoUnitConversionFoundError¶
- exception metrolopy.exceptions.UncertiantyPrecisionWarning¶
Bases:
Warning
- exception metrolopy.exceptions.UnitError¶
Bases:
Exception
Base class for Unit exceptions.
- exception metrolopy.exceptions.UnitLibError¶
Bases:
metrolopy.exceptions.UnitError
This exception is raised when the UnitLibrary cannot parse a unit string.
- exception metrolopy.exceptions.UnitLibNotFoundError¶
- exception metrolopy.exceptions.UnitNotFoundError¶
- exception metrolopy.exceptions.UnitWarning¶
Bases:
Warning
metrolopy.fit module¶
This module defines some classes to facilitate curve fitting.
- class metrolopy.fit.DoubleExpFit(x, y=None, p0=None, ux=None, uy=None, sigma_is_known=True, xunit=None, yunit=None, solver=None, maxiter=None, nprop=False, **kw)¶
Bases:
metrolopy.fit.Fit
- DoubleExpFit(x,y,p0=None,ux=None,uy=None,sigma_is_known=True,xunit=None, yunit=None,
solver=None,maxiter=None,nprop=False,**keywords)
Fits the x,y data to a function of the form:
p[0]*np.exp(x/p[1])+p[2]*np.exp(x/p[3])+p[4]
- Parameters
x (array_like) – The x-coordinates of the data. This is a list or numpy array of floats or gummys (all point must be of the same type, floats and gummys may not be mixed).
y (array_like, optional) – The y-coordinates of the data (the type requirements are the same as for the x-coordinates).
p0 (array_like of float, optional) – The initial values for the fit parameters.
ux (float, array_like of float or None, optional) – Uncertainty in the x values. This should not be specified if the x argument contains gummys. If this is specified then only the odr solver may be used. The default is None.
uy (float, array_like of float or None, optional) – Uncertainty in the y values. This should not be specified if the y argument contains gummys. The default is None.
sigma_is_known (bool, optional) – If this is True then any uncertainties in the data (either as gummys in the x or y values or in the ux or uy parameters) are used to calculate the uncertainties in the fit. Otherwise, the uncertainties are based on the standard deviation of the residuals and the uncertainties in the data are used only for weighting the data points. The default value is True. This parameter is ignored if nprop is True.
xunits, yunits (str or None, optional) – units for the x and y coordinates. These should not be specified if the x and y parameters contain gummys. These may only be specified if the get_punits method is overridden in a subclass.
solver ({‘nls’,’odr’}, optional) – If this is ‘nls’ then scipy.optimize.leastsq is used to perform the fit. If it is ‘odr’ then scipy.odr is used. ‘nls’ may not be used if the y-coordinate is None or multi-dimensional or if there is uncertainty in the x-coordinates. If this is None, then ‘nls’ will be used when possible.
maxiter (int or None, optional) – The maximum number of iterations that the solver may use. If this is None or omitted then the default value for the solver will be used.
nprop (bool, optional) –
- If this is True then uncertainties in the fit will be numerically
calculated by varying each data point. This will not work if there are more than a few data points or if the it is not very stable. If this is False than the covariance matrix generated by the solver will be used to calculate the uncertainties. The default value is False
other keywords (optional) – Any additional keyword parameters will be passed to the solver.
- p¶
The fitted values for the fit function parameters as gummys
- Type
list of gummy
- pf¶
The fitted values for the fit function parameters as floats
- Type
list of float
- res¶
the fit residuals
- Type
numpy.ndarray of float
- s¶
the standard deviation (or, when there are uncertainties for the input data, the square root of the reduced chi-squared) of the residuals
- Type
float
- cov¶
the covariance matrix generated by the solver
- Type
numpy.ndarray of float
- fit_output¶
the raw output of the solver
- x¶
numpy array of the x-coordinates of the data.
- Type
numpy.ndarray of float or of gummy
- xf¶
numpy array of the x-coordinates of the data as floats
- Type
numpy.ndarray of float
- xdim¶
the number of dimensions of the x-coordinates
- Type
int
- ux¶
uncertainties in the x-coordinates
- Type
float, numpy.ndarray of floats or None
- y¶
numpy array of the y-coordinates of the data.
- Type
numpy.ndarray of float or of gummy
- yf¶
numpy array of the y-coordinates of the data as floats
- Type
numpy.ndarray of float
- ydim¶
the number of dimensions of the y-coordinates
- Type
int
- uy¶
uncertainties in the y-coordinates
- Type
float, numpy.ndarray of floats or None
- count¶
the number of data points
- Type
int
- p0¶
the initial values for the fit function parameters
- Type
list of float
- solver¶
the solver used
- Type
str
- punits¶
the units of the fit parameters
- Type
list of Unit
- nparam¶
the number of fit parameters
- Type
int
- ypred(x1,x2,...):
Takes xdim floats and returns a gummy representing the predicted value at that x-coordinate.
- ypredf(x1,x2,...):
Takes xdim floats and returns a float giving the predicted value at that x-coordinate.
- plot(...):
plots the data (only available if x and y are one-dimensional)
- f(x, p1, p2, p3, p4, p5)¶
Not implemented, implemented this in a derived class.
The function to fit.
It must either have signature:
f(self,x,p1,p2,…,pn)
where there are p1 to pn are the n fit parameters and the independent variable x has one dimension, or:
f(self,x1,x2,…,xm,p1,p2,…,pn)
where the independent variable x has m dimensions at each observation.
f should return either a float or a 1-d array of floats depending on the dimension of the response variable.
- fhtml()¶
Not implemented, may optionally be implemented by a derived class.
Returns a string containing an html representation of the fit function.
- flatex()¶
Not implemented, may optionally be implemented by a derived class.
Returns a string containing a latex representation of the fit function.
- funicode()¶
Not implemented, may optionally be implemented by a derived class.
Returns a string containing a unicode representation of the fit function.
- get_p0()¶
Not implemented, may optionally be implemented by a derived class.
Returns an initial guess for the the fit parameters [p1,p2,…] based on the input x and y data.
If this method is not implemented then the inital values must be passed in the p0 parameter when the instance is created.
- get_punits()¶
Not implemented, may optionally be implemented by a derived class.
Returns a list of units for each fit parameter [p1,p2,…] based on the units of the input data.
If this is not implemented then only dimensionless data (with unit one) may be fit.
- jac(x, p1, p2, p3, p4, p5)¶
Not implemented, may optionally be implemented by a derived class.
The Jacobian of the fit function.
If this method throws a NotImplementedError the derivatives will be calculated numerically.
It must have the same signature as the f method and return a list of derivatives of the form:
[df/dx1,df/dx2,…,df/dp1,df/dp2,…]
if f returns a scalar or:
- [[df1/dx1,df1/dx2,…,df1/dp1,df1/dp2,…],
[df2/dx1,df2/dx2,…,df2/dp1,df2/dp2,…],…]
if f returns a 1-d array [f1,f2,…].
- class metrolopy.fit.ExpFit(x, y=None, p0=None, ux=None, uy=None, sigma_is_known=True, xunit=None, yunit=None, solver=None, maxiter=None, nprop=False, **kw)¶
Bases:
metrolopy.fit.Fit
- ExpFit(x,y,p0=None,ux=None,uy=None,sigma_is_known=True,xunit=None, yunit=None,
solver=None,maxiter=None,nprop=False,**keywords)
Fits the x,y data to a function of the form:
p[0]*np.exp(x/p[1])+p[2]
- Parameters
x (array_like) – The x-coordinates of the data. This is a list or numpy array of floats or gummys (all point must be of the same type, floats and gummys may not be mixed).
y (array_like, optional) – The y-coordinates of the data (the type requirements are the same as for the x-coordinates).
p0 (array_like of float, optional) – The initial values for the fit parameters.
ux (float, array_like of float or None, optional) – Uncertainty in the x values. This should not be specified if the x argument contains gummys. If this is specified then only the odr solver may be used. The default is None.
uy (float, array_like of float or None, optional) – Uncertainty in the y values. This should not be specified if the y argument contains gummys. The default is None.
sigma_is_known (bool, optional) – If this is True then any uncertainties in the data (either as gummys in the x or y values or in the ux or uy parameters) are used to calculate the uncertainties in the fit. Otherwise, the uncertainties are based on the standard deviation of the residuals and the uncertainties in the data are used only for weighting the data points. The default value is True. This parameter is ignored if nprop is True.
xunits, yunits (str or None, optional) – units for the x and y coordinates. These should not be specified if the x and y parameters contain gummys. These may only be specified if the get_punits method is overridden in a subclass.
solver ({‘nls’,’odr’}, optional) – If this is ‘nls’ then scipy.optimize.leastsq is used to perform the fit. If it is ‘odr’ then scipy.odr is used. ‘nls’ may not be used if the y-coordinate is None or multi-dimensional or if there is uncertainty in the x-coordinates. If this is None, then ‘nls’ will be used when possible.
maxiter (int or None, optional) – The maximum number of iterations that the solver may use. If this is None or omitted then the default value for the solver will be used.
nprop (bool, optional) –
- If this is True then uncertainties in the fit will be numerically
calculated by varying each data point. This will not work if there are more than a few data points or if the it is not very stable. If this is False than the covariance matrix generated by the solver will be used to calculate the uncertainties. The default value is False
other keywords (optional) – Any additional keyword parameters will be passed to the solver.
- p¶
The fitted values for the fit function parameters as gummys
- Type
list of gummy
- pf¶
The fitted values for the fit function parameters as floats
- Type
list of float
- res¶
the fit residuals
- Type
numpy.ndarray of float
- s¶
the standard deviation (or, when there are uncertainties for the input data, the square root of the reduced chi-squared) of the residuals
- Type
float
- cov¶
the covariance matrix generated by the solver
- Type
numpy.ndarray of float
- fit_output¶
the raw output of the solver
- x¶
numpy array of the x-coordinates of the data.
- Type
numpy.ndarray of float or of gummy
- xf¶
numpy array of the x-coordinates of the data as floats
- Type
numpy.ndarray of float
- xdim¶
the number of dimensions of the x-coordinates
- Type
int
- ux¶
uncertainties in the x-coordinates
- Type
float, numpy.ndarray of floats or None
- y¶
numpy array of the y-coordinates of the data.
- Type
numpy.ndarray of float or of gummy
- yf¶
numpy array of the y-coordinates of the data as floats
- Type
numpy.ndarray of float
- ydim¶
the number of dimensions of the y-coordinates
- Type
int
- uy¶
uncertainties in the y-coordinates
- Type
float, numpy.ndarray of floats or None
- count¶
the number of data points
- Type
int
- p0¶
the initial values for the fit function parameters
- Type
list of float
- solver¶
the solver used
- Type
str
- punits¶
the units of the fit parameters
- Type
list of Unit
- nparam¶
the number of fit parameters
- Type
int
- ypred(x1,x2,...):
Takes xdim floats and returns a gummy representing the predicted value at that x-coordinate.
- ypredf(x1,x2,...):
Takes xdim floats and returns a float giving the predicted value at that x-coordinate.
- plot(...):
plots the data (only available if x and y are one-dimensional)
- f(x, p1, p2, p3)¶
Not implemented, implemented this in a derived class.
The function to fit.
It must either have signature:
f(self,x,p1,p2,…,pn)
where there are p1 to pn are the n fit parameters and the independent variable x has one dimension, or:
f(self,x1,x2,…,xm,p1,p2,…,pn)
where the independent variable x has m dimensions at each observation.
f should return either a float or a 1-d array of floats depending on the dimension of the response variable.
- fhtml()¶
Not implemented, may optionally be implemented by a derived class.
Returns a string containing an html representation of the fit function.
- flatex()¶
Not implemented, may optionally be implemented by a derived class.
Returns a string containing a latex representation of the fit function.
- funicode()¶
Not implemented, may optionally be implemented by a derived class.
Returns a string containing a unicode representation of the fit function.
- get_p0()¶
Not implemented, may optionally be implemented by a derived class.
Returns an initial guess for the the fit parameters [p1,p2,…] based on the input x and y data.
If this method is not implemented then the inital values must be passed in the p0 parameter when the instance is created.
- get_punits()¶
Not implemented, may optionally be implemented by a derived class.
Returns a list of units for each fit parameter [p1,p2,…] based on the units of the input data.
If this is not implemented then only dimensionless data (with unit one) may be fit.
- jac(x, p1, p2, p3)¶
Not implemented, may optionally be implemented by a derived class.
The Jacobian of the fit function.
If this method throws a NotImplementedError the derivatives will be calculated numerically.
It must have the same signature as the f method and return a list of derivatives of the form:
[df/dx1,df/dx2,…,df/dp1,df/dp2,…]
if f returns a scalar or:
- [[df1/dx1,df1/dx2,…,df1/dp1,df1/dp2,…],
[df2/dx1,df2/dx2,…,df2/dp1,df2/dp2,…],…]
if f returns a 1-d array [f1,f2,…].
- class metrolopy.fit.Fit(x, y=None, p0=None, ux=None, uy=None, sigma_is_known=True, xunit=None, yunit=None, solver=None, maxiter=None, nprop=False, **kw)¶
Bases:
metrolopy.fit._Fit
,metrolopy.printing.PrettyPrinter
- f(*a)¶
Not implemented, implemented this in a derived class.
The function to fit.
It must either have signature:
f(self,x,p1,p2,…,pn)
where there are p1 to pn are the n fit parameters and the independent variable x has one dimension, or:
f(self,x1,x2,…,xm,p1,p2,…,pn)
where the independent variable x has m dimensions at each observation.
f should return either a float or a 1-d array of floats depending on the dimension of the response variable.
- fhtml()¶
Not implemented, may optionally be implemented by a derived class.
Returns a string containing an html representation of the fit function.
- flatex()¶
Not implemented, may optionally be implemented by a derived class.
Returns a string containing a latex representation of the fit function.
- funicode()¶
Not implemented, may optionally be implemented by a derived class.
Returns a string containing a unicode representation of the fit function.
- get_p0()¶
Not implemented, may optionally be implemented by a derived class.
Returns an initial guess for the the fit parameters [p1,p2,…] based on the input x and y data.
If this method is not implemented then the inital values must be passed in the p0 parameter when the instance is created.
- get_punits()¶
Not implemented, may optionally be implemented by a derived class.
Returns a list of units for each fit parameter [p1,p2,…] based on the units of the input data.
If this is not implemented then only dimensionless data (with unit one) may be fit.
- html()¶
If called from an IPython or Jupyter console, prints the fit function and best fit parameters with the html interpreter.
- jac(*a)¶
Not implemented, may optionally be implemented by a derived class.
The Jacobian of the fit function.
If this method throws a NotImplementedError the derivatives will be calculated numerically.
It must have the same signature as the f method and return a list of derivatives of the form:
[df/dx1,df/dx2,…,df/dp1,df/dp2,…]
if f returns a scalar or:
- [[df1/dx1,df1/dx2,…,df1/dp1,df1/dp2,…],
[df2/dx1,df2/dx2,…,df2/dp1,df2/dp2,…],…]
if f returns a 1-d array [f1,f2,…].
- latex()¶
If called from an IPython or Jupyter console, prints the fit function and best fit parameters with the latex interpreter.
- latex_math = None¶
- ptostring(fmt='unicode')¶
Returns a string that displays the fit parameters.
- Parameters
fmt ({‘unicode’, ‘ascii’, ‘latex’ or ‘html’}) – format for the output
- toascii()¶
Returns a string containing an ascii representation of the fit function and the best fit parameters.
Equivalent to
Fit.tostring('ascii')
.
- tohtml()¶
Returns a string containing an html representation of the fit function and the best fit parameters.
Equivalent to
Fit.tostring('html')
.
- tolatex()¶
Returns a string containing a latex representation of the fit function and the best fit parameters.
Equivalent to
Fit.tostring('latex')
.
- tostring(fmt='unicode')¶
Returns a string to display the fit function and fit parameters.
- Parameters
fmt ({‘unicode’, ‘ascii’, ‘latex’ or ‘html’}) – format for the output
- ypred(*x)¶
returns a gummy representing the value predicted by the fit at x
- ypredf(*x)¶
returns a float representing the value predicted by the fit at x
- class metrolopy.fit.OneOverTFit(x, y=None, p0=None, ux=None, uy=None, sigma_is_known=True, xunit=None, yunit=None, solver=None, maxiter=None, nprop=False, **kw)¶
Bases:
metrolopy.fit.Fit
- DoubleExpFit(x,y,p0=None,ux=None,uy=None,sigma_is_known=True,xunit=None, yunit=None,
solver=None,maxiter=None,nprop=False,**keywords)
Fits the x,y data to a function of the form:
p[0]/x + p[1]
- Parameters
x (array_like) – The x-coordinates of the data. This is a list or numpy array of floats or gummys (all point must be of the same type, floats and gummys may not be mixed).
y (array_like, optional) – The y-coordinates of the data (the type requirements are the same as for the x-coordinates).
p0 (array_like of float, optional) – The initial values for the fit parameters.
ux (float, array_like of float or None, optional) – Uncertainty in the x values. This should not be specified if the x argument contains gummys. If this is specified then only the odr solver may be used. The default is None.
uy (float, array_like of float or None, optional) – Uncertainty in the y values. This should not be specified if the y argument contains gummys. The default is None.
sigma_is_known (bool, optional) – If this is True then any uncertainties in the data (either as gummys in the x or y values or in the ux or uy parameters) are used to calculate the uncertainties in the fit. Otherwise, the uncertainties are based on the standard deviation of the residuals and the uncertainties in the data are used only for weighting the data points. The default value is True. This parameter is ignored if nprop is True.
xunits, yunits (str or None, optional) – units for the x and y coordinates. These should not be specified if the x and y parameters contain gummys. These may only be specified if the get_punits method is overridden in a subclass.
solver ({‘nls’,’odr’}, optional) – If this is ‘nls’ then scipy.optimize.leastsq is used to perform the fit. If it is ‘odr’ then scipy.odr is used. ‘nls’ may not be used if the y-coordinate is None or multi-dimensional or if there is uncertainty in the x-coordinates. If this is None, then ‘nls’ will be used when possible.
maxiter (int or None, optional) – The maximum number of iterations that the solver may use. If this is None or omitted then the default value for the solver will be used.
nprop (bool, optional) –
- If this is True then uncertainties in the fit will be numerically
calculated by varying each data point. This will not work if there are more than a few data points or if the it is not very stable. If this is False than the covariance matrix generated by the solver will be used to calculate the uncertainties. The default value is False
other keywords (optional) – Any additional keyword parameters will be passed to the solver.
- p¶
The fitted values for the fit function parameters as gummys
- Type
list of gummy
- pf¶
The fitted values for the fit function parameters as floats
- Type
list of float
- res¶
the fit residuals
- Type
numpy.ndarray of float
- s¶
the standard deviation (or, when there are uncertainties for the input data, the square root of the reduced chi-squared) of the residuals
- Type
float
- cov¶
the covariance matrix generated by the solver
- Type
numpy.ndarray of float
- fit_output¶
the raw output of the solver
- x¶
numpy array of the x-coordinates of the data.
- Type
numpy.ndarray of float or of gummy
- xf¶
numpy array of the x-coordinates of the data as floats
- Type
numpy.ndarray of float
- xdim¶
the number of dimensions of the x-coordinates
- Type
int
- ux¶
uncertainties in the x-coordinates
- Type
float, numpy.ndarray of floats or None
- y¶
numpy array of the y-coordinates of the data.
- Type
numpy.ndarray of float or of gummy
- yf¶
numpy array of the y-coordinates of the data as floats
- Type
numpy.ndarray of float
- ydim¶
the number of dimensions of the y-coordinates
- Type
int
- uy¶
uncertainties in the y-coordinates
- Type
float, numpy.ndarray of floats or None
- count¶
the number of data points
- Type
int
- p0¶
the initial values for the fit function parameters
- Type
list of float
- solver¶
the solver used
- Type
str
- punits¶
the units of the fit parameters
- Type
list of Unit
- nparam¶
the number of fit parameters
- Type
int
- ypred(x1,x2,...):
Takes xdim floats and returns a gummy representing the predicted value at that x-coordinate.
- ypredf(x1,x2,...):
Takes xdim floats and returns a float giving the predicted value at that x-coordinate.
- plot(...):
plots the data (only available if x and y are one-dimensional)
- f(x, p1, p2)¶
Not implemented, implemented this in a derived class.
The function to fit.
It must either have signature:
f(self,x,p1,p2,…,pn)
where there are p1 to pn are the n fit parameters and the independent variable x has one dimension, or:
f(self,x1,x2,…,xm,p1,p2,…,pn)
where the independent variable x has m dimensions at each observation.
f should return either a float or a 1-d array of floats depending on the dimension of the response variable.
- fhtml()¶
Not implemented, may optionally be implemented by a derived class.
Returns a string containing an html representation of the fit function.
- flatex()¶
Not implemented, may optionally be implemented by a derived class.
Returns a string containing a latex representation of the fit function.
- funicode()¶
Not implemented, may optionally be implemented by a derived class.
Returns a string containing a unicode representation of the fit function.
- get_p0()¶
Not implemented, may optionally be implemented by a derived class.
Returns an initial guess for the the fit parameters [p1,p2,…] based on the input x and y data.
If this method is not implemented then the inital values must be passed in the p0 parameter when the instance is created.
- get_punits()¶
Not implemented, may optionally be implemented by a derived class.
Returns a list of units for each fit parameter [p1,p2,…] based on the units of the input data.
If this is not implemented then only dimensionless data (with unit one) may be fit.
- jac(x, p1, p2)¶
Not implemented, may optionally be implemented by a derived class.
The Jacobian of the fit function.
If this method throws a NotImplementedError the derivatives will be calculated numerically.
It must have the same signature as the f method and return a list of derivatives of the form:
[df/dx1,df/dx2,…,df/dp1,df/dp2,…]
if f returns a scalar or:
- [[df1/dx1,df1/dx2,…,df1/dp1,df1/dp2,…],
[df2/dx1,df2/dx2,…,df2/dp1,df2/dp2,…],…]
if f returns a 1-d array [f1,f2,…].
- class metrolopy.fit.PolyFit(x, y, deg=1, ux=None, uy=None, sigma_is_known=True, p0=None, xunit=None, yunit=None, solver=None, maxiter=None, nprop=False, **kw)¶
Bases:
metrolopy.fit.Fit
- f(*a)¶
Not implemented, implemented this in a derived class.
The function to fit.
It must either have signature:
f(self,x,p1,p2,…,pn)
where there are p1 to pn are the n fit parameters and the independent variable x has one dimension, or:
f(self,x1,x2,…,xm,p1,p2,…,pn)
where the independent variable x has m dimensions at each observation.
f should return either a float or a 1-d array of floats depending on the dimension of the response variable.
- fhtml()¶
Not implemented, may optionally be implemented by a derived class.
Returns a string containing an html representation of the fit function.
- flatex()¶
Not implemented, may optionally be implemented by a derived class.
Returns a string containing a latex representation of the fit function.
- funicode()¶
Not implemented, may optionally be implemented by a derived class.
Returns a string containing a unicode representation of the fit function.
- get_p0()¶
Not implemented, may optionally be implemented by a derived class.
Returns an initial guess for the the fit parameters [p1,p2,…] based on the input x and y data.
If this method is not implemented then the inital values must be passed in the p0 parameter when the instance is created.
- get_punits()¶
Not implemented, may optionally be implemented by a derived class.
Returns a list of units for each fit parameter [p1,p2,…] based on the units of the input data.
If this is not implemented then only dimensionless data (with unit one) may be fit.
- jac(*a)¶
Not implemented, may optionally be implemented by a derived class.
The Jacobian of the fit function.
If this method throws a NotImplementedError the derivatives will be calculated numerically.
It must have the same signature as the f method and return a list of derivatives of the form:
[df/dx1,df/dx2,…,df/dp1,df/dp2,…]
if f returns a scalar or:
- [[df1/dx1,df1/dx2,…,df1/dp1,df1/dp2,…],
[df2/dx1,df2/dx2,…,df2/dp1,df2/dp2,…],…]
if f returns a 1-d array [f1,f2,…].
- class metrolopy.fit.SinFit(x, y=None, p0=None, ux=None, uy=None, sigma_is_known=True, xunit=None, yunit=None, solver=None, maxiter=None, nprop=False, **kw)¶
Bases:
metrolopy.fit.Fit
- SinFit(x,y,p0=None,ux=None,uy=None,sigma_is_known=True,xunit=None, yunit=None,
solver=None,maxiter=None,nprop=False,**keywords)
Fits the x,y data to a function of the form:
p[0]*sin(p[1]*x + p[2]) + p[3]
- Parameters
x (array_like) – The x-coordinates of the data. This is a list or numpy array of floats or gummys (all point must be of the same type, floats and gummys may not be mixed).
y (array_like, optional) – The y-coordinates of the data (the type requirements are the same as for the x-coordinates).
p0 (array_like of float, optional) – The initial values for the fit parameters.
ux (float, array_like of float or None, optional) – Uncertainty in the x values. This should not be specified if the x argument contains gummys. If this is specified then only the odr solver may be used. The default is None.
uy (float, array_like of float or None, optional) – Uncertainty in the y values. This should not be specified if the y argument contains gummys. The default is None.
sigma_is_known (bool, optional) – If this is True then any uncertainties in the data (either as gummys in the x or y values or in the ux or uy parameters) are used to calculate the uncertainties in the fit. Otherwise, the uncertainties are based on the standard deviation of the residuals and the uncertainties in the data are used only for weighting the data points. The default value is True. This parameter is ignored if nprop is True.
xunits, yunits (str or None, optional) – units for the x and y coordinates. These should not be specified if the x and y parameters contain gummys. These may only be specified if the get_punits method is overridden in a subclass.
solver ({‘nls’,’odr’}, optional) – If this is ‘nls’ then scipy.optimize.leastsq is used to perform the fit. If it is ‘odr’ then scipy.odr is used. ‘nls’ may not be used if the y-coordinate is None or multi-dimensional or if there is uncertainty in the x-coordinates. If this is None, then ‘nls’ will be used when possible.
maxiter (int or None, optional) – The maximum number of iterations that the solver may use. If this is None or omitted then the default value for the solver will be used.
nprop (bool, optional) –
- If this is True then uncertainties in the fit will be numerically
calculated by varying each data point. This will not work if there are more than a few data points or if the it is not very stable. If this is False than the covariance matrix generated by the solver will be used to calculate the uncertainties. The default value is False
other keywords (optional) – Any additional keyword parameters will be passed to the solver.
- p¶
The fitted values for the fit function parameters as gummys
- Type
list of gummy
- pf¶
The fitted values for the fit function parameters as floats
- Type
list of float
- res¶
the fit residuals
- Type
numpy.ndarray of float
- s¶
the standard deviation (or, when there are uncertainties for the input data, the square root of the reduced chi-squared) of the residuals
- Type
float
- cov¶
the covariance matrix generated by the solver
- Type
numpy.ndarray of float
- fit_output¶
the raw output of the solver
- x¶
numpy array of the x-coordinates of the data.
- Type
numpy.ndarray of float or of gummy
- xf¶
numpy array of the x-coordinates of the data as floats
- Type
numpy.ndarray of float
- xdim¶
the number of dimensions of the x-coordinates
- Type
int
- ux¶
uncertainties in the x-coordinates
- Type
float, numpy.ndarray of floats or None
- y¶
numpy array of the y-coordinates of the data.
- Type
numpy.ndarray of float or of gummy
- yf¶
numpy array of the y-coordinates of the data as floats
- Type
numpy.ndarray of float
- ydim¶
the number of dimensions of the y-coordinates
- Type
int
- uy¶
uncertainties in the y-coordinates
- Type
float, numpy.ndarray of floats or None
- count¶
the number of data points
- Type
int
- p0¶
the initial values for the fit function parameters
- Type
list of float
- solver¶
the solver used
- Type
str
- punits¶
the units of the fit parameters
- Type
list of Unit
- nparam¶
the number of fit parameters
- Type
int
- ypred(x1,x2,...):
Takes xdim floats and returns a gummy representing the predicted value at that x-coordinate.
- ypredf(x1,x2,...):
Takes xdim floats and returns a float giving the predicted value at that x-coordinate.
- plot(...):
plots the data (only available if x and y are one-dimensional)
- f(x, p1, p2, p3, p4)¶
Not implemented, implemented this in a derived class.
The function to fit.
It must either have signature:
f(self,x,p1,p2,…,pn)
where there are p1 to pn are the n fit parameters and the independent variable x has one dimension, or:
f(self,x1,x2,…,xm,p1,p2,…,pn)
where the independent variable x has m dimensions at each observation.
f should return either a float or a 1-d array of floats depending on the dimension of the response variable.
- fhtml()¶
Not implemented, may optionally be implemented by a derived class.
Returns a string containing an html representation of the fit function.
- flatex()¶
Not implemented, may optionally be implemented by a derived class.
Returns a string containing a latex representation of the fit function.
- funicode()¶
Not implemented, may optionally be implemented by a derived class.
Returns a string containing a unicode representation of the fit function.
- get_p0()¶
Not implemented, may optionally be implemented by a derived class.
Returns an initial guess for the the fit parameters [p1,p2,…] based on the input x and y data.
If this method is not implemented then the inital values must be passed in the p0 parameter when the instance is created.
- get_punits()¶
Not implemented, may optionally be implemented by a derived class.
Returns a list of units for each fit parameter [p1,p2,…] based on the units of the input data.
If this is not implemented then only dimensionless data (with unit one) may be fit.
- jac(x, p1, p2, p3, p4)¶
Not implemented, may optionally be implemented by a derived class.
The Jacobian of the fit function.
If this method throws a NotImplementedError the derivatives will be calculated numerically.
It must have the same signature as the f method and return a list of derivatives of the form:
[df/dx1,df/dx2,…,df/dp1,df/dp2,…]
if f returns a scalar or:
- [[df1/dx1,df1/dx2,…,df1/dp1,df1/dp2,…],
[df2/dx1,df2/dx2,…,df2/dp1,df2/dp2,…],…]
if f returns a 1-d array [f1,f2,…].
metrolopy.functions module¶
A number of mathematical functions are defined here that can be used with gummys.
- metrolopy.functions.absolute(x)¶
Returns the absoulte value of x where x can be float, complex, gummy or jummy. This is equivalent to abs(x).
- metrolopy.functions.add(x1, x2)¶
returns x1 + x2
- metrolopy.functions.angle(x)¶
Returns the complex argument of x, where x can be float, complex, gummy or jummy and the return value is a float if x is float or complex and gummy if x is gummy or jummy.
- metrolopy.functions.arccos(x)¶
Returns the inverse cosine of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.arccosh(x)¶
Returns the inverse hyperbolic cosine of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.arcsin(x)¶
Returns the inverse sine of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.arcsinh(x)¶
Returns the inverse hyperbolic sine of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.arctan(x)¶
Returns the inverse tangent of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.arctan2(x1, x2)¶
Returns the inverse tangent of x1/x2 choosing the quadrant correctly where x1 and x2 can be float, complex, gummy or jummy.
- metrolopy.functions.arctanh(x)¶
Returns the inverse hyperbolic tangent of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.around(x, n=0)¶
Returns x rounded to n digits where x can be float, complex, gummy or jummy but n must be int.
- metrolopy.functions.cbrt(x)¶
Returns the cube root of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.ceil(x)¶
Returns the ceiling of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.conj(x)¶
returns x.conjugate(), the complex conjugate of x
- metrolopy.functions.cos(x)¶
Returns the cosine of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.cosh(x)¶
Returns the hyperbolic cosine of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.cross(*args, **kwds)¶
Alias for numpy.cross
- metrolopy.functions.cumprod(*args, **kwds)¶
Alias for numpy.cumprod
- metrolopy.functions.cumsum(*args, **kwds)¶
Alias for numpy.cumsum
- metrolopy.functions.diff(*args, **kwds)¶
Alias for numpy.diff
- metrolopy.functions.divide(x1, x2)¶
returns x1 / x2
- metrolopy.functions.divmod(x1, x2)¶
returns (x1 // x2, x1 % x2)
- metrolopy.functions.ediff1d(*args, **kwds)¶
Alias for numpy.ediff1d
- metrolopy.functions.exp(x)¶
Returns e to the power of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.exp2(x)¶
Returns 2 to the power of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.expm1(x)¶
Returns exp(x) - 1 where x can be float, complex, gummy or jummy.
- metrolopy.functions.fix(x)¶
Returns x rounded towards zero where x can be float, complex, gummy or jummy.
- metrolopy.functions.floor(x)¶
Returns the floor of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.floor_divide(x1, x2)¶
returns x1 // x2
- metrolopy.functions.gradient(*args, **kwds)¶
Alias for numpy.gradient
- metrolopy.functions.heaviside(x, h0)¶
Heavyside function of x, h0 is the value at x = 0
- metrolopy.functions.imag(x)¶
returns x.imag
- metrolopy.functions.log(x)¶
Returns the natural logrithm of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.log10(x)¶
Returns the log base 10 of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.log1p(x)¶
Returns the natural logrithm of x plus 1 where x can be float, complex, gummy or jummy.
- metrolopy.functions.log2(x)¶
Returns the log base 2 of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.logaddexp(x1, x2)¶
Returns the log(exp(x1) + exp(x2)) where x1 and x2 can be float, complex, gummy or jummy and log is the natural logrithm.
- metrolopy.functions.logaddexp2(x1, x2)¶
Returns the log2(2**x1 + 2**x2) where x1 and x2 can be float, complex, gummy or jummy and log2 is the logrithm to base 2.
- metrolopy.functions.mod(x1, x2)¶
returns x1 % x2
- metrolopy.functions.modf(x1, x2)¶
returns (x1 % 1, x1 // 1), a tuple of integer and fractional parts
- metrolopy.functions.multiply(x1, x2)¶
returns x1 * x2
- metrolopy.functions.negative(x)¶
returns -x
- metrolopy.functions.power(x1, x2)¶
returns x1**x2
- metrolopy.functions.prod(*args, **kwds)¶
Alias for numpy.prod
- metrolopy.functions.real(x)¶
returns x.real
- metrolopy.functions.reciprocal(x)¶
returns 1/x
- metrolopy.functions.remainder(x1, x2)¶
returns x1 % x2
- metrolopy.functions.rint(x)¶
Returns x rounded to the nearest integer value where x can be float, complex, gummy or jummy.
- metrolopy.functions.sign(x)¶
sign of x
- metrolopy.functions.sin(x)¶
Returns the sine of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.sinh(x)¶
Returns the hyperbolic sine of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.sqrt(x)¶
Returns the square root of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.square(x)¶
Returns the square of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.subtract(x1, x2)¶
returns x1 - x2
- metrolopy.functions.sum(*args, **kwds)¶
Alias for numpy.sum
- metrolopy.functions.tan(x)¶
Returns the tangent of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.tanh(x)¶
Returns the hyperbolic tangent of x where x can be float, complex, gummy or jummy.
- metrolopy.functions.true_divide(x1, x2)¶
returns x1 / x2
- metrolopy.functions.trunc(x)¶
Returns x rounded towards zero where x can be float, complex, gummy or jummy.
metrolopy.gummy module¶
The gummy object defined here represents the core functionality of this package, though the code in this module only integrates the unit conversion machinery from the .unit module with the other functions and provides pretty printing functionality. The first-order uncertainty propagation code resides in the .ummy module. The Monte-Carlo propagation machinery is defined in the .distributions module and is integrated with the ummy object in the nummy module. The gummy object, in turn, inherits from the nummy object.
- class metrolopy.gummy.MetaGummy¶
Bases:
metrolopy.printing.MetaPrettyPrinter
- property bayesian¶
bool
Read/write at the class level, but read-only at the instance level. The default value is False; this should only be changed once at the beginning of the session. This property affects how the level of confidence p (sometimes called coverage probability) of an expanded uncertainty is related to the coverage factor k for a gummy based on data with finite degrees of freedom.
Standard uncertainties are often based on the standard deviation of a set of measurements (and the assumption that these measurements are drawn from a normally distributed population). Traditionally (e.g. the GUM 2008 edition) the standard uncertainty is taken to be the standard deviation of the mean (s/sqrt(n), where s is the sample standard deviation and n is the number of measurements). However there is some “extra uncertainty” because the sample standard devation not exactly equal to the population standard deviation. This is taken into account by using a Student’s t distribution to calculate the expanded uncertainty. However it has been pointed out, by those who advocate a Bayesian point of view, that the probability distribution for the measurand here is best described by a shifted and scaled Student’s t distribution. So the standard uncertainty should be the standard deviation of this distribution which is s*sqrt{(n-1)/[n*(n-3)]}. Thus
u(bayesian) = sqrt[dof/(dof - 2)]*u(traditional)
where dof = n - 1 and the “extra uncertainty” is incorporated directly into the standard uncertainty.
Example
>>> gummy.bayesian = True >>> g = gummy(1,0.03,dof=5) >>> g.bayesian True
- property cimethod¶
str in {‘shortest’, ‘symmetric’}
Get or set the method for calculating the confidence interval from Monte-Carlo data. If this property is set at the class level, it will change the default cimethod value for new gummys but will not affect gummys that have already been created.
Can be set either to the string ‘shortest’ or the string ‘symmetric’. This property gets or sets the method for calculating confidence intervals from Monte-Carlo data.
If it is set to ‘shortest’, the confidence interval will be taken to be the shortest interval that includes the desired fraction of the probability distribution.
If it is set to ‘symmetric’, then the confidence interval will be set so that, for n Monte-Carlo samples and a coverage probability of p, then n`*(1-`p)/2 samples lie below the lower limit of the confidence interval and the same number of samples lie above the upper limit of the confidence interval.
- property cmp_k¶
Get or set the coverage factor for comparisons between gummys. Setting this property sets the cmp_p property to None.
- property cmp_p¶
Get or set the probability level to use when comparing gummys. Setting this property sets the cmp_k property to None.
- property max_digits¶
int
Gets or sets the maximum number of digits in x to display.
- property max_dof¶
int
Gets or sets the maximum finite value for dof. Any dof larger than max_dof will be rounded to float(‘inf’).
- property mulsep¶
- property nsig¶
int
Gets or sets the number of significant digits in the uncertainty to display.
- property p_method¶
str in {‘loc’, ‘cp’, ‘gauss’, ‘ccp’, ‘chebyshev’}
This sets the default p_method attribute for newly created gummys which determines how the coverage factor is calculated from a given level of confidence or coverage probability p.
If p_method = ‘loc’, then the uncertainty is assumed to be represented by a normal probability distribution if dof = float(‘inf’) and shifted and scaled Student’s t distribution otherwise. If p_method = ‘gauss’ or ‘cp’ then the Gauss inequality is used, and if p_method = ‘chebyshev’ or ‘ccp’ then the Chebyshev inequality is used. For p = 0.95 and dof = float(‘inf’), p_method = ‘loc’ gives k = 2.0, while p_method = ‘gauss’ gives k = 3.0 and p_method = ‘chebyshev’ gives k = 4.5.
- property rounding_u¶
bool
If this is set to True then the uncertainty of the ummy or gummy includes a contribution to account for the finite resolution of the x-value.
- property sci_notation¶
bool or None
Setting this to True or False forces or prevents scientific notation in the display of the value. If this is set to None thr scientific notation will be used if the x value is below 10**sci_notation_low or above 10**sci_notation_high.
- property sci_notation_high¶
see the sci_notation property
- property sci_notation_low¶
see the sci_notation property
- property solidus¶
- property style¶
Get or set the default display style for new gummys. This is a string with one of the following values:
“pm” or “+-” gives, e.g. in ascii format “(1.00 +/- 0.12)e-12 cm”
“pmi” or “+-i” gives e.g. “1.00e-12 cm +/- 1.2e-13 cm”
“concise” or “()” gives e.g. “1.00(12)e-12 cm”
“ueq” or “u equals” gives e.g. “1.00e-12 cm with u = 1.2e-13 cm”
“x” or “x only” gives e.g. “1.00e-12 cm”
“xf” gives e.g. “1.00e-12”
“u” or “u only” gives “1.2e-13 cm”
“uf” gives “1.2e-13”
The following styles display a mean and confidence interval based on data from a Monte-Carlo simulation. If no simulated data is available “no simulated data” is returned.
“pmsim” gives e.g. “(1.01 + 0.11 - 0.13)e-12 cm”
“pmsimi” gives e.g. “1.01e-12 cm + 1.1e-13 cm - 1.3e-11 cm”
“mcisim” gives e.g. “mean = 1.01e-12 cm, confidence interval = [8.8e-13 cm, 1.13e-12 cm]”
“cisim” gives e.g “[8.8e-13 cm, 1.13e-12 cm]”
“usim” gives the standard deviation e.g. “1.2e-13 cm”
“ufsim” gives the standard deviation e.g. “1.2e-13”
Note if uunit has been defined for the gummy instance, then concise style and pm style are not valid and the display will default to pmi style.
The style can be set either at the class or the instance level.
To control whether the coverage factor (k), the level of confidence (p), the degrees of freedom (dof), and name are displayed as part of the uncertainty statement set the following variables to True or False (at either the class or instance level):
show_k
show_p
show_dof
show_name
show_k, show_p, and show_dof can also be set to None, which will allow the gummy object to decide whether to display the corresponding values.
The number of significant digits in the uncertainty to be displayed is set with the nsig attribute. This can be set either at the class level or the instance level. When the gummy module is loaded nsig is set to 2.
Scientific notation can be turned on or off by setting the sci_notation attribute to True or False. If sci_notation is set to None, scientific notation will be used if the exponent of gummy x value is greater than than the value of the sci_notation_high attribute or less than the sci_notation_low attribute. When the gummy module is loaded, sci_notation is None, sci_notation_high is 7 and sci_notation_low is -3. These attributes can be set either at the class or instance level.
Setting the solidus attribute to True uses a solidus (forward slash) to separate units with positive and negative exponents e.g. “m/s” and when solidus is set to False negative exponents are used e.g. “m s**-1”. Setting the mulsep attribute to True inserts a dot or * between units while setting this to False a space separates units. When the gummy module is loaded, both solidus and mulsep are set to False. They may be set at either the instance or class level.
- property thousand_spaces¶
bool
Gets or sets a bool value that determines whether to insert a space to group digits in x.
- class metrolopy.gummy.gummy(x, u=0, unit=one, dof=inf, k=1, p=None, uunit=None, utype=None, name=None)¶
Bases:
metrolopy.unit.Quantity
A gummy object represents a numerical value with an uncertainty and (or) a unit. They can be used in place of float values in Python expressions and the uncertainty can be propagated with with both first-order and Monte-Carlo methods. Correlations between gummys are tracked.
- Parameters
x (float, Distribution or gummy) – Either a float representing the value of the gummy or a sub-class of Distribution that represents the probability distribution of the gummy. If x is a Distribution neither u nor dof should be specified. If x is a gummy then all other parameters are ignored and
gummy(x)
is equivalent tox.copy(formatting=True)
.u (float >= 0, optional,) – A number representing the uncertainty in x. By default u is taken to be the standard (“1-sigma”) uncertainty. But if k or p are specified then u is taken to be the corresponding expanded uncertainty. The default value for u is 0.
unit (str or Unit, optional) – The units of the gummy. This may be a Unit object or, more commonly, a string that references a Unit object, e.g.
gummy(1,unit='kg')
orgummy(3.67,0.22,unit='m/s')
. The default is one.dof (float or int > 0, optional) – The number of degrees of freedom upon which the uncertainty is based. The default is
float('inf')
.k (float > 0 or None, optional) – The coverage factor if u is an expanded uncertainty. The value of the u parameter is divided by the coverage factor to get the standard uncertainty for the new gummy. If the parameter p is specified then the coverage factor is calculated using p and the value of the k parameter is ignored. The default for k is 1.
p (float between 0 and 1 or None, optional) – The level of confidence or probability level if u is an expanded uncertainty. If this parameter is specified, then the coverage factor is calculated using dof and the method specified by the p_method parameter. The standard uncertainty for the gummy is then set to u divided by the coverage factor.
p_method ({‘loc’, ‘cp’, ‘gauss’, ‘ccp’, ‘chebyshev’, None}, optional) – If the p parameter is specified, p_method `sets the method that is used to calculate the coverage factor. If `p_method is None then the value of gummy.p_method is used (which in turn has a default of ‘loc’).
If p_method = ‘loc’, then the uncertainty is assumed to be represented by a normal probability distribution if dof = float(‘inf’) and shifted and scaled Student’s t distribution otherwise. If p_method = ‘gauss’ or ‘cp’ then the Gauss inequality is used, and if p_method = ‘chebyshev’ or ‘ccp’ then the Chebyshev inequality is used. For p = 0.95 and dof = float(‘inf’), p_method = ‘loc’ gives k = 2.0, while p_method = ‘gauss’ gives k = 3.0 and p_method = ‘chebyshev’ gives k = 4.5.
uunit (str, Unit or None, optional) – This represents the units of u. It may be a unit with the same dimension as the unit parameter, e.g. a measurement result of 3 m with an uncertainty of 1 mm can be represented by
gummy(3,1,unit='m',uunit='mm')
The uunit parameter can also be a dimensionless unit if u represents a relative uncertainty, e.g. the gummy above can be equivalently represented bygummy(3,0.1,unit='m',uunit='%')
. If this is set to None, then the units of u are taken to be the same as those of x (as given by the unit parameter). The default is None.utype (str or None, optional) – An arbitrary string value labeling the uncertainty type. When a calculation is performed with gummys, the combined uncertainty of effective degrees of freedom from one particular uncertainty type can be found in the calculation result with the ufrom and doffrom methods. E.g. you can create a set of gummys with uncertainties assigned either utype “A” or utype “B”, insert them into a measurement equation and find the combined utype “A” uncertainty. The default is None.
name (str or None, optional) – An arbitrary string naming the gummy. The name is used when displaying the gummy value and serves no other function. The default is None.
- property U¶
Gets the expanded uncertainty. This property is read-only but changing the coverage factor (setting the k property), the level of confidence (setting the p property), or changing the units of the uncertainty (setting the uunit property) will change the U return value. This property returns a float.
The expanded uncertainty U (see the U property) is related to the standard uncertainty u (see the u property) by U = k`*`u. The coverage factor k can be set directly or the desired level of confidence p (see the p property) can be set an k will be calculated based on either a normal distribution if the number degrees of freedom (see the dof property) for the uncertainty is infinite or a Student’s t distribution otherwise.
Setting this property will change the value of the p property.
Examples
>>> g = gummy(1,u=0.1) # Setting k = 2 gives U = 2*u >>> g.k = 2 >>> g.U 0.2
U may be expressed in different units from x by setting the uunit property.
>>> g = gummy(2,0.001,unit='m') >>> g.uunit = 'mm' >>> g.U 1
U can also be expressed as a relative uncertainty:
>>> g.uunit = '%' >>> g.U 0.05
The expanded uncertainty is used when printing the gummy:
>>> g 2.0000 m +/- 0.050%
- property Usim¶
Gets the expanded uncertainty plus and minus components calculated from Monte-Carlo data at the level of confidence given by the p property. The return value is a tuple equivalent to
(cisim[1] - xsim,xsim - cisim[0])
, see the cisym and xsym properties. If no simulated data is available a NoSimulatedDataError will be raised when this property is called; see the sim and simulate methods. Usym is ready-only, but changing the p or k properties will affect Usym.
- angle()¶
- classmethod apply(function, derivative, *args)¶
A classmethod that applies a function to one or more gummy or jummy objects propagating the uncertainty.
- Parameters
function (function) – The the function to be applied. For gummy.apply, ‘function’ should take one or more float arguments and return a float value or float array. For jummy.apply, ‘function’ may also take and return complex values.
- derivative (function) – The name of a second function that gives the derivatives
with respect to the arguments of function. derivative should take an equal number of arguments as function. If function takes one argument derivative should return a float and if function takes more than one argument then derivative should return a tuple, list or array of floats that contains the derivatives with respect to each argument. In the case of jummy.apply, the derivatives with respect to each argument may be real or complex values, in which case function is assumed to be holomorphic. Or the derivative may be a 2 x 2 matrix of the form:
- [[ du/dx, du/dy ],
[ dv/dx, dv/dy ]]
where function(x + j*y) = u + j*v.
*args (gummy, jummy, or float) – One or more arguments to which function will be applied. These arguments need not all be Dfunc objects; arguments such as floats will be taken to be constants with no uncertainty. They may also be numpy ndarrays in which case the usual numpy broadcasting rules apply.
- Returns
If none of the arguments are gummy or jummy then the return value is the same type as the return value of function. Otherwise gummy.apply returns a gummy and jummy.apply returns either a gummy or a jummy depending on whether function has a float or a complex return value.
- Return type
gummy, jummy
Examples
>>> import numpy as np >>> x = gummy(0.678,u=0.077) >>> gummy.apply(np.sin,np.cos,x) 0.627 +/- 0.060
>>> x = gummy(1.22,u=0.44) >>> y = gummy(3.44,u=0.67) >>> def dhypot(x,y): ... return (x1/sqrt(x1**2 + x2**2),x2/np.sqrt(x1**2 + x2**2)) >>> gummy.apply(np.hypot,dhypot,x,y) 3.65 +/- 0.65
- ascii(**kwds)¶
Prints the gummy formatted using only ASCII characters. All parameters are optional. Any parameters that are not None override the corresponding attributes of the calling gummy.
- bayesian = False¶
- budget(xlist, **kwds)¶
Returns a Budget object that can be used to display an uncertainty budget table listing the the contributions of the gummys in xlist to the total uncertainty in the calling gummy.
To display the table use the Budget.html() or Budget.latex() methods in a console or notebook that supports this type of output or the python built-in function to get a unicode table.
The Budget.tohtml() and Budget.tolatex() methods can be used to get strings with the html or latex code.
The Budget.df property can be used to retrieve a pandas DataFrame with the table. Also Budget.df_str, Budget.df_html and Budget.df_latex return DataFrames with formatted strings as entries rather than numerical values.
- Parameters
xlist (array_like of gummy) – The independent variables. Warnings will be generated if the gummys in this list over determine self (that is if not all variables in this list can be treated as independent variables) or under determine self (that is if some variables contributing to the uncertainty in self are missing).
uunit (str or Unit, optional) – Unit to use to express the uncertainties. This useful if you wish to express all uncertainties as relative uncertainty unit (e.g. %).
k, p (float, optional) – k or p values for the expanded uncertainty; do not specify both k and p; if neither are specified the the k and p values of self are used
sort (bool, optional) – Whether or not to sort the gummys in xlist by significance.
columns (list of str or None, optional) – Allows the user to select the columns (and ordering of the columns) for display. The available columns are:
“component” or “name”: the names of the gummy, displayed by default
- “description”: description given in the description parameter list,
displayed by default if the description parameter is not None
“unit”: the unit of the gummy, displayed by default
“value”: the x value of the gummy, displayed by default
- “u” or “uncertainty”: The uncertainty of the gummy. This is the
standard uncertainty except possible in the last row where an expanded uncertainty is displayed. This column is displayed by default.
- “dof”: the degrees of freedom for the uncertainty, displayed by default
if any uncertainty has finite degrees of freedom
- “type”: the uncertainty type, displayed by default if any gummy has
a type defined
- “s” or “significance”: the sensitivity coefficient (below) multiplied
by the standard uncertainty, displayed by default
- “d”, “derivative” or “partial”: the partial derivative of the y gummy
with resect to the gummy in that row
“c” or “sensitivity coefficient”: the absolute value of “d”
- “custom”: value given in the custom parameter list, displayed by default
if the custom parameter is not None
The columns displayed can also be set with the columns property.
column_names (dict or None, optional) – Names to display as column headers, if this is None then the default names are used. The dictionary should use as keys any of the column names listed above in the columns parameter description and as values the desired heading for this column. The column names can also be set with the column_names property.
show_subtotals (bool, optional) – If any uncertainty types are defined, the combined standard uncertainty for each type is displayed in the table. This can also be changed by setting the show_subtotals attribute. The default is True.
show_expanded_u (bool or None, optional) – Whether or not to display the expanded uncertainty in the last row. If this is None, then the expanded uncertainty is displayed if ` self.k != 1`. This can also be changed by setting the show_expanded_u attribute.
show_s (bool, optional) – Whether or not to show the significance column. This is ignored if the columns parameter is not None. The default can be changed by setting the attribute class attribute Budget.show_s. The default value is True.
show_d (bool, optional) – Whether or not to show the partial derivatives column. This is ignored if columns is not None. The default can be changed by setting the attribute class attribute Budget.show_d. The default is True.
show_c (bool, optional) – Whether or not to show the sensitivity coefficient column. This is ignored if columns is not None. The default can be changed by setting the attribute class attribute Budget.show_c. Teh default value is False
units_on_values (bool or None) –
- If this is True, units are shown in the value and u columns and if False
the units are in a separate column. If None then the units are in a separate column unless any gummy in xlist or y has a uunit defined.
sim (bool, optional) – If True, the combined uncertainty and partial derivatives will be calculated using Monte-Carlo data. The default is False
css (str or None, optional) – A css header to be used when displaying the table in HTML format. If this is None then Budget.default_css will be used.
description (list of str or None, optional) – An optional column of descriptions to be printed in the table. This should be a description for y then for each x, and followed, optionally, by subtotal and expanded uncertainty descriptions.
description_math_mode (bool, optional) – If this is False, then when using a LaTeX format, the description is put in normal text mode rather than math mode. The default is False
custom (list of str or None, optional) – An optional column of additional information to be printed in the table. This should be a value for y then for each x, and followed, optionally, by subtotal and expanded uncertainty values.
custom_heading (str or None, optional) – A heading for the custom column.
custom_math_mode (bool) – If this is False, then when using a LaTeX format, the custom value is put in normal text mode rather than math mode. The default value is False.
solidus, mulsep, slashaxis – see gummy.solidus, gummy.mulsep and gummy.slashaxis
- cimethod = 'shortest'¶
- property cisim¶
Gets the confidence interval using the Monte-Carlo data with the level of confidence as set with the p property. A tuple is returned with the first element giving the lower limit and the second element giving the upper limit of the confidence interval. If the cimethod property is set to “shortest”, the confidence interval with the shortest length will be found and if the cimethod is set to “symmetric” the probabilities outside the interval on either side will be equal. If no simulated data is available a NoSimulatedDataError will be raised when this property is called; see the sim and simulate methods. This property is read-only, but changing the p, k, or cimethod properties will affect the return value.
- conjugate()¶
returns a copy of the gummy
- copy(formatting=True, tofloat=False)¶
Returns a copy of the gummy. If the formatting parameter is True the display formatting information will be copied and if False the display formatting will be set to the default for a new gummy. The default for formatting is True. If tofloat is true the x and u properties will be converted to float values before copying.
- correlation(gummy)¶
Returns the correlation coefficient between self and g.
- static correlation_matrix(gummys)¶
Returns the correlation matrix of a list or array of gummys.
- static correlation_matrix_sim(gummys)¶
The staticmethod takes a list of gummys an returns the correlation matrix calculated from Monte-Carlo data. The return value is numpy ndarray.
See the method gummy.correlation_matrix(gummys) for the corresponding result based on first order error propagation.
- correlation_sim(gummy)¶
Returns the correlation coefficient, calculated from Monte-Carlo data, between the owning gummy and the gummy g.
See the method gummy.correlation(g) for the corresponding result based on first order error propagation.
- covariance(gummy)¶
Returns the covariance between self and g.
- static covariance_matrix(gummys)¶
Returns the variance-covariance matrix of a list or array of gummys.
- static covariance_matrix_sim(gummys)¶
The staticmethod takes a list of gummys an returns the variance-covariance matrix calculated from Monte-Carlo data. The return value is numpy ndarray.
See the method gummy.covariance_matrix(gummys) for the corresponding result based on first order error propagation.
- covariance_sim(gummy)¶
Returns the covariance, calculated from Monte-Carlo data, between the owning gummy and the gummy g.
See the method gummy.covariance(g) for the corresponding result based on first order error propagation.
- static covplot(x, y, title=None, xlabel=None, ylabel=None, mean_marker=False, mean_marker_options={}, hold=False, math=None, **plot_options)¶
Creates scatter plot showing the covariance between two gummys.
- Parameters
x (gummy) – The gummy to plot on the horizontal axis.
y (gummy) – The gummy to plot on the vertical axis.
title (str or None, optional) – A title for the plot. If this is omitted or set to None then the correlation will be displayed as the title.
xlabel (str or None, optional) – A label for the horizontal axis. If this os omitted or None then that axis will be labeled either “x” or with the x gummy’s unit.
ylabel (str or None, optional) – A label for the vertical axis. If this os omitted or None then that axis will be labeled either “y” or with the y gummy’s unit.
mean_marker (bool, optional) – Whether or not to display line markers at the mean values of x and y. The default is False.
mean_marker_options (dict, optional) – A dictionary of options to be passed to the pyplot.axvline and pyplot.axhline methods that draw the mean_marker.
hold (bool, optional) – If this is False then
pyplot.show()
is called before this method exits. If it is Truepyplot.show()
is not called. The default is False.plot_options (These are optional keyword arguments that are passed to) – the pyplot.plot method. For example
ms=0.1
decreases the size of the dots in the plot.
- classmethod create(x, u=0, unit=one, dof=inf, k=1, p=None, uunit=None, utype=None, name=None, correlation_matrix=None, covariance_matrix=None)¶
A class method that creates a list of correlated gummys.
- Parameters
x – Either a list of floats corresponding to the x-value of each gummy or an and instance of a MultivariateDistribution sub-class.
u, unit, dof, k, p, uunit, utype, and name – Lists that correspond to the parameters in the gummy initializer (with the i-th value in each list passed to the initializer for the i-th gummy). With the exception of the “name” parameter, these may also be a single value with this same value is to passed to each initializer.
correlation_matrix – A list or array to be used as the correlation matrix of the gummys. This is optional and must be set to the default value of None if the covariance_matrix is specified.
covariance_matrix – A list or array to be used as the variance-covariance matrix of the gummys. If the covariance matrix is` specified the u parameter will be ignored This parameter is optional and must be set to the default value of None if the correlation_matrix is specified. If both the correlation_matrix and the covariance_matrix are None (or omitted) then the gummys will be uncorrelated.
- Return type
a list of gummys
Notes
This package does not implement a multivariate Student’s t distribution that has differing degrees of freedom for each component. So if if the elements of dof are finite and not all the same and either a correlation_matrix or a covariance_matrix is defined, the joint distribution for Monte-Carlo calculations (but not first- order calculations) will default to a multivariate normal distribution.
- property distribution¶
read-only
Returns ths Distribution instance associated with the gummy.
- property dof¶
float, read-only
Returns the number or degrees of freedom that the uncertainty of the gummy is based on. If the gummy was created as the result of an operation between two or more other gummys, then the dof is the effective number of degrees of freedom calculated using the Welch-Satterthwaite approximation. Caution: A variation of the the Welch-Satterthwaite approximation is used that takes into account correlations, see [R. Willink, Metrologia, 44, 340 (2007)]. However correlations are not handled perfectly. So if accurate dof calculations are need, care should be taken to ensure that correlations are not generated in intermediate calculations.
- doffrom(x)¶
Gets the degrees of freedom contributed from particular gummys or utypes if all other free variables are held fixed. Caution: any correlations in the calculations can cause errors in dof calculations.
- Parameters
x (gummy, str, or array_like) – A gummy, a string referencing a utype or a list containing gummys and strings.
- Return type
float
Example
>>> a = gummy(1.2,0.2,dof=5,utype='A') >>> b = gummy(3.2,0.5,dof=7,utype='A') >>> c = gummy(0.9,0.2,utype='B') >>> d = a + b + c >>> d.doffrom('A') 9.0932962619709627
- exception_on_fmt_error = False¶
- property finfo¶
- get_name(fmt='unicode', norm=None)¶
- Parameters
fmt (The format, must be a str in {‘unicode’,’html’,’latex’,’ascii’}.) – The default is ‘unicode’.
norm (An optional function which returns the name in nomral text. This) – function is applied to the name before it is returned if fmt = ‘latex’, name has been set to single string, and the name is more than one character long. The default is ‘text{’ + name + ‘}’.
- Return type
str, the name in the requested format.
- graft(unit)¶
Returns a copy of the gummy with different units but the same x and u values. This is different from
gummy.convert(unit)
in thatgummy.convert(unit)
changes the x and u `values to express the same quantity in different units while `gummy.graft(unit) simply tacks on a different unit to the same numerical values.- Parameters
unit (str or Unit) – The unit for the x value and if uunit is None, the uncertainty. It must be string, None, a Unit object, or the integer 1. Both 1 and None will be interpreted as the Unit instance one.
- hist(title=None, xlabel=None, p=None, show_p=True, title_style=None, mean_marker=True, mean_marker_options={}, ci_marker=True, ci_marker_options={}, hold=False, math=None, norm=None, **plot_options)¶
Plots a histogram of the Monte-Carlo data for the gummy. Before calling this method gummy.sim or gummy.simulate must be called to generate the Monte-Carlo data.
- Parameters
all parameters are optional
title (str or None, optional) – A title for the plot. If this is omitted or set to None then a title will be generated using the gummy name (if it has one) and the mean value and confidence interval. The title will also give the standard deviation of the date. The formatting of the auto-generated title depends on the value of the title_style parameter.
xlabel (str or None, optional) – A label for the horizontal axis of the plot. If this is omitted or set to None then a label will be generated using the name and unit of the gummy. If xlabel is None and the gummy has no name and a unit of one, then the horizontal axis will not be labeled.
p (float between 0 and 1 or None) – The probability for the confidence interval (as printed in the title and indicated by the ci_markers). If this is None then the value of the gummy.p class property is used. The default is None.
show_p (bool, optional) – Whether or not to show the level of confidence in the title if the title is auto-generated. The default value is True
title_style ({‘pmsim’,’pmsimi’,’cisim’,’mcisym’,’xsim’,’xfsim’,’usim’,’ufsim’}, optional) – The style for displaying the value in the title. See the gummy.style property for details. It this is None or omitted then the value of the gummy.style class property is used.
mean_marker (bool, optional) – Whether or not to display a vertical line at the mean value The default is True.
mean_marker_options (dict, optional) – A dictionary containing keywords to be passed to the pyplot.axvline method which draws the mean marker. For example setting this to
{'color'='r','linewidth'=4}
makes the mean marker red and with a thickness of four points.ci_marker (bool, optional) – Whether or not to display vertical lines at the upper and lower limits of the confidence interval. The default is True.
ci_marker_options (dict, optional) – A dictionary containing keywords to be passed to the pyplot.axvline method which draws the confidence interval markers.
hold (bool, optional) – If this is False
pyplot.show()
is called before this method exits. If it is Truepyplot.show()
is not called. The default is False.plot_options – These are optional keyword arguments that are passed to the pyplot.hist method. For example bins=50 overrides the default number of bins (100). For other options see the pyplot.hist documentation.
- html(**kwds)¶
` Prints the gummy using HTML if this method is executed from an Ipython console or from a Jupyter or Ipython notebook. All parameters are optional. Any parameters that are not None override the corresponding attributes of the calling gummy.
- property imag¶
- property independent¶
bool, read-only
Returns False if the owning gummy was created from a operation involving other gummys or has zero uncertainty and True otherwise.
- property k¶
Get or set the coverage factor; must be > 0.
The expanded uncertainty U (see the U property) is related to the standard uncertainty u (see the u property) by U = k`*`u. The coverage factor k can be set directly or the desired level of confidence p (see the p property) can be set an k will be calculated based on either a normal distribution if the number degrees of freedom (see the dof property) for the uncertainty is infinite or a Student’s t distribution otherwise.
Setting this property will change the value of the p property.
Examples
Setting k = 2 gives U = 2*`u`:
>>> g = gummy(1,u=0.1) >>> g.k = 2 >>> g.U 0.2
The p property has been set based on the value of k:
>>> g.p 0.95449973610364158
Changing the p property will change the value of the k property:
>>> g.p = 0.9973 >>> g.k 2.9999769927034015
- property ksim¶
read-only
Returns
0.5*(gummy.Usim[0] + gummy.Usim[1])/gummy.usim
- latex(**kwds)¶
Prints the gummy using LaTeX if this method is executed from an Ipython console or from a Jupyter or Ipython notebook. All parameters are optional. Any parameters that are not None override the corresponding attributes of the calling gummy.
- max_digits = 15¶
- mulsep = False¶
- property name¶
gets or sets an optional name for the gummy, may be str, None or a length four tuple of str. If name is set to a length four tuple the elements are, in order, the unicode name, the html name, the latex name and the ASCII name. Getting this property returns only the unicode name not the full tuple. Use the get_name method to get the name in html, latex or ASCII format.
- classmethod napply(function, *args, fxx=None)¶
gummy.napply(function, arg1, arg2, …) and jummy.napply(function, arg1, arg2, …)
A classmethod that applies a function to one or more gummy or jummy objects propagating the uncertainty. This method is similar to apply except that the derivatives are computed numerically so a derivative function does not need to be supplied.
- Parameters
function (function) – The the function to be applied. For gummy.apply, ‘function’ should take one or more float arguments and return a float value r float array. For jummy.apply, ‘function’ may also take and return complex values.
*args (gummy, jummy, or float) – One or more arguments to which function will be applied. These arguments need not all be Dfunc objects; arguments such as floats will be taken to be constants with no uncertainty. They may also be numpy ndarrays in which case the usual numpy broadcasting rules apply.
- Returns
If none of the arguments are gummy or jummy then the return value is the same type as the return value of function. Otherwise gummy.apply returns a gummy and jummy.apply returns either a gummy or a jummy depending on whether function has a float or a complex return value.
- Return type
gummy, jummy
Examples
>>> import numpy as np >>> x = gummy(0.678,u=0.077) >>> gummy.napply(np.sin,x) 0.627 +/- 0.060
>>> x = gummy(1.22,u=0.44) >>> y = gummy(3.44,u=0.67) >>> gummy.napply(np.hypot,x,y) 3.65 +/- 0.65
- nsig = 2¶
- property p¶
Get or set the level of confidence; must be in the interval (0,1).
The expanded uncertainty U (see the U property) is related to the standard uncertainty u (see the u property) by U = k`*`u. The coverage factor k can be set directly or the desired level of confidence p (see the p property) can be set an k will be calculated based on either a normal distribution if the number degrees of freedom (see the dof property) for the uncertainty is infinite or a Student’s t distribution otherwise.
Setting this property will change the value of the “k” property.
Examples
Setting k = 2 gives U = 2*`u`:
>>> g = gummy(1,u=0.1) >>> g.k = 2 >>> g.U 0.2
The p property has been set based on the value of k:
>>> g.p 0.95449973610364158
Changing the p property will change the value of the k property:
>>> g.p = 0.9973 >>> g.k 2.9999769927034015
- property real¶
returns a copy of the gummy
- sci_notation = None¶
- sci_notation_high = 7¶
- sci_notation_low = -3¶
- show_dof = None¶
- show_k = None¶
- show_name = True¶
- show_p = None¶
- sim(n=100000, ufrom=None)¶
Generates Monte-Carlo data for this gummy. Calling this method erases previously generated Monte-Carlo data for all gummys, so use the gummy.simulate() staticmethod if you need Monte-Carlo data for several gummys simultaneously.
- Parameters
n (int > 0, optional) – The number of samples to generate. The default value is 100000.
ufrom (None, gummy, str or array_like) – If this is not None, then only the gummys referenced here will be allowed to vary, and all other gummys will be held fixed at their mean values. This can be a gummy, a string referencing a utype or a list containing gummys and strings. The default value is None.
- property simdata¶
numpy.ndarray, read-only
Returns an array containing the Monte-Carlo simulation data. A NoSimulatedDataError is raised if no Monte-Carlo data is available.
- property simsorted¶
numpy.ndarray, read-only
Returns a sorted array containing the Monte-Carlo simulation data. A NoSimulatedDataError is raised if no Monte-Carlo data is available.
- static simulate(gummys, n=100000, ufrom=None)¶
Generates Monte-Carlo data for one or more gummys. Calling this method erases previously generated Monte-Carlo data for all gummys. See also the gummy.sim() method to generate data for one gummy only.
- Parameters
n (int > 0, optional) – The number of samples to generate. The default value is 100000.
ufrom (None, gummy, str or array_like) – If this is not None, then only the gummys referenced here will be allowed to vary, and all other gummys will be held fixed at their mean values. This can be a gummy, a string referencing a utype or a list containing gummys and strings. The default value is None.
- slashaxis = True¶
- solidus = True¶
- splonk()¶
splonks the gummy
- style = 'concise'¶
- thousand_spaces = True¶
- toascii(**kwds)¶
Returns a string with the value formatted so that only ASCII characters are used. All parameters are optional. Any parameters that are not None override the corresponding attributes of the calling gummy. This is equivalent to the gummy.tostring method with the fmt parameter set ‘ascii’.
- tohtml(**kwds)¶
Returns a string with the value as an html fragment. All parameters are optional. Any parameters that are not None override the corresponding attributes of the calling gummy. This is equivalent to the gummy.tostring method with the `fmt parameter set to ‘html’.
- tolatex(**kwds)¶
Returns a string with the value as an LaTeX fragment. It is assumed that LaTeX is in math mode. All parameters are optional. Any parameters that are not None override the corresponding attributes of the calling gummy. This is equivalent to the gummy.tostring method with the fmt parameter set to ‘latex’.
- tostring(fmt=None, style=None, k=None, p=None, show_k=None, show_p=None, show_dof=None, show_name=None, name=None, norm=None, raw=False, nsig=None, solidus=None, mulsep=None, **kwds)¶
Returns a string displaying the value of the gummy in the desired format. The fmt parameter is a string with the value in {“unicode”,”latex”, “html”,”ascii”} or None. fmt will default to ‘ascii’ if self.printer is ‘ascii’ or ‘unicode’ otherwise. Any other parameters that are not None override the corresponding attributes of self.
- toummy()¶
returns a Quantity with an ummy value.
- property u¶
Gets the gummy standard uncertainty in the units given by the units property (not the uunits property). The standard uncertainty is sometimes called the “1-sigma” uncertainty. The This property is read-only and returns a float.
- property ubreakdown¶
list of str or None, default is None
If this is set to a list containing strings referencing utypes then when the gummy is printed, the uncertainty from each utype will be displayed separately.
Examples
>>> a = gummy(1.2,0.2,utype='A') >>> b = gummy(3.2,0.5,utype='A') >>> c = gummy(0.9,0.2,utype='B') >>> d = a + b + c >>> d 5.30(57) >>> d.ubreakdown = ['A','B'] >>> d 5.30(54)(20) >>> d.style = 'ueq' >>> d 5.30 with u(A) = 0.54 and u(B) = 0.20
- ufrom(x, sim=False)¶
Gets the standard uncertainty contributed from particular gummys or utypes if all other free variables are held fixed.
- Parameters
x (gummy, str, or array_like) – A gummy, a string referencing a utype or a list containing gummys and strings.
- Return type
float
Example
>>> a = gummy(1.2,0.2,utype='A') >>> b = gummy(3.2,0.5,utype='A') >>> c = gummy(0.9,0.2,utype='B') >>> d = a + b + c >>> d.ufrom('A') 0.53851648071345048
- unicode(**kwds)¶
Prints the gummy. All parameters are optional. Any parameters that are not None override the corresponding attributes of the calling gummy.
- property unit¶
Gets or sets the unit for x `and, if the `uunit attribute is None, the units for the uncertainty.
If this property is set, a unit conversion will be performed. The value it is set to may be a string, None, a Unit object, or the integer 1. Both 1 and None will be interpreted as the Unit instance one. A NoUnitConversionFoundError will be raised if the unit conversion is not possible.
Example
>>> x = gummy(0.001,unit='V') >>> x 0.001 V >>> x.unit = 'uV' >>> x 1000.0 uV
- property usim¶
Gets the standard deviation of the Monte-Carlo data. If no simulated data is available a NoSimulatedDataError will be raised when this property is called; see the sim and simulate methods. This property is read-only.
- property utype¶
str or None
An arbitrary string value labeling the uncertainty type.
- property uunit¶
Gets or sets the units for the expanded uncertainty (see the U property). This property may be set to a unit with the same dimension as the unit property or to a dimensionless unit such at “%” or “ppm” in which case U will be a relative uncertainty. Setting uunit to None puts U in the units given by the units property.
Examples
U may be expressed in different units from x by setting the uunit property.
>>> g = gummy(2,0.001,unit='m') >>> g.uunit = 'mm' >>> g.U 1
U can also be expressed as a relative uncertainty:
>>> g.uunit = '%' >>> g.U 0.05
Setting uunit to None changes the units of U back to the original units: >>> g.uunit = None >>> g.U 0.001
More examples: >>> g = gummy(0.001,0.0000012,unit=’V’) >>> g (0.001 000 0 +/- 0.000 001 2) V >>> g.unit = ‘uV’ >>> g (1000.0 +/- 1.2) uV >>> g.uunit = ‘%’ >>> g.unit = ‘mV’ >>> g 1.0000 mV +/- 0.12% >>> g.unit = ‘uV’ >>> g 1000.0 uV +/- 0.12% >>> g.uunit = None >>> g (1000.0 +/- 1.2) uV
- property uunit_is_rel¶
Returns True if gummy.U is a relative uncertainty and False otherwise. This property is read-only.
- property x¶
Gets the gummy’s value. Usually this is the mean of the probability distribution. This property is read-only and returns a float.
- property xsim¶
Gets the mean value of the Monte-Carlo data. If no simulated data is available a NoSimulatedDataError will be raised when this property is called; see the sim and simulate methods. This property is read-only.
- class metrolopy.gummy.jummy(real=None, imag=None, r=None, phi=None, cov=None, name=None)¶
Bases:
metrolopy.ummy.immy
- get_name(fmt='unicode', norm=None)¶
- property name¶
- show_name = True¶
- splonk()¶
splonks the jummy
- toimmy()¶
returns an immy representation of the jummy
- tostring(fmt='unicode', norm=None, show_name=None, name=None, style=None, **kwds)¶
metrolopy.logunit module¶
Unit and Conversion sub-classes are defined here to implement logarithmic units.
- class metrolopy.logunit.LogConversion(reference, multiplier, log_base, log_func, offset=0)¶
Bases:
metrolopy.nonlinearunit.NonlinearConversion
- copy()¶
- frm(g)¶
- log_func(x)¶
- to(g)¶
- class metrolopy.logunit.LogUnit(*p, **kwds)¶
Bases:
metrolopy.nonlinearunit.NonlinearUnit
- get_composite(ul)¶
- zero()¶
metrolopy.mean module¶
Some miscellaneous functions that are useful for uncertainty analysis.
- metrolopy.mean.autocorrelation(x)¶
Find the de-meaned and normalized autocorrelation of the array x
- metrolopy.mean.delta_diff(x)¶
Returns a list containing differences of the type:
x[1] - (x[0]+x[2])/2 , (x[1]+x[3])/2 - x[2], x[3] - (x[2]+x[4])/2, ...
Differences of this type are useful when we want the difference between alternate points in a data set (e.g. we are alterately switching between a signal and a background). This delta type difference removes the effect of a slow drift from the data.
- Parameters
x (array_like of float) – the data
- Return type
numpy.ndarray
Notes
We assume the signal is in the second element (array index 1 and all elements with odd indices) and the background is in the first element (array index 0 and all elements with even indices).
- metrolopy.mean.delta_diff_mean(x, n_sigma=None, unit=1)¶
Returns a gummy representing the mean value and uncertainty of a delta type difference taken on the data. A delta type difference removes a linear drift from the data by taking differences:
x[1] - (x[0]+x[2])/2 , (x[1]+x[3])/2 - x[2], x[3] - (x[2]+x[4])/2, ...
- Parameters
x (array_like of float) – the data
n_sigma (int, optional) – If this is not None, then
sigma_trim(x, n_sigma_trim)
is applied to the differences before taking the mean. Set this argument to None if you don’t want sigma_trim to be applied. The default value is None.unit (str, Unit or 1) – The unit of returned gummy. The default is 1.
bayesian (bool, optional) – If bayesian is False the standard uncertainty of the returned gummy is s/sqrt(n) where s is the standard deviation of x and n is the the number of samples (or n_eff). If bayesian is True then the standard uncertainty is sqrt((n-1)/(n-3))*s/sqrt(n). If bayesian is None then the value of gummy.bayesian will be used. The default value is None.
- Returns
A gummy representing the mean of the differences along with the uncertainty and effective degrees of freedom.
- Return type
gummy
- metrolopy.mean.delta_sum(x)¶
Returns a list containing differences of the type:
x[1] + (x[0]+x[2])/2 , (x[1]+x[3])/2 + x[2], x[3] + (x[2]+x[4])/2, ...
- Parameters
x (array_like of float) – the data
- Return type
numpy.ndarray
- metrolopy.mean.delta_sum_mean(x, n_sigma=None, unit=1)¶
Returns a gummy representing the mean value and uncertainty of a delta type difference taken on the data. A delta type difference removes a linear drift from the data by taking differences:
x[1] + (x[0]+x[2])/2 , (x[1]+x[3])/2 + x[2], x[3] + (x[2]+x[4])/2, ...
- Parameters
x (array_like of float) – the data
n_sigma (int, optional) – If this is not None, then
sigma_trim(x, n_sigma_trim)
is applied to the differences before taking the mean. Set this argument to None if you don’t want sigma_trim to be applied. The default value is None.unit (str, Unit or 1, optional) – The unit of returned gummy. The default is 1.
- Returns
A gummy representing the mean of the differences along with the uncertainty and effective degrees of freedom.
- Return type
gummy
- metrolopy.mean.mean(x, n_sigma_trim=3, unit=1, ignore_nan=True, use_n_eff=None)¶
Returns a gummy representing the mean of a float array.
- Parameters
x (array_like of float or int) – the value to be averaged
n_sigma_trim (int, optional) – If this is not None, then
sigma_trim(x, n_sigma_trim)
is applied to the data before taking the mean. Set this argument to None if you don’t want sigma_trim to be applied. The default value is 3.unit (str, Unit or 1) – The unit of returned gummy. The default is 1.
ignore_nan (bool, optional) – If this is True, elements with a
float('nan')
or None value will be ignored. The default value is Trueuse_n_eff (bool, optional) – Whether to use the n_eff function to calculate an effective number of degrees of freedom. If use_n_eff is None, then n_eff will be used if the length of x is greater or equal to 20. The default value is None.
bayesian (bool, optional) – If bayesian is False the standard uncertainty of the returned gummy is s/sqrt(n) where s is the standard deviation of x and n is the the number of samples (or n_eff). If bayesian is True then the standard uncertainty is sqrt((n-1)/(n-3))*s/sqrt(n). If bayesian is None then the value of gummy.bayesian will be used. The default value is None.
- metrolopy.mean.mean_datetime(*params)¶
- metrolopy.mean.n_eff(x, y=None)¶
Takes a series of data points which may be correlated and uses the auto-correlation of the set to find an effective number of data points such that an estimate of the standard uncertainty is (standard deviation)/sqrt(n_eff).
See [N.F. Zhang, Metrologia, 43, S276 (2006)] for details.
If only one argument is given it is assumed that the argument represents an array of evenly spaced values. This list may be a masked array, in which case the masked values are filled in with a linear interpolation.
If two arguments are passed to n_eff, then it is assumed that the two arrays represent an array of x values followed by an array representing the corresponding y values of a set (x,y) points. A cubic spline interpolation is used to get a set of evently spaced points.
- Returns
A float that represents the effective number of data points.
- Return type
float
- metrolopy.mean.sigma_trim(x, n_sigma=3)¶
Returns a masked array with data attribute equal to x and any elements more the n_sigma standard deviations from the mean masked. (The standard deviation is calculated excluding the masked outliers.)
- metrolopy.mean.wmean(x, chi_correct=False)¶
Takes an array of gummys and returns the weighted mean with weights that minimize the uncertainty of the returned value (taking into account correlations)
- Parameters
x (array_like of gummy) – the values to be averaged
chi_correct (bool, optional) – If this is True, the uncertainty of the returned value is multiplied by the square root of the reduced chi-squared of the residuals to take into account any under estimation of the uncertainties in x. The default is False
- Returns
a gummy representing the weighted mean
- Return type
gummy
metrolopy.nonlinearunit module¶
This module defines the Nonlinear Unit and Nonlinear Conversion abstract classes that are the base class for the LogUnit and OffsetUnit classes.
- class metrolopy.nonlinearunit.NonlinearConversion(unit, factor=1)¶
Bases:
metrolopy.unit.Conversion
Base class for non-linear conversions.
- chain(c)¶
- copy()¶
- linear = False¶
- pow(e)¶
- rchain(c)¶
- class metrolopy.nonlinearunit.NonlinearUnit(name, symbol, conversion=None, short_name=None, add_symbol=False, html_symbol=None, latex_symbol=None, ascii_symbol=None, description=None, order=- 1, **kwds)¶
Bases:
metrolopy.unit.Unit
Base class of non-linear units.
- from_uunit(u, unit)¶
- get_composite(ul)¶
- to_uunit(u, unit)¶
- zero()¶
metrolopy.nummy module¶
The nummy object defined here integrates the Monte-Carlo uncertainty propagation code in the distributions module with the ummy object. The nummy class is not intended to be used directly; rather it is utilized by the gummy class.
- class metrolopy.nummy.nummy(x, u=0, dof=inf, utype=None, name=None)¶
Bases:
metrolopy.ummy.ummy
- property Usim¶
- property bayesian¶
bool
Read/write at the class level, but read-only at the instance level. The default value is False; this should only be changed once at the beginning of the session. This property affects how the level of confidence p (sometimes called coverage probability) of an expanded uncertainty is related to the coverage factor k for a gummy based on data with finite degrees of freedom.
Standard uncertainties are often based on the standard deviation of a set of measurements (and the assumption that these measurements are drawn from a normally distributed population). Traditionally (e.g. the GUM 2008 edition) the standard uncertainty is taken to be the standard deviation of the mean (s/sqrt(n), where s is the sample standard deviation and n is the number of measurements). However there is some “extra uncertainty” because the sample standard devation not exactly equal to the population standard deviation. This is taken into account by using a Student’s t distribution to calculate the expanded uncertainty. However it has been pointed out, by those who advocate a Bayesian point of view, that the probability distribution for the measurand here is best described by a shifted and scaled Student’s t distribution. So the standard uncertainty should be the standard deviation of this distribution which is s*sqrt{(n-1)/[n*(n-3)]}. Thus
u(bayesian) = sqrt[dof/(dof - 2)]*u(traditional)
where dof = n - 1 and the “extra uncertainty” is incorporated directly into the standard uncertainty.
Example
>>> gummy.bayesian = True >>> g = gummy(1,0.03,dof=5) >>> g.bayesian True
- property cimethod¶
str in {‘shortest’, ‘symmetric’}), default is ‘shortest’
Get or set the method for calculating the confidence interval from Monte-Carlo data. If this property is set at the class level, it will change the default cimethod value for new gummys but will no affect gummys that have already been created.
Can be set either to the string ‘shortest’ or the string ‘symmetric’. This property gets or sets the method for calculating confidence intervals from Monte-Carlo data.
If it is set to ‘shortest’, the confidence interval will be taken to be the shortest interval that includes the desired fraction of the probability distribution.
If it is set to ‘symmetric’, then the confidence interval will be set so that, for n Monte-Carlo samples and a coverage probability of p, then n`*(1-`p)/2 samples lie below the lower limit of the confidence interval and the same number of samples lie above the upper limit of the confidence interval.
- property cisim¶
- static correlation_matrix_sim(gummys)¶
The staticmethod takes a list of gummys an returns the correlation matrix calculated from Monte-Carlo data. The return value is numpy ndarray.
See the method gummy.correlation_matrix(gummys) for the corresponding result based on first order error propagation.
- correlation_sim(g)¶
Returns the correlation coefficient, calculated from Monte-Carlo data, between the owning gummy and the gummy g.
See the method gummy.correlation(g) for the corresponding result based on first order error propagation.
- static covariance_matrix_sim(gummys)¶
The staticmethod takes a list of gummys an returns the variance-covariance matrix calculated from Monte-Carlo data. The return value is numpy ndarray.
See the method gummy.covariance_matrix(gummys) for the corresponding result based on first order error propagation.
- covariance_sim(g)¶
Returns the covariance, calculated from Monte-Carlo data, between the owning gummy and the gummy g.
See the method gummy.covariance(g) for the corresponding result based on first order error propagation.
- static covplot(x, y, title=None, xlabel=None, ylabel=None, hold=False, **kwds)¶
- classmethod create(x, u=0, dof=inf, name=None, correlation_matrix=None, covariance_matrix=None)¶
A class method that creates a list of (possibly) correlated ummys.
- Parameters
x – A list of floats corresponding to the x-value of each ummy.
u, dof, k, loc, utype (optional) – Lists that correspond to the parameters in the ummy initializer (with the i-th value in each list passed to the initializer for the i-th ummy). These may also be a single value with this same value is to passed to each initializer.
correlation_matrix (optional) – A list or array to be used as the correlation matrix of the ummys. This is optional and must be set to the default value of None if the covariance_matrix is specified. If both the correlation_matrix and the covariance_matrix are None (or omitted) then the ummys will be uncorrelated.
covariance_matrix (optional) – A list or array to be used as the variance- covariance matrix of the ummys. If the covariance matrix is specified the u parameter will be ignored This parameter is optional and must be set to the default value of None if the correlation_matrix is specified. If both the correlation_matrix and the covariance_matrix are None (or omitted) then the ummys will be uncorrelated.
- Return type
a list of ummys
- property distribution¶
read-only
Returns ths Distribution instance associated with the gummy.
- property dof¶
float, read-only
Returns the number or degrees of freedom that the uncertainty of the gummy is based on. If gummy.bayesian is set to False, then the Welch- Satterthwaite approximation is used to calculate the effective number of degrees of freedom for gummys that result from an operation between two or more other gummys. A version of the Welch-Satterthwaite approximation that takes into account correlations is used here, see [R. Willink, Metrologia, 44, 340 (2007)]. If gummy.bayesian is True then gummys that are the result from an opertaion between other gummys will always have dof = float(‘inf’).
- get_name(fmt='unicode', norm=None)¶
- hist(xlabel=None, title=None, hold=False, **kwds)¶
- property independent¶
bool, read-only
Returns False if the owning gummy was created from a operation involving other gummys and True otherwise.
- property ksim¶
read-only
Returns
0.5*(gummy.Usim[0] + gummy.Usim[1])/gummy.usim
- property name¶
- property p¶
- static set_seed(seed)¶
Sets the seed for the numpy.random.RandomState object shared by all Distribution instances.
- property simdata¶
numpy.ndarray, read-only
Returns an array containing the Monte-Carlo simulation data. A NoSimulatedDataError is raised if no Monte-Carlo data is available.
- property simsorted¶
numpy.ndarray, read-only
Returns a sorted array containing the Monte-Carlo simulation data. A NoSimulatedDataError is raised if no Monte-Carlo data is available.
- static simulate(nummys, n=100000, ufrom=None)¶
- splonk()¶
splonks the nummy
- toummy()¶
returns an ummy representaion of the nummy
- ufrom(x, sim=False)¶
Gets the standard uncertainty contributed from particular gummys or utypes if all other free variables are held fixed.
- Parameters
x (gummy, str, or array_like) – A gummy, a string referencing a utype or a list containing gummys and strings.
- Return type
float
Example
>>> a = gummy(1.2,0.2,utype='A') >>> b = gummy(3.2,0.5,utype='A') >>> c = gummy(0.9,0.2,utype='B') >>> d = a + b + c >>> d.ufrom('A') 0.53851648071345048
- property usim¶
- property xsim¶
metrolopy.offsetunit module¶
The OffsetUnit class was created to handle Celsius and Fahrenheit units.
- class metrolopy.offsetunit.OffsetConversion(unit, offset)¶
Bases:
metrolopy.nonlinearunit.NonlinearConversion
Represents a conversion of the form x -> x + offset.
- copy()¶
- frm(g)¶
- to(g)¶
- class metrolopy.offsetunit.OffsetUnit(*params, **kwds)¶
Bases:
metrolopy.nonlinearunit.NonlinearUnit
This class was created to handle units such as the degree Celsius and the degree Fahrenheit. This class takes the same parameters as the Unit class, but actually creates two unit instances…
- zero()¶
metrolopy.pmethod module¶
Functions and classes for converting between coverage factor k and level of confidence p.
- metrolopy.pmethod.ccp_from_k(k, dof=inf, bayesian=False)¶
- metrolopy.pmethod.conservative_coverage_probability(p, dof=inf, bayesian=False)¶
- metrolopy.pmethod.coverage_factor(p, dof=inf, bayesian=False)¶
Returns the k factor for a given level of confidence and degrees of freedom calculated from a normal or Student’s t distribution
Parameters:
- p: float
The level of confidence (as a fraction of 1).
- dof: float or int,
optional (default is float(‘inf’)), the degrees of freedom.
- Return type
float
- metrolopy.pmethod.coverage_probability(p, dof=inf, bayesian=False)¶
- metrolopy.pmethod.cp_from_k(k, dof=inf, bayesian=False)¶
- metrolopy.pmethod.loc_from_k(k, dof=inf, bayesian=False)¶
Returns the level of confidence given a coverage factor k and degrees of freedom for a Student’s t distribution.
- Parameters
k – float coverage factor.
dof – float or int, optional (default is float(‘inf’)), the degrees of freedom.
Returns: float
metrolopy.prefixedunit module¶
Classes to automatically generate prefixed units from a base unit.
- class metrolopy.prefixedunit.BinaryPrefixedUnit(name, symbol, conversion=None, short_name=None, additional_names=None, additional_short_names=None, add_symbol=False, html_symbol=None, latex_symbol=None, ascii_symbol=None, linear=True, description=None, order=- 1, prefixes=None, base_prefix=None, base_description=None, **kwds)¶
Bases:
metrolopy.prefixedunit.PrefixedUnit
- PrefixedUnit(name,symbol,conversion=None,short_name=None,
additional_names=None,additional_short_names=None, add_symbol=False,html_symbol=None,latex_symbol=None, ascii_symbol=None,description=None,order=-1,prefixes=None, base_prefix=None,base_description=None)
Creating an instance of this class not only creates the base unit but also adds units with with a set of prefixes to the unit library.
If the prefixes keyword is None then units with the following prefixes will be generated: kibi, mebi, gibi, tebi, pebi, exbi, zibi, yobi, kilo, mega, giga, tera, peta, exa, zetta and yotta.
- prefix_definitions = {'exa': [1e+18, 'E', None, None, None], 'exbi': [1152921504606846976, 'Ei', None, None, None], 'gibi': [1073741824, 'Gi', None, None, None], 'giga': [1000000000.0, 'G', None, None, None], 'kibi': [1024, 'Ki', None, None, None], 'kilo': [1000, 'k', None, None, None], 'mebi': [1048576, 'Mi', None, None, None], 'mega': [1000000.0, 'M', None, None, None], 'pebi': [1125899906842624, 'Pi', None, None, None], 'peta': [1000000000000000.0, 'P', None, None, None], 'tebi': [1099511627776, 'Ti', None, None, None], 'tera': [1000000000000.0, 'T', None, None, None], 'yobi': [1208925819614629174706176, 'Yi', None, None, None], 'yotta': [1e+24, 'Y', None, None, None], 'zetta': [1e+21, 'Z', None, None, None], 'zibi': [1180591620717411303424, 'Zi', None, None, None]}¶
- class metrolopy.prefixedunit.PrefixedUnit(name, symbol, conversion=None, short_name=None, additional_names=None, additional_short_names=None, add_symbol=False, html_symbol=None, latex_symbol=None, ascii_symbol=None, linear=True, description=None, order=- 1, prefixes=None, base_prefix=None, base_description=None, **kwds)¶
Bases:
metrolopy.unit.Unit
- PrefixedUnit(name,symbol,conversion=None,short_name=None,
additional_names=None,additional_short_names=None, add_symbol=False,html_symbol=None,latex_symbol=None, ascii_symbol=None,description=None,order=-1,prefixes=None, base_prefix=None,base_description=None)
Creating an instance of this class not only creates the base unit but also adds units with with a set of prefixes to the unit library.
If the prefixes keyword is None then units with the standard SI prefixes will be generated.
- prefix_definitions = {'atto': [1e-18, 'a', None, None, None], 'centi': [0.01, 'c', None, None, None], 'deca': [10, 'da', None, None, None], 'deci': [0.1, 'd', None, None, None], 'exa': [1e+18, 'E', None, None, None], 'femto': [1e-15, 'f', None, None, None], 'giga': [1000000000.0, 'G', None, None, None], 'hecto': [100, 'h', None, None, None], 'kilo': [1000, 'k', None, None, None], 'mega': [1000000, 'M', None, None, None], 'micro': [1e-06, 'μ', 'μ', None, 'u'], 'milli': [0.001, 'm', None, None, None], 'nano': [1e-09, 'n', None, None, None], 'peta': [1000000000000000.0, 'P', None, None, None], 'pico': [1e-12, 'p', None, None, None], 'tera': [1000000000000.0, 'T', None, None, None], 'yocto': [1e-24, 'y', None, None, None], 'yotta': [1e+24, 'Y', None, None, None], 'zepto': [1e-21, 'z', None, None, None], 'zetta': [1e+21, 'Z', None, None, None]}¶
metrolopy.printing module¶
This module contains code to support pretty printing of gummys using LaTex and HTML.
- class metrolopy.printing.MetaPrettyPrinter¶
Bases:
type
- property printer¶
Get or set the prefered display printer. This is a string with one of the following values:
“any”, “latex”, “html”, “unicode”, “ascii”, or “any_but_latex”
“any” will usually pick html or latex output when running in an IPython console or Jupyter notebook and unicode otherwise.
“any_but_latex” will usually pick html when running in an IPython console or Jupyter notebook and unicode otherwise.
“latex” and “html” are only available when running under IPython. If these printers are not available the display will default to “unicode”.
- class metrolopy.printing.PrettyPrinter¶
Bases:
object
- ascii(**kwds)¶
Prints a representation of the object using only ASCII characters. Equivalent to print(cls.tostring(fmt=’ascii’)). See the tostring method.
- break_on_printing_error = False¶
- html(**kwds)¶
Prints a representation of the object using HTML formatting if this method is called from an IPython console or Juptyer notebook. See the tostring method.
- latex(math=None, **kwds)¶
Prints a representation of the object using LaTeX formatting if this method is called from an IPython console or Juptyer notebook. See the tostring method.
- latex_math()¶
- latex_math_plot()¶
- latex_norm()¶
- latex_norm_plot()¶
- printer = 'any_but_latex'¶
- toascii(**kwds)¶
Returns a string representing this object formatted using only ASCII characters; equivalent to PrettyPrinter.tostring(fmt=’ascii’,**kwds). See the tostring method.
- tohtml(**kwds)¶
Returns a string representing this object formatted for html; equivalent to PrettyPrinter.tostring(fmt=’html’,**kwds). See the tostring method.
- tolatex(**kwds)¶
Returns a string representing this object formatted for LaTeX; equivalent to PrettyPrinter.tostring(fmt=’latex’,**kwds). See the tostring method.
- tounicode(**kwds)¶
Returns a string representing this object; equivalent to PrettyPrinter.tostring(fmt=’unicode’,**kwds) and PrettyPrinter.__str__(). See the tostring method.
- unicode(**kwds)¶
Prints a representation of the object. Equivalent to print(cls.tostring(fmt=’unicode’)). See the tostring method.
- metrolopy.printing.print_html(text)¶
- metrolopy.printing.print_latex(text)¶
- metrolopy.printing.print_markdown(text)¶
- metrolopy.printing.set_printer(value)¶
Sets the preferred default display printer. This is a string with one of the following values:
“any”, “latex”, “html”, “unicode”, or “ascii”
“any” will usually pick html or latex output when running in an IPython console or Jupyter notebook and unicode otherwise.
“latex” and “html” are only available when running under IPython. If these printers are not available the display will default to “unicode”.
metrolopy.relunits module¶
This module is loaded by the gummy.units module and is not intended be be imported directly. Dimensionless units are defined here.
- class metrolopy.relunits.RatioUnit(name, symbol, conversion=None, short_name=None, add_symbol=False, html_symbol=None, latex_symbol=None, ascii_symbol=None, description=None, order=- 1, **kwds)¶
Bases:
metrolopy.unit.Unit
RatioUnit is used for dimensionless units like % where powers, e.g. %**2, are not desired.
metrolopy.siunits module¶
This module is loaded by the unit module and is not intended be be imported directly.
The most of the units here are from the SI Brochure, 9th edition.
metrolopy.ummy module¶
The ummy object defined here was created primarily to separate the code for first-order uncertainty propagation from the other methods in the gummy object. But the ummy object can be used as a stripped down verison of gummy without the Monte-Carlo uncertainty propagation, unit, and pretty printing functionality of gummy.
- class metrolopy.ummy.GummyTag(tag_name)¶
Bases:
object
- get_values()¶
- static set_tag(g, tag)¶
- tags = <WeakValueDictionary>¶
- class metrolopy.ummy.MFraction(*args, **kwargs)¶
Bases:
fractions.Fraction
A fraction.Fraction sub-class that works with mpmath.mpf objects
- class metrolopy.ummy.MetaImmy¶
Bases:
metrolopy.printing.MetaPrettyPrinter
- property imag_symbol¶
str
The symbol for the unit imaginary number. The default is ‘j’.
- property style¶
str in {‘polar’,’cartesian’}
Sets whether to print the value using a cartesian or polar representaion. This property can be set at the class or instance level. The default is ‘cartesian’.
- class metrolopy.ummy.immy(real=None, imag=None, r=None, phi=None, cov=None)¶
Bases:
metrolopy.printing.PrettyPrinter
,metrolopy.dfunc.Dfunc
- angle()¶
Returns the polar angle in radians.
- conjugate()¶
Returns the complex conjugate.
- copy(formatting=True, tofloat=False)¶
Returns a copy of the jummy. If the formatting parameter is True the display formatting information will be copied and if False the display formatting will be set to the default for a new jummy. The default for formatting is True. If the tofloats parameter is True x and u for both the real and imaginary components will be converted to floats.
- property cov¶
Returns the variance-covariance matrix between the real and imaginary parts of the value, read-only.
- property imag¶
read-only Returns the imaginary part of the value.
- property phi¶
read-only Returns the polar angle of the value.
- property r¶
read-only Returns the magnitude of the value.
- property real¶
read-only Returns real part of the value.
- splonk()¶
- style = 'cartesian'¶
- tofloat()¶
Returns a copy of the gummy with x an u (for both the real and imaginary components) converted to floats.
- tostring(fmt='unicode', norm=None, nsig=None, style=None)¶
- property x¶
Returns complex(self.real.x,self.imag.x), read-only
- class metrolopy.ummy.ummy(x, u=0, dof=inf, utype=None)¶
Bases:
metrolopy.dfunc.Dfunc
,metrolopy.printing.PrettyPrinter
- angle()¶
- conjugate()¶
- copy(formatting=True, tofloat=False)¶
Returns a copy of the ummy. If the formatting parameter is True the display formatting information will be copied and if False the display formatting will be set to the default for a new gummy. The default for formatting is True. If tofloat is true the x and u properties will be converted to float values before copying.
- correlation(g)¶
Returns the correlation coefficient between self and g.
- static correlation_matrix(gummys)¶
Returns the correlation matrix of a list or array of ummys.
- covariance(g)¶
Returns the covariance between self and g.
- static covariance_matrix(gummys)¶
Returns the variance-covariance matrix of a list or array of ummys.
- classmethod create(x, u=None, dof=None, correlation_matrix=None, covariance_matrix=None)¶
A class method that creates a list of (possibly) correlated ummys.
- Parameters
x – A list of floats corresponding to the x-value of each ummy.
u, dof, k, loc, utype (optional) – Lists that correspond to the parameters in the ummy initializer (with the i-th value in each list passed to the initializer for the i-th ummy). These may also be a single value with this same value is to passed to each initializer.
correlation_matrix (optional) – A list or array to be used as the correlation matrix of the ummys. This is optional and must be set to the default value of None if the covariance_matrix is specified. If both the correlation_matrix and the covariance_matrix are None (or omitted) then the ummys will be uncorrelated.
covariance_matrix (optional) – A list or array to be used as the variance- covariance matrix of the ummys. If the covariance matrix is specified the u parameter will be ignored This parameter is optional and must be set to the default value of None if the correlation_matrix is specified. If both the correlation_matrix and the covariance_matrix are None (or omitted) then the ummys will be uncorrelated.
- Return type
a list of ummys
- property dof¶
float, read-only
Returns the number or degrees of freedom that the uncertainty of the ummy is based on. If the ummy was created as the result of an operation between two or more other gummys, then the dof is the effective number of degrees of freedom calculated using the Welch-Satterthwaite approximation. Caution: A variation of the the Welch-Satterthwaite approximation is used that takes into account correlations, see [R. Willink, Metrologia, 44, 340 (2007)]. However correlations are not handled perfectly. So if accurate dof calculations are need, care should be taken to ensure that correlations are not generated in intermediate calculations.
- doffrom(x)¶
Gets the degrees of freedom contributed from particular ummys or utypes if all other free variables are held fixed. Caution: any correlations in the calculations can cause errors in dof calculations.
- Parameters
x (ummy, str, or array_like) – A ummy, a string referencing a utype or a list containing ummys and strings.
- Return type
float
Example
>>> a = ummy(1.2,0.2,dof=5,utype='A') >>> b = ummy(3.2,0.5,dof=7,utype='A') >>> c = ummy(0.9,0.2,utype='B') >>> d = a + b + c >>> d.doffrom('A') 9.0932962619709627
- property finfo¶
- property imag¶
- max_digits = 15¶
- max_dof = 10000¶
- nsig = 2¶
- property real¶
- rounding_u = False¶
- sci_notation = None¶
- sci_notation_high = 7¶
- sci_notation_low = -3¶
- splonk()¶
returns self.x if u == 0 else returns self
- thousand_spaces = True¶
- tofloat()¶
Returns a copy of the gummy with x an u converted to floats.
- tostring(fmt='unicode', nsig=None, **kwds)¶
- property u¶
- ufrom(x)¶
Gets the standard uncertainty contributed from particular ummys or utypes if all other free variables are held fixed.
- Parameters
x (ummy, str, or array_like) – A ummy, a string referencing a utype or a list containing ummys and strings.
- Return type
float
Example
>>> a = ummy(1.2,0.2,utype='A') >>> b = ummy(3.2,0.5,utype='A') >>> c = ummy(0.9,0.2,utype='B') >>> d = a + b + c >>> d.ufrom('A') 0.53851648071345048
- property utype¶
str or None
An arbitrary string value labeling the uncertainty type.
- property x¶
metrolopy.unit module¶
Classes that for handling units are defined here: Conversion, Unit, _CompositeUnit, one, Quantity and QuantityArray
- class metrolopy.unit.Conversion(unit, factor=1)¶
Bases:
object
Represents a unit conversion. This class should only be used as arguments to Unit object initializers. Each conversion should be associated with one and only one parent Unit; do not re-use conversion instances with more than one Unit instance.
The base Conversion class is defined by a single conversion factor. More comlicated conversions overriding the to and frm methods should inherit from the NonlinearConversion subclass and be used with units that inherit from the NonlinearUnit subclass.
- Parameters
unit (str or Unit) – the Unit that the parent Unit will be converted to.
factor (float, optional) – The conversion factor between the parent Unit and the new Unit: [value with new Unit] = factor * [value with parent Unit]. The conversion factor may not have a unit, but may be an ummy of gummy with not unit one. The default value is 1.
- chain(c)¶
- copy()¶
- frm(g)¶
- linear = True¶
- pow(e)¶
- to(g)¶
- property unit¶
- class metrolopy.unit.Quantity(value, unit=one)¶
Bases:
metrolopy.printing.PrettyPrinter
Instances of this class represent a quantity with a value and a unit. The behavior of Quantity instances under mathematical operations with other Quanitity object or numerical values depends on the unit. E.g. an interger of float may be added to Quantity(1,unit=’%’) but not to Quantity(1,unit=’m/s’). For operations involving only linear units, the units will be automatically converted to facilitate the operation, e.g. Quantity(1,unit=’psi’) may be added to Quantity(1,unit=’psi’) but not Quantity(1,unit=’db(uPa)’. Manual unit conversions can be realized by calling the `Quantity.convert method, or in place by setting the Quantity.unit property.
Quantity instances may be created directly or by multiplying or dividing a number by a Unit instance: Quantity(2.2,unit=’cm’) is equivalent to 2.2 * unit(‘cm’).
- Parameters
value (number like including ummy) – the value of the Quantity
unit (str or Unit) – The Unit instance representing the unit of the Quantity or a string that references the Unit instance.
- property c¶
This read-only property is used as a conversion flag during calculations. When an arithmetic operation is carried out between two Quantaties with different units, a unit conversion on one of the input quantities may be required to complete the calculation. Attach this flag to the unit that you prefer be converted.
Examples
>>> a = Quantity(1,unit='cm') >>> b = Quantity(2,unit='mm') >>> a + b 1.2 cm >>> a.c + b 12 mm >>> a + b.c 1.2 cm >>> a*b 0.2 cm**2 >>>a.c*b 20 mm**2
- convert(unit)¶
Returns a copy of the Quantity with converted units. A NoUnitConversionFoundError will be raised if the unit conversion is not possible.
- Parameters
unit (str or Unit) – The unit for the x value and if uunit is None, the uncertainty. It must be string, None, a Unit object, or the integer 1. Both 1 and None will be interpreted as the Unit instance one.
uunit `str`, `Unit` or None, optional – The unit for the uncertainty U. If this is None then U will have the same units as x. The default is None.
- copy(tofloat=False)¶
- property imag¶
- property real¶
- reduce_unit()¶
Cancels factors in a Quantity’s unit when possible. This modifies the calling gummy and returns None.
Example
>>> x = Quantity(5,unit='mm/m') >>> x.reduce_unit() >>> x 0.005
- splonk()¶
returns self.value if self.unit is one else returns self
- splonk_func_ret = False¶
- tofloat()¶
- tostring(fmt=None, **kwds)¶
- totuple()¶
- property unit¶
Gets or sets the unit for the Quantity.
If this property is set, a unit conversion will be performed. The value it is set to may be a string, None, a Unit object, or the integer 1. Both 1 and None will be interpreted as the Unit instance one. A NoUnitConversionFoundError will be raised if the unit conversion is not possible.
Example
>>> x = Quantity(0.001,unit='V') >>> x 0.001 V >>> x.unit = 'uV' >>> x 1000.0 uV
- property value¶
- class metrolopy.unit.QuantityArray(value, unit=one)¶
Bases:
metrolopy.unit.Quantity
A subclass of Quantity. Instance of this class represent a list, tuple, or numpy array of values all with the same unit. Elements of the array are returned as Quantity instances. Instances of this class can be created directly or by multiplying a list, tuple, or numpy array by a Unit instance.
- Parameters
value (list, tuple or ndarray) – the value of the Quantity
unit (str or Unit) – The Unit instance representing the unit of the Quantity or a string that references the Unit instance.
- class metrolopy.unit.Unit(name, symbol, conversion=None, short_name=None, add_symbol=False, html_symbol=None, latex_symbol=None, ascii_symbol=None, description=None, order=- 1, **kwds)¶
Bases:
metrolopy.printing.PrettyPrinter
,metrolopy.indexed.Indexed
Creating an instance of this class creates a representation of a physical unit and adds it to the unit library. Once created the unit intance may be retrived by passing a string with the unit name or alias to the unit or Unit.unit functions. Units can be multiplied and divided by other Units or Quantities and raised to numerical powers. Multiplying or dividing a numerical value by a Unit will create a Quantity instance.
- Parameters
name (str) – The name of the unit. The name can be used access the unit with the unit function, but note that if you define a Unit with an identical name to a previously defined unit then the older name will be shadowed.
symbol (str) – A unicode symbol used when displaying the unit. If the add_symbol parameter is set to True, then this symbol can also be used to access the unit with the unit function.
conversion (Conversion or None, optional) – A conversion to another unit. When creating units be careful to avoid circular conversions, i.e. you can define:
Unit(‘inch’,’in’,conversion=None) Unit(‘foot’,’ft’,conversion=Conversion(‘in’,12)) Unit(‘yard’,’yd’,conversion=Conversion(‘ft’,3))
but not:
Unit(‘inch’,’in’,conversion=Conversion(‘yd’,1/36)) Unit(‘foot’,’ft’,conversion=Conversion(‘in’,12)) Unit(‘yard’,’yd’,conversion=Conversion(‘ft’,3))
Note that an equivent and allowable way of defining the first set of units above is:
Unit(‘inch’,’in’,conversion=None) Unit(‘foot’,’ft’,conversion=Conversion(‘in’,12)) Unit(‘yard’,’yd’,conversion=Conversion(‘in’,36))
Either way will allow the free conversion between inches, feet, and yards. You can also define the inch as:
Unit(‘inch’,’in’,conversion=(‘cm’,2.54)
(The inch is actually defined this way in the builtin unit library.)
short_name (str or None) – a short name which can be used as an additional alias for the unit in the unit library
add_symbol (bool, optional) – If this is True, then the symbol can be used to look up the unit in the unit library. The default is False
html_symbol, latex_symbol, ascii_symbol (str or Mone, optional) – html, latex, and ascii versions of the symbol if they are different from the unicode representation of the symbol.
description (str or None, optional) – a description of the unit
order (int , optional) – When displaying composite derived units, the symbols with a lower order value will be displayed. The default if -1.
See also
The
PrefixedUnit
Creates a set of units with SI prefixes (…, kilo, mega, giga, …)
BinaryPrefixedUnit
Creates a set of unit with binary prefixes (…, kibi, mebi, gibi, …)
LogUnit
Logrithmic units (e.g. decibel or neper)
OffsetUnit
Units with an offset origin (degree Celsius or degree Fahrenheit)
- property conversion¶
Gets or sets the Conversion instance for the unit.
*This property is not intended to be used directly and setting this property may cause problems*
- convert(g, unit)¶
Converts a number from a quantity with the units self to unit.
- static format_latex(text)¶
- property is_dimensionless¶
bool, read-only
Returns True if a conversion exists between self and one, and False if not.
- property linear¶
Gets a bool value indicating whether the Unit is linear. If the unit is linear then any associated values will follow the standard rules of arithmatic for Quantaties and the unit’s Conversion is defined by multiplying or dividing by a single conversion factor. Nonlinear units may have a more complicated conversion and may override the unusal operator methods.
- mulsep = False¶
- static reorder(txt)¶
This changes the order in which the symbols of composite derived units are displayed.
Examples
>>> print(Unit.unit('ft lb')) ft lb >>> print(Unit.unit('lb ft')) #This is the same unit as above and displays identically ft lb >>> Unit.reorder('lb ft') #Now the order will be changed when the unit is displayed >>> print(Unit.unit('ft lb')) lb ft
- solidus = True¶
- static unit(txt, exception=True)¶
Finds an returns a Unit from the unit library.
- Parameters
txt (str, Unit or 1) – This may be a string representing the unit. The string can contain the name, short name or (if the unit was created with add_symbol set to True) the symbol of the unit or a combination of names and/or symbols of several different units. Spaces or the character ‘*’ represent multiplication, the character ‘/’ represents division and the string ‘**’ represents the power operator. For example txt can be:
‘kg m**2/s’
or equivalently:
‘kilogram*metre*metre*second**-1’ or ‘(kg/s)*m**2’.
If a unit name contains a space, ‘*’ or ‘/’ character then the name must be enclosed in square brackets, e.g:
[light year]
If txt is a Unit instance that instance is returned.
exception (bool, optional) – If this is True then a UnitNotFoundError or UnitLibError is raised if a unit is not found that matches txt. If it is False and a unit is not found, then Unit.unit returns None without raising an exception. The default is True.
- Returns
A Unit instance or possibly None if the exception parameter is
set to True.
- property units¶
read-only
Returns a list of the constituent units and their exponents, e.g. for kg m**2/s units would be [(kg, 1), (m, 2), (s, -1)].
- metrolopy.unit.unit(name, exception=True)¶
Finds an returns a Unit from the unit library. This function is an alias for the Unit.unit static method.
- Parameters
txt (str, Unit or 1) – This may be a string representing the unit. The string can contain the name, short name or (if the unit was created with add_symbol set to True) the symbol of the unit or a combination of names and/or symbols of several different units. Spaces or the character ‘*’ represent multiplication, the character ‘/’ represents division and the string ‘**’ represents the power operator. For example txt can be:
‘kg m**2/s’
or equivalently:
‘kilogram*metre*metre*second**-1’ or ‘(kg/s)*m**2’.
If a unit name contains a space, ‘*’ or ‘/’ character then the name must be enclosed in square brackets, e.g:
[light year]
If txt is a Unit instance that instance is returned.
exception (bool, optional) – If this is True then a UnitNotFoundError or UnitLibError is raised if a unit is not found that matches txt. If it is False and a unit is not found, then Unit.unit returns None without raising an exception. The default is True.
- Returns
A Unit instance or possibly None if the exception parameter is
set to True.
metrolopy.unitutils module¶
the search_units, shadow_units, and convert functions are defined here
- metrolopy.unitutils.convert(amount, from_unit, to_unit)¶
Performs a unit conversion of amount in units of from_unit to units of to_unit.
equivalent to
gummy(amount,from_unit).convert(to_unit)
- metrolopy.unitutils.search_units(search=None, fmt=None, show_all=False, units=None, prnt=True)¶
Prints a list of all loaded units or all units that match the search terms.
- Parameters
search (str or None, optional) – A space separated list of search terms to case insentively match. If this is omitted or set equal to None then a list of all loaded units will be printed. The default is None.
fmt ({‘html’,’latex’,’unicode’,’ascii’,`None`},optional) – The output format. If None, then the gummy.printer value is used. If latex output is selected, Markdown is actually used with the unit symbols and conversion displayed using inline LaTeX.
show_all (bool, optional) – If True units are shown with each prefix listed on a separate line (e.g. the millisecond and the microsecond are listed in addition to the second) and interval units are shown. If False only the base unit is shown. The default is False.
units (list of str or Unit,optional) – A list of units to print. If this parameter is specified the values of the search and show_all parameters are ignored.
prnt (bool, optional) – If this is True, the results are printed. If it is False the results are returned as a string. The default is True.
- metrolopy.unitutils.shadowed_units(fmt=None, prnt=True)¶
Lists any units which have a shadowed name or alias. Units may be shadowed if the user has defined a new unit with the same name or alias as an existing unit.
- Parameters
fmt ({‘html’,’latex’,’unicode’,’ascii’,`None`},optional) – The output format. If None, then the gummy.printer value is used. If latex output is selected, Markdown is actually used with the unit symbols and conversion displayed using inline LaTeX.
prnt (bool, optional) – If this is True, the results are printed. If it is False the results are returned as a string. The default is True.
metrolopy.usunits module¶
This module is loaded by the gummy.units module and is not intended be be imported directly. The gummy.siunits module must be loaded before loading this module.
Most units here are from:
NIST Special Publication 1038, “The International System of Units (SI) – Conversion Factors for General Use”, May 2006.