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:
PrettyPrinterA 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 (“c” below)
multiplied by the standard uncertainty for the component and divided by the combined standard uncertainty all squared, 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.budget.append_utype(a, utype)¶
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:
objectClass 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, **kwds)¶
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. If the function returns an array like value, it must be convertable to a numpy homogeneous array.
- 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 or a numpy.ndarray of gummy or 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, **kwds)¶
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. If the function returns an array like value, it must be convertable to a numpy homogeneous array.
*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 or a numpy.ndarray of gummy or 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 classes that represent distributions for Monte Carlo calculations.
- class metrolopy.distributions.Convolution(func, *args)¶
Bases:
Distribution- datafrom(ufrom, save=True)¶
Recomputes the convolution with only Distributions in ufrom allowed to vary. sim or simulate must be called to generate Monte-Carlo data before calling this method.
- Parameters:
ufrom (list containing Distribution (not Convolution) or str) – all independent Distributions not in the list or having a utype not in the list are held fixed at their .x() value
save (If save is True the recomputed data is stored in the simdata) – attribute and None is returned. If save is False then the recomputed data is returned and the simdata attribute is not overwritten.
- Return type:
‘numpy.array’ if save is False, otherwise returns None
- Raises:
NoSimulatedDataError – if no simulated data is available from a call to Distribution.simulate.
- property isindependent¶
- 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.Distribution¶
Bases:
objectAbstract 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.random.Generator object accessed with the Distribution.random_rng 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_rng().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
- cdf(*p)¶
- 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 clear_all()¶
Clears the Monte-Carlo data from all existing Distribution instances.
- static covplot(x, y, fmt='ko', xlabel=None, ylabel=None, title=None, hold=False, fig_options={}, subplot_options={}, **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, …
- discrete = False¶
- hist(hold=False, title=None, xlabel='$ \\mathrm{value} $', ylabel='$ \\mathrm{probability\\:density} $', fig_options={}, subplot_options={}, **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
fig_options (dict, optional) – keywords passed to pyplot.figure when creating the figure
subplot_options (dict, options) – keywords passed to pyplot.figure.add_subplot when creating the subplot
kwds – additional key words that will be passed to the pyplot.hist method that actually created the histogram
- Return type:
Figure, Axes
- Raises:
NoSimulatedDataError – if no simulated data is available from a call to Distribution.simulate.
- property isindependent¶
- 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(). –
- classmethod param_names(fmt='unicode')¶
- 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_rng()¶
Returns the numpy.random.Generator object shared by all distributions.
- static random_state()¶
Returns a legacy numpy.random.RandomState instance that may be used as a random number generator by derived classes. Use of the newer numpy.random.Generator class is now preferred. An instance of the numpy.random.Generator class shared by all distributions is returned with the Distribution.random_rng static method.
- static set_seed(seed)¶
Reinitalized the numpy.random.Generator object shared by all distributions with seed.
- sim(n=100000, ufrom=None)¶
- 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.
- utype = None¶
- 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.MultivariateDistribution(nd)¶
Bases:
object- clear()¶
- property cov¶
- u()¶
- x()¶
- class metrolopy.distributions.MultivariateElement(parent, index)¶
Bases:
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:
Distribution- cdf(x, s)¶
- 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.ScipyStatsDist(distribution)¶
Bases:
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:
Distribution- bayesian_default = False¶
- static cdf(z, x, s, dof)¶
- 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.ConstantNotFoundError¶
Bases:
ValueError
- exception metrolopy.exceptions.FitWarning¶
Bases:
Warning
- exception metrolopy.exceptions.GummyWarning¶
Bases:
Warning
- exception metrolopy.exceptions.IncompatibleUnitsError¶
Bases:
UnitErrorThis exception is raised when an operation or conversion is attempted with Quantity instances that have units that are incompatible for that operation.
- exception metrolopy.exceptions.NoSimulatedDataError¶
Bases:
Exception
- exception metrolopy.exceptions.UncertiantyPrecisionWarning¶
Bases:
Warning
- exception metrolopy.exceptions.UnitError¶
Bases:
ValueErrorBase class for Unit exceptions.
- exception metrolopy.exceptions.UnitLibError¶
Bases:
UnitErrorThis exception is raised when the UnitLibrary cannot parse a unit string.
- exception metrolopy.exceptions.UnitLibNotFoundError¶
Bases:
UnitLibError
- exception metrolopy.exceptions.UnitNotFoundError¶
Bases:
UnitLibError
- exception metrolopy.exceptions.UnitWarning¶
Bases:
Warning
metrolopy.fit module¶
This module defines some classes to facilitate curve fitting.
- class metrolopy.fit.Fit(x, y=None, f=None, p0=None, ux=None, uy=None, variance_is_known=None, xunit=None, yunit=None, solver=None, xweights=None, weights=None, xcov=None, ycov=None, ignore_correlations=False, fix=None, fargs=[], fkwds={}, **kw)¶
Bases:
_Fit,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 to the Fit initializer.
- 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)¶
The Jacobian of the fit function.
[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,…].
A NotImplementedError will be raised unless both the jacx and jacp methods are implemented.
- jacp(*a)¶
The Jacobian of the fit function with respect to the fit parameters.
This may be implemented in a derived class. Note that this function can also be passed to the Fit initializer using the jacp keyword or can be omitted entirely in which case the Jacobian will be calculated numerically.
It must either have signature:
jacp(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:
jacp(self,x1,x2,…,xm,p1,p2,…,pn)
where the independent variable x has m dimensions at each observation.
It must return an array (or array like object) with values:
[df/dx1,df/dx2,…]
if f returns a scalar or:
- [[df1/dx1,df1/dx2,…],
[df2/dx1,df2/dx2,…],…]
if f returns a 1-d array [f1,f2,…].
- jacx(*a)¶
The derivative fit function with respect to the x-values:
This may be implemented in a derived class. Note that this function can also be passed to the Fit initializer using the jacp keyword or can be omitted entirely in which case this Jacobian will be calculated numerically if it is needed.
It must either have signature:
jacp(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:
jacp(self,x1,x2,…,xm,p1,p2,…,pn)
where the independent variable x has m dimensions at each observation.
It must return an array (or array like object) with values:
[df/dp1,df/dp2,…]
if f returns a scalar or:
- [[df1/dp1,df1/dp2,…],
[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¶
- property njacx¶
- 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
- metrolopy.fit.getvalues(txt, x, u, cov, w, units, ignore_corr)¶
- metrolopy.fit.mmul(m, v)¶
- metrolopy.fit.odr_jac(work, count, xdim, nparam, ydim, nwe, task)¶
- metrolopy.fit.repl(a, p, fix)¶
- metrolopy.fit.wsqrt(w)¶
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.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)¶
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¶
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 (Number, Distribution,`scipy.stats.rv_frozen` or gummy) – A number representing the value of the gummy or a distribution, either a Distribution instance or a scipy.stats rv_frozen 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 a (correlated) copy is produced.
u (Number >= 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 (Number > 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.
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:
NonlinearConversion- copy()¶
- frm(g)¶
- log_func(x)¶
- to(g)¶
- class metrolopy.logunit.LogUnit(*p, **kwds)¶
Bases:
NonlinearUnit- get_composite(ul)¶
- zero()¶
metrolopy.mean module¶
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 or float, 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 None.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. The default value is False.
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.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:
ConversionBase class for non-linear conversions.
- chain(c)¶
- copy()¶
- linear = False¶
- pow(e)¶
- rchain(c)¶
metrolopy.nummy module¶
metrolopy.offsetunit module¶
The OffsetUnit class was created to handle Celsius and Fahrenheit units.
- class metrolopy.offsetunit.OffsetConversion(unit, offset)¶
Bases:
NonlinearConversionRepresents a conversion of the form x -> x + offset.
- copy()¶
- frm(g)¶
- to(g)¶
- class metrolopy.offsetunit.OffsetUnit(*params, **kwds)¶
Bases:
NonlinearUnitThis 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:
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': [1000000000000000000, 'E', None, None, None], 'exbi': [1152921504606846976, 'Ei', None, None, None], 'gibi': [1073741824, 'Gi', None, None, None], 'giga': [1000000000, 'G', None, None, None], 'kibi': [1024, 'Ki', None, None, None], 'kilo': [1000, 'k', None, None, None], 'mebi': [1048576, 'Mi', None, None, None], 'mega': [1000000, 'M', None, None, None], 'pebi': [1125899906842624, 'Pi', None, None, None], 'peta': [1000000000000000, 'P', None, None, None], 'tebi': [1099511627776, 'Ti', None, None, None], 'tera': [1000000000000, 'T', None, None, None], 'yobi': [1208925819614629174706176, 'Yi', None, None, None], 'yotta': [1000000000000000000000000, 'Y', None, None, None], 'zetta': [1000000000000000000000, '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:
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': [MFraction(1, 1000000000000000000), 'a', None, None, None], 'centi': [MFraction(1, 100), 'c', None, None, None], 'deca': [10, 'da', None, None, None], 'deci': [MFraction(1, 10), 'd', None, None, None], 'exa': [1000000000000000000, 'E', None, None, None], 'femto': [MFraction(1, 1000000000000000), 'f', None, None, None], 'giga': [1000000000, 'G', None, None, None], 'hecto': [100, 'h', None, None, None], 'kilo': [1000, 'k', None, None, None], 'mega': [1000000, 'M', None, None, None], 'micro': [MFraction(1, 1000000), 'μ', 'μ', None, 'u'], 'milli': [MFraction(1, 1000), 'm', None, None, None], 'nano': [MFraction(1, 1000000000), 'n', None, None, None], 'peta': [1000000000000000, 'P', None, None, None], 'pico': [MFraction(1, 1000000000000), 'p', None, None, None], 'tera': [1000000000000, 'T', None, None, None], 'yocto': [MFraction(1, 1000000000000000000000000), 'y', None, None, None], 'yotta': [1000000000000000000000000, 'Y', None, None, None], 'zepto': [MFraction(1, 1000000000000000000000), 'z', None, None, None], 'zetta': [1000000000000000000000, '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.
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¶
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), …
metrolopy.unit module¶
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, converts_to=None)¶
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.
- Returns:
A search_units_result instance which emulates a list of the returned
constants and pretty-prints the results to the output or None if no
units are found.
- class metrolopy.unitutils.search_units_result(units, show_all)¶
Bases:
PrettyPrinterA search_units_result instance emulates a list of units returned from a ‘search_units` function call, and pretty-prints the results to the output
- tostring(fmt='unicode', **kwds)¶
- metrolopy.unitutils.shadowed_units(fmt=None)¶
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.
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.
metrolopy.version module¶
Get the version string for the named package.
- param distribution_name:
The name of the distribution package to query.
- return:
The version string for the package as defined in the package’s “Version” metadata key.
Module contents¶
- class metrolopy.AbcQuantity¶
Bases:
Number- autoconvert = False¶
- abstract property c¶
- abstractmethod convert(unit)¶
- abstractmethod copy(unit)¶
- abstractmethod splonk(unit)¶
- abstractmethod tobaseunit(unit)¶
- abstractmethod tofloat(unit)¶
- abstractmethod tostring(**kwds)¶
- abstractmethod totuple(unit)¶
- abstract property unit¶
- abstract property unit_is_one¶
- abstract property value¶
- class metrolopy.AbcQuantityArray¶
Bases:
AbcQuantity
- class metrolopy.AbcUnit¶
Bases:
Number- abstract property base¶
- abstract property conversion¶
- abstractmethod convert(unit)¶
- abstract property is_dimensionless¶
- abstract property linear¶
- abstractmethod tostring(**kwds)¶
- abstract property units¶
- class metrolopy.ArcSinDist(center=None, half_width=None, lower_limit=None, upper_limit=None)¶
Bases:
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.AveragedDist(distribution, nsamples)¶
Bases:
Distribution- property dist¶
- 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.AveragedErrDist(distribution, nsamples)¶
Bases:
Distribution- property dist¶
- 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.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:
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': [1000000000000000000, 'E', None, None, None], 'exbi': [1152921504606846976, 'Ei', None, None, None], 'gibi': [1073741824, 'Gi', None, None, None], 'giga': [1000000000, 'G', None, None, None], 'kibi': [1024, 'Ki', None, None, None], 'kilo': [1000, 'k', None, None, None], 'mebi': [1048576, 'Mi', None, None, None], 'mega': [1000000, 'M', None, None, None], 'pebi': [1125899906842624, 'Pi', None, None, None], 'peta': [1000000000000000, 'P', None, None, None], 'tebi': [1099511627776, 'Ti', None, None, None], 'tera': [1000000000000, 'T', None, None, None], 'yobi': [1208925819614629174706176, 'Yi', None, None, None], 'yotta': [1000000000000000000000000, 'Y', None, None, None], 'zetta': [1000000000000000000000, 'Z', None, None, None], 'zibi': [1180591620717411303424, 'Zi', None, None, None]}¶
- class metrolopy.BinomialDist(n, p)¶
Bases:
Distribution- discrete = True¶
- 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.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:
PrettyPrinterA 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 (“c” below)
multiplied by the standard uncertainty for the component and divided by the combined standard uncertainty all squared, 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¶
- exception metrolopy.BudgetWarning¶
Bases:
Warning
- exception metrolopy.ConstantNotFoundError¶
Bases:
ValueError
- class metrolopy.Conversion(unit, factor=1)¶
Bases:
objectRepresents 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.Convolution(func, *args)¶
Bases:
Distribution- datafrom(ufrom, save=True)¶
Recomputes the convolution with only Distributions in ufrom allowed to vary. sim or simulate must be called to generate Monte-Carlo data before calling this method.
- Parameters:
ufrom (list containing Distribution (not Convolution) or str) – all independent Distributions not in the list or having a utype not in the list are held fixed at their .x() value
save (If save is True the recomputed data is stored in the simdata) – attribute and None is returned. If save is False then the recomputed data is returned and the simdata attribute is not overwritten.
- Return type:
‘numpy.array’ if save is False, otherwise returns None
- Raises:
NoSimulatedDataError – if no simulated data is available from a call to Distribution.simulate.
- property isindependent¶
- 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.CurvlinearTrapDist(center=None, half_width=None, limit_half_range=None, lower_limit=None, upper_limit=None)¶
Bases:
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.DistFit(x, cdf, p0=None, fix=None, rmin=None, p_names=None, **kwds)¶
Bases:
FitFits a one-dimensional continuous distribution. :Parameters: * x (array of float) – samples from the distribution to be fitted
cdf (Distribution, scipy.stats.rv_continuous distribution or) – function or method
This can be the distribution to be fit as represented by a gummy.Distribution (either the class or an instance of the class) or a scipy.stats.rv_continuous distribution (either the class or an instance of the class).
It can also be a function or a method that gives the cumlative distribution function of the distribtion to be fit.
fix (array of bool) – A mask for the fit parameters. For any element in fix that is True, the corresponding fit parameter will be held constant at its initial value.
p0 (array of float, optional) – Inital values for the fit parameters.
This is required if cdf is a function or method, but optional for most Distribution or scipy.stats distributions.
- p¶
The fitted values for the fit function parameters as gummys including uncertainties and units.
- Type:
numpy.array of gummy
- pf¶
The fitted values for the fit function parameters as floats
- Type:
numpy.array of float
- Properies¶
- ---------
- dist¶
- Type:
Returns a gummy.Distribution instance representing the fitted
- distribution.
- plot(...):
plots the histogram of the data and the fitted distribution
- cdf_plot(...):
plots cumulative distribution function of the fitted distribution along with the data points.
- property dist¶
Returns a gummy.Distribution instance representing the fitted distribution.
- f(x, *p, **kwds)¶
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.
- 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 to the Fit initializer.
- plot(ylabel=None, xlabel=None, title=None, hold=False, plot_points=None, show_fit=True, show_data=True, xmin=None, xmax=None, fit_options={}, fig_options={}, subplot_options={}, hist_options={})¶
plots the histogram of the data and the fitted distribution
- Parameters:
ylabel (str, optional) – label for the y-axis
xlabel (str, optional) – label for the x-axis
title (str, optional) – plot title
hold (bool, optional) – If this is True, pyplot.show is called before this method returns. The default is False.
plot_points (int, optional) – The number of points in the fitted curve. The default is 500.
show_fit (bool, optional) – Whether or not to plot the fitted curve The default is True.
show_data (bool, optional) – Whether or not to plot a histogra. The default is True.
xmin (float, optional) – Minimum value for the x-axis. The default is None.
xmax (float, optional) – Maximum value for the x-axis. The default is None.
fit_options (dict, optional) – keywords to be passed to the pyplot.plot called for the fitted curve.
fig_options (dict, optional) – keywords to be passed when the pyplot.figure is created.
subplot_options (dict, optional) – keywords to be passed when the pyplot.figure.add_subplot is called.
hist_options (dict, optional) – keywords to be passed to pyplot.hist
- Return type:
Figure,Axes
- plot_cdf(ylabel=None, xlabel=None, title=None, hold=False, plot_points=None, show_fit=True, show_data=True, xmin=None, xmax=None, fit_options={}, fit_format='k-', fig_options={}, subplot_options={}, data_options={}, data_format='ko')¶
plots the cumlative distribution function of the fitted distribution along with the data points.
- Parameters:
ylabel (str, optional) – label for the y-axis
xlabel (str, optional) – label for the x-axis
title (str, optional) – plot title
hold (bool, optional) – If this is True, pyplot.show is called before this method returns. The default is False.
plot_points (int, optional) – The number of points in the fitted curve. The default is 500.
show_fit (bool, optional) – Whether or not to plot the fitted curve The default is True.
show_data (bool, optional) – Whether or not to plot a histogra. The default is True.
xmin (float, optional) – Minimum value for the x-axis. The default is None.
xmax (float, optional) – Maximum value for the x-axis. The default is None.
fit_options (dict, optional) – keywords to be passed to the pyplot.plot called for the fitted curve.
fit_format (str, optional) – Format string for the fitted curve. The default is ‘k-‘.
fig_options (dict, optional) – keywords to be passed when the pyplot.figure is created.
subplot_options (dict, optional) – keywords to be passed when the pyplot.figure.add_subplot is called
fit_options (dict, optional) – keywords to be passed to the pyplot.plot called for the data points.
data_format (str, optional) – Format string for the data points. The default is ‘ko’.
- Return type:
Figure, Axes
- class metrolopy.Distribution¶
Bases:
objectAbstract 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.random.Generator object accessed with the Distribution.random_rng 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_rng().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
- cdf(*p)¶
- 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 clear_all()¶
Clears the Monte-Carlo data from all existing Distribution instances.
- static covplot(x, y, fmt='ko', xlabel=None, ylabel=None, title=None, hold=False, fig_options={}, subplot_options={}, **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, …
- discrete = False¶
- hist(hold=False, title=None, xlabel='$ \\mathrm{value} $', ylabel='$ \\mathrm{probability\\:density} $', fig_options={}, subplot_options={}, **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
fig_options (dict, optional) – keywords passed to pyplot.figure when creating the figure
subplot_options (dict, options) – keywords passed to pyplot.figure.add_subplot when creating the subplot
kwds – additional key words that will be passed to the pyplot.hist method that actually created the histogram
- Return type:
Figure, Axes
- Raises:
NoSimulatedDataError – if no simulated data is available from a call to Distribution.simulate.
- property isindependent¶
- 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(). –
- classmethod param_names(fmt='unicode')¶
- 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_rng()¶
Returns the numpy.random.Generator object shared by all distributions.
- static random_state()¶
Returns a legacy numpy.random.RandomState instance that may be used as a random number generator by derived classes. Use of the newer numpy.random.Generator class is now preferred. An instance of the numpy.random.Generator class shared by all distributions is returned with the Distribution.random_rng static method.
- static set_seed(seed)¶
Reinitalized the numpy.random.Generator object shared by all distributions with seed.
- sim(n=100000, ufrom=None)¶
- 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.
- utype = None¶
- 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.DoF(value)¶
Bases:
objectRepresents the degrees of freedom for an uncertainty. ummy or gummy instances that share the same DoF instance are assumed to have uncertainties based on the samples from the same underlying normal distribution.
For example if we define:
a = gummy(1.2,u=3.3,dof=5) b = gummy(0.7,u=3.3,dof=5)
we are assuming that, even though both a and b have the number of degrees of freedom, their uncertainites are esimated from samples from two different distributions that may not have exaclty the same population variance. However if we define:
c = gummy(1.2,u=3.3,dof=DoF(5)) d = gummy(0.7,u=2.4,dof=Dof(5))
we are now assuming that the uncertanties are both estimated using the same samples from the same distribution. E.g. c and d may represent the fitted parameters of a least squares regression where the variance of the same data points is used to estimate the uncertainty of both c and d.
- property value¶
- class metrolopy.DoubleExpFit(x, y=None, f=None, p0=None, ux=None, uy=None, variance_is_known=None, xunit=None, yunit=None, solver=None, xweights=None, weights=None, xcov=None, ycov=None, ignore_correlations=False, fix=None, fargs=[], fkwds={}, **kw)¶
Bases:
Fit- DoubleExpFit(x,y,p0=None,ux=None,uy=None,variance_is_known=True,xunit=None, yunit=None,
solver=None,**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) – The indepenant variables x. For n data points this should be an array of shape (n,) for a one-dimensional fit or shape (m,n) for an m-dimensional fit. The maximum dimension m is 3.
The x-values may be all float or all gummy, If uncertainties u are defined for the x-values, the xweights will be set to 1/u**2 for each point. To override this behavior set the keyword parameter “xweights = 1”. If uncertainties are defined for the x-values, the default solver is odr. If the nls or ols solver is manually selected then the uncertainties in the x-values will be ignored. For an m-dimential fit, the odr solver will take into account correlations between the m elements of the x-values for each data point, but ignores correlations between different data points and bewteen the x- and y-values.
y (array) – Response variables y.
The y-values may be all float or all gummy, If uncertainties u are defined for the y-values, the weights will be set to 1/u**2 for each point. To override this behavior set the keyword parameter “weights = 1”.
If the nls or odr solver is used, the weighting will take into account correlations between the different points. However, the odr solver ignores correlations between different data points. If the y-values are multi-dimensional, the odr solver will take into account correlations between the different elements at each point.
fix (array of bool) – A mask for the fit parameters. For any element in fix that is True, the corresponding fit parameter will be held constant at its initial value.
solver ({‘ols’,’nls’,’odr’}, optional) – A non-linear least squares (nls), ordinary least squares (ols) or othogonal distance regression solver (odr) can be used to perform the fit.
ols is the default solver unless uncertainties are specified for the x-values, in which case the default solver is odr.
The nls solver uses scipy.optimize.least_squares while the odr solver used odrpack.odr_fit. The ols solver uses scipy.linag.pinvh to invert the normal equation matrix.
ux (array or float, optional) – Uncertainties for the x-values. Specifying ux is an alternative to passing gummys with uncerainties defined as the the x-values. ux can be a number that applies to all the x-values or an array giving the uncertainty for each x-value.
If uncertainties u are defined individually for the x-values, the xweights will be set to 1/u**2 for each point. To override this behavior set the keyword parameter “xweights = 1”. If uncertainties are defined for the x-values, the default solver is odr. If the nls or ols solver is manually selected then the uncertainties in the x-values will be ignored.
uy (array or float, optional) – Uncertainties for the y-values. Specifying uy is an alternative to passing gummys with uncerainties defined as the the y-values. uy can be a number that applies to all the x-values or an array giving the uncertainty for each y-value.
If uncertainties u are defined individually for the y-values, the weights will be set to 1/u**2 for each point. To override this behavior set the keyword parameter “weights = 1”
variance_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.
p0 (array of float, optional) – initial values for the fit parameters.
- p¶
The fitted values for the fit function parameters as gummys including uncertainties and units.
- Type:
numpy.array of gummy
- pf¶
The fitted values for the fit function parameters as floats
- Type:
numpy.array of float
- res¶
the weighted fit residuals
- Type:
numpy.ndarray of float
- var¶
the variance of the weighted fit residuals
- Type:
float
- s¶
the standard deviation of weighted the residuals
- Type:
float
- cov¶
the covariance matrix of the (non-fixed) parameters
- Type:
numpy.ndarray of float
- known_var¶
If uncertainties are defined for the y-values (and possible the x-values), this is the predicted variance of the weighted fit residuals. If uncertainites are not defined for the y- or x-values, this is None.
- Type:
float
- yvar¶
the variance of the residual differences between the fitted values and the weighted y-values. For the nls and ols solver this is the same as var.
- Type:
float
- xvar¶
the variance of the residual differences between the fitted values and the weighted x-values. For the nls and ols solver this is None.
- Type:
float
- rcov¶
the covariance matrix of the (non-fixed) parameters divided by the variance
- Type:
numpy.ndarray of float
- fit_output¶
the return value of scipy.optimize.least_squares for the nls solver of the return value of odr_fit.odrpack for the odr solver. This is None if the ols solver is used.
- 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 (x) 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 (non-fixed) fit parameters
- Type:
int
- dof¶
degrees of freedom for the fit
- Type:
float
- ypred(x1,x2,...):
Takes xdim floats (or arrays of float) and returns a gummy representing the predicted value(s) at that x-coordinate.
- ypredf(x1,x2,...):
Takes xdim floats (or arrays of float) and returns a float giving the predicted value(s) 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 to the Fit initializer.
- 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)¶
The Jacobian of the fit function.
[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,…].
A NotImplementedError will be raised unless both the jacx and jacp methods are implemented.
- class metrolopy.ExpFit(x, y=None, f=None, p0=None, ux=None, uy=None, variance_is_known=None, xunit=None, yunit=None, solver=None, xweights=None, weights=None, xcov=None, ycov=None, ignore_correlations=False, fix=None, fargs=[], fkwds={}, **kw)¶
Bases:
Fit- ExpFit(x,y,p0=None,ux=None,uy=None,variance_is_known=True,xunit=None, yunit=None,
solver=None,**keywords)
Fits the x,y data to a function of the form:
p[0]*np.exp(x/p[1])+p[2]
- Parameters:
x (array) – The indepenant variables x. For n data points this should be an array of shape (n,) for a one-dimensional fit or shape (m,n) for an m-dimensional fit. The maximum dimension m is 3.
The x-values may be all float or all gummy, If uncertainties u are defined for the x-values, the xweights will be set to 1/u**2 for each point. To override this behavior set the keyword parameter “xweights = 1”. If uncertainties are defined for the x-values, the default solver is odr. If the nls or ols solver is manually selected then the uncertainties in the x-values will be ignored. For an m-dimential fit, the odr solver will take into account correlations between the m elements of the x-values for each data point, but ignores correlations between different data points and bewteen the x- and y-values.
y (array) – Response variables y.
The y-values may be all float or all gummy, If uncertainties u are defined for the y-values, the weights will be set to 1/u**2 for each point. To override this behavior set the keyword parameter “weights = 1”.
If the nls or odr solver is used, the weighting will take into account correlations between the different points. However, the odr solver ignores correlations between different data points. If the y-values are multi-dimensional, the odr solver will take into account correlations between the different elements at each point.
fix (array of bool) – A mask for the fit parameters. For any element in fix that is True, the corresponding fit parameter will be held constant at its initial value.
solver ({‘ols’,’nls’,’odr’}, optional) – A non-linear least squares (nls), ordinary least squares (ols) or othogonal distance regression solver (odr) can be used to perform the fit.
ols is the default solver unless uncertainties are specified for the x-values, in which case the default solver is odr.
The nls solver uses scipy.optimize.least_squares while the odr solver used odrpack.odr_fit. The ols solver uses scipy.linag.pinvh to invert the normal equation matrix.
ux (array or float, optional) – Uncertainties for the x-values. Specifying ux is an alternative to passing gummys with uncerainties defined as the the x-values. ux can be a number that applies to all the x-values or an array giving the uncertainty for each x-value.
If uncertainties u are defined individually for the x-values, the xweights will be set to 1/u**2 for each point. To override this behavior set the keyword parameter “xweights = 1”. If uncertainties are defined for the x-values, the default solver is odr. If the nls or ols solver is manually selected then the uncertainties in the x-values will be ignored.
uy (array or float, optional) – Uncertainties for the y-values. Specifying uy is an alternative to passing gummys with uncerainties defined as the the y-values. uy can be a number that applies to all the x-values or an array giving the uncertainty for each y-value.
If uncertainties u are defined individually for the y-values, the weights will be set to 1/u**2 for each point. To override this behavior set the keyword parameter “weights = 1”
variance_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.
p0 (array of float, optional) – initial values for the fit parameters.
- p¶
The fitted values for the fit function parameters as gummys including uncertainties and units.
- Type:
numpy.array of gummy
- pf¶
The fitted values for the fit function parameters as floats
- Type:
numpy.array of float
- res¶
the weighted fit residuals
- Type:
numpy.ndarray of float
- var¶
the variance of the weighted fit residuals
- Type:
float
- s¶
the standard deviation of weighted the residuals
- Type:
float
- cov¶
the covariance matrix of the (non-fixed) parameters
- Type:
numpy.ndarray of float
- known_var¶
If uncertainties are defined for the y-values (and possible the x-values), this is the predicted variance of the weighted fit residuals. If uncertainites are not defined for the y- or x-values, this is None.
- Type:
float
- yvar¶
the variance of the residual differences between the fitted values and the weighted y-values. For the nls and ols solver this is the same as var.
- Type:
float
- xvar¶
the variance of the residual differences between the fitted values and the weighted x-values. For the nls and ols solver this is None.
- Type:
float
- rcov¶
the covariance matrix of the (non-fixed) parameters divided by the variance
- Type:
numpy.ndarray of float
- fit_output¶
the return value of scipy.optimize.least_squares for the nls solver of the return value of odr_fit.odrpack for the odr solver. This is None if the ols solver is used.
- 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 (x) 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 (non-fixed) fit parameters
- Type:
int
- dof¶
degrees of freedom for the fit
- Type:
float
- ypred(x1,x2,...):
Takes xdim floats (or arrays of float) and returns a gummy representing the predicted value(s) at that x-coordinate.
- ypredf(x1,x2,...):
Takes xdim floats (or arrays of float) and returns a float giving the predicted value(s) 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 to the Fit initializer.
- 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)¶
The Jacobian of the fit function.
[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,…].
A NotImplementedError will be raised unless both the jacx and jacp methods are implemented.
- class metrolopy.ExponentialDist(scale=None, rate=None)¶
Bases:
Distribution- static cdf(z, scale)¶
- 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.Fit(x, y=None, f=None, p0=None, ux=None, uy=None, variance_is_known=None, xunit=None, yunit=None, solver=None, xweights=None, weights=None, xcov=None, ycov=None, ignore_correlations=False, fix=None, fargs=[], fkwds={}, **kw)¶
Bases:
_Fit,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 to the Fit initializer.
- 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)¶
The Jacobian of the fit function.
[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,…].
A NotImplementedError will be raised unless both the jacx and jacp methods are implemented.
- jacp(*a)¶
The Jacobian of the fit function with respect to the fit parameters.
This may be implemented in a derived class. Note that this function can also be passed to the Fit initializer using the jacp keyword or can be omitted entirely in which case the Jacobian will be calculated numerically.
It must either have signature:
jacp(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:
jacp(self,x1,x2,…,xm,p1,p2,…,pn)
where the independent variable x has m dimensions at each observation.
It must return an array (or array like object) with values:
[df/dx1,df/dx2,…]
if f returns a scalar or:
- [[df1/dx1,df1/dx2,…],
[df2/dx1,df2/dx2,…],…]
if f returns a 1-d array [f1,f2,…].
- jacx(*a)¶
The derivative fit function with respect to the x-values:
This may be implemented in a derived class. Note that this function can also be passed to the Fit initializer using the jacp keyword or can be omitted entirely in which case this Jacobian will be calculated numerically if it is needed.
It must either have signature:
jacp(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:
jacp(self,x1,x2,…,xm,p1,p2,…,pn)
where the independent variable x has m dimensions at each observation.
It must return an array (or array like object) with values:
[df/dp1,df/dp2,…]
if f returns a scalar or:
- [[df1/dp1,df1/dp2,…],
[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¶
- property njacx¶
- 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
- exception metrolopy.FitWarning¶
Bases:
Warning
- class metrolopy.GammaDist(shape, scale)¶
Bases:
Distribution- static cdf(z, shape, scale)¶
- 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.GummyConstant(x, u=0, unit=1, dof=inf, k=1, p=None, uunit=None, utype=None, name=None, symbol=None, short_name=None, add_symbol=False, html_symbol=None, latex_symbol=None, ascii_symbol=None, description=None, _key=None)¶
Bases:
gummy,Indexed- return_splonk = False¶
- return_toummy = False¶
- 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.
- 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
- exception metrolopy.GummyWarning¶
Bases:
Warning
- exception metrolopy.IncompatibleUnitsError¶
Bases:
UnitErrorThis exception is raised when an operation or conversion is attempted with Quantity instances that have units that are incompatible for that operation.
- class metrolopy.JummyConstant(real=None, imag=None, r=None, phi=None, cov=None, unit=1, name=None, symbol=None, short_name=None, add_symbol=False, html_symbol=None, latex_symbol=None, ascii_symbol=None, description=None)¶
Bases:
jummy,Indexed- tostring(fmt='unicode', norm=None, nsig=None, solidus=None, mulsep=None, show_name=False, name=None, **kwds)¶
Returns a string containing the symbol for the instance in the format given by the keyword fmt which may be set to a string the values ‘html’, ‘latex’, ‘ascii’ or ‘unicode’.
- class metrolopy.LaplaceDist(x, scale)¶
Bases:
Distribution- static cdf(z, x, scale)¶
- 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.LogConversion(reference, multiplier, log_base, log_func, offset=0)¶
Bases:
NonlinearConversion- copy()¶
- frm(g)¶
- log_func(x)¶
- to(g)¶
- class metrolopy.LogNormalDist(mu, sigma)¶
Bases:
Distribution- static cdf(z, mu, sigma)¶
- 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.LogUnit(*p, **kwds)¶
Bases:
NonlinearUnit- get_composite(ul)¶
- zero()¶
- class metrolopy.MFraction(*args, **kwargs)¶
Bases:
FractionA fraction.Fraction sub-class that works with Decimal and mpmath.mpf objects
- classmethod fromnum(x)¶
- todecimal()¶
- class metrolopy.MultiNormalDist(mean, cov)¶
Bases:
MultivariateDistribution- property cov¶
- u()¶
- x()¶
- class metrolopy.MultiTDist(mean, cov, dof)¶
Bases:
MultivariateDistribution- property cov¶
- u()¶
- x()¶
- class metrolopy.MultiTElement(parent, index, dof)¶
Bases:
MultivariateElement
- class metrolopy.MultivariateElement(parent, index)¶
Bases:
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.
- exception metrolopy.NoSimulatedDataError¶
Bases:
Exception
- class metrolopy.NonlinearConversion(unit, factor=1)¶
Bases:
ConversionBase class for non-linear conversions.
- chain(c)¶
- copy()¶
- linear = False¶
- pow(e)¶
- rchain(c)¶
- class metrolopy.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:
UnitBase class of non-linear units.
- get_composite(ul)¶
- zero()¶
- class metrolopy.NormalDist(x, s)¶
Bases:
Distribution- cdf(x, s)¶
- 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.OffsetConversion(unit, offset)¶
Bases:
NonlinearConversionRepresents a conversion of the form x -> x + offset.
- copy()¶
- frm(g)¶
- to(g)¶
- class metrolopy.OffsetUnit(*params, **kwds)¶
Bases:
NonlinearUnitThis 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()¶
- class metrolopy.OneOverTFit(x, y=None, f=None, p0=None, ux=None, uy=None, variance_is_known=None, xunit=None, yunit=None, solver=None, xweights=None, weights=None, xcov=None, ycov=None, ignore_correlations=False, fix=None, fargs=[], fkwds={}, **kw)¶
Bases:
Fit- DoubleExpFit(x,y,p0=None,ux=None,uy=None,variance_is_known=True,xunit=None, yunit=None,
solver=None,**keywords)
Fits the x,y data to a function of the form:
p[0]/x + p[1]
- Parameters:
x (array) – The indepenant variables x. For n data points this should be an array of shape (n,) for a one-dimensional fit or shape (m,n) for an m-dimensional fit. The maximum dimension m is 3.
The x-values may be all float or all gummy, If uncertainties u are defined for the x-values, the xweights will be set to 1/u**2 for each point. To override this behavior set the keyword parameter “xweights = 1”. If uncertainties are defined for the x-values, the default solver is odr. If the nls or ols solver is manually selected then the uncertainties in the x-values will be ignored. For an m-dimential fit, the odr solver will take into account correlations between the m elements of the x-values for each data point, but ignores correlations between different data points and bewteen the x- and y-values.
y (array) – Response variables y.
The y-values may be all float or all gummy, If uncertainties u are defined for the y-values, the weights will be set to 1/u**2 for each point. To override this behavior set the keyword parameter “weights = 1”.
If the nls or odr solver is used, the weighting will take into account correlations between the different points. However, the odr solver ignores correlations between different data points. If the y-values are multi-dimensional, the odr solver will take into account correlations between the different elements at each point.
fix (array of bool) – A mask for the fit parameters. For any element in fix that is True, the corresponding fit parameter will be held constant at its initial value.
solver ({‘ols’,’nls’,’odr’}, optional) – A non-linear least squares (nls), ordinary least squares (ols) or othogonal distance regression solver (odr) can be used to perform the fit.
ols is the default solver unless uncertainties are specified for the x-values, in which case the default solver is odr.
The nls solver uses scipy.optimize.least_squares while the odr solver used odrpack.odr_fit. The ols solver uses scipy.linag.pinvh to invert the normal equation matrix.
ux (array or float, optional) – Uncertainties for the x-values. Specifying ux is an alternative to passing gummys with uncerainties defined as the the x-values. ux can be a number that applies to all the x-values or an array giving the uncertainty for each x-value.
If uncertainties u are defined individually for the x-values, the xweights will be set to 1/u**2 for each point. To override this behavior set the keyword parameter “xweights = 1”. If uncertainties are defined for the x-values, the default solver is odr. If the nls or ols solver is manually selected then the uncertainties in the x-values will be ignored.
uy (array or float, optional) – Uncertainties for the y-values. Specifying uy is an alternative to passing gummys with uncerainties defined as the the y-values. uy can be a number that applies to all the x-values or an array giving the uncertainty for each y-value.
If uncertainties u are defined individually for the y-values, the weights will be set to 1/u**2 for each point. To override this behavior set the keyword parameter “weights = 1”
variance_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.
p0 (array of float, optional) – initial values for the fit parameters.
- p¶
The fitted values for the fit function parameters as gummys including uncertainties and units.
- Type:
numpy.array of gummy
- pf¶
The fitted values for the fit function parameters as floats
- Type:
numpy.array of float
- res¶
the weighted fit residuals
- Type:
numpy.ndarray of float
- var¶
the variance of the weighted fit residuals
- Type:
float
- s¶
the standard deviation of weighted the residuals
- Type:
float
- cov¶
the covariance matrix of the (non-fixed) parameters
- Type:
numpy.ndarray of float
- known_var¶
If uncertainties are defined for the y-values (and possible the x-values), this is the predicted variance of the weighted fit residuals. If uncertainites are not defined for the y- or x-values, this is None.
- Type:
float
- yvar¶
the variance of the residual differences between the fitted values and the weighted y-values. For the nls and ols solver this is the same as var.
- Type:
float
- xvar¶
the variance of the residual differences between the fitted values and the weighted x-values. For the nls and ols solver this is None.
- Type:
float
- rcov¶
the covariance matrix of the (non-fixed) parameters divided by the variance
- Type:
numpy.ndarray of float
- fit_output¶
the return value of scipy.optimize.least_squares for the nls solver of the return value of odr_fit.odrpack for the odr solver. This is None if the ols solver is used.
- 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 (x) 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 (non-fixed) fit parameters
- Type:
int
- dof¶
degrees of freedom for the fit
- Type:
float
- ypred(x1,x2,...):
Takes xdim floats (or arrays of float) and returns a gummy representing the predicted value(s) at that x-coordinate.
- ypredf(x1,x2,...):
Takes xdim floats (or arrays of float) and returns a float giving the predicted value(s) 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 to the Fit initializer.
- 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)¶
The Jacobian of the fit function.
[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,…].
A NotImplementedError will be raised unless both the jacx and jacp methods are implemented.
- class metrolopy.PoissonDist(lam)¶
Bases:
Distribution- discrete = True¶
- 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.PolyFit(x, y, deg=1, **kw)¶
Bases:
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 to the Fit initializer.
- 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.
- iiijac(*a)¶
- jacp(*a)¶
The Jacobian of the fit function with respect to the fit parameters.
This may be implemented in a derived class. Note that this function can also be passed to the Fit initializer using the jacp keyword or can be omitted entirely in which case the Jacobian will be calculated numerically.
It must either have signature:
jacp(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:
jacp(self,x1,x2,…,xm,p1,p2,…,pn)
where the independent variable x has m dimensions at each observation.
It must return an array (or array like object) with values:
[df/dx1,df/dx2,…]
if f returns a scalar or:
- [[df1/dx1,df1/dx2,…],
[df2/dx1,df2/dx2,…],…]
if f returns a 1-d array [f1,f2,…].
- jacx(*a)¶
The derivative fit function with respect to the x-values:
This may be implemented in a derived class. Note that this function can also be passed to the Fit initializer using the jacp keyword or can be omitted entirely in which case this Jacobian will be calculated numerically if it is needed.
It must either have signature:
jacp(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:
jacp(self,x1,x2,…,xm,p1,p2,…,pn)
where the independent variable x has m dimensions at each observation.
It must return an array (or array like object) with values:
[df/dp1,df/dp2,…]
if f returns a scalar or:
- [[df1/dp1,df1/dp2,…],
[df2/dp1,df2/dp2,…],…]
if f returns a 1-d array [f1,f2,…].
- class metrolopy.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:
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': [MFraction(1, 1000000000000000000), 'a', None, None, None], 'centi': [MFraction(1, 100), 'c', None, None, None], 'deca': [10, 'da', None, None, None], 'deci': [MFraction(1, 10), 'd', None, None, None], 'exa': [1000000000000000000, 'E', None, None, None], 'femto': [MFraction(1, 1000000000000000), 'f', None, None, None], 'giga': [1000000000, 'G', None, None, None], 'hecto': [100, 'h', None, None, None], 'kilo': [1000, 'k', None, None, None], 'mega': [1000000, 'M', None, None, None], 'micro': [MFraction(1, 1000000), 'μ', 'μ', None, 'u'], 'milli': [MFraction(1, 1000), 'm', None, None, None], 'nano': [MFraction(1, 1000000000), 'n', None, None, None], 'peta': [1000000000000000, 'P', None, None, None], 'pico': [MFraction(1, 1000000000000), 'p', None, None, None], 'tera': [1000000000000, 'T', None, None, None], 'yocto': [MFraction(1, 1000000000000000000000000), 'y', None, None, None], 'yotta': [1000000000000000000000000, 'Y', None, None, None], 'zepto': [MFraction(1, 1000000000000000000000), 'z', None, None, None], 'zetta': [1000000000000000000000, 'Z', None, None, None]}¶
- class metrolopy.Quantity(value, unit=1)¶
Bases:
PrettyPrinter,AbcQuantityInstances 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 (numeric (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
- conjugate()¶
- 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)¶
returns a copy of self. If tofloat is True, the self.value will be converted to float. The default is 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¶
- tobaseunit()¶
Returns a Quantity equal to self converted to unit self.unit.base
- tofloat()¶
returns a copy of self with value float(self.value) equivalent to copy(tofloat=True)
- tostring(fmt='unicode')¶
returns a string representation of the Quantity. fmt may be “unicode”, “html”,”latex” or “ascii”. The default is “unicode”.
- totuple()¶
returns the tuple (self.value,self.unit)
- 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 unit_is_one¶
- property value¶
- class metrolopy.SinFit(x, y=None, f=None, p0=None, ux=None, uy=None, variance_is_known=None, xunit=None, yunit=None, solver=None, xweights=None, weights=None, xcov=None, ycov=None, ignore_correlations=False, fix=None, fargs=[], fkwds={}, **kw)¶
Bases:
Fit- SinFit(x,y,p0=None,ux=None,uy=None,variance_is_known=True,xunit=None, yunit=None,
solver=None,**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) – The indepenant variables x. For n data points this should be an array of shape (n,) for a one-dimensional fit or shape (m,n) for an m-dimensional fit. The maximum dimension m is 3.
The x-values may be all float or all gummy, If uncertainties u are defined for the x-values, the xweights will be set to 1/u**2 for each point. To override this behavior set the keyword parameter “xweights = 1”. If uncertainties are defined for the x-values, the default solver is odr. If the nls or ols solver is manually selected then the uncertainties in the x-values will be ignored. For an m-dimential fit, the odr solver will take into account correlations between the m elements of the x-values for each data point, but ignores correlations between different data points and bewteen the x- and y-values.
y (array) – Response variables y.
The y-values may be all float or all gummy, If uncertainties u are defined for the y-values, the weights will be set to 1/u**2 for each point. To override this behavior set the keyword parameter “weights = 1”.
If the nls or odr solver is used, the weighting will take into account correlations between the different points. However, the odr solver ignores correlations between different data points. If the y-values are multi-dimensional, the odr solver will take into account correlations between the different elements at each point.
fix (array of bool) – A mask for the fit parameters. For any element in fix that is True, the corresponding fit parameter will be held constant at its initial value.
solver ({‘ols’,’nls’,’odr’}, optional) – A non-linear least squares (nls), ordinary least squares (ols) or othogonal distance regression solver (odr) can be used to perform the fit.
ols is the default solver unless uncertainties are specified for the x-values, in which case the default solver is odr.
The nls solver uses scipy.optimize.least_squares while the odr solver used odrpack.odr_fit. The ols solver uses scipy.linag.pinvh to invert the normal equation matrix.
ux (array or float, optional) – Uncertainties for the x-values. Specifying ux is an alternative to passing gummys with uncerainties defined as the the x-values. ux can be a number that applies to all the x-values or an array giving the uncertainty for each x-value.
If uncertainties u are defined individually for the x-values, the xweights will be set to 1/u**2 for each point. To override this behavior set the keyword parameter “xweights = 1”. If uncertainties are defined for the x-values, the default solver is odr. If the nls or ols solver is manually selected then the uncertainties in the x-values will be ignored.
uy (array or float, optional) – Uncertainties for the y-values. Specifying uy is an alternative to passing gummys with uncerainties defined as the the y-values. uy can be a number that applies to all the x-values or an array giving the uncertainty for each y-value.
If uncertainties u are defined individually for the y-values, the weights will be set to 1/u**2 for each point. To override this behavior set the keyword parameter “weights = 1”
variance_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.
p0 (array of float, optional) – initial values for the fit parameters.
- p¶
The fitted values for the fit function parameters as gummys including uncertainties and units.
- Type:
numpy.array of gummy
- pf¶
The fitted values for the fit function parameters as floats
- Type:
numpy.array of float
- res¶
the weighted fit residuals
- Type:
numpy.ndarray of float
- var¶
the variance of the weighted fit residuals
- Type:
float
- s¶
the standard deviation of weighted the residuals
- Type:
float
- cov¶
the covariance matrix of the (non-fixed) parameters
- Type:
numpy.ndarray of float
- known_var¶
If uncertainties are defined for the y-values (and possible the x-values), this is the predicted variance of the weighted fit residuals. If uncertainites are not defined for the y- or x-values, this is None.
- Type:
float
- yvar¶
the variance of the residual differences between the fitted values and the weighted y-values. For the nls and ols solver this is the same as var.
- Type:
float
- xvar¶
the variance of the residual differences between the fitted values and the weighted x-values. For the nls and ols solver this is None.
- Type:
float
- rcov¶
the covariance matrix of the (non-fixed) parameters divided by the variance
- Type:
numpy.ndarray of float
- fit_output¶
the return value of scipy.optimize.least_squares for the nls solver of the return value of odr_fit.odrpack for the odr solver. This is None if the ols solver is used.
- 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 (x) 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 (non-fixed) fit parameters
- Type:
int
- dof¶
degrees of freedom for the fit
- Type:
float
- ypred(x1,x2,...):
Takes xdim floats (or arrays of float) and returns a gummy representing the predicted value(s) at that x-coordinate.
- ypredf(x1,x2,...):
Takes xdim floats (or arrays of float) and returns a float giving the predicted value(s) 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 to the Fit initializer.
- 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)¶
The Jacobian of the fit function.
[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,…].
A NotImplementedError will be raised unless both the jacx and jacp methods are implemented.
- class metrolopy.TDist(x, s, dof)¶
Bases:
Distribution- bayesian_default = False¶
- static cdf(z, x, s, dof)¶
- 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.TrapezoidalDist(lower_limit, upper_limit, top_to_base_ratio)¶
Bases:
Distribution- static cdf(z, lower_limit, upper_limit, top_to_base_ratio)¶
- 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.TriangularDist(mode, left_width=None, right_width=None, half_width=None, lower_limit=None, upper_limit=None)¶
Bases:
Distribution- static cdf(z, mode, left_width, right_width)¶
- 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.UncertainComplexValue¶
Bases:
Number- abstractmethod angle()¶
- abstractmethod conjugate()¶
- abstract property cov¶
- abstract property imag¶
- abstract property phi¶
- abstract property r¶
- abstract property real¶
- abstract property x¶
- class metrolopy.UncertainValue¶
Bases:
Number- abstractmethod tostring(**kwds)¶
- abstract property u¶
- abstract property x¶
- exception metrolopy.UncertiantyPrecisionWarning¶
Bases:
Warning
- class metrolopy.UniformDist(center=None, half_width=None, lower_limit=None, upper_limit=None)¶
Bases:
Distribution- static cdf(z, center, half_width)¶
- 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.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:
AbcUnit,PrettyPrinter,IndexedCreating 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
ThePrefixedUnitCreates a set of units with SI prefixes (…, kilo, mega, giga, …)
BinaryPrefixedUnitCreates a set of unit with binary prefixes (…, kibi, mebi, gibi, …)
LogUnitLogrithmic units (e.g. decibel or neper)
OffsetUnitUnits with an offset origin (degree Celsius or degree Fahrenheit)
- property base¶
read-only
Returns the base unit. That is we follow the chain of conversions starting with this units Conversion instance until we get to a unit that has no Conversion instance. If this unit has no Conversion instance self is returned.
- 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¶
- tostring(fmt=None, strip=True, **kwds)¶
Returns a string containing the symbol for the instance in the format given by the keyword fmt which may be set to a string the values ‘html’, ‘latex’, ‘ascii’ or ‘unicode’.
- 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)].
- exception metrolopy.UnitError¶
Bases:
ValueErrorBase class for Unit exceptions.
- exception metrolopy.UnitLibError¶
Bases:
UnitErrorThis exception is raised when the UnitLibrary cannot parse a unit string.
- exception metrolopy.UnitLibNotFoundError¶
Bases:
UnitLibError
- exception metrolopy.UnitNotFoundError¶
Bases:
UnitLibError
- exception metrolopy.UnitWarning¶
Bases:
Warning
- class metrolopy.WeibullDist(shape, scale)¶
Bases:
Distribution- static cdf(z, shape, scale)¶
- 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.absolute(x)¶
Returns the absoulte value of x where x can be float, complex, gummy or jummy. This is equivalent to abs(x).
- metrolopy.add(x1, x2)¶
returns x1 + x2
- metrolopy.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.arccos(x)¶
Returns the inverse cosine of x where x can be float, complex, gummy or jummy.
- metrolopy.arccosh(x)¶
Returns the inverse hyperbolic cosine of x where x can be float, complex, gummy or jummy.
- metrolopy.arcsin(x)¶
Returns the inverse sine of x where x can be float, complex, gummy or jummy.
- metrolopy.arcsinh(x)¶
Returns the inverse hyperbolic sine of x where x can be float, complex, gummy or jummy.
- metrolopy.arctan(x)¶
Returns the inverse tangent of x where x can be float, complex, gummy or jummy.
- metrolopy.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.arctanh(x)¶
Returns the inverse hyperbolic tangent of x where x can be float, complex, gummy or jummy.
- metrolopy.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.autocorrelation(x)¶
Find the de-meaned and normalized autocorrelation of the array x
- metrolopy.cbrt(x)¶
Returns the cube root of x where x can be float, complex, gummy or jummy.
- metrolopy.ceil(x)¶
Returns the ceiling of x where x can be float, complex, gummy or jummy.
- metrolopy.clear_all_sim()¶
Clears Monte-Carlo data from all existing gummys.
This is an alias for the gummy.clear_all static method.
- metrolopy.conj(x)¶
returns x.conjugate(), the complex conjugate of x
- metrolopy.constant(name, toummy=None, splonk=None)¶
Finds an returns a constants from the constant library.
Parameter¶
- name: str, Unit or 1
The name or alias of the constant.
- returns:
A GummyConstant or JummyConstant instance
ummy/immy Quantity instances can bre retrieved by setting toummy to True
or GummyConstant.toummy to True. splonk the returned value by setting
splonk to True or GummyConstant.splonk to True
- metrolopy.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.correlation_matrix(gummys)¶
Returns the correlation matrix of a list or array of gummys.
This is an alias for the gummy.correlation_matrix static method.
- metrolopy.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.
This is an alias for the gummy.correlation_matrix_sim static method.
- metrolopy.cos(x)¶
Returns the cosine of x where x can be float, complex, gummy or jummy.
- metrolopy.cosh(x)¶
Returns the hyperbolic cosine of x where x can be float, complex, gummy or jummy.
- metrolopy.covariance_matrix(gummys)¶
Returns the variance-covariance matrix of a list or array of gummys.
This is an alias for the gummy.covariance_matrix static method.
- metrolopy.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.
This is an alias for the gummy.covariance_matrix_sim static method.
- metrolopy.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.1decreases the size of the dots in the plot.This is an alias for the `gummy.covplot` static method.
- metrolopy.cross(*args, **kwds)¶
Alias for numpy.cross
- metrolopy.cumprod(*args, **kwds)¶
Alias for numpy.cumprod
- metrolopy.cumsum(*args, **kwds)¶
Alias for numpy.cumsum
- metrolopy.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.delta_diff_mean(x, n_sigma=None, unit=1, utype=None)¶
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.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.delta_sum_mean(x, n_sigma=None, unit=1, utype=None)¶
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.diff(*args, **kwds)¶
Alias for numpy.diff
- metrolopy.divide(x1, x2)¶
returns x1 / x2
- metrolopy.divmod(x1, x2)¶
returns (x1 // x2, x1 % x2)
- metrolopy.ediff1d(*args, **kwds)¶
Alias for numpy.ediff1d
- metrolopy.exp(x)¶
Returns e to the power of x where x can be float, complex, gummy or jummy.
- metrolopy.exp2(x)¶
Returns 2 to the power of x where x can be float, complex, gummy or jummy.
- metrolopy.expm1(x)¶
Returns exp(x) - 1 where x can be float, complex, gummy or jummy.
- metrolopy.fix(x)¶
Returns x rounded towards zero where x can be float, complex, gummy or jummy.
- metrolopy.floor(x)¶
Returns the floor of x where x can be float, complex, gummy or jummy.
- metrolopy.floor_divide(x1, x2)¶
returns x1 // x2
- class metrolopy.gummy(x, u=0, unit=1, dof=DoF(inf), k=1, p=None, uunit=None, utype=None, name=None)¶
Bases:
Quantity,UncertainValue,DfuncA 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 (Number, Distribution,`scipy.stats.rv_frozen` or gummy) – A number representing the value of the gummy or a distribution, either a Distribution instance or a scipy.stats rv_frozen 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 a (correlated) copy is produced.
u (Number >= 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 (Number > 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()¶
- 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.
- clear()¶
Clears the gummys Monte-Carlo data.
- static clear_all()¶
Clears Monte-Carlo data from all existing gummys.
- conjugate()¶
returns a copy of the gummy
- copy(formatting=True, totype=None)¶
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 ‘totype` is defined the x and u properties will be converted to type totype 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.1decreases the size of the dots in the plot.
- classmethod create(x, u=0, unit=1, dof=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.
- datafrom(x, save=True)¶
Recomputes the Monte-Carlo simdata `with only the varaibles in `x allowed to vary. sim or simulate must be called to generate Monte-Carlo data before calling this method. This method cannot be called with save == True from from a gummy representing an independent variable (that is from a gummy not created by by mathematical operations between two or more other gummy’s).
- Parameters:
ufrom (list containing gummy or str) – all independent gummys not in the list or having a utype not in the list are held fixed at their .x value
save (If save is True the recomputed data is stored in the simdata) – attribute and None is returned. If save is False then the recomputed data is returned and the simdata attribute is not overwritten.
- Return type:
‘numpy.array’ if save is False, otherwise returns None
- Raises:
NoSimulatedDataError – if no simulated data is available from a call to Distribution.simulate.
RuntimeError – if this method is called from an independent gummy
- 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.
- 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, fig_options={}, subplot_options={}, **hist_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.fig_options (dict, optional) – keywords passed to pyplot.figure when creating the figure
subplot_options (dict, options) – keywords passed to pyplot.figure.add_subplot when creating the subplot
**kwds – Any additional keywords are passed to pyplot.hist.
- Return type:
Figure, Axes
- 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 True if the gummy is an independent variable. That is the ummy has u > 0 and was not correlated with any other gummy’s when it was created or is perfectly correlated or anti-correlated (correlation coefficeint 1 or -1) with such an ummy. Identical to the isindependent property.
- property isindependent¶
bool, read-only
Returns True if the gummy is an independent variable. That is the ummy has u > 0 and was not correlated with any other gummy’s when it was created or is perfectly correlated or anti-correlated (correlation coefficeint 1 or -1) with such an ummy.
- 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 = 20¶
- 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.
- 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 (as well as for any gummys that this gummy depends on). 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.
gummys (A list or array of gummy for which to generate the Monte-Carlo) – data.
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)¶
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
- ufromsim(x)¶
Gets the standard deviation of the Monte-Carlo data only allowing the independent variables in x to vary. Independent istributions not in x are held fixed. sim or simulate must be called to generate Monte-Carlo data before calling this method.
- Parameters:
x (gummy, str, or array_like) – A gummy, a string referencing a utype or a list containing gummys and strings.
- Return type:
float
- 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, None or a list containing strings and possibly None
An arbitrary string value labeling the uncertainty type or or a list of types if the gummy was constructed from independent variables with different utypes.
- 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.
- metrolopy.heaviside(x, h0)¶
Heavyside function of x, h0 is the value at x = 0
- metrolopy.imag(x)¶
returns x.imag
- class metrolopy.immy(real=None, imag=None, r=None, phi=None, cov=None)¶
Bases:
PrettyPrinter,Dfunc,UncertainComplexValue- angle()¶
Returns the polar angle in radians (which is also the phi read-only property value).
- conjugate()¶
Returns the complex conjugate.
- copy(formatting=True, totype=None)¶
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 (self.angle())
- property r¶
read-only Returns the magnitude of the value (abs(self)).
- 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.jummy(real=None, imag=None, r=None, phi=None, cov=None, name=None)¶
Bases:
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.log(x)¶
Returns the natural logrithm of x where x can be float, complex, gummy or jummy.
- metrolopy.log10(x)¶
Returns the log base 10 of x where x can be float, complex, gummy or jummy.
- metrolopy.log1p(x)¶
Returns the natural logrithm of x plus 1 where x can be float, complex, gummy or jummy.
- metrolopy.log2(x)¶
Returns the log base 2 of x where x can be float, complex, gummy or jummy.
- metrolopy.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.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.mean(x, n_sigma_trim=None, unit=1, ignore_nan=True, use_n_eff=False, utype=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 or float, 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 None.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. The default value is False.
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_datetime(*params)¶
- metrolopy.mod(x1, x2)¶
returns x1 % x2
- metrolopy.modf(x1)¶
returns (x1 % 1, x1 // 1), a tuple of integer and fractional parts
- metrolopy.multiply(x1, x2)¶
returns x1 * x2
- metrolopy.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.negative(x)¶
returns -x
- metrolopy.power(x1, x2)¶
returns x1**x2
- metrolopy.prod(*args, **kwds)¶
Alias for numpy.prod
- metrolopy.real(x)¶
returns x.real
- metrolopy.reciprocal(x)¶
returns 1/x
- metrolopy.remainder(x1, x2)¶
returns x1 % x2
- metrolopy.rint(x)¶
Returns x rounded to the nearest integer value where x can be float, complex, gummy or jummy.
- metrolopy.search_constants(search=None, fmt=None, constants=None)¶
Prints a list of all loaded constant or all constants 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 constants 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.
constants (list of str,optional) – A list of constants to print. If this parameter is specified the values of the search and show_all parameters are ignored.
- Returns:
A search_constants_result instance which emulates a list of the returned
constants and pretty-prints the results to the output or None if no
constants are found.
- class metrolopy.search_constants_result(constants)¶
Bases:
PrettyPrinterA search_constants_result instance emulates a list of constants returned from a ‘search_constants` function call, and pretty-prints the results to the output
- tostring(fmt='unicode', **kwds)¶
- metrolopy.search_units(search=None, fmt=None, show_all=False, units=None, converts_to=None)¶
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.
- Returns:
A search_units_result instance which emulates a list of the returned
constants and pretty-prints the results to the output or None if no
units are found.
- class metrolopy.search_units_result(units, show_all)¶
Bases:
PrettyPrinterA search_units_result instance emulates a list of units returned from a ‘search_units` function call, and pretty-prints the results to the output
- tostring(fmt='unicode', **kwds)¶
- metrolopy.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.shadowed_constants(fmt=None, prnt=True)¶
Lists any constants which have a shadowed name or alias. Constants may be shadowed if the user has defined a new constant with the same name or alias as an existing constant.
- 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.
- metrolopy.shadowed_units(fmt=None)¶
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.
- metrolopy.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.sign(x)¶
sign of x
- metrolopy.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.
gummys (A list or array of gummy for which to generate the Monte-Carlo) – data.
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.
This is an alias for the `gummy.simulate` static method.
- metrolopy.sin(x)¶
Returns the sine of x where x can be float, complex, gummy or jummy.
- metrolopy.sinh(x)¶
Returns the hyperbolic sine of x where x can be float, complex, gummy or jummy.
- metrolopy.sqrt(x)¶
Returns the square root of x where x can be float, complex, gummy or jummy.
- metrolopy.square(x)¶
Returns the square of x where x can be float, complex, gummy or jummy.
- metrolopy.subtract(x1, x2)¶
returns x1 - x2
- metrolopy.sum(*args, **kwds)¶
Alias for numpy.sum
- metrolopy.tan(x)¶
Returns the tangent of x where x can be float, complex, gummy or jummy.
- metrolopy.tanh(x)¶
Returns the hyperbolic tangent of x where x can be float, complex, gummy or jummy.
- metrolopy.true_divide(x1, x2)¶
returns x1 / x2
- metrolopy.trunc(x)¶
Returns x rounded towards zero where x can be float, complex, gummy or jummy.
- class metrolopy.ummy(x, u=0, dof=DoF(inf), utype=None)¶
Bases:
Dfunc,PrettyPrinter,UncertainValue- angle()¶
- conjugate()¶
- copy(formatting=True, totype=None)¶
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 totype is defined the x and u properties will be converted to type totype 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.
- correlation_tolerance = 1e-14¶
- 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=DoF(inf), utype=None, correlation_matrix=None, covariance_matrix=None)¶
A class method that creates a list of (possibly) correlated ummys.
- Parameters:
x – A list or array of numbers 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.
- doffrom(x)¶
Gets the degrees of freedom 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,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
- exception_on_fmt_error = False¶
- property finfo¶
- property imag¶
- property isindependent¶
bool, read-only
Returns True if the ummy is an independent variable. That is the ummy has u > 0 and was not correlated with any other ummy’s when it was created or is perfectly correlated or anti-correlated (correlation coefficeint 1 or -1) with such an ummy.’
- max_digits = 20¶
- 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 float.
- 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, None or a list containing strings and possibly None
An arbitrary string value labeling the uncertainty type or or a list of types if the gummy was constructed from independent variables with different utypes.
- property x¶
- metrolopy.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.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