grig.toolkit.splines package

Submodules

grig.toolkit.splines.spline module

class grig.toolkit.splines.spline.Spline(*args, weights=None, limits=None, degrees=3, smoothing=None, knots=None, knot_estimate=None, eps=1e-08, fix_knots=None, tolerance=0.001, max_iteration=20, exact=False, reduce_degrees=False, solve=True)[source]

Bases: object

Attributes:
exit_message

Returns an exit message for the spline fit.

knot_size

Return the number of knots in each dimension.

size

Return the number of values used for the spline fit.

Methods

__call__(*args)

Evaluate the spline at given coordinates.

check_array_inputs()

Remove zero weights and invalid data points.

create_mapping_indices()

Mapping indices allow 1-D representation of N-D data.

determine_smoothing_spline([smoothing])

Smooth the interpolating spline to the required level.

final_reorder()

Re-order the dimensions of various arrays to match those of the inputs.

fit_knots()

Derive fits at the current knot locations.

initialize_iteration()

Initialize the iteration for the number of current panels.

iterate()

Iteratively determine the spline fit.

knot_indices_to_panel_indices(knot_indices)

Convert knot indices to flat panel indices.

next_iteration()

Perform a single iteration of the spline fit.

order_points()

Sort the data points according to which panel they belong to.

panel_indices_to_knot_indices(panel_indices)

Convert panel indices to dimensional knot indices.

parse_inputs(*args[, weights, limits, ...])

Parse and apply user inputs to the spline fit.

reorder_dimensions(order)

Re-order the dimensions in various attributes.

check_array_inputs()[source]

Remove zero weights and invalid data points.

Invalid data points are those that contain NaN values, weights, or coordinates, or zero weights.

Returns:
None
create_mapping_indices()[source]

Mapping indices allow 1-D representation of N-D data.

Returns:
None
determine_smoothing_spline(smoothing=None)[source]

Smooth the interpolating spline to the required level.

Parameters:
smoothingfloat, optional

Used to specify the an alternate smoothing factor. Note that this should be very close to the original smoothing factor in order to succeed.

Returns:
None
property exit_message

Returns an exit message for the spline fit. Error codes in the range -2 -> 0 generally indicate a successful fit.

Returns:
messagestr
final_reorder()[source]

Re-order the dimensions of various arrays to match those of the inputs.

The dimensions of the various data structures may have changed during the course of processing to reduce the bandwidth of the observation matrix. This step correctly reorders all dimensions such that they match those initially provided by the user.

Returns:
None
fit_knots()[source]

Derive fits at the current knot locations.

In addition to finding the value of the function at each knot, the knot weights and weight normalized coordinates are also determined. These a subsequently used to decide where a new knot should be placed.

Returns:
None
initialize_iteration()[source]

Initialize the iteration for the number of current panels.

Creates array maps that represents N-dimensional data flattened to a single dimension for fast access and the ability to pass these structures to numba JIT compiled functions.

Returns:
None
iterate()[source]

Iteratively determine the spline fit.

Calculates the splines and coefficients for the provided data. If this cannot be accomplished before reaching the maximum number of iterations, a smoothing spline will be calculated instead.

Returns:
None
knot_indices_to_panel_indices(knot_indices)[source]

Convert knot indices to flat panel indices.

Parameters:
knot_indicesnumpy.ndarray (int)

An array of shape (n_dimensions, n_knots).

Returns:
panel_indicesnumpy.ndarray (int)

The flat 1-D panel indices for the knots.

property knot_size

Return the number of knots in each dimension.

Returns:
n_knotsnumpy.ndarray (int)

An array of shape (n_dimensions,).

next_iteration()[source]

Perform a single iteration of the spline fit.

During each iteration, the observation matrix is built and solved. An exit code will be generated in cases where no further modifications to the solution are appropriate. Additional knots will also be added if required and possible.

Returns:
continue_iterationsbool

If False no further iterations should occur due to an acceptable solution being reached or due to a given limitation. If True, subsequent iterations are deemed appropriate.

order_points()[source]

Sort the data points according to which panel they belong to.

This is based on the fporde Fortran fitpack routine.

Returns:
None
panel_indices_to_knot_indices(panel_indices)[source]

Convert panel indices to dimensional knot indices.

Parameters:
panel_indicesnumpy.ndarray (int)

An array of shape (n_knots,).

Returns:
panel_indicesnumpy.ndarray (int)

knot.

parse_inputs(*args, weights=None, limits=None, degrees=3, smoothing=None, knots=None, fix_knots=None, knot_estimate=None, exact=False, reduce_degrees=False, eps=1e-08, tolerance=0.001, max_iteration=20)[source]

Parse and apply user inputs to the spline fit.

Parameters:
argsn-tuple (numpy.ndarray) or numpy.ndarray

The input arguments of the form (c1, …, cn, d) or d where c signifies data coordinates and d are the data values. If a single data array is passed in, the coordinates are derived from the data dimensions. For example if d is an array of shape (a, b, c), c1 will range from 0 -> a - 1 etc. If coordinates are specified, the coordinates for each dimension and the data array should be one-dimensional.

weightsnumpy.ndarray, optional

Optional weights to supply to the spline fit for each data point. Should be the same shape as the supplied data values.

limitsnumpy.ndarray (float), optional

An array of shape (n_dimensions, 2) that may be supplied to set the minimum and maximum coordinate values used during the spline fit. For example, limits[1, 0] sets the minimum knot value in the second dimensions and limits[1, 1] sets the maximum knot value in the second dimension. By default this is set to the minimum and maximum values of the coordinates in each dimension.

degreesint or numpy.ndarray (int), optional

The degree of spline to fit in each dimension. Either a scalar can be supplied pertaining to all dimensions, or an array of shape (n_dimensions,) can be used.

smoothingfloat, optional

Used to specify the smoothing factor. If set to None, the smoothing will be determined based on user settings or input data. If exact is True, smoothing will be disabled (zero). If exact is False, smoothing will be set to n - sqrt(2 * n) where n is the number of data values. If supplied, smoothing must be greater than zero. See __init__() for further details. Note that if smoothing is zero, and the degrees are not equal over each dimension, smoothing will be set to eps due to numerical instabilities.

knotslist or tuple or numpy.ndarray, optional

A set of starting knot coordinates for each dimension. If a list or tuple is supplied it should be of length n_dimensions where element i is an array of shape (n_knots[i]) for dimension i. If an array is supplied, it should be of shape (n_dimension, max(n_knots)). Note that there must be at least 2 * (degree + 1) knots for each dimension. Unused or invalid knots may be set to NaN, at the end of each array. Knot coordinates must also be monotonically increasing in each dimension.

fix_knotsbool, optional

If True, do not attempt to modify or add knots to the spline fit. Only the initial supplied user knots will be used.

knot_estimatenumpy.ndarray (int), optional

The maximum number of knots required for the spline fit in each dimension and of shape (n_dimensions,). If not supplied, the knot estimate will be set to int((n / n_dimensions) ** n_dimensions^(-1)) or n_knots if knots were supplied and fixed.

exactbool, optional

If True, the initial knots used will coincide with the actual input coordinates and smoothing will be set to zero. No knots should be supplied by the user in this instance.

reduce_degreesbool, optional

Only relevant if exact is True. If set to True, the maximum allowable degree in each dimension will be limited to (len(unique(x)) // 2) - 1 where x are the coordinate values in any dimension.

epsfloat, optional

A value where 0 < eps < 1. This defines the magnitude used to identify singular values in the spline observation matrix (A). If any row of A[:, 0] < (eps * max(A[:,0])) it will be considered singular.

tolerancefloat, optional

A value in the range 0 < tolerance < 1 used to determine the exit criteria for the spline fit. See __init__() further details.

max_iterationint, optional

The maximum number of iterations to perform when solving for the spline fit.

Returns:
None
reorder_dimensions(order)[source]

Re-order the dimensions in various attributes.

Occasionally it is beneficial to re-order the dimensions of the data structures such that a minimal bandwidth for the observation matrix is achievable. This reduces the amount of processing time required to reach a solution.

Parameters:
ordernumpy.ndarray (int)

An array of shape (n_dimensions,) indicating the new order of the dimensions. E.g., to re-order dimensions [1, 2, 3] to [3, 1, 2], order should be [1, 2, 0].

Returns:
None
property size

Return the number of values used for the spline fit.

Returns:
nint

grig.toolkit.splines.spline_utils module

grig.toolkit.splines.spline_utils.add_knot(knot_weights, knot_coords, panel_shape, knots, n_knots, knot_estimate, k1)[source]

Add a knot to the spline fit.

Adds a knot near the currently highest weighted knot.

Parameters:
knot_weightsnumpy.ndarray (float)

The knot weights of shape (n_dimensions, n_knots).

knot_coordsnumpy.ndarray (float)

The knot coordinates of shape (n_dimensions, n_knots).

panel_shapenumpy.ndarray (int)

The number of panels in the spline fit of shape (n_dimensions,).

knotsnumpy.ndarray (float)

The knots in each dimension of shape (n_dimensions, max_knot_estimate). Must be monotonically increasing for each dimension.

n_knotsnumpy.ndarray (int)

The number of knots in each dimension of shape (n_dimensions,).

knot_estimatenumpy.ndarray (int)

The maximum number of knots allowable of shape (n_dimensions,).

k1numpy.ndarray (int)

An array of shape (n_dimensions,) where k1[dimension] = degree[dimension] + 1.

Returns:
exit_codeint

Returns an exit code of 1 if the maximum number of allowable knots has already been reached and no more should be added. Returns an exit code of 5 if the new knot location coincides with an already existing knot. Returns 0 if a knot was successfully added.

grig.toolkit.splines.spline_utils.back_substitute(amat, beta, n_coefficients, bandwidth)[source]

Use back-substitution to solve a reduced row-echelon form matrix.

The amat matrix MUST be full rank.

Parameters:
amatnumpy.ndarray (float)

The ‘A’ in the system Ax = B of shape (>=n_coefficients, >=bandwidth).

betanumpy.ndarray (float)

The ‘B’ in the system Ax = B of shape (>=n_coefficients,).

n_coefficientsint

The number of coefficients to solve for.

bandwidthint

The bandwidth of matrix A (amat).

Returns:
coefficientsnumpy.ndarray (float)

The coefficients of shape (n_coefficients.).

grig.toolkit.splines.spline_utils.build_observation(coordinates, values, weights, n_coefficients, bandwidth, degrees, knots, knot_steps, start_indices, next_indices, panel_mapping, spline_mapping)[source]

Build the spline observation matrices.

The observation matrices are used to solve the linear system of equations Ax = B in row-echelon form. A and B (amat and beta) may be used to solve for x using either back_substitute() if A is full rank, or solve_rank_deficiency() if A is rank deficient.

Parameters:
coordinatesnumpy.ndarray (float)

The m coordinates to fit (n_dimensions, m).

valuesnumpy.ndarray (float)

The values at each coordinate (m,).

weightsnumpy.ndarray (float)

The associated weight value for each coordinate (m,).

n_coefficientsint

The number of coefficients to fit.

bandwidthint

The bandwidth of the observation.

degreesnumpy.ndarray (int)

The degrees of the splines to fit (n_dimensions,).

knotsnumpy.ndarray (float)

The knots in each dimension of shape (n_dimensions, max_knot_estimate). Must be monotonically increasing for each dimension.

knot_stepsnumpy.ndarray (int)

The flat index mapping steps in knot-space of shape (n_dimensions,). These are returned by passing the shape (n_knots - degrees - 1) into flat_index_mapping().

start_indicesnumpy.ndarray (int)

The starting indices of shape (m,) as returned by create_ordering().

next_indicesnumpy.ndarray (int)

The next indices of shape (m,) as returned by create_ordering().

panel_mappingnumpy.ndarray (int)

An array containing the panel mapping (flat to n-D) indices. This is created by passing the panel shape (n_knots - (2 * degrees) - 1) into flat_index_mapping(). Should be an array of shape (n_dimensions, n_panels).

spline_mappingnumpy.ndarray (int)

An array containing the spline mapping (flat to n-D) indices. This is created by passing the spline shape (degrees + 1) into flat_index_mapping(). Should be an array of shape (n_dimensions, n_spline_coefficients).

Returns:
amat, beta, knot_splines, ssrarray, array, array, float

The observation matrix amat of shape (n_coefficients, bandwidth), the observation matrix beta of shape (n_coefficients,), the base spline coefficients for each knot (n_dimensions, n_knots, max(degree) + 1), and ssr (sum of the residuals squared)

grig.toolkit.splines.spline_utils.calculate_minimum_bandwidth(degrees, n_knots, permutations)[source]

Calculate the minimum possible bandwidth given knots and spline degree.

The bandwidth of a given observation matrix is given as:

k0(d1*d2*d3*…*dn) + k1(d2*d3*…*dn) + k2(d3*…*dn) + … + kn

for the n-dimensional case where a number (1,2,3, etc) signifies the dimension number, k represents the degree, and dn is given as n_knots - k - 1. This function loops through all available dimensional permutations in order to find the permutation that results in the smallest bandwidth.

Finding the bandwidth is only relevant in more than one dimension. The bandwidth of the observation matrix may be minimized by switching the order of dimensions (coordinates, degrees, knot lines, etc.). This can speed up evaluation of spline coefficients and knot locations.

To save speed, permutations should be pre-calculated and supplied to this function, containing each possible ordering of the dimensions. For example, for two dimensions, permutations would be [[0, 1], [1, 0]]. For three dimensions permutations would be:

[[0 1 2]

[0 2 1] [1 0 2] [1 2 0] [2 0 1] [2 1 0]]

Note that for 1-dimension the minimum bandwidth will be fixed.

Dimensional permutations can be calculated via:

permutations = np.array(list(itertools.permutations(range(n_dim))))

where ndim is the number of dimensions.

Parameters:
degreesnumpy.ndarray (int)

The degrees of the spline in each dimension (n_dimensions,).

n_knotsnumpy.ndarray (int)

The number of knots in each dimension (n_dimensions,).

permutationsnumpy.ndarray (int)

All possible dimensional ordering of shape (n_permutations, n_dimensions).

Returns:
minimum_bandwidth, permutation_index, changedint, int, bool

The minimum bandwidth, the index of the permutation for the minimum bandwidth, and whether the permutation is different to the first available permutation.

grig.toolkit.splines.spline_utils.check_input_arrays(values, coordinates, weights)[source]

Check all input arrays.

For a data point to be valid, it must have a finite value, weight and coordinate. The weight must greater than zero, and coordinates must be finite in each dimension.

Parameters:
valuesnumpy.ndarray (float)

An array of values of shape (n_data,).

coordinatesnumpy.ndarray (float)

The coordinate values of shape (n_dimensions, n_data).

weightsnumpy.ndarray (float)

The point weights of shape (n_data,).

Returns:
validnumpy.ndarray (bool)

A boolean mask of shape (n_data,) where False marks an invalid data coordinate.

grig.toolkit.splines.spline_utils.create_ordering(indices, size=-1)[source]

Given a list of indices, create an ordering structure for fast access.

The purpose of this function is to create two arrays than can be used to quickly retrieve all reverse indices for a given index using numba. For example, consider the array x:

>>> x = np.array([0, 0, 2, 1, 4, 2, 1, 2, 2, 1])
>>> si, ni = create_ordering(x)

We can now extract the indices on x for a given value. E.g.,

>>> ri = []
>>> for value in [0, 1, 2, 3, 4]:
...     inds = []
...     ri.append(inds)
...     reverse_index = si[value]
...     while reverse_index != -1:
...         inds.append(reverse_index)
...         reverse_index = ni[reverse_index]
>>> print(ri)
[[1, 0], [9, 6, 3], [8, 7, 5, 2], [], [4]]

i.e., the indices on x where x is equal to 0 are [1, 0], and [8, 7, 5, 2] where x is equal to 2.

This is a very useful feature for N-D numba functions as reverse indices can be precalculated and represented as 1-dimensional arrays and we avoid functions such as np.nonzero, argwhere etc, that introduce additional overhead associated with array creation.

Parameters:
indicesnumpy.ndarray (int)

A list of input indices.

sizeint

The size of the array to return.

Returns:
start_indices, next_indicesnumpy.ndarray (int), numpy.ndarray (int)
grig.toolkit.splines.spline_utils.determine_smoothing_spline(knots, n_knots, knot_estimate, degrees, initial_sum_square_residual, smoothing, smoothing_difference, n_coefficients, bandwidth, amat, beta, max_iteration, knot_steps, knot_mapping, eps, splines, start_indices, next_indices, panel_mapping, spline_mapping, coordinates, values, weights, panel_shape, accuracy)[source]

Smooth the current solution to a specified level.

Parameters:
knotsnumpy.ndarray (float)

The knots in each dimension of shape (n_dimensions, max_knot_estimate). Must be monotonically increasing for each dimension.

n_knotsnumpy.ndarray (int)

The number of knots in each dimension of shape (n_dimensions,).

knot_estimatenumpy.ndarray (int)

The maximum number of knots allowable of shape (n_dimensions,).

degreesnumpy.ndarray (int)

The degrees of the spline in each dimension (n_dimensions,).

initial_sum_square_residualfloat

The initial sum square of the residuals from the first knot fit.

smoothingfloat

Used to specify the smoothing factor.

smoothing_differencefloat

The sum of the square residuals minus the smoothing factor.

n_coefficientsint

The number of coefficients to fit.

bandwidthint

The bandwidth of the observation.

amatnumpy.ndarray (float)

The ‘A’ in the system Ax = B of shape (>=n_coefficients, >=bandwidth).

betanumpy.ndarray (float)

The ‘B’ in the system Ax = B of shape (>=n_coefficients,).

max_iterationint

The maximum number of iterations used to determine the smoothing spline.

knot_stepsnumpy.ndarray (int)

The flat index mapping steps in knot-space of shape (n_dimensions,). These are returned by passing the shape (n_knots - degrees - 1) into flat_index_mapping().

knot_mappingnumpy.ndarray (int)

An array containing the knot mapping (flat to n-D) indices. This is created by passing the shape (n_knots - degrees - 1) into flat_index_mapping(). Should be an array of shape (n_dimensions, n_panels).

epsfloat

The precision to determine singular values of A. If any row of amat[:,0] < (eps * max(amat[:,0])) it will be considered singular.

splinesnumpy.ndarray (float)

The splines of shape (n_dimensions, n_data, max(k1)).

start_indicesnumpy.ndarray (int)

The starting indices of shape (m,) as returned by create_ordering().

next_indicesnumpy.ndarray (int)

The next indices of shape (m,) as returned by create_ordering().

panel_mappingnumpy.ndarray (int)

An array containing the panel mapping (flat to n-D) indices. This is created by passing the panel shape (n_knots - (2 * degrees) - 1) into flat_index_mapping(). Should be an array of shape (n_dimensions, n_panels).

spline_mappingnumpy.ndarray (int)

The 1-D to N-D spline mapping array as returned by flat_index_mapping(). Should be of shape (n_dimensions, n_spline).

coordinatesnumpy.ndarray (float)

The coordinates at which to evaluate the spline of shape (n_dimensions, n).

valuesnumpy.ndarray (float)

An array of values of shape (n_data,).

weightsnumpy.ndarray (float)

The value weights of shape (n_data,).

panel_shapenumpy.ndarray (int)

The number of panels in the spline fit of shape (n_dimensions,).

accuracyfloat

The accuracy that is used to determine when a suitable smoothing fit has been achieved. Iterations will stop when abs(smoothing - sum_square_residuals) < accuracy.

Returns:
coefficients, fp, ier, fitted_valuesndarray, float, float, ndarray

The new spline coefficients, sum of the residuals^2, exit code, and the fitted values.

grig.toolkit.splines.spline_utils.discontinuity_jumps(knot_line, n_knot, degree, b_spline)[source]

Calculates the discontinuity jumps.

Calculates the discontinuity jumps of the kth derivative of the b-splines of degree k at the knots k+2 -> n - k - 1. The results are updated in-place in the b_spline array.

Adapted from the Fortran function fpdisc in the fitpack library.

Parameters:
knot_linenumpy.ndarray (float)

The knot locations in a single dimension of shape (>= n_knots,).

n_knotint

The number of knots in the knot line.

degreeint

The degree of the spline.

b_splinenumpy.ndarray (float)

An array of shape (max(knot_estimate), k + 2) where k is the degree of the spline containing the spline coefficients. Values will be updated in-place.

Returns:
None
grig.toolkit.splines.spline_utils.evaluate_bspline(knot_line, degree, x, knot_index, spline=None)[source]

Evaluate b-splines for given knots at a coordinate.

Evaluates the (degree + 1) non-zero b-splines at t[i] <= x < t[i + 1] where t is the line of knots knot_line and i is the knot_index. This uses the stable recurrence relation of DeBoor and Cox (2007).

Parameters:
knot_linenumpy.ndarray (float)

The line of monotonically increasing knots of shape (>=n_knots).

degreeint

The degree of spline to evaluate.

xfloat

The coordinate at which the spline should be evaluated.

knot_indexint

The index (i) of the knot satisfying t[i] <= x < t[i + 1] where t is the knot_line.

splinenumpy.ndarray (float), optional

An optionally created array to hold the results of this function of shape (>=degree + 1).

Returns:
splinenumpy.ndarray (float)

The output spline of shape (degree + 1) if spline is not supplied as an input parameter, or (spline.size,) otherwise.

grig.toolkit.splines.spline_utils.find_knot(coordinate, knots, valid_knot_start, valid_knot_end, allow_outside=True, lower_bounds=None, upper_bounds=None)[source]

Find the knot index for a single coordinate.

Parameters:
coordinatenumpy.ndarray (float)

The coordinates of shape (n_dimensions, m).

knotsnumpy.ndarray (float)

The knots in each dimension of shape (n_dimensions, max_knot_estimate). Must be monotonically increasing for each dimension.

valid_knot_startnumpy.ndarray (int)

The start indices for the first valid knot in each dimension. For a spline of degree k, this should be k. The shape is (n_dimensions,).

valid_knot_endnumpy.ndarray (int)

The last valid knot index in each dimension of shape (n_dimensions,). for a spline of degree k, this should be n_knots - degree - 1.

allow_outsidebool, optional

If True (default), allow a fit outside the bounds of the knots.

lower_boundsnumpy.ndarray (float)

Specifies the lower range of valid coordinates for each dimension.

upper_boundsnumpy.ndarray (float)

Specifies the upper range of valid coordinates for each dimension.

Returns:
knot_indicesnumpy.ndarray (int)

The knot index for each coordinate in each dimension of shape (n_dimensions, m).

grig.toolkit.splines.spline_utils.find_knots(coordinates, knots, valid_knot_start, valid_knot_end)[source]

Find the knot indices for an array of coordinates.

The knot index (i) for a given coordinate (x) is defined such that knot[i] <= x < knot[i + 1]. Coordinates that are less than the minimum valid knot are set to the minimum valid knot index, and values that are greater than the maximum valid knot are set to the maximum valid knot index - 1.

Parameters:
coordinatesnumpy.ndarray (float)

The coordinates of shape (n_dimensions, m) where m are the number of coordinates.

knotsnumpy.ndarray (float)

The knots in each dimension of shape (n_dimensions, max_knot_estimate). Must be monotonically increasing for each dimension.

valid_knot_startnumpy.ndarray (int)

The start indices for the first valid knot in each dimension. For a spline of degree k, this should be k. The shape is (n_dimensions,).

valid_knot_endnumpy.ndarray (int)

The last valid knot index in each dimension of shape (n_dimensions,). for a spline of degree k, this should be n_knots - degree - 1.

Returns:
knot_indicesnumpy.ndarray (int)

The knot index for each coordinate in each dimension of shape (n_dimensions, m).

grig.toolkit.splines.spline_utils.fit_point(coefficients, spline, spline_mapping, knot_steps, j_rot, n_spline, n_dimensions)[source]

Evaluate fitted value given a spline and coefficients.

Parameters:
coefficientsnumpy.ndarray (float)

The coefficients of shape (n_coefficients,).

splinenumpy.ndarray (float)

The spline for the point of shape (n_dimensions, n_spline).

spline_mappingnumpy.ndarray (int)

The 1-D to N-D spline mapping array as returned by flat_index_mapping(). Should be of shape (n_dimensions, n_spline).

knot_stepsnumpy.ndarray (int)

The N-D to 1-D knot mapping steps as returned by flat_index_mapping(). Should be of shape (n_dimensions,).

j_rotint

The starting 1-D index on the coefficient array for the given spline.

n_splineint

The total number of spline coefficients that will be used to perform the fit.

n_dimensionsint

The number of dimensions in the fit.

Returns:
fitted_valuefloat
grig.toolkit.splines.spline_utils.flat_index_mapping(shape)[source]

Return index slices for Numba flattened arrays.

Given the shape of an array, return a variety of useful parameters for indexing a flattened (x.ravel()) version of that array.

For example, consider an array (x) of shape (3, 4):

x = [[ 0, 1, 2, 3],

[ 4, 5, 6, 7], [ 8, 9, 10, 11]]

which when flattened (x_flat) is equal to

x_flat = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

map_indices returns the indices of x_flat on x, and is a 2-D array of shape (n_dimensions, x.size). map_indices[:, 6] gives the N-D index of element 6 of x_flat in terms of x. i.e, map_indices[:, 6] = [1, 2].

transpose_indices contains the flat indices of an array that has been transposed. i.e. x.T.ravel()[transpose_indices] == x_flat

step_size contains indicates the flat index jump along the given dimension. i.e., the step size for the above example is [4, 1], indicating that for every increment along the first dimension, the flat index increments by 4. Likewise, for every increment along the second dimension, the flat index increments by 1.

Parameters:
shapenumpy.ndarray (int)
Returns:
map_indices, transpose_indices, step_size
grig.toolkit.splines.spline_utils.givens_parameters(x, y)[source]

Calculate the parameters of a Givens transformation.

Parameters:
xfloat

The x value.

yfloat

The y value.

Returns:
updated_y, cos, sin
grig.toolkit.splines.spline_utils.givens_rotate(cos, sin, x, y)[source]

Apply the Givens transformation to a value.

Parameters:
cosfloat
sinfloat
xfloat
yfloat
Returns:
x_rotated, y_rotated
grig.toolkit.splines.spline_utils.knot_fit(splines, coefficients, start_indices, next_indices, panel_mapping, spline_mapping, knot_steps, panel_shape, k1, weights, values, coordinates)[source]

Calculate the spline fit at each knot location.

Parameters:
splinesnumpy.ndarray (float)

The splines of shape (n_dimensions, n_data, max(k1)).

coefficientsnumpy.ndarray (float)

The spline coefficients of shape (n_coefficients,).

start_indicesnumpy.ndarray (int)

The start indices of the reverse lookup array of shape (n_data,). See create_ordering() for further details.

next_indicesnumpy.ndarray (int)

The “next” indices of the reverse lookup array of shape (n_data,_. See create_ordering() for further details.

panel_mappingnumpy.ndarray (int)

An array containing the panel mapping (flat to n-D) indices. This is created by passing the panel shape (n_knots - (2 * degrees) - 1) into flat_index_mapping(). Should be an array of shape (n_dimensions, n_panels).

spline_mappingnumpy.ndarray (int)

An array containing the spline mapping (flat to n-D) indices. This is created by passing the spline shape (degrees + 1) into flat_index_mapping(). Should be an array of shape (n_dimensions, n_spline_coefficients).

knot_stepsnumpy.ndarray (int)

The flat index mapping steps in knot-space of shape (n_dimensions,). These are returned by passing the shape (n_knots - degrees - 1) into flat_index_mapping().

panel_shapenumpy.ndarray (int)

The panel shape will be defined as n_knots - (2 * k1) + 1 where k1 and n_knots are both of shape (n_dimensions,).

k1numpy.ndarray (int)

An array of shape (n_dimensions,) where k1[dimension] = degree[dimension] + 1.

weightsnumpy.ndarray (float)

The value weights of shape (n_data,).

valuesnumpy.ndarray (float)

The values to fit of shape (n_data,).

coordinatesnumpy.ndarray (float)

The coordinates of each value in each dimension of shape (n_dimensions, n_data).

Returns:
fit, knot_weights, knot_coordinates3-tuple of numpy.ndarray (float)

The fitted value at each knot of shape (n_data,), the knot weights of shape (max_panels,), and the knot coordinates of shape (max_panels,) where max_panels is the maximum number of panels available in the spline fit.

grig.toolkit.splines.spline_utils.perform_fit(coordinates, knots, coefficients, degrees, panel_mapping, panel_steps, knot_steps, nk1, spline_mapping, n_knots)[source]

Evaluate a given spline at multiple coordinates.

Parameters:
coordinatesnumpy.ndarray (float)

The coordinates at which to evaluate the spline of shape (n_dimensions, n).

knotsnumpy.ndarray (float)

The knots in each dimension of shape (n_dimensions, max_knot_estimate). Must be monotonically increasing for each dimension.

coefficientsnumpy.ndarray (float)

The spline coefficients of shape (n_coefficients,).

degreesnumpy.ndarray (int)

The degrees of the spline in each dimension (n_dimensions,).

panel_mappingnumpy.ndarray (int)

An array containing the panel mapping (flat to n-D) indices. This is created by passing the panel shape (n_knots - (2 * degrees) - 1) into flat_index_mapping(). Should be an array of shape (n_dimensions, n_panels).

panel_stepsnumpy.ndarray (int)

The flat index mapping steps in panel-space of shape (n_dimensions,). These are returned by passing the shape Spline.panel_shape into flat_index_mapping().

knot_stepsnumpy.ndarray (int)

The flat index mapping steps in knot-space of shape (n_dimensions,). These are returned by passing the shape (n_knots - degrees - 1) into flat_index_mapping().

nk1numpy.ndarray (int)

An array of shape (n_dimensions,) containing the values n_knots - k1 where n_knots are the number of knots in each dimension, and k1 are the spline degrees + 1 in each dimension.

spline_mappingnumpy.ndarray (int)

An array containing the spline mapping (flat to n-D) indices. This is created by passing the spline shape (degrees + 1) into flat_index_mapping(). Should be an array of shape (n_dimensions, n_spline_coefficients).

n_knotsnumpy.ndarray (int)

The number of knots in each dimension (n_dimensions,).

Returns:
fitted_valuesnumpy.ndarray (float)

The spline evaluated at coordinates of shape (n,).

grig.toolkit.splines.spline_utils.rational_interp_zero(p1, f1, p2, f2, p3, f3)[source]

Determines p where (u + p + v)/(p + w) = 0.

Given three points (p1, f1), (p2, f2), (p3, f3), rational_interp_zero gives the value of p such that the rational interpolating function of the form r(p) = (u*p+v)/(p+w) equals zero at p.

Adapted from the Fortran function fprati in the fitpack library.

Parameters:
p1float
f1float
p2float
f2float
p3float
f3float
Returns:
p, p1, f1, p2, f2, p3, f3float
grig.toolkit.splines.spline_utils.single_fit(coordinate, knots, coefficients, degrees, panel_mapping, panel_steps, knot_steps, nk1, spline_mapping, k1=None, n_spline=None, work_spline=None, lower_bounds=None, upper_bounds=None)[source]

Return a fitted value at the given coordinate.

Parameters:
coordinatenumpy.ndarray (float)

The coordinate at which to return a fit of shape (n_dimensions,).

knotsnumpy.ndarray (float)

The knots in each dimension of shape (n_dimensions, max_knot_estimate). Must be monotonically increasing for each dimension.

coefficientsnumpy.ndarray (float)

The coefficients of shape (n_coefficients,).

degreesnumpy.ndarray (int)

The degrees of the spline in each dimension (n_dimensions,).

panel_mappingnumpy.ndarray (int)

An array containing the panel mapping (flat to n-D) indices. This is created by passing the panel shape (n_knots - (2 * degrees) - 1) into flat_index_mapping(). Should be an array of shape (n_dimensions, n_panels).

panel_stepsnumpy.ndarray (int)

The flat index mapping steps in panel-space of shape (n_dimensions,). These are returned by passing the shape Spline.panel_shape into flat_index_mapping().

knot_stepsnumpy.ndarray (int)

The flat index mapping steps in knot-space of shape (n_dimensions,). These are returned by passing the shape (n_knots - degrees - 1) into flat_index_mapping().

nk1numpy.ndarray (int)

An array of shape (n_dimensions,) containing the values n_knots - k1 where n_knots are the number of knots in each dimension, and k1 are the spline degrees + 1 in each dimension.

spline_mappingnumpy.ndarray (int)

An array containing the spline mapping (flat to n-D) indices. This is created by passing the spline shape (degrees + 1) into flat_index_mapping(). Should be an array of shape (n_dimensions, n_spline_coefficients).

k1numpy.ndarray (int)

An array of shape (n_dimensions,) where k1[dimension] = degree[dimension] + 1.

n_splineint

The total number of spline coefficients that will be used to perform the fit.

work_splinenumpy.ndarray (float)

An optional work array of shape (n_dimensions, max(k1)) that can be supplied in order to skip the overhead involved with array creation.

lower_boundsnumpy.ndarray (float)

Specifies the lower range of valid coordinates for each dimension and is of shape (n_dimensions,).

upper_boundsnumpy.ndarray (float)

Specifies the upper range of valid coordinates for each dimension and is of shape (n_dimensions,).

Returns:
fitted_valuefloat
grig.toolkit.splines.spline_utils.solve_observation(amat, beta, n_coefficients, bandwidth, eps)[source]

Solve a row-echelon reduced linear system of equations Ax=B.

Returns the results of back_substitute() if A is full rank, or the results of solve_rank_deficiency() otherwise.

Parameters:
amatnumpy.ndarray (float)

The array A in row-echelon form. Should be of shape (>=n_coefficients, >=bandwidth).

betanumpy.ndarray (float)

The array B accounting for row-echelon form. Should be of shape (>=n_coefficients,).

n_coefficientsint

The number of coefficients to solve for.

bandwidthint

The bandwidth of the observation matrix A (amat).

epsfloat

The precision to determine singular values of A. If any row of amat[:,0] < (eps * max(amat[:,0])) it will be considered singular.

Returns:
coefficients, rank, ssrnumpy.ndarray (float), int, float

The derived coefficients, the rank of A, and the sum of the squared residuals.

grig.toolkit.splines.spline_utils.solve_rank_deficiency(amat, beta, n_coefficients, bandwidth, tolerance)[source]

Solve a rank-deficient row-echelon reduced form matrix.

Parameters:
amatnumpy.ndarray (float)

The ‘A’ in the system Ax = B of shape (>=n_coefficients, >=bandwidth).

betanumpy.ndarray (float)

The ‘B’ in the system Ax = B of shape (>=n_coefficients,).

n_coefficientsint

The number of coefficients to solve for.

bandwidthint

The bandwidth of matrix A (amat).

tolerancefloat

The value over which the zeroth element of amat will be considered rank deficient. Deficient rows will be rotated into a new reduced rank matrix and solved accordingly.

Returns:
coefficients, ssr, ranknumpy.ndarray (float), float, int

The coefficients of shape (n_coefficients.), the sum of the squared residuals (ssr), and the rank.