core
core.geometry
core.gradients
core.graph
core.histeq
core.ndindex
core.onetime
core.optimize
core.profile
core.rng
core.sphere
core.sphere_stats
core.subdivide_octahedron
core.wavelet
GradientTable
HemiSphere
Graph
OneTimeProperty
ResetMixin
LooseVersion
NonNegativeLeastSquares
Optimizer
SKLearnLinearSolver
Profiler
HemiSphere
Sphere
xrange
permutations
HemiSphere
core
Core objects
test |
Run tests for module using nose. |
core.geometry
Utility functions for algebra etc
cart2sphere (x, y, z) |
Return angles for Cartesian 3D coordinates x, y, and z |
cart_distance (pts1, pts2) |
Cartesian distance between pts1 and pts2 |
circumradius (a, b, c) |
a, b and c are 3-dimensional vectors which are the vertices of a triangle. |
compose_matrix ([scale, shear, angles, …]) |
Return 4x4 transformation matrix from sequence of transformations. |
compose_transformations (*mats) |
Compose multiple 4x4 affine transformations in one 4x4 matrix |
decompose_matrix (matrix) |
Return sequence of transformations from transformation matrix. |
dist_to_corner (affine) |
Calculate the maximal distance from the center to a corner of a voxel, given an affine |
euler_matrix (ai, aj, ak[, axes]) |
Return homogeneous rotation matrix from Euler angles and axis sequence. |
lambert_equal_area_projection_cart (x, y, z) |
Lambert Equal Area Projection from cartesian vector to plane |
lambert_equal_area_projection_polar (theta, phi) |
Lambert Equal Area Projection from polar sphere to plane |
nearest_pos_semi_def (B) |
Least squares positive semi-definite tensor estimation |
normalized_vector (vec[, axis]) |
Return vector divided by its Euclidean (L2) norm |
perpendicular_directions (v[, num, half]) |
Computes n evenly spaced perpendicular directions relative to a given vector v |
rodrigues_axis_rotation (r, theta) |
Rodrigues formula |
sph2latlon (theta, phi) |
Convert spherical coordinates to latitude and longitude. |
sphere2cart (r, theta, phi) |
Spherical to Cartesian coordinates |
sphere_distance (pts1, pts2[, radius, …]) |
Distance across sphere surface between pts1 and pts2 |
vec2vec_rotmat (u, v) |
rotation matrix from 2 unit vectors |
vector_cosine (vecs1, vecs2) |
Cosine of angle between two (sets of) vectors |
vector_norm (vec[, axis, keepdims]) |
Return vector Euclidean (L2) norm |
core.gradients
GradientTable (gradients[, big_delta, …]) |
Diffusion gradient information |
HemiSphere ([x, y, z, theta, phi, xyz, …]) |
Points on the unit sphere. |
auto_attr (func) |
Decorator to create OneTimeProperty attributes. |
check_multi_b (gtab, n_bvals[, non_zero, bmag]) |
Check if you have enough different b-values in your gradient table |
disperse_charges (hemi, iters[, const]) |
Models electrostatic repulsion on the unit sphere |
generate_bvecs (N[, iters]) |
Generates N bvectors. |
gradient_table (bvals[, bvecs, big_delta, …]) |
A general function for creating diffusion MR gradients. |
gradient_table_from_bvals_bvecs (bvals, bvecs) |
Creates a GradientTable from a bvals array and a bvecs array |
gradient_table_from_gradient_strength_bvecs (…) |
A general function for creating diffusion MR gradients. |
gradient_table_from_qvals_bvecs (qvals, …) |
A general function for creating diffusion MR gradients. |
inv (a[, overwrite_a, check_finite]) |
Compute the inverse of a matrix. |
polar (a[, side]) |
Compute the polar decomposition. |
reorient_bvecs (gtab, affines) |
Reorient the directions in a GradientTable. |
vector_norm (vec[, axis, keepdims]) |
Return vector Euclidean (L2) norm |
warn |
Issue a warning, or maybe ignore it or raise an exception. |
core.histeq
histeq (arr[, num_bins]) |
Performs an histogram equalization on arr . |
core.ndindex
as_strided (x[, shape, strides, subok, writeable]) |
Create a view into the array with the given shape and strides. |
ndindex (shape) |
An N-dimensional iterator object to index arrays. |
core.onetime
Descriptor support for NIPY.
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.
[1] How-To Guide for Descriptors, Raymond Hettinger. http://users.rcn.com/python/download/Descriptor.htm
[2] Python data model, http://docs.python.org/reference/datamodel.html
OneTimeProperty (func) |
A descriptor to make special properties that become normal attributes. |
ResetMixin |
A Mixin class to add a .reset() method to users of OneTimeProperty. |
auto_attr (func) |
Decorator to create OneTimeProperty attributes. |
setattr_on_read (func) |
Decorator to create OneTimeProperty attributes. |
core.optimize
A unified interface for performing and debugging optimization problems.
Only L-BFGS-B and Powell is supported in this class for versions of Scipy < 0.12. All optimizers are available for scipy >= 0.12.
LooseVersion ([vstring]) |
Version numbering for anarchists and software realists. | ||
NonNegativeLeastSquares (*args, **kwargs) |
A sklearn-like interface to scipy.optimize.nnls | ||
Optimizer (fun, x0[, args, method, jac, …]) |
|
||
SKLearnLinearSolver (*args, **kwargs) |
Provide a sklearn-like uniform interface to algorithms that solve problems of the form: \(y = Ax\) for \(x\) | ||
minimize (fun, x0[, args, method, jac, hess, …]) |
Minimization of scalar function of one or more variables. | ||
sparse_nnls (y, X[, momentum, step_size, …]) |
Solve y=Xh for h, using gradient descent, with X a sparse matrix | ||
spdot (A, B) |
The same as np.dot(A, B), except it works even if A or B or both are sparse matrices. | ||
with_metaclass (meta, *bases) |
Create a base class with a metaclass. |
core.profile
Class for profiling cython code
Profiler ([call]) |
Profile python/cython files or functions |
optional_package (name[, trip_msg]) |
Return package-like thing and module setup for package name |
core.rng
Random number generation utilities
LEcuyer () |
Generate uniformly distributed random numbers using the 32-bit generator from figure 3 of: L’Ecuyer, P. |
WichmannHill1982 () |
Algorithm AS 183 Appl. |
WichmannHill2006 () |
B.A. |
architecture ([executable, bits, linkage]) |
Queries the given executable (defaults to the Python interpreter binary) for various architecture information. |
floor (x) |
Return the floor of x as an Integral. |
core.sphere
HemiSphere ([x, y, z, theta, phi, xyz, …]) |
Points on the unit sphere. |
Sphere ([x, y, z, theta, phi, xyz, faces, edges]) |
Points on the unit sphere. |
xrange |
alias of builtins.range |
auto_attr (func) |
Decorator to create OneTimeProperty attributes. |
cart2sphere (x, y, z) |
Return angles for Cartesian 3D coordinates x, y, and z |
disperse_charges (hemi, iters[, const]) |
Models electrostatic repulsion on the unit sphere |
euler_characteristic_check (sphere[, chi]) |
Checks the euler characteristic of a sphere |
faces_from_sphere_vertices (vertices) |
Triangulate a set of vertices on the sphere. |
interp_rbf (data, sphere_origin, sphere_target) |
Interpolate data on the sphere, using radial basis functions. |
remove_similar_vertices |
Remove vertices that are less than theta degrees from any other |
sphere2cart (r, theta, phi) |
Spherical to Cartesian coordinates |
unique_edges (faces[, return_mapping]) |
Extract all unique edges from given triangular faces. |
unique_sets (sets[, return_inverse]) |
Remove duplicate sets. |
vector_norm (vec[, axis, keepdims]) |
Return vector Euclidean (L2) norm |
core.sphere_stats
Statistics on spheres
permutations |
permutations(iterable[, r]) –> permutations object |
angular_similarity (S, T) |
Computes the cosine distance of the best match between points of two sets of vectors S and T |
compare_orientation_sets (S, T) |
Computes the mean cosine distance of the best match between points of two sets of vectors S and T (angular similarity) |
eigenstats (points[, alpha]) |
Principal direction and confidence ellipse |
random_uniform_on_sphere ([n, coords]) |
Random unit vectors from a uniform distribution on the sphere. |
core.subdivide_octahedron
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.
HemiSphere ([x, y, z, theta, phi, xyz, …]) |
Points on the unit sphere. |
create_unit_hemisphere ([recursion_level]) |
Creates a unit sphere by subdividing a unit octahedron, returns half the sphere. |
create_unit_sphere ([recursion_level]) |
Creates a unit sphere by subdividing a unit octahedron. |
core.wavelet
afb3D (x, af1[, af2, af3]) |
3D Analysis Filter Bank |
afb3D_A (x, af, d) |
3D Analysis Filter Bank |
cshift3D (x, m, d) |
3D Circular Shift |
dwt3D (x, J, af) |
3-D Discrete Wavelet Transform |
idwt3D (w, J, sf) |
Inverse 3-D Discrete Wavelet Transform |
permutationinverse (perm) |
Function generating inverse of the permutation |
sfb3D (lo, hi, sf1[, sf2, sf3]) |
3D Synthesis Filter Bank |
sfb3D_A (lo, hi, sf, d) |
3D Synthesis Filter Bank |
dipy.core.
test
(label='fast', verbose=1, extra_argv=None, doctests=False, coverage=False, raise_warnings=None, timer=False)Run tests for module using nose.
Parameters: |
|
---|---|
Returns: |
|
Notes
Each NumPy module exposes test in its namespace to run all tests for it. For example, to run all tests for numpy.lib:
>>> np.lib.test()
Examples
>>> result = np.lib.test()
Running unit tests for numpy.lib
...
Ran 976 tests in 3.933s
OK
>>> result.errors
[]
>>> result.knownfail
[]
dipy.core.geometry.
cart2sphere
(x, y, z)Return angles for Cartesian 3D coordinates x, y, and z
See doc for sphere2cart
for angle conventions and derivation
of the formulae.
\(0\le\theta\mathrm{(theta)}\le\pi\) and \(-\pi\le\phi\mathrm{(phi)}\le\pi\)
Parameters: |
|
---|---|
Returns: |
|
dipy.core.geometry.
cart_distance
(pts1, pts2)Cartesian distance between pts1 and pts2
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: |
|
---|---|
Returns: |
|
See also
sphere_distance
Examples
>>> cart_distance([0,0,0], [0,0,3])
3.0
dipy.core.geometry.
circumradius
(a, b, c)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.
Parameters: |
|
---|---|
Returns: |
|
dipy.core.geometry.
compose_matrix
(scale=None, shear=None, angles=None, translate=None, perspective=None)Return 4x4 transformation matrix from sequence of transformations.
Code modified from the work of Christoph Gohlke link provided here http://www.lfd.uci.edu/~gohlke/code/transformations.py.html
This is the inverse of the decompose_matrix
function.
Parameters: |
|
---|---|
Returns: |
|
Examples
>>> import math
>>> import numpy as np
>>> import dipy.core.geometry as gm
>>> scale = np.random.random(3) - 0.5
>>> shear = np.random.random(3) - 0.5
>>> angles = (np.random.random(3) - 0.5) * (2*math.pi)
>>> trans = np.random.random(3) - 0.5
>>> persp = np.random.random(4) - 0.5
>>> M0 = gm.compose_matrix(scale, shear, angles, trans, persp)
dipy.core.geometry.
decompose_matrix
(matrix)Return sequence of transformations from transformation matrix.
Code modified from the excellent work of Christoph Gohlke link provided here: http://www.lfd.uci.edu/~gohlke/code/transformations.py.html
Parameters: |
|
---|---|
Returns: |
|
Raises: |
|
Examples
>>> import numpy as np
>>> T0=np.diag([2,1,1,1])
>>> scale, shear, angles, trans, persp = decompose_matrix(T0)
dipy.core.geometry.
dist_to_corner
(affine)Calculate the maximal distance from the center to a corner of a voxel, given an affine
Parameters: |
|
---|---|
Returns: |
|
dipy.core.geometry.
euler_matrix
(ai, aj, ak, axes='sxyz')Return homogeneous rotation matrix from Euler angles and axis sequence.
Code modified from the work of Christoph Gohlke link provided here http://www.lfd.uci.edu/~gohlke/code/transformations.py.html
Parameters: |
|
---|---|
Returns: |
|
Examples
>>> import numpy
>>> R = euler_matrix(1, 2, 3, 'syxz')
>>> numpy.allclose(numpy.sum(R[0]), -1.34786452)
True
>>> R = euler_matrix(1, 2, 3, (0, 1, 0, 1))
>>> numpy.allclose(numpy.sum(R[0]), -0.383436184)
True
>>> ai, aj, ak = (4.0*math.pi) * (numpy.random.random(3) - 0.5)
>>> for axes in _AXES2TUPLE.keys():
... _ = euler_matrix(ai, aj, ak, axes)
>>> for axes in _TUPLE2AXES.keys():
... _ = euler_matrix(ai, aj, ak, axes)
dipy.core.geometry.
lambert_equal_area_projection_cart
(x, y, z)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: |
|
---|---|
Returns: |
|
dipy.core.geometry.
lambert_equal_area_projection_polar
(theta, phi)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).
See doc for sphere2cart
for angle conventions
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: |
|
---|---|
Returns: |
|
dipy.core.geometry.
nearest_pos_semi_def
(B)Least squares positive semi-definite tensor estimation
Parameters: |
|
---|---|
Returns: |
|
References
[1] | Niethammer M, San Jose Estepar R, Bouix S, Shenton M, Westin CF. On diffusion tensor estimation. Conf Proc IEEE Eng Med Biol Soc. 2006;1:2622-5. PubMed PMID: 17946125; PubMed Central PMCID: PMC2791793. |
Examples
>>> B = np.diag([1, 1, -1])
>>> nearest_pos_semi_def(B)
array([[ 0.75, 0. , 0. ],
[ 0. , 0.75, 0. ],
[ 0. , 0. , 0. ]])
dipy.core.geometry.
normalized_vector
(vec, axis=-1)Return vector divided by its Euclidean (L2) norm
See unit vector and Euclidean norm
Parameters: |
|
---|---|
Returns: |
|
Examples
>>> vec = [1, 2, 3]
>>> l2n = np.sqrt(np.dot(vec, vec))
>>> nvec = normalized_vector(vec)
>>> np.allclose(np.array(vec) / l2n, nvec)
True
>>> vec = np.array([[1, 2, 3]])
>>> vec.shape == (1, 3)
True
>>> normalized_vector(vec).shape == (1, 3)
True
dipy.core.geometry.
perpendicular_directions
(v, num=30, half=False)Computes n evenly spaced perpendicular directions relative to a given vector v
Parameters: |
|
---|---|
Returns: |
|
Notes
Perpendicular directions are estimated using the following two step procedure:
1) the perpendicular directions are first sampled in a unit circumference parallel to the plane normal to the x-axis.
2) 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 ]
For more details on this calculation, see ` here <http://gsoc2015dipydki.blogspot.it/2015/07/rnh-post-8-computing-perpendicular.html>`_.
dipy.core.geometry.
rodrigues_axis_rotation
(r, theta)Rodrigues formula
Rotation matrix for rotation around axis r for angle theta.
The rotation matrix is given by the Rodrigues formula:
R = Id + sin(theta)*Sn + (1-cos(theta))*Sn^2
with:
0 -nz ny
Sn = nz 0 -nx
-ny nx 0
where n = r / ||r||
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)/tetha Sr + (1-cos(theta))/teta2 Sr^2
leading to:
R = I + (1-theta2/6)*Sr + (1/2-theta2/24)*Sr^2
Parameters: |
|
---|---|
Returns: |
|
Examples
>>> import numpy as np
>>> from dipy.core.geometry import rodrigues_axis_rotation
>>> v=np.array([0,0,1])
>>> u=np.array([1,0,0])
>>> R=rodrigues_axis_rotation(v,40)
>>> ur=np.dot(R,u)
>>> np.round(np.rad2deg(np.arccos(np.dot(ur,u))))
40.0
dipy.core.geometry.
sphere2cart
(r, theta, phi)Spherical to Cartesian coordinates
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’
Parameters: |
|
---|---|
Returns: |
|
Notes
See these pages:
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.
dipy.core.geometry.
sphere_distance
(pts1, pts2, radius=None, check_radius=True)Distance across sphere surface between pts1 and pts2
Parameters: |
|
---|---|
Returns: |
|
See also
cart_distance
vector_cosine
Examples
>>> print('%.4f' % sphere_distance([0,1],[1,0]))
1.5708
>>> print('%.4f' % sphere_distance([0,3],[3,0]))
4.7124
dipy.core.geometry.
vec2vec_rotmat
(u, v)rotation matrix from 2 unit vectors
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.
The transpose of R will align v to u.
Parameters: |
|
---|---|
Returns: |
|
Examples
>>> import numpy as np
>>> from dipy.core.geometry import vec2vec_rotmat
>>> u=np.array([1,0,0])
>>> v=np.array([0,1,0])
>>> R=vec2vec_rotmat(u,v)
>>> np.dot(R,u)
array([ 0., 1., 0.])
>>> np.dot(R.T,v)
array([ 1., 0., 0.])
dipy.core.geometry.
vector_cosine
(vecs1, vecs2)Cosine of angle between two (sets of) vectors
The cosine of the angle between two vectors v1
and v2
is
given by the inner product of v1
and v2
divided by the
product of the vector lengths:
v_cos = np.inner(v1, v2) / (np.sqrt(np.sum(v1**2)) *
np.sqrt(np.sum(v2**2)))
Parameters: |
|
---|---|
Returns: |
|
Notes
The vector cosine will be the same as the correlation only if all the input vectors have zero mean.
dipy.core.geometry.
vector_norm
(vec, axis=-1, keepdims=False)Return vector Euclidean (L2) norm
See unit vector and Euclidean norm
Parameters: |
|
---|---|
Returns: |
|
Examples
>>> import numpy as np
>>> vec = [[8, 15, 0], [0, 36, 77]]
>>> vector_norm(vec)
array([ 17., 85.])
>>> vector_norm(vec, keepdims=True)
array([[ 17.],
[ 85.]])
>>> vector_norm(vec, axis=0)
array([ 8., 39., 77.])
GradientTable
dipy.core.gradients.
GradientTable
(gradients, big_delta=None, small_delta=None, b0_threshold=50)Bases: object
Diffusion gradient information
Parameters: |
|
---|
See also
Notes
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
Attributes: |
|
---|
Methods
b0s_mask | |
bvals | |
bvecs | |
gradient_strength | |
qvals | |
tau |
HemiSphere
dipy.core.gradients.
HemiSphere
(x=None, y=None, z=None, theta=None, phi=None, xyz=None, faces=None, edges=None, tol=1e-05)Bases: dipy.core.sphere.Sphere
Points on the unit sphere.
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:
HemiSphere(x, y, z)
HemiSphere(xyz=xyz)
HemiSphere(theta=theta, phi=phi)
Parameters: |
|
---|
See also
Sphere
Attributes: |
|
---|
Methods
find_closest (xyz) |
Find the index of the vertex in the Sphere closest to the input vector, taking into account antipodal symmetry |
from_sphere (sphere[, tol]) |
Create instance from a Sphere |
mirror () |
Create a full Sphere from a HemiSphere |
subdivide ([n]) |
Create a more subdivided HemiSphere |
edges | |
faces | |
vertices |
__init__
(x=None, y=None, z=None, theta=None, phi=None, xyz=None, faces=None, edges=None, tol=1e-05)Create a HemiSphere from points
dipy.core.gradients.
auto_attr
(func)Decorator to create OneTimeProperty attributes.
Parameters: |
|
---|
Examples
>>> class MagicProp(object):
... @auto_attr
... def a(self):
... return 99
...
>>> x = MagicProp()
>>> 'a' in x.__dict__
False
>>> x.a
99
>>> 'a' in x.__dict__
True
dipy.core.gradients.
check_multi_b
(gtab, n_bvals, non_zero=True, bmag=None)Check if you have enough different b-values in your gradient table
Parameters: |
|
---|---|
Returns: |
|
dipy.core.gradients.
disperse_charges
(hemi, iters, const=0.2)Models electrostatic repulsion on the unit sphere
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: |
|
---|---|
Returns: |
|
dipy.core.gradients.
generate_bvecs
(N, iters=5000)Generates N bvectors.
Uses dipy.core.sphere.disperse_charges to model electrostatic repulsion on a unit sphere.
Parameters: |
|
---|---|
Returns: |
|
dipy.core.gradients.
gradient_table
(bvals, bvecs=None, big_delta=None, small_delta=None, b0_threshold=50, atol=0.01)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: |
|
---|---|
Returns: |
|
Notes
Examples
>>> from dipy.core.gradients import gradient_table
>>> bvals = 1500 * np.ones(7)
>>> bvals[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(bvals, bvecs)
>>> gt.bvecs.shape == bvecs.shape
True
>>> gt = gradient_table(bvals, bvecs.T)
>>> gt.bvecs.shape == bvecs.T.shape
False
dipy.core.gradients.
gradient_table_from_bvals_bvecs
(bvals, bvecs, b0_threshold=50, atol=0.01, **kwargs)Creates a GradientTable from a bvals array and a bvecs array
Parameters: |
|
---|---|
Returns: |
|
Other Parameters: | |
|
See also
dipy.core.gradients.
gradient_table_from_gradient_strength_bvecs
(gradient_strength, bvecs, big_delta, small_delta, b0_threshold=50, atol=0.01)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: |
|
---|---|
Returns: |
|
Notes
Examples
>>> from dipy.core.gradients import (
... 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)
dipy.core.gradients.
gradient_table_from_qvals_bvecs
(qvals, bvecs, big_delta, small_delta, b0_threshold=50, atol=0.01)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: |
|
---|---|
Returns: |
|
Notes
Examples
>>> from dipy.core.gradients import gradient_table_from_qvals_bvecs
>>> qvals = 30. * np.ones(7)
>>> big_delta = .03 # pulse separation of 30ms
>>> small_delta = 0.01 # pulse duration of 10ms
>>> qvals[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_qvals_bvecs(qvals, bvecs,
... big_delta, small_delta)
dipy.core.gradients.
inv
(a, overwrite_a=False, check_finite=True)Compute the inverse of a matrix.
Parameters: |
|
---|---|
Returns: |
|
Raises: |
|
Examples
>>> from scipy import linalg
>>> a = np.array([[1., 2.], [3., 4.]])
>>> linalg.inv(a)
array([[-2. , 1. ],
[ 1.5, -0.5]])
>>> np.dot(a, linalg.inv(a))
array([[ 1., 0.],
[ 0., 1.]])
dipy.core.gradients.
polar
(a, side='right')Compute the polar decomposition.
Returns the factors of the polar decomposition [1] u and p such
that a = up
(if side is “right”) or a = pu
(if side is
“left”), where p is positive semidefinite. Depending on the shape
of a, either the rows or columns of u are orthonormal. When a
is a square array, u is a square unitary array. When a is not
square, the “canonical polar decomposition” [2] is computed.
Parameters: |
|
---|---|
Returns: |
|
References
[1] | (1, 2) R. A. Horn and C. R. Johnson, “Matrix Analysis”, Cambridge University Press, 1985. |
[2] | (1, 2) N. J. Higham, “Functions of Matrices: Theory and Computation”, SIAM, 2008. |
Examples
>>> from scipy.linalg import polar
>>> a = np.array([[1, -1], [2, 4]])
>>> u, p = polar(a)
>>> u
array([[ 0.85749293, -0.51449576],
[ 0.51449576, 0.85749293]])
>>> p
array([[ 1.88648444, 1.2004901 ],
[ 1.2004901 , 3.94446746]])
A non-square example, with m < n:
>>> b = np.array([[0.5, 1, 2], [1.5, 3, 4]])
>>> u, p = polar(b)
>>> u
array([[-0.21196618, -0.42393237, 0.88054056],
[ 0.39378971, 0.78757942, 0.4739708 ]])
>>> p
array([[ 0.48470147, 0.96940295, 1.15122648],
[ 0.96940295, 1.9388059 , 2.30245295],
[ 1.15122648, 2.30245295, 3.65696431]])
>>> u.dot(p) # Verify the decomposition.
array([[ 0.5, 1. , 2. ],
[ 1.5, 3. , 4. ]])
>>> u.dot(u.T) # The rows of u are orthonormal.
array([[ 1.00000000e+00, -2.07353665e-17],
[ -2.07353665e-17, 1.00000000e+00]])
Another non-square example, with m > n:
>>> c = b.T
>>> u, p = polar(c)
>>> u
array([[-0.21196618, 0.39378971],
[-0.42393237, 0.78757942],
[ 0.88054056, 0.4739708 ]])
>>> p
array([[ 1.23116567, 1.93241587],
[ 1.93241587, 4.84930602]])
>>> u.dot(p) # Verify the decomposition.
array([[ 0.5, 1.5],
[ 1. , 3. ],
[ 2. , 4. ]])
>>> u.T.dot(u) # The columns of u are orthonormal.
array([[ 1.00000000e+00, -1.26363763e-16],
[ -1.26363763e-16, 1.00000000e+00]])
dipy.core.gradients.
reorient_bvecs
(gtab, affines)Reorient the directions in a GradientTable.
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 [Leemans2009].
Parameters: |
|
---|---|
Returns: |
|
References
[Leemans2009] | (1, 2) The B-Matrix Must Be Rotated When Correcting for Subject Motion in DTI Data. Leemans, A. and Jones, D.K. (2009). MRM, 61: 1336-1349 |
dipy.core.gradients.
vector_norm
(vec, axis=-1, keepdims=False)Return vector Euclidean (L2) norm
See unit vector and Euclidean norm
Parameters: |
|
---|---|
Returns: |
|
Examples
>>> import numpy as np
>>> vec = [[8, 15, 0], [0, 36, 77]]
>>> vector_norm(vec)
array([ 17., 85.])
>>> vector_norm(vec, keepdims=True)
array([[ 17.],
[ 85.]])
>>> vector_norm(vec, axis=0)
array([ 8., 39., 77.])
Graph
dipy.core.graph.
Graph
Bases: object
A simple graph class
Methods
add_edge | |
add_node | |
all_paths | |
children | |
del_node | |
del_node_and_edges | |
down | |
down_short | |
parents | |
shortest_path | |
up | |
up_short |
__init__
()A graph class with nodes and edges :-)
This class allows us to:
Examples
>>> from dipy.core.graph import Graph
>>> g=Graph()
>>> g.add_node('a',5)
>>> g.add_node('b',6)
>>> g.add_node('c',10)
>>> g.add_node('d',11)
>>> g.add_edge('a','b')
>>> g.add_edge('b','c')
>>> g.add_edge('c','d')
>>> g.add_edge('b','d')
>>> g.up_short('d')
['d', 'b', 'a']
dipy.core.histeq.
histeq
(arr, num_bins=256)Performs an histogram equalization on arr
.
This was taken from:
http://www.janeriksolem.net/2009/06/histogram-equalization-with-python-and.html
Parameters: |
|
---|---|
Returns: |
|
dipy.core.ndindex.
as_strided
(x, shape=None, strides=None, subok=False, writeable=True)Create a view into the array with the given shape and strides.
Warning
This function has to be used with extreme care, see notes.
Parameters: |
|
---|---|
Returns: |
|
See also
broadcast_to
reshape
Notes
as_strided
creates a view into the array given the exact strides
and shape. This means it manipulates the internal data structure of
ndarray and, if done incorrectly, the array elements can point to
invalid memory and can corrupt results or crash your program.
It is advisable to always use the original x.strides
when
calculating new strides to avoid reliance on a contiguous memory
layout.
Furthermore, arrays created with this function often contain self
overlapping memory, so that two elements are identical.
Vectorized write operations on such arrays will typically be
unpredictable. They may even give different results for small, large,
or transposed arrays.
Since writing to these arrays has to be tested and done with great
care, you may want to use writeable=False
to avoid accidental write
operations.
For these reasons it is advisable to avoid as_strided
when
possible.
dipy.core.ndindex.
ndindex
(shape)An N-dimensional iterator object to index arrays.
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.
Parameters: |
|
---|
Examples
>>> from dipy.core.ndindex import ndindex
>>> shape = (3, 2, 1)
>>> for index in ndindex(shape):
... print(index)
(0, 0, 0)
(0, 1, 0)
(1, 0, 0)
(1, 1, 0)
(2, 0, 0)
(2, 1, 0)
OneTimeProperty
dipy.core.onetime.
OneTimeProperty
(func)Bases: object
A descriptor to make special properties that become normal attributes.
This is meant to be used mostly by the auto_attr decorator in this module.
ResetMixin
dipy.core.onetime.
ResetMixin
Bases: object
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.
Examples
>>> class A(ResetMixin):
... def __init__(self,x=1.0):
... self.x = x
...
... @auto_attr
... def y(self):
... print('*** y computation executed ***')
... return self.x / 2.0
...
>>> a = A(10)
About to access y twice, the second time no computation is done: >>> a.y * y computation executed * 5.0 >>> a.y 5.0
Changing x >>> a.x = 20
a.y doesn’t change to 10, since it is a static attribute: >>> a.y 5.0
We now reset a, and this will then force all auto attributes to recompute the next time we access them: >>> a.reset()
About to access y twice again after reset(): >>> a.y * y computation executed * 10.0 >>> a.y 10.0
Methods
reset () |
Reset all OneTimeProperty attributes that may have fired already. |
dipy.core.onetime.
auto_attr
(func)Decorator to create OneTimeProperty attributes.
Parameters: |
|
---|
Examples
>>> class MagicProp(object):
... @auto_attr
... def a(self):
... return 99
...
>>> x = MagicProp()
>>> 'a' in x.__dict__
False
>>> x.a
99
>>> 'a' in x.__dict__
True
dipy.core.onetime.
setattr_on_read
(func)Decorator to create OneTimeProperty attributes.
Parameters: |
|
---|
Examples
>>> class MagicProp(object):
... @auto_attr
... def a(self):
... return 99
...
>>> x = MagicProp()
>>> 'a' in x.__dict__
False
>>> x.a
99
>>> 'a' in x.__dict__
True
LooseVersion
dipy.core.optimize.
LooseVersion
(vstring=None)Bases: distutils.version.Version
Version numbering for anarchists and software realists. Implements the standard interface for version number classes as described above. A version number consists of a series of numbers, separated by either periods or strings of letters. When comparing version numbers, the numeric components will be compared numerically, and the alphabetic components lexically. The following are all valid version numbers, in no particular order:
1.5.1 1.5.2b2 161 3.10a 8.02 3.4j 1996.07.12 3.2.pl0 3.1.1.6 2g6 11g 0.960923 2.2beta29 1.13++ 5.5.kw 2.0b1pl0
In fact, there is no such thing as an invalid version number under this scheme; the rules for comparison are simple and predictable, but may not always give the results you want (for some definition of “want”).
Methods
parse |
NonNegativeLeastSquares
dipy.core.optimize.
NonNegativeLeastSquares
(*args, **kwargs)Bases: dipy.core.optimize.SKLearnLinearSolver
A sklearn-like interface to scipy.optimize.nnls
Methods
fit (X, y) |
Fit the NonNegativeLeastSquares linear model to data |
predict (X) |
Predict using the result of the model |
Optimizer
dipy.core.optimize.
Optimizer
(fun, x0, args=(), method='L-BFGS-B', jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None, evolution=False)Bases: object
Attributes: |
|
---|
Methods
print_summary |
__init__
(fun, x0, args=(), method='L-BFGS-B', jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None, evolution=False)A class for handling minimization of scalar function of one or more variables.
Parameters: |
|
---|
See also
scipy.optimize.minimize
SKLearnLinearSolver
dipy.core.optimize.
SKLearnLinearSolver
(*args, **kwargs)Bases: abc.NewBase
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)
Methods
fit (X, y) |
Implement for all derived classes |
predict (X) |
Predict using the result of the model |
dipy.core.optimize.
minimize
(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)Minimization of scalar function of one or more variables.
Parameters: |
|
---|---|
Returns: |
|
See also
minimize_scalar
show_options
Notes
This section describes the available solvers that can be selected by the ‘method’ parameter. The default method is BFGS.
Unconstrained minimization
Method Nelder-Mead uses the Simplex algorithm [1], [2]. This algorithm is robust in many applications. However, if numerical computation of derivative can be trusted, other algorithms using the first and/or second derivatives information might be preferred for their better performance in general.
Method Powell is a modification of Powell’s method [3], [4] which is a conjugate direction method. It performs sequential one-dimensional minimizations along each vector of the directions set (direc field in options and info), which is updated at each iteration of the main minimization loop. The function need not be differentiable, and no derivatives are taken.
Method CG uses a nonlinear conjugate gradient algorithm by Polak and Ribiere, a variant of the Fletcher-Reeves method described in [5] pp. 120-122. Only the first derivatives are used.
Method BFGS uses the quasi-Newton method of Broyden, Fletcher, Goldfarb, and Shanno (BFGS) [5] pp. 136. It uses the first derivatives only. BFGS has proven good performance even for non-smooth optimizations. This method also returns an approximation of the Hessian inverse, stored as hess_inv in the OptimizeResult object.
Method Newton-CG uses a Newton-CG algorithm [5] pp. 168 (also known as the truncated Newton method). It uses a CG method to the compute the search direction. See also TNC method for a box-constrained minimization with a similar algorithm. Suitable for large-scale problems.
Method dogleg uses the dog-leg trust-region algorithm [5] for unconstrained minimization. This algorithm requires the gradient and Hessian; furthermore the Hessian is required to be positive definite.
Method trust-ncg uses the Newton conjugate gradient trust-region algorithm [5] for unconstrained minimization. This algorithm requires the gradient and either the Hessian or a function that computes the product of the Hessian with a given vector. Suitable for large-scale problems.
Method trust-krylov uses the Newton GLTR trust-region algorithm [14], [15] for unconstrained minimization. This algorithm requires the gradient and either the Hessian or a function that computes the product of the Hessian with a given vector. Suitable for large-scale problems. On indefinite problems it requires usually less iterations than the trust-ncg method and is recommended for medium and large-scale problems.
Method trust-exact is a trust-region method for unconstrained minimization in which quadratic subproblems are solved almost exactly [13]. This algorithm requires the gradient and the Hessian (which is not required to be positive definite). It is, in many situations, the Newton method to converge in fewer iteraction and the most recommended for small and medium-size problems.
Bound-Constrained minimization
Method L-BFGS-B uses the L-BFGS-B algorithm [6], [7] for bound constrained minimization.
Method TNC uses a truncated Newton algorithm [5], [8] to minimize a function with variables subject to bounds. This algorithm uses gradient information; it is also called Newton Conjugate-Gradient. It differs from the Newton-CG method described above as it wraps a C implementation and allows each variable to be given upper and lower bounds.
Constrained Minimization
Method COBYLA uses the Constrained Optimization BY Linear Approximation (COBYLA) method [9], [10], [11]. The algorithm is based on linear approximations to the objective function and each constraint. The method wraps a FORTRAN implementation of the algorithm. The constraints functions ‘fun’ may return either a single number or an array or list of numbers.
Method SLSQP uses Sequential Least SQuares Programming to minimize a function of several variables with any combination of bounds, equality and inequality constraints. The method wraps the SLSQP Optimization subroutine originally implemented by Dieter Kraft [12]. Note that the wrapper handles infinite values in bounds by converting them into large floating values.
Method trust-constr is a trust-region algorithm for constrained optimization. It swiches between two implementations depending on the problem definition. It is the most versatile constrained minimization algorithm implemented in SciPy and the most appropriate for large-scale problems. For equality constrained problems it is an implementation of Byrd-Omojokun Trust-Region SQP method described in [17] and in [5], p. 549. When inequality constraints are imposed as well, it swiches to the trust-region interior point method described in [16]. This interior point algorithm, in turn, solves inequality constraints by introducing slack variables and solving a sequence of equality-constrained barrier problems for progressively smaller values of the barrier parameter. The previously described equality constrained SQP method is used to solve the subproblems with increasing levels of accuracy as the iterate gets closer to a solution.
Finite-Difference Options
For Method trust-constr the gradient and the Hessian may be approximated using three finite-difference schemes: {‘2-point’, ‘3-point’, ‘cs’}. The scheme ‘cs’ is, potentially, the most accurate but it requires the function to correctly handles complex inputs and to be differentiable in the complex plane. The scheme ‘3-point’ is more accurate than ‘2-point’ but requires twice as much operations.
Custom minimizers
It may be useful to pass a custom minimization method, for example
when using a frontend to this method such as scipy.optimize.basinhopping
or a different library. You can simply pass a callable as the method
parameter.
The callable is called as method(fun, x0, args, **kwargs, **options)
where kwargs
corresponds to any other parameters passed to minimize
(such as callback, hess, etc.), except the options dict, which has
its contents also passed as method parameters pair by pair. Also, if
jac has been passed as a bool type, jac and fun are mangled so that
fun returns just the function values and jac is converted to a function
returning the Jacobian. The method shall return an OptimizeResult
object.
The provided method callable must be able to accept (and possibly ignore) arbitrary parameters; the set of parameters accepted by minimize may expand in future versions and then these parameters will be passed to the method. You can find an example in the scipy.optimize tutorial.
New in version 0.11.0.
References
[1] | (1, 2) Nelder, J A, and R Mead. 1965. A Simplex Method for Function Minimization. The Computer Journal 7: 308-13. |
[2] | (1, 2) Wright M H. 1996. Direct search methods: Once scorned, now respectable, in Numerical Analysis 1995: Proceedings of the 1995 Dundee Biennial Conference in Numerical Analysis (Eds. D F Griffiths and G A Watson). Addison Wesley Longman, Harlow, UK. 191-208. |
[3] | (1, 2) Powell, M J D. 1964. An efficient method for finding the minimum of a function of several variables without calculating derivatives. The Computer Journal 7: 155-162. |
[4] | (1, 2) Press W, S A Teukolsky, W T Vetterling and B P Flannery. Numerical Recipes (any edition), Cambridge University Press. |
[5] | (1, 2, 3, 4, 5, 6, 7, 8, 9) Nocedal, J, and S J Wright. 2006. Numerical Optimization. Springer New York. |
[6] | (1, 2) Byrd, R H and P Lu and J. Nocedal. 1995. A Limited Memory Algorithm for Bound Constrained Optimization. SIAM Journal on Scientific and Statistical Computing 16 (5): 1190-1208. |
[7] | (1, 2) Zhu, C and R H Byrd and J Nocedal. 1997. L-BFGS-B: Algorithm 778: L-BFGS-B, FORTRAN routines for large scale bound constrained optimization. ACM Transactions on Mathematical Software 23 (4): 550-560. |
[8] | (1, 2) Nash, S G. Newton-Type Minimization Via the Lanczos Method. 1984. SIAM Journal of Numerical Analysis 21: 770-778. |
[9] | (1, 2) Powell, M J D. A direct search optimization method that models the objective and constraint functions by linear interpolation. 1994. Advances in Optimization and Numerical Analysis, eds. S. Gomez and J-P Hennart, Kluwer Academic (Dordrecht), 51-67. |
[10] | (1, 2) Powell M J D. Direct search algorithms for optimization calculations. 1998. Acta Numerica 7: 287-336. |
[11] | (1, 2) Powell M J D. A view of algorithms for optimization without derivatives. 2007.Cambridge University Technical Report DAMTP 2007/NA03 |
[12] | (1, 2) Kraft, D. A software package for sequential quadratic programming. 1988. Tech. Rep. DFVLR-FB 88-28, DLR German Aerospace Center – Institute for Flight Mechanics, Koln, Germany. |
[13] | (1, 2) Conn, A. R., Gould, N. I., and Toint, P. L. Trust region methods. 2000. Siam. pp. 169-200. |
[14] | (1, 2) F. Lenders, C. Kirches, A. Potschka: “trlib: A vector-free implementation of the GLTR method for iterative solution of the trust region problem”, https://arxiv.org/abs/1611.04718 |
[15] | (1, 2) N. Gould, S. Lucidi, M. Roma, P. Toint: “Solving the Trust-Region Subproblem using the Lanczos Method”, SIAM J. Optim., 9(2), 504–525, (1999). |
[16] | (1, 2) Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal. 1999. An interior point algorithm for large-scale nonlinear programming. SIAM Journal on Optimization 9.4: 877-900. |
[17] | (1, 2) Lalee, Marucha, Jorge Nocedal, and Todd Plantega. 1998. On the implementation of an algorithm for large-scale equality constrained optimization. SIAM Journal on Optimization 8.3: 682-706. |
Examples
Let us consider the problem of minimizing the Rosenbrock function. This function (and its respective derivatives) is implemented in rosen (resp. rosen_der, rosen_hess) in the scipy.optimize.
>>> from scipy.optimize import minimize, rosen, rosen_der
A simple application of the Nelder-Mead method is:
>>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
>>> res = minimize(rosen, x0, method='Nelder-Mead', tol=1e-6)
>>> res.x
array([ 1., 1., 1., 1., 1.])
Now using the BFGS algorithm, using the first derivative and a few options:
>>> res = minimize(rosen, x0, method='BFGS', jac=rosen_der,
... options={'gtol': 1e-6, 'disp': True})
Optimization terminated successfully.
Current function value: 0.000000
Iterations: 26
Function evaluations: 31
Gradient evaluations: 31
>>> res.x
array([ 1., 1., 1., 1., 1.])
>>> print(res.message)
Optimization terminated successfully.
>>> res.hess_inv
array([[ 0.00749589, 0.01255155, 0.02396251, 0.04750988, 0.09495377], # may vary
[ 0.01255155, 0.02510441, 0.04794055, 0.09502834, 0.18996269],
[ 0.02396251, 0.04794055, 0.09631614, 0.19092151, 0.38165151],
[ 0.04750988, 0.09502834, 0.19092151, 0.38341252, 0.7664427 ],
[ 0.09495377, 0.18996269, 0.38165151, 0.7664427, 1.53713523]])
Next, consider a minimization problem with several constraints (namely Example 16.4 from [5]). The objective function is:
>>> fun = lambda x: (x[0] - 1)**2 + (x[1] - 2.5)**2
There are three constraints defined as:
>>> cons = ({'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1] + 2},
... {'type': 'ineq', 'fun': lambda x: -x[0] - 2 * x[1] + 6},
... {'type': 'ineq', 'fun': lambda x: -x[0] + 2 * x[1] + 2})
And variables must be positive, hence the following bounds:
>>> bnds = ((0, None), (0, None))
The optimization problem is solved using the SLSQP method as:
>>> res = minimize(fun, (2, 0), method='SLSQP', bounds=bnds,
... constraints=cons)
It should converge to the theoretical solution (1.4 ,1.7).
dipy.core.optimize.
sparse_nnls
(y, X, momentum=1, step_size=0.01, non_neg=True, check_error_iter=10, max_error_checks=10, converge_on_sse=0.99)Solve y=Xh for h, using gradient descent, with X a sparse matrix
Parameters: |
|
---|---|
Returns: |
|
dipy.core.optimize.
spdot
(A, B)The same as np.dot(A, B), except it works even if A or B or both are sparse matrices.
Parameters: |
|
---|---|
Returns: |
|
Profiler
dipy.core.profile.
Profiler
(call=None, *args)Bases: object
Profile python/cython files or functions
If you are profiling cython code you need to add # cython: profile=True on the top of your .pyx file
and for the functions that you do not want to profile you can use this decorator in your cython files
@cython.profile(False)
Parameters: |
|
---|
References
http://docs.cython.org/src/tutorial/profiling_tutorial.html http://docs.python.org/library/profile.html http://packages.python.org/line_profiler/
Examples
from dipy.core.profile import Profiler import numpy as np p=Profiler(np.sum,np.random.rand(1000000,3)) fname=’test.py’ p=Profiler(fname) p.print_stats(10) p.print_stats(‘det’)
Attributes: |
|
---|
Methods
print_stats ([N]) |
Print stats for profiling |
print_stats
(N=10)Print stats for profiling
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’
Parameters: |
|
---|
dipy.core.profile.
optional_package
(name, trip_msg=None)Return package-like thing and module setup for package name
Parameters: |
|
---|---|
Returns: |
|
dipy.core.rng.
WichmannHill1982
()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.
dipy.core.rng.
WichmannHill2006
()B.A. Wichmann, I.D. Hill, Generating good pseudo-random numbers, Computational Statistics & Data Analysis, Volume 51, Issue 3, 1 December 2006, Pages 1614-1622, ISSN 0167-9473, DOI: 10.1016/j.csda.2006.05.019. (http://www.sciencedirect.com/science/article/B6V8V-4K7F86W-2/2/a3a33291b8264e4c882a8f21b6e43351) for advice on generating many sequences for use together, and on alternative algorithms and codes
Examples
>>> from dipy.core import rng
>>> rng.ix, rng.iy, rng.iz, rng.it = 100001, 200002, 300003, 400004
>>> N = 1000
>>> a = [rng.WichmannHill2006() for i in range(N)]
dipy.core.rng.
architecture
(executable='/Users/koudoro/anaconda/envs/dipy_dev_3/bin/python', bits='', linkage='')Queries the given executable (defaults to the Python interpreter binary) for various architecture information.
Returns a tuple (bits, linkage) which contains information about the bit architecture and the linkage format used for the executable. Both values are returned as strings.
Values that cannot be determined are returned as given by the parameter presets. If bits is given as ‘’, the sizeof(pointer) (or sizeof(long) on Python version < 1.5.2) is used as indicator for the supported pointer size.
The function relies on the system’s “file” command to do the actual work. This is available on most if not all Unix platforms. On some non-Unix platforms where the “file” command does not exist and the executable is set to the Python interpreter binary defaults from _default_architecture are used.
HemiSphere
dipy.core.sphere.
HemiSphere
(x=None, y=None, z=None, theta=None, phi=None, xyz=None, faces=None, edges=None, tol=1e-05)Bases: dipy.core.sphere.Sphere
Points on the unit sphere.
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:
HemiSphere(x, y, z)
HemiSphere(xyz=xyz)
HemiSphere(theta=theta, phi=phi)
Parameters: |
|
---|
See also
Attributes: |
|
---|
Methods
find_closest (xyz) |
Find the index of the vertex in the Sphere closest to the input vector, taking into account antipodal symmetry |
from_sphere (sphere[, tol]) |
Create instance from a Sphere |
mirror () |
Create a full Sphere from a HemiSphere |
subdivide ([n]) |
Create a more subdivided HemiSphere |
edges | |
faces | |
vertices |
__init__
(x=None, y=None, z=None, theta=None, phi=None, xyz=None, faces=None, edges=None, tol=1e-05)Create a HemiSphere from points
Sphere
dipy.core.sphere.
Sphere
(x=None, y=None, z=None, theta=None, phi=None, xyz=None, faces=None, edges=None)Bases: object
Points on the unit sphere.
The sphere can be constructed using one of three conventions:
Sphere(x, y, z)
Sphere(xyz=xyz)
Sphere(theta=theta, phi=phi)
Parameters: |
|
---|---|
Attributes: |
|
Methods
find_closest (xyz) |
Find the index of the vertex in the Sphere closest to the input vector |
subdivide ([n]) |
Subdivides each face of the sphere into four new faces. |
edges | |
faces | |
vertices |
__init__
(x=None, y=None, z=None, theta=None, phi=None, xyz=None, faces=None, edges=None)Initialize self. See help(type(self)) for accurate signature.
find_closest
(xyz)Find the index of the vertex in the Sphere closest to the input vector
Parameters: |
|
---|
subdivide
(n=1)Subdivides each face of the sphere into four new faces.
New vertices are created at a, b, and c. Then each face [x, y, z] is divided into faces [x, a, c], [y, a, b], [z, b, c], and [a, b, c].
y
/ / a/____
/\ / / \ / /____\/____ x c z
Parameters: |
|
---|---|
Returns: |
|
dipy.core.sphere.
auto_attr
(func)Decorator to create OneTimeProperty attributes.
Parameters: |
|
---|
Examples
>>> class MagicProp(object):
... @auto_attr
... def a(self):
... return 99
...
>>> x = MagicProp()
>>> 'a' in x.__dict__
False
>>> x.a
99
>>> 'a' in x.__dict__
True
dipy.core.sphere.
cart2sphere
(x, y, z)Return angles for Cartesian 3D coordinates x, y, and z
See doc for sphere2cart
for angle conventions and derivation
of the formulae.
\(0\le\theta\mathrm{(theta)}\le\pi\) and \(-\pi\le\phi\mathrm{(phi)}\le\pi\)
Parameters: |
|
---|---|
Returns: |
|
dipy.core.sphere.
disperse_charges
(hemi, iters, const=0.2)Models electrostatic repulsion on the unit sphere
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: |
|
---|---|
Returns: |
|
dipy.core.sphere.
euler_characteristic_check
(sphere, chi=2)Checks the euler characteristic of a sphere
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.
Parameters: |
|
---|---|
Returns: |
|
Examples
>>> euler_characteristic_check(unit_octahedron)
True
>>> hemisphere = HemiSphere.from_sphere(unit_icosahedron)
>>> euler_characteristic_check(hemisphere, chi=1)
True
dipy.core.sphere.
interp_rbf
(data, sphere_origin, sphere_target, function='multiquadric', epsilon=None, smooth=0.1, norm='angle')Interpolate data on the sphere, using radial basis functions.
Parameters: |
|
---|---|
Returns: |
|
See also
scipy.interpolate.Rbf
dipy.core.sphere.
remove_similar_vertices
()Remove vertices that are less than theta degrees from any other
Returns vertices that are at least theta degrees from any other vertex. Vertex v and -v are considered the same so if v and -v are both in vertices only one is kept. Also if v and w are both in vertices, w must be separated by theta degrees from both v and -v to be unique.
Parameters: |
|
---|---|
Returns: |
|
dipy.core.sphere.
sphere2cart
(r, theta, phi)Spherical to Cartesian coordinates
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’
Parameters: |
|
---|---|
Returns: |
|
Notes
See these pages:
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.
dipy.core.sphere.
unique_edges
(faces, return_mapping=False)Extract all unique edges from given triangular faces.
Parameters: |
|
---|---|
Returns: |
|
dipy.core.sphere.
vector_norm
(vec, axis=-1, keepdims=False)Return vector Euclidean (L2) norm
See unit vector and Euclidean norm
Parameters: |
|
---|---|
Returns: |
|
Examples
>>> import numpy as np
>>> vec = [[8, 15, 0], [0, 36, 77]]
>>> vector_norm(vec)
array([ 17., 85.])
>>> vector_norm(vec, keepdims=True)
array([[ 17.],
[ 85.]])
>>> vector_norm(vec, axis=0)
array([ 8., 39., 77.])
permutations
dipy.core.sphere_stats.
permutations
Bases: object
permutations(iterable[, r]) –> permutations object
Return successive r-length permutations of elements in the iterable.
permutations(range(3), 2) –> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)
dipy.core.sphere_stats.
angular_similarity
(S, T)Computes the cosine distance of the best match between points of two sets of vectors S and T
Parameters: |
|
---|---|
Returns: |
|
Examples
>>> import numpy as np
>>> from dipy.core.sphere_stats import angular_similarity
>>> S=np.array([[1,0,0],[0,1,0],[0,0,1]])
>>> T=np.array([[1,0,0],[0,0,1]])
>>> angular_similarity(S,T)
2.0
>>> T=np.array([[0,1,0],[1,0,0],[0,0,1]])
>>> S=np.array([[1,0,0],[0,0,1]])
>>> angular_similarity(S,T)
2.0
>>> S=np.array([[-1,0,0],[0,1,0],[0,0,1]])
>>> T=np.array([[1,0,0],[0,0,-1]])
>>> angular_similarity(S,T)
2.0
>>> T=np.array([[0,1,0],[1,0,0],[0,0,1]])
>>> S=np.array([[1,0,0],[0,1,0],[0,0,1]])
>>> angular_similarity(S,T)
3.0
>>> S=np.array([[0,1,0],[1,0,0],[0,0,1]])
>>> T=np.array([[1,0,0],[0,np.sqrt(2)/2.,np.sqrt(2)/2.],[0,0,1]])
>>> angular_similarity(S,T)
2.7071067811865475
>>> S=np.array([[0,1,0],[1,0,0],[0,0,1]])
>>> T=np.array([[1,0,0]])
>>> angular_similarity(S,T)
1.0
>>> S=np.array([[0,1,0],[1,0,0]])
>>> T=np.array([[0,0,1]])
>>> angular_similarity(S,T)
0.0
>>> S=np.array([[0,1,0],[1,0,0]])
>>> T=np.array([[0,np.sqrt(2)/2.,np.sqrt(2)/2.]])
Now we use print
to reduce the precision of of the printed output
(so the doctests don’t detect unimportant differences)
>>> print('%.12f' % angular_similarity(S,T))
0.707106781187
>>> S=np.array([[0,1,0]])
>>> T=np.array([[0,np.sqrt(2)/2.,np.sqrt(2)/2.]])
>>> print('%.12f' % angular_similarity(S,T))
0.707106781187
>>> S=np.array([[0,1,0],[0,0,1]])
>>> T=np.array([[0,np.sqrt(2)/2.,np.sqrt(2)/2.]])
>>> print('%.12f' % angular_similarity(S,T))
0.707106781187
dipy.core.sphere_stats.
compare_orientation_sets
(S, T)Computes the mean cosine distance of the best match between points of two sets of vectors S and T (angular similarity)
Parameters: |
|
---|---|
Returns: |
|
Examples
>>> from dipy.core.sphere_stats import compare_orientation_sets
>>> S=np.array([[1,0,0],[0,1,0],[0,0,1]])
>>> T=np.array([[1,0,0],[0,0,1]])
>>> compare_orientation_sets(S,T)
1.0
>>> T=np.array([[0,1,0],[1,0,0],[0,0,1]])
>>> S=np.array([[1,0,0],[0,0,1]])
>>> compare_orientation_sets(S,T)
1.0
>>> from dipy.core.sphere_stats import compare_orientation_sets
>>> S=np.array([[-1,0,0],[0,1,0],[0,0,1]])
>>> T=np.array([[1,0,0],[0,0,-1]])
>>> compare_orientation_sets(S,T)
1.0
dipy.core.sphere_stats.
eigenstats
(points, alpha=0.05)Principal direction and confidence ellipse
Implements equations in section 6.3.1(ii) of Fisher, Lewis and Embleton, supplemented by equations in section 3.2.5.
Parameters: |
|
---|---|
Returns: |
|
dipy.core.sphere_stats.
random_uniform_on_sphere
(n=1, coords='xyz')Random unit vectors from a uniform distribution on the sphere.
Parameters: |
|
---|---|
Returns: |
|
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]\).
References
[1] | http://mathworld.wolfram.com/SpherePointPicking.html. |
Examples
>>> from dipy.core.sphere_stats import random_uniform_on_sphere
>>> X = random_uniform_on_sphere(4, 'radians')
>>> X.shape == (4, 2)
True
>>> X = random_uniform_on_sphere(4, 'xyz')
>>> X.shape == (4, 3)
True
HemiSphere
dipy.core.subdivide_octahedron.
HemiSphere
(x=None, y=None, z=None, theta=None, phi=None, xyz=None, faces=None, edges=None, tol=1e-05)Bases: dipy.core.sphere.Sphere
Points on the unit sphere.
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:
HemiSphere(x, y, z)
HemiSphere(xyz=xyz)
HemiSphere(theta=theta, phi=phi)
Parameters: |
|
---|
See also
Sphere
Attributes: |
|
---|
Methods
find_closest (xyz) |
Find the index of the vertex in the Sphere closest to the input vector, taking into account antipodal symmetry |
from_sphere (sphere[, tol]) |
Create instance from a Sphere |
mirror () |
Create a full Sphere from a HemiSphere |
subdivide ([n]) |
Create a more subdivided HemiSphere |
edges | |
faces | |
vertices |
__init__
(x=None, y=None, z=None, theta=None, phi=None, xyz=None, faces=None, edges=None, tol=1e-05)Create a HemiSphere from points
dipy.core.subdivide_octahedron.
create_unit_hemisphere
(recursion_level=2)Creates a unit sphere by subdividing a unit octahedron, returns half the sphere.
Parameters: |
|
---|---|
Returns: |
|
See also
create_unit_sphere
, Sphere
, HemiSphere
dipy.core.subdivide_octahedron.
create_unit_sphere
(recursion_level=2)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: |
|
---|---|
Returns: |
|
See also
create_unit_hemisphere
, Sphere
dipy.core.wavelet.
afb3D
(x, af1, af2=None, af3=None)3D Analysis Filter Bank
Parameters: |
|
---|---|
Returns: |
|
dipy.core.wavelet.
afb3D_A
(x, af, d)Parameters: |
|
---|---|
Returns: |
|