def calculate_corner_periods(periods, ground_motion, magnitude): """ periods - 1D array, dimension # of periods ground_motion - XD array, with last dimension periods. magnitude - 1D array, dimension # of events from Newmark and Hall 1982 returns TAV,TVD - the acceleration and velocity dependent corner periods TAV and TVD have the same dimensions as ground_motion, except the last axis (periods) is dropped. """ #reference_periods = 0.3,1.0 S03=interp(array(0.3),ground_motion,periods,axis=-1) S10=interp(array(1.0),ground_motion,periods,axis=-1) #print 'S03',S03[:,0:5] #print 'S10',S10[:,0:5] # interpolate the ground motion at reference periods acceleration_dependent=(S10/S03) acceleration_dependent[where(S03<0.00000000000001)]=0.0 acceleration_dependent=acceleration_dependent[...,0] # and collapse # This assumes ground_motion.shape = (1, events) velocity_dependent=(10**((magnitude-5.0)/2))[newaxis,:] assert len(acceleration_dependent.shape)==2 assert len(velocity_dependent.shape)==2 # removed this assert so test_cadell_damage passes. # This test passes 4660 sites, instead of the usual 1. # Fixing/ getting rid of the test is another option... #assert velocity_dependent.shape == acceleration_dependent.shape return acceleration_dependent, velocity_dependent
def get_dragon_type_for_potion(item): rand = random.randint(1, 20) item['xplo'] = interp(item['xplo'], item['xphi'], rand, 20) item['gplo'] = interp(item['gplo'], item['gphi'], rand, 20) if rand <= 2: item['name'] = item['name'] + " (white)" elif rand <= 4: item['name'] = item['name'] + " (black)" elif rand <= 7: item['name'] = item['name'] + " (green)" elif rand <= 9: item['name'] = item['name'] + " (blue)" elif rand <= 10: item['name'] = item['name'] + " (red)" elif rand <= 12: item['name'] = item['name'] + " (brass)" elif rand <= 14: item['name'] = item['name'] + " (copper)" elif rand <= 15: item['name'] = item['name'] + " (bronze)" elif rand <= 16: item['name'] = item['name'] + " (silver)" elif rand <= 17: item['xplo'] = item['xphi'] item['gplo'] = item['gphi'] item['name'] = item['name'] + " (gold)" elif rand <= 19: item['xplo'] = item['xphi'] item['gplo'] = item['gphi'] item['name'] = item['name'] + " (evil)" elif rand <= 20: item['xplo'] = item['xphi'] item['gplo'] = item['gphi'] item['name'] = item['name'] + " (good)"
def undamped_response(SA,periods,atten_override_RSA_shape=None, atten_cutoff_max_spectral_displacement=False, loss_min_pga=0.0, magnitude=None): """ Calculate SD from SA """ if atten_override_RSA_shape is None: pass elif atten_override_RSA_shape == 'Aust_standard_Sa': from eqrm_code.ground_motion_misc import Australian_standard_model SA=SA[:,:,0:1]*Australian_standard_model(periods[newaxis,newaxis,:]) elif atten_override_RSA_shape == 'HAZUS_Sa': #reference_periods = 0.3,1.0 S03=interp(array(0.3),SA,periods,axis=-1) S10=interp(array(1.0),SA,periods,axis=-1) # interpolate the ground motion at reference periods acceleration_dependent=(S10/S03) acceleration_dependent[where(S03<0.00000000000001)]=0.0 acceleration_dependent=acceleration_dependent[:,:,0] # and collapse velocity_dependent=(10**((magnitude-5.0)/2))[newaxis,:] Tm = periods[newaxis,newaxis,:] S03M = S03 S10M = S10 TavM = acceleration_dependent[:,:,newaxis] TvdM = velocity_dependent[:,:,newaxis] # set up Boolean arrays for the three regions # (accel, vel, disp, sensitive) bA = (Tm < TavM) bV = (Tm >= TavM) & (Tm <= TvdM) bD = (Tm > TvdM) SA=(S03M*bA) SA[where(bV)]=(S10M/Tm)[where(bV)] SA[where(bD)]=((S10M*TvdM)/(Tm**2))[where(bD)] #SA = (S03M*bA) + (S10M/Tm)*bV + ((S10M*TvdM)/(Tm**2))*bD else: print 'atten_override_RSA_shape = ',atten_override_RSA_shape raise NotImplementedError('atten_override_RSA_shape = '+str(atten_override_RSA_shape)) too_low=SA[:,:,0:1]<loss_min_pga scaling_factor=where(too_low,0,1) SA=SA*scaling_factor # calculate surface displacement: #surface_displacement~=(250*(periods**2))*SA #dimension=1e3*9.8 # convert from g forces to m/s^2, and m to mm # dimension/(4*pi**2) = 248.236899924 surface_displacement=((248.236899924)*(periods**2))*SA if atten_cutoff_max_spectral_displacement is True: surface_displacement=cutoff_after_max(surface_displacement,periods) return SA,surface_displacement
def _forward(self, input): if self.shift is not None: coord = self.coord + self.shift else: coord = self.coord real = interp.interp(self.table, coord, tf.real(input)) with tf.control_dependencies([real]): imag = interp.interp(self.table, coord, tf.imag(input)) return tf.reshape(tf.complex(real, imag), self.oshape)
def get_medallion_type(item): rand = random.randint(1, 20) item['xplo'] = interp(item['xplo'], item['xphi'], rand, 100) item['gplo'] = interp(item['gplo'], item['gphi'], rand, 100) if rand <= 15: item['name'] = item['name'] + " (30')" elif rand <= 18: item['name'] = item['name'] + " (30'+ empathy)" elif rand <= 19: item['name'] = item['name'] + " (60')" elif rand <= 20: item['name'] = item['name'] + " (90')"
def test_interp_no_extrapolate_low(self): functx = asarray([1,2]) functy = asarray([10,20]) x = asarray([1.3,1.5,1.7]) y = interp(x, functy, functx, extrapolate_low=False) y_ans = x * 10.0 self.assert_(allclose(y, y_ans, rtol=0.05)) x = asarray([0.5,1.5,2.5]) y = interp(x, functy, functx, extrapolate_low=False) y_ans = x * 10.0 self.assert_(allclose(y, [10.,15.,25.], rtol=0.05))
def test_interp_no_extrapolate_low_bad_ordering(self): functx = asarray([2, 1, 0.8]) functy = asarray([20, 10, 8]) x = asarray([1.3,1.5,1.7]) y = interp(x, functy, functx, extrapolate_low=False) y_ans = x * 10.0 self.assert_(allclose(y, y_ans, rtol=0.05)) x = asarray([0.5,1.5,2.5]) y = interp(x, functy, functx, extrapolate_low=False) y_ans = x * 10.0 self.assert_(allclose(y, [8.,15.,25.], rtol=0.05))
def test_interp(self): functx = asarray([1,2]) functy = asarray([10,20]) x = asarray([0.5,1.5,2.5]) y = interp(x, functy, functx) y_ans = x * 10.0 self.assert_(allclose(y, y_ans, rtol=0.05))
def get_misc_girdle_type(item): rand = random.randint(1, 100) item['xplo'] = interp(item['xplo'], item['xphi'], rand, 100) item['gplo'] = interp(item['gplo'], item['gphi'], rand, 100) if rand <= 30: item['name'] = item['name'] + ", hill" elif rand <= 50: item['name'] = item['name'] + ", stone" elif rand <= 70: item['name'] = item['name'] + ", frost" elif rand <= 85: item['name'] = item['name'] + ", fire" elif rand <= 95: item['name'] = item['name'] + ", cloud" elif rand <= 100: item['name'] = item['name'] + ", storm"
def get_token_type(item): rand = random.randint(1, 20) if rand <= 4: item['name'] = item['name'] + ", anchor" elif rand <= 7: item['name'] = item['name'] + ", bird" elif rand <= 10: item['name'] = item['name'] + ", fan" elif rand <= 13: item['name'] = item['name'] + ", swan boat" elif rand <= 18: item['name'] = item['name'] + ", tree" elif rand <= 20: item['name'] = item['name'] + ", whip" item['xplo'] = interp(item['xplo'], item['xphi'], rand, 20) item['gplo'] = interp(item['gplo'], item['gphi'], rand, 20)
def get_giant_strength_for_potion(item): rand = random.randint(1, 20) item['xplo'] = interp(item['xplo'], item['xphi'], rand, 20) item['gplo'] = interp(item['gplo'], item['gphi'], rand, 20) if rand <= 6: item['name'] = item['name'] + " (hill)" elif rand <= 10: item['name'] = item['name'] + " (stone)" elif rand <= 14: item['name'] = item['name'] + " (frost)" elif rand <= 17: item['name'] = item['name'] + " (fire)" elif rand <= 19: item['name'] = item['name'] + " (cloud)" elif rand == 20: item['name'] = item['name'] + " (storm)"
def test_interp_no_extrapolate_high_local_max(self): functx = asarray([2, 1, 3]) functy = asarray([30, 10, 20]) x = asarray([0.5, 1.5, 2.5, 3.0, 4.0]) y = interp(x, functy, functx, extrapolate_high=False) #print "y", y self.assert_(allclose(y, [0., 20., 25., 20., 20.], rtol=0.05))
def set_ring_subtype(item, rand=None): if not rand: rand = random.randint(1, 100) item['xplo'] = interp(item['xplo'], item['xphi'], rand, 100) item['gplo'] = interp(item['gplo'], item['gphi'], rand, 100) if rand <= 70: item['name'] = item['name'] + " +1" elif rand <= 82: item['name'] = item['name'] + " +2" elif rand <= 83: item['name'] = item['name'] + " +2 (5' radius)" elif rand <= 90: item['name'] = item['name'] + " +3" elif rand <= 91: item['name'] = item['name'] + " +3 (5' radius)" elif rand <= 97: item['name'] = item['name'] + " +4 AC, +2 saves" else: item['name'] = item['name'] + " +6 AC, +1 saves"
def main( argv ): """ Script execution entry point @param argv Arguments passed to the script @return Exit code (0 = success) """ # imports when using this as a script import argparse # create and configure an argument parser parser = argparse.ArgumentParser( description = 'Lester', add_help = False ) parser.add_argument( '-h', '--help', default = False, help = 'Display this help message and exit.', action = 'help' ) parser.add_argument( '-v', '--version', default = False, help = 'Display script version and exit.', action = 'version', version = __version__ ) # parse the arguments args = parser.parse_args( argv[ 1 : ] ) # check args.* for script execution here print 'Lester ' + __version__ print ' type "exit" to return to shell' lirp = interp.interp() lirp.run( sys.stdin, sys.stdout, interactive = True ) # return success return 0
def main(argv): """ Script execution entry point @param argv Arguments passed to the script @return Exit code (0 = success) """ # imports when using this as a script import argparse # create and configure an argument parser parser = argparse.ArgumentParser(description='Lester', add_help=False) parser.add_argument('-h', '--help', default=False, help='Display this help message and exit.', action='help') parser.add_argument('-v', '--version', default=False, help='Display script version and exit.', action='version', version=__version__) # parse the arguments args = parser.parse_args(argv[1:]) # check args.* for script execution here print 'Lester ' + __version__ print ' type "exit" to return to shell' lirp = interp.interp() lirp.run(sys.stdin, sys.stdout, interactive=True) # return success return 0
from Environment import default_environment from Tokenize import read_tokens, create_tokens from interp import interp, return_quoted_text if __name__=='__main__': env = default_environment() while True: lisp = raw_input("PyLisp>> ") if (lisp.lower() == 'exit' or lisp.lower() == 'exit()'): break elif lisp.replace(" ","") == '': continue lisp_tokens = read_tokens(create_tokens(lisp)) lisp_interpreted = interp(lisp_tokens,env) if lisp_interpreted: print lisp_interpreted
self.extIds = {} # Since we call getExpr with no left, must start with a noLeft op, presumably !!SOF def compiler(toks): doMCTcmd('operator "A.AstTuple" ["!!defaultOperand"]', None) doMCTcmd('operator "None" ["!!SOF"] ["!!EOF"]', None) doMCTcmd('operator "None" ["!!SOF"] () ["!!EOF"]', None) #opCtx = OpCtx(upOpCtx=None,indx=0,altOpInfos=[]) e, toks = getExpr(toks=toks, left=None, prio=None, opCtx=None, noneOK=False) c = A.AstClosure(e) c.fixUp(parent=None, closure=FakeAstClosure(I.builtins), upChain=()) # will fixup e as well return c import sys if __name__ == "__main__": import lexer global ast global debug debug = len(sys.argv) > 2 ast = compiler(L.lexer(sys.argv[1])) #for l in ast.pp(1): print(l) print(I.interp(ast, debug).pp())
import numpy as np from interp import interpolation as interp # Define start and end point and the number of points in the function (n) and in the interpolation (N) n = 50 N = 100 start = 0 end = 4 * np.pi # Make input -- as an example, the cosine function is used. x = np.linspace(start, end, n) y = np.cos(x) z = np.linspace(start, end, N) y_dev = -np.sin(x) y_int = np.sin(x) # Initialize the class i_cos = interp(x, y) # Interpolate s_qspl, s_qsplint, s_qspldev = i_cos.qspline(z) # Print the values in order to save the stdout for i in range(N): if i < n: print('%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s' % (z[i], s_qspl[i], s_qsplint[i], s_qspldev[i], x[i], y[i], y_int[i], y_dev[i])) else: print('%s\t%s\t%s\t%s' % (z[i], s_qspl[i], s_qsplint[i], s_qspldev[i]))
def main(dem, mesh_f, mesh_i): f = interp(dem) interp_mesh(mesh_f, mesh_i, f)
def Parameter_reader(profile_name, geomfile, q_scale, manual_ped, mid_ped0, plot, output_csv): n0 = 1. mref = 2. # mass of ion in proton mass if profile_type == "ITERDB": rhot0, rhop0, te0, ti0, ne0, ni0, nz0, vrot0 = read_profile_file( profile_type, profile_name, geomfile_name, suffix) else: rhot0, rhop0, te0, ti0, ne0, ni0, vrot0 = read_profile_file( profile_type, profile_name, geomfile_name, suffix) if geomfile_type == "gfile": xgrid, q = read_geom_file(geomfile_type, geomfile_name, suffix) elif geomfile_type == "GENE_tracor": xgrid, q, Lref, Bref, x0_from_para = read_geom_file( geomfile_type, geomfile_name, suffix) q = q * q_scale if geomfile_type == "GENE_tracor" and profile_type != "profile": rhot0_range_min = np.argmin(abs(rhot0 - xgrid[0])) rhot0_range_max = np.argmin(abs(rhot0 - xgrid[-1])) rhot0 = rhot0[rhot0_range_min:rhot0_range_max] rhop0 = rhop0[rhot0_range_min:rhot0_range_max] te0 = te0[rhot0_range_min:rhot0_range_max] ti0 = ti0[rhot0_range_min:rhot0_range_max] ne0 = ne0[rhot0_range_min:rhot0_range_max] ni0 = ni0[rhot0_range_min:rhot0_range_max] vrot0 = vrot0[rhot0_range_min:rhot0_range_max] uni_rhot = np.linspace(min(rhot0), max(rhot0), len(rhot0) * 10.) te_u = interp(rhot0, te0, uni_rhot) ne_u = interp(rhot0, ne0, uni_rhot) ni_u = interp(rhot0, ni0, uni_rhot) #nz_u = interp(rhot0,nz0,uni_rhot) vrot_u = interp(rhot0, vrot0, uni_rhot) q = interp(xgrid, q, uni_rhot) tprime_e = -fd_d1_o4(te_u, uni_rhot) / te_u nprime_e = -fd_d1_o4(ne_u, uni_rhot) / ne_u qprime = fd_d1_o4(q, uni_rhot) / q #center_index = np.argmax((tprime_e*te_u+nprime_e*ne_u)[0:int(len(tprime_e)*0.99)]) if manual_ped == 1: x0_center = mid_ped0 else: if geomfile_type == "gfile": midped, topped = find_pedestal(file_name=geomfile_name, path_name='', plot=False) elif geomfile_type == "GENE_tracor": midped = x0_from_para x0_center = midped print('mid pedestal is at r/a = ' + str(x0_center)) if geomfile_type == "gfile": Lref, Bref, R_major, q0, shat0 = get_geom_pars(geomfile_name, x0_center) print("Lref=" + str(Lref)) print("x0_center=" + str(x0_center)) index_begin = np.argmin(abs(uni_rhot - x0_center + 2 * (1. - x0_center))) te_u = te_u[index_begin:len(uni_rhot) - 1] ne_u = ne_u[index_begin:len(uni_rhot) - 1] ni_u = ni_u[index_begin:len(uni_rhot) - 1] vrot_u = vrot_u[index_begin:len(uni_rhot) - 1] q = q[index_begin:len(uni_rhot) - 1] tprime_e = tprime_e[index_begin:len(uni_rhot) - 1] nprime_e = nprime_e[index_begin:len(uni_rhot) - 1] qprime = qprime[index_begin:len(uni_rhot) - 1] uni_rhot = uni_rhot[index_begin:len(uni_rhot) - 1] Lt = 1. / tprime_e Ln = 1. / nprime_e Lq = 1. / qprime center_index = np.argmin(abs(uni_rhot - x0_center)) q0 = q[center_index] ne = ne_u / (10.**19.) # in 10^19 /m^3 ni = ni_u / (10.**19.) # in 10^19 /m^3 te = te_u / 1000. #in keV m_SI = mref * 1.6726 * 10**(-27) me_SI = 9.11 * 10**(-31) c = 1. qref = 1.6 * 10**(-19) #refes to GENE manual coll_c = 2.3031 * 10**(-5) * Lref * ne / (te)**2 * ( 24 - np.log(np.sqrt(ne * 10**13) / (te * 1000))) coll_ei = 4 * (ni / ne) * coll_c * np.sqrt( te * 1000. * qref / me_SI) / Lref nuei = coll_ei beta = 403. * 10**(-5) * ne * te / Bref**2. nref = ne_u[center_index] te_mid = te_u[center_index] Tref = te_u[center_index] * qref cref = np.sqrt(Tref / m_SI) Omegaref = qref * Bref / m_SI / c rhoref = cref / Omegaref kymin = n0 * q0 * rhoref / (Lref * x0_center) kyGENE = kymin * (q / q0) * np.sqrt(te_u / te_mid) * ( x0_center / uni_rhot) #Add the effect of the q varying #from mtm_doppler omMTM = kyGENE * (tprime_e + nprime_e) gyroFreq = 9.79E3 / np.sqrt(mref) * np.sqrt(te_u) / Lref mtmFreq = omMTM * gyroFreq / (2. * np.pi * 1000.) omegaDoppler = abs(vrot_u * n0 / (2. * np.pi * 1000.)) omega = mtmFreq + omegaDoppler omega_n_GENE = kyGENE * (nprime_e) #in cs/a omega_n = omega_n_GENE * gyroFreq / (2. * np.pi * 1000.) #in kHz zeff = (ni + nz * Z**2.) * (1. / ni) coll_ei = coll_ei / (1000.) #in kHz shat = Ln / Lq eta = Ln / Lt ky = kyGENE nu = (coll_ei) / (omega_n) nuei = nu * omega_n_GENE / omega_n mean_rho, xstar = omega_gaussian_fit(uni_rhot, mtmFreq, rhoref, Lref, plot) if plot == True: plt.clf() plt.plot(uni_rhot, nuei, label='nuei(cs/a)') plt.plot(uni_rhot, nuei * 2. * np.pi, label='nuei(cs/a)*2 pi') plt.plot(uni_rhot, nuei * zeff, label='nuei(cs/a)*2 pi') plt.legend() plt.title('nuei') plt.axvline(0.96, color='red', alpha=1.) plt.show() plt.clf() plt.xlabel('r/a') plt.ylabel('eta') plt.plot(uni_rhot, eta, label='eta') plt.show() plt.clf() #plt.title('mode number finder') plt.xlabel('r/a') plt.ylabel('omega*(Lab), kHz') plt.plot(uni_rhot, omega, label='omega*(Lab)') plt.show() plt.clf() plt.xlabel('r/a') plt.ylabel('eta') plt.plot(uni_rhot, eta, label='eta') plt.show() plt.clf() plt.xlabel('r/a') plt.ylabel('shat') plt.plot(uni_rhot, shat, label='shat') plt.show() plt.clf() plt.xlabel('r/a') plt.ylabel('beta') plt.plot(uni_rhot, beta, label='beta') plt.show() plt.clf() plt.xlabel('r/a') plt.ylabel('ky rhoi') plt.plot(uni_rhot, ky, label='ky') plt.show() if output_csv == True: with open('profile_output.csv', 'w') as csvfile: data = csv.writer(csvfile, delimiter=',') data.writerow([ 'x/a', 'nu_ei(kHz)', 'omega*n(kHz)', 'omega* plasma(kHz)', 'Doppler shift(kHz)', 'nu/omega*n', 'eta', 'shat', 'beta', 'ky rhoi(for n=1)' ]) for i in range(len(uni_rhot)): data.writerow([ uni_rhot[i], coll_ei[i], omega_n[i], mtmFreq[i], omegaDoppler[i], nu[i], eta[i], shat[i], beta[i], ky[i] ]) csvfile.close() return uni_rhot, nu, eta, shat, beta, ky, q, mtmFreq, omegaDoppler, omega_n, omega_n_GENE, xstar, Lref, rhoref
from parser import token_list, get_env, parse from interp import interp if __name__ == "__main__": #take in input as string input_str = "[hello,there]\nCOND\nCASE 0 > 1\nPRINT yes\nCASE 0 < 1\nPRINT no\nCONDEND" #seperate program into individual lines splt_line_lst = token_list(input_str) #get env from first line env = get_env(splt_line_lst) #fill_env(env) #parse program ast = parse(splt_line_lst) #interp ast with given env interp(ast, env)
def Parameter_reader(path, profile_name, geomfile, q_scale, manual_ped, mid_ped0, plot, output_csv): n0 = 1. mref = 2. # mass of ion in proton mass if profile_type == "ITERDB": rhot0, rhop0, te0, ti0, ne0, ni0, nz0, vrot0 = read_profile_file( profile_type, path + '/' + profile_name, path + '/' + geomfile_name, suffix) elif profile_type == "pfile": rhot0, rhop0, te0, ti0, ne0, ni0, nz0, vrot0 = read_profile_file( profile_type, path + '/' + profile_name, path + '/' + geomfile_name, suffix) if geomfile_type == "gfile": xgrid, q, R_ref = read_geom_file(geomfile_type, path + '/' + geomfile_name, suffix) elif geomfile_type == "GENE_tracor": xgrid, q, Lref, R_ref, Bref, x0_from_para = read_geom_file( geomfile_type, path + '/' + geomfile_name, suffix) q = q * q_scale if geomfile_type == "GENE_tracor" and profile_type != "profile": rhot0_range_min = np.argmin(abs(rhot0 - xgrid[0])) rhot0_range_max = np.argmin(abs(rhot0 - xgrid[-1])) rhot0 = rhot0[rhot0_range_min:rhot0_range_max] rhop0 = rhop0[rhot0_range_min:rhot0_range_max] te0 = te0[rhot0_range_min:rhot0_range_max] ti0 = ti0[rhot0_range_min:rhot0_range_max] ne0 = ne0[rhot0_range_min:rhot0_range_max] ni0 = ni0[rhot0_range_min:rhot0_range_max] nz0 = nz0[rhot0_range_min:rhot0_range_max] vrot0 = vrot0[rhot0_range_min:rhot0_range_max] uni_rhot = np.linspace(min(rhot0), max(rhot0), len(rhot0) * 10) te_u = interp(rhot0, te0, uni_rhot) ne_u = interp(rhot0, ne0, uni_rhot) ni_u = interp(rhot0, ni0, uni_rhot) print(str((len(rhot0), len(nz0), len(uni_rhot)))) nz_u = interp(rhot0, nz0, uni_rhot) vrot_u = interp(rhot0, vrot0, uni_rhot) q = interp(xgrid, q, uni_rhot) tprime_e = -fd_d1_o4(te_u, uni_rhot) / te_u nprime_e = -fd_d1_o4(ne_u, uni_rhot) / ne_u qprime = fd_d1_o4(q, uni_rhot) / q #center_index = np.argmax((tprime_e*te_u+nprime_e*ne_u)[0:int(len(tprime_e)*0.99)]) if manual_ped == 1: x0_center = mid_ped0 else: if geomfile_type == "gfile": midped, topped = find_pedestal(file_name=path + '/' + geomfile_name, path_name='', plot=False) elif geomfile_type == "GENE_tracor": midped = x0_from_para x0_center = midped print('mid pedestal is at r/a = ' + str(x0_center)) if geomfile_type == "gfile": Lref, Bref, R_major, q0, shat0 = get_geom_pars( path + '/' + geomfile_name, x0_center) print("Lref=" + str(Lref)) print("x0_center=" + str(x0_center)) index_begin = np.argmin(abs(uni_rhot - x0_center + 2 * (1. - x0_center))) te_u = te_u[index_begin:len(uni_rhot) - 1] ne_u = ne_u[index_begin:len(uni_rhot) - 1] ni_u = ni_u[index_begin:len(uni_rhot) - 1] nz_u = nz_u[index_begin:len(uni_rhot) - 1] vrot_u = vrot_u[index_begin:len(uni_rhot) - 1] q = q[index_begin:len(uni_rhot) - 1] tprime_e = tprime_e[index_begin:len(uni_rhot) - 1] nprime_e = nprime_e[index_begin:len(uni_rhot) - 1] qprime = qprime[index_begin:len(uni_rhot) - 1] uni_rhot = uni_rhot[index_begin:len(uni_rhot) - 1] Lt = 1. / tprime_e Ln = 1. / nprime_e center_index = np.argmin(abs(uni_rhot - x0_center)) q0 = q[center_index] ne = ne_u / (10.**19.) # in 10^19 /m^3 ni = ni_u / (10.**19.) # in 10^19 /m^3 nz = nz_u / (10.**19.) # in 10^19 /m^3 te = te_u / 1000. #in keV m_SI = mref * 1.6726 * 10**(-27) me_SI = 9.11 * 10**(-31) c = 1. qref = 1.6 * 10**(-19) #refes to GENE manual coll_c = 2.3031 * 10**(-5) * Lref * ne / (te)**2 * ( 24 - np.log(np.sqrt(ne * 10**13) / (te * 1000))) coll_ei = 4. * coll_c * np.sqrt(te * 1000. * qref / me_SI) / Lref nuei = coll_ei beta = 403. * 10**(-5) * ne * te / Bref**2. nref = ne_u[center_index] te_mid = te_u[center_index] Tref = te_u[center_index] * qref cref = np.sqrt(Tref / m_SI) Omegaref = qref * Bref / m_SI / c rhoref = cref / Omegaref rhoref_temp = rhoref * np.sqrt(te_u / te_mid) kymin = n0 * q0 * rhoref / (Lref * x0_center) kyGENE = kymin * (q / q0) * np.sqrt(te_u / te_mid) * ( x0_center / uni_rhot) #Add the effect of the q varying #from mtm_doppler omMTM = kyGENE * (tprime_e + nprime_e) gyroFreq = 9.79E3 / np.sqrt(mref) * np.sqrt(te_u) / Lref mtmFreq = omMTM * gyroFreq / (2. * np.pi * 1000.) omegaDoppler = abs(vrot_u * n0 / (2. * np.pi * 1000.)) omega = mtmFreq + omegaDoppler global zeff zeff = ((ni + Z**2 * nz) / ne)[center_index] if zeff_manual != False: zeff = zeff_manual print('********zeff*********') print('zeff=' + str(zeff)) print('********zeff*********') omega_n_GENE = kyGENE * (nprime_e) #in cs/a print("*******************") print("*******************") print(np.max(omega_n_GENE)) print("*******************") print("*******************") omega_n = omega_n_GENE * gyroFreq / (2. * np.pi * 1000.) #in kHz #coll_ei=coll_ei/(1000.) #in kHz coll_ei = coll_ei / (2. * np.pi * 1000.) #in kHz Lq = 1. / (Lref / (R_ref * q) * qprime) shat = Ln / Lq eta = Ln / Lt ky = kyGENE * np.sqrt(2.) nu = (coll_ei) / (np.max(omega_n)) nuei = nu * omega_n_GENE / omega_n if plot == True: if profile_type == "ITERDB0": plt.clf() plt.plot(uni_rhot, nuei, label='nuei(cs/a)') plt.plot(uni_rhot, nuei * 2. * np.pi, label='nuei(cs/a)*2 pi') plt.plot(uni_rhot, nuei * zeff, label='nuei*zeff') plt.legend() plt.title('nuei') plt.axvline(0.96, color='red', alpha=1.) plt.show() index = np.argmin( abs(float(input("Enter location of interest:\n")) - uni_rhot)) print('zeff(x/r=' + str(uni_rhot[index]) + ')=' + str(zeff[index])) #print('id(x/r='+str(rho)+')='+str(id[index])) print('nuei*zeff(x/r=' + str(uni_rhot[index]) + ')=' + str((nuei * zeff)[index])) print('nuei*2 pi(x/r=' + str(uni_rhot[index]) + ')=' + str((nuei * 2. * np.pi)[index])) plt.clf() plt.xlabel('r/a') plt.ylabel('nuei(kHZ)') plt.plot(uni_rhot, nu * np.max(omega_n), label='coll') plt.show() d = {'uni_rhot': uni_rhot, 'nu*np.max(omega_n)': nu * np.max(omega_n)} df = pd.DataFrame(d, columns=['uni_rhot', 'nu*np.max(omega_n)']) df.to_csv('0nu_ei_smooth.csv', index=False) plt.clf() #plt.title('mode number finder') plt.xlabel('r/a') plt.ylabel('omega*, kHz') plt.plot(uni_rhot, mtmFreq, label='omega*p') plt.plot(uni_rhot, omega_n, label='omega*n') plt.axvline(uni_rhot[np.argmax(mtmFreq)], color='red', alpha=1., label='peak of omega*p') plt.axvline(uni_rhot[np.argmax(omega_n)], color='green', alpha=1., label='peak of omega*n') plt.plot(uni_rhot, rhoref_temp, color='purple', label='rhoref') plt.legend() plt.show() print("rho i for peak of omega*p: " + str(rhoref_temp[np.argmax(mtmFreq)])) print("rho i for peak of omega*n: " + str(rhoref_temp[np.argmax(omega_n)])) plt.clf() plt.xlabel('r/a') plt.ylabel('eta') plt.plot(uni_rhot, eta, label='eta') plt.show() plt.clf() #plt.title('mode number finder') plt.xlabel('r/a') plt.ylabel('omega*(Lab), kHz') plt.plot(uni_rhot, omega, label='omega*(Lab)') plt.show() plt.clf() plt.xlabel('r/a') plt.ylabel('eta') plt.plot(uni_rhot, eta, label='eta') plt.show() plt.clf() plt.xlabel('r/a') plt.ylabel('shat') plt.plot(uni_rhot, shat, label='shat') plt.show() plt.clf() plt.xlabel('r/a') plt.ylabel('beta') plt.plot(uni_rhot, beta, label='beta') plt.show() plt.clf() plt.xlabel('r/a') plt.ylabel('ky rhoi') plt.plot(uni_rhot, ky, label='ky') plt.show() mean_rho, xstar = omega_gaussian_fit(uni_rhot, mtmFreq, rhoref * np.sqrt(2.), Lref, path, profile_name, plot) if abs(mean_rho) + abs(xstar) < 0.0001: quit() if output_csv == True: with open('profile_output.csv', 'w') as csvfile: data = csv.writer(csvfile, delimiter=',') data.writerow([ 'x/a', 'nu_ei(kHz)', 'omega*n(kHz)', 'omega* plasma(kHz)', 'Doppler shift(kHz)', 'nu/omega*n', 'eta', 'shat', 'beta', 'ky rhoi(for n=1)' ]) for i in range(len(uni_rhot)): data.writerow([ uni_rhot[i], coll_ei[i], omega_n[i], mtmFreq[i], omegaDoppler[i], nu[i], eta[i], shat[i], beta[i], ky[i] ]) csvfile.close() return uni_rhot, nu, eta, shat, beta, ky, q, mtmFreq, omegaDoppler, omega_n, omega_n_GENE, xstar, Lref, R_ref, rhoref
# uncomment if running on SageMaker #sys.path[0] = '/home/ec2-user/SageMaker/asteroid/code' #sys.path[0] = '/Users/lutz/Dropbox/URI/Projects/Asteroid/asteroid-git/code' # Get the path of this run-tests.py file file_path = os.path.dirname(os.path.abspath(__file__)) # Temporarly change the working directory to that path os.chdir(file_path) # Set the path to two levels above (the code directory) sys.path[0] = "../../" from interp import interp programs = os.listdir("programs") programs.sort() for pname in programs: f = open("programs/" + pname, "r") p = f.read() print("**********" + pname + "*************") #print(p) #print("********************output*********************") try: interp(p, exceptions=True) except: pass f.close()
def main(): # fetch_many() interp() label_and_rename() make_gif()
import factor_filter as ff import interp as intp from datetime import datetime if __name__ == '__main__': # ----user's input------- t1 = datetime.strptime('2017/08/03', '%Y/%m/%d') stock_list = [ '600725.SZ', '600306.SZ', '600000.SH', '600004.SH', '600006.SH', '600007.SH', '600008.SH', '600009.SH', '600010.SH', '600011.SH', '600012.SH', '600015.SH', '600016.SH' ] factor_txt = 'MA5 = MA(trade_closeprice,5)\nMA10 = MA(trade_closeprice, 10)' filter_txt = 'gx = CROSS(MA5, MA10)\nasc5 = SORT(MA5, asc, 5)' # ----interp user's input---- d1, d2 = intp.interp(factor_txt, filter_txt) # ----get daily stock list on day t1----- for key in d2.keys(): # print key, d2[key].factor_list, d2[key].method stocks = d2[key].filter(stock_list, t1) print 'Stock list by applying filter', key, ':', stocks
def test_diffenv(): """ Individual env """ unittest(lambda: None, lambda _, y: interp(parse(y)[0]), test_suite)
#!/usr/bin/env python3 # coding: utf-8 # # Regression Tests import sys import os # Get the path of this run-tests.py file file_path = os.path.dirname(os.path.abspath(__file__)) # Temporarly change the working directory to that path os.chdir(file_path) # Set the path to two levels above (the code directory) sys.path[0] = "../../" from interp import interp programs = os.listdir("programs") programs.sort() for pname in programs: f = open("programs/" + pname, "r") p = f.read() print("**********" + pname + "************") print(p) print("**********output***********") interp(p) f.close()
def read_profile_file(profile_type,profile_name,geomfile_name,suffix): if profile_type=="ITERDB": rhot0, te0, ti0, ne0, ni0, nz0, vrot0 = read_iterdb_file(profile_name) psi0 = np.linspace(0.,1.,len(rhot0)) rhop0 = np.sqrt(np.array(psi0)) return rhot0, rhop0, te0, ti0, ne0, ni0, nz0, vrot0 elif profile_type=="pfile": rhot0, rhop0, te0, ti0, ne0, ni0, nz0, vrot0 = p_to_iterdb_format(profile_name,geomfile_name) return rhot0, rhop0, te0, ti0, ne0, ni0, nz0, vrot0 elif profile_type=="profile_e": if suffix=="dat": suffix=".dat" else: suffix="_"+suffix rhot0, te0, ti0, ne0, ni0, nz0, vrot0 = read_iterdb_file(profile_name) psi0 = np.linspace(0.,1.,len(rhot0)) rhop0 = np.sqrt(np.array(psi0)) x_a,x_rho_ref,T,n0,omt,omn = profile_e_info(suffix) if 1==0: plt.clf() plt.plot(x_a,n0*1.0e19,label='profile') plt.plot(rhot0,ne0,label='ITERDB') #plt.plot(x_rho_ref,T,label='x_rho_ref') plt.legend() plt.show() plt.clf() plt.plot(x_a,T*1000.,label='profile') plt.plot(rhot0,te0,label='ITERDB') #plt.plot(x_rho_ref,T,label='x_rho_ref') plt.legend() plt.show() #x_a,x_rho_ref,T,n0,omt,omn = profile_i_info(suffix) rhot0_range_min=np.argmin(abs(rhot0-x_a[0])) rhot0_range_max=np.argmin(abs(rhot0-x_a[-1])) rhot=rhot0[rhot0_range_min:rhot0_range_max] rhop=rhop0[rhot0_range_min:rhot0_range_max] ti=ti0[rhot0_range_min:rhot0_range_max] ni=ni0[rhot0_range_min:rhot0_range_max] vrot=vrot0[rhot0_range_min:rhot0_range_max] rhot0 = np.linspace(min(rhot),max(rhot),len(rhot)*3.) rhop0=interp(rhot,rhop,rhot0) te0 = interp(x_a,T*1000.,rhot0) ti0=interp(rhot,ti,rhot0) ni0=interp(rhot,ni,rhot0) nz0 = interp(rhot,nz,rhot0) ne0 = interp(x_a,n0*1.0e19,rhot0) vrot0=interp(rhot,vrot,rhot0) print("**************************") print("**************************") print("x_a min max: "+str(np.min(x_a))+", "+str(np.max(x_a))) print("**************************") print("**************************") print("**************************") return rhot0, rhop0, te0, ti0, ne0, ni0, vrot0
def pic(electron, ion, nx, dx, nt, dt, L, B0, save_res=[], n_pairs=2, L_source=1.0, max_scale=2): N = 0 for s in [electron, ion]: N += s.N N_max = N*max_scale q, qm, wc, xp, vx, vy = [np.zeros(N_max) for _ in range(6)] el = np.ndarray((N_max,), dtype=np.bool) do_move = np.ndarray((N_max,), dtype=np.bool) do_move[:] = False count = 0 # Trailing count for s,t in [(electron,True), (ion,False)]: q[count:count+s.N] = s.q qm[count:count+s.N] = s.q/s.m wc[count:count+s.N] = (s.q/s.m)*B0 xp[count:count+s.N] = s.x0 vx[count:count+s.N] = s.vx0 vy[count:count+s.N] = s.vy0 el[count:count+s.N] = t do_move[count:count+s.N] = s.m>0 count += s.N # store the results at each time step save_xp = 'xp' in save_res save_vx = 'vx' in save_res save_vy = 'vy' in save_res save_E = 'E' in save_res save_phi = 'phi' in save_res save_rho = 'rho' in save_res save_sig = 'sig' in save_res save_N = 'N' in save_res save_el = 'el' in save_res save_pw = 'phi_wall' in save_res if save_xp or save_vx or save_vy: save_N = save_el = True if save_xp: xpa = np.zeros((nt+1, N_max)) if save_vx: vxa = np.zeros((nt+1, N_max)) if save_vy: vya = np.zeros((nt+1, N_max)) if save_E: Ea = np.zeros((nt+1, nx)) if save_phi: phia = np.zeros((nt+1, nx)) if save_pw: pwa = np.zeros(nt+1) if save_rho: rhoa = np.zeros((nt+1, nx)) if save_sig: siga = np.zeros(nt+1) if save_N: Na = np.zeros(nt+1) if save_el: ela = np.zeros((nt+1,N_max), dtype=np.bool) # Main solution loop # Init half step back sigma = 0. rho = weight(xp[:N], q[:N], nx, L)/dx phi = poisson_solve(rho, dx, sigma) E0 = calc_E(phi, dx, sigma) E = interp(E0, xp[:N], nx, L) #rotate(vx[:N], vy[:N], -wc[:N], dt) accel(vx[:N], vy[:N], E, -qm[:N], dt) if save_xp: xpa[0] = xp if save_vx: vxa[0] = vx if save_vy: vya[0] = vy if save_E: Ea[0] = E0 if save_phi: phia[0] = phi if save_pw: pwa[0] = phi[-1] if save_rho: rhoa[0] = rho if save_sig: siga[0] = sigma if save_N: Na[0] = N if save_el: ela[0] = el for i in range(1, nt+1): # Update velocity accel(vx[:N], vy[:N], E[:N], qm[:N], dt) #rotate(vx[:N], vy[:N], wc, dt) accel(vx[:N], vy[:N], E[:N], qm[:N], dt) # Update position move(xp[:N], vx[:N], vy[:N], dt, L) # Reflect particles reflect = xp[:N] < 0. n_reflect = np.sum(reflect) ne_reflect = np.sum(el[:N][reflect]) ni_reflect = n_reflect-ne_reflect xp[:N][reflect] = 0.0 vx[:N][ el[:N] &reflect] = np.abs(electron.sample(ne_reflect)) vx[:N][(~el[:N])&reflect] = np.abs(ion.sample(ni_reflect)) vy[:N][reflect] = 0.0 # Update wall charge density hit = xp[:N] >= L n_hit = np.sum(hit) sigma += np.sum(q[:N][hit]) # Remove particles that hit the wall xp[:N-n_hit] = xp[:N][~hit].copy() vx[:N-n_hit] = vx[:N][~hit].copy() vy[:N-n_hit] = vy[:N][~hit].copy() q[:N-n_hit] = q[:N][~hit].copy() qm[:N-n_hit] = qm[:N][~hit].copy() el[:N-n_hit] = el[:N][~hit].copy() N -= n_hit # Add particles from source term vxe = electron.source(n_pairs) vxi = ion.source(n_pairs) xe_new = np.random.rand(n_pairs)*L_source xi_new = np.random.rand(n_pairs)*L_source xp[N:N+n_pairs] = xe_new vx[N:N+n_pairs] = vxe vy[N:N+n_pairs] = 0.0 q[N:N+n_pairs] = electron.q qm[N:N+n_pairs] = electron.q/electron.m el[N:N+n_pairs] = True N += n_pairs xp[N:N+n_pairs] = xi_new vx[N:N+n_pairs] = vxi vy[N:N+n_pairs] = 0.0 q[N:N+n_pairs] = ion.q qm[N:N+n_pairs] = ion.q/ion.m el[N:N+n_pairs] = False N += n_pairs # Calc fields rho = weight(xp[:N], q[:N], nx, L)/dx phi = poisson_solve(rho, dx, sigma) E0 = calc_E(phi, dx, sigma) E = interp(E0, xp[:N], nx, L) if save_xp: xpa[i] = xp if save_vx: vxa[i] = vx if save_vy: vya[i] = vy if save_E: Ea[i] = E0 if save_phi: phia[i] = phi if save_pw: pwa[i] = phi[-1] if save_rho: rhoa[i] = rho if save_sig: siga[i] = sigma if save_N: Na[i] = N if save_el: ela[i] = el results = {} if save_xp: results['xp_all'] = xpa if save_vx: results['vx_all'] = vxa if save_vy: results['vy_all'] = vya if save_E: results['E_all'] = Ea if save_phi: results['phi_all'] = phia if save_pw: results['phi_wall'] = pwa if save_rho: results['rho_all'] = rhoa if save_sig: results['sig_all'] = siga if save_N: results['N_all'] = Na if save_el: results['el_all'] = ela # Save the last value for each variable results['N'] = N results['xp'] = xp[:N] results['vx'] = vx[:N] results['vy'] = vy[:N] results['el'] = el[:N] results['E'] = E0 results['phi'] = phi results['rho'] = rho results['sig'] = sigma return results