def get_labels(contours, shape, slices):
z = [np.around(s.ImagePositionPatient[2], 1) for s in slices]
pos_r = slices[0].ImagePositionPatient[1]
spacing_r = slices[0].PixelSpacing[1]
pos_c = slices[0].ImagePositionPatient[0]
spacing_c = slices[0].PixelSpacing[0]
label_map = np.zeros(shape, dtype=np.float32)
for con in contours:
num = ROI_ORDER.index(con['name']) + 1
for c in con['contours']:
nodes = np.array(c).reshape((-1, 3))
assert np.amax(np.abs(np.diff(nodes[:, 2]))) == 0
z_index = z.index(np.around(nodes[0, 2], 1))
r = (nodes[:, 1] - pos_r) / spacing_r
c = (nodes[:, 0] - pos_c) / spacing_c
rr, cc = polygon(r, c)
label_map[z_index, rr, cc] = num
return label_map
python类around()的实例源码
def ani_update(arg, ii=[0]):
i = ii[0] # don't ask...
if np.isclose(t_arr[i], np.around(t_arr[i], 1)):
fig2.suptitle('Evolution (Time: {})'.format(t_arr[i]), fontsize=24)
graphic_floor[0].set_data([-floor_lim*np.cos(incline_history[i]) + radius*np.sin(incline_history[i]), floor_lim*np.cos(incline_history[i]) + radius*np.sin(incline_history[i])], [-floor_lim*np.sin(incline_history[i])-radius*np.cos(incline_history[i]), floor_lim*np.sin(incline_history[i])-radius*np.cos(incline_history[i])])
graphic_wheel.center = (x_history[i], y_history[i])
graphic_ind[0].set_data([x_history[i], x_history[i] + radius*np.sin(w_history[i])],
[y_history[i], y_history[i] + radius*np.cos(w_history[i])])
graphic_pend[0].set_data([x_history[i], x_history[i] - cw_to_cm[1]*np.sin(q_history[i, 2])],
[y_history[i], y_history[i] + cw_to_cm[1]*np.cos(q_history[i, 2])])
graphic_dist[0].set_data([x_history[i] - cw_to_cm[1]*np.sin(q_history[i, 2]), x_history[i] - cw_to_cm[1]*np.sin(q_history[i, 2]) - pscale*p_history[i]*np.cos(q_history[i, 2])],
[y_history[i] + cw_to_cm[1]*np.cos(q_history[i, 2]), y_history[i] + cw_to_cm[1]*np.cos(q_history[i, 2]) - pscale*p_history[i]*np.sin(q_history[i, 2])])
ii[0] += int(1 / (timestep * framerate))
if ii[0] >= len(t_arr):
print("Resetting animation!")
ii[0] = 0
return [graphic_floor, graphic_wheel, graphic_ind, graphic_pend, graphic_dist]
# Run animation
def gen_adj_mat(longs, lats, prob_edge=.2,
additional_length=lambda: np.random.exponential(20,1)):
'''Get an adjacency matrix for the cities whose longitudes and latitudes
are passed. Each entry will either be a number somewhat greater than the
crow-flies distance between the two cities (with probability prob_edge),
or math.inf. The matrix will consist of floats, and be symmetric. The
diagonal will be all zeroes. The "somewhat greater" is controlled by the
additional_length parameter, a function returning a random amount.'''
# Generate full nxn Bernoulli's, even though we'll only use the upper
# triangle.
edges = np.random.binomial(1, prob_edge, size=(len(longs),len(longs)))
am = np.zeros((len(longs),len(longs)))
for i in range(len(longs)):
for j in range(len(longs)):
if i==j:
am[i,i] = 0
elif i < j:
if edges[i,j] == 1:
am[i,j] = (math.hypot(longs[i]-longs[j],lats[i]-lats[j])
+ additional_length())
am[j,i] = am[i,j]
else:
am[i,j] = am[j,i] = math.inf
return np.around(am,1)
def bbox_indices(self, bbox, shape, precision=7):
"""
Return row and column coordinates of a bounding box at a
given cellsize.
Parameters
----------
bbox : tuple of floats or ints (length 4)
bbox of new data.
shape : tuple of ints (length 2)
The shape of the 2D array (rows, columns).
precision : int
Precision to use when matching geographic coordinates.
"""
rows = np.around(np.linspace(bbox[1], bbox[3],
shape[0], endpoint=False)[::-1], precision)
cols = np.around(np.linspace(bbox[0], bbox[2],
shape[1], endpoint=False), precision)
return rows, cols
def round_(a, decimals=0, out=None):
"""
Round an array to the given number of decimals.
Refer to `around` for full documentation.
See Also
--------
around : equivalent function
"""
try:
round = a.round
except AttributeError:
return _wrapit(a, 'round', decimals, out)
return round(decimals, out)
def get_cell(self):
# from fractions import Fraction
marr = np.array(self._matrix, dtype=np.float64).reshape((3, 3))
g_arr = self._sites_grid.to_array()
d = self.depth
w = self.width
l = self.length
arr_bas = marr*np.array([d, w, l], dtype=np.int).reshape((3, 1))
grid_position = np.array([p for p in CStru._yield_position(d, w, l)])
frac = np.array([1/d, 1/w, 1/l], dtype=np.float64).reshape((1, 3))
# round_frac = np.around(frac, decimals=22)
arr_pos = grid_position * frac
arr_num = np.array([i for i in g_arr.flat])
return (arr_bas, arr_pos, arr_num)
def _get_new_id_seq(pos, numbers):
"""
A helper function to produce the new sequence of the transformed
structure. Algs is sort the position back to init and use the index
to sort numbers.
"""
# transfer the atom position into >=0 and <=1
pos = np.around(pos, decimals=3)
func_tofrac = np.vectorize(lambda x: round((x % 1), 3))
o_pos = func_tofrac(pos)
# round_o_pos = np.around(o_pos, decimals=3)
# z, y, x = round_o_pos[:, 2], round_o_pos[:, 1], round_o_pos[:, 0]
z, y, x = o_pos[:, 2], o_pos[:, 1], o_pos[:, 0]
inds = np.lexsort((z, y, x))
return inds
def _get_new_id_seq(pos, numbers):
"""
A helper function to produce the new sequence of the transformed
structure. Algs is sort the position back to init and use the index
to sort numbers.
"""
# transfer the atom position into >=0 and <=1
pos = np.around(pos, decimals=5)
func_tofrac = np.vectorize(lambda x: round((x % 1), 3))
o_pos = func_tofrac(pos)
# round_o_pos = np.around(o_pos, decimals=3)
# z, y, x = round_o_pos[:, 2], round_o_pos[:, 1], round_o_pos[:, 0]
z, y, x = o_pos[:, 2], o_pos[:, 1], o_pos[:, 0]
inds = np.lexsort((z, y, x))
return inds
def __init__(self, gcell):
self.lattice = np.around(gcell.lattice, decimals=6)
self.positions = np.around(gcell.positions, decimals=6)
self.numbers = gcell.numbers
atoms_name_list = list(map(lambda x: Specie.to_name(x),
list(self.numbers)))
d = Counter(atoms_name_list)
ordered_atoms = OrderedDict(sorted(d.items(),
key=lambda x: Specie(x[0]).Z))
# remove Ghostatoms
if 'G' in ordered_atoms:
del ordered_atoms['G']
self.comment = ''.join(['{}{}'.format(k, v)
for k, v in ordered_atoms.items()])
def _pnl_pos(self, e, s, a, pnl, inputs):
'''
Return the reward based on PnL from the last step marked to the
mid-price of the instruments traded
:param e: Environment object. Environment where the agent operates
:param a: Agent object. the agent that will perform the action
:param s: dictionary. The inputs from environment to the agent
:param pnl: float. The current pnl of the agent
:param inputs: dictionary. The inputs from environment to the agent
'''
reward = self._pnl(e, s, a, pnl, inputs)
s_main = e.s_main_intrument
if not a.logged_action:
return reward
f_penalty = abs(e.agent_states[a][s_main]['Position']) * 0.02
f_penalty += abs(np.around(a.log_info['duration'])) * 0.30
return reward - f_penalty
def fixOffset(self, offset, img):
size = img.shape
finalImg = np.ndarray(size)
indices = np.indices((self.videoSize[0],self.videoSize[1])).swapaxes(0,2).swapaxes(0,1)
indices = np.around(indices, decimals=1)
indices.shape = (self.videoSize[1] * self.videoSize[0], 2)
phi = 2 * np.arctan(np.exp(indices[:, 1] / self.videoSize[1])) - 1/2 * np.pi - offset[0]
lamb = indices[:, 0] - offset[1]
x = lamb
y = np.log(np.tan(np.pi / 4 + 1/2 * phi)) * self.videoSize[1]
finalIdx = np.ndarray((self.videoSize[1] * self.videoSize[0], 2))
finalIdx = np.around(finalIdx, decimals=1).astype(int)
finalIdx[:, 1] = y % self.videoSize[1]
finalIdx[:, 0] = x % self.videoSize[0]
finalImg[indices[:,1], indices[:,0]] = img[finalIdx[:,1], finalIdx[:,0]]
return finalImg
def imresizemex(inimg, weights, indices, dim):
in_shape = inimg.shape
w_shape = weights.shape
out_shape = list(in_shape)
out_shape[dim] = w_shape[0]
outimg = np.zeros(out_shape)
if dim == 0:
for i_img in range(in_shape[1]):
for i_w in range(w_shape[0]):
w = weights[i_w, :]
ind = indices[i_w, :]
im_slice = inimg[ind, i_img].astype(np.float64)
outimg[i_w, i_img] = np.sum(np.multiply(np.squeeze(im_slice, axis=0), w.T), axis=0)
elif dim == 1:
for i_img in range(in_shape[0]):
for i_w in range(w_shape[0]):
w = weights[i_w, :]
ind = indices[i_w, :]
im_slice = inimg[i_img, ind].astype(np.float64)
outimg[i_img, i_w] = np.sum(np.multiply(np.squeeze(im_slice, axis=0), w.T), axis=0)
if inimg.dtype == np.uint8:
outimg = np.clip(outimg, 0, 255)
return np.around(outimg).astype(np.uint8)
else:
return outimg
convolutional_gridding.py 文件源码
项目:algorithm-reference-library
作者: SKA-ScienceDataProcessor
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def frac_coord(npixel, kernel_oversampling, p):
""" Compute whole and fractional parts of coordinates, rounded to
kernel_oversampling-th fraction of pixel size
The fractional values are rounded to nearest 1/kernel_oversampling pixel value. At
fractional values greater than (kernel_oversampling-0.5)/kernel_oversampling coordinates are
rounded to next integer index.
:param npixel: Number of pixels in total
:param kernel_oversampling: Fractional values to round to
:param p: Coordinate in range [-.5,.5[
"""
assert numpy.array(p >= -0.5).all() and numpy.array(
p < 0.5).all(), "Cellsize is too large: uv overflows grid uv= %s" % str(p)
x = npixel // 2 + p * npixel
flx = numpy.floor(x + 0.5 / kernel_oversampling)
fracx = numpy.around((x - flx) * kernel_oversampling)
return flx.astype(int), fracx.astype(int)
def test_optimized(self):
"""
Test if optimized works well
"""
lr = self.logistic_regression
lr.set_data(self.iris)
op_theta = lr.optimized()
self.assertEqual(len(op_theta), 4)
# check if really minimal, function is monotonic so everywhere around
# j should be higher
self.assertLessEqual(
lr.j(op_theta), lr.j(op_theta + np.array([1, 0, 0, 0])))
self.assertLessEqual(
lr.j(op_theta), lr.j(op_theta + np.array([0, 1, 0, 0])))
self.assertLessEqual(
lr.j(op_theta), lr.j(op_theta + np.array([0, 0, 1, 0])))
self.assertLessEqual(
lr.j(op_theta), lr.j(op_theta + np.array([0, 0, 0, 1])))
def ani_update(arg, ii=[0]):
i = ii[0] # don't ask...
if np.isclose(t_arr[i], np.around(t_arr[i], 1)):
fig2.suptitle('Evolution (Time: {})'.format(t_arr[i]), fontsize=24)
graphic_robot_1.center = ((x_history[i, 0]+td*np.cos(x_history[i, 2]), x_history[i, 1]+td*np.sin(x_history[i, 2])))
graphic_robot_2.center = ((x_history[i, 0], x_history[i, 1]))
graphic_robot_3.center = ((x_history[i, 0]-td*np.cos(x_history[i, 2]), x_history[i, 1]-td*np.sin(x_history[i, 2])))
ii[0] += int(1 / (dt * framerate))
if ii[0] >= len(t_arr):
print("Resetting animation!")
ii[0] = 0
return None
# Run animation
def ani_update(arg, ii=[0]):
i = ii[0] # don't ask...
if np.isclose(t_arr[i], np.around(t_arr[i], 1)):
fig2.suptitle('Evolution (Time: {})'.format(t_arr[i]), fontsize=24)
graphic_robot_1.center = ((x_history[i, 0]+td*np.cos(x_history[i, 2]), x_history[i, 1]+td*np.sin(x_history[i, 2])))
graphic_robot_2.center = ((x_history[i, 0], x_history[i, 1]))
graphic_robot_3.center = ((x_history[i, 0]-td*np.cos(x_history[i, 2]), x_history[i, 1]-td*np.sin(x_history[i, 2])))
ii[0] += int(1 / (dt * framerate))
if ii[0] >= len(t_arr):
print("Resetting animation!")
ii[0] = 0
return None
# Run animation
def ani_update(arg, ii=[0]):
i = ii[0] # don't ask...
if np.isclose(t_arr[i], np.around(t_arr[i], 1)):
fig2.suptitle('Evolution (Time: {})'.format(t_arr[i]), fontsize=24)
graphic_robot_1.center = ((x_history[i, 0]+td*np.cos(x_history[i, 2]), x_history[i, 1]+td*np.sin(x_history[i, 2])))
graphic_robot_2.center = ((x_history[i, 0], x_history[i, 1]))
graphic_robot_3.center = ((x_history[i, 0]-td*np.cos(x_history[i, 2]), x_history[i, 1]-td*np.sin(x_history[i, 2])))
ii[0] += int(1 / (dt * framerate))
if ii[0] >= len(t_arr):
print("Resetting animation!")
ii[0] = 0
return None
# Run animation
def ani_update(arg, ii=[0]):
i = ii[0] # don't ask...
if np.isclose(t_arr[i], np.around(t_arr[i], 1)):
fig2.suptitle('Evolution (Time: {})'.format(t_arr[i]), fontsize=24)
graphic_robot_1.center = ((x_history[i, 0]+td*np.cos(x_history[i, 2]), x_history[i, 1]+td*np.sin(x_history[i, 2])))
graphic_robot_2.center = ((x_history[i, 0], x_history[i, 1]))
graphic_robot_3.center = ((x_history[i, 0]-td*np.cos(x_history[i, 2]), x_history[i, 1]-td*np.sin(x_history[i, 2])))
ii[0] += int(1 / (dt * framerate))
if ii[0] >= len(t_arr):
print("Resetting animation!")
ii[0] = 0
return None
# Run animation
def update(arg, ii=[0]):
i = ii[0] # don't ask...
if np.isclose(t_arr[i], np.around(t_arr[i], 1)):
fig3.suptitle('Evolution (Time: {})'.format(t_arr[i]), fontsize=24)
link1[0].set_data([0, elb_history[i, 0]], [0, elb_history[i, 1]])
link2[0].set_data([elb_history[i, 0], x_history[i, 0]], [elb_history[i, 1], x_history[i, 1]])
end.set_offsets((x_history[i, 0], x_history[i, 1]))
elb.set_offsets((elb_history[i, 0], elb_history[i, 1]))
ii[0] += int(1 / (dt * framerate))
if ii[0] >= len(t_arr):
print("Resetting animation!")
ii[0] = 0
return [link1, link2, end, elb]
# Run animation
def test_encode_texts():
""" Text encoding is stable.
"""
TEST_SENTENCES = [u'I love mom\'s cooking',
u'I love how you never reply back..',
u'I love cruising with my homies',
u'I love messing with yo mind!!',
u'I love you and now you\'re just gone..',
u'This is shit',
u'This is the shit']
maxlen = 30
batch_size = 32
with open(VOCAB_PATH, 'r') as f:
vocabulary = json.load(f)
st = SentenceTokenizer(vocabulary, maxlen)
tokenized, _, _ = st.tokenize_sentences(TEST_SENTENCES)
model = deepmoji_feature_encoding(maxlen, PRETRAINED_PATH)
encoding = model.predict(tokenized)
avg_across_sentences = np.around(np.mean(encoding, axis=0)[:5], 3)
assert np.allclose(avg_across_sentences, np.array([-0.023, 0.021, -0.037, -0.001, -0.005]))
def myImputer(kernel,sample):
kernelSize = kernel.shape[0];
vectorSize = sample.shape[3];
for fIndex in range(0,int(sample.shape[0])):
for sIndex in range(0,int(sample.shape[1])):
sslice = sample[fIndex][sIndex]
#find the index of -1
[x,y] = np.where(sslice == -1)
#change -1 to 0
sslice[sslice == -1] = 0
if x.size == 0:
continue
#broaden the vector
tempVectorH = np.zeros([int((kernelSize-1)/2),vectorSize])
tempVectorV = np.zeros([vectorSize-1+kernelSize,int((kernelSize-1)/2)])
tempSlice = np.vstack((tempVectorH,sslice,tempVectorH))
tempSlice = np.hstack((tempVectorV,tempSlice,tempVectorV))
zeroSlice = np.zeros(sslice.shape);
for k in range(len(x)):
subSlice = tempSlice[x[k]:x[k]+kernelSize,y[k]:y[k]+kernelSize]
imputerValue = np.sum(subSlice*kernel)
zeroSlice[x[k],y[k]] = np.around(imputerValue)
sslice += zeroSlice.astype("int32")
def round_(a, decimals=0, out=None):
"""
Round an array to the given number of decimals.
Refer to `around` for full documentation.
See Also
--------
around : equivalent function
"""
try:
round = a.round
except AttributeError:
return _wrapit(a, 'round', decimals, out)
return round(decimals, out)
def prepare_basemap(min_lat, min_lon, max_lat, max_lon, delta_lat, delta_lon):
"""
:param min_lat: float
:param min_lon: float
:param max_lat: float
:param max_lon: float
:param delta_lat: float
:param delta_lon: float
:return: A Basemap instance
"""
m = Basemap(projection='cyl', llcrnrlat=min_lat, urcrnrlat=max_lat, urcrnrlon=max_lon,
llcrnrlon=min_lon, resolution='l')
m.drawcountries()
m.drawcoastlines()
m.drawparallels(np.arange(np.around(min_lat, 1), np.around(max_lat, 1), -round(delta_lat) / 5.0),
labels=[1, 0, 0, 0])
m.drawmeridians(np.arange(np.around(min_lon, 1), np.around(max_lon, 1), -round(delta_lon) / 5.0),
labels=[0, 0, 0, 1])
return m
def svimg(totarr):
#print it out:
x,y=totarr.shape
vl = np.around(totarr.flatten(),5)#round to 5 digits
xx = np.repeat(np.arange(x),x)+1
yy = np.tile(np.arange(y),y)+1
big =np.column_stack((xx,yy,vl))
np.savetxt("noisyimage.txt",big,fmt=('%4.1f','%4.1f','%10.5f'))
##Add this if you want to
##read it out to make sure it works
##Otherwise slows down routine.
#row,col,data=np.loadtxt("noisyimage.txt",unpack=True)
#rsize = int(max(row))
#csize = int(max(col))
#data=np.array(data).reshape(rsize,csize)
# plt.imshow(data, interpolation='None',cmap=plt.cm.Greys_r)
def contour_edges(a):
import matplotlib.pyplot as plt
a = checkma(a)
#Contour nodata value
levels = [a.fill_value]
#kw = {'antialiased':True, 'colors':'r', 'linestyles':'-'}
kw = {'antialiased':True}
#Generate contours around nodata
cs = plt.contour(a.filled(), levels, **kw)
#This returns a list of numpy arrays
#allpts = np.vstack(cs.allsegs[0])
#Extract paths
p = cs.collections[0].get_paths()
#Sort by number of vertices in each path
p_len = [i.vertices.shape[0] for i in p]
p_sort = [x for (y,x) in sorted(zip(p_len,p), reverse=True)]
#cp = p[0].make_compound_path(*p)
return p_sort
#Brute force search for edges of valid data
def save_goal_image(self, traj):
rounded = np.around(traj.score, decimals=2)
best_score = np.min(rounded)
for i in range(traj.score.shape[0]):
if rounded[i] == best_score:
first_best_index = i
break
print 'best_score', best_score
print 'allscores', traj.score
print 'goal index: ', first_best_index
goalimage = traj._sample_images[first_best_index]
# goalstate = traj.X_Xdot_full[i]
img = Image.fromarray(goalimage)
cPickle.dump([], open(self._hyperparams['save_goal_image'] + '.pkl', 'wb'))
img.save(self._hyperparams['save_goal_image'] + '.png',)
def evaluate_checkpoints(self, filename):
# Load image
with open(UPLOAD_FOLDER + '/' + filename, 'rb') as f:
image_string = f.read()
# Session
with tf.Session() as sess:
# Restore variables values
self.saver.restore(sess, './models/'+self.loaded_model_name+'/model.ckpt')
prob_values = sess.run(self.probs, feed_dict={
self.input_image_string: image_string
})
pred_idx = prob_values[0].argsort()[-5:][::-1]
pred_class = self.classes[pred_idx - 1] # from 1001 to 1000 classes
pred_score = np.around(100*prob_values[0][pred_idx], decimals=2) # two decimals
return list(pred_class), list(pred_score)
def evaluate_frozen(self, filename):
# Load image
with open(UPLOAD_FOLDER + '/' + filename, 'rb') as f:
image_string = f.read()
# Session
with tf.Session() as sess:
prob_values = sess.run(self.probs, feed_dict={
self.input_image_string: image_string
})
pred_idx = prob_values[0].argsort()[-5:][::-1]
pred_class = self.classes[pred_idx - 1] # from 1001 to 1000 classes
pred_score = np.around(100*prob_values[0][pred_idx], decimals=2) # two decimals
return list(pred_class), list(pred_score)
def histo_plot(figure,X,color,xlabel="",ylabel="",cumul=False,bar=True,n_points=400,smooth_factor=0.1,spline_order=3,linewidth=3,alpha=1.0,label=""):
if '%' in xlabel:
magnitude = 100
X_values = np.array(np.minimum(np.around(X),n_points+1),int)
else:
# magnitude = np.power(10,np.around(4*np.log10(X.mean()))/4+0.5)
magnitude = np.power(10,np.around(4*np.log10(np.nanmean(X)+np.nanstd(X)+1e-7))/4+1)
magnitude = np.around(magnitude,int(-np.log10(magnitude))+1)
# print magnitude
#magnitude = X.mean()+5.0*X.std()
X_values = np.array(np.minimum(np.around(n_points*X[True-np.isnan(X)]/magnitude),n_points+1),int)
X_histo = np.zeros(n_points+1,float)
for x in np.linspace(0,n_points,n_points+1):
X_histo[x] = nd.sum(np.ones_like(X_values,float),X_values,index=x)
if '%' in ylabel:
X_histo[x] /= X_values.size/100.0
if cumul:
X_histo[x] += X_histo[x-1]
if bar:
bar_plot(figure,np.linspace(0,magnitude,n_points+1),X_histo,np.array([1,1,1]),color,xlabel,ylabel,label=label)
else:
smooth_plot(figure,np.linspace(0,magnitude,n_points+1),X_histo,color,color,xlabel,ylabel,n_points=n_points,smooth_factor=smooth_factor,spline_order=spline_order,linewidth=linewidth,alpha=alpha,label=label)
def make_pivots(start, stop, pivots_per_year=12, precision=2):
"""Makes an array of pivots (i.e., timepoints) between the given start and stop
by the given pivots per year. The generated pivots are floating point values
that are then rounded to the requested decimal precision.
>>> list(make_pivots(2000.0, 2001.0, 5))
[2000.0, 2000.25, 2000.5, 2000.75, 2001.0]
"""
# Calculate number of pivots (i.e., months) in the requested interval.
number_of_pivots = np.ceil((stop - start) * pivots_per_year)
# Build an evenly-spaced closed interval (including the start and stop
# points) based on the calculated number of pivots.
return np.around(
np.linspace(start, stop, number_of_pivots),
precision
)