Package uncertainties
source code
Calculations with full error propagation for quantities with uncertainties.
Derivatives can also be calculated.
Web user guide: http://packages.python.org/uncertainties/.
Example of possible calculation: (0.2 +/- 0.01)**2 = 0.04 +/- 0.004.
Correlations between expressions are correctly taken into account (for
instance, with x = 0.2+/-0.01, 2*x-x-x is exactly zero, as is y-x-x
with y = 2*x).
Examples:
import uncertainties
from uncertainties import ufloat
from uncertainties.umath import * # sin(), etc.
# Mathematical operations:
x = ufloat((0.20, 0.01)) # x = 0.20+/-0.01
x = ufloat("0.20+/-0.01") # Other representation
x = ufloat("0.20(1)") # Other representation
x = ufloat("0.20") # Implicit uncertainty of +/-1 on the last digit
print x**2 # Square: prints "0.04+/-0.004"
print sin(x**2) # Prints "0.0399...+/-0.00399..."
print x.position_in_sigmas(0.17) # Prints "-3.0": deviation of -3 sigmas
# Access to the nominal value, and to the uncertainty:
square = x**2 # Square
print square # Prints "0.04+/-0.004"
print square.nominal_value # Prints "0.04"
print square.std_dev() # Prints "0.004..."
print square.derivatives[x] # Partial derivative: 0.4 (= 2*0.20)
# Correlations:
u = ufloat((1, 0.05), "u variable") # Tag
v = ufloat((10, 0.1), "v variable")
sum_value = u+v
u.set_std_dev(0.1) # Standard deviations can be updated on the fly
print sum_value - u - v # Prints "0.0" (exact result)
# List of all sources of error:
print sum_value # Prints "11+/-0.1414..."
for (var, error) in sum_value.error_components().iteritems():
print "%s: %f" % (var.tag, error) # Individual error components
# Covariance matrices:
cov_matrix = uncertainties.covariance_matrix([u, v, sum_value])
print cov_matrix # 3x3 matrix
# Correlated variables can be constructed from a covariance matrix, if
# NumPy is available:
(u2, v2, sum2) = uncertainties.correlated_values([1, 10, 11],
cov_matrix)
print u2 # Value and uncertainty of u: correctly recovered (1+/-0.1)
print uncertainties.covariance_matrix([u2, v2, sum2]) # == cov_matrix
- The main function provided by this module is ufloat, which creates
numbers with uncertainties (Variable objects). Variable objects can
be used as if they were regular Python numbers. The main attributes
and methods of Variable objects are defined in the documentation of
the Variable class.
- Valid operations on numbers with uncertainties include basic
mathematical functions (addition, etc.).
Most operations from the standard math module (sin, etc.) can be applied
on numbers with uncertainties by using their generalization from the
uncertainties.umath module:
from uncertainties.umath import sin
print sin(ufloat("1+/-0.01")) # 0.841...+/-0.005...
print sin(1) # umath.sin() also works on floats, exactly like math.sin()
Logical operations (>, ==, etc.) are also supported.
Basic operations on NumPy arrays or matrices of numbers with
uncertainties can be performed:
2*numpy.array([ufloat((1, 0.01)), ufloat((2, 0.1))])
More complex operations on NumPy arrays can be performed through the
dedicated uncertainties.unumpy sub-module (see its documentation).
Calculations that are performed through non-Python code (Fortran, C,
etc.) can handle numbers with uncertainties instead of floats through
the provided wrap() wrapper:
import uncertainties
# wrapped_f is a version of f that can take arguments with
# uncertainties, even if f only takes floats:
wrapped_f = uncertainties.wrap(f)
If some derivatives of the wrapped function f are known (analytically,
or numerically), they can be given to wrap()--see the documentation
for wrap().
- Utility functions are also provided: the covariance matrix between
random variables can be calculated with covariance_matrix(), or used
as input for the definition of correlated quantities (correlated_values()
function--defined only if the NumPy module is available).
- Mathematical expressions involving numbers with uncertainties
generally return AffineScalarFunc objects, which also print as a value
with uncertainty. Their most useful attributes and methods are
described in the documentation for AffineScalarFunc. Note that
Variable objects are also AffineScalarFunc objects. UFloat is an
alias for AffineScalarFunc, provided as a convenience: testing whether
a value carries an uncertainty handled by this module should be done
with insinstance(my_value, UFloat).
- Mathematically, numbers with uncertainties are, in this package,
probability distributions. These probabilities are reduced to two
numbers: a nominal value and an uncertainty. Thus, both variables
(Variable objects) and the result of mathematical operations
(AffineScalarFunc objects) contain these two values (respectively in
their nominal_value attribute and through their std_dev() method).
The uncertainty of a number with uncertainty is simply defined in
this package as the standard deviation of the underlying probability
distribution.
The numbers with uncertainties manipulated by this package are assumed
to have a probability distribution mostly contained around their
nominal value, in an interval of about the size of their standard
deviation. This should cover most practical cases. A good choice of
nominal value for a number with uncertainty is thus the median of its
probability distribution, the location of highest probability, or the
average value.
- When manipulating ensembles of numbers, some of which contain
uncertainties, it can be useful to access the nominal value and
uncertainty of all numbers in a uniform manner:
x = ufloat("3+/-0.1")
print nominal_value(x) # Prints 3
print std_dev(x) # Prints 0.1
print nominal_value(3) # Prints 3: nominal_value works on floats
print std_dev(3) # Prints 0: std_dev works on floats
- Probability distributions (random variables and calculation results)
are printed as:
nominal value +/- standard deviation
but this does not imply any property on the nominal value (beyond the
fact that the nominal value is normally inside the region of high
probability density), or that the probability distribution of the
result is symmetrical (this is rarely strictly the case).
- Linear approximations of functions (around the nominal values) are
used for the calculation of the standard deviation of mathematical
expressions with this package.
The calculated standard deviations and nominal values are thus
meaningful approximations as long as the functions involved have
precise linear expansions in the region where the probability
distribution of their variables is the largest. It is therefore
important that uncertainties be small. Mathematically, this means
that the linear term of functions around the nominal values of their
variables should be much larger than the remaining higher-order terms
over the region of significant probability.
For instance, sin(0+/-0.01) yields a meaningful standard deviation
since it is quite linear over 0+/-0.01. However, cos(0+/-0.01) yields
an approximate standard deviation of 0 (because the cosine is not well
approximated by a line around 0), which might not be precise enough
for all applications.
- Comparison operations (>, ==, etc.) on numbers with uncertainties
have a pragmatic semantics, in this package: numbers with
uncertainties can be used wherever Python numbers are used, most of
the time with a result identical to the one that would be obtained
with their nominal value only. However, since the objects defined in
this module represent probability distributions and not pure numbers,
comparison operator are interpreted in a specific way.
The result of a comparison operation ("==", ">", etc.) is defined so as
to be essentially consistent with the requirement that uncertainties
be small: the value of a comparison operation is True only if the
operation yields True for all infinitesimal variations of its random
variables, except, possibly, for an infinitely small number of cases.
Example:
"x = 3.14; y = 3.14" is such that x == y
but
x = ufloat((3.14, 0.01))
y = ufloat((3.14, 0.01))
is not such that x == y, since x and y are independent random
variables that almost never give the same value. However, x == x
still holds.
The boolean value (bool(x), "if x...") of a number with uncertainty x
is the result of x != 0.
- The uncertainties package is for Python 2.5 and above.
- This package contains tests. They can be run either manually or
automatically with the nose unit testing framework (nosetests).
(c) 2009-2010 by Eric O. LEBIGOT (EOL) <eric.lebigot@normalesup.org>.
Please send feature requests, bug reports, or feedback to this address.
Please support future development by donating $5 or more through PayPal!
This software is released under a dual license. (1) The BSD license.
(2) Any other license, as long as it is obtained from the original
author.
Version:
1.7.1
Author:
Eric O. LEBIGOT (EOL)
|
NotUpcast
|
|
NumericalDerivatives
Sequence with the successive numerical derivatives of a function.
|
|
AffineScalarFunc
Affine functions that support basic mathematical operations
(addition, etc.).
|
|
UFloat
Affine functions that support basic mathematical operations
(addition, etc.).
|
|
Variable
Representation of a float-like scalar random variable, along with
its uncertainty.
|
|
set_doc(doc_string)
Decorator function that sets the docstring to the given text. |
source code
|
|
|
to_affine_scalar(x)
Transforms x into a constant affine scalar function
(AffineScalarFunc), unless it is already an AffineScalarFunc (in
which case x is returned unchanged). |
source code
|
|
|
partial_derivative(f,
param_num)
Returns a function that numerically calculates the partial derivative
of function f with respect to its argument number param_num. |
source code
|
|
|
wrap(f,
derivatives_funcs=None)
Wraps function f so that, when applied to numbers with uncertainties
(AffineScalarFunc objects) or float-like arguments, f returns a local
approximation of its values (in the form of an object of class
AffineScalarFunc). |
source code
|
|
|
|
|
_eq_on_aff_funcs(self,
y_with_uncert)
__eq__ operator, assuming that both self and y_with_uncert are
AffineScalarFunc objects. |
source code
|
|
|
_ne_on_aff_funcs(self,
y_with_uncert)
__ne__ operator, assuming that both self and y_with_uncert are
AffineScalarFunc objects. |
source code
|
|
|
_gt_on_aff_funcs(self,
y_with_uncert)
__gt__ operator, assuming that both self and y_with_uncert are
AffineScalarFunc objects. |
source code
|
|
|
_ge_on_aff_funcs(self,
y_with_uncert)
__ge__ operator, assuming that both self and y_with_uncert are
AffineScalarFunc objects. |
source code
|
|
|
_lt_on_aff_funcs(self,
y_with_uncert)
__lt__ operator, assuming that both self and y_with_uncert are
AffineScalarFunc objects. |
source code
|
|
|
_le_on_aff_funcs(self,
y_with_uncert)
__le__ operator, assuming that both self and y_with_uncert are
AffineScalarFunc objects. |
source code
|
|
|
get_ops_with_reflection()
Returns operators with a reflection, along with their derivatives
(for float operands). |
source code
|
|
|
add_operators_to_AffineScalarFunc()
Adds many operators (__add__, etc.) to the AffineScalarFunc class. |
source code
|
|
|
nominal_value(x)
Returns the nominal value of x if it is a quantity with uncertainty
(i.e., an AffineScalarFunc object); otherwise, returns x unchanged. |
source code
|
|
|
std_dev(x)
Returns the standard deviation of x if it is a quantity with
uncertainty (i.e., an AffineScalarFunc object); otherwise, returns
the float 0. |
source code
|
|
|
covariance_matrix(functions)
Returns a matrix that contains the covariances between the given
sequence of numbers with uncertainties (AffineScalarFunc objects). |
source code
|
|
|
correlated_values(values,
covariance_mat,
tags=None)
Returns numbers with uncertainties (AffineScalarFunc objects) that
correctly reproduce the given covariance matrix, and have the given
values as their nominal value. |
source code
|
|
|
|
|
|
|
ufloat(representation,
tag=None)
Returns a random variable (Variable object). |
source code
|
|
|
|
|
|
|
|
|
|
|
|
|
__version_info__ = ( 1, 7, 1)
|
|
_ops_with_reflection = get_ops_with_reflection()
|
|
_modified_operators = [ ' neg ' , ' abs ' , ' pos ' , ' trunc ' ]
|
|
POSITIVE_DECIMAL_UNSIGNED = ' (\\d+)(\\.\\d*)? '
|
|
NUMBER_WITH_UNCERT_RE_STR = ' \n ([+-])? # Sign\n (\\d+) ...
|
|
NUMBER_WITH_UNCERT_RE = re.compile(r'(?x) ^( [ \+-] ) ? ( \d+ ) ( \.\d* ) ...
|
|
__package__ = ' ComboCode.cc.ivs.units.uncertainties '
|
Decorator function that sets the docstring to the given text.
It is useful for functions whose docstring is calculated (including
string substitutions).
|
Transforms x into a constant affine scalar function
(AffineScalarFunc), unless it is already an AffineScalarFunc (in which
case x is returned unchanged).
Raises an exception unless 'x' belongs to some specific classes of
objects that are known not to depend on AffineScalarFunc objects (which
then cannot be considered as constants).
|
Returns a function that numerically calculates the partial derivative
of function f with respect to its argument number param_num.
The step parameter represents the shift of the parameter used in the
numerical approximation.
|
Wraps function f so that, when applied to numbers with uncertainties
(AffineScalarFunc objects) or float-like arguments, f returns a local
approximation of its values (in the form of an object of class
AffineScalarFunc). In this case, if none of the arguments of f involves
variables [i.e. Variable objects], f simply returns its usual result.
When f is not called on AffineScalarFunc or float-like arguments, the
original result of f is returned.
If supplied, 'derivatives_funcs' is a sequence or iterator that
generally contains functions; each successive function is the partial
derivatives of f with respect to the corresponding variable (one function
for each argument of f, which takes as many arguments as f). If
derivatives_funcs is None, or if derivatives_funcs contains a finite
number of elements, then missing derivatives are calculated numerically
through partial_derivative().
Example: wrap(math.sin) is a sine function that can be applied to
numbers with uncertainties. Its derivative will be calculated
numerically. wrap(math.sin, [None]) would have produced the same result.
wrap(math.sin, [math.cos]) is the same function, but with an analytically
defined derivative.
|
Takes an operator op(x, y) and wraps it.
The constructed operator returns func(x, to_affine_scalar(y)) if y can
be upcast with to_affine_scalar(); otherwise, it returns
NotImplemented.
Thus, func() is only called on two AffineScalarFunc objects, if its
first argument is an AffineScalarFunc.
|
Returns the nominal value of x if it is a quantity with uncertainty
(i.e., an AffineScalarFunc object); otherwise, returns x unchanged.
This utility function is useful for transforming a series of numbers,
when only some of them generally carry an uncertainty.
|
Returns the standard deviation of x if it is a quantity with
uncertainty (i.e., an AffineScalarFunc object); otherwise, returns the
float 0.
This utility function is useful for transforming a series of numbers,
when only some of them generally carry an uncertainty.
|
Returns a matrix that contains the covariances between the given
sequence of numbers with uncertainties (AffineScalarFunc objects). The
resulting matrix implicitly depends on their ordering in 'functions'.
The covariances are floats (never int objects).
The returned covariance matrix is the exact linear approximation
result, if the nominal values of the functions and of their variables are
their mean. Otherwise, the returned covariance matrix should be close to
it linear approximation value.
|
correlated_values(values,
covariance_mat,
tags=None)
| source code
|
Returns numbers with uncertainties (AffineScalarFunc objects) that
correctly reproduce the given covariance matrix, and have the given
values as their nominal value.
The list of values and the covariance matrix must have the same
length, and the matrix must be a square (symmetric) one.
The affine functions returned depend on newly created, independent
variables (Variable objects).
If 'tags' is not None, it must list the tag of each new independent
variable.
|
Returns (value, error) from a string representing a number with
uncertainty like 12.34(5), 12.34(142), 12.5(3.4) or 12.3(4.2)e3. If no
parenthesis is given, an uncertainty of one on the last digit is
assumed.
Raises ValueError if the string cannot be parsed.
|
Given a string that represents a number with uncertainty, returns the
nominal value and the uncertainty.
The string can be of the form:
- 124.5+/-0.15
- 124.50(15)
- 124.50(123)
- 124.5
When no numerical error is given, an uncertainty of 1 on the last
digit is implied.
Raises ValueError if the string cannot be parsed.
|
Returns a random variable (Variable object).
Converts the representation of a number into a number with
uncertainty (a random variable, defined by a nominal value and
a standard deviation).
The representation can be a (value, standard deviation) sequence,
or a string.
Strings of the form '12.345+/-0.015', '12.345(15)', or '12.3' are
recognized (see full list below). In the last case, an
uncertainty of +/-1 is assigned to the last digit.
'tag' is an optional string tag for the variable. Variables
don't have to have distinct tags. Tags are useful for tracing
what values (and errors) enter in a given result (through the
error_components() method).
Examples of valid string representations:
-1.23(3.4)
-1.34(5)
1(6)
3(4.2)
-9(2)
1234567(1.2)
12.345(15)
-12.3456(78)e-6
0.29
31.
-31.
31
-3.1e10
169.0(7)
169.1(15)
|
Wrapper for legacy code. Obsolete: do not use. Use ufloat
instead.
|
Wrapper for legacy code. Obsolete: do not use. Use ufloat
instead.
|
Wrapper for legacy code. Obsolete: do not use. Use unumpy.uarray
instead.
|
Wrapper for legacy code. Obsolete: do not use. Use
unumpy.nominal_values instead.
|
Wrapper for legacy code. Obsolete: do not use. Use ufloat
instead.
|
NUMBER_WITH_UNCERT_RE_STR
- Value:
'''
([+-])? # Sign
(\\d+)(\\.\\d*)? # Main number
(?:\\((\\d+)(\\.\\d*)?\\))? # Optional uncertainty
([eE][+-]?\\d+)? # Optional exponent
'''
|
|
NUMBER_WITH_UNCERT_RE
- Value:
re.compile(r'(?x) ^( [ \+-] ) ? ( \d+ ) ( \.\d* ) ? (?: \(( \d+ ) ( \.\d* ) ? \)) ? ( [ eE] [ \+-
] ? \d+ ) ? $')
|
|