def lookahead(self, point): lookahead_distance = 0.5 cl = self.closest(point) if cl[4] == 1: dst = self.lane2orig[cl[3]][0] dst += lookahead_distance if dst > self.lane1orig[-1][0]: dst -= self.lane1orig[-1][0] arcLenghtArray1 = self.lane1[:, 0] xArray1 = self.lane1[:, 1] yArray1 = self.lane1[:, 2] xCs1 = interpolate.CubicSpline(arcLenghtArray1, xArray1) yCs1 = interpolate.CubicSpline(arcLenghtArray1, yArray1) x = xCs1(dst) y = yCs1(dst) else: dst = self.lane2orig[cl[3]][0] dst += lookahead_distance if dst > self.lane2orig[-1][0]: dst -= self.lane2orig[-1][0] arcLenghtArray2 = self.lane2[:, 0] xArray2 = self.lane2[:, 1] yArray2 = self.lane2[:, 2] xCs2 = interpolate.CubicSpline(arcLenghtArray2, xArray2) yCs2 = interpolate.CubicSpline(arcLenghtArray2, yArray2) x = xCs2(dst) y = yCs2(dst) lookahead_point = (x, y) return (lookahead_point)
def interp_val(self, s, fourier='b'): if fourier == 'b': if self.interpb_at == s: return for i in range(self.nmnnyq): bspl = interp.CubicSpline(self.shalf, self.bmnc[:, i]) self.interpb_at = s self.binterp[i] = bspl(s) elif fourier == 'r': if self.interpr_at == s: return for i in range(self.nmn): bspl = interp.CubicSpline(self.s, self.rmnc[:, i]) self.interpr_at = s self.rinterp[i] = bspl(s) elif fourier == 'z': if self.interpz_at == s: return for i in range(self.nmn): bspl = interp.CubicSpline(self.s, self.zmns[:, i]) self.interpz_at = s self.zinterp[i] = bspl(s) elif fourier == 'l': if self.interpl_at == s: return for i in range(self.nmn): bspl = interp.CubicSpline(self.s, self.lmns[:, i]) self.interpl_at = s self.linterp[i] = bspl(s) else: print('wrong value passed to interp_val')
def compute_abscissas(self): """ Computes the normalized curvilinear abscissas t corresponding to the coordinates of the airfoil. """ # first, approximate the curve by linear interpolation to get an approximation of the curvilinear abscissa. lengths = np.sqrt(np.diff(self.x)**2 + np.diff(self.y)**2) s = np.concatenate(([0], lengths)).cumsum() # curvilinear abscissa t = s / s[-1] # normalize # compute the new curvilinear abscissa and iterate until convergence tc1 = np.linspace(0, 1, self.n) err = 1. i = 0 if self.verbose: print("Computing the curvilinear abscissa...") while err > self.tol: # get the high resolution points x1 = interpolate.CubicSpline(t, self.x)(tc1) y1 = interpolate.CubicSpline(t, self.y)(tc1) # approximate the curvilinear abscissa based on a linear interpolation between high resolution points lengths = np.sqrt(np.diff(x1)**2 + np.diff(y1)**2) s1 = np.concatenate(([0], lengths)).cumsum() t1 = s1 / s1[-1] # update the normalized curvilinear abscissa at coordinate points t_new = interpolate.CubicSpline(tc1, t1)(t) err = np.linalg.norm(t_new - t) t = t_new if self.verbose: print(f"iteration {i}, err = {err}") i = i + 1 return (t, s1[-1])
def spline(self): arcLengthArray1 = self.lane1[:, 0] xArray1 = self.lane1[:, 1] yArray1 = self.lane1[:, 2] arcLengthArray2 = self.lane2[:, 0] xArray2 = self.lane2[:, 1] yArray2 = self.lane2[:, 2] xCs1 = interpolate.CubicSpline(arcLengthArray1, xArray1) yCs1 = interpolate.CubicSpline(arcLengthArray1, yArray1) xCs2 = interpolate.CubicSpline(arcLengthArray2, xArray2) yCs2 = interpolate.CubicSpline(arcLengthArray2, yArray2) x1coord = xCs1(self.lane1Orig[:, 0]) y1coord = yCs1(self.lane1Orig[:, 0]) x2coord = xCs2(self.lane2Orig[:, 0]) y2coord = yCs2(self.lane2Orig[:, 0]) self.markerPoints1 = [Point(x, y, 0) for x, y in zip(x1coord, y1coord)] self.markerPoints2 = [Point(x, y, 0) for x, y in zip(x2coord, y2coord)] markerLane1 = self.makeMarkerLineStrip(self.markerPoints1, 0) markerLane2 = self.makeMarkerLineStrip(self.markerPoints2, 1) #subscriber rate = rospy.Rate(10) # 10hz self.clickPointSub = rospy.Subscriber("/clicked_point", PointStamped, self.callbackClosest) while not rospy.is_shutdown(): self.pub.publish(markerLane1) self.pub.publish(markerLane2) rate.sleep()
def make_pdf(lo, hi, params): """ """ grid = 500 x = np.linspace(0.9 * lo, 1.1 * hi, grid) s, b, total = model(x, **params) return (interpolate.CubicSpline(x, total), interpolate.CubicSpline(x, s), interpolate.CubicSpline(x, b), 1.01 * max(total))
def spline(self): arcLenghtArray1 = self.lane1[:, 0] xArray1 = self.lane1[:, 1] yArray1 = self.lane1[:, 2] arcLenghtArray2 = self.lane2[:, 0] xArray2 = self.lane2[:, 1] yArray2 = self.lane2[:, 2] xCs1 = interpolate.CubicSpline(arcLenghtArray1, xArray1) yCs1 = interpolate.CubicSpline(arcLenghtArray1, yArray1) xCs2 = interpolate.CubicSpline(arcLenghtArray2, xArray2) yCs2 = interpolate.CubicSpline(arcLenghtArray2, yArray2) marker1 = create_marker(1) x1coord = xCs1(self.lane1orig[:, 0]) y1coord = yCs1(self.lane1orig[:, 0]) points1 = [Point(x, y, 0) for x, y in zip(x1coord, y1coord)] marker1.points = points1 marker2 = create_marker(2) x2coord = xCs2(self.lane2orig[:, 0]) y2coord = yCs2(self.lane2orig[:, 0]) points2 = [Point(x, y, 0) for x, y in zip(x2coord, y2coord)] marker2.points = points2 self.array1 = points1 self.array2 = points2 rate = rospy.Rate(10) # 10hz while not rospy.is_shutdown(): self.marker_pub.publish(marker1) self.marker_pub.publish(marker2) rate.sleep()
def integrateprofile(m): profile = np.loadtxt("density_{0}_{1}_{2}.txt".format(name, m, h), usecols=(0, 1, 3, 4), unpack=True) for i in params: if int(i[0]) == m: fb = i[2] dfb = i[3] radius = i[1] break # for i in range(len(profile)): # if profile[i][0] > radius: # bord = i # profile = np.transpose(profile[:bord]) x = profile[0] y = 2*np.pi*x*profile[1] ymin = 2*np.pi*x*profile[2] ymax = 2*np.pi*x*profile[3] yspl = interpolate.CubicSpline(x, y) yminspl = interpolate.CubicSpline(x, ymin) ymaxspl = interpolate.CubicSpline(x, ymax) bkg = np.pi*fb*radius**2 sigmabkg = np.pi*dfb*radius**2 n1 = yspl.integrate(0, radius) # print('n1=', n1-bkg) n2 = yminspl.integrate(0, radius) # print('n2=', n2-bkg+sigmabkg) n3 = ymaxspl.integrate(0, radius) # print('n3=', n3-bkg-sigmabkg) sigmaint = max(abs(n2-n1), abs(n3-n1)) sigmanc = np.sqrt(sigmaint**2+sigmabkg**2) return (n1-bkg, sigmanc, sigmaint, sigmabkg)
def manglemin(params, SpectrumObject, data_table, verbose=False, clamped=False, *args, **kwargs): """ """ MangledSpectrumObject = copy.deepcopy(SpectrumObject) paramlist = np.array([params[key].value for key in params.keys()]) # weights = np.append(np.append(1.0, paramlist), 1.0) mc_l, mc_u = functions.calc_linear_terms(data_table[data_table["mask"]], key="weights") data_table["weights"][0] = mc_l[0] * data_table["lambda_eff"][0] + mc_l[1] data_table["weights"][-1] = mc_u[0] * data_table["lambda_eff"][-1] + mc_u[1] weights = data_table["weights"].data # print(weights) data_table["weights"][data_table["mask"]] = paramlist data_table["mangledspec_filterflux"][0] = data_table["spec_filterflux"][0] * data_table["weights"][0] data_table["mangledspec_filterflux"][-1] = data_table["spec_filterflux"][-1] * data_table["weights"][-1] if clamped: SplObj = interpolate.CubicSpline(data_table["lambda_eff"], weights, bc_type = "clamped") else: SplObj = interpolate.CubicSpline(data_table["lambda_eff"], weights) MangledSpectrumObject.flux = MangledSpectrumObject.flux * SplObj(MangledSpectrumObject.wavelength) specflux = np.array([calc_spectrum_filter_flux(filter_object=FilterObject, spectrum_object=MangledSpectrumObject, verbose=verbose) for FilterObject in data_table[data_table["mask"]]["filter_object"]]) if verbose: print("params:", paramlist) print("weights:", weights) print("flux:", specflux) print("fitflux:", data_table[data_table["mask"]]["fitflux"].data) return data_table[data_table["mask"]]["fitflux"] - specflux ## minimising residual - better to do chisq? or minimise the sum?? TODO
def gpsSatPositionSP3(fsp3, dt, sv=None, rx_position=None, coords='xyz'): assert sv is not None # Read in data D = gr.load(fsp3).sel(sv=sv) if isinstance(dt, list): dt = np.asarray(dt) dt = dt.astype('datetime64[s]') navtimes = D.time.values.astype('datetime64[s]') CSx = interpolate.CubicSpline(navtimes.astype(int), D.position.values[:, 0]) CSy = interpolate.CubicSpline(navtimes.astype(int), D.position.values[:, 1]) CSz = interpolate.CubicSpline(navtimes.astype(int), D.position.values[:, 2]) ecefxi = CSx(dt.astype(int)) * 1e3 ecefyi = CSy(dt.astype(int)) * 1e3 ecefzi = CSz(dt.astype(int)) * 1e3 if coords == 'xyz': return np.array([ecefxi, ecefyi, ecefzi]) else: AER = ecef2aer(x=ecefxi, y=ecefyi, z=ecefzi, lon0=rx_position[1], lat0=rx_position[0], h0=rx_position[2]) return np.array(AER)
def interp_3(motion_data): a = len(motion_data)*(1000/360) time = [] for i in range(len(motion_data)): time.append((1/360)*1000*i) #Hz to Milliseconds resolution = np.arange(0, a, 1) x = [] for i in motion_data: x.append(i[0]) x_function = interpolate.CubicSpline(time, x) x_interp = x_function(resolution) # use interpolation function returned by `interp1d` y = [] for i in motion_data: y.append(i[1]) y_function = interpolate.CubicSpline(time, y) y_interp = y_function(resolution) # use interpolation function returned by `interp1d` z = [] for i in motion_data: z.append(i[2]) z_function = interpolate.CubicSpline(time, z) z_interp = z_function(resolution) # use interpolation function returned by `interp1 final_motion_list = [] for i in range(len(x_interp)): final_motion_list.append([x_interp[i],y_interp[i],z_interp[i]]) print('lengths') print(len(motion_data)) print(len(final_motion_list)) return final_motion_list
def interpolate_orbit(orbit, hdr): """ Interpolate X, Y, Z values as sampling on the Rinex file. Thus, both measures have the same precision :param orbit: The python orbit object less precise than rinex :param hdr: Rinex header, to extract rinex precision, first and last acquisition :return: The python orbit object with the same precise than rinex, with interpolated values """ orbit_interpolated = {} rinex_last_obs_time = Utils.rinex_str_date_to_datetime(hdr) sat_date = orbit['date'] date_array_interpolated = np.array([]) aux_date = sat_date[0] date_array_interpolated = np.append(date_array_interpolated, sat_date[0]) while aux_date < rinex_last_obs_time: aux_date += timedelta(seconds=float(hdr['interval'])) date_array_interpolated = np.append(date_array_interpolated, aux_date) orbit_interpolated['date'] = date_array_interpolated for prn, data in orbit.items(): if prn is 'date' or prn is 'path': continue x_aux = np.array([]) y_aux = np.array([]) z_aux = np.array([]) for item in data: x_aux = np.append(x_aux, item['x']) y_aux = np.append(y_aux, item['y']) z_aux = np.append(z_aux, item['z']) x_interp = interp.CubicSpline(np.arange(x_aux.size), x_aux) x_interp = x_interp( np.linspace(0, x_aux.size - 1, date_array_interpolated.size)) y_interp = interp.CubicSpline(np.arange(y_aux.size), y_aux) y_interp = y_interp( np.linspace(0, y_aux.size - 1, date_array_interpolated.size)) z_interp = interp.CubicSpline(np.arange(z_aux.size), z_aux) z_interp = z_interp( np.linspace(0, z_aux.size - 1, date_array_interpolated.size)) pos_aux = [] for i in range(len(date_array_interpolated)): pos_aux.append({ 'x': x_interp[i], 'y': y_interp[i], 'z': z_interp[i] }) orbit_interpolated[prn] = pos_aux return orbit_interpolated
def fit(self): """ fit scan to an appropriate spline calculate a set of partition function values at different temperatures and fit a spline to the partition function values generate splines for the first and second derivatives of the partition function """ N = len(self.pivots) if N > 2: self.V = interpolate.LinearNDInterpolator(self.phis, self.Es) self.rootD = interpolate.LinearNDInterpolator( self.phis, self.rootDs) elif N == 2: self.V = interpolate.SmoothBivariateSpline(self.phis[:, 0], self.phis[:, 1], self.Es) self.rootD = interpolate.SmoothBivariateSpline( self.phis[:, 0], self.phis[:, 1], self.rootDs) else: self.V = interpolate.CubicSpline(self.phis, self.Es) self.rootD = interpolate.CubicSpline(self.phis, self.rootDs) Tlist = np.linspace(10.0, 3001.0, num=20, dtype=np.float64) Qs = [] for T in Tlist: Qs.append(self.calc_partition_function(T)) self.Q = interpolate.CubicSpline(Tlist, Qs) self.dQdT = self.Q.derivative() self.d2QdT2 = self.dQdT.derivative()
def stopping_conditions(imf,t): mins = signal.argrelmin(imf)[0] mins_ = [float(data*60/8064) for data in mins] maxs = signal.argrelmax(imf)[0] maxs_ = [float(data*60/8064) for data in maxs] spl_min = interpolate.CubicSpline(mins_,imf[mins])#, bc_type = 'natural') #clamped spl_max = interpolate.CubicSpline(maxs_, imf[maxs])#, bc_type = 'natural')#clamped mean_amplitude = [np.abs(spl_max(i)+spl_min(i))/2 for i in range(0,len(t))] envelope_amplitude = [np.abs(spl_max(i)- spl_min(i))/2 for i in range(0,len(t))] bo = [(m/e > 0.05) for m,e in zip(mean_amplitude,envelope_amplitude)] #at each point, mean_amplitude < THRESHOLD2*envelope_amplitude condition = [not(m < 0.5*e) for m,e in zip(mean_amplitude,envelope_amplitude)] #mean of boolean array {(mean_amplitude)/(envelope_amplitude) > THRESHOLD} < TOLERANCE if((1 in condition) or (not(np.mean(bo)<0.05))): return False # |#zeros-#extrema|<=1 zero_crossings = np.where(np.diff(np.signbit(imf)))[0] diff_zeroCr_extremas = np.abs(len(maxs)+len(mins)-len(zero_crossings)) if(diff_zeroCr_extremas <= 1):# and mean <0.1): return True else: return False
def __init__(self, x, y): x, y = map(np.asarray, (x, y)) s = np.append([0], (np.cumsum(np.diff(x)**2) + np.cumsum(np.diff(y)**2))**0.5) self.X = interpolate.CubicSpline(s, x) self.Y = interpolate.CubicSpline(s, y) self.length = s[-1]
def LoadNkData(wl, fname, delim=';', units=1000, omit=1): rawd = np.loadtxt(fname, delimiter=delim, skiprows=omit) wl0 = rawd[:, 0] * units nd = rawd[:, 1] kd = rawd[:, 2] ni = sinterp.CubicSpline(wl0, nd) ki = sinterp.CubicSpline(wl0, kd) return ni(wl) + 1j * ki(wl)
def currents_and_derivs(self, s): ipspl = interp.CubicSpline(self.s, self.Ip) ip = np.empty(2) ip[0] = ipspl(s) ip[1] = ipspl.derivatives(s) itspl = interp.CubicSpline(self.s, self.It) it = np.empty(2) it[0] = itspl(s) it[1] = itspl.derivatives(s) return ip, it
def writeTests2(config, format): data = np.random.randn(11) data = Tools.normalize(data) config.writeInput(7, data) ref = np.sort(data) config.writeReference(7, ref) data = np.random.randn(16) data = Tools.normalize(data) config.writeInput(8, data) ref = np.sort(data) config.writeReference(8, ref) data = np.random.randn(32) data = Tools.normalize(data) config.writeInput(9, data) ref = np.sort(data) config.writeReference(9, ref) data = np.full((16), np.random.randn(1)) data = Tools.normalize(data) config.writeInput(10, data) ref = np.sort(data) config.writeReference(10, ref) x = [0,3,10,20] config.writeInput(11,x,"InputX") y = [0,9,100,400] config.writeInput(11,y,"InputY") xnew = np.arange(0,20,1) config.writeInput(11,xnew,"OutputX") ynew = interpolate.CubicSpline(x,y) config.writeReference(11, ynew(xnew)) x = np.arange(0, 2*np.pi+np.pi/4, np.pi/4) config.writeInput(12,x,"InputX") y = np.sin(x) config.writeInput(12,y,"InputY") xnew = np.arange(0, 2*np.pi+np.pi/16, np.pi/16) config.writeInput(12,xnew,"OutputX") ynew = interpolate.CubicSpline(x,y,bc_type="natural") config.writeReference(12, ynew(xnew)) x = [0,3,10] config.writeInput(13,x,"InputX") y = x config.writeInput(13,y,"InputY") xnew = np.arange(-10,20,1) config.writeInput(13,xnew,"OutputX") ynew = interpolate.CubicSpline(x,y) config.writeReference(13, ynew(xnew))
def normalize_curve(points, npoints): px = points[:, 0] py = points[:, 1] t = np.linspace(0, 1, len(points)) fx = interpolate.CubicSpline(t, px) fy = interpolate.CubicSpline(t, py) nt = np.linspace(0, 1, npoints) npx = fx(nt) npy = fy(nt) return npx, npy
def siftStepCubSpl(xArray, sigArray): """ EMD sifting function : - Input -> [ xArray, sigArray ] signal time-history - Output -> [ candidate mode, inf envelope, sup envelope ] calculates a candidate Empirical Mode as a point-to-point average of sup and inf envelopes - using Cubic Splines. """ # # signal length sigLen = len(sigArray) # point-to-point differential sigDiff = 0.0 * sigArray sigDiff[1:sigLen] = sigArray[1:sigLen] - sigArray[0:sigLen - 1] # # gradient signature - positive and negative grdPls = sigDiff > 0.0 grdMns = ~grdPls # # calculate indexes to local sup and inf elements # # negative and positive gradients negGrdId = 1 * grdMns posGrdId = 1 * grdPls # markers of sup and inf elements supMrkFlg = 0 * grdPls infMrkFlg = 0 * grdMns supMrkFlg[0:sigLen - 1] = posGrdId[0:sigLen - 1] + negGrdId[1:sigLen] infMrkFlg[0:sigLen - 1] = negGrdId[0:sigLen - 1] + posGrdId[1:sigLen] # # inf and sup indexes supIdx = supMrkFlg == 2 infIdx = infMrkFlg == 2 # # extend supIdx and infIdx to extremes supIdx[0] = True supIdx[sigLen - 1] = True infIdx[0] = True infIdx[sigLen - 1] = True # # calculate sup and inf envelopes by cubic spline # infIntpFcn = intp.CubicSpline(xArray[infIdx], sigArray[infIdx]) supIntpFcn = intp.CubicSpline(xArray[supIdx], sigArray[supIdx]) # infEnv = infIntpFcn(xArray) supEnv = supIntpFcn(xArray) # # calculate candidate mode cndMode = sigArray - 0.5 * (infEnv + supEnv) # return [cndMode, infEnv, supEnv]
def __init__(self, x, y, n=10000, tol=1e-13, verbose=False): self.n = n self.tol = tol self.verbose = verbose self.x = x self.y = y (self.t, self.length) = self.compute_abscissas() self.x_int = interpolate.CubicSpline(self.t, self.x) self.y_int = interpolate.CubicSpline(self.t, self.y) self.dx_int = self.x_int.derivative(1) self.dy_int = self.y_int.derivative(1) self.d2x_int = self.x_int.derivative(2) self.d2y_int = self.y_int.derivative(2) self.trigonometric_direction = self.is_trigonometric()
def interp_1d_values_from_profiles(self): """Interpolate values in 1D (lateral + longitudinal) from profiles""" new_values = np.zeros((self.nb_var, self.nb_nodes_in_riverbed)) for i_zone in np.unique(self.points['zone']): filter_points = self.points['zone'] == i_zone section_us = self.section_seq[i_zone] section_ds = self.section_seq[i_zone + 1] xt_us = section_us.coord.array['Xt'] xt_ds = section_ds.coord.array['Xt'] xt_us_target = self.points['Xt_upstream'][filter_points] xt_ds_target = self.points['Xt_downstream'][filter_points] for i, var in enumerate(self.var_names()): values_us = section_us.coord.values[var] values_ds = section_ds.coord.values[var] if self.interp_values == 'LINEAR': new_values_us = np.interp(xt_us_target, xt_us, values_us) new_values_ds = np.interp(xt_ds_target, xt_ds, values_ds) elif self.interp_values == 'B-SPLINE': splrep_us = interpolate.splrep(xt_us, values_us) splrep_ds = interpolate.splrep(xt_ds, values_ds) new_values_us = interpolate.splev(xt_us_target, splrep_us) new_values_ds = interpolate.splev(xt_ds_target, splrep_ds) elif self.interp_values == 'AKIMA': new_values_us = interpolate.Akima1DInterpolator( xt_us, values_us)(xt_us_target) new_values_ds = interpolate.Akima1DInterpolator( xt_ds, values_ds)(xt_ds_target) elif self.interp_values == 'PCHIP': new_values_us = interpolate.pchip_interpolate( xt_us, values_us, xt_us_target) new_values_ds = interpolate.pchip_interpolate( xt_ds, values_ds, xt_ds_target) elif self.interp_values == 'CUBIC_SPLINE': new_values_us = interpolate.CubicSpline( xt_us, values_us)(xt_us_target) new_values_ds = interpolate.CubicSpline( xt_ds, values_ds)(xt_ds_target) else: raise NotImplementedError new_values[i, filter_points] = new_values_us * (1 - self.points['xl'][filter_points]) + \ new_values_ds * self.points['xl'][filter_points] return new_values
def interpolate_curve(px1, py1, px2, py2, z): px3 = np.zeros(shape=(z.shape[0], px1.shape[0])) py3 = np.zeros(shape=(z.shape[0], py1.shape[0])) t = np.array((0.0, 1.0)) for i in range(px1.shape[0]): fx = interpolate.CubicSpline(t, np.array((px1[i], px2[i]))) fy = interpolate.CubicSpline(t, np.array((py1[i], py2[i]))) px3[:, i] = fx(z) py3[:, i] = fy(z) return px3, py3
def emd(data, sd=0.1, bc="natural"): t = np.arange(data.shape[0]) imfs = [] last_imf = False residue = data.copy() for i in range(20): h_prev = residue _i = 0 for _ in range(50): maxima_idx = signal.argrelmax(h_prev, order=1)[0] minima_idx = signal.argrelmin(h_prev, order=1)[0] maxima_idx = np.insert(maxima_idx, 0, 0) maxima_idx = np.append(maxima_idx, len(h_prev) - 1) minima_idx = np.insert(minima_idx, 0, 0) minima_idx = np.append(minima_idx, len(h_prev) - 1) if (len(maxima_idx) + len(minima_idx)) <= 6: last_imf = True break maxima_vals = interpolate.CubicSpline(maxima_idx, h_prev[maxima_idx], bc_type=bc)(t) minima_vals = interpolate.CubicSpline(minima_idx, h_prev[minima_idx], bc_type=bc)(t) mean = 0.5 * (maxima_vals + minima_vals) h = h_prev - mean _i += 1 # sifting criterion sd_ = np.sum((h - h_prev)**2) / np.sum(h_prev**2) if sd_ < sd: break h_prev = h.copy() if last_imf: break imfs.append(np.nan_to_num(h)) residue -= h # Add residue imfs.append(data - sum(imfs)) return imfs
def test_stat_point_minimisation(): # Test that the minimisation works for very shallow minima energies_list = [ np.array([0.0, 3.8, -9.1, -1.6, 0.3]), np.array([0.0, 10, -20, 10, -5]) ] for energies in energies_list: result = minimize(plotting.error_on_stationary_points, x0=energies, args=(energies, ), method='BFGS', tol=0.1) assert result.success spline = interpolate.CubicSpline([0, 1, 2, 3, 4], result.x, bc_type='clamped') fine_zi_s = np.linspace(-0.2, 5.2, num=500) stationary_points = plotting.get_stationary_points( xs=fine_zi_s, dydx=spline.derivative()) assert len(stationary_points) == 5
def punto5(xi, yi, xk): nat = inter.CubicSpline(xi, yi, bc_type="natural") f = open("punto5.txt", "w") f.write("X_new \t{:^25s}\n".format("y_new(polinomial)")) for i in xk: f.write("{:}\t\t{:}\n".format(i, nat(i))) f.close()
def interpolate_axis(time, data): time = time.tolist() data = data.tolist() func = interpolate.CubicSpline(time, data) time_new = np.arange(0, time[-1], 0.04) data_new = func(time_new) return data_new
def get_band(self, band_index, interpolate_missing=False): """Return picked band with index *band_index*. Set *interpolate_missing* to return interpolated frequencies instead of -1 at k-vectors where no frequency was picked. The interpolation will be done with a cubic spline through the picked frequencies. """ try: band = self.bands[band_index] except IndexError: raise IndexError('ModePicker.get_band: band_index %i exceeds ' 'number of available bands.' % band_index) if not interpolate_missing: return band.values[:] # only use picked k-vecs for interpolation: X = np.nonzero(band.values != -1)[0] if len(X) <= 3: # too little points. Don't interpolate. return band.values[:] # interpolate data, using cubic spline try: f_interp = interpolate.CubicSpline( X, band.values[X], bc_type=map( ['not-a-knot', 'clamped'].__getitem__, [self.first_point_zero_deriv, self.last_point_zero_deriv])) except: raise ValueError('could not interpolate', X, band.values[X]) return f_interp(np.arange(len(band.values)))
def __init__(self, data, child, name=None, interpolator="cubic spline", extrapolate=True): if data.ndim != 2 or data.shape[1] != 2: raise ValueError(""" data should have exactly two columns (x and y) but has shape {} """.format(data.shape)) elif interpolator == "pchip": interpolating_function = interpolate.PchipInterpolator( data[:, 0], data[:, 1], extrapolate=extrapolate) elif interpolator == "cubic spline": interpolating_function = interpolate.CubicSpline( data[:, 0], data[:, 1], extrapolate=extrapolate) else: raise ValueError( "interpolator '{}' not recognised".format(interpolator)) # Set name if name is not None: name = "interpolating function ({})".format(name) else: name = "interpolating function" super().__init__(interpolating_function, child, name=name, derivative="derivative") # Store information as attributes self.interpolator = interpolator self.extrapolate = extrapolate
def GeneratePeriodicSplineLookupTable(control_points): """Generate a lookup table based on a periodic spline in the FBL format. FBL splines are equally spaced around the FBL loop (going clockwise with zero at 12 o'clock). Args: control_points: List of points defining the spline. Returns: A lookup table from 0 to 2 pi as a list. """ # The periodic cubic spline is built from the control points, reusing the # last point at the start to close out the period. # The control points are positioned in the center of equally divided segments # of the loop, leading to a half segment offset, to match FBL convention. spline_x = (np.linspace(0., 1., len(control_points) + 1, endpoint=True) - 0.5 / len(control_points)) spline_y = np.array([control_points[-1]] + control_points) spline_fit = interpolate.CubicSpline(spline_x, spline_y, bc_type='periodic', extrapolate='periodic') # The x coordinates in the crosswind controller domain from # _GenerateLookupTable are transformed from the controller to FBL domain # before sampling. return _GenerateLookupTable(lambda x: spline_fit((-x + 1.5 * np.pi) / (2.0 * np.pi)))
def __init__( self, time_list, value_list, crossing_value=0, neg_to_pos_is_start=True ): # Check whether time_list and value_list size are equal if len(time_list) != len(value_list): raise ValueError( f"Time list and value list are of different sizes. " f"({len(time_list)} vs. ({len(value_list)}))" ) self.search_interval = TimeInterval(time_list[0], time_list[-1]) # Convert time to "days since epoch" t_float_list = (time_list - time_list[0]).jd # Init interpolators (for splines, root finding possible for 3rd degree # (cubics) only) self._interpolator = interpolate.CubicSpline( t_float_list, value_list - crossing_value ) self._deriv_interpolator = self._interpolator.derivative() # Find start / end intervals self.start_end_intervals = self._find_intervals(time_list, neg_to_pos_is_start) # Find max / min events self.max_min_table = self._find_extrema_events(time_list[0]) # Return the table to absolute values self.max_min_table["value"] = self.max_min_table["value"] + crossing_value