def __call__(self, inputs,target_depth,target_label):
if random.random() < 0.5:
inputs = np.flip(inputs,axis=0).copy()
target_depth = np.flip(target_depth,axis=0).copy()
target_label = np.flip(target_label,axis=0).copy()
return inputs,target_depth,target_label
python类flip()的实例源码
def agg(file_name,store_file):
datas = joblib.load(file_name)
new_datas = []
for data in datas:
new_datas.append(data)
new_datas.append({"input":np.flip(data["input"],axis=2),"label":data["label"]})
new_datas.append({"input":np.flip(data["input"],axis=3),"label":data["label"]})
#new_datas.append({"input":np.rot90(m=data["input"],k=1,axes=(2,3)),"label":data["label"]})
#new_datas.append({"input":np.rot90(m=data["input"],k=2,axes=(2,3)),"label":data["label"]})
#new_datas.append({"input":np.rot90(m=data["input"],k=3,axes=(2,3)),"label":data["label"]})
joblib.dump(value=new_datas,filename=store_file,compress=3)
def get_radial_power_by_tally(self, state, tally_id, index=None, eps=0):
"""Get the radial power of a specific tally with a known ID
Parameters:
-----------
state: openmc.StatePoint with this Mesh_Group's tally results
tally_id: int; id of the desired openmc.Tally
index: int; index of the z-layer within the Tally's mesh.
If the index is None, the sum of all the Tally's
layers will be returned.
[Default: None]
Returns:
--------
xyarray: numpy.array of the radial power profile
"""
tally = state.tallies[tally_id]
talvals = tally.get_values()
nz = len(talvals)//(self._nx*self._ny)
talvals.shape = (nz, self._ny, self._nx)
talvals = np.flip(talvals, 1)
if index:
xyarray = talvals[index, :, :]
else:
xyarray = np.zeros((self._ny, self._nx))
for i in range(nz):
xyarray += talvals[i, :, :]
xyarray[xyarray <= eps] = np.NaN
return xyarray
dataset.py 文件源码
项目:neural-combinatorial-optimization-rl-tensorflow
作者: MichelDeudon
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def swap2opt(tsptw_sequence,i,j):
new_tsptw_sequence = np.copy(tsptw_sequence)
new_tsptw_sequence[i:j+1] = np.flip(tsptw_sequence[i:j+1], axis=0) # flip or swap ?
return new_tsptw_sequence
# One step of 2opt = one double loop and return first improved sequence
def random_flip_lr(img):
rand_num = np.random.rand(1)
if rand_num > 0.5:
img = np.flip(img, 1)
return img
def append_zeros_all(fls1, fls2, mode):
lens1, lens2 = [], []
for fl1, fl2 in zip(fls1, fls2):
if mode == 'audio':
lens1.append(fl1.shape[0]), lens2.append(fl2.shape[0])
elif mode == 'specs':
lens1.append(fl1.shape[0]), lens2.append(fl2.shape[0])
else:
raise ValueError('Whaaat?')
inds1, lens1 = list(np.flip(np.argsort(lens1),0)), np.flip(np.sort(lens1),0)
inds2, lens2 = list(np.flip(np.argsort(lens2),0)), np.flip(np.sort(lens2),0)
fls1, fls2 = np.array(fls1)[inds1], np.array(fls2)[inds2]
maxlen = max([max(lens1), max(lens2)])
mixes = []
for i, (fl1, fl2) in enumerate(zip(fls1, fls2)):
if mode == 'audio':
fls1[i] = np.pad(fl1, (0, maxlen - fl1.shape[0]), 'constant')
fls2[i] = np.pad(fl2, (0, maxlen - fl2.shape[0]), 'constant')
mixes.append(fls1[i] + fls2[i])
elif mode == 'specs':
fls1[i] = np.pad(fl1, ((0, maxlen - fl1.shape[0]), (0, 0)), 'constant')
fls2[i] = np.pad(fl2, ((0, maxlen - fl2.shape[0]), (0, 0)), 'constant')
else:
raise ValueError('Whaaat?')
return list(fls1), list(fls2), mixes, lens1, lens2
def pca_fit(X, var_ratio=1, return_transform=True):
"""
Parameters
----------
X : array_like
An array of data samples with shape (n_samples, n_features).
var_ratio : float
The variance ratio to be captured (Default value = 1).
return_transform : bool
Whether to apply the transformation to the given data.
Returns
-------
array_like
If return_transform is True, an array with shape (n_samples, n_components) which is the input samples projected
onto `n_components` principal components. Otherwise the first `n_components` eigenvectors of the covariance
matrix corresponding to the `n_components` largest eigenvalues are returned as rows.
"""
cov_ = np.cov(X, rowvar=False) # Mean is removed
evals, evecs = LA.eigh(cov_) # Get eigenvalues in ascending order, eigenvectors in columns
evecs = np.fliplr(evecs) # Flip eigenvectors to get them in descending eigenvalue order
if var_ratio == 1:
L = evecs.T
else:
evals = np.flip(evals, axis=0)
var_exp = np.cumsum(evals)
var_exp = var_exp / var_exp[-1]
n_components = np.argmax(np.greater_equal(var_exp, var_ratio))
L = evecs.T[:n_components] # Set the first n_components eigenvectors as rows of L
if return_transform:
return X.dot(L.T)
else:
return L
def _slice_cube(cube):
"""Creates 2D slices from a 3D volume.
Args:
cube: a [N x N x N] numpy array
Returns:
slices: a [N x N x 9] array of 2D slices
"""
slices = np.zeros((cube.shape[0], cube.shape[0], 9), dtype=np.float32)
# axis-aligned
slices[:,:,0] = cube[np.floor(cube.shape[0] / 2).astype(int), :, :]
slices[:,:,1] = cube[:, np.floor(cube.shape[0] / 2).astype(int), :]
slices[:,:,2] = cube[:, :, np.floor(cube.shape[0] / 2).astype(int)]
# diagonals
slices[:,:,3] = cube.diagonal(axis1=0, axis2=1)
slices[:,:,4] = cube.diagonal(axis1=0, axis2=2)
slices[:,:,5] = cube.diagonal(axis1=1, axis2=2)
slices[:,:,6] = np.flip(cube, 0).diagonal(axis1=0, axis2=1)
slices[:,:,7] = np.flip(cube, 0).diagonal(axis1=0, axis2=2)
slices[:,:,8] = np.flip(cube, 1).diagonal(axis1=1, axis2=2)
return slices
def set_raster_origin(data, coords, direction):
""" Converts Data and Coordinates Origin
.. versionadded 0.10.0
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
if data.shape[-2:] == coords.shape[:2]:
coords += [0, y_sp]
return data, coords
def test_set_raster_origin(self):
data, coords = georef.set_raster_origin(self.data.copy(),
self.coords.copy(), 'upper')
np.testing.assert_array_equal(data, self.data)
np.testing.assert_array_equal(coords, self.coords)
data, coords = georef.set_raster_origin(self.data.copy(),
self.coords.copy(), 'lower')
np.testing.assert_array_equal(data, np.flip(self.data, axis=-2))
np.testing.assert_array_equal(coords, np.flip(self.coords, axis=-3))
def get_image(self, header):
print(header)
prod = SIGMET_DATA_TYPES[header.get('data_type')]
x_size = header.get('x_size')
y_size = header.get('y_size')
z_size = header.get('z_size')
cnt = x_size * y_size * z_size
data = self.read_from_record(cnt, prod['dtype'])
data = self.decode_data(data, prod=prod)
data.shape = (z_size, y_size, x_size)
return np.flip(data, axis=1)
def drawTrace(self):
data = np.zeros((256, 256), dtype=np.uint8)
surface = cairo.ImageSurface.create_for_data(data,cairo.FORMAT_A8,256,256)
context = cairo.Context(surface)
t = [np.zeros((256,256))]
for l in self.lines:
l.draw(context)
t.append(np.flip(data, 0)/255.0)
return t
def work(self, task):
pts = task
audio_frame = int(pts * self._api.audio.sample_rate / 1000.0)
first_sample = (
audio_frame >> DERIVATION_DISTANCE) << DERIVATION_DISTANCE
sample_count = 2 << DERIVATION_SIZE
samples = self._api.audio.get_samples(first_sample, sample_count)
samples = np.mean(samples, axis=1)
sample_fmt = self._api.audio.sample_format
if sample_fmt is None:
return pts, np.zeros((1 << DERIVATION_SIZE) + 1)
elif sample_fmt == ffms.FFMS_FMT_S16:
samples /= 32768.
elif sample_fmt == ffms.FFMS_FMT_S32:
samples /= 4294967296.
elif sample_fmt not in (ffms.FFMS_FMT_FLT, ffms.FFMS_FMT_DBL):
raise RuntimeError('Unknown sample format: {}'.format(sample_fmt))
self._input[0:len(samples)] = samples
out = self._fftw()
scale_factor = 9 / np.sqrt(1 * (1 << DERIVATION_SIZE))
out = np.log(
np.sqrt(
np.real(out) * np.real(out)
+ np.imag(out) * np.imag(out)
) * scale_factor + 1)
out *= 255
out = np.clip(out, 0, 255)
out = np.flip(out, axis=0)
out = out.astype(dtype=np.uint8)
return pts, out
def getYae(Xae, reverseUtt):
assert len(Xae.shape) in [3,4], 'Invalid number of dimensions for Xae: %i (must be 3 or 4)' % len(Xae.shape)
if reverseUtt:
Yae = np.flip(Xae, 1)
if len(Xae.shape) == 4:
Yae = np.flip(Yae, 2)
else:
Yae = Xae
return Yae
def test_axes(self):
self.assertRaises(ValueError, np.flip, np.ones(4), axis=1)
self.assertRaises(ValueError, np.flip, np.ones((4, 4)), axis=2)
self.assertRaises(ValueError, np.flip, np.ones((4, 4)), axis=-3)
def test_basic_lr(self):
a = get_mat(4)
b = a[:, ::-1]
assert_equal(np.flip(a, 1), b)
a = [[0, 1, 2],
[3, 4, 5]]
b = [[2, 1, 0],
[5, 4, 3]]
assert_equal(np.flip(a, 1), b)
def test_basic_ud(self):
a = get_mat(4)
b = a[::-1, :]
assert_equal(np.flip(a, 0), b)
a = [[0, 1, 2],
[3, 4, 5]]
b = [[3, 4, 5],
[0, 1, 2]]
assert_equal(np.flip(a, 0), b)
def test_3d_swap_axis0(self):
a = np.array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
b = np.array([[[4, 5],
[6, 7]],
[[0, 1],
[2, 3]]])
assert_equal(np.flip(a, 0), b)
def test_3d_swap_axis1(self):
a = np.array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
b = np.array([[[2, 3],
[0, 1]],
[[6, 7],
[4, 5]]])
assert_equal(np.flip(a, 1), b)
def test_4d(self):
a = np.arange(2 * 3 * 4 * 5).reshape(2, 3, 4, 5)
for i in range(a.ndim):
assert_equal(np.flip(a, i), np.flipud(a.swapaxes(0, i)).swapaxes(i, 0))