def acceptance(mass=2, ctau=1, sample="hzd", whichbin="lxybin1_ptbin1_isobin1"): if sample == "hzd": if whichbin != "allbins": x_data = hzdbincsv['mass'].tolist() y_data = hzdbincsv['ctau'].tolist() z_data = hzdbincsv['acc_' + whichbin].tolist() elif whichbin == "allbins": x_data = hzdallcsv['mass'].tolist() y_data = hzdallcsv['ctau'].tolist() z_data = hzdallcsv['acc_' + whichbin].tolist() if sample == "bphi": if whichbin != "allbins": x_data = bphibincsv['mass'].tolist() y_data = bphibincsv['ctau'].tolist() z_data = bphibincsv['acc_' + whichbin].tolist() elif whichbin == "allbins": x_data = bphiallcsv['mass'].tolist() y_data = bphiallcsv['ctau'].tolist() z_data = bphiallcsv['acc_' + whichbin].tolist() acc = Rbf(x_data, y_data, z_data, epsilon=0.03) return acc(mass, ctau)
def rbf2d(x, y, z, x_new, y_new, epsilon, smooth, function): try: rbf = Rbf(x, y, z, epsilon=epsilon, smooth=smooth, function=function) except: return False z_new = rbf(x_new, y_new) return z_new
def plot_temporal_V(self): ut = Utils() coord = np.array([self.x, self.y, self.z]).transpose() _, phi, theta = ut.xyz2sph(coord) thetaI = np.linspace(theta.min(), theta.max()) phiI = np.linspace(phi.min(), phi.max()) thetaI, phiI = np.meshgrid(thetaI, phiI) from scipy.interpolate import Rbf dt = self.t[2] - self.t[1] fig = plt.figure(1) # fig2 = plt.figure(2) # fig3 = plt.figure(3) ax = fig.add_subplot(111) # ax2 = fig2.add_subplot(111) # ax3= fig3.add_subplot(111) skip_dt = 100 skip_time_step = int(skip_dt * (self.t.shape[0] - 1) / self.t[-1]) for n in range(0, self.t.shape[0], skip_time_step): print(n * dt) V_tmp = self.V[n] rbf = Rbf(theta, phi, V_tmp, function='linear', smooth=1) V_I = rbf(thetaI, phiI) ax.plot(thetaI[0], V_I[0], label='time:{}'.format(n * dt)) # ax2.imshow(V_I, origin='lower', extent=[thetaI.min(), thetaI.max(), phiI.min(), phiI.max()]) # ax3.scatter(theta, phi, c=V_tmp) ax.set_xlabel('theta') ax.set_ylabel('V') ax.set_title('Fast Variable (V)') ax.grid() ax.legend(loc='center lower', bbox_to_anchor=(1.0, -0.15), ncol=4) fig.tight_layout() return
def __init__(self, core, small_r_limit=None): self.core = core ''' Gunn & Kinzer 1949, Table 2 ''' ir = np.array([.078, .1, .2, .3, .4, .5, .6, .7, .8 , .9, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.2, 4.4, 4.6, 4.8, 5.0, 5.2, 5.4, 5.6, 5.8 ]) * 1e-3 / 2 iu = np.array([18, 27, 72, 117, 162, 206, 247, 287, 327, 367, 403, 464, 517, 565, 609, 649, 690, 727, 757, 782, 806, 826, 844, 860, 872, 883, 892, 898, 903, 907, 909, 912, 914, 916, 917 ]) / 100 rbf = Rbf(ir, iu) self.factor = 100000 num = 6 * self.factor//1000 + 1 space, step = np.linspace(0, .6 * const.si.cm, num, retstep=True) u = np.empty(num) u[:] = rbf(space) u[0] = 0 approximation_small = TpDependent.make(only_small=True) small_r_limit = small_r_limit or 40 * const.si.um approximation_small(u[1:], space[1:], small_r_limit) self.a = core.bck.Storage.from_ndarray(u) b = np.append(np.diff(u), [u[-1] - u[-2]]) / step self.b = core.bck.Storage.from_ndarray(b)
def RBF_weights(volume, control_pts, weight=None): # volume : D* H* W, 3 # pts: N, 3 # weight: N, M if weight is None: weight = np.eye(control_pts.shape[0]) xyz = volume.reshape(-1, 3) chunk = 50000 rbfi = Rbf(control_pts[:, 0], control_pts[:, 1], control_pts[:, 2], weight, function="thin_plate", mode="N-D") # rbfi = Rbf(pts[:, 0], pts[:, 1], pts[:, 2], weight, function="multiquadric", mode="N-D") weight_volume = np.concatenate([ rbfi(xyz[j:j + chunk, 0], xyz[j:j + chunk, 1], xyz[j:j + chunk, 2]) for j in range(0, xyz.shape[0], chunk) ], 0) weight_volume[weight_volume < 0] = 0 weight_volume = weight_volume / np.sum(weight_volume, axis=1).reshape( -1, 1) weight_volume = weight_volume.reshape(xyz.shape[0], -1) return weight_volume
def show_heatmap(self): d = ChooseHeatmapDialog(self.plan._signals) if not d.exec_(): return bssid = d.ssid_combo.currentData() contour = d.contour.isChecked() signals = [] for pos, ps in self.plan._signals.positions(): if bssid in ps: signals.append((pos, ps[bssid])) x = np.array([s[0][0] for s in signals]) y = np.array([s[0][1] for s in signals]) z = np.array([s[1].rssi for s in signals]) # Make evenly-spaced grid of xy values num_grid_x = num_grid_y = 100 grid_x, grid_y = np.meshgrid( np.linspace(0, self.plan.width(), num_grid_x), np.linspace(0, self.plan.height(), num_grid_y)) grid_x = grid_x.flatten() grid_y = grid_y.flatten() # Interpolate on the grid r = Rbf(x, y, z, function='linear') grid_z = r(grid_x, grid_y).reshape((num_grid_y, num_grid_x)) if contour: self.plot_contour(grid_x, grid_y, grid_z) else: self.plot_heatmap(grid_x, grid_y, grid_z)
def density_gradient(pos_data, dens, neigh, buffer, fbox, del_x=3): dn = np.zeros((len(pos_data), 3)) for i, p in enumerate(pos_data): inds = [i] + neigh[i] pos = np.zeros((1, 3), dtype=np.float32) pos[0] = p for j in neigh[i]: if (np.abs(p - pos_data[j]) > fbox.L / 2).any(): pos1 = buffer.buffer_particles[buffer.buffer_ids == j] dists = p - pos1 pos1 = pos1[np.where( np.sqrt(dists[:, 0]**2 + dists[:, 1]**2) < 13)[0]] if pos1.shape[0] == 0: pos1 = pos_data[j] else: pos1 = pos_data[j] # print(pos1) pos = np.concatenate((pos, pos1.reshape(1, 3)), axis=0) rbf = Rbf(pos[:, 0], pos[:, 1], dens[inds]) dn[i][0] = (rbf(p[0] + del_x, p[1]) - rbf(p[0] - del_x, p[1])) / (2 * del_x) dn[i][1] = (rbf(p[0], p[1] + del_x) - rbf(p[0], p[1] - del_x)) / (2 * del_x) del rbf return dn
def __init__(self, lookup_table_file, interpolation_kernel="multiquadric", orthogonalization="gram_schmidt"): self.orthogonalization = orthogonalization _, _, nc_lookup_table, coords \ = load_lookup_table(lookup_table_file) print("Bingham Interpolation Kernel: " + interpolation_kernel) self.interp_options = { "interp_data": torch.from_numpy(nc_lookup_table), "interp_coords": torch.from_numpy(coords) } rbf_file = os.path.splitext(lookup_table_file)[0] + ".rbf" if os.path.exists(rbf_file): with open(rbf_file, 'rb') as file: self.rbf = dill.load(file) else: x, y, z = generate_coordinates( self.interp_options["interp_coords"]) # Limit found empirically. assert len(x) < 71000, "Lookup table too large." print("Creating the interpolator... (this usually takes a while)") self.rbf = Rbf( x, y, z, torch.log(self.interp_options["interp_data"]).numpy().ravel(). squeeze()) with open(rbf_file, 'wb') as file: dill.dump(self.rbf, file)
def plot_samps(df): aniso = (300.) / (750.) fig, ax = plt.subplots(figsize=(15, 15 * aniso)) xx, yy = dgrid(1.) rbfi = Rbf(df.YPT, df.ZPT, df.AU_G_T, function='cubic') zz = rbfi(xx, yy) ax.contour(xx, yy, zz, cog, colors=color_seq, alpha=0.5) ax.imshow(zz, origin='lower', extent=(0., 750, 0., 300.), alpha=0.2, cmap=cmap, norm=norm) scat = ax.scatter(df.YPT, df.ZPT, c=df.AU_G_T, cmap=cmap, norm=norm, edgecolor="black", s=40) cbar = fig.colorbar(scat, ticks=cog) cbar.set_label('Au g/t', rotation=0) plt.xlim((0, 750)) plt.ylim((0, 300)) plt.xlabel('X') plt.ylabel('Y') return fig, ax
def splinevalue(x, y): x_data = data[0] y_data = data[1] z_data = data[2] rbf = Rbf(x_data, y_data, z_data, epsilon=0.03) return rbf(x, y)
def buildInterp(self): Px = list() Py = list() for i in range(0, len(self.PTs)): Px.append(self.PTs[i][0][1][0]) Py.append(self.PTs[i][0][1][1]) Px = np.array(Px) Py = np.array(Py) iX = Rbf(self.qBi1Ratio, self.SBi1Ratio, self.qDi1Ratio, self.SDi1Ratio, Px) iY = Rbf(self.qBi1Ratio, self.SBi1Ratio, self.qDi1Ratio, self.SDi1Ratio, Py) self.iX = iX self.iY = iY
def process(self): if not any(socket.is_linked for socket in self.outputs): return vertices_s = self.inputs['Vertices'].sv_get() faces_s = self.inputs['Faces'].sv_get() fields_out = [] for vertices, faces in zip_long_repeat(vertices_s, faces_s): if self.interpolate and scipy is None: self.info("Normal interpolation mode was enabled earlier, but scipy is not available currently. Will not apply interpolation.") if self.interpolate and scipy is not None: bvh = bvhtree.BVHTree.FromPolygons(vertices, faces) bm = bmesh_from_pydata(vertices, [], faces, normal_update=True) normals = np.array([f.normal for f in bm.faces]) centers = np.array([f.calc_center_median() for f in bm.faces]) bm.free() xs_from = centers[:,0] ys_from = centers[:,1] zs_from = centers[:,2] rbf = Rbf(xs_from, ys_from, zs_from, normals, function = self.function, mode = 'N-D') field = SvBvhRbfNormalVectorField(bvh, rbf) else: field = SvBvhAttractorVectorField(verts=vertices, faces=faces, use_normal=True, signed_normal=self.signed) fields_out.append(field) self.outputs['Field'].sv_set(fields_out)
def RBFInterpolation(data=None, mask=None, filePath=""): results = np.zeros(data.shape) for i in range(data.shape[0]): if i % 100 == 0: print(i) temp = np.zeros((int(np.sum(mask[i, :, :, 0].flatten())), 3)) index = 0 for j in range(data.shape[1]): for k in range(data.shape[2]): if mask[i, j, k, 0] == 1: temp[index, 0] = k temp[index, 1] = j temp[index, 2] = data[i, j, k, 0] index = index + 1 ti = np.linspace(0, 41, 41) x, y = np.meshgrid(ti, ti) rbf = Rbf(temp[:, 0], temp[:, 1], temp[:, 2], epsilon=2) z = rbf(x, y) results[i, :, :, 0] = z # plt.subplot(121) # plt.imshow(z) # plt.subplot(122) # plt.imshow(data[i,:,:,0]) # plt.show() np.save(filePath, results) return results
def interpolate(x, y, z, hres=50000, interp_type="linear", rbf_func='linear', rbf_smooth=0, spatial_pad=0): grid_x, grid_y = generate_grid( hres, get_boundary_coords(x, y, spatial_pad=spatial_pad)) if interp_type in ['linear', 'nearest', 'cubic']: points_zip = np.array(list(zip(x, y))) img = griddata(points_zip, z, (grid_x, grid_y), method=interp_type) elif interp_type == 'rbf': h = np.zeros((len(x))) rbfi = Rbf(x, y, h, z, function=rbf_func, smooth=rbf_smooth) hi = np.zeros(grid_x.shape) img = rbfi(grid_x, grid_y, hi) else: raise ValueError('Interpolation option not available. ' 'Try: linear, nearest, cubic, rbf') return grid_x, grid_y, img
def get_interpolated_rbf(nx, ny, xc, yc, v, smooth=1.e-12, nsample=16, nr=1000): from scipy.interpolate import Rbf rbf = Rbf(xc, yc, v, smooth=smooth) nn = nsample XI, YI = np.meshgrid(np.arange(0, nx), np.arange(0, ny)) xi_r4 = np.ravel(XI[::nn,::nn]) yi_r4 = np.ravel(YI[::nn,::nn]) d, r = divmod(len(xi_r4), nr) ii = [nr] * d + [r] zi_list = [] for i in range(d+1): xi = xi_r4[i*nr:(i+1)*nr] yi = yi_r4[i*nr:(i+1)*nr] zi = rbf(xi, yi) zi_list.append(zi) ZI4 = np.concatenate(zi_list).reshape(XI[::nn,::nn].shape) ZI = ni.zoom(ZI4, nn) return ZI
def __init__(self, params, func_vals, saved_rbf=maszcal.nothing.NoSavedRbf()): params = maszcal.mathutils.atleast_kd(params, 2) point_vals = make_flat(func_vals) self.rbfi = Rbf(*params.T, point_vals, function=self.rbf_function)
def changePointsAndProbability(points, probability): # unwrap points x = [] y = [] for point in points: x.append(point[0]) y.append(point[1]) # get new points z = [] for p in probability: if p < 0: z.append(0.15) else: if p > 0.16: z.append(0.05) else: z.append(0.15 - 0.625 * p) # bubble point points_new = bubblePoints(x, y, z, 5.0) x_new = [] y_new = [] for point in points_new: x_new.append(point[0]) y_new.append(point[1]) rbf_p = Rbf(x, y, probability) probability_new = list(rbf_p(x_new, y_new)) return points_new, probability_new
def generate_input_rates(module_field_width_dict, basis_function='gaussian', spacing_factor=1.0, peak_rate=1.): input_nodes_dict = {} input_groups_dict = {} input_rates_dict = {} for m in module_field_width_dict: nodes, groups, _ = poisson_disc_nodes(module_field_width_dict[m], (vert, smp)) input_groups_dict[m] = groups input_nodes_dict[m] = nodes input_rates_dict[m] = {} for i in range(nodes.shape[0]): xs = [[nodes[i, 0], nodes[i, 1]]] x_obs = np.asarray(xs).reshape((1, -1)) u_obs = np.asarray([[peak_rate]]).reshape((1, -1)) if basis_function == 'constant': input_rate_ip = lambda xx, yy: xx, yy else: input_rate_ip = Rbf(x_obs[:, 0], x_obs[:, 1], u_obs, function=basis_function, epsilon=module_field_width_dict[m] * spacing_factor) input_rates_dict[m][i] = input_rate_ip return input_nodes_dict, input_groups_dict, input_rates_dict
def make_surface(self, curve, epsilon, smooth, samples): t_min, t_max = curve.get_u_bounds() curve_ts = np.linspace(t_min, t_max, num=samples) curve_points = curve.evaluate_array(curve_ts) dvs = curve_points[1:] - curve_points[:-1] segment_lengths = np.linalg.norm(dvs, axis=1) last_segment_length = np.linalg.norm(curve_points[0] - curve_points[-1]) if last_segment_length < 0.001: # curve is closed: remove the last segment to make it non-closed segment_lengths = segment_lengths[:-1] curve_points = curve_points[:-1] last_segment_length = np.linalg.norm(curve_points[0] - curve_points[-1]) # T=0 will correspond to the center of gap between first and last point dt = min(last_segment_length / 2.0, segment_lengths.min()) cum_segment_lengths = np.insert(np.cumsum(segment_lengths), 0, 0) total_length = cum_segment_lengths[-1] + last_segment_length ts = cum_segment_lengths + dt ts = 2*pi * ts / total_length us = np.cos(ts) vs = np.sin(ts) rbf = Rbf(us, vs, curve_points, function = self.function, epsilon = epsilon, smooth = smooth, mode = 'N-D') surface = SvRbfSurface(rbf, 'UV', 'Z', Matrix()) surface.u_bounds = (-1.0, 1.0) surface.v_bounds = (-1.0, 1.0) return surface
def process(self): if not any(socket.is_linked for socket in self.outputs): return vertices_s = self.inputs['Vertices'].sv_get() vertices_s = ensure_nesting_level(vertices_s, 3) epsilon_s = self.inputs['Epsilon'].sv_get() smooth_s = self.inputs['Smooth'].sv_get() curves_out = [] for vertices, epsilon, smooth in zip_long_repeat(vertices_s, epsilon_s, smooth_s): if isinstance(epsilon, (list, int)): epsilon = epsilon[0] if isinstance(smooth, (list, int)): smooth = smooth[0] vertices = np.array(vertices) ts = make_euclidian_ts(vertices) rbf = Rbf(ts, vertices, function=self.function, smooth=smooth, epsilon=epsilon, mode='N-D') curve = SvExRbfCurve(rbf, (0.0, 1.0)) curves_out.append(curve) self.outputs['Curve'].sv_set(curves_out)
def spline_approximation(ped_indices, ped_x, ped_y): ''' Approximates missing frame poses through 2D spline approximation 1st function assumption is y = f(x, t) where f is a radial basis function 2nd function assumption is x = g(y, t) where g is a radial basis function Goal: Find best v, w s.t. v approx = g(f(x, t), t) and w approx = f(g(y, t), t) ''' y_spline_fnc = Rbf(ped_x, ped_indices, ped_y) # y = f(x, t) x_spline_fnc = Rbf(ped_y, ped_indices, ped_x) # x = f(y, t) max_radius = 2 # search range for missing data best # are 2 or 3 tol = 1 # From start_index to end_index determine the value of x, y for the missing_index start_index = ped_indices[0] end_index = ped_indices[-1] ped_track = None frame_pos = 0 for i in range(start_index, end_index + 1): if i in ped_indices: x = ped_x[frame_pos] y = ped_y[frame_pos] if ped_track is None: ped_track = np.asarray([x, y])[np.newaxis, ...] else: pose = np.asarray([x, y])[np.newaxis, ...] ped_track = np.concatenate((ped_track, pose), axis=0) frame_pos = frame_pos + 1 else: # Determining missing observation x, y values given a range from max_radius x_prev = ped_track[-1, 0] y_prev = ped_track[-1, 1] x_space = np.arange(x_prev - max_radius, x_prev + max_radius) y_space = np.arange(y_prev - max_radius, y_prev + max_radius) i_repeat = np.repeat(i, x_space.shape[0]) y_approx = y_spline_fnc(x_space, i_repeat) x_approx = x_spline_fnc(y_space, i_repeat) y_guess = y_spline_fnc(x_approx, i_repeat) x_guess = x_spline_fnc(y_approx, i_repeat) x_diff = np.power(x_space - x_guess, 2) y_diff = np.power(y_space - y_guess, 2) x_index = np.where(x_diff == np.min(x_diff))[0] y_index = np.where(y_diff == np.min(y_diff))[0] x = x_space[x_index[0]] y = y_space[x_index[0]] pose = np.asarray([x, y])[np.newaxis, ...] ped_track = np.concatenate((ped_track, pose), axis=0) return ped_track, np.arange(start_index, end_index + 1)
def plot_exciton_2D_ax(self, ax, excitons, f=None, mode='hexagon', limfactor=0.8, **kwargs): """ Plot the exciton weights in a 2D Brillouin zone Arguments: excitons -> list of exciton indexes to plot f -> function to apply to the exciton weights. Ex. f=log will compute the log of th weight to enhance the small contributions mode -> possible values are 'hexagon' to use hexagons as markers for the weights plot and 'rbf' to interpolate the weights using radial basis functions. limfactor -> factor of the lattice parameter to choose the limits of the plot scale -> size of the markers """ x, y, weights_bz_sum = self.get_exciton_2D(excitons, f=f) #filter points outside of area lim = np.max(self.lattice.rlat) * limfactor dlim = lim * 1.1 filtered_weights = [ [xi, yi, di] for xi, yi, di in zip(x, y, weights_bz_sum) if -dlim < xi and xi < dlim and -dlim < yi and yi < dlim ] x, y, weights_bz_sum = np.array(filtered_weights).T #plotting if mode == 'hexagon': scale = kwargs.pop('scale', 1) ax.scatter(x, y, s=scale, marker='H', c=weights_bz_sum, rasterized=True, **kwargs) ax.set_xlim(-lim, lim) ax.set_ylim(-lim, lim) elif mode == 'rbf': from scipy.interpolate import Rbf npts = kwargs.pop('npts', 100) interp_method = kwargs.pop('interp_method', 'bicubic') rbfi = Rbf(x, y, weights_bz_sum, function='linear') x = y = np.linspace(-lim, lim, npts) weights_bz_sum = np.zeros([npts, npts]) for col in range(npts): weights_bz_sum[:, col] = rbfi(x, np.ones_like(x) * y[col]) ax.imshow(weights_bz_sum, interpolation=interp_method) title = kwargs.pop('title', str(excitons)) ax.set_title(title) ax.set_aspect('equal') ax.set_xticks([]) ax.set_yticks([]) return ax
def interpolateV(points, values, xi): """ Parameters ---------- points : 2-D ndarray of floats with shape (m, D), or length D tuple of 1-D ndarrays with shape (m,). Data point coordinates. values : ndarray of float or complex, shape (m, r). V Matrix from SVD (not V.T!) Data values. xi : 2-D ndarray of floats with shape (m, D), or length D tuple of ndarrays broadcastable to the same shape. Points at which to interpolate data. Returns ------- V_interpolated : ndarray Array of interpolated values. n: n_modes = n_nodes*4 (u,v,p,t) D: 2 (time and Tamb or mu) r: 12 reduced rank """ m, D = points.shape m, r = values.shape # m, n_modes d1, D = xi.shape # snapshots_per_dataset d2 = m // d1 # n_trainingsets assert m == d1 * d2, "?" V_interpolated = np.zeros((d1, r)) for i in range(r): # points.shape (400, 2) | vals.shape (400, ) | xi.shape (50, 2) vals = values[:, i].numpy().copy() if vals.shape[0] != points.shape[0]: # print("repeat each oscillation") # print(points.shape, vals.shape, xi.shape) d_ = vals.reshape(d1, d2) # 50, 1 # print(d_.shape) # 8, 3*150 repeats each oscillation d = np.concatenate((d_, d_, d_), axis=0) # print(d.shape) vals = d.ravel() # print(np.allclose(vals, d.ravel())) # print(2, points.shape, vals.shape, xi.shape) # methods: # "linear" or "nearest" call RegularGridInterpolator # "splinef2d" calls RectBivariateSpline v = interpn(points, vals, xi) # includes expensive triangulation! # methods: # 'linear' calls LinearNDInterpolator # 'nearest' calls NearestNDInterpolator # 'cubic' calls CloughTocher2DInterpolator v = griddata(points, vals, xi, method='linear') rbfi = Rbf(points[..., 0], points[..., 1], vals) v = rbfi(xi[..., 0], xi[..., 1]) V_interpolated[:, i] = v.copy() return V_interpolated
def make(vertices): vertices = np.array(vertices) ts = make_euclidian_ts(vertices) rbf = Rbf(ts, vertices, function=self.function, smooth=smooth, epsilon=epsilon, mode='N-D') return SvExRbfCurve(rbf, (0.0, 1.0))
def rbf(x, y, z, grid, func='thin_plate', epsilon=None, smooth=0.05, norm='euclidean', **settings): # create the object f = Rbf(x, y, z, function=func, epsilon=epsilon, smooth=smooth, norm=norm) # get the shape shape = grid[0].shape return f(grid[0].flatten(), grid[1].flatten()).reshape(shape)
def __init__(self, X, Disp): np, n_nodes, dim = X.shape # X is of the form [pressures, nodes, [x y p]] # I need to construct P * 3 rbf models for each disp self.p = X[:, 0, 2] # pressures self.rbf_models_dx = [] self.rbf_models_dy = [] self.rbf_models_dz = [] for i in range(np): x = X[i, :, 0] y = X[i, :, 1] self.rbf_models_dx.append( Rbf(x, y, Disp[i, :, 0], function='linear')) self.rbf_models_dy.append( Rbf(x, y, Disp[i, :, 1], function='linear')) self.rbf_models_dz.append( Rbf(x, y, Disp[i, :, 2], function='linear'))
def build_model(self): """ Interpolated values. Parameters ---------- method: type of approximation. Returns ------- int_value: array Interpolated values from the input variables. """ if self.option is not None: self.model = Rbf(*self.input_vars.T, self.output_vars, function=self.option) self.model = Rbf(*self.input_vars.T, self.output_vars)
def spline_points(cls, X, Y, Z, xi, yi): """Creates a spline for given set of points. Uses Radial-basis function to extrapolate surfaces. It's not the best but gives something. Griddata algorithm didn't work. """ spline = Rbf(X, Y, Z, function='cubic') return spline(xi, yi)
def _plot(self, a, key, title, gx, gy, num_x, num_y): logger.debug('Plotting: %s', key) pp.rcParams['figure.figsize'] = (self._image_width / 300, self._image_height / 300) pp.title(title) # Interpolate the data rbf = Rbf(a['x'], a['y'], a[key], function='linear') z = rbf(gx, gy) z = z.reshape((num_y, num_x)) # Render the interpolated data to the plot pp.axis('off') # begin color mapping if 'min' in self.thresholds.get(key, {}): vmin = self.thresholds[key]['min'] logger.debug('Using min threshold from thresholds: %s', vmin) else: vmin = min(a[key]) logger.debug('Using calculated min threshold: %s', vmin) if 'max' in self.thresholds.get(key, {}): vmax = self.thresholds[key]['max'] logger.debug('Using max threshold from thresholds: %s', vmax) else: vmax = max(a[key]) logger.debug('Using calculated max threshold: %s', vmax) norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax, clip=True) mapper = cm.ScalarMappable(norm=norm, cmap='RdYlBu_r') # end color mapping image = pp.imshow(z, extent=(0, self._image_width, self._image_height, 0), cmap='RdYlBu_r', alpha=0.5, zorder=100, vmin=vmin, vmax=vmax) pp.colorbar(image) pp.imshow(self._layout, interpolation='bicubic', zorder=1, alpha=1) labelsize = FontManager.get_default_size() * 0.4 # begin plotting points for idx in range(0, len(a['x'])): if (a['x'][idx], a['y'][idx]) in self._corners: continue pp.plot(a['x'][idx], a['y'][idx], marker='o', markeredgecolor='black', markeredgewidth=1, markerfacecolor=mapper.to_rgba(a[key][idx]), markersize=6) pp.text(a['x'][idx], a['y'][idx] - 30, a['ap'][idx], fontsize=labelsize, horizontalalignment='center') # end plotting points fname = '%s_%s.png' % (key, self._title) logger.info('Writing plot to: %s', fname) pp.savefig(fname, dpi=300) pp.close('all')
def interpolate_image(img, num_points=2, method='RectBivariateSpline', kind='quadratic'): """ Interpolate an image. Parameters ---------- img : (N, M) ndarray Input image. num_points : int, optional Number of points introduced between fixed data points. method : str, optional Method used to interpolate. Must be `rbf`, `interp2d` or `RectBivariateSpline`. kind : str, optional Function used to interpolate. For valid parameters, see the `kind` argument of `np.interpolate.interp2d` or the `function` argument of `np.interpolate.Rbf`. Returns ------- interp_img : (N*num_points, M*num_points) ndarray Notes ----- For `RectBivariateSpline`, available kinds are: `linear`, `quadratic`, `cubic`. """ # Data points for interpolation x, y = np.indices(img.shape) z = np.ravel(img) # Interpolation grid num_points += 1 # need to increment for linspace ti = np.linspace(0, img.shape[0], num_points*img.shape[0], endpoint=False) tj = np.linspace(0, img.shape[1], num_points*img.shape[1], endpoint=False) # Interpolate Xi, Yi = np.meshgrid(ti, tj) if method.lower() == 'rbf': function = Rbf(x, y, z, epsilon=2, function=kind) Zi = function(Xi, Yi) elif method.lower() == 'interp2d': function = interp2d(x, y, z, kind=kind, fill_value=0) Zi = function(ti, tj) elif method.lower() == 'rectbivariatespline': if kind.lower() == 'linear': k = 1 elif kind.lower() == 'quadratic': k = 2 elif kind.lower() == 'cubic': k = 3 else: raise ValueError('Wrong kind') xi, yi = x[:, 0], y[0, :] function = RectBivariateSpline(yi, xi, img.T, kx=k, ky=k) Zi = function(tj, ti) else: raise ValueError('Wrong method') return Zi.reshape((tj.size, ti.size)).T