本文整理汇总了Python中numpy.roll方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.roll方法的具体用法?Python numpy.roll怎么用?Python numpy.roll使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.roll方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: equirect_facetype
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roll [as 别名]
def equirect_facetype(h, w):
'''
0F 1R 2B 3L 4U 5D
'''
tp = np.roll(np.arange(4).repeat(w // 4)[None, :].repeat(h, 0), 3 * w // 8, 1)
# Prepare ceil mask
mask = np.zeros((h, w // 4), np.bool)
idx = np.linspace(-np.pi, np.pi, w // 4) / 4
idx = h // 2 - np.round(np.arctan(np.cos(idx)) * h / np.pi).astype(int)
for i, j in enumerate(idx):
mask[:j, i] = 1
mask = np.roll(np.concatenate([mask] * 4, 1), 3 * w // 8, 1)
tp[mask] = 4
tp[np.flip(mask, 0)] = 5
return tp.astype(np.int32)
示例2: fig2data
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roll [as 别名]
def fig2data(fig):
"""
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
@param fig a matplotlib figure
@return a numpy 3D array of RGBA values
"""
# draw the renderer
fig.canvas.draw ( )
# Get the RGB buffer from the figure
w,h = fig.canvas.get_width_height()
buf = np.fromstring (fig.canvas.tostring_rgb(), dtype=np.uint8)
buf.shape = (w, h, 3)
# canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
buf = np.roll (buf, 3, axis=2)
return buf
示例3: augment_undo
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roll [as 别名]
def augment_undo(x_imgs_augmented, aug_type):
x_imgs_augmented = x_imgs_augmented.cpu().numpy()
sz = x_imgs_augmented.shape[0] // len(aug_type)
x_imgs = []
for i, aug in enumerate(aug_type):
x_img = x_imgs_augmented[i*sz : (i+1)*sz]
if aug == 'flip':
x_imgs.append(np.flip(x_img, axis=-1))
elif aug.startswith('rotate'):
shift = int(aug.split()[-1])
x_imgs.append(np.roll(x_img, -shift, axis=-1))
elif aug == '':
x_imgs.append(x_img)
else:
raise NotImplementedError()
return np.array(x_imgs)
示例4: computeUVN_vec
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roll [as 别名]
def computeUVN_vec(n, in_, planeID):
'''
vectorization version of computeUVN
@n N x 3
@in_ MN x 1
@planeID N
'''
n = n.copy()
if (planeID == 2).sum():
n[planeID == 2] = np.roll(n[planeID == 2], 2, axis=1)
if (planeID == 3).sum():
n[planeID == 3] = np.roll(n[planeID == 3], 1, axis=1)
n = np.repeat(n, in_.shape[0] // n.shape[0], axis=0)
assert n.shape[0] == in_.shape[0]
bc = n[:, [0]] * np.sin(in_) + n[:, [1]] * np.cos(in_)
bs = n[:, [2]]
out = np.arctan(-bc / (bs + 1e-9))
return out
示例5: gen_ww
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roll [as 别名]
def gen_ww(init_coorx, coory, z=50, coorW=1024, coorH=512, floorW=1024, floorH=512, tol=3, force_cuboid=True):
gpid = get_gpid(init_coorx, coorW)
coor = np.hstack([np.arange(coorW)[:, None], coory[:, None]])
xy = np_coor2xy(coor, z, coorW, coorH, floorW, floorH)
# Generate wall-wall
if force_cuboid:
xy_cor = gen_ww_cuboid(xy, gpid, tol)
else:
xy_cor = gen_ww_general(init_coorx, xy, gpid, tol)
# Ceiling view to normal view
cor = []
for j in range(len(xy_cor)):
next_j = (j + 1) % len(xy_cor)
if xy_cor[j]['type'] == 1:
cor.append((xy_cor[next_j]['val'], xy_cor[j]['val']))
else:
cor.append((xy_cor[j]['val'], xy_cor[next_j]['val']))
cor = np_xy2coor(np.array(cor), z, coorW, coorH, floorW, floorH)
cor = np.roll(cor, -2 * cor[::2, 0].argmin(), axis=0)
return cor, xy_cor
示例6: test_perturb_learnability
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roll [as 别名]
def test_perturb_learnability(frame, source_config, target_config):
bbox = derp.util.get_patch_bbox(target_config, source_config)
train_table, test_table = [], []
for shift in np.linspace(-0.4, 0.4, 51):
for rotate in np.linspace(-4, 4, 51):
p_frame = derp.util.perturb(frame.copy(), source_config, shift, rotate)
p_patch = derp.util.crop(p_frame, bbox)
table = test_table if shift == 0 or rotate == 0 else train_table
table.append([p_patch, torch.FloatTensor(), torch.FloatTensor([shift * 2.5,
rotate * 0.25])])
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
train_fetcher, test_fetcher = Fetcher(train_table), Fetcher(test_table)
train_loader = torch.utils.data.DataLoader(train_fetcher, 32, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_fetcher, len(test_fetcher))
model = derp.model.Tiny(np.roll(train_table[0][0].shape, 1), 0, 2).to(device)
optimizer = torch.optim.AdamW(model.parameters(), 1E-3)
criterion = torch.nn.MSELoss().to(device)
test_losses = []
for epoch in range(5):
train_loss = derp.model.train_epoch(device, model, optimizer, criterion, train_loader)
test_loss = derp.model.test_epoch(device, model, criterion, test_loader)
test_losses.append(test_loss)
assert min(test_losses) < 2E-3
示例7: detect_colspecs
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roll [as 别名]
def detect_colspecs(self, infer_nrows=100, skiprows=None):
# Regex escape the delimiters
delimiters = ''.join(r'\%s' % x for x in self.delimiter)
pattern = re.compile('([^%s]+)' % delimiters)
rows = self.get_rows(infer_nrows, skiprows)
if not rows:
raise EmptyDataError("No rows from which to infer column width")
max_len = max(map(len, rows))
mask = np.zeros(max_len + 1, dtype=int)
if self.comment is not None:
rows = [row.partition(self.comment)[0] for row in rows]
for row in rows:
for m in pattern.finditer(row):
mask[m.start():m.end()] = 1
shifted = np.roll(mask, 1)
shifted[0] = 0
edges = np.where((mask ^ shifted) == 1)[0]
edge_pairs = list(zip(edges[::2], edges[1::2]))
return edge_pairs
示例8: _compute_q_vectors
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roll [as 别名]
def _compute_q_vectors(self, box):
""" Compute the q-vectors compatible with the current box dimensions.
Calculated quantities:
q_vectors : two 2D arrays forming the grid of q-values, similar
to a meshgrid
Qxy : array of the different q-vectors
Q : squared module of Qxy with the first element missing
(no Q = 0.0)
"""
self.box = np.roll(box, 2 - self.normal)
nmax = list(map(int, np.ceil(self.box[0:2] / self.alpha)))
self.q_vectors = np.mgrid[0:nmax[0], 0:nmax[1]] * 1.0
self.q_vectors[0] *= 2. * np.pi / box[0]
self.q_vectors[1] *= 2. * np.pi / box[1]
self.modes_shape = self.q_vectors[0].shape
qx = self.q_vectors[0][:, 0]
qy = self.q_vectors[1][0]
Qx = np.repeat(qx, len(qy))
Qy = np.tile(qy, len(qx))
self.Qxy = np.vstack((Qx, Qy)).T
self.Q = np.sqrt(np.sum(self.Qxy * self.Qxy, axis=1)[1:])
示例9: logloss
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roll [as 别名]
def logloss(self, pred, actual, margin=12):
blocks = secondsToBlocks(margin)
logloss = np.ones(blocks*2)
indices = np.ones(blocks*2)
nonzero = np.nonzero(actual)[0]
begin = max(nonzero[0]-blocks, 0)
end = min(nonzero[-1]+blocks, len(actual)-1)
pred = pred[begin:end]
actual = actual[begin:end]
for i, offset in enumerate(range(-blocks, blocks)):
snippet = np.roll(actual, offset)
try:
logloss[i] = sklearn.metrics.log_loss(snippet[blocks:-blocks], pred[blocks:-blocks])
except (ValueError, RuntimeWarning):
pass
indices[i] = offset
return indices, logloss
示例10: p2o
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roll [as 别名]
def p2o(psf, shape):
'''
# psf: NxCxhxw
# shape: [H,W]
# otf: NxCxHxWx2
'''
otf = torch.zeros(psf.shape[:-2] + shape).type_as(psf)
otf[...,:psf.shape[2],:psf.shape[3]].copy_(psf)
for axis, axis_size in enumerate(psf.shape[2:]):
otf = torch.roll(otf, -int(axis_size / 2), dims=axis+2)
otf = torch.rfft(otf, 2, onesided=False)
n_ops = torch.sum(torch.tensor(psf.shape).type_as(psf) * torch.log2(torch.tensor(psf.shape).type_as(psf)))
otf[...,1][torch.abs(otf[...,1])<n_ops*2.22e-16] = torch.tensor(0).type_as(psf)
return otf
# otf2psf: not sure where I got this one from. Maybe translated from Octave source code or whatever. It's just math.
示例11: p2o
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roll [as 别名]
def p2o(psf, shape):
'''
Args:
psf: NxCxhxw
shape: [H,W]
Returns:
otf: NxCxHxWx2
'''
otf = torch.zeros(psf.shape[:-2] + shape).type_as(psf)
otf[...,:psf.shape[2],:psf.shape[3]].copy_(psf)
for axis, axis_size in enumerate(psf.shape[2:]):
otf = torch.roll(otf, -int(axis_size / 2), dims=axis+2)
otf = torch.rfft(otf, 2, onesided=False)
n_ops = torch.sum(torch.tensor(psf.shape).type_as(psf) * torch.log2(torch.tensor(psf.shape).type_as(psf)))
otf[...,1][torch.abs(otf[...,1])<n_ops*2.22e-16] = torch.tensor(0).type_as(psf)
return otf
示例12: roll_mps_unit_cell
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roll [as 别名]
def roll_mps_unit_cell(self, shift=1):
"""Shift the section we define as unit cellof an infinite MPS; in place.
Suppose we have a unit cell with tensors ``[A, B, C, D]`` (repeated on both sites).
With ``shift = 1``, the new unit cell will be ``[D, A, B, C]``,
whereas ``shift = -1`` will give ``[B, C, D, A]``.
Parameters
----------
shift : int
By how many sites to move the tensors to the right.
"""
if self.finite:
raise ValueError("makes only sense for infinite boundary conditions")
inds = np.roll(np.arange(self.L), shift)
self.sites = [self.sites[i] for i in inds]
self.form = [self.form[i] for i in inds]
self._B = [self._B[i] for i in inds]
self._S = [self._S[i] for i in inds]
self._S.append(self._S[0])
示例13: update
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roll [as 别名]
def update(self, actions, board, layers, backdrop, things, the_plot):
# Where are the laser bolts? Only bolts from the player kill a Marauder.
bolts = np.logical_or.reduce([layers[c] for c in UPWARD_BOLT_CHARS], axis=0)
hits = bolts & self.curtain # Any hits to Marauders?
np.logical_xor(self.curtain, hits, self.curtain) # If so, zap the marauder...
the_plot.add_reward(np.sum(hits)*10) # ...and supply a reward.
# Save the identities of marauder-striking bolts in the Plot.
the_plot['marauder_hitters'] = [chr(c) for c in board[hits]]
# If no Marauders are left, or if any are sitting on row 10, end the game.
if (not self.curtain.any()) or self.curtain[10, :].any():
return the_plot.terminate_episode() # i.e. return None.
# We move faster if there are fewer Marauders. The odd divisor causes speed
# jumps to align on the high sides of multiples of 8; so, speed increases as
# the number of Marauders decreases to 32 (or 24 etc.), not 31 (or 23 etc.).
if the_plot.frame % max(1, np.sum(self.curtain)//8.0000001): return
# If any Marauder reaches either side of the screen, reverse horizontal
# motion and advance vertically one row.
if np.any(self.curtain[:, 0] | self.curtain[:, -1]):
self._dx = -self._dx
self.curtain[:] = np.roll(self.curtain, shift=1, axis=0)
self.curtain[:] = np.roll(self.curtain, shift=self._dx, axis=1)
示例14: _polygon_area
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roll [as 别名]
def _polygon_area(self, x, y):
"""Compute the area of a component of a polygon.
Using the shoelace formula:
https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates
Args:
x (ndarray): x coordinates of the component
y (ndarray): y coordinates of the component
Return:
float: the are of the component
""" # noqa: 501
return 0.5 * np.abs(
np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))
示例15: inverse
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roll [as 别名]
def inverse(self, spectrum, in_phase=None):
spectrum = spectrum.astype(complex)
if in_phase is None:
in_phase = self.phase
self.spectrum_buffer[-1] = spectrum * in_phase
self.absolute_buffer[-1] = spectrum
for _ in range(self.loop_num):
self.overwrap_buf *= 0
waves = np.fft.ifft(self.spectrum_buffer, axis=1).real
last = self.spectrum_buffer
for i in range(self.buffer_size):
self.overwrap_buf[i*self.wave_dif:i*self.wave_dif+self.wave_len] += waves[i]
waves = np.vstack([self.overwrap_buf[i*self.wave_dif:i*self.wave_dif+self.wave_len]*self.window for i in range(self.buffer_size)])
spectrum = np.fft.fft(waves, axis=1)
self.spectrum_buffer = self.absolute_buffer * spectrum / (np.abs(spectrum)+1e-10)
self.spectrum_buffer += 0.5 * (self.spectrum_buffer - last)
waves = np.fft.ifft(self.spectrum_buffer[0]).real
self.absolute_buffer = np.roll(self.absolute_buffer, -1, axis=0)
self.spectrum_buffer = np.roll(self.spectrum_buffer, -1, axis=0)
self.wave_buf = np.roll(self.wave_buf, -self.wave_dif)
self.wave_buf[-self.wave_dif:] = 0
self.wave_buf[self.wave_dif:] += waves
return self.wave_buf[:self.wave_dif]*0.5