def test_objects(self):
from decimal import Decimal
p = np.poly1d([Decimal('4.0'), Decimal('3.0'), Decimal('2.0')])
p2 = p * Decimal('1.333333333333333')
assert_(p2[1] == Decimal("3.9999999999999990"))
p2 = p.deriv()
assert_(p2[1] == Decimal('8.0'))
p2 = p.integ()
assert_(p2[3] == Decimal("1.333333333333333333333333333"))
assert_(p2[2] == Decimal('1.5'))
assert_(np.issubdtype(p2.coeffs.dtype, np.object_))
p = np.poly([Decimal(1), Decimal(2)])
assert_equal(np.poly([Decimal(1), Decimal(2)]),
[1, Decimal(-3), Decimal(2)])
python类poly1d()的实例源码
def test_complex(self):
p = np.poly1d([3j, 2j, 1j])
p2 = p.integ()
assert_((p2.coeffs == [1j, 1j, 1j, 0]).all())
p2 = p.deriv()
assert_((p2.coeffs == [6j, 2j]).all())
def test_integ_coeffs(self):
p = np.poly1d([3, 2, 1])
p2 = p.integ(3, k=[9, 7, 6])
assert_(
(p2.coeffs == [1/4./5., 1/3./4., 1/2./3., 9/1./2., 7, 6]).all())
def fit_y(self, X, Y, x1, x2):
len(X)!=0
# if X only include one point, the function will get line y=Y[0]
if np.sum(X==X[0])==len(X):
return Y[0], Y[0]
p=np.poly1d(np.polyfit(X, Y, 1))
return p(x1), p(x2)
def get_text_lines(self, text_proposals, scores, im_size):
# tp=text proposal
tp_groups=self.group_text_proposals(text_proposals, scores, im_size)
text_lines=np.zeros((len(tp_groups), 8), np.float32)
for index, tp_indices in enumerate(tp_groups):
text_line_boxes=text_proposals[list(tp_indices)]
num = np.size(text_line_boxes)
X = (text_line_boxes[:,0] + text_line_boxes[:,2]) / 2
Y = (text_line_boxes[:,1] + text_line_boxes[:,3]) / 2
z1 = np.polyfit(X,Y,1)
p1 = np.poly1d(z1)
x0=np.min(text_line_boxes[:, 0])
x1=np.max(text_line_boxes[:, 2])
offset=(text_line_boxes[0, 2]-text_line_boxes[0, 0])*0.5
lt_y, rt_y=self.fit_y(text_line_boxes[:, 0], text_line_boxes[:, 1], x0+offset, x1-offset)
lb_y, rb_y=self.fit_y(text_line_boxes[:, 0], text_line_boxes[:, 3], x0+offset, x1-offset)
# the score of a text line is the average score of the scores
# of all text proposals contained in the text line
score=scores[list(tp_indices)].sum()/float(len(tp_indices))
text_lines[index, 0]=x0
text_lines[index, 1]=min(lt_y, rt_y)
text_lines[index, 2]=x1
text_lines[index, 3]=max(lb_y, rb_y)
text_lines[index, 4]=score
text_lines[index, 5]=z1[0]
text_lines[index, 6]=z1[1]
height = np.mean( (text_line_boxes[:,3]-text_line_boxes[:,1]) )
text_lines[index, 7]= height + 2.5
#text_lines=clip_boxes(text_lines, im_size)
return text_lines
def compute_grun_along_one_direction(nq,modes,ngeo,cgeo,celldmsx,freqgeo,rangegeo,xindex=0):
"""
Compute the Gruneisen parameters along one direction.
This function uses a 1-dimensional polynomial of fourth degree to fit the
frequencies along a certain direction (along a and c axis in hexagonal systems
for example).
"""
# set a numpy array of volumes for the fit (n=5)
xtemp=[]
for igeo in rangegeo:
xtemp.append(celldmsx[igeo,xindex])
x=np.array(xtemp)
grun=[]
for iq in range(0,nq):
grunq=[]
for ifreq in range(0,modes):
ytemp=[]
for igeo in rangegeo:
ytemp.append(freqgeo[igeo,iq,ifreq])
y=np.array(ytemp)
z=np.polyfit(x, y, 4)
p=np.poly1d(z)
pderiv=np.polyder(p)
if freqgeo[cgeo[xindex],iq,ifreq]<1E-3:
grunq.append(0.0)
else:
grunq.append(pderiv(celldmsx[cgeo[xindex],xindex])/freqgeo[cgeo[xindex],iq,ifreq]) #*celldmsx[cgeo[xindex],xindex])
grun.append(grunq)
return np.array(grun)
################################################################################
def _make_quality(self, seq):
"""
Simulates read quality from an error function.
Qualities are in Sanger Fastq format (Phred+33), i.e. quality is
represented by an integer from 0 to 93, represented by the ascii
characters 33-126.
Errors are represented as 10^-0.0 (random base) to 10^-9.3 (super
accurate).
ref: http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2847217/?tool=pubmed
This might be re-written in the future using Biopythons QualityIO,
http://www.biopython.org/DIST/docs/api/Bio.SeqIO.QualityIO-module.html
"""
output = ""
for i, q in enumerate(seq):
if len(self.quality_cache) <= i:
f = numpy.poly1d(self.quality_mean)
self.quality_cache += [f(len(self.quality_cache))]
if len(self.variance_cache) <= i:
v = numpy.poly1d(self.quality_var)
self.variance_cache += [v(len(self.variance_cache))]
quality = self.quality_cache[i]
var = numpy.random.normal(0, numpy.sqrt(self.variance_cache[i]))
if not numpy.isnan(var):
quality += var
quality = min(93, max(int(quality), 0))
output += "%c" % (33+quality)
return output
def fun(x, y):
z = np.polyfit(x, y, 1)
return np.poly1d(z)
# =======================================================================================
# Checks if there are enough input parameters; else exits
def fun(x, y):
z = np.polyfit(x, y, 1)
return np.poly1d(z)
# =======================================================================================
# Checks if there are enough input parameters; else exits
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
def loadADCFile(self,filename,newLimits=[-30,30]):
print ('Loading ',filename)
INPUTNAME = filename.split('_')[1]
GAIN = filename.split('_')[2].split('x')[0]
data = np.loadtxt('%s/%s'%(self.dirname,filename))
X=data[:,0];Y=data[:,1];
source=self.analogInputSource(INPUTNAME)
source.setGain(int(GAIN))
X2=[];Y2=[]
for B in range(len(X)):
if source.__conservativeInRange__(X[B]) and X[B]>newLimits[0] and X[B]<newLimits[1]:
X2.append(X[B]);Y2.append(Y[B])
X=np.array(X2);Y=np.array(Y2)
RAW = source.voltToCode12(Y) #convert back to ADC codes for testing
avg_shifts=(self.adc_shifts[np.int16(np.floor(RAW))]+self.adc_shifts[np.int16(np.ceil(RAW))])/2. # Find mean shift(in code units) of ADC INL at each code,
# so it can be removed (Next line) , before calculating slope & intercept for the channel under process
OFFSET_REMOVED = RAW-4095*(avg_shifts*self.INL_SLOPE - self.INL_INTERCEPT)/3.3 #apply calibration of the ADC. no slope correction yet.
#OFFSET_REMOVED = source.calPoly12(OFFSET_REMOVED) #convert to voltage values
fitvals = np.polyfit(OFFSET_REMOVED[1:],X[1:],3)
self.results[INPUTNAME][int(GAIN)]=fitvals
fitfn = np.poly1d(fitvals)
print (filename,fitvals,fitfn(0),fitfn(4095))
self.rawCurves[filename].setData(np.array(X),X-Y)
self.cleanCurves[filename].setData(np.array(X),X-fitfn(OFFSET_REMOVED))
#tmpfit = np.polyfit(X[1:],Y[1:],3)
#tmppoly = np.poly1d(tmpfit)
def __init__(self, coef, post_eng_to_phys=unit_function, pre_phys_to_eng=unit_function):
"""Linear interpolation for converting between physics and engineering units.
Args:
coef (array_like): The polynomial's coefficients, in decreasing powers.
"""
super(self.__class__, self).__init__(post_eng_to_phys, pre_phys_to_eng)
self.p = numpy.poly1d(coef)
def ttp_th_keygen(params, t, n):
""" generate keys for threshold signature """
(G, o, g1, hs, g2, e) = params
# generate polynomials
v = np.poly1d([o.random() for _ in range(0,t)])
w = np.poly1d([o.random() for _ in range(0,t)])
# generate shares
x = [v(i) % o for i in range(1,n+1)]
y = [w(i) % o for i in range(1,n+1)]
# set keys
sk = list(zip(x, y))
vk = [(g2, xi*g2, yi*g2) for (xi, yi) in zip(x, y)]
vvk = (g2, v(0)*g2, w(0)*g2)
return (sk, vk, vvk)
def mix_ttp_th_keygen(params, t, n, q):
""" generate keys for threshold signature """
(G, o, g1, hs, g2, e) = params
# generate polynomials
v = np.poly1d([o.random() for _ in range(0,t)])
w = [np.poly1d([o.random() for _ in range(0,t)]) for __ in range(q)]
# generate shares
x = [v(i) % o for i in range(1,n+1)]
y = [[w[j](i) % o for j in range(len(w))] for i in range(1,n+1)]
# set keys
sk = list(zip(x, y))
vk = [(g2, x[i]*g2, [y[i][j]*g2 for j in range(len(y[i]))]) for i in range(len(sk))]
vvk = (g2, v(0)*g2, [wi(0)*g2 for wi in w])
return (sk, vk, vvk)
def linear_fit( x,y, xrange=None):
'''YG Octo 16,2017 copied from XPCS_SAXS
a linear fit
'''
if xrange is not None:
xmin, xmax = xrange
x1,x2 = find_index( x,xmin,tolerance= None),find_index( x,xmax,tolerance= None)
x_ = x[x1:x2]
y_ = y[x1:x2]
else:
x_=x
y_=y
D0 = np.polyfit(x_, y_, 1)
gmfit = np.poly1d(D0)
return D0, gmfit
def __init__(self, target_orbit, target_inc):
Operations.__init__(self, target_orbit, target_inc)
self.vessel_flight_bdy = self.conn.add_stream(self.vessel.flight, self.bdy_reference_frame())
self.vessel_sur_speed = self.conn.add_stream(getattr, self.vessel_flight_bdy(), 'speed')
self.latitude = self.conn.add_stream(getattr, self.vessel.flight(), 'latitude')
self.lAz_data = self.azimuth_init()
self.Q = self.conn.add_stream(getattr, self.vessel.flight(), 'dynamic_pressure')
self.pitch = self.conn.add_stream(getattr, self.vessel.flight(), 'pitch')
self.altitude = self.conn.add_stream(getattr, self.vessel.flight(), 'mean_altitude')
self.period = self.conn.add_stream(getattr, self.vessel.orbit, 'period')
self.pitchSet = 90
self.azimuthSet = 90
self.pitchRate = 1.6
self.onInsertionStage = False
self.liftoffTWR = 1.37
self.pitchMode = "ASCENT"
# Calculate spline points for pitch program based on liftoff TWR and target Apogee
p1 = -30000*self.liftoffTWR + 80000
p2 = (7/36) * target_orbit + (25000/9)
self.pitchProgramX = np.array([0,max(p1,p2), target_orbit, target_orbit + 50000])
self.pitchProgramY = np.array([90,45, 0, 0])
self.pitchProgram = np.poly1d(np.polyfit(self.pitchProgramX, self.pitchProgramY, 3))
# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
# S E T H E A D I N G #
# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
def test_poly1d(self, level=rlevel):
# Ticket #28
assert_equal(np.poly1d([1]) - np.poly1d([1, 0]),
np.poly1d([-1, 1]))
def test_poly1d_nan_roots(self, level=rlevel):
# Ticket #396
p = np.poly1d([np.nan, np.nan, 1], r=0)
self.assertRaises(np.linalg.LinAlgError, getattr, p, "r")
def test_poly_div(self, level=rlevel):
# Ticket #553
u = np.poly1d([1, 2, 3])
v = np.poly1d([1, 2, 3, 4, 5])
q, r = np.polydiv(u, v)
assert_equal(q*v + r, u)
def test_poly_eq(self, level=rlevel):
# Ticket #554
x = np.poly1d([1, 2, 3])
y = np.poly1d([3, 4])
assert_(x != y)
assert_(x == x)