def get_spline(self): tckx = interp.CubicHermiteSpline(self.ts, self.xs, self.vxs) tcky = interp.CubicHermiteSpline(self.ts, self.ys, self.vys) coeffx = {} coeffy = {} t = [] for i in range(len(self.ts) - 1): coeffx[i], coeffy[i] = [], [] t.append(np.linspace(self.ts[i], self.ts[i + 1], 50)) for order in tckx.c: for i in range(len(self.ts) - 1): coeffx[i].append(order[i]) for order in tcky.c: for i in range(len(self.ts) - 1): coeffy[i].append(order[i]) x, y = [], [] for seg in coeffx: x.append(coeffx[seg][0] * (t[seg] - self.ts[seg])**3 + coeffx[seg][1] * (t[seg] - self.ts[seg])**2 + coeffx[seg][2] * (t[seg] - self.ts[seg]) + coeffx[seg][3]) for seg in coeffy: y.append(coeffy[seg][0] * (t[seg] - self.ts[seg])**3 + coeffy[seg][1] * (t[seg] - self.ts[seg])**2 + coeffy[seg][2] * (t[seg] - self.ts[seg]) + coeffy[seg][3]) x_plot, y_plot = [], [] for i in range(len(t)): for j in range(len(t[i])): x_plot.append(x[i][j]) y_plot.append(y[i][j]) return (x_plot, y_plot)
def approximate(self): x_y_s = list(zip(self.racines, np.zeros(len(self.racines)))) + self.extrema x_y_s = np.array(sorted(x_y_s, key=lambda x: x[0])) xs = x_y_s[:, 0] ys = x_y_s[:, 1] dp = self.derivesPentes() self.spline = spi.CubicHermiteSpline(xs, ys, dp)
def getTargetStates(observation_epochs, target_id='Duende', observer_id='I11', ephemeris_dt='1h', frame='ecliptic'): """Produce sun-observer state vectors at observation epochs. Parameters: ----------- observation_epochs ... Numpy array of observation epochs [JD] target_id ... Horizons identifier target, e.g. 'Ceres' observer_id ... Horizons identifier observer, e.g. 'I11' ephemeris_dt ... Time step for ephemeris query. Typically 1h since the actual times will be interpolated later. frame ... coordinate frame (default 'ecliptic' or 'icrf') Returns: -------- target_positions ... Heliocentric target states at observation epochs in [au, au/day]. target_velocities External Function Requirements: ------------------------------- # Interpolation import scipy.interpolate as spi # time transform mjd2jd ... change modified Julian date to Julian date, timescale TDB) # NASA JPL HORIZONS API call wrapper targetStatesFromHorizons ... Wrapper function for JPL Horizons state query via astropy """ tmin = tr.mjd2jd(np.min(observation_epochs)) tmax = tr.mjd2jd(np.max(observation_epochs)) #Start and stop times of the survey tstart = 'JD' + str(tmin - 1.) tstop = 'JD' + str(tmax + 1.) epochs = np.unique(observation_epochs) [target_mjd, target_xyz, target_vxyz] = targetStatesFromHorizons(target_id, observer_id, tstart, tstop, ephemeris_dt) # Interpolate heliocentric observer positions to the actual observation epochs ir = spi.CubicHermiteSpline(target_mjd, target_xyz, target_vxyz, axis=1, extrapolate=None) target_positions = ir(observation_epochs).T # Interpolate heliocentric observer velocities to the actual observation epochs dirdt = ir.derivative(nu=1) target_velocities = dirdt(observation_epochs).T return target_positions, target_velocities
def per_spl(x, y): assert len(x) == len(y) == 3 y[-1] = y[0] # shortcut x, y = map(np.asarray, (x, y)) h = x[1:] - x[:-1] m = (y[1:] - y[:-1]) / h s = (m / h).sum() / (1. / h).sum() #s = ((m / h)/ (1. / h)/2).sum() print('NEW S : ', s) return ipt.CubicHermiteSpline(x, y, [s, s, s])
def __init__(self, curve: 'Curve', *, extrapolate: ty.Optional[ty.Union[bool, str]] = None): super().__init__(curve) self.spline = interp.CubicHermiteSpline(curve.t, curve.data, curve.frenet1, axis=0, extrapolate=extrapolate)
def getObserverInterpolant(tmin, tmax, origin='SSB', observer_location='I11', ephemeris_dt='1h', frame='ecliptic'): """Produce sun-observer state vectors at observation epochs. Parameters: ----------- tmin,tmax ... float, float, start and stop time for interpolant [MJD] origin ... str, origin of the coordinate system (e.g. 'Sun' or 'SSB' =Solar System Barycenter) observer_location ... str, Horizons identifyer of observer location, e.g. 'I11' ephemeris_dt ... float, Time step for ephemeris query. Typically 1h since the actual times will be interpolated later. frame ... str, Coordinate system reference frame: 'ecliptic' or 'ICRF' Returns: -------- ipos, ivel ... scipy interpolants [au], [au/day] Heliocentric observer positions and velocity interpolants as function of time [MJD]. External Function Requirements: ------------------------------- # Interpolation import scipy.interpolate as spi # time transform mjd2jd ... change modified Julian date to Julian date, timescale TDB) # NASA JPL HORIZONS API call wrapper observerStatesFromHorizons ... Wrapper function for JPL Horizons state query via astropy """ tminjd = tr.mjd2jd(tmin) tmaxjd = tr.mjd2jd(tmax) #Start and stop times of the survey tstart = 'JD' + str(tminjd - 1.) tstop = 'JD' + str(tmaxjd + 1.) try: # Get observer locations (caution: choose the right plane of reference and direction of the vectors!) # check query by copy/pasting the output of print(observer_sun.uri) into a webbrowser if there are problems. if (origin == 'SSB' or origin == '@0'): observer_origin = Horizons(id='Sun', location=observer_location, id_type='majorbody', epochs={ 'start': tstart, 'stop': tstop, 'step': ephemeris_dt }) origin_barycenter = Horizons(id='Sun', location='@0', id_type='majorbody', epochs={ 'start': tstart, 'stop': tstop, 'step': ephemeris_dt }) if (frame == 'ecliptic'): oo = observer_origin.vectors(refplane='ecliptic') ob = origin_barycenter.vectors(refplane='ecliptic') elif (frame == 'ICRF' or frame == 'J2000' or frame == 'earth' or frame == 'icrf'): oo = observer_origin.vectors(refplane='earth') ob = origin_barycenter.vectors(refplane='earth') else: raise Exception('Error: requested frame unknown.') observer_xyz = ( -1) * (np.array([oo['x'], oo['y'], oo['z']]).astype('float') + np.array([ob['x'], ob['y'], ob['z']]).astype('float')) observer_vxyz = (-1) * ( np.array([oo['vx'], oo['vy'], oo['vz']]).astype('float') + np.array([ob['vx'], ob['vy'], ob['vz']]).astype('float')) observer_jd = np.array(oo['datetime_jd']).astype('float') else: observer_origin = Horizons(id=origin, location=observer_location, id_type='majorbody', epochs={ 'start': tstart, 'stop': tstop, 'step': ephemeris_dt }) if (frame == 'ecliptic'): obs = observer_origin.vectors(refplane='ecliptic') elif (frame == 'ICRF' or frame == 'J2000' or frame == 'earth' or frame == 'icrf'): obs = observer_orignin.vectors(refplane='earth') else: raise Exception('Error: requested frame unknown.') #We need the sun-observer vector not the observer-sun vector observer_xyz = (-1) * np.array([obs['x'], obs['y'], obs['z'] ]).astype('float') observer_vxyz = (-1) * np.array([obs['vx'], obs['vy'], obs['vz'] ]).astype('float') observer_jd = np.array(obs['datetime_jd']).astype('float') except: print( "Error: potential online ephemeris query failure. Make sure internet connectivity is available." ) raise observer_mjd = tr.jd2mjd(observer_jd) # Interpolate heliocentric observer positions to the actual observation epochs ipos = spi.CubicHermiteSpline(observer_mjd, observer_xyz, observer_vxyz, axis=1, extrapolate=None) # Interpolate heliocentric observer velocities to the actual observation epochs ivel = spi.CubicSpline(observer_mjd, observer_vxyz, axis=1, extrapolate=None) return ipos, ivel
import numpy as np import sympy as sp import scipy.interpolate as spi import matplotlib.pyplot as plt #Ejercicio Splines #Jose Calderon - Santiago Fernandez - Mariana Galavis - German Velasco #Principales referencias durante el desarrollo del codigo: #https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html #https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.CubicHermiteSpline.html xn = np.array([0, 1, 2], float) y = np.array([10.5, 15.33, 5.789], float) dydx = np.array( [1, (y[1] - y[0]) / (xn[1] - xn[0]), (y[2] - y[1]) / (xn[2] - xn[1])], float) a = spi.CubicHermiteSpline(xn, y, dydx) arr = np.array([a.c[0, 0], a.c[1, 0], a.c[2, 0], a.c[3, 0]]) x = sp.Symbol('x') fun = arr[3] * x**0 + arr[2] * x**1 + arr[1] * x**2 + arr[0] * x**3 xnew = np.linspace(0, 2, 50) plt.plot(xnew, a(xnew), 'r--') plt.show() print("La funcion del MENOR grado tres que pasa por los puntos es f(x) = {}". format(fun))
import scipy.interpolate as interp import matplotlib.pyplot as plt import numpy as np x_points = np.array([0, 1, 2, 3]) y_points = np.array([12,14,22,39]) dydx_values = np.array([20, 5, 3, -20]) tck = interp.CubicHermiteSpline(x_points, y_points, dydx_values) deriv = tck.derivative() x = [] y = [] coeff = {} d_coeff = {} print(tck.c) for i in range(len(x_points) - 1): coeff[i] = [] d_coeff[i] = [] x.append(np.linspace(x_points[i], x_points[i + 1], 100)) for order in tck.c: for i in range(len(x_points) - 1): coeff[i].append(order[i]) for order in deriv.c: for i in range(len(x_points) - 1): d_coeff[i].append(order[i])