diffpy.srfit.equation.literals package

Submodules

diffpy.srfit.equation.literals.abcs module

Abstract Base Classes for Literals.

class diffpy.srfit.equation.literals.abcs.ArgumentABC[source]

Bases: LiteralABC

Abstract Base Class for Argument.

See Argument for usage.

abstract property const
abstractmethod setValue(value)[source]
abstract property value
class diffpy.srfit.equation.literals.abcs.LiteralABC[source]

Bases: object

Abstract Base Class for Literal.

See Literal for usage.

abstractmethod getValue()[source]
abstractmethod identify(visitor)[source]
abstract property name
class diffpy.srfit.equation.literals.abcs.OperatorABC[source]

Bases: LiteralABC

Abstract Base Class for Operator.

See Operator for usage.

abstractmethod addLiteral(literal)[source]
abstract property args
abstract property nin
abstract property nout
abstract property operation
abstract property symbol
abstract property value

diffpy.srfit.equation.literals.argument module

Argument class.

Arguments are the leaves of an equation tree, in essence a variable or a constant.

class diffpy.srfit.equation.literals.argument.Argument(name=None, value=None, const=False)[source]

Bases: Literal, ArgumentABC

Argument class.

name

A name for this Argument.

const

A flag indicating whether this is considered a constant. Constants may be given special treatment by the Visitors.

_value

The value of the Argument. Modified with ‘setValue’.

value

Property for ‘getValue’ and ‘setValue’.

const = None
getValue()[source]

Get the value of this Literal.

identify(visitor)[source]

Identify self to a visitor.

setValue(val)[source]

Set the value of the Literal.

val

The value to assign

property value

diffpy.srfit.equation.literals.literal module

Literal base class used to construct equation trees.

Literals are base pieces of the equation hierarchy. The ‘identify’ method identifies the Literal to a visitor by calling the identifying method of the vistior.

class diffpy.srfit.equation.literals.literal.Literal(name=None)[source]

Bases: Observable, LiteralABC

Abstract class for equation pieces, such as operators and arguments.

Literal derives from Observable. See diffpy.srfit.util.observable.

name

A name for this Literal (default None).

_value

The value of the Literal.

getValue()[source]

Get the value of the Literal.

identify(visitor)[source]

Identify self to a visitor.

name = None

diffpy.srfit.equation.literals.operators module

Operator classes.

Operators are combined with other Literals to create an equation. Operators are non-leaf nodes on a Literal tree. These trees can be evaluated by the Evaluator visitor, or otherwise inspected.

The Operator class contains all the information necessary to be identified and evaluated by a Visitor. Thus, a single onOperator method exists in the Visitor base class. Other Operators can be derived from Operator (see AdditionOperator), but they all identify themselves with the Visitor.onOperator method.

class diffpy.srfit.equation.literals.operators.AdditionOperator(name=None)[source]

Bases: BinaryOperator

Addition operator.

name = 'add'
operation = <ufunc 'add'>
symbol = '+'
class diffpy.srfit.equation.literals.operators.ArrayOperator(name=None)[source]

Bases: Operator

Operator that will take parameters and turn them into an array.

name = 'array'
nin = -1
nout = 1
static operation(*args)[source]
symbol = 'array'
class diffpy.srfit.equation.literals.operators.ConvolutionOperator(name=None)[source]

Bases: BinaryOperator

Convolve two signals.

This convolves two signals such that centroid of the first array is not altered by the convolution. Furthermore, the integrated amplitude of the convolution is scaled to be that of the first signal. This is mean to act as a convolution of a signal by a probability distribution.

Note that this is only possible when the signals are computed over the same range.

name = 'convolve'
static operation(v1, v2)
symbol = 'convolve'
class diffpy.srfit.equation.literals.operators.DivisionOperator(name=None)[source]

Bases: BinaryOperator

Division operator.

name = 'divide'
operation = <ufunc 'divide'>
symbol = '/'
class diffpy.srfit.equation.literals.operators.ExponentiationOperator(name=None)[source]

Bases: BinaryOperator

Exponentiation operator.

name = 'power'
operation = <ufunc 'power'>
symbol = '**'
class diffpy.srfit.equation.literals.operators.MultiplicationOperator(name=None)[source]

Bases: BinaryOperator

Multiplication operator.

name = 'multiply'
operation = <ufunc 'multiply'>
symbol = '*'
class diffpy.srfit.equation.literals.operators.NegationOperator(name=None)[source]

Bases: UnaryOperator

Negation operator.

name = 'negative'
operation = <ufunc 'negative'>
symbol = '-'
class diffpy.srfit.equation.literals.operators.Operator(name=None)[source]

Bases: Literal, OperatorABC

Abstract class for specifying a general operator.

This class provides several methods that are common to a derived classes for concrete operations.

Class Attributes

ninint, abstract

Number of input arguments for the operator. Any number of arguments is allowed when -1. This attribute must be defined in a derived class.

noutint, abstract

Number of outputs returned by the operation. This attribute must be defined in a derived class.

operationcallable, abstract

Function that performs the operation, e.g., numpy.add. This must be defined in a derived class.

symbolstr, abstract

The symbolic representation for the operator such as “+” or “sin”. This attribute must be defined in a derived class.

args

The list of Literal arguments. Read-only, use the addLiteral method to change its content.

Type:

list

addLiteral(literal)[source]

Add a literal to this operator.

Note that order of operation matters. The first literal added is the leftmost argument. The last is the rightmost.

Raises ValueError if the literal causes a self-reference.

args = None
getValue()[source]

Get or evaluate the value of the operator.

identify(visitor)[source]

Identify self to a visitor.

property value
class diffpy.srfit.equation.literals.operators.PolyvalOperator(name=None)[source]

Bases: BinaryOperator

Operator for numpy polyval.

name = 'polyval'
static operation(p, x)

Evaluate a polynomial at specific values.

Note

This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.

If p is of length N, this function returns the value:

p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]

If x is a sequence, then p(x) is returned for each element of x. If x is another polynomial then the composite polynomial p(x(t)) is returned.

Parameters:
  • p (array_like or poly1d object) – 1D array of polynomial coefficients (including coefficients equal to zero) from highest degree to the constant term, or an instance of poly1d.

  • x (array_like or poly1d object) – A number, an array of numbers, or an instance of poly1d, at which to evaluate p.

Returns:

values – If x is a poly1d instance, the result is the composition of the two polynomials, i.e., x is “substituted” in p and the simplified result is returned. In addition, the type of x - array_like or poly1d - governs the type of the output: x array_like => values array_like, x a poly1d object => values is also.

Return type:

ndarray or poly1d

See also

poly1d

A polynomial class.

Notes

Horner’s scheme [1]_ is used to evaluate the polynomial. Even so, for polynomials of high degree the values may be inaccurate due to rounding errors. Use carefully.

If x is a subtype of ndarray the return value will be of the same type.

References

Examples

>>> import numpy as np
>>> np.polyval([3,0,1], 5)  # 3 * 5**2 + 0 * 5**1 + 1
76
>>> np.polyval([3,0,1], np.poly1d(5))
poly1d([76])
>>> np.polyval(np.poly1d([3,0,1]), 5)
76
>>> np.polyval(np.poly1d([3,0,1]), np.poly1d(5))
poly1d([76])
symbol = 'polyval'
class diffpy.srfit.equation.literals.operators.RemainderOperator(name=None)[source]

Bases: BinaryOperator

Remainder operator.

name = 'mod'
operation = <ufunc 'remainder'>
symbol = '%'
class diffpy.srfit.equation.literals.operators.SubtractionOperator(name=None)[source]

Bases: BinaryOperator

Subtraction operator.

name = 'subtract'
operation = <ufunc 'subtract'>
symbol = '-'
class diffpy.srfit.equation.literals.operators.SumOperator(name=None)[source]

Bases: UnaryOperator

numpy.sum operator.

name = 'sum'
static operation(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)

Sum of array elements over a given axis.

Parameters:
  • a (array_like) – Elements to sum.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis. If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.

  • dtype (dtype, optional) – The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

  • out (ndarray, optional) – Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • initial (scalar, optional) – Starting value for the sum. See ~numpy.ufunc.reduce for details.

  • where (array_like of bool, optional) – Elements to include in the sum. See ~numpy.ufunc.reduce for details.

Returns:

sum_along_axis – An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

Return type:

ndarray

See also

ndarray.sum

Equivalent method.

add

numpy.add.reduce equivalent function.

cumsum

Cumulative sum of array elements.

trapezoid

Integration of array values using composite trapezoidal rule.

mean, average

Notes

Arithmetic is modular when using integer types, and no error is raised on overflow.

The sum of an empty array is the neutral element 0:

>>> np.sum([])
0.0

For floating point numbers the numerical precision of sum (and np.add.reduce) is in general limited by directly adding each number individually to the result causing rounding errors in every step. However, often numpy will use a numerically better approach (partial pairwise summation) leading to improved precision in many use-cases. This improved precision is always provided when no axis is given. When axis is given, it will depend on which axis is summed. Technically, to provide the best speed possible, the improved precision is only used when the summation is along the fast axis in memory. Note that the exact precision may vary depending on other parameters. In contrast to NumPy, Python’s math.fsum function uses a slower but more precise approach to summation. Especially when summing a large number of lower precision floating point numbers, such as float32, numerical errors can become significant. In such cases it can be advisable to use dtype=”float64” to use a higher precision for the output.

Examples

>>> import numpy as np
>>> np.sum([0.5, 1.5])
2.0
>>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)
np.int32(1)
>>> np.sum([[0, 1], [0, 5]])
6
>>> np.sum([[0, 1], [0, 5]], axis=0)
array([0, 6])
>>> np.sum([[0, 1], [0, 5]], axis=1)
array([1, 5])
>>> np.sum([[0, 1], [np.nan, 5]], where=[False, True], axis=1)
array([1., 5.])

If the accumulator is too small, overflow occurs:

>>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
np.int8(-128)

You can also start the sum with a value other than zero:

>>> np.sum([10], initial=5)
15
symbol = 'sum'
class diffpy.srfit.equation.literals.operators.UFuncOperator(op)[source]

Bases: Operator

A operator wrapper around a numpy ufunc.

The name and symbol attributes are set equal to the ufunc.__name__ attribute. nin and nout are also taken from the ufunc.

nin = None
nout = None
operation = None
symbol = None

Module contents

Building blocks for defining a lazy evaluation network.

Literals are the building blocks of the evaluation network. An Argument holds the name and value of an equation variable. Operators are used to compose other Literals to produce a new value.

Literal networks can be evaluated or have other actions performed on them by Visitors (in diffpy.srfit.equation.visitors). The Literal- Visitor relationship is that described by the Visitor pattern (

http://en.wikipedia.org/wiki/Visitor_pattern).

class diffpy.srfit.equation.literals.AdditionOperator(name=None)[source]

Bases: BinaryOperator

Addition operator.

name = 'add'
operation = <ufunc 'add'>
symbol = '+'
class diffpy.srfit.equation.literals.Argument(name=None, value=None, const=False)[source]

Bases: Literal, ArgumentABC

Argument class.

name

A name for this Argument.

const

A flag indicating whether this is considered a constant. Constants may be given special treatment by the Visitors.

_value

The value of the Argument. Modified with ‘setValue’.

value

Property for ‘getValue’ and ‘setValue’.

const = None
getValue()[source]

Get the value of this Literal.

identify(visitor)[source]

Identify self to a visitor.

setValue(val)[source]

Set the value of the Literal.

val

The value to assign

property value
class diffpy.srfit.equation.literals.ArrayOperator(name=None)[source]

Bases: Operator

Operator that will take parameters and turn them into an array.

name = 'array'
nin = -1
nout = 1
static operation(*args)[source]
symbol = 'array'
class diffpy.srfit.equation.literals.BinaryOperator(name=None)[source]

Bases: Operator

Abstract class for a binary operator with two inputs and one result.

This base class defines the nin and nout attributes. The derived concrete operator must define the remaining abstract attributes of the Operator class.

nin = 2
nout = 1
class diffpy.srfit.equation.literals.ConvolutionOperator(name=None)[source]

Bases: BinaryOperator

Convolve two signals.

This convolves two signals such that centroid of the first array is not altered by the convolution. Furthermore, the integrated amplitude of the convolution is scaled to be that of the first signal. This is mean to act as a convolution of a signal by a probability distribution.

Note that this is only possible when the signals are computed over the same range.

name = 'convolve'
static operation(v1, v2)
symbol = 'convolve'
class diffpy.srfit.equation.literals.CustomOperator(name=None)[source]

Bases: Operator

Concrete class for a user-defined Operator.

Use the makeOperator factory function to create an instance.

nin = None
nout = None
operation = None
symbol = None
class diffpy.srfit.equation.literals.DivisionOperator(name=None)[source]

Bases: BinaryOperator

Division operator.

name = 'divide'
operation = <ufunc 'divide'>
symbol = '/'
class diffpy.srfit.equation.literals.ExponentiationOperator(name=None)[source]

Bases: BinaryOperator

Exponentiation operator.

name = 'power'
operation = <ufunc 'power'>
symbol = '**'
class diffpy.srfit.equation.literals.MultiplicationOperator(name=None)[source]

Bases: BinaryOperator

Multiplication operator.

name = 'multiply'
operation = <ufunc 'multiply'>
symbol = '*'
class diffpy.srfit.equation.literals.NegationOperator(name=None)[source]

Bases: UnaryOperator

Negation operator.

name = 'negative'
operation = <ufunc 'negative'>
symbol = '-'
class diffpy.srfit.equation.literals.Operator(name=None)[source]

Bases: Literal, OperatorABC

Abstract class for specifying a general operator.

This class provides several methods that are common to a derived classes for concrete operations.

Class Attributes

ninint, abstract

Number of input arguments for the operator. Any number of arguments is allowed when -1. This attribute must be defined in a derived class.

noutint, abstract

Number of outputs returned by the operation. This attribute must be defined in a derived class.

operationcallable, abstract

Function that performs the operation, e.g., numpy.add. This must be defined in a derived class.

symbolstr, abstract

The symbolic representation for the operator such as “+” or “sin”. This attribute must be defined in a derived class.

args

The list of Literal arguments. Read-only, use the addLiteral method to change its content.

Type:

list

addLiteral(literal)[source]

Add a literal to this operator.

Note that order of operation matters. The first literal added is the leftmost argument. The last is the rightmost.

Raises ValueError if the literal causes a self-reference.

args = None
getValue()[source]

Get or evaluate the value of the operator.

identify(visitor)[source]

Identify self to a visitor.

property value
class diffpy.srfit.equation.literals.PolyvalOperator(name=None)[source]

Bases: BinaryOperator

Operator for numpy polyval.

name = 'polyval'
static operation(p, x)

Evaluate a polynomial at specific values.

Note

This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.

If p is of length N, this function returns the value:

p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]

If x is a sequence, then p(x) is returned for each element of x. If x is another polynomial then the composite polynomial p(x(t)) is returned.

Parameters:
  • p (array_like or poly1d object) – 1D array of polynomial coefficients (including coefficients equal to zero) from highest degree to the constant term, or an instance of poly1d.

  • x (array_like or poly1d object) – A number, an array of numbers, or an instance of poly1d, at which to evaluate p.

Returns:

values – If x is a poly1d instance, the result is the composition of the two polynomials, i.e., x is “substituted” in p and the simplified result is returned. In addition, the type of x - array_like or poly1d - governs the type of the output: x array_like => values array_like, x a poly1d object => values is also.

Return type:

ndarray or poly1d

See also

poly1d

A polynomial class.

Notes

Horner’s scheme [1]_ is used to evaluate the polynomial. Even so, for polynomials of high degree the values may be inaccurate due to rounding errors. Use carefully.

If x is a subtype of ndarray the return value will be of the same type.

References

Examples

>>> import numpy as np
>>> np.polyval([3,0,1], 5)  # 3 * 5**2 + 0 * 5**1 + 1
76
>>> np.polyval([3,0,1], np.poly1d(5))
poly1d([76])
>>> np.polyval(np.poly1d([3,0,1]), 5)
76
>>> np.polyval(np.poly1d([3,0,1]), np.poly1d(5))
poly1d([76])
symbol = 'polyval'
class diffpy.srfit.equation.literals.RemainderOperator(name=None)[source]

Bases: BinaryOperator

Remainder operator.

name = 'mod'
operation = <ufunc 'remainder'>
symbol = '%'
class diffpy.srfit.equation.literals.SubtractionOperator(name=None)[source]

Bases: BinaryOperator

Subtraction operator.

name = 'subtract'
operation = <ufunc 'subtract'>
symbol = '-'
class diffpy.srfit.equation.literals.SumOperator(name=None)[source]

Bases: UnaryOperator

numpy.sum operator.

name = 'sum'
static operation(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)

Sum of array elements over a given axis.

Parameters:
  • a (array_like) – Elements to sum.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis. If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.

  • dtype (dtype, optional) – The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

  • out (ndarray, optional) – Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • initial (scalar, optional) – Starting value for the sum. See ~numpy.ufunc.reduce for details.

  • where (array_like of bool, optional) – Elements to include in the sum. See ~numpy.ufunc.reduce for details.

Returns:

sum_along_axis – An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

Return type:

ndarray

See also

ndarray.sum

Equivalent method.

add

numpy.add.reduce equivalent function.

cumsum

Cumulative sum of array elements.

trapezoid

Integration of array values using composite trapezoidal rule.

mean, average

Notes

Arithmetic is modular when using integer types, and no error is raised on overflow.

The sum of an empty array is the neutral element 0:

>>> np.sum([])
0.0

For floating point numbers the numerical precision of sum (and np.add.reduce) is in general limited by directly adding each number individually to the result causing rounding errors in every step. However, often numpy will use a numerically better approach (partial pairwise summation) leading to improved precision in many use-cases. This improved precision is always provided when no axis is given. When axis is given, it will depend on which axis is summed. Technically, to provide the best speed possible, the improved precision is only used when the summation is along the fast axis in memory. Note that the exact precision may vary depending on other parameters. In contrast to NumPy, Python’s math.fsum function uses a slower but more precise approach to summation. Especially when summing a large number of lower precision floating point numbers, such as float32, numerical errors can become significant. In such cases it can be advisable to use dtype=”float64” to use a higher precision for the output.

Examples

>>> import numpy as np
>>> np.sum([0.5, 1.5])
2.0
>>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)
np.int32(1)
>>> np.sum([[0, 1], [0, 5]])
6
>>> np.sum([[0, 1], [0, 5]], axis=0)
array([0, 6])
>>> np.sum([[0, 1], [0, 5]], axis=1)
array([1, 5])
>>> np.sum([[0, 1], [np.nan, 5]], where=[False, True], axis=1)
array([1., 5.])

If the accumulator is too small, overflow occurs:

>>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
np.int8(-128)

You can also start the sum with a value other than zero:

>>> np.sum([10], initial=5)
15
symbol = 'sum'
class diffpy.srfit.equation.literals.UFuncOperator(op)[source]

Bases: Operator

A operator wrapper around a numpy ufunc.

The name and symbol attributes are set equal to the ufunc.__name__ attribute. nin and nout are also taken from the ufunc.

nin = None
nout = None
operation = None
symbol = None
diffpy.srfit.equation.literals.makeOperator(name, symbol, operation, nin, nout)[source]

Return a new custom operator object.

Parameters:
  • name (str) – Name of the custom operator object.

  • symbol (str) – The symbolic representation for the operator such as “+” or “sin”.

  • operation (callable) – Function that performs the operation, e.g., numpy.add.

  • nin (int) – Number of input arguments for the operator. Any number of arguments is allowed when -1.

  • nout (in) – Number of outputs returned by the operation.

Returns:

The new custom operator object.

Return type:

CustomOperator