def invert_legendre_polynomial(wavemin, wavemax, ycoef, xcoef, sigmacoef, fiber, npix_y, wave_of_y, width=7): # Wavelength array used in 'invert_legendre_polynomial' wave = np.linspace(wavemin, wavemax, 100) # Determines value of Y, so we can know its coeficient and then its position y_of_wave = legval(u(wave, wavemin, wavemax), ycoef[fiber]) coef = legfit(u(y_of_wave, 0, npix_y), wave, deg=ycoef[fiber].size) wave_of_y[fiber] = legval(u(np.arange(npix_y).astype(float), 0, npix_y), coef) # Determines wavelength intensity (x) based on Y x_of_y = legval(u(wave_of_y[fiber], wavemin, wavemax), xcoef[fiber]) sigma_of_y = legval(u(wave_of_y[fiber], wavemin, wavemax), sigmacoef[fiber]) # Ascertain X by using low and high uncertainty x1_of_y = np.floor(x_of_y).astype(int) - width / 2 x2_of_y = np.floor(x_of_y).astype(int) + width / 2 + 2 return (x1_of_y, x_of_y, x2_of_y, sigma_of_y)
def leggauss(n, x0=None): """ Abscissa and weights for Gauss-Legendre quadrature. Parameters ---------- n : int Returns ------- x : ndarray weights : ndarray """ J = legjacobi(n) if x0 is None: x, vec = np.linalg.eigh(J) return x, vec[0]**2 * 2 else: from numpy.polynomial.legendre import legval J[-1, -1] = x0 - J[-1, -2]**2 * legval(x0, [0] * (n - 2) + [1]) / legval( x0, [0] * (n - 1) + [1]) x, vec = np.linalg.eigh(J) return x, vec[0]**2 * 2
def hamiltonian_matrix(BASIS_SIZE=BASIS_SIZE, BASIS_FUNC=BASIS_FUNC, DOMAIN=DOMAIN, C=C, V=V): '''Calculates the hamiltonian matrix <psi|H|psi>''' if BASIS_FUNC == 'legendre': hmat = np.zeros((BASIS_SIZE, BASIS_SIZE)) for i in range(BASIS_SIZE): for j in range(BASIS_SIZE): coefs_i = [0] * (i) + [1] coefs_j = [0] * (j) + [1] inside = L.legmul(coefs_i, list(hamiltonian(coefs_j))) integ = L.legint(inside) val = L.legval(DOMAIN[1], integ) - L.legval(DOMAIN[0], integ) hmat[i, j] = val if BASIS_FUNC == 'fourier': a = DOMAIN[ 1] #restrict the domain to be symmetric about origin for simplicity hmat = np.zeros((BASIS_SIZE, BASIS_SIZE)) for i in range(BASIS_SIZE): for j in range(BASIS_SIZE): p1 = 2 * V * np.sin(a * j) / j #cos V0 term p2 = 0 #cos cos term cancels due to parity if i != j if i == j: p2 = C * (j**2) * (a + np.sin(2 * a * j) / (2 * j)) hmat[i, j] = p1 + p2 return hmat
def evaluate_basis_gauss(self): """Evaluate the basis at the Gaussian quadrature nodes. phi will be used to transform Legendre solution coefficients to the solution evaluated at the Gaussian quadrature nodes. dphi_w will be used for the interior flux integral """ phi = np.zeros((len(self.x), self.N_s)) dphi_w = np.zeros((len(self.x), self.N_s)) for n in range(self.N_s): # Get the Legendre polynomial of order n and its gradient l = L.basis(n) dl = l.deriv() # Evaluate the basis at the Gaussian nodes phi[:, n] = leg.legval(self.x, l.coef) # Evaluate the gradient at the Gaussian nodes and multiply by the # weights dphi_w[n, :] = leg.legval(self.x, dl.coef) * self.w return phi, dphi_w
def fitcont(wave, flux, sigup, fitidx, maxorder=6): wavepts = wave[fitidx] fluxpts = flux[fitidx] sigpts = sigup[fitidx] ### Cycle through fits of several orders and decide the appropriate order by F-test coeffs = [] covmtxs = [] fits = [] chisqs = [] dfs = [] fprob = 0. i = 0 order = 1 while (fprob <= 0.95) & (order <= maxorder): order = i + 1 coeff, covmtx = fitlegendre(wavepts, fluxpts, sigpts, order) coeffs.append(coeff) covmtxs.append(covmtx) fit = L.legval(wavepts, coeff, order) fits.append(fit) chisq, df = redchisq(fluxpts, fit, sigpts, order) chisqs.append(chisq), dfs.append(df) if i > 0: fval = chisqs[i] / chisqs[i - 1] fprob = stats.f.cdf(fval, dfs[i], dfs[i - 1]) i += 1 ### Choose fit of order just prior to where F-test indicates no improvement fitcoeff = coeffs[i - 2] fitcovmtx = covmtxs[i - 2] wrange = range(fitidx[0], fitidx[-1]) cont = L.legval(wave[wrange], fitcoeff) return fitcoeff, fitcovmtx
def term_ijk(self, index): i, j, k = index ci = np.zeros(i + 1) cj = np.zeros(j + 1) ck = np.zeros(k + 1) ci[-1] = cj[-1] = ck[-1] = 1 return legval(self.r[0], ci) * legval(self.r[1], cj) * legval( self.r[2], ck)
def genericLegVal(locations, coeffs): if len(locations.shape)==1: return leg.legval(locations,coeffs) else: # assume dim 0 is points, dim 1 is dimensions c=leg.legval(locations[:,0], coeffs) for i in range(1, locations.shape[1]): c=leg.legval(locations[:,i],c, tensor=False) return c
def gaussian_latitudes(n): """Construct latitudes and latitude bounds for a Gaussian grid. Args: * n: The Gaussian grid number (half the number of latitudes in the grid. Returns: A 2-tuple where the first element is a length `n` array of latitudes (in degrees) and the second element is an `(n, 2)` array of bounds. """ if abs(int(n)) != n: raise ValueError('n must be a non-negative integer') nlat = 2 * n # Create the coefficients of the Legendre polynomial and construct the # companion matrix: cs = np.array([0] * nlat + [1], dtype=np.int) cm = legcompanion(cs) # Compute the eigenvalues of the companion matrix (the roots of the # Legendre polynomial) taking advantage of the fact that the matrix is # symmetric: roots = la.eigvalsh(cm) roots.sort() # Improve the roots by one application of Newton's method, using the # solved root as the initial guess: fx = legval(roots, cs) fpx = legval(roots, legder(cs)) roots -= fx / fpx # The roots should exhibit symmetry, but with a sign change, so make sure # this is the case: roots = (roots - roots[::-1]) / 2. # Compute the Gaussian weights for each interval: fm = legval(roots, cs[1:]) fm /= np.abs(fm).max() fpx /= np.abs(fpx).max() weights = 1. / (fm * fpx) # Weights should be symmetric and sum to two (unit weighting over the # interval [-1, 1]): weights = (weights + weights[::-1]) / 2. weights *= 2. / weights.sum() # Calculate the bounds from the weights, still on the interval [-1, 1]: bounds1d = np.empty([nlat + 1]) bounds1d[0] = -1 bounds1d[1:-1] = -1 + weights[:-1].cumsum() bounds1d[-1] = 1 # Convert the bounds to degrees of latitude on [-90, 90]: bounds1d = np.rad2deg(np.arcsin(bounds1d)) bounds2d = np.empty([nlat, 2]) bounds2d[:, 0] = bounds1d[:-1] bounds2d[:, 1] = bounds1d[1:] # Convert the roots from the interval [-1, 1] to latitude values on the # interval [-90, 90] degrees: latitudes = np.rad2deg(np.arcsin(roots)) return latitudes, bounds2d
def eval(self, x, u, output_array=None): if output_array is None: output_array = np.zeros(x.shape) x = self.map_reference_domain(x) w_hat = work[(u, 0, True)] self.set_factor_array(u) output_array[:] = leg.legval(x, u[:-2]) w_hat[2:] = self._factor * u[:-2] output_array -= leg.legval(x, w_hat) return output_array
def parallels_transitions(turbine, joints_parallel, joints_vel_parallel, joints_acc_parallel, times_parallel, step=.1, number_of_points=8.): """ Given all parallels solutions, i.e., joints solutions for all waypoints split in parallels (lists), this method computes cubic polynomials to interpolate the two points: end of a parallel - begin of the next parallel, in joint space, considering velocities. It will return the parallels and the computed transition paths between them. Obs.: This is taking too long. No improvements are being made since plates can be used on the transition part. Args: turbine: (@ref Turbine) turbine object joints_parallel: (float[m][n<SUB>i</SUB>][nDOF]) list of joints for all parallels times_parallel: (float[m][n<SUB>i</SUB>]) list of deltatimes for all parallels step: distance (meters) between points number_of_points: minimal number of points max_acc: maximum permitted acceleration (percentage) Returns: Modifies the current joints_parallel and times_parallel with the computed transitions. """ robot = turbine.robot for i in range(len(joints_parallel) - 1): joint_0 = joints_parallel[2 * i][-1] vel_0 = joints_vel_parallel[2 * i][-1] joint_1 = joints_parallel[2 * i + 1][0] vel_1 = joints_vel_parallel[2 * i + 1][0] c = mathtools.legn_path(3, [joint_0, joint_1], [vel_0, vel_1]) joints = [] joints_vel = [] joints_acc = [] times = [] dt = min([step, 1. / number_of_points]) for t in linspace(0, 1., max([1. / step, number_of_points])): joints.append(legendre.legval(t, c)) joints_vel.append(legendre.legval(t, legendre.legder(c, 1))) joints_acc.append(legendre.legval(t, legendre.legder(c, 2))) times.append(dt) joints = joints[1:-1] joints_vel = joints_vel[1:-1] joints_acc = joints_acc[1:-1] times_parallel[2 * i + 1][0] = times[-1] times = times[1:-1] joints_parallel.insert(2 * i + 1, joints) joints_vel_parallel.insert(2 * i + 1, joints_vel) joints_acc_parallel.insert(2 * i + 1, joints_acc) times_parallel.insert(2 * i + 1, times) return joints_parallel, joints_vel_parallel, joints_acc_parallel, times_parallel
def eval(self, ispec, x): xx = self._xnorm(x) if isinstance(ispec, int): return legval(xx, self._coeff[ispec]) else: if ispec is None: ispec = range(self._coeff.shape[0]) y = [legval(xx, self._coeff[i]) for i in ispec] return np.array(y)
def inner_product(): #do I even need this? if BASIS_FUNC == 'legendre': pmat = np.zeros((BASIS_SIZE, BASIS_SIZE)) for i in range(BASIS_SIZE): for j in range(BASIS_SIZE): coefs_i = [0] * (i) + [1] coefs_j = [0] * (j) + [1] inside = L.legmul(coefs_i, coefs_j) integ = L.legint(inside) val = L.legval(DOMAIN[1], integ) - L.legval(DOMAIN[0], integ) pmat[i, j] = val
def eval(self, x, u, output_array=None): if output_array is None: output_array = np.zeros(x.shape) x = self.map_reference_domain(x) w_hat = work[(u, 0, True)] self.set_factor_array(u) output_array[:] = leg.legval(x, u[:-2]*self._factor) w_hat[2:] = u[:-2]*self._factor output_array -= leg.legval(x, w_hat) output_array += 0.5*(u[-1]*(1-x)+u[-2]*(1+x)) return output_array
def term_ijk(self, index): if len(index) == 2: i, j = index ci = np.diag(np.ones(i + 1))[i] cj = np.diag(np.ones(j + 1))[j] return legval(self.r[2], ci) * legval(self.r[1], cj) elif len(index) == 1: k = index[0] ck = np.diag(np.ones(k + 1))[k] return legval(self.r[0], ck)
def diffxsec_legendre_eval(sig, mu, coeff): c = coeff.T ans = np.zeros_like(mu) if (len(mu.shape) == 1): ans = sig * legval(mu, c, tensor=False) elif (len(mu.shape) == 2): ans = sig * legval(mu, c[:, None, :], tensor=False) elif (len(mu.shape) == 3): ans = sig * legval(mu, c[:, None, None, :], tensor=False) ans[np.abs(mu) > 1.0] = 0.0 return ans
def eval(self, ispec, x): xx = self._xnorm(x) if isinstance(ispec, numbers.Integral): return legval(xx, self._coeff[ispec]) else: if ispec is None: ispec = list(range(self._coeff.shape[0])) y = [legval(xx, self._coeff[i]) for i in ispec] return np.array(y)
def weights_roots(order, rules='Gauss-Lobatto'): c_leg = [1] if order == 0 else [i//order for i in xrange(order+1)] c_dleg = lgd.legder(c_leg) if rules == 'Gauss-Lobatto': xs = np.array( [-1] + list( lgd.legroots(c_dleg) ) + [1] ) ws = 2 / ( order * (order + 1) * (lgd.legval(xs, c_leg)**2) ) elif rules == 'Gauss-Legendre': xs = lgd.legroots(c_leg) ws = 2 / ( (1 - xs**2) * (lgd.legval(xs, c_dleg)**2) ) return xs, ws
def test_legmul(self) : # check values of result for i in range(5) : pol1 = [0]*i + [1] val1 = leg.legval(self.x, pol1) for j in range(5) : msg = "At i=%d, j=%d" % (i,j) pol2 = [0]*j + [1] val2 = leg.legval(self.x, pol2) pol3 = leg.legmul(pol1, pol2) val3 = leg.legval(self.x, pol3) assert_(len(pol3) == i + j + 1, msg) assert_almost_equal(val3, val1*val2, err_msg=msg)
def eval(self, x, fk, output_array=None): if output_array is None: output_array = np.zeros(x.shape) x = self.map_reference_domain(x) w_hat = work[(fk, 0)] self.set_factor_arrays(fk) output_array[:] = leg.legval(x, fk[:-4]) w_hat[2:-2] = self._factor1 * fk[:-4] output_array += leg.legval(x, w_hat[:-2]) w_hat[4:] = self._factor2 * fk[:-4] w_hat[:4] = 0 output_array += leg.legval(x, w_hat) return output_array
def test_legmul(self) : # check values of result for i in range(5) : pol1 = [0]*i + [1] val1 = leg.legval(self.x, pol1) for j in range(5) : msg = "At i=%d, j=%d" % (i, j) pol2 = [0]*j + [1] val2 = leg.legval(self.x, pol2) pol3 = leg.legmul(pol1, pol2) val3 = leg.legval(self.x, pol3) assert_(len(pol3) == i + j + 1, msg) assert_almost_equal(val3, val1*val2, err_msg=msg)
def invert_legendre_polynomial(wavemin, wavemax, ycoef, xcoef, fiber, npix_y, wave_of_y) : # Wavelength array used in 'invert_legendre_polynomial' wave = np.linspace(wavemin, wavemax, 100) # Determines value of Y, so we can know its coeficient and then its position y_of_wave = legval(u(wave, wavemin, wavemax), ycoef[fiber]) coef = legfit(u(y_of_wave, 0, npix_y), wave, deg=ycoef[fiber].size) wave_of_y[fiber] = legval(u(np.arange(npix_y).astype(float), 0, npix_y), coef) # Determines wavelength intensity (x) based on Y x_of_y = legval(u(wave_of_y[fiber], wavemin, wavemax), xcoef[fiber]) # Ascertain X by using low and high uncertainty x1_of_y = np.floor(x_of_y).astype(int) - 3 x2_of_y = np.floor(x_of_y).astype(int) + 4 return (x1_of_y, x2_of_y)
def vizualize(self, x_left, x_right, points, coefs): y_interp = legndr.legval(points[0], coefs) self.q_residual.setText(str(np.linalg.norm(points[1] - y_interp))) x_interp = np.linspace(-1, 1, len(points[0])*20) x_interp = np.concatenate((x_interp, points[0])) x_interp = np.sort(x_interp) y_interp = legndr.legval(x_interp, coefs) x_interp = (x_left + x_right) / 2 + (x_right - x_left) / 2 * x_interp points[0] = (x_left + x_right) / 2 + (x_right - x_left) / 2 * points[0] plt.plot(points[0], points[1], 'ro') plt.plot(x_interp, y_interp) plt.show()
def build_spatial_flux(self): """ Calculates the flux across all nodes. Uses current flux_coefficients values. """ for node in xrange(self.nodes): for index in xrange(self.solution_cells): normalized_index = self.normalized_index(index) flux_index = self.solution_cells*node+index coeff_start = self.order*node coeff_end = self.order*(node+1) self.flux[0, 1, flux_index] = legval(normalized_index, self.flux_coefficients[1, coeff_start:coeff_end]) self.flux[0, 0, flux_index] = legval(normalized_index, self.flux_coefficients[0, coeff_start:coeff_end])
def Hamiltonian_Legendre_polynomial(c, potential, domain, N): #potential is a constant in this case x = np.linspace(-domain / 2, domain / 2, N) delta_x = domain / (N - 1) #here, the normalized legendre polynomical has been used # for the nth polynomials, normalization constant is sqrt(2/(2n + 1)) #kinetic term K = np.zeros((N, N)) for ii in range(N): legen_left = np.zeros(N) legen_left[ii] = mt.sqrt((2 * ii + 1) / 2) for jj in range(N): deriva_array = np.zeros(N + 2) deriva_array[jj] = mt.sqrt((2 * jj + 1) / 2) legen_right_deriva = legen.legder(deriva_array, 2) #multiply them legen_multiply = legen.legmul(legen_left, legen_right_deriva) #integral legen_integral = legen.legint(legen_multiply) #calculate the matrix elements K[ii][jj] = legen.legval(domain / 2, legen_integral) - \ legen.legval(-domain / 2, legen_integral) #the S matrix, inside the [-1, 1] domain, the legendre ploynomial can be treatedas basis and satisfying <xi|xj> = delta ij, thus S matrix is a identity matrix S = np.zeros((N, N)) for ii in range(N): legen_left_S = np.zeros(N) legen_left_S[ii] = mt.sqrt((2 * ii + 1) / 2) legen_multiply_S = legen.legmul(legen_left_S, legen_left_S) legen_integral_S = legen.legint(legen_multiply_S) S[ii][ii] = legen.legval(domain / 2, legen_integral_S) - \ legen.legval(-domain / 2, legen_integral_S) K = K * -1 * c #because the potential is just a constant here, we can calculate the V matrix simply by multiply the matrix S a constant potential value V = potential * S ##divide the obtained Hamiltonian by the S matrix H = K + V return H
def icb_interface_flux_matrix(p, K, T): """The interface flux matrices for the ICB schemes, we use upwinding to get the fluxes. Denote T the translation necessary to evaluate the flux from the other cell. """ # Enhanced polynomial degree phat = p + len(K) G0 = smp.zeros(p + 1, phat + 1) G1 = smp.zeros(p + 1, phat + 1) for i in range(0, p + 1): for j in range(0, phat + 1): li = L.basis(i) lj = L.basis(j) G0[i, j] = leg.legval(-1, li.coef) * \ leg.legval(1, lj.coef) * (T**-1) G1[i, j] = leg.legval(1, li.coef) * leg.legval(1, lj.coef) # Enhancement matrix A, Ainv, B, Binv = enhance.enhancement_matrices(p, K) # Using the enhanced function in the flux (see notes 21/4/15) BL = smp.zeros(phat + 1, phat + 1) BR = smp.zeros(phat + 1, phat + 1) for i in range(p + 1): li = L.basis(i) BL[i, i] = 1 # basis.integrate_legendre_product(li,li) BR[i, i] = 1 # BL[i,i] for i, k in enumerate(K): lk = L.basis(k) int_lklk = basis.integrate_legendre_product(lk, lk) BL[i + p + 1, i + p + 1] = T # * int_lklk BR[i + p + 1, i + p + 1] = (T**(-1)) # * int_lklk # reduction matrix R = smp.zeros(phat + 1, p + 1) for i in range(p + 1): R[i, i] = 1 for i, k in enumerate(K): for j in range(p + 1): R[i + p + 1, j] = auxf.delta(k, j) # Convert to sympy matrices G0 = smp.Matrix(G0) * smp.Matrix(Ainv) * BL * R G1 = smp.Matrix(G1) * smp.Matrix(Ainv) * BL * R return G0, G1
def legplot(nterms=6): """ Purpose: calculate (2l+1)/4pi * Pl and plot Procedure: Inputs: nterms: the number of Pl to plot, starting from 0 Returns: theta values and scaled legendre polynomials """ coefs = np.zeros([nterms, nterms]) for coef in range(nterms): coefs[coef, coef] = ((2 * coef) + 1) / (4 * np.pi) npoints = 1801 thetavals = np.linspace(0, 180, npoints) xvals = np.cos(thetavals * np.pi / 180.) print 'x vals: ', xvals Pl = np.empty([nterms, npoints]) for ell in range(nterms): Pl[ell] = legval(xvals, coefs[ell]) #print 'l = ',ell,', scaled Pl = ',Pl[ell] plt.plot(thetavals, Pl[ell], label='l = ' + str(ell)) plt.xlabel('angle (degrees)') plt.ylabel('P_l * (2*l+1)/4pi') plt.title('scaled legendre polynomials') #plt.legend() plt.show() return thetavals, Pl
def get_chi(blorder_max, ydata, xdata, blindex, noise): """ Returns the best-fit Legendre polynomial to an input spectra, based on a comparison of the reduced chi-squared values for each order of the polynomial. blorder_max = maximum order of polynomial to fit ydata = spectrum y values xdata = spectrum x values blindex = the indices of the spectra to include in baseline fitting noise = rms noise of spectrum""" opts = lsq(legendreLoss, np.zeros(blorder_max + 1), args=(ydata[blindex], xdata[blindex], noise), loss='arctan') chis = [] # first entry is order=1, second is order=2, ..., up to order=blorder ymods = [] # Loop through each order of polynomial and create model baseline # and calculate that model's chi-squared values for i in np.arange(blorder_max)+1: # i is the polynomial order ymod = legendre.legval(xdata, np.array(opts.x)[0:i+1]) #+1 to get last term ymods.append(ymod) chi = redchisqg(ydata,ymod,deg=i+1) chis.append(chi) # Find the model with the lowest chi-squared value find_low = np.where(np.array(chis)==min(chis)) low_model = np.array(ymods)[find_low] return ymod
def test_legvander(self) : # check for 1d x x = np.arange(3) v = leg.legvander(x, 3) assert_(v.shape == (3, 4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[..., i], leg.legval(x, coef)) # check for 2d x x = np.array([[1, 2], [3, 4], [5, 6]]) v = leg.legvander(x, 3) assert_(v.shape == (3, 2, 4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[..., i], leg.legval(x, coef))
def leg_l(l_index, numgrid): leg_access = np.zeros(l_index + 1) leg_access[l_index] = 1 #print leg_access x = np.linspace(0,1,numgrid) y = LG.legval(x, leg_access) return x,y
def cheb_fitcurve(x, y, order): x = cheb.chebpts2(len(x)) order = 64 coef = legend.legfit(x, y, order) assert_equal(len(coef), order + 1) y1 = legend.legval(x, coef) err_1 = np.linalg.norm(y1 - y) / np.linalg.norm(y) coef = cheb.chebfit(x, y, order) assert_equal(len(coef), order + 1) thrsh = abs(coef[0] / 1000) for i in range(len(coef)): if abs(coef[i]) < thrsh: coef = coef[0:i + 1] break y2 = cheb.chebval(x, coef) err_2 = np.linalg.norm(y2 - y) / np.linalg.norm(y) plt.plot(x, y2, '.') plt.plot(x, y, '-') plt.title("nPt={} order={} err_cheby={:.6g} err_legend={:.6g}".format( len(x), order, err_2, err_1)) plt.show() assert_almost_equal(cheb.chebval(x, coef), y) # return coef
def _sph_coefs_to_corr( self ): """ computes correlation from legendre polynomial coefficients computed from spherical harmonic coefficients sets coefficients of order-l polynomials to zero """ self.corr = np.zeros( (self.n_q, self.n_q, self.n_psi) ) self.cospsi = np.linspace(-1,1, self.n_psi, endpoint=True) # Cl = Cl[:(Lmax+1),:,:] for i in range(self.n_q): for j in range(i, self.n_q): coefs = self.cl[:,i,j] # even_coefs = Cl[:int(Lmax/2),i,j] # even_coefs= self.cl[::2,i,j] # for idx in range(even_coefs.size * 2): # if idx%2 ==0: # coefs.append(even_coefs[idx/2]) # else: # coefs.append(0) # coefs = np.array(coefs) self.corr[i,j,:] = legval( self.cospsi, coefs ) self.corr[j,i,:] = self.corr[i,j,:] # copy it to the lower triangle too
def _get_weights(num_points, inner_nodes): from numpy.polynomial import legendre base_weight = 2.0 / (num_points * (num_points - 1)) p_n_minus1 = [0] * (num_points - 1) + [1] p_n_minus1_at_nodes = legendre.legval(inner_nodes, p_n_minus1) return base_weight / p_n_minus1_at_nodes**2
def baselineWithAmmonia(y, v, baselineIndex, freqthrow=4.11 * u.MHz, v0=8.5, sigmav=1.0 * u.km / u.s, line='oneone', blorder=5, noiserms=None): x = np.linspace(-1, 1, len(y)) chthrow = (freqthrow.to(u.Hz).value / acons.freq_dict[line] * 299792.458 / np.abs(v[0] - v[1])) chthrow = (np.round(chthrow)).astype(np.int) if noiserms is None: noiserms = mad1d((y - np.roll(y, -2))[baselineIndex]) opts = lsq( ammoniaLoss, np.r_[[ np.nanmax(y[baselineIndex]), v[np.nanargmax(y[baselineIndex])], 1.0 ], np.zeros(blorder + 1)], args=(y[baselineIndex], x[baselineIndex], v[baselineIndex], noiserms), kwargs={'chthrow': chthrow}, loss='soft_l1') return y - legendre.legval(x, opts.x[3:])
def chisq_leg(p, x, y, w, flag_call): ind = np.where(flag_call==1)[0] y_c = y[ind] x_c = x[ind] w_c = w[ind] chisq = np.sum( (1/(w_c)**2)*(leg.legval(x_c, p) - y_c)**2 ) / np.sum(1/w_c**2) return chisq
def basisMatrixLegendre(x,order): ''' Builds (order+1,x) 2-d array of Legendre polynomials evaluated at x Parameters ---------- x: numpy 1-d array Points at which to evaluate basis functions order: Maximum order of polynomial set Returns ------- legmtx: numpy 2d array of shape (order+1,x) Legendre polynomials evaluated at x ''' ### Construct matrix of Legendre polynomials legmtx = np.zeros((order+1,len(x))) ### Prepare matrix of Leg. poly. basis functions evaluated at x for i in range(order+1): coeffs=np.zeros(i+1) coeffs[i]=1. legmtx[i,:]=L.legval(x, coeffs) return legmtx
def Likelihood_Sph(vertex, *args): coeff, PMT_pos, event_pe, cut = args y = event_pe # fixed axis z = np.sqrt(np.sum(vertex[1:4]**2)) / shell if (np.abs(z) > 1): z = np.sign(z) cos_theta = np.sum(vertex[1:4]*PMT_pos,axis=1)\ /np.sqrt(np.sum(vertex[1:4]**2)*np.sum(PMT_pos**2,axis=1)) # accurancy and nan value cos_theta = np.nan_to_num(cos_theta) cos_theta[cos_theta > 1] = 1 cos_theta[cos_theta < -1] = -1 size = np.size(PMT_pos[:, 0]) x = np.zeros((size, cut)) # legendre coeff for i in np.arange(0, cut): c = np.zeros(cut) c[i] = 1 x[:, i] = LG.legval(cos_theta, c) k = np.zeros(cut) for i in np.arange(cut): # cubic interp k[i] = np.sum(np.polynomial.legendre.legval(z, coeff[i, :])) #k[0] = k[0] + np.log(vertex[0]) k[0] = vertex[0] expect = np.exp(np.dot(x, k)) L = -np.sum(np.sum(np.log((expect**y) * np.exp(-expect)))) return L
def baselineSpectrum(spectrum,order=1,baselineIndex=()): x=np.arange(len(spectrum)) coeffs = legendre.legfit(x[baselineIndex],spectrum[baselineIndex],order) # pdb.set_trace() spectrum -= legendre.legval(x,coeffs) return(spectrum)
def work(j): i, order = annotation[j] c = numpy.zeros(5) c[order] = 1 # watch out the eigenmode is wikipedia # no negative phase on 2nd order pole! eigenmode = eigenmodes[j] eigenmode[i].xi[...] = \ powerspec.pole(eigenmode[i].r, order=order)[:, None] \ * legval(eigenmode[i].mu, c)[None, :]
def robustBaseline(y, baselineIndex, blorder=1, noiserms=None): x = np.linspace(-1, 1, len(y)) if noiserms is None: noiserms = mad1d((y - np.roll(y, -2))[baselineIndex]) opts = lsq(legendreLoss, np.zeros(blorder + 1), args=(y[baselineIndex], x[baselineIndex], noiserms), loss='arctan') return y - legendre.legval(x, opts.x)
def test_legfit(self) : def f(x) : return x*(x - 1)*(x - 2) # Test exceptions assert_raises(ValueError, leg.legfit, [1], [1], -1) assert_raises(TypeError, leg.legfit, [[1]], [1], 0) assert_raises(TypeError, leg.legfit, [], [1], 0) assert_raises(TypeError, leg.legfit, [1], [[[1]]], 0) assert_raises(TypeError, leg.legfit, [1, 2], [1], 0) assert_raises(TypeError, leg.legfit, [1], [1, 2], 0) assert_raises(TypeError, leg.legfit, [1], [1], 0, w=[[1]]) assert_raises(TypeError, leg.legfit, [1], [1], 0, w=[1, 1]) # Test fit x = np.linspace(0, 2) y = f(x) # coef3 = leg.legfit(x, y, 3) assert_equal(len(coef3), 4) assert_almost_equal(leg.legval(x, coef3), y) # coef4 = leg.legfit(x, y, 4) assert_equal(len(coef4), 5) assert_almost_equal(leg.legval(x, coef4), y) # coef2d = leg.legfit(x, np.array([y, y]).T, 3) assert_almost_equal(coef2d, np.array([coef3, coef3]).T) # test weighting w = np.zeros_like(x) yw = y.copy() w[1::2] = 1 y[0::2] = 0 wcoef3 = leg.legfit(x, yw, 3, w=w) assert_almost_equal(wcoef3, coef3) # wcoef2d = leg.legfit(x, np.array([yw, yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T) # test scaling with complex values x points whose square # is zero when summed. x = [1, 1j, -1, -1j] assert_almost_equal(leg.legfit(x, x, 1), [0, 1])
def test_legfromroots(self) : res = leg.legfromroots([]) assert_almost_equal(trim(res), [1]) for i in range(1,5) : roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2]) pol = leg.legfromroots(roots) res = leg.legval(roots, pol) tgt = 0 assert_(len(pol) == i + 1) assert_almost_equal(leg.leg2poly(pol)[-1], 1) assert_almost_equal(res, tgt)
def test_legval(self): #check empty input assert_equal(leg.legval([], [1]).size, 0) #check normal input) x = np.linspace(-1, 1) y = [polyval(x, c) for c in Llist] for i in range(10): msg = "At i=%d" % i tgt = y[i] res = leg.legval(x, [0]*i + [1]) assert_almost_equal(res, tgt, err_msg=msg) #check that shape is preserved for i in range(3): dims = [2]*i x = np.zeros(dims) assert_equal(leg.legval(x, [1]).shape, dims) assert_equal(leg.legval(x, [1, 0]).shape, dims) assert_equal(leg.legval(x, [1, 0, 0]).shape, dims)
def dg_interface_flux_matrix(p, T): """The interface flux matrices, we use upwinding to get the fluxes Denote T the translation necessary to evaluate the flux from the other cell. There are also analytical expressions for these. See my thesis page 73. """ G0 = smp.zeros(p + 1) G1 = smp.zeros(p + 1) for i in range(0, p + 1): for j in range(0, p + 1): li = L.basis(i) lj = L.basis(j) G0[i, j] = leg.legval(-1, li.coef) * \ leg.legval(1, lj.coef) * (T**-1) G1[i, j] = leg.legval(1, li.coef) * leg.legval(1, lj.coef) return G0, G1
def __worker(rbin): rr = r[rbin] # Axis distribution beta parameters beta_axis = beta_coeffs_point( rr, self.coef, self.kmax, self.rkstep, self.sigma, self.lmax, oddl, truncate) # Detection function beta parameters in the detection frame beta_df = beta_coeffs_point( rr, df.coef, df.kmax, df.rkstep, df.sigma, df.lmax, df_oddl, truncate) # Detection function beta parameters in the lab frame beta_df = beta_df[0:lmax + 1] * plbeta # The following is too slow # res = scipy.optimize.basinhopping( # lambda x: -legendre.legval(x, beta_df), # [0.0], stepsize = 1.0/lmax, T=1.0, # minimizer_kwargs=dict(method='TNC', bounds=((-1.0,1.0),)) # ) # Find approximate position of maxmimum. Note that there # are lmax maxima/minima between -1..1, so this value of # Ns should suffice. res = scipy.optimize.brute( lambda x, *args: -legendre.legval(x, beta_df), ((-1.0, 1.0),), Ns=5.0 * lmax, ) # Refine position of maximum - note that the 'finish' # option of optimize.brute doesn't work with fmin_tnc etc respolish = scipy.optimize.minimize(lambda x: -legendre.legval(x, beta_df), [res[0]], bounds=((-1.0,1.0),), method='TNC') maxval = -respolish.fun beta = beta_axis[0:lmax + 1] * beta_df[0:lmax + 1] * wt overlap[rbin] = beta.sum() / maxval
def get_basis(deg, dofset=None): # Legendre polynomials are used as the basis of polynomials. In the basis of # Legendre polynomials is row of eye polyset = np.eye(deg+1) if dofset is None: dofset = np.linspace(-1, 1, deg+1) # Reatange dofs to have external first dofset = np.r_[dofset[0], dofset[-1], dofset[1:-1]] # Compute the nodal matrix A = np.array([legval(dofset, base) for base in polyset]) # New coefficients B = np.linalg.inv(A) # Combine the basis according to new weights basis = [lambda x, c=c: legval(x, c) for c in B] # Check that the basis is nodal assert np.allclose(np.array([f(dofset) for f in basis]), polyset) # First deriv dbasis = [lambda x, c=legder(c): legval(x, c) for c in B] return basis, dbasis
def test_legval(self) : def f(x) : return x*(x**2 - 1) #check empty input assert_equal(leg.legval([], [1]).size, 0) #check normal input) for i in range(10) : msg = "At i=%d" % i ser = np.zeros tgt = self.y[i] res = leg.legval(self.x, [0]*i + [1]) assert_almost_equal(res, tgt, err_msg=msg) #check that shape is preserved for i in range(3) : dims = [2]*i x = np.zeros(dims) assert_equal(leg.legval(x, [1]).shape, dims) assert_equal(leg.legval(x, [1,0]).shape, dims) assert_equal(leg.legval(x, [1,0,0]).shape, dims)
def leg_proj_legguass(x, signal, weights,lmax): """projection into legendre polynomial using gauss-legendre polynomial """ coefs = np.zeros(lmax + 1) weights_sum = np.sum(weights) for l in range(lmax + 1): if l%2==0: cc = np.zeros(l+1) cc[l] = 1 coefs[l] = np.sum( weights*legval(x,cc)*signal) / weights_sum*(2*l+1) return coefs
def eval(pname,fiber,wavelength,verbose=False) : legdeg=hdulist[1].header["LEGDEG"] table=hdulist[1].data paramindex=numpy.where(table["PARAM"]==pname)[0][0] wavemin=table["WAVEMIN"][paramindex] wavemax=table["WAVEMAX"][paramindex] fiber_coeffs=table["COEFF"][paramindex][fiber] wr=2*(wavelength-(wavemin+wavemax)/2)/(wavemax-wavemin) val=legval(wr,fiber_coeffs) if verbose : print pname,"fiber=",fiber,"wave=",wavelength,"wrange=",wavemin,wavemax,"coefs=",fiber_coeffs,"val=",val return val
def coeff_fig(): """Plots a sorted degree sequence and its polynomial fit (used in lifting/restriction diagram). Also plots evolution of coefficients over time for both a cpi routine and a direct simulation (currently not included in manuscript). **To generate data:**:: mpirun -n 50 ./pref_attach -n 100 -m 50000 -nms 1000000 -omw 100000 -ci 10000 -pStep 500000 mpirun -n 50 ./pref_attach -n 100 -m 50000 -nms 1000000 -omw 100000 -ci 10000 -pStep 500000 -noinit cp ./paper-data/other-runs/withinitfitted_coeffs0.csv ./manuscript-materials/data cp ./paper-data/other-runs/withinitpre_proj_degs0.csv ./manuscript-materials/data cp ./paper-data/other-runs/withinittimes0.csv ./manuscript-materials/data cp ./paper-data/other-runs/noinittimes0.csv ./manuscript-materials/data cp ./paper-data/other-runs/noinitfitted_coeffs0.csv ./manuscript-materials/data cp ./paper-data/other-runs/noinitpre_proj_degs0.csv ./manuscript-materials/data """ init = "noinit" times = np.genfromtxt(data_directory + init + 'times0.csv', delimiter=',', skip_header=True) degs = np.genfromtxt(data_directory + init + 'pre_proj_degs0.csv', delimiter=',', skip_header=True) fitted_coeffs = np.genfromtxt(data_directory + init + 'fitted_coeffs0.csv', delimiter=',', skip_header=True) init = "withinit" times_cpi = np.genfromtxt(data_directory + init + 'times0.csv', delimiter=',', skip_header=True) degs_cpi = np.genfromtxt(data_directory + init + 'pre_proj_degs0.csv', delimiter=',', skip_header=True) fitted_coeffs_cpi = np.genfromtxt(data_directory + init + 'fitted_coeffs0.csv', delimiter=',', skip_header=True) gsize = degs.shape[1] fig = plt.figure() ax = fig.add_subplot(111) index = 50 # arbitrary index, should show some curvature ax.scatter(np.arange(gsize), degs[index], label='Sorted degree sequence') ax.plot(np.arange(gsize), npl.legval(np.arange(gsize), fitted_coeffs[index]), c='r', label='Polynomial fit') ax.set_xlim((0,gsize)) ax.set_xlabel('Vertex') ax.set_ylabel('Degree') ax.legend(loc=4, fontsize=42) fig.subplots_adjust(left=0.1, bottom=0.11) ncoeffs = fitted_coeffs.shape[1] for i in range(ncoeffs): fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(times, fitted_coeffs[:,i], label='Direct simulation') ax.scatter(times_cpi, fitted_coeffs_cpi[:,i], label='CPI') ax.set_xlabel('Step') ax.set_ylabel(r'$c_' + str(i) + '$') ax.legend() plt.show()
def test_legendre_val(): """Test Legendre polynomial (derivative) equivalence """ rng = np.random.RandomState(0) # check table equiv xs = np.linspace(-1., 1., 1000) n_terms = 100 # True, numpy vals_np = legendre.legvander(xs, n_terms - 1) # Table approximation for fun, nc in zip([_get_legen_lut_fast, _get_legen_lut_accurate], [100, 50]): lut, n_fact = _get_legen_table('eeg', n_coeff=nc, force_calc=True) vals_i = fun(xs, lut) # Need a "1:" here because we omit the first coefficient in our table! assert_allclose(vals_np[:, 1:vals_i.shape[1] + 1], vals_i, rtol=1e-2, atol=5e-3) # Now let's look at our sums ctheta = rng.rand(20, 30) * 2.0 - 1.0 beta = rng.rand(20, 30) * 0.8 lut_fun = partial(fun, lut=lut) c1 = _comp_sum_eeg(beta.flatten(), ctheta.flatten(), lut_fun, n_fact) c1.shape = beta.shape # compare to numpy n = np.arange(1, n_terms, dtype=float)[:, np.newaxis, np.newaxis] coeffs = np.zeros((n_terms,) + beta.shape) coeffs[1:] = (np.cumprod([beta] * (n_terms - 1), axis=0) * (2.0 * n + 1.0) * (2.0 * n + 1.0) / n) # can't use tensor=False here b/c it isn't in old numpy c2 = np.empty((20, 30)) for ci1 in range(20): for ci2 in range(30): c2[ci1, ci2] = legendre.legval(ctheta[ci1, ci2], coeffs[:, ci1, ci2]) assert_allclose(c1, c2, 1e-2, 1e-3) # close enough... # compare fast and slow for MEG ctheta = rng.rand(20 * 30) * 2.0 - 1.0 beta = rng.rand(20 * 30) * 0.8 lut, n_fact = _get_legen_table('meg', n_coeff=10, force_calc=True) fun = partial(_get_legen_lut_fast, lut=lut) coeffs = _comp_sums_meg(beta, ctheta, fun, n_fact, False) lut, n_fact = _get_legen_table('meg', n_coeff=20, force_calc=True) fun = partial(_get_legen_lut_accurate, lut=lut) coeffs = _comp_sums_meg(beta, ctheta, fun, n_fact, False)
def recompute_legendre_coefficients(xcoef,ycoef,wavemin,wavemax,degxx,degxy,degyx,degyy,dx_coeff,dy_coeff) : """ Modifies legendre coefficients of an input trace set using polynomial coefficents (as defined by the routine monomials) Args: xcoef : 2D np.array of shape (nfibers,ncoef) containing Legendre coefficents for each fiber to convert wavelenght to XCCD ycoef : 2D np.array of shape (nfibers,ncoef) containing Legendre coefficents for each fiber to convert wavelenght to YCCD wavemin : float wavemax : float. wavemin and wavemax are used to define a reduced variable legx(wave,wavemin,wavemax)=2*(wave-wavemin)/(wavemax-wavemin)-1 used to compute the traces, xccd=legval(legx(wave,wavemin,wavemax),xtrace[fiber]) degxx : int, degree of polynomial for x shifts as a function of x (x is axis=1 in numpy image array, AXIS=0 in FITS, cross-dispersion axis = fiber number direction) degxy : int, degree of polynomial for x shifts as a function of y (y is axis=0 in numpy image array, AXIS=1 in FITS, wavelength dispersion axis) degyx : int, degree of polynomial for y shifts as a function of x degyy : int, degree of polynomial for y shifts as a function of y dx_coeff : 1D np.array of polynomial coefficients of size (degxx*degxy) as defined by the routine monomials. dy_coeff : 1D np.array of polynomial coefficients of size (degyx*degyy) as defined by the routine monomials. Returns: xcoef : 2D np.array of shape (nfibers,ncoef) with modified Legendre coefficents ycoef : 2D np.array of shape (nfibers,ncoef) with modified Legendre coefficents """ wave=np.linspace(wavemin,wavemax,100) nfibers=xcoef.shape[0] rw=legx(wave,wavemin,wavemax) for fiber in range(nfibers) : x = legval(rw,xcoef[fiber]) y = legval(rw,ycoef[fiber]) m=monomials(x,y,degxx,degxy) dx=m.T.dot(dx_coeff) xcoef[fiber]=legfit(rw,x+dx,deg=xcoef.shape[1]-1) m=monomials(x,y,degyx,degyy) dy=m.T.dot(dy_coeff) ycoef[fiber]=legfit(rw,y+dy,deg=ycoef.shape[1]-1) return xcoef,ycoef
def test_evenly_spaced(self): import numpy as np from numpy.polynomial import legendre import six num_points = 17 points = np.linspace(0, 1, num_points) result = self._call_func_under_test(points) self.assertEqual(result.shape, (num_points, num_points)) self.assertTrue(result.flags.f_contiguous) expected_result = np.zeros((num_points, num_points)) for n in six.moves.xrange(num_points): leg_coeffs = [0] * n + [1] expected_result[:, n] = legendre.legval(points, leg_coeffs) self.assertTrue(np.allclose(result, expected_result)) frob_err = np.linalg.norm(result - expected_result, ord='fro') self.assertTrue(frob_err < 1e-13)
def _calc_h(cosang, stiffness=4, num_lterms=50): """Calculate spherical spline h function between points on a sphere. Parameters ---------- cosang : array-like of float, shape(n_channels, n_channels) cosine of angles between pairs of points on a spherical surface. This is equivalent to the dot product of unit vectors. stiffness : float stiffness of the spline. Also referred to as `m`. num_lterms : int number of Legendre terms to evaluate. H : np.ndrarray of float, shape(n_channels, n_channels) The H matrix. """ factors = [(2 * n + 1) / (n ** (stiffness - 1) * (n + 1) ** (stiffness - 1) * 4 * np.pi) for n in range(1, num_lterms + 1)] return legval(cosang, [0] + factors)
def contFitLegendreAboutLine(wave,flux,err,restlam,z,velfitregions,uniform=True,**kwargs): ''' Fits a continuum over a spectral region using the formalism of Sembach & Savage 1992, estimating the uncertainty at each point of the continuum. Parameters ---------- wave flux err restlam z velfitregions uniform Returns ------- ''' vels=joebgoodies.veltrans(z,wave,restlam) ### Find indices corresponding to velocities defined in velfitregions fitidxs=[] for reg in velfitregions: thesevels=np.where((vels>=reg[0])&(vels<=reg[1]))[0] fitidxs.extend(thesevels) if uniform != True: fitsol,err,parsol,errmtx,scalefac = fitLegendre(vels[fitidxs],flux[fitidxs], sig=err[fitidxs],**kwargs) else: fitsol,err,parsol,errmtx,scalefac = fitLegendre(vels[fitidxs],flux[fitidxs],**kwargs) ### Normalize x so that domain of fit is -1 to +1 vscale = vels/scalefac # must scale to fitted domain ### Evaluate continuum using all points, not just those in fit regions continuum = L.legval(vels/scalefac,parsol) err = errorsLegendre(vscale,errmtx) return wave,continuum,err