3. lib: Libraries
3.1. lib.fdtd: FDTD
3.2. lib.backend
Selects the backend for the openms-package.
The openms allows to choose a backend. The numpy backend is the
default one, but there are also several additional PyTorch backends:
numpy(defaults to float64 arrays)
torch(defaults to float64 tensors)
torch.float32
torch.float64
torch.cuda(defaults to float64 tensors)
torch.cuda.float32
torch.cuda.float64cutensor (todo?)
For example, this is how to choose the “torch” backend:
openms.set_backend("torch")
In general, the numpy backend is preferred for standard CPU calculations
with “float64” precision. In general, float64 precision is always
preferred over float32 for FDTD simulations, however, float32 might
give a significant performance boost.
The cuda backends are only available for computers with a GPU.
- class lib.backend.NumpyBackend[source]
Bases:
BackendNumpy Backend
- static allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)
Returns True if two arrays are element-wise equal within a tolerance.
The tolerance values are positive, typically very small numbers. The relative difference (rtol * abs(b)) and the absolute difference atol are added together to compare against the absolute difference between a and b.
NaNs are treated as equal if they are in the same place and if
equal_nan=True. Infs are treated as equal if they are in the same place and of the same sign in both arrays.- Parameters
a (
array_like) – Input arrays to compare.b (
array_like) – Input arrays to compare.rtol (
float) – The relative tolerance parameter (see Notes).atol (
float) – The absolute tolerance parameter (see Notes).equal_nan (
bool) –Whether to compare NaN’s as equal. If True, NaN’s in a will be considered equal to NaN’s in b in the output array.
New in version 1.10.0.
- Returns
allclose – Returns True if the two arrays are equal within the given tolerance; False otherwise.
- Return type
Notes
If the following equation is element-wise True, then allclose returns True.
absolute(a - b) <= (atol + rtol * absolute(b))
The above equation is not symmetric in a and b, so that
allclose(a, b)might be different fromallclose(b, a)in some rare cases.The comparison of a and b uses standard broadcasting, which means that a and b need not have the same shape in order for
allclose(a, b)to evaluate to True. The same is true for equal but not array_equal.allclose is not defined for non-numeric data types.
Examples
>>> np.allclose([1e10,1e-7], [1.00001e10,1e-8]) False >>> np.allclose([1e10,1e-8], [1.00001e10,1e-9]) True >>> np.allclose([1e10,1e-8], [1.0001e10,1e-9]) False >>> np.allclose([1.0, np.nan], [1.0, np.nan]) False >>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True) True
- arange([start, ]stop, [step, ]dtype=None, *, like=None)
create a range of values
- array()
create an array from an array-like sequence
- asarray(a, dtype=None, order=None, *, like=None)
Convert the input to an array.
- Parameters
a (
array_like) – Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.dtype (
data-type, optional) – By default, the data-type is inferred from the input data.order (
{'C', 'F', 'A', 'K'}, optional) – Memory layout. ‘A’ and ‘K’ depend on the order of input array a. ‘C’ row-major (C-style), ‘F’ column-major (Fortran-style) memory representation. ‘A’ (any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise ‘K’ (keep) preserve input order Defaults to ‘C’.like (
array_like) –Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as
likesupports the__array_function__protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.New in version 1.20.0.
- Returns
out – Array interpretation of a. No copy is performed if the input is already an ndarray with matching dtype and order. If a is a subclass of ndarray, a base class ndarray is returned.
- Return type
ndarray
See also
asanyarraySimilar function which passes through subclasses.
ascontiguousarrayConvert input to a contiguous array.
asfarrayConvert input to a floating point ndarray.
asfortranarrayConvert input to an ndarray with column-major memory order.
asarray_chkfiniteSimilar function which checks input for NaNs and Infs.
fromiterCreate an array from an iterator.
fromfunctionConstruct an array by executing a function on grid positions.
Examples
Convert a list into an array:
>>> a = [1, 2] >>> np.asarray(a) array([1, 2])
Existing arrays are not copied:
>>> a = np.array([1, 2]) >>> np.asarray(a) is a True
If dtype is set, array is copied only if dtype does not match:
>>> a = np.array([1, 2], dtype=np.float32) >>> np.asarray(a, dtype=np.float32) is a True >>> np.asarray(a, dtype=np.float64) is a False
Contrary to asanyarray, ndarray subclasses are not passed through:
>>> issubclass(np.recarray, np.ndarray) True >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray) >>> np.asarray(a) is a False >>> np.asanyarray(a) is a True
- static broadcast_arrays(*args, subok=False)
broadcast arrays
- static broadcast_to(array, shape, subok=False)
broadcast array into shape
- cos = <ufunc 'cos'>
cosine of all elements in array
- divide = <ufunc 'true_divide'>
- static einsum(*operands, out=None, optimize=False, **kwargs)
- einsum(subscripts, *operands, out=None, dtype=None, order=’K’,
casting=’safe’, optimize=False)
Evaluates the Einstein summation convention on the operands.
Using the Einstein summation convention, many common multi-dimensional, linear algebraic array operations can be represented in a simple fashion. In implicit mode einsum computes these values.
In explicit mode, einsum provides further flexibility to compute other array operations that might not be considered classical Einstein summation operations, by disabling, or forcing summation over specified subscript labels.
See the notes and examples for clarification.
- Parameters
subscripts (
str) – Specifies the subscripts for summation as comma separated list of subscript labels. An implicit (classical Einstein summation) calculation is performed unless the explicit indicator ‘->’ is included as well as subscript labels of the precise output form.operands (
listofarray_like) – These are the arrays for the operation.out (
ndarray, optional) – If provided, the calculation is done into this array.dtype (
{data-type, None}, optional) – If provided, forces the calculation to use the data type specified. Note that you may have to also give a more liberal casting parameter to allow the conversions. Default is None.order (
{'C', 'F', 'A', 'K'}, optional) – Controls the memory layout of the output. ‘C’ means it should be C contiguous. ‘F’ means it should be Fortran contiguous, ‘A’ means it should be ‘F’ if the inputs are all ‘F’, ‘C’ otherwise. ‘K’ means it should be as close to the layout as the inputs as is possible, including arbitrarily permuted axes. Default is ‘K’.casting (
{'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional) –Controls what kind of data casting may occur. Setting this to ‘unsafe’ is not recommended, as it can adversely affect accumulations.
’no’ means the data types should not be cast at all.
’equiv’ means only byte-order changes are allowed.
’safe’ means only casts which can preserve values are allowed.
’same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.
’unsafe’ means any data conversions may be done.
Default is ‘safe’.
optimize (
{False, True, 'greedy', 'optimal'}, optional) – Controls if intermediate optimization should occur. No optimization will occur if False and True will default to the ‘greedy’ algorithm. Also accepts an explicit contraction list from thenp.einsum_pathfunction. Seenp.einsum_pathfor more details. Defaults to False.
- Returns
output – The calculation based on the Einstein summation convention.
- Return type
ndarray
See also
einsum_path,dot,inner,outer,tensordot,linalg.multi_doteinopssimilar verbose interface is provided by einops package to cover additional operations: transpose, reshape/flatten, repeat/tile, squeeze/unsqueeze and reductions.
opt_einsumopt_einsum optimizes contraction order for einsum-like expressions in backend-agnostic manner.
Notes
New in version 1.6.0.
The Einstein summation convention can be used to compute many multi-dimensional, linear algebraic array operations. einsum provides a succinct way of representing these.
A non-exhaustive list of these operations, which can be computed by einsum, is shown below along with examples:
Trace of an array,
numpy.trace().Return a diagonal,
numpy.diag().Array axis summations,
numpy.sum().Transpositions and permutations,
numpy.transpose().Matrix multiplication and dot product,
numpy.matmul()numpy.dot().Vector inner and outer products,
numpy.inner()numpy.outer().Broadcasting, element-wise and scalar multiplication,
numpy.multiply().Tensor contractions,
numpy.tensordot().Chained array operations, in efficient calculation order,
numpy.einsum_path().
The subscripts string is a comma-separated list of subscript labels, where each label refers to a dimension of the corresponding operand. Whenever a label is repeated it is summed, so
np.einsum('i,i', a, b)is equivalent tonp.inner(a,b). If a label appears only once, it is not summed, sonp.einsum('i', a)produces a view ofawith no changes. A further examplenp.einsum('ij,jk', a, b)describes traditional matrix multiplication and is equivalent tonp.matmul(a,b). Repeated subscript labels in one operand take the diagonal. For example,np.einsum('ii', a)is equivalent tonp.trace(a).In implicit mode, the chosen subscripts are important since the axes of the output are reordered alphabetically. This means that
np.einsum('ij', a)doesn’t affect a 2D array, whilenp.einsum('ji', a)takes its transpose. Additionally,np.einsum('ij,jk', a, b)returns a matrix multiplication, while,np.einsum('ij,jh', a, b)returns the transpose of the multiplication since subscript ‘h’ precedes subscript ‘i’.In explicit mode the output can be directly controlled by specifying output subscript labels. This requires the identifier ‘->’ as well as the list of output subscript labels. This feature increases the flexibility of the function since summing can be disabled or forced when required. The call
np.einsum('i->', a)is likenp.sum(a, axis=-1), andnp.einsum('ii->i', a)is likenp.diag(a). The difference is that einsum does not allow broadcasting by default. Additionallynp.einsum('ij,jh->ih', a, b)directly specifies the order of the output subscript labels and therefore returns matrix multiplication, unlike the example above in implicit mode.To enable and control broadcasting, use an ellipsis. Default NumPy-style broadcasting is done by adding an ellipsis to the left of each term, like
np.einsum('...ii->...i', a). To take the trace along the first and last axes, you can donp.einsum('i...i', a), or to do a matrix-matrix product with the left-most indices instead of rightmost, one can donp.einsum('ij...,jk...->ik...', a, b).When there is only one operand, no axes are summed, and no output parameter is provided, a view into the operand is returned instead of a new array. Thus, taking the diagonal as
np.einsum('ii->i', a)produces a view (changed in version 1.10.0).einsum also provides an alternative way to provide the subscripts and operands as
einsum(op0, sublist0, op1, sublist1, ..., [sublistout]). If the output shape is not provided in this format einsum will be calculated in implicit mode, otherwise it will be performed explicitly. The examples below have corresponding einsum calls with the two parameter methods.New in version 1.10.0.
Views returned from einsum are now writeable whenever the input array is writeable. For example,
np.einsum('ijk...->kji...', a)will now have the same effect asnp.swapaxes(a, 0, 2)andnp.einsum('ii->i', a)will return a writeable view of the diagonal of a 2D array.New in version 1.12.0.
Added the
optimizeargument which will optimize the contraction order of an einsum expression. For a contraction with three or more operands this can greatly increase the computational efficiency at the cost of a larger memory footprint during computation.Typically a ‘greedy’ algorithm is applied which empirical tests have shown returns the optimal path in the majority of cases. In some cases ‘optimal’ will return the superlative path through a more expensive, exhaustive search. For iterative calculations it may be advisable to calculate the optimal path once and reuse that path by supplying it as an argument. An example is given below.
See
numpy.einsum_path()for more details.Examples
>>> a = np.arange(25).reshape(5,5) >>> b = np.arange(5) >>> c = np.arange(6).reshape(2,3)
Trace of a matrix:
>>> np.einsum('ii', a) 60 >>> np.einsum(a, [0,0]) 60 >>> np.trace(a) 60
Extract the diagonal (requires explicit form):
>>> np.einsum('ii->i', a) array([ 0, 6, 12, 18, 24]) >>> np.einsum(a, [0,0], [0]) array([ 0, 6, 12, 18, 24]) >>> np.diag(a) array([ 0, 6, 12, 18, 24])
Sum over an axis (requires explicit form):
>>> np.einsum('ij->i', a) array([ 10, 35, 60, 85, 110]) >>> np.einsum(a, [0,1], [0]) array([ 10, 35, 60, 85, 110]) >>> np.sum(a, axis=1) array([ 10, 35, 60, 85, 110])
For higher dimensional arrays summing a single axis can be done with ellipsis:
>>> np.einsum('...j->...', a) array([ 10, 35, 60, 85, 110]) >>> np.einsum(a, [Ellipsis,1], [Ellipsis]) array([ 10, 35, 60, 85, 110])
Compute a matrix transpose, or reorder any number of axes:
>>> np.einsum('ji', c) array([[0, 3], [1, 4], [2, 5]]) >>> np.einsum('ij->ji', c) array([[0, 3], [1, 4], [2, 5]]) >>> np.einsum(c, [1,0]) array([[0, 3], [1, 4], [2, 5]]) >>> np.transpose(c) array([[0, 3], [1, 4], [2, 5]])
Vector inner products:
>>> np.einsum('i,i', b, b) 30 >>> np.einsum(b, [0], b, [0]) 30 >>> np.inner(b,b) 30
Matrix vector multiplication:
>>> np.einsum('ij,j', a, b) array([ 30, 80, 130, 180, 230]) >>> np.einsum(a, [0,1], b, [1]) array([ 30, 80, 130, 180, 230]) >>> np.dot(a, b) array([ 30, 80, 130, 180, 230]) >>> np.einsum('...j,j', a, b) array([ 30, 80, 130, 180, 230])
Broadcasting and scalar multiplication:
>>> np.einsum('..., ...', 3, c) array([[ 0, 3, 6], [ 9, 12, 15]]) >>> np.einsum(',ij', 3, c) array([[ 0, 3, 6], [ 9, 12, 15]]) >>> np.einsum(3, [Ellipsis], c, [Ellipsis]) array([[ 0, 3, 6], [ 9, 12, 15]]) >>> np.multiply(3, c) array([[ 0, 3, 6], [ 9, 12, 15]])
Vector outer product:
>>> np.einsum('i,j', np.arange(2)+1, b) array([[0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]) >>> np.einsum(np.arange(2)+1, [0], b, [1]) array([[0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]) >>> np.outer(np.arange(2)+1, b) array([[0, 1, 2, 3, 4], [0, 2, 4, 6, 8]])
Tensor contraction:
>>> a = np.arange(60.).reshape(3,4,5) >>> b = np.arange(24.).reshape(4,3,2) >>> np.einsum('ijk,jil->kl', a, b) array([[4400., 4730.], [4532., 4874.], [4664., 5018.], [4796., 5162.], [4928., 5306.]]) >>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3]) array([[4400., 4730.], [4532., 4874.], [4664., 5018.], [4796., 5162.], [4928., 5306.]]) >>> np.tensordot(a,b, axes=([1,0],[0,1])) array([[4400., 4730.], [4532., 4874.], [4664., 5018.], [4796., 5162.], [4928., 5306.]])
Writeable returned arrays (since version 1.10.0):
>>> a = np.zeros((3, 3)) >>> np.einsum('ii->i', a)[:] = 1 >>> a array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
Example of ellipsis use:
>>> a = np.arange(6).reshape((3,2)) >>> b = np.arange(12).reshape((4,3)) >>> np.einsum('ki,jk->ij', a, b) array([[10, 28, 46, 64], [13, 40, 67, 94]]) >>> np.einsum('ki,...k->i...', a, b) array([[10, 28, 46, 64], [13, 40, 67, 94]]) >>> np.einsum('k...,jk', a, b) array([[10, 28, 46, 64], [13, 40, 67, 94]])
Chained array operations. For more complicated contractions, speed ups might be achieved by repeatedly computing a ‘greedy’ path or pre-computing the ‘optimal’ path and repeatedly applying it, using an einsum_path insertion (since version 1.12.0). Performance improvements can be particularly significant with larger arrays:
>>> a = np.ones(64).reshape(2,4,8)
Basic einsum: ~1520ms (benchmarked on 3.1GHz Intel i5.)
>>> for iteration in range(500): ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a)
Sub-optimal einsum (due to repeated path calculation time): ~330ms
>>> for iteration in range(500): ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='optimal')
Greedy einsum (faster optimal path approximation): ~160ms
>>> for iteration in range(500): ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='greedy')
Optimal einsum (best usage pattern in some use cases): ~110ms
>>> path = np.einsum_path('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='optimal')[0] >>> for iteration in range(500): ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize=path)
- exp = <ufunc 'exp'>
exponential of all elements in array
- static fft(a, n=None, axis=-1, norm=None)
Compute the one-dimensional discrete Fourier Transform.
This function computes the one-dimensional n-point discrete Fourier Transform (DFT) with the efficient Fast Fourier Transform (FFT) algorithm [CT].
- Parameters
a (
array_like) – Input array, can be complex.n (
int, optional) – Length of the transformed axis of the output. If n is smaller than the length of the input, the input is cropped. If it is larger, the input is padded with zeros. If n is not given, the length of the input along the axis specified by axis is used.axis (
int, optional) – Axis over which to compute the FFT. If not given, the last axis is used.norm (
{"backward", "ortho", "forward"}, optional) –New in version 1.10.0.
Normalization mode (see numpy.fft). Default is “backward”. Indicates which direction of the forward/backward pair of transforms is scaled and with what normalization factor.
New in version 1.20.0: The “backward”, “forward” values were added.
- Returns
out – The truncated or zero-padded input, transformed along the axis indicated by axis, or the last one if axis is not specified.
- Return type
complex ndarray- Raises
IndexError – If axis is not a valid axis of a.
See also
Notes
FFT (Fast Fourier Transform) refers to a way the discrete Fourier Transform (DFT) can be calculated efficiently, by using symmetries in the calculated terms. The symmetry is highest when n is a power of 2, and the transform is therefore most efficient for these sizes.
The DFT is defined, with the conventions used in this implementation, in the documentation for the numpy.fft module.
References
- CT
Cooley, James W., and John W. Tukey, 1965, “An algorithm for the machine calculation of complex Fourier series,” Math. Comput. 19: 297-301.
Examples
>>> np.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8)) array([-2.33486982e-16+1.14423775e-17j, 8.00000000e+00-1.25557246e-15j, 2.33486982e-16+2.33486982e-16j, 0.00000000e+00+1.22464680e-16j, -1.14423775e-17+2.33486982e-16j, 0.00000000e+00+5.20784380e-16j, 1.14423775e-17+1.14423775e-17j, 0.00000000e+00+1.22464680e-16j])
In this example, real input has an FFT which is Hermitian, i.e., symmetric in the real part and anti-symmetric in the imaginary part, as described in the numpy.fft documentation:
>>> import matplotlib.pyplot as plt >>> t = np.arange(256) >>> sp = np.fft.fft(np.sin(t)) >>> freq = np.fft.fftfreq(t.shape[-1]) >>> plt.plot(freq, sp.real, freq, sp.imag) [<matplotlib.lines.Line2D object at 0x...>, <matplotlib.lines.Line2D object at 0x...>] >>> plt.show()
- static fftfreq(n, d=1.0)
Return the Discrete Fourier Transform sample frequencies.
The returned float array f contains the frequency bin centers in cycles per unit of the sample spacing (with zero at the start). For instance, if the sample spacing is in seconds, then the frequency unit is cycles/second.
Given a window length n and a sample spacing d:
f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) if n is even f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) if n is odd
- Parameters
n (
int) – Window length.d (
scalar, optional) – Sample spacing (inverse of the sampling rate). Defaults to 1.
- Returns
f – Array of length n containing the sample frequencies.
- Return type
ndarray
Examples
>>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float) >>> fourier = np.fft.fft(signal) >>> n = signal.size >>> timestep = 0.1 >>> freq = np.fft.fftfreq(n, d=timestep) >>> freq array([ 0. , 1.25, 2.5 , ..., -3.75, -2.5 , -1.25])
- float
floating type for array
alias of
float64
- int
integer type for array
alias of
int64
- linspace(stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
create a linearly spaced array between two points
- static max(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
max element in array
- static norm(x, ord=None, axis=None, keepdims=False)
Matrix or vector norm.
This function is able to return one of eight different matrix norms, or one of an infinite number of vector norms (described below), depending on the value of the
ordparameter.- Parameters
x (
array_like) – Input array. If axis is None, x must be 1-D or 2-D, unless ord is None. If both axis and ord are None, the 2-norm ofx.ravelwill be returned.ord (
{non-zero int, inf, -inf, 'fro', 'nuc'}, optional) – Order of the norm (see table underNotes). inf means numpy’s inf object. The default is None.axis (
{None, int, 2-tuple of ints},optional.) –If axis is an integer, it specifies the axis of x along which to compute the vector norms. If axis is a 2-tuple, it specifies the axes that hold 2-D matrices, and the matrix norms of these matrices are computed. If axis is None then either a vector norm (when x is 1-D) or a matrix norm (when x is 2-D) is returned. The default is None.
New in version 1.8.0.
keepdims (
bool, optional) –If this is set to True, the axes which are normed over are left in the result as dimensions with size one. With this option the result will broadcast correctly against the original x.
New in version 1.10.0.
- Returns
n – Norm of the matrix or vector(s).
- Return type
floatorndarray
See also
scipy.linalg.normSimilar function in SciPy.
Notes
For values of
ord < 1, the result is, strictly speaking, not a mathematical ‘norm’, but it may still be useful for various numerical purposes.The following norms can be calculated:
ord
norm for matrices
norm for vectors
None
Frobenius norm
2-norm
‘fro’
Frobenius norm
–
‘nuc’
nuclear norm
–
inf
max(sum(abs(x), axis=1))
max(abs(x))
-inf
min(sum(abs(x), axis=1))
min(abs(x))
0
–
sum(x != 0)
1
max(sum(abs(x), axis=0))
as below
-1
min(sum(abs(x), axis=0))
as below
2
2-norm (largest sing. value)
as below
-2
smallest singular value
as below
other
–
sum(abs(x)**ord)**(1./ord)
The Frobenius norm is given by 1:
\(||A||_F = [\sum_{i,j} abs(a_{i,j})^2]^{1/2}\)
The nuclear norm is the sum of the singular values.
Both the Frobenius and nuclear norm orders are only defined for matrices and raise a ValueError when
x.ndim != 2.References
- 1
G. H. Golub and C. F. Van Loan, Matrix Computations, Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15
Examples
>>> from numpy import linalg as LA >>> a = np.arange(9) - 4 >>> a array([-4, -3, -2, ..., 2, 3, 4]) >>> b = a.reshape((3, 3)) >>> b array([[-4, -3, -2], [-1, 0, 1], [ 2, 3, 4]])
>>> LA.norm(a) 7.745966692414834 >>> LA.norm(b) 7.745966692414834 >>> LA.norm(b, 'fro') 7.745966692414834 >>> LA.norm(a, np.inf) 4.0 >>> LA.norm(b, np.inf) 9.0 >>> LA.norm(a, -np.inf) 0.0 >>> LA.norm(b, -np.inf) 2.0
>>> LA.norm(a, 1) 20.0 >>> LA.norm(b, 1) 7.0 >>> LA.norm(a, -1) -4.6566128774142013e-010 >>> LA.norm(b, -1) 6.0 >>> LA.norm(a, 2) 7.745966692414834 >>> LA.norm(b, 2) 7.3484692283495345
>>> LA.norm(a, -2) 0.0 >>> LA.norm(b, -2) 1.8570331885190563e-016 # may vary >>> LA.norm(a, 3) 5.8480354764257312 # may vary >>> LA.norm(a, -3) 0.0
Using the axis argument to compute vector norms:
>>> c = np.array([[ 1, 2, 3], ... [-1, 1, 4]]) >>> LA.norm(c, axis=0) array([ 1.41421356, 2.23606798, 5. ]) >>> LA.norm(c, axis=1) array([ 3.74165739, 4.24264069]) >>> LA.norm(c, ord=1, axis=1) array([ 6., 6.])
Using the axis argument to compute matrix norms:
>>> m = np.arange(8).reshape(2,2,2) >>> LA.norm(m, axis=(1,2)) array([ 3.74165739, 11.22497216]) >>> LA.norm(m[0, :, :]), LA.norm(m[1, :, :]) (3.7416573867739413, 11.224972160321824)
- numpy()
convert the array to numpy array
- ones(dtype=None, order='C', *, like=None)
create an array filled with ones
- static pad(array, pad_width, mode='constant', **kwargs)
Pad an array.
- Parameters
array (
array_likeofrank N) – The array to pad.pad_width (
{sequence, array_like, int}) – Number of values padded to the edges of each axis. ((before_1, after_1), … (before_N, after_N)) unique pad widths for each axis. ((before, after),) yields same before and after pad for each axis. (pad,) or int is a shortcut for before = after = pad width for all axes.mode (
strorfunction, optional) –One of the following string values or a user supplied function.
- ’constant’ (default)
Pads with a constant value.
- ’edge’
Pads with the edge values of array.
- ’linear_ramp’
Pads with the linear ramp between end_value and the array edge value.
- ’maximum’
Pads with the maximum value of all or part of the vector along each axis.
- ’mean’
Pads with the mean value of all or part of the vector along each axis.
- ’median’
Pads with the median value of all or part of the vector along each axis.
- ’minimum’
Pads with the minimum value of all or part of the vector along each axis.
- ’reflect’
Pads with the reflection of the vector mirrored on the first and last values of the vector along each axis.
- ’symmetric’
Pads with the reflection of the vector mirrored along the edge of the array.
- ’wrap’
Pads with the wrap of the vector along the axis. The first values are used to pad the end and the end values are used to pad the beginning.
- ’empty’
Pads with undefined values.
New in version 1.17.
- <function>
Padding function, see Notes.
stat_length (
sequenceorint, optional) –Used in ‘maximum’, ‘mean’, ‘median’, and ‘minimum’. Number of values at edge of each axis used to calculate the statistic value.
((before_1, after_1), … (before_N, after_N)) unique statistic lengths for each axis.
((before, after),) yields same before and after statistic lengths for each axis.
(stat_length,) or int is a shortcut for before = after = statistic length for all axes.
Default is
None, to use the entire axis.constant_values (
sequenceorscalar, optional) –Used in ‘constant’. The values to set the padded values for each axis.
((before_1, after_1), ... (before_N, after_N))unique pad constants for each axis.((before, after),)yields same before and after constants for each axis.(constant,)orconstantis a shortcut forbefore = after = constantfor all axes.Default is 0.
end_values (
sequenceorscalar, optional) –Used in ‘linear_ramp’. The values used for the ending value of the linear_ramp and that will form the edge of the padded array.
((before_1, after_1), ... (before_N, after_N))unique end values for each axis.((before, after),)yields same before and after end values for each axis.(constant,)orconstantis a shortcut forbefore = after = constantfor all axes.Default is 0.
reflect_type (
{'even', 'odd'}, optional) – Used in ‘reflect’, and ‘symmetric’. The ‘even’ style is the default with an unaltered reflection around the edge value. For the ‘odd’ style, the extended part of the array is created by subtracting the reflected values from two times the edge value.
- Returns
pad – Padded array of rank equal to array with shape increased according to pad_width.
- Return type
ndarray
Notes
New in version 1.7.0.
For an array with rank greater than 1, some of the padding of later axes is calculated from padding of previous axes. This is easiest to think about with a rank 2 array where the corners of the padded array are calculated by using padded values from the first axis.
The padding function, if used, should modify a rank 1 array in-place. It has the following signature:
padding_func(vector, iaxis_pad_width, iaxis, kwargs)
where
- vectorndarray
A rank 1 array already padded with zeros. Padded values are vector[:iaxis_pad_width[0]] and vector[-iaxis_pad_width[1]:].
- iaxis_pad_widthtuple
A 2-tuple of ints, iaxis_pad_width[0] represents the number of values padded at the beginning of vector where iaxis_pad_width[1] represents the number of values padded at the end of vector.
- iaxisint
The axis currently being calculated.
- kwargsdict
Any keyword arguments the function requires.
Examples
>>> a = [1, 2, 3, 4, 5] >>> np.pad(a, (2, 3), 'constant', constant_values=(4, 6)) array([4, 4, 1, ..., 6, 6, 6])
>>> np.pad(a, (2, 3), 'edge') array([1, 1, 1, ..., 5, 5, 5])
>>> np.pad(a, (2, 3), 'linear_ramp', end_values=(5, -4)) array([ 5, 3, 1, 2, 3, 4, 5, 2, -1, -4])
>>> np.pad(a, (2,), 'maximum') array([5, 5, 1, 2, 3, 4, 5, 5, 5])
>>> np.pad(a, (2,), 'mean') array([3, 3, 1, 2, 3, 4, 5, 3, 3])
>>> np.pad(a, (2,), 'median') array([3, 3, 1, 2, 3, 4, 5, 3, 3])
>>> a = [[1, 2], [3, 4]] >>> np.pad(a, ((3, 2), (2, 3)), 'minimum') array([[1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1], [3, 3, 3, 4, 3, 3, 3], [1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1]])
>>> a = [1, 2, 3, 4, 5] >>> np.pad(a, (2, 3), 'reflect') array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2])
>>> np.pad(a, (2, 3), 'reflect', reflect_type='odd') array([-1, 0, 1, 2, 3, 4, 5, 6, 7, 8])
>>> np.pad(a, (2, 3), 'symmetric') array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3])
>>> np.pad(a, (2, 3), 'symmetric', reflect_type='odd') array([0, 1, 1, 2, 3, 4, 5, 5, 6, 7])
>>> np.pad(a, (2, 3), 'wrap') array([4, 5, 1, 2, 3, 4, 5, 1, 2, 3])
>>> def pad_with(vector, pad_width, iaxis, kwargs): ... pad_value = kwargs.get('padder', 10) ... vector[:pad_width[0]] = pad_value ... vector[-pad_width[1]:] = pad_value >>> a = np.arange(6) >>> a = a.reshape((2, 3)) >>> np.pad(a, 2, pad_with) array([[10, 10, 10, 10, 10, 10, 10], [10, 10, 10, 10, 10, 10, 10], [10, 10, 0, 1, 2, 10, 10], [10, 10, 3, 4, 5, 10, 10], [10, 10, 10, 10, 10, 10, 10], [10, 10, 10, 10, 10, 10, 10]]) >>> np.pad(a, 2, pad_with, padder=100) array([[100, 100, 100, 100, 100, 100, 100], [100, 100, 100, 100, 100, 100, 100], [100, 100, 0, 1, 2, 100, 100], [100, 100, 3, 4, 5, 100, 100], [100, 100, 100, 100, 100, 100, 100], [100, 100, 100, 100, 100, 100, 100]])
- static rand(d0, d1, ..., dn)
Random values in a given shape.
Note
This is a convenience function for users porting code from Matlab, and wraps random_sample. That function takes a tuple to specify the size of the output, which is consistent with other NumPy functions like numpy.zeros and numpy.ones.
Create an array of the given shape and populate it with random samples from a uniform distribution over
[0, 1).- Parameters
d0 (
int, optional) – The dimensions of the returned array, must be non-negative. If no argument is given a single Python float is returned.d1 (
int, optional) – The dimensions of the returned array, must be non-negative. If no argument is given a single Python float is returned.... (
int, optional) – The dimensions of the returned array, must be non-negative. If no argument is given a single Python float is returned.dn (
int, optional) – The dimensions of the returned array, must be non-negative. If no argument is given a single Python float is returned.
- Returns
out – Random values.
- Return type
ndarray,shape ``(d0,d1,...,dn)``
See also
Examples
>>> np.random.rand(3,2) array([[ 0.14022471, 0.96360618], #random [ 0.37601032, 0.25528411], #random [ 0.49313049, 0.94909878]]) #random
- static reshape(a, newshape, order='C')
reshape array into given shape
- sin = <ufunc 'sin'>
sine of all elements in array
- static squeeze(a, axis=None)
remove dim-1 dimensions
- static stack(arrays, axis=0, out=None)
stack multiple arrays
- static sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
sum elements in array
- static transpose(a, axes=None)
transpose array by flipping two dimensions
- zeros(shape, dtype=float, order='C', *, like=None)
create an array filled with zeros
- static zeros_like(a, dtype=None, order='K', subok=True, shape=None)
create an array filled with zeros
- class lib.backend.cuTensorBackend[source]
Bases:
Backend- class int([x])
- class int(x, base=10) integer
Bases:
objectConvert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4
- bit_length()
Number of bits necessary to represent self in binary.
>>> bin(37) '0b100101' >>> (37).bit_length() 6
- conjugate()
Returns self, the complex conjugate of any int.
- denominator
the denominator of a rational number in lowest terms
- from_bytes(byteorder, *, signed=False)
Return the integer represented by the given array of bytes.
- bytes
Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.
- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value.
- signed
Indicates whether two’s complement is used to represent the integer.
- imag
the imaginary part of a complex number
- numerator
the numerator of a rational number in lowest terms
- real
the real part of a complex number
- to_bytes(length, byteorder, *, signed=False)
Return an array of bytes representing an integer.
- length
Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes.
- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value.
- signed
Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.
- lib.backend.set_backend(name: str)[source]
Set the backend for the FDTD simulations This function monkeypatches the backend object by changing its class. This way, all methods of the backend object will be replaced. :param name: name of the backend. Allowed backend names:
numpy(defaults to float64 arrays)numpy.float16numpy.float32numpy.float64numpy.float128torch(defaults to float64 tensors)torch.float16torch.float32torch.float64torch.cuda(defaults to float64 tensors)torch.cuda.float16torch.cuda.float32torch.cuda.float64TiledArrayTiledArray.sparseTiledArray.cudaTiledArray.cuda.sparse
3.3. lib.boson: Boson classes
This module contains the definition of the Boson
superclass and subclasses: Photon,
Phonon (WIP, not implemented).
3.3.1. Dipole/quadrupole moment functions
3.3.2. Boson class definition
Boson is largely a template class, functionality meant to
be implemented within subclasses.