def __init__( self, model, t_eval=np.geomspace(1, 1e30, 500), rtol=1e-8, method="RK45", save=False, ): self.r_ax = model.rc_ax self.t_ax = model.tc_ax self.vr_field = interpolate.RegularGridInterpolator( (self.r_ax, self.t_ax), model.vr[..., 0], bounds_error=False, fill_value=None, ) self.vt_field = interpolate.RegularGridInterpolator( (self.r_ax, self.t_ax), model.vt[..., 0], bounds_error=False, fill_value=None, ) self.t_eval = t_eval self.rtol = rtol self.method = method self.streamlines = [] self._hit_midplane.terminal = True self.save = save self.value_list = [] if hasattr(model, "rhogas"): self.add_value("rhogas", model.rhogas, "g cm^-3") if hasattr(model, "Tgas"): self.add_value("Tgas", model.Tgas, "K")
def __init__(self, brDistribution, bzDistribution, plotCubeX0, plotCubeY0, plotCubeZ0): self.brDistribution = brDistribution self.bzDistribution = bzDistribution self.plotCubeX0 = plotCubeX0 self.plotCubeY0 = plotCubeY0 self.plotCubeZ0 = plotCubeZ0 # https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp2d.html#scipy.interpolate.interp2d rs = brDistribution.index.values.ravel() zs = brDistribution.columns.values.ravel() # _rs, _zs = nu.meshgrid(rs, zs, indexing='ij') self.__interpolatedBrFunc = interpolate.RegularGridInterpolator( points=(rs, zs), values=self.brDistribution.values, method='linear', bounds_error=False, fill_value=0.0) self.__interpolatedBzFunc = interpolate.RegularGridInterpolator( points=(rs, zs), values=self.bzDistribution.values, method='linear', bounds_error=False, fill_value=0.0) # create b field distribution plots bFieldPlotPoints = 10 xs = nu.linspace(-plotCubeX0, plotCubeX0, bFieldPlotPoints) ys = nu.linspace(-plotCubeY0, plotCubeY0, bFieldPlotPoints) zs = nu.linspace(-plotCubeZ0, plotCubeZ0, bFieldPlotPoints) _xs, _ys, _zs, bs_x, bs_y, bs_z = self.bsAt(xs=xs, ys=ys, zs=zs) length = 0.03 arrow_length_ratio = 0.8 self.bFieldQuiverProperties = (_xs, _ys, _zs, bs_x, bs_y, bs_z, length, arrow_length_ratio)
def __init__( self, r_ax, t_ax, vr, vt, pos0list, t_span=(1, 1e30), t_eval=None, nt=500, rtol=1e-8, method="RK45", ): self.r_ax = r_ax self.t_ax = t_ax self.vr_field = interpolate.RegularGridInterpolator((r_ax, t_ax), vr, bounds_error=False, fill_value=None) self.vt_field = interpolate.RegularGridInterpolator((r_ax, t_ax), vt, bounds_error=False, fill_value=None) self.pos0list = pos0list self.t_eval = (t_eval if t_eval is not None else np.geomspace( t_span[0], t_span[-1], nt)) self.rtol = rtol self.method = method self.streamlines = [] self.value_list = [] self._hit_midplane.terminal = True
def makeInterpolator(self): """ Makes a linear interpolator :return: Fills out self. interpolator and sets self.interpExists = 1 after interpolator is calculated """ shape = self.vol.shape print(shape) img = self.vol.get_data() #TODO other shapes like scalars most impot if len(shape) > 3: if shape[3] == 3: i = np.linspace(0, shape[0] - 1, num=shape[0]) j = np.linspace(0, shape[1] - 1, num=shape[1]) k = np.linspace(0, shape[2] - 1, num=shape[2]) self.interpolator = [ interpolate.RegularGridInterpolator( (i, j, k), img[:, :, :, f]) for f in range(shape[3]) ] self.interpExists = 1 if shape[3] == 1: i = np.linspace(0, shape[0] - 1, num=shape[0]) j = np.linspace(0, shape[1] - 1, num=shape[1]) k = np.linspace(0, shape[2] - 1, num=shape[2]) self.interpolator = interpolate.RegularGridInterpolator( (i, j, k), img[:, :, :, 0]) self.interpExists = 1 else: i = np.linspace(0, shape[0] - 1, num=shape[0]) j = np.linspace(0, shape[1] - 1, num=shape[1]) k = np.linspace(0, shape[2] - 1, num=shape[2]) self.interpolator = interpolate.RegularGridInterpolator( (i, j, k), img[:, :, :]) self.interpExists = 1
def uv_list_to_baseline_measurements(baseline_table_object, frequency, visibility_grid, uv_grid, interpolation='spline'): u_bin_centers = uv_grid[0] v_bin_centers = uv_grid[1] baseline_coordinates = numpy.array([ baseline_table_object.u(frequency), baseline_table_object.v(frequency) ]) # now we have the bin edges we can start binning our baseline table # Create an empty array to store our baseline measurements in if interpolation == "linear": real_component = interpolate.RegularGridInterpolator( [u_bin_centers, v_bin_centers], numpy.real(visibility_grid)) imag_component = interpolate.RegularGridInterpolator( [u_bin_centers, v_bin_centers], numpy.imag(visibility_grid)) visibilities = real_component( baseline_coordinates.T) + 1j * imag_component( baseline_coordinates.T) elif interpolation == 'spline': real_component = interpolate.RectBivariateSpline( u_bin_centers, v_bin_centers, numpy.real(visibility_grid)) imag_component = interpolate.RectBivariateSpline( u_bin_centers, v_bin_centers, numpy.imag(visibility_grid)) visibilities = real_component.ev(baseline_coordinates[0, :], baseline_coordinates[1, :]) + \ 1j*imag_component.ev(baseline_coordinates[0, :], baseline_coordinates[1, :]) return visibilities
def __init__(self, db, mode='counts'): self.db = db self.db['lat_axis'] = np.arccos(np.sqrt(1.0 / db['L_axis'])) * R2D if mode == 'counts': # Electron number flux n_key = 'N_NH' s_key = 'N_SH' else: # Energy flux n_key = 'Q_NH' s_key = 'Q_SH' self.N_interp = interpolate.RegularGridInterpolator( (self.db['inlats'], self.db['lat_axis'], self.db['lon_axis']), self.db[n_key], fill_value=0, bounds_error=False) self.S_interp = interpolate.RegularGridInterpolator( (self.db['inlats'], self.db['lat_axis'], self.db['lon_axis']), self.db[s_key], fill_value=0, bounds_error=False) # Initialize any other parameters we might store: self.precalculated = None self.pc_inlats = None self.pc_L = None self.pc_lon = None
def resample_2d_complex(array, sample_pts, query_pts): ''' Resamples a 2D complex array by interpolating the magnitude and phase independently and merging the results into a complex value. Args: array (numpy.ndarray): complex 2D array. sample_pts (tuple): pair of numpy.ndarray objects that contain the x and y sample locations, each array should be 1D. query_pts (tuple): points to interpolate onto, also 1D for each array. Returns: numpy.ndarray array resampled onto query_pts via bivariate spline ''' xq, yq = np.meshgrid(*query_pts) mag = abs(array) phase = np.angle(array) magfunc = interpolate.RegularGridInterpolator(sample_pts, mag) phasefunc = interpolate.RegularGridInterpolator(sample_pts, phase) interp_mag = magfunc((yq, xq)) interp_phase = phasefunc((yq, xq)) return interp_mag * exp(1j * interp_phase)
def resample_2d_complex(array, sample_pts, query_pts): '''Resamples a 2D complex array. Works by interpolating the magnitude and phase independently and merging the results into a complex value. Parameters ---------- array : `numpy.ndarray` complex 2D array sample_pts : `tuple` pair of `numpy.ndarray` objects that contain the x and y sample locations, each array should be 1D query_pts : `tuple` points to interpolate onto, also 1D for each array Returns ------- `numpy.ndarray` array resampled onto query_pts via bivariate spline ''' xq, yq = m.meshgrid(*query_pts) mag = abs(array) phase = m.angle(array) magfunc = interpolate.RegularGridInterpolator(sample_pts, mag) phasefunc = interpolate.RegularGridInterpolator(sample_pts, phase) interp_mag = magfunc((yq, xq)) interp_phase = phasefunc((yq, xq)) return interp_mag * m.exp(1j * interp_phase)
def simulate(self): # a. solve the model at current parameters m1, c1, m2, c2 = self.solve() # b. construct interpolaters c1_interp = interpolate.RegularGridInterpolator([m1], c1, bounds_error=False, fill_value=None) c2_interp = interpolate.RegularGridInterpolator([m2], c2, bounds_error=False, fill_value=None) # c. sim period 1 based on draws of initial m and solution sim_c1 = c1_interp(self.sim_m1) sim_a1 = self.sim_m1 - sim_c1 # d. transition to period 2 m based on random draws sim_m2 = (1 + self.par.r) * sim_a1 + np.random.choice( [0.5, 1.5], p=[0.5, 0.5], size=(sim_a1.shape)) # e. sim period 2 consumption choice based on model solution and sim_m2 sim_c2 = c2_interp(sim_m2) return sim_c1, sim_c2
def SaveHeightasTiff(height_map,filename,input_feature_size=4.29e-6,output_feature_size=1e-6,mask_size=5.6e-3,quantization_res=21.16e-9,Interp_Method='Nearest'): #height_map is given in meters and should be saved as a 32-bit integer where 0=0 nm and 1=21.16 nm (quantization_res) #Interpolate the height_map to a higher resolution, then resample at the output_feature_size #Nearest neighbor interpolation works by far the best assert (np.allclose(np.mod(mask_size, output_feature_size), 0.)), "mask_size must be a common multiple of the output_feature_size" height_map = height_map/1e-6#Perform interpolation in um x_input = np.arange(height_map.shape[0]) * input_feature_size y_input = np.arange(height_map.shape[1]) * input_feature_size if Interp_Method=='Nearest': f = interp.RegularGridInterpolator((x_input,y_input), height_map,method='nearest',bounds_error=False,fill_value=0.) elif Interp_Method=='Linear': f = interp.RegularGridInterpolator((x_input, y_input), height_map, method='linear', bounds_error=False, fill_value=0.) else: f = interp.RectBivariateSpline(x_input, y_input, height_map, bbox=[None, None, None, None], kx=3, ky=3, s=0) n_pixel_out = int(mask_size / output_feature_size) if Interp_Method=='Nearest' or Interp_Method=='Linear': grid_x_out, grid_y_out = np.mgrid[0:n_pixel_out, 0:n_pixel_out]*output_feature_size grid_x_out=grid_x_out.flatten() grid_y_out=grid_y_out.flatten() points_out = np.array((grid_x_out,grid_y_out)).T resampled_height_map = f(points_out) resampled_height_map=np.reshape(resampled_height_map,(n_pixel_out,n_pixel_out)) else: x_output = np.arange(n_pixel_out) * output_feature_size y_output = np.arange(n_pixel_out) * output_feature_size resampled_height_map = f(x_output,y_output) resampled_height_map = np.clip(resampled_height_map,height_map.min(),height_map.max()) # Quantize the height map to the nearest quantization_res. Save as a fp value in um and as a integer value, where 0 = 0 and 1 = quantization_res quantized_resampled_height_map_fp = (np.floor((resampled_height_map)/(quantization_res/1e-6))*(quantization_res/1e-6)).astype(np.float32) quantized_resampled_height_map_int = (np.floor((resampled_height_map) / (quantization_res / 1e-6))).astype(np.int32) # In um, quantized to nearest 21.16nm # import matplotlib.pyplot as plt # plt.subplot(121) # imgplot = plt.imshow((height_map)) # plt.colorbar(imgplot) # plt.title('Height Map After Interpolation') # plt.subplot(122) # imgplot = plt.imshow((resampled_height_map)) # plt.colorbar(imgplot) # plt.title('Height Map After Interpolation') # plt.show() # # import matplotlib.pyplot as plt # plt.subplot(121) # height_map_slice = height_map[1000,:] # imgplot = plt.hist(height_map_slice) # plt.title('Height Map Slice After Interpolation') # plt.subplot(122) # resampled_height_map_slice = resampled_height_map[2500,:] # imgplot = plt.hist(resampled_height_map_slice) # plt.title('Height Map Slice After Interpolation') # plt.show() filename_fp=filename + "_fp32_wrt_um.tiff" imsave(filename_fp, quantized_resampled_height_map_fp) filename_int=filename + "_integer.tiff" imsave(filename_int, quantized_resampled_height_map_int) return [resampled_height_map,quantized_resampled_height_map_fp,quantized_resampled_height_map_int]
def main(): args = parse_args() fixed_img = skio.imread(args.fixed_img, as_gray=True) fixed_annot = np.loadtxt(args.fixed_annot, delimiter=',', skiprows=1, dtype=np.int32) moved_img = skio.imread(args.moved_img, as_gray=True) moved_annot = np.loadtxt(args.moved_annot, delimiter=',', skiprows=1, dtype=np.int32) # load map data mapdata = get_map_from_h5(args.map, args.map_group) nodes_x, nodes_y = get_nodes_from_h5(args.map, args.map_group) # update csv points from interpolated map interp_x = si.RegularGridInterpolator((nodes_x, nodes_y), mapdata[0]) interp_y = si.RegularGridInterpolator((nodes_x, nodes_y), mapdata[1]) offsets_x = interp_x(fixed_annot[:, 1:]) offsets_y = interp_y(fixed_annot[:, 1:]) # Set figsize for 1:1 pixels figsize = (fixed_img.shape[1] / dpi, fixed_img.shape[0] / dpi) fig = mf.Figure(figsize=figsize) canvas = mplbea.FigureCanvasAgg(fig) ax = fig.add_axes((0, 0, 1, 1)) ax.set_axis_off() ax.imshow(fixed_img, cmap=cols1[0], aspect='auto') ax.imshow(moved_img, cmap=cols2[0], alpha=0.5, aspect='auto') ax.plot(fixed_annot[:, 1], fixed_annot[:, 2], color=cols1[1], marker='.', linestyle="none", markersize="1") ax.plot(moved_annot[:, 1], moved_annot[:, 2], color=cols2[1], marker='.', linestyle="none", markersize="1") ax.quiver(fixed_annot[:, 1], fixed_annot[:, 2], offsets_x, offsets_y, angles='xy', scale_units='xy', scale=1) fig.savefig(args.output, dpi=dpi)
def __init__( self, plasma, particle_type="p", n_particles=1, scaling=1, dt=np.inf * u.s, nt=np.inf, integrator="explicit_boris", ): if np.isinf(dt) and np.isinf(nt): # coverage: ignore raise ValueError("Both dt and nt are infinite.") self.q = atomic.charge_number(particle_type) * constants.e.si self.m = atomic.particle_mass(particle_type) self.N = int(n_particles) self.scaling = scaling self.eff_q = self.q * scaling self.eff_m = self.m * scaling self.plasma = plasma self.dt = dt self.NT = int(nt) self.t = np.arange(nt) * dt self.x = np.zeros((n_particles, 3), dtype=float) * u.m self.v = np.zeros((n_particles, 3), dtype=float) * (u.m / u.s) self.name = particle_type self.position_history = np.zeros( (self.NT, *self.x.shape), dtype=float) * u.m self.velocity_history = np.zeros( (self.NT, *self.v.shape), dtype=float) * (u.m / u.s) # create intermediate array of dimension (nx,ny,nz,3) in order to allow # interpolation on non-equal spatial domain dimensions _B = np.moveaxis(self.plasma.magnetic_field.si.value, 0, -1) _E = np.moveaxis(self.plasma.electric_field.si.value, 0, -1) self.integrator = self._all_integrators[integrator] self._B_interpolator = interp.RegularGridInterpolator( (self.plasma.x.si.value, self.plasma.y.si.value, self.plasma.z.si.value), _B, method="linear", bounds_error=True, ) self._E_interpolator = interp.RegularGridInterpolator( (self.plasma.x.si.value, self.plasma.y.si.value, self.plasma.z.si.value), _E, method="linear", bounds_error=True, )
def solve_step(self, c_plus_interp, R, w): c_func = [] for i_z in range(self.Nz): # a. find next-period average marginal utility avg_marg_u_plus = np.zeros(self.Na) for i_zplus in range(self.Nz): for u in [0, 1]: # i. future cash-on-hand if u == 0: m_plus = R * self.grid_a + w * ( self.grid_z[i_zplus] - self.unemp_p * self.unemp_b ) / (1 - self.unemp_p) else: m_plus = R * self.grid_a + w * self.unemp_b # ii. future consumption c_plus = c_plus_interp[i_zplus](m_plus) # iii. future marginal utility marg_u_plus = self.u_prime(c_plus) # iv. accumulate average marginal utility weight = self.trans_p_z[i_z, i_zplus] if u == 0: weight *= 1 - self.unemp_p else: weight *= self.unemp_p avg_marg_u_plus += weight * marg_u_plus # b. find current consumption and cash-on-hand c = self.u_prime_inv(R * self.beta * avg_marg_u_plus) m = self.grid_a + c m = np.insert(m, 0, 0) # add 0 in beginning c = np.insert(c, 0, 0) # add 0 in beginning # c. interpolate to common grid c_raw_func = interpolate.RegularGridInterpolator( [m], c, method="linear", bounds_error=False, fill_value=None ) # d. construct interpolator at common grid c_func_now = interpolate.RegularGridInterpolator( [self.grid_m], c_raw_func(self.grid_m), method="linear", bounds_error=False, fill_value=None, ) c_func.append(c_func_now) return c_func
def set_colordata(self, colordata, color_min=-np.pi, color_max=+np.pi, color_num=256, color_type='phase'): # WARNING! this only work for orthogonal grid basis vectors a, b and c !! color_map = self._set_colormap(color_min, color_max, color_num, color_type) #print(color_map) import scipy.interpolate as interp a, b, c = self.grid['a'][0], self.grid['b'][1], self.grid['c'][2] nx, ny, nz = self.grid['nx'], self.grid['ny'], self.grid['nz'] origin = self.grid['origin'] x = np.linspace(origin[0], origin[0] + a, nx) y = np.linspace(origin[1], origin[1] + b, ny) z = np.linspace(origin[2], origin[2] + c, nz) if color_type == 'phase': phase = np.exp(1j * colordata) color_interp = interp.RegularGridInterpolator((x, y, z), phase, bounds_error=False, fill_value=np.nan) else: color_interp = interp.RegularGridInterpolator((x, y, z), colordata, bounds_error=False, fill_value=np.nan) for count, surface in enumerate(self.isosurface): color_index = [] for vertex in surface['vertices']: if color_type == 'phase': p = color_interp(vertex) c = np.angle(p) i = int(color_num / 2 + (color_num / (color_max - color_min)) * c) else: c = color_interp(vertex) i = int((color_num / (color_max - color_min)) * c) i = max(0, i) i = min(color_num - 1, i) color_index.append(i) color_index = np.array(color_index) self.isosurface[count]['color_index'] = color_index self.isosurface[count]['color_map'] = color_map return
def __init__(self, path): self.a = [None, None, None] self.b = [[None], [None, None], [None, None, None]] with open(path, 'rb') as f: self.g_edges = np.load(f) self.alpha_edges = np.load(f) self.L_edges = np.load(f) for i in range(3): self.a[i] = np.load(f) for i in range(3): for j in range(i + 1): self.b[i][j] = np.load(f) self.loss = np.load(f) self.loss_L_min = np.load(f) # scalar self.alpha_min = np.load(f) # same shape as L_edges self.lndt = np.load(f) self.g_centers = 0.5 * (self.g_edges[:-1] + self.g_edges[1:]) self.alpha_centers = 0.5 * (self.alpha_edges[:-1] + self.alpha_edges[1:]) self.L_centers = 0.5 * (self.L_edges[:-1] + self.L_edges[1:]) # XXX TRANSPOSE IS DUMB self.i_a = [None, None, None] self.i_b = [[None, None, None], [None, None, None], [None, None, None]] points = [self.g_edges, self.alpha_edges, self.L_edges] for i in range(3): self.i_a[i] = interpolate.RegularGridInterpolator( points, self.a[i].T) for j in range(i + 1): self.i_b[i][j] = interpolate.RegularGridInterpolator( points, self.b[i][j].T) self.i_b[j][i] = self.i_b[i][j] self.i_loss = interpolate.RegularGridInterpolator(points, self.loss.T) # In the Jokipii method function, we use this interpolator with # particles that might be out of bounds, which would lead to an # exception if we used the default `bounds_error = True`. Fortunately, # precisely because such particles are out of bounds, we can ignore # the error and return a nonsense value. self.i_alpha_min = interpolate.RegularGridInterpolator( [self.L_edges], self.alpha_min, bounds_error=False, fill_value=100.) self.i_lndt = interpolate.RegularGridInterpolator(points, self.lndt.T)
def __init__(self, db, mode='counts'): self.mode = mode self.db = db # Cast L-shell axis to latitude (dipole model) self.db['lat_axis'] = np.arccos(np.sqrt(1.0 / db['L_axis'])) * R2D if mode == 'counts': # Electron number flux n_key = 'N_NH' s_key = 'N_SH' if mode == 'energy': # Energy flux n_key = 'Q_NH' s_key = 'Q_SH' print n_key, s_key print np.max(self.db[s_key]), np.min(self.db[s_key]) band_axis = range(len(db['band_pairs'])) lon_axis = np.unique(np.abs(self.db['lon_axis'])) self.n_bands = len(db['band_pairs']) if self.n_bands == 1: # single band print "single band interpolators" self.N_interp = interpolate.RegularGridInterpolator( (self.db['kp_axis'], self.db['inlats'], self.db['lat_axis'], lon_axis), self.db[n_key], fill_value=0, bounds_error=False) self.S_interp = interpolate.RegularGridInterpolator( (self.db['kp_axis'], self.db['inlats'], self.db['lat_axis'], lon_axis), self.db[s_key], fill_value=0, bounds_error=False) else: print "multi band interpolators" # Multiple bands self.N_interp = interpolate.RegularGridInterpolator( (self.db['kp_axis'], self.db['inlats'], self.db['lat_axis'], lon_axis, band_axis), self.db[n_key], fill_value=0, bounds_error=False) self.S_interp = interpolate.RegularGridInterpolator( (self.db['kp_axis'], self.db['inlats'], self.db['lat_axis'], lon_axis, band_axis), self.db[s_key], fill_value=0, bounds_error=False) # Initialize any other parameters we might store: self.precalculated = dict()
def build_mod_grav_funcs(theory_data_dir): '''Loads data from the output of /data/grav_sim_data/process_data.py which processes the raw simulation output from the farmshare code INPUTS: theory_data_dir, path to the directory containing the data OUTPUTS: gfuncs, 3 element list with 3D interpolating functions for regular gravity [fx, fy, fz] yukfuncs, 3 x Nlambda array with 3D interpolating function for modified gravity with indexing: [[y0_fx, y1_fx, ...], [y0_fy, ...], [y0_fz, ...]] lambdas, np.array with all lambdas from the simulation ''' ### Load modified gravity curves from simulation output Gdata = np.load(theory_data_dir + 'Gravdata.npy') yukdata = np.load(theory_data_dir + 'yukdata.npy') lambdas = np.load(theory_data_dir + 'lambdas.npy') xpos = np.load(theory_data_dir + 'xpos.npy') ypos = np.load(theory_data_dir + 'ypos.npy') zpos = np.load(theory_data_dir + 'zpos.npy') if lambdas[-1] > lambdas[0]: lambdas = lambdas[::-1] yukdata = np.flip(yukdata, 0) ### Find limits to avoid out of range erros in interpolation xlim = (np.min(xpos), np.max(xpos)) ylim = (np.min(ypos), np.max(ypos)) zlim = (np.min(zpos), np.max(zpos)) ### Build interpolating functions for regular gravity gfuncs = [0, 0, 0] for resp in [0, 1, 2]: gfuncs[resp] = interp.RegularGridInterpolator((xpos, ypos, zpos), Gdata[:, :, :, resp]) ### Build interpolating functions for yukawa-modified gravity yukfuncs = [[], [], []] for resp in [0, 1, 2]: for lambind, yuklambda in enumerate(lambdas): lamb_func = interp.RegularGridInterpolator( (xpos, ypos, zpos), yukdata[lambind, :, :, :, resp]) yukfuncs[resp].append(lamb_func) lims = [xlim, ylim, zlim] outdic = { 'gfuncs': gfuncs, 'yukfuncs': yukfuncs, 'lambdas': lambdas, 'lims': lims } return outdic
def omega_interp(self, parameters): omega = self.omega(parameters) kappa = self.kappamesh kx, ky, kz = kmesh = self.kmesh k = self.k #print(omega, self.dks) vgs = np.gradient(omega, *self.dks, edge_order=2) vg = np.sqrt(sum(vgc**2 for vgc in vgs)) vg[:3,:3,:3] = 1 omega_interp = spinterp.RegularGridInterpolator((kx[:,0,0], ky[0,:,0], kz[0,0,:]), omega) vph_interp = spinterp.RegularGridInterpolator((kx[:,0,0], ky[0,:,0], kz[0,0,:]), vg) return omega_interp, vph_interp
def LoadFields(self, fieldFileName): self.fieldFileName = fieldFileName with np.load(fieldFileName) as data: data = np.load(fieldFileName) wpArray = data['wpArray'] efld_rArray = data['efld_rArray'] efld_zArray = data['efld_zArray'] gradList = data['gradList'] pcRadList = data['pcRadList'] pcLenList = data['pcLenList'] self.gradList = gradList self.pcRadList = pcRadList self.pcLenList = pcLenList r_space = np.arange(0, wpArray.shape[0] / 10., 0.1, dtype=np.dtype('f4')) z_space = np.arange(0, wpArray.shape[1] / 10., 0.1, dtype=np.dtype('f4')) # self.wp_functions = np.empty((wpArray.shape[0],wpArray.shape[1]), dtype=np.object) # self.efld_r_functions = np.empty((wpArray.shape[0],wpArray.shape[1]), dtype=np.object) # self.efld_z_functions = np.empty((wpArray.shape[0],wpArray.shape[1]), dtype=np.object) self.wpArray = wpArray self.efld_rArray = efld_rArray self.efld_zArray = efld_zArray ## # for r in range(wpArray.shape[0]): # for z in range(wpArray.shape[1]): # self.wp_functions[r,z] = interpolate.RectBivariateSpline(pcRadList, pcLenList, wpArray[r,z,:,:], kx=1, ky=1) # self.efld_r_functions[r,z] = interpolate.RegularGridInterpolator((gradList, pcRadList, pcLenList), efld_rArray[r,z,:,:,:]) # self.efld_z_functions[r,z] = interpolate.RegularGridInterpolator((gradList, pcRadList, pcLenList), efld_zArray[r,z,:,:,:]) # self.wp_function = interpolate.RegularGridInterpolator( (r_space, z_space, pcRadList, pcLenList), wpArray, ) self.efld_r_function = interpolate.RegularGridInterpolator( (r_space, z_space, gradList, pcRadList, pcLenList), efld_rArray, ) self.efld_z_function = interpolate.RegularGridInterpolator( (r_space, z_space, gradList, pcRadList, pcLenList), efld_zArray, ) (self.rr, self.zz) = np.meshgrid(r_space, z_space)
def interpolate_grid(df_pos): dim = int(np.sqrt(len(df_pos))) # requires square grid xx = df_pos.hx_deg.values yy = df_pos.hy_deg.values x = np.reshape(xx, (dim, dim))[0, :] y = np.reshape(yy, (dim, dim))[:, 0] zx = df_pos.x_pos.values.reshape([dim, dim]) zy = df_pos.y_pos.values.reshape([dim, dim]) u = interp.RegularGridInterpolator((x, y), zx.swapaxes(0,1), bounds_error=False) v = interp.RegularGridInterpolator((x, y), zy.swapaxes(0,1), bounds_error=False) return u, v
def __init__(self, xf, yf, wave, xc, yc, vignette): # Check the input _xf = numpy.atleast_1d(xf) if _xf.ndim != 1: raise ValueError('Input field x coordinates must be a 1D vector.') _yf = numpy.atleast_1d(yf) if _yf.shape != _xf.shape: raise ValueError( 'Input field y coordinates do not match field x coordinates.') _wave = numpy.atleast_1d(wave) if _wave.shape != _xf.shape: raise ValueError( 'Input wavelengths do not match field x coordinates.') _xc = numpy.atleast_1d(xc) if _xc.shape != _xf.shape: raise ValueError( 'Input camera x coordinates do not match field x coordinates.') _yc = numpy.atleast_1d(yc) if _yc.shape != _xf.shape: raise ValueError( 'Input camera y coordinates do not match field x coordinates.') _vignette = numpy.atleast_1d(vignette) if _vignette.shape != _xf.shape: raise ValueError( 'Input vignetting do not match field x coordinates.') if numpy.any(_vignette > 1): raise ValueError( 'Vignetting is an efficiency and cannot be greater than 1.') self.field = numpy.hstack( (_xf.reshape(-1, 1), _yf.reshape(-1, 1), _wave.reshape(-1, 1))) self.gridxf = numpy.unique(_xf) self.gridyf = numpy.unique(_yf) self.gridwv = numpy.unique(_wave) self.shape = (len(self.gridxf), len(self.gridyf), len(self.gridwv)) self.xc_interp = interpolate.RegularGridInterpolator( (self.gridxf, self.gridyf, self.gridl), _xc.reshape(self.shape)) self.yc_interp = interpolate.RegularGridInterpolator( (self.gridxf, self.gridyf, self.gridl), _yc.reshape(self.shape)) self.vg_interp = interpolate.RegularGridInterpolator( (self.gridxf, self.gridyf, self.gridl), _vignette.reshape(self.shape)) self.mk_interp = interpolate.RegularGridInterpolator( (self.gridxf, self.gridyf, self.gridl), (_vignette > 0).astype(float).reshape(self.shape))
def get_spixel_init(num_spixels, img_width, img_height): k = num_spixels k_w = int(np.floor(np.sqrt(k * img_width / img_height))) k_h = int(np.floor(np.sqrt(k * img_height / img_width))) spixel_height = img_height / (1. * k_h) spixel_width = img_width / (1. * k_w) h_coords = np.arange(-spixel_height / 2., img_height + spixel_height - 1, spixel_height) w_coords = np.arange(-spixel_width / 2., img_width + spixel_width - 1, spixel_width) h_grid, w_grid = np.meshgrid(h_coords, w_coords, indexing='ij') spix_values = np.int32(np.arange(0, k_w * k_h).reshape((k_h, k_w))) spix_values = np.pad(spix_values, 1, 'symmetric') f = interpolate.RegularGridInterpolator((h_coords, w_coords), spix_values, method='nearest') all_h_coords = np.arange(0, img_height, 1) all_w_coords = np.arange(0, img_width, 1) all_grid = np.array(np.meshgrid(all_h_coords, all_w_coords, indexing='ij')) all_points = np.reshape(all_grid, (2, img_width * img_height)).transpose() spixel_initmap = f(all_points).reshape((img_height, img_width)) feat_spixel_initmap = spixel_initmap return [spixel_initmap, feat_spixel_initmap, k_w, k_h]
def _make_interp(self) -> sp_int.RegularGridInterpolator: """Create interpolator form :py:attr:`corr_img`""" self.interp = sp_int.RegularGridInterpolator( [np.arange(i) for i in self.corr_img.shape], self.corr_img, bounds_error=False, fill_value=np.NaN)
def _zverts_smooth(self): """ For internal use only. The user should call zverts_smooth. """ # initialize the result array shape_verts = (self.nlay + 1, self.nrow + 1, self.ncol + 1) zverts_basic = np.empty(shape_verts, dtype='float64') # assign NaN to top_botm where idomain==0 both above and below if self._idomain is not None: _top_botm = self.top_botm_withnan # perform basic interpolation (this will be useful in all cases) # loop through layers for k in range(self.nlay + 1): zvertsk = array_at_verts_basic2d(_top_botm[k, :, :]) zverts_basic[k, :, :] = zvertsk if self.is_regular(): # if the grid is regular, basic interpolation is the correct one zverts = zverts_basic else: # cell centers xcenters, ycenters = self.get_local_coords(self.xcellcenters, self.ycellcenters) # flip y direction because RegularGridInterpolator requires # increasing input coordinates ycenters = np.flip(ycenters, axis=0) _top_botm = np.flip(_top_botm, axis=1) xycenters = (ycenters[:, 0], xcenters[0, :]) # vertices xverts, yverts = self.get_local_coords(self.xvertices, self.yvertices) xyverts = np.ndarray((xverts.size, 2)) xyverts[:, 0] = yverts.ravel() xyverts[:, 1] = xverts.ravel() # interpolate import scipy.interpolate as interp shape_verts2d = (self.nrow + 1, self.ncol + 1) zverts = np.empty(shape_verts, dtype='float64') # loop through layers for k in range(self.nlay + 1): # interpolate layer elevation zcenters_k = _top_botm[k, :, :] interp_func = interp.RegularGridInterpolator( xycenters, zcenters_k, bounds_error=False, fill_value=np.nan) zverts_k = interp_func(xyverts) zverts_k = zverts_k.reshape(shape_verts2d) zverts[k, :, :] = zverts_k # use basic interpolation for remaining NaNs at boundaries where_nan = np.isnan(zverts) zverts[where_nan] = zverts_basic[where_nan] return zverts
def _interpolation_sampling(images, mesh, affine, kind='auto', radius=3, n_points=None, mask=None, inner_mesh=None, depth=None): """In each image, measure the intensity at each node of the mesh. Image intensity at each sample point is computed with trilinear interpolation. A 2-d array is returned, where each row corresponds to an image and each column to a mesh vertex. See documentation of vol_to_surf for details. """ sample_locations = _sample_locations( mesh, affine, kind=kind, radius=radius, n_points=n_points, inner_mesh=inner_mesh, depth=depth) n_vertices, n_points, img_dim = sample_locations.shape grid = [np.arange(size) for size in images[0].shape] interp_locations = np.vstack(sample_locations) masked = _masked_indices(interp_locations, images[0].shape, mask=mask) # loop over images rather than building a big array to use less memory all_samples = [] for img in images: interpolator = interpolate.RegularGridInterpolator( grid, img, bounds_error=False, method='linear', fill_value=None) samples = interpolator(interp_locations) # if all samples around a mesh vertex are outside the image, # there is no reasonable value to assign to this vertex. # in this case we return NaN for this vertex. samples[masked] = np.nan all_samples.append(samples) all_samples = np.asarray(all_samples) all_samples = all_samples.reshape((len(images), n_vertices, n_points)) texture = np.nanmean(all_samples, axis=2) return texture
def init_interpolator(self, data, x_grid, y_grid, z_grid): for i_dim in range(3): self.interpolator[i_dim] = interpolate.RegularGridInterpolator( (z_grid, y_grid, x_grid), data[i_dim, :, :, :], bounds_error=False, fill_value=0.0)
def approximate_fitn(f_values, space_size, n_coeffs=None): n = len(f_values) d = len(space_size) if n_coeffs is None: rem_coeffs = n else: rem_coeffs = n - n_coeffs coeffs = np.fft.fftn(f_values) coeffs = np.fft.fftshift(coeffs) for idx_tuple in np.ndindex(coeffs.shape): for i in idx_tuple: if i < rem_coeffs // 2 or i >= n - rem_coeffs // 2: coeffs[idx_tuple] = 0 coeffs = np.fft.ifftshift(coeffs) f_approx_vals = np.fft.ifftn(coeffs).real points = [] for i in range(0, d): points.append(np.linspace(space_size[i][0], space_size[i][1], n)) interp = interpolate.RegularGridInterpolator(tuple(points), f_approx_vals, method='linear') def f_approx(coords): return interp(tuple(coords)) return f_approx
def resample(self, shape, center, spacing=None, bounds_error=False, fill_value=0): if not spacing: spacing = self.spacing grid = Grid() grid.n_elements = np.cumprod(shape)[-1] grid.spacing = spacing grid.shape = shape grid.center = center points = [ np.arange(self.origin[i], self.origin[i] + self.spacing[i] * self.shape[i], self.spacing[i]) for i in range(self.ndim) ] g = interpolate.RegularGridInterpolator(points, self.ndelements, bounds_error=bounds_error, fill_value=fill_value) origin = grid.origin points = [ np.arange(origin[i], origin[i] + shape[i] * spacing[i], spacing[i]) for i in range(self.ndim) ] ndpoints = np.meshgrid(*points, indexing='ij') points = np.array( [ndpoints[i].reshape(grid.n_elements) for i in range(self.ndim)]).T grid.elements = g(points) return grid
def interpolateData(self): with open('stations.txt') as f: content = f.readlines() latlons = [[float(num[:-1]) for num in line.split()[-2:]] for line in content] latlons = np.array(latlons)[:, ::-1] latlons[:, 0] = -1 * latlons[:, 0] #lats, lons = readGrid() #latlons = zip(lons[10::40,10::40].flatten(), lats[10::40,10::40].flatten()) f = interpolate.RegularGridInterpolator((self.y[:, 0], self.x[0, :]), self.data['fill'][0], fill_value=-9999, bounds_error=False, method='linear') x_ob, y_ob = self.m(*zip(*latlons)) fcst_val = f((y_ob, x_ob)) fontdict = {'family': 'monospace', 'size': 9} self.ax.cla() self.ax.axis('off') for i in range(fcst_val.size): if x_ob[i] < self.m.xmax and x_ob[i] > self.m.xmin and y_ob[ i] < self.m.ymax and y_ob[i] > self.m.ymin and fcst_val[ i] != -9999: self.ax.text(x_ob[i], y_ob[i], int(round(fcst_val[i])), fontdict=fontdict, ha='center', va='center')
def __init__(self, filename, verbose=1): """ Initialisation of class to load templates from a file and create the interpolation objects Parameters ---------- filename: string Location of Template file verbose: int Verbosity level, 0 = no logging 1 = File + interpolation point information 2 = Detailed description of interpolation points """ self.verbose = verbose if self.verbose: print("Loading lookup tables from", filename) grid, bins, template = self.parse_fits_table(filename) x_bins, y_bins = bins self.interpolator = interpolate.LinearNDInterpolator(grid, template, fill_value=0) self.nearest_interpolator = interpolate.NearestNDInterpolator( grid, template) self.grid_interp = interpolate.RegularGridInterpolator( (x_bins, y_bins), np.zeros([x_bins.shape[0], y_bins.shape[0]]), method="linear", bounds_error=False, fill_value=0)