Additional functions

The prefix function (or the alias fn) is needed as to resolve the names of objects defined in this module.

Coordinate transformation

Functions polar and rect provide polar and rectangular coordinate transformations for uncertain numbers.

Implicit problems

The function implicit solves problems of the form:

fn(x) = 0

obtaining the solution x as an uncertain real number.

Utility functions

The functions complex_to_seq and seq_to_complex support a matrix representation of complex numbers.

The function mul2 can be used when a product of a pair of uncertain numbers is close to zero. The evaluation of uncertainty components includes a second-order contribution to the uncertainty.

Least-squares regression

line_fit implements an ordinary least-squares straight-line regression calculation that accepts uncertain real numbers for the independent and dependent variables.

line_fit_wls implements a weighted least-squares straight-line regression calculation. It accepts uncertain real numbers for the independent and dependent variables. It is also possible to specify weights for the regression.

line_fit_wtls implements a total least-squares algorithm for a straight-line fitting that can perform a weighted least-squares regression when both y and x data are uncertain real numbers, it also handles correlation between (x,y) data pairs.

Module contents

polar(z)

Return a pair of uncertain real numbers for magnitude and phase.

Parameters:z (UncertainComplex) – an uncertain complex number
Returns:uncertain real numbers for magnitude and phase, a 2-element sequence of UncertainReal

Example:

>>> z = ucomplex(0.95+0.02j,0.01)
>>> z
ucomplex((0.94999999999999996+0.02j), u=[0.01,0.01], r=0, df=inf)
>>> m,p = function.polar(z)
>>> m
ureal(0.95021050299394183,0.01,inf)
>>> p
ureal(0.021049522137046431,0.010523983863040671,inf)

>>> z_mp = function.polar(z)
>>> z_mp.magnitude
ureal(0.95021050299394183,0.01,inf)
>>> z_mp.phase
ureal(0.021049522137046431,0.010523983863040671,inf)
rect(mag_phase)

Return an uncertain complex number in rectangular coordinates.

Parameters:mag_phase (2-element sequence of UncertainReal) – a sequence containing the magnitude and phase (radians)
Returns:UncertainComplex

Example:

>>> phi = ureal( math.radians(87), math.radians(.5) )
>>> mag = ureal( 0.87, 0.07)
>>> z = function.rect( (mag,phi) )
>>> z.s
'(0.0455+0.8688j), u=[0.0084,0.0699], r=0.4300, df=inf'
complex_to_seq(z)

Transform a complex number into a 4-element sequence

Parameters:z – a number

If z = x + yj, then matrix([[x,-y],[y,x]]) can be used to represent z in matrix computations.

Examples:

>>> z = 1 + 2j
>>> function.complex_to_seq(z)
(1.0, -2.0, 2.0, 1.0)

>>> m = linear_algebra.matrix( function.complex_to_seq(z) )
>>> m.shape = (2,2)
>>> print( m )
[[1.0 -2.0]
[2.0 1.0]]
seq_to_complex(seq)

Transform a 4-element sequence, or array, into a complex number

Parameters:seq – a 4-element sequence, array or matrix

A RuntimeError will be raised if seq is ill-conditioned.

If z = x + yj, then matrix([[x,-y],[y,x]]) can be used to represent z in matrix computations.

Examples:

>>> seq = (1,-2,2,1)
>>> z = function.seq_to_complex( seq )
>>> print( z )
(1+2j)

>>> a = linear_algebra.array((1,-2,2,1))
>>> a.shape = 2,2
>>> print(a)
[[1 -2]
[2 1]]
>>> z = function.seq_to_complex(a)
>>> print( z )
(1+2j)
mean(seq)

Return the arithmetic mean of elements in seq

seq - an iterable object

If the elements of seq are uncertain numbers, an uncertain number is returned.

Example

>>> seq = [ ureal(1,1), ureal(2,1), ureal(3,1) ]
>>> fn.mean(seq)
ureal(2,0.5773502691896257,inf)
line_fit(x, y)

-> Least-squares linear intercept and slope

Parameters:
  • x – sequence of independent variable data
  • y – sequence of dependent variable data

Returns a LineFitOLS object

y must be a sequence of uncertain real numbers.

Performs an ordinary least-squares regression.

Note

Uncertainty in the parameter estimates is found by propagating uncertainty through the regression formulae. This does not take account of the residuals.

The function type_a.line_fit can be used to carry out a regression analysis that obtains uncertainty in the parameter estimates due to the residuals.

If necessary, the results of both type-A and type-B analyses can be merged (see type_a.merge_components).

Example:

>>> a0 =10
>>> b0 = -3
>>> u0 = .2

>>> x = [ float(x_i) for x_i in xrange(10) ]
>>> y = [ ureal(b0*x_i + a0,u0) for x_i in x ]

>>> a,b = fn.line_fit(x,y).a_b
>>> a
ureal(10,0.1175507627290518,inf)
>>> b
ureal(-3,0.022019275302527213,inf)
line_fit_wls(x, y, u_y=None)

-> Weighted least-squares linear regression

Parameters:
  • x – sequence of independent variable data
  • y – sequence of dependent variable data
  • u_y – sequence of uncertainties in y

Returns a LineFitWLS object

y must be a sequence of uncertain real numbers.

Performs a weighted least-squares regression.

Weights are calculated from the uncertainty of the y elements unless the sequence u_y is provided.

Note

The uncertainty in the parameter estimates is found by propagation of uncertainty through the regression formulae. This does not take account of the residuals.

The function type_a.line_fit_wls can be used to carry out a regression analysis that obtains uncertainty in the parameter estimates due to the residuals.

If necessary, the results of both type-A and type-B analyses can be merged (see type_a.merge_components).

Example:

>>> x = [1,2,3,4,5,6]
>>> y = [3.2, 4.3, 7.6, 8.6, 11.7, 12.8]
>>> u_y = [0.5,0.5,0.5,1.0,1.0,1.0]
>>> y = [ ureal(y_i,u_y_i) for y_i, u_y_i in zip(y,u_y) ]

>>> fit = function.line_fit_wls(x,y)
>>> a, b = fit.a_b
>>> a
ureal(0.8852320675105498,0.5297081435088364,inf)
>>> b
ureal(2.056962025316455,0.177892016741205,inf)
line_fit_wtls(a_b, x, y, u_x=None, u_y=None, r_xy=None)

Perform straight-line regression with uncertainty in x and y

Parameters:
  • a_b – a pair of initial estimates for a and b
  • x – list of uncertain real numbers for the independent variable
  • y – list of uncertain real numbers for the dependent variable
  • u_x – a sequence of uncertainties for the x data
  • u_y – a sequence of uncertainties for the y data
  • r_xy – correlation between x-y pairs [default: 0]

Returns a LineFitWTLS object

The elements of x and y must be uncertain numbers with non-zero uncertainties. The uncertainties of the x and y sequences are used to calculate weights for the regression unless the optional arguments u_x and u_y are not specified.

Implements a Weighted Total Least Squares algorithm that allows for correlation between x-y pairs. See reference:

M Krystek and M Anton, Meas. Sci. Technol. 22 (2011) 035101 (9pp)

Example:

# Pearson-York test data
# see, e.g., Lybanon, M. in Am. J. Phys 52 (1), January 1984 
xin=[0.0,0.9,1.8,2.6,3.3,4.4,5.2,6.1,6.5,7.4]
wx=[1000.0,1000.0,500.0,800.0,200.0,80.0,60.0,20.0,1.8,1.0]

yin=[5.9,5.4,4.4,4.6,3.5,3.7,2.8,2.8,2.4,1.5]
wy=[1.0,1.8,4.0,8.0,20.0,20.0,70.0,70.0,100.0,500.0]

# Convert weights to standard uncertainties 
uxin=[1./math.sqrt(wx_i) for wx_i in wx ]
uyin=[1./math.sqrt(wy_i) for wy_i in wy ]

# Define uncertain numbers
x = [ ureal(xin_i,uxin_i) for xin_i,uxin_i in itertools.izip(xin,uxin) ]
y = [ ureal(yin_i,uyin_i) for yin_i,uyin_i in itertools.izip(yin,uyin) ]

# initial estimate
a_b = function.line_fit(x,y).a_b

# TLS returns uncertain numbers
a,b = function.line_fit_wtls(a_b,x,y).a_b
class LineFitOLS(a, b, ssr, N)

This object holds results from an ordinary linear regression to data.

N

The number of points in the sample

a_b

Return the intercept and slope as uncertain numbers

ssr

Sum of the squared residuals

The sum of the squared deviations between values predicted by the model and the actual data.

If weights are used during the fit, the squares of weighted deviations are summed.

class LineFitWLS(a, b, ssr, N)

This object holds results from a weighted LS linear regression to data.

N

The number of points in the sample

a_b

Return the intercept and slope as uncertain numbers

ssr

Sum of the squared residuals

The sum of the squared deviations between values predicted by the model and the actual data.

If weights are used during the fit, the squares of weighted deviations are summed.

class LineFitWTLS(a, b, ssr, N)

This object holds results from a TLS linear regression to data.

N

The number of points in the sample

a_b

Return the intercept and slope as uncertain numbers

ssr

Sum of the squared residuals

The sum of the squared deviations between values predicted by the model and the actual data.

If weights are used during the fit, the squares of weighted deviations are summed.

mul2(arg1, arg2, estimated=False)

Return the product of arg1 and arg2

Extends the usual calculation of a product, by using second-order contributions to uncertainty.

Parameters:
  • arg1 – uncertain real or complex number
  • arg2 – uncertain real or complex number
  • estimated – Boolean

When both arguments are uncertain numbers that always have the same fixed values then estimated should be set False. For instance, residual errors are often associated with the value 0, or 1, which is not measured, in that case estimated=False is appropriate. However, if either or both arguments are based on measured values set estimated=True.

Note

When estimated is True, and the product is close to zero, the result of a second-order uncertainty calculation is smaller than the uncertainty calculated by the usual first-order method. In some cases, an uncertainty of zero will be obtained.

There are fairly strict limitations on the use of this function, especially for uncertain complex numbers:

1) Arguments must be independent (have no common influence quantities) and there can be no correlation between any of the quantities that influence arg1 or arg2.

2) If either argument is uncertain complex, the real and imaginary components must have equal uncertainties (i.e., the covariance matrix must be diagonal with equal elements along the diagonal) and be independent (no common influences).

A RuntimeError exception is raised if these conditions are not met.

Note

This function has been developed to improve the accuracy of uncertainty calculations where one or both multiplicands are zero. In such cases, the usual method of uncertainty propagation fails.

For example

>>> x1 = ureal(0,1,label='x1')
>>> x2 = ureal(0,1,label='x2')
>>> y = x1 * x2
>>> y
ureal(0,0,inf)
>>> for cpt in rp.budget(y,trim=0):
...         print "  %s: %G" % cpt
...         
  x1: 0
  x2: 0

so none of the uncertainty in x1 or x2 is propagated to y. However, we may calculate the second-order contribution

>>> y = fn.mul2(x1,x2)
>>> y
ureal(0,1,inf)
>>> for cpt in rp.budget(y,trim=0):
...         print "  %s: %G" % cpt
...         
  x1: 0.707107
  x2: 0.707107

The product now has a standard uncertainty of unity.

Warning

mul2 departs from the first-order linear calculation of uncertainty in the GUM.

In particular, the strict proportionality between components of uncertainty and first-order partial derivatives no longer holds.

implicit(fn, x_min, x_max, epsilon=2.220446049250313e-16)

Return the solution to \(f(x) = 0\)

Parameters:
  • fn – a user-defined function
  • x_min (float) – lower limit of search range
  • x_max (float) – upper limit of search range
  • epsilon (float) – tolerance for algorithm convergence

The user-defined function fn takes a single uncertain real number argument.

x_min and x_max delimit a range containing a single root (ie, the function must cross the x-axis just once inside the range).

Note

  • A RuntimeError is raised if the search algorithm fails to converge.
  • An AssertionError is raised if preconditions are not satisfied.

Example:

>>> near_unity = ureal(1,0.05)
>>> fn = lambda x: x**2 - near_unity
>>> function.implicit(fn,0,2)
ureal(1,0.025000000000000001,inf)