def get_free_energy_for_minimize(grid_points): """ Calculates total elastic energy for given radius and pressure. """ global free_energy_elastic_stretching, \ free_energy_elastic_bending, \ free_energy_elastic_tail, \ free_energy_external, \ current_volume u_coef = grid_points[:N_COEF_U] h_coef = grid_points[N_COEF_U:] u = Chebyshev(u_coef, domain=[0, radius]) h = Chebyshev(h_coef, domain=[0, radius]) r = Chebyshev([radius/2, radius/2], domain=[0, radius]) dh_dr = h.deriv(m=1) d2h_dr2 = h.deriv(m=2) du_dr = u.deriv(m=1) current_volume = get_volume_from_h_coefs(h, radius) psi_str_to_integrate = \ (du_dr ** 2 + du_dr * dh_dr ** 2 \ + 0.25 * dh_dr ** 4 \ + (u // r) ** 2) * r free_energy_elastic_stretching = np.pi * YOUNGS_MODULUS \ * (psi_str_to_integrate.integ()(radius) \ - psi_str_to_integrate.integ()(0.0)) free_energy_elastic_tail = np.pi * YOUNGS_MODULUS * u(radius) ** 2 psi_bend_to_integrate = \ (d2h_dr2 ** 2 + (dh_dr // r) ** 2) * r free_energy_elastic_bending = RIGIDITY * np.pi \ * (psi_bend_to_integrate.integ()(radius) \ - psi_bend_to_integrate.integ()(0.0)) # free_energy_elastic_bending = 0.0 free_energy_external = -current_volume * pressure return free_energy_elastic_stretching \ + free_energy_elastic_bending \ + free_energy_elastic_tail \ + free_energy_external
def h_constraint(grid_points): """ Boundary condition h(r) = 0. """ h_coef = grid_points[N_COEF_U:] h = Chebyshev(h_coef, domain=[0, radius]) return h(radius)
def u_constraint_zero(grid_points): """ Boundary condition u(0) = 0. """ u_coef = grid_points[:N_COEF_U] u = Chebyshev(u_coef, domain=[0, radius]) return u(0.0)
def __init__(self, n): self.x0 = (1 + np.arange(n)) / (n + 1) specs = [] super(ChebyshevQuadrature, self).__init__(n, n, specs) cp = Chebyshev(1) self.T_all = [cp.basis(i + 1, domain=[0.0, 1.0]) for i in range(n)]
def interpolate_cheb_from_col(cheb_column, bands, wave): bluest = np.min(bands) #effective wavelength of bluest filter reddest = np.max(bands) #effective wavelength of reddest filter if len(cheb_column) != len(wave): warnings.warn( "wave must be an array with the same number of elements as cheb_column" ) else: funcs = { n: Chebyshev(cheb_column[n], domain=[bluest, reddest]) for n in range(len(cheb_column)) } polynom = np.zeros(len(cheb_column)) for i in range(len(cheb_column)): if cheb_column[i][0] != -99: polynom[i] = funcs[i](wave[i]) if wave[i] >= reddest or wave[i] <= bluest: warnings.warn( "The wavelength at which you're interpolating the Chebyshev polynomial for index:" + str(i) + " is outside the wavelength range of the used bands") else: polynom[i] = -99 return polynom
def h_constraint_der_zero(grid_points): """ Boundary condition h'(0) = 0. """ h_coef = grid_points[N_COEF_U:] h = Chebyshev(h_coef, domain=[0, radius]) return h.deriv(m=1)(0.0)
def cheb_series(x): sum = 0 alpha = np.sqrt(2) - 1 coef = np.zeros(11 * 2 + 1) for i in range(11): coef[2 * i + 1] = 1 sum += (-1)**i / (2 * i + 1) * alpha**(2 * i + 1) * Chebyshev(coef)(x) coef[2 * i + 1] = 0 return 2 * sum
def get_mode_cheb_coeffs(self, mode_index, cheb_order): """ Cheb coeffs of a mode. The projection process is performed on [0,1]^dim. """ import scipy.special as sps cheby_nodes, _, cheby_weights = \ sps.chebyt(cheb_order).weights.T # pylint: disable=E1136,E0633 window = [0, 1] cheby_nodes = cheby_nodes * (window[1] - window[0]) / 2 + np.mean(window) cheby_weights = cheby_weights * (window[1] - window[0]) / 2 mode = self.get_template_mode(mode_index) grid = np.meshgrid(*[cheby_nodes for d in range(self.dim)], indexing='ij') mvals = mode(*grid) from numpy.polynomial.chebyshev import Chebyshev coef_scale = 2 * np.ones(cheb_order) / cheb_order coef_scale[0] /= 2 basis_1d = np.array([ Chebyshev(coef=_orthonormal(cheb_order, i), domain=window)(cheby_nodes) for i in range(cheb_order) ]) from itertools import product if self.dim == 1: basis_set = basis_1d elif self.dim == 2: basis_set = np.array([ b1.reshape([cheb_order, 1]) * b2.reshape([1, cheb_order]) for b1, b2 in product(*[basis_1d for d in range(self.dim)]) ]) elif self.dim == 3: basis_set = np.array([ b1.reshape([cheb_order, 1, 1]) * b2.reshape([1, cheb_order, 1]) * b3.reshape([1, 1, cheb_order]) for b1, b2, b3 in product(*[basis_1d for d in range(self.dim)]) ]) mode_cheb_coeffs = np.array([ np.sum(mvals * basis) for basis in basis_set ]) * _self_tp(coef_scale, self.dim).reshape(-1) # purge small coeffs whose magnitude are less than 8 times machine epsilon mode_cheb_coeffs[np.abs(mode_cheb_coeffs) < 8 * np.finfo(mode_cheb_coeffs.dtype).eps] = 0 return mode_cheb_coeffs
def background(self, two_theta, intensities): n_deg = 5 spline = Chebyshev(coef=np.ones((5,))) red_two_theta, red_intensities = self.remove_peaks( two_theta, self.smooth_data(intensities)) # Fit the background using the reduced dataset spline = spline.fit(red_two_theta, red_intensities, n_deg) # Return the predicted background background = np.array(spline(two_theta)) return background
def get_volume_from_h_coefs(h, radius): """ Returns volum of the bubble. h is Chebyshev polynomial coefficients for shape. radius is radius in A. """ r = Chebyshev([radius/2, radius/2], domain=[0, radius]) pol_to_integrate = h * r return 2.0 * np.pi * (pol_to_integrate.integ()(radius) \ - pol_to_integrate.integ()(0.0))
def chebyshev(coefs, time, domain): """Evaluate a Chebyshev Polynomial. Args: coefs (list, np.array): Coefficients defining the polynomial time (int, float): Time where to evaluate the polynomial domain (list, tuple): Domain (or time interval) for which the polynomial is defined: [left, right] Reference: Appendix A in the MSG Level 1.5 Image Data Format Description. """ return Chebyshev(coefs, domain=domain)(time) - 0.5 * coefs[0]
def interpolate_cheb(cheb, bands, wave): bluest = np.min(bands) #effective wavelength of bluest filter reddest = np.max(bands) #effective wavelength of reddest filter if wave[i] >= reddest or wave[i] <= bluest: warnings.warn( "The wavelength at which you're interpolating the Chebyshev polynomial is outside the wavelength range of the used bands" ) func = Chebyshev(cheb, domain=[bluest, reddest ]) # This evaluates the Chebyshev polynomial return func(wave)
def fit_func(f): fn = 'fits/%s/fit%s.fits' % (f, f) if os.path.exists(fn): r = {} d = pyfits.getdata('fits/%s/fit%s.fits' % (f, f), 'fit_info')[0] ref = d.field('refwlband') low = d.field('lowdwlband') + ref high = d.field('highdwlband') + ref d = pyfits.getdata('fits/%s/fit%s.fits' % (f, f), 'final_cheb') for n in d.names: r[n] = Chebyshev(d.field(n), (low, high)) else: r = None return r
def cheb_polys(): resolution = 513 X = np.linspace(-1, 1, resolution + 1) n = 6 coeffs = np.zeros(n) ax = plt.subplot(1, 1, 1) for i in xrange(n): coeffs[i] = 1 f = Chebyshev(coeffs) plt.plot(X, f(X), label="$T_" + str(i) + "$") coeffs[i] = 0 plt.ylim((-1.2, 1.2)) handles, labels = ax.get_legend_handles_labels() ax.legend(handles, labels, loc="upper right") plt.savefig("cheb_polys.pdf") plt.clf()
def runge_plot(): a, b = -1, 1 resolution = 513 runge = lambda x: 1 / (1 + 25 * x**2) X2 = np.linspace(a, b, resolution) ax = plt.subplot(1, 1, 1) plt.plot(X2, runge(X2), label="$\\frac{1}{1+25x^2}$") for order in [5, 10, 15, 25]: X = nodes(a, b, order) Y = runge(X) C = get_coefs(Y) f = Chebyshev(C) plt.plot(X2, f(X2), label="Order " + str(order)) handles, labels = ax.get_legend_handles_labels() ax.legend(handles, labels, loc="upper right") plt.savefig("runge_chebyshev.pdf") plt.clf()
def roots(self): """Utilises Boyd's O(n^2) recursive subdivision algorithm. The chebfun is recursively subsampled until it is successfully represented to machine precision by a sequence of piecewise interpolants of degree 100 or less. A colleague matrix eigenvalue solve is then applied to each of these pieces and the results are concatenated. See: J. P. Boyd, Computing zeros on a real interval through Chebyshev expansion and polynomial rootfinding, SIAM J. Numer. Anal., 40 (2002), pp. 1666–1682. """ if self.size() == 1: return np.array([]) elif self.size() <= 100: ak = self.coefficients() v = np.zeros_like(ak[:-1]) v[1] = 0.5 C1 = toeplitz(v) C2 = np.zeros_like(C1) C1[0, 1] = 1. C2[-1, :] = ak[:-1] C = C1 - .5 / ak[-1] * C2 eigenvalues = eigvals(C) roots = [ eig.real for eig in eigenvalues if np.allclose(eig.imag, 0, atol=1e-10) and np.abs(eig.real) <= 1 ] scaled_roots = self._ui_to_ab(np.array(roots)) return scaled_roots else: try: # divide at a close-to-zero split-point split_point = self._ui_to_ab(0.0123456789) return np.concatenate( (self.restrict([self._domain[0], split_point]).roots(), self.restrict([split_point, self._domain[1]]).roots())) except: # Seems to have many fake roots for high degree fits coeffs = self.coefficients() domain = self._domain possibilities = Chebyshev(coeffs, domain).roots() return np.array( [float(i.real) for i in possibilities if i.imag == 0.0])
def cos_interp(): a = -1 b = 1 order = 20 resolution = 501 X = nodes(a, b, resolution) F = lambda x: np.cos(x) A = F(X) cfs = get_coefs(A) print "number of coefficients for cos that are greater than 1E-14: ", ( np.absolute(cfs) > 1E-14).sum() f = Chebyshev(cfs) X2 = np.linspace(a, b, resolution) ax = plt.subplot(1, 1, 1) plt.plot(X2, F(X2), label="$\\cos x$") plt.plot(X2, f(X2), label="Chebyshev Interpolant") handles, labels = ax.get_legend_handles_labels() ax.legend(handles, labels, loc="upper right") plt.show()
def refine_background(self, scattering_lengths, intensities, s=None, k=4): """Fit a univariate spline to the background data. Arguments --------- - scattering_lengths : Array of scattering vector lengths, q. - intensities : Array of intensity values at each q position - s : Smoothing factor passed to the spline. Default is the variance of the background. - k : Degree of the spline (default quartic spline). """ # Remove pre-indexed peaks for background fitting phase_list = self.phases + self.background_phases q, I = scattering_lengths, intensities for phase in phase_list: for reflection in phase.reflection_list: q, I = remove_peak_from_df(x=q, y=I, xrange=reflection.qrange) # Get an estimate for s from the non-peak data if s is None: s = np.std(I) # Smoothing for background fitting smoothI = savgol_filter(I, window_length=15, polyorder=5) # Determine a background line from the noise without peaks # self.spline = UnivariateSpline( # x=q, # y=I, # s=s / 25, # k=k, # ) self.spline = Chebyshev(coef=np.ones((20,))) self.spline = self.spline.fit(q, smoothI, 10) # background = self.spline.cast(scattering_lengths) # self.spline = splrep(q, I) # Extrapolate the background for the whole pattern # background = self.spline(scattering_lengths) background = self.spline(scattering_lengths) return background
def crazy_interp(): # This one takes a little time to run a = -1 b = 1 order = 100000 resolution = 100001 # Where to sample. X = nodes(a, b, order) F = lambda x: np.sin(1. / x) * np.sin(1. / np.sin(1. / x)) A = F(X) cfs = get_coefs(A) print "The last 10 coeffients are: ", cfs[-10:] f = Chebyshev(cfs) # Sample values for plot. X2 = np.linspace(a, b, resolution) ax = plt.subplot(1, 1, 1) plt.plot(X2, f(X2), label="Chebyshev Interpolant") plt.plot(X2, F(X2), label="$\\sin\\frac{1}{x} \\sin\\frac{1}{\\sin\\frac{1}{x}}$") handles, labels = ax.get_legend_handles_labels() ax.legend(handles, labels, loc="upper right") plt.show()
def debye_fn(x): """ Evaluate the Debye function. Takes the parameter xi = Debye_T/T """ sol = integrate.quad(lambda xi: pow(xi, 3.) / (np.exp(xi) - 1.), 0.0, x) # EQ B3 return 3. * sol[0] / pow(x, 3.) from numpy.polynomial.chebyshev import Chebyshev chebyshev_representation = Chebyshev( [ 2.707737068327440945/2.0, 0.340068135211091751, -0.12945150184440869e-01, \ 0.7963755380173816e-03, -0.546360009590824e-04, 0.39243019598805e-05, \ -0.2894032823539e-06, 0.217317613962e-07, -0.16542099950e-08, \ 0.1272796189e-09, -0.987963460e-11, 0.7725074e-12, -0.607797e-13, \ 0.48076e-14, -0.3820e-15, 0.305e-16, -0.24e-17] ) eps = np.finfo(np.float).eps sqrt_eps = np.sqrt(np.finfo(np.float).eps) log_eps = np.log(np.finfo(np.float).eps) def debye_fn_cheb(x): """ Evaluate the Debye function using a Chebyshev series expansion coupled with asymptotic solutions of the function. Shamelessly adapted from the GSL implementation of the same function (Itself adapted from Collected Algorithms from ACM). Should give the same result as debye_fn(x) to near machine-precision. """ val_infinity = 19.4818182068004875
def solve( self, d_mus:np.ndarray, lambd=None, ): n = self.n k = self.k if lambd is None: lambd = np.zeros(self.k) H = np.zeros(shape=(k, k)) fpoly = None for i_step in range(self.n_steps): if fpoly is None: fvals = np.exp(lambd.dot(self.G)) cs = fit_cheby(fvals) fpoly = Chebyshev(cs) e_mu = np.array([ (fpoly*cb(i)).integ(lbnd=-1)(1) for i in range(2*k) ]) grad = e_mu[:k] - d_mus grad_norm = np.linalg.norm(grad) grad_norm_old = grad_norm Pval_old = e_mu[0] - lambd.dot(d_mus) if self.verbose: print("Step: {}, Grad: {}, P: {}".format( i_step, grad_norm, Pval_old )) if grad_norm < self.grad_tol: break for i in range(k): for j in range(k): H[i, j] = (e_mu[i+j] + e_mu[abs(i-j)]) / 2 step = -np.linalg.solve(H, grad) dfdx = step.dot(grad) stepScaleFactor = 1.0 newX = lambd + stepScaleFactor * step alpha = .3 beta = .25 while True: fvals = np.exp(newX.dot(self.G)) cs = fit_cheby(fvals) fpoly = np.polynomial.chebyshev.Chebyshev(cs) e_mu = np.array([ (fpoly * cb(i)).integ(lbnd=-1)(1) for i in range(2 * k) ]) grad = e_mu[:k] - d_mus grad_norm = np.linalg.norm(grad) Pval_new = fpoly.integ(lbnd=-1)(1) - newX.dot(d_mus) delta_change = Pval_old + alpha * stepScaleFactor * dfdx - Pval_new # if (delta_change > -1e-6 and grad_norm < grad_norm_old) or stepScaleFactor < 1e-5: if (delta_change > -1e-6 or stepScaleFactor < 1e-5): break else: stepScaleFactor *= beta if self.verbose: print("step: {}, delta: {}".format(stepScaleFactor, delta_change)) newX = lambd + stepScaleFactor * step lambd = newX self.lambd = lambd self.f_poly = self.get_fpoly(lambd) self.cdf_poly = self.f_poly.integ(lbnd=-1)
def __init__(self, x0): super(ChebyshevQuadrature, self).__init__(11, 11, 2.799761e-03, x0) cp = Chebyshev(1) self.T_all = [cp.basis(i, domain=[0.0, 1.0]) for i in range(11)]
parser.add_argument( '--wavelength', dest='wave', help= 'input should be the wavelength value at which the polynomial will be evaluated' ) parser.add_argument( '--bands', dest='bands', help='input should be comma separated wavelengths of the used bands') args = parser.parse_args() cheb = list(map(float, args.cheb.split(','))) cheb = [float(i) for i in cheb] bands = list(map(float, args.bands.split(','))) bands = [float(i) for i in bands] wave = list(map(float, args.wave)) wave = [float(i) for i in wave] bluest = np.min(bands) #effective wavelength of bluest filter reddest = np.max(bands) #effective wavelength of reddest filter func = Chebyshev(cheb, domain=[bluest, reddest]) polynom = np.zeros(len(wave)) for i in range(len(wave)): polynom[i] = func(wave[i]) # This evaluates the Chebyshev polynomial print('At wavelength ' + str(wave[i]) + ' : ' + str(polynom[i]) + '\n')
def minimize_for_pressure(radius, density, mass): """ For given radius and pressure calculates solution of equation of elastisity of membranes. Then extract Chebyshev's polynomial coefficients. Pressure is evaluated from EOS. Returns volume, u and h coefficients. pressure deveoped by membrane, density of trapped ssubstance, and mass. """ global count_iterations pressure = pressure_from_density(density) pressure_ev = pressure / 160217.66208 get_free_energy_for_minimize = get_free_energy_wrapper(radius, pressure_ev) # print('{:>6} {:<20} {:<20} {:<20} {:<20} {:<20}'.format('Step', # 'Total', # 'Elastic str inside', # 'Elastic tail', # 'Elastic bend', # '-PV' # )) count_iterations = 1 u_initial = np.zeros(N_COEF_U) h_initial = np.zeros(N_COEF_H) h_initial[0] = 5 / 8 * 0.15 * radius h_initial[1] = -0.15 * radius / 2 h_initial[2] = -1 / 8 * 0.15 * radius h_constraint = h_constraint_wrapper(radius) h_constraint_der_zero = h_constraint_der_zero_wrapper(radius) u_constraint_zero = u_constraint_zero_wrapper(radius) cons = [{'type':'eq', 'fun': h_constraint}, {'type':'eq', 'fun': h_constraint_der_zero}, {'type':'eq', 'fun': u_constraint_zero} ] res_minimize = minimize(get_free_energy_for_minimize, np.append(u_initial, h_initial), constraints=cons, method='SLSQP', options={'disp' : True, 'maxiter' : MAX_ITER_IN_OPTIMIZATOR, }, #callback=callback_minimize_elastic_energy ) u_coef= res_minimize.x[:N_COEF_U] h_coef = res_minimize.x[N_COEF_U:] h = Chebyshev(h_coef, domain=[0, radius]) print('\n') print('H: {}, R: {}, H/R: {}'.format(h(0.0), radius, h(0.0) / radius)) print('Volume: {}, pressure: {}, density: {}'.format(current_volume, pressure, density)) print('{:<14}: {}'.format('Mass', mass)) print('{:<14}: {}'.format('Current mass', current_volume * density)) print('Running time: {} seconds'.format(time.time() - start_time)) print('\n') return current_volume, u_coef, h_coef, pressure, density, \ current_volume * density
import matplotlib.pyplot as plt import numpy as np from numpy.polynomial.chebyshev import Chebyshev, cheb2poly mindeg, maxdeg = 0, 5 cmap = plt.get_cmap('rainbow') colors = cmap(np.linspace(0, 1, maxdeg - mindeg + 1)) print(colors) l = list(np.zeros(mindeg, int)) + [1] xx = np.linspace(-1, 1, 100) tx = 0.2 for i, col in zip(range(mindeg, maxdeg + 1), colors): c = Chebyshev(l) print('T({}) = {}'.format(i, cheb2poly(c.coef))) yy = [c(x) for x in xx] #col = colors.pop() plt.gcf().text(tx, 0.9, 'T({})'.format(i), color=col) tx += 0.1 plt.plot(xx, yy, color=col) l.insert(0, 0) # increment the degree plt.grid(True) plt.show()
def _derivative(c, m): cheb = Chebyshev(c) dcheb = cheb.deriv(m=m) return dcheb.coef
def energy_for_radius(radius): """ Calculates total energy as sum of elastic energy, energy of trapped substance and vdW energy. """ start_time = time.time() return_shapes = find_shapes_for_radius(mass, radius) if return_shapes == -1: return -1 if return_shapes == -2: return -2 u_coef, h_coef, pressure, density = return_shapes h = Chebyshev(h_coef, domain=[0, radius]) volume = get_volume_from_h_coefs(h, radius) free_energy_fluid = get_fluid_energy(density, volume) free_energy_vdw = np.pi * radius ** 2 * 0.0175 \ - np.pi * radius ** 2 * gamma_gb(density) \ - get_surface_from_h_coefs(h, radius) * gamma_gb(density) total_elastic = free_energy_elastic_stretching \ + free_energy_elastic_bending \ + free_energy_elastic_tail total_energy = total_elastic + free_energy_fluid + free_energy_vdw print('\n') print('{:<16}: {:<24}'.format('Elastic energy', total_elastic)) print('{:<16}: {:<24}'.format('Fluid energy', free_energy_fluid)) print('{:<16}: {:<24}'.format('vdW energy', free_energy_vdw)) print('{:<16}: {:<24}'.format('Total energy', total_energy)) print('\n') print('H: {}, R: {}, H/R: {}'.format(h(0.0), radius, h(0.0) / radius)) print('Pressure: {}'.format(pressure)) print('Density: {}'.format(density)) print('Mass: {}'.format(mass)) print('volume * density: {}'.format(density * current_volume)) print('Running time: {} seconds'.format(time.time() - start_time)) print('\n') return total_energy, \ free_energy_vdw, \ free_energy_elastic_stretching, \ free_energy_elastic_bending, \ free_energy_elastic_tail, \ free_energy_fluid, \ u_coef, \ h_coef, \ current_volume, \ density, \ pressure, \ radius, \ h(0.0), \ h(0.0)/radius