def matrixCheby2D_7(x, y): '''Create and return a 2D array of Tx_i, Ty_j ordered as needed for use with cure distortion solutions. Parameters ---------- x, y : numbers or ndarray-like values of x and y where to compute the Ts Returns ------- two dimensional array with len(x) rows and 36 columns ''' T0x, T1x, T2x, T3x, T4x, T5x, T6x, T7x = chebvander(x, 7).T T0y, T1y, T2y, T3y, T4y, T5y, T6y, T7y = chebvander(y, 7).T return np.vstack( np.broadcast_arrays(T7x, T6x, T5x, T4x, T3x, T2x, T1x, T7y, T6y, T5y, T4y, T3y, T2y, T1y, T6x * T1y, T1x * T6y, T5x * T2y, T2x * T5y, T4x * T3y, T3x * T4y, T5x * T1y, T1x * T5y, T4x * T2y, T2x * T4y, T3x * T3y, T4x * T1y, T1x * T4y, T3x * T2y, T2x * T3y, T3x * T1y, T1x * T3y, T2x * T2y, T2x * T1y, T1x * T2y, T1x * T1y, T0x)).T
def orthpoly_coef(f, f_weighting, n_deg, **kwarg): """ Compute expension coefficients of f(x) under orthogonal polynomial basis with respect to weighting function f_weighting(x). Assume f and f_weighting is defined on (-1,1). Parameters ---------- f : The function to expended, defined in (-1,1). Need to accept vector input. If None, return Vandermonde matrix and interpolation points. f_weighting : weighting function for the inner product. """ if f_weighting == 'chebyshev': x_sample = chebyshev_roots(n_deg + 1) V = cheb.chebvander(x_sample, n_deg) # Note: seems that cond(V) -> sqrt(2) elif f_weighting == 'legendre': x_sample = legendre_roots(n_deg + 1) V = sqrt(arange(n_deg + 1) + 0.5) * lege.legvander(x_sample, n_deg) # Note: seems that cond(V) -> sqrt(n_deg) else: x_sample = legendre_roots(n_deg + 1) basis_repr_coef = get_orthpoly(n_deg, f_weighting, 100, **kwarg) V = dot(cheb.chebvander(x_sample, n_deg), basis_repr_coef) if f == None: # Return Pseudo-Vandermonde matrix and interpolation points. return V, x_sample y_sample = f(x_sample) coef = np.linalg.solve(V, y_sample) return coef
def init(self, N): self.points, self.weights = self.points_and_weights(N) k = self.wavenumbers(N) # Build Vandermonde matrix. Note! N points in real space gives N-3 bases in spectral space self.V = n_cheb.chebvander(self.points, N - 3).T - ( (k / (k + 2))**2)[:, np.newaxis] * n_cheb.chebvander( self.points, N - 1)[:, 2:].T self.V = self.V[1:, :]
def init(self, N): self.points, self.weights = self.points_and_weights(N) k = self.wavenumbers(N) # Build Vandermonde matrix. Note! N points in real space gives N-3 bases in spectral space self.V = ( n_cheb.chebvander(self.points, N - 3).T - ((k / (k + 2)) ** 2)[:, np.newaxis] * n_cheb.chebvander(self.points, N - 1)[:, 2:].T ) self.V = self.V[1:, :]
def init(self, N): self.points, self.weights = self.points_and_weights(N) k = self.wavenumbers(N) # Build Vandermonde matrix. self.V = n_cheb.chebvander( self.points, N - 5).T - (2 * (k + 2) / (k + 3))[:, np.newaxis] * n_cheb.chebvander( self.points, N - 3)[:, 2:].T + ( (k + 1) / (k + 3))[:, np.newaxis] * n_cheb.chebvander( self.points, N - 1)[:, 4:].T
def test_chebvander(self): # check for 1d x x = np.arange(3) v = ch.chebvander(x, 3) assert_(v.shape == (3, 4)) for i in range(4): coef = [0] * i + [1] assert_almost_equal(v[..., i], ch.chebval(x, coef)) # check for 2d x x = np.array([[1, 2], [3, 4], [5, 6]]) v = ch.chebvander(x, 3) assert_(v.shape == (3, 2, 4)) for i in range(4): coef = [0] * i + [1] assert_almost_equal(v[..., i], ch.chebval(x, coef))
def test_chebvander(self) : # check for 1d x x = np.arange(3) v = ch.chebvander(x, 3) assert_(v.shape == (3,4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[...,i], ch.chebval(x, coef)) # check for 2d x x = np.array([[1,2],[3,4],[5,6]]) v = ch.chebvander(x, 3) assert_(v.shape == (3,2,4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[...,i], ch.chebval(x, coef))
def spec_calibration(self, theta=None, obs=None, spec=None, **kwargs): """Implements a Chebyshev polynomial calibration model. This uses least-squares to find the maximum-likelihood Chebyshev polynomial of a certain order describing the ratio of the observed spectrum to the model spectrum, conditional on all other parameters, using least squares. If emission lines are being marginalized out, they are excluded from the least-squares fit. :returns cal: A polynomial given by :math:`\Sum_{m=0}^M a_{m} * T_m(x)`. """ if theta is not None: self.set_parameters(theta) # norm = self.params.get('spec_norm', 1.0) polyopt = ((self.params.get('polyorder', 0) > 0) & (obs.get('spectrum', None) is not None)) if polyopt: order = self.params['polyorder'] # generate mask # remove region around emission lines if doing analytical marginalization mask = obs.get('mask', np.ones_like(obs['wavelength'], dtype=bool)).copy() if self.params.get('marginalize_elines', False): mask[self._eline_wavelength_mask] = 0 # map unmasked wavelengths to the interval -1, 1 # masked wavelengths may have x>1, x<-1 x = self.wave_to_x(obs["wavelength"], mask) y = (obs['spectrum'] / spec)[mask] - 1.0 yerr = (obs['unc'] / spec)[mask] yvar = yerr**2 A = chebvander(x[mask], order) ATA = np.dot(A.T, A / yvar[:, None]) reg = self.params.get('poly_regularization', 0.) if np.any(reg > 0): ATA += reg**2 * np.eye(order) ATAinv = np.linalg.inv(ATA) c = np.dot(ATAinv, np.dot(A.T, y / yvar)) Afull = chebvander(x, order) poly = np.dot(Afull, c) self._poly_coeffs = c else: poly = np.zeros_like(self._outwave) return (1.0 + poly)
def optimal_polynomial(wave, model, obs, unc, order=10, mask=slice(None)): """ :param wave: Wavelengths, ndarray of shape (nw,) :param model: Model spectrum, same shape as `wave` :param obs: Observed spectrum, same shape as `wave` :param unc: 1sigma uncertainties on the observed spectrum, same shape as `wave` :param mask: A boolean array with `True` for good pixels and `False` for bad pixels, ndarray of same shape as `wave` :param order: order of the polynomial :returns poly: The optimal polynomial vector, ndarray of same shape as `wave` :returns coeffs: Coefficients of the Chabyshev polynomial. Note these are only valid when used with the wavelength vector transformed into `x` """ # map unmasked wavelengths to the interval -1, 1 # masked wavelengths may have x>1, x<-1 x = wave - wave[mask].min() x = 2.0 * (x / (x[mask]).max()) - 1.0 y = (obs / model)[mask] yerr = (unc / model)[mask] yvar = yerr**2 A = chebvander(x[mask], order) ATA = np.dot(A.T, A / yvar[:, None]) try: ATAinv = np.linalg.inv(ATA) c = np.dot(ATAinv, np.dot(A.T, y / yvar)) Afull = chebvander(x, order) poly = np.dot(Afull, c) return poly, c except: #handle it return None, None
def chebinterp(x,f,y): """ Interpolate a function f on a set of points x onto a set of points y x and y should must be in [-1,1]""" n = len(x) Tx = chebvander(x,n-1) a = solve(Tx,f) p = chebval(y,a) return p
def chebinterp(x, f, y): """ Interpolate a function f on a set of points x onto a set of points y x and y should must be in [-1,1]""" n = len(x) Tx = chebvander(x, n - 1) a = solve(Tx, f) p = chebval(y, a).T return p
def vandermonde(self, x): """Return Chebyshev Vandermonde matrix Parameters ---------- x : array points for evaluation """ return n_cheb.chebvander(x, self.N-1)
def spec_calibration(self, theta=None, obs=None, **kwargs): """Implements a Chebyshev polynomial calibration model. This uses least-squares to find the maximum-likelihood Chebyshev polynomial of a certain order describing the ratio of the observed spectrum to the model spectrum, conditional on all other parameters, using least squares. The first coefficient is always set to 1, as the overall normalization is controlled by ``spec_norm``. :returns cal: A polynomial given by 'spec_norm' * (1 + \Sum_{m=1}^M a_{m} * T_m(x)). """ if theta is not None: self.set_parameters(theta) norm = self.params.get('spec_norm', 1.0) polyopt = ((self.params.get('polyorder', 0) > 0) & (obs.get('spectrum', None) is not None)) if polyopt: order = self.params['polyorder'] mask = obs.get('mask', slice(None)) # map unmasked wavelengths to the interval -1, 1 # masked wavelengths may have x>1, x<-1 x = self.wave_to_x(obs["wavelength"], mask) y = (obs['spectrum'] / self._spec)[mask] / norm - 1.0 yerr = (obs['unc'] / self._spec)[mask] / norm yvar = yerr**2 A = chebvander(x[mask], order)[:, 1:] ATA = np.dot(A.T, A / yvar[:, None]) reg = self.params.get('poly_regularization', 0.) if np.any(reg > 0): ATA += reg**2 * np.eye(order) ATAinv = np.linalg.inv(ATA) c = np.dot(ATAinv, np.dot(A.T, y / yvar)) Afull = chebvander(x, order)[:, 1:] poly = np.dot(Afull, c) self._poly_coeffs = c else: poly = 0.0 return (1.0 + poly) * norm
def spec_calibration(self, theta=None, obs=None, **kwargs): """Implements a Chebyshev polynomial calibration model. This uses least-squares to find the maximum-likelihood Chebyshev polynomial of a certain order describing the ratio of the observed spectrum to the model spectrum, conditional on all other parameters, using least squares. The first coefficient is always set to 1, as the overall normalization is controlled by ``spec_norm``. :returns cal: A polynomial given by 'spec_norm' * (1 + \Sum_{m=1}^M a_{m} * T_m(x)). """ if theta is not None: self.set_parameters(theta) norm = self.params.get('spec_norm', 1.0) polyopt = ((self.params.get('polyorder', 0) > 0) & (obs.get('spectrum', None) is not None)) if polyopt: order = self.params['polyorder'] mask = obs.get('mask', slice(None)) # map unmasked wavelengths to the interval -1, 1 # masked wavelengths may have x>1, x<-1 x = obs['wavelength'] - (obs['wavelength'][mask]).min() x = 2.0 * (x / (x[mask]).max()) - 1.0 y = (obs['spectrum'] / self._spec)[mask] / norm - 1.0 yerr = (obs['unc'] / self._spec)[mask] / norm yvar = yerr**2 A = chebvander(x[mask], order)[:, 1:] ATA = np.dot(A.T, A / yvar[:, None]) reg = self.params.get('poly_regularization', 0.) if np.any(reg > 0): ATA += reg**2 * np.eye(order) ATAinv = np.linalg.inv(ATA) c = np.dot(ATAinv, np.dot(A.T, y / yvar)) Afull = chebvander(x, order)[:, 1:] poly = np.dot(Afull, c) else: poly = 0.0 return (1.0 + poly) * norm
def chebVander4d(locations, deg): # stolen straight from legvander3d and mondified n = locations.shape[1] ideg = [int(d) for d in deg] is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)] if is_valid != [ True, ] * n: raise ValueError("degrees must be non-negative integers") vi = [cheb.chebvander(locations[:, i], deg[i]) for i in range(n)] v = vi[0][..., None, None, None] * vi[1][..., None, :, None, None] * vi[2][ ..., None, None, :, None] * vi[3][..., None, None, None, :] return v.reshape(v.shape[:-n] + (-1, ))
def test_modal_to_nodal_matrix_chebyshev(self): for quadrature in [Quadrature.Gauss, Quadrature.GaussLobatto]: for num_coll_points in range(2, 13): mesh = Mesh1D(num_coll_points, Basis.Chebyshev, quadrature) coll_points = collocation_points(mesh) mtn_numpy = chebyshev.chebvander(coll_points, num_coll_points - 1) mtn_spectre = modal_to_nodal_matrix(mesh) np.testing.assert_allclose(mtn_spectre, mtn_numpy, 1e-12, 1e-12) ntm_spectre = nodal_to_modal_matrix(mesh) np.testing.assert_allclose(np.matmul(mtn_spectre, ntm_spectre), np.identity(num_coll_points), 1e-12, 1e-12)
def get_orthpoly(n_deg, f_weighting, n_extra_point=10, return_coef=True, representation='chebyshev', integral_method='legendre'): """ Get orthogonal polynomials with respect to the weighting (f_weighting). The polynomials are represented by coefficients of Chebyshev polynomials. Evaluate it as: np.dot(cheb.chebvander(set_of_x, n_deg), repr_coef) See weighted_orthpoly1.py for validation of this algorithm. """ n_sampling = n_deg + 1 + n_extra_point # Do the intergration by discrete sampling at good points. if integral_method == 'chebyshev': # Here we use (first kind) Chebyshev points. x_sampling = chebyshev_roots(n_sampling) # Put together the weighting and the weighting of the Gauss-Chebyshev quadrature. diag_weight = np.array( [f_weighting(x) / cheb.chebweight(x) for x in x_sampling]) * (pi / n_sampling) elif integral_method == 'legendre': # Use Gauss-Legendre quadrature. x_sampling, int_weight = lege.leggauss(n_sampling) diag_weight = np.array( [f_weighting(x) * w for x, w in zip(x_sampling, int_weight)]) if representation == 'chebyshev': V = cheb.chebvander(x_sampling, n_deg) else: V = lege.legvander(x_sampling, n_deg) # Get basis from chol of the Gramian matrix. # inner_prod_matrix = dot(V.T, diag_weight[:, np.newaxis] * V) # repr_coef = inv(cholesky(inner_prod_matrix).T) # QR decomposition should give more accurate result. repr_coef = inv(qr(sqrt(diag_weight[:, np.newaxis]) * V, mode='r')) repr_coef = repr_coef * sign(sum(repr_coef, axis=0)) if return_coef: return repr_coef else: if representation == 'chebyshev': polys = [cheb.Chebyshev(repr_coef[:, i]) for i in range(n_deg + 1)] else: polys = [lege.Legendre(repr_coef[:, i]) for i in range(n_deg + 1)] return polys
def genericChebVander(locations, deg): # stolen straight from legvander3d and modified n = locations.shape[1] ideg = [int(d) for d in deg] is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)] if is_valid != [ True, ] * n: raise ValueError("degrees must be non-negative integers") vi = [cheb.chebvander(locations[:, i], deg[i]) for i in range(n)] indexingTuples = [] raise NotImplementedError # v = vx[..., None, None]*vy[..., None,:, None]*vz[..., None, None,:] return v.reshape(v.shape[:-n] + (-1, ))
def test_100(self): x, w = cheb.chebgauss(100) # test orthogonality. Note that the results need to be normalized, # otherwise the huge values that can arise from fast growing # functions like Laguerre can be very confusing. v = cheb.chebvander(x, 99) vv = np.dot(v.T * w, v) vd = 1/np.sqrt(vv.diagonal()) vv = vd[:, None] * vv * vd assert_almost_equal(vv, np.eye(100)) # check that the integral of 1 is correct tgt = np.pi assert_almost_equal(w.sum(), tgt)
def test_100(self): x, w = cheb.chebgauss(100) # test orthogonality. Note that the results need to be normalized, # otherwise the huge values that can arise from fast growing # functions like Laguerre can be very confusing. v = cheb.chebvander(x, 99) vv = np.dot(v.T * w, v) vd = 1/np.sqrt(vv.diagonal()) vv = vd[:,None] * vv * vd assert_almost_equal(vv, np.eye(100)) # check that the integral of 1 is correct tgt = np.pi assert_almost_equal(w.sum(), tgt)
def recovery_matrix_cheb_Strassen(C_tilda, N, m, n, saved_nodes, l, p): x = np.arange(1, N + 1) x = np.cos((2 * x - 1) * np.pi / 2 / N) chebvander = cheb.chebvander(x, m * n - 1).astype(np.float64) H = generate_matrix_H(m, n) chebvander_pinv = np.linalg.pinv((chebvander @ H)[saved_nodes]) C_tilda_reshaped = np.hstack([C_tilda[i::l] for i in range(l)]) C_rec_reshaped = chebvander_pinv @ C_tilda_reshaped C_rec = C_rec_reshaped[::m + 1] C_rec = np.vstack([np.split(c, l) for c in C_rec]) return C_rec
def euler_error(outputs, all_seq, input_n, dim_used, N): """ :param outputs: :param all_seq: :param input_n: :param dim_used: :return: """ n, seq_len, dim_full_len = all_seq.data.shape dim_used_len = len(dim_used) t = np.arange(1, N + 1, 1) A = chebyshev.chebvander(t, N - 1) A = Variable(torch.from_numpy(A)).float().cuda() outputs_t = torch.mm(A, outputs.view(-1, N).transpose(0, 1)) outputs_exp = outputs_t.transpose(0, 1).view(-1, dim_used_len, seq_len).transpose(1, 2) pred_expmap = all_seq.clone() dim_used = np.array(dim_used) pred_expmap[:, :, dim_used] = outputs_exp pred_expmap = pred_expmap[:, input_n:, :].contiguous().view(-1, dim_full_len) targ_expmap = all_seq[:, input_n:, :].clone().contiguous().view( -1, dim_full_len) # pred_expmap[:, 0:6] = 0 # targ_expmap[:, 0:6] = 0 pred_expmap = pred_expmap.view(-1, 3) targ_expmap = targ_expmap.view(-1, 3) pred_eul = data_utils.rotmat2euler_torch( data_utils.expmap2rotmat_torch(pred_expmap)) pred_eul = pred_eul.view(-1, dim_full_len) targ_eul = data_utils.rotmat2euler_torch( data_utils.expmap2rotmat_torch(targ_expmap)) targ_eul = targ_eul.view(-1, dim_full_len) mean_errors = torch.mean(torch.norm(pred_eul - targ_eul, 2, 1)) return mean_errors
def sen_loss(outputs, all_seq, dim_used, N): """ :param outputs: N * (seq_len*dim_used_len) :param all_seq: N * seq_len * dim_full_len :param input_n: :param dim_used: :return: """ n, seq_len, dim_full_len = all_seq.data.shape dim_used_len = len(dim_used) dim_used = np.array(dim_used) t = np.arange(1, N + 1, 1) A = chebyshev.chebvander(t, N - 1) A = Variable(torch.from_numpy(A)).float().cuda() predict = torch.mm(A, outputs.view(-1, N).t()) pred_expmap = predict.t().view(-1, dim_used_len, seq_len).permute(0, 2, 1) targ_expmap = all_seq.clone()[:, :, dim_used] loss = torch.mean( torch.sum(torch.abs(pred_expmap - targ_expmap), dim=2).view(-1)) return loss
def mpjpe_error(outputs, all_seq, input_n, dim_used, N): """ :param outputs: :param all_seq: :param input_n: :param dim_used: :param data_mean: :param data_std: :return: """ n, seq_len, dim_full_len = all_seq.data.shape # batch, N, 99 dim_used_len = len(dim_used) # 48 t = np.arange(1, N + 1, 1) A = chebyshev.chebvander(t, N - 1) A = Variable(torch.from_numpy(A)).float().cuda() outputs_t = torch.mm(A, outputs.view(-1, N).transpose(0, 1)) outputs_exp = outputs_t.transpose(0, 1).view(-1, dim_used_len, seq_len).transpose(1, 2) pred_expmap = all_seq.clone() dim_used = np.array(dim_used) pred_expmap[:, :, dim_used] = outputs_exp pred_expmap = pred_expmap[:, input_n:, :].contiguous().view( -1, dim_full_len).clone() targ_expmap = all_seq[:, input_n:, :].clone().contiguous().view( -1, dim_full_len) pred_expmap[:, 0:6] = 0 targ_expmap[:, 0:6] = 0 targ_p3d = data_utils.expmap2xyz_torch(targ_expmap).view(-1, 3) pred_p3d = data_utils.expmap2xyz_torch(pred_expmap).view(-1, 3) mean_3d_err = torch.mean(torch.norm(targ_p3d - pred_p3d, 2, 1)) return mean_3d_err
def ValFun(x): scale = -1 + 2 * (x - θ_min) / (θ_max - θ_min) p_fun = np.dot(cheb.chebvander(scale, order - 1), c) return -p_fun
def p_fun2(x): scale = -1 + 2 * (x[1] - θ_min) / (θ_max - θ_min) p_fun = - (u(x[0],mbar) \ + self.β * np.dot(cheb.chebvander(scale, order - 1), c)) return p_fun
def solve_bellman(self, θ_min, θ_max, order, disp=False, tol=1e-7, maxiters=100): """ Continuous Method to solve the Bellman equation in section 25.3 """ mbar = self.mbar # Utility and production functions uc = lambda c: np.log(c) uc_p = lambda c: 1 / c v = lambda m: 1 / 500 * (mbar * m - 0.5 * m**2)**0.5 v_p = lambda m: 0.5 / 500 * (mbar * m - 0.5 * m**2)**(-0.5) * (mbar - m ) u = lambda h, m: uc(f(h, m)) + v(m) def f(h, m): x = m * (h - 1) f = 180 - (0.4 * x)**2 return f def θ(h, m): x = m * (h - 1) θ = uc_p(f(h, m)) * (m + x) return θ # Bounds for Maximization lb1 = np.array([self.h_min, 0, θ_min]) ub1 = np.array([self.h_max, self.mbar - 1e-5, θ_max]) lb2 = np.array([self.h_min, θ_min]) ub2 = np.array([self.h_max, θ_max]) # Initialize Value Function coefficients # Calculate roots of Chebyshev polynomial k = np.linspace(order, 1, order) roots = np.cos((2 * k - 1) * np.pi / (2 * order)) # Scale to approximation space s = θ_min + (roots - -1) / 2 * (θ_max - θ_min) # Create a basis matrix Φ = cheb.chebvander(roots, order - 1) c = np.zeros(Φ.shape[0]) # Function to minimize and constraints def p_fun(x): scale = -1 + 2 * (x[2] - θ_min) / (θ_max - θ_min) p_fun = - (u(x[0], x[1]) \ + self.β * np.dot(cheb.chebvander(scale, order - 1), c)) return p_fun def p_fun2(x): scale = -1 + 2 * (x[1] - θ_min) / (θ_max - θ_min) p_fun = - (u(x[0],mbar) \ + self.β * np.dot(cheb.chebvander(scale, order - 1), c)) return p_fun cons1 = ({ 'type': 'eq', 'fun': lambda x: uc_p(f(x[0], x[1])) * x[1] * (x[0] - 1) + v_p(x[1]) * x[1] + self.β * x[2] - θ }, { 'type': 'eq', 'fun': lambda x: uc_p(f(x[0], x[1])) * x[0] * x[1] - θ }) cons2 = ({ 'type': 'ineq', 'fun': lambda x: uc_p(f(x[0], mbar)) * mbar * (x[0] - 1) + v_p(mbar) * mbar + self.β * x[1] - θ }, { 'type': 'eq', 'fun': lambda x: uc_p(f(x[0], mbar)) * x[0] * mbar - θ }) bnds1 = np.concatenate([lb1.reshape(3, 1), ub1.reshape(3, 1)], axis=1) bnds2 = np.concatenate([lb2.reshape(2, 1), ub2.reshape(2, 1)], axis=1) # Bellman Iterations diff = 1 iters = 1 while diff > tol: # 1. Maximization, given value function guess p_iter1 = np.zeros(order) for i in range(order): θ = s[i] res = minimize(p_fun, lb1 + (ub1 - lb1) / 2, method='SLSQP', bounds=bnds1, constraints=cons1, tol=1e-10) if res.success == True: p_iter1[i] = -p_fun(res.x) res = minimize(p_fun2, lb2 + (ub2 - lb2) / 2, method='SLSQP', bounds=bnds2, constraints=cons2, tol=1e-10) if -p_fun2(res.x) > p_iter1[i] and res.success == True: p_iter1[i] = -p_fun2(res.x) # 2. Bellman updating of Value Function coefficients c1 = np.linalg.solve(Φ, p_iter1) # 3. Compute distance and update diff = np.linalg.norm(c - c1) if bool(disp == True): print(diff) c = np.copy(c1) iters = iters + 1 if iters > maxiters: print( 'Convergence failed after {} iterations'.format(maxiters)) break self.θ_grid = s self.p_iter = p_iter1 self.Φ = Φ self.c = c print('Convergence achieved after {} iterations'.format(iters)) # Check residuals θ_grid_fine = np.linspace(θ_min, θ_max, 100) resid_grid = np.zeros(100) p_grid = np.zeros(100) θ_prime_grid = np.zeros(100) m_grid = np.zeros(100) h_grid = np.zeros(100) for i in range(100): θ = θ_grid_fine[i] res = minimize(p_fun, lb1 + (ub1 - lb1) / 2, method='SLSQP', bounds=bnds1, constraints=cons1, tol=1e-10) if res.success == True: p = -p_fun(res.x) p_grid[i] = p θ_prime_grid[i] = res.x[2] h_grid[i] = res.x[0] m_grid[i] = res.x[1] res = minimize(p_fun2, lb2 + (ub2 - lb2) / 2, method='SLSQP', bounds=bnds2, constraints=cons2, tol=1e-10) if -p_fun2(res.x) > p and res.success == True: p = -p_fun2(res.x) p_grid[i] = p θ_prime_grid[i] = res.x[1] h_grid[i] = res.x[0] m_grid[i] = self.mbar scale = -1 + 2 * (θ - θ_min) / (θ_max - θ_min) resid_grid[i] = np.dot(cheb.chebvander(scale, order - 1), c) - p self.resid_grid = resid_grid self.θ_grid_fine = θ_grid_fine self.θ_prime_grid = θ_prime_grid self.m_grid = m_grid self.h_grid = h_grid self.p_grid = p_grid self.x_grid = m_grid * (h_grid - 1) # Simulate θ_series = np.zeros(31) m_series = np.zeros(30) h_series = np.zeros(30) # Find initial θ def ValFun(x): scale = -1 + 2 * (x - θ_min) / (θ_max - θ_min) p_fun = np.dot(cheb.chebvander(scale, order - 1), c) return -p_fun res = minimize(ValFun, (θ_min + θ_max) / 2, bounds=[(θ_min, θ_max)]) θ_series[0] = res.x # Simulate for i in range(30): θ = θ_series[i] res = minimize(p_fun, lb1 + (ub1 - lb1) / 2, method='SLSQP', bounds=bnds1, constraints=cons1, tol=1e-10) if res.success == True: p = -p_fun(res.x) h_series[i] = res.x[0] m_series[i] = res.x[1] θ_series[i + 1] = res.x[2] res2 = minimize(p_fun2, lb2 + (ub2 - lb2) / 2, method='SLSQP', bounds=bnds2, constraints=cons2, tol=1e-10) if -p_fun2(res2.x) > p and res2.success == True: h_series[i] = res2.x[0] m_series[i] = self.mbar θ_series[i + 1] = res2.x[1] self.θ_series = θ_series self.m_series = m_series self.h_series = h_series self.x_series = m_series * (h_series - 1)
def chebvander(x, deg) : from numpy.polynomial.chebyshev import chebvander return chebvander(x, deg)
# Choices banded = True fast_transform = False N = 20 k = np.arange(N - 2) # Get points and weights for Chebyshev weighted integrals points = n_cheb.chebpts2(N)[::-1] weights = np.zeros((N)) + np.pi / (N - 1) weights[0] /= 2 weights[-1] /= 2 # Note! N points in real space gives N-2 bases in spectral space # Build Vandermonde matrix for Lobatto points and weights V = n_cheb.chebvander(points, N - 3).T - n_cheb.chebvander(points, N - 1)[:, 2:].T # Gauss-Chebyshev quadrature to compute rhs fj = np.array([f.subs(x, j) for j in points], dtype=float) # Get f on quad points def fastChebScalar(fj): return dct(fj, 1) * np.pi / (2 * (len(fj) - 1)) def fastChebTrans(fj): cj = dct(fj, 1) / (len(fj) - 1) cj[0] /= 2 cj[-1] /= 2 return cj
def chebyshev_interp(x, y): X = chebyshev.chebvander(x, len(x) - 1) return np.linalg.solve(X, y)
def init(self, N): """Vandermonde matrix is used just for verification""" self.points, self.weights = self.points_and_weights(N) # Build Vandermonde matrix. self.V = n_cheb.chebvander(self.points, N-1).T
fl = lambdify(x, f, "numpy") ul = lambdify(x, u, "numpy") n = 32 domain = sys.argv[-1] if len(sys.argv) == 2 else "C1" # Chebyshev-Gauss nodes and weights from spectralDNS.shen.shentransform import ChebyshevTransform CT = ChebyshevTransform(quad="GL") points, w = CT.points_and_weights(n+1, CT.quad) #points, w = n_cheb.chebgauss(n+1) #points = -points # Chebyshev Vandermonde matrix V = n_cheb.chebvander(points, n) scl=1.0 # First derivative matrix zero padded to (n+1)x(n+1) D1 = np.zeros((n+1,n+1)) D1[:-1,:] = n_cheb.chebder(np.eye(n+1), 1, scl=scl) # Second derivative matrix zero padded to (n+1)x(n+1) D2 = np.zeros((n+1,n+1)) D2[:-2,:] = n_cheb.chebder(np.eye(n+1), 2, scl=scl) Vx = np.dot(V, D1) Vxx = np.dot(V, D2) # Matrix of trial functions P = np.zeros((n+1,n+1))
import numpy.polynomial.chebyshev as chebyshev import numpy as np import numpy.linalg as linalg N = 20 x = np.arange(1, N + 1, 1) A1 = A2 = chebyshev.chebvander(x, N - 1) y1 = np.array([ 0.3230213, 0.3259532, 0.3294488, 0.3234509, 0.3262547, 0.3266671, 0.3262381, 0.3262544, 0.3244484, 0.3187518, 0.3187518, 0.3187518, 0.3187518, 0.3187518, 0.3187518, 0.3187518, 0.3187518, 0.3187518, 0.3187518, 0.3187518, ]) y2 = np.array([ 0.3230213, 0.3259532, 0.3294488, 0.3234509, 0.3262547, 0.3266671,
# Choices banded = True fast_transform = False N = 20 k = np.arange(N-2) # Get points and weights for Chebyshev weighted integrals points = n_cheb.chebpts2(N)[::-1] weights = np.zeros((N))+np.pi/(N-1) weights[0] /= 2 weights[-1] /= 2 # Note! N points in real space gives N-2 bases in spectral space # Build Vandermonde matrix for Lobatto points and weights V = n_cheb.chebvander(points, N-3).T - n_cheb.chebvander(points, N-1)[:, 2:].T # Gauss-Chebyshev quadrature to compute rhs fj = np.array([f.subs(x, j) for j in points], dtype=float) # Get f on quad points def fastChebScalar(fj): return dct(fj, 1)*np.pi/(2*(len(fj)-1)) def fastChebTrans(fj): cj = dct(fj, 1)/(len(fj)-1) cj[0] /= 2 cj[-1] /= 2 return cj def ifastChebTrans(fj): cj = 0.5*dct(fj, 1)
def vandermonde(self, x): return n_cheb.chebvander(x, self.N-1)
fl = lambdify(x, f, "numpy") ul = lambdify(x, u, "numpy") n = 32 domain = sys.argv[-1] if len(sys.argv) == 2 else "C1" # Chebyshev-Gauss nodes and weights from spectralDNS.shen.shentransform import ChebyshevTransform CT = ChebyshevTransform(quad="GL") points, w = CT.points_and_weights(n + 1, CT.quad) #points, w = n_cheb.chebgauss(n+1) #points = -points # Chebyshev Vandermonde matrix V = n_cheb.chebvander(points, n) scl = 1.0 # First derivative matrix zero padded to (n+1)x(n+1) D1 = np.zeros((n + 1, n + 1)) D1[:-1, :] = n_cheb.chebder(np.eye(n + 1), 1, scl=scl) # Second derivative matrix zero padded to (n+1)x(n+1) D2 = np.zeros((n + 1, n + 1)) D2[:-2, :] = n_cheb.chebder(np.eye(n + 1), 2, scl=scl) Vx = np.dot(V, D1) Vxx = np.dot(V, D2) # Matrix of trial functions P = np.zeros((n + 1, n + 1))
# Use sympy to compute a rhs, given an analytical solution x = Symbol("x") u = cos(np.pi * x) f = u.diff(x, 2) N = 50 k = np.arange(N - 2).astype(np.float) # Get points and weights for Chebyshev weighted integrals points = n_cheb.chebpts2(N)[::-1] weights = np.zeros((N)) + np.pi / (N - 1) weights[0] /= 2 weights[-1] /= 2 # Build Vandermonde matrix for Lobatto points and weights V = n_cheb.chebvander(points, N - 3).T - ( (k / (k + 2))**2)[:, np.newaxis] * n_cheb.chebvander(points, N - 1)[:, 2:].T V = V[1:, :] # Not using k=0 def fastShenTransNeumann(fj): """Fast Shen transform on cos(j*pi/N). """ cj = fastShenScalarNeumann(fj) ck = np.ones(N - 3) ck[-1] = 2 # Note not the first since basis phi_0 is not included a = np.ones(N - 5) * (-np.pi / 2) * (k[1:-2] / (k[1:-2] + 2))**2 b = np.pi / 2 * (1 + (k[1:] / (k[1:] + 2))**4) c = a.copy() cj = TDMA.TDMA_1D(a, b, c, cj)
eph1957.evaluate('RAJ',m)/15., eph1957.evaluate('DECJ',m), int(m), m-int(m), 1, 0.)['frac'] import matplotlib.pylab as plt plt.ion() #plt.plot(t.utc.mjd, delay-rf_delay-d_orb) plt.plot(t.utc.mjd, d_earth-rf_delay) #plt.plot(t.utc.mjd, (rv-rf_rv-v_orb)*c.to(u.km/u.s).value) plt.draw() if False: for utc, tdb1, tdb2 in zip(t.utc.mjd, t.tdb.jd1, t.tdb.jd2): rf_tdb = rf_ephem.utc_to_tdb(int(utc), utc-int(utc))['tdb'] print utc, tdb, rf_tdb, tdb1-0.5-int(tdb1-0.5)+tdb2-rf_tdb if False: tdb = np.linspace(0.,1.,5) index = 10*np.ones(len(tdb), dtype=np.int) import numpy.polynomial.chebyshev as chebyshev coefficient_sets = jpleph.load('earthmoon') number_of_sets, axis_count, coefficient_count = coefficient_sets.shape coefficients = np.rollaxis(coefficient_sets[index], 1) T = np.empty((coefficient_count, len(tdb))) T[0] = 1.0 T[1] = t1 = 2.0 * tdb - 1.0 twot1 = t1 + t1 for i in range(2, coefficient_count): T[i] = twot1 * T[i-1] - T[i-2] result = (T.T * coefficients).sum(axis=2) V = chebyshev.chebvander(t1, coefficient_count-1)
def init(self, N): self.points, self.weights = self.points_and_weights(N) k = self.wavenumbers(N) ak, bk = self.shenCoefficients(k, self.BC) # Build Vandermonde matrix. Note! N points in real space gives N-2 bases in spectral space self.V = n_cheb.chebvander(self.points, N-3).T + ak[:, np.newaxis]*n_cheb.chebvander(self.points, N-2)[:, 1:].T + bk[:, np.newaxis]*n_cheb.chebvander(self.points, N-1)[:, 2:].T
# Use sympy to compute a rhs, given an analytical solution x = Symbol("x") u = cos(np.pi*x) f = u.diff(x, 2) N = 50 k = np.arange(N-2).astype(np.float) # Get points and weights for Chebyshev weighted integrals points = n_cheb.chebpts2(N)[::-1] weights = np.zeros((N))+np.pi/(N-1) weights[0] /= 2 weights[-1] /= 2 # Build Vandermonde matrix for Lobatto points and weights V = n_cheb.chebvander(points, N-3).T - ((k/(k+2))**2)[:, np.newaxis]*n_cheb.chebvander(points, N-1)[:, 2:].T V = V[1:, :] # Not using k=0 def fastShenTransNeumann(fj): """Fast Shen transform on cos(j*pi/N). """ cj = fastShenScalarNeumann(fj) ck = np.ones(N-3); ck[-1] = 2 # Note not the first since basis phi_0 is not included a = np.ones(N-5)*(-np.pi/2)*(k[1:-2]/(k[1:-2]+2))**2 b = np.pi/2*(1+(k[1:]/(k[1:]+2))**4) c = a.copy() cj = TDMA.TDMA_1D(a, b, c, cj) return cj def ifastShenTransNeumann(fj): """Inverse fast Shen transform on cos(j*pi/N).
def init(self, N): """Vandermonde matrix is used just for verification""" self.points, self.weights = self.points_and_weights(N) # Build Vandermonde matrix. Note! N points in real space gives N-2 bases in spectral space self.V = n_cheb.chebvander(self.points, N-3).T - n_cheb.chebvander(self.points, N-1)[:, 2:].T
def chebvander(x, deg): from numpy.polynomial.chebyshev import chebvander return chebvander(x, deg)
def init(self, N): self.points, self.weights = self.points_and_weights(N) k = self.wavenumbers(N) # Build Vandermonde matrix. self.V = n_cheb.chebvander(self.points, N-5).T - (2*(k+2)/(k+3))[:, np.newaxis]*n_cheb.chebvander(self.points, N-3)[:, 2:].T + ((k+1)/(k+3))[:, np.newaxis]*n_cheb.chebvander(self.points, N-1)[:, 4:].T