本文整理汇总了Python中scipy.interpolate.UnivariateSpline.derivative方法的典型用法代码示例。如果您正苦于以下问题:Python UnivariateSpline.derivative方法的具体用法?Python UnivariateSpline.derivative怎么用?Python UnivariateSpline.derivative使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.interpolate.UnivariateSpline
的用法示例。
在下文中一共展示了UnivariateSpline.derivative方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getCurvatureForPoints
# 需要导入模块: from scipy.interpolate import UnivariateSpline [as 别名]
# 或者: from scipy.interpolate.UnivariateSpline import derivative [as 别名]
def getCurvatureForPoints(arcLengthList, fx_s, fy_s, smoothing=None):
x, x_, x__, y, y_, y__ = getFirstAndSecondDerivForTPoints(arcLengthList, fx_s, fy_s)
curvature = abs(x_* y__ - y_* x__) / np.power(x_** 2 + y_** 2, 3 / 2)
fCurvature = UnivariateSpline(arcLengthList, curvature, s=smoothing)
dxcurvature = fCurvature.derivative(1)(arcLengthList)
dx2curvature = fCurvature.derivative(2)(arcLengthList)
return curvature, dxcurvature, dx2curvature
示例2: AlphaInterpolator
# 需要导入模块: from scipy.interpolate import UnivariateSpline [as 别名]
# 或者: from scipy.interpolate.UnivariateSpline import derivative [as 别名]
class AlphaInterpolator(object):
def __init__(self, a, x, y):
# Drop NaN values to avoid fitpack errors
self._data = pd.DataFrame(np.array([a, x, y]).T, columns=["a", "x", "y"])
self._data.dropna(inplace=True)
self._create_interpolating_polynomials()
self._find_path_length()
def _create_interpolating_polynomials(self):
self.x_interp = UnivariateSpline(self._data.a, self._data.x, s=0)
self.y_interp = UnivariateSpline(self._data.a, self._data.y, s=0)
def _find_path_length(self):
dx_interp = self.x_interp.derivative()
dy_interp = self.y_interp.derivative()
ts = np.linspace(0, 1, 200)
line_length = cumtrapz(np.sqrt(dx_interp(ts) ** 2 + dy_interp(ts) ** 2), x=ts, initial=0.0)
line_length /= line_length.max()
# Here we invert the line_length (ts) function, in order to evenly
# sample the pareto front
self.l_interp = UnivariateSpline(line_length, ts, s=0)
def sample(self, num):
""" Return estimates of alpha values that evenly sample the pareto
front """
out = self.l_interp(np.linspace(0, 1, num))
out[0] = 0.0
out[-1] = 1.0
return out
示例3: smoothing
# 需要导入模块: from scipy.interpolate import UnivariateSpline [as 别名]
# 或者: from scipy.interpolate.UnivariateSpline import derivative [as 别名]
def smoothing(x,y,err=None,k=5,s=None,newx=None,derivative_order=0):
# remove NaNs
idx = np.isfinite(x) & np.isfinite(y)
if idx.sum() != len(x): x=x[idx]; y=y[idx]
# if we don't need to interpolate, use same x as input
if newx is None: newx=x
if err is None:
w=None
elif err == "auto":
n=len(x)
imin = int(max(0,n/2-20))
imax = imin + 20
idx = range(imin,imax)
p = np.polyfit(x[idx],y[idx],2)
e = np.std( y[idx] - np.polyval(p,x[idx] ) )
w = np.ones_like(x)/e
else:
w=np.ones_like(x)/err
from scipy.interpolate import UnivariateSpline
if (s is not None):
s = len(x)*s
s = UnivariateSpline(x, y,w=w, k=k,s=s)
if (derivative_order==0):
return s(newx)
else:
try:
len(derivative_order)
return np.asarray([s.derivative(d)(newx) for d in derivative_order])
except:
return s.derivative(derivative_order)(newx)
示例4: curvature_spline
# 需要导入模块: from scipy.interpolate import UnivariateSpline [as 别名]
# 或者: from scipy.interpolate.UnivariateSpline import derivative [as 别名]
def curvature_spline(x, y):
"""
this function gets the curvature of the road.
"""
t = numpy.arange(x.shape[0])
fx = UnivariateSpline(t, x, k=4)
fy = UnivariateSpline(t, y, k=4)
xDer = fx.derivative(1)(t)
xDerDer = fx.derivative(2)(t)
yDer = fy.derivative(1)(t)
yDerDer = fy.derivative(2)(t)
curvature = (xDer * yDerDer - yDer * xDerDer) / numpy.power(xDer ** 2 + yDer ** 2, 3/2)
return curvature
示例5: softening_scale
# 需要导入模块: from scipy.interpolate import UnivariateSpline [as 别名]
# 或者: from scipy.interpolate.UnivariateSpline import derivative [as 别名]
def softening_scale(self,mq=70,auto=True,r=None,dens=None,mass=None,kernel='Gadget'):
opt_dict={'Gadget':0.698352, 'spline':0.977693}
rq=self.qmass(mq)
if auto==True:
prof=Profile(self.p,Ngrid=512,xmin=0.001*rq,xmax=10*rq,kind='lin')
r=prof.grid.gx
dens=prof.dens
dens_spline=UnivariateSpline(r, dens, k=1,s=0,ext=1)
der_dens=dens_spline.derivative()
derdens=der_dens(r)
ap=UnivariateSpline(r, r*r*dens*derdens*derdens, k=1,s=0,ext=1)
bp=UnivariateSpline(r, r*r*dens*dens, k=1,s=0,ext=1)
B=bp.integral(0,rq)
A=ap.integral(0,rq)/(mass*mq/100.)
C=(B/(A))**(1/5)
cost=opt_dict[kernel]
N=len(self.p.Id)**(1/5)
return C*cost/N
示例6: get_derivatives
# 需要导入模块: from scipy.interpolate import UnivariateSpline [as 别名]
# 或者: from scipy.interpolate.UnivariateSpline import derivative [as 别名]
def get_derivatives(xs, ys, fd=False):
"""
return the derivatives of y(x) at the points x
if scipy is available a spline is generated to calculate the derivatives
if scipy is not available the left and right slopes are calculated, if both exist the average is returned
putting fd to zero always returns the finite difference slopes
"""
try:
if fd:
raise SplineInputError('no spline wanted')
if len(xs) < 4:
er = SplineInputError('too few data points')
raise er
from scipy.interpolate import UnivariateSpline
spline = UnivariateSpline(xs, ys)
d = spline.derivative(1)(xs)
except (ImportError, SplineInputError):
d = []
m, left, right = 0, 0, 0
for n in range(0, len(xs), 1):
try:
left = (ys[n] - ys[n-1]) / (xs[n] - xs[n-1])
m += 1
except IndexError:
pass
try:
right = (ys[n+1] - ys[n]) / (xs[n+1] - xs[n])
m += 1
except IndexError:
pass
d.append(left + right / m)
return d
示例7: response
# 需要导入模块: from scipy.interpolate import UnivariateSpline [as 别名]
# 或者: from scipy.interpolate.UnivariateSpline import derivative [as 别名]
def response(self, disturbance_vector):
""" Returns the response of the sensor due to a disturbance
The acceleration imposed to the sensor is estimatad with the following equations:
acceleration(t) = d2stress(t)/t2 * material_depth/material_prop['modulus']
And the sensor response takes into account the frequency response, estimated by a normal curve
freq_response(f) = norm(scale = self.bandwidth/2, loc=self.resonant_freq).pdf(f_array)
freq_response(f) /= max(freq_response)
response(t) = ifft(fft(acceleration) * freq_response)
Args:
disturbance_vector (list): list with a temporal array, in the 0 index, and a
stress array, in the 1 index.
Returns:
list: with two arrays, the temporal array and the voltage response array.
"""
const = self.material_depth / self.material_prop['modulus']
t_vector = disturbance_vector[0]
# using the scipy UnivariateSpline to compute the second derivative
data_spl = UnivariateSpline(t_vector, disturbance_vector[1], s=0, k=3)
acceleration = data_spl.derivative(n=2)(t_vector) * const
# we need to take the frequency response of the acceleration stimuli
N = len(disturbance_vector[1])
T = t_vector[1] - t_vector[0]
f_array = np.fft.fftfreq(N, T)
freq_acc = np.fft.fft(acceleration)
# we need to apply a filter factor related to the frequency response of the sensor
freq_response = self.frequency_response(N, (0, max(f_array)), mirror=True)[1]
voltage = np.fft.ifft(freq_acc * freq_response) * self.sensitivity
return voltage
示例8: find_extrema_spline
# 需要导入模块: from scipy.interpolate import UnivariateSpline [as 别名]
# 或者: from scipy.interpolate.UnivariateSpline import derivative [as 别名]
def find_extrema_spline(x,y,k=4,s=0,**kwargs):
"""
find local extrema of y(x) by taking derivative of spline
Parameters
----------
x,y : array-like
find extrema of y(x)
k : int
order of spline interpolation [must be >3]
s : number
s parameter sent to scipy spline interpolation (used for smoothing)
**kwargs : extra arguments to UnivariateSpline
Returns
-------
sp : UnivariateSpline object
x_max,y_max : array
value of x and y at extrema(s)
"""
sp = UVSpline(x,y,k=k,s=s,**kwargs)
x_max = sp.derivative().roots()
y_max = sp(x_max)
return sp,x_max,y_max
示例9: getspline_Sold
# 需要导入模块: from scipy.interpolate import UnivariateSpline [as 别名]
# 或者: from scipy.interpolate.UnivariateSpline import derivative [as 别名]
def getspline_Sold(self):
"""Cubic spline interpolation of entropy and convective velocity.
"""
want = self.mass < max(self.mass)*self.mass_cut
S_old = UnivariateSpline(self.mass[want], self.Sgas[want], k=self.spline_k, s=self.spline_s, ext=self.spline_ext)
dS_old = S_old.derivative()
vconv_Sold = UnivariateSpline(self.mass[want], self.vconv[want], k=self.spline_k, s=self.spline_s, ext=self.spline_ext)
return [S_old, dS_old, vconv_Sold]
示例10: adiabat_steeper
# 需要导入模块: from scipy.interpolate import UnivariateSpline [as 别名]
# 或者: from scipy.interpolate.UnivariateSpline import derivative [as 别名]
def adiabat_steeper(self):
'''
Checks whether the adiabat is steeper than the liquidus. Ultimately this
should be part of determining the adiabat in the snow regime.
'''
p_oc = self.pressure[self.outer_core()]
t_oc = self.temperature[self.outer_core()]
t_func = UnivariateSpline(p_oc,t_oc)
return t_func.derivative()(p_oc) > self.liquidus.derivative()(p_oc)
示例11: find_ending_point
# 需要导入模块: from scipy.interpolate import UnivariateSpline [as 别名]
# 或者: from scipy.interpolate.UnivariateSpline import derivative [as 别名]
def find_ending_point(X, y, start_point, use_alternative = False):
"""
================
INPUT: array of X data (temperature), array of Y data (heat flow), int
OUTPUT: int
================
Finds the end point of the reaction to estimate enthalpy.
- NOTE: use_alternative: this variable decides which "end point finder" you
want to use. if you want to take the post-peak max point, select True. If
you want to use the end-point derived from the second derivative, select
False.
In order, this function:
1. Isolates data after the peak
2. Approximates the data with a spline.
3. Finds the point where the first derivative is closest to zero and nearest
to the end of the reaction. This is the end point.
## note, you could also set the end point to be when the function
## has returned closest to the gradient at the start_point
4. If this point is < post-peak max point, choose the maximum point.
"""
start_point = 1405
reaction_x = X[start_point:] # x's after the start_point
reaction_y = y[start_point:] # y's after the start_point
index_of_peak = start_point + reaction_y.argmin()
if use_alternative:
end_point_id = index_of_peak + y[index_of_peak : ].argmax()
else:
pp_X, pp_y = X[index_of_peak: ], y[index_of_peak: ]
spline = UnivariateSpline(pp_X, pp_y, k = 5)
second_derivative = spline.derivative(2)(pp_X)
relevant_end_points = np.abs(second_derivative)
end_point = np.max(relevant_end_points.argsort()[:50]) # get the largest of all the zero points
end_point_id = index_of_peak + end_point
# just in case there are larger points between peak & end point
if np.max(y[index_of_peak : end_point_id]) > y[end_point_id]:
index = y[index_of_peak : end_point_id].argmax()
end_point_id = index_of_peak + index
return end_point_id
示例12: get_splines
# 需要导入模块: from scipy.interpolate import UnivariateSpline [as 别名]
# 或者: from scipy.interpolate.UnivariateSpline import derivative [as 别名]
def get_splines(self, floor=25 * 1e-9, ceil=25 * 1e-6):
from scipy.interpolate import UnivariateSpline
mx, my = zip(*self.scatter_data)
yy, xx = zip(*lmseq(zip(my, mx))) # filter with LMS
spl = UnivariateSpline(xx, yy)
spld = spl.derivative()
def spl_derivative(x):
s = abs(spld(x))
s[s < floor] = floor
s[s > ceil] = ceil
return s
self.spl = spl
self.spld = spl_derivative
示例13: softening_scale
# 需要导入模块: from scipy.interpolate import UnivariateSpline [as 别名]
# 或者: from scipy.interpolate.UnivariateSpline import derivative [as 别名]
def softening_scale(self,mq=70,auto=True,r=None,dens=None,mass=None,kernel='Gadget',type=None):
"""
Calculate the optimal softening scale following Dehnen, 2012 eps=cost*a(dens)*N^-0.2. The output will be in unit
of r. If Auto==True, r and dens will be not considered.
:param mq: Mass fraction where calcualte the softening_scale.
:param auto: If True calculate the r-dens gride using the grid and Profile class
wit 512 points from 0.001*rq to 10*rq.
:param r: Array with the sampling radii.
:param dens: Array with the density at the sampling radii. Its unity need to be the same of mass/r^3
:param mass: Total mass of the system, the method will calculate in automatic the fraction mq/100*mass
:param kernel: Kernel to use. Different kernel have different constant C. The implemented kernels are:
-spline: generic cubic spline (as in Dehnen, 2012)
-Gadget: to calculate the softening_scale using the spline kernel of Gadget2
:return: the softening scale.
"""
opt_dict={'Gadget':0.698352, 'spline':0.977693}
rq=self.qmass(mq,type=type)
if auto==True:
prof=Profile(self.p,Ngrid=512,xmin=0.01*rq,xmax=10*rq,kind='lin',type=type)
r=prof.grid.gx
dens=prof.dens
dens_spline=UnivariateSpline(r, dens, k=1,s=0,ext=1)
der_dens=dens_spline.derivative()
derdens=der_dens(r)
ap=UnivariateSpline(r, r*r*dens*derdens*derdens, k=1,s=0,ext=1)
bp=UnivariateSpline(r, r*r*dens*dens, k=1,s=0,ext=1)
B=bp.integral(0,rq)
A=ap.integral(0,rq)/(mass*mq/100.)
C=(B/(A))**(1/5)
cost=opt_dict[kernel]
N=len(self.p.Id)**(1/5)
return C*cost/N
示例14: get_parameter_limits
# 需要导入模块: from scipy.interpolate import UnivariateSpline [as 别名]
# 或者: from scipy.interpolate.UnivariateSpline import derivative [as 别名]
def get_parameter_limits(xval, loglike, cl_limit=0.95, cl_err=0.68269, tol=1E-2,
bounds=None):
"""Compute upper/lower limits, peak position, and 1-sigma errors
from a 1-D likelihood function. This function uses the
delta-loglikelihood method to evaluate parameter limits by
searching for the point at which the change in the log-likelihood
value with respect to the maximum equals a specific value. A
cubic spline fit to the log-likelihood values is used to
improve the accuracy of the calculation.
Parameters
----------
xval : `~numpy.ndarray`
Array of parameter values.
loglike : `~numpy.ndarray`
Array of log-likelihood values.
cl_limit : float
Confidence level to use for limit calculation.
cl_err : float
Confidence level to use for two-sided confidence interval
calculation.
tol : float
Absolute precision of likelihood values.
Returns
-------
x0 : float
Coordinate at maximum of likelihood function.
err_lo : float
Lower error for two-sided confidence interval with CL
``cl_err``. Corresponds to point (x < x0) at which the
log-likelihood falls by a given value with respect to the
maximum (0.5 for 1 sigma). Set to nan if the change in the
log-likelihood function at the lower bound of the ``xval``
input array is less than than the value for the given CL.
err_hi : float
Upper error for two-sided confidence interval with CL
``cl_err``. Corresponds to point (x > x0) at which the
log-likelihood falls by a given value with respect to the
maximum (0.5 for 1 sigma). Set to nan if the change in the
log-likelihood function at the upper bound of the ``xval``
input array is less than the value for the given CL.
err : float
Symmetric 1-sigma error. Average of ``err_lo`` and ``err_hi``
if both are defined.
ll : float
Lower limit evaluated at confidence level ``cl_limit``.
ul : float
Upper limit evaluated at confidence level ``cl_limit``.
lnlmax : float
Log-likelihood value at ``x0``.
"""
dlnl_limit = onesided_cl_to_dlnl(cl_limit)
dlnl_err = twosided_cl_to_dlnl(cl_err)
try:
# Pad the likelihood function
# if len(xval) >= 3 and np.max(loglike) - loglike[-1] < 1.5*dlnl_limit:
# p = np.polyfit(xval[-3:], loglike[-3:], 2)
# x = np.linspace(xval[-1], 10 * xval[-1], 3)[1:]
# y = np.polyval(p, x)
# x = np.concatenate((xval, x))
# y = np.concatenate((loglike, y))
# else:
x, y = xval, loglike
spline = UnivariateSpline(x, y, k=2,
#k=min(len(xval) - 1, 3),
w=(1 / tol) * np.ones(len(x)))
except:
print("Failed to create spline: ", xval, loglike)
return {'x0': np.nan, 'ul': np.nan, 'll': np.nan,
'err_lo': np.nan, 'err_hi': np.nan, 'err': np.nan,
'lnlmax': np.nan}
sd = spline.derivative()
imax = np.argmax(loglike)
ilo = max(imax - 1, 0)
ihi = min(imax + 1, len(xval) - 1)
# Find the peak
x0 = xval[imax]
# Refine the peak position
if np.sign(sd(xval[ilo])) != np.sign(sd(xval[ihi])):
x0 = find_function_root(sd, xval[ilo], xval[ihi])
#.........这里部分代码省略.........
示例15: range
# 需要导入模块: from scipy.interpolate import UnivariateSpline [as 别名]
# 或者: from scipy.interpolate.UnivariateSpline import derivative [as 别名]
from scipy.interpolate import UnivariateSpline
from EOS import rho, cp
from const import *
from ext_data import opac
for i in range (0, z.size):
FconvArr[i] = Fconv(T[i], P[i], z[i])
FradArr[i] = Frad(T[i], P[i], z[i])
rhoArr[i] = rho(T[i], P[i], z[i])
cpArr[i] = cp(T[i], P[i])
opacArr[i] = opac(T[i],rhoArr[i])
F = FconvArr+FradArr
F_spline = UnivariateSpline(z, F, s=0)
dFdz = F_spline.derivative()
dFdz = dFdz(z)
#dFdz = np.diff(F)/h
#dFdz = np.append(dFdz, dFdz[dFdz.size-1])
# semi-implicitni metoda pro casovy prirustek
#d_main = np.empty(500)
#d_sub = np.zeros(500)
#d_sup = np.zeros(500)
#b = np.zeros(500)
#
#h = 25000 #grid spacing
#
#Bz0 = np.sqrt(8e-7*np.pi*(bcg.P[499]-P[499]))