def hermit_interpol_polynomial(nodes, f): def divided_difference(row, col): # row = j, col = i # Если знаменатель не ноль if nodes[row + col] != nodes[row]: return (dif_matrix[row + 1, col - 1] - dif_matrix[row, col - 1]) / (nodes[row + col] - nodes[row]) # Если знаменатель ноль else: deriv = derivative(f, col) return deriv(nodes[row]) / factorial(col) n = len(nodes) dif_matrix = np.zeros((n, n)) for i in range(n): dif_matrix[i, 0] = f(nodes[i]) for i in range(1, n): for j in range(0, n - i): dif_matrix[j, i] = divided_difference(j, i) result = Polynomial(dif_matrix[0, 0]) for i in range(n - 1): result = pl.polyadd( result, Polynomial(np.poly(nodes[0:i + 1])[::-1]) * dif_matrix[0, i + 1])[0] return result, dif_matrix
def construct_polynomials(self): """Construct polynomials up to nth degree. Save the results to the instance. """ from numpy.polynomial.polynomial import Polynomial p = [Polynomial([1])] # polynomials a = [] b = [0] innerprod = [.5 ] # constructed such that inner product of f(x)=1 is 1/2 # first polynomial is special a.append( quad(lambda x: self.K(x) * x, self.x0, self.x1)[0] / innerprod[0]) p.append(Polynomial([-a[0], 1]) * p[0]) for i in range(1, self.n + 1): innerprod.append( quad(lambda x: p[i](x)**2 * self.K(x), self.x0, self.x1)[0]) a.append( quad(lambda x: x * p[i] (x)**2 * self.K(x), self.x0, self.x1)[0] / innerprod[i]) b.append(innerprod[i] / innerprod[i - 1]) p.append(Polynomial([-a[i], 1]) * p[i] - b[i] * p[i - 1]) self.p = p self.a = a self.b = b self.innerprod = innerprod
def evaluate(self, par, mjd, t0par=None, integrate=False): """Evaluate 'par' at given MJD(s), with zero point t0par Parameters ---------- par : string key into dictionary = parameter to evaluate. Takes into account possible par+'DOT' (for 'F': F0, F1, F2, F3) mjd : float or Time object MJD at which to evaluate (or Time with .tdb.mjd attribute) t0par : string or None key into dictionary with zero point for par default: None -> PEPOCH for 'F', 'TASC' for all others integrate : bool Whether to integrate the polynomial (e.g., to get mean anomaly out of 'FB' or pulse phase out of 'F') """ if par == 'F': t0par = t0par or 'PEPOCH' parpol = Polynomial((self['F0'], self.get('F1', 0.), self.get('F2', 0.), self.get('F3', 0.))) else: t0par = t0par or 'TASC' parpol = Polynomial((self[par], self.get(par + 'DOT', 0.))) if integrate: parpol = parpol.integ() # given time can be Time object if hasattr(mjd, 'tdb'): mjd = mjd.tdb.mjd return parpol((mjd - self[t0par]) * 86400.)
def evaluate(self, par, mjd, t0par=None, integrate=False): """Evaluate 'par' at given MJD(s), with zero point t0par Parameters ---------- par : string key into dictionary = parameter to evaluate. Takes into account possible par+'DOT' (for 'F': F0, F1, F2, F3) mjd : float or Time object MJD at which to evaluate (or Time with .tdb.mjd attribute) t0par : string or None key into dictionary with zero point for par default: None -> PEPOCH for 'F', 'TASC' for all others integrate : bool Whether to integrate the polynomial (e.g., to get mean anomaly out of 'FB' or pulse phase out of 'F') """ if par == 'F': t0par = t0par or 'PEPOCH' parpol = Polynomial((self['F0'], self.get('F1', 0.), self.get('F2',0.), self.get('F3',0.))) else: t0par = t0par or 'TASC' parpol = Polynomial((self[par], self.get(par+'DOT', 0.))) if integrate: parpol = parpol.integ() # given time can be Time object if hasattr(mjd, 'tdb'): mjd = mjd.tdb.mjd return parpol((mjd - self[t0par]) * 86400.)
def newton_interpol_polynomial(nodes, f): n = len(nodes) dif_matrix = np.zeros((n, n)) for i in range(n): dif_matrix[i, 0] = f(nodes[i]) # Считаем разделённые разности. Храним их в верхнетреугольной матрице for i in range(1, n): for j in range(0, n - i): dif_matrix[j, i] = (dif_matrix[j + 1, i - 1] - dif_matrix[j, i - 1]) / (nodes[j + i] - nodes[j]) # Строим интерпол. полином Ньютона, испоьзуя полученные разности result = Polynomial(dif_matrix[0, 0]) for i in range(n - 1): result = pl.polyadd( result, Polynomial(np.poly(nodes[0:i + 1])[::-1]) * dif_matrix[0, i + 1])[0] # Помимо полинома возвращаем ещё и матрицу разностей, т.к. её, вообще говоря, можно использовать, # если мы захотим добавить ещё узлов интерполяции return result, dif_matrix
def transform_points(src, dst, pts, steps): surfaces = [] surf_array = np.zeros((1280, 720, 3)) first_line = poly.fit([src[0][0], dst[0][0]], [src[0][1], dst[0][1]], 1) second_line = poly.fit([src[1][0], dst[1][0]], [src[1][1], dst[1][1]], 1) third_line = poly.fit([src[2][0], dst[2][0]], [src[2][1], dst[2][1]], 1) fourth_line = poly.fit([src[3][0], dst[3][0]], [src[3][1], dst[3][1]], 1) first_points = first_line.linspace(steps) second_points = second_line.linspace(steps) third_points = third_line.linspace(steps) fourth_points = fourth_line.linspace(steps) for i in range(1, steps): dst = np.float32([[first_points[0][-i], first_points[1][-i]], [second_points[0][i], second_points[1][i]], [third_points[0][i], third_points[1][i]], [fourth_points[0][-i], fourth_points[1][-i]]]) M = cv2.getPerspectiveTransform(src, dst) transformed_points = cv2.perspectiveTransform(pts, M) surface = pygame.Surface((1280, 720)) pygame.draw.polygon(surface, (0, 130, 0), np.squeeze(transformed_points, axis=0)) surfaces.append(surface) return surfaces
def zernike_dict(nmax): zerDic = {} for n in range(nmax+1): for l in range(n,-1,-2): # print(n,l) key = (n,l) if l == n: # coef = [0 for _ in range(n+1)] # coef[n] = 1 poly = xn(n) # zerDic[key] = poly elif l == n-2: if n >=2: poly = (n+0.5)*zerDic[(n,n)] - (n-0.5)*zerDic[(n-2,n-2)] else: poly = (n+0.5)*zerDic[(n,n)] # zerDic[key] = poly elif l == 0: n2 = 2*n M1 = (n2+1)*(n2-1)/(n+l+1)/(n-l) M2 = -0.5*((2*l+1)**2*(n2-1) + (n2+1)*(n2-1)*(n2-3))/(n+l+1)/(n-l)/(n2-3) M3 = -1*(n2+1)*(n+l-1)*(n-l-2)/(n+l+1)/(n-l)/(n2-3) poly = (M1*Polynomial([0,0,1]) + M2)*zerDic[(n-2,l)] + M3*zerDic[(n-4,l)] # zerDic[key] = poly else: L1 = (2*n+1)/(n+l+1) L2 = -1*(n-l)/(n+l+1) poly = L1*Polynomial([0,1])*zerDic[(n-1,l-1)] + L2*zerDic[(n-2,l)] zerDic[key] = poly return zerDic
def calculate_root(f: Polynomial, a, b, eps): """ Return root (assuming there's one) of f function on the (a, b) interval using secant method and also return number of iterations. f's first two derivatives should be differentiable. """ assert f(a) * f(b) < 0 if f(a) > 0: f = -f if f(b) * f.deriv(2)(b) > 0: x = a c = b elif f(a) * f.deriv(2)(a) > 0: x = b c = a else: raise Exception() true_x = spo.brentq(f, a, b) iter_count = 0 while abs(x - true_x) > eps and iter_count < MAX_ITERATION_COUNT: x -= (c - x) / (f(c) - f(x)) * f(x) iter_count += 1 return x, iter_count
def __init__(self, data, fs=2 * np.pi, win_size=256, overlap=None, poly_order=6, initial_alpha=None): """ Initialize class. """ if initial_alpha is None: alpha = np.zeros(poly_order + 1) else: alpha = initial_alpha self.alpha = alpha self.z = data self.fs = fs self.poly_order = poly_order self._polynomial = Polynomial(alpha) # transform frequency num_time_bins = self.z.size // win_size num_freq_bins = win_size // 2 self.win_size = win_size if overlap is None: self.overlap = num_freq_bins // 2 else: self.overlap = overlap self.tfd = np.zeros((num_freq_bins, num_time_bins), dtype='complex')
def PolyDivModOverZn(a: poly, b: poly, n: int) -> (poly, poly): if n < 1: raise ValueError if n==1: raise ZeroDivisionError a = poly(np.mod(a.coef, n)) b = poly(np.mod(b.coef, n)) a = a.trim() b = b.trim() deg_a, deg_b = len(a.coef), len(b.coef) if deg_a < deg_b: return poly([0]), a else: f = poly(b.coef[::-1]).trim() g = PolyInverseModOverZn(f, deg_a - deg_b + 1, n) if g is None: raise ZeroDivisionError q = (poly(a.coef[::-1]).trim() * g).truncate(deg_a - deg_b + 1) # q:=rev_n(a)g mod x^(n-m+1) q = poly(np.mod(q.coef, n)) q = poly(q.coef[::-1]).trim() # q:=rev_(n-m)(q) if len(q.coef) < deg_a - deg_b + 1: q.coef = np.concatenate([np.zeros(deg_a - deg_b + 1 - len(q)), q.coef]) bq = poly(np.mod((b * q).coef, n)) r = a - bq r = poly(np.mod(r.coef, n)) q = poly(np.mod(q.coef, n)) r = r.trim() q = q.trim() return q, r
def lagrange(nodes): result = Polynomial([0]) w = Polynomial(np.poly(nodes)[::-1]) deriv = w.deriv(1) for i in range(len(nodes)): result = pl.polyadd(result, make_l_k(i, nodes, w, deriv) * f(nodes[i]))[0] return result
def n_k(order, coef_func): if order < 0: raise ValueError() if order == 0: return Polynomial([0, 1]) elif order > 0: return pl.polymul(n_k(order - 1, coef_func), Polynomial([coef_func(order), 1]))[0] / (order + 1)
def _pq_completion(P): """ Find polynomial Q given P such that the following matrix is unitary. [[P(a), i Q(a) sqrt(1-a^2)], i Q*(a) sqrt(1-a^2), P*(a)]] Args: P: Polynomial object P. Returns: Polynomial object Q giving described unitary matrix. """ pcoefs = P.coef P = Polynomial(pcoefs) Pc = Polynomial(pcoefs.conj()) roots = (1. - P * Pc).roots() # catagorize roots real_roots = np.array([], dtype=np.float64) imag_roots = np.array([], dtype=np.float64) cplx_roots = np.array([], dtype=np.complex128) tol = 1e-6 for root in roots: if np.abs(np.imag(root)) < tol: # real roots real_roots = np.append(real_roots, np.real(root)) elif np.real(root) > -tol and np.imag(root) > -tol: if np.real(root) < tol: imag_roots = np.append(imag_roots, np.imag(root)) else: cplx_roots = np.append(cplx_roots, root) # remove root r_i = +/- 1 ridx = np.argmin(np.abs(1. - real_roots)) real_roots = np.delete(real_roots, ridx) ridx = np.argmin(np.abs(-1. - real_roots)) real_roots = np.delete(real_roots, ridx) # choose real roots in +/- pairs real_roots = np.sort(real_roots) real_roots = real_roots[::2] # include negative conjugate of complex roots cplx_roots = np.r_[cplx_roots, -cplx_roots] # construct Q Q = Polynomial( polyfromroots(np.r_[real_roots, 1j * imag_roots, cplx_roots])) Qc = Polynomial(Q.coef.conj()) # normalize norm = np.sqrt( (1 - P * Pc).coef[-1] / (Q * Qc * Polynomial([1, 0, -1])).coef[-1]) return Q * norm
def _fitfunc(self, p, chip, x): """ThreeChipLineTable fit function: y = x - par[0] + par[1]*(chip-refchip) + par[2]*(chip-refchip)**2 w = refwave + par[3]*y + par[4]*y**2 + ... + par[n]*y**(n-2) where refchip, refwave are taken from the Table meta data. """ pchip = Polynomial([-p[0], p[1], p[2]]) px = Polynomial(np.hstack((self.meta['refwave'], p[3:]))) return px(x + pchip(chip - self.meta['refchip']))
def make_nodes(n, p, a, b): mu_list = np.array(make_mu_k(n, p, a, b), dtype=np.float64) left_part = np.array([mu_list[i:n+i][::-1] for i in range(n)], dtype=np.float64) right_part = -1 * mu_list[n:] coef = solve(left_part, right_part) coef = np.append(coef[::-1], 1) w = Polynomial(coef) return w.roots()
def test_verify_degree(self): """ Check the degree of the polynomio """ minimum = randint(2, 70) e = self.generate_Encrypter("test_files/") p = self.get_poly(e, "test_files/", minimum) polynomial = Poly(p.generate_random_poly()) assert polynomial.degree() == minimum - 1
def experiment(self): self.leg = self.genlegpoly() self.dataset = self.gendataset() self.g2 = Polynomial.fit(self.dataset[0], self.dataset[1], 2, [-1.0, 1.0]) self.g10 = Polynomial.fit(self.dataset[0], self.dataset[1], 10, [-1.0, 1.0]) self.eoutg2 = self.mse4(self.g2, self.leg) self.eoutg10 = self.mse4(self.g10, self.leg)
def evaluate(self, par, mjd, t0par='TASC', integrate=False): if par == 'F': parpol = Polynomial((self['F'], self.get('F1', 0.), self.get('F2',0.), self.get('F3',0.))) else: parpol = Polynomial((self[par], self.get(par+'DOT', 0.))) if integrate: parpol = parpol.integ() dt = (mjd-self[t0par])*24.*3600. return parpol(dt)
def lagrange(nodes): result = Polynomial([0]) # np.poly строит полином по набору корней. Но порядок коэффициетов противоположный тому, который # принимает конструктор класса Polynomial w = Polynomial(np.poly(nodes)[::-1]) deriv = w.deriv(1) for i in range(len(nodes)): result = pl.polyadd(result, make_l_k(i, nodes, w, deriv) * f(nodes[i]))[0] # возвращается не только сумма return result
def solve_root(coefficients, ploting=True): f = Polynomial(list(reversed(coefficients))) # Solve f(x) == 0. X, Y = [], [] roots = f.roots() """ print("polynomial: ", f) print("roots: ", roots) """ result = areRootsRealNegative(roots) return result, roots
def _coeffs2poly(self, coeffs): poly_coeffs = np.zeros((len(self.init_coeffs) + 2, )) poly_coeffs[0] = 0.5 * coeffs[0] # v1 poly_coeffs[1] = coeffs[0] # v1 poly_coeffs[2] = coeffs[1] # v2 poly_coeffs[3] = 2 * coeffs[1] - coeffs[0] poly_coeffs[4:] = coeffs[2:] p = Polynomial(poly_coeffs) * Polynomial([1, -1])**2 assert abs(p.coef[3]) < 1e-10 assert abs(p.coef[1]) < 1e-10 assert abs(p(1.)) < 1e-10 return p
def poles_to_rational_rep(poles, residues, d, h): """ Take the parameters produced by vectfit and construct a representation of the form f(s) / g(s), returning f and g """ pole_ps = [Polynomial([-p, 1]) for p in poles] denom = product(pole_ps) num = sum(r * denom / p for r, p in zip(residues, pole_ps)) num += Polynomial([d, h]) * denom # Since we're a PR function, should be safe to convert these to real values num = Polynomial(num.coef.real) denom = Polynomial(denom.coef.real) return num, denom
def fit(x, y, deg, regularization=0): # order = polyfit1d(y, x, deg, regularization) if deg == "best": order = best_fit(x, y) else: order = Polynomial.fit(y, x, deg=deg, domain=[]).coef[::-1] return order
def polyDataFor(arr): ''' t -> vel fit func = Poly.fit(arr[:, 0], arr[:, 1], 1) data = np.empty_like(arr) for i in range(len(arr)): data[i] = [arr[i,0], func(arr[i,0])]''' # before -> vel fit func = Poly.fit(arr[:-1, 1], (arr[1:, 1] - arr[:-1, 1]) / (arr[1:, 0] - arr[:-1, 0]), 1, domain=[]) print("Poly fitted:", func, func.domain, func.window) data = np.empty((arr.shape[0] - 1, arr.shape[1])) prevV = arr[0, 1] for i in range(len(arr) - 1): prevT = arr[i, 0] nextT = arr[i + 1, 0] #nextV = prevV + func(prevV) * (nextT - prevT) #fac = - 0.0305 * prevV # free in air -0.4690 #fac = -227.20539704480407 - 0.03047 * prevV # rollin on ground > 550 vel #fac = func(prevV) nextV = prevV + fac * (nextT - prevT) data[i] = [nextT, nextV] #func(prevV) prevV = nextV return data
def _get_pp_poly(self): p = self.ppsi_polynomial dp = p.deriv(1) dp_o_r = p.deriv(1) / Polynomial([0.,1.]) ddp = p.deriv(2) pp_poly = self.calibration_energy + 2*dp_o_r + (ddp + dp**2) return pp_poly
def test_response_4(self): pcoefs = [0., -2 + 1j, 0., 2.] poly = Polynomial(pcoefs) QuantumSignalProcessingPhases(poly, signal_operator="Wx", measurement="z")
def test_response_1(self): pcoefs = [0, 1] poly = Polynomial(pcoefs) QuantumSignalProcessingPhases(poly, signal_operator="Wx") QuantumSignalProcessingPhases(poly, signal_operator="Wz")
def poly_fit_eta(): from numpy.polynomial.polynomial import Polynomial x = np.linspace(1,0,2000) for i in range(10): U1, U2 = [unitary_group.rvs(4) for _ in range(2)] A1,A2 = [np.random.rand(16).reshape(4,4) + 1j*np.random.rand(16).reshape(4,4) for _ in range(2)] H1 = 0.5*(A1 + A1.conj().T) H2 = 0.5*(A2 + A2.conj().T) te1 = expm(1j*H1*0.1) te2 = expm(1j*H2*0.1) U1_ = (te1 @ U1).conj().T U2_ = (te2 @ U2).conj().T RE = RightEnvironment() params = [np.pi/4,0,0,0,0,0] # np.random.rand(6) C = CircuitSolver() M = C.M(params) M_ = RE.circuit(r(U1), r(U2), r(U1_), r(U2_), M) scores = [] for p in x: scores.append(np.linalg.norm(p * M - M_)) coefs = Polynomial.fit(x[:10],scores[:10],deg = 2, domain = (1,0.9)) new_vals = [coefs(a) for a in x] plt.plot(x, scores, label = "Exact") plt.plot(x, new_vals, label = "Poly Fit") plt.legend() plt.show()
def test_poly1D_fit_weighted(): polyOrder = np.random.randint(2, 5) numMeasurements = np.random.randint(50, 100) xValues = np.random.rand(numMeasurements) * 100 - 50 coefficients = np.random.rand(polyOrder + 1) * 5 - 10 yValues = [] for x in xValues: y = 0 for order in range(polyOrder + 1): y += coefficients[order] * x**order yValues.append(y + np.random.randn(1).item()) yValues = np.array(yValues) yValues = yValues.reshape(yValues.size, 1) weights = np.random.rand(numMeasurements) cX = NumCpp.NdArray(1, xValues.size) cY = NumCpp.NdArray(yValues.size, 1) cWeights = NumCpp.NdArray(1, xValues.size) cX.setArray(xValues) cY.setArray(yValues) cWeights.setArray(weights) poly = Polynomial.fit(xValues, yValues.flatten(), polyOrder, w=weights).convert().coef polyC = NumCpp.Poly1d.fitWeighted( cX, cY, cWeights, polyOrder).coefficients().getNumpyArray().flatten() assert np.array_equal(np.round(poly, 1), np.round(polyC, 1))
def momentum_analysis_global_chi2(meas_solver, analysis_B_func, B_name='Mau 13 (nominal)', sigma=1., delta=.2, N_hyp=7, plot_chi2=False): # use circle fit analysis mean to determine test_ps meas_solver.analyze_trajectory(step=25, stride=1, query="z >= 8.41 & z <= 11.66", B=analysis_B_func) circle_fit_mom = meas_solver.df_reco.p.mean() pmin = circle_fit_mom - delta pmax = circle_fit_mom + delta ps_test = np.linspace(pmin, pmax, N_hyp) # run particles for each hypothesis momentum sum_of_impacts2 = global_chi2_ptests(test_ps=ps_test, test_B_func=analysis_B_func, meas_solver=meas_solver, sigma=sigma) # fit quadratic to calculated chi2 values c, b, a = Polynomial.fit(ps_test, sum_of_impacts2, 2).convert().coef # use quadratic parameters to get momentum estimate chi2_fit_mom = -b / (2 * a) # plot (if selected) if plot_chi2: ptrue = meas_solver.init_conds.p0 ps_quad = np.linspace(pmin, pmax, 50) y_quad = a * ps_quad**2 + b * ps_quad + c fig = plt.figure() plt.plot(ps_quad, y_quad, c='gray', label='Quadratic Fit') plt.scatter(ps_test, sum_of_impacts2, c='black', label='Calculated ' + r"$\chi^2$", zorder=100) ymax = np.max(sum_of_impacts2) plt.plot([ptrue, ptrue], [0., ymax], 'r-', linewidth=2, label=f'True Momentum ={ptrue:.3f} MeV/c', zorder=90) plt.plot([chi2_fit_mom, chi2_fit_mom], [0., ymax], 'g--', label='Momentum ' + r'$(\chi^2) =$' + f'{chi2_fit_mom:.3f} MeV/c', zorder=92) plt.plot([circle_fit_mom, circle_fit_mom], [0., ymax], 'b--', label=f'Momentum (circle) = {circle_fit_mom:.3f} MeV/c', zorder=91) plt.xlabel(r"$p$" + " [MeV/c]") plt.ylabel(r"$\chi^2$") plt.title('Global ' + r'$\chi^2$' + f' Momentum Fit: {B_name}') l = plt.legend(loc='upper right') l.set_zorder(110) return chi2_fit_mom, circle_fit_mom, fig # return results return chi2_fit_mom, circle_fit_mom
def measure(self): """Compute some metrics that give an idea of how well each area is doing.""" for aoi in self.aoi.values(): if 'population' not in aoi: print("No population info for", aoi['name']) continue if 'cases' not in aoi['data']: print("No cases for", aoi['name']) continue if len(aoi['data']['cases']) < 2: print("Insufficient cases for", aoi['name']) continue distance = [] pop = aoi['population'] distance = [(v or 0) / pop for v in aoi['data']['cases']] window = min(14, len(distance)) polynomial = Polynomial.fit(range(window), distance[-window:], min(3, window)) coefficients = list(polynomial.convert().coef[1:]) # If the trailing coefficients are 0, they're not included in coef. # Add them back. while len(coefficients) < 3: coefficients.append(0) aoi['velocity'] = coefficients[0] aoi['acceleration'] = coefficients[1] aoi['jerk'] = coefficients[2]
def __init__(self, order, monom=None): self.monom = monom if monom else Polynomial( np.identity(order + 1)[order]) assert isinstance(self.monom, Polynomial) self.order = order self.derivative = self.monom.deriv() self.linear = order == 1
def evaluate(self, par, mjd, t0par="TASC", integrate=False): parpol = Polynomial((self[par], self.get(par + "DOT", 0.0))) if integrate: parpol = parpol.integ() dt = (mjd - self[t0par]) * 24.0 * 3600.0 return parpol(dt)
#!/usr/bin/env python """polynomial.py: Demonstrate equation solvers of SciPy. """ from numpy.polynomial.polynomial import Polynomial # pylint: disable=invalid-name # Define a polynomial x^3 - 2 x^2 + x - 2. f = Polynomial([-2, 1, -2, 1]) print("polynomial: ", f) # Solve f(x) == 0. print("roots: ", f.roots())