def isoMaxMass(isoage, isomh, isodict): ''' isoMaxMass - Finds the dependence of max and min mass of isochrones on age and metallicity. Parameters ---------- isoage, isomh: arr of float - Ages and metallicities of isochrones in the database isodict: dict - Dictionary of isochrones Returns ------- Mmin_interp, Mmax_interp: RGI - Interpolant of min and max mass over age and metallicity space ''' # Scaling interpolation agemh_scale = [] for age in isoage: for mh in isomh: interpname = stringLength(age, mh, isodict) isochrone = isodict[interpname] # Extract information from isochrones Mi = isochrone[:, 2] # Madimum mass to be used for scaling functions Mmax = np.max(Mi) Mmin = np.min(Mi) agemh_scale.append([age, mh, Mmax, Mmin]) agemh_scale = np.array(agemh_scale) agemh_scale = pd.DataFrame(agemh_scale, columns=['age', 'mh', 'mmax', 'mmin']) agegrid = np.array(agemh_scale.age) mhgrid = np.array(agemh_scale.mh) agemh_scale.set_index(['age', 'mh'], inplace=True) Mmax = np.array(agemh_scale['mmax'].unstack()) Mmin = np.array(agemh_scale['mmin'].unstack()) Mmax_interp = RGI((isoage, isomh), Mmax, bounds_error=False, fill_value=np.nan) Mmin_interp = RGI((isoage, isomh), Mmin, bounds_error=False, fill_value=np.nan) return Mmin_interp, Mmax_interp
def __init__(self, C_F, C_R, m, CoG_X, mu, alpha, CoP_X, C_la, rho, DriveType, gearRatio, tireRadius, fr, Lift2Drag, CarName, Pmax): self.C_F = C_F #Cornering stiffnes front [N/rad] self.C_R = C_R #Cornering stiffnes rear [N/rad] self.m = m #Weight [kg] including driver self.CoG_X = CoG_X #Center of gravity (0 at front axis, 1 at rear axis) self.mu = mu #Friction coefficient between tire gum and street self.alpha = alpha #Slip angle as optimum value [deg] self.CoP_X = CoP_X #Center of pressure self.C_la = C_la #Coefficient (lift coefficient*front area) self.rho = rho #Rho self.DriveType = DriveType #2WD or 4WD self.gearRatio = gearRatio self.tireRadius = tireRadius self.fr = fr #Friction coefficient self.Lift2Drag = Lift2Drag self.CarName = CarName self.Pmax = Pmax self.DrivingRes = None # Create GGV Map ggVMap = GG_ESB_TwoDim(C_F, C_R, m, CoG_X, mu, alpha, CoP_X, C_la, rho, DriveType, gearRatio, tireRadius, fr, Lift2Drag ) ax_upper_values, ax_lower_values, ay_values, speed_values = ggVMap.GGV_Map() #ggVMap.Plot_ggV(ax_upper_values, ax_lower_values, ay_values, speed_values) # Plot GGV map ggVMap.Plot_Long_Speed_Distance() # ax_max, ax_min self.x_u = np.asarray(ax_upper_values) self.x_l = np.asarray(ax_lower_values) # ay self.y = np.asarray(ay_values) # vehicle speed self.v = np.asarray(speed_values) # find spot where ay is at it's max ymaxind = np.argmax(self.y[0, :]) # find corresponding ax, ay, v self.xmax = self.x_u[:, ymaxind] self.ymax = self.y[:, ymaxind] self.vmax = self.v[:, ymaxind] # find limits when simulating forward and backward self.lim_f = RGI([self.v[:, 0], self.y[0, :ymaxind+1]/self.y[0, ymaxind]], self.x_u[:, :ymaxind+1]) self.lim_r = RGI([self.v[:, 0], self.y[0, :ymaxind+1]/self.y[0, ymaxind]], self.x_l[:, :ymaxind+1]) # find limit for lateral acceleration based on vehicle parameters self.lim_ay = RGI([(self.v[:, ymaxind])], self.y[:, ymaxind]) self.upper_max_speed = self.vmax.max() self.min_curvature = self.y.max() / self.upper_max_speed**2
def shellChgDen(r,chgdat,grid,pVec,a): chg = addCHGlayer(chgdat,grid) x = np.linspace(0,1,grid[0]+1) y = np.linspace(0,1,grid[1]+1) z = np.linspace(0,1,grid[2]+1) # print(x) func = RGI((x,y,z),chg) # pts = (1/grid[0]*a[0],0,0) # pts = (0,0,0) # print(func(pts)) thGrid = int(r*400) if thGrid < 200: thGrid = 200 shellChgSum = 0 pointN = 0 for i in range(thGrid): th = math.pi*i/thGrid phGrid = int(round(thGrid*2*math.sin(th))) for j in range(phGrid): ph = 2*math.pi*j/(phGrid) x = r * math.sin(th) * math.cos(ph) y = r * math.sin(th) * math.sin(ph) z = r * math.cos(th) vec = [x,y,z] # set r center vector r1 = [e * 0.5 for e in pVec[0]] r2 = [e * 0.5 for e in pVec[1]] r3 = [e * 0.5 for e in pVec[2]] rcenter = list(map(sum, zip(r1,r2,r3))) v_c = list(map(sum, zip(vec,rcenter))) M = np.array([[pVec[0][0], pVec[1][0], pVec[2][0]], [pVec[0][1], pVec[1][1], pVec[2][1]], [pVec[0][2], pVec[1][2], pVec[2][2]]]) inverseM = np.linalg.inv(M) r_c = inverseM.dot(v_c) # print(M) # print(r_c) # [i - j for i, j in zip(a, b)] # vecFromCenter = list(map(sum, zip(rcenter,vec))) # print(vecFromCenter) r_c[0] = r_c[0]%1.0 r_c[1] = r_c[1]%1.0 r_c[2] = r_c[2]%1.0 pts = (r_c[0],r_c[1],r_c[2]) # print(func(pts)) shellChgSum += func(pts) pointN += 1 # print(ph) rho = 0 print(r, shellChgSum/pointN) # print(shellChgSum/pointN) return rho
def interpolate_points(self, x, y, interpolator='rgi', bounds_error=False, **kwargs): """Interpolates the current data at the points [(x_1,y_1), (x_2,y_2),...]. Args: x_axis (float): Same es as constructor. y_axis (float): Same es as constructor. interpolator (string): Specifies the underlying interpolation method to be used. Currently available: rgi - RegularGridInterpolator from SciPy bounds_error (bool): If True interpolating outside current range will result in an error. If False data points outside will be filled with np.nan. **kwargs: Will be passed to the interpolation method, thus pass any arguments the chosen interpolation accepts. Returns: (float): List of data interpolated at the specified points. """ if interpolator == 'rgi': points = np.transpose([y, x]) rgi = RGI((self.y_axis, self.x_axis), self.data, bounds_error=bounds_error, **kwargs) intensities = np.array(rgi(points), dtype=np.float64) else: NotImplementedError('Chosen interpolator is unknown') return intensities
def get_delay_radar(ztd_file, cos_inc_angle, pts_new): """calc single path tropo delay in line-of-sight direction Parameters: ztd_file - str, path of zenith delay file cos_inc_angle - 2D np.ndarray in (len, wid) in float32, cos(inc_angle) pts_new - 2D np.ndarray in (len*wid, 2) in float32 Returns: delay - 2D np.ndarray in float32, LOS delay """ # read ztd file delay_ztd, atr_ztd = readfile.read(ztd_file) # flip to be consistent with the reversed lats delay_ztd = np.flipud(delay_ztd) # pixel coordinates in ztd file lats, lons = ut.get_lat_lon(atr_ztd, dimension=1) # set lats in ascending order as required by RGI lats = np.flipud(lats) pts_ztd = ((lats.flatten(), lons.flatten())) # resample in pts_new coordinates RGI_func = RGI(pts_ztd, delay_ztd, method='nearest', bounds_error=False, fill_value=0) delay = RGI_func(pts_new) delay = delay.reshape(cos_inc_angle.shape) # project from zenith to line-of-sight delay /= cos_inc_angle # reverse the sign for consistency between different phase correction steps/methods delay *= -1 return delay
def interpolate2d(oldx, oldy, vals, nx=None, ny=None, ret='interpolant', **kwargs): """ Interpolate values in a newer and/or finer grid. **Parameters**\n oldx, oldy: 1D array, 1D array Values of the old x and y axes. vals: 2D array Image pixel values associated with the old x and y axes. nx, ny: int, int | None, None Number of elements in the interpolated axes. ret: str | 'interpolant' Specification of the return parts. **kwargs: keyword arguments newx, newy: 1D array, 1D array Axes' values after interpolation. """ newx = kwargs.pop('newx', np.linspace(oldx.min(), oldx.max(), nx, endpoint=True)) newy = kwargs.pop('newy', np.linspace(oldy.min(), oldy.max(), ny, endpoint=True)) newxymesh = np.meshgrid(newx, newy, indexing='ij') newxy = np.stack(newxymesh, axis=-1).reshape((nx*ny, 2)) vip = RGI((oldx, oldy), vals) vals_interp = vip(newxy).reshape((nx, ny)) if ret == 'interpolant': return vals_interp, vip elif ret == 'all': return vals_interp, vip, newxymesh
def dotprod(pcb_3Dstrips_domain, pcb_domain, pcb_3Dstrips_sol, pcb_drift, velo): #get Ew for a quarter if you look along the stripin it slices through part with hole in the middle and takes right side up to the middle of the side hole points_ew = list() for num, spacing, origin in zip(pcb_3Dstrips_domain.shape, pcb_3Dstrips_domain.spacing, pcb_3Dstrips_domain.origin): start = origin stop = origin + num * spacing points_ew.append(numpy.arange(start, stop, spacing)) points_v = list() for num, spacing, origin in zip(pcb_domain.shape, pcb_domain.spacing, pcb_domain.origin): start = origin stop = origin + num * spacing points_v.append(numpy.arange(start, stop, spacing)) ew_interp = [RGI(points_ew, ew_i) for ew_i in pcb_3Dstrips_sol] velo_interp = [RGI(points_v, v_i) for v_i in velo] #units of charge are unclear q = -1 I = [] #This is slow, my attempt to make it interpolate for all points in path at once did not work (now it is about 13s per 10000 time ticks on mac) for path in pcb_drift: I_i = [] for point in path: #V is calcualted in quarter domain as drift is defined V = numpy.array([ velo_interp[0](point)[0], velo_interp[1](point)[0], velo_interp[2](point)[0] ]) #shift x coord of the point to accomodate for an extra strips for Ew calculation shift = pcb_3Dstrips_domain.shape[0] * pcb_3Dstrips_domain.spacing[ 0] / 2.0 point[0] = point[0] + shift E = numpy.array([ ew_interp[0](point)[0], ew_interp[1](point)[0], ew_interp[2](point)[0] ]) i = q * numpy.dot(E, V) I_i.append(i) I.append(I_i) return I
def interpolate_me(histo): from scipy.interpolate import RegularGridInterpolator as RGI import numpy as np xx = np.linspace(0, 1, histo.shape[0]) yy = np.linspace(0, 1, histo.shape[1]) zz = np.linspace(0, 1, histo.shape[2]) rgi = RGI((xx,yy,zz), histo, method='linear') return rgi
def backProjection_old(imageArray, RArray): ##back projections N = imageArray.shape[0] #print('Computing imageHat') imageHat = np.fft.fftshift(np.fft.fftn(imageArray)) NRange = np.arange(-(N - 1) / 2, (N - 1) / 2 + 1, dtype=int) wxJ, wyJ = np.meshgrid(NRange, NRange) imageHat = (((-1)**np.abs(wxJ + wyJ)) / N**2) * imageHat imageHat = np.tile(imageHat[..., np.newaxis], [1, 1, N]) #print("Computing l_j_hat") wz_j = NRange l_j = N * np.sinc(N * np.pi * wz_j) l_j_hat = np.tile(l_j[np.newaxis, np.newaxis, ...], [N, N, 1]) #print("Creating rotated grid") wlx, wly, wlz = np.meshgrid(NRange, NRange, NRange) rot_grid = np.zeros((N, N, N, 3)) #this is a 3D 0 array for j in range(N): for k in range(N): for l in range(N): point = np.array([wlx[j, k, l], wly[j, k, l], wlz[j, k, l]]).reshape(3, 1) rot_grid[j, k, l] = np.dot(np.transpose(RArray), point).reshape(1, 3) '''point = np.array([wlx[j,k,l], wly[j,k,l], wlz[j,k,l]]) rot_grid[j,k,l] = np.dot(RArray, point) print (rot_grid[j,k,l]) print ('ok')''' imageHat_fnc = RGI((NRange, NRange, NRange), imageHat, bounds_error=False, fill_value=0) b_j_hat_fnc = RGI((NRange, NRange, NRange), l_j_hat, bounds_error=False, fill_value=0) imageHat = imageHat_fnc(rot_grid) l_j_hat = imageHat_fnc(rot_grid) b_j_hat = imageHat * l_j_hat b_j_hat = ((-1)**np.abs(wlx + wly + wlz) * (N**3)) * b_j_hat b_j = np.fft.ifftn(np.fft.ifftshift(b_j_hat)) return np.real(b_j)
def findConsumptionFunction(par, sol, grids, vals): diff_cfunc = np.inf it = 0 while diff_cfunc > par.tol_cfunc: it += 1 c_old = sol['c'].copy() avg_marg_plus = np.full((par.Na, par.Nu), 0.0) for i_uplus in range(par.Nu): c_plus_interp = RGI( [np.insert(grids['m_mat'][:, i_uplus], 0, 0.0)], values=sol['c'][:, i_uplus], method='linear', bounds_error=False, fill_value=None) m_plus = vals['R_eq'] * grids['a_mat'] + vals['y_plus'][i_uplus] c_plus = np.reshape(c_plus_interp(m_plus.ravel()), m_plus.shape) marg_u_plus = par.marg_util(par, c_plus) trans_mat = np.repeat(par.trans_u[:, i_uplus].ravel(), par.Na, axis=0) avg_marg_plus = avg_marg_plus + par.beta * vals[ 'R_eq'] * np.multiply(trans_mat, marg_u_plus) c = par.inv_marg_util(par, avg_marg_plus) m = grids['a_mat'] + c for i_u in range(par.Nu): Gm = np.insert(grids['m'], 0, 0.0) M = np.insert(m[:, i_u], 0, 0.0) C = np.insert(c[:, i_u], 0, 0.0) c_interp = RGI([M], values=C, method='linear', bounds_error=False, fill_value=None) sol['c'][:, i_u] = c_interp(Gm) diff_cfunc = max(abs(c_old.ravel() - sol['c'].ravel())) assert (it < 2000) return sol
def plot_surface_dgrid(dgrid_np, data, value, rlpbc, select='all', opacity=1.0, cscale=None, stepsize=2): # import h5py import numpy as np import ase from ase.io import read import copy dgrid_np_copy = copy.deepcopy(dgrid_np) # data = read(path_to_cif) A_unit = ase.geometry.complete_cell(data.get_cell()).T # hfile = h5py.File(path_to_h5) # grid = np.array(hfile[gridname]) # * To select only a few reqions, # * Find all the regions that are not in the list, change the distance value to something absurd. if select != 'all': dgrid_np_copy[np.isin(rlpbc, select, assume_unique=False, invert=True)]=-10 # * FInd the isosurface from skimage.measure import marching_cubes_lewiner as mcl verts, faces, normals, values = mcl(dgrid_np_copy, value, step_size=stepsize)#, spacing=[0.2,0.2,0.2]) if cscale==None: # * Make a colorscale if no colorscale is provided cvals = np.linspace(0,1, (rlpbc.max()).astype(np.int)) cscale=[[cvals[i],"rgb("+np.str(np.random.randint(0,256))+','+np.str(np.random.randint(0,256))+','+np.str(np.random.randint(0,256))+')'] for i in range((rlpbc.max()).astype(np.int))] #* Find the colour for the vertices from scipy.interpolate import RegularGridInterpolator as RGI xx = np.linspace(0, rlpbc.shape[0]-1, rlpbc.shape[0]) yy = np.linspace(0, rlpbc.shape[1]-1, rlpbc.shape[1]) zz = np.linspace(0, rlpbc.shape[2]-1, rlpbc.shape[2]) rl = RGI((xx,yy,zz), rlpbc, method='nearest') colours = rl(verts) import plotly.graph_objects as go #* Find the actual coordinates hovertext=["Region: "+str(int(c)) for c in colours] true_verts = np.dot(A_unit, (verts/rlpbc.shape).T).T data_plot = go.Mesh3d(x=true_verts[:,0],y=true_verts[:,1],z=true_verts[:,2],intensity=colours.astype(np.int), hoverinfo='all', hovertext=hovertext, flatshading=False, colorscale=cscale , i=faces[:,0],j=faces[:,1],k=faces[:,2], opacity =opacity, name='Pores') # data_plot.update( lighting=dict(ambient=0.18, # diffuse=1, # fresnel=0.1, # specular=1, # roughness=0.05, # facenormalsepsilon=1e-15, # vertexnormalsepsilon=1e-15), # lightposition=dict(x=10, # y=10, # z=30 # ),showscale=False # ) return data_plot
def __init__(self, domain, vfield): ''' The vfield give vector feild on domain. ''' points = list() for num, spacing, origin in zip(domain.shape, domain.spacing, domain.origin): start = origin stop = origin + num * spacing points.append(np.arange(start, stop, spacing)) self.interp = [RGI(points, coord) for coord in vfield]
def __create_potacc_interpolators(self, r, theta, pot): """Set up interpolators for potential and acceleration.""" q = np.log(r) self.__f_pot = RGI((q, theta), pot) # first derivs via finite differencing dpdq = np.diff(pot, axis=0) / np.diff(q)[:, None] dpdth = np.diff(pot, axis=1) / np.diff(theta)[None, :] # average derivs in 'other' dimension to make appropriate grid shapes dpdq = 0.5 * (dpdq[:, 1:] + dpdq[:, :-1]) dpdth = 0.5 * (dpdth[1:, :] + dpdth[:-1, :]) # cell centre coordinates q_cen = 0.5 * (q[1:] + q[:-1]) th_cen = 0.5 * (theta[1:] + theta[:-1]) q_g, theta_g = np.meshgrid(q_cen, th_cen, indexing='ij') r_g = np.exp(q_g) # convert derivs to cylindrical coords sth = np.sin(theta_g) cth = np.cos(theta_g) dpdR = (dpdq * sth + dpdth * cth) / r_g dpdz = (dpdq * cth - dpdth * sth) / r_g # on disc plane, set z gradient to zero exactly i = th_cen.size // 2 dpdz[:, i] = 0 # add values on polar axis Nq = q_cen.size dpdR_new = np.hstack((np.zeros((Nq, 1)), dpdR, np.zeros((Nq, 1)))) dpdz_ax = np.sqrt(dpdR[:, 0]**2 + dpdz[:, 0]**2)[:, None] dpdz_new = np.hstack((dpdz_ax, dpdz, -dpdz_ax)) th_cen = np.hstack((0, th_cen, pi)) # interpolators for cylindrical coords self.__f_aR = RGI((q_cen, th_cen), -dpdR_new) self.__f_az = RGI((q_cen, th_cen), -dpdz_new) return
def __init__(self, photons, assume_symmetry=[], binning='auto'): self.ndim = 1 + photons.ndim - len(assume_symmetry) if binning == 'auto': binning = np.linspace( 0.0, 1.0, int((len(photons) * photons.n_steps)**(1.0 / (self.ndim + 1.0))) + 1) if type(binning) == int: binning = np.linspace(0.0, 1.0, binning) t = photons.t.flatten() x = photons.x.reshape(-1, photons.ndim) r = np.linalg.norm(x, axis=-1) vals = [t, r] self.bins = [binning * np.max(t), binning * np.max(r)] self.signature = 'f(t,r' if photons.ndim == 2: if 'phi' not in assume_symmetry: phi = np.arccos(x[:, 0] / r) vals.append(phi) self.bins.append(binning * 2.0 * np.pi) self.signature += ',phi' elif photons.ndim == 3: if 'theta' not in assume_symmetry: theta = np.arccos(x[:, 2] / r) vals.append(theta) self.bins.append(binning * np.pi) self.signature += ',theta' if 'phi' not in assume_symmetry: phi = np.arctan(x[:, 1], x[:, 0]) vals.append(phi) self.bins.append(2.0 * np.pi * binning - np.pi) self.signature += ',phi' self.signature += ')' self.H, _ = np.histogramdd(vals, self.bins) self.t = [(b[1:] + b[:-1]) * 0.5 for b in self.bins] if self.ndim == 2: self.interpolator = RBS(*self.t, np.log(self.H + 1e-8), bbox=[0.0, np.max(t), 0.0, np.max(r)], kx=1, ky=1) else: self.interpolator_ = RGI(self.t, self.H, bounds_error=False, fill_value=0.0) self.interpolator = lambda *x: self.interpolator_(x)
def step(self, vals, dt): """Passage de l'instant t à t - delta_t, contrôle supposé bang-bang. :param vals: Tableau des valeurs :type vals: numpy.array (len(self.xs), len(self.ys)) :param dt: pas de temps :type dt: float """ p_libre, p_bang = self.nouveaux_points(dt) approx = RGI((self.xs, self.ys), vals) v_libre = approx(p_libre) v_bang = approx(p_bang) return np.minimum(v_libre, v_bang).reshape(len(self.xs), len(self.ys))
def plot_surface_h5(path_to_h5, gridname, t1, value, rlpbc, select='all', opacity=1.0): import h5py import numpy as np from ase.io import read data = read(t1.file) A_unit = data.get_cell().T hfile = h5py.File(path_to_h5,'r') grid = np.array(hfile[gridname]) # * To select only a few reqions, # * Find all the regions that are not in the list, change the distance value to something absurd. if select != 'all': grid[np.isin(rlpbc, select, assume_unique=False, invert=True)]=-10 # faces = faces[np.isin(colours, select, assume_unique=False, invert=False)] # * FInd the isosurface from skimage.measure import marching_cubes_lewiner as mcl verts, faces, normals, values = mcl(grid, value, step_size=1)#, spacing=[0.2,0.2,0.2]) # * Make a colorscale cvals = np.linspace(0,1,32) cscale=[[cvals[i],"rgb("+np.str(np.random.randint(0,256))+','+np.str(np.random.randint(0,256))+','+np.str(np.random.randint(0,256))+')'] for i in range(32)] #* Find the colour for the vertices from scipy.interpolate import RegularGridInterpolator as RGI xx = np.linspace(0, rlpbc.shape[0]-1, rlpbc.shape[0]) yy = np.linspace(0, rlpbc.shape[1]-1, rlpbc.shape[1]) zz = np.linspace(0, rlpbc.shape[2]-1, rlpbc.shape[2]) rl = RGI((xx,yy,zz), rlpbc, method='nearest') colours = rl(verts) import plotly.graph_objects as go #* Find the actual coordinates hovertext=["Region: "+str(c) for c in colours] true_verts = np.dot(A_unit, (verts/rlpbc.shape).T).T data_plot = go.Mesh3d(x=true_verts[:,0],y=true_verts[:,1],z=true_verts[:,2],intensity=colours, hoverinfo='all', hovertext=hovertext, flatshading=False, colorscale=cscale , i=faces[:,0],j=faces[:,1],k=faces[:,2], showscale=False, opacity =opacity, name='Pores') # data_plot = go.Mesh3d(x=true_verts[:,0],y=true_verts[:,1],z=true_verts[:,2], alphahull=5, intensity=colours.astype(np.int), hoverinfo='all', hovertext=hovertext, flatshading=False, colorscale=cscale, showscale=False, opacity =opacity, name='Pores') data_plot.update( lighting=dict(ambient=0.18, diffuse=1, fresnel=0.1, specular=1, roughness=0.05, facenormalsepsilon=1e-15, vertexnormalsepsilon=1e-15), lightposition=dict(x=100, y=200, z=0 ) ) return data_plot
def getPointCHG(point,chgdat,grid,pVec,a): chg = addCHGlayer(chgdat,grid) x = np.linspace(0,1,grid[0]+1) y = np.linspace(0,1,grid[1]+1) z = np.linspace(0,1,grid[2]+1) # print(x) func = RGI((x,y,z),chg) # pts = (1/grid[0]*a[0],0,0) # pts = (0,0,0) # print(func(pts)) pointCHG = func(point) return pointCHG
def getPointsCHG(lis_points,chgdat,grid,pVec,a): chg = addCHGlayer(chgdat,grid) x = np.linspace(0,1,grid[0]+1) y = np.linspace(0,1,grid[1]+1) z = np.linspace(0,1,grid[2]+1) # print(x) func = RGI((x,y,z),chg) # pts = (1/grid[0]*a[0],0,0) # pts = (0,0,0) # print(func(pts)) lis = [] for p in lis_points: lis.append(pointCHG = func(p)) return lis
def get_bead_labels(region_labels, shifted_coord, cell, specie_name): import numpy as np from scipy.interpolate import RegularGridInterpolator as RGI chain_length = {'C7':7,'C8':8,'C9':9,'C10':10,'C11':11,'C12':12,'C13':13,'C14':14,'C15':15,'C16':16} xx = np.linspace(0,cell[0],region_labels.shape[0]) yy = np.linspace(0,cell[1],region_labels.shape[1]) zz = np.linspace(0,cell[2],region_labels.shape[2]) rl = RGI((xx,yy,zz),region_labels, method='nearest') bead_labels = rl(shifted_coord).reshape(-1,chain_length[specie_name]) number_of_regions = len(np.unique(region_labels)) molecule_groups = [] for i in range(number_of_regions): molecule_groups.append(np.unique(np.where(bead_labels==i)[0])) # molecule_groups.pop[0] return molecule_groups[1:], bead_labels
def run_regular_grid_interpolator(self, src_data, interp_method='nearest', fill_value=np.nan, print_msg=True): """Interpolate 2D matrix""" # prepare interpolation function rgi_func = RGI(self.src_pts, src_data, method=interp_method, bounds_error=False, fill_value=fill_value) # prepare output matrix geo_data = np.empty((self.length, self.width), src_data.dtype) geo_data.fill(fill_value) # interpolate output matrix geo_data[self.interp_mask] = rgi_func(self.dest_pts) return geo_data
def interp(sol2D, arr3D, barr3D, dom2D, dom3D, xcoord): points = list() for num, spacing, origin in zip(dom2D.shape, dom2D.spacing, dom2D.origin): start = origin stop = origin + num * spacing points.append(numpy.arange(start, stop, spacing)) points.insert( 1, numpy.arange(dom3D.origin[1], dom3D.origin[1] + (dom3D.shape[1]) * dom3D.spacing[1], dom3D.spacing[1])) shape2D_ext = (dom2D.shape[0], dom3D.shape[1], dom2D.shape[1]) sol2D_ext = numpy.zeros(shape2D_ext) for j in range(dom3D.shape[1]): sol2D_ext[:, j, :] = sol2D func_interp = RGI(points, sol2D_ext) barr3D[0, :, :] = 1 barr3D[-1, :, :] = 1 points3D_x = numpy.array([ dom2D.spacing[0] * dom2D.shape[0] / 2 - xcoord, dom2D.spacing[0] * dom2D.shape[0] / 2 + xcoord ]) points3D_z = numpy.arange( dom3D.origin[2], dom3D.origin[2] + (dom3D.shape[2]) * dom3D.spacing[2], dom3D.spacing[2]) points3D_y = numpy.arange( dom3D.origin[1], dom3D.origin[1] + (dom3D.shape[1]) * dom3D.spacing[1], dom3D.spacing[1]) #this part probably can be done faster for j in range(dom3D.shape[1]): points3D_i = list() points3D_f = list() for z in points3D_z: points3D_i.append(numpy.array([points3D_x[0], points3D_y[j], z])) points3D_f.append(numpy.array([points3D_x[1], points3D_y[j], z])) arr3D[0, j, :] = func_interp(points3D_i) arr3D[-1, j, :] = func_interp(points3D_f) return arr3D, barr3D
def simulate(par, sol, sim, vals, a_dist, grids): # IN: par, sol, sim, a_dist # Out: sim, a_dist # 1 predifened values sim['L'] = np.full((par.simT), ((1 - par.unemp) * par.lbar)) sim['K'] = np.full((par.simT), np.nan) sim['R'] = np.full((par.simT), vals['R_eq']) sim['W'] = np.full((par.simT), vals['W_eq']) #2 time loop for t in range(par.simT): #1 capital sim['K'][t] = np.mean(a_dist) for i_u in range(par.Nu): #a select on h Index = sim['h'][:, t] == i_u #unemployed #b. Generate income if i_u == 0: y = par.mu * sim['W'][t] else: fac = par.unemp / (1 - par.unemp) y = (par.lbar - fac * par.mu) * sim['W'][t] #c Cash-on-hand m = sim['R'][t] * a_dist[Index] + y #d consumption Gm = np.insert(grids['m'], 0, 0.0) c_interp = RGI([Gm], values=sol['c'][:, i_u], method='linear', bounds_error=False, fill_value=None) c = c_interp(m) #e End-of-peride assets a_dist[Index] = m - c #2 Checking for boundaries Index = a_dist < par.a_min a_dist[Index] = par.a_min Index = a_dist > par.a_max a_dist[Index] = par.a_max return sim, a_dist
def interpolate_data(inData, outShape, interpMethod='linear'): """Interpolate input 2D matrix into different shape. Used to get full resolution perp baseline from ISCE coarse grid baseline file. Parameters: inData : 2D array outShape : tuple of 2 int in (length, width) interpMethod : string, choose in [nearest, linear, cubic] Returns: outData : 2D array in outShape """ from scipy.interpolate import RegularGridInterpolator as RGI inShape = inData.shape inPts = (np.arange(inShape[0]), np.arange(inShape[1])) xx, yy = np.meshgrid(np.linspace(0, inShape[1]-1, outShape[1], endpoint=False), np.linspace(0, inShape[0]-1, outShape[0], endpoint=False)) outPts = np.hstack((yy.reshape(-1, 1), xx.reshape(-1, 1))) outData = RGI(inPts, inData, method=interpMethod, bounds_error=False)(outPts).reshape(outShape) return outData
def interpolate(self, **kwargs): if 'method' in kwargs: method = kwargs['method'] else: method = 'linear' xs = self.linepoints(self, 0) ys = self.linepoints(self, 1) zs = self.linepoints(self, 2) interp = RGI((xs, ys, zs), self.data, method=method, bounds_error=False, fill_value=0) self.interp = interp return interp
def __init__(self, domain, vfield): ''' The vfield give vector feild on domain. ''' shape = domain.shape spacing = domain.spacing origin = domain.origin points = list() self.calls = 0 for dim in range(len(domain.shape)): start = origin[dim] stop = origin[dim] + shape[dim] * spacing[dim] rang = numpy.arange(start, stop, spacing[dim]) print("interp dim:", dim, rang.shape, vfield[dim].shape) points.append(rang) self.interp = [RGI(points, component) for component in vfield]
def path_accumulation(self, field): """ This function performs a line integral of the quantity 'field' along each path that has been defined on the grid. In practice this is done by using the values of field defined in each cell to interpolate to the value of the field at each segment of the path. Once these values are known they can be used, along with the actual equations of the path segments themselves, to perform the line integral. Parameters: ----------- field : field class instance The field to be integrated along each path Returns: -------- None """ # Build list of coordinates for the interpolator object. This list is comprised # of a series of 1D arrays (1 array for each dimension). Each array contains the # coordinates of the known points in that dimension (i.e., the first array has all # of the x coordinates for the grid points, the second has all the y, etc.). I # feel like the first part of this (creating the coordinate arrays) should be # moved to the constructor, because having to separate out the coordinates for # every field you want to accumulate is dumb, since it's the same thing each time. coords = [] for i in range(self.ndims): coords.append([]) for c in self.grid: for i in range(self.ndims): coords[i].append(c.loc[i]) # Now build the data array (must have the same shape as the grid). This can # probably be done when assigning the field to each grid cell. data = np.zeros(self.grid.shape) it = np.nditer(self.grid, flags=['multi_index']) while not it.finished: data[it.multi_index] = self.grid[it.multi_index][field.name] it.iternext() # Instantiate interpolation object (possible issue (?): this presupposes that # the cells are accessed in the same order when building the coords list and # the data array. MAKE SURE THIS IS TRUE!!!!!) interp = RGI(coords, data)
def __init__(self, x, filter=None, k=.01, spring_type = 'quadratic', projected = True,mapfile = 'final.tif' ): self.x , self.spring_type, self.k, self.projected = x, spring_type, k, projected self.mapfile = mapfile self.m = x.shape[0] self.n = x.shape[1] self.solved = False self.eps = 1e-5 self.image = np.array(Image.open(self.mapfile)) self.original = np.copy(self.image) if filter is not None: numtaps = 129 filt = remez(numtaps, [0,filter-.02,filter+.02, .5],desired = [1,1e-4]) filt = np.outer(filt,filt) # plt.imshow(filt) # plt.show() self.image = oaconvolve(self.image, filt,mode='same') self.map = RGI([np.linspace(0,self.image.shape[1]-1,self.image.shape[1]), np.linspace(0,self.image.shape[0]-1,self.image.shape[0])], self.image.T)
def regrid_model(mod, new_x, new_y, new_z): x, y, z = (edge2center(arr) for arr in (mod.dx, mod.dy, mod.dz)) X, Y, Z = (edge2center(arr) for arr in (new_x, new_y, new_z)) X_grid, Y_grid, Z_grid = np.meshgrid(X, Y, Z) X_grid, Y_grid, Z_grid = (np.ravel(arr) for arr in (X_grid, Y_grid, Z_grid)) # interp = griddata((x_grid, y_grid, z_grid), # np.ravel(mod.vals), # (X_grid, Y_grid, Z_grid), # method='nearest') interp = RGI((y, x, z), np.transpose(mod.vals, [1, 0, 2]), method='nearest', bounds_error=False, fill_value=mod.background_resistivity) query_points = np.array((Y_grid, X_grid, Z_grid)).T new_vals = interp(query_points) new_vals = np.reshape(new_vals, [len(Y), len(X), len(Z)]) new_vals = np.transpose(new_vals, [1, 0, 2]) return new_vals
def generate_transect2D(self): if not (self.transect_plot['easting'] and self.transect_plot['northing']): return qx, qy = self.interpolate_between_points( self.transect_plot['easting'], self.transect_plot['northing']) qz = np.array(self.clip_model.dz) query_points = np.zeros((len(qx) * len(qz), 3)) faces = np.zeros(((len(qx) - 1) * (len(qz) - 1), 5)) cc = 0 cc2 = 0 for ix in range(len(qx)): for ii, iz in enumerate(qz): query_points[cc, :] = np.array((qx[ix], qy[ix], iz)) if ii < len(qz) - 1 and ix < len(qx) - 1: faces[cc2, 0] = 4 faces[cc2, 1] = cc faces[cc2, 2] = cc + 1 faces[cc2, 3] = len(qz) + cc + 1 faces[cc2, 4] = len(qz) + cc cc2 += 1 cc += 1 cell_N, cell_E, cell_z = self.clip_model.cell_centers() vals = np.transpose(np.log10(self.clip_model.vals), [1, 0, 2]) self.interpolator = RGI((cell_E, cell_N, cell_z), vals, bounds_error=False, fill_value=5) interp_vals = self.interpolator(query_points) # self.map.window['axes'][0].plot(qx, qy, 'k--') # self.canvas['2D'].draw() # debug_print self.interp_vals = np.reshape(interp_vals, [len(qx), len(qz)]) self.qx = qx self.qy = qy self.qz = qz self.query_points = query_points self.faces = faces self.plot_transect2D(redraw=True)
def reconstruction(image, R): R = np.transpose(R) a = R[0] b = R[1] b_j_hat, l_j_hat = backProjection(image) N = image.shape[0] NRange = np.arange(-(N - 1) / 2, (N - 1) / 2 + 1, dtype=int) # rotated coordinates rot_x, rot_y, rot_z = np.meshgrid( np.arange(-(N - 1) / 2, (N - 1) / 2 + 1, dtype=int), np.arange(-(N - 1) / 2, (N - 1) / 2 + 1, dtype=int), np.arange(-(N - 1) / 2, (N - 1) / 2 + 1, dtype=int)) rot_x = rot_x[..., np.newaxis] * a rot_y = rot_y[..., np.newaxis] * b rot_z = rot_z[..., np.newaxis] * np.cross(a, b) grid = rot_x + rot_y + rot_z # standard coordinates x = np.arange(-(N - 1) / 2, (N - 1) / 2 + 1) y = np.arange(-(N - 1) / 2, (N - 1) / 2 + 1) z = np.arange(-(N - 1) / 2, (N - 1) / 2 + 1) b_j_hat_f = (RGI(points=[x, y, z], values=b_j_hat, bounds_error=False, fill_value=0)) interpolated = b_j_hat_f(grid) w_x, w_y, w_z = np.meshgrid( np.arange(-(N - 1) / 2, (N - 1) / 2 + 1, dtype=int), np.arange(-(N - 1) / 2, (N - 1) / 2 + 1, dtype=int), np.arange(-(N - 1) / 2, (N - 1) / 2 + 1, dtype=int)) interpolated = np.exp(-np.pi * 1j * (w_x + w_y + w_z)) / N**3 * interpolated return interpolated, l_j_hat