本文整理汇总了Python中numpy.poly1d函数的典型用法代码示例。如果您正苦于以下问题:Python poly1d函数的具体用法?Python poly1d怎么用?Python poly1d使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了poly1d函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: calFinished
def calFinished(self,items):
ADC,DAC,correct = items
CHAN = self.I.DAC.CHANS[DAC]
X= np.linspace(CHAN.range[0],CHAN.range[1],4096)
fitvals = np.polyfit(X,correct,3)
fitfn = np.poly1d(fitvals)
DIFF = (fitfn(X)-correct)
intercept = DIFF.min()
slope = (DIFF.max()-DIFF.min())/255.
OFF = np.int16((( DIFF-intercept)/slope)) # compress the errors into an unsigned BYTE each
print (min(OFF),max(OFF),len(OFF))
self.p1.setData(X,correct-X)
self.DACPLOT.enableAutoRange(axis = self.DACPLOT.plotItem.vb.YAxis)
reply = QtGui.QMessageBox.question(self, 'Cross Check','Does the plot look okay? proceed with writing to flash?', QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.No:
return False
self.DAC_CALS[DAC]=struct.pack('6f',slope,intercept,fitvals[0],fitvals[1],fitvals[2],fitvals[3])
self.DAC_RELOADS[DAC] = OFF
print( '\n','>'*20,DAC,'<'*20)
print('Offsets :',OFF[:20],'...')
fitfn = np.poly1d(fitvals)
YDATA = fitfn(X) - (OFF*slope+intercept)
LOOKBEHIND = 100;LOOKAHEAD=100
OFF=np.array([np.argmin(np.fabs(YDATA[max(B-LOOKBEHIND,0):min(4095,B+LOOKAHEAD)]-X[B]) )- (B-max(B-LOOKBEHIND,0)) for B in range(0,4096)])
CHAN.load_calibration_table(OFF)
self.tabs.setEnabled(True)
self.__PVCH__(DAC,ADC,self.curdacrow,[CHAN.CodeToV(100),CHAN.CodeToV(4000),200]) #Check if fixed
示例2: test_polydiv
def test_polydiv(self):
b = np.poly1d([2, 6, 6, 1])
a = np.poly1d([-1j, (1+2j), -(2+1j), 1])
q, r = np.polydiv(b, a)
assert_equal(q.coeffs.dtype, np.complex128)
assert_equal(r.coeffs.dtype, np.complex128)
assert_equal(q*a + r, b)
示例3: var_fit
def var_fit(var_mean,var_name):
size_list = []
throuput_list = []
for var in var_mean:
get_per,set_per = normal_ops
get_per_s = "%.2f" % get_per
set_per_s = "%.2f" % set_per
if (var_name=='key'):
upperlimit = 64
filename = 'data_collected/'+str(var)+'_'+str(normal_value)+'_'+str(normal_hash)+'_'+get_per_s+'_'+set_per_s+'.out'
elif (var_name=='value'):
upperlimit = 2048
filename = 'data_collected/'+str(normal_key)+'_'+str(var)+'_'+str(normal_hash)+'_'+get_per_s+'_'+set_per_s+'.out'
with open(filename,'r') as f:
load, time = zip(*[(int(line.strip().split(',')[0]), float(line.strip().split(',')[1])) for line in f])
z = np.polyfit(time,load,2)
p = np.poly1d(z)
size = var
throuput = p(1)
size_list.append(size)
throuput_list.append(throuput)
#Record raw data point
with open ('data_collected/'+var_name+'_throuput','w') as g:
for size,throuput in zip(size_list,throuput_list):
g.write(str(size)+','+str(throuput)+'\n')
#Recide fit data point
z = np.polyfit(np.array(size_list),np.array(throuput_list),1)
p = np.poly1d(z)
size_fit_list = [i for i in range(1,upperlimit)]
throuput_fit_list = [p(i) for i in size_fit_list]
with open ('data_collected/'+var_name+'_throuput_fit','w') as g:
for size,throuput in zip(np.array(size_fit_list),np.array(throuput_fit_list)):
g.write(str(size)+','+str(throuput)+'\n')
var_plot(var_name,list(z))
示例4: extractfeatures
def extractfeatures(buf):
global yp1, yp2, yp3, x
x = range(len(buf))
features = []
link1 = []
link2 = []
link3 = []
for p in buf:
link1.append(p[0])
link2.append(p[1])
link3.append(p[2])
features.append(avgdelta(link1))
features.append(avgdelta(link2))
features.append(avgdelta(link3))
features.append(abs(link1[0]-link1[len(link1)-1]))
features.append(abs(link2[0]-link2[len(link2)-1]))
features.append(abs(link3[0]-link3[len(link3)-1]))
z1 = np.polyfit(x,link1,2)
z2 = np.polyfit(x,link2,2)
z3 = np.polyfit(x,link3,2)
abslink1 = [abs(z1[i]) for i in range(len(z1)-1)]
abslink2 = [abs(z2[i]) for i in range(len(z2)-1)]
abslink3 = [abs(z3[i]) for i in range(len(z3)-1)]
for a in abslink1:
features.append(a)
for a in abslink2:
features.append(a)
for a in abslink3:
features.append(a)
yp1 = np.poly1d(z1)
yp2 = np.poly1d(z2)
yp3 = np.poly1d(z3)
return features
示例5: plot
def plot(self):
self.worksheet()
fig, ax = plt.subplots()
axes = [ax, ax.twinx(), ax.twinx()]
fig.subplots_adjust(right=0.75)
axes[-1].spines['right'].set_position(('axes', 1.2))
colors = ('Green', 'Red', 'Blue')
cur=np.poly1d(np.polyfit(self.DISCHARGE,self.current,2))
eff=np.poly1d(np.polyfit(self.DISCHARGE,self.EFFICIENCY,2))
head=np.poly1d(np.polyfit(self.DISCHARGE,self.del_head,2))
dis=np.linspace(self.DISCHARGE[0],self.DISCHARGE[9],500)
#Head Axis Plotting
axes[2].plot(dis,eff(dis), color=colors[0])
axes[2].plot(self.DISCHARGE,self.EFFICIENCY,'ko',color=colors[0])
axes[2].set_ylabel('Efficiency (%)', color=colors[0])
axes[2].tick_params(axis='y', colors=colors[0])
#Current Axis Plotting
axes[1].plot(dis,cur(dis), color=colors[1])
axes[1].plot(self.DISCHARGE,self.current,'k+',color=colors[1])
axes[1].set_ylabel('Current (A)', color=colors[1])
axes[1].tick_params(axis='y', colors=colors[1])
#Efficiency Axis Plotting
axes[0].plot(dis,head(dis), color=colors[2])
axes[0].plot(self.DISCHARGE,self.del_head,'kx',color=colors[2])
axes[0].set_ylabel('Head (m)', color=colors[2])
axes[0].tick_params(axis='y', colors=colors[2])
axes[0].set_xlabel('Discharge in lps')
plt.grid()
plt.show()
self.DISCHARGE = []
self.EFFICIENCY= []
示例6: daub
def daub(p):
"""
The coefficients for the FIR low-pass filter producing Daubechies wavelets.
p>=1 gives the order of the zero at f=1/2.
There are 2p filter coefficients.
Parameters
----------
p : int
Order of the zero at f=1/2, can have values from 1 to 34.
"""
sqrt = np.sqrt
if p < 1:
raise ValueError("p must be at least 1.")
if p==1:
c = 1/sqrt(2)
return np.array([c,c])
elif p==2:
f = sqrt(2)/8
c = sqrt(3)
return f*np.array([1+c,3+c,3-c,1-c])
elif p==3:
tmp = 12*sqrt(10)
z1 = 1.5 + sqrt(15+tmp)/6 - 1j*(sqrt(15)+sqrt(tmp-15))/6
z1c = np.conj(z1)
f = sqrt(2)/8
d0 = np.real((1-z1)*(1-z1c))
a0 = np.real(z1*z1c)
a1 = 2*np.real(z1)
return f/d0*np.array([a0, 3*a0-a1, 3*a0-3*a1+1, a0-3*a1+3, 3-a1, 1])
elif p<35:
# construct polynomial and factor it
if p<35:
P = [comb(p-1+k,k,exact=1) for k in range(p)][::-1]
yj = np.roots(P)
else: # try different polynomial --- needs work
P = [comb(p-1+k,k,exact=1)/4.0**k for k in range(p)][::-1]
yj = np.roots(P) / 4
# for each root, compute two z roots, select the one with |z|>1
# Build up final polynomial
c = np.poly1d([1,1])**p
q = np.poly1d([1])
for k in range(p-1):
yval = yj[k]
part = 2*sqrt(yval*(yval-1))
const = 1-2*yval
z1 = const + part
if (abs(z1)) < 1:
z1 = const - part
q = q * [1,-z1]
q = c * np.real(q)
# Normalize result
q = q / np.sum(q) * sqrt(2)
return q.c[::-1]
else:
raise ValueError("Polynomial factorization does not work "
"well for p too large.")
示例7: fit
def fit(data, nz):
x = [0 for iz in range(0, nz, 1)]
y = [0 for iz in range(0, nz, 1)]
z = [iz for iz in range(0, nz, 1)]
for iz in range(0, nz, 1):
x[iz], y[iz] = ndimage.measurements.center_of_mass(np.array(data[:,:,iz]))
#Fit centerline in the Z-X plane using polynomial function
print '\nFit centerline in the Z-X plane using polynomial function...'
coeffsx = np.polyfit(z, x, 1)
polyx = np.poly1d(coeffsx)
x_fit = np.polyval(polyx, z)
print 'x_fit'
print x_fit
#Fit centerline in the Z-Y plane using polynomial function
print '\nFit centerline in the Z-Y plane using polynomial function...'
coeffsy = np.polyfit(z, y, 1)
polyy = np.poly1d(coeffsy)
y_fit = np.polyval(polyy, z)
#### 3D plot
fig1 = plt.figure()
ax = Axes3D(fig1)
ax.plot(x,y,z,zdir='z')
ax.plot(x_fit,y_fit,z,zdir='z')
plt.show()
return x, y, x_fit, y_fit
示例8: Q
def Q(dim, dfd=np.inf):
""" Q polynomial
If dfd == inf (the default), then
Q(dim) is the (dim-1)-st Hermite polynomial
H_j(x) = (-1)^j * e^{x^2/2} * (d^j/dx^j e^{-x^2/2})
If dfd != inf, then it is the polynomial Q defined in
Worsley, K.J. (1994). 'Local maxima and the expected Euler
characteristic of excursion sets of \chi^2, F and t fields.'
Advances in Applied Probability, 26:13-42.
"""
m = dfd
j = dim
if j > 0:
poly = hermitenorm(j - 1)
poly = np.poly1d(np.around(poly.c))
if np.isfinite(m):
for l in range((j - 1) / 2 + 1):
f = np.exp(
gammaln((m + 1) / 2.0)
- gammaln((m + 2 - j + 2 * l) / 2.0)
- 0.5 * (j - 1 - 2 * l) * (np.log(m / 2.0))
)
poly.c[2 * l] *= f
return np.poly1d(poly.c)
else:
raise ValueError, "Q defined only for dim > 0"
示例9: StepFit
def StepFit(df_timeser):
# receives the temporal series as a dataframe with 3 columns: time, nflux, Q
# NaN must be already droped
# df must be already sorted by time
# An array of quarters, non duplicate items.
nondup = np.unique(df_timeser['Q'].values)
# Go through time series, quarter by quarter
if len(nondup) > 1:
# Save the first quarter of the LC
df_Fit = df_timeser[ df_timeser.Q == nondup[0] ]
# Iterate up to the n-1 element
for index,q_item in enumerate( nondup[:len(nondup)-1] ): # indexing is OK!!!
df_tmp1 = df_timeser[ df_timeser.Q == q_item ]
df_tmp2 = df_timeser[ df_timeser.Q == nondup[index+1] ]
# fit the 2 linear fits using: np.polyfit, np.polyval, p = np.poly1d(z)
p1 = np.poly1d( np.polyfit(df_tmp1['time'].values, df_tmp1['nflux'].values,1) )
p2 = np.poly1d( np.polyfit(df_tmp2['time'].values, df_tmp2['nflux'].values,1) )
# then evaluate the borders of each piece, in the corresponding fit
# and determine the offset.
Offset = p1(df_tmp1['time'].values[-1]) - p2(df_tmp2['time'].values[-1])
# now add the offset to the second piece
df_tmp2['nflux'] += Offset
# and concatenate the 2nd piece with the previous
df_Fit = concat( [df_Fit, df_tmp2] )
else:
df_Fit = df_timeser
print 'no fit made, only ONE quarter in LC'
#return out of ELSE statement
return df_Fit
示例10: debye_T
def debye_T(self, x):
self.__EoB = []
self.__GoB = []
self.__B = []
self.__V = []
dic = self.get_Cij()
for scale in sorted(dic.keys()):
(a, b, c) = self.calculate_moduli(scale)
self.__EoB.append(c)
self.__GoB.append(b)
self.__B.append(a)
self.__V.append(float(scale)**3./2.)
c1= np.polyfit(self.__V, self.__EoB, 4)
p_EoB = np.poly1d(c1)
c2= np.polyfit(self.__V, self.__GoB, 4)
p_GoB = np.poly1d(c2)
c3= np.polyfit(self.__V, self.__B, 4)
p_B = np.poly1d(c3)
Const = 1.
theta = Const * ( 1./3.*(p_EoB(x))**(-3./2.) + 2./3.*(p_GoB(x))**(-3./2.) )
return theta
示例11: polynomial_fitting
def polynomial_fitting(input_array, degree=4, verbose=False, skip_col=[], skip_row=[]):
array_org = input_array.copy()
shape = input_array.shape
# apply on rows
for row in range(shape[0]):
if row in skip_row:
pass
else:
poly = np.poly1d(np.polyfit(x=np.linspace(1, shape[1], shape[1]), y=input_array[row,:], deg=degree))
input_array[row,:] = poly(np.linspace(1, shape[1], shape[1]))
# apply on columns
for col in range(shape[1]):
if col in skip_col:
pass
else:
poly = np.poly1d(np.polyfit(x=np.linspace(1, shape[0], shape[0]), y=input_array[:,col], deg=degree))
input_array[:,col] = poly(np.linspace(1, shape[0], shape[0]))
if verbose:
print("Polynomial fitting")
print("Degree of the fitting polynomial : {}".format(degree))
print("-----Normalized Table-------")
print(input_array)
print("-----Original Table-------")
print(array_org)
print("")
return input_array
示例12: bch_18_6
def bch_18_6(symbol_version):
"""Calculate BCH(18,6) on symbol version number.
This function is not used as in the specs we have a reference table
covering all the symbol version. It was just to test if I would have
obtained the same results.
"""
data_bit_string = to_binstring(symbol_version, 6)
numerator = (
poly1d([int(x) for x in data_bit_string]) *
poly1d([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]))
generator_polynomial = poly1d([1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1])
_quotient, remainder = numerator / generator_polynomial
coeff_list = [abs(int(x)) for x in remainder.coeffs]
# don't know why i have some 2 and 3 coefficients. used a modulo operation
# to obtain the expected results
coeff_list = [x % 2 for x in coeff_list]
while len(coeff_list) < 12:
coeff_list.insert(0, 0)
coeff_string = ''
for coeff in coeff_list:
coeff_string += str(coeff)
result = data_bit_string + coeff_string
return result
示例13: drawStats2
def drawStats2(prices, period):
ps2 = [p['close'] for p in prices][-140:-115]
ps = [p['close'] for p in prices][-140:-120]
phs = [p['high'] for p in prices][-140:-120]
pls = [p['low'] for p in prices][-140:-120]
l = len(prices)
ts = np.arange(20)
pz = np.poly1d(np.polyfit(ts, ps, 1))
phz = np.poly1d(np.polyfit(ts, phs, 1))
plz = np.poly1d(np.polyfit(ts, pls, 1))
fig = plt.figure()
ax1 = fig.add_subplot(311)
ax1.plot(ts, ps, '-', ts, pz(ts), '-', ts, phz(ts), '--', ts, plz(ts), '--')
#plt.plot(ts, ps, 'o', label='Original data', linestyle='-', markersize=2)
#plt.plot(ts, m * ts + c, 'r', label='Fitted line')
#plt.legend()
ax2 = fig.add_subplot(312)
ax2.plot(ts, (pz(ts) - plz(ts)) - (phz(ts) - pz(ts)), '-')
ax2.grid()
ts2 = np.arange(len(ps2))
ax3 = fig.add_subplot(313)
ax3.plot(ts2, ps2, '-')
multi = MultiCursor(fig.canvas, (ax1, ax2), color='r', lw=1, horizOn=False, vertOn=True)
plt.show()
return
示例14: optimum_polyfit
def optimum_polyfit(x, y, score=functoolz.compose(np.max, np.abs), max_degree=50, stop_at=1e-10):
"""
Optimize the degree of a polyfit polynomial so that score(y - poly(x)) is minimized.
:param max_degree: The maximum degree to try. LinAlgErrors are automatically ignored.
:param stop_at: If a score lower than this is reached, the function returns early
:param score: The score function that is applied to y - poly(x). Default: max deviation.
:return A tuple (poly1d object, degree, score)
"""
scores = np.empty(max_degree - 1, dtype=np.float64)
# Ignore rank warnings now, but do not ignore for the final polynomial if not early returning
with warnings.catch_warnings():
warnings.simplefilter('ignore', np.RankWarning)
for deg in range(1, max_degree):
# Set score to max float value
try:
poly = np.poly1d(np.polyfit(x, y, deg))
except np.linalg.LinAlgError:
scores[deg - 1] = np.finfo(np.float64).max
continue
scores[deg - 1] = score(y - poly(x))
# Early return if we found a polynomial that is good enough
if scores[deg - 1] <= stop_at:
return poly, deg, scores[deg - 1]
# Find minimum score
deg = np.argmin(scores) + 1
# Compute polyfit for that degreet
poly = np.poly1d(np.polyfit(x, y, deg))
return poly, deg, np.min(scores)
示例15: smooth_regress
def smooth_regress(path, dt, order):
"""
path: data frame with at least columns 't', 'lat', 'lon'
dt: resampling time interval
order: order of the polynomial to use
return: interpolated path
"""
import pandas as pd
import numpy as np
from numpy import polyfit, poly1d
start = path.t.iloc[0]
end = path.t.iloc[-1]
# new ts sequence
nt = start + np.linspace(0, end - start, (end - start) / dt + 1)
avg_t = np.mean(path['t'])
avg_lat = np.mean(path['lat'])
avg_lon = np.mean(path['lon'])
lat = np.poly1d(np.polyfit(path['t'] - avg_t, path['lat'] - avg_lat, order))
lon = np.poly1d(np.polyfit(path['t'] - avg_t, path['lon'] - avg_lon, order))
r = pd.DataFrame(columns = ('t', 'lat', 'lon'))
r['t'] = nt
r['lat'] = list(map(lat, nt - avg_t))
r['lon'] = list(map(lon, nt - avg_t))
# Repair path
r['lat'] += avg_lat
r['lon'] += avg_lon
r.set_index('t', inplace=True)
return r