Here are the examples of the python api numpy.polyfit taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
163 Examples
3
Source : test_fitting.py
with GNU General Public License v3.0
from ad12
with GNU General Public License v3.0
from ad12
def test_joint_optimization(self):
x, y, a, b = _generate_affine((1000,), a=None, b=None, as_med_vol=False)
popt_expected = np.polyfit(x, y, deg=1)
popt, _ = polyfit(x, y, deg=1, num_workers=None)
assert np.allclose(popt.T, popt_expected)
assert np.allclose(popt[..., 0], a)
assert np.allclose(popt[..., 1], b)
def test_multiple_workers(self):
3
Source : test_utils.py
with Creative Commons Zero v1.0 Universal
from aim-uofa
with Creative Commons Zero v1.0 Universal
from aim-uofa
def recover_metric_depth(pred, gt):
if type(pred).__module__ == torch.__name__:
pred = pred.cpu().numpy()
if type(gt).__module__ == torch.__name__:
gt = gt.cpu().numpy()
gt = gt.squeeze()
pred = pred.squeeze()
mask = (gt > 1e-8) & (pred > 1e-8)
gt_mask = gt[mask]
pred_mask = pred[mask]
a, b = np.polyfit(pred_mask, gt_mask, deg=1)
pred_metric = a * pred + b
return pred_metric
3
Source : analysis.py
with MIT License
from amirhajibabaei
with MIT License
from amirhajibabaei
def get_slopes(x, y, yerr):
a = np.polyfit(x, y, 1)
b = np.polyfit(x, y-yerr, 1)
c = np.polyfit(x, y+yerr, 1)
return a[0], b[0], c[0]
def mean_squared_displacement(traj, start=0, stop=-1, step=1, origin=None, numbers=None):
3
Source : response.py
with GNU Affero General Public License v3.0
from andrewcooke
with GNU Affero General Public License v3.0
from andrewcooke
def calc_observed(measureds, performances):
# this is a bit tricky. we don't know the exact relationship between 'fitness' and how fast we are.
# all we know is that it should track changes in a useful manner.
# so there's some arbitrary transform, which could quite easily be different for different routes
# (no reason 'fitness' should numerically predict the speed on *all* routes, obviously).
# so we assume that there's an arbitrary linear transform (scaling and offset) from measured speed
# (or whatever 'performance' is) to 'fitness'.
# we could fit for the best transform as we fit for the period, but it's more efficient to calculate
# the 'best' transform for a given period. this is more efficient because it's equivalent to line fitting
# (that linear transform is y = ax + b). so we can call the (fast) line fitting routine in numpy.
return [Series(np.polyval(np.polyfit(performance, measured, 1), performance),
performance.index)
for measured, performance in zip(measureds, performances)]
def calc_residuals(models, observations, method='L1'):
3
Source : icdar.py
with Apache License 2.0
from Ascend
with Apache License 2.0
from Ascend
def fit_line(p1, p2):
# fit a line ax+by+c = 0
if p1[0] == p1[1]:
return [1., 0., -p1[0]]
else:
[k, b] = np.polyfit(p1, p2, deg=1)
return [k, -1., b]
def line_cross_point(line1, line2):
3
Source : Math.py
with MIT License
from B-C-WANG
with MIT License
from B-C-WANG
def ThreeTimesPolyFit(point_list):
'''
输入是一系列的点[(x1,y1),(x2,y2)]
'''
x = []
y = []
for i in point_list:
x.append(i[0])
y.append(i[1])
# 拟合结果参数是高次在前
c3, c2, c1, c0 = list(np.polyfit(x, y, 3))
return c3, c2, c1, c0
3
Source : stats.py
with GNU General Public License v3.0
from belligerentbeagle
with GNU General Public License v3.0
from belligerentbeagle
def calc_trend(data):
""" Compile trend data """
points = len(data)
if points < 10:
dummy = [None for i in range(points)]
return dummy
x_range = range(points)
fit = np.polyfit(x_range, data, 3)
poly = np.poly1d(fit)
trend = poly(x_range)
return trend
3
Source : events.py
with MIT License
from bluella
with MIT License
from bluella
def get_trend_events(volume, threshold=1.01, lookback=60):
'''event of slope being bigger than threshold
use afterwards as:
result_df = events.rolling(prolong_timeframe).apply(prolong)'''
slopes = volume.rolling(lookback).apply(lambda x: \
np.polyfit(volume.index, volume/volume[-1], 1)[0])
pos_ind = slopes >= threshold
neg_ind = slopes < = - threshold
events = volume * 0
events[pos_ind] = 1
events[neg_ind] = -1
return events
3
Source : regression.py
with MIT License
from buds-lab
with MIT License
from buds-lab
def fit_poly(self, grid, order):
"""Regression using numpy polyfit for higher-order trends."""
def reg_func(_x, _y):
return np.polyval(np.polyfit(_x, _y, order), grid)
x, y = self.x, self.y
yhat = reg_func(x, y)
if self.ci is None:
return yhat, None
yhat_boots = algo.bootstrap(x, y, func=reg_func,
n_boot=self.n_boot, units=self.units)
return yhat, yhat_boots
def fit_statsmodels(self, grid, model, **kwargs):
3
Source : test_regression.py
with MIT License
from buds-lab
with MIT License
from buds-lab
def test_residplot(self):
x, y = self.df.x, self.df.y
ax = lm.residplot(x, y)
resid = y - np.polyval(np.polyfit(x, y, 1), x)
x_plot, y_plot = ax.collections[0].get_offsets().T
npt.assert_array_equal(x, x_plot)
npt.assert_array_almost_equal(resid, y_plot)
@skipif(_no_statsmodels)
3
Source : test_stabilitystatic.py
with Apache License 2.0
from cfsengineering
with Apache License 2.0
from cfsengineering
def test_polyfit():
"""Test function 'np.polyfit'"""
fit = np.polyfit([-1, 1], [-1, 1], 1) # returns [a,b] of y=ax+b
intercept = -fit[1] / fit[0] # Cml = 0 for y = 0 hence cruise angle = -b/a
slope = fit[0]
assert intercept == approx(0.0)
assert slope == approx(1.0)
def test_trim_condition():
3
Source : lane_detection.py
with MIT License
from ChengZhongShen
with MIT License
from ChengZhongShen
def get_polynomial(leftx, lefty, rightx, righty, img_size):
left_fit = np.polyfit(lefty, leftx, 2)
right_fit = np.polyfit(righty, rightx, 2)
left_lane_fun = np.poly1d(left_fit)
right_lane_fun = np.poly1d(right_fit)
ploty = ploty = np.linspace(0, img_size[0]-1, img_size[0])
left_fitx = left_lane_fun(ploty)
right_fitx = right_lane_fun(ploty)
return left_fitx, right_fitx, ploty
def lane_sanity_check(left_fitx, right_fitx, ploty):
3
Source : __init__.py
with BSD 3-Clause "New" or "Revised" License
from cw-jang
with BSD 3-Clause "New" or "Revised" License
from cw-jang
def get_half_life(ts):
lagged_ts = ts.shift(1).fillna(method='ffill')
delta = ts - lagged_ts
beta = np.polyfit(lagged_ts.dropna(), delta.dropna(), 1)[0]
half_life = (-1 * np.log(2) / beta)
return half_life
def get_hurst_exponent(ts):
3
Source : __init__.py
with BSD 3-Clause "New" or "Revised" License
from cw-jang
with BSD 3-Clause "New" or "Revised" License
from cw-jang
def get_hurst_exponent(ts):
"""Returns the Hurst Exponent of the time series vector ts"""
# Create the range of lag values
lags = range(2, 100)
# Calculate the array of the variances of the lagged differences
# Here it calculates the variances, but why it uses
# standard deviation and then make a root of it?
tau = [sqrt(std(subtract(ts[lag:], ts[:-lag]))) for lag in lags]
# Use a linear fit to estimate the Hurst Exponent
poly = polyfit(log(lags), log(tau), 1)
# Return the Hurst exponent from the polyfit output
return poly[0]*2.0
3
Source : test_onedspec.py
with BSD 3-Clause "New" or "Revised" License
from cylammarco
with BSD 3-Clause "New" or "Revised" License
from cylammarco
def test_add_trace_science_fail_type():
onedspec = spectral_reduction.OneDSpec(log_file_name=None)
onedspec.add_trace(np.polyfit, np.ndarray, stype="science")
# standard add_trace
def test_add_trace_standard():
3
Source : test_onedspec.py
with BSD 3-Clause "New" or "Revised" License
from cylammarco
with BSD 3-Clause "New" or "Revised" License
from cylammarco
def test_add_trace_standard_fail_type():
onedspec = spectral_reduction.OneDSpec(log_file_name=None)
onedspec.add_trace(np.polyfit, np.ndarray, stype="standard")
# science add_fit_coeff
def test_add_fit_coeff_science():
3
Source : test_onedspec.py
with BSD 3-Clause "New" or "Revised" License
from cylammarco
with BSD 3-Clause "New" or "Revised" License
from cylammarco
def test_extinction_function():
onedspec = spectral_reduction.OneDSpec(log_file_name=None)
onedspec.set_atmospheric_extinction()
onedspec.set_atmospheric_extinction(
extinction_func=np.polyfit([0, 1], [0, 1], 1)
)
@patch("plotly.graph_objects.Figure.show")
3
Source : test_twodspec.py
with BSD 3-Clause "New" or "Revised" License
from cylammarco
with BSD 3-Clause "New" or "Revised" License
from cylammarco
def test_add_random_data_expect_fail():
twodspec = spectral_reduction.TwoDSpec(log_file_name=None)
twodspec.add_data(np.polyfit)
def test_set_all_properties():
3
Source : regression.py
with Apache License 2.0
from dashanji
with Apache License 2.0
from dashanji
def fit_poly(self, grid, order):
"""Regression using numpy polyfit for higher-order trends."""
def reg_func(_x, _y):
return np.polyval(np.polyfit(_x, _y, order), grid)
x, y = self.x, self.y
yhat = reg_func(x, y)
if self.ci is None:
return yhat, None
yhat_boots = algo.bootstrap(x, y,
func=reg_func,
n_boot=self.n_boot,
units=self.units,
seed=self.seed)
return yhat, yhat_boots
def fit_statsmodels(self, grid, model, **kwargs):
3
Source : test_regression.py
with Apache License 2.0
from dashanji
with Apache License 2.0
from dashanji
def test_residplot(self):
x, y = self.df.x, self.df.y
ax = lm.residplot(x=x, y=y)
resid = y - np.polyval(np.polyfit(x, y, 1), x)
x_plot, y_plot = ax.collections[0].get_offsets().T
npt.assert_array_equal(x, x_plot)
npt.assert_array_almost_equal(resid, y_plot)
@pytest.mark.skipif(_no_statsmodels, reason="no statsmodels")
3
Source : mfp_eosfit.py
with GNU Lesser General Public License v3.0
from deepmodeling
with GNU Lesser General Public License v3.0
from deepmodeling
def init_guess(fin):
v, e = read_ve(fin)
a, b, c = np.polyfit(v, e, 2) # this comes from pylab
# initial guesses.
v0 = np.abs(-b / (2 * a))
e0 = a * v0 ** 2 + b * v0 + c
b0 = 2 * a * v0
bp = 3.0
bpp = 1 * eV2GPa
x0 = [e0, b0, bp, v0, bpp]
return x0
def repro_ve(func, vol_i, p):
3
Source : core.py
with MIT License
from dioph
with MIT License
from dioph
def polyfit(self, degree):
coefs = np.polyfit(self.time, self.values, degree)
fit = self._replace_data(np.poly1d(coefs)(self.time))
fit.attrs.update(coefficients=coefs)
return fit
def curvefit(self, fun, **kwargs):
3
Source : core.py
with MIT License
from dioph
with MIT License
from dioph
def polyfit(self, degree, use_period=False):
if use_period:
xdata = self.period
else:
xdata = self.frequency
coefs = np.polyfit(xdata, self.values, degree)
fit = self._replace_data(np.poly1d(coefs)(xdata))
fit.attrs.update(coefficients=coefs)
return fit
def curvefit(self, fun, use_period=False, **kwargs):
3
Source : polifit.py
with MIT License
from downingbots
with MIT License
from downingbots
def fit(self, x, y):
"""
Fits a 2nd degree polynomial to provided points and returns its coefficients.
Parameters
----------
x : Array of x coordinates for pixels representing a line.
y : Array of y coordinates for pixels representing a line.
"""
self.coefficients.append(np.polyfit(y, x, 2))
def radius_of_curvature(self):
3
Source : meas_utils.py
with MIT License
from dssg
with MIT License
from dssg
def L(x, y, x_la):
"""Get Euclidean distance from points fit by function (adapted from Zhang et al.)"""
if x.sum() == 0 or y.sum() == 0 or x_la.sum() == 0:
return 0
fit = np.polyfit(x, y, 1)
fit_fn = np.poly1d(fit)
line_points = fit_fn(x_la)
x_min = x_la[np.argmin(line_points)]
y_min = np.min(line_points)
x_max = x_la[np.argmax(line_points)]
y_max = np.max(line_points)
l = point_distance([x_min, y_min], [x_max, y_max])
return l
def point_distance(point1, point2):
3
Source : fit.py
with MIT License
from feihoo87
with MIT License
from feihoo87
def fit_pole(x, y):
a, b, c = np.polyfit(x, y, 2)
return -0.5 * b / a, c - 0.25 * b**2 / a
def fit_cosine(data, repeat=1, weight=None, x=None):
3
Source : fret_lines.py
with GNU General Public License v2.0
from Fluorescence-Tools
with GNU General Public License v2.0
from Fluorescence-Tools
def polynom_coefficients(
self
):
"""
A numpy array with polynomial coefficients approximating the tauX(tauF) conversion function
"""
x, y = self.fluorescence_averaged_lifetimes, self.fret_species_averaged_lifetimes
return np.polyfit(x, y, self.polynomial_degree)
@property
3
Source : coreg.py
with MIT License
from GlacioHack
with MIT License
from GlacioHack
def _fit_func(self, ref_dem: np.ndarray, tba_dem: np.ndarray, transform: Optional[rio.transform.Affine],
weights: Optional[np.ndarray], verbose: bool = False):
"""Estimate the scale difference between the two DEMs."""
ddem = ref_dem - tba_dem
medians = xdem.volume.hypsometric_binning(
ddem=ddem,
ref_dem=tba_dem,
bins=self.bin_count,
kind="count"
)["value"]
coefficients = np.polyfit(medians.index.mid, medians.values, deg=self.degree)
self._meta["coefficients"] = coefficients
def _apply_func(self, dem: np.ndarray, transform: rio.transform.Affine, **kwargs) -> np.ndarray:
3
Source : data_processor.py
with MIT License
from gtsoukas
with MIT License
from gtsoukas
def fit_line(p1, p2):
# fit a line ax+by+c = 0
if p1[0] == p1[1]:
return [1., 0., -p1[0]]
else:
[k, b] = np.polyfit(p1, p2, deg=1)
return [k, -1., b]
def line_cross_point(FLAGS, line1, line2):
3
Source : setjy.py
with GNU General Public License v3.0
from idia-astro
with GNU General Public License v3.0
from idia-astro
def linfit(xInput, xDataList, yDataList):
"""
"""
y_predict = np.poly1d(np.polyfit(xDataList, yDataList, 1))
yPredict = y_predict(xInput)
return yPredict
def do_setjy(visname, spw, fields, standard, dopol=False, createmms=True):
3
Source : lane_functions.py
with MIT License
from jawilk
with MIT License
from jawilk
def fit_poly_line(x_values, y_values, shape_0, orientation = 'Left'):
'''
Fit 2nd order polynomial to a line (left/right)
Return points on line
'''
# Fit a second order polynomial to each
line_fit = np.polyfit(y_values, x_values, 2)
ploty = np.linspace(0, shape_0 - 1, shape_0)
line_fitx = line_fit[0]*ploty**2 + line_fit[1]*ploty + line_fit[2]
if orientation == 'Left':
pts = np.array([np.transpose(np.vstack([line_fitx, ploty]))])
elif orientation == 'Right':
pts = np.array([np.flipud(np.transpose(np.vstack([line_fitx, ploty])))])
return pts, line_fitx
def lane_pipeline(image, src=[], dst=[]):
3
Source : Battery_data_analysis_final.py
with MIT License
from jogrady23
with MIT License
from jogrady23
def getPolyFitValues(order, xList, yList):
coefficients = np.polyfit(xList, yList, order)
modeledValues = list()
for x in xList:
yVal = 0
i = 0
while order - i >= 0:
yVal += coefficients[i] * x ** (order - i)
i += 1
modeledValues.append(yVal)
return modeledValues
# Finds the chi-square value for experimental and modeled values
# inputs: list of experimental x-values, list of experimental y-values, list of modeled y-values
# returns: the chi-squared value
def getChiSquaredValue(experimentalValues, modeledValues):
3
Source : plotter.py
with Apache License 2.0
from k-maheshkumar
with Apache License 2.0
from k-maheshkumar
def x_y_best_fit_curve(cls, x, y, xlabel, ylabel, title=None, deg=3):
plt.figure()
coeffs = np.polyfit(x, y, deg)
x2 = np.arange(min(x) - 1, max(x) + 1, .01) # use more points for a smoother plot
y2 = np.polyval(coeffs, x2) # Evaluates the polynomial for each x2 value
fig = plt.figure()
fig.suptitle(xlabel + ' vs ' + ylabel, fontsize=20)
plt.xlabel(xlabel, fontsize=18)
plt.ylabel(ylabel, fontsize=16)
plt.plot(x2, y2, label="deg=" + str(deg))
plt.plot(x, y, 'bx')
plt.show()
@classmethod
3
Source : plotter.py
with Apache License 2.0
from k-maheshkumar
with Apache License 2.0
from k-maheshkumar
def multi_plot_best_fit_curve(self, xs, ys, labels, title, c_x_title, c_y_title, deg=2):
plt.figure()
for x, y, l in zip(xs, ys, labels):
coeffs = np.polyfit(x, y, deg)
x2 = np.arange(min(x) - 1, max(x) + 1, .01) # use more points for a smoother plot
y2 = np.polyval(coeffs, x2) # Evaluates the polynomial for each x2 value
# plt.plot(x2, y2, label=l)
plt.plot(x, y, label=l)
plt.legend(loc='upper right', fontsize=18)
plt.title(title, fontsize=18)
plt.xlabel(c_x_title, fontsize=18)
plt.ylabel(c_y_title, fontsize=18)
@classmethod
3
Source : function.py
with MIT License
from karipov
with MIT License
from karipov
def _fit_data(self) -> Callable[[int], int]:
fitted = np.polyfit(self.x, self.y, self.order)
func = np.poly1d(fitted)
return func
def add_datapoint(self, pair: tuple):
3
Source : test_univariate.py
with BSD 3-Clause "New" or "Revised" License
from mne-tools
with BSD 3-Clause "New" or "Revised" License
from mne-tools
def test_slope_lstsq():
x = rng.standard_normal((100,))
m = rng.uniform()
y = m * x + 1
s1 = _slope_lstsq(x, y)
s2 = np.polyfit(x, y, 1)[0]
assert_almost_equal(s1, m)
assert_almost_equal(s1, s2)
def test_accumulate_max():
3
Source : wavelength.py
with GNU General Public License v3.0
from monocle-h2020
with GNU General Public License v3.0
from monocle-h2020
def fit_wavelength_coefficients(y, coefficients):
coeff_coeff = np.array([np.polyfit(y, coefficients[:, i], degree_of_coefficient_fit) for i in range(degree_of_wavelength_fit+1)])
coeff_fit = np.array([np.polyval(coeff, y) for coeff in coeff_coeff]).T
return coeff_coeff, coeff_fit
def wavelength_fit(y, *coeff_coeff):
3
Source : test_control_endpoint_defect_comp.py
with Apache License 2.0
from OpenMDAO
with Apache License 2.0
from OpenMDAO
def test_results(self):
u_coefs = np.polyfit(self.gd.node_ptau[-4:-1], self.p['controls:u'][-4:-1], deg=2)
u_poly = np.poly1d(u_coefs.ravel())
u_interp = u_poly(1.0)
u_given = self.p['controls:u'][-1]
assert_near_equal(np.ravel(self.p['endpoint_defect_comp.control_endpoint_defects:u']),
np.ravel(u_given - u_interp),
tolerance=1.0E-12)
def test_partials(self):
3
Source : fake.py
with MIT License
from OrganicMaterialsDatabase
with MIT License
from OrganicMaterialsDatabase
def place_mexican(position, width=.4):
k = [0, .25, .5, .75, 1]
E = [1, .4, 1, .4, 1]
p = np.poly1d(np.polyfit(k, E, 4))
k = np.linspace(0, 1, int(width/dk))
for i,j in enumerate(range(position, position+len(k))):
E_upper[j] = p(k[i])
E_lower[j] = -p(k[i])
place_crossing(int(19/200*len(k)), width=.4)
3
Source : PrecessingFisherMatrix.py
with MIT License
from oshaughn
with MIT License
from oshaughn
def EffectiveFisherMatrixElement(P,p1,p2,psd,max_t=True,**kwargs):
if p1 is p2:
dat = OverlapVersusChangingParameter(P,p1,psd,max_t=max_t,**kwargs)
xvals, yvals = dat[:,0], dat[:,1]
z = np.polyfit(xvals,yvals,2)
return -0.5*z[0]*np.sign( xvals[-1]-xvals[0]) # coefficient of quadratic
else:
print(" Off-diagonal elements not yet implemented")
sys.exit(0)
def ApproximatePrecessingFisherMatrixElement(P, p1,p2,psd,return_intermediate=False,phase_deriv_cache=None,break_out_beta=False,**kwargs):
3
Source : sazonal_consumption.py
with MIT License
from perkier
with MIT License
from perkier
def fit_func(reader, order):
x = reader.loc[:, 'month']
y = reader.loc[:, 'consumption']
n = order
z = np.polyfit(x, y, n)
p = np.poly1d(z)
xp = np.linspace(1, 12)
return p, xp
saz_reader = open('C:\\Users\\Diogo Sá\\Desktop\\perkier tech\\Energy\\CODE\\Google API\\sazonal_consumption_2.txt', 'rb')
3
Source : pythelec.py
with MIT License
from PhasesResearchLab
with MIT License
from PhasesResearchLab
def alt_curve_fit(BMfunc, x, y):
#it is found the python curve_fit can result in numerical instability
if 1==0: return curve_fit(BMfunc, x, y)
#change back to linear fitting to avoid numerical instability
xx = x**(-1/3)
if BMfunc.__name__=="BMvol4":
return np.polyfit(xx, y, 3)[::-1], 0
elif BMfunc.__name__=="BMvol5":
return np.polyfit(xx, y, 4)[::-1], 0
def BMfitB(V, x, y, BMfunc):
3
Source : outliers.py
with MIT License
from pylhc
with MIT License
from pylhc
def _get_data_without_slope(mask, x, y):
m, b = np.polyfit(x[mask], y[mask], 1)
return y[mask] - b - m * x[mask], y - b - m * x
def _get_data(mask, data):
3
Source : rainfarm.py
with BSD 3-Clause "New" or "Revised" License
from pySTEPS
with BSD 3-Clause "New" or "Revised" License
from pySTEPS
def _log_slope(log_k, log_power_spectrum):
lk_min = log_k.min()
lk_max = log_k.max()
lk_range = lk_max - lk_min
lk_min += (1 / 6) * lk_range
lk_max -= (1 / 6) * lk_range
selected = (lk_min < = log_k) & (log_k < = lk_max)
lk_sel = log_k[selected]
ps_sel = log_power_spectrum[selected]
alpha = np.polyfit(lk_sel, ps_sel, 1)[0]
alpha = -alpha
return alpha
def _balanced_spatial_average(x, k):
3
Source : plotter.py
with MIT License
from romulus97
with MIT License
from romulus97
def find_insurance_payment(annual_pumping, district_revenues, strike):
payout_years = annual_pumping < strike
payout_pumping = annual_pumping[payout_years]
payout_revenues = district_revenues[payout_years]
if len(payout_pumping > 1):
insurance_payout = np.polyfit(payout_pumping, payout_revenues, 1)
else:
insurance_payout = np.zeros(2)
insurance_payout[1] = 0.0
return insurance_payout
def make_insurance_series(annual_pumping, insurance_strike, revenue_series, pay_frac):
3
Source : training_results.py
with MIT License
from sash-a
with MIT License
from sash-a
def get_current_gradient_given_training_data(y_data, x_data=None):
if x_data is None:
x_data = list(range(len(y_data))) # if not specified - the x data is just 0..n
# hyperbolic_params, _ = curve_fit(hyperbolic_function, x_data, y_data)
linearised_data = linearise_data(y_data)
try:
params = np.polyfit(x_data, linearised_data, 2)
except Exception as e:
print("error fitting linearised data - ",linearised_data)
raise e
m = params[1]
a = 1/m
current_gradient = derivative_hyperbolic_function(x_data[-1], a)
# print("e:",len(x_data),"gradient value:", current_gradient)
return current_gradient
def linearise_data(y_data):
3
Source : elevation_vs_phase.py
with MIT License
from scottstanie
with MIT License
from scottstanie
def fit_halves(dem, phase, col=500, vm=2):
poly_left = np.polyfit(dem.data[:, :col].ravel(), phase.data[:, :col].ravel(), 1)
poly_right = np.polyfit(dem.data[:, col:].ravel(), phase.data[:, col:].ravel(), 1)
plot_phase_vs_elevation(dem.data[:, :col].ravel(), phase.data[:, :col].ravel())
plot_phase_vs_elevation(dem.data[:, col:].ravel(), phase.data[:, col:].ravel())
print(poly_left, poly_right)
ll, rr = np.polyval(poly_left, dem), np.polyval(poly_right, dem)
ll[:, col:] = 0
rr[:, :col] = 0
fig, axes = plt.subplots(1, 2)
axes[0].imshow(ll, cmap="seismic_wide_y_r", vmax=vm, vmin=-vm)
axes[1].imshow(rr, cmap="seismic_wide_y_r", vmax=vm, vmin=-vm)
return ll, rr
3
Source : utils.py
with MIT License
from singleron-RD
with MIT License
from singleron-RD
def get_slope(x, y, window=200, step=10):
assert len(x) == len(y)
start = 0
last = len(x)
res = [[], []]
while True:
end = start + window
if end > last:
break
z = np.polyfit(x[start:end], y[start:end], 1)
res[0].append(x[start])
res[1].append(z[0])
start += step
return res
def genDict(dim=3, valType=int):
3
Source : tools.py
with GNU General Public License v3.0
from slf-dot-ch
with GNU General Public License v3.0
from slf-dot-ch
def lin_fit(x, y):
m, c = np.polyfit(x, y, 1)
y_fit = x * m + c
std = np.std(y - y_fit)
return x, y_fit, m, c, std
3
Source : plotting.py
with MIT License
from SSubhnil
with MIT License
from SSubhnil
def ComputeCurvature(x, y, ref_point):
const = np.polyfit(x,y,2)
X = Symbol('X')
fun = const[0]*X**2 + const[1]*X + const[2]
first_deriv = Derivative(fun,X)
second_deriv = Derivative(first_deriv, X)
Y_dash = first_deriv.doit().subs({X:ref_point})
Y_Ddash= second_deriv.doit().subs({X:ref_point})
curvature = Y_Ddash/pow(1+pow(Y_dash,2),3/2)
return curvature
def isInside(x, y):
See More Examples