Copyright (c) 2006-2011, NIPY Developers
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
Neither the name of the NIPY Developers nor the names of any
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
“AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Utilities to support special Python descriptors [1], [2] in particular the use
of a useful pattern for properties we call ‘one time properties’. These are
object attributes which are declared as properties, but become regular
attributes once they’ve been read the first time. They can thus be evaluated
later in the object’s life cycle, but once evaluated they become normal, static
attributes with no function call overhead on access or any other constraints.
A special ResetMixin class is provided to add a .reset() method to users who
may want to have their objects capable of resetting these computed properties
to their ‘untriggered’ state.
Create a unit sphere by subdividing all triangles of an octahedron
recursively.
The unit sphere has a radius of 1, which also means that all points in this
sphere (assumed to have centre at [0, 0, 0]) have an absolute value (modulus)
of 1. Another feature of the unit sphere is that the unit normals of this
sphere are exactly the same as the vertices.
This recursive method will avoid the common problem of the polar singularity,
produced by 2d (lon-lat) parameterization methods.
This is the standard physics convention where theta is the
inclination (polar) angle, and phi is the azimuth angle.
Imagine a sphere with center (0,0,0). Orient it with the z axis
running south-north, the y axis running west-east and the x axis
from posterior to anterior. theta (the inclination angle) is the
angle to rotate from the z-axis (the zenith) around the y-axis,
towards the x axis. Thus the rotation is counter-clockwise from the
point of view of positive y. phi (azimuth) gives the angle of
rotation around the z-axis towards the y axis. The rotation is
counter-clockwise from the point of view of positive z.
Equivalently, given a point P on the sphere, with coordinates x, y,
z, theta is the angle between P and the z-axis, and phi is
the angle between the projection of P onto the XY plane, and the X
axis.
Geographical nomenclature designates theta as ‘co-latitude’, and phi
as ‘longitude’
for excellent discussion of the many different conventions
possible. Here we use the physics conventions, used in the
wikipedia page.
Derivations of the formulae are simple. Consider a vector x, y, z of
length r (norm of x, y, z). The inclination angle (theta) can be
found from: cos(theta) == z / r -> z == r * cos(theta). This gives
the hypotenuse of the projection onto the XY plane, which we will
call Q. Q == r*sin(theta). Now x / Q == cos(phi) -> x == r *
sin(theta) * cos(phi) and so on.
We have deliberately named this function sphere2cart rather than
sph2cart to distinguish it from the Matlab function of that
name, because the Matlab function uses an unusual convention for the
angles that we did not want to replicate. The Matlab function is
trivial to implement with the formulae given in the Matlab help.
In case the angle \(||r||\) is very small, the above formula may lead
to numerical instabilities. We instead use a Taylor expansion
around \(theta=0\):
R = I + \sin(\theta)/\theta \mathbf{S}_r +
(1-\cos(\theta))/\theta^2 \mathbf{S}_r^2
leading to:
R = \mathbf{I} + (1-\theta^2/6)*\mathbf{S}_r +
(\frac{1}{2}-\theta^2/24)*\mathbf{S}_r^2
Distance across sphere surface between pts1 and pts2
Parameters:
pts1(N,R) or (R,) array_like
where N is the number of points and R is the number of
coordinates defining a point (R==3 for 3D)
pts2(N,R) or (R,) array_like
where N is the number of points and R is the number of
coordinates defining a point (R==3 for 3D). It should be
possible to broadcast pts1 against pts2
radiusNone or float, optional
Radius of sphere. Default is to work out radius from mean of the
length of each point vector
check_radiusbool, optional
If True, check if the points are on the sphere surface - i.e
check if the vector lengths in pts1 and pts2 are close to
radius. Default is True.
Returns:
d(N,) or (0,) array
Distances between corresponding points in pts1 and pts2
across the spherical surface, i.e. the great circle distance
If either of pts1 or pts2 is 2D, then we take the first
dimension to index points, and the second indexes coordinate. More
generally, we take the last dimension to be the coordinate
dimension.
Parameters:
pts1(N,R) or (R,) array_like
where N is the number of points and R is the number of
coordinates defining a point (R==3 for 3D)
pts2(N,R) or (R,) array_like
where N is the number of points and R is the number of
coordinates defining a point (R==3 for 3D). It should be
possible to broadcast pts1 against pts2
Returns:
d(N,) or (0,) array
Cartesian distances between corresponding points in pts1 and
pts2
Lambert Equal Area Projection from polar sphere to plane
Return positions in (y1,y2) plane corresponding to the points
with polar coordinates (theta, phi) on the unit sphere, under the
Lambert Equal Area Projection mapping (see Mardia and Jupp (2000),
Directional Statistics, p. 161).
The Lambert EAP maps the upper hemisphere to the planar disc of radius 1
and the lower hemisphere to the planar annulus between radii 1 and 2,
and vice versa.
Parameters:
thetaarray_like
theta spherical coordinates
phiarray_like
phi spherical coordinates
Returns:
y(N,2) array
planar coordinates of points following mapping by Lambert’s EAP.
dipy.core.geometry.lambert_equal_area_projection_cart(x, y, z)[source]#
Lambert Equal Area Projection from cartesian vector to plane
Return positions in \((y_1,y_2)\) plane corresponding to the
directions of the vectors with cartesian coordinates xyz under the
Lambert Equal Area Projection mapping (see Mardia and Jupp (2000),
Directional Statistics, p. 161).
The Lambert EAP maps the upper hemisphere to the planar disc of radius 1
and the lower hemisphere to the planar annulus between radii 1 and 2,
The Lambert EAP maps the upper hemisphere to the planar disc of radius 1
and the lower hemisphere to the planar annulus between radii 1 and 2.
and vice versa.
See doc for sphere2cart for angle conventions
Parameters:
xarray_like
x coordinate in Cartesian space
yarray_like
y coordinate in Cartesian space
zarray_like
z coordinate
Returns:
y(N,2) array
planar coordinates of points following mapping by Lambert’s EAP.
a, b and c are 3-dimensional vectors which are the vertices of a
triangle. The function returns the circumradius of the triangle, i.e
the radius of the smallest circle that can contain the triangle. In
the degenerate case when the 3 points are collinear it returns
half the distance between the furthest apart points.
u, v being unit 3d vectors return a 3x3 rotation matrix R than aligns u to
v.
In general there are many rotations that will map u to v. If S is any
rotation using v as an axis then R.S will also map u to v since (S.R)u =
S(Ru) = Sv = v. The rotation R returned by vec2vec_rotmat leaves fixed the
perpendicular to the plane spanned by u and v.
Computes n evenly spaced perpendicular directions relative to a given
vector v
Parameters:
varray (3,)
Array containing the three cartesian coordinates of vector v
numint, optional
Number of perpendicular directions to generate
halfbool, optional
If half is True, perpendicular directions are sampled on half of the
unit circumference perpendicular to v, otherwive perpendicular
directions are sampled on the full circumference. Default of half is
False
Returns:
psamplesarray (n, 3)
array of vectors perpendicular to v
Notes
Perpendicular directions are estimated using the following two step
procedure:
the perpendicular directions are first sampled in a unit
circumference parallel to the plane normal to the x-axis.
Samples are then rotated and aligned to the plane normal to vector
v. The rotational matrix for this rotation is constructed as reference
frame basis which axis are the following:
The first axis is vector v
The second axis is defined as the normalized vector given by the
cross product between vector v and the unit vector aligned to the
x-axis
The third axis is defined as the cross product between the
previous computed vector and vector v.
Following this two steps, coordinates of the final perpendicular directions
are given as:
This procedure has a singularity when vector v is aligned to the x-axis. To
solve this singularity, perpendicular directions in procedure’s step 1 are
defined in the plane normal to y-axis and the second axis of the rotated
frame of reference is computed as the normalized vector given by the cross
product between vector v and the unit vector aligned to the y-axis.
Following this, the coordinates of the perpendicular directions are given
as:
left [ -frac{left (v_{x}v_{y}sin(a_{i})+v_{z}cos(a_{i}) right )}
{sqrt{{v_{x}}^{2}+{v_{z}}^{2}}}
; , ;
sin(a_{i}) sqrt{{v_{x}}^{2}+{v_{z}}^{2}}
; , ;
frac{v_{y}v_{z}sin(a_{i})+v_{x}cos(a_{i})}
{sqrt{{v_{x}}^{2}+{v_{z}}^{2}}} right ]
The GradientTable object is immutable. Do NOT assign attributes.
If you have your gradient table in a bval & bvec format, we recommend
using the factory function gradient_table
Creates a GradientTable from a bvals array and a bvecs array
Parameters:
bvalsarray_like (N,)
The b-value, or magnitude, of each gradient direction.
bvecsarray_like (N, 3)
The direction, represented as a unit vector, of each gradient.
b0_thresholdfloat
Gradients with b-value less than or equal to b0_threshold are
considered to not have diffusion weighting. If its value is equal to or
larger than all values in b-vals, then it is assumed that no
thresholding is requested.
atolfloat
Each vector in bvecs must be a unit vectors up to a tolerance of
atol.
btenscan be any of three options
a string specifying the shape of the encoding tensor for all volumes
in data. Options: ‘LTE’, ‘PTE’, ‘STE’, ‘CTE’ corresponding to
linear, planar, spherical, and “cigar-shaped” tensor encoding.
Tensors are rotated so that linear and cigar tensors are aligned
with the corresponding gradient direction and the planar tensor’s
normal is aligned with the corresponding gradient direction.
Magnitude is scaled to match the b-value.
an array of strings of shape (N,), (N, 1), or (1, N) specifying
encoding tensor shape for each volume separately. N corresponds to
the number volumes in data. Options for elements in array: ‘LTE’,
‘PTE’, ‘STE’, ‘CTE’ corresponding to linear, planar, spherical, and
“cigar-shaped” tensor encoding. Tensors are rotated so that linear
and cigar tensors are aligned with the corresponding gradient
direction and the planar tensor’s normal is aligned with the
corresponding gradient direction. Magnitude is scaled to match the
b-value.
an array of shape (N,3,3) specifying the b-tensor of each volume
exactly. N corresponds to the number volumes in data. No rotation or
scaling is performed.
Returns:
gradientsGradientTable
A GradientTable with all the gradient information.
A general function for creating diffusion MR gradients.
It reads, loads and prepares scanner parameters like the b-values and
b-vectors so that they can be useful during the reconstruction process.
Parameters:
qvalsan array of shape (N,),
q-value given in 1/mm
bvecscan be any of two options
an array of shape (N, 3) or (3, N) with the b-vectors.
a path for the file which contains an array like the previous.
big_deltafloat or array of shape (N,)
acquisition pulse separation time in seconds
small_deltafloat
acquisition pulse duration time in seconds
b0_thresholdfloat
All b-values with values less than or equal to bo_threshold are
considered as b0s i.e. without diffusion weighting.
atolfloat
All b-vectors need to be unit vectors up to a tolerance.
Returns:
gradientsGradientTable
A GradientTable with all the gradient information.
Notes
Often b0s (b-values which correspond to images without diffusion
weighting) have 0 values however in some cases the scanner cannot
provide b0s of an exact 0 value and it gives a bit higher values
e.g. 6 or 12. This is the purpose of the b0_threshold in the __init__.
We assume that the minimum number of b-values is 7.
A general function for creating diffusion MR gradients.
It reads, loads and prepares scanner parameters like the b-values and
b-vectors so that they can be useful during the reconstruction process.
Parameters:
gradient_strengthan array of shape (N,),
gradient strength given in T/mm
bvecscan be any of two options
an array of shape (N, 3) or (3, N) with the b-vectors.
a path for the file which contains an array like the previous.
big_deltafloat or array of shape (N,)
acquisition pulse separation time in seconds
small_deltafloat
acquisition pulse duration time in seconds
b0_thresholdfloat
All b-values with values less than or equal to bo_threshold are
considered as b0s i.e. without diffusion weighting.
atolfloat
All b-vectors need to be unit vectors up to a tolerance.
Returns:
gradientsGradientTable
A GradientTable with all the gradient information.
Notes
Often b0s (b-values which correspond to images without diffusion
weighting) have 0 values however in some cases the scanner cannot
provide b0s of an exact 0 value and it gives a bit higher values
e.g. 6 or 12. This is the purpose of the b0_threshold in the __init__.
We assume that the minimum number of b-values is 7.
B-vectors should be unit vectors.
Examples
>>> fromdipy.core.gradientsimport(... gradient_table_from_gradient_strength_bvecs)>>> gradient_strength=.03e-3*np.ones(7)# clinical strength at 30 mT/m>>> big_delta=.03# pulse separation of 30ms>>> small_delta=0.01# pulse duration of 10ms>>> gradient_strength[0]=0>>> sq2=np.sqrt(2)/2>>> bvecs=np.array([[0,0,0],... [1,0,0],... [0,1,0],... [0,0,1],... [sq2,sq2,0],... [sq2,0,sq2],... [0,sq2,sq2]])>>> gt=gradient_table_from_gradient_strength_bvecs(... gradient_strength,bvecs,big_delta,small_delta)
A general function for creating diffusion MR gradients.
It reads, loads and prepares scanner parameters like the b-values and
b-vectors so that they can be useful during the reconstruction process.
Parameters:
bvalscan be any of the four options
an array of shape (N,) or (1, N) or (N, 1) with the b-values.
a path for the file which contains an array like the above (1).
an array of shape (N, 4) or (4, N). Then this parameter is
considered to be a b-table which contains both bvals and bvecs. In
this case the next parameter is skipped.
a path for the file which contains an array like the one at (3).
bvecscan be any of two options
an array of shape (N, 3) or (3, N) with the b-vectors.
a path for the file which contains an array like the previous.
big_deltafloat
acquisition pulse separation time in seconds (default None)
small_deltafloat
acquisition pulse duration time in seconds (default None)
b0_thresholdfloat
All b-values with values less than or equal to bo_threshold are
considered as b0s i.e. without diffusion weighting.
atolfloat
All b-vectors need to be unit vectors up to a tolerance.
btenscan be any of three options
a string specifying the shape of the encoding tensor for all volumes
in data. Options: ‘LTE’, ‘PTE’, ‘STE’, ‘CTE’ corresponding to
linear, planar, spherical, and “cigar-shaped” tensor encoding.
Tensors are rotated so that linear and cigar tensors are aligned
with the corresponding gradient direction and the planar tensor’s
normal is aligned with the corresponding gradient direction.
Magnitude is scaled to match the b-value.
an array of strings of shape (N,), (N, 1), or (1, N) specifying
encoding tensor shape for each volume separately. N corresponds to
the number volumes in data. Options for elements in array: ‘LTE’,
‘PTE’, ‘STE’, ‘CTE’ corresponding to linear, planar, spherical, and
“cigar-shaped” tensor encoding. Tensors are rotated so that linear
and cigar tensors are aligned with the corresponding gradient
direction and the planar tensor’s normal is aligned with the
corresponding gradient direction. Magnitude is scaled to match the
b-value.
an array of shape (N,3,3) specifying the b-tensor of each volume
exactly. N corresponds to the number volumes in data. No rotation or
scaling is performed.
Returns:
gradientsGradientTable
A GradientTable with all the gradient information.
Notes
Often b0s (b-values which correspond to images without diffusion
weighting) have 0 values however in some cases the scanner cannot
provide b0s of an exact 0 value and it gives a bit higher values
e.g. 6 or 12. This is the purpose of the b0_threshold in the __init__.
We assume that the minimum number of b-values is 7.
When correcting for motion, rotation of the diffusion-weighted volumes
might cause systematic bias in rotationally invariant measures, such as FA
and MD, and also cause characteristic biases in tractography, unless the
gradient directions are appropriately reoriented to compensate for this
effect [2].
Parameters:
gtabGradientTable
The nominal gradient table with which the data were acquired.
affineslist or ndarray of shape (4, 4, n) or (3, 3, n)
Each entry in this list or array contain either an affine
transformation (4,4) or a rotation matrix (3, 3).
In both cases, the transformations encode the rotation that was applied
to the image corresponding to one of the non-zero gradient directions
(ordered according to their order in gtab.bvecs[~gtab.b0s_mask])
atol: see gradient_table()
Returns:
gtaba GradientTable class instance with the reoriented directions
The order of magnitude to round the b-values. If not given b-values
will be rounded relative to the order of magnitude
\(bmag = (bmagmax - 1)\), where bmaxmag is the magnitude order of the
larger b-value.
Gives the unique b-values of the data, within a tolerance gap
The b-values must be regrouped in clusters easily separated by a
distance greater than the tolerance gap. If all the b-values of a
cluster fit within the tolerance gap, the highest b-value is kept.
Parameters:
bvalsndarray
Array containing the b-values
tolint
The tolerated gap between the b-values to extract
and the actual b-values.
Returns:
ubvalsndarray
Array containing the unique b-values using the median value
for each cluster
This function gives the unique rounded b-values of the data
Parameters:
bvalsndarray
Array containing the b-values
bmagint
The order of magnitude that the bvalues have to differ to be
considered an unique b-value. B-values are also rounded up to
this order of magnitude. Default: derive this value from the
maximal b-value provided: \(bmag=log_{10}(max(bvals)) - 1\).
rbvalsbool, optional
If True function also returns all individual rounded b-values.
Check if you have enough different b-values in your gradient table
Parameters:
gtabGradientTable class instance.
Gradient table.
n_bvalsint
The number of different b-values you are checking for.
non_zerobool
Whether to check only non-zero bvalues. In this case, we will require
at least n_bvals non-zero b-values (where non-zero is defined
depending on the gtab object’s b0_threshold attribute)
bmagint
The order of magnitude of the b-values used. The function will
normalize the b-values relative \(10^{bmag}\). Default: derive this
value from the maximal b-value provided:
\(bmag=log_{10}(max(bvals)) - 1\).
Returns:
boolWhether there are at least n_bvals different b-values in the
Radial basis function (RBF) interpolation in N dimensions.
Parameters:
y(npoints, ndims) array_like
2-D array of data point coordinates.
d(npoints, …) array_like
N-D array of data values at y. The length of d along the first
axis must be equal to the length of y. Unlike some interpolators, the
interpolation axis cannot be changed.
neighborsint, optional
If specified, the value of the interpolant at each evaluation point
will be computed using only this many nearest data points. All the data
points are used by default.
smoothingfloat or (npoints, ) array_like, optional
Smoothing parameter. The interpolant perfectly fits the data when this
is set to 0. For large values, the interpolant approaches a least
squares fit of a polynomial with the specified degree. Default is 0.
kernelstr, optional
Type of RBF. This should be one of
‘linear’ : -r
‘thin_plate_spline’ : r**2*log(r)
‘cubic’ : r**3
‘quintic’ : -r**5
‘multiquadric’ : -sqrt(1+r**2)
‘inverse_multiquadric’ : 1/sqrt(1+r**2)
‘inverse_quadratic’ : 1/(1+r**2)
‘gaussian’ : exp(-r**2)
Default is ‘thin_plate_spline’.
epsilonfloat, optional
Shape parameter that scales the input to the RBF. If kernel is
‘linear’, ‘thin_plate_spline’, ‘cubic’, or ‘quintic’, this defaults to
1 and can be ignored because it has the same effect as scaling the
smoothing parameter. Otherwise, this must be specified.
degreeint, optional
Degree of the added polynomial. For some RBFs the interpolant may not
be well-posed if the polynomial degree is too small. Those RBFs and
their corresponding minimum degrees are
‘multiquadric’ : 0
‘linear’ : 0
‘thin_plate_spline’ : 1
‘cubic’ : 1
‘quintic’ : 2
The default value is the minimum degree for kernel or 0 if there is
no minimum degree. Set this to -1 for no added polynomial.
Methods
__call__(x)
Evaluate the interpolant at x.
See also
NearestNDInterpolator
LinearNDInterpolator
CloughTocher2DInterpolator
Notes
An RBF is a scalar valued function in N-dimensional space whose value at
\(x\) can be expressed in terms of \(r=||x - c||\), where \(c\)
is the center of the RBF.
An RBF interpolant for the vector of data values \(d\), which are from
locations \(y\), is a linear combination of RBFs centered at \(y\)
plus a polynomial with a specified degree. The RBF interpolant is written
as
\[f(x) = K(x, y) a + P(x) b,\]
where \(K(x, y)\) is a matrix of RBFs with centers at \(y\)
evaluated at the points \(x\), and \(P(x)\) is a matrix of
monomials, which span polynomials with the specified degree, evaluated at
\(x\). The coefficients \(a\) and \(b\) are the solution to the
linear equations
\[(K(y, y) + \lambda I) a + P(y) b = d\]
and
\[P(y)^T a = 0,\]
where \(\lambda\) is a non-negative smoothing parameter that controls
how well we want to fit the data. The data are fit exactly when the
smoothing parameter is 0.
The above system is uniquely solvable if the following requirements are
met:
\(P(y)\) must have full column rank. \(P(y)\) always has full
column rank when degree is -1 or 0. When degree is 1,
\(P(y)\) has full column rank if the data point locations are not
all collinear (N=2), coplanar (N=3), etc.
If kernel is ‘multiquadric’, ‘linear’, ‘thin_plate_spline’,
‘cubic’, or ‘quintic’, then degree must not be lower than the
minimum value listed above.
If smoothing is 0, then each data point location must be distinct.
When using an RBF that is not scale invariant (‘multiquadric’,
‘inverse_multiquadric’, ‘inverse_quadratic’, or ‘gaussian’), an appropriate
shape parameter must be chosen (e.g., through cross validation). Smaller
values for the shape parameter correspond to wider RBFs. The problem can
become ill-conditioned or singular when the shape parameter is too small.
The memory required to solve for the RBF interpolation coefficients
increases quadratically with the number of data points, which can become
impractical when interpolating more than about a thousand data points.
To overcome memory limitations for large interpolation problems, the
neighbors argument can be specified to compute an RBF interpolant for
each evaluation point using only the nearest data points.
Added in version 1.7.0.
References
[1]
Fasshauer, G., 2007. Meshfree Approximation Methods with Matlab.
World Scientific Publishing Co.
If callable, then it must take 2 arguments (self, r). The epsilon
parameter will be available as self.epsilon. Other keyword
arguments passed in will be available as well.
epsilonfloat, optional
Adjustable constant for gaussian or multiquadrics functions
- defaults to approximate average distance between nodes (which is
a good start).
smoothfloat, optional
Values greater than zero increase the smoothness of the
approximation. 0 is for interpolation (default), the function will
always go through the nodal points in this case.
normstr, callable, optional
A function that returns the ‘distance’ between two points, with
inputs as arrays of positions (x, y, z, …), and an output as an
array of distance. E.g., the default: ‘euclidean’, such that the result
is a matrix of the distances from each point in x1 to each point in
x2. For more options, see documentation of
scipy.spatial.distances.cdist.
modestr, optional
Mode of the interpolation, can be ‘1-D’ (default) or ‘N-D’. When it is
‘1-D’ the data d will be considered as 1-D and flattened
internally. When it is ‘N-D’ the data d is assumed to be an array of
shape (n_samples, m), where m is the dimension of the target domain.
Attributes:
Nint
The number of data points (as determined by the input arrays).
dindarray
The 1-D array of data values at each of the data coordinates xi.
xindarray
The 2-D array of data coordinates.
functionstr or callable
The radial basis function. See description under Parameters.
epsilonfloat
Parameter used by gaussian or multiquadrics functions. See Parameters.
smoothfloat
Smoothing parameter. See description under Parameters.
normstr or callable
The distance function. See description under Parameters.
modestr
Mode of the interpolation. See description under Parameters.
Return decorator function function for deprecation warning / error.
The decorated function / method will:
Raise the given warning_class warning when the function / method gets
called, up to (and including) version until (if specified);
Raise the given error_class error when the function / method gets
called, when the package version is greater than version until (if
specified).
Parameters:
messagestr
Message explaining deprecation, giving possible alternatives.
sincestr, optional
Released version at which object was first deprecated.
untilstr, optional
Last released version at which this function will still raise a
deprecation warning. Versions higher than this will raise an
error.
version_comparatorcallable
Callable accepting string as argument, and return 1 if string
represents a higher version than encoded in the version_comparator, 0
if the version is equal, and -1 if the version is lower. For example,
the version_comparator may compare the input version string to the
current package version string.
warn_classclass, optional
Class of warning to generate for deprecation.
error_classclass, optional
Class of error to generate when version_comparator returns 1 for a
given argument of until.
Interpolate data on the sphere, using radial basis functions.
dipy.core.interpolation.interp_rbf is deprecated, Please use dipy.core.interpolation.rbf_interpolation instead
deprecated from version: 1.10.0
Will raise <class ‘dipy.utils.deprecator.ExpiredDeprecationError’> as of version: 1.12.0
Parameters:
data(N,) ndarray
Function values on the unit sphere.
sphere_originSphere
Positions of data values.
sphere_targetSphere
M target positions for which to interpolate.
function{‘multiquadric’, ‘inverse’, ‘gaussian’}
Radial basis function.
epsilonfloat
Radial basis function spread parameter. Defaults to approximate average
distance between nodes.
a good start
smoothfloat
values greater than zero increase the smoothness of the
approximation with 0 as pure interpolation. Default: 0.1
normstr
A string indicating the function that returns the
“distance” between two points.
‘angle’ - The angle between two vectors
‘euclidean_norm’ - The Euclidean distance
Interpolates the 2D image at the given locations. This function is
a wrapper for _interpolate_scalar_2d for testing purposes, it is
equivalent to scipy.ndimage.map_coordinates with
bilinear interpolation
Parameters:
fieldarray, shape (S, R)
the 2D image to be interpolated
locationsarray, shape (n, 2)
(locations[i,0], locations[i,1]), 0<=i<n must contain the row and
column coordinates to interpolate the image at
Returns:
outarray, shape (n,)
out[i], 0<=i<n will be the interpolated scalar at coordinates
locations[i,:], or 0 if locations[i,:] is outside the image
insidearray, (n,)
if locations[i:] is inside the image then inside[i]=1, else
inside[i]=0
Interpolates the 3D image at the given locations. This function is
a wrapper for _interpolate_scalar_3d for testing purposes, it is
equivalent to scipy.ndimage.map_coordinates with
trilinear interpolation
Parameters:
fieldarray, shape (S, R, C)
the 3D image to be interpolated
locationsarray, shape (n, 3)
(locations[i,0], locations[i,1], locations[i,2), 0<=i<n must contain
the coordinates to interpolate the image at
Returns:
outarray, shape (n,)
out[i], 0<=i<n will be the interpolated scalar at coordinates
locations[i,:], or 0 if locations[i,:] is outside the image
insidearray, (n,)
if locations[i,:] is inside the image then inside[i]=1, else
inside[i]=0
Nearest neighbor interpolation of a 2D scalar image
Interpolates the 2D image at the given locations. This function is
a wrapper for _interpolate_scalar_nn_2d for testing purposes, it is
equivalent to scipy.ndimage.map_coordinates with
nearest neighbor interpolation
Parameters:
imagearray, shape (S, R)
the 2D image to be interpolated
locationsarray, shape (n, 2)
(locations[i,0], locations[i,1]), 0<=i<n must contain the row and
column coordinates to interpolate the image at
Returns:
outarray, shape (n,)
out[i], 0<=i<n will be the interpolated scalar at coordinates
locations[i,:], or 0 if locations[i,:] is outside the image
insidearray, (n,)
if locations[i:] is inside the image then inside[i]=1, else
inside[i]=0
Nearest neighbor interpolation of a 3D scalar image
Interpolates the 3D image at the given locations. This function is
a wrapper for _interpolate_scalar_nn_3d for testing purposes, it is
equivalent to scipy.ndimage.map_coordinates with
nearest neighbor interpolation
Parameters:
imagearray, shape (S, R, C)
the 3D image to be interpolated
locationsarray, shape (n, 3)
(locations[i,0], locations[i,1], locations[i,2), 0<=i<n must contain
the coordinates to interpolate the image at
Returns:
outarray, shape (n,)
out[i], 0<=i<n will be the interpolated scalar at coordinates
locations[i,:], or 0 if locations[i,:] is outside the image
insidearray, (n,)
if locations[i,:] is inside the image then inside[i]=1, else
inside[i]=0
Interpolates the 2D vector field at the given locations. This function is
a wrapper for _interpolate_vector_2d for testing purposes, it is
equivalent to using scipy.ndimage.map_coordinates with
bilinear interpolation at each vector component
Parameters:
fieldarray, shape (S, R, 2)
the 2D vector field to be interpolated
locationsarray, shape (n, 2)
(locations[i,0], locations[i,1]), 0<=i<n must contain the row and
column coordinates to interpolate the vector field at
Returns:
outarray, shape (n, 2)
out[i,:], 0<=i<n will be the interpolated vector at coordinates
locations[i,:], or (0,0) if locations[i,:] is outside the field
insidearray, (n,)
if (locations[i,0], locations[i,1]) is inside the vector field
then inside[i]=1, else inside[i]=0
Interpolates the 3D vector field at the given locations. This function is
a wrapper for _interpolate_vector_3d for testing purposes, it is
equivalent to using scipy.ndimage.map_coordinates with
trilinear interpolation at each vector component
Parameters:
fieldarray, shape (S, R, C, 3)
the 3D vector field to be interpolated
locationsarray, shape (n, 3)
(locations[i,0], locations[i,1], locations[i,2), 0<=i<n must contain
the coordinates to interpolate the vector field at
Returns:
outarray, shape (n, 3)
out[i,:], 0<=i<n will be the interpolated vector at coordinates
locations[i,:], or (0,0,0) if locations[i,:] is outside the field
insidearray, (n,)
if locations[i,:] is inside the vector field then inside[i]=1, else
inside[i]=0
Has similar behavior to map_coordinates from scipy.ndimage
Parameters:
dataarray, float64 shape (X, Y, Z)
pointsarray, float64 shape(N, 3)
data_stridesarray npy_intp shape (3,)
Strides sequence for data array
len_pointscnp.npy_intp
Number of points to interpolate
resultarray, float64 shape(N)
The output array. This array should be initialized before you call
this function. On exit it will contain the interpolated values from
data at points given by points.
Radial basis function spread parameter.
Defaults to 1 when function is ‘linear’, ‘thin_plate_spline’, ‘cubic’, or ‘quintic’.
Otherwise, epsilon must be specified.
smoothingfloat, optional
Smoothing parameter. When smoothing is 0, the interpolation is exact.
As smoothing increases, the interpolation approaches a least-squares fit of data
using the supplied radial basis function. Default: 0.
Returns:
v(…, M) ndarray
Interpolated values of the spherical function at M positions specified by sphere_target.
Interpolates vector from 4D data at 3D point given by index
Interpolates a vector of length T from a 4D volume of shape (I, J, K, T),
given point (x, y, z) where (x, y, z) are the coordinates of the point in
real units (not yet adjusted for voxel size).
Given the shape of an array, an ndindex instance iterates over
the N-dimensional index of the array. At each iteration a tuple
of indices is returned; the last dimension is iterated over first.
A Mixin class to add a .reset() method to users of OneTimeProperty.
By default, auto attributes once computed, become static. If they happen
to depend on other parts of an object and those parts change, their values
may now be invalid.
This class offers a .reset() method that users can call explicitly when
they know the state of their objects may have changed and they want to
ensure that all their special attributes should be invalidated. Once
reset() is called, all their auto attributes are reset to their
OneTimeProperty descriptors, and their accessor functions will be triggered
again.
Warning
If a class has a set of attributes that are OneTimeProperty, but that
can be initialized from any one of them, do NOT use this mixin! For
instance, UniformTimeSeries can be initialized with only sampling_rate
and t0, sampling_interval and time are auto-computed. But if you were
to reset() a UniformTimeSeries, it would lose all 4, and there would be
then no way to break the circular dependency chains.
If this becomes a problem in practice (for our analyzer objects it
isn’t, as they don’t have the above pattern), we can extend reset() to
check for a _no_reset set of names in the instance which are meant to be
kept protected. But for now this is NOT done, so caveat emptor.
The method that will be called the first time to compute a value.
Afterwards, the method’s name will be a standard attribute holding the
value of this computation.
Provide a sklearn-like uniform interface to algorithms that solve problems
of the form: \(y = Ax\) for \(x\)
Sub-classes of SKLearnLinearSolver should provide a ‘fit’ method that have
the following signature: SKLearnLinearSolver.fit(X, y), which would set
an attribute SKLearnLinearSolver.coef_, with the shape (X.shape[1],),
such that an estimate of y can be calculated as:
y_hat = np.dot(X, SKLearnLinearSolver.coef_.T)
Solve a CVXPY problem instance for a given design matrix and a given set
of observations, and return the optimum.
Parameters:
design_matrixarray (n, m)
Design matrix.
measurementsarray (n)
Measurements.
checkboolean, optional
If True check whether the unconstrained optimization solution
already satisfies the constraints, before running the constrained
optimization. This adds overhead, but can avoid unnecessary
constrained optimization calls.
You can use it in all different ways developed in pstats
for example
print_stats(10) will give you the 10 slowest calls
or
print_stats(‘function_name’)
will give you the stats for all the calls with name ‘function_name’
Algorithm AS 183 Appl. Statist. (1982) vol.31, no.2.
Returns a pseudo-random number rectangularly distributed
between 0 and 1. The cycle length is 6.95E+12 (See page 123
of Applied Statistics (1984) vol.33), not as claimed in the
original article.
ix, iy and iz should be set to integer values between 1 and
30000 before the first entry.
Integer arithmetic up to 5212632 is required.
Parameters:
ix: int
First seed value. Should not be null. (default 100001)
iy: int
Second seed value. Should not be null. (default 200002)
iz: int
Third seed value. Should not be null. (default 300003)
Returns:
r_numberfloat
pseudo-random number uniformly distributed between [0-1]
A HemiSphere is similar to a Sphere but it takes antipodal symmetry into
account. Antipodal symmetry means that point v on a HemiSphere is the same
as the point -v. Duplicate points are discarded when constructing a
HemiSphere (including antipodal duplicates). edges and faces are
remapped to the remaining points as closely as possible.
The HemiSphere can be constructed using one of three conventions:
Places charges on a sphere and simulates the repulsive forces felt by each
one. Allows the charges to move for some number of iterations and returns
their final location as well as the total potential of the system at each
step.
Parameters:
hemiHemiSphere
Points on a unit sphere.
itersint
Number of iterations to run.
constfloat
Using a smaller const could provide a more accurate result, but will
need more iterations to converge.
Returns:
hemiHemiSphere
Distributed points on a unit sphere.
potentialndarray
The electrostatic potential at each iteration. This can be useful to
check if the repulsion converged to a minimum.
Notes
This function is meant to be used with diffusion imaging so antipodal
symmetry is assumed. Therefore, each charge must not only be unique, but if
there is a charge at +x, there cannot be a charge at -x. These are treated
as the same location and because the distance between the two charges will
be zero, the result will be unstable.
If \(f\) = number of faces, \(e\) = number_of_edges and \(v\) = number of
vertices, the Euler formula says \(f-e+v = 2\) for a mesh on a sphere. More
generally, whether \(f -e + v == \chi\) where \(\chi\) is the Euler
characteristic of the mesh.
Open chain (track) has \(\chi=1\)
Closed chain (loop) has \(\chi=0\)
Disk has \(\chi=1\)
Sphere has \(\chi=2\)
HemiSphere has \(\chi=1\)
Parameters:
sphereSphere
A Sphere instance with vertices, edges and faces attributes.
chiint, optional
The Euler characteristic of the mesh to be checked
Returns:
checkbool
True if the mesh has Euler characteristic \(\chi\)
Random unit vectors from a uniform distribution on the sphere.
Parameters:
nint
Number of random vectors
coords{‘xyz’, ‘radians’, ‘degrees’}
‘xyz’ for cartesian form
‘radians’ for spherical form in rads
‘degrees’ for spherical form in degrees
Returns:
Xarray, shape (n,3) if coords=’xyz’ or shape (n,2) otherwise
Uniformly distributed vectors on the unit sphere.
Notes
The uniform distribution on the sphere, parameterized by spherical
coordinates \((\theta, \phi)\), should verify \(\phi\sim U[0,2\pi]\), while
\(z=\cos(\theta)\sim U[-1,1]\).
Creates a unit sphere by subdividing a unit octahedron.
Starts with a unit octahedron and subdivides the faces, projecting the
resulting points onto the surface of a unit sphere.
Parameters:
recursion_levelint
Level of subdivision, recursion_level=1 will return an octahedron,
anything bigger will return a more subdivided sphere. The sphere will
have \(4^recursion_level+2\) vertices.
Creates a unit sphere by subdividing a unit octahedron, returns half
the sphere.
Parameters:
recursion_levelint
Level of subdivision, recursion_level=1 will return an octahedron,
anything bigger will return a more subdivided sphere. The sphere will
have \((4^recursion_level+2)/2\) vertices.