def discretize(values, interp_type, minval, maxval, disc_points): """interpolates and discretizes given potential Args: pot_values (list): potential values [[x], [V(x)]] type (string): type of interpolation minval (float): x-min point maxval (float): x-max point disc_points (int): number of discretization points Returns: list: discretized potential [[x], [V(x)]] """ if interp_type == "linear": pot_values = interpolate.interp1d(values[0], values[1], "linear") elif interp_type == "cspline": pot_values = interpolate.CubicSpline(values[0], values[1]) elif interp_type == "polynomial": pot_values = interpolate.BarycentricInterpolator(values[0], values[1]) else: pot_values = 0 pot_disc = [] pot_disc.append(np.linspace(minval, maxval, disc_points)) pot_disc.append(pot_values(pot_disc[0])) return pot_disc
def interpolation(x, y, kind): """Make the interpolation function""" assert scipy is not None, ( 'You must have scipy installed to use interpolation') order = None if len(y) < len(x): x = x[:len(y)] x, y = zip(*filter(lambda t: None not in t, zip(x, y))) if len(x) < 2: return ident if isinstance(kind, int): order = kind elif kind in KINDS: order = { 'nearest': 0, 'zero': 0, 'slinear': 1, 'quadratic': 2, 'cubic': 3, 'univariate': 3 }[kind] if order and len(x) <= order: kind = len(x) - 1 if kind == 'krogh': return interpolate.KroghInterpolator(x, y) elif kind == 'barycentric': return interpolate.BarycentricInterpolator(x, y) elif kind == 'univariate': return interpolate.InterpolatedUnivariateSpline(x, y) return interpolate.interp1d(x, y, kind=kind, bounds_error=False)
def calc_frequency(freqs, raw_spectrum, verbose=False): """ :param freqs: array of frequency values, same size as spectrum :param raw_spectrum: array of intensity values, usually the output of a fourier transform. Must be same size as freqs Find the top frequency in the spectrum by interpolating the spectrum around the largest peak """ spectrum = np.abs(raw_spectrum) # find the location of the top frequency, but remove 0 as it's not relevant i = np.argmax(spectrum[1:-1]) + 1 # take di points either side of x. 3 points => can interpolate a quadratic di = 1 idxs = [i - j for j in range(di, 0, -1)] + [i] + [i + j + 1 for j in range(di)] xs = [freqs[i] for i in idxs] ys = [spectrum[i] for i in idxs] if verbose: print('indices %s' % idxs) print('frequencies %s' % xs) print('spectrum %s' % ys) # interpolate poly = interpolate.BarycentricInterpolator(xs, ys) res = optimize.fmin(lambda x: -poly(x), freqs[i], disp=False) return abs(res[0])
def interpolation(x_axis, y_axis, x_value, model='chip', method=None, is_function=False): methods = [ 'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'previous', 'next' ] # print(type(x_value),type(min(x_axis))) models = [ 'akima', 'chip', 'interp1d', 'cubicspline', 'krogh', 'barycentric' ] # print('x_axis => ',x_axis) result = None f = None if model is None or model == 'interp1d': if method in methods: f = interpolate.interp1d(x_axis, y_axis, kind=method) else: f = interpolate.interp1d(x_axis, y_axis, kind='cubic') elif model in models: if model == 'akima': f = interpolate.Akima1DInterpolator(x_axis, y_axis) elif model == 'chip': f = interpolate.PchipInterpolator(x_axis, y_axis) elif model == 'cubicspline': f = interpolate.CubicSpline(x_axis, y_axis) elif model == 'krogh': f = interpolate.KroghInterpolator(x_axis, y_axis) elif model == 'barycentric': f = interpolate.BarycentricInterpolator(x_axis, y_axis) else: f = interpolate.PchipInterpolator(x_axis, y_axis) if is_function == True: return f else: if not isinstance(x_value, list): # if x_value <min(x_axis) or x_value >max(x_axis): # raise Exception('interpolation error: value requested is outside of range') # return result try: result = float(f(x_value)) except: return result else: result = list(map(lambda x: float(f(x)), x_value)) return result
def _interpolation(minmax, ipoints, iptype): """Interpolates the potential from sample points and saves it to document Args: minmax: minimum and maximum x value and number of steps ipoints: sample points as array iptype: type of interpolation Returns: potwithx: array of xvalues and interpolated potential """ # Extracting x and y values from the input file sample points # saved in ipoints for the interpolation xx = ipoints[:, 0] yy = ipoints[:, 1] # Setting up the intervall for the interpolated potential xnew = np.linspace(int(minmax[0]), int(minmax[1]), int(minmax[2])) # Depending on the type of interpolation given by the user # creating the interpolation function and defining the potential if iptype == 'linear': fl = spip.interp1d(xx, yy, kind='linear') pot = fl(xnew) elif iptype == 'cspline': if np.shape(xx)[0] < 4: # For less than four points cubic interpolation isn't possible. fl = spip.interp1d(xx, yy, kind='linear') print('Not enough points for cubic interpolation.' ' ''Interpolation type changed to linear.') pot = fl(xnew) else: fc = spip.interp1d(xx, yy, kind='cubic') pot = fc(xnew) elif iptype == 'polynomial': fbar = spip.BarycentricInterpolator(xx, yy) pot = fbar(xnew) else: print('Invalid interpolation type.') # Transposing row vectors and stacking them to a matrice xnew_t = np.reshape(xnew, (int(minmax[2]), 1)) pot_t = np.reshape(pot, (int(minmax[2]), 1)) potwithx = np.hstack((xnew_t, pot_t)) # potwithx fulfills the saving file requirements return potwithx
def _interpolating(basedata, path): """ Interpolates the given potentialpoints while considering the given plotsize and the given number of potentialpoints args: basedata (array): contains the values to interpolate the potential path (string): is the directory where the potential.dat will be saved """ # defining constants plotsize1 = int(basedata[1]) plotsize2 = int(basedata[2]) plotsize3 = int(basedata[3]) potp = basedata[8:] interpol = basedata[6] xnew = np.linspace(plotsize1, plotsize2, num=plotsize3) # interpolation for each type if interpol == "polynomial": xx = potp[::2] yy = potp[1::2] pot = interpolate.BarycentricInterpolator(xx, yy) ynew = pot(xnew) elif interpol == "linear": xx = potp[::2] yy = potp[1::2] pot = interpolate.interp1d(xx, yy) ynew = pot(xnew) elif interpol == "cspline": xx = potp[::2] yy = potp[1::2] pot = interpolate.CubicSpline(xx, yy, bc_type='natural') ynew = pot(xnew) # saving results in files potnew = np.array([xnew[0], ynew[0]]) for i in range(1, len(xnew)): potnew = np.vstack((potnew, np.array([xnew[i], ynew[i]]))) np.savetxt(os.path.join(path, "potential.dat"), potnew)
import matplotlib.pyplot as plt from scipy import interpolate, linspace def cauchy(x): return (1 + x**2)**-1 n = 16 x = linspace(-5, 5, n) y = cauchy(x) f = interpolate.BarycentricInterpolator(x, y) newx = linspace(-5, 5, 200) newy = f(newx) plt.plot(x, y, 'o', newx, newy, '-') plt.show()
}, { 'name': 'data max', 'L': '#3F871B', 'M': '#493F9E', 'H': '#AF2020' }, { 'name': 'data cv', 'L': '#87D77B', 'M': '#847BD7', 'H': '##914C4C' }] nomi = [' data_mean', ' data_max', ' data_cv'] for data in [data_mean, data_max]: #,data_cv]: nome = nomi[k] colore = colori[k] for prova in N_prove: for livello in ['L', 'M', 'H']: data[data['force'] == livello].plot.scatter(x='fr', y='rapporto', c=colore[livello], ax=ax_0, label=livello + ' ' + colore['name'] + nome) f_temp = np.array(data[data['force'] == livello].groupby('fr') ['rapporto'].mean()).flatten() ax_0.plot(ff, interpolate.BarycentricInterpolator(f, f_temp)(ff), c=colore[livello]) k = +1 plt.show()
plt.plot(X, Y, 'r', label='Función') plt.plot(X, Z, 'b', label='Lagrange Interpolate') plt.plot(X, Z2, 'y', label='Interpolación paso a paso') plt.legend() plt.title('Interpolación genérica', fontsize=20) plt.xlabel('x') plt.ylabel('y') plt.show() '''EJERCICIO 2 Dada la función f (x) = x4−2x+1, obtener y representar la función y el polinomio de interpolación cuando se utilizan 7 puntos de interpolación esquiespaciados en el intervalo [−5,5].''' x = N.linspace(-5, 5, 7) y = x**4 - 2 * x + 1 poly = si.BarycentricInterpolator( x, y) #la función de interpolacion es la propia función #porque al tener 7 puntos de intepolacion el polin de interp. es de grado 6 o menor, #siendo la propia función. APROXIMACIÓN PERFECTA. X = N.linspace(x[0], x[-1]) # representación Y = X**4 - 2 * X + 1 # funcion Z = poly(X) fig = plt.figure(2) plt.plot(x, y, 'ro', X, Y) plt.plot(X, Z) plt.legend(('Datos', 'Interpolante Baricentro', 'función')) plt.title('Interpolación genérica', fontsize=20) plt.xlabel('x') plt.ylabel('y') plt.show()
# 最近傍点による補間 f6 = interpolate.interp1d(t, y, kind="nearest") y6 = f6(tt) # 秋間法による補間 f7 = interpolate.Akima1DInterpolator(t, y) y7 = f7(tt) # 区分的 3 次エルミート補間 # y8 = interpolate.pchip_interpolate(t, y, tt)でも結果は同じ f8 = interpolate.PchipInterpolator(t, y) y8 = f8(tt) # 重心補間 # y9 = interpolate.barycentric_interpolate(t, y, tt)でも結果は同じ f9 = interpolate.BarycentricInterpolator(t, y) y9 = f9(tt) # Krogh により提案された補間法 # y10 = interpolate.Krogh_interpolate(t, y, tt)でも結果は同じ f10 = interpolate.KroghInterpolator(t, y) y10 = f10(tt) plt.figure(figsize=(12, 9)) plt.plot(t, y, "o") plt.plot(tt, y1, "r", label="linear") plt.plot(tt, y2, "b", label="quadratic") plt.plot(tt, y3, "g", label="cubic") plt.plot(tt, y4, "y", label="slinear") plt.plot(tt, y5, "m", label="zero") plt.plot(tt, y6, "c", label="nearest")
def interpolation(x, y, x_new, model="InterpolatedUnivariateSpline", plot=False, title=""): """Determination of interpolated data and its derivation by choosing a interpolation method Args: x (numpy.ndarray) - 1-dimensional array with original x-values (e.g. time entries in [s]). y (numpy.ndarray) - 2-dimensional array with original y-values (e.g. orbit position vectors). x_new (numpy.ndarray) - 1-dimensional array with x-values (e.g. time entries in [s]), for which interpolation should be done. model (str) - Interpolation model, which can be:t InterpolatedUnivariateSpline interp1d lagrange (limited to around 20 data points) window_size (int) - size of moving window, which defines number of datapoints before and after the interpolation entry plot (bool) - Flag (True|False) for plotting original data against interpolated ones. title (str) - Title of plot. Returns: tuple: with following entries ==================== ================= ========================================================================== Entry Type Description ==================== ================= ========================================================================== y_new numpy.ndarray 2-dimensional array with interpolated y-values (e.g. orbit position vectors). y_new_derivate numpy.ndarray 2-dimensional array with time derivate of y-values (e.g. orbit position vectors). ==================== ================= ========================================================================== """ num_col = y.shape[1] if isinstance(x_new, float): num_row = 1 else: num_row = len(x_new) y_new = np.zeros((num_row, num_col)) y_new_dot = np.zeros((num_row, num_col)) if model == "InterpolatedUnivariateSpline": for idx in range(0, num_col): # TODO: InterpolatedUnivariateSpline seems to have problems with multidimensional arrays interpolate_ = interpolate.InterpolatedUnivariateSpline(x, y[:, idx], k=3) y_new[:, idx] = interpolate_(x_new) # y_new_dot[:,idx] = spline.derivative()(x_new) #TODO: Does this work too? y_new_dot[:, idx] = _determine_time_derivate(interpolate_, x_new, 1) if plot == True: _plot_interpolation(x, y, x_new, y_new, title=title) elif model == "interp1d": # TODO: Extrapolation has to be handled (e.g. with fill_value=(0.0,0.0) argument) interpolate_ = interpolate.interp1d(x, y, kind="cubic", axis=0, bounds_error=False) y_new = interpolate_(x_new) y_new_dot = _determine_time_derivate(interpolate_, x_new, num_col) if plot == True: _plot_interpolation(x, y, x_new, y_new, title=title) elif model == "lagrange": for idx in range(0, num_col): # Rescaling of data necessary, because Lagrange interpolation is numerical unstable xm = np.mean(x) ym = np.mean(y[:, idx]) xs = np.std(x) ys = np.std(y[:, idx]) xscaled = (x - xm) / xs yscaled = (y[:, idx] - ym) / ys # interpolate_ = interpolate.lagrange(xscaled, yscaled) # worst performance # interpolate_ = _lagrange2(xscaled, yscaled) # improved performance interpolate_ = _lagrange(xscaled, yscaled) # fastest performance y_new[:, idx] = interpolate_((x_new - xm) / xs) * ys + ym # Determine derivate of 'y_new' t_offset = 0.5 y1 = interpolate_((x_new - t_offset - xm) / xs) * ys + ym y2 = interpolate_((x_new + t_offset - xm) / xs) * ys + ym y_new_dot[:, idx] = (y2 - y1) / (t_offset * 2) if plot == True: _plot_interpolation(x, y, x_new, y_new, title=title) elif model == "BarycentricInterpolator": for idx in range(0, num_col): # TODO: Is the rescaling of data necessary here? xm = np.mean(x) ym = np.mean(y[:, idx]) xs = np.std(x) ys = np.std(y[:, idx]) xscaled = (x - xm) / xs yscaled = (y[:, idx] - ym) / ys interpolate_ = interpolate.BarycentricInterpolator(xscaled, yscaled) y_new[:, idx] = interpolate_((x_new - xm) / xs) * ys + ym # Determine derivate of 'y_new' t_offset = 0.5 y1 = interpolate_((x_new - t_offset - xm) / xs) * ys + ym y2 = interpolate_((x_new + t_offset - xm) / xs) * ys + ym y_new_dot[:, idx] = (y2 - y1) / (t_offset * 2) if plot == True: _plot_interpolation(x, y, x_new, y_new, title=title) # elif model == 'polyfit': # #y_new_dot = np.zeros((len(x_new), num_col)) # degree = 2 # poly_dot_coeff = np.zeros((degree, num_col)) # # #TODO: Polynomial fit over the complete time period of 3 days are not convenient. # # Difference of up to 1000 km between original SP3 orbit data and polynomial # # fit. # x_ref = np.amin(x) #TODO: orb_ref_time should be part of 'orb' Dataset # x = (x - x_ref) * 86400 # poly_coeff = poly.polyfit(x, y, degree) # y_new = poly.polyval(x_new,poly_coeff) # for idx in range(0,num_col): # poly_dot_coeff[:,idx] = np.polyder(poly_coeff[:,idx]) # polynomial_dot = np.poly1d(poly_dot_coeff[:,idx]) # y_new_dot[:,idx] = polynomial_dot((x_new - x_ref) * 86400) # if plot == True: # _plot_orbit_polynomial(sat, poly_coeff, x, y) return y_new, y_new_dot
data = consec_sensor.sort_index().reset_index() if len(data) < 10: continue # print(len(data)) freq = '15T' xn = pd.date_range( min(data['result_time']).ceil(freq), max(data['result_time']).floor(freq), freq=freq) xn = xn.view('int64') // pd.Timedelta(1, unit='s') data['result_time'] = data['result_time'].view( 'int64') // pd.Timedelta( 1, unit='s') data = data.as_matrix() f = interpolate.BarycentricInterpolator(data[:, 0], data[:, 1]) yn = f(xn) interp_ser = pd.Series( yn, index=pd.to_datetime(xn * pd.Timedelta(1, unit='s')), name=(node_id, depth)) no_batt_tail_ser, bad_start, bad_end = remove_batt_tails( interp_ser) if bad_end != bad_start: old_df_chopped.loc[(old_df_chopped['node_id'] == node_id) & ( old_df_chopped.index < bad_end) & ( old_df_chopped.index > bad_start), depth] = np.nan no_spike_ser, spike_start_end_tups = squash_spikes( no_batt_tail_ser) if len(spike_start_end_tups) != 0: for (start, end) in spike_start_end_tups: old_df_chopped.loc[(old_df_chopped['node_id'] == node_id) &
f = interpolate.interp1d(t0, x0, kind="nearest") x1 = f(t1) elif n == 5: # 3d Hermite interpolate sys.stderr.write('N = 5: 3d Hermite-interpolation\n') f = interpolate.PchipInterpolator(t0, x0) x1 = f(t1) elif n == 6: # Akima interpolate sys.stderr.write('N = 6: Akima-interpolation\n') f = interpolate.Akima1DInterpolator(t0, x0) x1 = f(t1) elif n == 7: # Barycentric interpolate sys.stderr.write('N = 7: Barycentric-interpolation\n') f = interpolate.BarycentricInterpolator(t0, x0) x1 = f(t1) elif n == 8: # Krogh interpolate sys.stderr.write('N = 8: Krogh-interpolation\n') f = interpolate.KroghInterpolator(t0, x0) x1 = f(t1) elif n == 9: # lagrange interpolate sys.stderr.write('N = 9: Lagrange-interpolation\n') f = interpolate.lagrange(t0, x0) x1 = f(t1) else: sys.stderr.write('! Argument N is not defined\n') sys.exit()
def interpolate_catalog_sb(cat, bandname='r', radtype='eff', sbname='sbeff_r', radname='rad_sb', loopfunc=lambda x: x): """ Takes a DECaLS tractor catalog and adds r-band half-light surface brightness to it. ``radtype`` can be "eff" for model-determined reff, or a angle-unit quantity for a fixed aperture SB For details/tests that this function works, see the "DECALS low-SB_completeness figures" notebook. """ bandidx = decam_band_name_to_idx[bandname] if 'decam_apflux' in cat.colnames: r_ap_fluxes = cat['decam_apflux'][:, bandidx, :] elif 'apflux_' + bandname in cat.colnames: r_ap_fluxes = cat['apflux_' + bandname] else: raise ValueError( 'found no valid {}-band apflux column!'.format(bandname)) assert r_ap_fluxes.shape[-1] == 8, 'Column does not have 8 apertures' expflux_r = np.empty_like(r_ap_fluxes[:, 0]) rad = np.empty(len(r_ap_fluxes[:, 0])) ap_sizesv = DECALS_AP_SIZES.to(u.arcsec).value intr = interpolate.BarycentricInterpolator(ap_sizesv, [0] * len(ap_sizesv)) if loopfunc == 'ProgressBar': from astropy.utils.console import ProgressBar loopfunc = lambda x: ProgressBar(x) elif loopfunc == 'NBProgressBar': from astropy.utils.console import ProgressBar loopfunc = lambda x: ProgressBar(x, ipython_widget=True) elif loopfunc == 'tqdm': import tqdm loopfunc = lambda x: tqdm.tqdm(x) elif loopfunc == 'tqdm_notebook': import tqdm loopfunc = lambda x: tqdm.tqdm_notebook(x) for i in loopfunc(range(len(r_ap_fluxes))): f = r_ap_fluxes[i] if radtype != 'eff': r = radtype elif cat['type'][i] == 'PSF ': if 'decam_psfsize' in cat.colnames: r = cat['decam_psfsize'][i, bandidx] else: r = cat['psfsize_' + bandname][i] elif cat['type'][i] == 'DEV ': if 'shapeDev_r' in cat.colnames: r = cat['shapeDev_r'][i] else: # DR4 changed to all lower-case... WWHHHHYYY!!?!?!??!?!?!?!? r = cat['shapedev_r'][i] else: if 'shapeExp_r' in cat.colnames: r = cat['shapeExp_r'][i] else: # DR4 changed to all lower-case... WWHHHHYYY!!?!?!??!?!?!?!? r = cat['shapeexp_r'][i] intr.set_yi(f) expflux_r[i] = intr(r) rad[i] = r cat[sbname] = compute_sb(rad * u.arcsec, np.array(expflux_r)) cat[radname] = rad * u.arcsec