Here are the examples of the python api numpy.swapaxes taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
54 Examples
3
Example 1
Project: shapelets Source File: ClassMS.py
def SaveVis(self,vis=None,Col="CORRECTED_DATA",spw=0,DoPrint=True):
if vis==None:
vis=self.data
if DoPrint: print " Writting data in column %s"%ModColor.Str(Col,col="green")
table_all=table(self.MSName,ack=False,readonly=False)
if self.swapped:
visout=np.swapaxes(vis[spw*self.Nchan:(spw+1)*self.Nchan],0,1)
else:
visout=vis
table_all.putcol(Col,visout,self.ROW0,self.nRowRead)
table_all.close()
3
Example 2
def _swapaxes(self, axis1, axis2):
""" Swap the axis axis1 and axis2 of the data array and reorder the
affine matrix to stay consistent with the data
See also
--------
self.xyz_ordered
"""
if (axis1 > 2) or (axis2 > 2):
raise ValueError('Can swap axis only on spatial axis. '
'Use np.swapaxes of the data array.')
reordered_data = np.swapaxes(self.get_data(), axis1, axis2)
new_affine = self.affine
order = np.array((0, 1, 2, 3))
order[axis1] = axis2
order[axis2] = axis1
new_affine = new_affine.T[order].T
return VolumeImg(reordered_data, new_affine, self.world_space,
metadata=self.metadata)
3
Example 3
Project: scipy Source File: test_basic.py
def test_shape_axes_argument(self):
small_x = [[1,2,3],[4,5,6],[7,8,9]]
large_x1 = array([[1,2,3,0],
[4,5,6,0],
[7,8,9,0],
[0,0,0,0]])
# Disable tests with shape and axes of different lengths
# y = fftn(small_x,shape=(4,4),axes=(-1,))
# for i in range(4):
# assert_array_almost_equal (y[i],fft(large_x1[i]))
# y = fftn(small_x,shape=(4,4),axes=(-2,))
# for i in range(4):
# assert_array_almost_equal (y[:,i],fft(large_x1[:,i]))
y = fftn(small_x,shape=(4,4),axes=(-2,-1))
assert_array_almost_equal(y,fftn(large_x1))
y = fftn(small_x,shape=(4,4),axes=(-1,-2))
assert_array_almost_equal(y,swapaxes(
fftn(swapaxes(large_x1,-1,-2)),-1,-2))
3
Example 4
Project: scipy Source File: realtransforms.py
def _eval_fun(f, tmp, n, axis, nm, overwrite_x):
if axis == -1 or axis == len(tmp.shape) - 1:
return f(tmp, n, nm, overwrite_x)
tmp = np.swapaxes(tmp, axis, -1)
tmp = f(tmp, n, nm, overwrite_x)
return np.swapaxes(tmp, axis, -1)
3
Example 5
Project: shapelets Source File: ClassMS.py
def ZeroFlagSave(self,spw=0):
self.flag_all.fill(0)
if self.swapped:
flagout=np.swapaxes(self.flag_all[spw*self.Nchan:(spw+1)*self.Nchan],0,1)
else:
flagout=self.flag_all
t=table(self.MSName,readonly=False,ack=False)
t.putcol("FLAG",flagout)
t.close()
3
Example 6
def eval(self, t_in):
"""
Evaluate the spline at the points in t_in, which must be an array
with values in [0,1]
returns and np array with the corresponding points
"""
splines = self.splines
tknots = self.tknots
index = tknots.searchsorted(t_in, side='left') - 1
index = index.clip(0, len(splines) - 1)
to_calc = splines[index]
ax, bx, cx, dx, tx = np.swapaxes(to_calc, 0, 1)
t_r = t_in[:, np.newaxis] - tx
out = ax + t_r * (bx + t_r * (cx + t_r * dx))
return out
3
Example 7
Project: neural-doodle Source File: doodle.py
def finalize_image(self, image, resolution):
"""Based on the output of the neural network, convert it into an image format that can be saved
to disk -- shuffling dimensions as appropriate.
"""
image = np.swapaxes(np.swapaxes(image[::-1], 0, 1), 1, 2)
image = np.clip(image, 0, 255).astype('uint8')
return scipy.misc.imresize(image, resolution, interp='bicubic')
3
Example 8
def eval_spline(splines, tknots, t_in):
"""
Evaluate the spline at the points in t_in, which must be an array
with values in [0,1]
returns and np array with the corresponding points
"""
index = tknots.searchsorted(t_in, side='left') - 1
index = index.clip(0, len(splines) - 1)
to_calc = splines[index]
ax, bx, cx, dx, tx = np.swapaxes(to_calc, 0, 1)
t_r = t_in[:, np.newaxis] - tx
out = ax + t_r * (bx + t_r * (cx + t_r * dx))
return out
3
Example 9
def roll(self):
" xxx rotate stuff - destroys biomes"
self.root_tag.pop('Biomes', None)
self._fakeEntities = None
self._Blocks = swapaxes(self._Blocks, 2, 0)[:, :, ::-1] # x=y; y=-x
self.root_tag["Data"].value = swapaxes(self.root_tag["Data"].value, 2, 0)[:, :, ::-1]
self._update_shape()
3
Example 10
def _raw_fft(x, n, axis, direction, overwrite_x, work_function):
""" Internal auxiliary function for fft, ifft, rfft, irfft."""
if n is None:
n = x.shape[axis]
elif n != x.shape[axis]:
x, copy_made = _fix_shape(x,n,axis)
overwrite_x = overwrite_x or copy_made
if n < 1:
raise ValueError("Invalid number of FFT data points "
"(%d) specified." % n)
if axis == -1 or axis == len(x.shape)-1:
r = work_function(x,n,direction,overwrite_x=overwrite_x)
else:
x = swapaxes(x, axis, -1)
r = work_function(x,n,direction,overwrite_x=overwrite_x)
r = swapaxes(r, axis, -1)
return r
3
Example 11
Project: rpigl Source File: glesutils.py
@staticmethod
def from_surface(surface):
"""Create texture data from a Pygame Surface."""
if surface.get_flags() & pygame.SRCALPHA:
desired_depth = 32
get_array = _get_array_from_alpha_surface
convert = surface.convert_alpha
else:
desired_depth = 24
get_array = pygame.surfarray.pixels3d
convert = surface.convert
if surface.get_bitsize() != desired_depth:
surface = convert(desired_depth, surface.get_flags())
ar = numpy.swapaxes(get_array(surface), 0, 1)
return TextureData.from_ndarray(ar)
3
Example 12
def transpose(X, ndim=1):
"""
Transpose the matrix.
"""
for n in range(ndim):
X = np.swapaxes(X, -1-n, -1-ndim-n)
return X
3
Example 13
def __call__( self, domainArray ):
"""Projects the n-d slicing 'domainArray' to 2 dimensions"""
assert domainArray.ndim == self.domainDim, "ndim %d != %d (domainArray.shape=%r, domainDim=%r)" % (domainArray.ndim, self.domainDim, domainArray.shape, self.domainDim)
slicing = self.domainDim*[0]
slicing[self._abscissa], slicing[self._ordinate] = slice(None,None), slice(None,None)
projectedArray = domainArray[slicing]
assert projectedArray.ndim == 2, "dim %d != 2" % projectedArray.ndim
if self.handednessSwitched():
projectedArray = np.swapaxes(projectedArray,0,1)
return projectedArray
3
Example 14
Project: deep_recommend_system Source File: matrix_solve_ls_op_test.py
def BatchRegularizedLeastSquares(matrices, rhss, l2_regularization=0.0):
# A numpy implementation of regularized least squares solver using
# the normal equations.
matrix_dims = matrices.shape
matrices_transposed = np.swapaxes(matrices, -2, -1)
rows = matrix_dims[-2]
cols = matrix_dims[-1]
if rows >= cols:
preconditioner = l2_regularization * np.identity(cols)
gramian = BatchMatMul(matrices_transposed, matrices) + preconditioner
inverse = np.linalg.inv(gramian)
left_pseudo_inverse = BatchMatMul(inverse, matrices_transposed)
return BatchMatMul(left_pseudo_inverse, rhss)
else:
preconditioner = l2_regularization * np.identity(rows)
gramian = BatchMatMul(matrices, matrices_transposed) + preconditioner
inverse = np.linalg.inv(gramian)
right_pseudo_inverse = BatchMatMul(matrices_transposed, inverse)
return BatchMatMul(right_pseudo_inverse, rhss)
3
Example 15
def prepare_image(self, image):
"""Given an image loaded from disk, turn it into a representation compatible with the model.
The format is (b,c,y,x) with batch=1 for a single image, channels=3 for RGB, and y,x matching
the resolution.
"""
image = np.swapaxes(np.swapaxes(image, 1, 2), 0, 1)[::-1, :, :]
image = image.astype(np.float32) - self.pixel_mean
return image[np.newaxis]
3
Example 16
def rotateLeft(self):
MCLevel.rotateLeft(self)
self.Data = swapaxes(self.Data, 1, 0)[:, ::-1, :] # x=y; y=-x
torchRotation = array([0, 4, 3, 1, 2, 5,
6, 7,
8, 9, 10, 11, 12, 13, 14, 15])
torchIndexes = (self.Blocks == self.materials.Torch.ID)
log.info(u"Rotating torches: {0}".format(len(torchIndexes.nonzero()[0])))
self.Data[torchIndexes] = torchRotation[self.Data[torchIndexes]]
2
Example 17
def get_chunk(self, x, z):
x,z = self.unrotate(x,z)
chunk_data = dict(super(RotatedRegionSet, self).get_chunk(x,z))
newsections = []
for section in chunk_data['Sections']:
section = dict(section)
newsections.append(section)
for arrayname in ['Blocks', 'Data', 'SkyLight', 'BlockLight']:
array = section[arrayname]
# Since the anvil change, arrays are arranged with axes Y,Z,X
# numpy.rot90 always rotates the first two axes, so for it to
# work, we need to temporarily move the X axis to the 0th axis.
array = numpy.swapaxes(array, 0,2)
array = numpy.rot90(array, self.north_dir)
array = numpy.swapaxes(array, 0,2)
section[arrayname] = array
chunk_data['Sections'] = newsections
# same as above, for biomes (Z/X indexed)
biomes = numpy.swapaxes(chunk_data['Biomes'], 0, 1)
biomes = numpy.rot90(biomes, self.north_dir)
chunk_data['Biomes'] = numpy.swapaxes(biomes, 0, 1)
return chunk_data
0
Example 18
def rotateLeft(self):
self.Blocks = swapaxes(self.Blocks, 1, 0)[:, ::-1, :] # x=z; z=-x
pass
0
Example 19
def roll(self):
self.Blocks = swapaxes(self.Blocks, 2, 0)[:, :, ::-1] # x=y; y=-x
pass
0
Example 20
@property
def Blocks(self):
return swapaxes(self._Blocks, 0, 2)
0
Example 21
@property
def Biomes(self):
return swapaxes(self.root_tag["Biomes"].value, 0, 1)
0
Example 22
Project: ba-dls-deepspeech Source File: test.py
def test(model, test_fn, datagen, mb_size=16, conv_context=11,
conv_border_mode='valid', conv_stride=2):
""" Testing routine for speech-models
Params:
model (keras.model): Constructed keras model
test_fn (theano.function): A theano function that calculates the cost
over a test set
datagen (DataGenerator)
mb_size (int): Size of each minibatch
conv_context (int): Convolution context
conv_border_mode (str): Convolution border mode
conv_stride (int): Convolution stride
Returns:
test_cost (float): Average test cost over the whole test set
"""
avg_cost = 0.0
i = 0
for batch in datagen.iterate_test(mb_size):
inputs = batch['x']
labels = batch['y']
input_lengths = batch['input_lengths']
label_lengths = batch['label_lengths']
ground_truth = batch['texts']
# Due to convolution, the number of timesteps of the output
# is different from the input length. Calculate the resulting
# timesteps
output_lengths = [conv_output_length(l, conv_context,
conv_border_mode, conv_stride)
for l in input_lengths]
predictions, ctc_cost = test_fn([inputs, output_lengths, labels,
label_lengths, True])
predictions = np.swapaxes(predictions, 0, 1)
for i, prediction in enumerate(predictions):
print ("Truth: {}, Prediction: {}"
.format(ground_truth[i], argmax_decode(prediction)))
avg_cost += ctc_cost
i += 1
return avg_cost / i
0
Example 23
Project: MCEdit-Unified Source File: schematic.py
def rotateLeft(self):
self._fakeEntities = None
self._Blocks = swapaxes(self._Blocks, 1, 2)[:, ::-1, :] # x=z; z=-x
if "Biomes" in self.root_tag:
self.root_tag["Biomes"].value = swapaxes(self.root_tag["Biomes"].value, 0, 1)[::-1, :]
self.root_tag["Data"].value = swapaxes(self.root_tag["Data"].value, 1, 2)[:, ::-1, :] # x=z; z=-x
self._update_shape()
blockrotation.RotateLeft(self.Blocks, self.Data)
log.info(u"Relocating entities...")
for entity in self.Entities:
for p in "Pos", "Motion":
if p == "Pos":
zBase = self.Length
else:
zBase = 0.0
newX = entity[p][2].value
newZ = zBase - entity[p][0].value
entity[p][0].value = newX
entity[p][2].value = newZ
entity["Rotation"][0].value -= 90.0
if entity["id"].value in ("Painting", "ItemFrame"):
x, z = entity["TileX"].value, entity["TileZ"].value
newx = z
newz = self.Length - x - 1
entity["TileX"].value, entity["TileZ"].value = newx, newz
facing = entity.get("Facing", entity.get("Direction"))
if facing is None:
dirFacing = entity.get("Dir")
if dirFacing is not None:
if dirFacing.value == 0:
dirFacing.value = 2
elif dirFacing.value == 2:
dirFacing.value = 0
facing = dirFacing
else:
raise Exception("None of tags Facing/Direction/Dir found in entity %s during rotating - %r" % (entity["id"].value, entity))
facing.value = (facing.value - 1) % 4
for tileEntity in self.TileEntities:
if 'x' not in tileEntity:
continue
newX = tileEntity["z"].value
newZ = self.Length - tileEntity["x"].value - 1
tileEntity["x"].value = newX
tileEntity["z"].value = newZ
if "TileTicks" in self.root_tag:
for tileTick in self.TileTicks:
newX = tileTick["z"].value
newZ = tileTick["x"].value
tileTick["x"].value = newX
tileTick["z"].value = newZ
0
Example 24
Project: MCEdit-Unified Source File: schematic.py
def roll(self):
" xxx rotate stuff - destroys biomes"
self.root_tag.pop('Biomes', None)
self._fakeEntities = None
self._Blocks = swapaxes(self._Blocks, 2, 0)[:, :, ::-1] # x=y; y=-x
self.root_tag["Data"].value = swapaxes(self.root_tag["Data"].value, 2, 0)[:, :, ::-1]
self._update_shape()
blockrotation.Roll(self.Blocks, self.Data)
log.info(u"N/S Roll: Relocating entities...")
for i, entity in enumerate(self.Entities):
newX = self.Width - entity["Pos"][1].value
newY = entity["Pos"][0].value
entity["Pos"][0].value = newX
entity["Pos"][1].value = newY
newX = entity["Motion"][1].value
newY = -entity["Motion"][0].value
entity["Motion"][0].value = newX
entity["Motion"][1].value = newY
# I think this is right
# Although rotation isn't that important as most entities can't rotate and mobs
# don't serialize rotation.
newX = entity["Rotation"][1].value
newY = -entity["Rotation"][0].value
entity["Rotation"][0].value = newX
entity["Rotation"][1].value = newY
if entity["id"].value in ("Painting", "ItemFrame"):
newX = self.Width - entity["TileY"].value - 1
newY = entity["TileX"].value
entity["TileX"].value = newX
entity["TileY"].value = newY
for tileEntity in self.TileEntities:
newX = self.Width - tileEntity["y"].value - 1
newY = tileEntity["x"].value
tileEntity["x"].value = newX
tileEntity["y"].value = newY
if hasattr(self, "TileTicks"):
for tileTick in self.TileTicks:
newX = self.Width - tileTick["y"].value - 1
newY = tileTick["x"].value
tileTick["x"].value = newX
tileTick["y"].value = newY
0
Example 25
@property
def Data(self):
return swapaxes(self.rootTag["Data"].value, 0, 2)
0
Example 26
Project: hessianfree Source File: rnnet.py
def load_GPU_data(self):
"""Load data for the current epoch onto GPU."""
from pycuda import gpuarray
def split_axes(array, n=1):
# split a multidimensional array into a corresponding list of lists
# along the first n axes (this is used so that array.__getitem__
# isn't called repeatedly, as it is somewhat expensive for
# gpuarrays)
if n == 1:
return [a for a in array]
return [split_axes(a, n - 1) for a in array]
# clear out old data (this would happen eventually on its own, but by
# doing it first we make sure there is room on the GPU before
# creating new arrays)
if hasattr(self, "GPU_W"):
del self.GPU_W
del self.GPU_activations
del self.GPU_d_activations
del self.GPU_d2_loss
del self.GPU_tmp_space
del self.GPU_states
del self.GPU_errors
del self.GPU_deltas
self.GPU_W = gpuarray.to_gpu(self.W)
# rearrange GPU data so that signal is the first axis (so
# that each time step is a single block of memory in GPU_calc_G)
self.GPU_activations = [
split_axes(gpuarray.to_gpu(np.ascontiguousarray(
np.swapaxes(a, 0, 1))), 1)
for a in self.activations]
self.GPU_d_activations = [
split_axes(gpuarray.to_gpu(np.ascontiguousarray(
np.rollaxis(np.swapaxes(a, 0, 1), -1, 1))), 2)
if self.layers[i].stateful else
split_axes(gpuarray.to_gpu(np.ascontiguousarray(
np.swapaxes(a, 0, 1))), 1)
for i, a in enumerate(self.d_activations)]
self.GPU_d2_loss = [
split_axes(gpuarray.to_gpu(np.ascontiguousarray(
np.swapaxes(a, 0, 1))), 1)
if a is not None else None for a in self.d2_loss]
self.GPU_tmp_space = [split_axes(gpuarray.empty((a.shape[1],
a.shape[0],
a.shape[2]),
self.dtype), 1)
for a in self.activations]
# pre-allocate calc_G arrays
batch_size = self.inputs.shape[0]
self.GPU_states = [[gpuarray.empty((batch_size, self.shape[i]),
dtype=self.dtype) for _ in range(2)]
if l.stateful else None
for i, l in enumerate(self.layers)]
self.GPU_errors = [gpuarray.empty((batch_size, l),
dtype=self.dtype)
for l in self.shape]
self.GPU_deltas = [gpuarray.empty((batch_size, l),
dtype=self.dtype)
for l in self.shape]
0
Example 27
Project: pymclevel Source File: indev.py
def __init__(self, root_tag=None, filename=""):
self.Width = 0
self.Height = 0
self.Length = 0
self.Blocks = array([], "uint8")
self.Data = array([], "uint8")
self.Spawn = (0, 0, 0)
self.filename = filename
if root_tag:
self.root_tag = root_tag
mapTag = root_tag["Map"]
self.Width = mapTag["Width"].value
self.Length = mapTag["Length"].value
self.Height = mapTag["Height"].value
mapTag["Blocks"].value.shape = (self.Height, self.Length, self.Width)
self.Blocks = swapaxes(mapTag["Blocks"].value, 0, 2)
mapTag["Data"].value.shape = (self.Height, self.Length, self.Width)
self.Data = swapaxes(mapTag["Data"].value, 0, 2)
self.BlockLight = self.Data & 0xf
self.Data >>= 4
self.Spawn = [mapTag[Spawn][i].value for i in range(3)]
if "Entities" not in root_tag:
root_tag["Entities"] = nbt.TAG_List()
self.Entities = root_tag["Entities"]
# xxx fixup Motion and Pos to match infdev format
def numbersToDoubles(ent):
for attr in "Motion", "Pos":
if attr in ent:
ent[attr] = nbt.TAG_List([nbt.TAG_Double(t.value) for t in ent[attr]])
for ent in self.Entities:
numbersToDoubles(ent)
if "TileEntities" not in root_tag:
root_tag["TileEntities"] = nbt.TAG_List()
self.TileEntities = root_tag["TileEntities"]
# xxx fixup TileEntities positions to match infdev format
for te in self.TileEntities:
pos = te["Pos"].value
(x, y, z) = self.decodePos(pos)
TileEntity.setpos(te, (x, y, z))
localPlayerList = [tag for tag in root_tag["Entities"] if tag['id'].value == 'LocalPlayer']
if len(localPlayerList) == 0: # omen doesn't make a player entity
playerTag = nbt.TAG_Compound()
playerTag['id'] = nbt.TAG_String('LocalPlayer')
playerTag['Pos'] = nbt.TAG_List([nbt.TAG_Float(0.), nbt.TAG_Float(64.), nbt.TAG_Float(0.)])
playerTag['Rotation'] = nbt.TAG_List([nbt.TAG_Float(0.), nbt.TAG_Float(45.)])
self.LocalPlayer = playerTag
else:
self.LocalPlayer = localPlayerList[0]
else:
log.info(u"Creating new Indev levels is not yet implemented.!")
raise ValueError("Can't do that yet")
0
Example 28
Project: MCEdit-Unified Source File: indev.py
def saveToFile(self, filename=None):
if filename is None:
filename = self.filename
if filename is None:
log.warn(u"Attempted to save an unnamed file in place")
return # you fool!
self.Data <<= 4
self.Data |= (self.BlockLight & 0xf)
self.Blocks = swapaxes(self.Blocks, 0, 2)
self.Data = swapaxes(self.Data, 0, 2)
mapTag = nbt.TAG_Compound()
mapTag["Width"] = nbt.TAG_Short(self.Width)
mapTag["Height"] = nbt.TAG_Short(self.Height)
mapTag["Length"] = nbt.TAG_Short(self.Length)
mapTag["Blocks"] = nbt.TAG_Byte_Array(self.Blocks)
mapTag["Data"] = nbt.TAG_Byte_Array(self.Data)
self.Blocks = swapaxes(self.Blocks, 0, 2)
self.Data = swapaxes(self.Data, 0, 2)
mapTag[Spawn] = nbt.TAG_List([nbt.TAG_Short(i) for i in self.Spawn])
self.root_tag["Map"] = mapTag
self.Entities.append(self.LocalPlayer)
# fix up Entities imported from Alpha worlds
def numbersToFloats(ent):
for attr in "Motion", "Pos":
if attr in ent:
ent[attr] = nbt.TAG_List([nbt.TAG_Double(t.value) for t in ent[attr]])
for ent in self.Entities:
numbersToFloats(ent)
# fix up TileEntities imported from Alpha worlds.
for ent in self.TileEntities:
if "Pos" not in ent and all(c in ent for c in 'xyz'):
ent["Pos"] = nbt.TAG_Int(self.encodePos(ent['x'].value, ent['y'].value, ent['z'].value))
# output_file = gzip.open(self.filename, "wb", compresslevel=1)
try:
os.rename(filename, filename + ".old")
except Exception:
pass
try:
self.root_tag.save(filename)
except:
os.rename(filename + ".old", filename)
try:
os.remove(filename + ".old")
except Exception:
pass
self.Entities.remove(self.LocalPlayer)
self.BlockLight = self.Data & 0xf
self.Data >>= 4
0
Example 29
Project: bayespy Source File: misc.py
def symm(X):
"""
Make X symmetric.
"""
return 0.5 * (X + np.swapaxes(X, -1, -2))
0
Example 30
def ifft(x, n=None, axis=-1, overwrite_x=False):
"""
Return discrete inverse Fourier transform of real or complex sequence.
The returned complex array contains ``y(0), y(1),..., y(n-1)`` where
``y(j) = (x * exp(2*pi*sqrt(-1)*j*np.arange(n)/n)).mean()``.
Parameters
----------
x : array_like
Transformed data to invert.
n : int, optional
Length of the inverse Fourier transform. If ``n < x.shape[axis]``,
`x` is truncated. If ``n > x.shape[axis]``, `x` is zero-padded.
The default results in ``n = x.shape[axis]``.
axis : int, optional
Axis along which the ifft's are computed; the default is over the
last axis (i.e., ``axis=-1``).
overwrite_x : bool, optional
If True, the contents of `x` can be destroyed; the default is False.
Returns
-------
ifft : ndarray of floats
The inverse discrete Fourier transform.
See Also
--------
fft : Forward FFT
Notes
-----
This function is most efficient when `n` is a power of two, and least
efficient when `n` is prime.
If the data type of `x` is real, a "real IFFT" algorithm is automatically
used, which roughly halves the computation time.
"""
tmp = _asfarray(x)
try:
work_function = _DTYPE_TO_FFT[tmp.dtype]
except KeyError:
raise ValueError("type %s is not supported" % tmp.dtype)
if not (istype(tmp, numpy.complex64) or istype(tmp, numpy.complex128)):
overwrite_x = 1
overwrite_x = overwrite_x or _datacopied(tmp, x)
if n is None:
n = tmp.shape[axis]
elif n != tmp.shape[axis]:
tmp, copy_made = _fix_shape(tmp,n,axis)
overwrite_x = overwrite_x or copy_made
if n < 1:
raise ValueError("Invalid number of FFT data points "
"(%d) specified." % n)
if axis == -1 or axis == len(tmp.shape) - 1:
return work_function(tmp,n,-1,1,overwrite_x)
tmp = swapaxes(tmp, axis, -1)
tmp = work_function(tmp,n,-1,1,overwrite_x)
return swapaxes(tmp, axis, -1)
0
Example 31
@property
def Data(self):
return swapaxes(self.root_tag["Data"].value, 0, 2)
0
Example 32
Project: deep_recommend_system Source File: rnn_test.py
def _testStackBidirectionalDynamicRNN(self, use_gpu, use_shape,
use_state_tuple):
with self.test_session(use_gpu=use_gpu, graph=tf.Graph()) as sess:
input_value, inputs, outputs, state_fw, state_bw, sequence_length = (
self._createStackBidirectionalDynamicRNN(use_gpu, use_shape,
use_state_tuple))
tf.global_variables_initializer().run()
# Run with pre-specified sequence length of 2, 3
out, s_fw, s_bw = sess.run([outputs, state_fw, state_bw],
feed_dict={inputs[0]: input_value,
sequence_length: [2, 3]})
# Since the forward and backward LSTM cells were initialized with the
# same parameters, the forward and backward states of the first layer has
# to be the same.
# For the next layers, since the input is a concat of forward and backward
# outputs of the previous layers the symmetry is broken and the following
# states and outputs differ.
# We cannot access the intermediate values between layers but we can
# check that the forward and backward states of the first layer match.
self.assertAllClose(s_fw[0], s_bw[0])
out = np.swapaxes(out, 0, 1)
# If outputs are not concat between layers the output of the forward
# and backward would be the same but symmetric.
# Check that is not the case.
# Due to depth concatenation (as num_units=3 for both RNNs):
# - forward output: out[][][depth] for 0 <= depth < 3
# - backward output: out[][][depth] for 4 <= depth < 6
# First sequence in batch is length=2
# Check that the time=0 forward output is not equal to time=1 backward.
self.assertNotEqual(out[0][0][0], out[1][0][3])
self.assertNotEqual(out[0][0][1], out[1][0][4])
self.assertNotEqual(out[0][0][2], out[1][0][5])
# Check that the time=1 forward output is not equal to time=0 backward.
self.assertNotEqual(out[1][0][0], out[0][0][3])
self.assertNotEqual(out[1][0][1], out[0][0][4])
self.assertNotEqual(out[1][0][2], out[0][0][5])
# Second sequence in batch is length=3
# Check that the time=0 forward output is not equal to time=2 backward.
self.assertNotEqual(out[0][1][0], out[2][1][3])
self.assertNotEqual(out[0][1][1], out[2][1][4])
self.assertNotEqual(out[0][1][2], out[2][1][5])
# Check that the time=1 forward output is not equal to time=1 backward.
self.assertNotEqual(out[1][1][0], out[1][1][3])
self.assertNotEqual(out[1][1][1], out[1][1][4])
self.assertNotEqual(out[1][1][2], out[1][1][5])
# Check that the time=2 forward output is not equal to time=0 backward.
self.assertNotEqual(out[2][1][0], out[0][1][3])
self.assertNotEqual(out[2][1][1], out[0][1][4])
self.assertNotEqual(out[2][1][2], out[0][1][5])
0
Example 33
def imread(fname, as_grey=False, plugin=None, flatten=None,
**plugin_args):
"""Load an image from file.
Parameters
----------
fname : string
Image file name, e.g. ``test.jpg`` or URL.
as_grey : bool
If True, convert color images to grey-scale (64-bit floats).
Images that are already in grey-scale format are not converted.
plugin : str
Name of plugin to use. By default, the different plugins are
tried (starting with the Python Imaging Library) until a suitable
candidate is found. If not given and fname is a tiff file, the
tifffile plugin will be used.
Other Parameters
----------------
flatten : bool
Backward compatible keyword, superseded by `as_grey`.
Returns
-------
img_array : ndarray
The different colour bands/channels are stored in the
third dimension, such that a grey-image is MxN, an
RGB-image MxNx3 and an RGBA-image MxNx4.
Other parameters
----------------
plugin_args : keywords
Passed to the given plugin.
"""
# Backward compatibility
if flatten is not None:
as_grey = flatten
if plugin is None and hasattr(fname, 'lower'):
if fname.lower().endswith(('.tiff', '.tif')):
plugin = 'tifffile'
with file_or_url_context(fname) as fname:
img = call_plugin('imread', fname, plugin=plugin, **plugin_args)
if not hasattr(img, 'ndim'):
return img
if img.ndim > 2:
if img.shape[-1] not in (3, 4) and img.shape[-3] in (3, 4):
img = np.swapaxes(img, -1, -3)
img = np.swapaxes(img, -2, -3)
if as_grey:
img = rgb2grey(img)
return img
0
Example 34
def _get_data(self):
if self.transposed:
return swapaxes(self._data, 0, 1)
else:
return self._data
0
Example 35
def rotateLeft(self):
self._fakeEntities = None
self._Blocks = swapaxes(self._Blocks, 1, 2)[:, ::-1, :] # x=z; z=-x
if "Biomes" in self.root_tag:
self.root_tag["Biomes"].value = swapaxes(self.root_tag["Biomes"].value, 0, 1)[::-1, :]
self.root_tag["Data"].value = swapaxes(self.root_tag["Data"].value, 1, 2)[:, ::-1, :] # x=z; z=-x
self._update_shape()
blockrotation.RotateLeft(self.Blocks, self.Data)
log.info(u"Relocating entities...")
for entity in self.Entities:
for p in "Pos", "Motion":
if p == "Pos":
zBase = self.Length
else:
zBase = 0.0
newX = entity[p][2].value
newZ = zBase - entity[p][0].value
entity[p][0].value = newX
entity[p][2].value = newZ
entity["Rotation"][0].value -= 90.0
if entity["id"].value in ("Painting", "ItemFrame"):
x, z = entity["TileX"].value, entity["TileZ"].value
newx = z
newz = self.Length - x - 1
entity["TileX"].value, entity["TileZ"].value = newx, newz
entity["Dir"].value = (entity["Dir"].value + 1) % 4
for tileEntity in self.TileEntities:
if not 'x' in tileEntity:
continue
newX = tileEntity["z"].value
newZ = self.Length - tileEntity["x"].value - 1
tileEntity["x"].value = newX
tileEntity["z"].value = newZ
0
Example 36
Project: chaco Source File: image_data_test_case.py
def test_get_data_transposed(self):
myarray = arange(15).reshape(5, 3, 1)
data_source = ImageData(data=myarray, transposed=True)
assert_array_equal(swapaxes(myarray, 0, 1), data_source.get_data())
0
Example 37
def reorder(self, a): return np.swapaxes(a, axis1=self.axis1, axis2=self.axis2)
def unique_reorder_id(self): return (self.a.shape, self.axis1, self.axis2)
0
Example 38
def _transpose(data):
return tuple(np.swapaxes(array,0,1) for array in data)
0
Example 39
@property
def Biomes(self):
return swapaxes(self.rootTag["Biomes"].value, 0, 1)
0
Example 40
Project: scipy Source File: test_basic.py
def test_axes_argument(self):
# plane == ji_plane, x== kji_space
plane1 = [[1,2,3],[4,5,6],[7,8,9]]
plane2 = [[10,11,12],[13,14,15],[16,17,18]]
plane3 = [[19,20,21],[22,23,24],[25,26,27]]
ki_plane1 = [[1,2,3],[10,11,12],[19,20,21]]
ki_plane2 = [[4,5,6],[13,14,15],[22,23,24]]
ki_plane3 = [[7,8,9],[16,17,18],[25,26,27]]
jk_plane1 = [[1,10,19],[4,13,22],[7,16,25]]
jk_plane2 = [[2,11,20],[5,14,23],[8,17,26]]
jk_plane3 = [[3,12,21],[6,15,24],[9,18,27]]
kj_plane1 = [[1,4,7],[10,13,16],[19,22,25]]
kj_plane2 = [[2,5,8],[11,14,17],[20,23,26]]
kj_plane3 = [[3,6,9],[12,15,18],[21,24,27]]
ij_plane1 = [[1,4,7],[2,5,8],[3,6,9]]
ij_plane2 = [[10,13,16],[11,14,17],[12,15,18]]
ij_plane3 = [[19,22,25],[20,23,26],[21,24,27]]
ik_plane1 = [[1,10,19],[2,11,20],[3,12,21]]
ik_plane2 = [[4,13,22],[5,14,23],[6,15,24]]
ik_plane3 = [[7,16,25],[8,17,26],[9,18,27]]
ijk_space = [jk_plane1,jk_plane2,jk_plane3]
ikj_space = [kj_plane1,kj_plane2,kj_plane3]
jik_space = [ik_plane1,ik_plane2,ik_plane3]
jki_space = [ki_plane1,ki_plane2,ki_plane3]
kij_space = [ij_plane1,ij_plane2,ij_plane3]
x = array([plane1,plane2,plane3])
assert_array_almost_equal(fftn(x),fftn(x,axes=(-3,-2,-1))) # kji_space
assert_array_almost_equal(fftn(x),fftn(x,axes=(0,1,2)))
y = fftn(x,axes=(2,1,0)) # ijk_space
assert_array_almost_equal(swapaxes(y,-1,-3),fftn(ijk_space))
y = fftn(x,axes=(2,0,1)) # ikj_space
assert_array_almost_equal(swapaxes(swapaxes(y,-1,-3),
-1,-2),
fftn(ikj_space))
y = fftn(x,axes=(1,2,0)) # jik_space
assert_array_almost_equal(swapaxes(swapaxes(y,-1,-3),
-3,-2),
fftn(jik_space))
y = fftn(x,axes=(1,0,2)) # jki_space
assert_array_almost_equal(swapaxes(y,-2,-3),fftn(jki_space))
y = fftn(x,axes=(0,2,1)) # kij_space
assert_array_almost_equal(swapaxes(y,-2,-1),
fftn(kij_space))
y = fftn(x,axes=(-2,-1)) # ji_plane
assert_array_almost_equal(fftn(plane1),y[0])
assert_array_almost_equal(fftn(plane2),y[1])
assert_array_almost_equal(fftn(plane3),y[2])
y = fftn(x,axes=(1,2)) # ji_plane
assert_array_almost_equal(fftn(plane1),y[0])
assert_array_almost_equal(fftn(plane2),y[1])
assert_array_almost_equal(fftn(plane3),y[2])
y = fftn(x,axes=(-3,-2)) # kj_plane
assert_array_almost_equal(fftn(x[:,:,0]),y[:,:,0])
assert_array_almost_equal(fftn(x[:,:,1]),y[:,:,1])
assert_array_almost_equal(fftn(x[:,:,2]),y[:,:,2])
y = fftn(x,axes=(-3,-1)) # ki_plane
assert_array_almost_equal(fftn(x[:,0,:]),y[:,0,:])
assert_array_almost_equal(fftn(x[:,1,:]),y[:,1,:])
assert_array_almost_equal(fftn(x[:,2,:]),y[:,2,:])
y = fftn(x,axes=(-1,-2)) # ij_plane
assert_array_almost_equal(fftn(ij_plane1),swapaxes(y[0],-2,-1))
assert_array_almost_equal(fftn(ij_plane2),swapaxes(y[1],-2,-1))
assert_array_almost_equal(fftn(ij_plane3),swapaxes(y[2],-2,-1))
y = fftn(x,axes=(-1,-3)) # ik_plane
assert_array_almost_equal(fftn(ik_plane1),swapaxes(y[:,0,:],-1,-2))
assert_array_almost_equal(fftn(ik_plane2),swapaxes(y[:,1,:],-1,-2))
assert_array_almost_equal(fftn(ik_plane3),swapaxes(y[:,2,:],-1,-2))
y = fftn(x,axes=(-2,-3)) # jk_plane
assert_array_almost_equal(fftn(jk_plane1),swapaxes(y[:,:,0],-1,-2))
assert_array_almost_equal(fftn(jk_plane2),swapaxes(y[:,:,1],-1,-2))
assert_array_almost_equal(fftn(jk_plane3),swapaxes(y[:,:,2],-1,-2))
y = fftn(x,axes=(-1,)) # i_line
for i in range(3):
for j in range(3):
assert_array_almost_equal(fft(x[i,j,:]),y[i,j,:])
y = fftn(x,axes=(-2,)) # j_line
for i in range(3):
for j in range(3):
assert_array_almost_equal(fft(x[i,:,j]),y[i,:,j])
y = fftn(x,axes=(0,)) # k_line
for i in range(3):
for j in range(3):
assert_array_almost_equal(fft(x[:,i,j]),y[:,i,j])
y = fftn(x,axes=()) # point
assert_array_almost_equal(y,x)
0
Example 41
Project: pymclevel Source File: indev.py
def saveToFile(self, filename=None):
if filename is None:
filename = self.filename
if filename is None:
log.warn(u"Attempted to save an unnamed file in place")
return # you fool!
self.Data <<= 4
self.Data |= (self.BlockLight & 0xf)
self.Blocks = swapaxes(self.Blocks, 0, 2)
self.Data = swapaxes(self.Data, 0, 2)
mapTag = nbt.TAG_Compound()
mapTag["Width"] = nbt.TAG_Short(self.Width)
mapTag["Height"] = nbt.TAG_Short(self.Height)
mapTag["Length"] = nbt.TAG_Short(self.Length)
mapTag["Blocks"] = nbt.TAG_Byte_Array(self.Blocks)
mapTag["Data"] = nbt.TAG_Byte_Array(self.Data)
self.Blocks = swapaxes(self.Blocks, 0, 2)
self.Data = swapaxes(self.Data, 0, 2)
mapTag[Spawn] = nbt.TAG_List([nbt.TAG_Short(i) for i in self.Spawn])
self.root_tag["Map"] = mapTag
self.Entities.append(self.LocalPlayer)
# fix up Entities imported from Alpha worlds
def numbersToFloats(ent):
for attr in "Motion", "Pos":
if attr in ent:
ent[attr] = nbt.TAG_List([nbt.TAG_Double(t.value) for t in ent[attr]])
for ent in self.Entities:
numbersToFloats(ent)
# fix up TileEntities imported from Alpha worlds.
for ent in self.TileEntities:
if "Pos" not in ent and all(c in ent for c in 'xyz'):
ent["Pos"] = nbt.TAG_Int(self.encodePos(ent['x'].value, ent['y'].value, ent['z'].value))
# output_file = gzip.open(self.filename, "wb", compresslevel=1)
try:
os.rename(filename, filename + ".old")
except Exception:
pass
try:
self.root_tag.save(filename)
except:
os.rename(filename + ".old", filename)
try:
os.remove(filename + ".old")
except Exception:
pass
self.Entities.remove(self.LocalPlayer)
self.BlockLight = self.Data & 0xf
self.Data >>= 4
0
Example 42
Project: attention-lvcsr Source File: test_blocksparse.py
def test_sparseblockgemvF(self):
"""
Test the fortan order for W (which can happen in the grad for some
graphs).
"""
b = tensor.fmatrix()
W = tensor.ftensor4()
h = tensor.ftensor3()
iIdx = tensor.imatrix()
oIdx = tensor.imatrix()
o = self.gemv_op(b.take(oIdx, axis=0),
tensor.DimShuffle((False, False, False, False),
(0, 1, 3, 2))
(tensor.as_tensor_variable(W)),
h, iIdx, oIdx)
f = theano.function([W, h, iIdx, b, oIdx], o, mode=self.mode)
W_val, h_val, iIdx_val, b_val, oIdx_val = \
BlockSparse_Gemv_and_Outer.gemv_data()
th_out = f(numpy.swapaxes(W_val, 2, 3), h_val, iIdx_val, b_val,
oIdx_val)
ref_out = BlockSparse_Gemv_and_Outer.gemv_numpy(
b_val.take(oIdx_val, axis=0), W_val, h_val, iIdx_val, oIdx_val)
utt.assert_allclose(ref_out, th_out)
0
Example 43
def get_fargs(self, mat, vvar, svar,
mode=None, term_mode=None, diff_var=None, **kwargs):
sym_mode = False if mat.shape[-2] == mat.shape[-1] > 1 else True
if not sym_mode:
sh = mat.shape
# the gradient given by 'self.get' is transposed
mat = nm.swapaxes(mat, 2, 3)
mat = mat.reshape(sh[:2] + (sh[2]**2, 1))
if self.mode == 'grad':
qp_var, qp_name = svar, 'val'
else:
if sym_mode:
qp_var, qp_name = vvar, 'cauchy_strain'
else:
qp_var, qp_name = vvar, 'grad'
if mode == 'weak':
vvg, _ = self.get_mapping(vvar)
svg, _ = self.get_mapping(svar)
if diff_var is None:
val_qp = self.get(qp_var, qp_name)
if qp_name == 'grad':
sh = val_qp.shape
val_qp = val_qp.reshape(sh[:2] + (sh[2]**2, 1))
fmode = 0
else:
val_qp = nm.array([0], ndmin=4, dtype=nm.float64)
fmode = 1
return 1.0, val_qp, mat, svg, vvg, fmode
elif mode == 'eval':
vvg, _ = self.get_mapping(vvar)
if sym_mode:
strain = self.get(vvar, 'cauchy_strain')
else:
strain = self.get(vvar, 'grad')
sh = strain.shape
strain = strain.reshape(sh[:2] + (sh[2]**2, 1))
pval = self.get(svar, 'val')
return 1.0, pval, strain, mat, vvg
else:
raise ValueError('unsupported evaluation mode in %s! (%s)'
% (self.name, mode))
0
Example 44
@Cache_this(limit=3, ignore_args=(0,2,3,4))
def _psiDerivativecomputations(self, kern, dL_dpsi0, dL_dpsi1, dL_dpsi2, Z, variational_posterior):
# resolve the requirement of dL_dpsi2 to be symmetric
if len(dL_dpsi2.shape)==2: dL_dpsi2 = (dL_dpsi2+dL_dpsi2.T)/2
else: dL_dpsi2 = (dL_dpsi2+ np.swapaxes(dL_dpsi2, 1,2))/2
variance, lengthscale = kern.variance, kern.lengthscale
from ....util.linalg_gpu import sum_axis
ARD = (len(lengthscale)!=1)
N,M,Q = self.get_dimensions(Z, variational_posterior)
psi1_gpu = self.gpuCache['psi1_gpu']
psi2n_gpu = self.gpuCache['psi2n_gpu']
l_gpu = self.gpuCache['l_gpu']
Z_gpu = self.gpuCache['Z_gpu']
mu_gpu = self.gpuCache['mu_gpu']
S_gpu = self.gpuCache['S_gpu']
dvar_gpu = self.gpuCache['dvar_gpu']
dl_gpu = self.gpuCache['dl_gpu']
dZ_gpu = self.gpuCache['dZ_gpu']
dmu_gpu = self.gpuCache['dmu_gpu']
dS_gpu = self.gpuCache['dS_gpu']
grad_l_gpu = self.gpuCache['grad_l_gpu']
grad_mu_gpu = self.gpuCache['grad_mu_gpu']
grad_S_gpu = self.gpuCache['grad_S_gpu']
if self.GPU_direct:
dL_dpsi1_gpu = dL_dpsi1
dL_dpsi2_gpu = dL_dpsi2
dL_dpsi0_sum = dL_dpsi0.get().sum() #gpuarray.sum(dL_dpsi0).get()
else:
dL_dpsi1_gpu = self.gpuCache['dL_dpsi1_gpu']
dL_dpsi2_gpu = self.gpuCache['dL_dpsi2_gpu']
dL_dpsi1_gpu.set(np.asfortranarray(dL_dpsi1))
dL_dpsi2_gpu.set(np.asfortranarray(dL_dpsi2))
dL_dpsi0_sum = dL_dpsi0.sum()
self.reset_derivative()
# t=self.g_psi1compDer(dvar_gpu,dl_gpu,dZ_gpu,dmu_gpu,dS_gpu,dL_dpsi1_gpu,psi1_gpu, np.float64(variance),l_gpu,Z_gpu,mu_gpu,S_gpu, np.int32(N), np.int32(M), np.int32(Q), block=(self.threadnum,1,1), grid=(self.blocknum,1),time_kernel=True)
# print 'g_psi1compDer '+str(t)
# t=self.g_psi2compDer(dvar_gpu,dl_gpu,dZ_gpu,dmu_gpu,dS_gpu,dL_dpsi2_gpu,psi2n_gpu, np.float64(variance),l_gpu,Z_gpu,mu_gpu,S_gpu, np.int32(N), np.int32(M), np.int32(Q), block=(self.threadnum,1,1), grid=(self.blocknum,1),time_kernel=True)
# print 'g_psi2compDer '+str(t)
self.g_psi1compDer.prepared_call((self.blocknum,1),(self.threadnum,1,1),dvar_gpu.gpudata,dl_gpu.gpudata,dZ_gpu.gpudata,dmu_gpu.gpudata,dS_gpu.gpudata,dL_dpsi1_gpu.gpudata,psi1_gpu.gpudata, np.float64(variance),l_gpu.gpudata,Z_gpu.gpudata,mu_gpu.gpudata,S_gpu.gpudata, np.int32(N), np.int32(M), np.int32(Q))
self.g_psi2compDer.prepared_call((self.blocknum,1),(self.threadnum,1,1),dvar_gpu.gpudata,dl_gpu.gpudata,dZ_gpu.gpudata,dmu_gpu.gpudata,dS_gpu.gpudata,dL_dpsi2_gpu.gpudata,psi2n_gpu.gpudata, np.float64(variance),l_gpu.gpudata,Z_gpu.gpudata,mu_gpu.gpudata,S_gpu.gpudata, np.int32(N), np.int32(M), np.int32(Q))
dL_dvar = dL_dpsi0_sum + dvar_gpu.get().sum()#gpuarray.sum(dvar_gpu).get()
sum_axis(grad_mu_gpu,dmu_gpu,N*Q,self.blocknum)
dL_dmu = grad_mu_gpu.get()
sum_axis(grad_S_gpu,dS_gpu,N*Q,self.blocknum)
dL_dS = grad_S_gpu.get()
dL_dZ = dZ_gpu.get()
if ARD:
sum_axis(grad_l_gpu,dl_gpu,Q,self.blocknum)
dL_dlengscale = grad_l_gpu.get()
else:
dL_dlengscale = dl_gpu.get().sum() #gpuarray.sum(dl_gpu).get()
return dL_dvar, dL_dlengscale, dL_dZ, dL_dmu, dL_dS
0
Example 45
def getBatch(self, dataset, batch_pointer, is_train):
"""
Inputs:
dataset - tuples of (wav file, transcribed_text)
batch_pointer - start point in dataset from where to take the batch
is_train - training mode (to choose which pipe to use)
Returns:
input_feat_vecs, input_feat_vec_lengths, target_lengths,
target_labels, target_indices
"""
input_feat_vecs = []
input_feat_vec_lengths = []
target_lengths = []
target_labels = []
target_indices = []
batch_counter = 0
while batch_counter < self.batch_size:
file_text = dataset[batch_pointer]
batch_pointer += 1
if batch_pointer == dataset.__len__():
batch_pointer = 0
# Process the audio file to get the input
feat_vec, original_feat_vec_length = self.audio_processor.processFLACAudio(file_text[0])
# Process the label to get the output
# Labels len does not need to be always the same as for input, don't need padding
try:
labels = self.getStrLabels(file_text[1])
except:
# Incorrect label
print("Incorrect label for {0} ({1})".format(file_text[0], file_text[1]))
continue
# Check sizes
if (len(labels) > self.max_target_seq_length) or (original_feat_vec_length > self.max_input_seq_length):
# If either input or output vector is too long we shouldn't take this sample
print("Warning - sample too long : {0} (input : {1} / text : {2})".format(file_text[0],
original_feat_vec_length, len(labels)))
continue
assert len(labels) <= self.max_target_seq_length
assert len(feat_vec) <= self.max_input_seq_length
# Add input to inputs matrix and unpadded or cut size to dedicated vector
input_feat_vecs.append(feat_vec)
input_feat_vec_lengths.append(min(original_feat_vec_length, self.max_input_seq_length))
# Compute sparse tensor for labels
indices = [[batch_counter, i] for i in range(len(labels))]
target_indices += indices
target_labels += labels
target_lengths.append(len(labels))
batch_counter += 1
input_feat_vecs = np.swapaxes(input_feat_vecs, 0, 1)
if is_train and self.train_conn is not None:
self.train_conn.send([input_feat_vecs, input_feat_vec_lengths,
target_lengths, target_labels, target_indices, batch_pointer])
elif not is_train and self.test_conn is not None:
self.test_conn.send([input_feat_vecs, input_feat_vec_lengths,
target_lengths, target_labels, target_indices, batch_pointer])
else:
return [input_feat_vecs, input_feat_vec_lengths,
target_lengths, target_labels, target_indices, batch_pointer]
0
Example 46
def setImage(self, image=None, **kwds):
if image is not None and self.__transpose is True:
image = np.swapaxes(image, 0, 1)
return ImageItem.setImage(self, image, **kwds)
0
Example 47
Project: PRST Source File: __init__.py
def rlencode(A, axis=0):
"""
Compute run length encoding of array A along axis.
Synopsis:
A, n = rlencode(A)
A, n = rlencode(A, axis)
Arguments:
A (np.ndarray): Array to be encoded.
axis (Optional[int]): Axis of A where run length encoding is done.
Default value: axis=0
Example (default axis):
>>> A = np.array([
... [1, 2, 3, 4],
... [1, 2, 3, 4],
... [3, 4, 5, 6],
... [3, 3, 3, 3],
... [3, 3, 4, 5],
... [3, 3, 4, 5]])
>>> A, n = rlencode(A, 0)
>>> print(A)
[[1 2 3 4]
[3 4 5 6]
[3 3 3 3]
[3 3 4 5]]
>>> print(n)
[2 1 1 2]
Example (j-axis):
>>> A = np.array([
... [1,1,3,3,3,3],
... [2,2,4,3,3,3],
... [3,3,5,3,4,4],
... [4,4,6,3,5,5]])
>>> A, n = rlencode(A, 1)
>>> print(A)
[[1 3 3 3]
[2 4 3 3]
[3 5 3 4]
[4 6 3 5]]
>>> print(n)
[2 1 1 2]
"""
# Let the relevant axis be the first axis
B = np.swapaxes(A, 0, axis)
# Flatten axes that are normal to the encoding axis
B = B.reshape([B.shape[0],-1])
# Pick indices where the next index is different
i = np.append(np.where(np.any(B[:-1] != B[1:], axis=1)), B.shape[0]-1)
# Find the number of repetitions
n = np.diff(np.insert(i, 0, -1))
# Pick necessary slices of the encoding axis
return A.take(i, axis=axis), n
0
Example 48
def fft(x, n=None, axis=-1, overwrite_x=False):
"""
Return discrete Fourier transform of real or complex sequence.
The returned complex array contains ``y(0), y(1),..., y(n-1)`` where
``y(j) = (x * exp(-2*pi*sqrt(-1)*j*np.arange(n)/n)).sum()``.
Parameters
----------
x : array_like
Array to Fourier transform.
n : int, optional
Length of the Fourier transform. If ``n < x.shape[axis]``, `x` is
truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
default results in ``n = x.shape[axis]``.
axis : int, optional
Axis along which the fft's are computed; the default is over the
last axis (i.e., ``axis=-1``).
overwrite_x : bool, optional
If True, the contents of `x` can be destroyed; the default is False.
Returns
-------
z : complex ndarray
with the elements::
[y(0),y(1),..,y(n/2),y(1-n/2),...,y(-1)] if n is even
[y(0),y(1),..,y((n-1)/2),y(-(n-1)/2),...,y(-1)] if n is odd
where::
y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k* 2*pi/n), j = 0..n-1
Note that ``y(-j) = y(n-j).conjugate()``.
See Also
--------
ifft : Inverse FFT
rfft : FFT of a real sequence
Notes
-----
The packing of the result is "standard": If ``A = fft(a, n)``, then
``A[0]`` contains the zero-frequency term, ``A[1:n/2]`` contains the
positive-frequency terms, and ``A[n/2:]`` contains the negative-frequency
terms, in order of decreasingly negative frequency. So for an 8-point
transform, the frequencies of the result are [0, 1, 2, 3, -4, -3, -2, -1].
To rearrange the fft output so that the zero-frequency component is
centered, like [-4, -3, -2, -1, 0, 1, 2, 3], use `fftshift`.
For `n` even, ``A[n/2]`` contains the sum of the positive and
negative-frequency terms. For `n` even and `x` real, ``A[n/2]`` will
always be real.
This function is most efficient when `n` is a power of two, and least
efficient when `n` is prime.
If the data type of `x` is real, a "real FFT" algorithm is automatically
used, which roughly halves the computation time. To increase efficiency
a little further, use `rfft`, which does the same calculation, but only
outputs half of the symmetrical spectrum. If the data is both real and
symmetrical, the `dct` can again double the efficiency, by generating
half of the spectrum from half of the signal.
Examples
--------
>>> from scipy.fftpack import fft, ifft
>>> x = np.arange(5)
>>> np.allclose(fft(ifft(x)), x, atol=1e-15) # within numerical accuracy.
True
"""
tmp = _asfarray(x)
try:
work_function = _DTYPE_TO_FFT[tmp.dtype]
except KeyError:
raise ValueError("type %s is not supported" % tmp.dtype)
if not (istype(tmp, numpy.complex64) or istype(tmp, numpy.complex128)):
overwrite_x = 1
overwrite_x = overwrite_x or _datacopied(tmp, x)
if n is None:
n = tmp.shape[axis]
elif n != tmp.shape[axis]:
tmp, copy_made = _fix_shape(tmp,n,axis)
overwrite_x = overwrite_x or copy_made
if n < 1:
raise ValueError("Invalid number of FFT data points "
"(%d) specified." % n)
if axis == -1 or axis == len(tmp.shape) - 1:
return work_function(tmp,n,1,0,overwrite_x)
tmp = swapaxes(tmp, axis, -1)
tmp = work_function(tmp,n,1,0,overwrite_x)
return swapaxes(tmp, axis, -1)
0
Example 49
def T(X):
"""
Transpose the matrix.
"""
return np.swapaxes(X, -1, -2)
0
Example 50
Project: MCEdit-Unified Source File: indev.py
def __init__(self, root_tag=None, filename=""):
self.Width = 0
self.Height = 0
self.Length = 0
self.Blocks = array([], "uint8")
self.Data = array([], "uint8")
self.Spawn = (0, 0, 0)
self.filename = filename
if root_tag:
self.root_tag = root_tag
mapTag = root_tag["Map"]
self.Width = mapTag["Width"].value
self.Length = mapTag["Length"].value
self.Height = mapTag["Height"].value
mapTag["Blocks"].value.shape = (self.Height, self.Length, self.Width)
self.Blocks = swapaxes(mapTag["Blocks"].value, 0, 2)
mapTag["Data"].value.shape = (self.Height, self.Length, self.Width)
self.Data = swapaxes(mapTag["Data"].value, 0, 2)
self.BlockLight = self.Data & 0xf
self.Data >>= 4
self.Spawn = [mapTag[Spawn][i].value for i in range(3)]
if "Entities" not in root_tag:
root_tag["Entities"] = nbt.TAG_List()
self.Entities = root_tag["Entities"]
# xxx fixup Motion and Pos to match infdev format
def numbersToDoubles(ent):
for attr in "Motion", "Pos":
if attr in ent:
ent[attr] = nbt.TAG_List([nbt.TAG_Double(t.value) for t in ent[attr]])
for ent in self.Entities:
numbersToDoubles(ent)
if "TileEntities" not in root_tag:
root_tag["TileEntities"] = nbt.TAG_List()
self.TileEntities = root_tag["TileEntities"]
# xxx fixup TileEntities positions to match infdev format
for te in self.TileEntities:
pos = te["Pos"].value
(x, y, z) = self.decodePos(pos)
TileEntity.setpos(te, (x, y, z))
localPlayerList = [tag for tag in root_tag["Entities"] if tag['id'].value == 'LocalPlayer']
if len(localPlayerList) == 0: # omen doesn't make a player entity
playerTag = nbt.TAG_Compound()
playerTag['id'] = nbt.TAG_String('LocalPlayer')
playerTag['Pos'] = nbt.TAG_List([nbt.TAG_Float(0.), nbt.TAG_Float(64.), nbt.TAG_Float(0.)])
playerTag['Rotation'] = nbt.TAG_List([nbt.TAG_Float(0.), nbt.TAG_Float(45.)])
self.LocalPlayer = playerTag
else:
self.LocalPlayer = localPlayerList[0]
else:
log.info(u"Creating new Indev levels is not yet implemented.!")
raise ValueError("Can't do that yet")