index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
61,699 |
eval_type_backport.eval_type_backport
|
eval_type_backport
|
Like `typing._eval_type`, but lets older Python versions use newer typing features.
Specifically, this transforms `X | Y` into `typing.Union[X, Y]`
and `list[X]` into `typing.List[X]` etc. (for all the types made generic in PEP 585)
if the original syntax is not supported in the current Python version.
|
def eval_type_backport(
value: Any,
globalns: dict[str, Any] | None = None,
localns: dict[str, Any] | None = None,
try_default: bool = True,
) -> Any:
"""
Like `typing._eval_type`, but lets older Python versions use newer typing features.
Specifically, this transforms `X | Y` into `typing.Union[X, Y]`
and `list[X]` into `typing.List[X]` etc. (for all the types made generic in PEP 585)
if the original syntax is not supported in the current Python version.
"""
if not try_default:
return _eval_direct(value, globalns, localns)
try:
return typing._eval_type( # type: ignore
value, globalns, localns
)
except TypeError as e:
if not (isinstance(value, typing.ForwardRef) and is_backport_fixable_error(e)):
raise
return _eval_direct(value, globalns, localns)
|
(value: Any, globalns: Optional[dict[str, Any]] = None, localns: Optional[dict[str, Any]] = None, try_default: bool = True) -> Any
|
61,701 |
uncertainties.core
|
AffineScalarFunc
|
Affine functions that support basic mathematical operations
(addition, etc.). Such functions can for instance be used for
representing the local (linear) behavior of any function.
This class can also be used to represent constants.
The variables of affine scalar functions are Variable objects.
AffineScalarFunc objects include facilities for calculating the
'error' on the function, from the uncertainties on its variables.
Main attributes and methods:
- nominal_value, std_dev: value at the origin / nominal value, and
standard deviation. The standard deviation can be NaN or infinity.
- n, s: abbreviations for nominal_value and std_dev.
- error_components(): error_components()[x] is the error due to
Variable x.
- derivatives: derivatives[x] is the (value of the) derivative
with respect to Variable x. This attribute is a Derivatives
dictionary whose keys are the Variable objects on which the
function depends. The values are the numerical values of the
derivatives.
All the Variable objects on which the function depends are in
'derivatives'.
- std_score(x): position of number x with respect to the
nominal value, in units of the standard deviation.
|
class AffineScalarFunc(object):
"""
Affine functions that support basic mathematical operations
(addition, etc.). Such functions can for instance be used for
representing the local (linear) behavior of any function.
This class can also be used to represent constants.
The variables of affine scalar functions are Variable objects.
AffineScalarFunc objects include facilities for calculating the
'error' on the function, from the uncertainties on its variables.
Main attributes and methods:
- nominal_value, std_dev: value at the origin / nominal value, and
standard deviation. The standard deviation can be NaN or infinity.
- n, s: abbreviations for nominal_value and std_dev.
- error_components(): error_components()[x] is the error due to
Variable x.
- derivatives: derivatives[x] is the (value of the) derivative
with respect to Variable x. This attribute is a Derivatives
dictionary whose keys are the Variable objects on which the
function depends. The values are the numerical values of the
derivatives.
All the Variable objects on which the function depends are in
'derivatives'.
- std_score(x): position of number x with respect to the
nominal value, in units of the standard deviation.
"""
# To save memory in large arrays:
__slots__ = ('_nominal_value', '_linear_part')
# !! Fix for mean() in NumPy 1.8.0:
class dtype(object):
type = staticmethod(lambda value: value)
#! The code could be modified in order to accommodate for non-float
# nominal values. This could for instance be done through
# the operator module: instead of delegating operations to
# float.__*__ operations, they could be delegated to
# operator.__*__ functions (while taking care of properly handling
# reverse operations: __radd__, etc.).
def __init__(self, nominal_value, linear_part):
"""
nominal_value -- value of the function when the linear part is
zero.
linear_part -- LinearCombination that describes the linear
part of the AffineScalarFunc.
"""
# ! A technical consistency requirement is that the
# linear_part can be nested inside a NestedLinearCombination
# (because this is how functions on AffineScalarFunc calculate
# their result: by constructing nested expressions for them).
# Defines the value at the origin:
# Only float-like values are handled. One reason is that it
# does not make sense for a scalar function to be affine to
# not yield float values. Another reason is that it would not
# make sense to have a complex nominal value, here (it would
# not be handled correctly at all): converting to float should
# be possible.
self._nominal_value = float(nominal_value)
# In order to have a linear execution time for long sums, the
# _linear_part is generally left as is (otherwise, each
# successive term would expand to a linearly growing sum of
# terms: efficiently handling such terms [so, without copies]
# is not obvious, when the algorithm should work for all
# functions beyond sums).
self._linear_part = linear_part
# The following prevents the 'nominal_value' attribute from being
# modified by the user:
@property
def nominal_value(self):
"Nominal value of the random number."
return self._nominal_value
# Abbreviation (for formulas, etc.):
n = nominal_value
############################################################
# Making derivatives a property gives the user a clean syntax,
# which is consistent with derivatives becoming a dictionary.
@property
def derivatives(self):
"""
Return a mapping from each Variable object on which the function
(self) depends to the value of the derivative with respect to
that variable.
This mapping should not be modified.
Derivative values are always floats.
This mapping is cached, for subsequent calls.
"""
if not self._linear_part.expanded():
self._linear_part.expand()
# Attempts to get the contribution of a variable that the
# function does not depend on raise a KeyError:
self._linear_part.linear_combo.default_factory = None
return self._linear_part.linear_combo
############################################################
### Operators: operators applied to AffineScalarFunc and/or
### float-like objects only are supported. This is why methods
### from float are used for implementing these operators.
# Operators with no reflection:
########################################
# __nonzero__() is supposed to return a boolean value (it is used
# by bool()). It is for instance used for converting the result
# of comparison operators to a boolean, in sorted(). If we want
# to be able to sort AffineScalarFunc objects, __nonzero__ cannot
# return a AffineScalarFunc object. Since boolean results (such
# as the result of bool()) don't have a very meaningful
# uncertainty unless it is zero, this behavior is fine.
def __bool__(self):
"""
Equivalent to self != 0.
"""
#! This might not be relevant for AffineScalarFunc objects
# that contain values in a linear space which does not convert
# the float 0 into the null vector (see the __eq__ function:
# __nonzero__ works fine if subtracting the 0 float from a
# vector of the linear space works as if 0 were the null
# vector of that space):
return self != 0. # Uses the AffineScalarFunc.__ne__ function
########################################
## Logical operators: warning: the resulting value cannot always
## be differentiated.
# The boolean operations are not differentiable everywhere, but
# almost...
# (1) I can rely on the assumption that the user only has "small"
# errors on variables, as this is used in the calculation of the
# standard deviation (which performs linear approximations):
# (2) However, this assumption is not relevant for some
# operations, and does not have to hold, in some cases. This
# comes from the fact that logical operations (e.g. __eq__(x,y))
# are not differentiable for many usual cases. For instance, it
# is desirable to have x == x for x = n+/-e, whatever the size of e.
# Furthermore, n+/-e != n+/-e', if e != e', whatever the size of e or
# e'.
# (3) The result of logical operators does not have to be a
# function with derivatives, as these derivatives are either 0 or
# don't exist (i.e., the user should probably not rely on
# derivatives for his code).
# !! In Python 2.7+, it may be possible to use functools.total_ordering.
# __eq__ is used in "if data in [None, ()]", for instance. It is
# therefore important to be able to handle this case too, which is
# taken care of when force_aff_func_args(eq_on_aff_funcs)
# returns NotImplemented.
__eq__ = force_aff_func_args(eq_on_aff_funcs)
__ne__ = force_aff_func_args(ne_on_aff_funcs)
__gt__ = force_aff_func_args(gt_on_aff_funcs)
# __ge__ is not the opposite of __lt__ because these operators do
# not always yield a boolean (for instance, 0 <= numpy.arange(10)
# yields an array).
__ge__ = force_aff_func_args(ge_on_aff_funcs)
__lt__ = force_aff_func_args(lt_on_aff_funcs)
__le__ = force_aff_func_args(le_on_aff_funcs)
########################################
# Uncertainties handling:
def error_components(self):
"""
Individual components of the standard deviation of the affine
function (in absolute value), returned as a dictionary with
Variable objects as keys. The returned variables are the
independent variables that the affine function depends on.
This method assumes that the derivatives contained in the
object take scalar values (and are not a tuple, like what
math.frexp() returns, for instance).
"""
# Calculation of the variance:
error_components = {}
for (variable, derivative) in self.derivatives.items():
# print "TYPE", type(variable), type(derivative)
# Individual standard error due to variable:
# 0 is returned even for a NaN derivative (in this case no
# multiplication by the derivative is performed): an exact
# variable obviously leads to no uncertainty in the
# functions that depend on it.
if variable._std_dev == 0:
# !!! Shouldn't the errors always be floats, as a
# convention of this module?
error_components[variable] = 0
else:
error_components[variable] = abs(derivative*variable._std_dev)
return error_components
@property
def std_dev(self):
"""
Standard deviation of the affine function.
This method assumes that the function returns scalar results.
This returned standard deviation depends on the current
standard deviations [std_dev] of the variables (Variable
objects) involved.
"""
#! It would be possible to not allow the user to update the
#std dev of Variable objects, in which case AffineScalarFunc
#objects could have a pre-calculated or, better, cached
#std_dev value (in fact, many intermediate AffineScalarFunc do
#not need to have their std_dev calculated: only the final
#AffineScalarFunc returned to the user does).
return CallableStdDev(sqrt(sum(
delta**2 for delta in self.error_components().values())))
# Abbreviation (for formulas, etc.):
s = std_dev
def __repr__(self):
# Not putting spaces around "+/-" helps with arrays of
# Variable, as each value with an uncertainty is a
# block of signs (otherwise, the standard deviation can be
# mistaken for another element of the array).
std_dev = self.std_dev # Optimization, since std_dev is calculated
# A zero standard deviation is printed because otherwise,
# ufloat_fromstr() does not correctly parse back the value
# ("1.23" is interpreted as "1.23(1)"):
if std_dev:
std_dev_str = repr(std_dev)
else:
std_dev_str = '0'
return "%r+/-%s" % (self.nominal_value, std_dev_str)
def __str__(self):
# An empty format string and str() usually return the same
# string
# (http://docs.python.org/2/library/string.html#format-specification-mini-language):
return self.format('')
def __format__(self, format_spec):
'''
Formats a number with uncertainty.
The format specification are the same as for format() for
floats, as defined for Python 2.6+ (restricted to what the %
operator accepts, if using an earlier version of Python),
except that the n presentation type is not supported. In
particular, the usual precision, alignment, sign flag,
etc. can be used. The behavior of the various presentation
types (e, f, g, none, etc.) is similar. Moreover, the format
is extended: the number of digits of the uncertainty can be
controlled, as is the way the uncertainty is indicated (with
+/- or with the short-hand notation 3.14(1), in LaTeX or with
a simple text string,...).
Beyond the use of options at the end of the format
specification, the main difference with floats is that a "u"
just before the presentation type (f, e, g, none, etc.)
activates the "uncertainty control" mode (e.g.: ".6u"). This
mode is also activated when not using any explicit precision
(e.g.: "g", "10f", "+010,e" format specifications). If the
uncertainty does not have a meaningful number of significant
digits (0 and NaN uncertainties), this mode is automatically
deactivated.
The nominal value and the uncertainty always use the same
precision. This implies trailing zeros, in general, even with
the g format type (contrary to the float case). However, when
the number of significant digits of the uncertainty is not
defined (zero or NaN uncertainty), it has no precision, so
there is no matching. In this case, the original format
specification is used for the nominal value (any "u" is
ignored).
Any precision (".p", where p is a number) is interpreted (if
meaningful), in the uncertainty control mode, as indicating
the number p of significant digits of the displayed
uncertainty. Example: .1uf will return a string with one
significant digit in the uncertainty (and no exponent).
If no precision is given, the rounding rules from the
Particle Data Group are used, if possible
(http://pdg.lbl.gov/2010/reviews/rpp2010-rev-rpp-intro.pdf). For
example, the "f" format specification generally does not use
the default 6 digits after the decimal point, but applies the
PDG rules.
A common exponent is used if an exponent is needed for the
larger of the nominal value (in absolute value) and the
standard deviation, unless this would result in a zero
uncertainty being represented as 0e... or a NaN uncertainty as
NaNe.... Thanks to this common exponent, the quantity that
best describes the associated probability distribution has a
mantissa in the usual 1-10 range. The common exponent is
factored (as in "(1.2+/-0.1)e-5"). unless the format
specification contains an explicit width (" 1.2e-5+/- 0.1e-5")
(this allows numbers to be in a single column, when printing
numbers over many lines). Specifying a minimum width of 1 is a
way of forcing any common exponent to not be factored out.
The fill, align, zero and width parameters of the format
specification are applied individually to each of the nominal
value and standard deviation or, if the shorthand notation is
used, globally.
The sign parameter of the format specification is only applied
to the nominal value (since the standard deviation is
positive).
In the case of a non-LaTeX output, the returned string can
normally be parsed back with ufloat_fromstr(). This however
excludes cases where numbers use the "," thousands separator,
for example.
Options can be added, at the end of the format
specification. Multiple options can be specified:
- When "P" is present, the pretty-printing mode is activated: "±"
separates the nominal value from the standard deviation, exponents
use superscript characters, etc.
- When "S" is present (like in .1uS), the short-hand notation 1.234(5)
is used, indicating an uncertainty on the last digits; if the digits
of the uncertainty straddle the decimal point, it uses a fixed-point
notation, like in 12.3(4.5).
- When "L" is present, the output is formatted with LaTeX.
- "p" ensures that there are parentheses around the …±… part (no
parentheses are added if some are already present, for instance
because of an exponent or of a trailing % sign, etc.). This produces
outputs like (1.0±0.2) or (1.0±0.2)e7, which can be useful for
removing any ambiguity if physical units are added after the printed
number.
An uncertainty which is exactly zero is represented as the
integer 0 (i.e. with no decimal point).
The "%" format type forces the percent sign to be at the end
of the returned string (it is not attached to each of the
nominal value and the standard deviation).
Some details of the formatting can be customized as described
in format_num().
'''
# Convention on limits "between" digits: 0 = exactly at the
# decimal point, -1 = after the first decimal, 1 = before the
# units digit, etc.
# Convention on digits: 0 is units (10**0), 1 is tens, -1 is
# tenths, etc.
# This method does the format specification parsing, and
# calculates the various parts of the displayed value
# (mantissas, exponent, position of the last digit). The
# formatting itself is delegated to format_num().
########################################
# Format specification parsing:
match = re.match(r'''
(?P<fill>[^{}]??)(?P<align>[<>=^]?) # fill cannot be { or }
(?P<sign>[-+ ]?)
(?P<zero>0?)
(?P<width>\d*)
(?P<comma>,?)
(?:\.(?P<prec>\d+))?
(?P<uncert_prec>u?) # Precision for the uncertainty?
# The type can be omitted. Options must not go here:
(?P<type>[eEfFgG%]??) # n not supported
(?P<options>[PSLp]*) # uncertainties-specific flags
$''',
format_spec,
re.VERBOSE)
# Does the format specification look correct?
if not match:
raise ValueError(
'Format specification %r cannot be used with object of type'
' %r. Note that uncertainties-specific flags must be put at'
' the end of the format string.'
# Sub-classes handled:
% (format_spec, self.__class__.__name__))
# Effective format presentation type: f, e, g, etc., or None,
# like in
# https://docs.python.org/3.4/library/string.html#format-specification-mini-language. Contrary
# to what is written in the documentation, it is not true that
# None is "the same as 'g'": "{}".format() and "{:g}" do not
# give the same result, on 31415000000.0. None is thus kept as
# is instead of being replaced by "g".
pres_type = match.group('type') or None
# Shortcut:
fmt_prec = match.group('prec') # Can be None
########################################
# Since the '%' (percentage) format specification can change
# the value to be displayed, this value must first be
# calculated. Calculating the standard deviation is also an
# optimization: the standard deviation is generally
# calculated: it is calculated only once, here:
nom_val = self.nominal_value
std_dev = self.std_dev
# 'options' is the options that must be given to format_num():
options = set(match.group('options'))
########################################
# The '%' format is treated internally as a display option: it
# should not be applied individually to each part:
if pres_type == '%':
# Because '%' does 0.0055*100, the value
# 0.5499999999999999 is obtained, which rounds to 0.5. The
# original rounded value is 0.006. The same behavior is
# found in Python 2.7: '{:.1%}'.format(0.0055) is '0.5%'.
# If a different behavior is needed, a solution to this
# problem would be to do the rounding before the
# multiplication.
std_dev *= 100
nom_val *= 100
pres_type = 'f'
options.add('%')
# At this point, pres_type is in eEfFgG or None (not %).
########################################
# Non-real values (nominal value or standard deviation) must
# be handled in a specific way:
real_values = [value for value in [abs(nom_val), std_dev]
if not isinfinite(value)]
# Calculation of digits_limit, which defines the precision of
# the nominal value and of the standard deviation (it can be
# None when it does not matter, like for NaN±NaN):
# Reference value for the calculation of a possible exponent,
# if needed:
if pres_type in (None, 'e', 'E', 'g', 'G'):
# Reference value for the exponent: the largest value
# defines what the exponent will be (another convention
# could have been chosen, like using the exponent of the
# nominal value, irrespective of the standard deviation):
try:
exp_ref_value = max(real_values)
except ValueError: # No non-NaN value: NaN±NaN…
# No meaningful common exponent can be obtained:
pass
## else:
## print "EXP_REF_VAL", exp_ref_value
# Should the precision be interpreted like for a float, or
# should the number of significant digits on the uncertainty
# be controlled?
if ((
# Default behavior: number of significant digits on the
# uncertainty controlled (if useful, i.e. only in
# situations where the nominal value and the standard
# error digits are truncated at the same place):
(not fmt_prec and len(real_values)==2)
or match.group('uncert_prec')) # Explicit control
# The number of significant digits of the uncertainty must
# be meaningful, otherwise the position of the significant
# digits of the uncertainty does not have a clear
# meaning. This gives us the *effective* uncertainty
# control mode:
and std_dev
and not isinfinite(std_dev)):
# The number of significant digits on the uncertainty is
# controlled.
# The limit digits_limit on the digits of nom_val and std_dev
# to be displayed is calculated. If the exponent notation is
# used, this limit is generally different from the finally
# displayed limit (e.g. 314.15+/-0.01 has digits_limit=-2, but
# will be displayed with an exponent as (3.1415+/-0.0001)e+02,
# which corresponds to 4 decimals after the decimal point, not
# 2).
# Number of significant digits to use:
if fmt_prec:
num_signif_d = int(fmt_prec) # Can only be non-negative
if not num_signif_d:
raise ValueError("The number of significant digits"
" on the uncertainty should be positive")
else:
(num_signif_d, std_dev) = PDG_precision(std_dev)
digits_limit = signif_dgt_to_limit(std_dev, num_signif_d)
else:
# No control of the number of significant digits on the
# uncertainty.
## print "PRECISION NOT BASED ON UNCERTAINTY"
# The precision has the same meaning as for floats (it is
# not the uncertainty that defines the number of digits).
# The usual default precision is used (this is useful for
# 3.141592±NaN with an "f" format specification, for
# example):
#
# prec is the precision for the main parts of the final
# format (in the sense of float formatting):
#
# https://docs.python.org/3.4/library/string.html#format-specification-mini-language
if fmt_prec:
prec = int(fmt_prec)
elif pres_type is None:
prec = 12
else:
prec = 6
if pres_type in ('f', 'F'):
digits_limit = -prec
else: # Format type in None, eEgG
# We first calculate the number of significant digits
# to be displayed (if possible):
if pres_type in ('e', 'E'):
# The precision is the number of significant
# digits required - 1 (because there is a single
# digit before the decimal point, which is not
# included in the definition of the precision with
# the e/E format type):
num_signif_digits = prec+1
else: # Presentation type in None, g, G
# Effective format specification precision: the rule
# of
# http://docs.python.org/2.7/library/string.html#format-specification-mini-language
# is used:
# The final number of significant digits to be
# displayed is not necessarily obvious: trailing
# zeros are removed (with the gG presentation
# type), so num_signif_digits is the number of
# significant digits if trailing zeros were not
# removed. This quantity is relevant for the
# rounding implied by the exponent test of the g/G
# format:
# 0 is interpreted like 1 (as with floats with a
# gG presentation type):
num_signif_digits = prec or 1
# The number of significant digits is important for
# example for determining the exponent:
## print "NUM_SIGNIF_DIGITS", num_signif_digits
digits_limit = (
signif_dgt_to_limit(exp_ref_value, num_signif_digits)
if real_values
else None)
## print "DIGITS_LIMIT", digits_limit
#######################################
# Common exponent notation: should it be used? use_exp is set
# accordingly. If a common exponent should be used (use_exp is
# True), 'common_exp' is set to the exponent that should be
# used.
if pres_type in ('f', 'F'):
use_exp = False
elif pres_type in ('e', 'E'):
if not real_values:
use_exp = False
else:
use_exp = True
# !! This calculation might have been already done,
# for instance when using the .0e format:
# signif_dgt_to_limit() was called before, which
# prompted a similar calculation:
common_exp = first_digit(round(exp_ref_value, -digits_limit))
else: # None, g, G
# The rules from
# https://docs.python.org/3.4/library/string.html#format-specification-mini-language
# are applied.
# Python's native formatting (whose result could be parsed
# in order to determine whether a common exponent should
# be used) is not used because there is shared information
# between the nominal value and the standard error (same
# last digit, common exponent) and extracting this
# information from Python would entail parsing its
# formatted string, which is in principle inefficient
# (internally, Python performs calculations that yield a
# string, and the string would be parsed back into
# separate parts and numbers, which is in principle
# unnecessary).
# Should the scientific notation be used? The same rule as
# for floats is used ("-4 <= exponent of rounded value <
# p"), on the nominal value.
if not real_values:
use_exp = False
else:
# Common exponent *if* used:
common_exp = first_digit(round(exp_ref_value, -digits_limit))
# print "COMMON EXP TEST VALUE", common_exp
# print "LIMIT EXP", common_exp-digits_limit+1
# print "WITH digits_limit", digits_limit
# The number of significant digits of the reference value
# rounded at digits_limit is exponent-digits_limit+1:
if -4 <= common_exp < common_exp-digits_limit+1:
use_exp = False
else:
use_exp = True
########################################
# Calculation of signif_limit (position of the significant
# digits limit in the final fixed point representations; this
# is either a non-positive number, or None), of
# nom_val_mantissa ("mantissa" for the nominal value,
# i.e. value possibly corrected for a factorized exponent),
# and std_dev_mantissa (similarly for the standard
# deviation). common_exp is also set to None if no common
# exponent should be used.
if use_exp:
# Not 10.**(-common_exp), for limit values of common_exp:
factor = 10.**common_exp
nom_val_mantissa = nom_val/factor
std_dev_mantissa = std_dev/factor
# Limit for the last digit of the mantissas:
signif_limit = digits_limit - common_exp
else: # No common exponent
common_exp = None
nom_val_mantissa = nom_val
std_dev_mantissa = std_dev
signif_limit = digits_limit
## print "SIGNIF_LIMIT", signif_limit
########################################
# Format of the main (i.e. with no exponent) parts (the None
# presentation type is similar to the g format type):
main_pres_type = 'fF'[(pres_type or 'g').isupper()]
# The precision of the main parts must be adjusted so as
# to take into account the special role of the decimal
# point:
if signif_limit is not None: # If signif_limit is pertinent
# The decimal point location is always included in the
# printed digits (e.g., printing 3456 with only 2
# significant digits requires to print at least four
# digits, like in 3456 or 3500).
#
# The max() is important for example for
# 1234567.89123+/-12345.678 with the f format: in this
# case, signif_limit is +3 (2 significant digits necessary
# for the error, as per the PDG rules), but the (Python
# float formatting) precision to be used for the main
# parts is 0 (all digits must be shown).
#
# The 1 for the None pres_type represents "at least one
# digit past the decimal point" of Python
# (https://docs.python.org/3.4/library/string.html#format-specification-mini-language). This
# is only applied for null uncertainties.
prec = max(-signif_limit,
1 if pres_type is None and not std_dev
else 0)
## print "PREC", prec
########################################
# print (
# "FORMAT_NUM parameters: nom_val_mantissa={},"
# " std_dev_mantissa={}, common_exp={},"
# " match.groupdict()={}, prec={}, main_pres_type={},"
# " options={}".format(
# nom_val_mantissa, std_dev_mantissa, common_exp,
# match.groupdict(),
# prec,
# main_pres_type,
# options))
# Final formatting:
return format_num(nom_val_mantissa, std_dev_mantissa, common_exp,
match.groupdict(),
prec=prec,
main_pres_type=main_pres_type,
options=options)
# Alternate name for __format__, for use with Python < 2.6 (and
# other Python versions if the user so chooses: this helps moving
# code from Python 2.6 to more recent versions):
@set_doc("""
Return the same result as self.__format__(format_spec), or
equivalently as the format(self, format_spec) of Python 2.6+.
This method is meant to be used for formatting numbers with
uncertainties in Python < 2.6, with '... %s ...' %
num.format('.2e').
""")
def format(*args, **kwargs):
return args[0].__format__(*args[1:], **kwargs)
def std_score(self, value):
"""
Return 'value' - nominal value, in units of the standard
deviation.
Raises a ValueError exception if the standard deviation is zero.
"""
try:
# The ._nominal_value is a float: there is no integer division,
# here:
return (value - self._nominal_value) / self.std_dev
except ZeroDivisionError:
raise ValueError("The standard deviation is zero:"
" undefined result")
def __deepcopy__(self, memo):
"""
Hook for the standard copy module.
The returned AffineScalarFunc is a completely fresh copy,
which is fully independent of any variable defined so far.
New variables are specially created for the returned
AffineScalarFunc object.
"""
return AffineScalarFunc(self._nominal_value,
copy.deepcopy(self._linear_part))
def __getstate__(self):
"""
Hook for the pickle module.
The slot attributes of the parent classes are returned, as
well as those of the __dict__ attribute of the object (if
any).
"""
# In general (case where this class is subclassed), data
# attribute are stored in two places: possibly in __dict_, and
# in slots. Data from both locations is returned by this
# method.
all_attrs = {}
# Support for subclasses that do not use __slots__ (except
# through inheritance): instances have a __dict__
# attribute. The keys in this __dict__ are shadowed by the
# slot attribute names (reference:
# http://stackoverflow.com/questions/15139067/attribute-access-in-python-first-slots-then-dict/15139208#15139208).
# The method below not only preserves this behavior, but also
# saves the full contents of __dict__. This is robust:
# unpickling gives back the original __dict__ even if __dict__
# contains keys that are shadowed by slot names:
try:
all_attrs['__dict__'] = self.__dict__
except AttributeError:
pass
# All the slot attributes are gathered.
# Classes that do not define __slots__ have the __slots__ of
# one of their parents (the first parent with their own
# __slots__ in MRO). This is why the slot names are first
# gathered (with repetitions removed, in general), and their
# values obtained later.
all_slots = set()
for cls in type(self).mro():
# In the diamond inheritance pattern, some parent classes
# may not have __slots__:
slot_names = getattr(cls, '__slots__', ())
# Slot names can be given in various forms (string,
# sequence, iterable):
if isinstance(slot_names, basestring):
all_slots.add(slot_names) # Single name
else:
all_slots.update(slot_names)
# The slot values are stored:
for name in all_slots:
try:
# !! It might happen that '__dict__' is itself a slot
# name. In this case, its value is saved
# again. Alternatively, the loop could be done on
# all_slots - {'__dict__'}:
all_attrs[name] = getattr(self, name)
except AttributeError:
pass # Undefined slot attribute
return all_attrs
def __setstate__(self, data_dict):
"""
Hook for the pickle module.
"""
for (name, value) in data_dict.items():
# Contrary to the default __setstate__(), this does not
# necessarily save to the instance dictionary (because the
# instance might contain slots):
setattr(self, name, value)
|
(nominal_value, linear_part)
|
61,702 |
uncertainties.core
|
f_with_affine_output
|
Version of __abs__(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
abs(self)
|
def wrap(f, derivatives_args=[], derivatives_kwargs={}):
"""
Wraps a function f into a function that also accepts numbers with
uncertainties (UFloat objects); the wrapped function returns the
value of f with the correct uncertainty and correlations. The
wrapped function is intended to be used as a drop-in replacement
for the original function: they can be called in the exact same
way, the only difference being that numbers with uncertainties can
be given to the wrapped function where f accepts float arguments.
Doing so may be necessary when function f cannot be expressed
analytically (with uncertainties-compatible operators and
functions like +, *, umath.sin(), etc.).
f must return a float-like (i.e. a float, an int, etc., not a
list, etc.), unless when called with no number with
uncertainty. This is because the wrapped function generally
returns numbers with uncertainties: they represent a probability
distribution over the real numbers.
If the wrapped function is called with no argument that has an
uncertainty, the value of f is returned.
Parameters: the derivatives_* parameters can be used for defining
some of the partial derivatives of f. All the (non-None)
derivatives must have the same signature as f.
derivatives_args --
Iterable that, when iterated over, returns either derivatives
(functions) or None. derivatives_args can in particular be a
simple sequence (list or tuple) that gives the derivatives of
the first positional parameters of f.
Each function must be the partial derivative of f with respect
to the corresponding positional parameters. These functions
take the same arguments as f.
The positional parameters of a function are usually
positional-or-keyword parameters like in the call func(a,
b=None). However, they also include var-positional parameters
given through the func(a, b, *args) *args syntax. In the last
example, derivatives_args can be an iterable that returns the
derivative with respect to a, b and then to each optional
argument in args.
A value of None (instead of a function) obtained when
iterating over derivatives_args is automatically replaced by
the relevant numerical derivative. This derivative is not used
if the corresponding argument is not a number with
uncertainty. A None value can therefore be used for non-scalar
arguments of f (like string arguments).
If the derivatives_args iterable yields fewer derivatives than
needed, wrap() automatically sets the remaining unspecified
derivatives to None (i.e. to the automatic numerical
calculation of derivatives).
An indefinite number of derivatives can be specified by having
derivatives_args be an infinite iterator; this can for
instance be used for specifying the derivatives of functions
with a undefined number of argument (like sum(), whose partial
derivatives all return 1).
derivatives_kwargs --
Dictionary that maps keyword parameters to their derivatives,
or None (as in derivatives_args).
Keyword parameters are defined as being those of kwargs when f
has a signature of the form f(..., **kwargs). In Python 3,
these keyword parameters also include keyword-only parameters.
Non-mapped keyword parameters are replaced automatically by
None: the wrapped function will use, if necessary, numerical
differentiation for these parameters (as with
derivatives_args).
Note that this dictionary only maps keyword *parameters* from
the *signature* of f. The way the wrapped function is called
is immaterial: for example, if f has signature f(a, b=None),
then derivatives_kwargs should be the empty dictionary, even
if the wrapped f can be called a wrapped_f(a=123, b=42).
Example (for illustration purposes only, as
uncertainties.umath.sin() runs faster than the examples that
follow): 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.
Numerically calculated derivatives are meaningless when the
function is not differentiable (e.g., math.hypot(x, y) in (x, y) =
(0, 0), and sqrt(x) in x = 0). The corresponding uncertainties are
either meaningless (case of hypot) or raise an exception when
calculated (case of sqrt). In such cases, it is recommended (but
not mandatory) to supply instead a derivative function that
returns NaN where the function is not differentiable. This
function can still numerically calculate the derivative where
defined, for instance by using the
uncertainties.core.partial_derivative() function.
The correctness of the supplied analytical derivatives an be
tested by setting them to None instead and comparing the
analytical and the numerical differentiation results.
Note on efficiency: the wrapped function assumes that f cannot
accept numbers with uncertainties as arguments. If f actually does
handle some arguments even when they have an uncertainty, the
wrapped function ignores this fact, which might lead to a
performance hit: wrapping a function that actually accepts numbers
with uncertainty is likely to make it slower.
"""
derivatives_args_index = IndexableIter(
# Automatic addition of numerical derivatives in case the
# supplied derivatives_args is shorter than the number of
# arguments in *args:
itertools.chain(derivatives_args, itertools.repeat(None)))
# Derivatives for keyword arguments (includes var-keyword
# parameters **kwargs, but also var-or-keyword parameters, and
# keyword-only parameters (Python 3):
derivatives_all_kwargs = {}
for (name, derivative) in derivatives_kwargs.items():
# Optimization: None keyword-argument derivatives are converted
# right away to derivatives (instead of doing this every time a
# None derivative is encountered when calculating derivatives):
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# When the wrapped function is called with keyword arguments that
# map to positional-or-keyword parameters, their derivative is
# looked for in derivatives_all_kwargs. We define these
# additional derivatives:
try:
argspec = getargspec(f)
except TypeError:
# Some functions do not provide meta-data about their
# arguments (see PEP 362). One cannot use keyword arguments
# for positional-or-keyword parameters with them: nothing has
# to be done:
pass
else:
# With Python 3, there is no need to handle keyword-only
# arguments (and therefore to use inspect.getfullargspec())
# because they are already handled by derivatives_kwargs.
for (index, name) in enumerate(argspec.args):
# The following test handles the case of
# positional-or-keyword parameter for which automatic
# numerical differentiation is used: when the wrapped
# function is called with a keyword argument for this
# parameter, the numerical derivative must be calculated
# with respect to the parameter name. In the other case,
# where the wrapped function is called with a positional
# argument, the derivative with respect to its index must
# be used:
derivative = derivatives_args_index[index]
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# Optimization: None derivatives for the positional arguments are
# converted to the corresponding numerical differentiation
# function (instead of doing this over and over later every time a
# None derivative is found):
none_converter = lambda index: partial_derivative(f, index)
for (index, derivative) in enumerate(
derivatives_args_index.returned_elements):
if derivative is None:
derivatives_args_index.returned_elements[index] = (
none_converter(index))
# Future None values are also automatically converted:
derivatives_args_index.none_converter = none_converter
## Wrapped function:
#! Setting the doc string after "def f_with...()" does not
# seem to work. We define it explicitly:
@set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))
def f_with_affine_output(*args, **kwargs):
########################################
# The involved random variables must first be gathered, so
# that they can be independently updated.
# The arguments that contain an uncertainty (AffineScalarFunc
# objects) are gathered, as positions or names; they will be
# replaced by their nominal value in order to calculate
# the necessary derivatives of f.
pos_w_uncert = [index for (index, value) in enumerate(args)
if isinstance(value, AffineScalarFunc)]
names_w_uncert = [key for (key, value) in kwargs.items()
if isinstance(value, AffineScalarFunc)]
########################################
# Value of f() at the nominal value of the arguments with
# uncertainty:
# The usual behavior of f() is kept, if no number with
# uncertainty is provided:
if (not pos_w_uncert) and (not names_w_uncert):
return f(*args, **kwargs)
### Nominal values of the (scalar) arguments:
# !! Possible optimization: If pos_w_uncert is empty, there
# is actually no need to create a mutable version of args and
# one could do args_values = args. However, the wrapped
# function is typically called with numbers with uncertainties
# as positional arguments (i.e., pos_w_uncert is not emtpy),
# so this "optimization" is not implemented here.
## Positional arguments:
args_values = list(args) # Now mutable: modified below
# Arguments with an uncertainty are converted to their nominal
# value:
for index in pos_w_uncert:
args_values[index] = args[index].nominal_value
## Keyword arguments:
# For efficiency reasons, kwargs is not copied. Instead, its
# values with uncertainty are modified:
# The original values with uncertainties are needed: they are
# saved in the following dictionary (which only contains
# values with uncertainty):
kwargs_uncert_values = {}
for name in names_w_uncert:
value_with_uncert = kwargs[name]
# Saving for future use:
kwargs_uncert_values[name] = value_with_uncert
# The original dictionary is modified (for efficiency reasons):
kwargs[name] = value_with_uncert.nominal_value
f_nominal_value = f(*args_values, **kwargs)
# If the value is not a float, then this code cannot provide
# the result, as it returns a UFloat, which represents a
# random real variable. This happens for instance when
# ufloat()*numpy.array() is calculated: the
# AffineScalarFunc.__mul__ operator, obtained through wrap(),
# returns a NumPy array, not a float:
if not isinstance(f_nominal_value, FLOAT_LIKE_TYPES):
return NotImplemented
########################################
# Calculation of the linear part of the function value,
# defined by (coefficient, argument) pairs, where 'argument'
# is an AffineScalarFunc (for all AffineScalarFunc found as
# argument of f):
linear_part = []
for pos in pos_w_uncert:
linear_part.append((
# Coefficient:
derivatives_args_index[pos](*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
args[pos]._linear_part))
for name in names_w_uncert:
# Optimization: caching of the automatic numerical
# derivatives for keyword arguments that are
# discovered. This gives a speedup when the original
# function is called repeatedly with the same keyword
# arguments:
derivative = derivatives_all_kwargs.setdefault(
name,
# Derivative never needed before:
partial_derivative(f, name))
linear_part.append((
# Coefficient:
derivative(*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
kwargs_uncert_values[name]._linear_part))
# The function now returns the necessary linear approximation
# to the function:
return AffineScalarFunc(
f_nominal_value, LinearCombination(linear_part))
f_with_affine_output = set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))(f_with_affine_output)
# It is easier to work with f_with_affine_output, which represents
# a wrapped version of 'f', when it bears the same name as 'f':
# ! __name__ is read-only, in Python 2.3:
f_with_affine_output.name = f.__name__
return f_with_affine_output
|
(*args, **kwargs)
|
61,703 |
uncertainties.core
|
f_with_affine_output
|
Version of __add__(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
Return self+value.
|
def wrap(f, derivatives_args=[], derivatives_kwargs={}):
"""
Wraps a function f into a function that also accepts numbers with
uncertainties (UFloat objects); the wrapped function returns the
value of f with the correct uncertainty and correlations. The
wrapped function is intended to be used as a drop-in replacement
for the original function: they can be called in the exact same
way, the only difference being that numbers with uncertainties can
be given to the wrapped function where f accepts float arguments.
Doing so may be necessary when function f cannot be expressed
analytically (with uncertainties-compatible operators and
functions like +, *, umath.sin(), etc.).
f must return a float-like (i.e. a float, an int, etc., not a
list, etc.), unless when called with no number with
uncertainty. This is because the wrapped function generally
returns numbers with uncertainties: they represent a probability
distribution over the real numbers.
If the wrapped function is called with no argument that has an
uncertainty, the value of f is returned.
Parameters: the derivatives_* parameters can be used for defining
some of the partial derivatives of f. All the (non-None)
derivatives must have the same signature as f.
derivatives_args --
Iterable that, when iterated over, returns either derivatives
(functions) or None. derivatives_args can in particular be a
simple sequence (list or tuple) that gives the derivatives of
the first positional parameters of f.
Each function must be the partial derivative of f with respect
to the corresponding positional parameters. These functions
take the same arguments as f.
The positional parameters of a function are usually
positional-or-keyword parameters like in the call func(a,
b=None). However, they also include var-positional parameters
given through the func(a, b, *args) *args syntax. In the last
example, derivatives_args can be an iterable that returns the
derivative with respect to a, b and then to each optional
argument in args.
A value of None (instead of a function) obtained when
iterating over derivatives_args is automatically replaced by
the relevant numerical derivative. This derivative is not used
if the corresponding argument is not a number with
uncertainty. A None value can therefore be used for non-scalar
arguments of f (like string arguments).
If the derivatives_args iterable yields fewer derivatives than
needed, wrap() automatically sets the remaining unspecified
derivatives to None (i.e. to the automatic numerical
calculation of derivatives).
An indefinite number of derivatives can be specified by having
derivatives_args be an infinite iterator; this can for
instance be used for specifying the derivatives of functions
with a undefined number of argument (like sum(), whose partial
derivatives all return 1).
derivatives_kwargs --
Dictionary that maps keyword parameters to their derivatives,
or None (as in derivatives_args).
Keyword parameters are defined as being those of kwargs when f
has a signature of the form f(..., **kwargs). In Python 3,
these keyword parameters also include keyword-only parameters.
Non-mapped keyword parameters are replaced automatically by
None: the wrapped function will use, if necessary, numerical
differentiation for these parameters (as with
derivatives_args).
Note that this dictionary only maps keyword *parameters* from
the *signature* of f. The way the wrapped function is called
is immaterial: for example, if f has signature f(a, b=None),
then derivatives_kwargs should be the empty dictionary, even
if the wrapped f can be called a wrapped_f(a=123, b=42).
Example (for illustration purposes only, as
uncertainties.umath.sin() runs faster than the examples that
follow): 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.
Numerically calculated derivatives are meaningless when the
function is not differentiable (e.g., math.hypot(x, y) in (x, y) =
(0, 0), and sqrt(x) in x = 0). The corresponding uncertainties are
either meaningless (case of hypot) or raise an exception when
calculated (case of sqrt). In such cases, it is recommended (but
not mandatory) to supply instead a derivative function that
returns NaN where the function is not differentiable. This
function can still numerically calculate the derivative where
defined, for instance by using the
uncertainties.core.partial_derivative() function.
The correctness of the supplied analytical derivatives an be
tested by setting them to None instead and comparing the
analytical and the numerical differentiation results.
Note on efficiency: the wrapped function assumes that f cannot
accept numbers with uncertainties as arguments. If f actually does
handle some arguments even when they have an uncertainty, the
wrapped function ignores this fact, which might lead to a
performance hit: wrapping a function that actually accepts numbers
with uncertainty is likely to make it slower.
"""
derivatives_args_index = IndexableIter(
# Automatic addition of numerical derivatives in case the
# supplied derivatives_args is shorter than the number of
# arguments in *args:
itertools.chain(derivatives_args, itertools.repeat(None)))
# Derivatives for keyword arguments (includes var-keyword
# parameters **kwargs, but also var-or-keyword parameters, and
# keyword-only parameters (Python 3):
derivatives_all_kwargs = {}
for (name, derivative) in derivatives_kwargs.items():
# Optimization: None keyword-argument derivatives are converted
# right away to derivatives (instead of doing this every time a
# None derivative is encountered when calculating derivatives):
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# When the wrapped function is called with keyword arguments that
# map to positional-or-keyword parameters, their derivative is
# looked for in derivatives_all_kwargs. We define these
# additional derivatives:
try:
argspec = getargspec(f)
except TypeError:
# Some functions do not provide meta-data about their
# arguments (see PEP 362). One cannot use keyword arguments
# for positional-or-keyword parameters with them: nothing has
# to be done:
pass
else:
# With Python 3, there is no need to handle keyword-only
# arguments (and therefore to use inspect.getfullargspec())
# because they are already handled by derivatives_kwargs.
for (index, name) in enumerate(argspec.args):
# The following test handles the case of
# positional-or-keyword parameter for which automatic
# numerical differentiation is used: when the wrapped
# function is called with a keyword argument for this
# parameter, the numerical derivative must be calculated
# with respect to the parameter name. In the other case,
# where the wrapped function is called with a positional
# argument, the derivative with respect to its index must
# be used:
derivative = derivatives_args_index[index]
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# Optimization: None derivatives for the positional arguments are
# converted to the corresponding numerical differentiation
# function (instead of doing this over and over later every time a
# None derivative is found):
none_converter = lambda index: partial_derivative(f, index)
for (index, derivative) in enumerate(
derivatives_args_index.returned_elements):
if derivative is None:
derivatives_args_index.returned_elements[index] = (
none_converter(index))
# Future None values are also automatically converted:
derivatives_args_index.none_converter = none_converter
## Wrapped function:
#! Setting the doc string after "def f_with...()" does not
# seem to work. We define it explicitly:
@set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))
def f_with_affine_output(*args, **kwargs):
########################################
# The involved random variables must first be gathered, so
# that they can be independently updated.
# The arguments that contain an uncertainty (AffineScalarFunc
# objects) are gathered, as positions or names; they will be
# replaced by their nominal value in order to calculate
# the necessary derivatives of f.
pos_w_uncert = [index for (index, value) in enumerate(args)
if isinstance(value, AffineScalarFunc)]
names_w_uncert = [key for (key, value) in kwargs.items()
if isinstance(value, AffineScalarFunc)]
########################################
# Value of f() at the nominal value of the arguments with
# uncertainty:
# The usual behavior of f() is kept, if no number with
# uncertainty is provided:
if (not pos_w_uncert) and (not names_w_uncert):
return f(*args, **kwargs)
### Nominal values of the (scalar) arguments:
# !! Possible optimization: If pos_w_uncert is empty, there
# is actually no need to create a mutable version of args and
# one could do args_values = args. However, the wrapped
# function is typically called with numbers with uncertainties
# as positional arguments (i.e., pos_w_uncert is not emtpy),
# so this "optimization" is not implemented here.
## Positional arguments:
args_values = list(args) # Now mutable: modified below
# Arguments with an uncertainty are converted to their nominal
# value:
for index in pos_w_uncert:
args_values[index] = args[index].nominal_value
## Keyword arguments:
# For efficiency reasons, kwargs is not copied. Instead, its
# values with uncertainty are modified:
# The original values with uncertainties are needed: they are
# saved in the following dictionary (which only contains
# values with uncertainty):
kwargs_uncert_values = {}
for name in names_w_uncert:
value_with_uncert = kwargs[name]
# Saving for future use:
kwargs_uncert_values[name] = value_with_uncert
# The original dictionary is modified (for efficiency reasons):
kwargs[name] = value_with_uncert.nominal_value
f_nominal_value = f(*args_values, **kwargs)
# If the value is not a float, then this code cannot provide
# the result, as it returns a UFloat, which represents a
# random real variable. This happens for instance when
# ufloat()*numpy.array() is calculated: the
# AffineScalarFunc.__mul__ operator, obtained through wrap(),
# returns a NumPy array, not a float:
if not isinstance(f_nominal_value, FLOAT_LIKE_TYPES):
return NotImplemented
########################################
# Calculation of the linear part of the function value,
# defined by (coefficient, argument) pairs, where 'argument'
# is an AffineScalarFunc (for all AffineScalarFunc found as
# argument of f):
linear_part = []
for pos in pos_w_uncert:
linear_part.append((
# Coefficient:
derivatives_args_index[pos](*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
args[pos]._linear_part))
for name in names_w_uncert:
# Optimization: caching of the automatic numerical
# derivatives for keyword arguments that are
# discovered. This gives a speedup when the original
# function is called repeatedly with the same keyword
# arguments:
derivative = derivatives_all_kwargs.setdefault(
name,
# Derivative never needed before:
partial_derivative(f, name))
linear_part.append((
# Coefficient:
derivative(*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
kwargs_uncert_values[name]._linear_part))
# The function now returns the necessary linear approximation
# to the function:
return AffineScalarFunc(
f_nominal_value, LinearCombination(linear_part))
f_with_affine_output = set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))(f_with_affine_output)
# It is easier to work with f_with_affine_output, which represents
# a wrapped version of 'f', when it bears the same name as 'f':
# ! __name__ is read-only, in Python 2.3:
f_with_affine_output.name = f.__name__
return f_with_affine_output
|
(*args, **kwargs)
|
61,704 |
uncertainties.core
|
__bool__
|
Equivalent to self != 0.
|
def __bool__(self):
"""
Equivalent to self != 0.
"""
#! This might not be relevant for AffineScalarFunc objects
# that contain values in a linear space which does not convert
# the float 0 into the null vector (see the __eq__ function:
# __nonzero__ works fine if subtracting the 0 float from a
# vector of the linear space works as if 0 were the null
# vector of that space):
return self != 0. # Uses the AffineScalarFunc.__ne__ function
|
(self)
|
61,705 |
uncertainties.core
|
raise_error
| null |
def add_operators_to_AffineScalarFunc():
"""
Adds many operators (__add__, etc.) to the AffineScalarFunc class.
"""
########################################
#! Derivatives are set to return floats. For one thing,
# uncertainties generally involve floats, as they are based on
# small variations of the parameters. It is also better to
# protect the user from unexpected integer result that behave
# badly with the division.
## Operators that return a numerical value:
def _simple_add_deriv(x):
if x >= 0:
return 1.
else:
return -1.
# Single-argument operators that should be adapted from floats to
# AffineScalarFunc objects, associated to their derivative:
simple_numerical_operators_derivatives = {
'abs': _simple_add_deriv,
'neg': lambda x: -1.,
'pos': lambda x: 1.,
'trunc': lambda x: 0.
}
for (op, derivative) in (
iter(simple_numerical_operators_derivatives.items())):
attribute_name = "__%s__" % op
# float objects don't exactly have the same attributes between
# different versions of Python (for instance, __trunc__ was
# introduced with Python 2.6):
try:
setattr(AffineScalarFunc, attribute_name,
wrap(getattr(float, attribute_name), [derivative]))
except AttributeError:
# Version of Python where floats don't have attribute_name:
pass
else:
modified_operators.append(op)
########################################
# Final definition of the operators for AffineScalarFunc objects:
# Reversed versions (useful for float*AffineScalarFunc, for instance):
for (op, derivatives) in ops_with_reflection.items():
attribute_name = '__%s__' % op
# float objects don't exactly have the same attributes between
# different versions of Python (for instance, __div__ and
# __rdiv__ were removed, in Python 3):
# float objects don't exactly have the same attributes between
# different versions of Python (for instance, __trunc__ was
# introduced with Python 2.6):
try:
if op not in custom_ops:
func_to_wrap = getattr(float, attribute_name)
else:
func_to_wrap = custom_ops[op]
except AttributeError:
# Version of Python with floats that don't have attribute_name:
pass
else:
setattr(AffineScalarFunc, attribute_name,
wrap(func_to_wrap, derivatives))
modified_ops_with_reflection.append(op)
########################################
# Conversions to pure numbers are meaningless. Note that the
# behavior of float(1j) is similar.
for coercion_type in ('complex', 'int', 'long', 'float'):
def raise_error(self):
raise TypeError("can't convert an affine function (%s)"
' to %s; use x.nominal_value'
# In case AffineScalarFunc is sub-classed:
% (self.__class__, coercion_type))
setattr(AffineScalarFunc, '__%s__' % coercion_type, raise_error)
|
(self)
|
61,706 |
uncertainties.core
|
__deepcopy__
|
Hook for the standard copy module.
The returned AffineScalarFunc is a completely fresh copy,
which is fully independent of any variable defined so far.
New variables are specially created for the returned
AffineScalarFunc object.
|
def __deepcopy__(self, memo):
"""
Hook for the standard copy module.
The returned AffineScalarFunc is a completely fresh copy,
which is fully independent of any variable defined so far.
New variables are specially created for the returned
AffineScalarFunc object.
"""
return AffineScalarFunc(self._nominal_value,
copy.deepcopy(self._linear_part))
|
(self, memo)
|
61,707 |
uncertainties.core
|
op_on_upcast_args
| null |
def force_aff_func_args(func):
"""
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.
"""
def op_on_upcast_args(x, y):
"""
Return %s(self, to_affine_scalar(y)) if y can be upcast
through to_affine_scalar. Otherwise returns NotImplemented.
""" % func.__name__
try:
y_with_uncert = to_affine_scalar(y)
except NotUpcast:
# This module does not know how to handle the comparison:
# (example: y is a NumPy array, in which case the NumPy
# array will decide that func() should be applied
# element-wise between x and all the elements of y):
return NotImplemented
else:
return func(x, y_with_uncert)
return op_on_upcast_args
|
(x, y)
|
61,709 |
uncertainties.core
|
f_with_affine_output
|
Version of __floordiv__(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
Return self//value.
|
def wrap(f, derivatives_args=[], derivatives_kwargs={}):
"""
Wraps a function f into a function that also accepts numbers with
uncertainties (UFloat objects); the wrapped function returns the
value of f with the correct uncertainty and correlations. The
wrapped function is intended to be used as a drop-in replacement
for the original function: they can be called in the exact same
way, the only difference being that numbers with uncertainties can
be given to the wrapped function where f accepts float arguments.
Doing so may be necessary when function f cannot be expressed
analytically (with uncertainties-compatible operators and
functions like +, *, umath.sin(), etc.).
f must return a float-like (i.e. a float, an int, etc., not a
list, etc.), unless when called with no number with
uncertainty. This is because the wrapped function generally
returns numbers with uncertainties: they represent a probability
distribution over the real numbers.
If the wrapped function is called with no argument that has an
uncertainty, the value of f is returned.
Parameters: the derivatives_* parameters can be used for defining
some of the partial derivatives of f. All the (non-None)
derivatives must have the same signature as f.
derivatives_args --
Iterable that, when iterated over, returns either derivatives
(functions) or None. derivatives_args can in particular be a
simple sequence (list or tuple) that gives the derivatives of
the first positional parameters of f.
Each function must be the partial derivative of f with respect
to the corresponding positional parameters. These functions
take the same arguments as f.
The positional parameters of a function are usually
positional-or-keyword parameters like in the call func(a,
b=None). However, they also include var-positional parameters
given through the func(a, b, *args) *args syntax. In the last
example, derivatives_args can be an iterable that returns the
derivative with respect to a, b and then to each optional
argument in args.
A value of None (instead of a function) obtained when
iterating over derivatives_args is automatically replaced by
the relevant numerical derivative. This derivative is not used
if the corresponding argument is not a number with
uncertainty. A None value can therefore be used for non-scalar
arguments of f (like string arguments).
If the derivatives_args iterable yields fewer derivatives than
needed, wrap() automatically sets the remaining unspecified
derivatives to None (i.e. to the automatic numerical
calculation of derivatives).
An indefinite number of derivatives can be specified by having
derivatives_args be an infinite iterator; this can for
instance be used for specifying the derivatives of functions
with a undefined number of argument (like sum(), whose partial
derivatives all return 1).
derivatives_kwargs --
Dictionary that maps keyword parameters to their derivatives,
or None (as in derivatives_args).
Keyword parameters are defined as being those of kwargs when f
has a signature of the form f(..., **kwargs). In Python 3,
these keyword parameters also include keyword-only parameters.
Non-mapped keyword parameters are replaced automatically by
None: the wrapped function will use, if necessary, numerical
differentiation for these parameters (as with
derivatives_args).
Note that this dictionary only maps keyword *parameters* from
the *signature* of f. The way the wrapped function is called
is immaterial: for example, if f has signature f(a, b=None),
then derivatives_kwargs should be the empty dictionary, even
if the wrapped f can be called a wrapped_f(a=123, b=42).
Example (for illustration purposes only, as
uncertainties.umath.sin() runs faster than the examples that
follow): 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.
Numerically calculated derivatives are meaningless when the
function is not differentiable (e.g., math.hypot(x, y) in (x, y) =
(0, 0), and sqrt(x) in x = 0). The corresponding uncertainties are
either meaningless (case of hypot) or raise an exception when
calculated (case of sqrt). In such cases, it is recommended (but
not mandatory) to supply instead a derivative function that
returns NaN where the function is not differentiable. This
function can still numerically calculate the derivative where
defined, for instance by using the
uncertainties.core.partial_derivative() function.
The correctness of the supplied analytical derivatives an be
tested by setting them to None instead and comparing the
analytical and the numerical differentiation results.
Note on efficiency: the wrapped function assumes that f cannot
accept numbers with uncertainties as arguments. If f actually does
handle some arguments even when they have an uncertainty, the
wrapped function ignores this fact, which might lead to a
performance hit: wrapping a function that actually accepts numbers
with uncertainty is likely to make it slower.
"""
derivatives_args_index = IndexableIter(
# Automatic addition of numerical derivatives in case the
# supplied derivatives_args is shorter than the number of
# arguments in *args:
itertools.chain(derivatives_args, itertools.repeat(None)))
# Derivatives for keyword arguments (includes var-keyword
# parameters **kwargs, but also var-or-keyword parameters, and
# keyword-only parameters (Python 3):
derivatives_all_kwargs = {}
for (name, derivative) in derivatives_kwargs.items():
# Optimization: None keyword-argument derivatives are converted
# right away to derivatives (instead of doing this every time a
# None derivative is encountered when calculating derivatives):
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# When the wrapped function is called with keyword arguments that
# map to positional-or-keyword parameters, their derivative is
# looked for in derivatives_all_kwargs. We define these
# additional derivatives:
try:
argspec = getargspec(f)
except TypeError:
# Some functions do not provide meta-data about their
# arguments (see PEP 362). One cannot use keyword arguments
# for positional-or-keyword parameters with them: nothing has
# to be done:
pass
else:
# With Python 3, there is no need to handle keyword-only
# arguments (and therefore to use inspect.getfullargspec())
# because they are already handled by derivatives_kwargs.
for (index, name) in enumerate(argspec.args):
# The following test handles the case of
# positional-or-keyword parameter for which automatic
# numerical differentiation is used: when the wrapped
# function is called with a keyword argument for this
# parameter, the numerical derivative must be calculated
# with respect to the parameter name. In the other case,
# where the wrapped function is called with a positional
# argument, the derivative with respect to its index must
# be used:
derivative = derivatives_args_index[index]
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# Optimization: None derivatives for the positional arguments are
# converted to the corresponding numerical differentiation
# function (instead of doing this over and over later every time a
# None derivative is found):
none_converter = lambda index: partial_derivative(f, index)
for (index, derivative) in enumerate(
derivatives_args_index.returned_elements):
if derivative is None:
derivatives_args_index.returned_elements[index] = (
none_converter(index))
# Future None values are also automatically converted:
derivatives_args_index.none_converter = none_converter
## Wrapped function:
#! Setting the doc string after "def f_with...()" does not
# seem to work. We define it explicitly:
@set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))
def f_with_affine_output(*args, **kwargs):
########################################
# The involved random variables must first be gathered, so
# that they can be independently updated.
# The arguments that contain an uncertainty (AffineScalarFunc
# objects) are gathered, as positions or names; they will be
# replaced by their nominal value in order to calculate
# the necessary derivatives of f.
pos_w_uncert = [index for (index, value) in enumerate(args)
if isinstance(value, AffineScalarFunc)]
names_w_uncert = [key for (key, value) in kwargs.items()
if isinstance(value, AffineScalarFunc)]
########################################
# Value of f() at the nominal value of the arguments with
# uncertainty:
# The usual behavior of f() is kept, if no number with
# uncertainty is provided:
if (not pos_w_uncert) and (not names_w_uncert):
return f(*args, **kwargs)
### Nominal values of the (scalar) arguments:
# !! Possible optimization: If pos_w_uncert is empty, there
# is actually no need to create a mutable version of args and
# one could do args_values = args. However, the wrapped
# function is typically called with numbers with uncertainties
# as positional arguments (i.e., pos_w_uncert is not emtpy),
# so this "optimization" is not implemented here.
## Positional arguments:
args_values = list(args) # Now mutable: modified below
# Arguments with an uncertainty are converted to their nominal
# value:
for index in pos_w_uncert:
args_values[index] = args[index].nominal_value
## Keyword arguments:
# For efficiency reasons, kwargs is not copied. Instead, its
# values with uncertainty are modified:
# The original values with uncertainties are needed: they are
# saved in the following dictionary (which only contains
# values with uncertainty):
kwargs_uncert_values = {}
for name in names_w_uncert:
value_with_uncert = kwargs[name]
# Saving for future use:
kwargs_uncert_values[name] = value_with_uncert
# The original dictionary is modified (for efficiency reasons):
kwargs[name] = value_with_uncert.nominal_value
f_nominal_value = f(*args_values, **kwargs)
# If the value is not a float, then this code cannot provide
# the result, as it returns a UFloat, which represents a
# random real variable. This happens for instance when
# ufloat()*numpy.array() is calculated: the
# AffineScalarFunc.__mul__ operator, obtained through wrap(),
# returns a NumPy array, not a float:
if not isinstance(f_nominal_value, FLOAT_LIKE_TYPES):
return NotImplemented
########################################
# Calculation of the linear part of the function value,
# defined by (coefficient, argument) pairs, where 'argument'
# is an AffineScalarFunc (for all AffineScalarFunc found as
# argument of f):
linear_part = []
for pos in pos_w_uncert:
linear_part.append((
# Coefficient:
derivatives_args_index[pos](*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
args[pos]._linear_part))
for name in names_w_uncert:
# Optimization: caching of the automatic numerical
# derivatives for keyword arguments that are
# discovered. This gives a speedup when the original
# function is called repeatedly with the same keyword
# arguments:
derivative = derivatives_all_kwargs.setdefault(
name,
# Derivative never needed before:
partial_derivative(f, name))
linear_part.append((
# Coefficient:
derivative(*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
kwargs_uncert_values[name]._linear_part))
# The function now returns the necessary linear approximation
# to the function:
return AffineScalarFunc(
f_nominal_value, LinearCombination(linear_part))
f_with_affine_output = set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))(f_with_affine_output)
# It is easier to work with f_with_affine_output, which represents
# a wrapped version of 'f', when it bears the same name as 'f':
# ! __name__ is read-only, in Python 2.3:
f_with_affine_output.name = f.__name__
return f_with_affine_output
|
(*args, **kwargs)
|
61,710 |
uncertainties.core
|
__format__
|
Formats a number with uncertainty.
The format specification are the same as for format() for
floats, as defined for Python 2.6+ (restricted to what the %
operator accepts, if using an earlier version of Python),
except that the n presentation type is not supported. In
particular, the usual precision, alignment, sign flag,
etc. can be used. The behavior of the various presentation
types (e, f, g, none, etc.) is similar. Moreover, the format
is extended: the number of digits of the uncertainty can be
controlled, as is the way the uncertainty is indicated (with
+/- or with the short-hand notation 3.14(1), in LaTeX or with
a simple text string,...).
Beyond the use of options at the end of the format
specification, the main difference with floats is that a "u"
just before the presentation type (f, e, g, none, etc.)
activates the "uncertainty control" mode (e.g.: ".6u"). This
mode is also activated when not using any explicit precision
(e.g.: "g", "10f", "+010,e" format specifications). If the
uncertainty does not have a meaningful number of significant
digits (0 and NaN uncertainties), this mode is automatically
deactivated.
The nominal value and the uncertainty always use the same
precision. This implies trailing zeros, in general, even with
the g format type (contrary to the float case). However, when
the number of significant digits of the uncertainty is not
defined (zero or NaN uncertainty), it has no precision, so
there is no matching. In this case, the original format
specification is used for the nominal value (any "u" is
ignored).
Any precision (".p", where p is a number) is interpreted (if
meaningful), in the uncertainty control mode, as indicating
the number p of significant digits of the displayed
uncertainty. Example: .1uf will return a string with one
significant digit in the uncertainty (and no exponent).
If no precision is given, the rounding rules from the
Particle Data Group are used, if possible
(http://pdg.lbl.gov/2010/reviews/rpp2010-rev-rpp-intro.pdf). For
example, the "f" format specification generally does not use
the default 6 digits after the decimal point, but applies the
PDG rules.
A common exponent is used if an exponent is needed for the
larger of the nominal value (in absolute value) and the
standard deviation, unless this would result in a zero
uncertainty being represented as 0e... or a NaN uncertainty as
NaNe.... Thanks to this common exponent, the quantity that
best describes the associated probability distribution has a
mantissa in the usual 1-10 range. The common exponent is
factored (as in "(1.2+/-0.1)e-5"). unless the format
specification contains an explicit width (" 1.2e-5+/- 0.1e-5")
(this allows numbers to be in a single column, when printing
numbers over many lines). Specifying a minimum width of 1 is a
way of forcing any common exponent to not be factored out.
The fill, align, zero and width parameters of the format
specification are applied individually to each of the nominal
value and standard deviation or, if the shorthand notation is
used, globally.
The sign parameter of the format specification is only applied
to the nominal value (since the standard deviation is
positive).
In the case of a non-LaTeX output, the returned string can
normally be parsed back with ufloat_fromstr(). This however
excludes cases where numbers use the "," thousands separator,
for example.
Options can be added, at the end of the format
specification. Multiple options can be specified:
- When "P" is present, the pretty-printing mode is activated: "±"
separates the nominal value from the standard deviation, exponents
use superscript characters, etc.
- When "S" is present (like in .1uS), the short-hand notation 1.234(5)
is used, indicating an uncertainty on the last digits; if the digits
of the uncertainty straddle the decimal point, it uses a fixed-point
notation, like in 12.3(4.5).
- When "L" is present, the output is formatted with LaTeX.
- "p" ensures that there are parentheses around the …±… part (no
parentheses are added if some are already present, for instance
because of an exponent or of a trailing % sign, etc.). This produces
outputs like (1.0±0.2) or (1.0±0.2)e7, which can be useful for
removing any ambiguity if physical units are added after the printed
number.
An uncertainty which is exactly zero is represented as the
integer 0 (i.e. with no decimal point).
The "%" format type forces the percent sign to be at the end
of the returned string (it is not attached to each of the
nominal value and the standard deviation).
Some details of the formatting can be customized as described
in format_num().
|
def __format__(self, format_spec):
'''
Formats a number with uncertainty.
The format specification are the same as for format() for
floats, as defined for Python 2.6+ (restricted to what the %
operator accepts, if using an earlier version of Python),
except that the n presentation type is not supported. In
particular, the usual precision, alignment, sign flag,
etc. can be used. The behavior of the various presentation
types (e, f, g, none, etc.) is similar. Moreover, the format
is extended: the number of digits of the uncertainty can be
controlled, as is the way the uncertainty is indicated (with
+/- or with the short-hand notation 3.14(1), in LaTeX or with
a simple text string,...).
Beyond the use of options at the end of the format
specification, the main difference with floats is that a "u"
just before the presentation type (f, e, g, none, etc.)
activates the "uncertainty control" mode (e.g.: ".6u"). This
mode is also activated when not using any explicit precision
(e.g.: "g", "10f", "+010,e" format specifications). If the
uncertainty does not have a meaningful number of significant
digits (0 and NaN uncertainties), this mode is automatically
deactivated.
The nominal value and the uncertainty always use the same
precision. This implies trailing zeros, in general, even with
the g format type (contrary to the float case). However, when
the number of significant digits of the uncertainty is not
defined (zero or NaN uncertainty), it has no precision, so
there is no matching. In this case, the original format
specification is used for the nominal value (any "u" is
ignored).
Any precision (".p", where p is a number) is interpreted (if
meaningful), in the uncertainty control mode, as indicating
the number p of significant digits of the displayed
uncertainty. Example: .1uf will return a string with one
significant digit in the uncertainty (and no exponent).
If no precision is given, the rounding rules from the
Particle Data Group are used, if possible
(http://pdg.lbl.gov/2010/reviews/rpp2010-rev-rpp-intro.pdf). For
example, the "f" format specification generally does not use
the default 6 digits after the decimal point, but applies the
PDG rules.
A common exponent is used if an exponent is needed for the
larger of the nominal value (in absolute value) and the
standard deviation, unless this would result in a zero
uncertainty being represented as 0e... or a NaN uncertainty as
NaNe.... Thanks to this common exponent, the quantity that
best describes the associated probability distribution has a
mantissa in the usual 1-10 range. The common exponent is
factored (as in "(1.2+/-0.1)e-5"). unless the format
specification contains an explicit width (" 1.2e-5+/- 0.1e-5")
(this allows numbers to be in a single column, when printing
numbers over many lines). Specifying a minimum width of 1 is a
way of forcing any common exponent to not be factored out.
The fill, align, zero and width parameters of the format
specification are applied individually to each of the nominal
value and standard deviation or, if the shorthand notation is
used, globally.
The sign parameter of the format specification is only applied
to the nominal value (since the standard deviation is
positive).
In the case of a non-LaTeX output, the returned string can
normally be parsed back with ufloat_fromstr(). This however
excludes cases where numbers use the "," thousands separator,
for example.
Options can be added, at the end of the format
specification. Multiple options can be specified:
- When "P" is present, the pretty-printing mode is activated: "±"
separates the nominal value from the standard deviation, exponents
use superscript characters, etc.
- When "S" is present (like in .1uS), the short-hand notation 1.234(5)
is used, indicating an uncertainty on the last digits; if the digits
of the uncertainty straddle the decimal point, it uses a fixed-point
notation, like in 12.3(4.5).
- When "L" is present, the output is formatted with LaTeX.
- "p" ensures that there are parentheses around the …±… part (no
parentheses are added if some are already present, for instance
because of an exponent or of a trailing % sign, etc.). This produces
outputs like (1.0±0.2) or (1.0±0.2)e7, which can be useful for
removing any ambiguity if physical units are added after the printed
number.
An uncertainty which is exactly zero is represented as the
integer 0 (i.e. with no decimal point).
The "%" format type forces the percent sign to be at the end
of the returned string (it is not attached to each of the
nominal value and the standard deviation).
Some details of the formatting can be customized as described
in format_num().
'''
# Convention on limits "between" digits: 0 = exactly at the
# decimal point, -1 = after the first decimal, 1 = before the
# units digit, etc.
# Convention on digits: 0 is units (10**0), 1 is tens, -1 is
# tenths, etc.
# This method does the format specification parsing, and
# calculates the various parts of the displayed value
# (mantissas, exponent, position of the last digit). The
# formatting itself is delegated to format_num().
########################################
# Format specification parsing:
match = re.match(r'''
(?P<fill>[^{}]??)(?P<align>[<>=^]?) # fill cannot be { or }
(?P<sign>[-+ ]?)
(?P<zero>0?)
(?P<width>\d*)
(?P<comma>,?)
(?:\.(?P<prec>\d+))?
(?P<uncert_prec>u?) # Precision for the uncertainty?
# The type can be omitted. Options must not go here:
(?P<type>[eEfFgG%]??) # n not supported
(?P<options>[PSLp]*) # uncertainties-specific flags
$''',
format_spec,
re.VERBOSE)
# Does the format specification look correct?
if not match:
raise ValueError(
'Format specification %r cannot be used with object of type'
' %r. Note that uncertainties-specific flags must be put at'
' the end of the format string.'
# Sub-classes handled:
% (format_spec, self.__class__.__name__))
# Effective format presentation type: f, e, g, etc., or None,
# like in
# https://docs.python.org/3.4/library/string.html#format-specification-mini-language. Contrary
# to what is written in the documentation, it is not true that
# None is "the same as 'g'": "{}".format() and "{:g}" do not
# give the same result, on 31415000000.0. None is thus kept as
# is instead of being replaced by "g".
pres_type = match.group('type') or None
# Shortcut:
fmt_prec = match.group('prec') # Can be None
########################################
# Since the '%' (percentage) format specification can change
# the value to be displayed, this value must first be
# calculated. Calculating the standard deviation is also an
# optimization: the standard deviation is generally
# calculated: it is calculated only once, here:
nom_val = self.nominal_value
std_dev = self.std_dev
# 'options' is the options that must be given to format_num():
options = set(match.group('options'))
########################################
# The '%' format is treated internally as a display option: it
# should not be applied individually to each part:
if pres_type == '%':
# Because '%' does 0.0055*100, the value
# 0.5499999999999999 is obtained, which rounds to 0.5. The
# original rounded value is 0.006. The same behavior is
# found in Python 2.7: '{:.1%}'.format(0.0055) is '0.5%'.
# If a different behavior is needed, a solution to this
# problem would be to do the rounding before the
# multiplication.
std_dev *= 100
nom_val *= 100
pres_type = 'f'
options.add('%')
# At this point, pres_type is in eEfFgG or None (not %).
########################################
# Non-real values (nominal value or standard deviation) must
# be handled in a specific way:
real_values = [value for value in [abs(nom_val), std_dev]
if not isinfinite(value)]
# Calculation of digits_limit, which defines the precision of
# the nominal value and of the standard deviation (it can be
# None when it does not matter, like for NaN±NaN):
# Reference value for the calculation of a possible exponent,
# if needed:
if pres_type in (None, 'e', 'E', 'g', 'G'):
# Reference value for the exponent: the largest value
# defines what the exponent will be (another convention
# could have been chosen, like using the exponent of the
# nominal value, irrespective of the standard deviation):
try:
exp_ref_value = max(real_values)
except ValueError: # No non-NaN value: NaN±NaN…
# No meaningful common exponent can be obtained:
pass
## else:
## print "EXP_REF_VAL", exp_ref_value
# Should the precision be interpreted like for a float, or
# should the number of significant digits on the uncertainty
# be controlled?
if ((
# Default behavior: number of significant digits on the
# uncertainty controlled (if useful, i.e. only in
# situations where the nominal value and the standard
# error digits are truncated at the same place):
(not fmt_prec and len(real_values)==2)
or match.group('uncert_prec')) # Explicit control
# The number of significant digits of the uncertainty must
# be meaningful, otherwise the position of the significant
# digits of the uncertainty does not have a clear
# meaning. This gives us the *effective* uncertainty
# control mode:
and std_dev
and not isinfinite(std_dev)):
# The number of significant digits on the uncertainty is
# controlled.
# The limit digits_limit on the digits of nom_val and std_dev
# to be displayed is calculated. If the exponent notation is
# used, this limit is generally different from the finally
# displayed limit (e.g. 314.15+/-0.01 has digits_limit=-2, but
# will be displayed with an exponent as (3.1415+/-0.0001)e+02,
# which corresponds to 4 decimals after the decimal point, not
# 2).
# Number of significant digits to use:
if fmt_prec:
num_signif_d = int(fmt_prec) # Can only be non-negative
if not num_signif_d:
raise ValueError("The number of significant digits"
" on the uncertainty should be positive")
else:
(num_signif_d, std_dev) = PDG_precision(std_dev)
digits_limit = signif_dgt_to_limit(std_dev, num_signif_d)
else:
# No control of the number of significant digits on the
# uncertainty.
## print "PRECISION NOT BASED ON UNCERTAINTY"
# The precision has the same meaning as for floats (it is
# not the uncertainty that defines the number of digits).
# The usual default precision is used (this is useful for
# 3.141592±NaN with an "f" format specification, for
# example):
#
# prec is the precision for the main parts of the final
# format (in the sense of float formatting):
#
# https://docs.python.org/3.4/library/string.html#format-specification-mini-language
if fmt_prec:
prec = int(fmt_prec)
elif pres_type is None:
prec = 12
else:
prec = 6
if pres_type in ('f', 'F'):
digits_limit = -prec
else: # Format type in None, eEgG
# We first calculate the number of significant digits
# to be displayed (if possible):
if pres_type in ('e', 'E'):
# The precision is the number of significant
# digits required - 1 (because there is a single
# digit before the decimal point, which is not
# included in the definition of the precision with
# the e/E format type):
num_signif_digits = prec+1
else: # Presentation type in None, g, G
# Effective format specification precision: the rule
# of
# http://docs.python.org/2.7/library/string.html#format-specification-mini-language
# is used:
# The final number of significant digits to be
# displayed is not necessarily obvious: trailing
# zeros are removed (with the gG presentation
# type), so num_signif_digits is the number of
# significant digits if trailing zeros were not
# removed. This quantity is relevant for the
# rounding implied by the exponent test of the g/G
# format:
# 0 is interpreted like 1 (as with floats with a
# gG presentation type):
num_signif_digits = prec or 1
# The number of significant digits is important for
# example for determining the exponent:
## print "NUM_SIGNIF_DIGITS", num_signif_digits
digits_limit = (
signif_dgt_to_limit(exp_ref_value, num_signif_digits)
if real_values
else None)
## print "DIGITS_LIMIT", digits_limit
#######################################
# Common exponent notation: should it be used? use_exp is set
# accordingly. If a common exponent should be used (use_exp is
# True), 'common_exp' is set to the exponent that should be
# used.
if pres_type in ('f', 'F'):
use_exp = False
elif pres_type in ('e', 'E'):
if not real_values:
use_exp = False
else:
use_exp = True
# !! This calculation might have been already done,
# for instance when using the .0e format:
# signif_dgt_to_limit() was called before, which
# prompted a similar calculation:
common_exp = first_digit(round(exp_ref_value, -digits_limit))
else: # None, g, G
# The rules from
# https://docs.python.org/3.4/library/string.html#format-specification-mini-language
# are applied.
# Python's native formatting (whose result could be parsed
# in order to determine whether a common exponent should
# be used) is not used because there is shared information
# between the nominal value and the standard error (same
# last digit, common exponent) and extracting this
# information from Python would entail parsing its
# formatted string, which is in principle inefficient
# (internally, Python performs calculations that yield a
# string, and the string would be parsed back into
# separate parts and numbers, which is in principle
# unnecessary).
# Should the scientific notation be used? The same rule as
# for floats is used ("-4 <= exponent of rounded value <
# p"), on the nominal value.
if not real_values:
use_exp = False
else:
# Common exponent *if* used:
common_exp = first_digit(round(exp_ref_value, -digits_limit))
# print "COMMON EXP TEST VALUE", common_exp
# print "LIMIT EXP", common_exp-digits_limit+1
# print "WITH digits_limit", digits_limit
# The number of significant digits of the reference value
# rounded at digits_limit is exponent-digits_limit+1:
if -4 <= common_exp < common_exp-digits_limit+1:
use_exp = False
else:
use_exp = True
########################################
# Calculation of signif_limit (position of the significant
# digits limit in the final fixed point representations; this
# is either a non-positive number, or None), of
# nom_val_mantissa ("mantissa" for the nominal value,
# i.e. value possibly corrected for a factorized exponent),
# and std_dev_mantissa (similarly for the standard
# deviation). common_exp is also set to None if no common
# exponent should be used.
if use_exp:
# Not 10.**(-common_exp), for limit values of common_exp:
factor = 10.**common_exp
nom_val_mantissa = nom_val/factor
std_dev_mantissa = std_dev/factor
# Limit for the last digit of the mantissas:
signif_limit = digits_limit - common_exp
else: # No common exponent
common_exp = None
nom_val_mantissa = nom_val
std_dev_mantissa = std_dev
signif_limit = digits_limit
## print "SIGNIF_LIMIT", signif_limit
########################################
# Format of the main (i.e. with no exponent) parts (the None
# presentation type is similar to the g format type):
main_pres_type = 'fF'[(pres_type or 'g').isupper()]
# The precision of the main parts must be adjusted so as
# to take into account the special role of the decimal
# point:
if signif_limit is not None: # If signif_limit is pertinent
# The decimal point location is always included in the
# printed digits (e.g., printing 3456 with only 2
# significant digits requires to print at least four
# digits, like in 3456 or 3500).
#
# The max() is important for example for
# 1234567.89123+/-12345.678 with the f format: in this
# case, signif_limit is +3 (2 significant digits necessary
# for the error, as per the PDG rules), but the (Python
# float formatting) precision to be used for the main
# parts is 0 (all digits must be shown).
#
# The 1 for the None pres_type represents "at least one
# digit past the decimal point" of Python
# (https://docs.python.org/3.4/library/string.html#format-specification-mini-language). This
# is only applied for null uncertainties.
prec = max(-signif_limit,
1 if pres_type is None and not std_dev
else 0)
## print "PREC", prec
########################################
# print (
# "FORMAT_NUM parameters: nom_val_mantissa={},"
# " std_dev_mantissa={}, common_exp={},"
# " match.groupdict()={}, prec={}, main_pres_type={},"
# " options={}".format(
# nom_val_mantissa, std_dev_mantissa, common_exp,
# match.groupdict(),
# prec,
# main_pres_type,
# options))
# Final formatting:
return format_num(nom_val_mantissa, std_dev_mantissa, common_exp,
match.groupdict(),
prec=prec,
main_pres_type=main_pres_type,
options=options)
|
(self, format_spec)
|
61,712 |
uncertainties.core
|
__getstate__
|
Hook for the pickle module.
The slot attributes of the parent classes are returned, as
well as those of the __dict__ attribute of the object (if
any).
|
def __getstate__(self):
"""
Hook for the pickle module.
The slot attributes of the parent classes are returned, as
well as those of the __dict__ attribute of the object (if
any).
"""
# In general (case where this class is subclassed), data
# attribute are stored in two places: possibly in __dict_, and
# in slots. Data from both locations is returned by this
# method.
all_attrs = {}
# Support for subclasses that do not use __slots__ (except
# through inheritance): instances have a __dict__
# attribute. The keys in this __dict__ are shadowed by the
# slot attribute names (reference:
# http://stackoverflow.com/questions/15139067/attribute-access-in-python-first-slots-then-dict/15139208#15139208).
# The method below not only preserves this behavior, but also
# saves the full contents of __dict__. This is robust:
# unpickling gives back the original __dict__ even if __dict__
# contains keys that are shadowed by slot names:
try:
all_attrs['__dict__'] = self.__dict__
except AttributeError:
pass
# All the slot attributes are gathered.
# Classes that do not define __slots__ have the __slots__ of
# one of their parents (the first parent with their own
# __slots__ in MRO). This is why the slot names are first
# gathered (with repetitions removed, in general), and their
# values obtained later.
all_slots = set()
for cls in type(self).mro():
# In the diamond inheritance pattern, some parent classes
# may not have __slots__:
slot_names = getattr(cls, '__slots__', ())
# Slot names can be given in various forms (string,
# sequence, iterable):
if isinstance(slot_names, basestring):
all_slots.add(slot_names) # Single name
else:
all_slots.update(slot_names)
# The slot values are stored:
for name in all_slots:
try:
# !! It might happen that '__dict__' is itself a slot
# name. In this case, its value is saved
# again. Alternatively, the loop could be done on
# all_slots - {'__dict__'}:
all_attrs[name] = getattr(self, name)
except AttributeError:
pass # Undefined slot attribute
return all_attrs
|
(self)
|
61,714 |
uncertainties.core
|
__init__
|
nominal_value -- value of the function when the linear part is
zero.
linear_part -- LinearCombination that describes the linear
part of the AffineScalarFunc.
|
def __init__(self, nominal_value, linear_part):
"""
nominal_value -- value of the function when the linear part is
zero.
linear_part -- LinearCombination that describes the linear
part of the AffineScalarFunc.
"""
# ! A technical consistency requirement is that the
# linear_part can be nested inside a NestedLinearCombination
# (because this is how functions on AffineScalarFunc calculate
# their result: by constructing nested expressions for them).
# Defines the value at the origin:
# Only float-like values are handled. One reason is that it
# does not make sense for a scalar function to be affine to
# not yield float values. Another reason is that it would not
# make sense to have a complex nominal value, here (it would
# not be handled correctly at all): converting to float should
# be possible.
self._nominal_value = float(nominal_value)
# In order to have a linear execution time for long sums, the
# _linear_part is generally left as is (otherwise, each
# successive term would expand to a linearly growing sum of
# terms: efficiently handling such terms [so, without copies]
# is not obvious, when the algorithm should work for all
# functions beyond sums).
self._linear_part = linear_part
|
(self, nominal_value, linear_part)
|
61,719 |
uncertainties.core
|
f_with_affine_output
|
Version of __mod__(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
Return self%value.
|
def wrap(f, derivatives_args=[], derivatives_kwargs={}):
"""
Wraps a function f into a function that also accepts numbers with
uncertainties (UFloat objects); the wrapped function returns the
value of f with the correct uncertainty and correlations. The
wrapped function is intended to be used as a drop-in replacement
for the original function: they can be called in the exact same
way, the only difference being that numbers with uncertainties can
be given to the wrapped function where f accepts float arguments.
Doing so may be necessary when function f cannot be expressed
analytically (with uncertainties-compatible operators and
functions like +, *, umath.sin(), etc.).
f must return a float-like (i.e. a float, an int, etc., not a
list, etc.), unless when called with no number with
uncertainty. This is because the wrapped function generally
returns numbers with uncertainties: they represent a probability
distribution over the real numbers.
If the wrapped function is called with no argument that has an
uncertainty, the value of f is returned.
Parameters: the derivatives_* parameters can be used for defining
some of the partial derivatives of f. All the (non-None)
derivatives must have the same signature as f.
derivatives_args --
Iterable that, when iterated over, returns either derivatives
(functions) or None. derivatives_args can in particular be a
simple sequence (list or tuple) that gives the derivatives of
the first positional parameters of f.
Each function must be the partial derivative of f with respect
to the corresponding positional parameters. These functions
take the same arguments as f.
The positional parameters of a function are usually
positional-or-keyword parameters like in the call func(a,
b=None). However, they also include var-positional parameters
given through the func(a, b, *args) *args syntax. In the last
example, derivatives_args can be an iterable that returns the
derivative with respect to a, b and then to each optional
argument in args.
A value of None (instead of a function) obtained when
iterating over derivatives_args is automatically replaced by
the relevant numerical derivative. This derivative is not used
if the corresponding argument is not a number with
uncertainty. A None value can therefore be used for non-scalar
arguments of f (like string arguments).
If the derivatives_args iterable yields fewer derivatives than
needed, wrap() automatically sets the remaining unspecified
derivatives to None (i.e. to the automatic numerical
calculation of derivatives).
An indefinite number of derivatives can be specified by having
derivatives_args be an infinite iterator; this can for
instance be used for specifying the derivatives of functions
with a undefined number of argument (like sum(), whose partial
derivatives all return 1).
derivatives_kwargs --
Dictionary that maps keyword parameters to their derivatives,
or None (as in derivatives_args).
Keyword parameters are defined as being those of kwargs when f
has a signature of the form f(..., **kwargs). In Python 3,
these keyword parameters also include keyword-only parameters.
Non-mapped keyword parameters are replaced automatically by
None: the wrapped function will use, if necessary, numerical
differentiation for these parameters (as with
derivatives_args).
Note that this dictionary only maps keyword *parameters* from
the *signature* of f. The way the wrapped function is called
is immaterial: for example, if f has signature f(a, b=None),
then derivatives_kwargs should be the empty dictionary, even
if the wrapped f can be called a wrapped_f(a=123, b=42).
Example (for illustration purposes only, as
uncertainties.umath.sin() runs faster than the examples that
follow): 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.
Numerically calculated derivatives are meaningless when the
function is not differentiable (e.g., math.hypot(x, y) in (x, y) =
(0, 0), and sqrt(x) in x = 0). The corresponding uncertainties are
either meaningless (case of hypot) or raise an exception when
calculated (case of sqrt). In such cases, it is recommended (but
not mandatory) to supply instead a derivative function that
returns NaN where the function is not differentiable. This
function can still numerically calculate the derivative where
defined, for instance by using the
uncertainties.core.partial_derivative() function.
The correctness of the supplied analytical derivatives an be
tested by setting them to None instead and comparing the
analytical and the numerical differentiation results.
Note on efficiency: the wrapped function assumes that f cannot
accept numbers with uncertainties as arguments. If f actually does
handle some arguments even when they have an uncertainty, the
wrapped function ignores this fact, which might lead to a
performance hit: wrapping a function that actually accepts numbers
with uncertainty is likely to make it slower.
"""
derivatives_args_index = IndexableIter(
# Automatic addition of numerical derivatives in case the
# supplied derivatives_args is shorter than the number of
# arguments in *args:
itertools.chain(derivatives_args, itertools.repeat(None)))
# Derivatives for keyword arguments (includes var-keyword
# parameters **kwargs, but also var-or-keyword parameters, and
# keyword-only parameters (Python 3):
derivatives_all_kwargs = {}
for (name, derivative) in derivatives_kwargs.items():
# Optimization: None keyword-argument derivatives are converted
# right away to derivatives (instead of doing this every time a
# None derivative is encountered when calculating derivatives):
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# When the wrapped function is called with keyword arguments that
# map to positional-or-keyword parameters, their derivative is
# looked for in derivatives_all_kwargs. We define these
# additional derivatives:
try:
argspec = getargspec(f)
except TypeError:
# Some functions do not provide meta-data about their
# arguments (see PEP 362). One cannot use keyword arguments
# for positional-or-keyword parameters with them: nothing has
# to be done:
pass
else:
# With Python 3, there is no need to handle keyword-only
# arguments (and therefore to use inspect.getfullargspec())
# because they are already handled by derivatives_kwargs.
for (index, name) in enumerate(argspec.args):
# The following test handles the case of
# positional-or-keyword parameter for which automatic
# numerical differentiation is used: when the wrapped
# function is called with a keyword argument for this
# parameter, the numerical derivative must be calculated
# with respect to the parameter name. In the other case,
# where the wrapped function is called with a positional
# argument, the derivative with respect to its index must
# be used:
derivative = derivatives_args_index[index]
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# Optimization: None derivatives for the positional arguments are
# converted to the corresponding numerical differentiation
# function (instead of doing this over and over later every time a
# None derivative is found):
none_converter = lambda index: partial_derivative(f, index)
for (index, derivative) in enumerate(
derivatives_args_index.returned_elements):
if derivative is None:
derivatives_args_index.returned_elements[index] = (
none_converter(index))
# Future None values are also automatically converted:
derivatives_args_index.none_converter = none_converter
## Wrapped function:
#! Setting the doc string after "def f_with...()" does not
# seem to work. We define it explicitly:
@set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))
def f_with_affine_output(*args, **kwargs):
########################################
# The involved random variables must first be gathered, so
# that they can be independently updated.
# The arguments that contain an uncertainty (AffineScalarFunc
# objects) are gathered, as positions or names; they will be
# replaced by their nominal value in order to calculate
# the necessary derivatives of f.
pos_w_uncert = [index for (index, value) in enumerate(args)
if isinstance(value, AffineScalarFunc)]
names_w_uncert = [key for (key, value) in kwargs.items()
if isinstance(value, AffineScalarFunc)]
########################################
# Value of f() at the nominal value of the arguments with
# uncertainty:
# The usual behavior of f() is kept, if no number with
# uncertainty is provided:
if (not pos_w_uncert) and (not names_w_uncert):
return f(*args, **kwargs)
### Nominal values of the (scalar) arguments:
# !! Possible optimization: If pos_w_uncert is empty, there
# is actually no need to create a mutable version of args and
# one could do args_values = args. However, the wrapped
# function is typically called with numbers with uncertainties
# as positional arguments (i.e., pos_w_uncert is not emtpy),
# so this "optimization" is not implemented here.
## Positional arguments:
args_values = list(args) # Now mutable: modified below
# Arguments with an uncertainty are converted to their nominal
# value:
for index in pos_w_uncert:
args_values[index] = args[index].nominal_value
## Keyword arguments:
# For efficiency reasons, kwargs is not copied. Instead, its
# values with uncertainty are modified:
# The original values with uncertainties are needed: they are
# saved in the following dictionary (which only contains
# values with uncertainty):
kwargs_uncert_values = {}
for name in names_w_uncert:
value_with_uncert = kwargs[name]
# Saving for future use:
kwargs_uncert_values[name] = value_with_uncert
# The original dictionary is modified (for efficiency reasons):
kwargs[name] = value_with_uncert.nominal_value
f_nominal_value = f(*args_values, **kwargs)
# If the value is not a float, then this code cannot provide
# the result, as it returns a UFloat, which represents a
# random real variable. This happens for instance when
# ufloat()*numpy.array() is calculated: the
# AffineScalarFunc.__mul__ operator, obtained through wrap(),
# returns a NumPy array, not a float:
if not isinstance(f_nominal_value, FLOAT_LIKE_TYPES):
return NotImplemented
########################################
# Calculation of the linear part of the function value,
# defined by (coefficient, argument) pairs, where 'argument'
# is an AffineScalarFunc (for all AffineScalarFunc found as
# argument of f):
linear_part = []
for pos in pos_w_uncert:
linear_part.append((
# Coefficient:
derivatives_args_index[pos](*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
args[pos]._linear_part))
for name in names_w_uncert:
# Optimization: caching of the automatic numerical
# derivatives for keyword arguments that are
# discovered. This gives a speedup when the original
# function is called repeatedly with the same keyword
# arguments:
derivative = derivatives_all_kwargs.setdefault(
name,
# Derivative never needed before:
partial_derivative(f, name))
linear_part.append((
# Coefficient:
derivative(*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
kwargs_uncert_values[name]._linear_part))
# The function now returns the necessary linear approximation
# to the function:
return AffineScalarFunc(
f_nominal_value, LinearCombination(linear_part))
f_with_affine_output = set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))(f_with_affine_output)
# It is easier to work with f_with_affine_output, which represents
# a wrapped version of 'f', when it bears the same name as 'f':
# ! __name__ is read-only, in Python 2.3:
f_with_affine_output.name = f.__name__
return f_with_affine_output
|
(*args, **kwargs)
|
61,720 |
uncertainties.core
|
f_with_affine_output
|
Version of __mul__(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
Return self*value.
|
def wrap(f, derivatives_args=[], derivatives_kwargs={}):
"""
Wraps a function f into a function that also accepts numbers with
uncertainties (UFloat objects); the wrapped function returns the
value of f with the correct uncertainty and correlations. The
wrapped function is intended to be used as a drop-in replacement
for the original function: they can be called in the exact same
way, the only difference being that numbers with uncertainties can
be given to the wrapped function where f accepts float arguments.
Doing so may be necessary when function f cannot be expressed
analytically (with uncertainties-compatible operators and
functions like +, *, umath.sin(), etc.).
f must return a float-like (i.e. a float, an int, etc., not a
list, etc.), unless when called with no number with
uncertainty. This is because the wrapped function generally
returns numbers with uncertainties: they represent a probability
distribution over the real numbers.
If the wrapped function is called with no argument that has an
uncertainty, the value of f is returned.
Parameters: the derivatives_* parameters can be used for defining
some of the partial derivatives of f. All the (non-None)
derivatives must have the same signature as f.
derivatives_args --
Iterable that, when iterated over, returns either derivatives
(functions) or None. derivatives_args can in particular be a
simple sequence (list or tuple) that gives the derivatives of
the first positional parameters of f.
Each function must be the partial derivative of f with respect
to the corresponding positional parameters. These functions
take the same arguments as f.
The positional parameters of a function are usually
positional-or-keyword parameters like in the call func(a,
b=None). However, they also include var-positional parameters
given through the func(a, b, *args) *args syntax. In the last
example, derivatives_args can be an iterable that returns the
derivative with respect to a, b and then to each optional
argument in args.
A value of None (instead of a function) obtained when
iterating over derivatives_args is automatically replaced by
the relevant numerical derivative. This derivative is not used
if the corresponding argument is not a number with
uncertainty. A None value can therefore be used for non-scalar
arguments of f (like string arguments).
If the derivatives_args iterable yields fewer derivatives than
needed, wrap() automatically sets the remaining unspecified
derivatives to None (i.e. to the automatic numerical
calculation of derivatives).
An indefinite number of derivatives can be specified by having
derivatives_args be an infinite iterator; this can for
instance be used for specifying the derivatives of functions
with a undefined number of argument (like sum(), whose partial
derivatives all return 1).
derivatives_kwargs --
Dictionary that maps keyword parameters to their derivatives,
or None (as in derivatives_args).
Keyword parameters are defined as being those of kwargs when f
has a signature of the form f(..., **kwargs). In Python 3,
these keyword parameters also include keyword-only parameters.
Non-mapped keyword parameters are replaced automatically by
None: the wrapped function will use, if necessary, numerical
differentiation for these parameters (as with
derivatives_args).
Note that this dictionary only maps keyword *parameters* from
the *signature* of f. The way the wrapped function is called
is immaterial: for example, if f has signature f(a, b=None),
then derivatives_kwargs should be the empty dictionary, even
if the wrapped f can be called a wrapped_f(a=123, b=42).
Example (for illustration purposes only, as
uncertainties.umath.sin() runs faster than the examples that
follow): 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.
Numerically calculated derivatives are meaningless when the
function is not differentiable (e.g., math.hypot(x, y) in (x, y) =
(0, 0), and sqrt(x) in x = 0). The corresponding uncertainties are
either meaningless (case of hypot) or raise an exception when
calculated (case of sqrt). In such cases, it is recommended (but
not mandatory) to supply instead a derivative function that
returns NaN where the function is not differentiable. This
function can still numerically calculate the derivative where
defined, for instance by using the
uncertainties.core.partial_derivative() function.
The correctness of the supplied analytical derivatives an be
tested by setting them to None instead and comparing the
analytical and the numerical differentiation results.
Note on efficiency: the wrapped function assumes that f cannot
accept numbers with uncertainties as arguments. If f actually does
handle some arguments even when they have an uncertainty, the
wrapped function ignores this fact, which might lead to a
performance hit: wrapping a function that actually accepts numbers
with uncertainty is likely to make it slower.
"""
derivatives_args_index = IndexableIter(
# Automatic addition of numerical derivatives in case the
# supplied derivatives_args is shorter than the number of
# arguments in *args:
itertools.chain(derivatives_args, itertools.repeat(None)))
# Derivatives for keyword arguments (includes var-keyword
# parameters **kwargs, but also var-or-keyword parameters, and
# keyword-only parameters (Python 3):
derivatives_all_kwargs = {}
for (name, derivative) in derivatives_kwargs.items():
# Optimization: None keyword-argument derivatives are converted
# right away to derivatives (instead of doing this every time a
# None derivative is encountered when calculating derivatives):
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# When the wrapped function is called with keyword arguments that
# map to positional-or-keyword parameters, their derivative is
# looked for in derivatives_all_kwargs. We define these
# additional derivatives:
try:
argspec = getargspec(f)
except TypeError:
# Some functions do not provide meta-data about their
# arguments (see PEP 362). One cannot use keyword arguments
# for positional-or-keyword parameters with them: nothing has
# to be done:
pass
else:
# With Python 3, there is no need to handle keyword-only
# arguments (and therefore to use inspect.getfullargspec())
# because they are already handled by derivatives_kwargs.
for (index, name) in enumerate(argspec.args):
# The following test handles the case of
# positional-or-keyword parameter for which automatic
# numerical differentiation is used: when the wrapped
# function is called with a keyword argument for this
# parameter, the numerical derivative must be calculated
# with respect to the parameter name. In the other case,
# where the wrapped function is called with a positional
# argument, the derivative with respect to its index must
# be used:
derivative = derivatives_args_index[index]
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# Optimization: None derivatives for the positional arguments are
# converted to the corresponding numerical differentiation
# function (instead of doing this over and over later every time a
# None derivative is found):
none_converter = lambda index: partial_derivative(f, index)
for (index, derivative) in enumerate(
derivatives_args_index.returned_elements):
if derivative is None:
derivatives_args_index.returned_elements[index] = (
none_converter(index))
# Future None values are also automatically converted:
derivatives_args_index.none_converter = none_converter
## Wrapped function:
#! Setting the doc string after "def f_with...()" does not
# seem to work. We define it explicitly:
@set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))
def f_with_affine_output(*args, **kwargs):
########################################
# The involved random variables must first be gathered, so
# that they can be independently updated.
# The arguments that contain an uncertainty (AffineScalarFunc
# objects) are gathered, as positions or names; they will be
# replaced by their nominal value in order to calculate
# the necessary derivatives of f.
pos_w_uncert = [index for (index, value) in enumerate(args)
if isinstance(value, AffineScalarFunc)]
names_w_uncert = [key for (key, value) in kwargs.items()
if isinstance(value, AffineScalarFunc)]
########################################
# Value of f() at the nominal value of the arguments with
# uncertainty:
# The usual behavior of f() is kept, if no number with
# uncertainty is provided:
if (not pos_w_uncert) and (not names_w_uncert):
return f(*args, **kwargs)
### Nominal values of the (scalar) arguments:
# !! Possible optimization: If pos_w_uncert is empty, there
# is actually no need to create a mutable version of args and
# one could do args_values = args. However, the wrapped
# function is typically called with numbers with uncertainties
# as positional arguments (i.e., pos_w_uncert is not emtpy),
# so this "optimization" is not implemented here.
## Positional arguments:
args_values = list(args) # Now mutable: modified below
# Arguments with an uncertainty are converted to their nominal
# value:
for index in pos_w_uncert:
args_values[index] = args[index].nominal_value
## Keyword arguments:
# For efficiency reasons, kwargs is not copied. Instead, its
# values with uncertainty are modified:
# The original values with uncertainties are needed: they are
# saved in the following dictionary (which only contains
# values with uncertainty):
kwargs_uncert_values = {}
for name in names_w_uncert:
value_with_uncert = kwargs[name]
# Saving for future use:
kwargs_uncert_values[name] = value_with_uncert
# The original dictionary is modified (for efficiency reasons):
kwargs[name] = value_with_uncert.nominal_value
f_nominal_value = f(*args_values, **kwargs)
# If the value is not a float, then this code cannot provide
# the result, as it returns a UFloat, which represents a
# random real variable. This happens for instance when
# ufloat()*numpy.array() is calculated: the
# AffineScalarFunc.__mul__ operator, obtained through wrap(),
# returns a NumPy array, not a float:
if not isinstance(f_nominal_value, FLOAT_LIKE_TYPES):
return NotImplemented
########################################
# Calculation of the linear part of the function value,
# defined by (coefficient, argument) pairs, where 'argument'
# is an AffineScalarFunc (for all AffineScalarFunc found as
# argument of f):
linear_part = []
for pos in pos_w_uncert:
linear_part.append((
# Coefficient:
derivatives_args_index[pos](*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
args[pos]._linear_part))
for name in names_w_uncert:
# Optimization: caching of the automatic numerical
# derivatives for keyword arguments that are
# discovered. This gives a speedup when the original
# function is called repeatedly with the same keyword
# arguments:
derivative = derivatives_all_kwargs.setdefault(
name,
# Derivative never needed before:
partial_derivative(f, name))
linear_part.append((
# Coefficient:
derivative(*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
kwargs_uncert_values[name]._linear_part))
# The function now returns the necessary linear approximation
# to the function:
return AffineScalarFunc(
f_nominal_value, LinearCombination(linear_part))
f_with_affine_output = set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))(f_with_affine_output)
# It is easier to work with f_with_affine_output, which represents
# a wrapped version of 'f', when it bears the same name as 'f':
# ! __name__ is read-only, in Python 2.3:
f_with_affine_output.name = f.__name__
return f_with_affine_output
|
(*args, **kwargs)
|
61,722 |
uncertainties.core
|
f_with_affine_output
|
Version of __neg__(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
-self
|
def wrap(f, derivatives_args=[], derivatives_kwargs={}):
"""
Wraps a function f into a function that also accepts numbers with
uncertainties (UFloat objects); the wrapped function returns the
value of f with the correct uncertainty and correlations. The
wrapped function is intended to be used as a drop-in replacement
for the original function: they can be called in the exact same
way, the only difference being that numbers with uncertainties can
be given to the wrapped function where f accepts float arguments.
Doing so may be necessary when function f cannot be expressed
analytically (with uncertainties-compatible operators and
functions like +, *, umath.sin(), etc.).
f must return a float-like (i.e. a float, an int, etc., not a
list, etc.), unless when called with no number with
uncertainty. This is because the wrapped function generally
returns numbers with uncertainties: they represent a probability
distribution over the real numbers.
If the wrapped function is called with no argument that has an
uncertainty, the value of f is returned.
Parameters: the derivatives_* parameters can be used for defining
some of the partial derivatives of f. All the (non-None)
derivatives must have the same signature as f.
derivatives_args --
Iterable that, when iterated over, returns either derivatives
(functions) or None. derivatives_args can in particular be a
simple sequence (list or tuple) that gives the derivatives of
the first positional parameters of f.
Each function must be the partial derivative of f with respect
to the corresponding positional parameters. These functions
take the same arguments as f.
The positional parameters of a function are usually
positional-or-keyword parameters like in the call func(a,
b=None). However, they also include var-positional parameters
given through the func(a, b, *args) *args syntax. In the last
example, derivatives_args can be an iterable that returns the
derivative with respect to a, b and then to each optional
argument in args.
A value of None (instead of a function) obtained when
iterating over derivatives_args is automatically replaced by
the relevant numerical derivative. This derivative is not used
if the corresponding argument is not a number with
uncertainty. A None value can therefore be used for non-scalar
arguments of f (like string arguments).
If the derivatives_args iterable yields fewer derivatives than
needed, wrap() automatically sets the remaining unspecified
derivatives to None (i.e. to the automatic numerical
calculation of derivatives).
An indefinite number of derivatives can be specified by having
derivatives_args be an infinite iterator; this can for
instance be used for specifying the derivatives of functions
with a undefined number of argument (like sum(), whose partial
derivatives all return 1).
derivatives_kwargs --
Dictionary that maps keyword parameters to their derivatives,
or None (as in derivatives_args).
Keyword parameters are defined as being those of kwargs when f
has a signature of the form f(..., **kwargs). In Python 3,
these keyword parameters also include keyword-only parameters.
Non-mapped keyword parameters are replaced automatically by
None: the wrapped function will use, if necessary, numerical
differentiation for these parameters (as with
derivatives_args).
Note that this dictionary only maps keyword *parameters* from
the *signature* of f. The way the wrapped function is called
is immaterial: for example, if f has signature f(a, b=None),
then derivatives_kwargs should be the empty dictionary, even
if the wrapped f can be called a wrapped_f(a=123, b=42).
Example (for illustration purposes only, as
uncertainties.umath.sin() runs faster than the examples that
follow): 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.
Numerically calculated derivatives are meaningless when the
function is not differentiable (e.g., math.hypot(x, y) in (x, y) =
(0, 0), and sqrt(x) in x = 0). The corresponding uncertainties are
either meaningless (case of hypot) or raise an exception when
calculated (case of sqrt). In such cases, it is recommended (but
not mandatory) to supply instead a derivative function that
returns NaN where the function is not differentiable. This
function can still numerically calculate the derivative where
defined, for instance by using the
uncertainties.core.partial_derivative() function.
The correctness of the supplied analytical derivatives an be
tested by setting them to None instead and comparing the
analytical and the numerical differentiation results.
Note on efficiency: the wrapped function assumes that f cannot
accept numbers with uncertainties as arguments. If f actually does
handle some arguments even when they have an uncertainty, the
wrapped function ignores this fact, which might lead to a
performance hit: wrapping a function that actually accepts numbers
with uncertainty is likely to make it slower.
"""
derivatives_args_index = IndexableIter(
# Automatic addition of numerical derivatives in case the
# supplied derivatives_args is shorter than the number of
# arguments in *args:
itertools.chain(derivatives_args, itertools.repeat(None)))
# Derivatives for keyword arguments (includes var-keyword
# parameters **kwargs, but also var-or-keyword parameters, and
# keyword-only parameters (Python 3):
derivatives_all_kwargs = {}
for (name, derivative) in derivatives_kwargs.items():
# Optimization: None keyword-argument derivatives are converted
# right away to derivatives (instead of doing this every time a
# None derivative is encountered when calculating derivatives):
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# When the wrapped function is called with keyword arguments that
# map to positional-or-keyword parameters, their derivative is
# looked for in derivatives_all_kwargs. We define these
# additional derivatives:
try:
argspec = getargspec(f)
except TypeError:
# Some functions do not provide meta-data about their
# arguments (see PEP 362). One cannot use keyword arguments
# for positional-or-keyword parameters with them: nothing has
# to be done:
pass
else:
# With Python 3, there is no need to handle keyword-only
# arguments (and therefore to use inspect.getfullargspec())
# because they are already handled by derivatives_kwargs.
for (index, name) in enumerate(argspec.args):
# The following test handles the case of
# positional-or-keyword parameter for which automatic
# numerical differentiation is used: when the wrapped
# function is called with a keyword argument for this
# parameter, the numerical derivative must be calculated
# with respect to the parameter name. In the other case,
# where the wrapped function is called with a positional
# argument, the derivative with respect to its index must
# be used:
derivative = derivatives_args_index[index]
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# Optimization: None derivatives for the positional arguments are
# converted to the corresponding numerical differentiation
# function (instead of doing this over and over later every time a
# None derivative is found):
none_converter = lambda index: partial_derivative(f, index)
for (index, derivative) in enumerate(
derivatives_args_index.returned_elements):
if derivative is None:
derivatives_args_index.returned_elements[index] = (
none_converter(index))
# Future None values are also automatically converted:
derivatives_args_index.none_converter = none_converter
## Wrapped function:
#! Setting the doc string after "def f_with...()" does not
# seem to work. We define it explicitly:
@set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))
def f_with_affine_output(*args, **kwargs):
########################################
# The involved random variables must first be gathered, so
# that they can be independently updated.
# The arguments that contain an uncertainty (AffineScalarFunc
# objects) are gathered, as positions or names; they will be
# replaced by their nominal value in order to calculate
# the necessary derivatives of f.
pos_w_uncert = [index for (index, value) in enumerate(args)
if isinstance(value, AffineScalarFunc)]
names_w_uncert = [key for (key, value) in kwargs.items()
if isinstance(value, AffineScalarFunc)]
########################################
# Value of f() at the nominal value of the arguments with
# uncertainty:
# The usual behavior of f() is kept, if no number with
# uncertainty is provided:
if (not pos_w_uncert) and (not names_w_uncert):
return f(*args, **kwargs)
### Nominal values of the (scalar) arguments:
# !! Possible optimization: If pos_w_uncert is empty, there
# is actually no need to create a mutable version of args and
# one could do args_values = args. However, the wrapped
# function is typically called with numbers with uncertainties
# as positional arguments (i.e., pos_w_uncert is not emtpy),
# so this "optimization" is not implemented here.
## Positional arguments:
args_values = list(args) # Now mutable: modified below
# Arguments with an uncertainty are converted to their nominal
# value:
for index in pos_w_uncert:
args_values[index] = args[index].nominal_value
## Keyword arguments:
# For efficiency reasons, kwargs is not copied. Instead, its
# values with uncertainty are modified:
# The original values with uncertainties are needed: they are
# saved in the following dictionary (which only contains
# values with uncertainty):
kwargs_uncert_values = {}
for name in names_w_uncert:
value_with_uncert = kwargs[name]
# Saving for future use:
kwargs_uncert_values[name] = value_with_uncert
# The original dictionary is modified (for efficiency reasons):
kwargs[name] = value_with_uncert.nominal_value
f_nominal_value = f(*args_values, **kwargs)
# If the value is not a float, then this code cannot provide
# the result, as it returns a UFloat, which represents a
# random real variable. This happens for instance when
# ufloat()*numpy.array() is calculated: the
# AffineScalarFunc.__mul__ operator, obtained through wrap(),
# returns a NumPy array, not a float:
if not isinstance(f_nominal_value, FLOAT_LIKE_TYPES):
return NotImplemented
########################################
# Calculation of the linear part of the function value,
# defined by (coefficient, argument) pairs, where 'argument'
# is an AffineScalarFunc (for all AffineScalarFunc found as
# argument of f):
linear_part = []
for pos in pos_w_uncert:
linear_part.append((
# Coefficient:
derivatives_args_index[pos](*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
args[pos]._linear_part))
for name in names_w_uncert:
# Optimization: caching of the automatic numerical
# derivatives for keyword arguments that are
# discovered. This gives a speedup when the original
# function is called repeatedly with the same keyword
# arguments:
derivative = derivatives_all_kwargs.setdefault(
name,
# Derivative never needed before:
partial_derivative(f, name))
linear_part.append((
# Coefficient:
derivative(*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
kwargs_uncert_values[name]._linear_part))
# The function now returns the necessary linear approximation
# to the function:
return AffineScalarFunc(
f_nominal_value, LinearCombination(linear_part))
f_with_affine_output = set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))(f_with_affine_output)
# It is easier to work with f_with_affine_output, which represents
# a wrapped version of 'f', when it bears the same name as 'f':
# ! __name__ is read-only, in Python 2.3:
f_with_affine_output.name = f.__name__
return f_with_affine_output
|
(*args, **kwargs)
|
61,723 |
uncertainties.core
|
f_with_affine_output
|
Version of __pos__(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
+self
|
def wrap(f, derivatives_args=[], derivatives_kwargs={}):
"""
Wraps a function f into a function that also accepts numbers with
uncertainties (UFloat objects); the wrapped function returns the
value of f with the correct uncertainty and correlations. The
wrapped function is intended to be used as a drop-in replacement
for the original function: they can be called in the exact same
way, the only difference being that numbers with uncertainties can
be given to the wrapped function where f accepts float arguments.
Doing so may be necessary when function f cannot be expressed
analytically (with uncertainties-compatible operators and
functions like +, *, umath.sin(), etc.).
f must return a float-like (i.e. a float, an int, etc., not a
list, etc.), unless when called with no number with
uncertainty. This is because the wrapped function generally
returns numbers with uncertainties: they represent a probability
distribution over the real numbers.
If the wrapped function is called with no argument that has an
uncertainty, the value of f is returned.
Parameters: the derivatives_* parameters can be used for defining
some of the partial derivatives of f. All the (non-None)
derivatives must have the same signature as f.
derivatives_args --
Iterable that, when iterated over, returns either derivatives
(functions) or None. derivatives_args can in particular be a
simple sequence (list or tuple) that gives the derivatives of
the first positional parameters of f.
Each function must be the partial derivative of f with respect
to the corresponding positional parameters. These functions
take the same arguments as f.
The positional parameters of a function are usually
positional-or-keyword parameters like in the call func(a,
b=None). However, they also include var-positional parameters
given through the func(a, b, *args) *args syntax. In the last
example, derivatives_args can be an iterable that returns the
derivative with respect to a, b and then to each optional
argument in args.
A value of None (instead of a function) obtained when
iterating over derivatives_args is automatically replaced by
the relevant numerical derivative. This derivative is not used
if the corresponding argument is not a number with
uncertainty. A None value can therefore be used for non-scalar
arguments of f (like string arguments).
If the derivatives_args iterable yields fewer derivatives than
needed, wrap() automatically sets the remaining unspecified
derivatives to None (i.e. to the automatic numerical
calculation of derivatives).
An indefinite number of derivatives can be specified by having
derivatives_args be an infinite iterator; this can for
instance be used for specifying the derivatives of functions
with a undefined number of argument (like sum(), whose partial
derivatives all return 1).
derivatives_kwargs --
Dictionary that maps keyword parameters to their derivatives,
or None (as in derivatives_args).
Keyword parameters are defined as being those of kwargs when f
has a signature of the form f(..., **kwargs). In Python 3,
these keyword parameters also include keyword-only parameters.
Non-mapped keyword parameters are replaced automatically by
None: the wrapped function will use, if necessary, numerical
differentiation for these parameters (as with
derivatives_args).
Note that this dictionary only maps keyword *parameters* from
the *signature* of f. The way the wrapped function is called
is immaterial: for example, if f has signature f(a, b=None),
then derivatives_kwargs should be the empty dictionary, even
if the wrapped f can be called a wrapped_f(a=123, b=42).
Example (for illustration purposes only, as
uncertainties.umath.sin() runs faster than the examples that
follow): 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.
Numerically calculated derivatives are meaningless when the
function is not differentiable (e.g., math.hypot(x, y) in (x, y) =
(0, 0), and sqrt(x) in x = 0). The corresponding uncertainties are
either meaningless (case of hypot) or raise an exception when
calculated (case of sqrt). In such cases, it is recommended (but
not mandatory) to supply instead a derivative function that
returns NaN where the function is not differentiable. This
function can still numerically calculate the derivative where
defined, for instance by using the
uncertainties.core.partial_derivative() function.
The correctness of the supplied analytical derivatives an be
tested by setting them to None instead and comparing the
analytical and the numerical differentiation results.
Note on efficiency: the wrapped function assumes that f cannot
accept numbers with uncertainties as arguments. If f actually does
handle some arguments even when they have an uncertainty, the
wrapped function ignores this fact, which might lead to a
performance hit: wrapping a function that actually accepts numbers
with uncertainty is likely to make it slower.
"""
derivatives_args_index = IndexableIter(
# Automatic addition of numerical derivatives in case the
# supplied derivatives_args is shorter than the number of
# arguments in *args:
itertools.chain(derivatives_args, itertools.repeat(None)))
# Derivatives for keyword arguments (includes var-keyword
# parameters **kwargs, but also var-or-keyword parameters, and
# keyword-only parameters (Python 3):
derivatives_all_kwargs = {}
for (name, derivative) in derivatives_kwargs.items():
# Optimization: None keyword-argument derivatives are converted
# right away to derivatives (instead of doing this every time a
# None derivative is encountered when calculating derivatives):
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# When the wrapped function is called with keyword arguments that
# map to positional-or-keyword parameters, their derivative is
# looked for in derivatives_all_kwargs. We define these
# additional derivatives:
try:
argspec = getargspec(f)
except TypeError:
# Some functions do not provide meta-data about their
# arguments (see PEP 362). One cannot use keyword arguments
# for positional-or-keyword parameters with them: nothing has
# to be done:
pass
else:
# With Python 3, there is no need to handle keyword-only
# arguments (and therefore to use inspect.getfullargspec())
# because they are already handled by derivatives_kwargs.
for (index, name) in enumerate(argspec.args):
# The following test handles the case of
# positional-or-keyword parameter for which automatic
# numerical differentiation is used: when the wrapped
# function is called with a keyword argument for this
# parameter, the numerical derivative must be calculated
# with respect to the parameter name. In the other case,
# where the wrapped function is called with a positional
# argument, the derivative with respect to its index must
# be used:
derivative = derivatives_args_index[index]
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# Optimization: None derivatives for the positional arguments are
# converted to the corresponding numerical differentiation
# function (instead of doing this over and over later every time a
# None derivative is found):
none_converter = lambda index: partial_derivative(f, index)
for (index, derivative) in enumerate(
derivatives_args_index.returned_elements):
if derivative is None:
derivatives_args_index.returned_elements[index] = (
none_converter(index))
# Future None values are also automatically converted:
derivatives_args_index.none_converter = none_converter
## Wrapped function:
#! Setting the doc string after "def f_with...()" does not
# seem to work. We define it explicitly:
@set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))
def f_with_affine_output(*args, **kwargs):
########################################
# The involved random variables must first be gathered, so
# that they can be independently updated.
# The arguments that contain an uncertainty (AffineScalarFunc
# objects) are gathered, as positions or names; they will be
# replaced by their nominal value in order to calculate
# the necessary derivatives of f.
pos_w_uncert = [index for (index, value) in enumerate(args)
if isinstance(value, AffineScalarFunc)]
names_w_uncert = [key for (key, value) in kwargs.items()
if isinstance(value, AffineScalarFunc)]
########################################
# Value of f() at the nominal value of the arguments with
# uncertainty:
# The usual behavior of f() is kept, if no number with
# uncertainty is provided:
if (not pos_w_uncert) and (not names_w_uncert):
return f(*args, **kwargs)
### Nominal values of the (scalar) arguments:
# !! Possible optimization: If pos_w_uncert is empty, there
# is actually no need to create a mutable version of args and
# one could do args_values = args. However, the wrapped
# function is typically called with numbers with uncertainties
# as positional arguments (i.e., pos_w_uncert is not emtpy),
# so this "optimization" is not implemented here.
## Positional arguments:
args_values = list(args) # Now mutable: modified below
# Arguments with an uncertainty are converted to their nominal
# value:
for index in pos_w_uncert:
args_values[index] = args[index].nominal_value
## Keyword arguments:
# For efficiency reasons, kwargs is not copied. Instead, its
# values with uncertainty are modified:
# The original values with uncertainties are needed: they are
# saved in the following dictionary (which only contains
# values with uncertainty):
kwargs_uncert_values = {}
for name in names_w_uncert:
value_with_uncert = kwargs[name]
# Saving for future use:
kwargs_uncert_values[name] = value_with_uncert
# The original dictionary is modified (for efficiency reasons):
kwargs[name] = value_with_uncert.nominal_value
f_nominal_value = f(*args_values, **kwargs)
# If the value is not a float, then this code cannot provide
# the result, as it returns a UFloat, which represents a
# random real variable. This happens for instance when
# ufloat()*numpy.array() is calculated: the
# AffineScalarFunc.__mul__ operator, obtained through wrap(),
# returns a NumPy array, not a float:
if not isinstance(f_nominal_value, FLOAT_LIKE_TYPES):
return NotImplemented
########################################
# Calculation of the linear part of the function value,
# defined by (coefficient, argument) pairs, where 'argument'
# is an AffineScalarFunc (for all AffineScalarFunc found as
# argument of f):
linear_part = []
for pos in pos_w_uncert:
linear_part.append((
# Coefficient:
derivatives_args_index[pos](*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
args[pos]._linear_part))
for name in names_w_uncert:
# Optimization: caching of the automatic numerical
# derivatives for keyword arguments that are
# discovered. This gives a speedup when the original
# function is called repeatedly with the same keyword
# arguments:
derivative = derivatives_all_kwargs.setdefault(
name,
# Derivative never needed before:
partial_derivative(f, name))
linear_part.append((
# Coefficient:
derivative(*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
kwargs_uncert_values[name]._linear_part))
# The function now returns the necessary linear approximation
# to the function:
return AffineScalarFunc(
f_nominal_value, LinearCombination(linear_part))
f_with_affine_output = set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))(f_with_affine_output)
# It is easier to work with f_with_affine_output, which represents
# a wrapped version of 'f', when it bears the same name as 'f':
# ! __name__ is read-only, in Python 2.3:
f_with_affine_output.name = f.__name__
return f_with_affine_output
|
(*args, **kwargs)
|
61,724 |
uncertainties.core
|
f_with_affine_output
|
Version of no_complex_func(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
None
|
def wrap(f, derivatives_args=[], derivatives_kwargs={}):
"""
Wraps a function f into a function that also accepts numbers with
uncertainties (UFloat objects); the wrapped function returns the
value of f with the correct uncertainty and correlations. The
wrapped function is intended to be used as a drop-in replacement
for the original function: they can be called in the exact same
way, the only difference being that numbers with uncertainties can
be given to the wrapped function where f accepts float arguments.
Doing so may be necessary when function f cannot be expressed
analytically (with uncertainties-compatible operators and
functions like +, *, umath.sin(), etc.).
f must return a float-like (i.e. a float, an int, etc., not a
list, etc.), unless when called with no number with
uncertainty. This is because the wrapped function generally
returns numbers with uncertainties: they represent a probability
distribution over the real numbers.
If the wrapped function is called with no argument that has an
uncertainty, the value of f is returned.
Parameters: the derivatives_* parameters can be used for defining
some of the partial derivatives of f. All the (non-None)
derivatives must have the same signature as f.
derivatives_args --
Iterable that, when iterated over, returns either derivatives
(functions) or None. derivatives_args can in particular be a
simple sequence (list or tuple) that gives the derivatives of
the first positional parameters of f.
Each function must be the partial derivative of f with respect
to the corresponding positional parameters. These functions
take the same arguments as f.
The positional parameters of a function are usually
positional-or-keyword parameters like in the call func(a,
b=None). However, they also include var-positional parameters
given through the func(a, b, *args) *args syntax. In the last
example, derivatives_args can be an iterable that returns the
derivative with respect to a, b and then to each optional
argument in args.
A value of None (instead of a function) obtained when
iterating over derivatives_args is automatically replaced by
the relevant numerical derivative. This derivative is not used
if the corresponding argument is not a number with
uncertainty. A None value can therefore be used for non-scalar
arguments of f (like string arguments).
If the derivatives_args iterable yields fewer derivatives than
needed, wrap() automatically sets the remaining unspecified
derivatives to None (i.e. to the automatic numerical
calculation of derivatives).
An indefinite number of derivatives can be specified by having
derivatives_args be an infinite iterator; this can for
instance be used for specifying the derivatives of functions
with a undefined number of argument (like sum(), whose partial
derivatives all return 1).
derivatives_kwargs --
Dictionary that maps keyword parameters to their derivatives,
or None (as in derivatives_args).
Keyword parameters are defined as being those of kwargs when f
has a signature of the form f(..., **kwargs). In Python 3,
these keyword parameters also include keyword-only parameters.
Non-mapped keyword parameters are replaced automatically by
None: the wrapped function will use, if necessary, numerical
differentiation for these parameters (as with
derivatives_args).
Note that this dictionary only maps keyword *parameters* from
the *signature* of f. The way the wrapped function is called
is immaterial: for example, if f has signature f(a, b=None),
then derivatives_kwargs should be the empty dictionary, even
if the wrapped f can be called a wrapped_f(a=123, b=42).
Example (for illustration purposes only, as
uncertainties.umath.sin() runs faster than the examples that
follow): 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.
Numerically calculated derivatives are meaningless when the
function is not differentiable (e.g., math.hypot(x, y) in (x, y) =
(0, 0), and sqrt(x) in x = 0). The corresponding uncertainties are
either meaningless (case of hypot) or raise an exception when
calculated (case of sqrt). In such cases, it is recommended (but
not mandatory) to supply instead a derivative function that
returns NaN where the function is not differentiable. This
function can still numerically calculate the derivative where
defined, for instance by using the
uncertainties.core.partial_derivative() function.
The correctness of the supplied analytical derivatives an be
tested by setting them to None instead and comparing the
analytical and the numerical differentiation results.
Note on efficiency: the wrapped function assumes that f cannot
accept numbers with uncertainties as arguments. If f actually does
handle some arguments even when they have an uncertainty, the
wrapped function ignores this fact, which might lead to a
performance hit: wrapping a function that actually accepts numbers
with uncertainty is likely to make it slower.
"""
derivatives_args_index = IndexableIter(
# Automatic addition of numerical derivatives in case the
# supplied derivatives_args is shorter than the number of
# arguments in *args:
itertools.chain(derivatives_args, itertools.repeat(None)))
# Derivatives for keyword arguments (includes var-keyword
# parameters **kwargs, but also var-or-keyword parameters, and
# keyword-only parameters (Python 3):
derivatives_all_kwargs = {}
for (name, derivative) in derivatives_kwargs.items():
# Optimization: None keyword-argument derivatives are converted
# right away to derivatives (instead of doing this every time a
# None derivative is encountered when calculating derivatives):
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# When the wrapped function is called with keyword arguments that
# map to positional-or-keyword parameters, their derivative is
# looked for in derivatives_all_kwargs. We define these
# additional derivatives:
try:
argspec = getargspec(f)
except TypeError:
# Some functions do not provide meta-data about their
# arguments (see PEP 362). One cannot use keyword arguments
# for positional-or-keyword parameters with them: nothing has
# to be done:
pass
else:
# With Python 3, there is no need to handle keyword-only
# arguments (and therefore to use inspect.getfullargspec())
# because they are already handled by derivatives_kwargs.
for (index, name) in enumerate(argspec.args):
# The following test handles the case of
# positional-or-keyword parameter for which automatic
# numerical differentiation is used: when the wrapped
# function is called with a keyword argument for this
# parameter, the numerical derivative must be calculated
# with respect to the parameter name. In the other case,
# where the wrapped function is called with a positional
# argument, the derivative with respect to its index must
# be used:
derivative = derivatives_args_index[index]
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# Optimization: None derivatives for the positional arguments are
# converted to the corresponding numerical differentiation
# function (instead of doing this over and over later every time a
# None derivative is found):
none_converter = lambda index: partial_derivative(f, index)
for (index, derivative) in enumerate(
derivatives_args_index.returned_elements):
if derivative is None:
derivatives_args_index.returned_elements[index] = (
none_converter(index))
# Future None values are also automatically converted:
derivatives_args_index.none_converter = none_converter
## Wrapped function:
#! Setting the doc string after "def f_with...()" does not
# seem to work. We define it explicitly:
@set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))
def f_with_affine_output(*args, **kwargs):
########################################
# The involved random variables must first be gathered, so
# that they can be independently updated.
# The arguments that contain an uncertainty (AffineScalarFunc
# objects) are gathered, as positions or names; they will be
# replaced by their nominal value in order to calculate
# the necessary derivatives of f.
pos_w_uncert = [index for (index, value) in enumerate(args)
if isinstance(value, AffineScalarFunc)]
names_w_uncert = [key for (key, value) in kwargs.items()
if isinstance(value, AffineScalarFunc)]
########################################
# Value of f() at the nominal value of the arguments with
# uncertainty:
# The usual behavior of f() is kept, if no number with
# uncertainty is provided:
if (not pos_w_uncert) and (not names_w_uncert):
return f(*args, **kwargs)
### Nominal values of the (scalar) arguments:
# !! Possible optimization: If pos_w_uncert is empty, there
# is actually no need to create a mutable version of args and
# one could do args_values = args. However, the wrapped
# function is typically called with numbers with uncertainties
# as positional arguments (i.e., pos_w_uncert is not emtpy),
# so this "optimization" is not implemented here.
## Positional arguments:
args_values = list(args) # Now mutable: modified below
# Arguments with an uncertainty are converted to their nominal
# value:
for index in pos_w_uncert:
args_values[index] = args[index].nominal_value
## Keyword arguments:
# For efficiency reasons, kwargs is not copied. Instead, its
# values with uncertainty are modified:
# The original values with uncertainties are needed: they are
# saved in the following dictionary (which only contains
# values with uncertainty):
kwargs_uncert_values = {}
for name in names_w_uncert:
value_with_uncert = kwargs[name]
# Saving for future use:
kwargs_uncert_values[name] = value_with_uncert
# The original dictionary is modified (for efficiency reasons):
kwargs[name] = value_with_uncert.nominal_value
f_nominal_value = f(*args_values, **kwargs)
# If the value is not a float, then this code cannot provide
# the result, as it returns a UFloat, which represents a
# random real variable. This happens for instance when
# ufloat()*numpy.array() is calculated: the
# AffineScalarFunc.__mul__ operator, obtained through wrap(),
# returns a NumPy array, not a float:
if not isinstance(f_nominal_value, FLOAT_LIKE_TYPES):
return NotImplemented
########################################
# Calculation of the linear part of the function value,
# defined by (coefficient, argument) pairs, where 'argument'
# is an AffineScalarFunc (for all AffineScalarFunc found as
# argument of f):
linear_part = []
for pos in pos_w_uncert:
linear_part.append((
# Coefficient:
derivatives_args_index[pos](*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
args[pos]._linear_part))
for name in names_w_uncert:
# Optimization: caching of the automatic numerical
# derivatives for keyword arguments that are
# discovered. This gives a speedup when the original
# function is called repeatedly with the same keyword
# arguments:
derivative = derivatives_all_kwargs.setdefault(
name,
# Derivative never needed before:
partial_derivative(f, name))
linear_part.append((
# Coefficient:
derivative(*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
kwargs_uncert_values[name]._linear_part))
# The function now returns the necessary linear approximation
# to the function:
return AffineScalarFunc(
f_nominal_value, LinearCombination(linear_part))
f_with_affine_output = set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))(f_with_affine_output)
# It is easier to work with f_with_affine_output, which represents
# a wrapped version of 'f', when it bears the same name as 'f':
# ! __name__ is read-only, in Python 2.3:
f_with_affine_output.name = f.__name__
return f_with_affine_output
|
(*args, **kwargs)
|
61,725 |
uncertainties.core
|
f_with_affine_output
|
Version of __radd__(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
Return value+self.
|
def wrap(f, derivatives_args=[], derivatives_kwargs={}):
"""
Wraps a function f into a function that also accepts numbers with
uncertainties (UFloat objects); the wrapped function returns the
value of f with the correct uncertainty and correlations. The
wrapped function is intended to be used as a drop-in replacement
for the original function: they can be called in the exact same
way, the only difference being that numbers with uncertainties can
be given to the wrapped function where f accepts float arguments.
Doing so may be necessary when function f cannot be expressed
analytically (with uncertainties-compatible operators and
functions like +, *, umath.sin(), etc.).
f must return a float-like (i.e. a float, an int, etc., not a
list, etc.), unless when called with no number with
uncertainty. This is because the wrapped function generally
returns numbers with uncertainties: they represent a probability
distribution over the real numbers.
If the wrapped function is called with no argument that has an
uncertainty, the value of f is returned.
Parameters: the derivatives_* parameters can be used for defining
some of the partial derivatives of f. All the (non-None)
derivatives must have the same signature as f.
derivatives_args --
Iterable that, when iterated over, returns either derivatives
(functions) or None. derivatives_args can in particular be a
simple sequence (list or tuple) that gives the derivatives of
the first positional parameters of f.
Each function must be the partial derivative of f with respect
to the corresponding positional parameters. These functions
take the same arguments as f.
The positional parameters of a function are usually
positional-or-keyword parameters like in the call func(a,
b=None). However, they also include var-positional parameters
given through the func(a, b, *args) *args syntax. In the last
example, derivatives_args can be an iterable that returns the
derivative with respect to a, b and then to each optional
argument in args.
A value of None (instead of a function) obtained when
iterating over derivatives_args is automatically replaced by
the relevant numerical derivative. This derivative is not used
if the corresponding argument is not a number with
uncertainty. A None value can therefore be used for non-scalar
arguments of f (like string arguments).
If the derivatives_args iterable yields fewer derivatives than
needed, wrap() automatically sets the remaining unspecified
derivatives to None (i.e. to the automatic numerical
calculation of derivatives).
An indefinite number of derivatives can be specified by having
derivatives_args be an infinite iterator; this can for
instance be used for specifying the derivatives of functions
with a undefined number of argument (like sum(), whose partial
derivatives all return 1).
derivatives_kwargs --
Dictionary that maps keyword parameters to their derivatives,
or None (as in derivatives_args).
Keyword parameters are defined as being those of kwargs when f
has a signature of the form f(..., **kwargs). In Python 3,
these keyword parameters also include keyword-only parameters.
Non-mapped keyword parameters are replaced automatically by
None: the wrapped function will use, if necessary, numerical
differentiation for these parameters (as with
derivatives_args).
Note that this dictionary only maps keyword *parameters* from
the *signature* of f. The way the wrapped function is called
is immaterial: for example, if f has signature f(a, b=None),
then derivatives_kwargs should be the empty dictionary, even
if the wrapped f can be called a wrapped_f(a=123, b=42).
Example (for illustration purposes only, as
uncertainties.umath.sin() runs faster than the examples that
follow): 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.
Numerically calculated derivatives are meaningless when the
function is not differentiable (e.g., math.hypot(x, y) in (x, y) =
(0, 0), and sqrt(x) in x = 0). The corresponding uncertainties are
either meaningless (case of hypot) or raise an exception when
calculated (case of sqrt). In such cases, it is recommended (but
not mandatory) to supply instead a derivative function that
returns NaN where the function is not differentiable. This
function can still numerically calculate the derivative where
defined, for instance by using the
uncertainties.core.partial_derivative() function.
The correctness of the supplied analytical derivatives an be
tested by setting them to None instead and comparing the
analytical and the numerical differentiation results.
Note on efficiency: the wrapped function assumes that f cannot
accept numbers with uncertainties as arguments. If f actually does
handle some arguments even when they have an uncertainty, the
wrapped function ignores this fact, which might lead to a
performance hit: wrapping a function that actually accepts numbers
with uncertainty is likely to make it slower.
"""
derivatives_args_index = IndexableIter(
# Automatic addition of numerical derivatives in case the
# supplied derivatives_args is shorter than the number of
# arguments in *args:
itertools.chain(derivatives_args, itertools.repeat(None)))
# Derivatives for keyword arguments (includes var-keyword
# parameters **kwargs, but also var-or-keyword parameters, and
# keyword-only parameters (Python 3):
derivatives_all_kwargs = {}
for (name, derivative) in derivatives_kwargs.items():
# Optimization: None keyword-argument derivatives are converted
# right away to derivatives (instead of doing this every time a
# None derivative is encountered when calculating derivatives):
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# When the wrapped function is called with keyword arguments that
# map to positional-or-keyword parameters, their derivative is
# looked for in derivatives_all_kwargs. We define these
# additional derivatives:
try:
argspec = getargspec(f)
except TypeError:
# Some functions do not provide meta-data about their
# arguments (see PEP 362). One cannot use keyword arguments
# for positional-or-keyword parameters with them: nothing has
# to be done:
pass
else:
# With Python 3, there is no need to handle keyword-only
# arguments (and therefore to use inspect.getfullargspec())
# because they are already handled by derivatives_kwargs.
for (index, name) in enumerate(argspec.args):
# The following test handles the case of
# positional-or-keyword parameter for which automatic
# numerical differentiation is used: when the wrapped
# function is called with a keyword argument for this
# parameter, the numerical derivative must be calculated
# with respect to the parameter name. In the other case,
# where the wrapped function is called with a positional
# argument, the derivative with respect to its index must
# be used:
derivative = derivatives_args_index[index]
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# Optimization: None derivatives for the positional arguments are
# converted to the corresponding numerical differentiation
# function (instead of doing this over and over later every time a
# None derivative is found):
none_converter = lambda index: partial_derivative(f, index)
for (index, derivative) in enumerate(
derivatives_args_index.returned_elements):
if derivative is None:
derivatives_args_index.returned_elements[index] = (
none_converter(index))
# Future None values are also automatically converted:
derivatives_args_index.none_converter = none_converter
## Wrapped function:
#! Setting the doc string after "def f_with...()" does not
# seem to work. We define it explicitly:
@set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))
def f_with_affine_output(*args, **kwargs):
########################################
# The involved random variables must first be gathered, so
# that they can be independently updated.
# The arguments that contain an uncertainty (AffineScalarFunc
# objects) are gathered, as positions or names; they will be
# replaced by their nominal value in order to calculate
# the necessary derivatives of f.
pos_w_uncert = [index for (index, value) in enumerate(args)
if isinstance(value, AffineScalarFunc)]
names_w_uncert = [key for (key, value) in kwargs.items()
if isinstance(value, AffineScalarFunc)]
########################################
# Value of f() at the nominal value of the arguments with
# uncertainty:
# The usual behavior of f() is kept, if no number with
# uncertainty is provided:
if (not pos_w_uncert) and (not names_w_uncert):
return f(*args, **kwargs)
### Nominal values of the (scalar) arguments:
# !! Possible optimization: If pos_w_uncert is empty, there
# is actually no need to create a mutable version of args and
# one could do args_values = args. However, the wrapped
# function is typically called with numbers with uncertainties
# as positional arguments (i.e., pos_w_uncert is not emtpy),
# so this "optimization" is not implemented here.
## Positional arguments:
args_values = list(args) # Now mutable: modified below
# Arguments with an uncertainty are converted to their nominal
# value:
for index in pos_w_uncert:
args_values[index] = args[index].nominal_value
## Keyword arguments:
# For efficiency reasons, kwargs is not copied. Instead, its
# values with uncertainty are modified:
# The original values with uncertainties are needed: they are
# saved in the following dictionary (which only contains
# values with uncertainty):
kwargs_uncert_values = {}
for name in names_w_uncert:
value_with_uncert = kwargs[name]
# Saving for future use:
kwargs_uncert_values[name] = value_with_uncert
# The original dictionary is modified (for efficiency reasons):
kwargs[name] = value_with_uncert.nominal_value
f_nominal_value = f(*args_values, **kwargs)
# If the value is not a float, then this code cannot provide
# the result, as it returns a UFloat, which represents a
# random real variable. This happens for instance when
# ufloat()*numpy.array() is calculated: the
# AffineScalarFunc.__mul__ operator, obtained through wrap(),
# returns a NumPy array, not a float:
if not isinstance(f_nominal_value, FLOAT_LIKE_TYPES):
return NotImplemented
########################################
# Calculation of the linear part of the function value,
# defined by (coefficient, argument) pairs, where 'argument'
# is an AffineScalarFunc (for all AffineScalarFunc found as
# argument of f):
linear_part = []
for pos in pos_w_uncert:
linear_part.append((
# Coefficient:
derivatives_args_index[pos](*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
args[pos]._linear_part))
for name in names_w_uncert:
# Optimization: caching of the automatic numerical
# derivatives for keyword arguments that are
# discovered. This gives a speedup when the original
# function is called repeatedly with the same keyword
# arguments:
derivative = derivatives_all_kwargs.setdefault(
name,
# Derivative never needed before:
partial_derivative(f, name))
linear_part.append((
# Coefficient:
derivative(*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
kwargs_uncert_values[name]._linear_part))
# The function now returns the necessary linear approximation
# to the function:
return AffineScalarFunc(
f_nominal_value, LinearCombination(linear_part))
f_with_affine_output = set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))(f_with_affine_output)
# It is easier to work with f_with_affine_output, which represents
# a wrapped version of 'f', when it bears the same name as 'f':
# ! __name__ is read-only, in Python 2.3:
f_with_affine_output.name = f.__name__
return f_with_affine_output
|
(*args, **kwargs)
|
61,726 |
uncertainties.core
|
__repr__
| null |
def __repr__(self):
# Not putting spaces around "+/-" helps with arrays of
# Variable, as each value with an uncertainty is a
# block of signs (otherwise, the standard deviation can be
# mistaken for another element of the array).
std_dev = self.std_dev # Optimization, since std_dev is calculated
# A zero standard deviation is printed because otherwise,
# ufloat_fromstr() does not correctly parse back the value
# ("1.23" is interpreted as "1.23(1)"):
if std_dev:
std_dev_str = repr(std_dev)
else:
std_dev_str = '0'
return "%r+/-%s" % (self.nominal_value, std_dev_str)
|
(self)
|
61,727 |
uncertainties.core
|
f_with_affine_output
|
Version of __rfloordiv__(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
Return value//self.
|
def wrap(f, derivatives_args=[], derivatives_kwargs={}):
"""
Wraps a function f into a function that also accepts numbers with
uncertainties (UFloat objects); the wrapped function returns the
value of f with the correct uncertainty and correlations. The
wrapped function is intended to be used as a drop-in replacement
for the original function: they can be called in the exact same
way, the only difference being that numbers with uncertainties can
be given to the wrapped function where f accepts float arguments.
Doing so may be necessary when function f cannot be expressed
analytically (with uncertainties-compatible operators and
functions like +, *, umath.sin(), etc.).
f must return a float-like (i.e. a float, an int, etc., not a
list, etc.), unless when called with no number with
uncertainty. This is because the wrapped function generally
returns numbers with uncertainties: they represent a probability
distribution over the real numbers.
If the wrapped function is called with no argument that has an
uncertainty, the value of f is returned.
Parameters: the derivatives_* parameters can be used for defining
some of the partial derivatives of f. All the (non-None)
derivatives must have the same signature as f.
derivatives_args --
Iterable that, when iterated over, returns either derivatives
(functions) or None. derivatives_args can in particular be a
simple sequence (list or tuple) that gives the derivatives of
the first positional parameters of f.
Each function must be the partial derivative of f with respect
to the corresponding positional parameters. These functions
take the same arguments as f.
The positional parameters of a function are usually
positional-or-keyword parameters like in the call func(a,
b=None). However, they also include var-positional parameters
given through the func(a, b, *args) *args syntax. In the last
example, derivatives_args can be an iterable that returns the
derivative with respect to a, b and then to each optional
argument in args.
A value of None (instead of a function) obtained when
iterating over derivatives_args is automatically replaced by
the relevant numerical derivative. This derivative is not used
if the corresponding argument is not a number with
uncertainty. A None value can therefore be used for non-scalar
arguments of f (like string arguments).
If the derivatives_args iterable yields fewer derivatives than
needed, wrap() automatically sets the remaining unspecified
derivatives to None (i.e. to the automatic numerical
calculation of derivatives).
An indefinite number of derivatives can be specified by having
derivatives_args be an infinite iterator; this can for
instance be used for specifying the derivatives of functions
with a undefined number of argument (like sum(), whose partial
derivatives all return 1).
derivatives_kwargs --
Dictionary that maps keyword parameters to their derivatives,
or None (as in derivatives_args).
Keyword parameters are defined as being those of kwargs when f
has a signature of the form f(..., **kwargs). In Python 3,
these keyword parameters also include keyword-only parameters.
Non-mapped keyword parameters are replaced automatically by
None: the wrapped function will use, if necessary, numerical
differentiation for these parameters (as with
derivatives_args).
Note that this dictionary only maps keyword *parameters* from
the *signature* of f. The way the wrapped function is called
is immaterial: for example, if f has signature f(a, b=None),
then derivatives_kwargs should be the empty dictionary, even
if the wrapped f can be called a wrapped_f(a=123, b=42).
Example (for illustration purposes only, as
uncertainties.umath.sin() runs faster than the examples that
follow): 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.
Numerically calculated derivatives are meaningless when the
function is not differentiable (e.g., math.hypot(x, y) in (x, y) =
(0, 0), and sqrt(x) in x = 0). The corresponding uncertainties are
either meaningless (case of hypot) or raise an exception when
calculated (case of sqrt). In such cases, it is recommended (but
not mandatory) to supply instead a derivative function that
returns NaN where the function is not differentiable. This
function can still numerically calculate the derivative where
defined, for instance by using the
uncertainties.core.partial_derivative() function.
The correctness of the supplied analytical derivatives an be
tested by setting them to None instead and comparing the
analytical and the numerical differentiation results.
Note on efficiency: the wrapped function assumes that f cannot
accept numbers with uncertainties as arguments. If f actually does
handle some arguments even when they have an uncertainty, the
wrapped function ignores this fact, which might lead to a
performance hit: wrapping a function that actually accepts numbers
with uncertainty is likely to make it slower.
"""
derivatives_args_index = IndexableIter(
# Automatic addition of numerical derivatives in case the
# supplied derivatives_args is shorter than the number of
# arguments in *args:
itertools.chain(derivatives_args, itertools.repeat(None)))
# Derivatives for keyword arguments (includes var-keyword
# parameters **kwargs, but also var-or-keyword parameters, and
# keyword-only parameters (Python 3):
derivatives_all_kwargs = {}
for (name, derivative) in derivatives_kwargs.items():
# Optimization: None keyword-argument derivatives are converted
# right away to derivatives (instead of doing this every time a
# None derivative is encountered when calculating derivatives):
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# When the wrapped function is called with keyword arguments that
# map to positional-or-keyword parameters, their derivative is
# looked for in derivatives_all_kwargs. We define these
# additional derivatives:
try:
argspec = getargspec(f)
except TypeError:
# Some functions do not provide meta-data about their
# arguments (see PEP 362). One cannot use keyword arguments
# for positional-or-keyword parameters with them: nothing has
# to be done:
pass
else:
# With Python 3, there is no need to handle keyword-only
# arguments (and therefore to use inspect.getfullargspec())
# because they are already handled by derivatives_kwargs.
for (index, name) in enumerate(argspec.args):
# The following test handles the case of
# positional-or-keyword parameter for which automatic
# numerical differentiation is used: when the wrapped
# function is called with a keyword argument for this
# parameter, the numerical derivative must be calculated
# with respect to the parameter name. In the other case,
# where the wrapped function is called with a positional
# argument, the derivative with respect to its index must
# be used:
derivative = derivatives_args_index[index]
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# Optimization: None derivatives for the positional arguments are
# converted to the corresponding numerical differentiation
# function (instead of doing this over and over later every time a
# None derivative is found):
none_converter = lambda index: partial_derivative(f, index)
for (index, derivative) in enumerate(
derivatives_args_index.returned_elements):
if derivative is None:
derivatives_args_index.returned_elements[index] = (
none_converter(index))
# Future None values are also automatically converted:
derivatives_args_index.none_converter = none_converter
## Wrapped function:
#! Setting the doc string after "def f_with...()" does not
# seem to work. We define it explicitly:
@set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))
def f_with_affine_output(*args, **kwargs):
########################################
# The involved random variables must first be gathered, so
# that they can be independently updated.
# The arguments that contain an uncertainty (AffineScalarFunc
# objects) are gathered, as positions or names; they will be
# replaced by their nominal value in order to calculate
# the necessary derivatives of f.
pos_w_uncert = [index for (index, value) in enumerate(args)
if isinstance(value, AffineScalarFunc)]
names_w_uncert = [key for (key, value) in kwargs.items()
if isinstance(value, AffineScalarFunc)]
########################################
# Value of f() at the nominal value of the arguments with
# uncertainty:
# The usual behavior of f() is kept, if no number with
# uncertainty is provided:
if (not pos_w_uncert) and (not names_w_uncert):
return f(*args, **kwargs)
### Nominal values of the (scalar) arguments:
# !! Possible optimization: If pos_w_uncert is empty, there
# is actually no need to create a mutable version of args and
# one could do args_values = args. However, the wrapped
# function is typically called with numbers with uncertainties
# as positional arguments (i.e., pos_w_uncert is not emtpy),
# so this "optimization" is not implemented here.
## Positional arguments:
args_values = list(args) # Now mutable: modified below
# Arguments with an uncertainty are converted to their nominal
# value:
for index in pos_w_uncert:
args_values[index] = args[index].nominal_value
## Keyword arguments:
# For efficiency reasons, kwargs is not copied. Instead, its
# values with uncertainty are modified:
# The original values with uncertainties are needed: they are
# saved in the following dictionary (which only contains
# values with uncertainty):
kwargs_uncert_values = {}
for name in names_w_uncert:
value_with_uncert = kwargs[name]
# Saving for future use:
kwargs_uncert_values[name] = value_with_uncert
# The original dictionary is modified (for efficiency reasons):
kwargs[name] = value_with_uncert.nominal_value
f_nominal_value = f(*args_values, **kwargs)
# If the value is not a float, then this code cannot provide
# the result, as it returns a UFloat, which represents a
# random real variable. This happens for instance when
# ufloat()*numpy.array() is calculated: the
# AffineScalarFunc.__mul__ operator, obtained through wrap(),
# returns a NumPy array, not a float:
if not isinstance(f_nominal_value, FLOAT_LIKE_TYPES):
return NotImplemented
########################################
# Calculation of the linear part of the function value,
# defined by (coefficient, argument) pairs, where 'argument'
# is an AffineScalarFunc (for all AffineScalarFunc found as
# argument of f):
linear_part = []
for pos in pos_w_uncert:
linear_part.append((
# Coefficient:
derivatives_args_index[pos](*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
args[pos]._linear_part))
for name in names_w_uncert:
# Optimization: caching of the automatic numerical
# derivatives for keyword arguments that are
# discovered. This gives a speedup when the original
# function is called repeatedly with the same keyword
# arguments:
derivative = derivatives_all_kwargs.setdefault(
name,
# Derivative never needed before:
partial_derivative(f, name))
linear_part.append((
# Coefficient:
derivative(*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
kwargs_uncert_values[name]._linear_part))
# The function now returns the necessary linear approximation
# to the function:
return AffineScalarFunc(
f_nominal_value, LinearCombination(linear_part))
f_with_affine_output = set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))(f_with_affine_output)
# It is easier to work with f_with_affine_output, which represents
# a wrapped version of 'f', when it bears the same name as 'f':
# ! __name__ is read-only, in Python 2.3:
f_with_affine_output.name = f.__name__
return f_with_affine_output
|
(*args, **kwargs)
|
61,728 |
uncertainties.core
|
f_with_affine_output
|
Version of __rmod__(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
Return value%self.
|
def wrap(f, derivatives_args=[], derivatives_kwargs={}):
"""
Wraps a function f into a function that also accepts numbers with
uncertainties (UFloat objects); the wrapped function returns the
value of f with the correct uncertainty and correlations. The
wrapped function is intended to be used as a drop-in replacement
for the original function: they can be called in the exact same
way, the only difference being that numbers with uncertainties can
be given to the wrapped function where f accepts float arguments.
Doing so may be necessary when function f cannot be expressed
analytically (with uncertainties-compatible operators and
functions like +, *, umath.sin(), etc.).
f must return a float-like (i.e. a float, an int, etc., not a
list, etc.), unless when called with no number with
uncertainty. This is because the wrapped function generally
returns numbers with uncertainties: they represent a probability
distribution over the real numbers.
If the wrapped function is called with no argument that has an
uncertainty, the value of f is returned.
Parameters: the derivatives_* parameters can be used for defining
some of the partial derivatives of f. All the (non-None)
derivatives must have the same signature as f.
derivatives_args --
Iterable that, when iterated over, returns either derivatives
(functions) or None. derivatives_args can in particular be a
simple sequence (list or tuple) that gives the derivatives of
the first positional parameters of f.
Each function must be the partial derivative of f with respect
to the corresponding positional parameters. These functions
take the same arguments as f.
The positional parameters of a function are usually
positional-or-keyword parameters like in the call func(a,
b=None). However, they also include var-positional parameters
given through the func(a, b, *args) *args syntax. In the last
example, derivatives_args can be an iterable that returns the
derivative with respect to a, b and then to each optional
argument in args.
A value of None (instead of a function) obtained when
iterating over derivatives_args is automatically replaced by
the relevant numerical derivative. This derivative is not used
if the corresponding argument is not a number with
uncertainty. A None value can therefore be used for non-scalar
arguments of f (like string arguments).
If the derivatives_args iterable yields fewer derivatives than
needed, wrap() automatically sets the remaining unspecified
derivatives to None (i.e. to the automatic numerical
calculation of derivatives).
An indefinite number of derivatives can be specified by having
derivatives_args be an infinite iterator; this can for
instance be used for specifying the derivatives of functions
with a undefined number of argument (like sum(), whose partial
derivatives all return 1).
derivatives_kwargs --
Dictionary that maps keyword parameters to their derivatives,
or None (as in derivatives_args).
Keyword parameters are defined as being those of kwargs when f
has a signature of the form f(..., **kwargs). In Python 3,
these keyword parameters also include keyword-only parameters.
Non-mapped keyword parameters are replaced automatically by
None: the wrapped function will use, if necessary, numerical
differentiation for these parameters (as with
derivatives_args).
Note that this dictionary only maps keyword *parameters* from
the *signature* of f. The way the wrapped function is called
is immaterial: for example, if f has signature f(a, b=None),
then derivatives_kwargs should be the empty dictionary, even
if the wrapped f can be called a wrapped_f(a=123, b=42).
Example (for illustration purposes only, as
uncertainties.umath.sin() runs faster than the examples that
follow): 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.
Numerically calculated derivatives are meaningless when the
function is not differentiable (e.g., math.hypot(x, y) in (x, y) =
(0, 0), and sqrt(x) in x = 0). The corresponding uncertainties are
either meaningless (case of hypot) or raise an exception when
calculated (case of sqrt). In such cases, it is recommended (but
not mandatory) to supply instead a derivative function that
returns NaN where the function is not differentiable. This
function can still numerically calculate the derivative where
defined, for instance by using the
uncertainties.core.partial_derivative() function.
The correctness of the supplied analytical derivatives an be
tested by setting them to None instead and comparing the
analytical and the numerical differentiation results.
Note on efficiency: the wrapped function assumes that f cannot
accept numbers with uncertainties as arguments. If f actually does
handle some arguments even when they have an uncertainty, the
wrapped function ignores this fact, which might lead to a
performance hit: wrapping a function that actually accepts numbers
with uncertainty is likely to make it slower.
"""
derivatives_args_index = IndexableIter(
# Automatic addition of numerical derivatives in case the
# supplied derivatives_args is shorter than the number of
# arguments in *args:
itertools.chain(derivatives_args, itertools.repeat(None)))
# Derivatives for keyword arguments (includes var-keyword
# parameters **kwargs, but also var-or-keyword parameters, and
# keyword-only parameters (Python 3):
derivatives_all_kwargs = {}
for (name, derivative) in derivatives_kwargs.items():
# Optimization: None keyword-argument derivatives are converted
# right away to derivatives (instead of doing this every time a
# None derivative is encountered when calculating derivatives):
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# When the wrapped function is called with keyword arguments that
# map to positional-or-keyword parameters, their derivative is
# looked for in derivatives_all_kwargs. We define these
# additional derivatives:
try:
argspec = getargspec(f)
except TypeError:
# Some functions do not provide meta-data about their
# arguments (see PEP 362). One cannot use keyword arguments
# for positional-or-keyword parameters with them: nothing has
# to be done:
pass
else:
# With Python 3, there is no need to handle keyword-only
# arguments (and therefore to use inspect.getfullargspec())
# because they are already handled by derivatives_kwargs.
for (index, name) in enumerate(argspec.args):
# The following test handles the case of
# positional-or-keyword parameter for which automatic
# numerical differentiation is used: when the wrapped
# function is called with a keyword argument for this
# parameter, the numerical derivative must be calculated
# with respect to the parameter name. In the other case,
# where the wrapped function is called with a positional
# argument, the derivative with respect to its index must
# be used:
derivative = derivatives_args_index[index]
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# Optimization: None derivatives for the positional arguments are
# converted to the corresponding numerical differentiation
# function (instead of doing this over and over later every time a
# None derivative is found):
none_converter = lambda index: partial_derivative(f, index)
for (index, derivative) in enumerate(
derivatives_args_index.returned_elements):
if derivative is None:
derivatives_args_index.returned_elements[index] = (
none_converter(index))
# Future None values are also automatically converted:
derivatives_args_index.none_converter = none_converter
## Wrapped function:
#! Setting the doc string after "def f_with...()" does not
# seem to work. We define it explicitly:
@set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))
def f_with_affine_output(*args, **kwargs):
########################################
# The involved random variables must first be gathered, so
# that they can be independently updated.
# The arguments that contain an uncertainty (AffineScalarFunc
# objects) are gathered, as positions or names; they will be
# replaced by their nominal value in order to calculate
# the necessary derivatives of f.
pos_w_uncert = [index for (index, value) in enumerate(args)
if isinstance(value, AffineScalarFunc)]
names_w_uncert = [key for (key, value) in kwargs.items()
if isinstance(value, AffineScalarFunc)]
########################################
# Value of f() at the nominal value of the arguments with
# uncertainty:
# The usual behavior of f() is kept, if no number with
# uncertainty is provided:
if (not pos_w_uncert) and (not names_w_uncert):
return f(*args, **kwargs)
### Nominal values of the (scalar) arguments:
# !! Possible optimization: If pos_w_uncert is empty, there
# is actually no need to create a mutable version of args and
# one could do args_values = args. However, the wrapped
# function is typically called with numbers with uncertainties
# as positional arguments (i.e., pos_w_uncert is not emtpy),
# so this "optimization" is not implemented here.
## Positional arguments:
args_values = list(args) # Now mutable: modified below
# Arguments with an uncertainty are converted to their nominal
# value:
for index in pos_w_uncert:
args_values[index] = args[index].nominal_value
## Keyword arguments:
# For efficiency reasons, kwargs is not copied. Instead, its
# values with uncertainty are modified:
# The original values with uncertainties are needed: they are
# saved in the following dictionary (which only contains
# values with uncertainty):
kwargs_uncert_values = {}
for name in names_w_uncert:
value_with_uncert = kwargs[name]
# Saving for future use:
kwargs_uncert_values[name] = value_with_uncert
# The original dictionary is modified (for efficiency reasons):
kwargs[name] = value_with_uncert.nominal_value
f_nominal_value = f(*args_values, **kwargs)
# If the value is not a float, then this code cannot provide
# the result, as it returns a UFloat, which represents a
# random real variable. This happens for instance when
# ufloat()*numpy.array() is calculated: the
# AffineScalarFunc.__mul__ operator, obtained through wrap(),
# returns a NumPy array, not a float:
if not isinstance(f_nominal_value, FLOAT_LIKE_TYPES):
return NotImplemented
########################################
# Calculation of the linear part of the function value,
# defined by (coefficient, argument) pairs, where 'argument'
# is an AffineScalarFunc (for all AffineScalarFunc found as
# argument of f):
linear_part = []
for pos in pos_w_uncert:
linear_part.append((
# Coefficient:
derivatives_args_index[pos](*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
args[pos]._linear_part))
for name in names_w_uncert:
# Optimization: caching of the automatic numerical
# derivatives for keyword arguments that are
# discovered. This gives a speedup when the original
# function is called repeatedly with the same keyword
# arguments:
derivative = derivatives_all_kwargs.setdefault(
name,
# Derivative never needed before:
partial_derivative(f, name))
linear_part.append((
# Coefficient:
derivative(*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
kwargs_uncert_values[name]._linear_part))
# The function now returns the necessary linear approximation
# to the function:
return AffineScalarFunc(
f_nominal_value, LinearCombination(linear_part))
f_with_affine_output = set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))(f_with_affine_output)
# It is easier to work with f_with_affine_output, which represents
# a wrapped version of 'f', when it bears the same name as 'f':
# ! __name__ is read-only, in Python 2.3:
f_with_affine_output.name = f.__name__
return f_with_affine_output
|
(*args, **kwargs)
|
61,729 |
uncertainties.core
|
f_with_affine_output
|
Version of __rmul__(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
Return value*self.
|
def wrap(f, derivatives_args=[], derivatives_kwargs={}):
"""
Wraps a function f into a function that also accepts numbers with
uncertainties (UFloat objects); the wrapped function returns the
value of f with the correct uncertainty and correlations. The
wrapped function is intended to be used as a drop-in replacement
for the original function: they can be called in the exact same
way, the only difference being that numbers with uncertainties can
be given to the wrapped function where f accepts float arguments.
Doing so may be necessary when function f cannot be expressed
analytically (with uncertainties-compatible operators and
functions like +, *, umath.sin(), etc.).
f must return a float-like (i.e. a float, an int, etc., not a
list, etc.), unless when called with no number with
uncertainty. This is because the wrapped function generally
returns numbers with uncertainties: they represent a probability
distribution over the real numbers.
If the wrapped function is called with no argument that has an
uncertainty, the value of f is returned.
Parameters: the derivatives_* parameters can be used for defining
some of the partial derivatives of f. All the (non-None)
derivatives must have the same signature as f.
derivatives_args --
Iterable that, when iterated over, returns either derivatives
(functions) or None. derivatives_args can in particular be a
simple sequence (list or tuple) that gives the derivatives of
the first positional parameters of f.
Each function must be the partial derivative of f with respect
to the corresponding positional parameters. These functions
take the same arguments as f.
The positional parameters of a function are usually
positional-or-keyword parameters like in the call func(a,
b=None). However, they also include var-positional parameters
given through the func(a, b, *args) *args syntax. In the last
example, derivatives_args can be an iterable that returns the
derivative with respect to a, b and then to each optional
argument in args.
A value of None (instead of a function) obtained when
iterating over derivatives_args is automatically replaced by
the relevant numerical derivative. This derivative is not used
if the corresponding argument is not a number with
uncertainty. A None value can therefore be used for non-scalar
arguments of f (like string arguments).
If the derivatives_args iterable yields fewer derivatives than
needed, wrap() automatically sets the remaining unspecified
derivatives to None (i.e. to the automatic numerical
calculation of derivatives).
An indefinite number of derivatives can be specified by having
derivatives_args be an infinite iterator; this can for
instance be used for specifying the derivatives of functions
with a undefined number of argument (like sum(), whose partial
derivatives all return 1).
derivatives_kwargs --
Dictionary that maps keyword parameters to their derivatives,
or None (as in derivatives_args).
Keyword parameters are defined as being those of kwargs when f
has a signature of the form f(..., **kwargs). In Python 3,
these keyword parameters also include keyword-only parameters.
Non-mapped keyword parameters are replaced automatically by
None: the wrapped function will use, if necessary, numerical
differentiation for these parameters (as with
derivatives_args).
Note that this dictionary only maps keyword *parameters* from
the *signature* of f. The way the wrapped function is called
is immaterial: for example, if f has signature f(a, b=None),
then derivatives_kwargs should be the empty dictionary, even
if the wrapped f can be called a wrapped_f(a=123, b=42).
Example (for illustration purposes only, as
uncertainties.umath.sin() runs faster than the examples that
follow): 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.
Numerically calculated derivatives are meaningless when the
function is not differentiable (e.g., math.hypot(x, y) in (x, y) =
(0, 0), and sqrt(x) in x = 0). The corresponding uncertainties are
either meaningless (case of hypot) or raise an exception when
calculated (case of sqrt). In such cases, it is recommended (but
not mandatory) to supply instead a derivative function that
returns NaN where the function is not differentiable. This
function can still numerically calculate the derivative where
defined, for instance by using the
uncertainties.core.partial_derivative() function.
The correctness of the supplied analytical derivatives an be
tested by setting them to None instead and comparing the
analytical and the numerical differentiation results.
Note on efficiency: the wrapped function assumes that f cannot
accept numbers with uncertainties as arguments. If f actually does
handle some arguments even when they have an uncertainty, the
wrapped function ignores this fact, which might lead to a
performance hit: wrapping a function that actually accepts numbers
with uncertainty is likely to make it slower.
"""
derivatives_args_index = IndexableIter(
# Automatic addition of numerical derivatives in case the
# supplied derivatives_args is shorter than the number of
# arguments in *args:
itertools.chain(derivatives_args, itertools.repeat(None)))
# Derivatives for keyword arguments (includes var-keyword
# parameters **kwargs, but also var-or-keyword parameters, and
# keyword-only parameters (Python 3):
derivatives_all_kwargs = {}
for (name, derivative) in derivatives_kwargs.items():
# Optimization: None keyword-argument derivatives are converted
# right away to derivatives (instead of doing this every time a
# None derivative is encountered when calculating derivatives):
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# When the wrapped function is called with keyword arguments that
# map to positional-or-keyword parameters, their derivative is
# looked for in derivatives_all_kwargs. We define these
# additional derivatives:
try:
argspec = getargspec(f)
except TypeError:
# Some functions do not provide meta-data about their
# arguments (see PEP 362). One cannot use keyword arguments
# for positional-or-keyword parameters with them: nothing has
# to be done:
pass
else:
# With Python 3, there is no need to handle keyword-only
# arguments (and therefore to use inspect.getfullargspec())
# because they are already handled by derivatives_kwargs.
for (index, name) in enumerate(argspec.args):
# The following test handles the case of
# positional-or-keyword parameter for which automatic
# numerical differentiation is used: when the wrapped
# function is called with a keyword argument for this
# parameter, the numerical derivative must be calculated
# with respect to the parameter name. In the other case,
# where the wrapped function is called with a positional
# argument, the derivative with respect to its index must
# be used:
derivative = derivatives_args_index[index]
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# Optimization: None derivatives for the positional arguments are
# converted to the corresponding numerical differentiation
# function (instead of doing this over and over later every time a
# None derivative is found):
none_converter = lambda index: partial_derivative(f, index)
for (index, derivative) in enumerate(
derivatives_args_index.returned_elements):
if derivative is None:
derivatives_args_index.returned_elements[index] = (
none_converter(index))
# Future None values are also automatically converted:
derivatives_args_index.none_converter = none_converter
## Wrapped function:
#! Setting the doc string after "def f_with...()" does not
# seem to work. We define it explicitly:
@set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))
def f_with_affine_output(*args, **kwargs):
########################################
# The involved random variables must first be gathered, so
# that they can be independently updated.
# The arguments that contain an uncertainty (AffineScalarFunc
# objects) are gathered, as positions or names; they will be
# replaced by their nominal value in order to calculate
# the necessary derivatives of f.
pos_w_uncert = [index for (index, value) in enumerate(args)
if isinstance(value, AffineScalarFunc)]
names_w_uncert = [key for (key, value) in kwargs.items()
if isinstance(value, AffineScalarFunc)]
########################################
# Value of f() at the nominal value of the arguments with
# uncertainty:
# The usual behavior of f() is kept, if no number with
# uncertainty is provided:
if (not pos_w_uncert) and (not names_w_uncert):
return f(*args, **kwargs)
### Nominal values of the (scalar) arguments:
# !! Possible optimization: If pos_w_uncert is empty, there
# is actually no need to create a mutable version of args and
# one could do args_values = args. However, the wrapped
# function is typically called with numbers with uncertainties
# as positional arguments (i.e., pos_w_uncert is not emtpy),
# so this "optimization" is not implemented here.
## Positional arguments:
args_values = list(args) # Now mutable: modified below
# Arguments with an uncertainty are converted to their nominal
# value:
for index in pos_w_uncert:
args_values[index] = args[index].nominal_value
## Keyword arguments:
# For efficiency reasons, kwargs is not copied. Instead, its
# values with uncertainty are modified:
# The original values with uncertainties are needed: they are
# saved in the following dictionary (which only contains
# values with uncertainty):
kwargs_uncert_values = {}
for name in names_w_uncert:
value_with_uncert = kwargs[name]
# Saving for future use:
kwargs_uncert_values[name] = value_with_uncert
# The original dictionary is modified (for efficiency reasons):
kwargs[name] = value_with_uncert.nominal_value
f_nominal_value = f(*args_values, **kwargs)
# If the value is not a float, then this code cannot provide
# the result, as it returns a UFloat, which represents a
# random real variable. This happens for instance when
# ufloat()*numpy.array() is calculated: the
# AffineScalarFunc.__mul__ operator, obtained through wrap(),
# returns a NumPy array, not a float:
if not isinstance(f_nominal_value, FLOAT_LIKE_TYPES):
return NotImplemented
########################################
# Calculation of the linear part of the function value,
# defined by (coefficient, argument) pairs, where 'argument'
# is an AffineScalarFunc (for all AffineScalarFunc found as
# argument of f):
linear_part = []
for pos in pos_w_uncert:
linear_part.append((
# Coefficient:
derivatives_args_index[pos](*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
args[pos]._linear_part))
for name in names_w_uncert:
# Optimization: caching of the automatic numerical
# derivatives for keyword arguments that are
# discovered. This gives a speedup when the original
# function is called repeatedly with the same keyword
# arguments:
derivative = derivatives_all_kwargs.setdefault(
name,
# Derivative never needed before:
partial_derivative(f, name))
linear_part.append((
# Coefficient:
derivative(*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
kwargs_uncert_values[name]._linear_part))
# The function now returns the necessary linear approximation
# to the function:
return AffineScalarFunc(
f_nominal_value, LinearCombination(linear_part))
f_with_affine_output = set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))(f_with_affine_output)
# It is easier to work with f_with_affine_output, which represents
# a wrapped version of 'f', when it bears the same name as 'f':
# ! __name__ is read-only, in Python 2.3:
f_with_affine_output.name = f.__name__
return f_with_affine_output
|
(*args, **kwargs)
|
61,731 |
uncertainties.core
|
f_with_affine_output
|
Version of __rsub__(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
Return value-self.
|
def wrap(f, derivatives_args=[], derivatives_kwargs={}):
"""
Wraps a function f into a function that also accepts numbers with
uncertainties (UFloat objects); the wrapped function returns the
value of f with the correct uncertainty and correlations. The
wrapped function is intended to be used as a drop-in replacement
for the original function: they can be called in the exact same
way, the only difference being that numbers with uncertainties can
be given to the wrapped function where f accepts float arguments.
Doing so may be necessary when function f cannot be expressed
analytically (with uncertainties-compatible operators and
functions like +, *, umath.sin(), etc.).
f must return a float-like (i.e. a float, an int, etc., not a
list, etc.), unless when called with no number with
uncertainty. This is because the wrapped function generally
returns numbers with uncertainties: they represent a probability
distribution over the real numbers.
If the wrapped function is called with no argument that has an
uncertainty, the value of f is returned.
Parameters: the derivatives_* parameters can be used for defining
some of the partial derivatives of f. All the (non-None)
derivatives must have the same signature as f.
derivatives_args --
Iterable that, when iterated over, returns either derivatives
(functions) or None. derivatives_args can in particular be a
simple sequence (list or tuple) that gives the derivatives of
the first positional parameters of f.
Each function must be the partial derivative of f with respect
to the corresponding positional parameters. These functions
take the same arguments as f.
The positional parameters of a function are usually
positional-or-keyword parameters like in the call func(a,
b=None). However, they also include var-positional parameters
given through the func(a, b, *args) *args syntax. In the last
example, derivatives_args can be an iterable that returns the
derivative with respect to a, b and then to each optional
argument in args.
A value of None (instead of a function) obtained when
iterating over derivatives_args is automatically replaced by
the relevant numerical derivative. This derivative is not used
if the corresponding argument is not a number with
uncertainty. A None value can therefore be used for non-scalar
arguments of f (like string arguments).
If the derivatives_args iterable yields fewer derivatives than
needed, wrap() automatically sets the remaining unspecified
derivatives to None (i.e. to the automatic numerical
calculation of derivatives).
An indefinite number of derivatives can be specified by having
derivatives_args be an infinite iterator; this can for
instance be used for specifying the derivatives of functions
with a undefined number of argument (like sum(), whose partial
derivatives all return 1).
derivatives_kwargs --
Dictionary that maps keyword parameters to their derivatives,
or None (as in derivatives_args).
Keyword parameters are defined as being those of kwargs when f
has a signature of the form f(..., **kwargs). In Python 3,
these keyword parameters also include keyword-only parameters.
Non-mapped keyword parameters are replaced automatically by
None: the wrapped function will use, if necessary, numerical
differentiation for these parameters (as with
derivatives_args).
Note that this dictionary only maps keyword *parameters* from
the *signature* of f. The way the wrapped function is called
is immaterial: for example, if f has signature f(a, b=None),
then derivatives_kwargs should be the empty dictionary, even
if the wrapped f can be called a wrapped_f(a=123, b=42).
Example (for illustration purposes only, as
uncertainties.umath.sin() runs faster than the examples that
follow): 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.
Numerically calculated derivatives are meaningless when the
function is not differentiable (e.g., math.hypot(x, y) in (x, y) =
(0, 0), and sqrt(x) in x = 0). The corresponding uncertainties are
either meaningless (case of hypot) or raise an exception when
calculated (case of sqrt). In such cases, it is recommended (but
not mandatory) to supply instead a derivative function that
returns NaN where the function is not differentiable. This
function can still numerically calculate the derivative where
defined, for instance by using the
uncertainties.core.partial_derivative() function.
The correctness of the supplied analytical derivatives an be
tested by setting them to None instead and comparing the
analytical and the numerical differentiation results.
Note on efficiency: the wrapped function assumes that f cannot
accept numbers with uncertainties as arguments. If f actually does
handle some arguments even when they have an uncertainty, the
wrapped function ignores this fact, which might lead to a
performance hit: wrapping a function that actually accepts numbers
with uncertainty is likely to make it slower.
"""
derivatives_args_index = IndexableIter(
# Automatic addition of numerical derivatives in case the
# supplied derivatives_args is shorter than the number of
# arguments in *args:
itertools.chain(derivatives_args, itertools.repeat(None)))
# Derivatives for keyword arguments (includes var-keyword
# parameters **kwargs, but also var-or-keyword parameters, and
# keyword-only parameters (Python 3):
derivatives_all_kwargs = {}
for (name, derivative) in derivatives_kwargs.items():
# Optimization: None keyword-argument derivatives are converted
# right away to derivatives (instead of doing this every time a
# None derivative is encountered when calculating derivatives):
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# When the wrapped function is called with keyword arguments that
# map to positional-or-keyword parameters, their derivative is
# looked for in derivatives_all_kwargs. We define these
# additional derivatives:
try:
argspec = getargspec(f)
except TypeError:
# Some functions do not provide meta-data about their
# arguments (see PEP 362). One cannot use keyword arguments
# for positional-or-keyword parameters with them: nothing has
# to be done:
pass
else:
# With Python 3, there is no need to handle keyword-only
# arguments (and therefore to use inspect.getfullargspec())
# because they are already handled by derivatives_kwargs.
for (index, name) in enumerate(argspec.args):
# The following test handles the case of
# positional-or-keyword parameter for which automatic
# numerical differentiation is used: when the wrapped
# function is called with a keyword argument for this
# parameter, the numerical derivative must be calculated
# with respect to the parameter name. In the other case,
# where the wrapped function is called with a positional
# argument, the derivative with respect to its index must
# be used:
derivative = derivatives_args_index[index]
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# Optimization: None derivatives for the positional arguments are
# converted to the corresponding numerical differentiation
# function (instead of doing this over and over later every time a
# None derivative is found):
none_converter = lambda index: partial_derivative(f, index)
for (index, derivative) in enumerate(
derivatives_args_index.returned_elements):
if derivative is None:
derivatives_args_index.returned_elements[index] = (
none_converter(index))
# Future None values are also automatically converted:
derivatives_args_index.none_converter = none_converter
## Wrapped function:
#! Setting the doc string after "def f_with...()" does not
# seem to work. We define it explicitly:
@set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))
def f_with_affine_output(*args, **kwargs):
########################################
# The involved random variables must first be gathered, so
# that they can be independently updated.
# The arguments that contain an uncertainty (AffineScalarFunc
# objects) are gathered, as positions or names; they will be
# replaced by their nominal value in order to calculate
# the necessary derivatives of f.
pos_w_uncert = [index for (index, value) in enumerate(args)
if isinstance(value, AffineScalarFunc)]
names_w_uncert = [key for (key, value) in kwargs.items()
if isinstance(value, AffineScalarFunc)]
########################################
# Value of f() at the nominal value of the arguments with
# uncertainty:
# The usual behavior of f() is kept, if no number with
# uncertainty is provided:
if (not pos_w_uncert) and (not names_w_uncert):
return f(*args, **kwargs)
### Nominal values of the (scalar) arguments:
# !! Possible optimization: If pos_w_uncert is empty, there
# is actually no need to create a mutable version of args and
# one could do args_values = args. However, the wrapped
# function is typically called with numbers with uncertainties
# as positional arguments (i.e., pos_w_uncert is not emtpy),
# so this "optimization" is not implemented here.
## Positional arguments:
args_values = list(args) # Now mutable: modified below
# Arguments with an uncertainty are converted to their nominal
# value:
for index in pos_w_uncert:
args_values[index] = args[index].nominal_value
## Keyword arguments:
# For efficiency reasons, kwargs is not copied. Instead, its
# values with uncertainty are modified:
# The original values with uncertainties are needed: they are
# saved in the following dictionary (which only contains
# values with uncertainty):
kwargs_uncert_values = {}
for name in names_w_uncert:
value_with_uncert = kwargs[name]
# Saving for future use:
kwargs_uncert_values[name] = value_with_uncert
# The original dictionary is modified (for efficiency reasons):
kwargs[name] = value_with_uncert.nominal_value
f_nominal_value = f(*args_values, **kwargs)
# If the value is not a float, then this code cannot provide
# the result, as it returns a UFloat, which represents a
# random real variable. This happens for instance when
# ufloat()*numpy.array() is calculated: the
# AffineScalarFunc.__mul__ operator, obtained through wrap(),
# returns a NumPy array, not a float:
if not isinstance(f_nominal_value, FLOAT_LIKE_TYPES):
return NotImplemented
########################################
# Calculation of the linear part of the function value,
# defined by (coefficient, argument) pairs, where 'argument'
# is an AffineScalarFunc (for all AffineScalarFunc found as
# argument of f):
linear_part = []
for pos in pos_w_uncert:
linear_part.append((
# Coefficient:
derivatives_args_index[pos](*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
args[pos]._linear_part))
for name in names_w_uncert:
# Optimization: caching of the automatic numerical
# derivatives for keyword arguments that are
# discovered. This gives a speedup when the original
# function is called repeatedly with the same keyword
# arguments:
derivative = derivatives_all_kwargs.setdefault(
name,
# Derivative never needed before:
partial_derivative(f, name))
linear_part.append((
# Coefficient:
derivative(*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
kwargs_uncert_values[name]._linear_part))
# The function now returns the necessary linear approximation
# to the function:
return AffineScalarFunc(
f_nominal_value, LinearCombination(linear_part))
f_with_affine_output = set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))(f_with_affine_output)
# It is easier to work with f_with_affine_output, which represents
# a wrapped version of 'f', when it bears the same name as 'f':
# ! __name__ is read-only, in Python 2.3:
f_with_affine_output.name = f.__name__
return f_with_affine_output
|
(*args, **kwargs)
|
61,732 |
uncertainties.core
|
f_with_affine_output
|
Version of __rtruediv__(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
Return value/self.
|
def wrap(f, derivatives_args=[], derivatives_kwargs={}):
"""
Wraps a function f into a function that also accepts numbers with
uncertainties (UFloat objects); the wrapped function returns the
value of f with the correct uncertainty and correlations. The
wrapped function is intended to be used as a drop-in replacement
for the original function: they can be called in the exact same
way, the only difference being that numbers with uncertainties can
be given to the wrapped function where f accepts float arguments.
Doing so may be necessary when function f cannot be expressed
analytically (with uncertainties-compatible operators and
functions like +, *, umath.sin(), etc.).
f must return a float-like (i.e. a float, an int, etc., not a
list, etc.), unless when called with no number with
uncertainty. This is because the wrapped function generally
returns numbers with uncertainties: they represent a probability
distribution over the real numbers.
If the wrapped function is called with no argument that has an
uncertainty, the value of f is returned.
Parameters: the derivatives_* parameters can be used for defining
some of the partial derivatives of f. All the (non-None)
derivatives must have the same signature as f.
derivatives_args --
Iterable that, when iterated over, returns either derivatives
(functions) or None. derivatives_args can in particular be a
simple sequence (list or tuple) that gives the derivatives of
the first positional parameters of f.
Each function must be the partial derivative of f with respect
to the corresponding positional parameters. These functions
take the same arguments as f.
The positional parameters of a function are usually
positional-or-keyword parameters like in the call func(a,
b=None). However, they also include var-positional parameters
given through the func(a, b, *args) *args syntax. In the last
example, derivatives_args can be an iterable that returns the
derivative with respect to a, b and then to each optional
argument in args.
A value of None (instead of a function) obtained when
iterating over derivatives_args is automatically replaced by
the relevant numerical derivative. This derivative is not used
if the corresponding argument is not a number with
uncertainty. A None value can therefore be used for non-scalar
arguments of f (like string arguments).
If the derivatives_args iterable yields fewer derivatives than
needed, wrap() automatically sets the remaining unspecified
derivatives to None (i.e. to the automatic numerical
calculation of derivatives).
An indefinite number of derivatives can be specified by having
derivatives_args be an infinite iterator; this can for
instance be used for specifying the derivatives of functions
with a undefined number of argument (like sum(), whose partial
derivatives all return 1).
derivatives_kwargs --
Dictionary that maps keyword parameters to their derivatives,
or None (as in derivatives_args).
Keyword parameters are defined as being those of kwargs when f
has a signature of the form f(..., **kwargs). In Python 3,
these keyword parameters also include keyword-only parameters.
Non-mapped keyword parameters are replaced automatically by
None: the wrapped function will use, if necessary, numerical
differentiation for these parameters (as with
derivatives_args).
Note that this dictionary only maps keyword *parameters* from
the *signature* of f. The way the wrapped function is called
is immaterial: for example, if f has signature f(a, b=None),
then derivatives_kwargs should be the empty dictionary, even
if the wrapped f can be called a wrapped_f(a=123, b=42).
Example (for illustration purposes only, as
uncertainties.umath.sin() runs faster than the examples that
follow): 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.
Numerically calculated derivatives are meaningless when the
function is not differentiable (e.g., math.hypot(x, y) in (x, y) =
(0, 0), and sqrt(x) in x = 0). The corresponding uncertainties are
either meaningless (case of hypot) or raise an exception when
calculated (case of sqrt). In such cases, it is recommended (but
not mandatory) to supply instead a derivative function that
returns NaN where the function is not differentiable. This
function can still numerically calculate the derivative where
defined, for instance by using the
uncertainties.core.partial_derivative() function.
The correctness of the supplied analytical derivatives an be
tested by setting them to None instead and comparing the
analytical and the numerical differentiation results.
Note on efficiency: the wrapped function assumes that f cannot
accept numbers with uncertainties as arguments. If f actually does
handle some arguments even when they have an uncertainty, the
wrapped function ignores this fact, which might lead to a
performance hit: wrapping a function that actually accepts numbers
with uncertainty is likely to make it slower.
"""
derivatives_args_index = IndexableIter(
# Automatic addition of numerical derivatives in case the
# supplied derivatives_args is shorter than the number of
# arguments in *args:
itertools.chain(derivatives_args, itertools.repeat(None)))
# Derivatives for keyword arguments (includes var-keyword
# parameters **kwargs, but also var-or-keyword parameters, and
# keyword-only parameters (Python 3):
derivatives_all_kwargs = {}
for (name, derivative) in derivatives_kwargs.items():
# Optimization: None keyword-argument derivatives are converted
# right away to derivatives (instead of doing this every time a
# None derivative is encountered when calculating derivatives):
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# When the wrapped function is called with keyword arguments that
# map to positional-or-keyword parameters, their derivative is
# looked for in derivatives_all_kwargs. We define these
# additional derivatives:
try:
argspec = getargspec(f)
except TypeError:
# Some functions do not provide meta-data about their
# arguments (see PEP 362). One cannot use keyword arguments
# for positional-or-keyword parameters with them: nothing has
# to be done:
pass
else:
# With Python 3, there is no need to handle keyword-only
# arguments (and therefore to use inspect.getfullargspec())
# because they are already handled by derivatives_kwargs.
for (index, name) in enumerate(argspec.args):
# The following test handles the case of
# positional-or-keyword parameter for which automatic
# numerical differentiation is used: when the wrapped
# function is called with a keyword argument for this
# parameter, the numerical derivative must be calculated
# with respect to the parameter name. In the other case,
# where the wrapped function is called with a positional
# argument, the derivative with respect to its index must
# be used:
derivative = derivatives_args_index[index]
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# Optimization: None derivatives for the positional arguments are
# converted to the corresponding numerical differentiation
# function (instead of doing this over and over later every time a
# None derivative is found):
none_converter = lambda index: partial_derivative(f, index)
for (index, derivative) in enumerate(
derivatives_args_index.returned_elements):
if derivative is None:
derivatives_args_index.returned_elements[index] = (
none_converter(index))
# Future None values are also automatically converted:
derivatives_args_index.none_converter = none_converter
## Wrapped function:
#! Setting the doc string after "def f_with...()" does not
# seem to work. We define it explicitly:
@set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))
def f_with_affine_output(*args, **kwargs):
########################################
# The involved random variables must first be gathered, so
# that they can be independently updated.
# The arguments that contain an uncertainty (AffineScalarFunc
# objects) are gathered, as positions or names; they will be
# replaced by their nominal value in order to calculate
# the necessary derivatives of f.
pos_w_uncert = [index for (index, value) in enumerate(args)
if isinstance(value, AffineScalarFunc)]
names_w_uncert = [key for (key, value) in kwargs.items()
if isinstance(value, AffineScalarFunc)]
########################################
# Value of f() at the nominal value of the arguments with
# uncertainty:
# The usual behavior of f() is kept, if no number with
# uncertainty is provided:
if (not pos_w_uncert) and (not names_w_uncert):
return f(*args, **kwargs)
### Nominal values of the (scalar) arguments:
# !! Possible optimization: If pos_w_uncert is empty, there
# is actually no need to create a mutable version of args and
# one could do args_values = args. However, the wrapped
# function is typically called with numbers with uncertainties
# as positional arguments (i.e., pos_w_uncert is not emtpy),
# so this "optimization" is not implemented here.
## Positional arguments:
args_values = list(args) # Now mutable: modified below
# Arguments with an uncertainty are converted to their nominal
# value:
for index in pos_w_uncert:
args_values[index] = args[index].nominal_value
## Keyword arguments:
# For efficiency reasons, kwargs is not copied. Instead, its
# values with uncertainty are modified:
# The original values with uncertainties are needed: they are
# saved in the following dictionary (which only contains
# values with uncertainty):
kwargs_uncert_values = {}
for name in names_w_uncert:
value_with_uncert = kwargs[name]
# Saving for future use:
kwargs_uncert_values[name] = value_with_uncert
# The original dictionary is modified (for efficiency reasons):
kwargs[name] = value_with_uncert.nominal_value
f_nominal_value = f(*args_values, **kwargs)
# If the value is not a float, then this code cannot provide
# the result, as it returns a UFloat, which represents a
# random real variable. This happens for instance when
# ufloat()*numpy.array() is calculated: the
# AffineScalarFunc.__mul__ operator, obtained through wrap(),
# returns a NumPy array, not a float:
if not isinstance(f_nominal_value, FLOAT_LIKE_TYPES):
return NotImplemented
########################################
# Calculation of the linear part of the function value,
# defined by (coefficient, argument) pairs, where 'argument'
# is an AffineScalarFunc (for all AffineScalarFunc found as
# argument of f):
linear_part = []
for pos in pos_w_uncert:
linear_part.append((
# Coefficient:
derivatives_args_index[pos](*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
args[pos]._linear_part))
for name in names_w_uncert:
# Optimization: caching of the automatic numerical
# derivatives for keyword arguments that are
# discovered. This gives a speedup when the original
# function is called repeatedly with the same keyword
# arguments:
derivative = derivatives_all_kwargs.setdefault(
name,
# Derivative never needed before:
partial_derivative(f, name))
linear_part.append((
# Coefficient:
derivative(*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
kwargs_uncert_values[name]._linear_part))
# The function now returns the necessary linear approximation
# to the function:
return AffineScalarFunc(
f_nominal_value, LinearCombination(linear_part))
f_with_affine_output = set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))(f_with_affine_output)
# It is easier to work with f_with_affine_output, which represents
# a wrapped version of 'f', when it bears the same name as 'f':
# ! __name__ is read-only, in Python 2.3:
f_with_affine_output.name = f.__name__
return f_with_affine_output
|
(*args, **kwargs)
|
61,733 |
uncertainties.core
|
__setstate__
|
Hook for the pickle module.
|
def __setstate__(self, data_dict):
"""
Hook for the pickle module.
"""
for (name, value) in data_dict.items():
# Contrary to the default __setstate__(), this does not
# necessarily save to the instance dictionary (because the
# instance might contain slots):
setattr(self, name, value)
|
(self, data_dict)
|
61,734 |
uncertainties.core
|
__str__
| null |
def __str__(self):
# An empty format string and str() usually return the same
# string
# (http://docs.python.org/2/library/string.html#format-specification-mini-language):
return self.format('')
|
(self)
|
61,735 |
uncertainties.core
|
f_with_affine_output
|
Version of __sub__(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
Return self-value.
|
def wrap(f, derivatives_args=[], derivatives_kwargs={}):
"""
Wraps a function f into a function that also accepts numbers with
uncertainties (UFloat objects); the wrapped function returns the
value of f with the correct uncertainty and correlations. The
wrapped function is intended to be used as a drop-in replacement
for the original function: they can be called in the exact same
way, the only difference being that numbers with uncertainties can
be given to the wrapped function where f accepts float arguments.
Doing so may be necessary when function f cannot be expressed
analytically (with uncertainties-compatible operators and
functions like +, *, umath.sin(), etc.).
f must return a float-like (i.e. a float, an int, etc., not a
list, etc.), unless when called with no number with
uncertainty. This is because the wrapped function generally
returns numbers with uncertainties: they represent a probability
distribution over the real numbers.
If the wrapped function is called with no argument that has an
uncertainty, the value of f is returned.
Parameters: the derivatives_* parameters can be used for defining
some of the partial derivatives of f. All the (non-None)
derivatives must have the same signature as f.
derivatives_args --
Iterable that, when iterated over, returns either derivatives
(functions) or None. derivatives_args can in particular be a
simple sequence (list or tuple) that gives the derivatives of
the first positional parameters of f.
Each function must be the partial derivative of f with respect
to the corresponding positional parameters. These functions
take the same arguments as f.
The positional parameters of a function are usually
positional-or-keyword parameters like in the call func(a,
b=None). However, they also include var-positional parameters
given through the func(a, b, *args) *args syntax. In the last
example, derivatives_args can be an iterable that returns the
derivative with respect to a, b and then to each optional
argument in args.
A value of None (instead of a function) obtained when
iterating over derivatives_args is automatically replaced by
the relevant numerical derivative. This derivative is not used
if the corresponding argument is not a number with
uncertainty. A None value can therefore be used for non-scalar
arguments of f (like string arguments).
If the derivatives_args iterable yields fewer derivatives than
needed, wrap() automatically sets the remaining unspecified
derivatives to None (i.e. to the automatic numerical
calculation of derivatives).
An indefinite number of derivatives can be specified by having
derivatives_args be an infinite iterator; this can for
instance be used for specifying the derivatives of functions
with a undefined number of argument (like sum(), whose partial
derivatives all return 1).
derivatives_kwargs --
Dictionary that maps keyword parameters to their derivatives,
or None (as in derivatives_args).
Keyword parameters are defined as being those of kwargs when f
has a signature of the form f(..., **kwargs). In Python 3,
these keyword parameters also include keyword-only parameters.
Non-mapped keyword parameters are replaced automatically by
None: the wrapped function will use, if necessary, numerical
differentiation for these parameters (as with
derivatives_args).
Note that this dictionary only maps keyword *parameters* from
the *signature* of f. The way the wrapped function is called
is immaterial: for example, if f has signature f(a, b=None),
then derivatives_kwargs should be the empty dictionary, even
if the wrapped f can be called a wrapped_f(a=123, b=42).
Example (for illustration purposes only, as
uncertainties.umath.sin() runs faster than the examples that
follow): 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.
Numerically calculated derivatives are meaningless when the
function is not differentiable (e.g., math.hypot(x, y) in (x, y) =
(0, 0), and sqrt(x) in x = 0). The corresponding uncertainties are
either meaningless (case of hypot) or raise an exception when
calculated (case of sqrt). In such cases, it is recommended (but
not mandatory) to supply instead a derivative function that
returns NaN where the function is not differentiable. This
function can still numerically calculate the derivative where
defined, for instance by using the
uncertainties.core.partial_derivative() function.
The correctness of the supplied analytical derivatives an be
tested by setting them to None instead and comparing the
analytical and the numerical differentiation results.
Note on efficiency: the wrapped function assumes that f cannot
accept numbers with uncertainties as arguments. If f actually does
handle some arguments even when they have an uncertainty, the
wrapped function ignores this fact, which might lead to a
performance hit: wrapping a function that actually accepts numbers
with uncertainty is likely to make it slower.
"""
derivatives_args_index = IndexableIter(
# Automatic addition of numerical derivatives in case the
# supplied derivatives_args is shorter than the number of
# arguments in *args:
itertools.chain(derivatives_args, itertools.repeat(None)))
# Derivatives for keyword arguments (includes var-keyword
# parameters **kwargs, but also var-or-keyword parameters, and
# keyword-only parameters (Python 3):
derivatives_all_kwargs = {}
for (name, derivative) in derivatives_kwargs.items():
# Optimization: None keyword-argument derivatives are converted
# right away to derivatives (instead of doing this every time a
# None derivative is encountered when calculating derivatives):
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# When the wrapped function is called with keyword arguments that
# map to positional-or-keyword parameters, their derivative is
# looked for in derivatives_all_kwargs. We define these
# additional derivatives:
try:
argspec = getargspec(f)
except TypeError:
# Some functions do not provide meta-data about their
# arguments (see PEP 362). One cannot use keyword arguments
# for positional-or-keyword parameters with them: nothing has
# to be done:
pass
else:
# With Python 3, there is no need to handle keyword-only
# arguments (and therefore to use inspect.getfullargspec())
# because they are already handled by derivatives_kwargs.
for (index, name) in enumerate(argspec.args):
# The following test handles the case of
# positional-or-keyword parameter for which automatic
# numerical differentiation is used: when the wrapped
# function is called with a keyword argument for this
# parameter, the numerical derivative must be calculated
# with respect to the parameter name. In the other case,
# where the wrapped function is called with a positional
# argument, the derivative with respect to its index must
# be used:
derivative = derivatives_args_index[index]
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# Optimization: None derivatives for the positional arguments are
# converted to the corresponding numerical differentiation
# function (instead of doing this over and over later every time a
# None derivative is found):
none_converter = lambda index: partial_derivative(f, index)
for (index, derivative) in enumerate(
derivatives_args_index.returned_elements):
if derivative is None:
derivatives_args_index.returned_elements[index] = (
none_converter(index))
# Future None values are also automatically converted:
derivatives_args_index.none_converter = none_converter
## Wrapped function:
#! Setting the doc string after "def f_with...()" does not
# seem to work. We define it explicitly:
@set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))
def f_with_affine_output(*args, **kwargs):
########################################
# The involved random variables must first be gathered, so
# that they can be independently updated.
# The arguments that contain an uncertainty (AffineScalarFunc
# objects) are gathered, as positions or names; they will be
# replaced by their nominal value in order to calculate
# the necessary derivatives of f.
pos_w_uncert = [index for (index, value) in enumerate(args)
if isinstance(value, AffineScalarFunc)]
names_w_uncert = [key for (key, value) in kwargs.items()
if isinstance(value, AffineScalarFunc)]
########################################
# Value of f() at the nominal value of the arguments with
# uncertainty:
# The usual behavior of f() is kept, if no number with
# uncertainty is provided:
if (not pos_w_uncert) and (not names_w_uncert):
return f(*args, **kwargs)
### Nominal values of the (scalar) arguments:
# !! Possible optimization: If pos_w_uncert is empty, there
# is actually no need to create a mutable version of args and
# one could do args_values = args. However, the wrapped
# function is typically called with numbers with uncertainties
# as positional arguments (i.e., pos_w_uncert is not emtpy),
# so this "optimization" is not implemented here.
## Positional arguments:
args_values = list(args) # Now mutable: modified below
# Arguments with an uncertainty are converted to their nominal
# value:
for index in pos_w_uncert:
args_values[index] = args[index].nominal_value
## Keyword arguments:
# For efficiency reasons, kwargs is not copied. Instead, its
# values with uncertainty are modified:
# The original values with uncertainties are needed: they are
# saved in the following dictionary (which only contains
# values with uncertainty):
kwargs_uncert_values = {}
for name in names_w_uncert:
value_with_uncert = kwargs[name]
# Saving for future use:
kwargs_uncert_values[name] = value_with_uncert
# The original dictionary is modified (for efficiency reasons):
kwargs[name] = value_with_uncert.nominal_value
f_nominal_value = f(*args_values, **kwargs)
# If the value is not a float, then this code cannot provide
# the result, as it returns a UFloat, which represents a
# random real variable. This happens for instance when
# ufloat()*numpy.array() is calculated: the
# AffineScalarFunc.__mul__ operator, obtained through wrap(),
# returns a NumPy array, not a float:
if not isinstance(f_nominal_value, FLOAT_LIKE_TYPES):
return NotImplemented
########################################
# Calculation of the linear part of the function value,
# defined by (coefficient, argument) pairs, where 'argument'
# is an AffineScalarFunc (for all AffineScalarFunc found as
# argument of f):
linear_part = []
for pos in pos_w_uncert:
linear_part.append((
# Coefficient:
derivatives_args_index[pos](*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
args[pos]._linear_part))
for name in names_w_uncert:
# Optimization: caching of the automatic numerical
# derivatives for keyword arguments that are
# discovered. This gives a speedup when the original
# function is called repeatedly with the same keyword
# arguments:
derivative = derivatives_all_kwargs.setdefault(
name,
# Derivative never needed before:
partial_derivative(f, name))
linear_part.append((
# Coefficient:
derivative(*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
kwargs_uncert_values[name]._linear_part))
# The function now returns the necessary linear approximation
# to the function:
return AffineScalarFunc(
f_nominal_value, LinearCombination(linear_part))
f_with_affine_output = set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))(f_with_affine_output)
# It is easier to work with f_with_affine_output, which represents
# a wrapped version of 'f', when it bears the same name as 'f':
# ! __name__ is read-only, in Python 2.3:
f_with_affine_output.name = f.__name__
return f_with_affine_output
|
(*args, **kwargs)
|
61,736 |
uncertainties.core
|
f_with_affine_output
|
Version of __truediv__(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
Return self/value.
|
def wrap(f, derivatives_args=[], derivatives_kwargs={}):
"""
Wraps a function f into a function that also accepts numbers with
uncertainties (UFloat objects); the wrapped function returns the
value of f with the correct uncertainty and correlations. The
wrapped function is intended to be used as a drop-in replacement
for the original function: they can be called in the exact same
way, the only difference being that numbers with uncertainties can
be given to the wrapped function where f accepts float arguments.
Doing so may be necessary when function f cannot be expressed
analytically (with uncertainties-compatible operators and
functions like +, *, umath.sin(), etc.).
f must return a float-like (i.e. a float, an int, etc., not a
list, etc.), unless when called with no number with
uncertainty. This is because the wrapped function generally
returns numbers with uncertainties: they represent a probability
distribution over the real numbers.
If the wrapped function is called with no argument that has an
uncertainty, the value of f is returned.
Parameters: the derivatives_* parameters can be used for defining
some of the partial derivatives of f. All the (non-None)
derivatives must have the same signature as f.
derivatives_args --
Iterable that, when iterated over, returns either derivatives
(functions) or None. derivatives_args can in particular be a
simple sequence (list or tuple) that gives the derivatives of
the first positional parameters of f.
Each function must be the partial derivative of f with respect
to the corresponding positional parameters. These functions
take the same arguments as f.
The positional parameters of a function are usually
positional-or-keyword parameters like in the call func(a,
b=None). However, they also include var-positional parameters
given through the func(a, b, *args) *args syntax. In the last
example, derivatives_args can be an iterable that returns the
derivative with respect to a, b and then to each optional
argument in args.
A value of None (instead of a function) obtained when
iterating over derivatives_args is automatically replaced by
the relevant numerical derivative. This derivative is not used
if the corresponding argument is not a number with
uncertainty. A None value can therefore be used for non-scalar
arguments of f (like string arguments).
If the derivatives_args iterable yields fewer derivatives than
needed, wrap() automatically sets the remaining unspecified
derivatives to None (i.e. to the automatic numerical
calculation of derivatives).
An indefinite number of derivatives can be specified by having
derivatives_args be an infinite iterator; this can for
instance be used for specifying the derivatives of functions
with a undefined number of argument (like sum(), whose partial
derivatives all return 1).
derivatives_kwargs --
Dictionary that maps keyword parameters to their derivatives,
or None (as in derivatives_args).
Keyword parameters are defined as being those of kwargs when f
has a signature of the form f(..., **kwargs). In Python 3,
these keyword parameters also include keyword-only parameters.
Non-mapped keyword parameters are replaced automatically by
None: the wrapped function will use, if necessary, numerical
differentiation for these parameters (as with
derivatives_args).
Note that this dictionary only maps keyword *parameters* from
the *signature* of f. The way the wrapped function is called
is immaterial: for example, if f has signature f(a, b=None),
then derivatives_kwargs should be the empty dictionary, even
if the wrapped f can be called a wrapped_f(a=123, b=42).
Example (for illustration purposes only, as
uncertainties.umath.sin() runs faster than the examples that
follow): 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.
Numerically calculated derivatives are meaningless when the
function is not differentiable (e.g., math.hypot(x, y) in (x, y) =
(0, 0), and sqrt(x) in x = 0). The corresponding uncertainties are
either meaningless (case of hypot) or raise an exception when
calculated (case of sqrt). In such cases, it is recommended (but
not mandatory) to supply instead a derivative function that
returns NaN where the function is not differentiable. This
function can still numerically calculate the derivative where
defined, for instance by using the
uncertainties.core.partial_derivative() function.
The correctness of the supplied analytical derivatives an be
tested by setting them to None instead and comparing the
analytical and the numerical differentiation results.
Note on efficiency: the wrapped function assumes that f cannot
accept numbers with uncertainties as arguments. If f actually does
handle some arguments even when they have an uncertainty, the
wrapped function ignores this fact, which might lead to a
performance hit: wrapping a function that actually accepts numbers
with uncertainty is likely to make it slower.
"""
derivatives_args_index = IndexableIter(
# Automatic addition of numerical derivatives in case the
# supplied derivatives_args is shorter than the number of
# arguments in *args:
itertools.chain(derivatives_args, itertools.repeat(None)))
# Derivatives for keyword arguments (includes var-keyword
# parameters **kwargs, but also var-or-keyword parameters, and
# keyword-only parameters (Python 3):
derivatives_all_kwargs = {}
for (name, derivative) in derivatives_kwargs.items():
# Optimization: None keyword-argument derivatives are converted
# right away to derivatives (instead of doing this every time a
# None derivative is encountered when calculating derivatives):
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# When the wrapped function is called with keyword arguments that
# map to positional-or-keyword parameters, their derivative is
# looked for in derivatives_all_kwargs. We define these
# additional derivatives:
try:
argspec = getargspec(f)
except TypeError:
# Some functions do not provide meta-data about their
# arguments (see PEP 362). One cannot use keyword arguments
# for positional-or-keyword parameters with them: nothing has
# to be done:
pass
else:
# With Python 3, there is no need to handle keyword-only
# arguments (and therefore to use inspect.getfullargspec())
# because they are already handled by derivatives_kwargs.
for (index, name) in enumerate(argspec.args):
# The following test handles the case of
# positional-or-keyword parameter for which automatic
# numerical differentiation is used: when the wrapped
# function is called with a keyword argument for this
# parameter, the numerical derivative must be calculated
# with respect to the parameter name. In the other case,
# where the wrapped function is called with a positional
# argument, the derivative with respect to its index must
# be used:
derivative = derivatives_args_index[index]
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# Optimization: None derivatives for the positional arguments are
# converted to the corresponding numerical differentiation
# function (instead of doing this over and over later every time a
# None derivative is found):
none_converter = lambda index: partial_derivative(f, index)
for (index, derivative) in enumerate(
derivatives_args_index.returned_elements):
if derivative is None:
derivatives_args_index.returned_elements[index] = (
none_converter(index))
# Future None values are also automatically converted:
derivatives_args_index.none_converter = none_converter
## Wrapped function:
#! Setting the doc string after "def f_with...()" does not
# seem to work. We define it explicitly:
@set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))
def f_with_affine_output(*args, **kwargs):
########################################
# The involved random variables must first be gathered, so
# that they can be independently updated.
# The arguments that contain an uncertainty (AffineScalarFunc
# objects) are gathered, as positions or names; they will be
# replaced by their nominal value in order to calculate
# the necessary derivatives of f.
pos_w_uncert = [index for (index, value) in enumerate(args)
if isinstance(value, AffineScalarFunc)]
names_w_uncert = [key for (key, value) in kwargs.items()
if isinstance(value, AffineScalarFunc)]
########################################
# Value of f() at the nominal value of the arguments with
# uncertainty:
# The usual behavior of f() is kept, if no number with
# uncertainty is provided:
if (not pos_w_uncert) and (not names_w_uncert):
return f(*args, **kwargs)
### Nominal values of the (scalar) arguments:
# !! Possible optimization: If pos_w_uncert is empty, there
# is actually no need to create a mutable version of args and
# one could do args_values = args. However, the wrapped
# function is typically called with numbers with uncertainties
# as positional arguments (i.e., pos_w_uncert is not emtpy),
# so this "optimization" is not implemented here.
## Positional arguments:
args_values = list(args) # Now mutable: modified below
# Arguments with an uncertainty are converted to their nominal
# value:
for index in pos_w_uncert:
args_values[index] = args[index].nominal_value
## Keyword arguments:
# For efficiency reasons, kwargs is not copied. Instead, its
# values with uncertainty are modified:
# The original values with uncertainties are needed: they are
# saved in the following dictionary (which only contains
# values with uncertainty):
kwargs_uncert_values = {}
for name in names_w_uncert:
value_with_uncert = kwargs[name]
# Saving for future use:
kwargs_uncert_values[name] = value_with_uncert
# The original dictionary is modified (for efficiency reasons):
kwargs[name] = value_with_uncert.nominal_value
f_nominal_value = f(*args_values, **kwargs)
# If the value is not a float, then this code cannot provide
# the result, as it returns a UFloat, which represents a
# random real variable. This happens for instance when
# ufloat()*numpy.array() is calculated: the
# AffineScalarFunc.__mul__ operator, obtained through wrap(),
# returns a NumPy array, not a float:
if not isinstance(f_nominal_value, FLOAT_LIKE_TYPES):
return NotImplemented
########################################
# Calculation of the linear part of the function value,
# defined by (coefficient, argument) pairs, where 'argument'
# is an AffineScalarFunc (for all AffineScalarFunc found as
# argument of f):
linear_part = []
for pos in pos_w_uncert:
linear_part.append((
# Coefficient:
derivatives_args_index[pos](*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
args[pos]._linear_part))
for name in names_w_uncert:
# Optimization: caching of the automatic numerical
# derivatives for keyword arguments that are
# discovered. This gives a speedup when the original
# function is called repeatedly with the same keyword
# arguments:
derivative = derivatives_all_kwargs.setdefault(
name,
# Derivative never needed before:
partial_derivative(f, name))
linear_part.append((
# Coefficient:
derivative(*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
kwargs_uncert_values[name]._linear_part))
# The function now returns the necessary linear approximation
# to the function:
return AffineScalarFunc(
f_nominal_value, LinearCombination(linear_part))
f_with_affine_output = set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))(f_with_affine_output)
# It is easier to work with f_with_affine_output, which represents
# a wrapped version of 'f', when it bears the same name as 'f':
# ! __name__ is read-only, in Python 2.3:
f_with_affine_output.name = f.__name__
return f_with_affine_output
|
(*args, **kwargs)
|
61,737 |
uncertainties.core
|
f_with_affine_output
|
Version of __trunc__(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
Return the Integral closest to x between 0 and x.
|
def wrap(f, derivatives_args=[], derivatives_kwargs={}):
"""
Wraps a function f into a function that also accepts numbers with
uncertainties (UFloat objects); the wrapped function returns the
value of f with the correct uncertainty and correlations. The
wrapped function is intended to be used as a drop-in replacement
for the original function: they can be called in the exact same
way, the only difference being that numbers with uncertainties can
be given to the wrapped function where f accepts float arguments.
Doing so may be necessary when function f cannot be expressed
analytically (with uncertainties-compatible operators and
functions like +, *, umath.sin(), etc.).
f must return a float-like (i.e. a float, an int, etc., not a
list, etc.), unless when called with no number with
uncertainty. This is because the wrapped function generally
returns numbers with uncertainties: they represent a probability
distribution over the real numbers.
If the wrapped function is called with no argument that has an
uncertainty, the value of f is returned.
Parameters: the derivatives_* parameters can be used for defining
some of the partial derivatives of f. All the (non-None)
derivatives must have the same signature as f.
derivatives_args --
Iterable that, when iterated over, returns either derivatives
(functions) or None. derivatives_args can in particular be a
simple sequence (list or tuple) that gives the derivatives of
the first positional parameters of f.
Each function must be the partial derivative of f with respect
to the corresponding positional parameters. These functions
take the same arguments as f.
The positional parameters of a function are usually
positional-or-keyword parameters like in the call func(a,
b=None). However, they also include var-positional parameters
given through the func(a, b, *args) *args syntax. In the last
example, derivatives_args can be an iterable that returns the
derivative with respect to a, b and then to each optional
argument in args.
A value of None (instead of a function) obtained when
iterating over derivatives_args is automatically replaced by
the relevant numerical derivative. This derivative is not used
if the corresponding argument is not a number with
uncertainty. A None value can therefore be used for non-scalar
arguments of f (like string arguments).
If the derivatives_args iterable yields fewer derivatives than
needed, wrap() automatically sets the remaining unspecified
derivatives to None (i.e. to the automatic numerical
calculation of derivatives).
An indefinite number of derivatives can be specified by having
derivatives_args be an infinite iterator; this can for
instance be used for specifying the derivatives of functions
with a undefined number of argument (like sum(), whose partial
derivatives all return 1).
derivatives_kwargs --
Dictionary that maps keyword parameters to their derivatives,
or None (as in derivatives_args).
Keyword parameters are defined as being those of kwargs when f
has a signature of the form f(..., **kwargs). In Python 3,
these keyword parameters also include keyword-only parameters.
Non-mapped keyword parameters are replaced automatically by
None: the wrapped function will use, if necessary, numerical
differentiation for these parameters (as with
derivatives_args).
Note that this dictionary only maps keyword *parameters* from
the *signature* of f. The way the wrapped function is called
is immaterial: for example, if f has signature f(a, b=None),
then derivatives_kwargs should be the empty dictionary, even
if the wrapped f can be called a wrapped_f(a=123, b=42).
Example (for illustration purposes only, as
uncertainties.umath.sin() runs faster than the examples that
follow): 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.
Numerically calculated derivatives are meaningless when the
function is not differentiable (e.g., math.hypot(x, y) in (x, y) =
(0, 0), and sqrt(x) in x = 0). The corresponding uncertainties are
either meaningless (case of hypot) or raise an exception when
calculated (case of sqrt). In such cases, it is recommended (but
not mandatory) to supply instead a derivative function that
returns NaN where the function is not differentiable. This
function can still numerically calculate the derivative where
defined, for instance by using the
uncertainties.core.partial_derivative() function.
The correctness of the supplied analytical derivatives an be
tested by setting them to None instead and comparing the
analytical and the numerical differentiation results.
Note on efficiency: the wrapped function assumes that f cannot
accept numbers with uncertainties as arguments. If f actually does
handle some arguments even when they have an uncertainty, the
wrapped function ignores this fact, which might lead to a
performance hit: wrapping a function that actually accepts numbers
with uncertainty is likely to make it slower.
"""
derivatives_args_index = IndexableIter(
# Automatic addition of numerical derivatives in case the
# supplied derivatives_args is shorter than the number of
# arguments in *args:
itertools.chain(derivatives_args, itertools.repeat(None)))
# Derivatives for keyword arguments (includes var-keyword
# parameters **kwargs, but also var-or-keyword parameters, and
# keyword-only parameters (Python 3):
derivatives_all_kwargs = {}
for (name, derivative) in derivatives_kwargs.items():
# Optimization: None keyword-argument derivatives are converted
# right away to derivatives (instead of doing this every time a
# None derivative is encountered when calculating derivatives):
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# When the wrapped function is called with keyword arguments that
# map to positional-or-keyword parameters, their derivative is
# looked for in derivatives_all_kwargs. We define these
# additional derivatives:
try:
argspec = getargspec(f)
except TypeError:
# Some functions do not provide meta-data about their
# arguments (see PEP 362). One cannot use keyword arguments
# for positional-or-keyword parameters with them: nothing has
# to be done:
pass
else:
# With Python 3, there is no need to handle keyword-only
# arguments (and therefore to use inspect.getfullargspec())
# because they are already handled by derivatives_kwargs.
for (index, name) in enumerate(argspec.args):
# The following test handles the case of
# positional-or-keyword parameter for which automatic
# numerical differentiation is used: when the wrapped
# function is called with a keyword argument for this
# parameter, the numerical derivative must be calculated
# with respect to the parameter name. In the other case,
# where the wrapped function is called with a positional
# argument, the derivative with respect to its index must
# be used:
derivative = derivatives_args_index[index]
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# Optimization: None derivatives for the positional arguments are
# converted to the corresponding numerical differentiation
# function (instead of doing this over and over later every time a
# None derivative is found):
none_converter = lambda index: partial_derivative(f, index)
for (index, derivative) in enumerate(
derivatives_args_index.returned_elements):
if derivative is None:
derivatives_args_index.returned_elements[index] = (
none_converter(index))
# Future None values are also automatically converted:
derivatives_args_index.none_converter = none_converter
## Wrapped function:
#! Setting the doc string after "def f_with...()" does not
# seem to work. We define it explicitly:
@set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))
def f_with_affine_output(*args, **kwargs):
########################################
# The involved random variables must first be gathered, so
# that they can be independently updated.
# The arguments that contain an uncertainty (AffineScalarFunc
# objects) are gathered, as positions or names; they will be
# replaced by their nominal value in order to calculate
# the necessary derivatives of f.
pos_w_uncert = [index for (index, value) in enumerate(args)
if isinstance(value, AffineScalarFunc)]
names_w_uncert = [key for (key, value) in kwargs.items()
if isinstance(value, AffineScalarFunc)]
########################################
# Value of f() at the nominal value of the arguments with
# uncertainty:
# The usual behavior of f() is kept, if no number with
# uncertainty is provided:
if (not pos_w_uncert) and (not names_w_uncert):
return f(*args, **kwargs)
### Nominal values of the (scalar) arguments:
# !! Possible optimization: If pos_w_uncert is empty, there
# is actually no need to create a mutable version of args and
# one could do args_values = args. However, the wrapped
# function is typically called with numbers with uncertainties
# as positional arguments (i.e., pos_w_uncert is not emtpy),
# so this "optimization" is not implemented here.
## Positional arguments:
args_values = list(args) # Now mutable: modified below
# Arguments with an uncertainty are converted to their nominal
# value:
for index in pos_w_uncert:
args_values[index] = args[index].nominal_value
## Keyword arguments:
# For efficiency reasons, kwargs is not copied. Instead, its
# values with uncertainty are modified:
# The original values with uncertainties are needed: they are
# saved in the following dictionary (which only contains
# values with uncertainty):
kwargs_uncert_values = {}
for name in names_w_uncert:
value_with_uncert = kwargs[name]
# Saving for future use:
kwargs_uncert_values[name] = value_with_uncert
# The original dictionary is modified (for efficiency reasons):
kwargs[name] = value_with_uncert.nominal_value
f_nominal_value = f(*args_values, **kwargs)
# If the value is not a float, then this code cannot provide
# the result, as it returns a UFloat, which represents a
# random real variable. This happens for instance when
# ufloat()*numpy.array() is calculated: the
# AffineScalarFunc.__mul__ operator, obtained through wrap(),
# returns a NumPy array, not a float:
if not isinstance(f_nominal_value, FLOAT_LIKE_TYPES):
return NotImplemented
########################################
# Calculation of the linear part of the function value,
# defined by (coefficient, argument) pairs, where 'argument'
# is an AffineScalarFunc (for all AffineScalarFunc found as
# argument of f):
linear_part = []
for pos in pos_w_uncert:
linear_part.append((
# Coefficient:
derivatives_args_index[pos](*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
args[pos]._linear_part))
for name in names_w_uncert:
# Optimization: caching of the automatic numerical
# derivatives for keyword arguments that are
# discovered. This gives a speedup when the original
# function is called repeatedly with the same keyword
# arguments:
derivative = derivatives_all_kwargs.setdefault(
name,
# Derivative never needed before:
partial_derivative(f, name))
linear_part.append((
# Coefficient:
derivative(*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
kwargs_uncert_values[name]._linear_part))
# The function now returns the necessary linear approximation
# to the function:
return AffineScalarFunc(
f_nominal_value, LinearCombination(linear_part))
f_with_affine_output = set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))(f_with_affine_output)
# It is easier to work with f_with_affine_output, which represents
# a wrapped version of 'f', when it bears the same name as 'f':
# ! __name__ is read-only, in Python 2.3:
f_with_affine_output.name = f.__name__
return f_with_affine_output
|
(*args, **kwargs)
|
61,738 |
uncertainties.core
|
error_components
|
Individual components of the standard deviation of the affine
function (in absolute value), returned as a dictionary with
Variable objects as keys. The returned variables are the
independent variables that the affine function depends on.
This method assumes that the derivatives contained in the
object take scalar values (and are not a tuple, like what
math.frexp() returns, for instance).
|
def error_components(self):
"""
Individual components of the standard deviation of the affine
function (in absolute value), returned as a dictionary with
Variable objects as keys. The returned variables are the
independent variables that the affine function depends on.
This method assumes that the derivatives contained in the
object take scalar values (and are not a tuple, like what
math.frexp() returns, for instance).
"""
# Calculation of the variance:
error_components = {}
for (variable, derivative) in self.derivatives.items():
# print "TYPE", type(variable), type(derivative)
# Individual standard error due to variable:
# 0 is returned even for a NaN derivative (in this case no
# multiplication by the derivative is performed): an exact
# variable obviously leads to no uncertainty in the
# functions that depend on it.
if variable._std_dev == 0:
# !!! Shouldn't the errors always be floats, as a
# convention of this module?
error_components[variable] = 0
else:
error_components[variable] = abs(derivative*variable._std_dev)
return error_components
|
(self)
|
61,739 |
uncertainties.core
|
format
|
Return the same result as self.__format__(format_spec), or
equivalently as the format(self, format_spec) of Python 2.6+.
This method is meant to be used for formatting numbers with
uncertainties in Python < 2.6, with '... %s ...' %
num.format('.2e').
|
@set_doc("""
Return the same result as self.__format__(format_spec), or
equivalently as the format(self, format_spec) of Python 2.6+.
This method is meant to be used for formatting numbers with
uncertainties in Python < 2.6, with '... %s ...' %
num.format('.2e').
""")
def format(*args, **kwargs):
return args[0].__format__(*args[1:], **kwargs)
|
(*args, **kwargs)
|
61,740 |
uncertainties.core
|
std_score
|
Return 'value' - nominal value, in units of the standard
deviation.
Raises a ValueError exception if the standard deviation is zero.
|
def std_score(self, value):
"""
Return 'value' - nominal value, in units of the standard
deviation.
Raises a ValueError exception if the standard deviation is zero.
"""
try:
# The ._nominal_value is a float: there is no integer division,
# here:
return (value - self._nominal_value) / self.std_dev
except ZeroDivisionError:
raise ValueError("The standard deviation is zero:"
" undefined result")
|
(self, value)
|
61,742 |
uncertainties.core
|
correlated_values
|
Return numbers with uncertainties (AffineScalarFunc objects)
that correctly reproduce the given covariance matrix, and have
the given (float) values as their nominal value.
The correlated_values_norm() function returns the same result,
but takes a correlation matrix instead of a covariance matrix.
The list of values and the covariance matrix must have the
same length, and the matrix must be a square (symmetric) one.
The numbers with uncertainties returned depend on newly
created, independent variables (Variable objects).
nom_values -- sequence with the nominal (real) values of the
numbers with uncertainties to be returned.
covariance_mat -- full covariance matrix of the returned numbers with
uncertainties. For example, the first element of this matrix is the
variance of the first number with uncertainty. This matrix must be a
NumPy array-like (list of lists, NumPy array, etc.).
tags -- if 'tags' is not None, it must list the tag of each new
independent variable.
|
def correlated_values(nom_values, covariance_mat, tags=None):
"""
Return numbers with uncertainties (AffineScalarFunc objects)
that correctly reproduce the given covariance matrix, and have
the given (float) values as their nominal value.
The correlated_values_norm() function returns the same result,
but takes a correlation matrix instead of a covariance matrix.
The list of values and the covariance matrix must have the
same length, and the matrix must be a square (symmetric) one.
The numbers with uncertainties returned depend on newly
created, independent variables (Variable objects).
nom_values -- sequence with the nominal (real) values of the
numbers with uncertainties to be returned.
covariance_mat -- full covariance matrix of the returned numbers with
uncertainties. For example, the first element of this matrix is the
variance of the first number with uncertainty. This matrix must be a
NumPy array-like (list of lists, NumPy array, etc.).
tags -- if 'tags' is not None, it must list the tag of each new
independent variable.
"""
# !!! It would in principle be possible to handle 0 variance
# variables by first selecting the sub-matrix that does not contain
# such variables (with the help of numpy.ix_()), and creating
# them separately.
std_devs = numpy.sqrt(numpy.diag(covariance_mat))
# For numerical stability reasons, we go through the correlation
# matrix, because it is insensitive to any change of scale in the
# quantities returned. However, care must be taken with 0 variance
# variables: calculating the correlation matrix cannot be simply done
# by dividing by standard deviations. We thus use specific
# normalization values, with no null value:
norm_vector = std_devs.copy()
norm_vector[norm_vector==0] = 1
return correlated_values_norm(
# !! The following zip() is a bit suboptimal: correlated_values()
# separates back the nominal values and the standard deviations:
list(zip(nom_values, std_devs)),
covariance_mat/norm_vector/norm_vector[:,numpy.newaxis],
tags)
|
(nom_values, covariance_mat, tags=None)
|
61,743 |
uncertainties.core
|
correlated_values_norm
|
Return correlated values like correlated_values(), but takes
instead as input:
- nominal (float) values along with their standard deviation, and
- a correlation matrix (i.e. a normalized covariance matrix).
values_with_std_dev -- sequence of (nominal value, standard
deviation) pairs. The returned, correlated values have these
nominal values and standard deviations.
correlation_mat -- correlation matrix between the given values, except
that any value with a 0 standard deviation must have its correlations
set to 0, with a diagonal element set to an arbitrary value (something
close to 0-1 is recommended, for a better numerical precision). When
no value has a 0 variance, this is the covariance matrix normalized by
standard deviations, and thus a symmetric matrix with ones on its
diagonal. This matrix must be an NumPy array-like (list of lists,
NumPy array, etc.).
tags -- like for correlated_values().
|
def correlated_values_norm(values_with_std_dev, correlation_mat,
tags=None):
'''
Return correlated values like correlated_values(), but takes
instead as input:
- nominal (float) values along with their standard deviation, and
- a correlation matrix (i.e. a normalized covariance matrix).
values_with_std_dev -- sequence of (nominal value, standard
deviation) pairs. The returned, correlated values have these
nominal values and standard deviations.
correlation_mat -- correlation matrix between the given values, except
that any value with a 0 standard deviation must have its correlations
set to 0, with a diagonal element set to an arbitrary value (something
close to 0-1 is recommended, for a better numerical precision). When
no value has a 0 variance, this is the covariance matrix normalized by
standard deviations, and thus a symmetric matrix with ones on its
diagonal. This matrix must be an NumPy array-like (list of lists,
NumPy array, etc.).
tags -- like for correlated_values().
'''
# If no tags were given, we prepare tags for the newly created
# variables:
if tags is None:
tags = (None,) * len(values_with_std_dev)
(nominal_values, std_devs) = numpy.transpose(values_with_std_dev)
# We diagonalize the correlation matrix instead of the
# covariance matrix, because this is generally more stable
# numerically. In fact, the covariance matrix can have
# coefficients with arbitrary values, through changes of units
# of its input variables. This creates numerical instabilities.
#
# The covariance matrix is diagonalized in order to define
# the independent variables that model the given values:
(variances, transform) = numpy.linalg.eigh(correlation_mat)
# Numerical errors might make some variances negative: we set
# them to zero:
variances[variances < 0] = 0.
# Creation of new, independent variables:
# We use the fact that the eigenvectors in 'transform' are
# special: 'transform' is unitary: its inverse is its transpose:
variables = tuple(
# The variables represent "pure" uncertainties:
Variable(0, sqrt(variance), tag)
for (variance, tag) in zip(variances, tags))
# The coordinates of each new uncertainty as a function of the
# new variables must include the variable scale (standard deviation):
transform *= std_devs[:, numpy.newaxis]
# Representation of the initial correlated values:
values_funcs = tuple(
AffineScalarFunc(
value,
LinearCombination(dict(zip(variables, coords))))
for (coords, value) in zip(transform, nominal_values))
return values_funcs
|
(values_with_std_dev, correlation_mat, tags=None)
|
61,744 |
uncertainties.core
|
correlation_matrix
|
Return the correlation matrix of the given sequence of
numbers with uncertainties, as a NumPy array of floats.
|
def correlation_matrix(nums_with_uncert):
'''
Return the correlation matrix of the given sequence of
numbers with uncertainties, as a NumPy array of floats.
'''
cov_mat = numpy.array(covariance_matrix(nums_with_uncert))
std_devs = numpy.sqrt(cov_mat.diagonal())
return cov_mat/std_devs/std_devs[numpy.newaxis].T
|
(nums_with_uncert)
|
61,745 |
uncertainties.core
|
covariance_matrix
|
Return 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
'nums_with_uncert'.
The covariances are floats (never int objects).
The returned covariance matrix is the exact linear approximation
result, if the nominal values of the numbers with uncertainties
and of their variables are their mean. Otherwise, the returned
covariance matrix should be close to its linear approximation
value.
The returned matrix is a list of lists.
|
def covariance_matrix(nums_with_uncert):
"""
Return 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
'nums_with_uncert'.
The covariances are floats (never int objects).
The returned covariance matrix is the exact linear approximation
result, if the nominal values of the numbers with uncertainties
and of their variables are their mean. Otherwise, the returned
covariance matrix should be close to its linear approximation
value.
The returned matrix is a list of lists.
"""
# See PSI.411 in EOL's notes.
covariance_matrix = []
for (i1, expr1) in enumerate(nums_with_uncert, 1):
derivatives1 = expr1.derivatives # Optimization
vars1 = set(derivatives1) # !! Python 2.7+: viewkeys() would work
coefs_expr1 = []
for expr2 in nums_with_uncert[:i1]:
derivatives2 = expr2.derivatives # Optimization
coefs_expr1.append(sum(
((derivatives1[var]*derivatives2[var]*var._std_dev**2)
# var is a variable common to both numbers with
# uncertainties:
for var in vars1.intersection(derivatives2)),
# The result is always a float (sum() with no terms
# returns an integer):
0.))
covariance_matrix.append(coefs_expr1)
# We symmetrize the matrix:
for (i, covariance_coefs) in enumerate(covariance_matrix):
covariance_coefs.extend([covariance_matrix[j][i]
for j in range(i+1, len(covariance_matrix))])
return covariance_matrix
|
(nums_with_uncert)
|
61,747 |
uncertainties.core
|
nominal_value
|
Return 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.
|
def nominal_value(x):
"""
Return 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.
"""
if isinstance(x, AffineScalarFunc):
return x.nominal_value
else:
return x
|
(x)
|
61,748 |
uncertainties.core
|
std_dev
|
Return 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.
|
def std_dev(x):
"""
Return 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.
"""
if isinstance(x, AffineScalarFunc):
return x.std_dev
else:
return 0.
|
(x)
|
61,749 |
uncertainties.core
|
ufloat
|
Return a new random variable (Variable object).
The only non-obsolete use is:
- ufloat(nominal_value, std_dev),
- ufloat(nominal_value, std_dev, tag=...).
Other input parameters are temporarily supported:
- ufloat((nominal_value, std_dev)),
- ufloat((nominal_value, std_dev), tag),
- ufloat(str_representation),
- ufloat(str_representation, tag).
Valid string representations str_representation are listed in
the documentation for ufloat_fromstr().
nominal_value -- nominal value of the random variable. It is more
meaningful to use a value close to the central value or to the
mean. This value is propagated by mathematical operations as if it
was a float.
std_dev -- standard deviation of the random variable. The standard
deviation must be convertible to a positive float, or be NaN.
tag -- 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).
|
def ufloat(nominal_value, std_dev=None, tag=None):
"""
Return a new random variable (Variable object).
The only non-obsolete use is:
- ufloat(nominal_value, std_dev),
- ufloat(nominal_value, std_dev, tag=...).
Other input parameters are temporarily supported:
- ufloat((nominal_value, std_dev)),
- ufloat((nominal_value, std_dev), tag),
- ufloat(str_representation),
- ufloat(str_representation, tag).
Valid string representations str_representation are listed in
the documentation for ufloat_fromstr().
nominal_value -- nominal value of the random variable. It is more
meaningful to use a value close to the central value or to the
mean. This value is propagated by mathematical operations as if it
was a float.
std_dev -- standard deviation of the random variable. The standard
deviation must be convertible to a positive float, or be NaN.
tag -- 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).
"""
try:
# Standard case:
return Variable(nominal_value, std_dev, tag=tag)
# Exception types raised by, respectively: tuple or string that
# can be converted through float() (case of a number with no
# uncertainty), and string that cannot be converted through
# float():
except (TypeError, ValueError):
if tag is not None:
tag_arg = tag # tag keyword used:
else:
tag_arg = std_dev # 2 positional arguments form
try:
final_ufloat = ufloat_obsolete(nominal_value, tag_arg)
except: # The input is incorrect, not obsolete
raise
else:
# Obsolete, two-argument call:
deprecation(
'either use ufloat(nominal_value, std_dev),'
' ufloat(nominal_value, std_dev, tag), or the'
' ufloat_fromstr() function, for string representations.')
return final_ufloat
|
(nominal_value, std_dev=None, tag=None)
|
61,750 |
uncertainties.core
|
ufloat_fromstr
|
Return a new random variable (Variable object) from a string.
Strings 'representation' of the form '12.345+/-0.015',
'12.345(15)', '12.3' or u'1.2±0.1' (Unicode string) are recognized
(see more complete list below). In the last case, an uncertainty
of +/-1 is assigned to the last digit.
Invalid representations raise a ValueError.
This function tries to parse back most of the formats that are made
available by this module. Examples of valid string representations:
12.3e10+/-5e3
(-3.1415 +/- 0.0001)e+02 # Factored exponent
# Pretty-print notation (only with a unicode string):
12.3e10 ± 5e3 # ± symbol
(12.3 ± 5.0) × 10⁻¹² # Times symbol, superscript
12.3 ± 5e3 # Mixed notation (± symbol, but e exponent)
# Double-exponent values:
(-3.1415 +/- 1e-4)e+200
(1e-20 +/- 3)e100
0.29
31.
-31.
31
-3.1e10
-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
12.3(0.4)e-5
169.0(7)
169.1(15)
.123(4)
.1(.4)
# NaN uncertainties:
12.3(nan)
12.3(NAN)
3±nan
Surrounding spaces are ignored.
About the "shorthand" notation: 1.23(3) = 1.23 ± 0.03 but
1.23(3.) = 1.23 ± 3.00. Thus, the presence of a decimal point in
the uncertainty signals an absolute uncertainty (instead of an
uncertainty on the last digits of the nominal value).
|
def ufloat_fromstr(representation, tag=None):
"""
Return a new random variable (Variable object) from a string.
Strings 'representation' of the form '12.345+/-0.015',
'12.345(15)', '12.3' or u'1.2±0.1' (Unicode string) are recognized
(see more complete list below). In the last case, an uncertainty
of +/-1 is assigned to the last digit.
Invalid representations raise a ValueError.
This function tries to parse back most of the formats that are made
available by this module. Examples of valid string representations:
12.3e10+/-5e3
(-3.1415 +/- 0.0001)e+02 # Factored exponent
# Pretty-print notation (only with a unicode string):
12.3e10 ± 5e3 # ± symbol
(12.3 ± 5.0) × 10⁻¹² # Times symbol, superscript
12.3 ± 5e3 # Mixed notation (± symbol, but e exponent)
# Double-exponent values:
(-3.1415 +/- 1e-4)e+200
(1e-20 +/- 3)e100
0.29
31.
-31.
31
-3.1e10
-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
12.3(0.4)e-5
169.0(7)
169.1(15)
.123(4)
.1(.4)
# NaN uncertainties:
12.3(nan)
12.3(NAN)
3±nan
Surrounding spaces are ignored.
About the "shorthand" notation: 1.23(3) = 1.23 ± 0.03 but
1.23(3.) = 1.23 ± 3.00. Thus, the presence of a decimal point in
the uncertainty signals an absolute uncertainty (instead of an
uncertainty on the last digits of the nominal value).
"""
(nominal_value, std_dev) = str_to_number_with_uncert(
representation.strip())
return ufloat(nominal_value, std_dev, tag)
|
(representation, tag=None)
|
61,751 |
uncertainties.core
|
wrap
|
Wraps a function f into a function that also accepts numbers with
uncertainties (UFloat objects); the wrapped function returns the
value of f with the correct uncertainty and correlations. The
wrapped function is intended to be used as a drop-in replacement
for the original function: they can be called in the exact same
way, the only difference being that numbers with uncertainties can
be given to the wrapped function where f accepts float arguments.
Doing so may be necessary when function f cannot be expressed
analytically (with uncertainties-compatible operators and
functions like +, *, umath.sin(), etc.).
f must return a float-like (i.e. a float, an int, etc., not a
list, etc.), unless when called with no number with
uncertainty. This is because the wrapped function generally
returns numbers with uncertainties: they represent a probability
distribution over the real numbers.
If the wrapped function is called with no argument that has an
uncertainty, the value of f is returned.
Parameters: the derivatives_* parameters can be used for defining
some of the partial derivatives of f. All the (non-None)
derivatives must have the same signature as f.
derivatives_args --
Iterable that, when iterated over, returns either derivatives
(functions) or None. derivatives_args can in particular be a
simple sequence (list or tuple) that gives the derivatives of
the first positional parameters of f.
Each function must be the partial derivative of f with respect
to the corresponding positional parameters. These functions
take the same arguments as f.
The positional parameters of a function are usually
positional-or-keyword parameters like in the call func(a,
b=None). However, they also include var-positional parameters
given through the func(a, b, *args) *args syntax. In the last
example, derivatives_args can be an iterable that returns the
derivative with respect to a, b and then to each optional
argument in args.
A value of None (instead of a function) obtained when
iterating over derivatives_args is automatically replaced by
the relevant numerical derivative. This derivative is not used
if the corresponding argument is not a number with
uncertainty. A None value can therefore be used for non-scalar
arguments of f (like string arguments).
If the derivatives_args iterable yields fewer derivatives than
needed, wrap() automatically sets the remaining unspecified
derivatives to None (i.e. to the automatic numerical
calculation of derivatives).
An indefinite number of derivatives can be specified by having
derivatives_args be an infinite iterator; this can for
instance be used for specifying the derivatives of functions
with a undefined number of argument (like sum(), whose partial
derivatives all return 1).
derivatives_kwargs --
Dictionary that maps keyword parameters to their derivatives,
or None (as in derivatives_args).
Keyword parameters are defined as being those of kwargs when f
has a signature of the form f(..., **kwargs). In Python 3,
these keyword parameters also include keyword-only parameters.
Non-mapped keyword parameters are replaced automatically by
None: the wrapped function will use, if necessary, numerical
differentiation for these parameters (as with
derivatives_args).
Note that this dictionary only maps keyword *parameters* from
the *signature* of f. The way the wrapped function is called
is immaterial: for example, if f has signature f(a, b=None),
then derivatives_kwargs should be the empty dictionary, even
if the wrapped f can be called a wrapped_f(a=123, b=42).
Example (for illustration purposes only, as
uncertainties.umath.sin() runs faster than the examples that
follow): 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.
Numerically calculated derivatives are meaningless when the
function is not differentiable (e.g., math.hypot(x, y) in (x, y) =
(0, 0), and sqrt(x) in x = 0). The corresponding uncertainties are
either meaningless (case of hypot) or raise an exception when
calculated (case of sqrt). In such cases, it is recommended (but
not mandatory) to supply instead a derivative function that
returns NaN where the function is not differentiable. This
function can still numerically calculate the derivative where
defined, for instance by using the
uncertainties.core.partial_derivative() function.
The correctness of the supplied analytical derivatives an be
tested by setting them to None instead and comparing the
analytical and the numerical differentiation results.
Note on efficiency: the wrapped function assumes that f cannot
accept numbers with uncertainties as arguments. If f actually does
handle some arguments even when they have an uncertainty, the
wrapped function ignores this fact, which might lead to a
performance hit: wrapping a function that actually accepts numbers
with uncertainty is likely to make it slower.
|
def wrap(f, derivatives_args=[], derivatives_kwargs={}):
"""
Wraps a function f into a function that also accepts numbers with
uncertainties (UFloat objects); the wrapped function returns the
value of f with the correct uncertainty and correlations. The
wrapped function is intended to be used as a drop-in replacement
for the original function: they can be called in the exact same
way, the only difference being that numbers with uncertainties can
be given to the wrapped function where f accepts float arguments.
Doing so may be necessary when function f cannot be expressed
analytically (with uncertainties-compatible operators and
functions like +, *, umath.sin(), etc.).
f must return a float-like (i.e. a float, an int, etc., not a
list, etc.), unless when called with no number with
uncertainty. This is because the wrapped function generally
returns numbers with uncertainties: they represent a probability
distribution over the real numbers.
If the wrapped function is called with no argument that has an
uncertainty, the value of f is returned.
Parameters: the derivatives_* parameters can be used for defining
some of the partial derivatives of f. All the (non-None)
derivatives must have the same signature as f.
derivatives_args --
Iterable that, when iterated over, returns either derivatives
(functions) or None. derivatives_args can in particular be a
simple sequence (list or tuple) that gives the derivatives of
the first positional parameters of f.
Each function must be the partial derivative of f with respect
to the corresponding positional parameters. These functions
take the same arguments as f.
The positional parameters of a function are usually
positional-or-keyword parameters like in the call func(a,
b=None). However, they also include var-positional parameters
given through the func(a, b, *args) *args syntax. In the last
example, derivatives_args can be an iterable that returns the
derivative with respect to a, b and then to each optional
argument in args.
A value of None (instead of a function) obtained when
iterating over derivatives_args is automatically replaced by
the relevant numerical derivative. This derivative is not used
if the corresponding argument is not a number with
uncertainty. A None value can therefore be used for non-scalar
arguments of f (like string arguments).
If the derivatives_args iterable yields fewer derivatives than
needed, wrap() automatically sets the remaining unspecified
derivatives to None (i.e. to the automatic numerical
calculation of derivatives).
An indefinite number of derivatives can be specified by having
derivatives_args be an infinite iterator; this can for
instance be used for specifying the derivatives of functions
with a undefined number of argument (like sum(), whose partial
derivatives all return 1).
derivatives_kwargs --
Dictionary that maps keyword parameters to their derivatives,
or None (as in derivatives_args).
Keyword parameters are defined as being those of kwargs when f
has a signature of the form f(..., **kwargs). In Python 3,
these keyword parameters also include keyword-only parameters.
Non-mapped keyword parameters are replaced automatically by
None: the wrapped function will use, if necessary, numerical
differentiation for these parameters (as with
derivatives_args).
Note that this dictionary only maps keyword *parameters* from
the *signature* of f. The way the wrapped function is called
is immaterial: for example, if f has signature f(a, b=None),
then derivatives_kwargs should be the empty dictionary, even
if the wrapped f can be called a wrapped_f(a=123, b=42).
Example (for illustration purposes only, as
uncertainties.umath.sin() runs faster than the examples that
follow): 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.
Numerically calculated derivatives are meaningless when the
function is not differentiable (e.g., math.hypot(x, y) in (x, y) =
(0, 0), and sqrt(x) in x = 0). The corresponding uncertainties are
either meaningless (case of hypot) or raise an exception when
calculated (case of sqrt). In such cases, it is recommended (but
not mandatory) to supply instead a derivative function that
returns NaN where the function is not differentiable. This
function can still numerically calculate the derivative where
defined, for instance by using the
uncertainties.core.partial_derivative() function.
The correctness of the supplied analytical derivatives an be
tested by setting them to None instead and comparing the
analytical and the numerical differentiation results.
Note on efficiency: the wrapped function assumes that f cannot
accept numbers with uncertainties as arguments. If f actually does
handle some arguments even when they have an uncertainty, the
wrapped function ignores this fact, which might lead to a
performance hit: wrapping a function that actually accepts numbers
with uncertainty is likely to make it slower.
"""
derivatives_args_index = IndexableIter(
# Automatic addition of numerical derivatives in case the
# supplied derivatives_args is shorter than the number of
# arguments in *args:
itertools.chain(derivatives_args, itertools.repeat(None)))
# Derivatives for keyword arguments (includes var-keyword
# parameters **kwargs, but also var-or-keyword parameters, and
# keyword-only parameters (Python 3):
derivatives_all_kwargs = {}
for (name, derivative) in derivatives_kwargs.items():
# Optimization: None keyword-argument derivatives are converted
# right away to derivatives (instead of doing this every time a
# None derivative is encountered when calculating derivatives):
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# When the wrapped function is called with keyword arguments that
# map to positional-or-keyword parameters, their derivative is
# looked for in derivatives_all_kwargs. We define these
# additional derivatives:
try:
argspec = getargspec(f)
except TypeError:
# Some functions do not provide meta-data about their
# arguments (see PEP 362). One cannot use keyword arguments
# for positional-or-keyword parameters with them: nothing has
# to be done:
pass
else:
# With Python 3, there is no need to handle keyword-only
# arguments (and therefore to use inspect.getfullargspec())
# because they are already handled by derivatives_kwargs.
for (index, name) in enumerate(argspec.args):
# The following test handles the case of
# positional-or-keyword parameter for which automatic
# numerical differentiation is used: when the wrapped
# function is called with a keyword argument for this
# parameter, the numerical derivative must be calculated
# with respect to the parameter name. In the other case,
# where the wrapped function is called with a positional
# argument, the derivative with respect to its index must
# be used:
derivative = derivatives_args_index[index]
if derivative is None:
derivatives_all_kwargs[name] = partial_derivative(f, name)
else:
derivatives_all_kwargs[name] = derivative
# Optimization: None derivatives for the positional arguments are
# converted to the corresponding numerical differentiation
# function (instead of doing this over and over later every time a
# None derivative is found):
none_converter = lambda index: partial_derivative(f, index)
for (index, derivative) in enumerate(
derivatives_args_index.returned_elements):
if derivative is None:
derivatives_args_index.returned_elements[index] = (
none_converter(index))
# Future None values are also automatically converted:
derivatives_args_index.none_converter = none_converter
## Wrapped function:
#! Setting the doc string after "def f_with...()" does not
# seem to work. We define it explicitly:
@set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))
def f_with_affine_output(*args, **kwargs):
########################################
# The involved random variables must first be gathered, so
# that they can be independently updated.
# The arguments that contain an uncertainty (AffineScalarFunc
# objects) are gathered, as positions or names; they will be
# replaced by their nominal value in order to calculate
# the necessary derivatives of f.
pos_w_uncert = [index for (index, value) in enumerate(args)
if isinstance(value, AffineScalarFunc)]
names_w_uncert = [key for (key, value) in kwargs.items()
if isinstance(value, AffineScalarFunc)]
########################################
# Value of f() at the nominal value of the arguments with
# uncertainty:
# The usual behavior of f() is kept, if no number with
# uncertainty is provided:
if (not pos_w_uncert) and (not names_w_uncert):
return f(*args, **kwargs)
### Nominal values of the (scalar) arguments:
# !! Possible optimization: If pos_w_uncert is empty, there
# is actually no need to create a mutable version of args and
# one could do args_values = args. However, the wrapped
# function is typically called with numbers with uncertainties
# as positional arguments (i.e., pos_w_uncert is not emtpy),
# so this "optimization" is not implemented here.
## Positional arguments:
args_values = list(args) # Now mutable: modified below
# Arguments with an uncertainty are converted to their nominal
# value:
for index in pos_w_uncert:
args_values[index] = args[index].nominal_value
## Keyword arguments:
# For efficiency reasons, kwargs is not copied. Instead, its
# values with uncertainty are modified:
# The original values with uncertainties are needed: they are
# saved in the following dictionary (which only contains
# values with uncertainty):
kwargs_uncert_values = {}
for name in names_w_uncert:
value_with_uncert = kwargs[name]
# Saving for future use:
kwargs_uncert_values[name] = value_with_uncert
# The original dictionary is modified (for efficiency reasons):
kwargs[name] = value_with_uncert.nominal_value
f_nominal_value = f(*args_values, **kwargs)
# If the value is not a float, then this code cannot provide
# the result, as it returns a UFloat, which represents a
# random real variable. This happens for instance when
# ufloat()*numpy.array() is calculated: the
# AffineScalarFunc.__mul__ operator, obtained through wrap(),
# returns a NumPy array, not a float:
if not isinstance(f_nominal_value, FLOAT_LIKE_TYPES):
return NotImplemented
########################################
# Calculation of the linear part of the function value,
# defined by (coefficient, argument) pairs, where 'argument'
# is an AffineScalarFunc (for all AffineScalarFunc found as
# argument of f):
linear_part = []
for pos in pos_w_uncert:
linear_part.append((
# Coefficient:
derivatives_args_index[pos](*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
args[pos]._linear_part))
for name in names_w_uncert:
# Optimization: caching of the automatic numerical
# derivatives for keyword arguments that are
# discovered. This gives a speedup when the original
# function is called repeatedly with the same keyword
# arguments:
derivative = derivatives_all_kwargs.setdefault(
name,
# Derivative never needed before:
partial_derivative(f, name))
linear_part.append((
# Coefficient:
derivative(*args_values, **kwargs),
# Linear part of the AffineScalarFunc expression:
kwargs_uncert_values[name]._linear_part))
# The function now returns the necessary linear approximation
# to the function:
return AffineScalarFunc(
f_nominal_value, LinearCombination(linear_part))
f_with_affine_output = set_doc("""\
Version of %s(...) that returns an affine approximation
(AffineScalarFunc object), if its result depends on variables
(Variable objects). Otherwise, returns a simple constant (when
applied to constant arguments).
Warning: arguments of the function that are not AffineScalarFunc
objects must not depend on uncertainties.Variable objects in any
way. Otherwise, the dependence of the result in
uncertainties.Variable objects will be incorrect.
Original documentation:
%s""" % (f.__name__, f.__doc__))(f_with_affine_output)
# It is easier to work with f_with_affine_output, which represents
# a wrapped version of 'f', when it bears the same name as 'f':
# ! __name__ is read-only, in Python 2.3:
f_with_affine_output.name = f.__name__
return f_with_affine_output
|
(f, derivatives_args=[], derivatives_kwargs={})
|
61,752 |
collections.abc
|
AsyncIterable
| null |
from collections.abc import AsyncIterable
|
()
|
61,754 |
collections.abc
|
Callable
| null |
from collections.abc import Callable
|
()
|
61,766 |
waiter
|
Stats
|
Mapping of attempt counts.
|
class Stats(collections.Counter):
"""Mapping of attempt counts."""
def add(self, attempt: int, elapsed: float) -> float:
"""Record attempt and return next value."""
self[attempt] += 1
return elapsed
@property
def total(self) -> float: # type: ignore
"""total number of attempts"""
return sum(self.values())
@property
def failures(self) -> float:
"""number of repeat attempts"""
return self.total - self[0]
|
(iterable=None, /, **kwds)
|
61,789 |
waiter
|
add
|
Record attempt and return next value.
|
def add(self, attempt: int, elapsed: float) -> float:
"""Record attempt and return next value."""
self[attempt] += 1
return elapsed
|
(self, attempt: int, elapsed: float) -> float
|
61,798 |
waiter
|
fibonacci
|
Generate fibonacci sequence.
|
def fibonacci(x, y):
"""Generate fibonacci sequence."""
while True:
yield x
x, y = y, (x + y)
|
(x, y)
|
61,799 |
waiter
|
first
|
Return first item which evaluates to true, like `any` with filtering.
|
def first(predicate: Callable, iterable: Iterable, *default):
"""Return first item which evaluates to true, like `any` with filtering."""
return next(filter(predicate, iterable), *default)
|
(predicate: collections.abc.Callable, iterable: collections.abc.Iterable, *default)
|
61,800 |
waiter
|
grouped
|
Generate slices from a sequence without relying on a fixed `len`.
|
def grouped(queue, size=None):
"""Generate slices from a sequence without relying on a fixed `len`."""
group, start = queue[:size], 0
while group:
start += len(group)
yield group
group = queue[start : size and start + size]
|
(queue, size=None)
|
61,801 |
asyncio.coroutines
|
iscoroutinefunction
|
Return True if func is a decorated coroutine function.
|
def iscoroutinefunction(func):
"""Return True if func is a decorated coroutine function."""
return (inspect.iscoroutinefunction(func) or
getattr(func, '_is_coroutine', None) is _is_coroutine)
|
(func)
|
61,803 |
multimethod
|
multimethod
|
A callable directed acyclic graph of methods.
|
class multimethod(dict):
"""A callable directed acyclic graph of methods."""
__name__: str
pending: set
generics: list[tuple] # positional bases which require instance checks
def __new__(cls, func):
homonym = inspect.currentframe().f_back.f_locals.get(func.__name__)
if isinstance(homonym, multimethod):
return homonym
self = functools.update_wrapper(dict.__new__(cls), func)
self.pending = set()
self.generics = []
return self
def __init__(self, func: Callable):
try:
self[signature.from_hints(func)] = func
except (NameError, AttributeError):
self.pending.add(func)
@tp_overload
def register(self, __func: REGISTERED) -> REGISTERED: ... # pragma: no cover
@tp_overload
def register(self, *args: type) -> Callable[[REGISTERED], REGISTERED]: ... # pragma: no cover
def register(self, *args) -> Callable:
"""Decorator for registering a function.
Optionally call with types to return a decorator for unannotated functions.
"""
if len(args) == 1 and hasattr(args[0], '__annotations__'):
multimethod.__init__(self, *args)
return self if self.__name__ == args[0].__name__ else args[0]
return lambda func: self.__setitem__(args, func) or func
def __get__(self, instance, owner):
return self if instance is None else types.MethodType(self, instance)
def parents(self, types: tuple) -> set:
"""Find immediate parents of potential key."""
parents = {key for key in list(self) if isinstance(key, signature) and key < types}
return parents - {ancestor for parent in parents for ancestor in parent.parents}
def clean(self):
"""Empty the cache."""
for key in list(self):
if not isinstance(key, signature):
super().__delitem__(key)
def copy(self):
"""Return a new multimethod with the same methods."""
return dict.__new__(type(self)).__ior__(self)
def __setitem__(self, types: tuple, func: Callable):
self.clean()
if not isinstance(types, signature):
types = signature(types)
parents = types.parents = self.parents(types)
with contextlib.suppress(ValueError):
types.sig = inspect.signature(func)
self.pop(types, None) # ensure key is overwritten
for key in self:
if types < key and (not parents or parents & key.parents):
key.parents -= parents
key.parents.add(types)
for index, cls in enumerate(types):
if origins := set(subtype.origins(cls)):
self.generics += [()] * (index + 1 - len(self.generics))
self.generics[index] = tuple(origins.union(self.generics[index]))
super().__setitem__(types, func)
self.__doc__ = self.docstring
def __delitem__(self, types: tuple):
self.clean()
super().__delitem__(types)
for key in self:
if types in key.parents:
key.parents = self.parents(key)
self.__doc__ = self.docstring
def select(self, types: tuple, keys: set[signature]) -> Callable:
keys = {key for key in keys if key.callable(*types)}
funcs = {self[key] for key in keys}
if len(funcs) > 1:
groups = collections.defaultdict(set)
for key in keys:
groups[types - key].add(key)
keys = groups[min(groups)]
funcs = {self[key] for key in keys}
if len(funcs) == 1:
warnings.warn("positional distance tie-breaking is deprecated", DeprecationWarning)
if len(funcs) == 1:
return funcs.pop()
raise DispatchError(f"{self.__name__}: {len(keys)} methods found", types, keys)
def __missing__(self, types: tuple) -> Callable:
"""Find and cache the next applicable method of given types."""
self.evaluate()
types = tuple(map(subtype, types))
if types in self:
return self[types]
return self.setdefault(types, self.select(types, self.parents(types)))
def dispatch(self, *args) -> Callable:
types = tuple(map(type, args))
if not any(map(issubclass, types, self.generics)):
return self[types]
matches = {key for key in list(self) if isinstance(key, signature) and key.instances(*args)}
matches -= {ancestor for match in matches for ancestor in match.parents}
return self.select(types, matches)
def __call__(self, *args, **kwargs):
"""Resolve and dispatch to best method."""
self.evaluate()
func = self.dispatch(*args)
try:
return func(*args, **kwargs)
except TypeError as ex:
raise DispatchError(f"Function {func.__code__}") from ex
def evaluate(self):
"""Evaluate any pending forward references."""
while self.pending:
func = self.pending.pop()
self[signature.from_hints(func)] = func
@property
def docstring(self):
"""a descriptive docstring of all registered functions"""
docs = []
for key, func in self.items():
sig = getattr(key, 'sig', '')
if func.__doc__:
docs.append(f'{func.__name__}{sig}\n {func.__doc__}')
return '\n\n'.join(docs)
|
(func)
|
61,804 |
multimethod
|
__call__
|
Resolve and dispatch to best method.
|
def __call__(self, *args, **kwargs):
"""Resolve and dispatch to best method."""
self.evaluate()
func = self.dispatch(*args)
try:
return func(*args, **kwargs)
except TypeError as ex:
raise DispatchError(f"Function {func.__code__}") from ex
|
(self, *args, **kwargs)
|
61,805 |
multimethod
|
__delitem__
| null |
def __delitem__(self, types: tuple):
self.clean()
super().__delitem__(types)
for key in self:
if types in key.parents:
key.parents = self.parents(key)
self.__doc__ = self.docstring
|
(self, types: tuple)
|
61,806 |
multimethod
|
__get__
| null |
def __get__(self, instance, owner):
return self if instance is None else types.MethodType(self, instance)
|
(self, instance, owner)
|
61,807 |
multimethod
|
__init__
| null |
def __init__(self, func: Callable):
try:
self[signature.from_hints(func)] = func
except (NameError, AttributeError):
self.pending.add(func)
|
(self, func: collections.abc.Callable)
|
61,808 |
multimethod
|
__missing__
|
Find and cache the next applicable method of given types.
|
def __missing__(self, types: tuple) -> Callable:
"""Find and cache the next applicable method of given types."""
self.evaluate()
types = tuple(map(subtype, types))
if types in self:
return self[types]
return self.setdefault(types, self.select(types, self.parents(types)))
|
(self, types: tuple) -> collections.abc.Callable
|
61,809 |
multimethod
|
__new__
| null |
def __new__(cls, func):
homonym = inspect.currentframe().f_back.f_locals.get(func.__name__)
if isinstance(homonym, multimethod):
return homonym
self = functools.update_wrapper(dict.__new__(cls), func)
self.pending = set()
self.generics = []
return self
|
(cls, func)
|
61,810 |
multimethod
|
__setitem__
| null |
def __setitem__(self, types: tuple, func: Callable):
self.clean()
if not isinstance(types, signature):
types = signature(types)
parents = types.parents = self.parents(types)
with contextlib.suppress(ValueError):
types.sig = inspect.signature(func)
self.pop(types, None) # ensure key is overwritten
for key in self:
if types < key and (not parents or parents & key.parents):
key.parents -= parents
key.parents.add(types)
for index, cls in enumerate(types):
if origins := set(subtype.origins(cls)):
self.generics += [()] * (index + 1 - len(self.generics))
self.generics[index] = tuple(origins.union(self.generics[index]))
super().__setitem__(types, func)
self.__doc__ = self.docstring
|
(self, types: tuple, func: collections.abc.Callable)
|
61,811 |
multimethod
|
clean
|
Empty the cache.
|
def clean(self):
"""Empty the cache."""
for key in list(self):
if not isinstance(key, signature):
super().__delitem__(key)
|
(self)
|
61,812 |
multimethod
|
copy
|
Return a new multimethod with the same methods.
|
def copy(self):
"""Return a new multimethod with the same methods."""
return dict.__new__(type(self)).__ior__(self)
|
(self)
|
61,813 |
multimethod
|
dispatch
| null |
def dispatch(self, *args) -> Callable:
types = tuple(map(type, args))
if not any(map(issubclass, types, self.generics)):
return self[types]
matches = {key for key in list(self) if isinstance(key, signature) and key.instances(*args)}
matches -= {ancestor for match in matches for ancestor in match.parents}
return self.select(types, matches)
|
(self, *args) -> collections.abc.Callable
|
61,814 |
multimethod
|
evaluate
|
Evaluate any pending forward references.
|
def evaluate(self):
"""Evaluate any pending forward references."""
while self.pending:
func = self.pending.pop()
self[signature.from_hints(func)] = func
|
(self)
|
61,815 |
multimethod
|
parents
|
Find immediate parents of potential key.
|
def parents(self, types: tuple) -> set:
"""Find immediate parents of potential key."""
parents = {key for key in list(self) if isinstance(key, signature) and key < types}
return parents - {ancestor for parent in parents for ancestor in parent.parents}
|
(self, types: tuple) -> set
|
61,816 |
multimethod
|
register
|
Decorator for registering a function.
Optionally call with types to return a decorator for unannotated functions.
|
def register(self, *args) -> Callable:
"""Decorator for registering a function.
Optionally call with types to return a decorator for unannotated functions.
"""
if len(args) == 1 and hasattr(args[0], '__annotations__'):
multimethod.__init__(self, *args)
return self if self.__name__ == args[0].__name__ else args[0]
return lambda func: self.__setitem__(args, func) or func
|
(self, *args) -> collections.abc.Callable
|
61,817 |
multimethod
|
select
| null |
def select(self, types: tuple, keys: set[signature]) -> Callable:
keys = {key for key in keys if key.callable(*types)}
funcs = {self[key] for key in keys}
if len(funcs) > 1:
groups = collections.defaultdict(set)
for key in keys:
groups[types - key].add(key)
keys = groups[min(groups)]
funcs = {self[key] for key in keys}
if len(funcs) == 1:
warnings.warn("positional distance tie-breaking is deprecated", DeprecationWarning)
if len(funcs) == 1:
return funcs.pop()
raise DispatchError(f"{self.__name__}: {len(keys)} methods found", types, keys)
|
(self, types: tuple, keys: set[multimethod.signature]) -> collections.abc.Callable
|
61,819 |
multimethod
|
overload
|
Ordered functions which dispatch based on their annotated predicates.
|
class overload(dict):
"""Ordered functions which dispatch based on their annotated predicates."""
pending: set
__get__ = multimethod.__get__
def __new__(cls, func):
namespace = inspect.currentframe().f_back.f_locals
if func.__name__ not in namespace:
warnings.warn("use `parametric(<base>, <func>)` as a type instead", DeprecationWarning)
self = functools.update_wrapper(super().__new__(cls), func)
self.pending = set()
return namespace.get(func.__name__, self)
def __init__(self, func: Callable):
try:
sig = self.signature(func)
except (NameError, AttributeError):
self.pending.add(func)
else:
self[sig] = func
@classmethod
def signature(cls, func: Callable) -> inspect.Signature:
for name, value in get_type_hints(func).items():
if not callable(value) or isinstance(value, type) or hasattr(value, '__origin__'):
func.__annotations__[name] = isa(value)
return inspect.signature(func)
def __call__(self, *args, **kwargs):
"""Dispatch to first matching function."""
while self.pending:
func = self.pending.pop()
self[self.signature(func)] = func
for sig in reversed(self):
try:
arguments = sig.bind(*args, **kwargs).arguments
except TypeError:
continue
if all(
param.annotation is param.empty or param.annotation(arguments[name])
for name, param in sig.parameters.items()
if name in arguments
):
return self[sig](*args, **kwargs)
raise DispatchError("No matching functions found")
def register(self, func: Callable) -> Callable:
"""Decorator for registering a function."""
self.__init__(func) # type: ignore
return self if self.__name__ == func.__name__ else func # type: ignore
|
(func)
|
61,820 |
multimethod
|
__call__
|
Dispatch to first matching function.
|
def __call__(self, *args, **kwargs):
"""Dispatch to first matching function."""
while self.pending:
func = self.pending.pop()
self[self.signature(func)] = func
for sig in reversed(self):
try:
arguments = sig.bind(*args, **kwargs).arguments
except TypeError:
continue
if all(
param.annotation is param.empty or param.annotation(arguments[name])
for name, param in sig.parameters.items()
if name in arguments
):
return self[sig](*args, **kwargs)
raise DispatchError("No matching functions found")
|
(self, *args, **kwargs)
|
61,822 |
multimethod
|
__init__
| null |
def __init__(self, func: Callable):
try:
sig = self.signature(func)
except (NameError, AttributeError):
self.pending.add(func)
else:
self[sig] = func
|
(self, func: collections.abc.Callable)
|
61,823 |
multimethod
|
__new__
| null |
def __new__(cls, func):
namespace = inspect.currentframe().f_back.f_locals
if func.__name__ not in namespace:
warnings.warn("use `parametric(<base>, <func>)` as a type instead", DeprecationWarning)
self = functools.update_wrapper(super().__new__(cls), func)
self.pending = set()
return namespace.get(func.__name__, self)
|
(cls, func)
|
61,824 |
multimethod
|
register
|
Decorator for registering a function.
|
def register(self, func: Callable) -> Callable:
"""Decorator for registering a function."""
self.__init__(func) # type: ignore
return self if self.__name__ == func.__name__ else func # type: ignore
|
(self, func: collections.abc.Callable) -> collections.abc.Callable
|
61,826 |
waiter
|
partialmethod
|
Variant of functools.partialmethod.
|
class partialmethod(partial):
"""Variant of functools.partialmethod."""
def __get__(self, instance, owner):
return self if instance is None else types.MethodType(self, instance)
| null |
61,829 |
waiter
|
reiter
|
A partial iterator which is re-iterable.
|
class reiter(partial):
"""A partial iterator which is re-iterable."""
__iter__ = partial.__call__
| null |
61,830 |
waiter
|
suppress
|
Variant of `contextlib.suppress`, which also records exception.
| null |
(*exceptions: Exception)
|
61,833 |
waiter
|
waiter
|
An iterable which sleeps for given delays. Aliased as `wait`.
Args:
delays iterable | number: any iterable of seconds, or a scalar which is repeated endlessly
timeout number: optional timeout for iteration
|
class waiter:
"""An iterable which sleeps for given delays. Aliased as `wait`.
Args:
delays iterable | number: any iterable of seconds, or a scalar which is repeated endlessly
timeout number: optional timeout for iteration
"""
Stats = Stats
def __init__(self, delays, timeout=float('inf')):
with suppress(TypeError) as excs:
iter(delays)
self.delays = itertools.repeat(delays) if excs else delays
self.timeout = timeout
self.stats = self.Stats()
def __iter__(self):
"""Generate a slow loop of elapsed time."""
start = time.time()
yield self.stats.add(0, 0.0)
for attempt, delay in enumerate(self.delays, 1):
remaining = start + self.timeout - time.time()
if remaining < 0:
break
time.sleep(min(delay, remaining))
yield self.stats.add(attempt, time.time() - start)
async def __aiter__(self):
"""Asynchronously generate a slow loop of elapsed time."""
start = time.time()
yield self.stats.add(0, 0.0)
for attempt, delay in enumerate(self.delays, 1):
remaining = start + self.timeout - time.time()
if remaining < 0:
break
await asyncio.sleep(min(delay, remaining))
yield self.stats.add(attempt, time.time() - start)
def clone(self, func: Callable, *args) -> 'waiter':
return type(self)(reiter(func, *args), self.timeout)
def map(self, func: Callable, *iterables: Iterable) -> 'waiter':
"""Return new waiter with function mapped across delays."""
return self.clone(map, func, self.delays, *iterables)
@classmethod
def fibonacci(cls, delay, **kwargs) -> 'waiter':
"""Create waiter with fibonacci backoff."""
return cls(reiter(fibonacci, delay, delay), **kwargs)
@classmethod
def count(cls, *args, **kwargs) -> 'waiter':
"""Create waiter based on `itertools.count`."""
return cls(reiter(itertools.count, *args), **kwargs)
@classmethod
def accumulate(cls, *args, **kwargs) -> 'waiter':
"""Create waiter based on `itertools.accumulate`."""
return cls(reiter(itertools.accumulate, *args), **kwargs)
@classmethod
def exponential(cls, base, **kwargs) -> 'waiter':
"""Create waiter with exponential backoff."""
return cls.count(**kwargs).map(base.__pow__)
@classmethod
def polynomial(cls, exp, **kwargs) -> 'waiter':
"""Create waiter with polynomial backoff."""
return cls.count(**kwargs).map(exp.__rpow__)
def __getitem__(self, slc: slice) -> 'waiter':
"""Slice delays, e.g., to limit attempt count."""
return self.clone(itertools.islice, self.delays, slc.start, slc.stop, slc.step)
def __le__(self, ceiling) -> 'waiter':
"""Limit maximum delay generated."""
return self.map(partial(min, ceiling))
def __ge__(self, floor) -> 'waiter':
"""Limit minimum delay generated."""
return self.map(partial(max, floor))
def __add__(self, step) -> 'waiter':
"""Generate incremental backoff."""
return self.map(operator.add, reiter(itertools.count, 0, step))
def __mul__(self, factor) -> 'waiter':
"""Generate exponential backoff."""
return self.map(operator.mul, reiter(map, factor.__pow__, reiter(itertools.count)))
def random(self, start, stop) -> 'waiter':
"""Add random jitter within given range."""
return self.map(lambda delay: delay + random.uniform(start, stop))
@multimethod
def throttle(self, iterable) -> Iterator:
"""Delay iteration."""
return map(operator.itemgetter(1), zip(self, iterable))
@multimethod
async def throttle(self, iterable: AsyncIterable):
anext = iterable.__aiter__().__anext__
with suppress(StopAsyncIteration):
async for _ in self:
yield await anext()
def stream(self, queue: Iterable, size: Optional[int] = None) -> Iterator:
"""Generate chained values in groups from an iterable.
The queue can be extended while in use.
"""
it = iter(queue)
groups = iter(lambda: list(itertools.islice(it, size)), [])
if isinstance(queue, Sequence):
groups = grouped(queue, size)
return itertools.chain.from_iterable(self.throttle(groups))
def suppressed(self, exception, func: Callable, iterable: Iterable) -> Iterator[tuple]:
"""Generate `arg, func(arg)` pairs while exception isn't raised."""
queue = list(iterable)
for arg in self.stream(queue):
try:
yield arg, func(arg)
except exception:
queue.append(arg)
def filtered(self, predicate: Callable, func: Callable, iterable: Iterable) -> Iterator[tuple]:
"""Generate `arg, func(arg)` pairs while predicate evaluates to true."""
queue = list(iterable)
for arg in self.stream(queue):
result = func(arg)
if predicate(result):
yield arg, result
else:
queue.append(arg)
@overload
def repeat(self, func, *args, **kwargs):
"""Repeat function call."""
return (func(*args, **kwargs) for _ in self)
@overload
async def repeat(self, func: iscoro, *args, **kwargs):
async for _ in self:
yield await func(*args, **kwargs)
@overload
def retry(self, exception, func, *args, **kwargs):
"""Repeat function call until exception isn't raised."""
for _ in self:
with suppress(exception) as excs:
return func(*args, **kwargs)
raise excs[0]
@overload
async def retry(self, exception, func: iscoro, *args, **kwargs):
async for _ in self:
with suppress(exception) as excs:
return await func(*args, **kwargs)
raise excs[0]
@overload
def poll(self, predicate, func, *args, **kwargs):
"""Repeat function call until predicate evaluates to true."""
return first(predicate, self.repeat(func, *args, **kwargs))
@overload
async def poll(self, predicate, func: iscoro, *args, **kwargs):
async for result in self.repeat(func, *args, **kwargs):
if predicate(result): # pragma: no branch
return result
raise StopAsyncIteration
def repeating(self, func: Callable):
"""A decorator for `repeat`."""
return partialmethod(self.repeat, func)
def retrying(self, exception: Exception):
"""Return a decorator for `retry`."""
return partial(partialmethod, self.retry, exception)
def polling(self, predicate: Callable):
"""Return a decorator for `poll`."""
return partial(partialmethod, self.poll, predicate)
|
(delays, timeout=inf)
|
61,834 |
waiter
|
__add__
|
Generate incremental backoff.
|
def __add__(self, step) -> 'waiter':
"""Generate incremental backoff."""
return self.map(operator.add, reiter(itertools.count, 0, step))
|
(self, step) -> waiter.waiter
|
61,835 |
waiter
|
__aiter__
|
Asynchronously generate a slow loop of elapsed time.
|
def __iter__(self):
"""Generate a slow loop of elapsed time."""
start = time.time()
yield self.stats.add(0, 0.0)
for attempt, delay in enumerate(self.delays, 1):
remaining = start + self.timeout - time.time()
if remaining < 0:
break
time.sleep(min(delay, remaining))
yield self.stats.add(attempt, time.time() - start)
|
(self)
|
61,836 |
waiter
|
__ge__
|
Limit minimum delay generated.
|
def __ge__(self, floor) -> 'waiter':
"""Limit minimum delay generated."""
return self.map(partial(max, floor))
|
(self, floor) -> waiter.waiter
|
61,837 |
waiter
|
__getitem__
|
Slice delays, e.g., to limit attempt count.
|
def __getitem__(self, slc: slice) -> 'waiter':
"""Slice delays, e.g., to limit attempt count."""
return self.clone(itertools.islice, self.delays, slc.start, slc.stop, slc.step)
|
(self, slc: slice) -> waiter.waiter
|
61,838 |
waiter
|
__init__
| null |
def __init__(self, delays, timeout=float('inf')):
with suppress(TypeError) as excs:
iter(delays)
self.delays = itertools.repeat(delays) if excs else delays
self.timeout = timeout
self.stats = self.Stats()
|
(self, delays, timeout=inf)
|
61,839 |
waiter
|
__iter__
|
Generate a slow loop of elapsed time.
|
def __iter__(self):
"""Generate a slow loop of elapsed time."""
start = time.time()
yield self.stats.add(0, 0.0)
for attempt, delay in enumerate(self.delays, 1):
remaining = start + self.timeout - time.time()
if remaining < 0:
break
time.sleep(min(delay, remaining))
yield self.stats.add(attempt, time.time() - start)
|
(self)
|
61,840 |
waiter
|
__le__
|
Limit maximum delay generated.
|
def __le__(self, ceiling) -> 'waiter':
"""Limit maximum delay generated."""
return self.map(partial(min, ceiling))
|
(self, ceiling) -> waiter.waiter
|
61,841 |
waiter
|
__mul__
|
Generate exponential backoff.
|
def __mul__(self, factor) -> 'waiter':
"""Generate exponential backoff."""
return self.map(operator.mul, reiter(map, factor.__pow__, reiter(itertools.count)))
|
(self, factor) -> waiter.waiter
|
61,842 |
waiter
|
clone
| null |
def clone(self, func: Callable, *args) -> 'waiter':
return type(self)(reiter(func, *args), self.timeout)
|
(self, func: collections.abc.Callable, *args) -> waiter.waiter
|
61,843 |
waiter
|
filtered
|
Generate `arg, func(arg)` pairs while predicate evaluates to true.
|
def filtered(self, predicate: Callable, func: Callable, iterable: Iterable) -> Iterator[tuple]:
"""Generate `arg, func(arg)` pairs while predicate evaluates to true."""
queue = list(iterable)
for arg in self.stream(queue):
result = func(arg)
if predicate(result):
yield arg, result
else:
queue.append(arg)
|
(self, predicate: collections.abc.Callable, func: collections.abc.Callable, iterable: collections.abc.Iterable) -> Iterator[tuple]
|
61,844 |
waiter
|
map
|
Return new waiter with function mapped across delays.
|
def map(self, func: Callable, *iterables: Iterable) -> 'waiter':
"""Return new waiter with function mapped across delays."""
return self.clone(map, func, self.delays, *iterables)
|
(self, func: collections.abc.Callable, *iterables: collections.abc.Iterable) -> waiter.waiter
|
61,845 |
waiter
|
polling
|
Return a decorator for `poll`.
|
def polling(self, predicate: Callable):
"""Return a decorator for `poll`."""
return partial(partialmethod, self.poll, predicate)
|
(self, predicate: collections.abc.Callable)
|
61,846 |
waiter
|
random
|
Add random jitter within given range.
|
def random(self, start, stop) -> 'waiter':
"""Add random jitter within given range."""
return self.map(lambda delay: delay + random.uniform(start, stop))
|
(self, start, stop) -> waiter.waiter
|
61,847 |
waiter
|
repeating
|
A decorator for `repeat`.
|
def repeating(self, func: Callable):
"""A decorator for `repeat`."""
return partialmethod(self.repeat, func)
|
(self, func: collections.abc.Callable)
|
61,848 |
waiter
|
retrying
|
Return a decorator for `retry`.
|
def retrying(self, exception: Exception):
"""Return a decorator for `retry`."""
return partial(partialmethod, self.retry, exception)
|
(self, exception: Exception)
|
61,849 |
waiter
|
stream
|
Generate chained values in groups from an iterable.
The queue can be extended while in use.
|
def stream(self, queue: Iterable, size: Optional[int] = None) -> Iterator:
"""Generate chained values in groups from an iterable.
The queue can be extended while in use.
"""
it = iter(queue)
groups = iter(lambda: list(itertools.islice(it, size)), [])
if isinstance(queue, Sequence):
groups = grouped(queue, size)
return itertools.chain.from_iterable(self.throttle(groups))
|
(self, queue: collections.abc.Iterable, size: Optional[int] = None) -> Iterator
|
61,850 |
waiter
|
suppressed
|
Generate `arg, func(arg)` pairs while exception isn't raised.
|
def suppressed(self, exception, func: Callable, iterable: Iterable) -> Iterator[tuple]:
"""Generate `arg, func(arg)` pairs while exception isn't raised."""
queue = list(iterable)
for arg in self.stream(queue):
try:
yield arg, func(arg)
except exception:
queue.append(arg)
|
(self, exception, func: collections.abc.Callable, iterable: collections.abc.Iterable) -> Iterator[tuple]
|
61,869 |
freezable.freezable
|
Freezable
|
A class that allows instances to marked as "frozen" or "unfrozen."
When an instance is "frozen," it is treated as an *immutable* object; all
mutating operations/methods are disabled.
By default, this class disables setting and deleting attributes to help
preserve the frozen guarantee. Note that this adds some overhead to each
set and delete. To remove this behavior (for performance or some other
reason), override the `__setattr__` and `__delattr__` methods with the ones
from `object`:
```python
__setattr__ = object.__setattr__
__delattr__ = object.__delattr__
```
This class can be used both in cases of single and multiple inheritance.
There is no need to call `super().__init__()` in the subclass's `__init__`
method. You can call it, but it will not do anything.
Example: Example: Freezable Stack
Here is an example of a freezable stack data structure:
```python
from freezable import Freezable, enabled_when_unfrozen
class FreezableStack(Freezable):
def __init__(self):
self._data = []
#
# Mutating methods
#
# These methods use the @enabled_when_unfrozen decorator. This
# prevents the object from being mutated while the object is
# frozen.
@enabled_when_unfrozen
def push(self, x):
self._data.append(x)
@enabled_when_unfrozen
def pop(self):
return self._data.pop()
#
# Non-mutating methods
#
# These methods are non-mutating and can be used any time.
def is_empty(self):
return not bool(self._data)
def top(self):
return self._data[-1] if self._data else None
```
|
class Freezable:
"""A class that allows instances to marked as "frozen" or "unfrozen."
When an instance is "frozen," it is treated as an *immutable* object; all
mutating operations/methods are disabled.
By default, this class disables setting and deleting attributes to help
preserve the frozen guarantee. Note that this adds some overhead to each
set and delete. To remove this behavior (for performance or some other
reason), override the `__setattr__` and `__delattr__` methods with the ones
from `object`:
```python
__setattr__ = object.__setattr__
__delattr__ = object.__delattr__
```
This class can be used both in cases of single and multiple inheritance.
There is no need to call `super().__init__()` in the subclass's `__init__`
method. You can call it, but it will not do anything.
Example: Example: Freezable Stack
Here is an example of a freezable stack data structure:
```python
from freezable import Freezable, enabled_when_unfrozen
class FreezableStack(Freezable):
def __init__(self):
self._data = []
#
# Mutating methods
#
# These methods use the @enabled_when_unfrozen decorator. This
# prevents the object from being mutated while the object is
# frozen.
@enabled_when_unfrozen
def push(self, x):
self._data.append(x)
@enabled_when_unfrozen
def pop(self):
return self._data.pop()
#
# Non-mutating methods
#
# These methods are non-mutating and can be used any time.
def is_empty(self):
return not bool(self._data)
def top(self):
return self._data[-1] if self._data else None
```
"""
__frozen: bool = False
"""True if this object is marked as 'frozen'; false otherwise."""
#
# Freezing-related Methods
#
def freeze(self) -> None:
"""Freezes this object. All methods/operations that could mutate this
object become disabled."""
_object_setattr(self, '_Freezable__frozen', True)
def unfreeze(self) -> None:
"""Unfreezes this object. All methods/operations that could mutate this
object become re-enabled."""
_object_setattr(self, '_Freezable__frozen', False)
def is_frozen(self) -> bool:
"""Checks if this object is frozen.
Returns:
True if this object is frozen; False otherwise.
"""
return self.__frozen
#
# Special methods
#
def __setattr__(self, __name: str, __value: Any) -> None:
"""Sets an attribute.
This raises a FrozenError if this object is frozen. You may override
this behavior in a subclass if needed.
"""
if self.is_frozen():
raise FrozenError('cannot set attributes while object is frozen')
object.__setattr__(self, __name, __value)
def __delattr__(self, __name: str) -> None:
"""Deletes an attribute.
This raises a FrozenError is this object is frozen. You may override
this behavior in a subclass if needed.
"""
if self.is_frozen():
raise FrozenError('cannot delete attributes while object is frozen')
object.__delattr__(self, __name)
|
()
|
61,870 |
freezable.freezable
|
__delattr__
|
Deletes an attribute.
This raises a FrozenError is this object is frozen. You may override
this behavior in a subclass if needed.
|
def __delattr__(self, __name: str) -> None:
"""Deletes an attribute.
This raises a FrozenError is this object is frozen. You may override
this behavior in a subclass if needed.
"""
if self.is_frozen():
raise FrozenError('cannot delete attributes while object is frozen')
object.__delattr__(self, __name)
|
(self, _Freezable__name: str) -> NoneType
|
61,871 |
freezable.freezable
|
__setattr__
|
Sets an attribute.
This raises a FrozenError if this object is frozen. You may override
this behavior in a subclass if needed.
|
def __setattr__(self, __name: str, __value: Any) -> None:
"""Sets an attribute.
This raises a FrozenError if this object is frozen. You may override
this behavior in a subclass if needed.
"""
if self.is_frozen():
raise FrozenError('cannot set attributes while object is frozen')
object.__setattr__(self, __name, __value)
|
(self, _Freezable__name: str, _Freezable__value: Any) -> NoneType
|
61,872 |
freezable.freezable
|
freeze
|
Freezes this object. All methods/operations that could mutate this
object become disabled.
|
def freeze(self) -> None:
"""Freezes this object. All methods/operations that could mutate this
object become disabled."""
_object_setattr(self, '_Freezable__frozen', True)
|
(self) -> NoneType
|
61,873 |
freezable.freezable
|
is_frozen
|
Checks if this object is frozen.
Returns:
True if this object is frozen; False otherwise.
|
def is_frozen(self) -> bool:
"""Checks if this object is frozen.
Returns:
True if this object is frozen; False otherwise.
"""
return self.__frozen
|
(self) -> bool
|
61,874 |
freezable.freezable
|
unfreeze
|
Unfreezes this object. All methods/operations that could mutate this
object become re-enabled.
|
def unfreeze(self) -> None:
"""Unfreezes this object. All methods/operations that could mutate this
object become re-enabled."""
_object_setattr(self, '_Freezable__frozen', False)
|
(self) -> NoneType
|
61,875 |
freezable.freezable
|
FrozenError
|
Raised when an operation that could mutate a Freezable object
is used when that object is frozen.
|
class FrozenError(RuntimeError):
"""Raised when an operation that could mutate a Freezable object
is used when that object is frozen."""
| null |
61,876 |
freezable.freezable
|
enabled_when_unfrozen
|
Decorates a instance method to raise an FrozenError if
the instance is frozen.
If the decorated instance method is run while the instance is frozen, a
`FrozenError` raised and the inner method body is not executed.
It is required that the class that owns the instance method subclasses
the `Freezable` class.
Example: Example: Decorating Mutating Methods on a Freezable Stack
This is one example of using the decorator in a class. Here, the
decorator is used on the `push` and `pop` methods. This is to
prevent the instance from being mutated while frozen.
```python
from freezable import Freezable, enabled_when_unfrozen
class FreezableStack(Freezable):
def __init__(self):
self._data = []
#
# Mutating methods
#
# These methods use the @enabled_when_unfrozen decorator. This
# prevents the object from being mutated while the object is
# frozen.
@enabled_when_unfrozen
def push(self, x):
self._data.append(x)
@enabled_when_unfrozen
def pop(self):
return self._data.pop()
#
# Non-mutating methods
#
# These methods are non-mutating and can be used any time.
def is_empty(self):
return not bool(self._data)
def top(self):
return self._data[-1] if self._data else None
```
Example usage of the freezable stack:
```python
stk = FreezableStack()
assert stk.top() == None
stk.push(1)
assert stk.top() == 1
stk.push(2)
assert stk.top() == 2
stk.freeze()
try:
stk.push(3) # this raises FrozenError because stk is frozen
except FrozenError:
pass
assert stk.top() == 2 # stack was not modified
stk.unfreeze()
stk.push(3) # now we can push an element
assert stk.top() == 3
```
|
def enabled_when_unfrozen(method: Callable):
"""Decorates a instance method to raise an FrozenError if
the instance is frozen.
If the decorated instance method is run while the instance is frozen, a
`FrozenError` raised and the inner method body is not executed.
It is required that the class that owns the instance method subclasses
the `Freezable` class.
Example: Example: Decorating Mutating Methods on a Freezable Stack
This is one example of using the decorator in a class. Here, the
decorator is used on the `push` and `pop` methods. This is to
prevent the instance from being mutated while frozen.
```python
from freezable import Freezable, enabled_when_unfrozen
class FreezableStack(Freezable):
def __init__(self):
self._data = []
#
# Mutating methods
#
# These methods use the @enabled_when_unfrozen decorator. This
# prevents the object from being mutated while the object is
# frozen.
@enabled_when_unfrozen
def push(self, x):
self._data.append(x)
@enabled_when_unfrozen
def pop(self):
return self._data.pop()
#
# Non-mutating methods
#
# These methods are non-mutating and can be used any time.
def is_empty(self):
return not bool(self._data)
def top(self):
return self._data[-1] if self._data else None
```
Example usage of the freezable stack:
```python
stk = FreezableStack()
assert stk.top() == None
stk.push(1)
assert stk.top() == 1
stk.push(2)
assert stk.top() == 2
stk.freeze()
try:
stk.push(3) # this raises FrozenError because stk is frozen
except FrozenError:
pass
assert stk.top() == 2 # stack was not modified
stk.unfreeze()
stk.push(3) # now we can push an element
assert stk.top() == 3
```
"""
@wraps(method)
def wrapped(*args, **kwargs):
self = args[0]
if self.is_frozen():
if hasattr(method, '__name__'):
raise FrozenError(f"cannot call method '{method.__name__}' "
"while object is frozen")
else:
raise FrozenError("cannot call method while object is frozen")
return method(*args, **kwargs)
return wrapped
|
(method: Callable)
|
61,878 |
graphql_relay.connection.connection
|
Connection
|
A type designed to be exposed as a `Connection` over GraphQL.
|
class Connection(NamedTuple):
"""A type designed to be exposed as a `Connection` over GraphQL."""
edges: List[Edge]
pageInfo: PageInfo
|
(edges: List[graphql_relay.connection.connection.Edge], pageInfo: graphql_relay.connection.connection.PageInfo)
|
61,880 |
namedtuple_Connection
|
__new__
|
Create new instance of Connection(edges, pageInfo)
|
from builtins import function
|
(_cls, edges: List[graphql_relay.connection.connection.Edge], pageInfo: graphql_relay.connection.connection.PageInfo)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.