Here are the examples of the python api numpy.ascontiguousarray taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
78 Examples
4
Example 1
def _as_float_array(x, check_finite=False):
"""Convert the input into a C contiguous float array."""
x = np.ascontiguousarray(x)
if not np.issubdtype(x.dtype, np.inexact):
x = x.astype(float)
if check_finite and not np.isfinite(x).all():
raise ValueError("Array must not contain infs or nans.")
return x
3
Example 2
Project: iris Source File: test_interpolation.py
def normalise_order(cube):
# Avoid the crazy array ordering which results from using:
# * np.append() in NumPy 1.6, which is triggered in the `linear()`
# function when the circular flag is true.
# * scipy.interpolate.interp1d in 0.11.0 which is used in
# `Linear1dExtrapolator`.
cube.data = np.ascontiguousarray(cube.data)
3
Example 3
def update_matrices(self):
'''Update inverse and OpenGL matrices, from the current transformation.
If you change manually the transformation, you should call this
function, or the drawing will failed.
'''
self._transform_inv = inverse_matrix(self._transform)
self._transform_gl = ascontiguousarray(self._transform.T,
dtype='float32')
self._transform_inv_gl = ascontiguousarray(self._transform.T,
dtype='float32')
3
Example 4
def get_base(self, coors, diff=False):
"""
Get base functions or their gradient evaluated in given
coordinates.
"""
bf = self.poly_space.eval_base(coors, diff=diff)
return nm.ascontiguousarray(bf[..., :self.dim-1:, self.indices])
3
Example 5
Project: rpigl Source File: glesutils.py
def prep_array(self, ar):
"""Convert ar to an array of the correct type and check its shape."""
ar = numpy.ascontiguousarray(ar, dtype=self.dtype)
if ar.shape[1:] not in self.allowed_shapes:
raise ValueError("Invalid array shape: %s" % ar.shape)
return ar
3
Example 6
Project: chaco Source File: image_plot.py
def _kiva_array_from_numpy_array(self, data):
if data.shape[2] not in KIVA_DEPTH_MAP:
msg = "Unknown colormap depth value: {}"
raise RuntimeError(msg.format(data.shape[2]))
kiva_depth = KIVA_DEPTH_MAP[data.shape[2]]
# Data presented to the GraphicsContextArray needs to be contiguous.
data = np.ascontiguousarray(data)
return GraphicsContextArray(data, pix_format=kiva_depth)
3
Example 7
Project: chaco Source File: color_bar.py
def _make_color_image(self, color_values, width, orientation, direction):
"""
Returns an image graphics context representing the array of color
values (Nx3 or Nx4). The *width* parameter is the width of the
colorbar, and *orientation* is the orientation of the plot.
"""
bmparray = ones((width, color_values.shape[0],
color_values.shape[1]))* color_values * 255
if orientation == "v":
bmparray = ascontiguousarray(transpose(bmparray, axes=(1,0,2))[::-1])
bmparray = bmparray.astype(uint8)
img = GraphicsContext(bmparray, "rgba32")
return img
3
Example 8
Project: pyphi Source File: utils.py
def np_hash(a):
"""Return a hash of a NumPy array."""
if a is None:
return hash(None)
# Ensure that hashes are equal whatever the ordering in memory (C or
# Fortran)
a = np.ascontiguousarray(a)
# Compute the digest and return a decimal int
return int(hashlib.sha1(a.view(a.dtype)).hexdigest(), 16)
3
Example 9
Project: scikit-image Source File: test_find_contours.py
def test_memory_order():
contours = find_contours(np.ascontiguousarray(r), 0.5)
assert len(contours) == 1
contours = find_contours(np.asfortranarray(r), 0.5)
assert len(contours) == 1
3
Example 10
Project: cocos Source File: particle.py
def PointerToNumpy(a, ptype=ctypes.c_float):
"""PointerToNumpy(a, ptype=ctypes.c_float)
Provides a ctype pointer to a Numpy array.
Arguments:
a (numpy.array): The Numpy array.
ptype (ctypes): The ctypes type contained in the array.
Returns:
Pointer to the Numpy array.
"""
a = numpy.ascontiguousarray(a) # Probably a NO-OP, but perhaps not
return a.ctypes.data_as(ctypes.POINTER(ptype)) # Ugly and undocuemented!
3
Example 11
def get_fargs(self, parameter,
mode=None, term_mode=None, diff_var=None, **kwargs):
sg, _ = self.get_mapping(parameter)
sd = parameter.field.surface_data[self.region.name]
bf = parameter.field.get_base(sd.bkey, 0, self.integral)
name = parameter.name
fd = self.get_family_data(parameter, self.region, self.integral,
self.geometry_types[name],
self.arg_steps[name],
self.arg_derivatives[name])
asc = nm.ascontiguousarray
coors0 = parameter.field.get_coor()
coors = asc(coors0 + parameter().reshape(coors0.shape))
return coors, fd.det_f, fd.inv_f, bf, sg, asc(sd.econn)
3
Example 12
Project: GPy Source File: stationary.py
def _gradients_X_cython(self, dL_dK, X, X2=None):
invdist = self._inv_dist(X, X2)
dL_dr = self.dK_dr_via_X(X, X2) * dL_dK
tmp = invdist*dL_dr
if X2 is None:
tmp = tmp + tmp.T
X2 = X
X, X2 = np.ascontiguousarray(X), np.ascontiguousarray(X2)
grad = np.zeros(X.shape)
stationary_cython.grad_X(X.shape[0], X.shape[1], X2.shape[0], X, X2, tmp, grad)
return grad/self.lengthscale**2
3
Example 13
@staticmethod
def function(out, mat, vg):
div_bf = vg.bfg
n_el, n_qp, dim, n_ep = div_bf.shape
div_bf = div_bf.reshape((n_el, n_qp, dim * n_ep, 1))
div_bf = nm.ascontiguousarray(div_bf)
if mat is not None:
status = vg.integrate(out, mat * div_bf)
else:
status = vg.integrate(out, div_bf)
return status
3
Example 14
Project: betty-cropper Source File: dssim.py
def get_distortion(one, two):
# This computes the "DSSIM" of the images, using the SSIM of each channel
ssims = []
for channel in range(one.shape[2]):
one_channeled = np.ascontiguousarray(one[:, :, channel])
two_channeled = np.ascontiguousarray(two[:, :, channel])
ssim = compute_ssim(one_channeled, two_channeled)
ssims.append(ssim)
return (1 / np.mean(ssims) - 1) * 20
3
Example 15
@staticmethod
def function(out, force, normal, geo, fmode):
bf = geo.bf[0]
nbf = bf * normal[None, :, None]
nbf.shape = (bf.shape[0], bf.shape[2] * normal.shape[0])
if fmode == 0:
out_qp = force * nbf[None, :, :, None]
else:
nbf2 = nbf[:, :, None] * nbf[:, None, :]
out_qp = force * nbf2[None, :, :, :]
status = geo.integrate(out, nm.ascontiguousarray(out_qp))
return status
3
Example 16
def update_output(self, x):
N, C, H, W = x.shape
x_flat = x.transpose(0, 2, 3, 1).reshape(-1, C)
x_flat = np.ascontiguousarray(x_flat, dtype=x.dtype)
super(SpatialBatchNormalization, self).update_output(x_flat)
self.output = self.output.reshape(N, H, W, C).transpose(0, 3, 1, 2)
return self.output
3
Example 17
Project: orange Source File: lasso.py
def get_lipschitz(self, X):
"""Return the Lipschitz constant of :math:`\\nabla f`,
where :math:`f(w) = \\frac{1}{2}||Xw-y||^2`.
"""
n, m = X.shape
if n > m:
X = ascontiguousarray(X.T)
k = min(n, m) - 1
eigvals = eigh(dot(X, X.T), eigvals_only=True, eigvals=(k, k))
return eigvals[-1]
3
Example 18
def update_grad_input(self, x, grad_output, scale=1):
N, C, H, W = grad_output.shape
dout_flat = grad_output.transpose(0, 2, 3, 1).reshape(-1, C)
dout_flat = np.ascontiguousarray(dout_flat, dtype=dout_flat.dtype)
super(SpatialBatchNormalization, self).update_grad_input(x, dout_flat, scale)
self.grad_input = self.grad_input.reshape(N, H, W, C).transpose(0, 3, 1, 2)
return self.grad_input
3
Example 19
Project: sfepy Source File: terms_dot.py
@staticmethod
def dw_fun(out, bf, vg, grad, idx, fmode):
cc = nm.ascontiguousarray
bft = cc(nm.tile(bf, (out.shape[0], 1, 1, 1)))
if fmode == 0:
status = terms.mulAB_integrate(out, bft,
cc(grad[..., idx:idx+1, :]), vg,
mode='ATB')
else:
status = terms.mulAB_integrate(out, bft,
cc(vg.bfg[:,:,idx:(idx + 1),:]), vg,
mode='ATB')
return status
3
Example 20
def resize(self, N, M):
self.memberships.resize((M,N))
self.memberships = np.ascontiguousarray(self.memberships)
self.loglikelihoods.resize(N, refcheck=False)
self.loglikelihoods = np.ascontiguousarray(self.loglikelihoods)
self.M = M
self.N = N
3
Example 21
Project: inselect Source File: utils.py
def qimage_of_bgr(bgr):
""" A QImage representation of a BGR numpy array
"""
import cv2
import numpy as np
bgr = cv2.cvtColor(bgr.astype('uint8'), cv2.COLOR_BGR2RGB)
bgr = np.ascontiguousarray(bgr)
qt_image = QImage(bgr.data,
bgr.shape[1], bgr.shape[0],
bgr.strides[0], QImage.Format_RGB888)
# QImage does not take a deep copy of np_arr.data so hold a reference
# to it
assert(not hasattr(qt_image, 'bgr_array'))
qt_image.bgr_array = bgr
return qt_image
3
Example 22
def get_fargs(self, parameter,
mode=None, term_mode=None, diff_var=None, **kwargs):
vg, _ = self.get_mapping(parameter)
grad = self.get(parameter, 'grad')
grad = nm.ascontiguousarray(grad.transpose((0, 1, 3, 2)))
fmode = {'eval' : 0, 'el_avg' : 1, 'qp' : 2}.get(mode, 1)
return grad, vg, fmode
3
Example 23
def __init__(self, name, geometry, order):
PolySpace.__init__(self, name, geometry, order)
aux = self._define_nodes()
self.nodes, self.nts, node_coors, self.face_axes, self.sfnodes = aux
self.node_coors = nm.ascontiguousarray(node_coors)
self.n_nod = self.nodes.shape[0]
aux = nm.where(self.nodes > 0, self.nodes, 1)
self.node_orders = nm.prod(aux, axis=1)
self.edge_indx = nm.where(self.nts[:, 0] == 1)[0]
self.face_indx = nm.where(self.nts[:, 0] == 2)[0]
self.face_axes_nodes = self._get_face_axes_nodes(self.face_axes)
3
Example 24
Project: dipy Source File: test_peaks.py
def odf(self, sphere=None):
if sphere is None:
sphere = self.model.sphere
# Use ascontiguousarray to work around a bug in NumPy
return np.ascontiguousarray((sphere.vertices * [1, 2, 3]).sum(-1))
2
Example 25
Project: brickv Source File: numpymodule.py
@classmethod
def contiguous( cls, source, typeCode=None ):
"""Get contiguous array from source
source -- numpy Python array (or compatible object)
for use as the data source. If this is not a contiguous
array of the given typeCode, a copy will be made,
otherwise will just be returned unchanged.
typeCode -- optional 1-character typeCode specifier for
the numpy.array function.
All gl*Pointer calls should use contiguous arrays, as non-
contiguous arrays will be re-copied on every rendering pass.
Although this doesn't raise an error, it does tend to slow
down rendering.
"""
typeCode = GL_TYPE_TO_ARRAY_MAPPING[ typeCode ]
try:
contiguous = source.flags.contiguous
except AttributeError, err:
if typeCode:
return numpy.ascontiguousarray( source, typeCode )
else:
return numpy.ascontiguousarray( source )
else:
if contiguous and (typeCode is None or typeCode==source.dtype.char):
return source
elif (contiguous and cls.ERROR_ON_COPY):
from OpenGL import error
raise error.CopyError(
"""Array of type %r passed, required array of type %r""",
source.dtype.char, typeCode,
)
else:
# We have to do astype to avoid errors about unsafe conversions
# XXX Confirm that this will *always* create a new contiguous array
# XXX Guard against wacky conversion types like uint to float, where
# we really don't want to have the C-level conversion occur.
# XXX ascontiguousarray is apparently now available in numpy!
if cls.ERROR_ON_COPY:
from OpenGL import error
raise error.CopyError(
"""Non-contiguous array passed""",
source,
)
if typeCode is None:
typeCode = source.dtype.char
return numpy.ascontiguousarray( source, typeCode )
2
Example 26
@classmethod
def contiguous( cls, source, typeCode=None ):
"""Get contiguous array from source
source -- numpy Python array (or compatible object)
for use as the data source. If this is not a contiguous
array of the given typeCode, a copy will be made,
otherwise will just be returned unchanged.
typeCode -- optional 1-character typeCode specifier for
the numpy.array function.
All gl*Pointer calls should use contiguous arrays, as non-
contiguous arrays will be re-copied on every rendering pass.
Although this doesn't raise an error, it does tend to slow
down rendering.
"""
typeCode = GL_TYPE_TO_ARRAY_MAPPING[ typeCode ]
try:
contiguous = source.flags.contiguous
except AttributeError as err:
if typeCode:
return numpy.ascontiguousarray( source, typeCode )
else:
return numpy.ascontiguousarray( source )
else:
if contiguous and (typeCode is None or typeCode==source.dtype.char):
return source
elif (contiguous and cls.ERROR_ON_COPY):
from OpenGL import error
raise error.CopyError(
"""Array of type %r passed, required array of type %r""",
source.dtype.char, typeCode,
)
else:
# We have to do astype to avoid errors about unsafe conversions
# XXX Confirm that this will *always* create a new contiguous array
# XXX Guard against wacky conversion types like uint to float, where
# we really don't want to have the C-level conversion occur.
# XXX ascontiguousarray is apparently now available in numpy!
if cls.ERROR_ON_COPY:
from OpenGL import error
raise error.CopyError(
"""Non-contiguous array passed""",
source,
)
if typeCode is None:
typeCode = source.dtype.char
return numpy.ascontiguousarray( source, typeCode )
2
Example 27
@classmethod
def contiguous( cls, source, typeCode=None ):
"""Get contiguous array from source
source -- numpy Python array (or compatible object)
for use as the data source. If this is not a contiguous
array of the given typeCode, a copy will be made,
otherwise will just be returned unchanged.
typeCode -- optional 1-character typeCode specifier for
the numpy.array function.
All gl*Pointer calls should use contiguous arrays, as non-
contiguous arrays will be re-copied on every rendering pass.
Although this doesn't raise an error, it does tend to slow
down rendering.
"""
typeCode = GL_TYPE_TO_ARRAY_MAPPING[ typeCode ]
try:
contiguous = source.flags.contiguous
except AttributeError as err:
if typeCode:
return numpy.ascontiguousarray( source, typeCode )
else:
return numpy.ascontiguousarray( source )
else:
if contiguous and (typeCode is None or typeCode==source.dtype.char):
return source
elif (contiguous and cls.ERROR_ON_COPY):
from OpenGL import error
raise error.CopyError(
"""Array of type %r passed, required array of type %r""",
source.dtype.char, typeCode,
)
else:
# We have to do astype to avoid errors about unsafe conversions
# XXX Confirm that this will *always* create a new contiguous array
# XXX Guard against wacky conversion types like uint to float, where
# we really don't want to have the C-level conversion occur.
# XXX ascontiguousarray is apparently now available in numpy!
if cls.ERROR_ON_COPY:
from OpenGL import error
raise error.CopyError(
"""Non-contiguous array passed""",
source,
)
if typeCode is None:
typeCode = source.dtype.char
return numpy.ascontiguousarray( source, typeCode )
2
Example 28
Project: GPy Source File: stationary.py
def _lengthscale_grads_cython(self, tmp, X, X2):
N,M = tmp.shape
Q = self.input_dim
X, X2 = np.ascontiguousarray(X), np.ascontiguousarray(X2)
grads = np.zeros(self.input_dim)
stationary_cython.lengthscale_grads(N, M, Q, tmp, X, X2, grads)
return -grads/self.lengthscale**3
0
Example 29
Project: scipy Source File: interpolate_wrapper.py
def atleast_1d_and_contiguous(ary, dtype=np.float64):
return np.atleast_1d(np.ascontiguousarray(ary, dtype))
0
Example 30
def jitchol(A, maxtries=5):
A = np.ascontiguousarray(A)
L, info = lapack.dpotrf(A, lower=1)
if info == 0:
return L
else:
diagA = np.diag(A)
if np.any(diagA <= 0.):
raise linalg.LinAlgError("not pd: non-positive diagonal elements")
jitter = diagA.mean() * 1e-6
num_tries = 1
while num_tries <= maxtries and np.isfinite(jitter):
try:
L = linalg.cholesky(A + np.eye(A.shape[0]) * jitter, lower=True)
return L
except:
jitter *= 10
finally:
num_tries += 1
raise linalg.LinAlgError("not positive definite, even with jitter.")
import traceback
try: raise
except:
logging.warning('\n'.join(['Added jitter of {:.10e}'.format(jitter),
' in '+traceback.format_list(traceback.extract_stack(limit=3)[-2:-1])[0][2:]]))
return L
0
Example 31
Project: scikit-image Source File: corner.py
def corner_fast(image, n=12, threshold=0.15):
"""Extract FAST corners for a given image.
Parameters
----------
image : 2D ndarray
Input image.
n : int
Minimum number of consecutive pixels out of 16 pixels on the circle
that should all be either brighter or darker w.r.t testpixel.
A point c on the circle is darker w.r.t test pixel p if
`Ic < Ip - threshold` and brighter if `Ic > Ip + threshold`. Also
stands for the n in `FAST-n` corner detector.
threshold : float
Threshold used in deciding whether the pixels on the circle are
brighter, darker or similar w.r.t. the test pixel. Decrease the
threshold when more corners are desired and vice-versa.
Returns
-------
response : ndarray
FAST corner response image.
References
----------
.. [1] Edward Rosten and Tom Drummond
"Machine Learning for high-speed corner detection",
http://www.edwardrosten.com/work/rosten_2006_machine.pdf
.. [2] Wikipedia, "Features from accelerated segment test",
https://en.wikipedia.org/wiki/Features_from_accelerated_segment_test
Examples
--------
>>> from skimage.feature import corner_fast, corner_peaks
>>> square = np.zeros((12, 12))
>>> square[3:9, 3:9] = 1
>>> square.astype(int)
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
>>> corner_peaks(corner_fast(square, 9), min_distance=1)
array([[3, 3],
[3, 8],
[8, 3],
[8, 8]])
"""
image = _prepare_grayscale_input_2D(image)
image = np.ascontiguousarray(image)
response = _corner_fast(image, n, threshold)
return response
0
Example 32
def load(self, array):
self.bind()
array = numpy.ravel(numpy.ascontiguousarray(array, dtype=self.dtype))
self.length = len(array)
self.buffer_data(self.itemsize * self.length, array.ctypes.data)
0
Example 33
Project: scipy Source File: mio4.py
def read_sparse_array(self, hdr):
''' Read and return sparse matrix type
Parameters
----------
hdr : ``VarHeader4`` instance
Returns
-------
arr : ``scipy.sparse.coo_matrix``
with dtype ``float`` and shape read from the sparse matrix data
Notes
-----
MATLAB 4 real sparse arrays are saved in a N+1 by 3 array format, where
N is the number of non-zero values. Column 1 values [0:N] are the
(1-based) row indices of the each non-zero value, column 2 [0:N] are the
column indices, column 3 [0:N] are the (real) values. The last values
[-1,0:2] of the rows, column indices are shape[0] and shape[1]
respectively of the output matrix. The last value for the values column
is a padding 0. mrows and ncols values from the header give the shape of
the stored matrix, here [N+1, 3]. Complex data is saved as a 4 column
matrix, where the fourth column contains the imaginary component; the
last value is again 0. Complex sparse data do *not* have the header
``imagf`` field set to True; the fact that the data are complex is only
detectable because there are 4 storage columns
'''
res = self.read_sub_array(hdr)
tmp = res[:-1,:]
dims = res[-1,0:2]
I = np.ascontiguousarray(tmp[:,0],dtype='intc') # fixes byte order also
J = np.ascontiguousarray(tmp[:,1],dtype='intc')
I -= 1 # for 1-based indexing
J -= 1
if res.shape[1] == 3:
V = np.ascontiguousarray(tmp[:,2],dtype='float')
else:
V = np.ascontiguousarray(tmp[:,2],dtype='complex')
V.imag = tmp[:,3]
return scipy.sparse.coo_matrix((V,(I,J)), dims)
0
Example 34
Project: attention-lvcsr Source File: server.py
def send_arrays(socket, arrays, stop=False):
"""Send NumPy arrays using the buffer interface and some metadata.
Parameters
----------
socket : :class:`zmq.Socket`
The socket to send data over.
arrays : list
A list of :class:`numpy.ndarray` to transfer.
stop : bool, optional
Instead of sending a series of NumPy arrays, send a JSON object
with a single `stop` key. The :func:`recv_arrays` will raise
``StopIteration`` when it receives this.
Notes
-----
The protocol is very simple: A single JSON object describing the array
format (using the same specification as ``.npy`` files) is sent first.
Subsequently the arrays are sent as bytestreams (through NumPy's
support of the buffering protocol).
"""
if arrays:
# The buffer protocol only works on contiguous arrays
arrays = [numpy.ascontiguousarray(array) for array in arrays]
if stop:
headers = {'stop': True}
socket.send_json(headers)
else:
headers = [header_data_from_array_1_0(array) for array in arrays]
socket.send_json(headers, zmq.SNDMORE)
for array in arrays[:-1]:
socket.send(array, zmq.SNDMORE)
socket.send(arrays[-1])
0
Example 35
def detect(self, image):
"""Detect oriented FAST keypoints along with the corresponding scale.
Parameters
----------
image : 2D array
Input image.
"""
assert_nD(image, 2)
pyramid = self._build_pyramid(image)
keypoints_list = []
orientations_list = []
scales_list = []
responses_list = []
for octave in range(len(pyramid)):
octave_image = np.ascontiguousarray(pyramid[octave])
keypoints, orientations, responses = \
self._detect_octave(octave_image)
keypoints_list.append(keypoints * self.downscale ** octave)
orientations_list.append(orientations)
scales_list.append(self.downscale ** octave
* np.ones(keypoints.shape[0], dtype=np.intp))
responses_list.append(responses)
keypoints = np.vstack(keypoints_list)
orientations = np.hstack(orientations_list)
scales = np.hstack(scales_list)
responses = np.hstack(responses_list)
if keypoints.shape[0] < self.n_keypoints:
self.keypoints = keypoints
self.scales = scales
self.orientations = orientations
self.responses = responses
else:
# Choose best n_keypoints according to Harris corner response
best_indices = responses.argsort()[::-1][:self.n_keypoints]
self.keypoints = keypoints[best_indices]
self.scales = scales[best_indices]
self.orientations = orientations[best_indices]
self.responses = responses[best_indices]
0
Example 36
Project: scipy Source File: mmio.py
def _parse_body(self, stream):
rows, cols, entries, format, field, symm = (self.rows, self.cols,
self.entries, self.format,
self.field, self.symmetry)
try:
from scipy.sparse import coo_matrix
except ImportError:
coo_matrix = None
dtype = self.DTYPES_BY_FIELD.get(field, None)
has_symmetry = self.has_symmetry
is_complex = field == self.FIELD_COMPLEX
is_skew = symm == self.SYMMETRY_SKEW_SYMMETRIC
is_herm = symm == self.SYMMETRY_HERMITIAN
is_pattern = field == self.FIELD_PATTERN
if format == self.FORMAT_ARRAY:
a = zeros((rows, cols), dtype=dtype)
line = 1
i, j = 0, 0
while line:
line = stream.readline()
if not line or line.startswith(b'%'):
continue
if is_complex:
aij = complex(*map(float, line.split()))
else:
aij = float(line)
a[i, j] = aij
if has_symmetry and i != j:
if is_skew:
a[j, i] = -aij
elif is_herm:
a[j, i] = conj(aij)
else:
a[j, i] = aij
if i < rows-1:
i = i + 1
else:
j = j + 1
if not has_symmetry:
i = 0
else:
i = j
if not (i in [0, j] and j == cols):
raise ValueError("Parse error, did not read all lines.")
elif format == self.FORMAT_COORDINATE and coo_matrix is None:
# Read sparse matrix to dense when coo_matrix is not available.
a = zeros((rows, cols), dtype=dtype)
line = 1
k = 0
while line:
line = stream.readline()
if not line or line.startswith(b'%'):
continue
l = line.split()
i, j = map(int, l[:2])
i, j = i-1, j-1
if is_complex:
aij = complex(*map(float, l[2:]))
else:
aij = float(l[2])
a[i, j] = aij
if has_symmetry and i != j:
if is_skew:
a[j, i] = -aij
elif is_herm:
a[j, i] = conj(aij)
else:
a[j, i] = aij
k = k + 1
if not k == entries:
ValueError("Did not read all entries")
elif format == self.FORMAT_COORDINATE:
# Read sparse COOrdinate format
if entries == 0:
# empty matrix
return coo_matrix((rows, cols), dtype=dtype)
try:
if not _is_fromfile_compatible(stream):
flat_data = fromstring(stream.read(), sep=' ')
else:
# fromfile works for normal files
flat_data = fromfile(stream, sep=' ')
except Exception:
# fallback - fromfile fails for some file-like objects
flat_data = fromstring(stream.read(), sep=' ')
# TODO use iterator (e.g. xreadlines) to avoid reading
# the whole file into memory
if is_pattern:
flat_data = flat_data.reshape(-1, 2)
I = ascontiguousarray(flat_data[:, 0], dtype='intc')
J = ascontiguousarray(flat_data[:, 1], dtype='intc')
V = ones(len(I), dtype='int8') # filler
elif is_complex:
flat_data = flat_data.reshape(-1, 4)
I = ascontiguousarray(flat_data[:, 0], dtype='intc')
J = ascontiguousarray(flat_data[:, 1], dtype='intc')
V = ascontiguousarray(flat_data[:, 2], dtype='complex')
V.imag = flat_data[:, 3]
else:
flat_data = flat_data.reshape(-1, 3)
I = ascontiguousarray(flat_data[:, 0], dtype='intc')
J = ascontiguousarray(flat_data[:, 1], dtype='intc')
V = ascontiguousarray(flat_data[:, 2], dtype='float')
I -= 1 # adjust indices (base 1 -> base 0)
J -= 1
if has_symmetry:
mask = (I != J) # off diagonal mask
od_I = I[mask]
od_J = J[mask]
od_V = V[mask]
I = concatenate((I, od_J))
J = concatenate((J, od_I))
if is_skew:
od_V *= -1
elif is_herm:
od_V = od_V.conjugate()
V = concatenate((V, od_V))
a = coo_matrix((V, (I, J)), shape=(rows, cols), dtype=dtype)
else:
raise NotImplementedError(format)
return a
0
Example 37
Project: scikit-image Source File: orb.py
def detect_and_extract(self, image):
"""Detect oriented FAST keypoints and extract rBRIEF descriptors.
Note that this is faster than first calling `detect` and then
`extract`.
Parameters
----------
image : 2D array
Input image.
"""
assert_nD(image, 2)
pyramid = self._build_pyramid(image)
keypoints_list = []
responses_list = []
scales_list = []
orientations_list = []
descriptors_list = []
for octave in range(len(pyramid)):
octave_image = np.ascontiguousarray(pyramid[octave])
keypoints, orientations, responses = \
self._detect_octave(octave_image)
if len(keypoints) == 0:
keypoints_list.append(keypoints)
responses_list.append(responses)
descriptors_list.append(np.zeros((0, 256), dtype=np.bool))
continue
descriptors, mask = self._extract_octave(octave_image, keypoints,
orientations)
keypoints_list.append(keypoints[mask] * self.downscale ** octave)
responses_list.append(responses[mask])
orientations_list.append(orientations[mask])
scales_list.append(self.downscale ** octave
* np.ones(keypoints.shape[0], dtype=np.intp))
descriptors_list.append(descriptors)
keypoints = np.vstack(keypoints_list)
responses = np.hstack(responses_list)
scales = np.hstack(scales_list)
orientations = np.hstack(orientations_list)
descriptors = np.vstack(descriptors_list).view(np.bool)
if keypoints.shape[0] < self.n_keypoints:
self.keypoints = keypoints
self.scales = scales
self.orientations = orientations
self.responses = responses
self.descriptors = descriptors
else:
# Choose best n_keypoints according to Harris corner response
best_indices = responses.argsort()[::-1][:self.n_keypoints]
self.keypoints = keypoints[best_indices]
self.scales = scales[best_indices]
self.orientations = orientations[best_indices]
self.responses = responses[best_indices]
self.descriptors = descriptors[best_indices]
0
Example 38
Project: sfepy Source File: mesh.py
def _set_io_data(self, coors, ngroups, conns, mat_ids, descs,
nodal_bcs=None):
"""
Set mesh data.
Parameters
----------
coors : array
Coordinates of mesh nodes.
ngroups : array
Node groups.
conns : list of arrays
The array of mesh elements (connectivities) for each element group.
mat_ids : list of arrays
The array of material ids for each element group.
descs: list of strings
The element type for each element group.
nodal_bcs : dict of arrays, optional
The nodes defining regions for boundary conditions referred
to by the dict keys in problem description files.
"""
ac = nm.ascontiguousarray
coors = ac(coors, dtype=nm.float64)
if ngroups is None:
ngroups = nm.zeros((coors.shape[0],), dtype=nm.int32)
self.descs = descs
self.nodal_bcs = get_default(nodal_bcs, {})
from sfepy.discrete.common.extmods.cmesh import CMesh
self.cmesh = CMesh.from_data(coors, ac(ngroups),
[ac(conn, dtype=nm.int32)
for conn in conns],
ac(nm.concatenate(mat_ids)), descs)
0
Example 39
Project: molecular-design-toolkit Source File: pyscf_interface.py
@compute.runsremotely(enable=force_remote)
def basis_values(mol, basis, coords, coeffs=None, positions=None):
""" Calculate the orbital's value at a position in space
Args:
mol (moldesign.Molecule): Molecule to attach basis set to
basis (moldesign.orbitals.BasisSet): set of basis functions
coords (Array[length]): List of coordinates (with shape ``(len(coords), 3)``)
coeffs (Vector): List of ao coefficients (optional; if not passed, all basis fn
values are returned)
Returns:
Array[length]: if ``coeffs`` is not passed, an array of basis fn values at each
coordinate. Otherwise, a list of orbital values at each coordinate
"""
from pyscf.dft import numint
# TODO: more than just create the basis by name ...
pmol = mol_to_pyscf(mol, basis=basis.basisname, positions=positions)
aovals = numint.eval_ao(pmol, np.ascontiguousarray(coords.value_in(u.bohr)))
if coeffs is None:
return aovals
else:
return aovals.dot(coeffs)
0
Example 40
Project: attention-lvcsr Source File: utils.py
def hash_from_ndarray(data):
"""
Return a hash from an ndarray.
It takes care of the data, shapes, strides and dtype.
"""
# We need to hash the shapes and strides as hash_from_code only hashes
# the data buffer. Otherwise, this will cause problem with shapes like:
# (1, 0) and (2, 0) and problem with inplace transpose.
# We also need to add the dtype to make the distinction between
# uint32 and int32 of zeros with the same shape and strides.
# python hash are not strong, so I always use md5 in order not to have a
# too long hash, I call it again on the concatenation of all parts.
if not data.flags["C_CONTIGUOUS"]:
# Version 1.7.1 and previous of NumPy allowed calling
# hash_from_code on an F-contiguous array, but more recent
# versions need a C-contiguous one.
data = numpy.ascontiguousarray(data)
return hash_from_code(hash_from_code(data) +
hash_from_code(str(data.shape)) +
hash_from_code(str(data.strides)) +
hash_from_code(str(data.dtype)))
0
Example 41
Project: scikit-image Source File: texture.py
def greycomatrix(image, distances, angles, levels=None, symmetric=False,
normed=False):
"""Calculate the grey-level co-occurrence matrix.
A grey level co-occurrence matrix is a histogram of co-occurring
greyscale values at a given offset over an image.
Parameters
----------
image : array_like
Integer typed input image. Only positive valued images are supported.
If type is other than uint8, the argument `levels` needs to be set.
distances : array_like
List of pixel pair distance offsets.
angles : array_like
List of pixel pair angles in radians.
levels : int, optional
The input image should contain integers in [0, `levels`-1],
where levels indicate the number of grey-levels counted
(typically 256 for an 8-bit image). This argument is required for
16-bit images or higher and is typically the maximum of the image.
As the output matrix is at least `levels` x `levels`, it might
be preferable to use binning of the input image rather than
large values for `levels`.
symmetric : bool, optional
If True, the output matrix `P[:, :, d, theta]` is symmetric. This
is accomplished by ignoring the order of value pairs, so both
(i, j) and (j, i) are accuemulated when (i, j) is encountered
for a given offset. The default is False.
normed : bool, optional
If True, normalize each matrix `P[:, :, d, theta]` by dividing
by the total number of accuemulated co-occurrences for the given
offset. The elements of the resulting matrix sum to 1. The
default is False.
Returns
-------
P : 4-D ndarray
The grey-level co-occurrence histogram. The value
`P[i,j,d,theta]` is the number of times that grey-level `j`
occurs at a distance `d` and at an angle `theta` from
grey-level `i`. If `normed` is `False`, the output is of
type uint32, otherwise it is float64. The dimensions are:
levels x levels x number of distances x number of angles.
References
----------
.. [1] The GLCM Tutorial Home Page,
http://www.fp.ucalgary.ca/mhallbey/tutorial.htm
.. [2] Pattern Recognition Engineering, Morton Nadler & Eric P.
Smith
.. [3] Wikipedia, http://en.wikipedia.org/wiki/Co-occurrence_matrix
Examples
--------
Compute 2 GLCMs: One for a 1-pixel offset to the right, and one
for a 1-pixel offset upwards.
>>> image = np.array([[0, 0, 1, 1],
... [0, 0, 1, 1],
... [0, 2, 2, 2],
... [2, 2, 3, 3]], dtype=np.uint8)
>>> result = greycomatrix(image, [1], [0, np.pi/4, np.pi/2, 3*np.pi/4],
... levels=4)
>>> result[:, :, 0, 0]
array([[2, 2, 1, 0],
[0, 2, 0, 0],
[0, 0, 3, 1],
[0, 0, 0, 1]], dtype=uint32)
>>> result[:, :, 0, 1]
array([[1, 1, 3, 0],
[0, 1, 1, 0],
[0, 0, 0, 2],
[0, 0, 0, 0]], dtype=uint32)
>>> result[:, :, 0, 2]
array([[3, 0, 2, 0],
[0, 2, 2, 0],
[0, 0, 1, 2],
[0, 0, 0, 0]], dtype=uint32)
>>> result[:, :, 0, 3]
array([[2, 0, 0, 0],
[1, 1, 2, 0],
[0, 0, 2, 1],
[0, 0, 0, 0]], dtype=uint32)
"""
assert_nD(image, 2)
assert_nD(distances, 1, 'distances')
assert_nD(angles, 1, 'angles')
image = np.ascontiguousarray(image)
image_max = image.max()
if np.issubdtype(image.dtype, np.float):
raise ValueError("Float images are not supported by greycomatrix. "
"Convert the image to an unsigned integer type.")
# for image type > 8bit, levels must be set.
if image.dtype not in (np.uint8, np.int8) and levels is None:
raise ValueError("The levels argument is required for data types "
"other than uint8. The resulting matrix will be at "
"least levels ** 2 in size.")
if np.issubdtype(image.dtype, np.signedinteger) and np.any(image < 0):
raise ValueError("Negative-valued images are not supported.")
if levels is None:
levels = 256
if image_max >= levels:
raise ValueError("The maximum grayscale value in the image should be "
"smaller than the number of levels.")
distances = np.ascontiguousarray(distances, dtype=np.float64)
angles = np.ascontiguousarray(angles, dtype=np.float64)
P = np.zeros((levels, levels, len(distances), len(angles)),
dtype=np.uint32, order='C')
# count co-occurences
_glcm_loop(image, distances, angles, levels, P)
# make each GLMC symmetric
if symmetric:
Pt = np.transpose(P, (1, 0, 2, 3))
P = P + Pt
# normalize each GLMC
if normed:
P = P.astype(np.float64)
glcm_sums = np.apply_over_axes(np.sum, P, axes=(0, 1))
glcm_sums[glcm_sums == 0] = 1
P /= glcm_sums
return P
0
Example 42
def __init__(self, name, geometry, order, init_context=True):
PolySpace.__init__(self, name, geometry, order)
g1d = Struct(n_vertex = 2,
dim = 1,
coors = self.bbox[:,0:1])
self.ps1d = LagrangeSimplexPolySpace('P_aux', g1d, order,
init_context=False)
self.nodes, self.nts, node_coors = self._define_nodes()
self.node_coors = nm.ascontiguousarray(node_coors)
self.n_nod = self.nodes.shape[0]
if init_context:
tdim = int(nm.sqrt(geometry.n_vertex))
self.eval_ctx = self.create_context(None, 0, 1e-15, 100, 1e-8,
tdim=tdim)
else:
self.eval_ctx = None
0
Example 43
def rgb2gray(rgb):
"""Compute luminance of an RGB image.
Parameters
----------
rgb : array_like
The image in RGB format, in a 3-D or 4-D array of shape
``(.., ..,[ ..,] 3)``, or in RGBA format with shape
``(.., ..,[ ..,] 4)``.
Returns
-------
out : ndarray
The luminance image - an array which is the same size as the input
array, but with the channel dimension removed.
Raises
------
ValueError
If `rgb2gray` is not a 3-D or 4-D arrays of shape
``(.., ..,[ ..,] 3)`` or ``(.., ..,[ ..,] 4)``.
References
----------
.. [1] http://www.poynton.com/PDFs/ColorFAQ.pdf
Notes
-----
The weights used in this conversion are calibrated for contemporary
CRT phosphors::
Y = 0.2125 R + 0.7154 G + 0.0721 B
If there is an alpha channel present, it is ignored.
Examples
--------
>>> from skimage.color import rgb2gray
>>> from skimage import data
>>> img = data.astronaut()
>>> img_gray = rgb2gray(img)
"""
if rgb.ndim == 2:
return np.ascontiguousarray(rgb)
rgb = _prepare_colorarray(rgb[..., :3])
gray = 0.2125 * rgb[..., 0]
gray[:] += 0.7154 * rgb[..., 1]
gray[:] += 0.0721 * rgb[..., 2]
return gray
0
Example 44
Project: scikit-image Source File: test_pil.py
def test_cmyk():
ref = imread(os.path.join(data_dir, 'color.png'))
img = Image.open(os.path.join(data_dir, 'color.png'))
img = img.convert('CMYK')
f = NamedTemporaryFile(suffix='.jpg')
fname = f.name
f.close()
img.save(fname)
try:
img.close()
except AttributeError: # `close` not available on PIL
pass
new = imread(fname)
ref_lab = rgb2lab(ref)
new_lab = rgb2lab(new)
for i in range(3):
newi = np.ascontiguousarray(new_lab[:, :, i])
refi = np.ascontiguousarray(ref_lab[:, :, i])
sim = ssim(refi, newi, dynamic_range=refi.max() - refi.min())
assert sim > 0.99
0
Example 45
def unique_rows(ar, return_index=False, return_inverse=False):
"""
Return unique rows of a two-dimensional array `ar`. The arguments follow
`numpy.unique()`.
"""
ar = nm.ascontiguousarray(ar)
# View the rows as a 1D structured array.
arv = ar.view(ar.shape[1] * [('', ar.dtype)])
out = nm.unique(arv, return_index=return_index,
return_inverse=return_inverse)
if isinstance(out, tuple):
uarv = out[0]
else:
uarv = out
# Restore the original dimensions.
uar = uarv.view(ar.dtype).reshape((-1, ar.shape[1]))
if isinstance(out, tuple):
out = (uar,) + out[1:]
else:
out = uar
return out
0
Example 46
Project: scikit-image Source File: _skeletonize_3d.py
def skeletonize_3d(img):
"""Compute the skeleton of a binary image.
Thinning is used to reduce each connected component in a binary image
to a single-pixel wide skeleton.
Parameters
----------
img : ndarray, 2D or 3D
A binary image containing the objects to be skeletonized. Zeros
represent background, nonzero values are foreground.
Returns
-------
skeleton : ndarray
The thinned image.
See also
--------
skeletonize, medial_axis
Notes
-----
The method of [Lee94]_ uses an octree data structure to examine a 3x3x3
neighborhood of a pixel. The algorithm proceeds by iteratively sweeping
over the image, and removing pixels at each iteration until the image
stops changing. Each iteration consists of two steps: first, a list of
candidates for removal is assembled; then pixels from this list are
rechecked sequentially, to better preserve connectivity of the image.
The algorithm this function implements is different from the algorithms
used by either `skeletonize` or `medial_axis`, thus for 2D images the
results produced by this function are generally different.
References
----------
.. [Lee94] T.-C. Lee, R.L. Kashyap and C.-N. Chu, Building skeleton models
via 3-D medial surface/axis thinning algorithms.
Computer Vision, Graphics, and Image Processing, 56(6):462-478, 1994.
"""
# make sure the image is 3D or 2D
if img.ndim < 2 or img.ndim > 3:
raise ValueError("skeletonize_3d can only handle 2D or 3D images; "
"got img.ndim = %s instead." % img.ndim)
img = np.ascontiguousarray(img)
img = img_as_ubyte(img, force_copy=False)
# make an in image 3D and pad it w/ zeros to simplify dealing w/ boundaries
# NB: careful here to not clobber the original *and* minimize copying
img_o = img
if img.ndim == 2:
img_o = img[np.newaxis, ...]
img_o = np.pad(img_o, pad_width=1, mode='constant')
# normalize to binary
maxval = img_o.max()
img_o[img_o != 0] = 1
# do the computation
img_o = np.asarray(_compute_thin_image(img_o))
# crop it back and restore the original intensity range
img_o = crop(img_o, crop_width=1)
if img.ndim == 2:
img_o = img_o[0]
img_o *= maxval
return img_o
0
Example 47
Project: warpedLMM Source File: linalg.py
def jitchol(A, maxtries=5):
A = np.ascontiguousarray(A)
L, info = lapack.dpotrf(A, lower=1)
if info == 0:
return L
else:
diagA = np.diag(A)
if np.any(diagA <= 0.):
raise linalg.LinAlgError, "not pd: non-positive diagonal elements"
jitter = diagA.mean() * 1e-6
while maxtries > 0 and np.isfinite(jitter):
try:
L = linalg.cholesky(A + np.eye(A.shape[0]) * jitter, lower=True)
except:
jitter *= 10
finally:
maxtries -= 1
raise linalg.LinAlgError, "not positive definite, even with jitter."
import traceback
try: raise
except:
logging.warning('\n'.join(['Added jitter of {:.10e}'.format(jitter),
' in '+traceback.format_list(traceback.extract_stack(limit=2)[-2:-1])[0][2:]]))
import ipdb;ipdb.set_trace()
return L
0
Example 48
def ascarray(a, name=''):
if not a.flags.contiguous:
logger.debug("converting %s array %s to C order", a.shape, name)
a = numpy.ascontiguousarray(a)
return a
0
Example 49
def detect(self, image):
"""Detect CENSURE keypoints along with the corresponding scale.
Parameters
----------
image : 2D ndarray
Input image.
"""
# (1) First we generate the required scales on the input grayscale
# image using a bi-level filter and stack them up in `filter_response`.
# (2) We then perform Non-Maximal suppression in 3 x 3 x 3 window on
# the filter_response to suppress points that are neither minima or
# maxima in 3 x 3 x 3 neighbourhood. We obtain a boolean ndarray
# `feature_mask` containing all the minimas and maximas in
# `filter_response` as True.
# (3) Then we suppress all the points in the `feature_mask` for which
# the corresponding point in the image at a particular scale has the
# ratio of principal curvatures greater than `line_threshold`.
# (4) Finally, we remove the border keypoints and return the keypoints
# along with its corresponding scale.
assert_nD(image, 2)
num_scales = self.max_scale - self.min_scale
image = np.ascontiguousarray(_prepare_grayscale_input_2D(image))
# Generating all the scales
filter_response = _filter_image(image, self.min_scale, self.max_scale,
self.mode)
# Suppressing points that are neither minima or maxima in their
# 3 x 3 x 3 neighborhood to zero
minimas = minimum_filter(filter_response, (3, 3, 3)) == filter_response
maximas = maximum_filter(filter_response, (3, 3, 3)) == filter_response
feature_mask = minimas | maximas
feature_mask[filter_response < self.non_max_threshold] = False
for i in range(1, num_scales):
# sigma = (window_size - 1) / 6.0, so the window covers > 99% of
# the kernel's distribution
# window_size = 7 + 2 * (min_scale - 1 + i)
# Hence sigma = 1 + (min_scale - 1 + i)/ 3.0
_suppress_lines(feature_mask[:, :, i], image,
(1 + (self.min_scale + i - 1) / 3.0),
self.line_threshold)
rows, cols, scales = np.nonzero(feature_mask[..., 1:num_scales])
keypoints = np.column_stack([rows, cols])
scales = scales + self.min_scale + 1
if self.mode == 'dob':
self.keypoints = keypoints
self.scales = scales
return
cuemulative_mask = np.zeros(keypoints.shape[0], dtype=np.bool)
if self.mode == 'octagon':
for i in range(self.min_scale + 1, self.max_scale):
c = (OCTAGON_OUTER_SHAPE[i - 1][0] - 1) // 2 \
+ OCTAGON_OUTER_SHAPE[i - 1][1]
cuemulative_mask |= (
_mask_border_keypoints(image.shape, keypoints, c)
& (scales == i))
elif self.mode == 'star':
for i in range(self.min_scale + 1, self.max_scale):
c = STAR_SHAPE[STAR_FILTER_SHAPE[i - 1][0]] \
+ STAR_SHAPE[STAR_FILTER_SHAPE[i - 1][0]] // 2
cuemulative_mask |= (
_mask_border_keypoints(image.shape, keypoints, c)
& (scales == i))
self.keypoints = keypoints[cuemulative_mask]
self.scales = scales[cuemulative_mask]
0
Example 50
def unique_rows(ar):
"""Remove repeated rows from a 2D array.
In particular, if given an array of coordinates of shape
(Npoints, Ndim), it will remove repeated points.
Parameters
----------
ar : 2-D ndarray
The input array.
Returns
-------
ar_out : 2-D ndarray
A copy of the input array with repeated rows removed.
Raises
------
ValueError : if `ar` is not two-dimensional.
Notes
-----
The function will generate a copy of `ar` if it is not
C-contiguous, which will negatively affect performance for large
input arrays.
Examples
--------
>>> ar = np.array([[1, 0, 1],
... [0, 1, 0],
... [1, 0, 1]], np.uint8)
>>> unique_rows(ar)
array([[0, 1, 0],
[1, 0, 1]], dtype=uint8)
"""
if ar.ndim != 2:
raise ValueError("unique_rows() only makes sense for 2D arrays, "
"got %dd" % ar.ndim)
# the view in the next line only works if the array is C-contiguous
ar = np.ascontiguousarray(ar)
# np.unique() finds identical items in a raveled array. To make it
# see each row as a single item, we create a view of each row as a
# byte string of length itemsize times number of columns in `ar`
ar_row_view = ar.view('|S%d' % (ar.itemsize * ar.shape[1]))
_, unique_row_indices = np.unique(ar_row_view, return_index=True)
ar_out = ar[unique_row_indices]
return ar_out