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 secondorder contribution to
the uncertainty.
Leastsquares regression¶
line_fit
implements an ordinary leastsquares
straightline regression calculation that accepts uncertain
real numbers for the independent and dependent variables.
line_fit_wls
implements a weighted leastsquares
straightline 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 leastsquares
algorithm for a straightline fitting that can perform a
weighted leastsquares 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 numberReturns: uncertain real numbers for magnitude and phase, a 2element 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 (2element 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 4element sequence
Parameters: z – a number If
z = x + yj
, thenmatrix([[x,y],[y,x]])
can be used to representz
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 4element sequence, or array, into a complex number
Parameters: seq – a 4element sequence, array
ormatrix
A
RuntimeError
will be raised ifseq
is illconditioned.If
z = x + yj
, thenmatrix([[x,y],[y,x]])
can be used to representz
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)¶ > Leastsquares linear intercept and slope
Parameters:  x – sequence of independent variable data
 y – sequence of dependent variable data
Returns a
LineFitOLS
objecty
must be a sequence of uncertain real numbers.Performs an ordinary leastsquares 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 typeA and typeB 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 leastsquares 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
objecty
must be a sequence of uncertain real numbers.Performs a weighted leastsquares regression.
Weights are calculated from the uncertainty of the
y
elements unless the sequenceu_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 typeA and typeB 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 straightline regression with uncertainty in
x
andy
Parameters:  a_b – a pair of initial estimates for
a
andb
 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 xy pairs [default: 0]
Returns a
LineFitWTLS
objectThe elements of
x
andy
must be uncertain numbers with nonzero uncertainties. The uncertainties of thex
andy
sequences are used to calculate weights for the regression unless the optional argumentsu_x
andu_y
are not specified.Implements a Weighted Total Least Squares algorithm that allows for correlation between xy pairs. See reference:
M Krystek and M Anton, Meas. Sci. Technol. 22 (2011) 035101 (9pp)
Example:
# PearsonYork 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
 a_b – a pair of initial estimates for

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
andarg2
Extends the usual calculation of a product, by using secondorder 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 setFalse
. For instance, residual errors are often associated with the value 0, or 1, which is not measured, in that caseestimated=False
is appropriate. However, if either or both arguments are based on measured values setestimated=True
.Note
When
estimated
isTrue
, and the product is close to zero, the result of a secondorder uncertainty calculation is smaller than the uncertainty calculated by the usual firstorder 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
orx2
is propagated toy
. However, we may calculate the secondorder 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 firstorder linear calculation of uncertainty in the GUM.In particular, the strict proportionality between components of uncertainty and firstorder partial derivatives no longer holds.

implicit
(fn, x_min, x_max, epsilon=2.220446049250313e16)¶ Return the solution to \(f(x) = 0\)
Parameters:  fn – a userdefined function
 x_min (float) – lower limit of search range
 x_max (float) – upper limit of search range
 epsilon (float) – tolerance for algorithm convergence
The userdefined function
fn
takes a single uncertain real number argument.x_min
andx_max
delimit a range containing a single root (ie, the function must cross the xaxis 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)