def update(self, idxs, x):
# Fetch the classes for the regression
_, y = self.dataset.train_data[idxs]
# If we are doing the regression in logspace
if self.log:
x = np.log(x)
# Train the lstm so that it can predict x given the history
self.model.train_on_batch([self.history[idxs], self._to_ids(y)], x)
# Update the history to include x
full = idxs[self.cnts[idxs] == self.history.shape[1]]
self.history[full] = np.roll(self.history[full], -1, axis=1)
self.cnts[full] -= 1
self.history[idxs, self.cnts[idxs], :1] = x
self.cnts[idxs] += 1
python类roll()的实例源码
def update(self, idxs, x):
# Fetch the classes for the regression
_, y = self.dataset.train_data[idxs]
# If we are doing the regression in logspace
if self.log:
x = np.log(x)
# Train the lstm so that it can predict x given the history
self.model.train_on_batch([self.history[idxs], self._to_ids(y)], x)
# Update the history to include x
full = idxs[self.cnts[idxs] == self.history.shape[1]]
self.history[full] = np.roll(self.history[full], -1, axis=1)
self.cnts[full] -= 1
self.history[idxs, self.cnts[idxs], :1] = x
self.cnts[idxs] += 1
def update(self, idxs, x):
# Fetch the classes for the regression
_, y = self.dataset.train_data[idxs]
# If we are doing the regression in logspace
if self.log:
x = np.log(x)
# Train the lstm so that it can predict x given the history
self.model.train_on_batch([self.history[idxs], self._to_ids(y)], x)
# Update the history to include x
full = idxs[self.cnts[idxs] == self.history.shape[1]]
self.history[full] = np.roll(self.history[full], -1, axis=1)
self.cnts[full] -= 1
self.history[idxs, self.cnts[idxs], :1] = x
self.cnts[idxs] += 1
def uwt_align_h2(X, inverse=False):
"""UWT h2 coefficients aligment.
If inverse = True performs the misalignment
for a correct reconstruction.
"""
J = X.shape[0] / 2
shifts = np.asarray([2 ** j for j in range(J)])
if not inverse:
shifts *= -1
for j in range(J):
X[j] = np.roll(X[j], shifts[j])
X[j + J] = np.roll(X[j + J], shifts[j])
def uwt_align_d4(X, inverse=False):
"""UWT d4 coefficients aligment.
If inverse = True performs the misalignment
for a correct reconstruction.
"""
J = X.shape[0] / 2
w_shifts = np.asarray([(3 * 2 ** j) - 1 for j in range(J)])
v_shifts = np.asarray([1] + [(2 ** (j + 1) - 1) for j in range(1, J)])
if not inverse:
w_shifts *= -1
v_shifts *= -1
for j in range(J):
X[j] = np.roll(X[j], w_shifts[j])
X[j + J] = np.roll(X[j + J], v_shifts[j])
def finalize(self,mskp_model):
print('found %i islands'%self.nbisland)
mskp = zeros((self.nyl,self.nxl),dtype=int8)
work = zeros((self.nyl,self.nxl))
mskr = zeros((self.nyl,self.nxl))
for k in range(self.nbisland):
idx = self.data[k]['idx']
psi0 = self.data[k]['psi0']
mskr[:,:]=1.
mskp[:,:]=0
mskr[idx]=0.
celltocorner(mskr,work)
mskp[work==1]=1
mskp=1-mskp
vort = (roll(mskp,-1,axis=1)+roll(mskp,-1,axis=0)
+roll(mskp,+1,axis=1)+roll(mskp,+1,axis=0) )
z=(vort)*psi0/self.dx**2#*(1-mskp)
self.rhsp[vort>0] = z[vort>0]
self.psi[mskp==1]=psi0
# print(self.psi[:,10])
print('island are ok')
def to_intervals(X):
def _roll_rows(x):
""" Circularly shift ('roll') rows i in array by -i, recursively.
If 2d-array: circularly shift each row i to the left, i times so that
X(i, j-i) = X(i, j)
If 3d-array (or 4d, 5d..):
X(i, j-i, k-j) = X(i, j, k)
"""
if len(x.shape) > 2:
x = np.array([_roll_rows(xi) for xi in x])
elif len(x.shape) == 1:
raise ValueError('Method requires nd-array with n >= 2.')
x_rolled = np.array([np.roll(xi, -i, axis=0) for i, xi in enumerate(x)])
return x_rolled
X_rolled = _roll_rows(X)
X_inv = np.sum(X_rolled, axis=0)
return X_inv
## ------------------------- feature alignment
def lower_periodic(self, periodic, direction=0):
""" Sets the periodicity of the spline object in the given direction,
keeping the geometry unchanged.
:param int periodic: new periodicity, i.e. the basis is C^k over the start/end
:param int direction: the parametric direction of the basis to modify
:return: self
"""
direction = check_direction(direction, self.pardim)
b = self.bases[direction]
while periodic < b.periodic:
self.insert_knot(self.start(direction), direction)
self.controlpoints = np.roll(self.controlpoints, -1, direction)
b.roll(1)
b.periodic -= 1
b.knots = b.knots[:-1]
if periodic > b.periodic:
raise ValueError('Cannot raise periodicity')
return self
def sharpenOld(s, kernelFunc, dist=None, scale=None,
normalize=False, m1=False, *args, **kwargs):
s = util.colmat(s)
if dist is None:
dist = np.arange(s.shape[1])+1.0
dist = np.abs(dist[None,:]-dist[:,None])
#dist = np.insert(spsig.triang(s.shape[1]-1, sym=False), 0, 0.0)
#dist = np.vstack([np.roll(dist, i) for i in xrange(dist.size)])
if scale is None:
# minimum off-diagonal distance
scale = np.min(dist[np.asarray(1.0-np.eye(dist.shape[0]), dtype=np.bool)])
kernel = kernelFunc(dist.T/scale, *args, **kwargs)
if m1:
np.fill_diagonal(kernel, 0.0)
if normalize:
kernel = kernel/np.abs(kernel.sum(axis=0))
return s - s.dot(kernel)
def get_samples(self, sample_count):
"""
Fetch a number of samples from self.wave_cache
Args:
sample_count (int): Number of samples to fetch
Returns: ndarray
"""
if self.amplitude.value <= 0:
return None
# Build samples by rolling the period cache through the buffer
rolled_array = numpy.roll(self.wave_cache,
-1 * self.last_played_sample)
# Append remaining partial period
full_count, remainder = divmod(sample_count, self.cache_length)
final_subarray = rolled_array[:int(remainder)]
return_array = numpy.concatenate((numpy.tile(rolled_array, full_count),
final_subarray))
# Keep track of where we left off to prevent popping between chunks
self.last_played_sample = int(((self.last_played_sample + remainder) %
self.cache_length))
# Multiply output by amplitude
return return_array * (self.amplitude.value *
self.amplitude_multiplier)
def gen_blurred_diag_pxy(s):
X = 1024
Y = X
# generate pdf
from scipy.stats import multivariate_normal
pxy = np.zeros((X,Y))
rv = multivariate_normal(cov=s)
for x in range(X):
pxy[x,:] = np.roll(rv.pdf(np.linspace(-X/2,X/2,X+1)[:-1]),int(X/2+x))
pxy = pxy/np.sum(pxy)
# plot p(x,y)
import matplotlib.pyplot as plt
plt.figure()
plt.contourf(pxy)
plt.ion()
plt.title("p(x,y)")
plt.show()
return pxy
def _roll_data(self):
"""
Roll window worth of data up to position zero.
Save the effort of having to expensively roll at each iteration
"""
self.buffer.values[:, :self._window, :] = \
self.buffer.values[:, -self._window:, :]
self.date_buf[:self._window] = self.date_buf[-self._window:]
self._pos = self._window
def _roll_data(self):
"""
Roll window worth of data up to position zero.
Save the effort of having to expensively roll at each iteration
"""
self.buffer.values[:, :self._window, :] = \
self.buffer.values[:, -self._window:, :]
self.date_buf[:self._window] = self.date_buf[-self._window:]
self._pos = self._window
def setSinusoidalWaveform(self,
waveTableId,
append,
lengthInPoints,
amplitudeOfTheSineCurve,
offsetOfTheSineCurve,
wavelengthOfTheSineCurveInPoints,
startPoint,
curveCenterPoint):
'''
See description of PI_WAV_SIN_P in PI GCS 2.0 DLL doc
'''
curveCenterPoint= int(round(curveCenterPoint))
wavelengthOfTheSineCurveInPoints= \
int(round(wavelengthOfTheSineCurveInPoints))
startPoint= int(round(startPoint))
lengthInPoints= int(round(lengthInPoints))
assert append == WaveformGenerator.CLEAR, 'only CLEAR implemented'
assert startPoint >= 0
assert startPoint < lengthInPoints
assert curveCenterPoint >= 0
assert startPoint + curveCenterPoint < lengthInPoints
ccUp= 0.5* curveCenterPoint
rampUp= 0.5 * amplitudeOfTheSineCurve* (1 + np.sin(
np.arange(-ccUp, ccUp) / ccUp * np.pi / 2))
ccDown= 0.5* (wavelengthOfTheSineCurveInPoints - curveCenterPoint)
rampDown= 0.5 * amplitudeOfTheSineCurve* (1 - np.sin(
np.arange(-ccDown, ccDown) / ccDown * np.pi / 2))
waveform= np.zeros(lengthInPoints) + offsetOfTheSineCurve
waveform[0: curveCenterPoint]= offsetOfTheSineCurve + rampUp
waveform[curveCenterPoint: wavelengthOfTheSineCurveInPoints]= \
offsetOfTheSineCurve + rampDown
waveform= np.roll(waveform, startPoint)
self._waveform[waveTableId]= waveform
def publish_sensor_frame(self, channel, pose=None):
"""
Publish sensor frame in which the point clouds
are drawn with reference to. sensor_frame_msg.id is hashed
by its channel (may be collisions since its right shifted by 32)
"""
# Sensor frames msg
msg = vs.obj_collection_t()
msg.id = self.channel_uid(channel)
msg.name = 'BOTFRAME_' + channel
msg.type = vs.obj_collection_t.AXIS3D
msg.reset = True
# Send sensor pose
pose_msg = vs.obj_t()
roll, pitch, yaw, x, y, z = pose.to_rpyxyz(axes='sxyz')
pose_msg.id = 0
pose_msg.x, pose_msg.y, pose_msg.z, \
pose_msg.roll, pose_msg.pitch, pose_msg.yaw = x, y, z, roll, pitch, yaw
# Save pose
self.set_sensor_pose(channel, pose)
msg.objs = [pose_msg]
msg.nobjs = len(msg.objs)
self.lc.publish("OBJ_COLLECTION", msg.encode())
def corners_to_edges(corners):
""" Edges are represented in N x 6 form """
return np.hstack([corners, np.roll(corners, 1, axis=0)])
def interpolate(self, other, this_weight):
q0, q1 = np.roll(self.q, shift=1), np.roll(other.q, shift=1)
u = 1 - this_weight
assert(u >= 0 and u <= 1)
cos_omega = np.dot(q0, q1)
if cos_omega < 0:
result = -q0[:]
cos_omega = -cos_omega
else:
result = q0[:]
cos_omega = min(cos_omega, 1)
omega = math.acos(cos_omega)
sin_omega = math.sin(omega)
a = math.sin((1-u) * omega)/ sin_omega
b = math.sin(u * omega) / sin_omega
if abs(sin_omega) < 1e-6:
# direct linear interpolation for numerically unstable regions
result = result * this_weight + q1 * u
result /= math.sqrt(np.dot(result, result))
else:
result = result*a + q1*b
return Quaternion(np.roll(result, shift=-1))
# To conversions
def to_wxyz(self):
q = np.roll(self.q, shift=1)
return q
def from_wxyz(cls, q):
return cls(np.roll(q, shift=-1))
def from_rpy (cls, roll, pitch, yaw, axes='rxyz'):
""" Construct Quaternion from axis-angle representation """
return cls(tf.quaternion_from_euler(roll, pitch, yaw, axes=axes))