def helpu(): loop() print(" I am your assistant") loop() print(" Let me tell you what can I do for you") menuexpl() time.sleep(10000)
def welcome(): #intial welcome print(" Hi! I am Pybot") loop() #taking user name while True: try: name = input(" What's yours: ") except ValueError: pass else: if name.isalpha() == True: print(f" Hi! {name}") break else: print(" I can't get your name") continue #fuction call helpu() time.sleep(10000) # here we can get introduced
def test_loop(rerun=0): #TEST LOOPING OVER PARAMETERS, SAVING TO FOLDER HIERARCHY #LOADING AND PLOTTING AGGREGATE MEASURES path=Path('tests/test_loop') try: if not os.listdir(path): rerun=1 except: rerun =1 if rerun: #If not already run before prm={} prm.update(dftparams) axes=[ ('community_std', [.1,1,10.] ), ('growth_std',[0,1.]) ] loop(path=path,axes=axes,check_key=1,print_msg=1,tsample=.1,**prm ) make_measures(path) rebuild_filelist(path) plot_data(path,axes=['community_std','growth_std'],values=['n_biomass'],style='3d', #split_by=[] )
def rl_train_fn(args, reporter): for e in range(args.epochs): dummy_accuracy = 1 - np.power(1.8, -np.random.uniform(e, 2 * e)) loop(1, training_data_loader) reporter(epoch=e + 1, accuracy=dummy_accuracy, lr=args.lr, wd=args.wd)
def main_loop() -> None: environment = base_environment().extend() def statement_loop(statement_text): block = parse(statement_text) expression_stack = MachineExpressionStack([]) interpret(block, expression_stack, environment) return expression_stack.values loop(statement_loop)
def test_build_marine_random(): with sc2_env.SC2Env("BuildMarines", step_mul=step_mul, game_steps_per_episode=steps * step_mul) as env: env.observation_spec() agent = random_agent.RandomAgent() loop([agent], env, steps) print agent.reward
def encode(): loop() #taking input for encoding text = input("Enter what to be encrypted: ") text = text + "|||" # encoding encoded = base64.b64encode(bytes(text, 'utf-8')) # writing text in it encoded_text = open("E:\\PROJ.RC\\python\\pyBot\\enc_files\\enc.txt", mode='b+a') encoded_text.write(encoded) encoded_text.close() time.sleep(10000)
def encryption(): loop() while True: o=input(" How do you want to proceed\n (W)Encrypt text\n (S)Show encrypted text: \n") if o=='w' or o=='W': encrypt() break # tell me more function elif o=='S' or o=='s': decrypt() break #tell me more function else: print(" I can't get it") continue menu() time.sleep(10000)
def panel_method(a, b, N, Z): cz = 0.5 * (Z[1:] + Z[:-1]) # complex midpoint L = abs(Z[1:] - Z[:-1]) # Panel length n1 = (-Z.imag[1:] + Z.imag[:-1]) / L # x-comp normal vector n2 = ( Z.real[1:] - Z.real[:-1]) / L # y-comp normal vector # P*phi = Q P = np.zeros( (N, N), order='Fortran' ) Q = np.zeros( (N, 3), order='Fortran' ) # Migrated fortran loop computes the lhs matrix P, # and the rhs integral for surge, heave and pitch. P, Q = loop.loop(N, Z, cz, L, n1, n2, P, Q) # Solve the linear matrix system, P * phi = Q, yields phi on each panel phi_i = np.linalg.solve(P, Q) # Added mass. m11 = np.sum( phi_i[:, 0] * n1 * L ) m22 = np.sum( phi_i[:, 1] * n2 * L ) m12 = np.sum( phi_i[:, 0] * n2 * L ) m66 = np.sum( phi_i[:, 2] * (cz.real*n2 - cz.imag*n1) * L ) return m11, m22, m12, m66
def Ricci__generate_Ccode(Ricci_exprs_list): Ricci_SymbExpressions = Ricci_exprs_list[0] print("Generating C code for Ricci tensor (FD_order="+str(FD_order)+") in "+par.parval_from_str("reference_metric::CoordSystem")+" coordinates.") start = time.time() # Store original finite-differencing order: FD_order_orig = par.parval_from_str("finite_difference::FD_CENTDERIVS_ORDER") # Set new finite-differencing order: par.set_parval_from_str("finite_difference::FD_CENTDERIVS_ORDER", FD_order) Ricci_string = fin.FD_outputC("returnstring", Ricci_SymbExpressions, params="outCverbose=False,SIMD_enable=True,GoldenKernelsEnable=True") filename = "BSSN_Ricci_FD_order_"+str(FD_order)+".h" with open(os.path.join(outdir, filename), "w") as file: file.write(lp.loop(["i2","i1","i0"],["cctk_nghostzones[2]","cctk_nghostzones[1]","cctk_nghostzones[0]"], ["cctk_lsh[2]-cctk_nghostzones[2]","cctk_lsh[1]-cctk_nghostzones[1]","cctk_lsh[0]-cctk_nghostzones[0]"], ["1","1","SIMD_width"], ["#pragma omp parallel for", "#include \"rfm_files/rfm_struct__SIMD_outer_read2.h\"", r""" #include "rfm_files/rfm_struct__SIMD_outer_read1.h" #if (defined __INTEL_COMPILER && __INTEL_COMPILER_BUILD_DATE >= 20180804) #pragma ivdep // Forces Intel compiler (if Intel compiler used) to ignore certain SIMD vector dependencies #pragma vector always // Forces Intel compiler (if Intel compiler used) to vectorize #endif"""],"", "#include \"rfm_files/rfm_struct__SIMD_inner_read0.h\"\n"+Ricci_string)) # Restore original finite-differencing order: par.set_parval_from_str("finite_difference::FD_CENTDERIVS_ORDER", FD_order_orig) end = time.time() print("(BENCH) Finished Ricci C codegen (FD_order="+str(FD_order)+") in " + str(end - start) + " seconds.")
def panel_method(a, b, N, Z, tau=0.5): cz = 0.5 * (Z[1:] + Z[:-1]) # complex midpoint L = abs(Z[1:] - Z[:-1]) # Panel length n1 = (-Z.imag[1:] + Z.imag[:-1]) / L # x-comp normal vector n2 = ( Z.real[1:] - Z.real[:-1]) / L # y-comp normal vector # P*phi = Q P = np.zeros( (N, N), order='Fortran' ) Q = np.zeros( (N, 3), order='Fortran' ) # Migrated fortran loop computes the lhs matrix P, # and the rhs integral for surge, heave and pitch. P, Q = loop.loop(N, Z, cz, L, n1, n2, P, Q) # Additional term due to porosity mu = 0.4 # Discharge coeff. (Molin p. 3) K = (1 - tau) / (mu * tau**2) # Resistance coefficient #P += 1j * K * Q # Solve the linear matrix system, P * phi = Q, yields phi on each panel phi_i = np.linalg.solve(P, Q) # Added mass. m11 = np.sum( phi_i[:, 0] * n1 * L ) m22 = np.sum( phi_i[:, 1] * n2 * L ) m12 = np.sum( phi_i[:, 0] * n2 * L ) m66 = np.sum( phi_i[:, 2] * (cz.real*n2 - cz.imag*n1) * L ) return m11, m22, m12, m66
def menu(): loop() while True: x = input( " So what do you want to do: \n (C)Open Calculator\n (E)Encrypted vaults: " ) if x == "C" or x == "c": calc() break elif x == "E" or x == "e": encryption() break else: print(" Wrong input") continue time.sleep(10000)
def encrypt(): try: # creating new directory or checking if file exist or not os.path.exists("E:\\PROJ.RC\\python\\pyBot\\enc_files") #if file exist if will run except code except IOError: #if file exist call encode function encode() else: # otherwise (if there is no exception then it meas that file do not exist so create new file and call encode function) loop() print(" Directory does not exist") os.makedirs("E:\\PROJ.RC\\python\\pyBot\\enc_files") loop() print(" Created new file") encode() menu()
def enforce_detgammabar_eq_detgammahat__generate_symbolic_expressions_and_C_code( ): ###################################### # START: GENERATE SYMBOLIC EXPRESSIONS # Enable rfm_precompute infrastructure, which results in # BSSN RHSs that are free of transcendental functions, # even in curvilinear coordinates, so long as # ConformalFactor is set to "W" (default). par.set_parval_from_str("reference_metric::enable_rfm_precompute", "True") par.set_parval_from_str( "reference_metric::rfm_precompute_Ccode_outdir", os.path.join(outdir, "rfm_files/")) import BSSN.Enforce_Detgammabar_Constraint as EGC enforce_detg_constraint_symb_expressions = EGC.Enforce_Detgammabar_Constraint_symb_expressions( ) # Now that we are finished with all the rfm hatted # quantities in generic precomputed functional # form, let's restore them to their closed- # form expressions. par.set_parval_from_str( "reference_metric::enable_rfm_precompute", "False") # Reset to False to disable rfm_precompute. rfm.ref_metric__hatted_quantities() # END: GENERATE SYMBOLIC EXPRESSIONS ###################################### start = time.time() print( "Generating optimized C code (FD_order=" + str(FD_order) + ") for gamma constraint. May take a while, depending on CoordSystem." ) enforce_gammadet_string = fin.FD_outputC( "returnstring", enforce_detg_constraint_symb_expressions, params="outCverbose=False,preindent=0,includebraces=False") with open(os.path.join(outdir, "enforcedetgammabar_constraint.h"), "w") as file: file.write( lp.loop(["i2", "i1", "i0"], ["0", "0", "0"], ["cctk_lsh[2]", "cctk_lsh[1]", "cctk_lsh[0]"], ["1", "1", "1"], [ "#pragma omp parallel for", "#include \"rfm_files/rfm_struct__read2.h\"", "#include \"rfm_files/rfm_struct__read1.h\"" ], "", "#include \"rfm_files/rfm_struct__read0.h\"\n" + enforce_gammadet_string)) end = time.time() print("(BENCH) Finished gamma constraint C codegen (FD_order=" + str(FD_order) + ") in " + str(end - start) + " seconds.")
def boost(): args = request.args model = pickle.load(open('prediction_model.sav', 'rb')) out = {} out['price'] = boost_predict(model, args['model'], args['releaseDate'], args['maxRes'], args['lowRes'], args['effPix'], args['zoomW'], args['zoomT'], args['normalFocus'], args['macroFocus'], args['storage'], args['weight'], args['dimension'])[0] out['sentimentScore'] = loop(videos[args['model']]) return jsonify(out)
def BSSN_RHSs_Ricci__generate_Ccode(which_expressions, all_RHSs_Ricci_exprs_list): betaU = all_RHSs_Ricci_exprs_list[0] BSSN_RHSs_SymbExpressions = all_RHSs_Ricci_exprs_list[1] Ricci_SymbExpressions = all_RHSs_Ricci_exprs_list[2] if(which_expressions == "BSSN_RHSs"): print("Generating C code for BSSN RHSs (FD_order="+str(FD_order)+",Tmunu="+str(enable_stress_energy_source_terms)+") in "+par.parval_from_str("reference_metric::CoordSystem")+" coordinates.") start = time.time() BSSN_RHSs_string = fin.FD_outputC("returnstring",BSSN_RHSs_SymbExpressions, params="outCverbose=False,SIMD_enable=True", upwindcontrolvec=betaU) with open(os.path.join(outdir,"BSSN_RHSs_FD_order_"+str(FD_order)+"_enable_Tmunu_"+str(enable_stress_energy_source_terms)+".h"), "w") as file: file.write(lp.loop(["i2","i1","i0"],["cctk_nghostzones[2]","cctk_nghostzones[1]","cctk_nghostzones[0]"], ["cctk_lsh[2]-cctk_nghostzones[2]","cctk_lsh[1]-cctk_nghostzones[1]","cctk_lsh[0]-cctk_nghostzones[0]"], ["1","1","SIMD_width"], ["#pragma omp parallel for", "#include \"rfm_files/rfm_struct__SIMD_outer_read2.h\"", "#include \"rfm_files/rfm_struct__SIMD_outer_read1.h\""],"", "#include \"rfm_files/rfm_struct__SIMD_inner_read0.h\"\n"+BSSN_RHSs_string)) end = time.time() print("Finished BSSN_RHS C codegen (FD_order="+str(FD_order)+",Tmunu="+str(enable_stress_energy_source_terms)+") in " + str(end - start) + " seconds.") elif(which_expressions == "Ricci"): print("Generating C code for Ricci tensor (FD_order="+str(FD_order)+") in "+par.parval_from_str("reference_metric::CoordSystem")+" coordinates.") start = time.time() Ricci_string = fin.FD_outputC("returnstring", Ricci_SymbExpressions, params="outCverbose=False,SIMD_enable=True") with open(os.path.join(outdir,"BSSN_Ricci_FD_order_"+str(FD_order)+".h"), "w") as file: file.write(lp.loop(["i2","i1","i0"],["cctk_nghostzones[2]","cctk_nghostzones[1]","cctk_nghostzones[0]"], ["cctk_lsh[2]-cctk_nghostzones[2]","cctk_lsh[1]-cctk_nghostzones[1]","cctk_lsh[0]-cctk_nghostzones[0]"], ["1","1","SIMD_width"], ["#pragma omp parallel for", "#include \"rfm_files/rfm_struct__SIMD_outer_read2.h\"", "#include \"rfm_files/rfm_struct__SIMD_outer_read1.h\""],"", "#include \"rfm_files/rfm_struct__SIMD_inner_read0.h\"\n"+Ricci_string)) end = time.time() print("Finished Ricci C codegen (FD_order="+str(FD_order)+") in " + str(end - start) + " seconds.") else: print("Error: unexpected argument, "+str(which_expressions)+" to BSSN_RHSs_Ricci__generate_Ccode()")
def bfield(P): B_LAB = np.array([0, 0, 0]) # % The location P is defined as the segment OP, where O is the origin of the #% laboratory reference frame. The vector is expressed in the Lab reference #% frame. oplab = P #% Iterated over all the loops (ie., lines of the 'CurrentLoops' matrix), #% and sum the contribution of each loop at the location P for ii in range(0, cfg.CurrentLoops.shape[0]): # % Keep data of the Current Loop of index 'ii' oclab = cfg.CurrentLoops[ii][0:3] nh = cfg.CurrentLoops[ii][3:6] I0 = cfg.CurrentLoops[ii][6] Ra = cfg.CurrentLoops[ii][7] Nw = cfg.CurrentLoops[ii][8] # % Rotation matrix ROT_LAB_LOOP = roto.ROT(nh) # % Roto-traslation of the P point variable2 = oplab - oclab P_LOOP = ROT_LAB_LOOP.dot(variable2) R = P_LOOP[2] Z = P_LOOP[1] # % Field contribution from the current Loop 'ii' # % (for the analytical solution see Jackson Chap. 5) Br, Bz = lp.loop(R, Z, I0, Ra, Nw) # % Magnitude of the magnetic field variable1 = Br * Br + Bz * Bz Bnorm = np.sqrt(variable1) # % B-field vector, expressed in the 'LOOP' reference frame B_LOOP = [Br, 0.0, Bz] # % Rotate the b-field in the LAB frame and sum to the # % the total cumulative vector B_LAB = B_LAB + ROT_LAB_LOOP.dot(B_LOOP) return B_LAB
def output_C__MomentumConstraint_h(outdir="BSSN/", add_T4UUmunu_source_terms=False, enable_verbose=True): # Step 0: Check if outdir is string; error out if not. check_if_string__error_if_not(outdir, "outdir") # Calling BSSN_constraints() (defined above) computes H and MU: BSSN_constraints(add_T4UUmunu_source_terms) if add_T4UUmunu_source_terms == True: print( "ERROR: MOMENTUM CONSTRAINT DOES NOT YET ADD T4UUmunu source terms." ) exit(1) import time start = time.time() if enable_verbose: print( "Generating optimized C code for Momentum constraint. May take a while, depending on CoordSystem." ) MomentumConstraintString = fin.FD_outputC("returnstring", [ lhrh(lhs=gri.gfaccess("aux_gfs", "MU0"), rhs=MU[0]), lhrh(lhs=gri.gfaccess("aux_gfs", "MU1"), rhs=MU[1]), lhrh(lhs=gri.gfaccess("aux_gfs", "MU2"), rhs=MU[2]) ], params="outCverbose=False") end = time.time() if enable_verbose: print("Finished in " + str(end - start) + " seconds.") import loop as lp with open(outdir + "MomentumConstraint.h", "w") as file: file.write( lp.loop(["i2", "i1", "i0"], ["NGHOSTS", "NGHOSTS", "NGHOSTS"], [ "NGHOSTS+Nxx[2]", "NGHOSTS+Nxx[1]", "NGHOSTS+Nxx[0]" ], ["1", "1", "1"], [ "const REAL invdx0 = 1.0/dxx[0];\n" + "const REAL invdx1 = 1.0/dxx[1];\n" + "const REAL invdx2 = 1.0/dxx[2];\n" + "#pragma omp parallel for", " const REAL xx2 = xx[2][i2];", " const REAL xx1 = xx[1][i1];" ], "", "const REAL xx0 = xx[0][i0];\n" + MomentumConstraintString)) print("Output C implementation of Momentum constraint to " + outdir + "MomentumConstraint.h")
def evaluate(): data = request.get_json() logging.info("data sent for evaluation {}".format(data)) # print(type(data)) result = [] for case in data: n = case['n'] # cleaning text patterns = [r'\w+'] for p in patterns: match = re.findall(p, case['text']) txt = ''.join(match) txt = txt.upper() # encrypting... answer = loop(txt, n) result = [""] * len(txt) # first one result[0] = txt[0] txt = txt[1:] counter = 0 # start encrypting while "" in result: for i in range(len(result)): # result[i] = txt[0] # txt = txt[1:] # result divisible by n if (i + counter) % n == 0: # empty cell if result[i] == '': result[i] = txt[0] txt = txt[1:] counter += 1 else: pass else: pass logging.info("My result :{}".format(''.join(result))) return json.dumps(result)
def BSSN_constraints__generate_symbolic_expressions_and_C_code(): ###################################### # START: GENERATE SYMBOLIC EXPRESSIONS # Define the Hamiltonian constraint and output the optimized C code. import BSSN.BSSN_constraints as bssncon bssncon.BSSN_constraints(add_T4UUmunu_source_terms=False) if T4UU != None: import BSSN.BSSN_stress_energy_source_terms as Bsest Bsest.BSSN_source_terms_for_BSSN_RHSs(T4UU) Bsest.BSSN_source_terms_for_BSSN_constraints(T4UU) bssncon.H += Bsest.sourceterm_H for i in range(3): bssncon.MU[i] += Bsest.sourceterm_MU[i] # END: GENERATE SYMBOLIC EXPRESSIONS ###################################### # Store original finite-differencing order: FD_order_orig = par.parval_from_str("finite_difference::FD_CENTDERIVS_ORDER") # Set new finite-differencing order: par.set_parval_from_str("finite_difference::FD_CENTDERIVS_ORDER", FD_order) start = time.time() print("Generating optimized C code for Ham. & mom. constraints. May take a while, depending on CoordSystem.") Ham_mom_string = fin.FD_outputC("returnstring", [lhrh(lhs=gri.gfaccess("aux_gfs", "H"), rhs=bssncon.H), lhrh(lhs=gri.gfaccess("aux_gfs", "MU0"), rhs=bssncon.MU[0]), lhrh(lhs=gri.gfaccess("aux_gfs", "MU1"), rhs=bssncon.MU[1]), lhrh(lhs=gri.gfaccess("aux_gfs", "MU2"), rhs=bssncon.MU[2])], params="outCverbose=False") with open(os.path.join(outdir,"BSSN_constraints_enable_Tmunu_"+str(enable_stress_energy_source_terms)+"_FD_order_"+str(FD_order)+".h"), "w") as file: file.write(lp.loop(["i2","i1","i0"],["cctk_nghostzones[2]","cctk_nghostzones[1]","cctk_nghostzones[0]"], ["cctk_lsh[2]-cctk_nghostzones[2]","cctk_lsh[1]-cctk_nghostzones[1]","cctk_lsh[0]-cctk_nghostzones[0]"], ["1","1","1"],["#pragma omp parallel for","",""], "", Ham_mom_string)) # Restore original finite-differencing order: par.set_parval_from_str("finite_difference::FD_CENTDERIVS_ORDER", FD_order_orig) end = time.time() print("(BENCH) Finished Hamiltonian & momentum constraint C codegen (FD_order="+str(FD_order)+",Tmunu="+str(enable_stress_energy_source_terms)+") in " + str(end - start) + " seconds.")
def panel_method(a, b, N, Z, tau=0.5, d=1, rho=1, w=1): # cz = 0.5 * (Z[1:] + Z[:-1]) # complex midpoint L = abs(Z[1:] - Z[:-1]) # Panel length n1 = (-Z.imag[1:] + Z.imag[:-1]) / L # x-comp normal vector n2 = ( Z.real[1:] - Z.real[:-1]) / L # y-comp normal vector # Parameters for fluid and porous media mu = 0.4 # Discharge coefficient (Molin p. 3) K = (1 - tau) / (mu*tau**2) # Resistance coefficient (Molin p. 3) KC = d / (2.*a) # Keulegan-Carpenter number b = 1 / (K * KC) # Porosity coefficient from Chwang w = 1.0 # Frequency omega # theta = np.zeros((N, N), dtype=complex, order='Fortran') intLog = np.zeros((N, N), dtype=complex, order='Fortran') A = np.pi * np.eye(2*N, dtype=complex) B = np.zeros(2*N, dtype=complex, order='Fortran') # B = loop.loop(N, Z, cz, L, n1, theta, intLog, A, B, mu, tau, a, d, w, rho) # Psi and Phi on each panel Phi = B[:N] Psi = B[N:] # Inner and outer potential phi_e = 0.5 * (Phi + Psi) phi_i = 0.5 * (Phi - Psi) # Added mass m11 = np.sum(phi_e.real * n1 * L) + np.sum(phi_i.real * n1 * L) # Damping coefficient b11 = np.sum(phi_e.imag * n1 * L / w) + np.sum(phi_i.imag * n1 * L / w) return m11, b11
def output_Enforce_Detgammabar_Constraint_Ccode(outdir="BSSN/"): # Step 0: Check if outdir is string; error out if not. check_if_string__error_if_not(outdir,"outdir") enforce_detg_constraint_symb_expressions = Enforce_Detgammabar_Constraint_symb_expressions() enforce_gammadet_string = fin.FD_outputC("returnstring", enforce_detg_constraint_symb_expressions, params="outCverbose=False,preindent=0,includebraces=False") with open(outdir+"enforce_detgammabar_constraint.h", "w") as file: indent = " " file.write( "void enforce_detgammabar_constraint(const int Nxx_plus_2NGHOSTS[3],REAL *xx[3], REAL *in_gfs) {\n\n") file.write(lp.loop(["i2", "i1", "i0"], ["0", "0", "0"], ["Nxx_plus_2NGHOSTS[2]", "Nxx_plus_2NGHOSTS[1]", "Nxx_plus_2NGHOSTS[0]"], ["1", "1", "1"], ["#pragma omp parallel for", " const REAL xx2 = xx[2][i2];", " const REAL xx1 = xx[1][i1];"], "", "const REAL xx0 = xx[0][i0];\n" + enforce_gammadet_string)) file.write("}\n") print("Output C implementation of det(gammabar) constraint to file "+outdir+"enforce_detgammabar_constraint.h")
def output_C__Hamiltonian_h(add_T4UUmunu_source_terms=False, enable_verbose=True): # Calling BSSN_constraints() (defined above) computes H and MU: BSSN_constraints(add_T4UUmunu_source_terms) import time start = time.time() if enable_verbose: print( "Generating optimized C code for Hamiltonian constraint. May take a while, depending on CoordSystem." ) Hamiltonianstring = fin.FD_outputC("returnstring", lhrh(lhs=gri.gfaccess("aux_gfs", "H"), rhs=H), params="outCverbose=False") end = time.time() if enable_verbose: print("Finished in " + str(end - start) + " seconds.") import loop as lp with open("BSSN/Hamiltonian.h", "w") as file: file.write( lp.loop(["i2", "i1", "i0"], ["NGHOSTS", "NGHOSTS", "NGHOSTS"], ["NGHOSTS+Nxx[2]", "NGHOSTS+Nxx[1]", "NGHOSTS+Nxx[0]"], ["1", "1", "1"], [ "const REAL invdx0 = 1.0/dxx[0];\n" + "const REAL invdx1 = 1.0/dxx[1];\n" + "const REAL invdx2 = 1.0/dxx[2];\n" + "#pragma omp parallel for", " const REAL xx2 = xx[2][i2];", " const REAL xx1 = xx[1][i1];" ], "", "const REAL xx0 = xx[0][i0];\n" + Hamiltonianstring)) print( "Output C implementation of Hamiltonian constraint to BSSN/Hamiltonian.h" )
def decaptcha(filenames): print("In Progress...") numChars, codes = loop.loop(filenames) return (numChars, codes)
def driver_C_codes(Csrcdict, ThornName, rhs_list, evol_gfs_list, aux_gfs_list, auxevol_gfs_list, LapseCondition="OnePlusLog", enable_stress_energy_source_terms=False): # First the ETK banner code, proudly showing the NRPy+ banner import NRPy_logo as logo outstr = """ #include <stdio.h> void BaikalETK_Banner() { """ logostr = logo.print_logo(print_to_stdout=False) outstr += "printf(\"BaikalETK: another Einstein Toolkit thorn generated by\\n\");\n" for line in logostr.splitlines(): outstr += " printf(\"" + line + "\\n\");\n" outstr += "}\n" # Finally add C code string to dictionaries (Python dictionaries are immutable) # Add C code string to dictionary (Python dictionaries are immutable) Csrcdict[append_to_make_code_defn_list("Banner.c")] = outstr.replace( "BaikalETK", ThornName) # Then the RegisterSlicing() function, needed for other ETK thorns outstr = """ #include "cctk.h" #include "Slicing.h" int BaikalETK_RegisterSlicing (void) { Einstein_RegisterSlicing ("BaikalETK"); return 0; }""" # Add C code string to dictionary (Python dictionaries are immutable) Csrcdict[append_to_make_code_defn_list( "RegisterSlicing.c")] = outstr.replace("BaikalETK", ThornName) # Next BaikalETK_Symmetry_registration(): Register symmetries full_gfs_list = [] full_gfs_list.extend(evol_gfs_list) full_gfs_list.extend(auxevol_gfs_list) full_gfs_list.extend(aux_gfs_list) outstr = """ #include "cctk.h" #include "cctk_Arguments.h" #include "cctk_Parameters.h" #include "Symmetry.h" void BaikalETK_Symmetry_registration(CCTK_ARGUMENTS) { DECLARE_CCTK_ARGUMENTS; DECLARE_CCTK_PARAMETERS; // Stores gridfunction parity across x=0, y=0, and z=0 planes, respectively int sym[3]; // Next register parities for each gridfunction based on its name // (to ensure this algorithm is robust, gridfunctions with integers // in their base names are forbidden in NRPy+). """ outstr += "" for gf in full_gfs_list: # Do not add T4UU gridfunctions if enable_stress_energy_source_terms==False: if not (enable_stress_energy_source_terms == False and "T4UU" in gf): outstr += """ // Default to scalar symmetry: sym[0] = 1; sym[1] = 1; sym[2] = 1; // Now modify sym[0], sym[1], and/or sym[2] as needed // to account for gridfunction parity across // x=0, y=0, and/or z=0 planes, respectively """ # If gridfunction name does not end in a digit, by NRPy+ syntax, it must be a scalar if gf[len(gf) - 1].isdigit() == False: pass # Scalar = default elif len(gf) > 2: # Rank-1 indexed expression (e.g., vector) if gf[len(gf) - 2].isdigit() == False: if int(gf[-1]) > 2: print("Error: Found invalid gridfunction name: " + gf) sys.exit(1) symidx = gf[-1] outstr += " sym[" + symidx + "] = -1;\n" # Rank-2 indexed expression elif gf[len(gf) - 2].isdigit() == True: if len(gf) > 3 and gf[len(gf) - 3].isdigit() == True: print("Error: Found a Rank-3 or above gridfunction: " + gf + ", which is at the moment unsupported.") print("It should be easy to support this if desired.") sys.exit(1) symidx0 = gf[-2] outstr += " sym[" + symidx0 + "] *= -1;\n" symidx1 = gf[-1] outstr += " sym[" + symidx1 + "] *= -1;\n" else: print( "Don't know how you got this far with a gridfunction named " + gf + ", but I'll take no more of this nonsense.") print( " Please follow best-practices and rename your gridfunction to be more descriptive" ) sys.exit(1) outstr += " SetCartSymVN(cctkGH, sym, \"BaikalETK::" + gf + "\");\n" outstr += "}\n" # Add C code string to dictionary (Python dictionaries are immutable) Csrcdict[append_to_make_code_defn_list("Symmetry_registration_oldCartGrid3D.c")] = \ outstr.replace("BaikalETK",ThornName) # Next set RHSs to zero outstr = """ #include "cctk.h" #include "cctk_Arguments.h" #include "cctk_Parameters.h" #include "Symmetry.h" void BaikalETK_zero_rhss(CCTK_ARGUMENTS) { DECLARE_CCTK_ARGUMENTS; DECLARE_CCTK_PARAMETERS; """ set_rhss_to_zero = "" for gf in rhs_list: set_rhss_to_zero += gf + "[CCTK_GFINDEX3D(cctkGH,i0,i1,i2)] = 0.0;\n" outstr += lp.loop(["i2", "i1", "i0"], ["0", "0", "0"], ["cctk_lsh[2]", "cctk_lsh[1]", "cctk_lsh[0]"], ["1", "1", "1"], [ "#pragma omp parallel for", "", "", ], "", set_rhss_to_zero) outstr += "}\n" # Add C code string to dictionary (Python dictionaries are immutable) Csrcdict[append_to_make_code_defn_list("zero_rhss.c")] = outstr.replace( "BaikalETK", ThornName) # Next registration with the Method of Lines thorn outstr = """ //-------------------------------------------------------------------------- // Register with the Method of Lines time stepper // (MoL thorn, found in arrangements/CactusBase/MoL) // MoL documentation located in arrangements/CactusBase/MoL/doc //-------------------------------------------------------------------------- #include <stdio.h> #include "cctk.h" #include "cctk_Parameters.h" #include "cctk_Arguments.h" #include "Symmetry.h" void BaikalETK_MoL_registration(CCTK_ARGUMENTS) { DECLARE_CCTK_ARGUMENTS; DECLARE_CCTK_PARAMETERS; CCTK_INT ierr = 0, group, rhs; // Register evolution & RHS gridfunction groups with MoL, so it knows group = CCTK_GroupIndex("BaikalETK::evol_variables"); rhs = CCTK_GroupIndex("BaikalETK::evol_variables_rhs"); ierr += MoLRegisterEvolvedGroup(group, rhs); if (ierr) CCTK_ERROR("Problems registering with MoL"); } """ # Add C code string to dictionary (Python dictionaries are immutable) Csrcdict[append_to_make_code_defn_list( "MoL_registration.c")] = outstr.replace("BaikalETK", ThornName) # Next register with the boundary conditions thorns. # PART 1: Set BC type to "none" for all variables # Since we choose NewRad boundary conditions, we must register all # gridfunctions to have boundary type "none". This is because # NewRad is seen by the rest of the Toolkit as a modification to the # RHSs. # This code is based on Kranc's McLachlan/ML_BSSN/src/Boundaries.cc code. outstr = """ #include "cctk.h" #include "cctk_Arguments.h" #include "cctk_Parameters.h" #include "cctk_Faces.h" #include "util_Table.h" #include "Symmetry.h" // Set `none` boundary conditions on BSSN RHSs, as these are set via NewRad. void BaikalETK_BoundaryConditions_evolved_gfs(CCTK_ARGUMENTS) { DECLARE_CCTK_ARGUMENTS; DECLARE_CCTK_PARAMETERS; CCTK_INT ierr CCTK_ATTRIBUTE_UNUSED = 0; """ for gf in evol_gfs_list: outstr += """ ierr = Boundary_SelectVarForBC(cctkGH, CCTK_ALL_FACES, 1, -1, "BaikalETK::""" + gf + """", "none"); if (ierr < 0) CCTK_ERROR("Failed to register BC for BaikalETK::""" + gf + """!"); """ outstr += """ } // Set `flat` boundary conditions on BSSN constraints, similar to what Lean does. void BaikalETK_BoundaryConditions_aux_gfs(CCTK_ARGUMENTS) { DECLARE_CCTK_ARGUMENTS; DECLARE_CCTK_PARAMETERS; CCTK_INT ierr CCTK_ATTRIBUTE_UNUSED = 0; """ for gf in aux_gfs_list: outstr += """ ierr = Boundary_SelectVarForBC(cctkGH, CCTK_ALL_FACES, cctk_nghostzones[0], -1, "BaikalETK::""" + gf + """", "flat"); if (ierr < 0) CCTK_ERROR("Failed to register BC for BaikalETK::""" + gf + """!"); """ outstr += "}\n" # Add C code string to dictionary (Python dictionaries are immutable) Csrcdict[append_to_make_code_defn_list( "BoundaryConditions.c")] = outstr.replace("BaikalETK", ThornName) # PART 2: Set C code for calling NewRad BCs # As explained in lean_public/LeanBSSNMoL/src/calc_bssn_rhs.F90, # the function NewRad_Apply takes the following arguments: # NewRad_Apply(cctkGH, var, rhs, var0, v0, radpower), # which implement the boundary condition: # var = var_at_infinite_r + u(r-var_char_speed*t)/r^var_radpower # Obviously for var_radpower>0, var_at_infinite_r is the value of # the variable at r->infinity. var_char_speed is the propagation # speed at the outer boundary, and var_radpower is the radial # falloff rate. outstr = """ #include <math.h> #include "cctk.h" #include "cctk_Arguments.h" #include "cctk_Parameters.h" void BaikalETK_NewRad(CCTK_ARGUMENTS) { DECLARE_CCTK_ARGUMENTS; DECLARE_CCTK_PARAMETERS; """ for gf in evol_gfs_list: var_at_infinite_r = "0.0" var_char_speed = "1.0" var_radpower = "1.0" if gf == "alpha": var_at_infinite_r = "1.0" if LapseCondition == "OnePlusLog": var_char_speed = "sqrt(2.0)" else: pass # 1.0 (default) is fine if "aDD" in gf or "trK" in gf: # consistent with Lean code. var_radpower = "2.0" outstr += " NewRad_Apply(cctkGH, " + gf + ", " + gf.replace( "GF", "" ) + "_rhsGF, " + var_at_infinite_r + ", " + var_char_speed + ", " + var_radpower + ");\n" outstr += "}\n" # Add C code string to dictionary (Python dictionaries are immutable) Csrcdict[append_to_make_code_defn_list( "BoundaryCondition_NewRad.c")] = outstr.replace( "BaikalETK", ThornName) # First we convert from ADM to BSSN, as is required to convert initial data # (given using) ADM quantities, to the BSSN evolved variables import BSSN.ADM_Numerical_Spherical_or_Cartesian_to_BSSNCurvilinear as atob IDhDD,IDaDD,IDtrK,IDvetU,IDbetU,IDalpha,IDcf,IDlambdaU = \ atob.Convert_Spherical_or_Cartesian_ADM_to_BSSN_curvilinear("Cartesian","DoNotOutputADMInputFunction",os.path.join(ThornName,"src")) # Store the original list of registered gridfunctions; we'll want to unregister # all the *SphorCart* gridfunctions after we're finished with them below. orig_glb_gridfcs_list = [] for gf in gri.glb_gridfcs_list: orig_glb_gridfcs_list.append(gf) alphaSphorCart = gri.register_gridfunctions("AUXEVOL", "alphaSphorCart") betaSphorCartU = ixp.register_gridfunctions_for_single_rank1( "AUXEVOL", "betaSphorCartU") BSphorCartU = ixp.register_gridfunctions_for_single_rank1( "AUXEVOL", "BSphorCartU") gammaSphorCartDD = ixp.register_gridfunctions_for_single_rank2( "AUXEVOL", "gammaSphorCartDD", "sym01") KSphorCartDD = ixp.register_gridfunctions_for_single_rank2( "AUXEVOL", "KSphorCartDD", "sym01") # ADM to BSSN conversion, used for converting ADM initial data into a form readable by this thorn. # ADM to BSSN, Part 1: Set up function call and pointers to ADM gridfunctions outstr = """ #include <math.h> #include "cctk.h" #include "cctk_Arguments.h" #include "cctk_Parameters.h" void BaikalETK_ADM_to_BSSN(CCTK_ARGUMENTS) { DECLARE_CCTK_ARGUMENTS; DECLARE_CCTK_PARAMETERS; CCTK_REAL *alphaSphorCartGF = alp; """ # It's ugly if we output code in the following ordering, so we'll first # output to a string and then sort the string to beautify the code a bit. outstrtmp = [] for i in range(3): outstrtmp.append(" CCTK_REAL *betaSphorCartU" + str(i) + "GF = beta" + chr(ord('x') + i) + ";\n") outstrtmp.append(" CCTK_REAL *BSphorCartU" + str(i) + "GF = dtbeta" + chr(ord('x') + i) + ";\n") for j in range(i, 3): outstrtmp.append(" CCTK_REAL *gammaSphorCartDD" + str(i) + str(j) + "GF = g" + chr(ord('x') + i) + chr(ord('x') + j) + ";\n") outstrtmp.append(" CCTK_REAL *KSphorCartDD" + str(i) + str(j) + "GF = k" + chr(ord('x') + i) + chr(ord('x') + j) + ";\n") outstrtmp.sort() for line in outstrtmp: outstr += line # ADM to BSSN, Part 2: Set up ADM to BSSN conversions for BSSN gridfunctions that do not require # finite-difference derivatives (i.e., all gridfunctions except lambda^i (=Gamma^i # in non-covariant BSSN)): # h_{ij}, a_{ij}, trK, vet^i=beta^i,bet^i=B^i, cf (conformal factor), and alpha all_but_lambdaU_expressions = [ lhrh(lhs=gri.gfaccess("in_gfs", "hDD00"), rhs=IDhDD[0][0]), lhrh(lhs=gri.gfaccess("in_gfs", "hDD01"), rhs=IDhDD[0][1]), lhrh(lhs=gri.gfaccess("in_gfs", "hDD02"), rhs=IDhDD[0][2]), lhrh(lhs=gri.gfaccess("in_gfs", "hDD11"), rhs=IDhDD[1][1]), lhrh(lhs=gri.gfaccess("in_gfs", "hDD12"), rhs=IDhDD[1][2]), lhrh(lhs=gri.gfaccess("in_gfs", "hDD22"), rhs=IDhDD[2][2]), lhrh(lhs=gri.gfaccess("in_gfs", "aDD00"), rhs=IDaDD[0][0]), lhrh(lhs=gri.gfaccess("in_gfs", "aDD01"), rhs=IDaDD[0][1]), lhrh(lhs=gri.gfaccess("in_gfs", "aDD02"), rhs=IDaDD[0][2]), lhrh(lhs=gri.gfaccess("in_gfs", "aDD11"), rhs=IDaDD[1][1]), lhrh(lhs=gri.gfaccess("in_gfs", "aDD12"), rhs=IDaDD[1][2]), lhrh(lhs=gri.gfaccess("in_gfs", "aDD22"), rhs=IDaDD[2][2]), lhrh(lhs=gri.gfaccess("in_gfs", "trK"), rhs=IDtrK), lhrh(lhs=gri.gfaccess("in_gfs", "vetU0"), rhs=IDvetU[0]), lhrh(lhs=gri.gfaccess("in_gfs", "vetU1"), rhs=IDvetU[1]), lhrh(lhs=gri.gfaccess("in_gfs", "vetU2"), rhs=IDvetU[2]), lhrh(lhs=gri.gfaccess("in_gfs", "betU0"), rhs=IDbetU[0]), lhrh(lhs=gri.gfaccess("in_gfs", "betU1"), rhs=IDbetU[1]), lhrh(lhs=gri.gfaccess("in_gfs", "betU2"), rhs=IDbetU[2]), lhrh(lhs=gri.gfaccess("in_gfs", "alpha"), rhs=IDalpha), lhrh(lhs=gri.gfaccess("in_gfs", "cf"), rhs=IDcf) ] outCparams = "preindent=1,outCfileaccess=a,outCverbose=False,includebraces=False" all_but_lambdaU_outC = fin.FD_outputC("returnstring", all_but_lambdaU_expressions, outCparams) outstr += lp.loop(["i2", "i1", "i0"], ["0", "0", "0"], ["cctk_lsh[2]", "cctk_lsh[1]", "cctk_lsh[0]"], ["1", "1", "1"], ["#pragma omp parallel for", "", ""], " ", all_but_lambdaU_outC) # ADM to BSSN, Part 3: Set up ADM to BSSN conversions for BSSN gridfunctions defined from # finite-difference derivatives: lambda^i, which is Gamma^i in non-covariant BSSN): outstr += """ const CCTK_REAL invdx0 = 1.0/CCTK_DELTA_SPACE(0); const CCTK_REAL invdx1 = 1.0/CCTK_DELTA_SPACE(1); const CCTK_REAL invdx2 = 1.0/CCTK_DELTA_SPACE(2); """ path = os.path.join(ThornName, "src") BSSN_RHS_FD_orders_output = [] for root, dirs, files in os.walk(path): for file in files: if "BSSN_RHSs_FD_order" in file: array = file.replace(".", "_").split("_") BSSN_RHS_FD_orders_output.append(int(array[4])) for current_FD_order in BSSN_RHS_FD_orders_output: # Store original finite-differencing order: orig_FD_order = par.parval_from_str( "finite_difference::FD_CENTDERIVS_ORDER") # Set new finite-differencing order: par.set_parval_from_str("finite_difference::FD_CENTDERIVS_ORDER", current_FD_order) outCparams = "preindent=1,outCfileaccess=a,outCverbose=False,includebraces=False" lambdaU_expressions = [ lhrh(lhs=gri.gfaccess("in_gfs", "lambdaU0"), rhs=IDlambdaU[0]), lhrh(lhs=gri.gfaccess("in_gfs", "lambdaU1"), rhs=IDlambdaU[1]), lhrh(lhs=gri.gfaccess("in_gfs", "lambdaU2"), rhs=IDlambdaU[2]) ] lambdaU_expressions_FDout = fin.FD_outputC("returnstring", lambdaU_expressions, outCparams) lambdafile = "ADM_to_BSSN__compute_lambdaU_FD_order_" + str( current_FD_order) + ".h" with open(os.path.join(ThornName, "src", lambdafile), "w") as file: file.write( lp.loop(["i2", "i1", "i0"], [ "cctk_nghostzones[2]", "cctk_nghostzones[1]", "cctk_nghostzones[0]" ], [ "cctk_lsh[2]-cctk_nghostzones[2]", "cctk_lsh[1]-cctk_nghostzones[1]", "cctk_lsh[0]-cctk_nghostzones[0]" ], ["1", "1", "1"], ["#pragma omp parallel for", "", ""], "", lambdaU_expressions_FDout)) outstr += " if(FD_order == " + str(current_FD_order) + ") {\n" outstr += " #include \"" + lambdafile + "\"\n" outstr += " }\n" # Restore original FD order par.set_parval_from_str("finite_difference::FD_CENTDERIVS_ORDER", orig_FD_order) outstr += """ ExtrapolateGammas(cctkGH,lambdaU0GF); ExtrapolateGammas(cctkGH,lambdaU1GF); ExtrapolateGammas(cctkGH,lambdaU2GF); } """ # Unregister the *SphorCartGF's. gri.glb_gridfcs_list = orig_glb_gridfcs_list # Add C code string to dictionary (Python dictionaries are immutable) Csrcdict[append_to_make_code_defn_list("ADM_to_BSSN.c")] = outstr.replace( "BaikalETK", ThornName) import BSSN.ADM_in_terms_of_BSSN as btoa import BSSN.BSSN_quantities as Bq btoa.ADM_in_terms_of_BSSN() Bq.BSSN_basic_tensors() # Gives us betaU & BU outstr = """ #include <math.h> #include "cctk.h" #include "cctk_Arguments.h" #include "cctk_Parameters.h" void BaikalETK_BSSN_to_ADM(CCTK_ARGUMENTS) { DECLARE_CCTK_ARGUMENTS; DECLARE_CCTK_PARAMETERS; """ btoa_lhrh = [] for i in range(3): for j in range(i, 3): btoa_lhrh.append( lhrh(lhs="g" + chr(ord('x') + i) + chr(ord('x') + j) + "[CCTK_GFINDEX3D(cctkGH,i0,i1,i2)]", rhs=btoa.gammaDD[i][j])) for i in range(3): for j in range(i, 3): btoa_lhrh.append( lhrh(lhs="k" + chr(ord('x') + i) + chr(ord('x') + j) + "[CCTK_GFINDEX3D(cctkGH,i0,i1,i2)]", rhs=btoa.KDD[i][j])) btoa_lhrh.append( lhrh(lhs="alp[CCTK_GFINDEX3D(cctkGH,i0,i1,i2)]", rhs=Bq.alpha)) for i in range(3): btoa_lhrh.append( lhrh(lhs="beta" + chr(ord('x') + i) + "[CCTK_GFINDEX3D(cctkGH,i0,i1,i2)]", rhs=Bq.betaU[i])) for i in range(3): btoa_lhrh.append( lhrh(lhs="dtbeta" + chr(ord('x') + i) + "[CCTK_GFINDEX3D(cctkGH,i0,i1,i2)]", rhs=Bq.BU[i])) outCparams = "preindent=1,outCfileaccess=a,outCverbose=False,includebraces=False" bssn_to_adm_Ccode = fin.FD_outputC("returnstring", btoa_lhrh, outCparams) outstr += lp.loop(["i2", "i1", "i0"], ["0", "0", "0"], ["cctk_lsh[2]", "cctk_lsh[1]", "cctk_lsh[0]"], ["1", "1", "1"], ["#pragma omp parallel for", "", ""], "", bssn_to_adm_Ccode) outstr += "}\n" # Add C code string to dictionary (Python dictionaries are immutable) Csrcdict[append_to_make_code_defn_list("BSSN_to_ADM.c")] = outstr.replace( "BaikalETK", ThornName) # Next, the driver for computing the Ricci tensor: outstr = """ #include <math.h> #include "SIMD/SIMD_intrinsics.h" #include "cctk.h" #include "cctk_Arguments.h" #include "cctk_Parameters.h" void BaikalETK_driver_pt1_BSSN_Ricci(CCTK_ARGUMENTS) { DECLARE_CCTK_ARGUMENTS; const CCTK_INT *FD_order = CCTK_ParameterGet("FD_order","BaikalETK",NULL); const CCTK_REAL NOSIMDinvdx0 = 1.0/CCTK_DELTA_SPACE(0); const REAL_SIMD_ARRAY invdx0 = ConstSIMD(NOSIMDinvdx0); const CCTK_REAL NOSIMDinvdx1 = 1.0/CCTK_DELTA_SPACE(1); const REAL_SIMD_ARRAY invdx1 = ConstSIMD(NOSIMDinvdx1); const CCTK_REAL NOSIMDinvdx2 = 1.0/CCTK_DELTA_SPACE(2); const REAL_SIMD_ARRAY invdx2 = ConstSIMD(NOSIMDinvdx2); """ path = os.path.join(ThornName, "src") for root, dirs, files in os.walk(path): for file in files: if "BSSN_Ricci_FD_order" in file: array = file.replace(".", "_").split("_") outstr += " if(*FD_order == " + str(array[4]) + ") {\n" outstr += " #include \"" + file + "\"\n" outstr += " }\n" outstr += "}\n" # Add C code string to dictionary (Python dictionaries are immutable) Csrcdict[append_to_make_code_defn_list( "driver_pt1_BSSN_Ricci.c")] = outstr.replace("BaikalETK", ThornName) def SIMD_declare_C_params(): SIMD_declare_C_params_str = "" for i in range(len(par.glb_Cparams_list)): # keep_param is a boolean indicating whether we should accept or reject # the parameter. singleparstring will contain the string indicating # the variable type. keep_param, singleparstring = ccl.keep_param__return_type( par.glb_Cparams_list[i]) if (keep_param) and ("CCTK_REAL" in singleparstring): parname = par.glb_Cparams_list[i].parname SIMD_declare_C_params_str += " const "+singleparstring + "*NOSIMD"+parname+\ " = CCTK_ParameterGet(\""+parname+"\",\"BaikalETK\",NULL);\n" SIMD_declare_C_params_str += " const REAL_SIMD_ARRAY " + parname + " = ConstSIMD(*NOSIMD" + parname + ");\n" return SIMD_declare_C_params_str # Next, the driver for computing the BSSN RHSs: outstr = """ #include <math.h> #include "SIMD/SIMD_intrinsics.h" #include "cctk.h" #include "cctk_Arguments.h" #include "cctk_Parameters.h" void BaikalETK_driver_pt2_BSSN_RHSs(CCTK_ARGUMENTS) { DECLARE_CCTK_ARGUMENTS; const CCTK_INT *FD_order = CCTK_ParameterGet("FD_order","BaikalETK",NULL); const CCTK_REAL NOSIMDinvdx0 = 1.0/CCTK_DELTA_SPACE(0); const REAL_SIMD_ARRAY invdx0 = ConstSIMD(NOSIMDinvdx0); const CCTK_REAL NOSIMDinvdx1 = 1.0/CCTK_DELTA_SPACE(1); const REAL_SIMD_ARRAY invdx1 = ConstSIMD(NOSIMDinvdx1); const CCTK_REAL NOSIMDinvdx2 = 1.0/CCTK_DELTA_SPACE(2); const REAL_SIMD_ARRAY invdx2 = ConstSIMD(NOSIMDinvdx2); """ + SIMD_declare_C_params() path = os.path.join(ThornName, "src") for root, dirs, files in os.walk(path): for file in files: if "BSSN_RHSs_FD_order" in file: array = file.replace(".", "_").split("_") outstr += " if(*FD_order == " + str(array[4]) + ") {\n" outstr += " #include \"" + file + "\"\n" outstr += " }\n" outstr += "}\n" # Add C code string to dictionary (Python dictionaries are immutable) Csrcdict[append_to_make_code_defn_list( "driver_pt2_BSSN_RHSs.c")] = outstr.replace("BaikalETK", ThornName) # Next, the driver for enforcing detgammabar = detgammahat constraint: outstr = """ #include <math.h> #include "cctk.h" #include "cctk_Arguments.h" #include "cctk_Parameters.h" void BaikalETK_enforce_detgammabar_constraint(CCTK_ARGUMENTS) { DECLARE_CCTK_ARGUMENTS; DECLARE_CCTK_PARAMETERS; """ path = os.path.join(ThornName, "src") for root, dirs, files in os.walk(path): for file in files: if "enforcedetgammabar_constraint_FD_order" in file: array = file.replace(".", "_").split("_") outstr += " if(FD_order == " + str(array[4]) + ") {\n" outstr += " #include \"" + file + "\"\n" outstr += " }\n" outstr += "}\n" # Add C code string to dictionary (Python dictionaries are immutable) Csrcdict[append_to_make_code_defn_list("driver_enforcedetgammabar_constraint.c")] = \ outstr.replace("BaikalETK",ThornName) # Next, the driver for computing the BSSN Hamiltonian & momentum constraints outstr = """ #include <math.h> #include "cctk.h" #include "cctk_Arguments.h" #include "cctk_Parameters.h" void BaikalETK_BSSN_constraints(CCTK_ARGUMENTS) { DECLARE_CCTK_ARGUMENTS; DECLARE_CCTK_PARAMETERS; const CCTK_REAL invdx0 = 1.0/CCTK_DELTA_SPACE(0); const CCTK_REAL invdx1 = 1.0/CCTK_DELTA_SPACE(1); const CCTK_REAL invdx2 = 1.0/CCTK_DELTA_SPACE(2); """ path = os.path.join(ThornName, "src") for root, dirs, files in os.walk(path): for file in files: if "BSSN_constraints_FD_order" in file: array = file.replace(".", "_").split("_") outstr += " if(FD_order == " + str(array[4]) + ") {\n" outstr += " #include \"" + file + "\"\n" outstr += " }\n" outstr += "}\n" # Add C code string to dictionary (Python dictionaries are immutable) Csrcdict[append_to_make_code_defn_list( "driver_BSSN_constraints.c")] = outstr.replace("BaikalETK", ThornName) if enable_stress_energy_source_terms == True: # Declare T4DD as a set of gridfunctions. These won't # actually appear in interface.ccl, as interface.ccl # was set above. Thus before calling the code output # by FD_outputC(), we'll have to set pointers # to the actual gridfunctions they reference. # (In this case the eTab's.) T4DD = ixp.register_gridfunctions_for_single_rank2("AUXEVOL", "T4DD", "sym01", DIM=4) import BSSN.ADMBSSN_tofrom_4metric as AB4m AB4m.g4UU_ito_BSSN_or_ADM("BSSN") T4UUraised = ixp.zerorank2(DIM=4) for mu in range(4): for nu in range(4): for delta in range(4): for gamma in range(4): T4UUraised[mu][nu] += AB4m.g4UU[mu][delta] * AB4m.g4UU[ nu][gamma] * T4DD[delta][gamma] T4UU_expressions = [ lhrh(lhs=gri.gfaccess("in_gfs", "T4UU00"), rhs=T4UUraised[0][0]), lhrh(lhs=gri.gfaccess("in_gfs", "T4UU01"), rhs=T4UUraised[0][1]), lhrh(lhs=gri.gfaccess("in_gfs", "T4UU02"), rhs=T4UUraised[0][2]), lhrh(lhs=gri.gfaccess("in_gfs", "T4UU03"), rhs=T4UUraised[0][3]), lhrh(lhs=gri.gfaccess("in_gfs", "T4UU11"), rhs=T4UUraised[1][1]), lhrh(lhs=gri.gfaccess("in_gfs", "T4UU12"), rhs=T4UUraised[1][2]), lhrh(lhs=gri.gfaccess("in_gfs", "T4UU13"), rhs=T4UUraised[1][3]), lhrh(lhs=gri.gfaccess("in_gfs", "T4UU22"), rhs=T4UUraised[2][2]), lhrh(lhs=gri.gfaccess("in_gfs", "T4UU23"), rhs=T4UUraised[2][3]), lhrh(lhs=gri.gfaccess("in_gfs", "T4UU33"), rhs=T4UUraised[3][3]) ] outCparams = "outCverbose=False,includebraces=False,preindent=2,SIMD_enable=True" T4UUstr = fin.FD_outputC("returnstring", T4UU_expressions, outCparams) T4UUstr_loop = lp.loop(["i2", "i1", "i0"], ["0", "0", "0"], ["cctk_lsh[2]", "cctk_lsh[1]", "cctk_lsh[0]"], ["1", "1", "SIMD_width"], ["#pragma omp parallel for", "", ""], "", T4UUstr) outstr = """ #include <math.h> #include "cctk.h" #include "cctk_Arguments.h" #include "cctk_Parameters.h" #include "SIMD/SIMD_intrinsics.h" void BaikalETK_driver_BSSN_T4UU(CCTK_ARGUMENTS) { DECLARE_CCTK_ARGUMENTS; DECLARE_CCTK_PARAMETERS; const CCTK_REAL *restrict T4DD00GF = eTtt; const CCTK_REAL *restrict T4DD01GF = eTtx; const CCTK_REAL *restrict T4DD02GF = eTty; const CCTK_REAL *restrict T4DD03GF = eTtz; const CCTK_REAL *restrict T4DD11GF = eTxx; const CCTK_REAL *restrict T4DD12GF = eTxy; const CCTK_REAL *restrict T4DD13GF = eTxz; const CCTK_REAL *restrict T4DD22GF = eTyy; const CCTK_REAL *restrict T4DD23GF = eTyz; const CCTK_REAL *restrict T4DD33GF = eTzz; """ + T4UUstr_loop + """ }\n""" # Add C code string to dictionary (Python dictionaries are immutable) Csrcdict[append_to_make_code_defn_list( "driver_BSSN_T4UU.c")] = outstr.replace("BaikalETK", ThornName)
'id1': id1, 'class0': class0, 'class1': class1 }) snapshots = [] start_time = links[0]['time'] end_time = links[len(links)-1]['time'] flag = 0 link_number = 0 interval_time = 360 snapshot_time = 3600 while start_time + flag * interval_time - interval_time <= end_time - snapshot_time: if link_number >= len(links): break link_graph, link_number = loop(links, link_number, start_time, flag, interval_time, snapshot_time) snapshots.append(link_graph) flag += 1 nodes = Nodes(snapshots) graphs = [] graphs_nodes = [] for snapshot in snapshots: graph, graph_nodes = network(snapshot, nodes) graphs.append(graph) graphs_nodes.append(graph_nodes) vectors = [] for num in range(len(graphs)): vector = matrix(graphs, num) vectors.append(vector)
import loop # Are we on the right host machine? hostname = socket.gethostname() if not ("psexport" in hostname or "login" == hostname): sys.exit("ERROR: Cannot submit jobs from this host. You are logged in to %s but you need to be logged in to psexport or davinci (login node) to submit jobs to the queue." % hostname) # Read configuration if len(sys.argv) < 2: sys.exit("Usage: cheman_server.py cheman_server.cfg") #debug = False #if len(sys.argv) >= 3: # if sys.argv[2] == "DEBUG": # debug = True configfilename = sys.argv[1] #print "Gmail login" #email = raw_input("Email address: ") #password = getpass.getpass("Password: "******"WARNING: loop() crashed, restarting..."
#this is the size of the chunks which are used for faster scene loading const.CHUNK_SIZE = 40 #odds WHO doctors will spawn # for example: 10 will give one in ten const.WHO_ODDS = 100 const.NOG_ODDS = 10 #getting the users home directory from os.path import expanduser const.HOME = expanduser("~") ############################################## gameloop = loop.loop() if __name__=="__main__": gameloop.run()
geigerPower = pyb.Pin('Y9', pyb.Pin.OUT_PP) #relay for power geiger geigerPower.high() #turn off geigerIn = pyb.Pin('Y10', pyb.Pin.IN) #pitido inicial en salida Y8 tim12 = pyb.Timer(12, freq=3500) ch2=tim12.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.Y8, pulse_width=12000) pyb.delay(100) #in msecs ch2.pulse_width(0) #uart6 a wixel, pins Y1 y Y2 uart = UART(6,9600) uart.init(9600,bits=8,stop=1,parity=None) pyb.repl_uart(uart) #initalize fram fr = fram.fram() frt = fram_t.fram_t(fr) #rtc rtc = pyb.RTC() #initialize am2302 a = am2302.am2302(ch2, frt) #initialize loop l = loop.loop(geigerPower, a, fr, frt, ch2, uart, wixel) #initialize commands cms = commands.commands(rtc, fr, frt)
import getpass import loop # Are we on the right host machine? hostname = socket.gethostname() if not ("psexport" in hostname or "login" == hostname): sys.exit("ERROR: Cannot submit jobs from this host. You are logged in to %s but you need to be logged in to psexport or davinci (login node) to simultaneously submit jobs to the queue and communicate with the google spreadsheet." % hostname) # Read configuration if len(sys.argv) < 2: sys.exit("Usage: cheetah_manager.py cheetah_manager.cfg") debug = False if len(sys.argv) >= 3: if sys.argv[2] == "DEBUG": debug = True configfilename = sys.argv[1] print "Gmail login" password = getpass.getpass() if debug: loop.loop(configfilename,password) else: while True: try: loop.loop(configfilename,password) except: print "WARNING: loop() crashed, restarting..."
def run_loops_generation(self): ranks = list(set(map(lambda x: x.rank, self.callstacks))) # First one loop per rank is done. After the generation step, the # rank merge step is done. # ranks_loops=[] # If aliasing is detected, every subloop will be an independent loop # object. After generation, the cluster is divided into sub-clusters # ranks_subloops=[] loops_id = 0 for rank in ranks: callstacks = list(filter(lambda x: x.rank == rank, self.callstacks)) # Trying to remove aliasing by a new clustering dimension... # On that case, just code after the "else" is needed aliasing_detector=tmatrix.from_callstacks_obj(callstacks) if aliasing_detector.aliased(): callstack_parts = aliasing_detector.get_subloops() subloops = [] for x in callstack_parts: new_loop = loop(callstacks=x,id=loops_id) new_loop.cluster_id = self.cluster_id subloops.append(new_loop) loops_id += 1 ranks_subloops.append(subloops) else: new_loop = loop(callstacks=callstacks, id=loops_id) new_loop.cluster_id = self.cluster_id ranks_loops.append(new_loop) loops_id += 1 if len(ranks_loops) > 0: self.loops.append(self.__ranks_level_merge(ranks_loops)) self.nloops = 1 elif len(ranks_subloops) > 0: # Here i am assuming that all subloops of all ranks are related # between them in function of the order they appear in the ranks_ # subloop. # ranks_subloops = [ [loop1.1, loop1.2, loop1.3], # [loop2.1, loop2.2, loop2.3]] # | | | # merged merged merged ssubloops = [] nsubloops = 0 for i in range(len(max(ranks_subloops))): loops_to_merge = [] for subloops in ranks_subloops: if len(subloops) > i: loops_to_merge.append(subloops[i]) merged_ranks_loop = self.__ranks_level_merge(loops_to_merge) ssubloops.append(merged_ranks_loop) nsubloops += 1 # self.loops.append(merged_ranks_loop) # self.nloops += 1 if aliasing_detector.is_hidden_superloop(): superloop = loop(callstacks=[], id=-1) # Void loop superloop.cluster_id = self.cluster_id superloop.iterations = aliasing_detector\ .get_hidden_superloop_its() superloop.original_iterations = superloop.iterations superloop.set_hidden_loop() logging.debug("Cluster {0}: Superloop detected ({1} its)" .format(self.cluster_id, superloop.iterations)) for sl in ssubloops: superloop.merge_with_subloop(sl) self.loops.append(superloop) self.nloops = 1 else: self.loops.extend(ssubloops) self.nloops = nsubloops else: assert False, "Not managed situation." self.loops_generation_done = True
const.OFFSET_X = 0 const.OFFSET_Y = 0 #this is the size of the screen in tiles, by multiplying LENGTH with SCALE you get the total screen size in pixels #I forget why I have LENGTH WIDE X/Y, marked for removal const.LENGTH_X = 40 const.LENGTH_Y = 30 const.LARGE_X = const.SCALE * LENGTH_X const.LARGE_Y = const.SCALE * LENGHT_Y #this is the size of the chunks which are used for faster scene loading const.CHUNK_SIZE = 40 #odds WHO doctors will spawn # for example: 10 will give one in ten const.WHO_ODDS = 100 const.NOG_ODDS = 10 #getting the users home directory from os.path import expanduser const.HOME = expanduser("~") ############################################## gameloop = loop.loop() if __name__ == "__main__": gameloop.run()
def Tmunu_Numerical_Spherical_or_Cartesian_to_BSSNCurvilinear( CoordType_in, Tmunu_input_function_name, pointer_to_ID_inputs=False): # The ADM & BSSN formalisms only work in 3D; they are 3+1 decompositions of Einstein's equations. # To implement axisymmetry or spherical symmetry, simply set all spatial derivatives in # the relevant angular directions to zero; DO NOT SET DIM TO ANYTHING BUT 3. # Step 0: Set spatial dimension (must be 3 for BSSN) DIM = 3 # Step 1: Define the input variables: the 4D stress-energy tensor, and the ADM 3-metric, lapse, & shift: T4SphorCartUU = ixp.declarerank2("T4SphorCartUU", "sym01", DIM=4) gammaSphorCartDD = ixp.declarerank2("gammaSphorCartDD", "sym01") alphaSphorCart = sp.symbols("alphaSphorCart") betaSphorCartU = ixp.declarerank1("betaSphorCartU") # Step 2: All Tmunu initial data quantities are functions of xx0,xx1,xx2, but # in the Spherical or Cartesian basis. # We first define the BSSN stress-energy source terms in the Spherical # or Cartesian basis, respectively. # To get \gamma_{\mu \nu} = gammabar4DD[mu][nu], we'll need to construct the 4-metric, using Eq. 2.122 in B&S: # S_{ij} = \gamma_{i \mu} \gamma_{j \nu} T^{\mu \nu} # S_{i} = -\gamma_{i\mu} n_\nu T^{\mu\nu} # S = \gamma^{ij} S_{ij} # rho = n_\mu n_\nu T^{\mu\nu}, # where # \gamma_{\mu\nu} = g_{\mu\nu} + n_\mu n_\nu # and # n_mu = {-\alpha,0,0,0}, # Step 2.1: Construct the 4-metric based on the input ADM quantities. # This is provided by Eq 4.47 in [Gourgoulhon](https://arxiv.org/pdf/gr-qc/0703035.pdf): # g_{tt} = -\alpha^2 + \beta^k \beta_k # g_{ti} = \beta_i # g_{ij} = \gamma_{ij} # Eq. 2.121 in B&S betaSphorCartD = ixp.zerorank1() for i in range(DIM): for j in range(DIM): betaSphorCartD[i] += gammaSphorCartDD[i][j] * betaSphorCartU[j] # Now compute the beta contraction. beta2 = sp.sympify(0) for i in range(DIM): beta2 += betaSphorCartU[i] * betaSphorCartD[i] # Eq. 2.122 in B&S g4SphorCartDD = ixp.zerorank2(DIM=4) g4SphorCartDD[0][0] = -alphaSphorCart**2 + beta2 for i in range(DIM): g4SphorCartDD[i + 1][0] = g4SphorCartDD[0][i + 1] = betaSphorCartD[i] for i in range(DIM): for j in range(DIM): g4SphorCartDD[i + 1][j + 1] = gammaSphorCartDD[i][j] # Step 2.2: Construct \gamma_{mu nu} = g_{mu nu} + n_mu n_nu: n4SphorCartD = ixp.zerorank1(DIM=4) n4SphorCartD[0] = -alphaSphorCart gamma4SphorCartDD = ixp.zerorank2(DIM=4) for mu in range(4): for nu in range(4): gamma4SphorCartDD[mu][nu] = g4SphorCartDD[mu][ nu] + n4SphorCartD[mu] * n4SphorCartD[nu] # Step 2.3: We now have all we need to construct the BSSN source # terms in the current basis (Spherical or Cartesian): # S_{ij} = \gamma_{i \mu} \gamma_{j \nu} T^{\mu \nu} # S_{i} = -\gamma_{i\mu} n_\nu T^{\mu\nu} # S = \gamma^{ij} S_{ij} # rho = n_\mu n_\nu T^{\mu\nu}, SSphorCartDD = ixp.zerorank2() SSphorCartD = ixp.zerorank1() SSphorCart = sp.sympify(0) rhoSphorCart = sp.sympify(0) for i in range(DIM): for j in range(DIM): for mu in range(4): for nu in range(4): SSphorCartDD[i][j] += gamma4SphorCartDD[ i + 1][mu] * gamma4SphorCartDD[ j + 1][nu] * T4SphorCartUU[mu][nu] for i in range(DIM): for mu in range(4): for nu in range(4): SSphorCartD[i] += -gamma4SphorCartDD[ i + 1][mu] * n4SphorCartD[nu] * T4SphorCartUU[mu][nu] gammaSphorCartUU, gammaDET = ixp.symm_matrix_inverter3x3(gammaSphorCartDD) for i in range(DIM): for j in range(DIM): SSphorCart += gammaSphorCartUU[i][j] * SSphorCartDD[i][j] for mu in range(4): for nu in range(4): rhoSphorCart += n4SphorCartD[mu] * n4SphorCartD[ nu] * T4SphorCartUU[mu][nu] # Step 3: Perform basis conversion to # Make sure that rfm.reference_metric() has been called. # We'll need the variables it defines throughout this module. if rfm.have_already_called_reference_metric_function == False: print( "Error. Called Tmunu_Numerical_Spherical_or_Cartesian_to_BSSNCurvilinear() without" ) print( " first setting up reference metric, by calling rfm.reference_metric()." ) exit(1) # Step 1: All input quantities are in terms of r,th,ph or x,y,z. We want them in terms # of xx0,xx1,xx2, so here we call sympify_integers__replace_rthph() to replace # r,th,ph or x,y,z, respectively, with the appropriate functions of xx0,xx1,xx2 # as defined for this particular reference metric in reference_metric.py's # xxSph[] or xxCart[], respectively: r_th_ph_or_Cart_xyz_oID_xx = [] if CoordType_in == "Spherical": r_th_ph_or_Cart_xyz_oID_xx = rfm.xxSph elif CoordType_in == "Cartesian": r_th_ph_or_Cart_xyz_oID_xx = rfm.xxCart else: print( "Error: Can only convert ADM Cartesian or Spherical initial data to BSSN Curvilinear coords." ) exit(1) # Next apply Jacobian transformations to convert into the (xx0,xx1,xx2) basis # alpha is a scalar, so no Jacobian transformation is necessary. alpha = alphaSphorCart Jac_dUSphorCart_dDrfmUD = ixp.zerorank2() for i in range(DIM): for j in range(DIM): Jac_dUSphorCart_dDrfmUD[i][j] = sp.diff( r_th_ph_or_Cart_xyz_oID_xx[i], rfm.xx[j]) Jac_dUrfm_dDSphorCartUD, dummyDET = ixp.generic_matrix_inverter3x3( Jac_dUSphorCart_dDrfmUD) betaU = ixp.zerorank1() BU = ixp.zerorank1() gammaSphorCartDD = ixp.zerorank2() KDD = ixp.zerorank2() for i in range(DIM): for j in range(DIM): betaU[i] += Jac_dUrfm_dDSphorCartUD[i][j] * betaSphorCartU[j] BU[i] += Jac_dUrfm_dDSphorCartUD[i][j] * BSphorCartU[j] for k in range(DIM): for l in range(DIM): gammaSphorCartDD[i][j] += Jac_dUSphorCart_dDrfmUD[k][i] * Jac_dUSphorCart_dDrfmUD[l][j] * \ gammaSphorCartDD[k][l] KDD[i][j] += Jac_dUSphorCart_dDrfmUD[k][ i] * Jac_dUSphorCart_dDrfmUD[l][j] * KSphorCartDD[k][l] # Step 3: All ADM quantities were input into this function in the Spherical or Cartesian # basis, as functions of r,th,ph or x,y,z, respectively. In Steps 1 and 2 above, # we converted them to the xx0,xx1,xx2 basis, and as functions of xx0,xx1,xx2. # Here we convert ADM quantities to their BSSN Curvilinear counterparts: # Step 3.1: Convert ADM $\gamma_{ij}$ to BSSN $\bar{\gamma}_{ij}$: # We have (Eqs. 2 and 3 of [Ruchlin *et al.*](https://arxiv.org/pdf/1712.07658.pdf)): # \bar{\gamma}_{i j} = \left(\frac{\bar{\gamma}}{\gamma}\right)^{1/3} \gamma_{ij}. gammaSphorCartUU, gammaDET = ixp.symm_matrix_inverter3x3(gammaSphorCartDD) gammabarDD = ixp.zerorank2() for i in range(DIM): for j in range(DIM): gammabarDD[i][j] = (rfm.detgammahat / gammaDET)**(sp.Rational( 1, 3)) * gammaSphorCartDD[i][j] # Step 3.2: Convert the extrinsic curvature $K_{ij}$ to the trace-free extrinsic # curvature $\bar{A}_{ij}$, plus the trace of the extrinsic curvature $K$, # where (Eq. 3 of [Baumgarte *et al.*](https://arxiv.org/pdf/1211.6632.pdf)): # K = \gamma^{ij} K_{ij}, and # \bar{A}_{ij} &= \left(\frac{\bar{\gamma}}{\gamma}\right)^{1/3} \left(K_{ij} - \frac{1}{3} \gamma_{ij} K \right) trK = sp.sympify(0) for i in range(DIM): for j in range(DIM): trK += gammaSphorCartUU[i][j] * KDD[i][j] AbarDD = ixp.zerorank2() for i in range(DIM): for j in range(DIM): AbarDD[i][j] = (rfm.detgammahat / gammaDET)**(sp.Rational( 1, 3)) * (KDD[i][j] - sp.Rational(1, 3) * gammaSphorCartDD[i][j] * trK) # Step 3.3: Set the conformal factor variable $\texttt{cf}$, which is set # by the "BSSN_RHSs::ConformalFactor" parameter. For example if # "ConformalFactor" is set to "phi", we can use Eq. 3 of # [Ruchlin *et al.*](https://arxiv.org/pdf/1712.07658.pdf), # which in arbitrary coordinates is written: # \phi = \frac{1}{12} \log\left(\frac{\gamma}{\bar{\gamma}}\right). # Alternatively if "BSSN_RHSs::ConformalFactor" is set to "chi", then # \chi = e^{-4 \phi} = \exp\left(-4 \frac{1}{12} \left(\frac{\gamma}{\bar{\gamma}}\right)\right) # = \exp\left(-\frac{1}{3} \log\left(\frac{\gamma}{\bar{\gamma}}\right)\right) = \left(\frac{\gamma}{\bar{\gamma}}\right)^{-1/3}. # # Finally if "BSSN_RHSs::ConformalFactor" is set to "W", then # W = e^{-2 \phi} = \exp\left(-2 \frac{1}{12} \log\left(\frac{\gamma}{\bar{\gamma}}\right)\right) = # \exp\left(-\frac{1}{6} \log\left(\frac{\gamma}{\bar{\gamma}}\right)\right) = # \left(\frac{\gamma}{\bar{\gamma}}\right)^{-1/6}. # First compute gammabarDET: gammabarUU, gammabarDET = ixp.symm_matrix_inverter3x3(gammabarDD) cf = sp.sympify(0) if par.parval_from_str("ConformalFactor") == "phi": cf = sp.Rational(1, 12) * sp.log(gammaDET / gammabarDET) elif par.parval_from_str("ConformalFactor") == "chi": cf = (gammaDET / gammabarDET)**(-sp.Rational(1, 3)) elif par.parval_from_str("ConformalFactor") == "W": cf = (gammaDET / gammabarDET)**(-sp.Rational(1, 6)) else: print("Error ConformalFactor type = \"" + par.parval_from_str("ConformalFactor") + "\" unknown.") exit(1) # Step 4: Rescale tensorial quantities according to the prescription described in # the [BSSN in curvilinear coordinates tutorial module](Tutorial-BSSNCurvilinear.ipynb) # (also [Ruchlin *et al.*](https://arxiv.org/pdf/1712.07658.pdf)): # # h_{ij} &= (\bar{\gamma}_{ij} - \hat{\gamma}_{ij})/\text{ReDD[i][j]}\\ # a_{ij} &= \bar{A}_{ij}/\text{ReDD[i][j]}\\ # \lambda^i &= \bar{\Lambda}^i/\text{ReU[i]}\\ # \mathcal{V}^i &= \beta^i/\text{ReU[i]}\\ # \mathcal{B}^i &= B^i/\text{ReU[i]}\\ hDD = ixp.zerorank2() aDD = ixp.zerorank2() vetU = ixp.zerorank1() betU = ixp.zerorank1() for i in range(DIM): vetU[i] = betaU[i] / rfm.ReU[i] betU[i] = BU[i] / rfm.ReU[i] for j in range(DIM): hDD[i][j] = (gammabarDD[i][j] - rfm.ghatDD[i][j]) / rfm.ReDD[i][j] aDD[i][j] = AbarDD[i][j] / rfm.ReDD[i][j] # Step 5: Output all ADM-to-BSSN expressions to a C function. This function # must first call the ID_ADM_SphorCart() defined above. Using these # Spherical or Cartesian data, it sets up all quantities needed for # BSSNCurvilinear initial data, *except* $\lambda^i$, which must be # computed from numerical data using finite-difference derivatives. with open("BSSN/ID_ADM_xx0xx1xx2_to_BSSN_xx0xx1xx2__ALL_BUT_LAMBDAs.h", "w") as file: file.write( "void ID_ADM_xx0xx1xx2_to_BSSN_xx0xx1xx2__ALL_BUT_LAMBDAs(const REAL xx0xx1xx2[3]," ) if pointer_to_ID_inputs == True: file.write("ID_inputs *other_inputs,") else: file.write("ID_inputs other_inputs,") file.write(""" REAL *hDD00,REAL *hDD01,REAL *hDD02,REAL *hDD11,REAL *hDD12,REAL *hDD22, REAL *aDD00,REAL *aDD01,REAL *aDD02,REAL *aDD11,REAL *aDD12,REAL *aDD22, REAL *trK, REAL *vetU0,REAL *vetU1,REAL *vetU2, REAL *betU0,REAL *betU1,REAL *betU2, REAL *alpha, REAL *cf) { REAL gammaSphorCartDD00,gammaSphorCartDD01,gammaSphorCartDD02, gammaSphorCartDD11,gammaSphorCartDD12,gammaSphorCartDD22; REAL KSphorCartDD00,KSphorCartDD01,KSphorCartDD02, KSphorCartDD11,KSphorCartDD12,KSphorCartDD22; REAL alphaSphorCart,betaSphorCartU0,betaSphorCartU1,betaSphorCartU2; REAL BSphorCartU0,BSphorCartU1,BSphorCartU2; const REAL xx0 = xx0xx1xx2[0]; const REAL xx1 = xx0xx1xx2[1]; const REAL xx2 = xx0xx1xx2[2]; REAL xyz_or_rthph[3];\n""") outCparams = "preindent=1,outCfileaccess=a,outCverbose=False,includebraces=False" outputC(r_th_ph_or_Cart_xyz_oID_xx[0:3], ["xyz_or_rthph[0]", "xyz_or_rthph[1]", "xyz_or_rthph[2]"], "BSSN/ID_ADM_xx0xx1xx2_to_BSSN_xx0xx1xx2__ALL_BUT_LAMBDAs.h", outCparams + ",CSE_enable=False") with open("BSSN/ID_ADM_xx0xx1xx2_to_BSSN_xx0xx1xx2__ALL_BUT_LAMBDAs.h", "a") as file: file.write(" " + ADM_input_function_name + """(xyz_or_rthph, other_inputs, &gammaSphorCartDD00,&gammaSphorCartDD01,&gammaSphorCartDD02, &gammaSphorCartDD11,&gammaSphorCartDD12,&gammaSphorCartDD22, &KSphorCartDD00,&KSphorCartDD01,&KSphorCartDD02, &KSphorCartDD11,&KSphorCartDD12,&KSphorCartDD22, &alphaSphorCart,&betaSphorCartU0,&betaSphorCartU1,&betaSphorCartU2, &BSphorCartU0,&BSphorCartU1,&BSphorCartU2); // Next compute all rescaled BSSN curvilinear quantities:\n""") outCparams = "preindent=1,outCfileaccess=a,outCverbose=False,includebraces=False" outputC([ hDD[0][0], hDD[0][1], hDD[0][2], hDD[1][1], hDD[1][2], hDD[2][2], aDD[0][0], aDD[0][1], aDD[0][2], aDD[1][1], aDD[1][2], aDD[2][2], trK, vetU[0], vetU[1], vetU[2], betU[0], betU[1], betU[2], alpha, cf ], [ "*hDD00", "*hDD01", "*hDD02", "*hDD11", "*hDD12", "*hDD22", "*aDD00", "*aDD01", "*aDD02", "*aDD11", "*aDD12", "*aDD22", "*trK", "*vetU0", "*vetU1", "*vetU2", "*betU0", "*betU1", "*betU2", "*alpha", "*cf" ], "BSSN/ID_ADM_xx0xx1xx2_to_BSSN_xx0xx1xx2__ALL_BUT_LAMBDAs.h", params=outCparams) with open("BSSN/ID_ADM_xx0xx1xx2_to_BSSN_xx0xx1xx2__ALL_BUT_LAMBDAs.h", "a") as file: file.write("}\n") # Step 5.A: Output the driver function for the above # function ID_ADM_xx0xx1xx2_to_BSSN_xx0xx1xx2__ALL_BUT_LAMBDAs() # Next write the driver function for ID_ADM_xx0xx1xx2_to_BSSN_xx0xx1xx2__ALL_BUT_LAMBDAs(): with open("BSSN/ID_BSSN__ALL_BUT_LAMBDAs.h", "w") as file: file.write( "void ID_BSSN__ALL_BUT_LAMBDAs(const int Nxx_plus_2NGHOSTS[3],REAL *xx[3]," ) if pointer_to_ID_inputs == True: file.write("ID_inputs *other_inputs,") else: file.write("ID_inputs other_inputs,") file.write("REAL *in_gfs) {\n") file.write( lp.loop(["i2", "i1", "i0"], ["0", "0", "0"], [ "Nxx_plus_2NGHOSTS[2]", "Nxx_plus_2NGHOSTS[1]", "Nxx_plus_2NGHOSTS[0]" ], ["1", "1", "1"], [ "#pragma omp parallel for", " const REAL xx2 = xx[2][i2];", " const REAL xx1 = xx[1][i1];" ], "", """const REAL xx0 = xx[0][i0]; const int idx = IDX3(i0,i1,i2); const REAL xx0xx1xx2[3] = {xx0,xx1,xx2}; ID_ADM_xx0xx1xx2_to_BSSN_xx0xx1xx2__ALL_BUT_LAMBDAs(xx0xx1xx2,other_inputs, &in_gfs[IDX4pt(HDD00GF,idx)],&in_gfs[IDX4pt(HDD01GF,idx)],&in_gfs[IDX4pt(HDD02GF,idx)], &in_gfs[IDX4pt(HDD11GF,idx)],&in_gfs[IDX4pt(HDD12GF,idx)],&in_gfs[IDX4pt(HDD22GF,idx)], &in_gfs[IDX4pt(ADD00GF,idx)],&in_gfs[IDX4pt(ADD01GF,idx)],&in_gfs[IDX4pt(ADD02GF,idx)], &in_gfs[IDX4pt(ADD11GF,idx)],&in_gfs[IDX4pt(ADD12GF,idx)],&in_gfs[IDX4pt(ADD22GF,idx)], &in_gfs[IDX4pt(TRKGF,idx)], &in_gfs[IDX4pt(VETU0GF,idx)],&in_gfs[IDX4pt(VETU1GF,idx)],&in_gfs[IDX4pt(VETU2GF,idx)], &in_gfs[IDX4pt(BETU0GF,idx)],&in_gfs[IDX4pt(BETU1GF,idx)],&in_gfs[IDX4pt(BETU2GF,idx)], &in_gfs[IDX4pt(ALPHAGF,idx)],&in_gfs[IDX4pt(CFGF,idx)]); """)) file.write("}\n") # Step 6: Compute $\bar{\Lambda}^i$ (Eqs. 4 and 5 of # [Baumgarte *et al.*](https://arxiv.org/pdf/1211.6632.pdf)), # from finite-difference derivatives of rescaled metric # quantities $h_{ij}$: # \bar{\Lambda}^i = \bar{\gamma}^{jk}\left(\bar{\Gamma}^i_{jk} - \hat{\Gamma}^i_{jk}\right). # The reference_metric.py module provides us with analytic expressions for # $\hat{\Gamma}^i_{jk}$, so here we need only compute # finite-difference expressions for $\bar{\Gamma}^i_{jk}$, based on # the values for $h_{ij}$ provided in the initial data. Once # $\bar{\Lambda}^i$ has been computed, we apply the usual rescaling # procedure: # \lambda^i = \bar{\Lambda}^i/\text{ReU[i]}, # and then output the result to a C file using the NRPy+ # finite-difference C output routine. # We will need all BSSN gridfunctions to be defined, as well as # expressions for gammabarDD_dD in terms of exact derivatives of # the rescaling matrix and finite-difference derivatives of # hDD's. gammabarDD = bssnrhs.gammabarDD gammabarUU, gammabarDET = ixp.symm_matrix_inverter3x3(gammabarDD) gammabarDD_dD = bssnrhs.gammabarDD_dD # Next compute Christoffel symbols \bar{\Gamma}^i_{jk}: GammabarUDD = ixp.zerorank3() for i in range(DIM): for j in range(DIM): for k in range(DIM): for l in range(DIM): GammabarUDD[i][j][k] += sp.Rational( 1, 2) * gammabarUU[i][l] * (gammabarDD_dD[l][j][k] + gammabarDD_dD[l][k][j] - gammabarDD_dD[j][k][l]) # Next evaluate \bar{\Lambda}^i, based on GammabarUDD above and GammahatUDD # (from the reference metric): LambdabarU = ixp.zerorank1() for i in range(DIM): for j in range(DIM): for k in range(DIM): LambdabarU[i] += gammabarUU[j][k] * ( GammabarUDD[i][j][k] - rfm.GammahatUDD[i][j][k]) # Finally apply rescaling: # lambda^i = Lambdabar^i/\text{ReU[i]} lambdaU = ixp.zerorank1() for i in range(DIM): lambdaU[i] = LambdabarU[i] / rfm.ReU[i] outCparams = "preindent=1,outCfileaccess=a,outCverbose=False,includebraces=False" lambdaU_expressions = [ lhrh(lhs=gri.gfaccess("in_gfs", "lambdaU0"), rhs=lambdaU[0]), lhrh(lhs=gri.gfaccess("in_gfs", "lambdaU1"), rhs=lambdaU[1]), lhrh(lhs=gri.gfaccess("in_gfs", "lambdaU2"), rhs=lambdaU[2]) ] lambdaU_expressions_FDout = fin.FD_outputC("returnstring", lambdaU_expressions, outCparams) with open("BSSN/ID_BSSN_lambdas.h", "w") as file: file.write(""" void ID_BSSN_lambdas(const int Nxx[3],const int Nxx_plus_2NGHOSTS[3],REAL *xx[3],const REAL dxx[3],REAL *in_gfs) {\n""" ) file.write( lp.loop(["i2", "i1", "i0"], ["NGHOSTS", "NGHOSTS", "NGHOSTS"], ["NGHOSTS+Nxx[2]", "NGHOSTS+Nxx[1]", "NGHOSTS+Nxx[0]"], ["1", "1", "1"], [ "const REAL invdx0 = 1.0/dxx[0];\n" + "const REAL invdx1 = 1.0/dxx[1];\n" + "const REAL invdx2 = 1.0/dxx[2];\n" + "#pragma omp parallel for", " const REAL xx2 = xx[2][i2];", " const REAL xx1 = xx[1][i1];" ], "", "const REAL xx0 = xx[0][i0];\n" + lambdaU_expressions_FDout)) file.write("}\n")
import sys import os import signal from loop import loop def handle_pdb(sig, frame): import pdb pdb.Pdb().set_trace(frame) if __name__ == '__main__': signal.signal(signal.SIGUSR1, handle_pdb) sys.stdout.write(str(os.getpid())) sys.stdout.flush() loop()
import evaluate as e # 读取一张图片,做灰度化处理,转为二维矩阵。虽然原图是灰度图,但仍需此步骤,不然会是三维矩阵 peppers = cv2.imread('raw_peppers.png', 0) # 使用高斯滤波消除噪声 # (5,5)是高斯核的大小,0是sigmaX,0的意思是让方程自己给你算对应的sigma peppers_b = cv2.GaussianBlur(peppers, (5, 5), 0) peppers_t = copy.deepcopy(peppers_b) # 返回的是经过非极大值抑制后的矩阵 peppers_g = g.gradient(peppers_t) # 返回的是迭代后的最优阈值 peppers_T = l.loop(peppers_g) # ret是返回的最优阈值,image是处理后的图 # THRESH_BINARY就是三角法(这句话存疑,忘记哪里看来的了,但实际使用起来似乎使用的阈值是传入的阈值) # THRESH_OTSU是大津法 # 这一个函数会根据直方图选择最优的阈值,即otus或传入的阈值,可以从返回值ret中获取 # peppers_ret, new1 = cv2.threshold(peppers_b, peppers_T, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # 这一条就只会使用大津法算出的阈值,但大津有缺点,直方图没有明显双峰时效果可能不好 peppers_ret, image = cv2.threshold(peppers_b, peppers_T, 255, cv2.THRESH_OTSU) # 因为想要有更多的边被画出来,所以取更小的(我自己一厢情愿的,可能没有理论依据) peppers_T = min(peppers_ret, peppers_T) peppers = cv2.Canny(peppers_b, peppers_T / 2, peppers_T) # 这是自适应阈值的边缘切割,用高斯核做窗口去给每一个像素一个自适应阈值 # 最后一个参数会影响切割质量,具体原理请参考文档
from output import output_class from input import input_class from translator import translator_class from loop import loop output = output_class() input = input_class() translator = translator_class(output) output.finalize() loop(output, input, translator)
def Convert_Spherical_or_Cartesian_ADM_to_BSSN_curvilinear( CoordType_in, ADM_input_function_name, Ccodesdir="BSSN", pointer_to_ID_inputs=False): # The ADM & BSSN formalisms only work in 3D; they are 3+1 decompositions of Einstein's equations. # To implement axisymmetry or spherical symmetry, simply set all spatial derivatives in # the relevant angular directions to zero; DO NOT SET DIM TO ANYTHING BUT 3. # Step 0: Set spatial dimension (must be 3 for BSSN) DIM = 3 # Step 1: All ADM initial data quantities are now functions of xx0,xx1,xx2, but # they are still in the Spherical or Cartesian basis. We can now directly apply # Jacobian transformations to get them in the correct xx0,xx1,xx2 basis: # All input quantities are in terms of r,th,ph or x,y,z. We want them in terms # of xx0,xx1,xx2, so here we call sympify_integers__replace_rthph() to replace # r,th,ph or x,y,z, respectively, with the appropriate functions of xx0,xx1,xx2 # as defined for this particular reference metric in reference_metric.py's # xxSph[] or xxCart[], respectively: # Define the input variables: gammaSphorCartDD = ixp.declarerank2("gammaSphorCartDD", "sym01") KSphorCartDD = ixp.declarerank2("KSphorCartDD", "sym01") alphaSphorCart = sp.symbols("alphaSphorCart") betaSphorCartU = ixp.declarerank1("betaSphorCartU") BSphorCartU = ixp.declarerank1("BSphorCartU") # Make sure that rfm.reference_metric() has been called. # We'll need the variables it defines throughout this module. if rfm.have_already_called_reference_metric_function == False: print( "Error. Called Convert_Spherical_ADM_to_BSSN_curvilinear() without" ) print( " first setting up reference metric, by calling rfm.reference_metric()." ) sys.exit(1) r_th_ph_or_Cart_xyz_oID_xx = [] if CoordType_in == "Spherical": r_th_ph_or_Cart_xyz_oID_xx = rfm.xxSph elif CoordType_in == "Cartesian": r_th_ph_or_Cart_xyz_oID_xx = rfm.xxCart else: print( "Error: Can only convert ADM Cartesian or Spherical initial data to BSSN Curvilinear coords." ) sys.exit(1) # Step 2: All ADM initial data quantities are now functions of xx0,xx1,xx2, but # they are still in the Spherical or Cartesian basis. We can now directly apply # Jacobian transformations to get them in the correct xx0,xx1,xx2 basis: # alpha is a scalar, so no Jacobian transformation is necessary. alpha = alphaSphorCart Jac_dUSphorCart_dDrfmUD = ixp.zerorank2() for i in range(DIM): for j in range(DIM): Jac_dUSphorCart_dDrfmUD[i][j] = sp.diff( r_th_ph_or_Cart_xyz_oID_xx[i], rfm.xx[j]) Jac_dUrfm_dDSphorCartUD, dummyDET = ixp.generic_matrix_inverter3x3( Jac_dUSphorCart_dDrfmUD) betaU = ixp.zerorank1() BU = ixp.zerorank1() gammaDD = ixp.zerorank2() KDD = ixp.zerorank2() for i in range(DIM): for j in range(DIM): betaU[i] += Jac_dUrfm_dDSphorCartUD[i][j] * betaSphorCartU[j] BU[i] += Jac_dUrfm_dDSphorCartUD[i][j] * BSphorCartU[j] for k in range(DIM): for l in range(DIM): gammaDD[i][j] += Jac_dUSphorCart_dDrfmUD[k][i] * Jac_dUSphorCart_dDrfmUD[l][j] * \ gammaSphorCartDD[k][l] KDD[i][j] += Jac_dUSphorCart_dDrfmUD[k][ i] * Jac_dUSphorCart_dDrfmUD[l][j] * KSphorCartDD[k][l] # Step 3: All ADM quantities were input into this function in the Spherical or Cartesian # basis, as functions of r,th,ph or x,y,z, respectively. In Steps 1 and 2 above, # we converted them to the xx0,xx1,xx2 basis, and as functions of xx0,xx1,xx2. # Here we convert ADM quantities in the "rfm" basis to their BSSN Curvilinear # counterparts, for all BSSN quantities *except* lambda^i: import BSSN.BSSN_in_terms_of_ADM as BitoA BitoA.gammabarDD_hDD(gammaDD) BitoA.trK_AbarDD_aDD(gammaDD, KDD) BitoA.cf_from_gammaDD(gammaDD) BitoA.betU_vetU(betaU, BU) hDD = BitoA.hDD trK = BitoA.trK aDD = BitoA.aDD cf = BitoA.cf vetU = BitoA.vetU betU = BitoA.betU # Step 4: Compute $\bar{\Lambda}^i$ (Eqs. 4 and 5 of # [Baumgarte *et al.*](https://arxiv.org/pdf/1211.6632.pdf)), # from finite-difference derivatives of rescaled metric # quantities $h_{ij}$: # \bar{\Lambda}^i = \bar{\gamma}^{jk}\left(\bar{\Gamma}^i_{jk} - \hat{\Gamma}^i_{jk}\right). # The reference_metric.py module provides us with analytic expressions for # $\hat{\Gamma}^i_{jk}$, so here we need only compute # finite-difference expressions for $\bar{\Gamma}^i_{jk}$, based on # the values for $h_{ij}$ provided in the initial data. Once # $\bar{\Lambda}^i$ has been computed, we apply the usual rescaling # procedure: # \lambda^i = \bar{\Lambda}^i/\text{ReU[i]}, # and then output the result to a C file using the NRPy+ # finite-difference C output routine. # We will need all BSSN gridfunctions to be defined, as well as # expressions for gammabarDD_dD in terms of exact derivatives of # the rescaling matrix and finite-difference derivatives of # hDD's. This functionality is provided by BSSN.BSSN_unrescaled_and_barred_vars, # which we call here to overwrite above definitions of gammabarDD,gammabarUU, etc. Bq.gammabar__inverse_and_derivs() # Provides gammabarUU and GammabarUDD gammabarUU = Bq.gammabarUU GammabarUDD = Bq.GammabarUDD # Next evaluate \bar{\Lambda}^i, based on GammabarUDD above and GammahatUDD # (from the reference metric): LambdabarU = ixp.zerorank1() for i in range(DIM): for j in range(DIM): for k in range(DIM): LambdabarU[i] += gammabarUU[j][k] * (GammabarUDD[i][j][k] - rfm.GammahatUDD[i][j][k]) # Finally apply rescaling: # lambda^i = Lambdabar^i/\text{ReU[i]} lambdaU = ixp.zerorank1() for i in range(DIM): lambdaU[i] = LambdabarU[i] / rfm.ReU[i] if ADM_input_function_name == "DoNotOutputADMInputFunction": return hDD, aDD, trK, vetU, betU, alpha, cf, lambdaU # Step 5.A: Output files containing finite-differenced lambdas. outCparams = "preindent=1,outCfileaccess=a,outCverbose=False,includebraces=False" lambdaU_expressions = [ lhrh(lhs=gri.gfaccess("in_gfs", "lambdaU0"), rhs=lambdaU[0]), lhrh(lhs=gri.gfaccess("in_gfs", "lambdaU1"), rhs=lambdaU[1]), lhrh(lhs=gri.gfaccess("in_gfs", "lambdaU2"), rhs=lambdaU[2]) ] lambdaU_expressions_FDout = fin.FD_outputC("returnstring", lambdaU_expressions, outCparams) with open(os.path.join(Ccodesdir, "ID_BSSN_lambdas.h"), "w") as file: file.write(""" void ID_BSSN_lambdas(const int Nxx[3],const int Nxx_plus_2NGHOSTS[3],REAL *xx[3],const REAL dxx[3],REAL *in_gfs) {\n""" ) file.write( lp.loop(["i2", "i1", "i0"], ["NGHOSTS", "NGHOSTS", "NGHOSTS"], ["NGHOSTS+Nxx[2]", "NGHOSTS+Nxx[1]", "NGHOSTS+Nxx[0]"], ["1", "1", "1"], [ "const REAL invdx0 = 1.0/dxx[0];\n" + "const REAL invdx1 = 1.0/dxx[1];\n" + "const REAL invdx2 = 1.0/dxx[2];\n" + "#pragma omp parallel for", " const REAL xx2 = xx[2][i2];", " const REAL xx1 = xx[1][i1];" ], "", "const REAL xx0 = xx[0][i0];\n" + lambdaU_expressions_FDout)) file.write("}\n") # Step 5: Output all ADM-to-BSSN expressions to a C function. This function # must first call the ID_ADM_SphorCart() defined above. Using these # Spherical or Cartesian data, it sets up all quantities needed for # BSSNCurvilinear initial data, *except* $\lambda^i$, which must be # computed from numerical data using finite-difference derivatives. with open( os.path.join( Ccodesdir, "ID_ADM_xx0xx1xx2_to_BSSN_xx0xx1xx2__ALL_BUT_LAMBDAs.h"), "w") as file: file.write( "void ID_ADM_xx0xx1xx2_to_BSSN_xx0xx1xx2__ALL_BUT_LAMBDAs(const REAL xx0xx1xx2[3]," ) if pointer_to_ID_inputs == True: file.write("ID_inputs *other_inputs,") else: file.write("ID_inputs other_inputs,") file.write(""" REAL *hDD00,REAL *hDD01,REAL *hDD02,REAL *hDD11,REAL *hDD12,REAL *hDD22, REAL *aDD00,REAL *aDD01,REAL *aDD02,REAL *aDD11,REAL *aDD12,REAL *aDD22, REAL *trK, REAL *vetU0,REAL *vetU1,REAL *vetU2, REAL *betU0,REAL *betU1,REAL *betU2, REAL *alpha, REAL *cf) { REAL gammaSphorCartDD00,gammaSphorCartDD01,gammaSphorCartDD02, gammaSphorCartDD11,gammaSphorCartDD12,gammaSphorCartDD22; REAL KSphorCartDD00,KSphorCartDD01,KSphorCartDD02, KSphorCartDD11,KSphorCartDD12,KSphorCartDD22; REAL alphaSphorCart,betaSphorCartU0,betaSphorCartU1,betaSphorCartU2; REAL BSphorCartU0,BSphorCartU1,BSphorCartU2; const REAL xx0 = xx0xx1xx2[0]; const REAL xx1 = xx0xx1xx2[1]; const REAL xx2 = xx0xx1xx2[2]; REAL xyz_or_rthph[3];\n""") outCparams = "preindent=1,outCfileaccess=a,outCverbose=False,includebraces=False" outputC( r_th_ph_or_Cart_xyz_oID_xx[0:3], ["xyz_or_rthph[0]", "xyz_or_rthph[1]", "xyz_or_rthph[2]"], os.path.join(Ccodesdir, "ID_ADM_xx0xx1xx2_to_BSSN_xx0xx1xx2__ALL_BUT_LAMBDAs.h"), outCparams + ",CSE_enable=False") with open( os.path.join( Ccodesdir, "ID_ADM_xx0xx1xx2_to_BSSN_xx0xx1xx2__ALL_BUT_LAMBDAs.h"), "a") as file: file.write(" " + ADM_input_function_name + """(xyz_or_rthph, other_inputs, &gammaSphorCartDD00,&gammaSphorCartDD01,&gammaSphorCartDD02, &gammaSphorCartDD11,&gammaSphorCartDD12,&gammaSphorCartDD22, &KSphorCartDD00,&KSphorCartDD01,&KSphorCartDD02, &KSphorCartDD11,&KSphorCartDD12,&KSphorCartDD22, &alphaSphorCart,&betaSphorCartU0,&betaSphorCartU1,&betaSphorCartU2, &BSphorCartU0,&BSphorCartU1,&BSphorCartU2); // Next compute all rescaled BSSN curvilinear quantities:\n""") outCparams = "preindent=1,outCfileaccess=a,outCverbose=False,includebraces=False" outputC([ hDD[0][0], hDD[0][1], hDD[0][2], hDD[1][1], hDD[1][2], hDD[2][2], aDD[0][0], aDD[0][1], aDD[0][2], aDD[1][1], aDD[1][2], aDD[2][2], trK, vetU[0], vetU[1], vetU[2], betU[0], betU[1], betU[2], alpha, cf ], [ "*hDD00", "*hDD01", "*hDD02", "*hDD11", "*hDD12", "*hDD22", "*aDD00", "*aDD01", "*aDD02", "*aDD11", "*aDD12", "*aDD22", "*trK", "*vetU0", "*vetU1", "*vetU2", "*betU0", "*betU1", "*betU2", "*alpha", "*cf" ], os.path.join( Ccodesdir, "ID_ADM_xx0xx1xx2_to_BSSN_xx0xx1xx2__ALL_BUT_LAMBDAs.h"), params=outCparams) with open( os.path.join( Ccodesdir, "ID_ADM_xx0xx1xx2_to_BSSN_xx0xx1xx2__ALL_BUT_LAMBDAs.h"), "a") as file: file.write("}\n") # Step 5.a: Output the driver function for the above # function ID_ADM_xx0xx1xx2_to_BSSN_xx0xx1xx2__ALL_BUT_LAMBDAs() # Next write the driver function for ID_ADM_xx0xx1xx2_to_BSSN_xx0xx1xx2__ALL_BUT_LAMBDAs(): with open(os.path.join(Ccodesdir, "ID_BSSN__ALL_BUT_LAMBDAs.h"), "w") as file: file.write( "void ID_BSSN__ALL_BUT_LAMBDAs(const int Nxx_plus_2NGHOSTS[3],REAL *xx[3]," ) if pointer_to_ID_inputs == True: file.write("ID_inputs *other_inputs,") else: file.write("ID_inputs other_inputs,") file.write("REAL *in_gfs) {\n") file.write( lp.loop(["i2", "i1", "i0"], ["0", "0", "0"], [ "Nxx_plus_2NGHOSTS[2]", "Nxx_plus_2NGHOSTS[1]", "Nxx_plus_2NGHOSTS[0]" ], ["1", "1", "1"], [ "#pragma omp parallel for", " const REAL xx2 = xx[2][i2];", " const REAL xx1 = xx[1][i1];" ], "", """const REAL xx0 = xx[0][i0]; const int idx = IDX3(i0,i1,i2); const REAL xx0xx1xx2[3] = {xx0,xx1,xx2}; ID_ADM_xx0xx1xx2_to_BSSN_xx0xx1xx2__ALL_BUT_LAMBDAs(xx0xx1xx2,other_inputs, &in_gfs[IDX4pt(HDD00GF,idx)],&in_gfs[IDX4pt(HDD01GF,idx)],&in_gfs[IDX4pt(HDD02GF,idx)], &in_gfs[IDX4pt(HDD11GF,idx)],&in_gfs[IDX4pt(HDD12GF,idx)],&in_gfs[IDX4pt(HDD22GF,idx)], &in_gfs[IDX4pt(ADD00GF,idx)],&in_gfs[IDX4pt(ADD01GF,idx)],&in_gfs[IDX4pt(ADD02GF,idx)], &in_gfs[IDX4pt(ADD11GF,idx)],&in_gfs[IDX4pt(ADD12GF,idx)],&in_gfs[IDX4pt(ADD22GF,idx)], &in_gfs[IDX4pt(TRKGF,idx)], &in_gfs[IDX4pt(VETU0GF,idx)],&in_gfs[IDX4pt(VETU1GF,idx)],&in_gfs[IDX4pt(VETU2GF,idx)], &in_gfs[IDX4pt(BETU0GF,idx)],&in_gfs[IDX4pt(BETU1GF,idx)],&in_gfs[IDX4pt(BETU2GF,idx)], &in_gfs[IDX4pt(ALPHAGF,idx)],&in_gfs[IDX4pt(CFGF,idx)]); """)) file.write("}\n")
#!/usr/bin/python from button import button from led import led from setup import setup from loop import loop # Open a file fo = open("arduino.c", "w") b = button(9) le = led(12) s = setup() s.addComposant(b) s.addComposant(le) fo.write(str(s.arduino())) lo = loop() lo.addRead(["BUTTON9", "BUTTON10"]) lo.addActionIf(["BUTTON9", "BUTTON10"], "dualPush", ["active"], "LED12") fo.write(str(lo.arduino())) # Close opend file fo.close()
def output_Enforce_Detgammabar_Constraint_Ccode(): # Set spatial dimension (must be 3 for BSSN) DIM = 3 # Then we set the coordinate system for the numerical grid rfm.reference_metric( ) # Create ReU, ReDD needed for rescaling B-L initial data, generating BSSN RHSs, etc. # We will need the h_{ij} quantities defined within BSSN_RHSs # below when we enforce the gammahat=gammabar constraint # Step 1: All barred quantities are defined in terms of BSSN rescaled gridfunctions, # which we declare here in case they haven't yet been declared elsewhere. Bq.declare_BSSN_gridfunctions_if_not_declared_already() hDD = Bq.hDD Bq.BSSN_basic_tensors() gammabarDD = Bq.gammabarDD # First define the Kronecker delta: KroneckerDeltaDD = ixp.zerorank2() for i in range(DIM): KroneckerDeltaDD[i][i] = sp.sympify(1) # The detgammabar in BSSN_RHSs is set to detgammahat when BSSN_RHSs::detgbarOverdetghat_equals_one=True (default), # so we manually compute it here: dummygammabarUU, detgammabar = ixp.symm_matrix_inverter3x3(gammabarDD) # Next apply the constraint enforcement equation above. hprimeDD = ixp.zerorank2() for i in range(DIM): for j in range(DIM): hprimeDD[i][j] = \ (sp.Abs(rfm.detgammahat) / detgammabar) ** (sp.Rational(1, 3)) * (KroneckerDeltaDD[i][j] + hDD[i][j]) \ - KroneckerDeltaDD[i][j] enforce_detg_constraint_vars = [ \ lhrh(lhs=gri.gfaccess("in_gfs", "hDD00"), rhs=hprimeDD[0][0]), lhrh(lhs=gri.gfaccess("in_gfs", "hDD01"), rhs=hprimeDD[0][1]), lhrh(lhs=gri.gfaccess("in_gfs", "hDD02"), rhs=hprimeDD[0][2]), lhrh(lhs=gri.gfaccess("in_gfs", "hDD11"), rhs=hprimeDD[1][1]), lhrh(lhs=gri.gfaccess("in_gfs", "hDD12"), rhs=hprimeDD[1][2]), lhrh(lhs=gri.gfaccess("in_gfs", "hDD22"), rhs=hprimeDD[2][2])] enforce_gammadet_string = fin.FD_outputC( "returnstring", enforce_detg_constraint_vars, params="outCverbose=False,preindent=0,includebraces=False") with open("BSSN/enforce_detgammabar_constraint.h", "w") as file: indent = " " file.write( "void enforce_detgammabar_constraint(const int Nxx_plus_2NGHOSTS[3],REAL *xx[3], REAL *in_gfs) {\n\n" ) file.write( lp.loop(["i2", "i1", "i0"], ["0", "0", "0"], [ "Nxx_plus_2NGHOSTS[2]", "Nxx_plus_2NGHOSTS[1]", "Nxx_plus_2NGHOSTS[0]" ], ["1", "1", "1"], [ "#pragma omp parallel for", " const REAL xx2 = xx[2][i2];", " const REAL xx1 = xx[1][i1];" ], "", "const REAL xx0 = xx[0][i0];\n" + enforce_gammadet_string)) file.write("}\n") print( "Output C implementation of det(gammabar) constraint to file BSSN/enforce_detgammabar_constraint.h" )