def video_efficiency(self, usuario): x_eff_video_1 = array([70.0, 85.0, 100.0]) y_eff_video_1 = array([75.0, 85.0, 100.0]) pol_eff_video_1 = Polynomial.fit(x_eff_video_1, y_eff_video_1, 2) x_eff_video_2 = array([100.0, 150.0, 200.0, 250.0, 300.0]) y_eff_video_2 = array([100.0, 60.0, 30.0, 10.0, 0.0]) pol_eff_video_2 = Polynomial.fit(x_eff_video_2, y_eff_video_2, 2) subject_videos = GqlQuery("SELECT * FROM ViewerVideo") videosAbove70 = 0 videoPoints = 0 for subject_video in subject_videos: userVideo = GqlQuery("SELECT * FROM UserVideo WHERE video = :1 AND user = :2", subject_video.video, usuario.user).get() if(userVideo != None): porcentajeVideo = (userVideo.seconds_watched/userVideo.duration)*100 if(porcentajeVideo > 70): videosAbove70 += 1 if(porcentajeVideo >= 100): videoPoints += pol_eff_video_2(porcentajeVideo) if(porcentajeVideo < 100): videoPoints += pol_eff_video_1(porcentajeVideo) if(videosAbove70 != 0): videoPoints = int(videoPoints/videosAbove70) return videoPoints
def findRootParameters(self, coordinates): left = self.left right = self.right p0 = left.location - coordinates p1 = left.rightHandle - coordinates p2 = right.leftHandle - coordinates p3 = right.location - coordinates a = p3 - 3 * p2 + 3 * p1 - p0 b = 3 * p2 - 6 * p1 + 3 * p0 c = 3 * (p1 - p0) coeffs = [0] * 6 coeffs[0] = c.dot(p0) coeffs[1] = c.dot(c) + b.dot(p0) * 2.0 coeffs[2] = b.dot(c) * 3.0 + a.dot(p0) * 3.0 coeffs[3] = a.dot(c) * 4.0 + b.dot(b) * 2.0 coeffs[4] = a.dot(b) * 5.0 coeffs[5] = a.dot(a) * 3.0 poly = Polynomial(coeffs, [0.0, 1.0], [0.0, 1.0]) roots = poly.roots() realRoots = [float(min(max(root.real, 0), 1)) for root in roots] return realRoots
def phasepol(self, index, rphase=None): """Phase prediction polynomial set up for times in MJD Parameters ---------- index : int index into the polyco table rphase : None or 'fraction' or float phase zero point; if None, use the one stored in polyco. (Those are typically large, so one looses some precision.) Can also set 'fraction' to use the stored one modulo 1, which is fine for folding, but breaks phase continuity between sets. Returns ------- phasepol : Polynomial set up for MJDs between mjd_mid ± span """ domain = np.array([-1, 1]) * self['span'][index]/2 # span is in minutes -> 1/1440 of a day phasepol = Polynomial(self['coeff'][index], domain/1440.+self['mjd_mid'][index], domain) if rphase is None: phasepol.coef[0] += self['rphase'][index] elif rphase in 'fraction': phasepol.coef[0] += self['rphase'][index] % 1 else: phasepol.coef[0] = rphase phasepol.coef[1] += self['f0'][index]*60. return phasepol
def find_roots(coefficients): p = Polynomial(coefficients) print "\nRoots of U(x) with E = %d are:" % fabs(coefficients[0]) for i, r in enumerate(p.roots()): if r.imag != 0.0: sign = "-" if r.imag < 0 else "+" print "x%d: %.1f %s %.1fi" % (i+1, r.real, sign, fabs(r.imag)) else: print "x%d: %.1f" % (i + 1, r.real)
def pwc_function_approximation(linear_piece: P, left_bound, right_bound, error_tolerance): if linear_piece.degree() <= 0: return [linear_piece], [left_bound, right_bound] elif linear_piece.degree() >= 2: print(linear_piece) raise ValueError('The function must be constant or linear.') a = linear_piece.coef[-1] piece_num = math.ceil((math.fabs(a) * (right_bound - left_bound)) / (2 * error_tolerance)) delta_x = (right_bound - left_bound) / piece_num pwc_result = [] bounds_result = [left_bound] for i in range(0, piece_num): pwc_result.append(P([linear_piece(left_bound + (i - 0.5) * delta_x)])) bounds_result.append(left_bound + (i + 1) * delta_x) return pwc_result, bounds_result
def process_pal5_densdata(options): # Read and prep data backg = 400.0 data = numpy.loadtxt("data/ibata_fig7b_raw.dat", delimiter=",") sindx = numpy.argsort(data[:, 0]) data = data[sindx] data_lowerr = numpy.loadtxt("data/ibata_fig7b_rawlowerr.dat", delimiter=",") sindx = numpy.argsort(data_lowerr[:, 0]) data_lowerr = data_lowerr[sindx] data_uperr = numpy.loadtxt("data/ibata_fig7b_rawuperr.dat", delimiter=",") sindx = numpy.argsort(data_uperr[:, 0]) data_uperr = data_uperr[sindx] data_err = 0.5 * (data_uperr - data_lowerr) # CUTS indx = (data[:, 0] > options.minxi - 0.05) * (data[:, 0] < options.maxxi) data = data[indx] data_lowerr = data_lowerr[indx] data_uperr = data_uperr[indx] data_err = data_err[indx] # Compute power spectrum tdata = data[:, 1] - backg pp = Polynomial.fit(data[:, 0], tdata, deg=options.polydeg, w=1.0 / data_err[:, 1]) tdata /= pp(data[:, 0]) ll = data[:, 0] py = signal.csd(tdata, tdata, fs=1.0 / (ll[1] - ll[0]), scaling="spectrum", nperseg=len(ll))[1] py = py.real # Also compute the bispectrum Bspec, Bpx = bispectrum.bispectrum(numpy.vstack((tdata, tdata)).T, nfft=len(tdata), wind=7, nsamp=1, overlap=0) ppyr = numpy.fabs(Bspec[len(Bspec) // 2 + _BISPECIND, len(Bspec) // 2 :].real) ppyi = numpy.fabs(Bspec[len(Bspec) // 2 + _BISPECIND, len(Bspec) // 2 :].imag) return (numpy.sqrt(py * (ll[-1] - ll[0])), data_err[:, 1] / pp(data[:, 0]), ppyr, ppyi)
def process_mock_densdata(options): print ("Using mock Pal 5 data from %s" % options.mockfilename) # Read and prep data for mocks xvid = numpy.loadtxt(options.mockfilename) xv = xvid[:, :6] xv = xv[numpy.argsort(xvid[:, 6])] XYZ = bovy_coords.galcenrect_to_XYZ(xv[:, 0], xv[:, 1], xv[:, 2], Xsun=R0, Zsun=0.025) lbd = bovy_coords.XYZ_to_lbd(XYZ[0], XYZ[1], XYZ[2], degree=True) radec = bovy_coords.lb_to_radec(lbd[:, 0], lbd[:, 1], degree=True) xieta = pal5_util.radec_to_pal5xieta(radec[:, 0], radec[:, 1], degree=True) # make sure the progenitor is at (0,0) xieta[:, 0] -= numpy.median(xieta[:, 0]) xieta[:, 1] -= numpy.median(xieta[:, 1]) h, e = numpy.histogram(xieta[:, 0], range=[0.2, 14.3], bins=141) xdata = numpy.arange(0.25, 14.35, 0.1) # Compute power spectrum tdata = h - 0.0 pp = Polynomial.fit(xdata, tdata, deg=options.polydeg, w=1.0 / numpy.sqrt(h + 1.0)) tdata /= pp(xdata) ll = xdata py = signal.csd(tdata, tdata, fs=1.0 / (ll[1] - ll[0]), scaling="spectrum", nperseg=len(ll))[1] py = py.real # Also compute the bispectrum Bspec, Bpx = bispectrum.bispectrum(numpy.vstack((tdata, tdata)).T, nfft=len(tdata), wind=7, nsamp=1, overlap=0) ppyr = numpy.fabs(Bspec[len(Bspec) // 2 + _BISPECIND, len(Bspec) // 2 :].real) ppyi = numpy.fabs(Bspec[len(Bspec) // 2 + _BISPECIND, len(Bspec) // 2 :].imag) return (numpy.sqrt(py * (ll[-1] - ll[0])), numpy.sqrt(h + 1.0) / pp(xdata), ppyr, ppyi)
def fit_polynomial(data, deg=2): poly = Polynomial.fit(data['alphas'], data['chi2'], deg) if np.isnan(np.min(poly.coef)): print 'RankWarning in fit' return None return poly
class TripleSpline(object): _coeffs=[ [2 / 3.0, 0, -4, 4], [4 / 3.0, -4, 4, -4 / 3.0]] def __init__(self): self.func1=Polynomial(self._coeffs[0]) self.func2=Polynomial(self._coeffs[1]) self.func1_diff=self.func1.deriv() self.func2_diff=self.func2.deriv() self.diff_order=0 def __call__(self,x,result=None): if x<0: raise ValueError('input value should be nonnegative, not '+str(x)) if result is None: result=np.zeros((self._diff_order+1,),dtype=np.double) if x>=1: result.fill(0) return result if x<=0.5: result[0]=self.func1(x) if self.diff_order>=1: result[1]=self.func1_diff(x) else: result[0]=self.func2(x) if self.diff_order>=1: result[1]=self.func2_diff(x) return result def values(self,x,result): return self.__call__(x, result) def set_diff_order(self, diff_order): if diff_order < 0 or diff_order > 1: raise ValueError("only support _diff_order 0/1, not " + str(diff_order)) self._diff_order = diff_order def get_diff_order(self): return self._diff_order diff_order = property(get_diff_order, set_diff_order)
def __init__(self, addr, max_power, power_recv=None): Sensor.__init__(self, addr) power_expected = array([max_power*i/100 for i in xrange(0, 110, 10)]) if power_recv is None: power_recv = power_expected[:] self._poly = Polynomial.fit(power_recv, power_expected, 2) #self.least_squares(power_recv, power_expected) self._conv = interp1d(*self._poly.linspace()) self._min_recv = min(power_recv) self._max_recv = max(power_recv) self._min_pow = min(power_expected) self._max_pow = max(power_expected) self.recv_read = 0 self.SEND_DELAY = 2
def check_fromroots(Poly): # check that requested roots are zeros of a polynomial # of correct degree, domain, and window. d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 r = random((5,)) p1 = Poly.fromroots(r, domain=d, window=w) assert_equal(p1.degree(), len(r)) assert_equal(p1.domain, d) assert_equal(p1.window, w) assert_almost_equal(p1(r), 0) # check that polynomial is monic p2 = Polynomial.cast(p1, domain=d, window=w) assert_almost_equal(p2.coef[-1], 1)
def varying_likelyhood(): number_of_surnames = 10 number_of_surviving_sons = 5 number_of_generations = 10 chance_of_i_surviving_sons = [ 1 / (number_of_surviving_sons + i) for i in range(1, number_of_surviving_sons + 1) ] chance_of_0_surviving_sons = 1 - sum(chance_of_i_surviving_sons) fn = Polynomial([chance_of_0_surviving_sons] + chance_of_i_surviving_sons) plot_graph( fn, number_of_surnames, number_of_generations, "Varying Likelyhood with Number of Surnames = {0} and Number of Surviving Sons = {1}" .format(number_of_surnames, number_of_surviving_sons))
def l(k, x): n = len(x) assert (k < len(x)) x_k = x[k] x_copy = np.delete(x, k) denominator = np.prod(x_copy - x_k) coeff = [] for i in range(n): coeff.append(sum([np.prod(x) for x in combinations(x_copy, i)]) * (-1)**(i) / denominator) coeff.reverse() return Polynomial(coeff)
def calc_quartic_polynomial(start_state, end_state, duration): s0, sd0, sdd0 = start_state s1, sd1, sdd1 = end_state dT1 = duration dT2 = dT1 * dT1 dT3 = dT2 * dT1 x = np.array([[sd1 - sd0 - sdd0 * dT1], [sdd1 - sdd0]]) A = np.array([[3 * dT2, 4 * dT3], [6 * dT1, 12 * dT2]]) coeffs1 = np.array([s0, sd0, 0.5 * sdd0]) coeffs2 = np.dot(np.linalg.inv(A), x) return Polynomial( np.concatenate((coeffs1, coeffs2.reshape((2, ))), axis=0))
def get_fitness_function_polynomial(): """ Returns a polynomial function p that can be used to calculate the expected tumour volume at a time t, 0 <= t <= 300. The time is expressed in DAYS. Eg: p(2) returns the expected volume at day 2. Returns ------- Polynomial The polynomial function. """ xs = [0, 13, 24] ys = [0, 50, 150] p = Polynomial.fit(xs, ys, 2) return p
def poisson_distribution(): number_of_surnames = 10 number_of_surviving_sons = 5 mean_number_of_surviving_sons = 1 number_of_generations = 10 chance_of_i_surviving_sons = [ poisson.pmf(i, mean_number_of_surviving_sons) for i in range(0, number_of_surviving_sons + 1) ] fn = Polynomial(chance_of_i_surviving_sons) plot_graph( fn, number_of_surnames, number_of_generations, "Poisson Distribution with Number of Surnames = {0} and Number of Surviving Sons = {1}" .format(number_of_surnames, number_of_surviving_sons))
def _calculate_hif_expression_rate_from_oxygen_warburg( self, oxygen_at_pos): if oxygen_at_pos > self.oxygen_warburg_hypoxic_domain: return self.min_hif if oxygen_at_pos > self.oxygen_ultra_hypoxic_domain: coef = self.oxygen_to_hif_coeffs_hypoxic_warburg domain = [ self.oxygen_ultra_hypoxic_domain, self.oxygen_warburg_hypoxic_domain ] else: coef = self.oxygen_to_hif_coeffs_ultra_hypoxic domain = [0.0, self.oxygen_ultra_hypoxic_domain] p = Polynomial(coef=coef, domain=domain) return p(oxygen_at_pos)
def estimate_polyfit(x, y, labels): """ NOT USED - Experiments """ ## x is a list of numpy arrays ## y is a list of numpy arrays ## labels is a list of strings fig, ax = plt.subplots(dpi=150) ax.set_xlabel('Number of Samples') ax.set_ylabel(r'$|A_{it} - A_{is}|$') plt.title('Polynomial Fit of Convergence') for i in range(0, len(labels)): p = Polynomial.fit(x[i], y[i], 5) plt.plot(*p.linspace(), label=labels[i]) # print('Slope of ', labels[i], ' at 100 ', slope(p, 100)) plt.legend() plt.show()
def process_pal5_densdata(options): # Read and prep data backg = 400. data = numpy.loadtxt('data/ibata_fig7b_raw.dat', delimiter=',') sindx = numpy.argsort(data[:, 0]) data = data[sindx] data_lowerr = numpy.loadtxt('data/ibata_fig7b_rawlowerr.dat', delimiter=',') sindx = numpy.argsort(data_lowerr[:, 0]) data_lowerr = data_lowerr[sindx] data_uperr = numpy.loadtxt('data/ibata_fig7b_rawuperr.dat', delimiter=',') sindx = numpy.argsort(data_uperr[:, 0]) data_uperr = data_uperr[sindx] data_err = 0.5 * (data_uperr - data_lowerr) # CUTS indx = (data[:, 0] > options.minxi - 0.05) * (data[:, 0] < options.maxxi) data = data[indx] data_lowerr = data_lowerr[indx] data_uperr = data_uperr[indx] data_err = data_err[indx] # Compute power spectrum tdata = data[:, 1] - backg pp = Polynomial.fit(data[:, 0], tdata, deg=options.polydeg, w=1. / data_err[:, 1]) tdata /= pp(data[:, 0]) ll = data[:, 0] py = signal.csd(tdata, tdata, fs=1. / (ll[1] - ll[0]), scaling='spectrum', nperseg=len(ll))[1] py = py.real # Also compute the bispectrum Bspec, Bpx = bispectrum.bispectrum(numpy.vstack((tdata, tdata)).T, nfft=len(tdata), wind=7, nsamp=1, overlap=0) ppyr = numpy.fabs(Bspec[len(Bspec) // 2 + _BISPECIND, len(Bspec) // 2:].real) ppyi = numpy.fabs(Bspec[len(Bspec) // 2 + _BISPECIND, len(Bspec) // 2:].imag) return (numpy.sqrt(py * (ll[-1] - ll[0])), data_err[:, 1] / pp(data[:, 0]), ppyr, ppyi)
def check_fromroots(Poly): # check that requested roots are zeros of a polynomial # of correct degree, domain, and window. d = Poly.domain + random((2, )) * .25 w = Poly.window + random((2, )) * .25 r = random((5, )) p1 = Poly.fromroots(r, domain=d, window=w) assert_equal(p1.degree(), len(r)) assert_equal(p1.domain, d) assert_equal(p1.window, w) assert_almost_equal(p1(r), 0) # check that polynomial is monic pdom = Polynomial.domain pwin = Polynomial.window p2 = Polynomial.cast(p1, domain=pdom, window=pwin) assert_almost_equal(p2.coef[-1], 1)
def process_mock_densdata(options): print("Using mock Pal 5 data from %s" % options.mockfilename) # Read and prep data for mocks xvid = numpy.loadtxt(options.mockfilename) xv = xvid[:, :6] xv = xv[numpy.argsort(xvid[:, 6])] XYZ = bovy_coords.galcenrect_to_XYZ(xv[:, 0], xv[:, 1], xv[:, 2], Xsun=R0, Zsun=0.025) lbd = bovy_coords.XYZ_to_lbd(XYZ[0], XYZ[1], XYZ[2], degree=True) radec = bovy_coords.lb_to_radec(lbd[:, 0], lbd[:, 1], degree=True) xieta = pal5_util.radec_to_pal5xieta(radec[:, 0], radec[:, 1], degree=True) # make sure the progenitor is at (0,0) xieta[:, 0] -= numpy.median(xieta[:, 0]) xieta[:, 1] -= numpy.median(xieta[:, 1]) h, e = numpy.histogram(xieta[:, 0], range=[0.2, 14.3], bins=141) xdata = numpy.arange(0.25, 14.35, 0.1) # Compute power spectrum tdata = h - 0. pp = Polynomial.fit(xdata, tdata, deg=options.polydeg, w=1. / numpy.sqrt(h + 1.)) tdata /= pp(xdata) ll = xdata py = signal.csd(tdata, tdata, fs=1. / (ll[1] - ll[0]), scaling='spectrum', nperseg=len(ll))[1] py = py.real # Also compute the bispectrum Bspec, Bpx = bispectrum.bispectrum(numpy.vstack((tdata, tdata)).T, nfft=len(tdata), wind=7, nsamp=1, overlap=0) ppyr = numpy.fabs(Bspec[len(Bspec) // 2 + _BISPECIND, len(Bspec) // 2:].real) ppyi = numpy.fabs(Bspec[len(Bspec) // 2 + _BISPECIND, len(Bspec) // 2:].imag) return (numpy.sqrt(py * (ll[-1] - ll[0])), numpy.sqrt(h + 1.) / pp(xdata), ppyr, ppyi)
def gen_C0(Ramanshift, norm_pnt): '''Ramanshift = vector, the x-axis in wavenumbers norm_pnt = normalization point (corrections will be set to unity at this point) ''' spacing = np.diff(Ramanshift) # normalization wavenum_corr = spacing / spacing[norm_pnt] temp_xaxis = np.arange(spacing.shape[0]) # fitting the wavenumber diff c = Polynomial.fit(temp_xaxis, wavenum_corr, deg=3) # extrpolate the last point wavenum_corr = np.append(wavenum_corr, c(spacing.shape[0] + 1)) return wavenum_corr
def linear_fit(sub_edf, timeline, fdr): lin_fit = [] for k in range(len(sub_edf)): x_time = [] y_val = [] for i in range(len(sub_edf[k])): t = timeline[fdr[k][i][1]] x_time.append(t) y_val.append(sub_edf[k][i]) p = P.fit(x_time, y_val, 3) lin_fit.append(p) return lin_fit
def xi_csd(d, bins=np.linspace(-15, 0, 150), nbg=0., binned=False): from scipy import signal from numpy.polynomial import Polynomial np.random.seed(42) if binned == False: actcounts, bins = np.histogram(d, bins=bins) counts = actcounts + np.random.poisson(nbg, size=len(d)) else: counts = d + np.random.poisson(nbg, size=len(d)) counts = np.maximum(counts - nbg, np.zeros_like(counts)) centroids = (bins[1:] + bins[:-1]) / 2. err = np.sqrt(counts + nbg) #*(counts/actcounts) bkg = 0 degree = 1 pp = Polynomial.fit(centroids, counts, degree, w=1. / numpy.sqrt(counts + 1.)) tdata = counts / pp(centroids) terr = err / pp(centroids) px, py = signal.csd(tdata, tdata, fs=1. / (centroids[1] - centroids[0]), scaling='spectrum', nperseg=len(centroids)) py = py.real px = 1. / px py = numpy.sqrt(py * (centroids[-1] - centroids[0])) nerrsim = 1000 ppy_err = numpy.empty((nerrsim, len(px))) for ii in range(nerrsim): tmock = terr * numpy.random.normal(size=len(centroids)) ppy_err[ii] = signal.csd(tmock, tmock, fs=1. / (centroids[1] - centroids[0]), scaling='spectrum', nperseg=len(centroids))[1].real py_err = numpy.sqrt( numpy.median(ppy_err, axis=0) * (centroids[-1] - centroids[0])) np.save('/Users/hendel/Desktop/pscrosscheck_xi_csd.npy', (d, bins, counts, tdata, terr, px, py, py_err)) return px, py, py_err
def poly(p): """Obtention du polynome représentant un entier entre 0 et 255 Fonction renvoyant le polynome associé à la représentation en base 2 d'un entier. Parameters ---------- p : int entier compris entre 0 et 255 Returns ------- Polynomial polynome associé à la représentation de l'entier """ t = bin(p)[2:] mat_p = [] for e in t: mat_p = [int(e)] + mat_p return Polynomial(mat_p)
def test_divmod(Poly): # This checks commutation, not numerical correctness c1 = list(random((4, )) + .5) c2 = list(random((3, )) + .5) c3 = list(random((2, )) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = Poly(c3) p4 = p1 * p2 + p3 c4 = list(p4.coef) quo, rem = divmod(p4, p2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(p4, c2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(c4, p2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(p4, tuple(c2)) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(tuple(c4), p2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(p4, np.array(c2)) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(np.array(c4), p2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(p2, 2) assert_poly_almost_equal(quo, 0.5 * p2) assert_poly_almost_equal(rem, Poly([0])) quo, rem = divmod(2, p2) assert_poly_almost_equal(quo, Poly([0])) assert_poly_almost_equal(rem, Poly([2])) assert_raises(TypeError, divmod, p1, Poly([0], domain=Poly.domain + 1)) assert_raises(TypeError, divmod, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, divmod, p1, Chebyshev([0])) else: assert_raises(TypeError, divmod, p1, Polynomial([0]))
def check_add(Poly): # This checks commutation, not numerical correctness c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = p1 + p2 assert_poly_almost_equal(p2 + p1, p3) assert_poly_almost_equal(p1 + c2, p3) assert_poly_almost_equal(c2 + p1, p3) assert_poly_almost_equal(p1 + tuple(c2), p3) assert_poly_almost_equal(tuple(c2) + p1, p3) assert_poly_almost_equal(p1 + np.array(c2), p3) assert_poly_almost_equal(np.array(c2) + p1, p3) assert_raises(TypeError, p1.__add__, Poly([0], domain=Poly.domain + 1)) assert_raises(TypeError, p1.__add__, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, p1.__add__, Chebyshev([0])) else: assert_raises(TypeError, p1.__add__, Polynomial([0]))
def test_sub(Poly): # This checks commutation, not numerical correctness c1 = list(random((4, )) + .5) c2 = list(random((3, )) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = p1 - p2 assert_poly_almost_equal(p2 - p1, -p3) assert_poly_almost_equal(p1 - c2, p3) assert_poly_almost_equal(c2 - p1, -p3) assert_poly_almost_equal(p1 - tuple(c2), p3) assert_poly_almost_equal(tuple(c2) - p1, -p3) assert_poly_almost_equal(p1 - np.array(c2), p3) assert_poly_almost_equal(np.array(c2) - p1, -p3) assert_raises(TypeError, op.sub, p1, Poly([0], domain=Poly.domain + 1)) assert_raises(TypeError, op.sub, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, op.sub, p1, Chebyshev([0])) else: assert_raises(TypeError, op.sub, p1, Polynomial([0]))
def nce_temperature(poly_coeff, logR, wl_v0, wl_v1, wl_binm, wl_binM, wl_min, wl_max): ''' Function: nce_temperature Calculates the temperature based on a Non-Constant Emissivity (NCE). The emissivity is modeled with a Chebyshev polynomial of order N where N is determined by a separate routine Inputs: - Outputs: - Predicted temperature from averaging (K) - Standard deviation (K) - Standard deviation (%) ''' # Create a polynomial representation with the proposed coefficients # Rescaling is done internally by providing the bounds l_min and l_max domain = np.array([wl_min, wl_max]) pol = Polynomial(poly_coeff, domain) # Calculate the emissivities at the corresponding wavelengths eps1 = polynomial.polyval(wl_v1, pol.coef) eps0 = polynomial.polyval(wl_v0, pol.coef) ### Inverse temperature try: invT = logR - 5 * np.log(wl_v1 / wl_v0) - np.log(eps0 / eps1) ### Temperature Tout = 1 / invT Tout *= sc.C2 * (1 / wl_v1 - 1 / wl_v0) ### Returns # Tout = Tout[Tout>0] Tave, Tstd, Tmetric, Tleft = tukey_fence(Tout) # print('Coeffs: ', poly_coeff, '\t p-value:',normaltest(Tleft)[1]) except: Tave, Tstd, Tmetric = 1e5 * np.ones(3) return Tave, Tstd, Tmetric
def exercise_progress(self, usuario): x_vid = array([0.0, 25.0, 50.0, 75.0, 100.0]) y_vid = array([0.0, 40.0, 65.0, 85.0, 100.0]) pol_exercise_progress = Polynomial.fit(x_vid, y_vid, 5) subject_exercises = GqlQuery("SELECT * FROM ViewerExercise") exercise_progress = 0 for subject_exercise in subject_exercises: userExercise = GqlQuery("SELECT * FROM UserExercise WHERE exercise_model = :1 AND user = :2", subject_exercise.exercise, usuario.user).get() if(userExercise != None): if(userExercise._progress == 1.0): exercise_progress += 100 else: exercise_progress += pol_exercise_progress(userExercise._progress*100) return int(exercise_progress/subject_exercises.count())
def test_mul(Poly): c1 = list(random((4, )) + .5) c2 = list(random((3, )) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = p1 * p2 assert_poly_almost_equal(p2 * p1, p3) assert_poly_almost_equal(p1 * c2, p3) assert_poly_almost_equal(c2 * p1, p3) assert_poly_almost_equal(p1 * tuple(c2), p3) assert_poly_almost_equal(tuple(c2) * p1, p3) assert_poly_almost_equal(p1 * np.array(c2), p3) assert_poly_almost_equal(np.array(c2) * p1, p3) assert_poly_almost_equal(p1 * 2, p1 * Poly([2])) assert_poly_almost_equal(2 * p1, p1 * Poly([2])) assert_raises(TypeError, op.mul, p1, Poly([0], domain=Poly.domain + 1)) assert_raises(TypeError, op.mul, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, op.mul, p1, Chebyshev([0])) else: assert_raises(TypeError, op.mul, p1, Polynomial([0]))
def test_normalize(): w = np.arange(4000., 5000., 10.) coeff = [1., 0.1, 0.1] pol = Polynomial(coeff) obs_spectrum = Spectrum1D.from_array(w, pol(w), dispersion_unit=u.AA, unit='erg/(cm^2 s Angstrom)') norm = Normalize(obs_spectrum, npol=3) model = Spectrum1D.from_array(w, np.ones_like(w), dispersion_unit=u.AA, unit='erg/(cm^2 s Angstrom)') fit = norm(model) npt.assert_allclose(fit.flux.value, obs_spectrum.flux.value) npt.assert_allclose(norm.polynomial(obs_spectrum.wavelength.value), obs_spectrum.flux.value) npt.assert_allclose(norm.polynomial.convert().coef, np.array(coeff + [0.]), rtol=1e-5, atol=1.e-10)
def env_residual_rms(env, xs, ys): """Calculate the RMS of the envelope fit residuals Parameters ---------- env : np.ndarray envelope parameters (polynomial coefficients) xs : list x values for the envelope fit ys : list y values for the envelope fit Returns ------- float """ xs = np.asarray(xs) ys = np.asarray(ys) resids = Polynomial(env)(xs) - ys return np.std(resids)
def test_normalize_parts(): w = np.arange(4000., 5000., 10.) coeff = [1., 0.1, 0.1] pol = Polynomial(coeff) obs_spectrum = Spectrum1D.from_array(w, pol(w), dispersion_unit=u.AA) parts = [slice(0, 30), slice(30, None)] norm_parts = NormalizeParts(obs_spectrum, parts, npol=[3, 3]) model = Spectrum1D.from_array(w, np.ones_like(w), dispersion_unit=u.AA) fit = norm_parts(model) nptesting.assert_allclose(fit.flux.value, obs_spectrum.flux.value) for normalizer in norm_parts.normalizers: nptesting.assert_allclose(normalizer.polynomial.convert().coef, np.array(coeff + [0.]), rtol=1e-3, atol=1.e-5) # try also with boolean arrays parts = [np.where(w < 4400.), np.where(w >= 4400.)] norm_parts = NormalizeParts(obs_spectrum, parts, npol=[3, 3]) model = Spectrum1D.from_array(w, np.ones_like(w), dispersion_unit=u.AA) fit = norm_parts(model) nptesting.assert_allclose(fit.flux, obs_spectrum.flux) for normalizer in norm_parts.normalizers: nptesting.assert_allclose(normalizer.polynomial.convert().coef, np.array(coeff + [0.]), rtol=1e-3, atol=1.e-5)
def approx_legendre_poly(Moments): n_moments = Moments.shape[0]-1 exp_coef = (np.zeros((1))) # For method description see, for instance: # Chapter 3 of "The Problem of Moments", James Alexander Shohat, Jacob David Tamarkin for i in range(n_moments+1): p = Legendre.basis(i).convert(window = [0.0,1.0], kind=Polynomial) q = (2*i+1)*np.sum(Moments[0:(i+1)]*p.coef) pq = (p.coef*q) exp_coef = polynomial.polyadd(exp_coef, pq) expansion = Polynomial(exp_coef) return expansion
def get_hif_to_p_synthesis(self, degree=1, render=False): """ Returns coefficients for hif to probability of synthesis. The domain of the function is [0, maxHIF]. Parameters ---------- degree : int, optional Degree of the generated polynomial. Optional, defaults to 1. render : bool, optional If set to true, will display the generated function Returns ------- list Function coefficients """ points = [(0, self.min_p_synthesis), (self.max_hif, 1)] xs = [p[0] for p in points] ys = [p[1] for p in points] p = Polynomial.fit(xs, ys, degree) # Getting data to reproduce polynomials, use of sort: # p = Polynomial(coef=[list of coeffs], domain=[xstart, xend] if render: plt.plot(*p.linspace(), label="Fit", color="orange") plt.scatter(xs, ys, label="Raw Points") plt.legend() plt.xlabel("HIF Expression Rates") plt.ylabel("Probability Synthesis") plt.title("Probability of Synthesis across HIF Expression Rates") plt.show() return [round(c, 2) for c in list(p.coef)]
def video_progress(self, usuario): x_vid = array([0.0, 50.0, 75.0, 100.0]) y_vid = array([0.0, 30.0, 55.0, 100.0]) pol_video_progress = Polynomial.fit(x_vid, y_vid, 5) total_video_progress = 0 subject_videos = GqlQuery("SELECT * FROM ViewerVideo") for subject_video in subject_videos: userVideo = GqlQuery("SELECT * FROM UserVideo WHERE video = :1 AND user = :2", subject_video.video, usuario.user).get() if(userVideo != None): porcentajeVideo = (userVideo.seconds_watched/userVideo.duration)*100 if(porcentajeVideo >= 100): total_video_progress += 100 else: total_video_progress += pol_video_progress(porcentajeVideo) return int(total_video_progress/subject_videos.count())
def detrend_dates(df): """ Build a model to detrend log10(nratings) vs date published, since older books have more ratings. """ numerical_data = df[~df['pub_date'].isna()] numerical_data['pub_date'] = pd.to_datetime(numerical_data['pub_date'], errors='coerce').dt.date x = numerical_data['pub_date'] - datetime.date(1954, 1, 1) y = np.log10(numerical_data['nratings']) x = x.dt.days x = x.fillna(0) mask = (x >= 0) & (x < x.max()) maxday = x[mask].max() x = x.values / x[mask].max() numerical_data = numerical_data[mask] from numpy.polynomial import Polynomial p = Polynomial.fit(x[mask], y[mask], 6) xp, yp = p.linspace() np.save("trained_models/maxday.npy", maxday) np.save("trained_models/daypolyfit.npy", [xp, yp])
def parabola(initial_trajectory, speed): """ Find the quadratic form of the parabolic path Parameters ---------- initial_trajectory : float The initial angular trajectory of the path (degrees), measured from the x-axis. A positive angle is in an anticlockwise direction. speed : float The initial speed of the object (m/s) Returns ------- eqn : np.polynomial.Polynomial object Equation of parabolic path """ traj_rad = np.radians(initial_trajectory) eqn = Polynomial([ 0, np.tan(traj_rad), -constants.g / 2. / (speed * np.cos(traj_rad))**2. ]) return eqn
def evaluate(self, wavelength, flux): # V[:,0]=mfi/e, Vp[:,1]=mfi/e*w, .., Vp[:,npol]=mfi/e*w**npol V = self._Vp * (flux / self.observed.uncertainty.value)[:, np.newaxis] # normalizes different powers scl = np.sqrt((V * V).sum(0)) if np.isfinite(scl[0]): # check for validity before evaluating sol, resids, rank, s = np.linalg.lstsq(V / scl, self.signal_to_noise, self._rcond) sol = (sol.T / scl).T if rank != self._Vp.shape[-1] - 1: msg = "The fit may be poorly conditioned" warnings.warn(msg) fit = np.dot(V, sol) * self.observed.uncertainty.value # keep coefficients in case the outside wants to look at it self.polynomial = Polynomial(sol, domain=self.domain.value, window=self.window.value) return wavelength, fit else: return wavelength, flux
def gradeSchoolParallel(poly1, poly2): pRes = Polynomial( [0 for _ in range(len(poly1.coef) + len(poly2.coef) - 1)]) nrWorkers = 4 step = len(poly1.coef) // nrWorkers stepRemainder = len(poly1.coef) % nrWorkers threads = [] for x in range(nrWorkers): if stepRemainder != 0: t = Thread(target=singleMultiplication, args=(poly1, poly2, pRes, x * (step + 1), (x + 1) * (step + 1))) stepRemainder -= 1 else: t = Thread(target=singleMultiplication, args=(poly1, poly2, pRes, x * step + len(poly1.coef) % nrWorkers, (x + 1) * step + len(poly1.coef) % nrWorkers)) t.start() threads.append(t) for t in threads: t.join() return pRes
def initial_exploration(df): """ Plot some basic quantities from the works dataframe. """ sns.pairplot( df[["rating", "nratings", "nreviews", "to_read", "favs", "dnf"]]) plt.savefig("eda/pairplot.png") plt.clf() sns.kdeplot(np.log10(np.clip(df['nratings'], 1, None)), df['rating'], shade=True, shade_lowest=False) plt.xlabel("log10(nratings)") plt.savefig("eda/ratings_dist.png") plt.clf() mask = np.log10(df['nratings']) > 3 sns.regplot(np.log10(df['nratings'][mask]), df['rating'][mask]) plt.xlabel("log(nratings)") plt.savefig("eda/ratings_scaling.png") plt.clf() mask = df['pubyear'] > 2010 x = df['pubyear'][mask] y = np.log10(np.clip(df['nratings'][mask], 1, None)) from numpy.polynomial import Polynomial p = Polynomial.fit(x, y, 4) sns.boxplot(df['pubyear'][mask].astype(int), np.log10(df['nratings'][mask])) xp, yp = p.linspace() maskp = xp > 2010.5 xp -= 2011 plt.plot(xp[maskp], yp[maskp], color='black', lw=3) plt.xlim((plt.gca().get_xlim()[0], plt.gca().get_xlim()[1] - 1)) plt.ylabel("log10(nratings)") plt.savefig("eda/nratings_year_scaling.png") plt.clf()
def ls_american_option_quadratic_iter(X, t, r, strike): # given no prior exercise we just receive the payoff of a European option cashflow = np.maximum(strike - X[-1, :], 0.0) # iterating backwards in time for i in reversed(range(1, X.shape[0] - 1)): # discount factor between t[i] and t[i+1] df = np.exp(-r * (t[i + 1] - t[i])) # discount cashflows from next period cashflow = cashflow * df x = X[i, :] # exercise value for time t[i] exercise = np.maximum(strike - x, 0.0) # boolean index of all in-the-money paths itm = exercise > 0 # fit polynomial of degree 2 fitted = Polynomial.fit(x[itm], cashflow[itm], 2) # approximate continuation value continuation = fitted(x) # boolean index where exercise is beneficial ex_idx = itm & (exercise > continuation) # update cashflows with early exercises cashflow[ex_idx] = exercise[ex_idx] yield cashflow, x, fitted, continuation, exercise, ex_idx
def getCafeExptime(swasp_id, vmag): V=np.arange(8,14.0,0.5) t=np.array([30,120,300,900,2700]) snr=defaultdict(list) snr[8.] = np.array([23.381,46.762,73.937,128.063,221.812]) snr[8.5] = np.array([18.572,37.144,58.731,101.724,176.192]) snr[9.] = np.array([15.306,30.612,48.402,83.835,145.206]) snr[9.5] = np.array([12.158,24.316,38.447,66.592,115.341]) snr[10.] = np.array([9.657,19.315,30.540,52.896,91.619]) snr[10.5] = np.array([7.671,15.342,24.258,42.017,72.776]) snr[11.] = np.array([6.093,12.817,19.269,33.375,57.807]) snr[11.5] = np.array([4.840,9.680,15.306,26.511,45.918]) snr[12.] = np.array([3.844,7.689,12.158,21.058,36.474]) snr[12.5] = np.array([3.05,6.108,9.657,16.727,28.972]) snr[13.] = np.array([2.426,4.852,7.671,13.287,23.014]) snr[13.5] = np.array([1.923,3.854,6.093,10.554,18.280]) coeffs_store=defaultdict(list) for i in sorted(snr.keys()): coeffs=np.polyfit(t,snr[i],2) coeffs_store[i]=coeffs tn=np.arange(30,3060,60) besty=np.polyval(coeffs,tn) diff=V-vmag n=np.where(abs(diff)==min(abs(diff)))[0][0] p=P.fit(t,snr[V[n]],2) t1,t2=(p-args.snr).roots() if t1<t2: predicted=t1.real else: predicted=t2.real print('Predicted exptime {0:.2f}'.format(predicted)) # round to the nearest 60 predicted = int(math.ceil(predicted/60))*60 print('Rounding up to nearest 60s {0:d}'.format(predicted)) # check for texp>2700, scale to right number of # spectra to get required SNR if predicted > 2700: print('Predicted time > 2700s, looking for good combo of spectra') snr_max = snr[V[n]][-1] print('SNR_max @ 2700 = {0:.2f}'.format(snr_max)) n_spectra = (args.snr/snr[V[n]][-1])**2 print('This needs {0:.2f} spectra @ 2700'. format(n_spectra)) n_spectra = math.ceil(n_spectra) print('Rounding up to next integer n_spectra = {0:d}'.format(n_spectra)) # now work out the best exptime to use to combine # n_spectra spectra to get the desired args.snr target_single_spectra_snr = args.snr/math.sqrt(n_spectra) print('Working out the target SNR per spectra...') print('To achive SNR_total = {0:d} we need {1:d} spectra of SNR_i = {2:.2f}'.format(args.snr, n_spectra, target_single_spectra_snr)) snr_range = np.polyval(coeffs_store[V[n]], tn) diff_ss_snr = abs(snr_range - target_single_spectra_snr) loc_ss_snr = np.where(diff_ss_snr == min(diff_ss_snr))[0][0] predicted = tn[loc_ss_snr] print('The best exposure time for this combination of spectra is {0:d} x {1:d}s'.format(n_spectra, predicted)) elif predicted < 0: predicted = 60 n_spectra=1 else: n_spectra=1 print("{0:s} {1:.2f} {2:d} x {3:.2f}s".format(swasp_id,vmag,n_spectra,predicted)) return n_spectra, predicted
A = [3.9, 4.0, 4.1, 4.2] E = [] for a in A: name = 'bulk-fcc-%.1f' % a b = a / 2 bulk = Atoms('Al', cell=[[0, b, b], [b, 0, b], [b, b, 0]], pbc=True) k = 4 calc = GPAW(mode=PW(300), # cutoff kpts=(k, k, k), # k-points txt=name + '.txt') # output file bulk.set_calculator(calc) energy = bulk.get_potential_energy() calc.write(name + '.gpw') E.append(energy) p = Polynomial.fit(A, E, 3) a0 = p.deriv(1).roots()[0] B = p.deriv(2)(a0) * 4 / 9 / a0 / u.J * u.m**3 * 1e-9 # GPa print((a0, B)) assert abs(a0 - 3.9924) < 0.001 assert abs(B - 87.22) < 0.1
def polfit_residuals( x, y, deg, reject=None, color='b', size=75, xlim=None, ylim=None, xlabel=None, ylabel=None, title=None, use_r=False, debugplot=0): """Polynomial fit with display of residuals and additional work with R. Parameters ---------- x : 1d numpy array, float X coordinates of the data being fitted. y : 1d numpy array, float Y coordinates of the data being fitted. deg : int Degree of the fitting polynomial. reject : None or 1d numpy array (bool) If not None, it must be a boolean array indicating whether a particular point is rejected or not (i.e., the rejected points are flagged as True in this array). Rejected points are displayed but not used in the fit. color : single character or 1d numpy array of characters Color for all the symbols (single character) or for each individual symbol (array of color names with the same length as 'x' or 'y'). If 'color' is a single character, the rejected points are displayed in red color, whereas when 'color' is an array of color names, rejected points are displayed with the color provided in this array. size : int Marker size for all the symbols (single character) or for each individual symbol (array of integers with the same length as 'x' or 'y'). xlim : tuple (floats) Plot limits in the X axis. ylim : tuple (floats) Plot limits in the Y axis. xlabel : string Character string for label in X axis. ylabel : string Character string for label in y axis. title : string Character string for graph title. use_r : bool If True, the function computes several fits, using R, to polynomials of degree deg, deg+1 and deg+2 (when possible). debugplot : int Determines whether intermediate computations and/or plots are displayed: 00 : no debug, no plots 01 : no debug, plots without pauses 02 : no debug, plots with pauses 10 : debug, no plots 11 : debug, plots without pauses 12 : debug, plots with pauses Return ------ poly : instance of Polynomial (numpy) Result from the polynomial fit using numpy Polynomial. Only points not flagged as rejected are employed in the fit. yres : 1d numpy array, float Residuals from polynomial fit. Note that the residuals are computed for all the points, including the rejected ones. In this way the dimension of this array is the same as the dimensions of the input 'x' and 'y' arrays. """ # protections if type(x) is not np.ndarray: raise ValueError("x=" + str(x) + " must be a numpy.ndarray") elif x.ndim != 1: raise ValueError("x.ndim=" + str(x.ndim) + " must be 1") if type(y) is not np.ndarray: raise ValueError("y=" + str(y) + " must be a numpy.ndarray") elif y.ndim != 1: raise ValueError("y.ndim=" + str(y.ndim) + " must be 1") npoints = x.size if npoints != y.size: raise ValueError("x.size != y.size") if reject is not None: if npoints != reject.size: raise ValueError("x.size != reject.size") if type(deg) not in [np.int, np.int64]: raise ValueError("deg=" + str(deg) + " is not a valid integer") # select points for fit if reject is None: xfitted = np.copy(x) yfitted = np.copy(y) xrejected = None yrejected = None nfitted = npoints nrejected = 0 else: xfitted = x[np.logical_not(reject)] yfitted = y[np.logical_not(reject)] xrejected = x[reject] yrejected = y[reject] # update number of points for fit nfitted = xfitted.size nrejected = sum(reject) if deg > nfitted - 1: raise ValueError("Insufficient nfitted=" + str(nfitted) + " for deg=" + str(deg)) # polynomial fits using R if use_r: from ..rutilities import LinearModelYvsX print("\n>>> Total number of points:", nfitted) # using orthogonal polynomials for delta_deg in [2, 1, 0]: deg_eff = deg + delta_deg if deg_eff <= nfitted - 1: myfit = LinearModelYvsX(x=xfitted, y=yfitted, degree=deg_eff, raw=False) print(">>> Fit with R, using orthogonal polynomials:") print(myfit.summary) pause_debugplot(debugplot) # fit using raw polynomials myfit = LinearModelYvsX(x=xfitted, y=yfitted, degree=deg, raw=True) print(">>> Fit with R, using raw polynomials:") print(myfit.summary) pause_debugplot(debugplot) # fit with requested degree (and raw polynomials) poly = Polynomial.fit(x=xfitted, y=yfitted, deg=deg) poly = Polynomial.cast(poly) # compute residuals yres = y - poly(x) # of all the points yres_fitted = yfitted - poly(xfitted) # points employed in the fit yres_rejected = None if nrejected > 0: yres_rejected = yrejected - poly(xrejected) # points rejected if debugplot >= 10: print(">>> Polynomial fit:\n", poly) if debugplot % 10 != 0: # define colors, markers and sizes for symbols if np.array(color).size == 1: mycolor = np.array([color] * npoints) if reject is not None: mycolor[reject] = 'r' elif np.array(color).size == npoints: mycolor = np.copy(np.array(color)) elif np.array(color).shape[0] == npoints: # assume rgb color mycolor = np.copy(np.array(color)) else: raise ValueError("color=" + str(color) + " doesn't have the expected dimension") if np.array(size).size == 1: mysize = np.repeat([size], npoints) elif np.array(size).size == npoints: mysize = np.copy(np.array(size)) else: raise ValueError("size=" + str(size) + " doesn't have the expected dimension") if reject is None: cfitted = np.copy(mycolor) crejected = None sfitted = np.copy(mysize) srejected = None else: cfitted = mycolor[np.logical_not(reject)] crejected = mycolor[reject] sfitted = mysize[np.logical_not(reject)] srejected = mysize[reject] import matplotlib matplotlib.use('Qt4Agg') import matplotlib.pyplot as plt fig = plt.figure() # residuals ax2 = fig.add_subplot(2, 1, 2) if xlabel is None: ax2.set_xlabel('x') else: ax2.set_xlabel(xlabel) ax2.set_ylabel('residuals') if xlim is None: xmin = min(x) xmax = max(x) dx = xmax - xmin xmin -= dx/20 xmax += dx/20 else: xmin, xmax = xlim ax2.set_xlim([xmin, xmax]) ymin = min(yres_fitted) ymax = max(yres_fitted) dy = ymax - ymin ymin -= dy/20 ymax += dy/20 ax2.set_ylim([ymin, ymax]) ax2.axhline(y=0.0, color="black", linestyle="dashed") ax2.scatter(xfitted, yres_fitted, color=cfitted, marker='o', edgecolor='k', s=sfitted) if nrejected > 0: ax2.scatter(xrejected, yres_rejected, marker='x', s=srejected, color=crejected) # original data and polynomial fit ax = fig.add_subplot(2, 1, 1, sharex=ax2) if ylabel is None: ax.set_ylabel('y') else: ax.set_ylabel(ylabel) ax.set_xlim([xmin, xmax]) if ylim is None: ymin = min(y) ymax = max(y) dy = ymax - ymin ymin -= dy/20 ymax += dy/20 else: ymin, ymax = ylim ax.set_ylim([ymin, ymax]) ax.scatter(xfitted, yfitted, color=cfitted, marker='o', edgecolor='k', s=sfitted, label="fitted data") xpol = np.linspace(start=xmin, stop=xmax, num=1000) ypol = poly(xpol) ax.plot(xpol, ypol, 'c-', label="fit") if nrejected > 0: ax.scatter(xrejected, yrejected, marker='x', s=srejected, color=crejected, label="rejected") # shrink axes and put a legend box = ax2.get_position() ax2.set_position([box.x0, box.y0, box.width, box.height * 0.92]) delta_ybox = box.height*0.15 box = ax.get_position() ax.set_position([box.x0, box.y0 - delta_ybox, box.width, box.height * 0.92]) ax.legend(loc=3, bbox_to_anchor=(0.0, 1.1, 1., 0.07), mode="expand", borderaxespad=0., ncol=4, numpoints=1) # graph title if title is not None: plt.title(title + "\n\n") plt.show(block=False) plt.pause(0.001) pause_debugplot(debugplot) # return result return poly, yres
def Phi(P): return 3 * X * P.deriv() - (1 - X**2) * P.deriv(2)
def __init__(self): self.func1=Polynomial(self._coeffs[0]) self.func2=Polynomial(self._coeffs[1]) self.func1_diff=self.func1.deriv() self.func2_diff=self.func2.deriv() self.diff_order=0
points = np.array([ (0.4, 0.587), (1, 0.967), (5, 5.01), (10, 10.09), (15, 15.16), (20, 20.23), (25, 25.32), (30, 30.37), (35, 35.4), (40, 40.5), (45, 45.6), (50, 50.6), (51, 51.6), (52, 52.6), (53, 53.7), (54, 54.7), (55, 54.8), (56, 54.8) ]) # get x and y vectors x = points[:,0] y = points[:,1] p = Polynomial.fit(x, y, 8) plt.plot(x,y,'o') plt.plot(*p.linspace()) plt.show()
def polynomial(self, index, rphase=None, deriv=0, t0=None, time_unit=u.min, out_unit=None, convert=False): """Prediction polynomial set up for times in MJD Parameters ---------- index : int or float index into the polyco table (or MJD for finding closest) rphase : None or 'fraction' or float phase zero point; if None, use the one stored in polyco. (Those are typically large, so one looses some precision.) Can also set 'fraction' to use the stored one modulo 1, which is fine for folding, but breaks phase continuity between sets. deriv : int derivative of phase to take (1=frequency, 2=fdot, etc.); default 0 Returns ------- polynomial : Polynomial set up for MJDs between mjd_mid ± span Notes ----- Units for the polynomial are cycles/second**deriv. Taking a derivative outside will be per day (e.g., self.polynomial(1).deriv() gives frequencies in cycles/day) """ out_unit = out_unit or time_unit try: window = np.array([-1, 1]) * self["span"][index] / 2 * u.min except (IndexError, TypeError): # assume index is really a Time or MJD index = self.searchclosest(index) window = np.array([-1, 1]) * self["span"][index] / 2 * u.min polynomial = Polynomial(self["coeff"][index], window.value, window.value) polynomial.coef[1] += self["f0"][index] * 60.0 if deriv == 0: if rphase is None: polynomial.coef[0] += self["rphase"][index] elif rphase == "fraction": polynomial.coef[0] += self["rphase"][index] % 1 else: polynomial.coef[0] = rphase else: polynomial = polynomial.deriv(deriv) polynomial.coef /= u.min.to(out_unit) ** deriv if t0 is None: dt = 0.0 * time_unit elif not hasattr(t0, "jd1") and t0 == 0: dt = (-self["mjd_mid"][index] * u.day).to(time_unit) else: dt = ((t0 - Time(self["mjd_mid"][index], format="mjd", scale="utc")).jd * u.day).to(time_unit) polynomial.domain = (window.to(time_unit) - dt).value if convert: return polynomial.convert() else: return polynomial