def df_fixer(df_path): """ There are usually holes/blank spots toward the outside of the df. The extrapolation we do isn't totally necessary, but it makes the later deformation have cleaner edges and the background color is much easier to fix. """ df = np.fromfile(df_path, dtype='float32', count=-1) df = df.reshape((256, 256, 3), order='F') df_R = df[:, :, 0] df_C = df[:, :, 1] # df_R += 1 # df_C += 1 # fill holes in df with spline interpolation/extrapolation [r1, c1] = np.where(df_R != -1) [rq, cq] = np.where(df_R == -1) splineR = SmoothBivariateSpline(r1, c1, df_R[r1, c1]) df_R[rq, cq] = splineR.ev(rq, cq) [r1, c1] = np.where(df_C != -1) [rq, cq] = np.where(df_C == -1) splineC = SmoothBivariateSpline(r1, c1, df_C[r1, c1]) df_C[rq, cq] = splineC.ev(rq, cq) return (df_R, df_C)
def single_fit_give(xTest, yTest, xData, yData, zData, w): initialFitReturn = SmoothBivariateSpline(xData, yData, zData, w=w).ev(xTest, yTest) adjXData = np.append(xData, xTest) adjYData = np.append(yData, yTest) posAdjZData = np.append(zData, initialFitReturn + 1) negAdjZData = np.append(zData, initialFitReturn - 1) wAdj = np.append(w, 1) posFitReturn = SmoothBivariateSpline(adjXData, adjYData, posAdjZData, w=wAdj).ev(xTest, yTest) negFitReturn = SmoothBivariateSpline(adjXData, adjYData, negAdjZData, w=wAdj).ev(xTest, yTest) posGive = posFitReturn - initialFitReturn negGive = initialFitReturn - negFitReturn give = np.mean([posGive, negGive]) return give
def gen_cross_section_kinetic(mv, eps, alpha_d): with open("data/xs_dis_Ap.txt") as infile: array1 = infile.read() array2 = array1.split("\n")[:-1] array3 = [line.split() for line in array2] array4 = np.array([[ float(line[0].split('_')[1].split('p')[1]), float(line[0].split('_')[2].split('.')[0][1:]), float(line[1]) ] for line in array3]) alpha_d_set = 1 / 4.0 / math.pi epsilon_set = 1e-3 DIS_Func = SmoothBivariateSpline(array4[:, 0], array4[:, 1], array4[:, 2]) with open("data/xs_dis_Ap_neutron.txt") as infile: array1 = infile.read() array2 = array1.split("\n")[:-1] array3 = [line.split() for line in array2] array4 = np.array([[ float(line[0].split('_')[1].split('p')[1]), float(line[0].split('_')[2].split('.')[0][1:]), float(line[1]) ] for line in array3]) alpha_d_set = 1 / 4.0 / math.pi epsilon_set = 1e-3 DIS_Func2 = SmoothBivariateSpline(array4[:, 0], array4[:, 1], array4[:, 2]) return np.array([[ En, DIS_Func(mv, En) * (eps / 1e-3)**2 * alpha_d / alpha_d_set, DIS_Func2(mv, En) * (eps / 1e-3)**2 * alpha_d / alpha_d_set ] for En in range(3, 301, 1)])
def single_fit_give(xTest, yTest, xData, yData, zData, s=None, kx=2, ky=1, deviation=0.02): adjXData = np.append(xData, xTest) adjYData = np.append(yData, yTest) bbox = [ min(adjXData), max(adjXData), min(adjYData), max(adjYData)] initialFitReturn = SmoothBivariateSpline( xData, yData, zData, bbox=bbox, kx=kx, ky=ky, s=s).ev(xTest, yTest) posAdjZData = np.append(zData, initialFitReturn + deviation) negAdjZData = np.append(zData, initialFitReturn - deviation) posFitReturn = SmoothBivariateSpline( adjXData, adjYData, posAdjZData, kx=kx, ky=ky, s=s).ev(xTest, yTest) negFitReturn = SmoothBivariateSpline( adjXData, adjYData, negAdjZData, kx=kx, ky=ky, s=s).ev(xTest, yTest) posGive = (posFitReturn - initialFitReturn) / deviation negGive = (initialFitReturn - negFitReturn) / deviation give = np.mean([posGive, negGive]) return give
def genShiftVectorFieldSpline(nx, ny, nsx, nsy, err_sx, err_sy, bbox=None): """interpolates shift vectors using smoothing splines""" wonky = findWonkyVectors(nx, ny, nsx, nsy, tol=2 * err_sx.mean()) #wonky = findWonkyVectors(nx, ny, nsx, nsy, tol=100) good = wonky == 0 print(('%d wonky vectors found and discarded' % wonky.sum())) if bbox: spx = SmoothBivariateSpline(nx[good], ny[good], nsx[good], 1. / err_sx[good], bbox=bbox) spy = SmoothBivariateSpline(nx[good], ny[good], nsy[good], 1. / err_sy[good], bbox=bbox) else: spx = SmoothBivariateSpline(nx[good], ny[good], nsx[good], 1. / err_sx[good]) spy = SmoothBivariateSpline(nx[good], ny[good], nsy[good], 1. / err_sy[good]) X, Y = np.meshgrid(np.arange(0, 512 * 70, 100), np.arange(0, 256 * 70, 100)) dx = spx.ev(X.ravel(), Y.ravel()).reshape(X.shape) dy = spy.ev(X.ravel(), Y.ravel()).reshape(X.shape) return (dx.T, dy.T, spx, spy, good)
def _single_calculate_deformability(x_test, y_test, x_data, y_data, z_data): """Return the result of the deformability test for a single test point. The deformability test applies a shift to the spline to determine whether or not sufficient information for modelling is available. For further details on the deformability test see the *Methods: Defining valid prediction regions of the spline* section within <http://dx.doi.org/10.1016/j.ejmp.2015.11.002>. Args: x_test (float): The x coordinate of the point to test y_test (float): The y coordinate of the point to test x_data (np.array): The x coordinates of the model data to test y_data (np.array): The y coordinates of the model data to test z_data (np.array): The z coordinates of the model data to test Returns: deformability (float): The resulting deformability between 0 and 1 representing the ratio of deviation the spline model underwent at the point in question by introducing an outlier at the point in question. """ deviation = 0.02 adjusted_x_data = np.append(x_data, x_test) adjusted_y_data = np.append(y_data, y_test) bbox = [ min(adjusted_x_data), max(adjusted_x_data), min(adjusted_y_data), max(adjusted_y_data)] initial_model = SmoothBivariateSpline( x_data, y_data, z_data, bbox=bbox, kx=2, ky=1).ev(x_test, y_test) pos_adjusted_z_data = np.append(z_data, initial_model + deviation) neg_adjusted_z_data = np.append(z_data, initial_model - deviation) pos_adjusted_model = SmoothBivariateSpline( adjusted_x_data, adjusted_y_data, pos_adjusted_z_data, kx=2, ky=1 ).ev(x_test, y_test) neg_adjusted_model = SmoothBivariateSpline( adjusted_x_data, adjusted_y_data, neg_adjusted_z_data, kx=2, ky=1 ).ev(x_test, y_test) deformability_from_pos_adjustment = ( pos_adjusted_model - initial_model) / deviation deformability_from_neg_adjustment = ( initial_model - neg_adjusted_model) / deviation deformability = np.max( [deformability_from_pos_adjustment, deformability_from_neg_adjustment]) return deformability
def loadInterpolatedMin(degree=5): """ Good for range 0 to 1, 0 to 5.0 Equivalent to def min_interpolate(x,y): return BoundedBrownianMotion(0,0,1,y).expected_error(x) """ global interpolatedMin, interpolatedMinSpl if interpolatedMin is not None: return interpolatedMin f = open( os.path.join(os.path.dirname(__file__), "brownian-opt-min-interpolates.dat")) xys = cPickle.load(f) zs = cPickle.load(f) f.close() interpolatedMinSpl = SmoothBivariateSpline([x for x, y in xys], [y for x, y in xys], zs, kx=degree, ky=degree) interpolatedMin = lambda x, y: interpolatedMinSpl(x, y)[0, 0] return interpolatedMin
def approximateValueFunction(TV,Para): ''' Approximates the value function over the grid defined by Para.domain. Uses mpi. Returns both an interpolated value function and the value of TV at each point in the domain. ''' comm = MPI.COMM_WORLD #first split up domain for each process s = comm.Get_size() rank = comm.Get_rank() n = len(Para.domain) m = n//s r = n%s #let each process take a slice of the domain mydomain = Para.domain[rank*m+min(rank,r): (rank+1)*m+min(rank+1,r)] #get the value at each point in my domain myV = hstack(map(TV,mydomain)) #gather the values for each process Vs = comm.gather(myV) if rank == 0: #fit Vs = hstack(Vs).flatten() Vf = SmoothBivariateSpline(Para.domain[:,0],Para.domain[:,1],Vs) else: Vf = None return comm.bcast(Vf),comm.bcast(Vs)
def process(self, obj_data): ''' Preprocesses sentinel 1 data @param obj_data: Data wrapper ''' for index, (label, image) in enumerate(obj_data.getIterator()): tree = obj_data.info(label)['Tree'] azimuth_time, line_index, split_indicies = retrieve_azimuth_time(tree) if self._cut_on_master and index==0: master_azimuth_time = azimuth_time master_line_index = line_index master_split_indicies = split_indicies elif self._cut_on_master: line_index = master_line_index obj_data.info(label)['Azimuth Time'] = azimuth_time[line_index].reset_index(drop=True) obj_data.info(label)['Split Indicies'] = split_indicies obj_data.info(label)['Line Index'] = line_index geo_info = read_geolocation(tree) updated_lines = update_geolocation_lines(tree, azimuth_time[line_index], geo_info) lat_spline = SmoothBivariateSpline(updated_lines, geo_info['Samples'], geo_info['Latitudes'], kx=1, ky=1) lon_spline = SmoothBivariateSpline(updated_lines, geo_info['Samples'], geo_info['Longitudes'], kx=1, ky=1) obj_data.info(label)['Geolocation'] = SplineLatLon(lat_spline, lon_spline) obj_data.updateData(label, image[line_index,:])
def smooth_matrix(M, t): N = len(t) a, b = np.meshgrid(t, t) a = a.ravel() b = b.ravel() spl = SmoothBivariateSpline(a, b, M.ravel()) x = np.zeros((N, N)) for i in range(N): for j in range(N): x[i, j] = spl(i / N, j / N) return x
def nextIter(self): # Calculate value assuming W and y are known WMesh, yMesh = np.meshgrid(self.WGrid, self.yGrid) cMesh = WMesh + yMesh - (self.findOptW1(yMesh, WMesh) / self.R) VMesh = -self.negValue(yMesh, WMesh) UPrimeMesh = self.uPrime(cMesh) # Integrate over y to get expected value EVMesh = self.yProb @ VMesh EUPrimeMesh = self.yProb @ UPrimeMesh # Now do 2D spline interpolation # Next line returns a warning message - ignore for now because I think it's working EV = SmoothBivariateSpline(yMesh.flatten(), WMesh.flatten(), EVMesh.flatten(), kx=self.spline_order, ky=self.spline_order, s=0) # Policy is to consume everything # I think we don't want to take the expected value here because we don't need to know the policy from the perspective of the previous period but only for the current period # Next line returns a warning message - ignore for now because I think it's working policy = SmoothBivariateSpline(yMesh.flatten(), WMesh.flatten(), cMesh.flatten(), kx=self.spline_order, ky=self.spline_order, s=0) # Marginal utility at optimum EUPrime = SmoothBivariateSpline(yMesh.flatten(), WMesh.flatten(), EUPrimeMesh.flatten(), kx=self.spline_order, ky=self.spline_order, s=0) return EV, policy, EUPrime
def spline_model(width_test, ratio_perim_area_test, width_data, ratio_perim_area_data, factor_data): """Return the result of the spline model. The bounding box is chosen so as to allow extrapolation. The spline orders are two in the width direction and one in the perimeter/area direction. For justification on using this method for modelling electron insert factors see the *Methods: Bivariate spline model* section within <http://dx.doi.org/10.1016/j.ejmp.2015.11.002>. Parameters ---------- width_test : np.ndarray The width point(s) which are to have the electron insert factor interpolated. ratio_perim_area_test : np.ndarray The perimeter/area which are to have the electron insert factor interpolated. width_data : np.ndarray The width data points for the relevant applicator, energy and ssd. ratio_perim_area_data : np.ndarray The perimeter/area data points for the relevant applicator, energy and ssd. factor_data : np.ndarray The insert factor data points for the relevant applicator, energy and ssd. Returns ------- result : np.ndarray The interpolated electron insert factors for width_test and ratio_perim_area_test. """ bbox = [ np.min([np.min(width_data), np.min(width_test)]), np.max([np.max(width_data), np.max(width_test)]), np.min([np.min(ratio_perim_area_data), np.min(ratio_perim_area_test)]), np.max([np.max(ratio_perim_area_data), np.max(ratio_perim_area_test)]) ] spline = SmoothBivariateSpline(width_data, ratio_perim_area_data, factor_data, kx=2, ky=1, bbox=bbox) return spline.ev(width_test, ratio_perim_area_test)
def spline_interpolation(x, y, z, **kwargs): """ """ x_grid, y_grid = np.meshgrid( np.arange(np.shape(z)[0]), np.arange(np.shape(z)[1]), ) x_grid = x_grid.ravel() y_grid = y_grid.ravel() z = z.T.ravel() z_spline = SmoothBivariateSpline(x_grid, y_grid, z, **kwargs) z_interpolated = z_spline(x, y, grid=False) return z_interpolated
def get_color_map_2d(anchors): n, m, ch = anchors.shape assert ch == 3 s, t = np.mgrid[0:1:n*1j, 0:1:m*1j] lab = color.rgb2lab(anchors) lch = color.lab2lch(lab) s = s.ravel() t = t.ravel() h = lch[:,:,2] for j in range(1, m): for i in range(n): while True: diff = h[i, j] - h[i, j-1] if diff > pi: h[i, j] -= 2*pi elif diff < -pi: h[i, j] += 2*pi else: break h_avg = np.average(h, weights=lch[:,:,1], axis=1) reverse = np.zeros(h_avg.shape, dtype=np.uint8) reverse[1:] = h_avg[1:] < h_avg[:-1] reverse=np.cumsum(reverse) print(reverse) h += reverse.reshape((-1, 1)) * 2*pi print(h) l = lch[:,:,0].ravel() c = lch[:,:,1].ravel() h = h.ravel() kx = min(1, n-1) L = SmoothBivariateSpline(s, t, l, kx=kx) C = SmoothBivariateSpline(s, t, c, kx=kx) H = SmoothBivariateSpline(s, t, h, kx=kx) def surface(s, t): LCH = np.stack((L(s, t, grid=False), C(s, t, grid=False), H(s, t, grid=False)), axis=-1) return color.lch2lab(LCH) return surface
def compute2DSpline(self, interpolated=[0, -1]): "TODO : Calcul spline 2d ???Je ne sais pas à quoi ca sert, ni ce que j'ai voulu essayer..." X = self.points[:, 0] Y = self.points[:, 1] Z = self.points[:, 2] maxw = 100.0 weight = ones(len(self.points)) for index in interpolated: weight[index] = maxw spl2d = SmoothBivariateSpline(X, Z, Y, w=weight, kx=3, ky=3, s=len(X) * 1.0e-8) self.spline2d = spl2d
def calc_t_map(t_values, breast_side): _init(breast_side) f = SmoothBivariateSpline(x=_x_breast, y=_y_breast, z=t_values[:-1], kx=2, ky=2) temperature_table = _fill_table( x_range=np.arange(-1, 1.01, 0.01), y_range=np.arange(-1, 1.01, 0.01), f=f, circle_x=_x_armpit, circle_y=_y_armpit, circle_r=_r_armpit, circle_value=t_values[-1]) min = _not_negative_min(temperature_table) max = _max(temperature_table) return temperature_table, min, max
def initialize_splines(self, splinedata, spline_smoothing=None): """Initialize Bivariate Splines used to interpolate and get derivatives for gaussian amplitudes as a function of sersic and rh """ with h5py.File(splinedata, "r") as data: n = data["nsersic"][:] r = data["rh"][:] A = data["amplitudes"][:] self.radii = data["radii"][:] nm, ng = A.shape self.splines = [ SmoothBivariateSpline(n, r, A[:, i], s=spline_smoothing) for i in range(ng) ] self.rh_range = (r.min(), r.max()) self.sersic_range = (n.min(), n.max())
def model(x, y): bbox = [ np.min([np.min(width), np.min(x)]), np.max([np.max(width), np.max(x)]), np.min([np.min(eqPonA), np.min(y)]), np.max([np.max(eqPonA), np.max(y)]) ] spline = SmoothBivariateSpline(width, eqPonA, factor, kx=2, ky=1, bbox=bbox) result = spline.ev(x, y) return result
def fit_spline(prf_data, domain, cmdline_args): """Return the best-fit spline to the PRF per the command line config.""" print("DOMAINDOMAIN", domain) if cmdline_args.spline_method == 'scipy': return SmoothBivariateSpline( prf_data[0], prf_data[1], prf_data[2], 1.0 / prf_data[3], s=cmdline_args.spline_smoothing * prf_data[3].size, bbox=domain ) return AlglibSpline( prf_data, cmdline_args.spline_resolution, cmdline_args.spline_smoothing, domain=domain )
def gen_cross_section_baryonic(mv, alpha_d): with open("data/xs_dis_B.txt") as infile: array1 = infile.read() array2 = array1.split("\n")[:-1] array3 = [line.split() for line in array2] array4 = np.array([[ float(line[0].split('_')[1].split('p')[1]), float(line[0].split('_')[2].split('.')[0][1:]), float(line[1]) ] for line in array3]) alpha_d_set = 1 / 4.0 / math.pi DIS_Func = SmoothBivariateSpline(array4[:, 0], array4[:, 1], array4[:, 2], kx=1, ky=1) return np.array([[ En, DIS_Func(mv, En) * (alpha_d / alpha_d_set)**2, DIS_Func(mv, En) * (alpha_d / alpha_d_set)**2 ] for En in range(3, 301, 1)])
def get_sfr_table(bad_extrapolation=False): """ LOAD SFR TABLE from Behroozi+13a,b Columns are: z+1, logmass, logsfr, logstellarmass Intermediate processing of tabulated data with option to extrapolate to unphysical masses """ tablepath = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) tablepath += '/tables/sfr_behroozi_release.dat' dat_zp1, dat_logm, dat_logsfr, _ = np.loadtxt(tablepath, unpack=True) dat_logzp1 = np.log10(dat_zp1) dat_sfr = 10.**dat_logsfr # Reshape arrays dat_logzp1 = np.unique(dat_logzp1) # log(z), 1D dat_logm = np.unique(dat_logm) # log(Mhalo), 1D dat_sfr = np.reshape(dat_sfr, (dat_logm.size, dat_logzp1.size)) dat_logsfr = np.reshape(dat_logsfr, dat_sfr.shape) # optional extrapolation to masses excluded in Behroozi+13 if bad_extrapolation: from scipy.interpolate import SmoothBivariateSpline dat_logzp1_, dat_logm_ = np.meshgrid(dat_logzp1, dat_logm) badspl = SmoothBivariateSpline(dat_logzp1_[-1000 < (dat_logsfr)], dat_logm_[-1000 < (dat_logsfr)], dat_logsfr[-1000 < (dat_logsfr)], kx=4, ky=4) dat_sfr[dat_logsfr == -1000.] = 10**badspl( dat_logzp1, dat_logm).T[dat_logsfr == -1000.] # Get interpolated SFR value(s) sfr_interp_tab = sp.interpolate.RectBivariateSpline(dat_logm, dat_logzp1, dat_sfr, kx=1, ky=1) return sfr_interp_tab
def SBS(self, ax, smooth, finegrid_size): # Elimino data con valores 'nan' fillbin = np.where(~np.isnan(self.param)) # Convierto arreglos 2D a 1D xf = self.x[fillbin].ravel() yf = self.y[fillbin].ravel() zf = self.param[fillbin].ravel() # print zf.shape, xf.shape, yf.shape # Grilla fina regularmente espaciada dx, dy = finegrid_size[0], finegrid_size[1] xi = np.arange(xf.min(), xf.max(), dx) yi = np.arange(yf.min(), yf.max(), dy) # Use SmoothBivariateSpline interpolation z2sum = np.sum(zf**2) kx, ky = 3, 3 # Spline s = smooth * z2sum, see note # s is a target for sum (Z() - spline())**2 ~ Ndata and Z**2; # smooth is relative, s absolute ''' NOTE: BivariateSpline y and x to be passed in this order (opposite to that of interp2d.) This issue is related to the way that meshgrid is indexed which is based on the conventions of MATLAB. ''' fit = SmoothBivariateSpline(yf, xf, zf, kx=kx, ky=ky, s=smooth * z2sum) Zspline = fit(yi, xi) # Plot pc = ax.pcolormesh(xi, yi, Zspline, cmap=self.cm, vmax=self.vmax, vmin=self.vmin) ax.set_title(self.par_name + ' - ' + self.time + ' SBSpline ' + str(smooth)) return pc
def spline_fit(x, y, z, evaluate=False, full_ccd=True, **interp_kwargs): """ spline fit to unstructured 3d data using scipy SmoothBivariateSpline. return callable and function evaluated over the pixels. Parameters: ----------- x, y, z: `array-like` data points to fit: f(x,y) = z evaluate: `bool` if True, evaluate the function over the pixels full_ccd: `bool` if you want to evaluate the model over a full CCD or just a RC. Returns: -------- spline function (+array) """ # smooth spline fit spline = SmoothBivariateSpline(x, y, z, **interp_kwargs) # eval spline over the pixels if evaluate: xmin, ymin = 0, 0 if full_ccd: xmin, ymin = -xsize, -ysize x_pix, y_pix = np.arange(xmin, xsize)[np.newaxis, ], np.arange( ymin, ysize)[:, np.newaxis] spline_arr = spline.ev(x_pix, y_pix) return spline, spline_arr else: return spline
def interpolate_apertures_try(self, aperture_centers, aperture_means): """ This function ... :return: """ return x_values = np.array([center.x for center in aperture_centers]) y_values = np.array([center.y for center in aperture_centers]) #X, Y = np.meshgrid(x_values, y_values) X = x_values Y = y_values Z = aperture_means #print(X, Y, Z) #print(len(X), len(Y), len(Z)) #C = intp((X, Y), Z) x_space = np.linspace(0, self.frame.xsize, 1) y_space = np.linspace(0, self.frame.ysize, 1) xi, yi = np.meshgrid(x_space, y_space) #zi = C(xi, yi) #self.sky = Frame(zi) from scipy.interpolate import LSQBivariateSpline spline = SmoothBivariateSpline(X, Y, Z, kx=1, ky=1) #spline = LSQBivariateSpline(X, Y, Z, X, Y) #zi = spline(xi, yi) #self.sky = Frame(zi) from scipy.interpolate import griddata #x_space = np.linspace(0.3*self.frame.xsize, 0.7*self.frame.xsize) #y_space = np.linspace(0.3*self.frame.ysize, 0.7*self.frame.ysize) x_space = np.array( range(int(0.3 * self.frame.xsize), int(0.7 * self.frame.xsize))) y_space = np.array( range(int(0.3 * self.frame.ysize), int(0.7 * self.frame.ysize))) znew = griddata((X, Y), Z, (x_space[None, :], y_space[:, None]), method='cubic') plt.figure() levels = np.linspace(min(Z), max(Z), 15) plt.ylabel('Y', size=15) plt.xlabel('X', size=15) cmap = plt.cm.jet_r cs = plt.contourf(x_space, y_space, znew, levels=levels, cmap=cmap) cbar = plt.colorbar(cs) cbar.set_label('Z', rotation=90, fontsize=15) # gas fraction plt.show() self.sky = Frame.zeros_like(self.frame) self.sky[int(0.3 * self.frame.ysize):int(0.3 * self.frame.ysize) + len(y_space), int(0.3 * self.frame.xsize):int(0.3 * self.frame.xsize) + len(x_space)] = znew
# # #xnew = np.arange(9,11.5, 0.01) #ynew = np.arange(9,15, 0.01) #znew = griddata((x, y), z, (xnew[None,:], ynew[:,None]), method='linear') from scipy.interpolate import SmoothBivariateSpline x = x.ravel() x = (x[x != np.isnan]) y = y.ravel() y = (y[y != np.isnan]) z = z.ravel() z = (z[z != np.isnan]) xnew = np.arange(9, 11.5, 0.01) ynew = np.arange(10.5, 15, 0.01) f = SmoothBivariateSpline(x, y, z, kx=1, ky=1) znew = np.transpose(f(xnew, ynew)) levels = np.linspace(min(z), max(z), 15) plt.ylabel('Y', size=15) plt.xlabel('X', size=15) cmap = plt.cm.jet_r cs = plt.contourf(xnew, ynew, znew, levels=levels, cmap=cmap) cbar = plt.colorbar(cs) cbar.set_label('Z', rotation=90, fontsize=15) # gas fraction plt.show()
# number of angles noa = data.shape[0] # create new x and y axes x = np.arange(0, noa) y = np.arange(min(heights), max(heights) + 1, noa) plot_array = np.zeros((max(x) + 1, max(y) + 1), dtype=np.float64) xinput = np.tile(x, noh) yinput = np.repeat(heights, noa) zinput = data[:, plot_column, :].T.flatten() # f = interp2d(x = xinput, y = yinput, z = zinput, kind='cubic') # interpolate f = SmoothBivariateSpline(x=xinput, y=yinput, z=zinput) xnew = np.arange(min(x), max(x) + 0.5, 1) ynew = np.arange(min(heights), max(heights), 1) # znew = f(xnew, ynew) znew = np.zeros((len(ynew), len(xnew))) # evaluate interpolation function on new grid j = 0 i = 0 for y in ynew: for x in xnew: znew[i, j] = f.ev(x, y) j += 1 i += 1
def makeInterpolation(self, myMethod="sbs", methodVal=None): # construct the interpolation grids for all coordinate systems # dictionaries with interpolation grids and coordinate systems self.interpGrids = {} self.interpEdges = {} self.interpValues = {} self.interpSpline = {} self.interpRbf = {} self.interpIDW = {} self.interpBMedian = {} self.interpBNentry = {} self.interpBMAD = {} self.interpTMean = {} self.interpTStd = {} # loop over Coordinate systems for iCoord in self.coordList: # build cell-centers for the interpolation grid ny, ylo, yhi, nx, xlo, xhi = self.gridArray[iCoord] yGrid, xGrid, yEdge, xEdge = self.makeGrid(ny, ylo, yhi, nx, xlo, xhi) self.interpGrids[iCoord] = [xGrid, yGrid] self.interpEdges[iCoord] = [xEdge, yEdge] data = self.pointsArray[iCoord] if self.debugFlag: print("PointMesh: At ", iCoord, "we have ", data.shape[0], " points") npts = data.shape[0] # check number of points if npts >= 5: xData = data[:, 0] yData = data[:, 1] zData = data[:, 2] if myMethod == "sbs": # SmoothBivariateSpline if npts > 600: self.interpSpline[iCoord] = SmoothBivariateSpline( xData, yData, zData, bbox=[xlo, xhi, ylo, yhi], kx=4, ky=4, s=1.e6) elif npts >= 100: self.interpSpline[iCoord] = SmoothBivariateSpline( xData, yData, zData, bbox=[xlo, xhi, ylo, yhi], kx=3, ky=3, s=1.e6) elif npts > 9: self.interpSpline[iCoord] = SmoothBivariateSpline( xData, yData, zData, bbox=[xlo, xhi, ylo, yhi], kx=2, ky=2, s=1.e6) else: self.interpSpline[iCoord] = SmoothBivariateSpline( xData, yData, zData, bbox=[xlo, xhi, ylo, yhi], kx=1, ky=1, s=1.e7) self.interpValues[iCoord] = self.interpSpline[iCoord].ev( xGrid.reshape((ny * nx)), yGrid.reshape( (ny * nx))).reshape((ny, nx)) elif myMethod == "rbf": self.interpRbf[iCoord] = Rbf(xData, yData, zData) self.interpValues[iCoord] = self.interpRbf[iCoord]( xGrid.reshape((ny * nx)), yGrid.reshape( (ny * nx))).reshape((ny, nx)) elif myMethod == "tmean": # use the truncated mean for each Coord -- very very simple!! zstd = stats.tstd(zData) zmean = stats.tmean(zData) ztmean = stats.tmean( zData, (zmean - 3. * zstd, zmean + 3. * zstd)) ztstd = stats.tstd(zData, (zmean - 3. * zstd, zmean + 3. * zstd)) self.interpTMean[iCoord] = ztmean self.interpTStd[iCoord] = ztstd self.interpValues[iCoord] = ztmean * numpy.ones((ny, nx)) elif myMethod == "bmedian": # use the median for each bin in each Coord self.interpBMedian[iCoord] = numpy.zeros((ny, nx)) self.interpBNentry[iCoord] = numpy.zeros((ny, nx)) self.interpBMAD[iCoord] = numpy.zeros((ny, nx)) zvalL = [] xbin = numpy.digitize(xData, xEdge[0, :]) - 1 ybin = numpy.digitize(yData, yEdge[:, 0]) - 1 for i in range(nx): for j in range(ny): ok = numpy.logical_and.reduce( (xbin == i, ybin == j)) zHere = zData[ok] # add nEntry, MAD to the saved variables for the Mesh nEntry = zHere.shape[0] if nEntry >= 1: median_value = numpy.median(zHere) self.interpBMedian[iCoord][j, i] = median_value self.interpBNentry[iCoord][j, i] = nEntry self.interpBMAD[iCoord][j, i] = numpy.median( numpy.abs(zHere - median_value)) else: # need to do something better! self.interpBMedian[iCoord][j, i] = 0. # fill interpValues, need to match order of locations in xGrid and yGrid self.interpValues[iCoord] = self.interpBMedian[ iCoord].copy() elif myMethod == "grid": Z = griddata((xData, yData), zData, (xGrid.reshape( (ny * nx)), yGrid.reshape((ny * nx))), "linear") self.interpValues[iCoord] = Z.reshape(xGrid.shape) elif myMethod == "idw": # July 15, 2013 - change to use epsilon=1.0 (mm) to set a cutoff in the distance # this will make small changes in the results for all Donuts if methodVal != None: usekNN = methodVal[0] useEpsilon = methodVal[1] else: usekNN = 4 useEpsilon = 1.0 self.interpIDW[iCoord] = IDWInterp(xData, yData, zData, kNN=usekNN, epsilon=useEpsilon) self.interpValues[iCoord] = self.interpIDW[iCoord].ev( xGrid.reshape((ny * nx)), yGrid.reshape( (ny * nx))).reshape((ny, nx)) else: self.interpSpline[iCoord] = None self.interpValues[iCoord] = numpy.zeros(xGrid.shape) else: self.interpTMean[iCoord] = 0.0 self.interpBMedian[iCoord] = None self.interpBNentry[iCoord] = None self.interpBMAD[iCoord] = None self.interpTStd[iCoord] = 0.0 self.interpSpline[iCoord] = None self.interpRbf[iCoord] = None self.interpValues[iCoord] = numpy.zeros(xGrid.shape)
blade_mass = blade_mass / max(blade_mass) Vrated = Vrated / max(Vrated) I1 = I1 / max(I1) I2 = I2 / max(I2) I3 = I3 / max(I3) ratedT = ratedT / max(ratedT) extremeT = extremeT / max(extremeT) cartcoord = list(zip(ratedPower, rotorDiameter)) w = np.ones(len(ratedPower)) * 2. order = 2 interp_spline_ratedQ = SmoothBivariateSpline(ratedPower, rotorDiameter, ratedQ, w, kx=order, ky=order) interp_spline_blade_mass = SmoothBivariateSpline(ratedPower, rotorDiameter, blade_mass, w, kx=order, ky=order) #, s=1000.) interp_spline_Vrated = SmoothBivariateSpline(ratedPower, rotorDiameter, Vrated, w, kx=order, ky=order) interp_spline_I1 = SmoothBivariateSpline(ratedPower,
def interpolate_potential_old_smooth(potential, smoothing=None): x = np.array(potential.mesh.getFaceCenters()[0]) y = np.array(potential.mesh.getFaceCenters()[1]) z = np.array(potential.arithmeticFaceValue()) return SmoothBivariateSpline(x, y, z, s=smoothing, kx=3, ky=3)
Z += np.random.normal(0, noise, Z.shape) # print "Z:\n", Z z2sum = np.sum(Z**2) xnew = np.linspace(0, 1, Newx) ynew = np.linspace(0, 1, Newy) Zexact = testfunc(*np.meshgrid(xnew, ynew)) if imclip is None: imclip = np.min(Zexact), np.max(Zexact) xflat, yflat, zflat = X.flatten(), Y.flatten(), Z.flatten() #............................................................................... print "SmoothBivariateSpline:" fit = SmoothBivariateSpline(xflat, yflat, zflat, kx=kx, ky=ky, s=smooth * z2sum) Zspline = fit(xnew, ynew).T # .T ?? splineerr = Zspline - Zexact print "Zspline - Z:", avminmax(splineerr) print "Zspline: ", avminmax(Zspline) print "Z: ", avminmax(Zexact) res = fit.get_residual() print "residual %.0f res/z2sum %.2g" % (res, res / z2sum) # print "knots:", fit.get_knots() # print "Zspline:", Zspline.shape, "\n", Zspline print "" #...............................................................................