def calculateCentroidMeasurements(self): self.X[self.badFrames, :] = ma.masked if not self.useSmoothingFilterDerivatives: self.v[1:-1] = (self.X[2:, :] - self.X[0:-2])/(2.0/self.frameRate) else: # use a cubic polynomial filter to estimate the velocity self.v = ma.zeros(self.X.shape) halfWindow = int(np.round(self.filterWindow/2.*self.frameRate)) for i in xrange(halfWindow, self.v.shape[0]-halfWindow): start = i-halfWindow mid = i finish = i+halfWindow+1 if not np.any(self.X.mask[start:finish,:]): px = np.polyder(np.polyfit(self.t[start:finish]-self.t[mid], self.X[start:finish, 0], 3)) py = np.polyder(np.polyfit(self.t[start:finish]-self.t[mid], self.X[start:finish, 1], 3)) self.v[i,:] = [np.polyval(px, 0), np.polyval(py, 0)] else: self.v[i,:] = ma.masked self.s = ma.sqrt(ma.sum(ma.power(self.v, 2), axis=1)) self.phi = ma.arctan2(self.v[:, 1], self.v[:, 0]) self.t[self.badFrames] = ma.masked self.X[self.badFrames, :] = ma.masked self.v[self.badFrames, :] = ma.masked self.s[self.badFrames] = ma.masked self.phi[self.badFrames] = ma.masked
def sin_poly(P): poly_size = len(P)+1 temp = np.poly1d([0]) coeffCos = np.poly1d([0]) coeffSin = np.poly1d([0]) tmpCoeffCos = np.poly1d([0]) tmpCoeffSin = np.poly1d([0]) cos0 = math.cos(P[0]) sin0 = math.sin(P[0]) coeffSin[0] = 1.0 temp[0] = sin0 # compute the derivative of P dP = np.polyder(P) facti = 1 for i in xrange(1,poly_size): facti *= i tmpCoeffCos = np.polyder(coeffCos) + coeffSin * dP tmpCoeffSin = np.polyder(coeffSin) - coeffCos * dP coeffCos = tmpCoeffCos coeffSin = tmpCoeffSin temp[i] = (coeffCos[0] * cos0 + coeffSin[0] * sin0)/float(facti) return temp
def solve_pathlength_func_bendrad(p, edge_y, edge_dydx, D, L0, BendRad, n_grid=100): """A helper function for solve_pathlength where a fixed minimum bend radius is desired. Parameters ---------- BendRad: float Enforced minimum bend radius. """ pathlength_poly = np.poly1d(p) p_d = np.polyder(pathlength_poly) p_d_d = np.polyder(p_d) L = integrate.quad(polynomial_pathlength, 0, D, args=(p_d)) # Find the minimum radius of curvature along the curve. # Given the the curve is non-differentiable, try brute-force with n_grid points # along the curve. x_vect = np.meshgrid(0, D, n_grid) a = bend_radius(x_vect, p_d, p_d_d) # Find the minimum radius of curvature. SmallCurve = np.min(a) retpar = [ pathlength_poly(0) - edge_y[0], pathlength_poly(D) - edge_y[1], p_d(0) - edge_dydx[0], p_d(D) - edge_dydx[1], L[0] - L0, SmallCurve - BendRad, ] # print(retpar); pdb.set_trace() return retpar
def fit_sjeos(self): """Calculate volume, energy, and bulk modulus. Returns the optimal volume, the minimum energy, and the bulk modulus. Notice that the ASE units for the bulk modulus is eV/Angstrom^3 - to get the value in GPa, do this:: v0, e0, B = eos.fit() print(B / kJ * 1.0e24, 'GPa') """ fit0 = np.poly1d(np.polyfit(self.v**-(1 / 3), self.e, 3)) fit1 = np.polyder(fit0, 1) fit2 = np.polyder(fit1, 1) self.v0 = None for t in np.roots(fit1): if isinstance(t, float) and t > 0 and fit2(t) > 0: self.v0 = t**-3 break if self.v0 is None: raise ValueError('No minimum!') self.e0 = fit0(t) self.B = t**5 * fit2(t) / 9 self.fit0 = fit0 return self.v0, self.e0, self.B
def BM(energies): fitdata = np.polyfit(energies[:, 0] ** (-2.0 / 3.0), energies[:, 1], 3, full=True) ssr = fitdata[1] sst = np.sum((energies[:, 1] - np.average(energies[:, 1])) ** 2.0) residuals0 = ssr / sst deriv0 = np.poly1d(fitdata[0]) deriv1 = np.polyder(deriv0, 1) deriv2 = np.polyder(deriv1, 1) deriv3 = np.polyder(deriv2, 1) volume0 = 0 x = 0 for x in np.roots(deriv1): if x > 0 and deriv2(x) > 0: volume0 = x ** (-3.0 / 2.0) break if volume0 == 0: print("Error: No minimum could be found") exit() derivV2 = 4.0 / 9.0 * x ** 5.0 * deriv2(x) derivV3 = -20.0 / 9.0 * x ** (13.0 / 2.0) * deriv2(x) - 8.0 / 27.0 * x ** (15.0 / 2.0) * deriv3(x) bulk_modulus0 = derivV2 / x ** (3.0 / 2.0) bulk_deriv0 = -1 - x ** (-3.0 / 2.0) * derivV3 / derivV2 return volume0, bulk_modulus0, bulk_deriv0, residuals0
def findStepWithPoly(x,data,kind="stepUp",excludePoints=100,order=20,fitrange=100): """ Look for a step in the data Data is 1D array The 'kind' keywords should be either 'stepUp' or 'stepDown' the 'excludePoints' keyword is used to limit the search 'excludePoints' away from the extremes The data are fit with a polynomial of order 'order', then the maximum (or minimum) of derivative is located. After this first attempt, the position is refined by a second polyfit in a range [-fitrange,+fitrange] around the first guess """ if (kind == "stepUp"): use = "max" else: use = "min" poly = np.polyfit(x,data,order) polyder = np.polyder(poly) x_poly1 = findDerPeak(x,np.polyval(polyder,x),use=use,excludePoints=excludePoints) # find closest idx = np.abs(x - x_poly1).argmin() idx = slice(idx-fitrange,idx+fitrange) poly = np.polyfit(x[idx],data[idx],order) polyder = np.polyder(poly) x_poly2 = findDerPeak(x[idx],np.polyval(polyder,x[idx]),use=use,excludePoints=10) return x_poly2
def deltafactor_polyfit(volumes, energies): """ This is the routine used to compute V0, B0, B1 in the deltafactor code. Taken from deltafactor/eosfit.py """ fitdata = np.polyfit(volumes**(-2./3.), energies, 3, full=True) ssr = fitdata[1] sst = np.sum((energies - np.average(energies))**2.) residuals0 = ssr/sst deriv0 = np.poly1d(fitdata[0]) deriv1 = np.polyder(deriv0, 1) deriv2 = np.polyder(deriv1, 1) deriv3 = np.polyder(deriv2, 1) v0 = 0 x = 0 for x in np.roots(deriv1): if x > 0 and deriv2(x) > 0: v0 = x**(-3./2.) break else: raise EOSError("No minimum could be found") derivV2 = 4./9. * x**5. * deriv2(x) derivV3 = (-20./9. * x**(13./2.) * deriv2(x) - 8./27. * x**(15./2.) * deriv3(x)) b0 = derivV2 / x**(3./2.) b1 = -1 - x**(-3./2.) * derivV3 / derivV2 #print('deltafactor polyfit:') #print('e0, b0, b1, v0') #print(fitdata[0], b0, b1, v0) n = collections.namedtuple("DeltaFitResults", "v0 b0 b1 poly1d") return n(v0, b0, b1, fitdata[0])
def solve_for_nearest( px,py,rx,ry ): dpx = polyder(px) dpy = polyder(py) cp = polymul( dpx, px ) + polymul( dpy, py ) cp = polyadd( cp, -rx*dpx ) cp = polyadd( cp, -ry*dpy ) t = roots(cp) t = real(t[isreal(t)]) t = t[ (t>=0) * (t<=1) ] ##tt = linspace(0,1,100) ##from pylab import plot ##plot( polyval(px,tt), polyval(py,tt), 'k', hold = 0 ) ##plot( [rx],[ry], 'r.' ) ##plot( polyval(px,t[isreal(t)*(real(t)>=0)*(real(t)<=1)]), ## polyval(py,t[isreal(t)*(real(t)>=0)*(real(t)<=1)]), 'o' ) ##pdb.set_trace() if len(t): if len(t) == 1: return t[0] else: ux = polyval( px, t ) uy = polyval( py, t ) d = hypot( ux - rx, uy - ry ) return t[ d==d.min() ][0] else: t = array([0.0,1.0]) ux = polyval( px, t ) uy = polyval( py, t ) d = hypot( ux - rx, uy - ry ) if d[0] < d[1]: return 0.0 else: return 1.0
def calc_max_curvature_point(x_arr, y_arr): rot_x = [] rot_y = [] # Rotate all of the x and y co-ordinates around the origin by 90deg for current_x, current_y in zip(x_arr, y_arr): out_x, out_y = rotate(current_x, current_y, 90) rot_x.append(out_x) rot_y.append(out_y) pol = get_best_poly_fit(rot_x, rot_y, 7) # Differentiate the polynomial deriv_one = numpy.polyder(pol) deriv_two = numpy.polyder(deriv_one) # Roots of the 1st derivative - that is, X-values for where 1st deriv = 0 roots = numpy.roots(deriv_one) if roots.size == 1: result = rotate(roots, numpy.polyval(pol, roots), -90) else: prev_val = 0 selected_root = -1 for root in roots: val = numpy.polyval(deriv_two, root) if val > prev_val: selected_root = root result = rotate(selected_root, numpy.polyval(pol, selected_root), -90) return [float(result[0]), float(result[1])]
def poly_sigma(time, y): """ Calculates velocity and acceleration by fitting a polynomial over the prior N elements defined by poly_window. The sigma value defines an averaging window inside of poly_window in which all points inside of sigma window are averaged and treated as a single point for the polynomial fitting process. """ y_d = np.zeros(time.shape) y_dd = np.zeros(time.shape) window = poly_window for i in range(window * sigma, time.shape[0]): y_history = y[i - window * sigma + 1:i + 1] y_hist_avg = np.mean(y_history.reshape(-1, sigma), axis=1) params = np.polyfit( x=time[i - window * sigma + 1:i + 1:sigma], y=y_hist_avg, deg=degree) p = np.poly1d(params) p_d = np.polyder(p) p_dd = np.polyder(p_d) y_d[i] = p_d(time[i]) y_dd[i] = p_dd(time[i]) y_d = y_d / encoder_resolution y_dd = y_dd / encoder_resolution return y_d, y_dd
def splitBimodal(self, x, y, largepoly=30): p = np.polyfit(x, y, largepoly) # polynomial coefficients for fit extrema = np.roots(np.polyder(p)) extrema = extrema[np.isreal(extrema)] extrema = extrema[(extrema - x[1]) * (x[-2] - extrema) > 0] # exclude the endpoints due false maxima during fitting try: root_vals = [sum([p[::-1][i]*(root**i) for i in range(len(p))]) for root in extrema] peaks = extrema[np.argpartition(root_vals, -2)][-2:] # find two peaks of bimodal distribution mid, = np.where((x - peaks[0])* (peaks[1] - x) > 0) # want data points between the peaks except: warnings.warn("Peak finding failed!") return None try: p_mid = np.polyfit(x[mid], y[mid], 2) # fit middle section to a parabola midpoint = np.roots(np.polyder(p_mid))[0] except: warnings.warn("Polynomial fit between peaks of distribution poorly conditioned. Falling back on using the minimum! May result in inaccurate split determination.") if len(mid) == 0: return None midx = np.argmin(y[mid]) midpoint = x[mid][midx] return midpoint
def fit_edge_hist(bins, counts, fwhm_guess=10.0): if len(bins) == len(counts)+1: bins = bins[:-1]+0.5*(bins[1]-bins[0]) # convert bin edge to bin centers if neccesary pfit = np.polyfit(bins, counts, 3) edgeGuess = np.roots(np.polyder(pfit,2)) try: preGuessX, postGuessX = np.sort(np.roots(np.polyder(pfit,1))) except: raise ValueError("failed to generate guesses") use = bins>(edgeGuess+2*fwhm_guess) if np.sum(use)>4: pfit2 = np.polyfit(bins[use], counts[use],1) slope_guess = pfit2[0] else: slope_guess=1 pGuess = np.array([edgeGuess, np.polyval(pfit,preGuessX), np.polyval(pfit,postGuessX),fwhm_guess,slope_guess],dtype='float64') try: pOut = curve_fit(edge_model, bins, counts, pGuess) except: return (0,0,0,0,0,0) (edgeCenter, preHeight, postHeight, fwhm, bgSlope) = pOut[0] model_counts = edge_model(bins, edgeCenter, preHeight, postHeight, fwhm, bgSlope) num_degree_of_freedom = float(len(bins)-1-5) # num points - 1 - number of fitted parameters chi2 = np.sum(((counts - model_counts)**2)/model_counts)/num_degree_of_freedom return (edgeCenter, preHeight, postHeight, fwhm, bgSlope, chi2)
def _set_params(self): """ Overriden to account for the fact the fit with volume**(2/3) instead of volume. """ deriv0 = np.poly1d(self.eos_params) deriv1 = np.polyder(deriv0, 1) deriv2 = np.polyder(deriv1, 1) deriv3 = np.polyder(deriv2, 1) for x in np.roots(deriv1): if x > 0 and deriv2(x) > 0: v0 = x**(-3./2.) break else: raise EOSError("No minimum could be found") derivV2 = 4./9. * x**5. * deriv2(x) derivV3 = (-20./9. * x**(13./2.) * deriv2(x) - 8./27. * x**(15./2.) * deriv3(x)) b0 = derivV2 / x**(3./2.) b1 = -1 - x**(-3./2.) * derivV3 / derivV2 # e0, b0, b1, v0 self._params = [deriv0(v0**(-2./3.)), b0, b1, v0]
def second_deriv_from_profile(xinterp,F): """Calculate second derivative at extrema""" dFdx = np.polyder(F,m=1) d2Fdx2 = np.polyder(F,m=2) minidx, maxidx = extrema_from_profile(xinterp,F) omegamin = d2Fdx2(xinterp[minidx]) omegamax = d2Fdx2(xinterp[maxidx]) return omegamin, omegamax
def polykruemm(p,x): y = np.polyval(p,x) dy = np.polyval(np.polyder(p),x) ddy = np.polyval(np.polyder(p,2),x) kappa = np.abs(ddy/(1+dy**2)**(3/2)) mx = x - dy*(1+dy**2)/ddy my = y + (1+dy**2)/ddy return kappa,mx,my
def elastic_constant(name, atoms, e0, u0, mode, strain=0.007, debug=False): """Calculate an elastic constant. Parameters:: name Name of the constant (a string). atoms The atoms. e0 Energy in the equilibrium configuration. u0 Unit cell in the equilibrium configuration. mode The deformation mode as six numbers, giving weights to the six strain components. """ strainlist = (-1.0, 0.5, 0, 0.5, 1.0) energies = [] order = np.array([[0, 5, 4], [5, 1, 3], [4, 3, 2]]) straintensor = np.array(mode)[order] if debug: print "%s unit strain tensor:" % (name,) print straintensor for s in strainlist: if s == 0: energies.append(e0) else: # Apply strain s = s * strain * straintensor + np.identity(3) atoms.set_cell(np.dot(u0, s), scale_atoms=True) energies.append(atoms.get_potential_energy()) atoms.set_cell(u0, scale_atoms=True) # Reset atoms fit0 = np.poly1d(np.polyfit(strain * np.array(strainlist), energies, 3)) fit1 = np.polyder(fit0, 1) fit2 = np.polyder(fit1, 1) x0 = None for x in np.roots(fit1): if fit2(x) > 0: if x0 is not None: raise RuntimeError("More than two roots found.") assert x0 is None x0 = x if x0 is None: raise RuntimeError("No roots found.") if np.abs(x0) > 0.5 * strain: raise RuntimeError("Unreasonable root (%f): " % (x0,) + "Maybe the system was not at the equilibrium configuration") if debug: print "Root:", x0 value = fit2(x0) return value / atoms.get_volume()
def compute_join_length( px, py, tlow = 0.0, thigh = 1.0 ): from scipy.integrate import quad xp = polyder( px, 1 ) yp = polyder( py, 1 ) xp2 = polymul( xp, xp ) yp2 = polymul( yp, yp ) p = polyadd( xp2, yp2 ) integrand = lambda t: sqrt( polyval( p, t ) ) return quad(integrand, tlow, thigh) [0]
def analyse(self): OptimizeTask.analyse(self) for name, data in self.data.items(): if 'distances' in data: distances = data['distances'] energies = data['energies'] fit0 = np.poly1d(np.polyfit(1 / distances, energies, 3)) fit1 = np.polyder(fit0, 1) fit2 = np.polyder(fit1, 1) dmin = None for t in np.roots(fit1): if t > 0 and fit2(t) > 0: dmin = 1 / t break if dmin is None: raise ValueError('No minimum!') if abs(dmin) < min(distances) or abs(dmin) > max(distances): raise ValueError('Fit outside of range! ' + \ str(abs(dmin)) + ' not in ' + \ str(distances)) emin = fit0(t) k = fit2(t) * t**4 m1, m2 = self.create_system(name).get_masses() m = m1 * m2 / (m1 + m2) hnu = units._hbar * 1e10 * sqrt(k / units._e / units._amu / m) data['minimum energy'] = emin self.results[name][1:] = [energies[2] - emin, dmin, 1000 * hnu] else: self.results[name].extend([None, None]) for name, data in self.data.items(): atoms = self.create_system(name) if len(atoms) == 1: self.results[name].extend([None, None]) continue eatoms = 0.0 for symbol in atoms.get_chemical_symbols(): if symbol in self.data and symbol != name: eatoms += self.data[symbol]['energy'] else: eatoms = None break ea = None ea0 = None if eatoms is not None: ea = eatoms - data['energy'] if 'minimum energy' in data: ea0 = eatoms - data['minimum energy'] self.results[name].extend([ea, ea0])
def root_angle_rad(w, side, dx, n=16): n = min(n, len(w.x) / 4) L = cumulative_path_length(w) tt = L / L.max() teval = tt[n] if side == 0 else tt[-n] px = np.polyfit(tt[n:-n], w.x[n:-n], 2) py = np.polyfit(tt[n:-n], w.y[n:-n], 2) xp = np.polyder(px, 1) yp = np.polyder(py, 1) return np.arctan2(dx * np.polyval(yp, teval), dx * np.polyval(xp, teval))
def solveEqnsSubOld(spline1,r1bar,r3bar,alphabar,offset): dspline1 = np.polyder(spline1) ddspline1 = np.polyder(dspline1) energy1 = morse(r1bar,alphabar,offset) denergy1 = morseD(r1bar,alphabar) f1 = np.polyval(spline1,r1bar) - energy1 f2 = np.polyval(dspline1,r1bar) - denergy1 f3 = np.polyval(spline1,r3bar) f4 = np.polyval(dspline1,r3bar) return np.array([f1,f2,f3,f4])
def compute_join_curvature( px, py ): from scipy.integrate import quad xp = polyder( px, 1 ) xpp = polyder( px, 2 ) yp = polyder( py, 1 ) ypp = polyder( py, 2 ) pn = polyadd( polymul( xp, ypp ), polymul( yp, xpp )) #numerator pd = polyadd( polymul( xp, xp ) , polymul( yp, yp ) ) #denominator integrand = lambda t: fabs(polyval( pn, t )/( polyval( pd, t )**(1.5)) ) return quad(integrand, 0, 1) [0]
def from_poly(cls, x_poly, y_poly): x = np.poly1d(x_poly) y = np.poly1d(y_poly) dx = np.polyder(x) dy = np.polyder(y) ddx = np.polyder(dx) ddy = np.polyder(dy) return Trajectory(x=x, y=y, dx=dx, dy=dy, ddx=ddx, ddy=ddy)
def residue(b,a,tol=1e-3,rtype='avg'): """Compute partial-fraction expansion of b(s) / a(s). If M = len(b) and N = len(a) b(s) b[0] s**(M-1) + b[1] s**(M-2) + ... + b[M-1] H(s) = ------ = ---------------------------------------------- a(s) a[0] s**(N-1) + a[1] s**(N-2) + ... + a[N-1] r[0] r[1] r[-1] = -------- + -------- + ... + --------- + k(s) (s-p[0]) (s-p[1]) (s-p[-1]) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like r[i] r[i+1] r[i+n-1] -------- + ----------- + ... + ----------- (s-p[i]) (s-p[i])**2 (s-p[i])**n See also: invres, poly, polyval, unique_roots """ b,a = map(asarray,(b,a)) k,b = polydiv(b,a) p = roots(a) r = p*0.0 pout, mult = unique_roots(p,tol=tol,rtype=rtype) p = [] for n in range(len(pout)): p.extend([pout[n]]*mult[n]) p = asarray(p) # Compute the residue from the general formula indx = 0 for n in range(len(pout)): bn = b.copy() pn = [] for l in range(len(pout)): if l != n: pn.extend([pout[l]]*mult[l]) an = atleast_1d(poly(pn)) # bn(s) / an(s) is (s-po[n])**Nn * b(s) / a(s) where Nn is # multiplicity of pole at po[n] sig = mult[n] for m in range(sig,0,-1): if sig > m: # compute next derivative of bn(s) / an(s) term1 = polymul(polyder(bn,1),an) term2 = polymul(bn,polyder(an,1)) bn = polysub(term1,term2) an = polymul(an,an) r[indx+m-1] = polyval(bn,pout[n]) / polyval(an,pout[n]) \ / factorial(sig-m) indx += sig return r, p, k
def do_fit(self, results): "Fit the results to a polynomial" if results is None: results = self.results # Use cached results else: self.results = results # Keep for next time self.minimum_ok = False if self.radio_fit_3.get_active(): order = 3 else: order = 2 if len(results) < 3: txt = (_("Insufficent data for a fit\n(only %i data points)\n") % (len(results),) ) order = 0 elif len(results) == 3 and order == 3: txt = _("REVERTING TO 2ND ORDER FIT\n(only 3 data points)\n\n") order = 2 else: txt = "" if order > 0: fit0 = np.poly1d(np.polyfit(results[:,0], results[:,1], order)) fit1 = np.polyder(fit0, 1) fit2 = np.polyder(fit1, 1) x0 = None for t in np.roots(fit1): if fit2(t) > 0: x0 = t break if x0 is None: txt = txt + _("No minimum found!") else: e0 = fit0(x0) e2 = fit2(x0) txt += "E = " if order == 3: txt += "A(x - x0)³ + " txt += "B(x - x0)² + C\n\n" txt += "B = %.5g eV\n" % (e2,) txt += "C = %.5g eV\n" % (e0,) txt += "x0 = %.5g\n" % (x0,) lowest = self.scale_offset.value - self.max_scale.value highest = self.scale_offset.value + self.max_scale.value if x0 < lowest or x0 > highest: txt += _("\nWARNING: Minimum is outside interval\n") txt += _("It is UNRELIABLE!\n") else: self.minimum_ok = True self.x0 = x0 self.fit_output.set_text(txt)
def gruneisen_parameter(self, temperature, volume): """ Slater-gamma formulation(the default): gruneisen paramter = - d log(theta)/ d log(V) = - ( 1/6 + 0.5 d log(B)/ d log(V) ) = - (1/6 + 0.5 V/B dB/dV), where dB/dV = d^2E/dV^2 + V * d^3E/dV^3 Mie-gruneisen formulation: Eq(31) in doi.org/10.1016/j.comphy.2003.12.001 Eq(7) in Blanco et. al. Joumal of Molecular Structure (Theochem) 368 (1996) 245-255 Also se J.P. Poirier, Introduction to the Physics of the Earth’s Interior, 2nd ed. (Cambridge University Press, Cambridge, 2000) Eq(3.53) Args: temperature (float): temperature in K volume (float): in Ang^3 Returns: float: unitless """ if isinstance(self.eos, PolynomialEOS): p = np.poly1d(self.eos.eos_params) # first derivative of energy at 0K wrt volume evaluated at the # given volume, in eV/Ang^3 dEdV = np.polyder(p, 1)(volume) # second derivative of energy at 0K wrt volume evaluated at the # given volume, in eV/Ang^6 d2EdV2 = np.polyder(p, 2)(volume) # third derivative of energy at 0K wrt volume evaluated at the # given volume, in eV/Ang^9 d3EdV3 = np.polyder(p, 3)(volume) else: func = self.ev_eos_fit.func dEdV = derivative(func, volume, dx=1e-3) d2EdV2 = derivative(func, volume, dx=1e-3, n=2, order=5) d3EdV3 = derivative(func, volume, dx=1e-3, n=3, order=7) # Mie-gruneisen formulation if self.use_mie_gruneisen: p0 = dEdV return (self.gpa_to_ev_ang * volume * (self.pressure + p0 / self.gpa_to_ev_ang) / self.vibrational_internal_energy(temperature, volume)) # Slater-gamma formulation # first derivative of bulk modulus wrt volume, eV/Ang^6 dBdV = d2EdV2 + d3EdV3 * volume return -(1./6. + 0.5 * volume * dBdV / FloatWithUnit(self.ev_eos_fit.b0_GPa, "GPa").to("eV ang^-3"))
def _residual_(self): f = np.zeros(8) f[0] = self._morse_energy_(self.r1bar) - self._spline_energy_(self.r1bar,0) f[1] = self._morse_force_(self.r1bar) - self._spline_force_(self.r1bar,0) f[2] = self._spline_energy_(self.r2bar,0) - (-self.ep) f[3] = self._spline_force_(self.r2bar,0) - self._spline_force_(self.r2bar,1) f[4] = self._spline_energy_(self.r2bar,1) - (-self.ep) f[5] = self._spline_energy_(self.r3bar,1) - 0 f[6] = self._spline_force_(self.r3bar,1) - 0 # unnecessary, but nice to have ddspline0, ddspline1 = np.polyder(self.dspline[0]), np.polyder(self.dspline[1]) f[7] = np.polyval(ddspline0,self.r2bar) - np.polyval(ddspline1,self.r2bar) return np.array(f)
def LokaleExtrema(polynom): """Gibt die Koordinaten der lokalen Extrema des übergebenen Polynoms aus""" poly1 = np.polyder(polynom,1) poly2 = np.polyder(polynom,2) roots = poly1.r print roots for root in roots: if (poly2(root) <0): print "Lokales Maximum: " + str(root) + ";" + str(poly(root)) elif (poly2(root) >0): print "Lokales Minimum: " + str(root) + ";" + str(poly(root)) else: #! hmm … break
def analyse(self): for name, data in self.data.items(): if 'distances' in data: distances = data['distances'] energies = data['energies'] fit0 = np.poly1d(np.polyfit(1 / distances, energies, 3)) fit1 = np.polyder(fit0, 1) fit2 = np.polyder(fit1, 1) dmin = None for t in np.roots(fit1): if t > 0 and fit2(t) > 0: dmin = 1 / t break if dmin is None: raise ValueError('No minimum!') if abs(dmin) < min(distances) or abs(dmin) > max(distances): raise ValueError('Fit outside of range! ' + \ str(abs(dmin)) + ' not in ' + \ str(distances)) emin = fit0(t) k = fit2(t) * t**4 m1, m2 = self.create_system(name).get_masses() m = m1 * m2 / (m1 + m2) hnu = units._hbar * 1e10 * sqrt(k / units._e / units._amu / m) data['relaxed energy'] = emin data['distance'] = dmin data['frequency'] = hnu for name, data in self.data.items(): atoms = self.create_system(name) if len(atoms) == 1: continue eatoms = 0.0 for symbol in atoms.get_chemical_symbols(): if symbol in self.data and symbol != name: eatoms += self.data[symbol]['energy'] else: eatoms = None break ea = None ea0 = None if eatoms is not None: data['atomic energy'] = eatoms
def mean_curvature(w, side, dx, n=16): n = min(n, len(w.x) / 4) L = cumulative_path_length(w) tt = L / L.max() teval = tt[n] if side == 0 else tt[-n] px = np.polyfit(tt[n:-n], w.x[n:-n], 2) py = np.polyfit(tt[n:-n], w.y[n:-n], 2) xp = np.polyder(px, 1) xpp = np.polyder(px, 2) yp = np.polyder(py, 1) ypp = np.polyder(py, 2) pn = np.polyadd(np.polymul(xp, ypp), np.polymul(yp, xpp)) # numerator pd = np.polyadd(np.polymul(xp, xp), np.polymul(yp, yp)) # denominator kappa = lambda t: dx * np.polyval(pn, t) / (np.polyval(pd, t) ** (1.5)) # d Tangent angle/ds * ds/dt return quad(kappa, 0, 1, epsrel=1e-3)[0]
def bondlengths(Ea, dE): """Calculate bond lengths and write to bondlengths.csv file""" B = [] E0 = [] csv = open('bondlengths.csv', 'w') for formula, energies in dE: bref = diatomic[formula][1] b = np.linspace(0.96 * bref, 1.04 * bref, 5) e = np.polyfit(b, energies, 3) if not formula in Ea: continue ea, eavasp = Ea[formula] dedb = np.polyder(e, 1) b0 = np.roots(dedb)[1] assert abs(b0 - bref) < 0.1 b = np.linspace(0.96 * bref, 1.04 * bref, 20) e = np.polyval(e, b) - ea if formula == 'O2': plt.plot(b, e, '-', color='0.7', label='GPAW') else: plt.plot(b, e, '-', color='0.7', label='_nolegend_') name = latex(data[formula]['name']) plt.text(b[0], e[0] + 0.2, name) B.append(bref) E0.append(-eavasp) csv.write('`%s`, %.3f, %.3f, %+.3f\n' % (name[1:-1], b0, bref, b0 - bref)) plt.plot(B, E0, 'g.', label='reference') plt.legend(loc='lower right') plt.xlabel('Bond length $\mathrm{\AA}$') plt.ylabel('Energy [eV]') plt.savefig('bondlengths.png')
t_initial = 0.0 t_final = 8.0 t_vec = np.arange(t_initial, t_final + h, h) # Time scaling A = np.array([[1.0, t_initial, t_initial**2, t_initial**3], [0.0, 1.0, 2.0 * t_initial, 3.0 * t_initial**2], [1.0, t_final, t_final**2, t_final**3], [0.0, 1.0, 2.0 * t_final, 3.0 * t_final**2]]) b = np.array([0.0, 0.0, 1.0, 0.0]) # coefficients of the cubic time scaling polynomial (s(t) = a[0] * t**3+ a[1] * t**2 + a[2] * t + a[3] * t) a = (la.inv(A) @ b)[::-1] # coefficients of the first derivative of the cubic time scaling polynomial ap = np.polyder(a) # coefficients of the first derivative of the cubic time scaling polynomial app = np.polyder(ap) # Initial and final configuration of the manipulator q_initial = np.array([0.0, -np.pi / 3, 0.0, -np.pi / 3, 0.0, -np.pi / 3, 0.0]) p_initial, R_initial = spatial_mechanism.forward_kinematics(q_initial) p_final, R_final = spatial_mechanism.forward_kinematics( np.array([ np.pi / 6, np.pi / 3, np.pi / 6, np.pi / 3, np.pi / 6, np.pi / 3, 0.0 ])) # In homogeneous coordinates T_initial = np.eye(4)
def chromatic_analysis(model_path, phase_output): """ Computes chromaticity and writes them to an output file. WARNING: ONLY TESTED FOR PYTHON 3! """ for plane in ['x', 'y']: for pngpdf in ['png', 'pdf']: fo2 = os.path.join(phase_output, 'average/getkick.out') fo3 = os.path.join(phase_output, 'average/kick_' + plane + '.tfs') if os.path.isfile(fo3): ff = fo3 else: ff = fo2 with open(ff) as fo: lines = fo.readlines() fo.close() dpp_meas = np.array([float(lines[11+i].split()[1]) for i in range(len(lines[11:]))]) Q = np.array([float(lines[11+i].split()[3]) for i in range(len(lines[11:]))]) Q_err = [float(lines[11+i].split()[4]) for i in range(len(lines[11:]))] fit, cov = np.polyfit(dpp_meas, Q, 3, cov=True) poly = np.poly1d(fit) chrom1 = np.polyder(poly) chrom2 = np.polyder(chrom1) chrom3 = np.polyder(chrom2) chromaticity = os.path.join(phase_output, 'average/chromaticity_'+plane+'.tfs') chrom = open(chromaticity, 'w') chrom.write("@ Q"+plane+' '+str(poly(0.0))+' +/- '+str(np.sqrt(cov[3][3]))+'\n') chrom.write("@ Q'"+plane+' '+str(chrom1(0.0))+' +/- '+str(np.sqrt(cov[2][2]))+'\n') chrom.write("@ Q''"+plane+' '+str(chrom2(0.0))+' +/- '+str(2*np.sqrt(cov[1][1]))+'\n') chrom.write("@ Q'''"+plane+' '+str(chrom3(0.0))+' +/- '+str(6*np.sqrt(cov[0][0]))+'\n\n') try: model = os.path.join(model_path, 'tune_over_mom.txt') with open(model) as mo: lines = mo.readlines() mo.close() col = 1 if plane == 'x' else 2 Q_mdl = np.array([float(lines[1+i].split()[col]) for i in range(len(lines[1:]))]) dpp_mdl = np.array([float(lines[1+i].split()[0]) for i in range(len(lines[1:]))]) Q_mdl = np.array([Q_mdl[i] for i in range(len(Q_mdl)) if abs(dpp_mdl[i])<0.0025]) dpp_mdl = np.array([dpp_mdl[i] for i in range(len(dpp_mdl)) if abs(dpp_mdl[i])<0.0025]) fit_mdl, cov_mdl = np.polyfit(dpp_mdl, Q_mdl, 3, cov=True) poly_mdl = np.poly1d(fit_mdl) chrom1_mdl = np.polyder(poly_mdl) chrom2_mdl = np.polyder(chrom1_mdl) chrom3_mdl = np.polyder(chrom2_mdl) chrom.write("@ MDL Q"+plane+' '+str(poly_mdl(0.0))+' +/- '+str(np.sqrt(cov_mdl[3][3]))+'\n') chrom.write("@ MDL Q'"+plane+' '+str(chrom1_mdl(0.0))+' +/- '+str(np.sqrt(cov_mdl[2][2]))+'\n') chrom.write("@ MDL Q''"+plane+' '+str(chrom2_mdl(0.0))+' +/- '+str(2*np.sqrt(cov_mdl[1][1]))+'\n') chrom.write("@ MDL Q'''"+plane+' '+str(chrom3_mdl(0.0))+' +/- '+str(6*np.sqrt(cov_mdl[0][0]))+'\n') except: print(" ********************************************\n", "Chromatic analysis:\n", '"No accurate model found."\n', "********************************************") chrom.close() dpp = np.arange(1.1*min((dpp_meas)),1.1*max((dpp_meas)),1e-4) try: size=20 num=1 import matplotlib.pyplot as plt plt.figure(figsize=(10,4.5)) plt.plot(dpp, poly_mdl(dpp)-poly_mdl(0.0), label = 'Model', c='#1f77b4') plt.plot(dpp, poly(dpp)-poly(0.0), label = 'Fit', c='#ff7f0e') #plt.errorbar(dpp_meas, Q, yerr=Q_err, fmt = 'o', ms=5.5, mec= '#d62728', mfc = 'None', capsize=4, c = '#d62728', label = 'Measurement') plt.errorbar(dpp_meas, Q-poly(0.0), yerr=Q_err, fmt = 'o', ms=5.5, mec= '#d62728', mfc = 'None', capsize=4, c = '#d62728', label = 'Measurement') plt.legend(loc = 9, ncol = 3, fontsize=size, bbox_to_anchor=(0.5, 1.42), fancybox=True, numpoints=1, scatterpoints = 1) plt.tick_params('both', labelsize=size) plt.xlabel(r'$\delta_{p}$', fontsize=size) if plane == 'x': plt.ylabel(r'$\Delta Q_{x}$', fontsize=size) else: plt.ylabel(r'$\Delta Q_{y}$', fontsize=size) plt.xlim(1.1*min((dpp_meas)),1.1*max((dpp_meas))) plt.tight_layout() plt.savefig(phase_output+'/average/Chroma_w_MDL_'+plane+'.'+pngpdf, bbox_inches='tight') plt.close(num) num=num+1 except: print(" ********************************************\n", "Chromatic analysis:\n", '"I could not plot model chromaticity."\n', "********************************************") try: plt.figure(figsize=(10,4.5)) plt.plot(dpp, poly(dpp)-poly(0.0), label = 'Fit', c='#ff7f0e') plt.errorbar(dpp_meas, Q-poly(0.0), yerr=Q_err, fmt = 'o', ms=5.5, mec= '#d62728', mfc = 'None', capsize=4, c = '#d62728', label = 'Measurement') plt.legend(loc = 9, ncol = 3, fontsize=size, bbox_to_anchor=(0.5, 1.42), fancybox=True, numpoints=1, scatterpoints = 1) plt.tick_params('both', labelsize=size) plt.xlabel(r'$\delta_{p}$', fontsize=size) if plane == 'x': plt.ylabel(r'$\Delta Q_{x}$', fontsize=size) else: plt.ylabel(r'$\Delta Q_{y}$', fontsize=size) plt.xlim(1.1*min((dpp_meas)),1.1*max((dpp_meas))) plt.tight_layout() plt.savefig(phase_output+'/average/Chroma_'+plane+'.'+pngpdf, bbox_inches='tight') plt.close(num) except: print(" ********************************************\n", "Chromatic analysis:\n", '"I could not plot chromaticity."\n', "********************************************")
strain.append(float(line.split()[0])) strain, energy = sortstrain(strain, energy) #------------------------------------------------------------------------------- bohr_radius = 0.529177 joule2hartree = 4.3597482 joule2rydberg = joule2hartree / 2. unitconv = joule2hartree / bohr_radius**3 * 10.**3 #------------------------------------------------------------------------------- fitr = numpy.polyfit(strain, energy, order_of_fit) curv = numpy.poly1d(fitr) bulk = numpy.poly1d(numpy.polyder(fitr, 2)) vmin = numpy.roots(numpy.polyder(fitr)) dmin = [] for i in range(len(vmin)): if (abs(vmin[i].imag) < 1.e-10): if (strain[0] <= vmin[i] and vmin[i] <= strain[-1]): if (bulk(vmin[i]) > 0): dmin.append(vmin[i].real) xvol = numpy.linspace(strain[0], strain[-1], 100) chi = 0 for i in range(len(energy)): chi = chi + (energy[i] - curv(strain[i]))**2 chi = sqrt(chi) / len(energy)
def residue(b, a, tol=1e-3, rtype='avg'): """ Compute partial-fraction expansion of b(s) / a(s). If ``M = len(b)`` and ``N = len(a)``, then the partial-fraction expansion H(s) is defined as:: b(s) b[0] s**(M-1) + b[1] s**(M-2) + ... + b[M-1] H(s) = ------ = ---------------------------------------------- a(s) a[0] s**(N-1) + a[1] s**(N-2) + ... + a[N-1] r[0] r[1] r[-1] = -------- + -------- + ... + --------- + k(s) (s-p[0]) (s-p[1]) (s-p[-1]) If there are any repeated roots (closer together than `tol`), then H(s) has terms like:: r[i] r[i+1] r[i+n-1] -------- + ----------- + ... + ----------- (s-p[i]) (s-p[i])**2 (s-p[i])**n Returns ------- r : ndarray Residues. p : ndarray Poles. k : ndarray Coefficients of the direct polynomial term. See Also -------- invres, numpy.poly, unique_roots """ b, a = map(asarray, (b, a)) rscale = a[0] k, b = polydiv(b, a) p = roots(a) r = p * 0.0 pout, mult = unique_roots(p, tol=tol, rtype=rtype) p = [] for n in range(len(pout)): p.extend([pout[n]] * mult[n]) p = asarray(p) # Compute the residue from the general formula indx = 0 for n in range(len(pout)): bn = b.copy() pn = [] for l in range(len(pout)): if l != n: pn.extend([pout[l]] * mult[l]) an = atleast_1d(poly(pn)) # bn(s) / an(s) is (s-po[n])**Nn * b(s) / a(s) where Nn is # multiplicity of pole at po[n] sig = mult[n] for m in range(sig, 0, -1): if sig > m: # compute next derivative of bn(s) / an(s) term1 = polymul(polyder(bn, 1), an) term2 = polymul(bn, polyder(an, 1)) bn = polysub(term1, term2) an = polymul(an, an) r[indx + m - 1] = polyval(bn, pout[n]) / polyval(an, pout[n]) \ / factorial(sig - m) indx += sig return r / rscale, p, k
dfdt_analytical = np.cos(t) dfdt_fwd = forward_diff(t, f) dfdt_bck = backward_diff(t, f) dfdt_ctr = central_diff(t, f) plt.plot(t, dfdt_fwd, label='forward difference approxmation') plt.plot(t, dfdt_bck, label='backward difference approxmation') plt.plot(t, dfdt_ctr, label='central difference approxmation') plt.plot(t, dfdt_analytical, 'k--', label='analytical derivative') plt.legend() plt.show() # using numpy function p = np.poly1d([1, 1, 1, 1]) pd = np.polyder(p) print(pd) # we can simply using pd as a function to calculate the # derivative at certain location print(pd(3.5)) # second derivative of p print(np.polyder(p, 2)) # dealing with piece-wise functions def f1(x): if x < 0: return 0 elif 0 <= x <= 1: return x
import numpy as np import sys from matplotlib.pyplot import plot from matplotlib.pyplot import show bhp=np.loadtxt('BHP.csv', delimiter=',', usecols=(6,), unpack=True) vale=np.loadtxt('VALE.csv', delimiter=',', usecols=(6,), unpack=True) t = np.arange(len(bhp)) poly = np.polyfit(t, bhp - vale, int(sys.argv[1])) print "Polynomial fit", poly print "Next value", np.polyval(poly, t[-1] + 1) print "Roots", np.roots(poly) der = np.polyder(poly) print "Derivative", der print "Extremas", np.roots(der) vals = np.polyval(poly, t) print np.argmax(vals) print np.argmin(vals) plot(t, bhp - vale) plot(t, vals) show()
def test_polyder_return_type(self): # Ticket #1249 assert_(isinstance(np.polyder(np.poly1d([1]), 0), np.poly1d)) assert_(isinstance(np.polyder([1], 0), np.ndarray)) assert_(isinstance(np.polyder(np.poly1d([1]), 1), np.poly1d)) assert_(isinstance(np.polyder([1], 1), np.ndarray))
def stability_margins(sysdata, returnall=False, epsw=1e-8): """Calculate stability margins and associated crossover frequencies. Parameters ---------- sysdata: LTI system or (mag, phase, omega) sequence sys : LTI system Linear SISO system mag, phase, omega : sequence of array_like Arrays of magnitudes (absolute values, not dB), phases (degrees), and corresponding frequencies. Crossover frequencies returned are in the same units as those in `omega` (e.g., rad/sec or Hz). returnall: bool, optional If true, return all margins found. If false (default), return only the minimum stability margins. For frequency data or FRD systems, only one margin is found and returned. epsw: float, optional Frequencies below this value (default 1e-8) are considered static gain, and not returned as margin. Returns ------- gm: float or array_like Gain margin pm: float or array_loke Phase margin sm: float or array_like Stability margin, the minimum distance from the Nyquist plot to -1 wg: float or array_like Gain margin crossover frequency (where phase crosses -180 degrees) wp: float or array_like Phase margin crossover frequency (where gain crosses 0 dB) ws: float or array_like Stability margin frequency (where Nyquist plot is closest to -1) """ try: if isinstance(sysdata, frdata.FRD): sys = frdata.FRD(sysdata, smooth=True) elif isinstance(sysdata, xferfcn.TransferFunction): sys = sysdata elif getattr(sysdata, '__iter__', False) and len(sysdata) == 3: mag, phase, omega = sysdata sys = frdata.FRD(mag * np.exp(1j * phase * np.pi / 180), omega, smooth=True) else: sys = xferfcn._convertToTransferFunction(sysdata) except Exception as e: print(e) raise ValueError("Margin sysdata must be either a linear system or " "a 3-sequence of mag, phase, omega.") # calculate gain of system if isinstance(sys, xferfcn.TransferFunction): # check for siso if not issiso(sys): raise ValueError("Can only do margins for SISO system") # real and imaginary part polynomials in omega: rnum, inum = _polyimsplit(sys.num[0][0]) rden, iden = _polyimsplit(sys.den[0][0]) # test (imaginary part of tf) == 0, for phase crossover/gain margins test_w_180 = np.polyadd(np.polymul(inum, rden), np.polymul(rnum, -iden)) w_180 = np.roots(test_w_180) #print ('1:w_180', w_180) # first remove imaginary and negative frequencies, epsw removes the # "0" frequency for type-2 systems w_180 = np.real(w_180[(np.imag(w_180) == 0) * (w_180 >= epsw)]) #print ('2:w_180', w_180) # evaluate response at remaining frequencies, to test for phase 180 vs 0 resp_w_180 = np.real( np.polyval(sys.num[0][0], 1.j * w_180) / np.polyval(sys.den[0][0], 1.j * w_180)) #print ('resp_w_180', resp_w_180) # only keep frequencies where the negative real axis is crossed w_180 = w_180[np.real(resp_w_180) < 0.0] # and sort w_180.sort() #print ('3:w_180', w_180) # test magnitude is 1 for gain crossover/phase margins test_wc = np.polysub(np.polyadd(_polysqr(rnum), _polysqr(inum)), np.polyadd(_polysqr(rden), _polysqr(iden))) wc = np.roots(test_wc) wc = np.real(wc[(np.imag(wc) == 0) * (wc > epsw)]) wc.sort() # stability margin was a bitch to elaborate, relies on magnitude to # point -1, then take the derivative. Second derivative needs to be >0 # to have a minimum test_wstabd = np.polyadd(_polysqr(rden), _polysqr(iden)) test_wstabn = np.polyadd(_polysqr(np.polyadd(rnum, rden)), _polysqr(np.polyadd(inum, iden))) test_wstab = np.polysub( np.polymul(np.polyder(test_wstabn), test_wstabd), np.polymul(np.polyder(test_wstabd), test_wstabn)) # find the solutions, for positive omega, and only real ones wstab = np.roots(test_wstab) #print('wstabr', wstab) wstab = np.real(wstab[(np.imag(wstab) == 0) * (np.real(wstab) >= 0)]) #print('wstab', wstab) # and find the value of the 2nd derivative there, needs to be positive wstabplus = np.polyval(np.polyder(test_wstab), wstab) #print('wstabplus', wstabplus) wstab = np.real(wstab[(np.imag(wstab) == 0) * (wstab > epsw) * (wstabplus > 0.)]) #print('wstab', wstab) wstab.sort() else: # a bit coarse, have the interpolated frd evaluated again def mod(w): """to give the function to calculate |G(jw)| = 1""" return np.abs(sys.evalfr(w)[0][0]) - 1 def arg(w): """function to calculate the phase angle at -180 deg""" return np.angle(-sys.evalfr(w)[0][0]) def dstab(w): """function to calculate the distance from -1 point""" return np.abs(sys.evalfr(w)[0][0] + 1.) # Find all crossings, note that this depends on omega having # a correct range widx = np.where(np.diff(np.sign(mod(sys.omega))))[0] wc = np.array([ sp.optimize.brentq(mod, sys.omega[i], sys.omega[i + 1]) for i in widx if i + 1 < len(sys.omega) ]) # find the phase crossings ang(H(jw) == -180 widx = np.where(np.diff(np.sign(arg(sys.omega))))[0] #print('widx (180)', widx, sys.omega[widx]) #print('x', sys.evalfr(sys.omega[widx])[0][0]) widx = widx[np.real(sys.evalfr(sys.omega[widx])[0][0]) <= 0] #print('widx (180,2)', widx) w_180 = np.array([ sp.optimize.brentq(arg, sys.omega[i], sys.omega[i + 1]) for i in widx if i + 1 < len(sys.omega) ]) #print('x', sys.evalfr(w_180)[0][0]) #print('w_180', w_180) # find all stab margins? widx = np.where(np.diff(np.sign(np.diff(dstab(sys.omega)))))[0] #print('widx', widx) #print('wstabx', sys.omega[widx]) wstab = np.array([ sp.optimize.minimize_scalar(dstab, bracket=(sys.omega[i], sys.omega[i + 1])).x for i in widx if i + 1 < len(sys.omega) and np.diff(np.diff(dstab(sys.omega[i - 1:i + 2])))[0] > 0 ]) #print('wstabf0', wstab) wstab = wstab[(wstab >= sys.omega[0]) * (wstab <= sys.omega[-1])] #print ('wstabf', wstab) # margins, as iterables, converted frdata and xferfcn calculations to # vector for this GM = 1 / np.abs(sys.evalfr(w_180)[0][0]) SM = np.abs(sys.evalfr(wstab)[0][0] + 1) PM = np.angle(sys.evalfr(wc)[0][0], deg=True) + 180 if returnall: return GM, PM, SM, w_180, wc, wstab else: return ((GM.shape[0] or None) and np.amin(GM), (PM.shape[0] or None) and np.amin(PM), (SM.shape[0] or None) and np.amin(SM), (w_180.shape[0] or None) and w_180[GM == np.amin(GM)][0], (wc.shape[0] or None) and wc[PM == np.amin(PM)][0], (wstab.shape[0] or None) and wstab[SM == np.amin(SM)][0])
np.where(a>2, b, c) #wherever a>2, choose corresp item in b, wherever false, choose in c # Linear Algebra np.linalg.det(a) vals, vecs = np.linalg.eig(a) np.linalg.inv(a) a*b #element wise a@b #matrix mult np.dot(a,b) #dot product # Random numbers np.random.seed(12345) np.random.randint(5,10, size=(3,2)) #random int between [5,10) np.random.normal(1.5, 4.0) #random gaussian mean stdev np.random.rand(3,2) #Statistics a.mean() a.var() a.std() a.min() a.max() a.argmin() a.argmax() #Calculus np.poly([-1,1,1,10]) #roots to coeffs np.roots([1,4,-2,3]) #coeffs to roots np.polyint([1,1,1,1]) #symbolic integration of coeffs np.polyder([1./4., 1./3., 1./2., 1., 0.]) #symbolic deriv of coeffs np.polyfit(x,y,2) #ordered pairs to coeffs of best fit order 2 poly
def angular_equation_f_series_expansion(m,L,a,b,c2, sigma, parity, etas, n=20): """ solve angular equation for f(eta) around eta=sigma (where sigma=+1 or -1) by a series expansion of length n. Parameters ---------- m : number of nodes in angular wavefunction S(eta) L : value of separation constant a : R*(Za+Zb) = 2*D, where D is the distance between the two protons b : R*(Za-Zb) = 0, has to be zero c2 : related to energy E of solution, c^2 = 1/2 E D^2 etas : 1d numpy array with grid on which f(eta) should be evaluated, the points should lie close to eta=sigma for the solution to be valid sigma : point around which solution is expanded, +1 or -1 parity : initial value, f(sigma) = parity, +1 or -1 Optional -------- n : degree of polynomial in expansion Returns ------- fs : 1d numpy array with f(etas) fs_der : 1d numpy array with derivative f'(etas) The differential equation to be solve is: (1-eta^2) f''(eta) - 2*(m+1) eta f'(eta) - [m*(m+1) - L + c^2*eta^2] f(eta) = 0 The angular wavefunction S(eta) is related to f(eta) by: S(eta) = f(eta) * (1-eta^2)^(m/2) The ansatz for f(eta) around eta=sigma is given by f(eta) = sum_i^n d_i (1-sigma*eta)^i Substituting this ansatz into the differential equation and equating coefficients leads again to a four term recurrence relation for the d's: p_i d_(i+1) + q_i d_i + r_i d_(i-1) + s_i d_(i-2) = 0 with the coefficients p_i = 2*(i+1)*(i+m+1) q_i = -c^2 + L - m*(m+1) - i*(2*m+i+1) r_i = 2*c^2 s_i = -c^2 and the initial conditions d_(-2) = 0 , d_(-1) = 0, d_0 = sigma """ assert b == 0.0, "Code does not work for Za != Zb" # compute coefficients of 4 term recurrence p = np.zeros(n+1) q = np.zeros(n+1) r = np.zeros(n+1) s = np.zeros(n+1) for i in range(0, n+1): p[i] = 2*(i+1)*(i+m+1) q[i] = -c2+L-m*(m+1) - i*(2*m+i+1) r[i] = 2*c2 s[i] = -c2 # initialize recurrence relation d = np.zeros(n+1+2) d[-2] = 0.0 d[-1] = 0.0 d[0] = parity # iterate recurrence relation for i in range(0,n): d[i+1] = (-q[i]*d[i]-r[i]*d[i-1]-s[i]*d[i-2])/p[i] # remove entries for d_(-2) and d_(-1) d = d[0:-2] # evaluate the polynomial # f(eta) = sum_i=0^n d_i (1-sigma*eta)^i omes = 1.0-sigma*etas # poly1d needs the coefficients in reverse order poly = np.poly1d(d[::-1]) # derivative poly_der = np.polyder(poly, m=1) # evaluate polynomial fs = np.polyval(poly, omes) # evaluate derivative of polynomial # The minus sign comes from the chain rule # d/d(x) = -sigma* d/d(1-sigma*x) fs_der = -sigma*np.polyval(poly_der, omes) return fs, fs_der
def get_gradient(self): tmp_coeff = self.coeff + [0] self.gd_coeff = np.polyder(self.coeff) self.mem_gd_coeff = np.polyder(tmp_coeff)
def radial_equation_g_series_expansion(m,L,a,b,c2, xs, n=20): """ solve radial equation for g(x) around x=1 by a series expansion of length n. Parameters ---------- m : number of nodes in angular wavefunction S(eta) L : value of separation constant a : R*(Za+Zb) = 2*D, where D is the distance between the two protons b : R*(Za-Zb) = 0, has to be zero c2 : related to energy E of solution, c^2 = 1/2 E D^2 xs : 1d numpy array with grid on which g(x) should be evaluated, the points should lie close to x=1 for the solution to be valid Optional -------- n : degree of polynomial in expansion Returns ------- gs : 1d numpy array with g(xs) gs_der : 1d numpy array with derivative g'(xs) The differential equation to be solved is: (x^2-1) g''(x) + 2*(m+1) x g'(x) + [a*x + c^2*x^2 + m*(m+1) - L] g(x) = 0 The radial wavefunction R(x) is related to g(x) by: R(x) = g(x) * (x^2-1)^(m/2) The ansatz for g(x) around x=1 is given by g(x) = sum_i^n d_i (1 - x)^i Substituting this ansatz into the differential equation and equating coefficients leads to a four term recurrence relation (see eqn. 14 in Ref. [2]) for the d's: p_i d_(i+1) + q_i d_i + r_i d_(i-1) + s_i d_(i-2) = 0 with the coefficients p_i = -2*(i+1)*(i+m+1) q_i = i*(i-1) + 2*i*(m+1) + m*(m+1) - L + c^2 + a r_i = -a - 2*c^2 s_i = c^2 and the initial conditions d_(-2) = 0 , d_(-1) = 0, d_0 = 1 """ assert b == 0.0, "Code does not work for Za != Zb" # compute coefficients of 4 term recurrence p = np.zeros(n+1) q = np.zeros(n+1) r = np.zeros(n+1) s = np.zeros(n+1) for i in range(0, n+1): p[i] = -2*(i+1)*(i+m+1) q[i] = i*(i-1)+2*(m+1)*i+m*(m+1)-L+c2 + a r[i] = -a - 2*c2 s[i] = c2 # initialize recurrence relation d = np.zeros(n+1+2) d[-2] = 0.0 d[-1] = 0.0 d[0] = 1.0 # iterate recurrence relation for i in range(0,n): d[i+1] = (-q[i]*d[i]-r[i]*d[i-1]-s[i]*d[i-2])/p[i] # remove entries for d_(-2) and d_(-1) d = d[0:-2] # evaluate the polynomial # g(x) = sum_i=0^n d_i (1-x)^i omxs = 1.0-xs # poly1d needs the coefficients in reverse order poly = np.poly1d(d[::-1]) # derivative poly_der = np.polyder(poly, m=1) # evaluate polynomial gs = np.polyval(poly, omxs) # evaluate derivative of polynomial # The minus sign comes from the chain rule # d/d(x) = - d/d(1-x) gs_der = -np.polyval(poly_der, omxs) return gs, gs_der
def odom_callback(self, odom): """send command to px4""" self.odom_time = odom.header.stamp.to_sec() X = ar([[odom.pose.pose.position.x], [odom.pose.pose.position.y], [odom.pose.pose.position.z]]) q = Quaternion(odom.pose.pose.orientation.w, odom.pose.pose.orientation.x,\ odom.pose.pose.orientation.y, odom.pose.pose.orientation.z) R = q.rotation_matrix # ensure that the linear velocity is in inertial frame, ETHZ code multiply linear vel to rotation matrix V = ar([[odom.twist.twist.linear.x], [odom.twist.twist.linear.y], [odom.twist.twist.linear.z]]) # CROSSCHECK AND MAKE SURE THAT THE ANGULAR VELOCITY IS IN INERTIAL FRAME...HOW? Omega = ar([[odom.twist.twist.angular.x], [odom.twist.twist.angular.y], [odom.twist.twist.angular.z]]) #Omega = np.dot(R.T, Omega) # this is needed because "vicon" package from Upenn publishes spatial angular velocities t = float(self.odom_time - self.traj_start_time) if t <= self.traj_end_time[self.number_of_segments]: index = bisect.bisect(self.traj_end_time, t)-1 else: index = bisect.bisect(self.traj_end_time, t)-2 if index == -1: pass else: xx = np.poly1d(self.p1[index]) vx = np.polyder(xx, 1); aax = np.polyder(xx, 2) jx = np.polyder(xx, 3) yy = np.poly1d(self.p2[index]) vy = np.polyder(yy, 1); aay = np.polyder(yy, 2) jy = np.polyder(yy, 3) zz = np.poly1d(self.p3[index]) vz = np.polyder(zz, 1); aaz = np.polyder(zz, 2) jz = np.polyder(zz, 3) if self.mode == 'hover' or self.mode == 'land': if t <= self.traj_end_time[self.number_of_segments]: self.pdes = ar([[xx(t)], [yy(t)], [zz(t)]]) self.vdes = ar([[vx(t)], [vy(t)], [vz(t)]]) self.ades = ar([[aax(t)], [aay(t)], [aaz(t)]]) self.jdes = ar([[jx(t)], [jy(t)], [jz(t)]]) #self.ddes = self.ddir else: self.pdes = ar([[xx(self.traj_end_time[-1])], [yy(self.traj_end_time[-1])], [zz(self.traj_end_time[-1])]]) self.vdes = ar([[vx(self.traj_end_time[-1])], [vy(self.traj_end_time[-1])], [vz(self.traj_end_time[-1])]]) self.ades = ar([[aax(self.traj_end_time[-1])], [aay(self.traj_end_time[-1])], [aaz(self.traj_end_time[-1])]]) self.jdes = ar([[jx(self.traj_end_time[-1])], [jy(self.traj_end_time[-1])], [jz(self.traj_end_time[-1])]]) #self.ddes = self.ddir else: if t<= self.execution_time_horizon: self.pdes = ar([[xx(t)], [yy(t)], [zz(t)]]) self.vdes = ar([[vx(t)], [vy(t)], [vz(t)]]) self.ades = ar([[aax(t)], [aay(t)], [aaz(t)]]) self.jdes = ar([[jx(t)], [jy(t)], [jz(t)]]) #self.ddes = self.ddir else: ttt = self.execution_time_horizon self.pdes = ar([[xx(ttt)], [yy(ttt)], [zz(ttt)]]) self.vdes = ar([[vx(ttt)], [vy(ttt)], [vz(ttt)]]) self.ades = ar([[aax(ttt)], [aay(ttt)], [aaz(ttt)]]) self.jdes = ar([[jx(ttt)], [jy(ttt)], [jz(ttt)]]) #self.ddes = self.ddir current_time = time.time()-self.start_time if self.counter == 0: self.initial_odom_time = current_time Xd = self.pdes; Vd = self.vdes; ad = self.ades; b1d = self.ddes b1d_dot = ar([[0],[0],[0]]); ad_dot = self.jdes if self.controller == 1: # velocity controller ex = ar([[0],[0],[0]]) else: ex = X-Xd ev = V-Vd #_b3c = -(mult(self.kx, ex) + mult(self.kv, ev)+ mult(self.ki, ei))/self.m + self.g*self.e[:,2][np.newaxis].T + ad # desired direction _b3c = -(mult(self.kx, ex) + mult(self.kv, ev))/self.m + self.g*self.e[:,2][np.newaxis].T + ad # desired direction b3c = ar(_b3c/np.linalg.norm(_b3c)) # get a normalized vector b2c = tp(np.cross(b3c.T,b1d.T)/np.linalg.norm(np.cross(b3c.T, b1d.T))) # vector b2d b1c = tp(np.cross(b2c.T, b3c.T)) Rc = np.column_stack((b1c, b2c, b3c)) # desired rotation matrix` qc = self.rotmat2quat(Rc) omega_des = q.inverse*qc self.f = self.m*np.dot(_b3c.T, tp(R[:,2][np.newaxis]))/self.norm_thrust_constant # normalized thrust #self.M = -(mult(self.kR, eR) + mult(self.kOmega, eOmega)) + tp(np.cross(Omega.T, tp(np.dot(self.J,Omega)))) msg = AttitudeTarget() msg.header.stamp = odom.header.stamp msg.type_mask = 128 msg.body_rate.x = self.factor*np.sign(omega_des[0])*omega_des[1] msg.body_rate.y = self.factor*np.sign(omega_des[0])*omega_des[2] msg.body_rate.z = self.factor*np.sign(omega_des[0])*omega_des[3] msg.thrust = min(1.0, self.f[0][0]) print 'thrust:', self.f*self.norm_thrust_constant, 'thrust_factor:', min(1.0, self.f[0][0]) print 'omega_des',msg.body_rate.x, msg.body_rate.y, msg.body_rate.z print 'zheight', Xd[2][0] f1 = open(self.path+'position_trajectory.txt', 'a') f1.write("%s, %s, %s, %s, %s, %s\n" % (Xd[0][0], Xd[1][0], Xd[2][0], X[0][0], X[1][0], X[2][0])) f2 = open(self.path+'velocity_trajectory.txt', 'a') f2.write("%s, %s, %s, %s, %s, %s\n" % (Vd[0][0], Vd[1][0], Vd[2][0], V[0][0], V[1][0], V[2][0])) f3 = open(self.path + 'commands.txt', 'a') f3.write("%s, %s, %s, %s\n" % (msg.thrust, msg.body_rate.x, msg.body_rate.y, msg.body_rate.z)) self.counter = self.counter+1 self.pub.publish(msg)
coeff = np.float64(coeff) t0 = np.float64(t0 - stt_date) * 86400.0 t1 = np.float64(t1 - stt_date) * 86400.0 dt = (np.array([0, nbin0]) * tsamp + stt_sec - t0) / (t1 - t0) * 2 - 1 coeff1 = coeff.sum(1) phase = nc.chebval(dt, coeff1) + dispc / freq_end**2 phase0 = np.ceil(phase[0]) nperiod = int( np.floor(phase[-1] - phase0 + dispc / freq_start**2 - dispc / freq_end**2)) coeff[0, 0] -= phase0 coeff1 = coeff.sum(1) roots = nc.chebroots(coeff1) roots = np.real(roots[np.isreal(roots)]) root = roots[np.argmin(np.abs(roots - dt[0]))] period = 1. / np.polyval(np.polyder(nc.cheb2poly(coeff1)[::-1]), root) / 2.0 * (t1 - t0) stt_sec = (root + 1) / 2.0 * (t1 - t0) + t0 stt_date = stt_date + stt_sec // 86400 stt_sec = stt_sec % 86400 info['phase0'] = int(phase0) + tmp phase -= phase0 # info['nperiod'] = nperiod info['period'] = period # nbin_max = (nbin0 - 1) / (np.max(phase) - np.min(phase)) if args.nbin: nbin = args.nbin if nbin > nbin_max: temp_multi = 1
(r * cos(a / 2), -r * sin(a / 2), 0), (0, 0, 0)]) dimer.calc = calc E = [] F = [] for d in D: dimer.positions[3:, 0] += d - dimer.positions[5, 0] E.append(dimer.get_potential_energy()) F.append(dimer.get_forces()) F = np.array(F) # plt.plot(D, E) F1 = np.polyval(np.polyder(np.polyfit(D, E, 7)), D) F2 = F[:, :3, 0].sum(1) error = abs(F1 - F2).max() dimer.constraints = FixInternals( bonds=[(r, (0, 2)), (r, (1, 2)), (r, (3, 5)), (r, (4, 5))], angles=[(a, (0, 2, 1)), (a, (3, 5, 4))]) opt = GPMin(dimer, trajectory=calc.name + '.traj', logfile=calc.name + 'd.log') opt.run(0.01) e0 = dimer.get_potential_energy() d0 = dimer.get_distance(2, 5) R = dimer.positions v1 = R[1] - R[5]
#Construcao de Funcao Polinomial #%% import numpy as np f2grau = np.poly1d([1, 2, 3])#coeficientes f2OtherVariable = np.poly1d([1,2,3], variable='z') print(p(1)) f3grau = np.poly1d([1, 2, 3], True)#raizes f3grau = np.poly1d([1,1,1,1]) #derivar derivadaPrimeira = np.polyder(f3grau) derivadaSegunda = np.polyder(f3grau, 2) derivadaTerceira = np.polyder(f3grau, 3) #integrar integralPrimeira = np.polyint(f3grau) integralSegunda = np.polyint(f3grau, 2) integralTerceira = np.polyint(f3grau, 3) #Tratamento de sinais - convolucao
def make_page(symbol): filename = symbol + '.rst' try: data = pickle.load(open( '../_static/setups-data/%s.pckl' % symbol, 'rb')) except EOFError: print(symbol, 'missing!') return Z = atomic_numbers[symbol] name = atomic_names[Z] bulk = [] if symbol in ('Ni Pd Pt La Na Nb Mg Li Pb Rb Rh Ta Ba Fe Mo C K Si W V ' + 'Zn Co Ag Ca Ir Al Cd Ge Au Cs Cr Cu').split(): bulk.append(symbol) for alloy in ('LaN LiCl MgO NaCl GaN AlAs BP FeAl BN LiF NaF ' + 'SiC ZrC ZrN AlN VN NbC GaP AlP BAs GaAs MgS ' + 'ZnO NiAl CaO').split(): if symbol in alloy: bulk.append(alloy) if len(bulk) > 0: if len(bulk) == 1: bulk = 'test for ' + bulk[0] else: bulk = 'tests for ' + ', '.join(bulk[:-1]) + ' and ' + bulk[-1] tests = 'See %s here: :ref:`bulk_tests`. ' % bulk else: tests = '' molecules = [] for x in atomization_vasp: if symbol in x: molecules.append(molecule_data[x]['name']) if molecules: names = [rest(m) for m in molecules] if len(molecules) == 1: mols = names[0] elif len(molecules) > 5: mols = ', '.join(names[:5]) + ' ...' else: mols = ', '.join(names[:-1]) + ' and ' + names[-1] tests += 'See tests for %s here: :ref:`molecule_tests`.' % mols if name[0] in 'AEIOUY': aname = 'an ' + name.lower() else: aname = 'a ' + name.lower() table = '' for n, l, f, e, rcut in data['nlfer']: if n == -1: n = '\*' table += '%2s%s %3d %10.3f Ha' % (n, 'spdf'[l], f, e) if rcut: table += ' %.2f Bohr\n' % rcut else: table += '\n' f = open(symbol + '.rst', 'w') f.write(page % { 'name': name, 'aname': aname, 'tests': tests, 'symbol': symbol, 'Nv': data['Nv'], 'Nc': data['Nc'], 'plural': 's'[:data['Nv'] > 1], 'table': table, 'rcutcomp': data['rcutcomp'], 'rcutfilter': data['rcutfilter'], 'rcutcore': data['rcore'], 'Ekin': data['Ekin'], 'Epot': data['Epot'], 'Exc': data['Exc'], 'Etot': data['Ekin'] + data['Epot'] + data['Exc']}) f.close() # Make convergence test figure: d = data['d0'] * np.linspace(0.94, 1.06, 7) h = data['gridspacings'] ng = len(h) Edimer0 = np.empty(ng) ddimer0 = np.empty(ng) Eegg = data['Eegg'] Edimer = data['Edimer'] for i in range(ng): E = Edimer[i] energy = np.polyfit(d**-1, E, 3) der = np.polyder(energy, 1) roots = np.roots(der) der2 = np.polyder(der, 1) if np.polyval(der2, roots[0]) > 0: root = roots[0] else: root = roots[1] if isinstance(root, complex): print('??????') root = root.real d0 = 1.0 / root.real E0 = np.polyval(energy, root) Edimer0[i] = E0 ddimer0[i] = d0 if not (d[0] < d0 < d[-1]): print(d, d0, symbol) print('%2s %.3f %+7.1f %%' % (symbol, d0, 100 * (d0 / d[3] - 1))) Ediss = 2 * Eegg[:, 0] - Edimer0 import pylab as plt dpi = 80 fig = plt.figure(figsize=(6, 11), dpi=dpi) fig.subplots_adjust(left=0.15, right=0.97, top=0.97, bottom=0.04) plt.subplot(311) plt.semilogy(h[:-1], 2 * abs(Eegg[:-1, 0] - Eegg[-1, 0]), '-o', label=r'$2E_a$') plt.semilogy(h[:-1], abs(Edimer0[:-1] - Edimer0[-1]), '-o', label=r'$E_d$') plt.semilogy(h[:-1], abs(Ediss[:-1] - Ediss[-1]), '-o', label=r'$2E_a-E_d$') plt.semilogy(h, Eegg.ptp(axis=1), '-o', label=r'$E_{egg}$') #plt.title('Energy differences') plt.xlabel(r'h [\AA]') plt.ylabel('energy [eV]') plt.legend(loc='best') plt.subplot(312) plt.semilogy(h, np.abs(data['Fegg']).max(axis=1), '-o', label=r'$|\mathbf{F}_{egg}|$') plt.semilogy(h, np.abs(data['Fdimer'].sum(axis=2)).max(axis=1), '-o', label=r'$|\mathbf{F}_1 + \mathbf{F}_2|$') #plt.title('Forces') plt.xlabel(r'h [\AA]') plt.ylabel(r'force [eV/\AA]') plt.legend(loc='best') plt.subplot(313) d = ddimer0[-1] plt.plot(h, ddimer0, '-o') #plt.title('Bond length') plt.xlabel(r'h [\AA]') plt.axis(ymin=d * 0.98, ymax=d * 1.02) plt.ylabel(r'bond length [\AA]') plt.savefig('../_static/setups-data/%s-dimer-eggbox.png' % symbol, dpi=dpi)
exit() # obtaining upper bound on roots using Cauchy p /= p[0] # to make it monic coeffs = list(np.absolute(p))[1:] upper_bound = max(map(lambda x: x[1]**(1 / (x[0] + 1)), enumerate(coeffs))) p /= upper_bound**np.arange(p.shape[0]) p /= p[0] # to ensure it's monic #obtaining starting points N = math.ceil(2 * d * math.log(d)) x0s = 2 * np.exp(1j * np.linspace(0, 2 * np.pi, N, endpoint=False)) #defining some functions pprime = np.polyder(p) fun = lambda x: np.polyval(p, x) funprime = lambda x: np.polyval(pprime, x) zeros = [] for x0 in x0s: try: zero = newton(func=fun, x0=x0, fprime=funprime, maxiter=N) except RuntimeError: print('Increase the limit') continue zeros.append(zero) # filtering out zeros by evaluating on function zeros = np.array([ z * upper_bound for z in zeros
DELTAS = np.linspace(-0.05, 0.05, 5) calcs = [] volumes = [] for delta in DELTAS: atoms = FaceCenteredCubic(symbol='Al') cell = atoms.cell T = np.array([[1 + delta, 0, 0], [0, 1, 0], [0, 0, 1]]) newcell = np.dot(cell, T) atoms.set_cell(newcell, scale_atoms=True) volumes += [atoms.get_volume()] calcs += [ Vasp('bulk/Al-c11-{}'.format(delta), xc='pbe', kpts=[12, 12, 12], encut=350, atoms=atoms) ] Vasp.run() energies = [calc.potential_energy for calc in calcs] # fit a parabola eos = np.polyfit(DELTAS, energies, 2) # first derivative d_eos = np.polyder(eos) print(np.roots(d_eos)) xfit = np.linspace(min(DELTAS), max(DELTAS)) yfit = np.polyval(eos, xfit) plt.plot(DELTAS, energies, 'bo', xfit, yfit, 'b-') plt.xlabel('$\delta$') plt.ylabel('Energy (eV)') plt.savefig('images/Al-c11.png')
-0.53474862 ]) wnlist = np.array( [1j * (2. * n + 1.) * np.pi / test[0] for n in range(len(test) - 2)]) test2 = np.array([ 70., 3.05, -0.74226073, -1.84369238, -2.3795746, -2.53100616, -2.489231, -2.36816348 ]) wnlist2 = np.array( [1j * (2. * n + 1.) * np.pi / test2[0] for n in range(len(test) - 2)]) res = np.polyfit(wnlist, 1j * test[2:], 4).imag res2 = np.polyfit(wnlist2, 1j * test2[2:], 4).imag res = np.poly1d(res) res2 = np.poly1d(res2) resd = np.polyder(res) res2d = np.polyder(res2) x = np.linspace(0., 0.1, 100) plt.figure() plt.title(r"$\beta = $" + str(test[0])) plt.plot(x, res(x), label="U=2.05") plt.plot(x, res2(x), label="U=3.05") plt.xlabel(r"$\omega$") plt.ylabel(r"$Im[\Sigma(\omega)]$") plt.legend() plt.figure() plt.title(r"$\beta = $" + str(test[0])) plt.plot(x, resd(x), label="U=2.05") plt.plot(x, res2d(x), label="U=3.05") plt.xlabel(r"$\omega$") plt.ylabel(r"$\frac{\partial\, Im[\Sigma(\omega)]}{\partial \omega}$")
def residuez(b, a, tol=1e-3, rtype='avg'): """Compute partial-fraction expansion of b(z) / a(z). If ``M = len(b)`` and ``N = len(a)``:: b(z) b[0] + b[1] z**(-1) + ... + b[M-1] z**(-M+1) H(z) = ------ = ---------------------------------------------- a(z) a[0] + a[1] z**(-1) + ... + a[N-1] z**(-N+1) r[0] r[-1] = --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ... (1-p[0]z**(-1)) (1-p[-1]z**(-1)) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like:: r[i] r[i+1] r[i+n-1] -------------- + ------------------ + ... + ------------------ (1-p[i]z**(-1)) (1-p[i]z**(-1))**2 (1-p[i]z**(-1))**n See also -------- invresz, poly, polyval, unique_roots """ b, a = map(asarray, (b, a)) gain = a[0] brev, arev = b[::-1], a[::-1] krev, brev = polydiv(brev, arev) if krev == []: k = [] else: k = krev[::-1] b = brev[::-1] p = roots(a) r = p * 0.0 pout, mult = unique_roots(p, tol=tol, rtype=rtype) p = [] for n in range(len(pout)): p.extend([pout[n]] * mult[n]) p = asarray(p) # Compute the residue from the general formula (for discrete-time) # the polynomial is in z**(-1) and the multiplication is by terms # like this (1-p[i] z**(-1))**mult[i]. After differentiation, # we must divide by (-p[i])**(m-k) as well as (m-k)! indx = 0 for n in range(len(pout)): bn = brev.copy() pn = [] for l in range(len(pout)): if l != n: pn.extend([pout[l]] * mult[l]) an = atleast_1d(poly(pn))[::-1] # bn(z) / an(z) is (1-po[n] z**(-1))**Nn * b(z) / a(z) where Nn is # multiplicity of pole at po[n] and b(z) and a(z) are polynomials. sig = mult[n] for m in range(sig, 0, -1): if sig > m: # compute next derivative of bn(s) / an(s) term1 = polymul(polyder(bn, 1), an) term2 = polymul(bn, polyder(an, 1)) bn = polysub(term1, term2) an = polymul(an, an) r[indx + m - 1] = (polyval(bn, 1.0 / pout[n]) / polyval(an, 1.0 / pout[n]) / factorial(sig - m) / (-pout[n])**(sig - m)) indx += sig return r / gain, p, k
def test_qmmm(): from math import cos, sin, pi import numpy as np # import matplotlib.pyplot as plt import ase.units as units from ase import Atoms from ase.calculators.tip3p import TIP3P, epsilon0, sigma0, rOH, angleHOH from ase.calculators.qmmm import (SimpleQMMM, EIQMMM, LJInteractions, LJInteractionsGeneral) from ase.constraints import FixInternals from ase.optimize import GPMin r = rOH a = angleHOH * pi / 180 # From https://doi.org/10.1063/1.445869 eexp = 6.50 * units.kcal / units.mol dexp = 2.74 aexp = 27 D = np.linspace(2.5, 3.5, 30) i = LJInteractions({('O', 'O'): (epsilon0, sigma0)}) # General LJ interaction object sigma_mm = np.array([0, 0, sigma0]) epsilon_mm = np.array([0, 0, epsilon0]) sigma_qm = np.array([0, 0, sigma0]) epsilon_qm = np.array([0, 0, epsilon0]) ig = LJInteractionsGeneral(sigma_qm, epsilon_qm, sigma_mm, epsilon_mm, 3) for calc in [ TIP3P(), SimpleQMMM([0, 1, 2], TIP3P(), TIP3P(), TIP3P()), SimpleQMMM([0, 1, 2], TIP3P(), TIP3P(), TIP3P(), vacuum=3.0), EIQMMM([0, 1, 2], TIP3P(), TIP3P(), i), EIQMMM([3, 4, 5], TIP3P(), TIP3P(), i, vacuum=3.0), EIQMMM([0, 1, 2], TIP3P(), TIP3P(), i, vacuum=3.0), EIQMMM([0, 1, 2], TIP3P(), TIP3P(), ig), EIQMMM([3, 4, 5], TIP3P(), TIP3P(), ig, vacuum=3.0), EIQMMM([0, 1, 2], TIP3P(), TIP3P(), ig, vacuum=3.0) ]: dimer = Atoms('H2OH2O', [(r * cos(a), 0, r * sin(a)), (r, 0, 0), (0, 0, 0), (r * cos(a / 2), r * sin(a / 2), 0), (r * cos(a / 2), -r * sin(a / 2), 0), (0, 0, 0)]) dimer.calc = calc E = [] F = [] for d in D: dimer.positions[3:, 0] += d - dimer.positions[5, 0] E.append(dimer.get_potential_energy()) F.append(dimer.get_forces()) F = np.array(F) # plt.plot(D, E) F1 = np.polyval(np.polyder(np.polyfit(D, E, 7)), D) F2 = F[:, :3, 0].sum(1) error = abs(F1 - F2).max() assert error < 0.01 dimer.constraints = FixInternals(bonds=[(r, (0, 2)), (r, (1, 2)), (r, (3, 5)), (r, (4, 5))], angles=[(a, (0, 2, 1)), (a, (3, 5, 4))]) opt = GPMin(dimer, trajectory=calc.name + '.traj', logfile=calc.name + 'd.log') opt.run(0.01) e0 = dimer.get_potential_energy() d0 = dimer.get_distance(2, 5) R = dimer.positions v1 = R[1] - R[5] v2 = R[5] - (R[3] + R[4]) / 2 a0 = np.arccos( np.dot(v1, v2) / (np.dot(v1, v1) * np.dot(v2, v2))**0.5) / np.pi * 180 fmt = '{0:>20}: {1:.3f} {2:.3f} {3:.3f} {4:.1f}' print(fmt.format(calc.name, -min(E), -e0, d0, a0)) assert abs(e0 + eexp) < 0.002 assert abs(d0 - dexp) < 0.01 assert abs(a0 - aexp) < 4 print(fmt.format('reference', 9.999, eexp, dexp, aexp))
def update_line_chart(ticker, degree): good_data = results[ticker] try: good_data['time'] = good_data.index start = good_data['time'][0] time = np.array([ pd.Timedelta(x - start).total_seconds() for x in good_data['time'] ]) fig1 = px.scatter(good_data, x='time', y='Open', template='simple_white', title='Time Series') fig1.update_traces(marker={'size': 4}) bt = Backtest(results[ticker], SmaCross, cash=10_000, commission=.002) stats = bt.optimize(n1=range(5, 50, 5), n2=range(10, 200, 5), maximize='Equity Final [$]', constraint=lambda param: param.n1 < param.n2) eq_curve = stats._equity_curve eq_curve['time'] = eq_curve.index fig5 = px.line(eq_curve, x='time', y='Equity', template='simple_white') smac = str(stats._strategy) fig1.add_trace( Scatter(x=good_data['time'], y=SMA(good_data['Open'], stats._strategy.n1), name='Short MA')) fig1.add_trace( Scatter(x=good_data['time'], y=SMA(good_data['Open'], stats._strategy.n2), name='Long MA')) print( np.nan_to_num( np.array(SMA(good_data['Open'], stats._strategy.n1)))) coefs = np.polyfit( time, np.nan_to_num( np.array(SMA(good_data['Open'], stats._strategy.n1))), degree) print(coefs) print(np.polyval(time, coefs)) coef_df = pd.DataFrame.from_dict({ 'time': time, 'coeffs': np.polyval(coefs, time), 'original_t': good_data['time'] }) fig2 = px.line(coef_df, x='original_t', y='coeffs', template='simple_white', title='Polynomial Fit') der1 = np.polyder(coefs, 1) print('der1: ', der1) der1_df = pd.DataFrame.from_dict({ 'time': time, 'der1': np.polyval(der1, time), 'original_t': good_data['time'] }) fig3 = px.line(der1_df, x='original_t', y='der1', template='simple_white', title='First Derivative') der2 = np.polyder(coefs, 2) print('der2: ', der2) der2_df = pd.DataFrame.from_dict({ 'time': time, 'der2': np.polyval(der2, time), 'original_t': good_data['time'] }) fig4 = px.line(der2_df, x='original_t', y='der2', template='simple_white', title='Second Derivative') coefs = np.polyfit(time, np.array(good_data['Open']), degree) print('coefs: ', coefs) coef_df = pd.DataFrame.from_dict({ 'time': time, 'coeffs': np.polyval(coefs, time), 'original_t': good_data['time'] }) except exceptions.YahooFinanceError: fig1, fig2, fig3, fig4, fig5 = 'No Ticker Available' return fig1, fig2, fig3, fig4, fig5, coefs, smac
# </editor-fold> # <editor-fold desc="Read Satellite data from csv"> satellite_data = pd.read_csv("Satellite_Data.csv") # data of satellites names = satellite_data["Name"] azimuth = satellite_data["Azimuth"] altitude = satellite_data["Altitude"] longitude = satellite_data["Longitude"] # </editor-fold> # <editor-fold desc="Fitting and derivative polynomials"> coeffs = np.polyfit(azimuth, altitude, 2) poly_fit = np.poly1d(coeffs) poly_fit_deriv = np.polyder(poly_fit) a_max_azimuth = poly_fit_deriv.roots[0] a_max = poly_fit(a_max_azimuth) azimuth_fit_values = np.linspace( min(azimuth), max(azimuth), 200) # calculate 200 polyiaml values, so pictue looks smooth poly_fit_values = np.polyval(poly_fit, azimuth_fit_values) # </editor-fold> # <editor-fold desc="Plotting"> fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) ax.set_xlim(min(azimuth_fit_values) - 10, max(azimuth_fit_values) + 10)
from scipy.interpolate import lagrange import numpy as np x = [-2.2, -0.3, 0.8, 1.9] y = [-15.18, 10.962, 1.92, -2.04] poly = lagrange(x, y) polyder = np.polyder(poly) print("Wartość pochodnej w x = 0, to", polyder(0)) polyder2 = np.polyder(polyder) print("Wartość pochodnej w x = 0, to", polyder2(0))
def _interpolate_table(self, key, leap_second_correction=False, derivative_order=0): """Interpolate daily values to the given time epochs Uses Lagrange interpolation with the given interpolation window. We have observed that the Lagrange interpolation introduces instabilities when the EOP data are constant (as for instance in the VASCC-data). In this case, we force the Lagrange polynomial to be constant. Args: key (String): Name of data to be interpolated, key in `self.data`. leap_second_correction (Bool): Whether data should be corrected for leap seconds before interpolation. Returns: Array: Interpolated values, one value for each time epoch. """ days = np.unique(self.time.utc.mjd_int) offsets = range(int(-np.ceil(self.window / 2) + 1), int(np.floor(self.window / 2) + 1)) if leap_second_correction: leap = { d: np.array([ self.data[d + o].get("leap_offset", np.nan) - self.data[d]["leap_offset"] for o in offsets ]) for d in days } for lo in leap.values(): lo[np.isnan(lo)] = 0 else: leap = {d: 0 for d in days} table_values = { d: np.array([self.data[d + o][key] for o in offsets]) + leap[d] for d in days } interpolators = { d: interpolate.lagrange(offsets, v) for d, v in table_values.items() } for poly in interpolators.values(): poly.c[ np.abs(poly.c) < 1e-15] = 0 # Avoid numerical instabilities for constant values if derivative_order: interp_values = { d: np.polyder(ip, derivative_order)(self.time.utc.mjd_frac) for d, ip in interpolators.items() } else: interp_values = { d: ip(self.time.utc.mjd_frac) for d, ip in interpolators.items() } if self.time.size == 1: return interp_values[self.time.utc.mjd_int] values = np.empty(self.time.size) for day in days: idx = self.time.utc.mjd_int == day values[idx] = interp_values[day][idx] return values
#!/usr/bin/env python3 import matplotlib.pyplot as plt # for show figure import scipy.linalg as sl # for linear alogorithm import numpy as np # for scipy a = np.linspace(0, 10, 20) print(a[0:10]) b = [5, 3, 2, 1] print(np.polyder(b))
def compute_eos_fit(self): """Performs the least-squares curve fitting for the chosen EOS function. Ground state quantities are returned. """ if self.eos_string == 'sjeos': self.eos_parameters = np.polyfit(self.v**-(1.0 / 3), self.e, 3) self.e += self.eMin fit0 = np.poly1d(self.eos_parameters) fit1 = np.polyder(fit0, 1) fit2 = np.polyder(fit1, 1) self.v0 = None for t in np.roots(fit1): if isinstance(t, float) and t > 0 and fit2(t) > 0: self.v0 = t**-3 break if self.v0 is None: raise ValueError('SJEOS: No minimum!') self.sws0 = self.vol2wsrad(self.v0) / self.bohr2a self.e0 = fit0(t) + self.eMin self.B0 = t**5 * fit2(t) / 9.0 # Bmod pressure derivative and Gruneisen parameter self.B1 = (108*self.eos_parameters[0]/self.v0 + 50*self.eos_parameters[1]/ self.v0**(2.0/3.0) + 16*self.eos_parameters[2]/self.v0**(1.0/3.0))/\ (27*self.B0*self.v0) #self.grun = -0.5 + self.B1/2 self.grun = -self.grun_g_factor + 0.5 * (1 + self.B1) # Convert B to GPa self.B0 *= self.ry2ev * self.ev2gpa else: if self.eos_string == 'morse': self.eos_parameters, pcov, self.fit_infodict, mesg, ier = curve_fit( eval('self.{0}'.format(self.eos_string)), self.sws, self.e, self.initial_guess) else: self.eos_parameters, pcov, self.fit_infodict, mesg, ier = curve_fit( eval('self.{0}'.format(self.eos_string)), self.v, self.e, self.initial_guess) if self.eos_string == 'morse': ma, mb, mc, ml = self.eos_parameters #print('a,b,c,lambda = ',ma,mb,mc,ml) self.e += self.eMin mx0 = -0.5 * mb / mc self.sws0 = -np.log(mx0) / ml self.v0 = self.wsrad2vol(self.bohr2a * self.sws0) self.e0 = ma + mb * mx0 + mc * mx0**2 + self.eMin self.B0 = -(mc * mx0**2 * ml**3) / (6 * np.pi * np.log(mx0)) # Convert B to GPa self.B0 = self.ev2gpa * self.ry2ev / self.bohr2a**3 * self.B0 #self.grun = 0.5 * ml * self.sws0 # Pressure derivative of bmod #self.B1 = 2*self.grun + 1.0 self.B1 = 1 - np.log(mx0) self.grun = -self.grun_g_factor + 0.5 * (1 + self.B1) elif self.eos_string == 'oldpoly': c0, c1, c2, c3 = self.eos_parameters # find minimum E in E = c0 + c1*V + c2*V**2 + c3*V**3 # dE/dV = c1+ 2*c2*V + 3*c3*V**2 = 0 # solve by quadratic formula with the positive root a = 3 * c3 b = 2 * c2 c = c1 self.sws0 = (-b + np.sqrt(b**2 - 4 * a * c)) / (2 * a) self.v0 = wsrad2vol(self.bohr2a * self.sws0) self.e0 = self.oldpoly(self.v0, c0, c1, c2, c3) self.B0 = (2 * c2 + 6 * c3 * self.v0) * self.v0 # Convert B to GPa self.B0 *= self.ry2ev * self.ev2gpa # Gruneisen parameter for oldpoly not implemented self.grun = 0.0 else: self.e0 = self.eos_parameters[0] self.v0 = self.eos_parameters[3] self.sws0 = self.vol2wsrad(self.v0) / self.bohr2a self.B0 = self.eos_parameters[1] self.B1 = self.eos_parameters[2] #self.grun = -0.5 + self.B1 / 2.0 self.grun = -self.grun_g_factor + 0.5 * (1 + self.B1) # Convert B to GPa self.B0 *= self.ry2ev * self.ev2gpa return
def poly_fit(x, y, deg=5): ''' Return the local extreme of the polynomial function fitting to data series (x, y) >>> x = np.linspace(0, 2.0 * np.pi, 10) >>> y = np.sin(x) >>> xm, ym = poly_fit(x, y) Polynomial fitting: local minimum is -1.0046 at x = 4.7241 local maximum is 1.0046 at x = 1.5591 ''' # First fit the data series to a polynomial function coef1 = np.polyfit(x, y, deg) # Get the first derivative of the fitted function pcoef1 = np.polyder(coef1, 1) # Get the second derivative pcoef2 = np.polyder(coef1, 2) # Find the roots for the equation of first derivative proots = np.roots(pcoef1) # Arrays to store local extrema xm = np.empty(0) ym = np.empty(0) # Number of found local extrema count = 0 print "Polynomial fitting: " # Check we get the real root in the inverval for xr in proots: # Calculate the value of second derivative for each root der2 = np.polyval(pcoef2, xr) # Ensure it's real number and locates in the interval if xr.imag == 0 and xr >= x[0] and xr <= x[-1]: xm = np.append(xm, xr.real) ym = np.append(ym, float(np.polyval(coef1, xm[count]))) # Local maximum if 2nd derivative is negative if der2 < 0: print "local maximum is %6.4f at x = %6.4f" % (ym[count], xm[count]) # Local minimum if 2nd derivative is positive elif der2 > 0: print "local minimum is %6.4f at x = %6.4f" % (ym[count], xm[count]) count += 1 # Exit if no local extreme found if not count: print " No local minimum/maximum found in [%6.4f, %6.4f]" % (x[0], x[-1]) print " Choose another interval space." exit() # Generate data set of fitted function xx = np.linspace(x[0], x[-1], 50) yy = np.polyval(coef1, xx) if PLOT: # Plot original and fitted function data plt.plot(x, y, 'gs-', xx, yy, 'b--', linewidth=2) # Plot the local maximum/minimum # plt.plot(xm[:count], ym[:count], 'ro', ms = 6) plt.plot(xm, ym, 'ro', ms=6) plt.show() return xm, ym
def birdcounts_derivative(coeff_mat, time): q = numpy.polyval(coeff_mat.T, time) p = numpy.exp(q) der = numpy.array([numpy.polyder(x) for x in coeff_mat]) der = numpy.polyval(der.T, time) return (der * p)