def main(): fs = 500.0 # Sampling Frequency (Hz) Ts = 1/fs # Sample time, period # Compute the time vector t = np.arange(0.0, 3.0, Ts, dtype=float) scr = screen.Screen(weight=111000.00, momentInertia=0.0) cw1 = screen.CounterWeight(posX=0.0,posY=0.0, radius=0.5, weight=300.0, rpm=800.0, startAngle=270.0, counterclockwise=False) cw2 = screen.CounterWeight(posX=0.0,posY=0.0, radius=0.5, weight=300.0, rpm=800.0, startAngle=270.0, counterclockwise=False) scr.addCounterWeight(cw1) scr.addCounterWeight(cw2) ax, ay = scr.calculate_acceleration(t) x, _, freq_x, ffta_x = integrate(ax, Ts) y, _, freq_y, ffta_y = integrate(ay, Ts) # Convert the motion of x and y into polar coords r = np.sqrt((x*x)+(y*y)) theta = np.arctan2(y, x) plt.subplot(311) plt.plot(t, ax) plt.grid() plt.xlabel("time (t)") plt.ylabel("Accel (ft/s/s)") plt.subplot(312, polar=True) plt.plot(theta, r, '--r') plt.title("CG Movement Profile") plt.subplot(313) plt.plot(freq_x, np.abs(ffta_x), 'r') plt.grid() plt.xlabel("Frequency (Hz)") plt.ylabel("Amplitude") plt.show()
def tbfunc(tb, extra, verbose=None): import numpy as np import integrate arat = extra[0] frat = extra[1] freq = extra[2] trans = extra[3] istar = extra[4] c = 2.99792458e8 # m/s, speed of light h = 6.6260693e-34 # J s, Planck's constant, Wikipedia k = 1.3806503e-23 # J/K, Boltzmann's constant, Google if (verbose is not None): print tb ntb = np.array(tb).size if ntb == 1: ret = c**2 * frat / (2.*h*arat) * integrate.integrate(freq, trans * istar) - \ integrate.integrate(freq, trans*freq**3 / (np.exp(h*freq/(k*tb)) - 1.)) else: ret = np.zeros(ntb) for i in range(ntb): ret[i] = c**2 * frat / (2.*h*arat) * integrate.integrate(freq, trans * istar) - \ integrate.integrate(freq, trans*freq**3 / (np.exp(h*freq/(k*tb[i])) - 1.)) if (verbose is not None): print ret return ret
def process_data(keys): for key in keys: r = data_ingest_table.query( KeyConditionExpression=Key('address').eq(str(key[0])) & Key('inserted_at').eq(key[1]) ) integrate(r[u'Items'][0], key[0]) ratings = update_ratings() return
def transplan_tb(arat, frat, logg, tstar, kfreq=None, kgrav=None, ktemp=None, kinten=None, ffreq=None, ftrans=None, fmfreq=None, fstar=None, fmstar=None, guess=None, gmult=None, itmax=None, stop=None, tol=None, verbose=None, status=None): import numpy as np import transplan_tb import kurucz_inten import integrate # unpack arat if array if np.array(arat).size == 4: iarat = arat[0] frat = arat[1] logg = arat[2] tstar = arat[3] else: iarat = arat status = 1 # guess always succeeds # default guess array if gmult == None: gmult = np.array([1.0, 0.6, 1.6]) # constants, MKS c = 2.99792458e8 # m/s, speed of light h = 6.6260693e-34 # J s, Planck's constant, Wikipedia k = 1.3806503e-23 # J/K, Boltzmann's constant, Google # find fstar if fstar == None: kstar = kurucz_inten.interp(kinten, kgrav, ktemp, logg, tstar) fstar = np.interp(ffreq, kfreq, kstar) # calculate filter mean and brightness there if fmfreq == None: fmfreq = (integrate.integrate(ffreq, ffreq*ftrans, min(ffreq), max(ffreq)) / integrate.integrate(ffreq, ftrans, min(ffreq), max(ffreq))) if fmstar == None: fmstar = np.interp([fmfreq], ffreq, fstar) # guess Tb at the weighted band center tbg = (h*fmfreq)/k/np.log((2.*h*iarat*fmfreq**3)/(c**2*frat*fmstar) + 1.) if (guess is not None): return -1, tbg[0], fmfreq, fmstar # fx_root parameters guess3 = tbg * gmult func = tbfunc extra = [iarat, frat, ffreq, ftrans, fstar] #Convert line below tb = transplan_tb.root(guess3, func, extra=extra) return tb, tbg, fmfreq, fmstar #, fmfreq, fstar, fmstar
def test_integrate_logistic_adaptive(self): r = 1.0 k = 1.0 def rhs(t, u): return r * u * (1 - u / k) def jac(t, u, x): return r * (1 - 2 * u / k) * x u0 = 0.1 t = np.linspace(0, 1, 100) y = integrate(rhs, t, u0) y_exp = y + np.random.normal(scale=0.05, size=y.shape) def functional(y): return np.sum((y - y_exp)**2) def dfunc_dy(y): return 2 * (y - y_exp) y = integrate_adaptive(rhs, jac, dfunc_dy, t, u0, tol=1e-6) analytic = k / (1 + (k / u0 - 1) * np.exp(-r * t))\ .reshape(-1, 1) np.testing.assert_allclose(functional(analytic), functional(y), rtol=1e-6, atol=0)
def test_interpolate(self): r = 1.0 k = 1.0 def rhs(t, u): return r * u * (1 - u / k) u0 = 0.1 t = np.linspace(0, 1, 100) y = integrate(rhs, t, u0) interp_t = np.linspace(0, 1, 33) interp_y = interpolate(y, t, rhs, interp_t) analytic = k / (1 + (k / u0 - 1) * np.exp(-r * interp_t))\ .reshape(-1, 1) np.testing.assert_allclose(analytic, interp_y, rtol=1e-5, atol=0) interp_t = np.linspace(0, 1, 133) interp_y = interpolate(y, t, rhs, interp_t) analytic = k / (1 + (k / u0 - 1) * np.exp(-r * interp_t))\ .reshape(-1, 1) np.testing.assert_allclose(analytic, interp_y, rtol=1e-5, atol=0)
def test_rand(self): from random import randint for i in range(50): rand_co = randint(1, 100) rand_ex = randint(3, 100) self.assertEqual(integrate(rand_co * rand_ex, rand_ex - 1), "{}x^{}".format(rand_co, rand_ex))
def run(self): global args, events, hist p = Parse(args.infile, ('chan','raw') ) data = None while True: if self._abort_flag: print("Worker aborted") return if self._pause_flag: time.sleep(0.1) continue try: data = p.next() except StopIteration: time.sleep(1) continue if self._notify_window.ready: self._notify_window.ready = False wx.PostEvent(self._notify_window, DataReadyEvent(data)) events.append(data) #TODO: if hist: e_ts, e_chan, e_summ, e_baseline, e_dbaseline = integrate(data)[0:5] hist.append(e_summ)
def run(self): global args, events, hist p = Parse(args.infile) data = None while True: if self._abort_flag: print("Worker aborted") return if self._pause_flag: time.sleep(0.1) continue try: data = p.next() except StopIteration: time.sleep(0.5) continue vals = integrate(data) e_summ, e_baseline = vals.summ, vals.bl if self._notify_window.ready: self._notify_window.ready = False wx.PostEvent(self._notify_window, DataReadyEvent(data)) sys.stderr.write("progress: %2.3f%%\n" % (100.0 * p.progress())) events.append(data) #TODO: if hist: hist.append(e_summ)
def test_integrate(self): def rhs(t, y): return -y times = np.linspace(0.0, 1.0, 100) for method in [runge_kutta4, runge_kutta41, runge_kutta5]: y = integrate(rhs, times, 1.0, method=method) analytic = np.exp(-times).reshape(-1, 1) np.testing.assert_allclose(analytic, y, rtol=1e-5, atol=0)
def test_integrate2d(self): def rhs(t, y): return -y times = np.linspace(0.0, 1.0, 100) y0 = np.array([1.0, 2.0]) for method in [runge_kutta4, runge_kutta41, runge_kutta5]: y = integrate(rhs, times, y0, method=method) analytic = np.stack((np.exp(-times), 2 * np.exp(-times)), axis=1) np.testing.assert_allclose(analytic, y, rtol=1e-5, atol=0)
def test_integrate(self): metadata = { 'exposure_time': 0.05000000074505806, 'oscillation': (0.0, 0.20000000298023224), 'wavelength': 0.9201257824897766, 'matching': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50 ], 'size': (3269, 3110), 'detector_class': 'eiger 9M', 'end': 50, 'start': 1, 'template': 'CataApo05_1444_??????.h5', 'serial_number': 0, 'detector': 'EIGER_9M', 'sensor': 0.44999999227002263, 'pixel': (0.07500000356230885, 0.07500000356230885), 'phi_start': 0.0, 'saturation': 92461.0, 'beam': (120.55726144764847, 119.44351135718689), 'phi_end': 0.20000000298023224, 'distance': 200.04000666485112, 'oscillation_axis': 'Omega_I_guess', 'phi_width': 0.20000000298023224, 'extra_text': 'LIB=/usr/local/crys-local/ccp4-7.0/bin/eiger2cbf.so\n\nLIB=/usr/local/crys-local/XDS_2Sep17/dectris-neggia.so\n', 'directory': '/mnt/optane/hbernstein/CollinsLaccases/data/CataApo05/5/NSLS2-18_10' } p1_unit_cell = (199.7, 200.9, 202.5, 108.0, 109.9, 109.6) resolution_low = 30.0 n_jobs = 1 n_processors = 0 self.assertEqual( integrate(metadata, p1_unit_cell, resolution_low, n_jobs, n_processors), (0.224, 0.224, 0.224))
def test_integrate_logistic(self): r = 1.0 k = 1.0 def rhs(t, u): return r * u * (1 - u / k) u0 = 0.1 t = np.linspace(0, 1, 100) y = integrate(rhs, t, u0) analytic = k / (1 + (k / u0 - 1) * np.exp(-r * t))\ .reshape(-1, 1) np.testing.assert_allclose(analytic, y, rtol=1e-5, atol=0)
def matrixEntries(s): a1,a2,b1,b2 = s fk2 = lambda x,y: ( space_proj.derivative(a1+(a2-a1)*x) * space_proj.derivative(b1+(b2-b1)*y) )*(a2-a1)*(b2-b1) # Pick integrations routine(s) if flag == 'singleLayer': def f(x, y): xhat = space_proj(a1 + (a2 - a1) * x) yhat = space_proj(b1 + (b2 - b1) * y) return fk2(x,y)*timeQuad(xhat - yhat, endT, basis, **kwargs).reshape(-1,1) elif flag == 'doubleLayer': def f(x, y): xhat = space_proj(a1 + (a2 - a1) * x) yhat = space_proj(b1 + (b2 - b1) * y) return fk2(x, y) * dot_prod(space_proj.normal(yhat), xhat - yhat) * timeQuadN(xhat - yhat, endT, basis, **kwargs).reshape(-1, 1) else: raise "unknown flag" if a2 < b1 or b2 < a1: return integrate(f,[], n = numx, flag = 'SingNone') if a1 == b1: return integrate(f, [], n = numx, flag = 'SingDiag') elif a1 == b2: return integrate(f, [], n = numx, flag = 'SingLeftupper') else: # Last case is a2 == b1: return integrate(f, [], n = numx+3, flag = 'SingRightbottom')
def assembleVector(g, basis, space_proj, time_proj): Nx = basis.nx Nt = basis.nt numx = 25 B = array(zeros(Nt*Nx)) for l in range(Nt): intervals2 = basis.baseT[l].support for alpha in range(basis.nx): intervals1 = basis.baseX[alpha].support for s1 in intervals1: for s2 in intervals2: f = vectorEntries(basis.baseX[alpha],s1, basis.baseT[l],s2, g, space_proj, time_proj) from projection import interval B[l*Nx+alpha] += integrate(f, interval(0,1), interval(0,1), n=numx) return B
def normalize(dx, n, f): """ given sample separation dx (array-like), sample number (array-like), and function f (array-like), normalizes the function f """ # make copy of the dimension of the system m = copy.copy(n) # append -1 so that the dimension of g is inferred in the last dimension np.append(m, -1) # calculate PDF and reshape to integrate along distinct dimensions g = np.reshape(np.multiply(np.conj(f), f), m) # integrate over PDF g = integrate(dx, g, np.arange(0, len(n), 1)) # cases to habdle the possible types of the integration constant if type(g) == np.ndarray: f = f / np.sqrt(g[0]) else: f = f / np.sqrt(g) # return normalized function return f
def on_integrate(self): page = self.book.active_page if not isinstance(page, GraphView): return sys.path.append(os.path.join(DATADIR, 'data', 'scripts')) from integrate import integrate for dataset in page.graph.selected_datasets: w = dataset.worksheet ind = dataset.active_data() x = dataset.x[ind] y = dataset.y[ind] res = integrate(x, y) xname = 'int_%s_%s_x' % (dataset.x.name, dataset.y.name) yname = 'int_%s_%s_y' % (dataset.x.name, dataset.y.name) w[xname], w[yname] = x, res page.graph.add(w[xname], w[yname])
def test_adjoint_error(self): r = 1.0 k = 1.0 def rhs(t, u): return r * u * (1 - u / k) def jac(t, u, x): return r * (1 - 2 * u / k) * x def drhs_dp(t, u, x): return np.array([ u * (1 - u / k), r * u**2 / k**2, ]).dot(x) u0 = 0.1 t = np.linspace(0, 10.0, 20) y = integrate(rhs, t, u0) np.random.seed(0) for ntimes in [13, 23]: ft = np.linspace(0, 10.0, ntimes) fy = interpolate(y, t, rhs, ft) analytic = k / (1 + (k / u0 - 1) * np.exp(-r * ft))\ .reshape(-1, 1) y_exp = fy + np.random.normal(scale=0.05, size=fy.shape) def functional(y): return np.sum((y - y_exp)**2) def dfunc_dy(y): return 2 * (y - y_exp) error, errors, f, _, _ = adjoint_error(rhs, jac, functional, dfunc_dy, ft, t, y) np.testing.assert_allclose(f - functional(analytic), error, rtol=7e-2, atol=1e-8)
def BilinearformM(bi,bj, px,pt): bXalpha, bTm = bi bXbeta, bTn = bj support1 = bXalpha.support support2 = bXbeta.support supportT1 = bTm.support supportT2 = bTn.support m = 0 for s1 in support1: for s2 in support2: for sT1 in supportT1: for sT2 in supportT2: assert s1.intersect(s2) == s2.intersect(s1) assert sT1.intersect(sT2) == sT2.intersect(sT1) intersection = s1.intersect(s2) intersectionT = sT1.intersect(sT2) if(intersection and intersection.length and intersectionT and intersectionT.length): bi = lambda x,t: bXalpha(x) * bTm(t) bj = lambda x,t: bXbeta(x) * bTn(t) m += integrate(lambda x,t: bi(x,t)*bj(x,t) *px.derivative(x)*pt.derivative(t), intersection,intersectionT, n = 13) return m
def start(): res = requests.post(URL + START, json={'key': KEY, 'type': "N"}) print('start', res.status_code) url = res.json()['url'] while True: print(url) answer = integrate(url) print(answer) res = requests.post(URL + SUBMIT, json={'key': KEY, 'answer': answer}) left = res.json()[u'left'] url = res.json()[u'url'] if left <= 1: requests.post(URL + SUBMIT, json={'key': KEY, 'answer': answer}) break if left % 100 == 0: print(left) res = requests.get(URL + STATUS, {'key': KEY}) print('status', res.status_code) print(res.text)
def DrawWaveform(self, ax, event_data): """ Plot waveforms.""" data = event_data.raw backlog = 8 if len(self.graphs) > backlog: self.graphs.pop(0).remove() if data: ydata = [d for d in data] xdata = range(0, len(data)) #~ self.graph.set_xdata(xdata) #~ self.graph.set_ydata(data) self.graphs.append(self.axes.plot(xdata, ydata, '-g')[0]) current_limits = ax.get_ylim() self.vline.set_xdata((args.baseline, ) * 2) # (x,x) self.vline.set_ydata(current_limits) if self.f_autoscale: baseline_position = 0.3 vals = integrate(event_data) e_summ, e_baseline = vals.summ, vals.bl new_limits = self.autoscale_baseline(current_limits, max(data), min(data), e_baseline, baseline_position) ax.set_ylim(new_limits) ax.set_xlim(0, len(data)) #Fade effect for i, g in enumerate(self.graphs): g.set_alpha(float(i) / backlog) self.canvas.draw()
def remesh(meshfile, omeshfile, keep_normals=False): # Load pre-defined normals from a CSV (exported from MATLAB). # Use psereo.get_normals(images, lights) to obtain normals using photometric # stereo. (vertices, normals, indices) = plyutils.readPLY(meshfile) old_normals = np.array(normals) print("OLD: ", old_normals[0, :]) print(normals.shape) w = int(math.sqrt(normals.shape[0])) h = w normals = normals.reshape((w,h,3)) #normals[:, :, 2] = -normals[:, :, 2] # Integrate normals into a heightfield. zfield = integrate.integrate(normals, 0.0) # Some stats. print("zmax: ", np.max(zfield)) print("zmin: ", np.min(zfield)) # Create a mesh from the heightfield. mesh = z2mesh.z2mesh(zfield, -1.0, 1.0, -1.0, 1.0) # Expand mesh components. new_vertices, new_normals, new_indices = mesh new_vertices[:, 2] = -new_vertices[:, 2] if keep_normals: #old_normals[:, :, 2] = -old_normals[:, :, 2] #old_normals[:, 2] = -old_normals[:, 2] new_normals = old_normals print("NEW: ", new_normals[0, :]) # Write the mesh to mesh file. plyutils.writePLY(omeshfile, new_vertices, new_normals, new_indices)
def DrawWaveform(self, ax, event_data): """ Plot waveforms.""" data = event_data.raw backlog = 8 if len(self.graphs) > backlog: self.graphs.pop(0).remove() if data: ydata = [d for d in data] xdata = range(0,len(data)) #~ self.graph.set_xdata(xdata) #~ self.graph.set_ydata(data) self.graphs.append( self.axes.plot(xdata,ydata, '-g')[0] ) current_limits = ax.get_ylim() self.vline.set_xdata( (args.baseline,) * 2) # (x,x) self.vline.set_ydata(current_limits) if self.f_autoscale: baseline_position = 0.3 e_ts, e_chan, e_summ, e_baseline, e_dbaseline = integrate(event_data)[0:5] new_limits = self.autoscale_baseline(current_limits, max(data), min(data), e_baseline, baseline_position) ax.set_ylim( new_limits) ax.set_xlim(0,len(data)) #Fade effect for i,g in enumerate(self.graphs): g.set_alpha(float(i)/backlog) self.canvas.draw()
#!/usr/bin/env python import read_file import parse_prop import get_snpcount import add_seq import append import integrate import add_to_db import run_struct import get_sites file = integrate.integrate() df = read_file.read_file(file) new_df = parse_prop.parse_prop(df) #kage = get_snpcount.enough_info(file) str = append.append(new_df) sites, indices = get_sites.get_sites(new_df) #add_to_db.add_to_base(kage,df) run_struct.call_structure(sites, indices)
allsigmas=np.zeros((3,len(kbar))) allkappas=np.zeros(len(kbar)) print kbar for n in range(len(kbar)): kappa,sigma = calculate_sigmas(kbar[n]) allsigmas[:,n] = sigma allkappas[n] = kappa print print "Cutoff at k=",kbar[n] for samp in tqdm(range(nsamples)): ret = integrate.integrate(nu[samp],sigma[0],sigma[1],kappa,npoints,ordered=True,test=False) means[samp][n]=ret[0] sdevs[samp][n]=ret[1] pct_sdevs[samp][n] = abs(100.0*(sdevs[samp][n])/means[samp][n]) """ Format an output table for spot-checking! """ for n in range(len(kbar)): print print "Cutoff at k=",kbar[n] t = PrettyTable(['Nu','Means','Sdev','PctSdev'])
def getlimbparam(kuruczfile, chan, Nparam=4, lamfact=1000., spit=None, returnmu=False): """ Reads in Kurucz grid data and Spitzer specral responses to return four parameters for a non-linear limb darkening model. This function requires a Kurucz grid of flux responses for a star over effective temperature, specific gravity, metalicity and angle. The return parameters are to fit the following model, I(mu) / I(1) = 1 - a1(1 - mu^0.5) - a2(1 - mu) - a3(1 - mu^1.5) - a4(1 - mu^2) where mu is cos(angle) from star's center, I(mu) is flux/intensity given angle, and a# are the four parameters. Paramaters ---------- kuruczfile : str String giving the location of the Kurucz grid (Only for the target star's TEFF, log(g), M/H (or Fe/H)) ex: kuruczfile = "/home/esp01/ancil/limbdarkening/WASP-11" chan : int The Spitzer channel to be used for model fitting ex: chan = 1 Returns ------- coeff : 1D array Contains four parameters for the non-linear limb darkening model as follows: I(mu) / I(1) = 1 - a1(1 - mu^[1/2]) - a2(1 - mu) - a3(1 - mu^[3/2]) - a4(1 - mu^2) coeff array is in format array([ a1, a2, a3, a4]) Examples -------- >>> from getlimbparam import getlimbparam >>> kuruczfile = "/home/esp01/ancil/limbdarkening/WASP-11" >>> chan = 2 >>> paramschan2 = getlimbparam(kuruczfile, chan) >>> print(paramschan2) [ 0.64940497 -0.85966835 0.85679169 -0.31649174] >>> chan = 3 >>> paramschan3 = getlimbparam(kuruczfile, chan) >>> print(paramschan3) [ 0.60509989 -0.86795052 0.86195088 -0.31567865] Revisions --------- 2011-02-22 0.0 [email protected] Inital version. 2011-03-22 0.1 [email protected] Added documentation, cleaned up code style. 2011-05-11 0.2 [email protected] Further cleaned up style. """ # Define conversion factors kurconv = 100000. # Detect proper spitzer file if chan == 1: spitfile = "/home/kevin/Documents/esp01/ancil/filter/irac_tr1_2004-08-09.dat" elif chan == 2: spitfile = "/home/kevin/Documents/esp01/ancil/filter/irac_tr2_2004-08-09.dat" elif chan == 3: spitfile = "/home/kevin/Documents/esp01/ancil/filter/irac_tr3_2004-08-09.dat" elif chan == 4: spitfile = "/home/kevin/Documents/esp01/ancil/filter/irac_tr4_2004-08-09.dat" # Retrieve data from Kurucz grid and Spitzer spectral response table for # the appropriate channel # First column of kurucz is the wavelength kurucz = np.loadtxt(kuruczfile, skiprows=3, unpack=True) isfilter = False if spit == None: isfilter = True spit = np.loadtxt(spitfile, unpack=True) spit = spit[0:2] # Use second column for spectral response # Convert kurucz grid flux to standard units for i in range(np.shape(kurucz)[1]): for j in range(np.shape(kurucz)[0] - 2): kurucz[j + 2, i] *= kurucz[1, i] / kurconv # Find where kurucz is approx. equal to spit's min and max lowspit = spit[0].min() * lamfact highspit = spit[0].max() * lamfact #lowspitin = np.where(spit[0] == spit[0].min())[0] #highspitin = np.where(spit[0] == spit[0].max())[0] lowkur = np.abs(kurucz[0] - lowspit).argmin() highkur = np.abs(kurucz[0] - highspit).argmin() # Cut kurucz grid to match wavelength range with spitzer kurucznew = kurucz[:, lowkur:highkur] kurucznew[0] /= lamfact # Spline for spitzer data fit at exact kurucz wavelengths points = np.size(kurucznew[0]) spitfit = np.zeros((2, points)) spitfit[0] = kurucznew[0] for i in range(points): tck = intr.splrep(spit[0], spit[1]) spitfit[1, i] = intr.splev(spitfit[0, i], tck) # Make array for angle vs flux angvflux = np.zeros((2, kurucznew.shape[0] - 1)) angvflux[0] = np.loadtxt(kuruczfile, skiprows=2, usecols=range(0, 17))[0] # Integrate spitzer / kurucz data over wavelength intbottom = integrate(spitfit[0], spitfit[1]) #print("Assuming kurucznew is actual spectrum (not filter) that needs to be normalized. See Line 130.") for i in range(kurucznew.shape[0] - 1): if isfilter == True: #Use filter inttop = integrate(spitfit[0], spitfit[1] * kurucznew[i + 1]) else: #Use actual spectrum inttop = integrate(spitfit[0], spitfit[1] * kurucznew[i + 1] / kurucznew[0]) #inttop = integrate(kurucznew[0] * spitfit[0], spitfit[1] * kurucznew[i + 1]) angvflux[1, i] = inttop / intbottom # I(mu) / I(1) = 1 - a1(1 - mu^[1/2]) - a2(1 - mu) # - a3(1 - mu^[3/2]) - a4(1 - mu^2) # Therefore: # 1 - I(mu) / I(1) = a1(1 - mu^[1/2]) + a2(1 - mu) # + a3(1 - mu^[3/2]) + a4(1 - mu^2) # Use least sqaures to find parameters (a1, etc.) for best # model fit using the above equation #mu = angvflux[0] #y = 1. - angvflux[1] / angvflux[1,0] #Trim mu < 0.1 imu = np.where(angvflux[0] >= 0.1)[0] mu = angvflux[0, imu] y = 1. - angvflux[1, imu] / angvflux[1, 0] A = np.zeros((len(mu), Nparam)) if Nparam == 4: A[:, 0] = (1 - mu**0.5) A[:, 1] = (1 - mu) A[:, 2] = (1 - mu**1.5) A[:, 3] = (1 - mu**2.) elif Nparam == 2: A[:, 0] = (1. - mu) A[:, 1] = (1. - mu)**2 elif Nparam == 1: A[:, 0] = (1. - mu) coeff = lstsq(A, y)[0] # If wanted, plot results using ''' plt.ion() plt.plot(angvflux[0], angvflux[1], '.') plt.plot(angvflux[0], (1 - coeff[0] * (1 - angvflux[0]**0.5) - coeff[1] \ * (1 - angvflux[0]) - coeff[2] * (1 - angvflux[0]**1.5) - coeff[3] \ * (1 - angvflux[0]**2.)) * angvflux[1,0]) plt.ylabel("Intensity in $ergs * cm^-2 * s^-1 * hz ^-1 * ster^-1$ ") plt.xlabel('cosine of Angle (center = 1)') plt.title('Angle vs Intensity') # ''' if returnmu: return (coeff, mu, 1 - y) else: return (coeff)
import numpy as np import integrate ## Now let's the interval over which we will integrate x1 = 0.0 x2 = 1.0 ## Define the width of each of the rectangles we use to determine the area. Remember ## that the smaller the width, the more accurate our solution will be -but the time ## to solution will increase. dx = 0.0000001 points = np.arange(x1 + dx, x2 + dx, dx) computed_soln = integrate.integrate(points, dx) print "Computed integral of f was " + str(computed_soln) ## Let's compare our computed solution to the analytical solution def g(x): y = 3.0 * x + 0.5 * x * x - x * x * x return y analytical_soln = g(x2) - g(x1) print "Analytical solution was " + str(analytical_soln)
#!/usr/bin/env python # from integrate import integrate_f_with_functional_tools as integrate_f from integrate import integrate, f a = 0.0 b = 10.0 for N in (10**i for i in xrange(1,6)): print "Numerical solution with N=%(N)d : %(x)f" % \ {'N': N, 'x': integrate(f, a, b, N)}
from integrate import integrate, f print integrate(f, 0.0,10.0,500000)
#!/usr/bin/env python # from integrate import integrate_f_with_functional_tools as integrate_f from integrate import integrate, f a = 0.0 b = 10.0 for N in (10**i for i in range(1, 8)): print("Numerical solution with N=%(N)d : %(x)f" % { 'N': N, 'x': integrate(f, a, b, N) })
def main(): # make environment pot_region = (2 / np.sqrt(3), 2 / np.sqrt(3), 2 / np.sqrt(3)) radius = np.sqrt(pot_region[0]**2 + pot_region[1]**2 + pot_region[2]**2) region = (radius, radius, radius) nr = 201 gridpx = 200 gridpy = 200 gridpz = 200 x, y, z = grid(gridpx, gridpy, gridpz, region) xx, yy, zz = np.meshgrid(x, y, z) #make mesh #linear mesh #r =np.linspace(0.0001,region,nr) #log mesh a = np.log(2) / (nr - 1) b = radius / (np.e**(a * (nr - 1)) - 1) rofi = np.array([b * (np.e**(a * i) - 1) for i in range(nr)]) # make potential V = makepotential(xx, yy, zz, pot_region, pottype="cubic", potbottom=-1, potshow_f=False) # surface integral V_radial = surfaceintegral(x, y, z, rofi, V, method="lebedev_py", potshow_f=False) vofi = np.array(V_radial) # select method of surface integral # make basis node_open = 1 node_close = 2 LMAX = 10 all_basis = [] for lvalsh in range(LMAX): l_basis = [] # for open channel val = 1. slo = 0. for node in range(node_open): basis = Basis(nr) emin = -10. emax = 100. basis.make_basis(a, b, emin, emax, lvalsh, node, nr, rofi, slo, vofi, val) l_basis.append(basis) # for close channel val = 0. slo = -1. for node in range(node_close): basis = Basis(nr) emin = -10. emax = 100. basis.make_basis(a, b, emin, emax, lvalsh, node, nr, rofi, slo, vofi, val) l_basis.append(basis) all_basis.append(l_basis) with open("wavefunc.dat", mode="w") as fw_w: fw_w.write("#r, l, node, open or close = ") for l_basis in all_basis: for nyu_basis in l_basis: fw_w.write(str(nyu_basis.l)) fw_w.write(str(nyu_basis.node)) if nyu_basis.open: fw_w.write("open") else: fw_w.write("close") fw_w.write(" ") fw_w.write("\n") for i in range(nr): fw_w.write("{:>13.8f}".format(rofi[i])) for l_basis in all_basis: for nyu_basis in l_basis: fw_w.write("{:>13.8f}".format(nyu_basis.g[i])) fw_w.write("\n") hsmat = np.zeros( (LMAX, LMAX, node_open + node_close, node_open + node_close), dtype=np.float64) lmat = np.zeros( (LMAX, LMAX, node_open + node_close, node_open + node_close), dtype=np.float64) qmat = np.zeros( (LMAX, LMAX, node_open + node_close, node_open + node_close), dtype=np.float64) for l1 in range(LMAX): for l2 in range(LMAX): if l1 != l2: continue for n1 in range(node_open + node_close): for n2 in range(node_open + node_close): if all_basis[l1][n1].l != l1 or all_basis[l2][n2].l != l2: print("error: L is differnt") sys.exit() hsmat[l1][l2][n1][n2] = integrate( all_basis[l1][n1].g[:nr] * all_basis[l2][n2].g[:nr], rofi, nr) * all_basis[l1][n1].e lmat[l1][l2][n1][ n2] = all_basis[l1][n1].val * all_basis[l2][n2].slo qmat[l1][l2][n1][ n2] = all_basis[l1][n1].val * all_basis[l2][n2].val print("\nhsmat") print(hsmat) print("\nlmat") print(lmat) print("\nqmat") print(qmat) #make not spherical potential my_radial_interfunc = interpolate.interp1d(rofi, V_radial) #V_ang = np.where(np.sqrt(xx * xx + yy * yy + zz * zz) < rofi[-1] , V - my_radial_interfunc(np.sqrt(xx * xx + yy * yy + zz * zz)),0. ) #my_V_ang_inter_func = RegularGridInterpolator((x, y, z), V_ang) my_V_inter_func = RegularGridInterpolator((x, y, z), V) #WARING!!!!!!!!!!!!!!!!!!!!!! """ Fujikata rewrote ~/.local/lib/python3.6/site-packages/scipy/interpolate/interpolate.py line 690~702 To avoid exit with error "A value in x_new is below the interpolation range." """ #!!!!!!!!!!!!!!!!!!!!!!!!!!! #mayavi.mlab.plot3d(xx,yy,V_ang) # mlab.contour3d(V_ang,color = (1,1,1),opacity = 0.1) # obj = mlab.volume_slice(V_ang) # mlab.show() #for V_L fw_umat_vl = open("umat_vl_all.dat", mode="w") for LMAX_k in range(10, 13): fw_umat_vl_2 = open("umat_vl_L" + str(LMAX_k) + ".dat", mode="w") t1 = time.time() umat = np.zeros((node_open + node_close, node_open + node_close, LMAX, LMAX, 2 * LMAX + 1, 2 * LMAX + 1), dtype=np.complex64) #LMAX_k = 3 fw_umat_vl.write(str(LMAX_k)) igridnr = 201 leb_r = np.linspace(0, radius, igridnr) lebedev_num = lebedev_num_list[-8] V_L = np.zeros((LMAX_k, 2 * LMAX_k + 1, igridnr), dtype=np.complex64) leb_x = np.zeros(lebedev_num) leb_y = np.zeros(lebedev_num) leb_z = np.zeros(lebedev_num) leb_w = np.zeros(lebedev_num) lebedev(lebedev_num, leb_x, leb_y, leb_z, leb_w) theta = np.arccos(leb_z) phi = np.where( leb_x**2 + leb_y**2 != 0., np.where(leb_y >= 0, np.arccos(leb_x / np.sqrt(leb_x**2 + leb_y**2)), np.pi + np.arccos(leb_x / np.sqrt(leb_x**2 + leb_y**2))), 0.) for i in range(igridnr): V_leb_r = my_V_inter_func( np.array([leb_x, leb_y, leb_z]).T * leb_r[i]) * leb_w for k in range(LMAX_k): for q in range(-k, k + 1): V_L[k][q][i] = 4 * np.pi * np.sum( V_leb_r * sph_harm(q, k, phi, theta).conjugate()) """ for k in range(LMAX_k): for q in range(-k,k+1): print("k = ",k,"q = ", q) plt.plot(leb_r,V_L[k][q].real,marker=".") plt.show() sys.exit() """ g_ln = np.zeros((node_open + node_close, LMAX, igridnr), dtype=np.float64) for n1 in range(node_open + node_close): for l1 in range(LMAX): my_radial_g_inter_func = interpolate.interp1d( rofi, all_basis[l1][n1].g[:nr]) g_ln[n1][l1] = my_radial_g_inter_func(leb_r) C_kq = np.zeros( (LMAX, LMAX, 2 * LMAX + 1, 2 * LMAX + 1, LMAX_k, 2 * LMAX_k + 1), dtype=np.float64) for l1 in range(LMAX): for l2 in range(LMAX): for m1 in range(-l1, l1 + 1): for m2 in range(-l2, l2 + 1): for k in range(1, LMAX_k): for q in range(-k, k + 1): C_kq[l1][l2][m1][m2][k][q] = (-1)**( -m1) * np.sqrt( (2 * l1 + 1) * (2 * l2 + 1)) * Wigner3j( l1, 0, k, 0, l2, 0).doit() * Wigner3j( l1, -m1, k, q, l2, m2).doit() #print(l1,l2,m1,m2,k,q,C_kq[l1][l2][m1][m2][k][q]) count = 0 for l1 in range(LMAX): for l2 in range(LMAX): for m1 in range(-l1, l1 + 1): for m2 in range(-l2, l2 + 1): for n1 in range(node_open + node_close): for n2 in range(node_open + node_close): for k in range(1, LMAX_k): for q in range(-k, k + 1): umat[n1][n2][l1][l2][m1][m2] += simps( g_ln[n1][l1] * V_L[k][q] * g_ln[n2][l2], leb_r) * C_kq[l1][ l2][m1][m2][k][q] * np.sqrt( (2 * k + 1) / (4 * np.pi)) fw_umat_vl.write("{:>15.8f}".format( umat[n1][n2][l1][l2][m1][m2].real)) fw_umat_vl_2.write("{:>15.8f}".format(count)) fw_umat_vl_2.write("{:>15.8f}\n".format( umat[n1][n2][l1][l2][m1][m2].real)) count += 1 t2 = time.time() print("LMAX = ", LMAX_k, " time = ", t2 - t1) fw_umat_vl_2.close() fw_umat_vl.write("\n") fw_umat_vl.close()
means=np.zeros(nsamples) sdevs=np.zeros(nsamples) true_vals=np.zeros(nsamples) pct_sdevs=np.zeros(nsamples) errs=np.zeros(nsamples) abs_errs=np.zeros(nsamples) pct_errs=np.zeros(nsamples) """ Run the vegas algorithm over varying nu. """ for samp in tqdm(range(nsamples)): ret = integrate.integrate(nu[samp],s0,s1,kap,npoints,ordered=True,test=True) means[samp]=ret[0] sdevs[samp]=ret[1] true_vals[samp]=truint(nu[samp],s0,s1) pct_sdevs[samp] = abs(100.0*(sdevs[samp])/means[samp]) errs[samp] = (means[samp]-true_vals[samp]) abs_errs[samp] = abs(means[samp]-true_vals[samp]) pct_errs[samp] = abs(100.0*(means[samp]-true_vals[samp])/true_vals[samp]) """ Format an output table for spot-checking! """
""" Created on Apr 14 2016 @author: Diego Castaneda email: [email protected] """ # Import the Fortran subroutine: import integrate as it # And you're set, call it and pass the required # arguments! f_name = "outputflux875" # Name of file n_elem = 1048992 # Number of lines in file area = it.integrate(f_name,n_elem) # Fortran call
def test(): for N in (10**i for i in xrange(1,8)): print "Numerical solution with N=%(N)d : %(x)f" % \ {'N': N, 'x': integrate(f, a, b, N)}
def main(): # make environment t1 = time.time() pot_region = (2 / np.sqrt(3), 2 / np.sqrt(3), 2 / np.sqrt(3)) radius = np.sqrt(pot_region[0]**2 + pot_region[1]**2 + pot_region[2]**2) region = (radius, radius, radius) nr = 201 gridpx = 200 gridpy = 200 gridpz = 200 x, y, z = grid(gridpx, gridpy, gridpz, region) xx, yy, zz = np.meshgrid(x, y, z) #make mesh #linear mesh #r =np.linspace(0.0001,region,nr) #log mesh #a = np.log(2) / (nr - 1) a = 0.03 b = radius / (np.e**(a * (nr - 1)) - 1) rofi = np.array([b * (np.e**(a * i) - 1) for i in range(nr)]) # make potential V = makepotential(xx, yy, zz, pot_region, pottype="cubic", potbottom=-1, potshow_f=False) # surface integral V_radial = surfaceintegral(x, y, z, rofi, V, method="lebedev_py", potshow_f=False) vofi = np.array(V_radial) # select method of surface integral """ #test 20191029 V_test = np.zeros(nr,dtype=np.float64) for i in range(nr): ri = rofi[i] if ri < pot_region[0]: V_test[i] = -1 elif ri >= pot_region[0] and ri < pot_region[0] * np.sqrt(2) : V_test[i] = -1 * ( 1 - 12 * np.pi * ri * ( ri - 0.5 * radius )/(4 * np.pi * ri**2)) elif ri >= pot_region[0] * np.sqrt(2) and ri <=radius: V_test[i] = -1 * ( ri - 0.5 * np.sqrt(3) * radius ) * ( 2 - 3 * np.sqrt(2) * ( np.sqrt(2) - 1 ) ) / ( ri**2 * (np.sqrt(2) - np.sqrt(3))**2) #plt.plot(rofi,V_test,marker=".") #plt.show() V_radial = V_test vofi = V_test """ # make basis node_open = 1 node_close = 2 node = node_open + node_close LMAX = 3 nstates = node * LMAX**2 all_basis = [] for lvalsh in range(LMAX): l_basis = [] # for open channel val = 1. slo = 0. for no in range(node_open): basis = Basis(nr) emin = -10. emax = 100. basis.make_basis(a, b, emin, emax, lvalsh, no, nr, rofi, slo, vofi, val) l_basis.append(basis) # for close channel val = 0. slo = -1. for nc in range(node_close): basis = Basis(nr) emin = -10. emax = 100. basis.make_basis(a, b, emin, emax, lvalsh, nc, nr, rofi, slo, vofi, val) l_basis.append(basis) all_basis.append(l_basis) with open("wavefunc_2.dat", mode="w") as fw_w: fw_w.write("#r, l, node, open or close = ") for l_basis in all_basis: for nyu_basis in l_basis: fw_w.write(str(nyu_basis.l)) fw_w.write(str(nyu_basis.node)) if nyu_basis.open: fw_w.write("open") else: fw_w.write("close") fw_w.write(" ") fw_w.write("\n") for i in range(nr): fw_w.write("{:>13.8f}".format(rofi[i])) for l_basis in all_basis: for nyu_basis in l_basis: fw_w.write("{:>13.8f}".format(nyu_basis.g[i])) fw_w.write("\n") Smat = np.zeros((LMAX, LMAX, node, node), dtype=np.float64) hsmat = np.zeros((LMAX, LMAX, node, node), dtype=np.float64) lmat = np.zeros((LMAX, LMAX, node, node), dtype=np.float64) qmat = np.zeros((LMAX, LMAX, node, node), dtype=np.float64) """ for l1 in range (LMAX): for n1 in range (node_open + node_close): print("l1 = ",l1,"n1 = ",n1,all_basis[l1][n1].val,all_basis[l1][n1].g[nr-1]) sys.exit() """ for l1 in range(LMAX): for l2 in range(LMAX): if l1 != l2: continue for n1 in range(node): for n2 in range(node): if all_basis[l1][n1].l != l1 or all_basis[l2][n2].l != l2: print("error: L is differnt") sys.exit() Smat[l1][l2][n1][n2] = integrate( all_basis[l1][n1].g[:nr] * all_basis[l2][n2].g[:nr], rofi, nr) hsmat[l1][l2][n1][ n2] = Smat[l1][l2][n1][n2] * all_basis[l2][n2].e lmat[l1][l2][n1][ n2] = all_basis[l1][n1].val * all_basis[l2][n2].slo qmat[l1][l2][n1][ n2] = all_basis[l1][n1].val * all_basis[l2][n2].val print("\nSmat") print(Smat) print("\nhsmat") print(hsmat) print("\nlmat") print(lmat) print("\nqmat") print(qmat) hs_L = np.zeros((LMAX, LMAX, node, node)) """ for l1 in range(LMAX): for n1 in range(node): for l2 in range(LMAX): for n2 in range(node): print("{:>8.4f}".format(lmat[l1][l2][n1][n2]),end="") print("") print("") """ print("hs_L") for l1 in range(LMAX): for n1 in range(node): for l2 in range(LMAX): for n2 in range(node): hs_L[l1][l2][n1][ n2] = hsmat[l1][l2][n1][n2] + lmat[l1][l2][n1][n2] print("{:>8.4f}".format(hs_L[l1][l2][n1][n2]), end="") print("") #make not spherical potential my_radial_interfunc = interpolate.interp1d(rofi, V_radial) V_ang = np.where( np.sqrt(xx * xx + yy * yy + zz * zz) < rofi[-1], V - my_radial_interfunc(np.sqrt(xx**2 + yy**2 + zz**2)), 0.) """ for i in range(gridpx): for j in range(gridpy): for k in range(gridpz): print(V_ang[i][j][k],end=" ") print("") print("\n") sys.exit() """ #WARING!!!!!!!!!!!!!!!!!!!!!! """ Fujikata rewrote ~/.local/lib/python3.6/site-packages/scipy/interpolate/interpolate.py line 690~702 To avoid exit with error "A value in x_new is below the interpolation range." """ #!!!!!!!!!!!!!!!!!!!!!!!!!!! """ with open ("V_ang.dat",mode = "w") as fw_a: for i in range(len(V_ang)): fw_a.write("{:>13.8f}".format(xx[50][i][50])) fw_a.write("{:>13.8f}\n".format(V_ang[i][50][50])) """ #mayavi.mlab.plot3d(xx,yy,V_ang) # mlab.contour3d(V_ang,color = (1,1,1),opacity = 0.1) # obj = mlab.volume_slice(V_ang) # mlab.show() umat_av = np.zeros((node, node, LMAX, LMAX, 2 * LMAX + 1, 2 * LMAX + 1), dtype=np.complex64) gridstart = 50 gridend = 60 gridrange = gridend - gridstart + 1 for ngrid in range(gridstart, gridend + 1): t1 = time.time() fw_u = open("umat_grid" + str(ngrid) + ".dat", mode="w") umat = np.zeros((node, node, LMAX, LMAX, 2 * LMAX + 1, 2 * LMAX + 1), dtype=np.complex64) my_V_ang_inter_func = RegularGridInterpolator((x, y, z), V_ang) igridpx = ngrid igridpy = ngrid igridpz = ngrid ix, iy, iz = grid(igridpx, igridpy, igridpz, region) ixx, iyy, izz = np.meshgrid(ix, iy, iz) V_ang_i = my_V_ang_inter_func((ixx, iyy, izz)) #mlab.contour3d(V_ang_i,color = (1,1,1),opacity = 0.1) #obj = mlab.volume_slice(V_ang_i) #mlab.show() dis = np.sqrt(ixx**2 + iyy**2 + izz**2) dis2 = ixx**2 + iyy**2 + izz**2 theta = np.where(dis != 0., np.arccos(izz / dis), 0.) phi = np.where( iyy**2 + ixx**2 != 0, np.where(iyy >= 0, np.arccos(ixx / np.sqrt(ixx**2 + iyy**2)), np.pi + np.arccos(ixx / np.sqrt(ixx**2 + iyy**2))), 0.) #phi = np.where( iyy != 0. , phi, 0.) #phi = np.where(iyy > 0, phi,-phi) # region_t = np.where(dis < rofi[-1],1,0) sph_harm_mat = np.zeros( (LMAX, 2 * LMAX + 1, igridpx, igridpy, igridpz), dtype=np.complex64) for l1 in range(LMAX): for m1 in range(-l1, l1 + 1): sph_harm_mat[l1][m1] = np.where(dis != 0., sph_harm(m1, l1, phi, theta), 0.) g_ln_mat = np.zeros((node, LMAX, igridpx, igridpy, igridpz), dtype=np.float64) for n1 in range(node): for l1 in range(LMAX): my_radial_g_inter_func = interpolate.interp1d( rofi, all_basis[l1][n1].g[:nr]) g_ln_mat[n1][l1] = my_radial_g_inter_func( np.sqrt(ixx**2 + iyy**2 + izz**2)) for n1 in range(node): for n2 in range(node): for l1 in range(LMAX): for l2 in range(LMAX): if all_basis[l1][n1].l != l1 or all_basis[l2][ n2].l != l2: print("error: L is differnt") sys.exit() # to avoid nan in region where it can not interpolate ie: dis > rofi g_V_g = np.where( dis < rofi[-1], g_ln_mat[n1][l1] * V_ang_i * g_ln_mat[n2][l2], 0.) for m1 in range(-l1, l1 + 1): for m2 in range(-l2, l2 + 1): #print("n1 = {} n2 = {} l1 = {} l2 = {} m1 = {} m2 = {}".format(n1,n2,l1,l2,m1,m2)) umat[n1][n2][l1][l2][m1][m2] = np.sum( np.where( dis2 != 0., sph_harm_mat[l1][m1].conjugate() * g_V_g * sph_harm_mat[l2][m2] / dis2, 0.)) * (2 * region[0] * 2 * region[1] * 2 * region[2]) / (igridpx * igridpy * igridpz) #print(umat[n1][n2][l1][l2][m1][m2]) count = 0 for l1 in range(LMAX): for l2 in range(LMAX): for m1 in range(-l1, l1 + 1): for m2 in range(-l2, l2 + 1): for n1 in range(node): for n2 in range(node): fw_u.write(str(count)) fw_u.write("{:>15.8f}{:>15.8f}\n".format( umat[n1][n2][l1][l2][m1][m2].real, umat[n1][n2][l1][l2][m1][m2].imag)) count += 1 umat_av += umat fw_u.close() t2 = time.time() print("grid = ", ngrid, "time = ", t2 - t1) umat_av /= gridrange count = 0 fw_u_av = open("umat_grid_av" + str(gridstart) + "_" + str(gridend) + ".dat", mode="w") for l1 in range(LMAX): for l2 in range(LMAX): for m1 in range(-l1, l1 + 1): for m2 in range(-l2, l2 + 1): for n1 in range(node): for n2 in range(node): fw_u_av.write(str(count)) fw_u_av.write("{:>15.8f}{:>15.8f}\n".format( umat_av[n1][n2][l1][l2][m1][m2].real, umat_av[n1][n2][l1][l2][m1][m2].imag)) count += 1 fw_u_av.close() ham_mat = np.zeros((nstates * nstates), dtype=np.float64) qmetric_mat = np.zeros((nstates * nstates), dtype=np.float64) for l1 in range(LMAX): for m1 in range(-l1, l1 + 1): for n1 in range(node): for l2 in range(LMAX): for m2 in range(-l2, l2 + 1): for n2 in range(node): if l1 == l2 and m1 == m2: ham_mat[l1**2 * node * LMAX**2 * node + (l1 + m1) * node * LMAX**2 * node + n1 * LMAX**2 * node + l2**2 * node + (l2 + m2) * node + n2] += hs_L[l1][l2][n1][n2] qmetric_mat[l1**2 * node * LMAX**2 * node + (l1 + m1) * node * LMAX**2 * node + n1 * LMAX**2 * node + l2**2 * node + (l2 + m2) * node + n2] = qmat[l1][l2][n1][n2] ham_mat[l1**2 * node * LMAX**2 * node + (l1 + m1) * node * LMAX**2 * node + n1 * LMAX**2 * node + l2**2 * node + (l2 + m2) * node + n2] += umat_av[n1][n2][l1][l2][m1][m2].real lambda_mat = np.zeros(nstates * nstates, dtype=np.float64) alphalong = np.zeros(nstates) betalong = np.zeros(nstates) revec = np.zeros(nstates * nstates) for e_num in range(1, 2): E = e_num * 10 lambda_mat = np.zeros(nstates * nstates, dtype=np.float64) lambda_mat -= ham_mat """ for i in range(nstates): lambda_mat[i + i * nstates] += E """ count = 0 fw_lam = open("lambda.dat", mode="w") for l1 in range(LMAX): for m1 in range(-l1, l1 + 1): for n1 in range(node): for l2 in range(LMAX): for m2 in range(-l2, l2 + 1): for n2 in range(node): if l1 == l2 and m1 == m2: lambda_mat[l1**2 * node * LMAX**2 * node + (l1 + m1) * node * LMAX**2 * node + n1 * LMAX**2 * node + l2**2 * node + (l2 + m2) * node + n2] += Smat[l1][l2][n1][n2] * E fw_lam.write(str(count)) fw_lam.write("{:>15.8f}\n".format( lambda_mat[l1**2 * node * LMAX**2 * node + (l1 + m1) * node * LMAX**2 * node + n1 * LMAX**2 * node + l2**2 * node + (l2 + m2) * node + n2])) count += 1 info = solve_genev(nstates, lambda_mat, qmetric_mat, alphalong, betalong, revec) print("info = ", info) print("alphalong") print(alphalong) print("betalong") print(betalong) #print(revec) k = 0 jk = np.zeros(nstates, dtype=np.int32) for i in range(nstates): if betalong[i] != 0.: jk[k] = i k += 1 fw_revec = open("revec.dat", mode="w") print("revec") for j in range(nstates): fw_revec.write("{:>4}".format(j)) for i in range(LMAX**2): fw_revec.write("{:>13.8f}".format(revec[j + jk[i] * nstates])) print("{:>11.6f}".format(revec[j + jk[i] * nstates]), end="") print("") fw_revec.write("\n") print("")
def meanValue(self, A, F): """ when called, uses an operator A (array-like) and a wavefunction F (array-like) to calculate the mean value of the observable associated with the operator A with respect to the wavefunction F """ return integrate(self.dx, np.multiply(np.conj(F), A * F), [0])
#!/usr/bin/env python import sys sys.path.append("..") from integrate import integrate, f # integrate_f_with_functional_tools as integrate_f # from integrate import integrate_f import argparse parser = argparse.ArgumentParser(description='integrator') parser.add_argument('a', nargs='?', type=float, default=0.0) parser.add_argument('b', nargs='?', type=float, default=10.0) parser.add_argument('N', nargs='?', type=int, default=10**7) args = parser.parse_args() a = args.a b = args.b N = args.N # print "Numerical solution from (%(a)f to %(b)f with N=%(N)d : \n%(x)f" % \ # {'a': a, 'b': b, 'N': N, 'x': integrate_f(a, b, N)} print "%(x)f" % {'x': integrate(f, a, b, N)}
def main(): f = lambda x: x**3 - 2*x**2 + 5 print integrate(f, 3, 5)
def test(): for N in (10**i for i in xrange(1, 8)): print "Numerical solution with N=%(N)d : %(x)f" % \ {'N': N, 'x': integrate(f, a, b, N)}
def main(argv): with open('config.json', 'r') as f: config = json.load(f) integrate.integrate(**config) return 0
def main(): a, b = 0.0, 2.0 * pi return integrate(a, b, sin2, N=400000)
def worker(*args): results.put(integrate(*args))
def main(): # make environment fw_t = open("time_log",mode="w") t1 = time.time() pot_region,bound_rad,radius,region,nr,gridpx,gridpy,gridpz,x,y,z,xx,yy,zz,a,b,rofi,pot_type,pot_bottom,pot_show_f,si_method,radial_pot_show_f,new_radial_pot_show_f,node_open,node_close,LMAX = make_environment() # make potential V = makepotential(xx,yy,zz,pot_region,pot_type=pot_type,pot_bottom=pot_bottom,pot_show_f=pot_show_f) # surface integral V_radial = surfaceintegral(x,y,z,rofi,V,si_method=si_method,radial_pot_show_f=radial_pot_show_f) V_radial_new = make_V_radial_new(V_radial,rofi,pot_region,bound_rad,new_radial_pot_show_f=new_radial_pot_show_f) vofi = np.array (V_radial_new) # select method of surface integral # make basis node = node_open + node_close nstates = node * LMAX**2 all_basis = make_basis(LMAX,node_open,node_close,nr,a,b,rofi,vofi) #make spherical matrix element Smat = np.zeros((LMAX,LMAX,node,node),dtype = np.float64) hsmat = np.zeros((LMAX,LMAX,node,node),dtype = np.float64) lmat = np.zeros((LMAX,LMAX,node,node), dtype = np.float64) qmat = np.zeros((LMAX,LMAX,node,node), dtype = np.float64) for l1 in range (LMAX): for l2 in range (LMAX): if l1 != l2 : continue for n1 in range (node): for n2 in range (node): if all_basis[l1][n1].l != l1 or all_basis[l2][n2].l != l2: print("error: L is differnt") sys.exit() Smat[l1][l2][n1][n2] = integrate(all_basis[l1][n1].g[:nr] * all_basis[l2][n2].g[:nr],rofi,nr) hsmat[l1][l2][n1][n2] = Smat[l1][l2][n1][n2] * all_basis[l2][n2].e lmat[l1][l2][n1][n2] = all_basis[l1][n1].val * all_basis[l2][n2].slo qmat[l1][l2][n1][n2] = all_basis[l1][n1].val * all_basis[l2][n2].val print("\nSmat") print(Smat) print ("\nhsmat") print (hsmat) print ("\nlmat") print (lmat) print ("\nqmat") print (qmat) hs_L = np.zeros((LMAX,LMAX,node,node)) """ for l1 in range(LMAX): for n1 in range(node): for l2 in range(LMAX): for n2 in range(node): print("{:>8.4f}".format(lmat[l1][l2][n1][n2]),end="") print("") print("") """ print("hs_L") for l1 in range(LMAX): for n1 in range(node): for l2 in range(LMAX): for n2 in range(node): hs_L[l1][l2][n1][n2] = hsmat[l1][l2][n1][n2] + lmat[l1][l2][n1][n2] print("{:>8.4f}".format(hs_L[l1][l2][n1][n2]),end="") print("") t2 = time.time() fw_t.write("make environment, make basis and calculate spherical matrix element\n") fw_t.write("time = {:>11.8}s\n".format(t2-t1)) t1 = time.time() #make not spherical potential my_radial_interfunc = interpolate.interp1d(rofi, V_radial_new) V_ang = np.where(np.sqrt(xx * xx + yy * yy + zz * zz) < rofi[-1] , V - my_radial_interfunc(np.sqrt(xx **2 + yy **2 + zz **2)),0. ) """ for i in range(gridpx): for j in range(gridpy): for k in range(gridpz): print(V_ang[i][j][k],end=" ") print("") print("\n") sys.exit() """ #WARING!!!!!!!!!!!!!!!!!!!!!! """ Fujikata rewrote ~/.local/lib/python3.6/site-packages/scipy/interpolate/interpolate.py line 690~702 To avoid exit with error "A value in x_new is below the interpolation range." """ #!!!!!!!!!!!!!!!!!!!!!!!!!!! """ with open ("V_ang.dat",mode = "w") as fw_a: for i in range(len(V_ang)): fw_a.write("{:>13.8f}".format(xx[50][i][50])) fw_a.write("{:>13.8f}\n".format(V_ang[i][50][50])) """ #mayavi.mlab.plot3d(xx,yy,V_ang) # mlab.contour3d(V_ang,color = (1,1,1),opacity = 0.1) # obj = mlab.volume_slice(V_ang) # mlab.show() ngrid = 10 fw_u = open("umat_gauss.dat",mode="w") umat = np.zeros((node,node,LMAX,LMAX,2 * LMAX + 1,2 * LMAX + 1), dtype = np.complex64) igridpx = ngrid igridpy = ngrid igridpz = ngrid gauss_px,gauss_wx = np.polynomial.legendre.leggauss(igridpx) gauss_py,gauss_wy = np.polynomial.legendre.leggauss(igridpy) gauss_pz,gauss_wz = np.polynomial.legendre.leggauss(igridpz) ix,iy,iz = gauss_px * pot_region[0],gauss_py * pot_region[1],gauss_pz * pot_region[2] ixx,iyy,izz = np.meshgrid(ix,iy,iz) gauss_weight = np.zeros((igridpx,igridpy,igridpz)) for i in range(igridpx): for j in range(igridpy): for k in range(igridpz): gauss_weight[i][j][k] = gauss_wx[i] * gauss_wy[j] * gauss_wz[k] #my_V_ang_inter_func = RegularGridInterpolator((x, y, z), V_ang) #V_ang_i = my_V_ang_inter_func((ixx,iyy,izz)) V_ang_i = np.zeros((igridpx,igridpy,igridpz)) V_ang_i = -1. - my_radial_interfunc(np.sqrt(ixx * ixx + iyy * iyy + izz * izz)) #mlab.contour3d(V_ang_i,color = (1,1,1),opacity = 0.1) #obj = mlab.volume_slice(V_ang_i) #mlab.show() dis = np.sqrt(ixx **2 + iyy **2 + izz **2) dis2 = ixx **2 + iyy **2 + izz **2 theta = np.where( dis != 0., np.arccos(izz / dis), 0.) phi = np.where( iyy**2 + ixx **2 != 0 , np.where(iyy >= 0, np.arccos(ixx / np.sqrt(ixx **2 + iyy **2)), np.pi + np.arccos(ixx / np.sqrt(ixx **2 + iyy **2))), 0.) #phi = np.where( iyy != 0. , phi, 0.) #phi = np.where(iyy > 0, phi,-phi) # region_t = np.where(dis < rofi[-1],1,0) sph_harm_mat = np.zeros((LMAX,2 * LMAX + 1, igridpx,igridpy,igridpz),dtype = np.complex64) for l1 in range (LMAX): for m1 in range (-l1,l1 + 1): sph_harm_mat[l1][m1] = np.where(dis != 0., sph_harm(m1,l1,phi,theta),0.) g_ln_mat = np.zeros((node,LMAX,igridpx,igridpy,igridpz),dtype = np.float64) for n1 in range (node): for l1 in range (LMAX): my_radial_g_inter_func = interpolate.interp1d(rofi,all_basis[l1][n1].g[:nr]) g_ln_mat[n1][l1] = my_radial_g_inter_func(np.sqrt(ixx **2 + iyy **2 + izz **2)) for n1 in range (node): for n2 in range (node): for l1 in range (LMAX): for l2 in range (LMAX): if all_basis[l1][n1].l != l1 or all_basis[l2][n2].l != l2: print("error: L is differnt") sys.exit() # to avoid nan in region where it can not interpolate ie: dis > rofi g_V_g = np.where(dis < rofi[-1], g_ln_mat[n1][l1] * V_ang_i * g_ln_mat[n2][l2], 0.) for m1 in range (-l1,l1+1): for m2 in range (-l2,l2+1): #print("n1 = {} n2 = {} l1 = {} l2 = {} m1 = {} m2 = {}".format(n1,n2,l1,l2,m1,m2)) umat[n1][n2][l1][l2][m1][m2] = np.sum(np.where( dis2 != 0., sph_harm_mat[l1][m1].conjugate() * g_V_g * sph_harm_mat[l2][m2] / dis2 * gauss_weight, 0.)) * pot_region[0] * pot_region[1] * pot_region[2] #print(umat[n1][n2][l1][l2][m1][m2]) count = 0 for l1 in range (LMAX): for l2 in range (LMAX): for m1 in range (-l1,l1+1): for m2 in range (-l2,l2+1): for n1 in range (node): for n2 in range (node): fw_u.write(str(count)) fw_u.write("{:>15.8f}{:>15.8f}\n".format(umat[n1][n2][l1][l2][m1][m2].real,umat[n1][n2][l1][l2][m1][m2].imag)) count += 1 fw_u.close() t2 = time.time() fw_t.write("calculate U-matrix\n") fw_t.write("grid = {:<5} time ={:>11.8}s\n".format(ngrid,t2 - t1)) t1 = time.time() ham_mat = np.zeros((nstates * nstates),dtype = np.float64) qmetric_mat = np.zeros((nstates * nstates),dtype = np.float64) for l1 in range(LMAX): for m1 in range (-l1,l1+1): for n1 in range(node): for l2 in range(LMAX): for m2 in range(-l2,l2+1): for n2 in range(node): if l1 == l2 and m1 == m2 : ham_mat[l1 **2 * node * LMAX**2 * node + (l1 + m1) * node * LMAX**2 * node + n1 * LMAX**2 * node + l2 **2 * node + (l2 + m2) * node + n2] += hs_L[l1][l2][n1][n2] qmetric_mat[l1 **2 * node * LMAX**2 * node + (l1 + m1) * node * LMAX**2 * node + n1 * LMAX**2 * node + l2 **2 * node + (l2 + m2) * node + n2] = qmat[l1][l2][n1][n2] ham_mat[l1 **2 * node * LMAX**2 * node + (l1 + m1) * node * LMAX**2 * node + n1 * LMAX**2 * node + l2 **2 * node + (l2 + m2) * node + n2] += umat[n1][n2][l1][l2][m1][m2].real lambda_mat = np.zeros(nstates * nstates,dtype = np.float64) alphalong = np.zeros(nstates) betalong = np.zeros(nstates) alpha = np.zeros(LMAX**2) beta = np.zeros(LMAX**2) reveclong = np.zeros(nstates * nstates) revec = np.zeros((LMAX**2,nstates)) for e_num in range(1,2): E = e_num * 1 lambda_mat = np.zeros(nstates * nstates,dtype = np.float64) lambda_mat -= ham_mat """ for i in range(nstates): lambda_mat[i + i * nstates] += E """ count = 0 fw_lam = open("lambda.dat",mode="w") for l1 in range(LMAX): for m1 in range (-l1,l1+1): for n1 in range(node): for l2 in range(LMAX): for m2 in range(-l2,l2+1): for n2 in range(node): if l1 == l2 and m1 == m2 : lambda_mat[l1 **2 * node * LMAX**2 * node + (l1 + m1) * node * LMAX**2 * node + n1 * LMAX**2 * node + l2 **2 * node + (l2 + m2) * node + n2] += Smat[l1][l2][n1][n2] * E fw_lam.write(str(count)) fw_lam.write("{:>15.8f}\n".format(lambda_mat[l1 **2 * node * LMAX**2 * node + (l1 + m1) * node * LMAX**2 * node + n1 * LMAX**2 * node + l2 **2 * node + (l2 + m2) * node + n2])) count += 1 fw_lam.close() info = solve_genev(nstates,lambda_mat,qmetric_mat,alphalong,betalong,reveclong) print("info = ",info) print("alphalong") print(alphalong) print("betalong") print(betalong) #print(revec) k = 0 jk = np.zeros(nstates,dtype=np.int32) for i in range(nstates): if abs(betalong[i]) > BETAZERO : jk[k] = i k += 1 if k != LMAX**2: print(" main PANIC: solution of genev has rank k != nchannels ") sys.exit() for k in range(LMAX**2): j = jk[k] alpha[k] = alphalong[j] beta[k] = betalong[j] revec[k] = reveclong[j * nstates : (j + 1) * nstates] fw_revec = open("revec.dat",mode="w") print("revec") for j in range(nstates): fw_revec.write("{:>4}".format(j)) for i in range(LMAX**2): fw_revec.write("{:>13.8f}".format(revec[i][j])) print("{:>11.6f}".format(revec[i][j]),end="") print("") fw_revec.write("\n") print("") fw_revec.close() t2 = time.time() fw_t.write("solve eigenvalue progrem\n") fw_t.write("time = {:>11.8}s\n".format(t2-t1)) fw_t.close()
def main(): # make environment pot_region = (2 / np.sqrt(3), 2 / np.sqrt(3), 2 / np.sqrt(3)) radius = np.sqrt(pot_region[0]**2 + pot_region[1]**2 + pot_region[2]**2) region = (radius, radius, radius) nr = 201 gridpx = 200 gridpy = 200 gridpz = 200 x, y, z = grid(gridpx, gridpy, gridpz, region) xx, yy, zz = np.meshgrid(x, y, z) #make mesh #linear mesh #r =np.linspace(0.0001,region,nr) #log mesh a = np.log(2) / (nr - 1) b = radius / (np.e**(a * (nr - 1)) - 1) rofi = np.array([b * (np.e**(a * i) - 1) for i in range(nr)]) # make potential V = makepotential(xx, yy, zz, pot_region, pottype="cubic", potbottom=-1, potshow_f=False) # surface integral V_radial = surfaceintegral(x, y, z, rofi, V, method="lebedev_py", potshow_f=False) vofi = np.array(V_radial) # select method of surface integral # make basis node_open = 1 node_close = 2 LMAX = 4 all_basis = [] for lvalsh in range(LMAX): l_basis = [] # for open channel val = 1. slo = 0. for node in range(node_open): basis = Basis(nr) emin = -10. emax = 100. basis.make_basis(a, b, emin, emax, lvalsh, node, nr, rofi, slo, vofi, val) l_basis.append(basis) # for close channel val = 0. slo = -1. for node in range(node_close): basis = Basis(nr) emin = -10. emax = 100. basis.make_basis(a, b, emin, emax, lvalsh, node, nr, rofi, slo, vofi, val) l_basis.append(basis) all_basis.append(l_basis) with open("wavefunc.dat", mode="w") as fw_w: fw_w.write("#r, l, node, open or close = ") for l_basis in all_basis: for nyu_basis in l_basis: fw_w.write(str(nyu_basis.l)) fw_w.write(str(nyu_basis.node)) if nyu_basis.open: fw_w.write("open") else: fw_w.write("close") fw_w.write(" ") fw_w.write("\n") for i in range(nr): fw_w.write("{:>13.8f}".format(rofi[i])) for l_basis in all_basis: for nyu_basis in l_basis: fw_w.write("{:>13.8f}".format(nyu_basis.g[i])) fw_w.write("\n") hsmat = np.zeros( (LMAX, LMAX, node_open + node_close, node_open + node_close), dtype=np.float64) lmat = np.zeros( (LMAX, LMAX, node_open + node_close, node_open + node_close), dtype=np.float64) qmat = np.zeros( (LMAX, LMAX, node_open + node_close, node_open + node_close), dtype=np.float64) for l1 in range(LMAX): for l2 in range(LMAX): if l1 != l2: continue for n1 in range(node_open + node_close): for n2 in range(node_open + node_close): if all_basis[l1][n1].l != l1 or all_basis[l2][n2].l != l2: print("error: L is differnt") sys.exit() hsmat[l1][l2][n1][n2] = integrate( all_basis[l1][n1].g[:nr] * all_basis[l2][n2].g[:nr], rofi, nr) * all_basis[l1][n1].e lmat[l1][l2][n1][ n2] = all_basis[l1][n1].val * all_basis[l2][n2].slo qmat[l1][l2][n1][ n2] = all_basis[l1][n1].val * all_basis[l2][n2].val print("\nhsmat") print(hsmat) print("\nlmat") print(lmat) print("\nqmat") print(qmat) #make not spherical potential my_radial_interfunc = interpolate.interp1d(rofi, V_radial) V_ang = np.where( np.sqrt(xx * xx + yy * yy + zz * zz) < rofi[-1], V - my_radial_interfunc(np.sqrt(xx * xx + yy * yy + zz * zz)), 0.) """ for i in range(gridpx): for j in range(gridpy): for k in range(gridpz): print(V_ang[i][j][k],end=" ") print("") print("\n") sys.exit() """ #WARING!!!!!!!!!!!!!!!!!!!!!! """ Fujikata rewrote ~/.local/lib/python3.6/site-packages/scipy/interpolate/interpolate.py line 690~702 To avoid exit with error "A value in x_new is below the interpolation range." """ #!!!!!!!!!!!!!!!!!!!!!!!!!!! """ with open ("V_ang.dat",mode = "w") as fw_a: for i in range(len(V_ang)): fw_a.write("{:>13.8f}".format(xx[50][i][50])) fw_a.write("{:>13.8f}\n".format(V_ang[i][50][50])) """ #mayavi.mlab.plot3d(xx,yy,V_ang) # mlab.contour3d(V_ang,color = (1,1,1),opacity = 0.1) # obj = mlab.volume_slice(V_ang) # mlab.show() fw_grid = open("umat_grid_all.dat", mode="w") for ngrid in range(20, 100): fw_grid_2 = open("umat_grid" + str(ngrid) + ".dat", mode="w") fw_grid.write(str(ngrid) + " ") t1 = time.time() umat = np.zeros((node_open + node_close, node_open + node_close, LMAX, LMAX, 2 * LMAX + 1, 2 * LMAX + 1), dtype=np.complex64) # umat_t = np.zeros((LMAX,LMAX,2 * LMAX + 1,2 * LMAX + 1,node_open + node_close,node_open + node_close), dtype = np.complex64) my_V_ang_inter_func = RegularGridInterpolator((x, y, z), V_ang) igridpx = ngrid igridpy = ngrid igridpz = ngrid ix, iy, iz = grid(igridpx, igridpy, igridpz, region) ixx, iyy, izz = np.meshgrid(ix, iy, iz) V_ang_i = my_V_ang_inter_func((ixx, iyy, izz)) #mlab.points3d(V_ang_i,scale_factor=0.4) # mlab.contour3d(V_ang_i,color = (1,1,1),opacity = 0.1) # obj = mlab.volume_slice(V_ang_i) #mlab.show() dis = np.sqrt(ixx**2 + iyy**2 + izz**2) dis2 = ixx**2 + iyy**2 + izz**2 theta = np.where(dis != 0., np.arccos(izz / dis), 0.) phi = np.where( iyy**2 + ixx**2 != 0, np.where(iyy >= 0, np.arccos(ixx / np.sqrt(ixx**2 + iyy**2)), np.pi + np.arccos(ixx / np.sqrt(ixx**2 + iyy**2))), 0.) # region_t = np.where(dis < rofi[-1],1,0) sph_harm_mat = np.zeros( (LMAX, 2 * LMAX + 1, igridpx, igridpy, igridpz), dtype=np.complex64) for l1 in range(LMAX): for m1 in range(-l1, l1 + 1): sph_harm_mat[l1][m1] = np.where(dis != 0., sph_harm(m1, l1, phi, theta), 0.) g_ln_mat = np.zeros( (node_open + node_close, LMAX, igridpx, igridpy, igridpz), dtype=np.float64) for n1 in range(node_open + node_close): for l1 in range(LMAX): my_radial_g_inter_func = interpolate.interp1d( rofi, all_basis[l1][n1].g[:nr]) g_ln_mat[n1][l1] = my_radial_g_inter_func( np.sqrt(ixx**2 + iyy**2 + izz**2)) for n1 in range(node_open + node_close): for n2 in range(node_open + node_close): for l1 in range(LMAX): for l2 in range(LMAX): if all_basis[l1][n1].l != l1 or all_basis[l2][ n2].l != l2: print("error: L is differnt") sys.exit() # to avoid nan in region where it can not interpolate ie: dis > rofi g_V_g = np.where( dis < rofi[-1], g_ln_mat[n1][l1] * V_ang_i * g_ln_mat[n2][l2], 0.) for m1 in range(-l1, l1 + 1): for m2 in range(-l2, l2 + 1): #print("n1 = {} n2 = {} l1 = {} l2 = {} m1 = {} m2 = {}".format(n1,n2,l1,l2,m1,m2)) umat[n1][n2][l1][l2][m1][m2] = np.sum( np.where( dis2 != 0., sph_harm_mat[l1][m1].conjugate() * g_V_g * sph_harm_mat[l2][m2] / dis2, 0.)) * (2 * region[0] * 2 * region[1] * 2 * region[2]) / (igridpx * igridpy * igridpz) fw_grid.write("{:>13.8f}".format( umat[n1][n2][l1][l2][m1][m2].real)) count = 0 for l1 in range(LMAX): for l2 in range(LMAX): for m1 in range(-l1, l1 + 1): for m2 in range(-l2, l2 + 1): for n1 in range(node_open + node_close): for n2 in range(node_open + node_close): fw_grid_2.write(str(count)) fw_grid_2.write("{:>15.8f}{:>15.8f}\n".format( umat[n1][n2][l1][l2][m1][m2].real, umat[n1][n2][l1][l2][m1][m2].imag)) count += 1 t2 = time.time() fw_grid.write("\n") print("grid = ", ngrid, "time = ", t2 - t1) fw_grid.close()
def dispcal(data, samprate, fcs, hs, gap, volts, displ, bfc=0.0, bm=0): dt = 1.0 / samprate npts = len(data) npol = 3 perc1 = 50 perc2 = 95 fac = volts / displ * 0.001 # remove offset using the first 6 seconds that have to be quiet! z = np.ones(npts) offset = np.sum(data[0:int(6.0*samprate)]) data = data - offset # apply butterworth low pass filter if required if bfc > 0.0 and bm > 0: bt0 = 1.0 / bfc mm = int(bm / 2.0) # if odd order apply first order low pass if bm > 2 * mm: f0_lp1, f1_lp1, f2_lp1, g1_lp1, g2_lp1 = lp1(bt0*samprate) data = rekfl(data, npts, f0_lp1, f1_lp1, f2_lp1, g1_lp1, g2_lp1) # now apply second order low pass for i in range(mm): h = np.sin(np.pi / 2.0 * (2.0 * i - 1.0) / bm) f0_lp2, f1_lp2, f2_lp2, g1_lp2, g2_lp2 = lp2(bt0*samprate, h) data = rekfl(data, npts, f0_lp2, f1_lp2, f2_lp2, g1_lp2, g2_lp2) # report filtering print 'Input data filtered with low pass Butterworth filter:' print ' corner frequency: ' + str(bfc) + 'Hz' print ' order: ' + str(bm) + '.' raw = data.copy() # deconvolution to velocity step # done by appling an exact invers second order high pass filter (infinit period) t0 = 1.0e12 h = 1.0 t0s = 1.0 / fcs f0_he2, f1_he2, f2_he2, g1_he2, g2_he2 = he2(t0/dt, t0s/dt, h, hs) data = rekfl(data, npts, f0_he2, f1_he2, f2_he2, g1_he2, g2_he2) data = politrend(npol, data, npts, z) x = data.copy() deconv = data.copy() # store deconvolves data np.savetxt('dispcal_vel.txt', deconv) # loop over fife trial values if no gap is given if gap > 0.0: onegap = True ngap = 1 else: #gap = 0.125 #onegap = False #ngap = 5 print 'parameter "gap" not specified!' sys.exit(1) for k in range(ngap): avglen = 6.0 * gap iab = int(gap / dt) iavg = int(avglen / dt) data = x z = np.ones(npts) P0 = np.zeros(npts) y = np.zeros(npts) ja = np.ones(99) # search for quiet section of minimum length 2*iab+1 samples P = krum(data, npts, 2*iab+1, P0) for j in range(npts): P[j] = np.log10(max(P[j], 1.0e-6)) P1 = P.copy() # import ipdb; ipdb.set_trace() z = heapsort(npts, P1) n50 = int(perc1 * npts / 100.0) n95 = int(perc2 * npts / 100.0) zlim = 0.5 * (z[n50] + z[n95]) P = P - zlim z = z - zlim # create trigger z = 0 if quiet, z = 1 if pulse for j in range(npts): if P[j] < 0: z[j] = 1.0 else: z[j] = 0.0 #zn1 = z[npts-1] #zn = z[n] #z[n-1] = -0.4 #z[n] = 1.4 #z[n-1] = zn1 #z[n] = zn data = politrend(npol, data, npts, z) data_c = data.copy() # cut out pulses quiet = data * z # identifiy pulses number = 0 i = 0 while i < npts and z[i] < 0.5: i = i + 1 n1 = i while i < npts and z[i] > 0.5: i = i + 1 n2 = i - 1 if i == npts: print 'No pulses found! Check dispcal.??? for pulses!' sys.exit(1) # continue if interval is too small (< gap) while n2 < n1 + iab: while i < npts and z[i] < 0.5: i = i + 1 n1 = i while i < npts and z[i] > 0.5: i = i + 1 n2 = i - 1 # now we have the first (n1) and the last (n2) sample of the first quiet interval if i == n: print 'No pulses found! Check dispcal.??? for pulses!' sys.exit(1) # now continue with the next pulses steps = [] marks = [] while i < npts: while i < npts and z[i] < 0.5: i = i + 1 if i == npts: break n3 = i while i < npts and z[i] > 0.5: i = i + 1 if i == npts: break n4 = i - 1 # continue if interval is too small (< gap) while n4 < n3 + iab: while i < npts and z[i] < 0.5: i = i + 1 if i == npts: break n3 = i while i < npts and z[i] > 0.5: i = i + 1 if i == npts: break n4 = i - 1 # now we have the first (n1) and the last (n2) sample of the next quiet interval number = number + 1 if number == 1: data_c = zspline('zsp', 1, n2, n3, npts, data_c, npts) n2null = n2 elif n4 >= n3+iab: data_c = zspline('zsp', n1, n2, n3, npts, data_c, npts) n3null = n3 marks.append((n2,n3-1)) print 'found pulse # ' + str(number) + ': from sample ' + str(n2) + ' to sample ' + str(n3 - 1) n1a = 0 n2a = n2 - n1 n3a = n3 - n1 n4a = n4 - n1 n1a = max(n1a, n2a-iavg) n4a = min(n4a, n3a+iavg) for ii in range(n4a): y[ii] = data[n1-1+ii] y_z = zspline('zsp', n1a, n2a, n3a, n4a, y, n4a) y_int = integrate(y_z, npts, dt) stp = step(y_int, n1a, n2a, n3a, n4a, n4a) n1 = n3 n2 = n4 steps.append(stp) dtr = trend('tre', 0, n2-n1+1, 0, 0, data_c[n1:], npts-n1) data2 = data_c.copy() for i in np.arange(n1, npts, 1): data2[i] = dtr[i-n1] y = data_c * z ymin = 0.0 ymax = 0.0 for i in np.arange(n2null+1, n3null-1,1): ymin = min(ymin,y[i]) ymax = max(ymax,y[i]) for i in range(n2null): y[i] = min(ymax, max(ymin, y[i])) for i in np.arange(n3null, npts, 1): y[i] = min(ymax, max(ymin, y[i])) np.savetxt('dispcal_res.txt', y) y_dis = integrate(data2, npts, dt) # remove offset from displacement offset = np.mean(y_dis) y_dis = y_dis - offset displ = y_dis.copy() np.savetxt('dispcal_dis.txt', displ) ############################################################## # Statistics total = sum(np.abs(steps)) avgs = total / number sigma = np.std(np.abs(steps)) print '' print '-------------------------------------------------------------' print 'Raw average step: ' + str(np.round(avgs,3)) + ' +/- ' + str(np.round(sigma, 3)) print 'Raw generator constant: ' + str(np.round((avgs * fac) * 1e6,3)) + ' +/- ' + str(np.round((sigma * fac) *1e6, 3)) + 'Vs/m' print '-------------------------------------------------------------' if number <= 2: return raw, deconv, displ, marks # import ipdb; ipdb.set_trace() ja = np.ones(len(steps)) for nrest in np.arange(number-1,int(float(number+1.0)/2.0),-1): siga = sigma kmax = np.argmax(steps) ja[kmax] = 0 total = 0 #for k in range(number): # total = total + ja[k] * steps[k] stepsa = ja * steps total = sum(np.abs(stepsa)) #print total avgs = total / nrest #print avgs total = 0 for k in range(number): total = total + ja[k] * (abs(steps[k]) - avgs)**2 sigma = np.sqrt(total / nrest) print 'Pulse ' + str(kmax) + ' eliminated; ' + str(nrest) + ' pulses remaning: ' + str(np.round((avgs * fac) * 1e6,3)) + ' +/- ' + str(np.round((sigma * fac) *1e6, 3)) + 'Vs/m' # if sigma < 0.05*avgs and siga-sigma < siga/ nrest: break steps[kmax] = 0.0 print '------------------------------------------------------------' print '' return raw, deconv, displ, marks
def tiltcal(data, samprate, fcs, hs, gap, volts, tilt, bfc=0.0, bm=0): dt = 1.0 / samprate npts = len(data) npol = 3 perc1 = 50 perc2 = 95 fac = volts / tilt * 0.001 # remove offset using the first 6 seconds that have to be quiet! z = np.ones(npts) offset = np.sum(data[0:int(6.0 * samprate)]) data = data - offset # apply butterworth low pass filter if required if bfc > 0.0 and bm > 0: bt0 = 1.0 / bfc mm = int(bm / 2.0) # if odd order apply first order low pass if bm > 2 * mm: f0_lp1, f1_lp1, f2_lp1, g1_lp1, g2_lp1 = lp1(bt0 * samprate) data = rekfl(data, npts, f0_lp1, f1_lp1, f2_lp1, g1_lp1, g2_lp1) # now apply second order low pass for i in range(mm): h = np.sin(np.pi / 2.0 * (2.0 * i - 1.0) / bm) f0_lp2, f1_lp2, f2_lp2, g1_lp2, g2_lp2 = lp2(bt0 * samprate, h) data = rekfl(data, npts, f0_lp2, f1_lp2, f2_lp2, g1_lp2, g2_lp2) # report filtering print 'Input data filtered with low pass Butterworth filter:' print ' corner frequency: ' + str(bfc) + 'Hz' print ' order: ' + str(bm) + '.' raw = data.copy() # deconvolution to ground acceleration # done by appling an exact invers second order high pass filter (infinit period) t0 = 1.0e12 h = 1.0 t0s = 1.0 / fcs f0_he2, f1_he2, f2_he2, g1_he2, g2_he2 = he2(t0 / dt, t0s / dt, h, hs) data = rekfl(data, npts, f0_he2, f1_he2, f2_he2, g1_he2, g2_he2) data = politrend(npol, data, npts, z) x = data.copy() deconv_vel = data.copy() np.savetxt('tiltcal_vel.txt', deconv_vel) # differentiate to get ground acceleration data_diff = differentiate(data, npts, dt, 1) #np.savetxt('diff_test', data_diff) # loop over fife trial values if no gap is given if gap > 0.0: onegap = True ngap = 1 else: gap = 0.125 onegap = False ngap = 5 for k in range(ngap): avglen = 6.0 * gap iab = int(gap / dt) iavg = int(avglen / dt) data = x z = np.ones(npts) P0 = np.zeros(npts) y = np.zeros(npts) ja = np.ones(99) # search for quiet section of minimum length 2*iab+1 samples P = krum(data, npts, 2 * iab + 1, P0) for j in range(npts): P[j] = np.log10(max(P[j], 1.0e-6)) P1 = P.copy() # import ipdb; ipdb.set_trace() z = heapsort(npts, P1) n50 = int(perc1 * npts / 100.0) n95 = int(perc2 * npts / 100.0) zlim = 0.5 * (z[n50] + z[n95]) P = P - zlim z = z - zlim # create trigger z = 0 if quiet, z = 1 if pulse for j in range(npts): if P[j] < 0: z[j] = 1.0 else: z[j] = 0.0 #zn1 = z[npts-1] #zn = z[n] #z[n-1] = -0.4 #z[n] = 1.4 #z[n-1] = zn1 #z[n] = zn mpol = npol - 2 if mpol < 1: print 'npol too small!' sys.exit(1) # compute residual signal data2 = data_diff.copy() quiet = differentiate(data2, npts, dt, 0) quiet = quiet * z res, a = politrendTilt(npol, quiet, npts, z) res = res * z res_int = integrate(res, npts, dt) np.savetxt('tiltcal_res.txt', res_int) # final trend removal on acceleration signal xpolint = 0.0 xavg = 0.0 for i in range(npts): xpol = a[mpol] for j in np.arange(mpol - 1, 0, -1): xpol = xpol * (float(i + 1) / fnh - 1.0) + a[j] xpolint = xpolint + xpol * dt data_diff[i] = data_diff[i] - xpolint xavg = xavg + data_diff[i] xavg = xavg / npts for i in range(npts): data_diff[i] = data_diff[i] - xavg acc = data_diff.copy() np.savetxt('tiltcal_acc.txt', acc) data_c = data_diff.copy() # identifiy pulses number = 0 i = 0 while i < npts and z[i] < 0.5: i = i + 1 n1 = i while i < npts and z[i] > 0.5: i = i + 1 n2 = i - 1 if i == npts: print 'No pulses found! Check dispcal.??? for pulses!' sys.exit(1) # continue if interval is too small (< gap) while n2 < n1 + iab: while i < npts and z[i] < 0.5: i = i + 1 n1 = i while i < npts and z[i] > 0.5: i = i + 1 n2 = i - 1 # now we have the first (n1) and the last (n2) sample of the first quiet interval if i == n: print 'No pulses found! Check dispcal.??? for pulses!' sys.exit(1) # now continue with the next pulses steps = [] marks = [] while i < npts: while i < npts and z[i] < 0.5: i = i + 1 if i == npts: break n3 = i while i < npts and z[i] > 0.5: i = i + 1 if i == npts: break n4 = i - 1 # continue if interval is too small (< gap) while n4 < n3 + iab: while i < npts and z[i] < 0.5: i = i + 1 if i == npts: break n3 = i while i < npts and z[i] > 0.5: i = i + 1 if i == npts: break n4 = i - 1 # now we have the first (n1) and the last (n2) sample of the next quiet interval number = number + 1 #if number == 1: # data_c = zspline('zsp', 1, n2, n3, npts, data_c, npts) # n2null = n2 #elif n4 >= n3+iab: # #print 'bin da!' # data_c = zspline('zsp', n1, n2, n3, npts, data_c, npts) #n3null = n3 marks.append((n2, n3 - 1)) print 'found pulse # ' + str(number) + ': from sample ' + str( n2) + ' to sample ' + str(n3 - 1) n1a = 0 n2a = n2 - n1 n3a = n3 - n1 n4a = n4 - n1 n1a = max(n1a, n2a - iavg) n4a = min(n4a, n3a + iavg) for ii in range(n4a): y[ii] = data_diff[n1 - 1 + ii] #print n1a, n2a, n3a, n4a y_m = mspline('msp', n1a, n2a, n3a, n4a, y, n4a) #y_int = integrate(y_z, npts, dt) #y_int = cumtrapz(y_z) * dt stp = step(y_m, n1a, n2a, n3a, n4a, n4a) n1 = n3 n2 = n4 steps.append(stp) #np.savetxt('y_z'+str(number), y_z) #np.savetxt('y_int'+str(number), y_int) #print steps #dtr = trend('tre', 0, n2-n1+1, 0, 0, data_c[n1:], npts-n1) #for i in np.arange(n1, npts, 1): # data_c[i] = dtr[i-n1] # #y = data_c * z #ymin = 0.0 #ymax = 0.0 #for i in np.arange(n2null+1, n3null-1,1): # ymin = min(ymin,y[i]) # ymax = max(ymax,y[i]) #for i in range(n2null): # y[i] = min(ymax, max(ymin, y[i])) #for i in np.arange(n3null, npts, 1): # y[i] = min(ymax, max(ymin, y[i])) # # #y_dis = integrate(data_c, npts, dt) # remove offset from displacement #offset = np.mean(y_dis) #y_dis = y_dis - offset #displ = y_dis.copy() ############################################################## # Statistics total = sum(np.abs(steps)) avgs = total / number sigma = np.std(np.abs(steps)) print '' print '-------------------------------------------------------------' print 'Raw average step: ' + str(np.round(avgs, 3)) + ' +/- ' + str( np.round(sigma, 3)) print 'Raw generator constant: ' + str(np.round( (avgs * fac) * 1e6, 3)) + ' +/- ' + str( np.round((sigma * fac) * 1e6, 3)) + 'Vs/m' print '-------------------------------------------------------------' if number <= 2: return raw, deconv, displ, marks # import ipdb; ipdb.set_trace() ja = np.ones(len(steps)) for nrest in np.arange(number - 1, int(float(number + 1.0) / 2.0), -1): siga = sigma kmax = np.argmax(steps) ja[kmax] = 0 total = 0 #for k in range(number): # total = total + ja[k] * steps[k] stepsa = ja * steps total = sum(np.abs(stepsa)) #print total avgs = total / nrest #print avgs total = 0 for k in range(number): total = total + ja[k] * (abs(steps[k]) - avgs)**2 sigma = np.sqrt(total / nrest) print 'Pulse ' + str(kmax) + ' eliminated; ' + str( nrest) + ' pulses remaning: ' + str( np.round((avgs * fac) * 1e6, 3)) + ' +/- ' + str( np.round((sigma * fac) * 1e6, 3)) + 'Vs/m' # if sigma < 0.05*avgs and siga-sigma < siga/ nrest: break steps[kmax] = 0.0 print '------------------------------------------------------------' print '' gap = gap * 2.0 return raw, deconv_vel, acc, marks