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 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 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 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 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 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 _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 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 _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 hermite5(x0, x1, v0, v1, a0, a1): return Polynomial([x0, v0, 0.5 * a0, -10 * x0 + 10 * x1 - 6 * v0 - 4 * v1 - 1.5 * a0 + 0.5 * a1, 15 * x0 - 15 * x1 + 8 * v0 + 7 * v1 + 1.5 * a0 - a1, -6 * x0 + 6 * x1 - 3 * v0 - 3 * v1 + -.5 * a0 + 0.5 * a1])
def _fitfunc(self, par, x): """LineTable fit function meta['refwave'] + \ par[1]*(x-par[0])+par[2]*(x-par[0])**2+... +par[n]*(x-par[0])**n """ px = Polynomial(np.hstack((self.meta['refwave'], par[1:]))) return px(x - par[0])
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 __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 Newton(pts, prec): título("Newton", "=") # Definir Precisão mm.mp.dps = prec nv = len(pts[0]) matX = pts[0] matY = [pts[1]] for i in range(1, nv): matY.append([]) for j in range(nv - i): matY[i].append((matY[i - 1][j + 1] - matY[i - 1][j]) / (matX[j + i] - matX[j])) print("\nTabela\n\n", mm.matrix(matY)) # matP = [matY[1][0]] # for i in range(nv-1): # mult = 1 # for n in range(i): # mult *= -matX[n] # matP.append(mult) matX = pts[0] matY = pts[1] matP = mm.matrix(list(reversed(Polynomial(lagrange(matX, matY)).coef))) # Transformar Resposta em String Polinômio sPol = pol2str(matP) print("\nPolinômio: ", sPol) return sPol
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 fit(cls, x, y): if 0: # scipy version, numerically unstable from scipy.interpolate import lagrange final = lagrange(x, y) if 0: # numpy version import numpy as np x_ = np.array(x) x_[:, None] - x_[None, :] js, ms = np.triu_indices(len(x), 1) x_[js] - x_[ms] else: import operator as op from functools import reduce basis_polys = [] for j, x_j in enumerate(x): parts_j = [] for m, x_m in enumerate(x): if m != j: part_m_j = Polynomial([-1 * x_m, 1]) / (x_j - x_m) parts_j.append(part_m_j) basis_j = reduce(op.mul, parts_j, 1) basis_polys.append(basis_j) final = sum(y_j * basis_j for y_j, basis_j in zip(y, basis_polys)) if __debug__: # Final lagrance polynomial must have this property for j in range(len(x)): assert final(x[j]) == y[j]
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 sturms_sequence(p: Polynomial): """ Returns Sturm's sequence of a given polynomial. """ # setting up the Sturm's sequence. sturms_seq = [] sturms_seq.append(p) sturms_seq.append(p.deriv()) # filling the Sturm's sequence list. f = -Polynomial(poly.polydiv(sturms_seq[-2].coef, sturms_seq[-1].coef)[1]) while f.degree() != 0 or f.coef[0] != 0: sturms_seq.append(f.copy()) f = -Polynomial( poly.polydiv(sturms_seq[-2].coef, sturms_seq[-1].coef)[1]) return sturms_seq
def div_xn(poly, n): """ Divide the polynomial by x^n n <= m, m is the minimal index """ c = poly.coef assert np.all(c[:n] == 0) return Polynomial(c[n:])
def test_response_5(self): pcoefs = [-1., 0., 50., 0., -400., 0., 1120., 0., -1280., 0., 512.] poly = Polynomial(pcoefs) QuantumSignalProcessingPhases(poly, signal_operator="Wx") QuantumSignalProcessingPhases(poly, signal_operator="Wz") QuantumSignalProcessingPhases(poly, signal_operator="Wx", measurement="z")
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 __init__(self, x, y, dy): """ Spline initialization Parameters ---------- x, y : array_like float The (x, y) values at nodes that defines the spline dy : array_like float with two elements The first derivatives of the left and right ends of the nodes """ from numpy.linalg import solve from numpy.polynomial.polynomial import Polynomial self.x = np.asarray(x) self.y = np.asarray(y) self.dy = np.asarray(dy) n = len(self.y) h = self.x[1:]-self.x[:-1] r = (self.y[1:]-self.y[:-1])/(self.x[1:]-self.x[:-1]) B = np.zeros((n-2, n)) for i in range(n-2): k = i+1 B[i, i:i+3] = [h[k], 2*(h[k-1]+h[k]), h[k-1]] C = np.empty((n-2, 1)) for i in range(n-2): k = i+1 C[i] = 3*(r[k-1]*h[k]+r[k]*h[k-1]) C[0] = C[0]-self.dy[0]*B[0, 0] C[-1] = C[-1]-self.dy[1]*B[-1, -1] B = B[:, 1:n-1] dys = solve(B, C) dys = np.array( [self.dy[0]] + [tmp for tmp in dys.flatten()] + [self.dy[1]]) A0 = self.y[:-1] A1 = dys[:-1] A2 = (3*r-2*dys[:-1]-dys[1:])/h A3 = (-2*r+dys[:-1]+dys[1:])/h**2 self.coef = np.array([A0, A1, A2, A3]).T self.polys = [Polynomial(c) for c in self.coef] self.polys.insert(0, Polynomial( [self.y[0]-self.x[0]*self.dy[0], self.dy[0]])) self.polys.append(Polynomial( [self.y[-1]-self.x[-1]*self.dy[-1], self.dy[-1]]))
def encode(self, message): poly_coeffs = strencode(message, self.k) polynomial = Polynomial(poly_coeffs) shares = [(x, int(polyval(x, polynomial.coef))) for x in range(1, (self.k+self.e+1))] signed_shares = [(i, sign(str(i[1]), self.pri_key, self.bitlen, self.generator, self.prime)) for i in shares] return signed_shares
def expectedStockValue(p, x_test, days): poly = Polynomial(p) results = [poly(num) for num in x_test] for i in range(days - 1): results.append(poly(results[-1])) return np.array(results)
def test_response_6(self): pcoefs = [ -1., 0., (1 / 2) * (4 + 3j - (1 - 2j) * np.sqrt(3)), 0., (1 - 1j) * (-1j + np.sqrt(3)) ] poly = Polynomial(pcoefs) QuantumSignalProcessingPhases(poly, signal_operator="Wx", measurement="z")
def __init__(self): #distance from encoders self.distance = 0 #polynomial self.c_poly = Polynomial(0) self.r_poly = Polynomial(0) self.l_poly = Polynomial(0) self.lookahead_c = 0.2 #obstacles polygon self.polygons = [] self.start_distance = 0 self.start_back_distance = 0 self.change_distance = 0 #distance from center lane self.center_dis = 0 self.once_detected =0 self.get_change_distance = 0 self.border_distance_x = 1.1 self.border_distance_y = 0.7 self.fraction = 0.1 self.normal_drive = 0 self.box_right = 0 self.get_call = 0 self.threshold_normal = 2 self.threshold_anormal = 2 self.tests = False self.stop_call = False