本文整理汇总了Python中numpy.flip函数的典型用法代码示例。如果您正苦于以下问题:Python flip函数的具体用法?Python flip怎么用?Python flip使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了flip函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: postprocess_buffer
def postprocess_buffer(self, buffer):
if not self.init:
raise IOError("Hardware need to be initialized for buffer preparation!")
ACTIVATION_BITS = self.network_json['parameters']['ACTIVATION_BITS']
if (ACTIVATION_BITS > 8):
raise IOError("prepare buffer algorithm cannot handle more than 8 activation bits!")
dim = buffer.shape[0]
channels = buffer.shape[2]
ele= math.ceil((channels * ACTIVATION_BITS) / 8)
#delete entries that we don't need
buffer = np.delete(buffer, np.s_[ele:], 2)
#unpack bits
buffer = np.unpackbits(buffer, 2)
#fix endianness in 8 bits blocks
buffer = buffer.reshape(dim,dim,-1,8)
buffer = np.flip(buffer, 3)
#delete bits that are left over
if ((channels * ACTIVATION_BITS) % 8) != 0:
buffer = np.delete(buffer, np.s_[channels * ACTIVATION_BITS:], 2)
#reshape to that every channel value has its own value
buffer = buffer.reshape(dim,dim,-1, ACTIVATION_BITS)
#fix endianness of the single values
buffer = np.flip(buffer,3)
#packbits will append zeros at the end, so put them in front
buffer = np.pad(buffer, [(0,0),(0,0),(0,0),((8-ACTIVATION_BITS),0)], mode='constant')
#pack the bits to values again
buffer = np.packbits(buffer,3)
#fc layers are not intereseted in the shape
return buffer.flatten().astype(np.float32)
示例2: convolution
def convolution(matrix, filter):
#flip filter
filter = np.flip(filter, axis=0)
filter = np.flip(filter, axis=1)
print filter.shape
print matrix.shape
if filter.shape[1] % 2 == 0:
return convolution_1d(matrix, filter)
#gather shape/dimensions
rows = matrix.shape[0]
cols = matrix.shape[1]
#first zero pad the matrix, but only if filter is of odd length
start_index = 0 # by default, non padded matrices will start at 0,0
col_end_index = cols # same logic for end index
row_end_index = rows
if filter.shape[0] % 2 == 1:
matrix = np.pad(matrix, pad_width=1, mode='constant', constant_values=0)
start_index = 1 # if zero padded, then start index is going to be 1,1
col_end_index += 1
row_end_index += 1
filtered_matrix = np.zeros((rows, cols))
for x in range (start_index, col_end_index):
for y in range (start_index, row_end_index):
#calculate filter math
sum = 0
for i in range(filter.shape[0]):
for j in range(filter.shape[1]):
#print 'Matrix value: ' + str(matrix[x-i+start_index][y+j-1])
#print 'filter value: ' + str(filter[i][j])
sum += np.multiply(matrix[x-i+start_index][y+j-1],filter[i][j])
filtered_matrix[x-start_index][y-start_index] = sum
return filtered_matrix
示例3: set_fft_form
def set_fft_form(self, fft_form, copy=False):
if copy:
R=self.copy()
else:
R=self
if self.fft_form==fft_form:
return R
fft_form_orig = self.fft_form
if R.Fourier:
if fft_form_orig in ['r']:
nval=np.flip(R.val[...,1:].conj(),axis=-1)
for ax in self.axes[:-1]:
N,F = np.split(nval, [1], axis=ax)
nval=np.concatenate((N, np.flip(F, axis=ax)), axis=ax)
if R.N[-1] % 2 == 0:
nval=nval[...,1:]
val=np.concatenate((R.val,nval), axis=-1)
R.val=1./np.prod(R.N)*val # fft_form=0
if fft_form in ['c']:
R.val=np.fft.fftshift(R.val, axes=R.axes)
elif fft_form_orig in ['c']:
R.val=np.fft.ifftshift(R.val, axes=R.axes) # common for fft_form in [0,'r']
if fft_form in ['r']:
R.val=R.val[...,:self.get_N_real(self.N)[-1]]*np.prod(self.N)
elif fft_form_orig in [0]:
if fft_form in ['c']:
R.val=np.fft.fftshift(R.val, axes=R.axes)
else: # if fft_form in ['r']:
R.val=R.val[...,:self.get_N_real(self.N)[-1]]*np.prod(self.N)
R._set_fft(fft_form)
return R
示例4: parse_polynomial
def parse_polynomial(s):
'''Parse a polynomial string (e.g. 1101^7).
Returns the corresponding polynomial in a Latex-friendly form.'''
poly_str = ''
p = s.split('^')
if len(p) == 2:
base = np.array([int(y) for y in p[0]])
power = int(p[1])
modulus = np.flip(base, axis=0)
else:
base = np.array([int(y) for y in s])
power = 1
modulus = np.flip(base, axis=0)
for k in range(len(modulus)):
if modulus[k] == 1:
if poly_str != '':
poly_str += '+'
poly_str += ' z^{' + str(len(modulus)-k-1) + '}'
elif modulus[k] not in [0, 1]:
return ''
if poly_str == '':
return ''
if power != 1:
poly_str = '(' + poly_str + ')^{' + str(power) + '}'
return poly_str
示例5: getFullMesh
def getFullMesh(left_mesh=None, right_mesh=None):
"""
For a symmetric wing, OAS only keeps and does computation on the left half.
This script mirros the OAS mesh and attaches it to the existing mesh to
obtain the full mesh.
Parameters
----------
left_mesh[nx,ny,3] or right_mesh : numpy array
The half mesh to be mirrored.
Returns
-------
full_mesh[nx,2*ny-1,3] : numpy array
The computed full mesh.
"""
if left_mesh is None and right_mesh is None:
raise ValueError("Either the left or right mesh need to be supplied.")
elif left_mesh is not None and right_mesh is not None:
raise ValueError("Please only provide either left or right mesh, not both.")
elif left_mesh is not None:
right_mesh = np.flip(left_mesh,axis=1).copy()
right_mesh[:,:,1] *= -1
else:
left_mesh = np.flip(right_mesh,axis=1).copy()
left_mesh[:,:,1] *= -1
full_mesh = np.concatenate((left_mesh,right_mesh[:,1:,:]),axis=1)
return full_mesh
示例6: frequency_response
def frequency_response(self, N_points, freq_range=(0,200), mirror=False):
""" Frequency response curve of the sensor
Args:
freq_range (tuple): min and max frequency, defining the frequency range of the response
N_points (int): number of points generated in the curve (lenght of the response arrays)
mirror (bool): if true generates a mirror of the response for negative frequencies. The
effective freq_range would be from -1*freq_range[1] to freq_range[1]
Returns:
list: with two arrays, one of the frequency range array and the other with the corresponding
intensities, normalized from 0 to 1, 1 being the response in the resonant frequency.
"""
if not mirror:
f_array = np.linspace(*freq_range, N_points)
freq_response = norm(scale=self.bandwidth/2, loc=self.resonant_freq).pdf(f_array)
freq_response /= max(freq_response)
else:
f_array = np.linspace(*freq_range, N_points//2)
freq_response = norm(scale=self.bandwidth/2, loc=self.resonant_freq).pdf(f_array)
freq_response /= max(freq_response)
mirrored = (np.flip(f_array*-1, 0), np.flip(freq_response, 0))
f_array = np.hstack((mirrored[0], f_array))
freq_response = np.hstack((freq_response, mirrored[1]))
return [f_array, freq_response]
示例7: set_raster_origin
def set_raster_origin(data, coords, direction):
""" Converts Data and Coordinates Origin
Parameters
----------
data : :class:`numpy:numpy.ndarray`
Array of shape (rows, cols) or (bands, rows, cols) containing
the data values.
coords : :class:`numpy:numpy.ndarray`
Array of shape (rows, cols, 2) containing xy-coordinates.
direction : str
'lower' or 'upper', direction in which to convert data and coordinates.
Returns
-------
data : :class:`numpy:numpy.ndarray`
Array of shape (rows, cols) or (bands, rows, cols) containing
the data values.
coords : :class:`numpy:numpy.ndarray`
Array of shape (rows, cols, 2) containing xy-coordinates.
"""
x_sp, y_sp = coords[1, 1] - coords[0, 0]
origin = ('lower' if y_sp > 0 else 'upper')
same = (origin == direction)
if not same:
data = np.flip(data, axis=-2)
coords = np.flip(coords, axis=-3)
# we need to shift y-coordinate if data and coordinates have the same
# number of rows and cols (only the ll or ul raster coords are given)
if data.shape[-2:] == coords.shape[:2]:
coords += [0, y_sp]
return data, coords
示例8: prepare_buffer
def prepare_buffer(self, buffer):
if not self.init:
raise IOError("Hardware need to be initialized for buffer preparation!")
ACTIVATION_BITS = self.network_json['parameters']['ACTIVATION_BITS']
if (ACTIVATION_BITS > 8):
raise IOError("prepare buffer algorithm cannot handle more than 8 activation bits!")
buffer = buffer.astype(np.uint8)
dim = buffer.shape[1]
#change shape to (dim,dim,chan)
buffer = np.rollaxis(buffer,0,3)
#transform channels to bits
buffer = np.unpackbits(buffer, 2)
#reshape to so that the fourth dimension always is one byte in bits
buffer = buffer.reshape(dim, dim , -1, 8)
#remove all the zero bits that we do not need, activation bits are left over
buffer = np.delete(buffer, np.s_[0:(8-ACTIVATION_BITS)], 3)
#flip left over bits, to fix endianness
buffer = np.flip(buffer,3)
#shape back to (dim, dim, chans in bits)
buffer = np.reshape(buffer,(dim, dim, -1))
#pad channels to multiple of 8
if (buffer.shape[2] % 8):
buffer = np.pad(buffer, [(0, 0), (0, 0), (0, 8 - (buffer.shape[2] % 8))], mode='constant')
#fix endianness in 8 bits blocks
buffer = np.reshape(buffer, (dim, dim, -1, 8))
buffer = np.flip(buffer, 3)
#pack bits together
return np.packbits(buffer.reshape(dim, dim, -1), 2)
示例9: testGetNonContiguous
def testGetNonContiguous(self):
"""Check that we can index on non-contiguous tables"""
# Make a non-contiguous catalog
nonContiguous = type(self.catalog)(self.catalog.table)
for rr in reversed(self.catalog):
nonContiguous.append(rr)
num = len(self.catalog)
# Check assumptions
self.assertFalse(nonContiguous.isContiguous()) # We managed to produce a non-contiguous catalog
self.assertEqual(len(set(self.catalog["id"])), num) # ID values are unique
# Indexing with boolean array
select = np.zeros(num, dtype=bool)
select[1] = True
self.assertEqual(nonContiguous[np.flip(select, 0)]["id"], self.catalog[select]["id"])
# Extracting a number column
column = "a_instFlux"
array = nonContiguous[column]
self.assertFloatsEqual(np.flip(array, 0), self.catalog[column])
with self.assertRaises(ValueError):
array[1] = 1.2345 # Should be immutable
# Extracting a flag column
column = "a_flag"
array = nonContiguous[column]
np.testing.assert_equal(np.flip(array, 0), self.catalog[column])
with self.assertRaises(ValueError):
array[1] = True # Should be immutable
示例10: d21
def d21(data):
# Requires Python3
import numpy as np
rules = {}
for row in data.split('\n')[:-1]:
src, trg = [e.split('/') for e in row.split(' => ')]
src = np.array([list(r) for r in src])
trg = np.array([list(r) for r in trg])
# Original matrix
rules[src.tobytes()] = trg
# Rotated matrices
rules[np.rot90(src, k=1).tobytes()] = trg
rules[np.rot90(src, k=2).tobytes()] = trg
rules[np.rot90(src, k=3).tobytes()] = trg
# Flipped (and rotated) matrices
rules[np.flip(src, axis=1).tobytes()] = trg
# Rotated matrices
rules[np.rot90(np.flip(src, axis=1), k=1).tobytes()] = trg
rules[np.rot90(np.flip(src, axis=1), k=2).tobytes()] = trg
rules[np.rot90(np.flip(src, axis=1), k=3).tobytes()] = trg
# Starting grid
grid = np.array([['.', '#', '.'], ['.', '.', '#'], ['#', '#', '#']])
for _ in range(0, 18):
if len(grid) % 2 == 0:
tgrid = False
for row in range(0, len(grid), 2):
rgrid = np.array([[]])
for col in range(0, len(grid), 2):
subset = grid[row:row + 2, col:col + 2]
if col == 0:
rgrid = rules[subset.tobytes()]
else:
rgrid = np.concatenate((rgrid,
rules[subset.tobytes()]),
axis=1)
if row == 0:
tgrid = rgrid
else:
tgrid = np.concatenate((tgrid, rgrid),
axis=0)
else:
tgrid = False
for row in range(0, len(grid), 3):
rgrid = np.array([[]])
for col in range(0, len(grid), 3):
subset = grid[row:row + 3, col:col + 3]
if col == 0:
rgrid = rules[subset.tobytes()]
else:
rgrid = np.concatenate((rgrid,
rules[subset.tobytes()]),
axis=1)
if row == 0:
tgrid = rgrid
else:
tgrid = np.concatenate((tgrid, rgrid), axis=0)
grid = tgrid
return (grid == '#').sum()
示例11: init_dynamic_map
def init_dynamic_map(self,path_to_map="/home/racecar/racecar_ws/src/obstacle/maps/basement_fixed.png"):
self.dynamic_map = cv.imread(path_to_map, cv.IMREAD_GRAYSCALE)
self.dynamic_map = cv.threshold(self.dynamic_map, 127 ,255, cv.THRESH_BINARY)[1]
free_space = self.dynamic_map > 127
occupied_space = self.dynamic_map < 127
self.dynamic_map[free_space] = 0
self.dynamic_map[occupied_space] = 100
np.flip(self.dynamic_map, 0)
示例12: process_sample_specialized
def process_sample_specialized(self, features, label):
if np.random.uniform() > self.prob:
aug_f = np.flip(features, axis=1)
aug_l = np.flip(label, axis=1)
return aug_f, aug_l
else:
return features, label
示例13: build_plotting_moc
def build_plotting_moc(moc, wcs):
# Get the WCS cdelt giving the deg.px^(-1) resolution.
cdelt = wcs.wcs.cdelt
# Convert in rad.px^(-1)
cdelt = np.abs((2*np.pi/360)*cdelt[0])
# Get the minimum depth such as the resolution of a cell is contained in 1px.
depth_res = int(np.floor(np.log2(np.sqrt(np.pi/3)/cdelt)))
depth_res = max(depth_res, 0)
# Degrade the moc to that depth for plotting purposes. It is not necessary to plot pixels
# that we will not see because they are contained in 1px.
moc_plot = moc
if moc.max_order > depth_res:
moc_plot = moc.degrade_to_order(depth_res)
moc_plot = moc_plot.refine_to_order(min_depth=2)
# Get the MOC delimiting the FOV polygon
width_px = int(wcs.wcs.crpix[0]*2.) # Supposing the wcs is centered in the axis
heigth_px = int(wcs.wcs.crpix[1]*2.)
# Compute the sky coordinate path delimiting the viewport.
# It consists of a closed polygon of (4 - 1)*4 = 12 vertices
x_px = np.linspace(0, width_px, 4)
y_px = np.linspace(0, heigth_px, 4)
X, Y = np.meshgrid(x_px, y_px)
X_px = np.append(X[0, :-1], X[:-1, -1])
X_px = np.append(X_px, np.flip(X[-1, 1:]))
X_px = np.append(X_px, X[:-1, 0])
Y_px = np.append(Y[0, :-1], Y[:-1, -1])
Y_px = np.append(Y_px, Y[-1, :-1])
Y_px = np.append(Y_px, np.flip(Y[1:, 0]))
# Disable the output of warnings when encoutering NaNs.
warnings.filterwarnings("ignore")
# Inverse projection from pixel coordinate space to the world coordinate space
viewport = pixel_to_skycoord(X_px, Y_px, wcs)
# If one coordinate is a NaN we exit the function and do not go further
ra_deg, dec_deg = viewport.icrs.ra.deg, viewport.icrs.dec.deg
warnings.filterwarnings("default")
if np.isnan(ra_deg).any() or np.isnan(dec_deg).any():
return moc_plot
center_x_px, center_y_px = wcs.wcs.crpix[0], wcs.wcs.crpix[1]
inside = pixel_to_skycoord(center_x_px, center_y_px, wcs)
# Import MOC here to avoid circular imports
from ..moc import MOC
# Create a rough MOC (depth=3 is sufficient) from the viewport
moc_viewport = MOC.from_polygon_skycoord(viewport, max_depth=3, inside=inside)
# The moc to plot is the INPUT_MOC & MOC_VIEWPORT. For small FOVs this can reduce
# a lot the time to draw the MOC along with its borders.
moc_plot = moc_plot.intersection(moc_viewport)
return moc_plot
示例14: reflect
def reflect(self, axis=0):
"""
Reflect the lattice of control points along the direction defined
by `axis`. In particular the origin point of the lattice is preserved.
So, for instance, the reflection along x, is made with respect to the
face of the lattice in the yz plane that is opposite to the origin.
Same for the other directions. Only the weights (mu) along the chosen
axis are reflected, while the others are preserved. The symmetry plane
can not present deformations along the chosen axis.
After the refletcion there will be 2n-1 control points along `axis`,
witha doubled box length.
:param int axis: axis along which the reflection is performed.
Default is 0. Possible values are 0, 1, or 2, corresponding
to x, y, and z respectively.
"""
# check axis value
if axis not in (0, 1, 2):
raise ValueError(
"The axis has to be 0, 1, or 2. Current value {}.".format(axis))
# check that the plane of symmetry is undeformed
if (axis == 0 and np.count_nonzero(self.array_mu_x[-1, :, :]) != 0) or (
axis == 1 and np.count_nonzero(self.array_mu_y[:, -1, :]) != 0
) or (axis == 2 and np.count_nonzero(self.array_mu_z[:, :, -1]) != 0):
raise RuntimeError(
"If you want to reflect the FFD bounding box along axis " + \
"{} you can not diplace the control ".format(axis) + \
"points in the symmetry plane along that axis."
)
# double the control points in the given axis -1 (the symmetry plane)
self.n_control_points[axis] = 2 * self.n_control_points[axis] - 1
# double the box length
self.box_length[axis] *= 2
# we have to reflect the dispacements only along the correct axis
reflection = np.ones(3)
reflection[axis] = -1
# we select all the indeces but the ones in the plane of symmetry
indeces = [slice(None), slice(None), slice(None)] # = [:, :, :]
indeces[axis] = slice(1, None) # = [1:]
indeces = tuple(indeces)
# we append along the given axis all the displacements reflected
# and in the reverse order
self.array_mu_x = np.append(
self.array_mu_x,
reflection[0] * np.flip(self.array_mu_x, axis)[indeces], axis=axis)
self.array_mu_y = np.append(
self.array_mu_y,
reflection[1] * np.flip(self.array_mu_y, axis)[indeces], axis=axis)
self.array_mu_z = np.append(
self.array_mu_z,
reflection[2] * np.flip(self.array_mu_z, axis)[indeces], axis=axis)
示例15: apply_filter_backwards
def apply_filter_backwards(self, traces):
for tr in traces:
tr.data = np.flip(tr.data)
traces = self.apply_filter()
for tr in traces:
tr.data = np.flip(tr.data)
return traces