def __init__(self, t0, y0, dt): self.t = [t0] self.y = [y0] self.dt = dt from hedge.timestep.runge_kutta import LSRK4TimeStepper self.forward_stepper = LSRK4TimeStepper() self.backward_stepper = LSRK4TimeStepper()
def __init__(self, order, startup_stepper=None, dtype=numpy.float64, rcon=None): self.f_history = [] from pytools import match_precision self.dtype = numpy.dtype(dtype) self.scalar_dtype = match_precision(numpy.dtype(numpy.float64), self.dtype) self.coefficients = numpy.asarray(make_ab_coefficients(order), dtype=self.scalar_dtype) if startup_stepper is not None: self.startup_stepper = startup_stepper else: from hedge.timestep.runge_kutta import LSRK4TimeStepper self.startup_stepper = LSRK4TimeStepper(self.dtype) from pytools.log import IntervalTimer, EventCounter timer_factory = IntervalTimer if rcon is not None: timer_factory = rcon.make_timer self.timer = timer_factory( "t_ab", "Time spent doing algebra in Adams-Bashforth") self.flop_counter = EventCounter( "n_flops_ab", "Floating point operations performed in AB")
def __init__(self, method, large_dt, substep_count, order, order_f2f=None, order_s2f=None, order_f2s=None, order_s2s=None, startup_stepper=None): if isinstance(method, str): from hedge.timestep.multirate_ab.methods import methods self.method_name = method method = methods[method] else: self.method_name = None self.method = method self.large_dt = large_dt self.small_dt = large_dt / substep_count self.substep_count = substep_count from hedge.timestep.multirate_ab.methods import \ HIST_F2F, HIST_S2F, HIST_F2S, HIST_S2S self.orders = { HIST_F2F: order_f2f, HIST_S2F: order_s2f, HIST_F2S: order_f2s, HIST_S2S: order_s2s, } for hn in HIST_NAMES: if self.orders[hn] is None: self.orders[hn] = order self.max_order = max(self.orders.values()) # histories of rhs evaluations self.histories = dict((hn, []) for hn in HIST_NAMES) if startup_stepper is not None: self.startup_stepper = startup_stepper else: self.startup_stepper = LSRK4TimeStepper() self.startup_history = [] self.hist_is_fast = { HIST_F2F: True, HIST_S2F: self.method.s2f_hist_is_fast, HIST_S2S: False, HIST_F2S: False }
def run_setup(units, casename, setup, discr, pusher, visualize=False): from hedge.timestep.runge_kutta import LSRK4TimeStepper from hedge.visualization import SiloVisualizer from hedge.models.em import MaxwellOperator vis = SiloVisualizer(discr) from pyrticle.cloud import PicMethod from pyrticle.deposition.shape import ShapeFunctionDepositor method = PicMethod(discr, units, ShapeFunctionDepositor(), pusher(), 3, 3, debug=set(["verbose_vis"])) e, h = setup.fields(discr) b = units.MU0 * h init_positions = setup.positions(0) init_velocities = setup.velocities(0) nparticles = len(init_positions) state = method.make_state() method.add_particles( state, zip( init_positions, init_velocities, nparticles * [setup.charge], nparticles * [units.EL_MASS], ), nparticles) final_time = setup.final_time() nsteps = setup.nsteps() dt = final_time / nsteps # timestepping ------------------------------------------------------------ from hedge.models.em import MaxwellOperator max_op = MaxwellOperator(epsilon=units.EPSILON0, mu=units.MU0, flux_type=1) fields = max_op.assemble_eh(e, h) from pyrticle.cloud import \ FieldToParticleRhsCalculator, \ ParticleRhsCalculator p_rhs_calculator = ParticleRhsCalculator(method, max_op) f2p_rhs_calculator = FieldToParticleRhsCalculator(method, max_op) def rhs(t, ts_state): return (p_rhs_calculator(t, lambda: fields, lambda: ts_state.state) + f2p_rhs_calculator(t, lambda: fields, lambda: ts_state.state)) stepper = LSRK4TimeStepper() t = 0 bbox = discr.mesh.bounding_box() z_period = bbox[1][2] - bbox[0][2] def check_result(): from hedge.tools import cross deriv_dt = 1e-12 dim = discr.dimensions true_x = setup.positions(t) true_v = setup.velocities(t) true_f = [(p2 - p1) / (2 * deriv_dt) for p1, p2 in zip( setup.momenta(t - deriv_dt), setup.momenta(t + deriv_dt))] state = ts_state.state from pyrticle.tools import NumberShiftableVector vis_info = state.vis_listener.particle_vis_map sim_x = state.positions sim_v = method.velocities(state) sim_f = NumberShiftableVector.unwrap(vis_info["mag_force"] + vis_info["el_force"]) sim_el_f = NumberShiftableVector.unwrap(vis_info["el_force"]) sim_mag_f = NumberShiftableVector.unwrap(vis_info["mag_force"]) local_e = setup.e() local_b = units.MU0 * setup.h() x_err = 0 v_err = 0 f_err = 0 for i in range(len(state)): #real_f = numpy.array(cross(sim_v, setup.charge*local_b)) + setup.charge*local_e my_true_x = true_x[i] my_true_x[2] = my_true_x[2] % z_period if False and i == 0: #print "particle %d" % i print "pos:", la.norm(true_x[i] - sim_x[i]) / la.norm( true_x[i]) #print "vel:", la.norm(true_v[i]-sim_v[i])/la.norm(true_v[i]) #print "force:", la.norm(true_f[i]-sim_f[i])/la.norm(true_f[i]) print "pos:", true_x[i], sim_x[i] #print "vel:", true_v[i], sim_v[i] #print "force:", true_f[i], sim_f[i] #print "forces%d:..." % i, sim_el_f[i], sim_mag_f[i] #print "acc%d:" % i, la.norm(a-sim_a) #u = numpy.vstack((v, sim_v, f, sim_f, real_f)) #print "acc%d:\n%s" % (i, u) #raw_input() def rel_err(sim, true): return la.norm(true - sim) / la.norm(true) x_err = max(x_err, rel_err(sim_x[i], my_true_x)) v_err = max(v_err, rel_err(sim_v[i], true_v[i])) f_err = max(f_err, rel_err(sim_f[i], true_f[i])) return x_err, v_err, f_err # make sure verbose-vis fields are filled from pyrticle.cloud import TimesteppablePicState ts_state = TimesteppablePicState(method, state) del state rhs(t, ts_state) errors = (0, 0, 0) for step in xrange(nsteps): if step % int(setup.nsteps() / 300) == 0: errors = tuple( max(old_err, new_err) for old_err, new_err in zip(errors, check_result())) if visualize: visf = vis.make_file("%s-%04d" % (casename, step)) method.add_to_vis(vis, visf, ts_state.state, time=t, step=step) if True: vis.add_data(visf, [ ("e", e), ("h", h), ], time=t, step=step) else: vis.add_data(visf, [], time=t, step=step) visf.close() method.upkeep(ts_state.state) ts_state = stepper(ts_state, t, dt, rhs) t += dt assert errors[0] < 2e-12, casename + "-pos" assert errors[1] < 2e-13, casename + "-vel" assert errors[2] < 2e-4, casename + "-acc" vis.close()
def main(write_output=True, dir_tag=TAG_NONE, neu_tag=TAG_NONE, rad_tag=TAG_ALL, flux_type_arg="upwind"): from math import sin, cos, pi, exp, sqrt # noqa from hedge.backends import guess_run_context rcon = guess_run_context() dim = 2 if dim == 1: if rcon.is_head_rank: from hedge.mesh.generator import make_uniform_1d_mesh mesh = make_uniform_1d_mesh(-10, 10, 500) elif dim == 2: from hedge.mesh.generator import make_rect_mesh if rcon.is_head_rank: mesh = make_rect_mesh(a=(-1, -1), b=(1, 1), max_area=0.003) elif dim == 3: if rcon.is_head_rank: from hedge.mesh.generator import make_ball_mesh mesh = make_ball_mesh(max_volume=0.0005) else: raise RuntimeError("bad number of dimensions") if rcon.is_head_rank: print "%d elements" % len(mesh.elements) mesh_data = rcon.distribute_mesh(mesh) else: mesh_data = rcon.receive_mesh() discr = rcon.make_discretization(mesh_data, order=4) from hedge.timestep.runge_kutta import LSRK4TimeStepper stepper = LSRK4TimeStepper() from hedge.visualization import VtkVisualizer if write_output: vis = VtkVisualizer(discr, rcon, "fld") source_center = np.array([0.7, 0.4]) source_width = 1 / 16 source_omega = 3 import hedge.optemplate as sym sym_x = sym.nodes(2) sym_source_center_dist = sym_x - source_center from hedge.models.wave import VariableVelocityStrongWaveOperator op = VariableVelocityStrongWaveOperator( c=sym.If(sym.Comparison(np.dot(sym_x, sym_x), "<", 0.4**2), 1, 0.5), dimensions=discr.dimensions, source=sym.CFunction("sin")(source_omega * sym.ScalarParameter("t")) * sym.CFunction("exp")( -np.dot(sym_source_center_dist, sym_source_center_dist) / source_width**2), dirichlet_tag=dir_tag, neumann_tag=neu_tag, radiation_tag=rad_tag, flux_type=flux_type_arg) from hedge.tools import join_fields fields = join_fields( discr.volume_zeros(), [discr.volume_zeros() for i in range(discr.dimensions)]) # {{{ diagnostics setup from pytools.log import LogManager, \ add_general_quantities, \ add_simulation_quantities, \ add_run_info if write_output: log_file_name = "wave.dat" else: log_file_name = None logmgr = LogManager(log_file_name, "w", rcon.communicator) add_run_info(logmgr) add_general_quantities(logmgr) add_simulation_quantities(logmgr) discr.add_instrumentation(logmgr) from pytools.log import IntervalTimer vis_timer = IntervalTimer("t_vis", "Time spent visualizing") logmgr.add_quantity(vis_timer) stepper.add_instrumentation(logmgr) from hedge.log import LpNorm u_getter = lambda: fields[0] logmgr.add_quantity(LpNorm(u_getter, discr, 1, name="l1_u")) logmgr.add_quantity(LpNorm(u_getter, discr, name="l2_u")) logmgr.add_watches(["step.max", "t_sim.max", "l2_u", "t_step.max"]) # }}} # {{{ timestep loop rhs = op.bind(discr) try: from hedge.timestep.stability import \ approximate_rk4_relative_imag_stability_region max_dt = (1 / discr.compile(op.max_eigenvalue_expr())() * discr.dt_non_geometric_factor() * discr.dt_geometric_factor() * approximate_rk4_relative_imag_stability_region(stepper)) if flux_type_arg == "central": max_dt *= 0.25 from hedge.timestep import times_and_steps step_it = times_and_steps(final_time=3, logmgr=logmgr, max_dt_getter=lambda t: max_dt) for step, t, dt in step_it: if step % 10 == 0 and write_output: visf = vis.make_file("fld-%04d" % step) vis.add_data(visf, [ ("u", fields[0]), ("v", fields[1:]), ], time=t, step=step) visf.close() fields = stepper(fields, t, dt, rhs) assert discr.norm(fields) < 1 finally: if write_output: vis.close() logmgr.close() discr.close()
def main(write_output=True): from math import sin, exp, sqrt # noqa from hedge.mesh.generator import make_rect_mesh mesh = make_rect_mesh(a=(-0.5, -0.5), b=(0.5, 0.5), max_area=0.008) from hedge.backends.jit import Discretization discr = Discretization(mesh, order=4) from hedge.visualization import VtkVisualizer vis = VtkVisualizer(discr, None, "fld") source_center = np.array([0.1, 0.22]) source_width = 0.05 source_omega = 3 import hedge.optemplate as sym sym_x = sym.nodes(2) sym_source_center_dist = sym_x - source_center from hedge.models.wave import StrongWaveOperator from hedge.mesh import TAG_ALL, TAG_NONE op = StrongWaveOperator( -0.1, discr.dimensions, source_f=sym.CFunction("sin")( source_omega * sym.ScalarParameter("t")) * sym.CFunction("exp")( -np.dot(sym_source_center_dist, sym_source_center_dist) / source_width**2), dirichlet_tag=TAG_NONE, neumann_tag=TAG_NONE, radiation_tag=TAG_ALL, flux_type="upwind") from hedge.tools import join_fields fields = join_fields( discr.volume_zeros(), [discr.volume_zeros() for i in range(discr.dimensions)]) from hedge.timestep.runge_kutta import LSRK4TimeStepper stepper = LSRK4TimeStepper() dt = op.estimate_timestep(discr, stepper=stepper, fields=fields) nsteps = int(10 / dt) print "dt=%g nsteps=%d" % (dt, nsteps) rhs = op.bind(discr) for step in range(nsteps): t = step * dt if step % 10 == 0 and write_output: print step, t, discr.norm(fields[0]) visf = vis.make_file("fld-%04d" % step) vis.add_data(visf, [ ("u", fields[0]), ("v", fields[1:]), ], time=t, step=step) visf.close() fields = stepper(fields, t, dt, rhs) vis.close()
def main(write_output=True): from math import sin, cos, pi, exp, sqrt from hedge.data import TimeConstantGivenFunction, \ ConstantGivenFunction from hedge.backends import guess_run_context rcon = guess_run_context() dim = 2 def boundary_tagger(fvi, el, fn, all_v): if el.face_normals[fn][0] > 0: return ["dirichlet"] else: return ["neumann"] if dim == 2: if rcon.is_head_rank: from hedge.mesh.generator import make_disk_mesh mesh = make_disk_mesh(r=0.5, boundary_tagger=boundary_tagger) elif dim == 3: if rcon.is_head_rank: from hedge.mesh.generator import make_ball_mesh mesh = make_ball_mesh(max_volume=0.001) else: raise RuntimeError, "bad number of dimensions" if rcon.is_head_rank: print "%d elements" % len(mesh.elements) mesh_data = rcon.distribute_mesh(mesh) else: mesh_data = rcon.receive_mesh() discr = rcon.make_discretization(mesh_data, order=3, debug=["cuda_no_plan"], default_scalar_type=numpy.float64) if write_output: from hedge.visualization import VtkVisualizer vis = VtkVisualizer(discr, rcon, "fld") def u0(x, el): if la.norm(x) < 0.2: return 1 else: return 0 def coeff(x, el): if x[0] < 0: return 0.25 else: return 1 def dirichlet_bc(t, x): return 0 def neumann_bc(t, x): return 2 from hedge.models.diffusion import DiffusionOperator op = DiffusionOperator( discr.dimensions, #coeff=coeff, dirichlet_tag="dirichlet", dirichlet_bc=TimeConstantGivenFunction(ConstantGivenFunction(0)), neumann_tag="neumann", neumann_bc=TimeConstantGivenFunction(ConstantGivenFunction(1))) u = discr.interpolate_volume_function(u0) # diagnostics setup ------------------------------------------------------- from pytools.log import LogManager, \ add_general_quantities, \ add_simulation_quantities, \ add_run_info if write_output: log_file_name = "heat.dat" else: log_file_name = None logmgr = LogManager(log_file_name, "w", rcon.communicator) add_run_info(logmgr) add_general_quantities(logmgr) add_simulation_quantities(logmgr) discr.add_instrumentation(logmgr) from hedge.log import LpNorm u_getter = lambda: u logmgr.add_quantity(LpNorm(u_getter, discr, 1, name="l1_u")) logmgr.add_quantity(LpNorm(u_getter, discr, name="l2_u")) logmgr.add_watches(["step.max", "t_sim.max", "l2_u", "t_step.max"]) # timestep loop ----------------------------------------------------------- from hedge.timestep.runge_kutta import LSRK4TimeStepper, ODE45TimeStepper from hedge.timestep.dumka3 import Dumka3TimeStepper #stepper = LSRK4TimeStepper() stepper = Dumka3TimeStepper( 3, rtol=1e-6, rcon=rcon, vector_primitive_factory=discr.get_vector_primitive_factory(), dtype=discr.default_scalar_type) #stepper = ODE45TimeStepper(rtol=1e-6, rcon=rcon, #vector_primitive_factory=discr.get_vector_primitive_factory(), #dtype=discr.default_scalar_type) stepper.add_instrumentation(logmgr) rhs = op.bind(discr) try: next_dt = op.estimate_timestep(discr, stepper=LSRK4TimeStepper(), t=0, fields=u) from hedge.timestep import times_and_steps step_it = times_and_steps(final_time=0.1, logmgr=logmgr, max_dt_getter=lambda t: next_dt, taken_dt_getter=lambda: taken_dt) for step, t, dt in step_it: if step % 10 == 0 and write_output: visf = vis.make_file("fld-%04d" % step) vis.add_data(visf, [ ("u", discr.convert_volume(u, kind="numpy")), ], time=t, step=step) visf.close() u, t, taken_dt, next_dt = stepper(u, t, next_dt, rhs) #u = stepper(u, t, dt, rhs) assert discr.norm(u) < 1 finally: if write_output: vis.close() logmgr.close() discr.close()
def main(write_output=True, dir_tag=TAG_NONE, neu_tag=TAG_NONE, rad_tag=TAG_ALL, flux_type_arg="upwind", dtype=np.float64, debug=[]): from math import sin, cos, pi, exp, sqrt # noqa from hedge.backends import guess_run_context rcon = guess_run_context() dim = 2 if dim == 1: if rcon.is_head_rank: from hedge.mesh.generator import make_uniform_1d_mesh mesh = make_uniform_1d_mesh(-10, 10, 500) elif dim == 2: from hedge.mesh.generator import make_rect_mesh if rcon.is_head_rank: mesh = make_rect_mesh(a=(-0.5, -0.5), b=(0.5, 0.5), max_area=0.008) elif dim == 3: if rcon.is_head_rank: from hedge.mesh.generator import make_ball_mesh mesh = make_ball_mesh(max_volume=0.0005) else: raise RuntimeError("bad number of dimensions") if rcon.is_head_rank: print "%d elements" % len(mesh.elements) mesh_data = rcon.distribute_mesh(mesh) else: mesh_data = rcon.receive_mesh() from hedge.timestep.runge_kutta import LSRK4TimeStepper stepper = LSRK4TimeStepper(dtype=dtype) from hedge.models.wave import StrongWaveOperator from hedge.mesh import TAG_ALL, TAG_NONE # noqa source_center = np.array([0.1, 0.22]) source_width = 0.05 source_omega = 3 import hedge.optemplate as sym sym_x = sym.nodes(2) sym_source_center_dist = sym_x - source_center op = StrongWaveOperator( -1, dim, source_f=sym.CFunction("sin")( source_omega * sym.ScalarParameter("t")) * sym.CFunction("exp")( -np.dot(sym_source_center_dist, sym_source_center_dist) / source_width**2), dirichlet_tag=dir_tag, neumann_tag=neu_tag, radiation_tag=rad_tag, flux_type=flux_type_arg) discr = rcon.make_discretization(mesh_data, order=4, debug=debug, default_scalar_type=dtype, tune_for=op.op_template()) from hedge.visualization import VtkVisualizer if write_output: vis = VtkVisualizer(discr, rcon, "fld") from hedge.tools import join_fields fields = join_fields( discr.volume_zeros(dtype=dtype), [discr.volume_zeros(dtype=dtype) for i in range(discr.dimensions)]) # {{{ diagnostics setup from pytools.log import LogManager, \ add_general_quantities, \ add_simulation_quantities, \ add_run_info if write_output: log_file_name = "wave.dat" else: log_file_name = None logmgr = LogManager(log_file_name, "w", rcon.communicator) add_run_info(logmgr) add_general_quantities(logmgr) add_simulation_quantities(logmgr) discr.add_instrumentation(logmgr) from pytools.log import IntervalTimer vis_timer = IntervalTimer("t_vis", "Time spent visualizing") logmgr.add_quantity(vis_timer) stepper.add_instrumentation(logmgr) from hedge.log import LpNorm u_getter = lambda: fields[0] logmgr.add_quantity(LpNorm(u_getter, discr, 1, name="l1_u")) logmgr.add_quantity(LpNorm(u_getter, discr, name="l2_u")) logmgr.add_watches(["step.max", "t_sim.max", "l2_u", "t_step.max"]) # }}} # {{{ timestep loop rhs = op.bind(discr) try: from hedge.timestep import times_and_steps step_it = times_and_steps( final_time=4, logmgr=logmgr, max_dt_getter=lambda t: op.estimate_timestep( discr, stepper=stepper, t=t, fields=fields)) for step, t, dt in step_it: if step % 10 == 0 and write_output: visf = vis.make_file("fld-%04d" % step) vis.add_data(visf, [ ("u", discr.convert_volume(fields[0], kind="numpy")), ("v", discr.convert_volume(fields[1:], kind="numpy")), ], time=t, step=step) visf.close() fields = stepper(fields, t, dt, rhs) assert discr.norm(fields) < 1 assert fields[0].dtype == dtype finally: if write_output: vis.close() logmgr.close() discr.close()
def main(write_output=True, allow_features=None, flux_type_arg=1, bdry_flux_type_arg=None, extra_discr_args={}): from hedge.mesh.generator import make_cylinder_mesh, make_box_mesh from hedge.tools import EOCRecorder, to_obj_array from math import sqrt, pi # noqa from analytic_solutions import ( # noqa RealPartAdapter, SplitComplexAdapter, CylindricalFieldAdapter, CylindricalCavityMode, RectangularWaveguideMode, RectangularCavityMode) from hedge.models.em import MaxwellOperator logging.basicConfig(level=logging.DEBUG) from hedge.backends import guess_run_context rcon = guess_run_context(allow_features) epsilon0 = 8.8541878176e-12 # C**2 / (N m**2) mu0 = 4 * pi * 1e-7 # N/A**2. epsilon = 1 * epsilon0 mu = 1 * mu0 eoc_rec = EOCRecorder() cylindrical = False periodic = False if cylindrical: R = 1 d = 2 mode = CylindricalCavityMode(m=1, n=1, p=1, radius=R, height=d, epsilon=epsilon, mu=mu) # r_sol = CylindricalFieldAdapter(RealPartAdapter(mode)) # c_sol = SplitComplexAdapter(CylindricalFieldAdapter(mode)) if rcon.is_head_rank: mesh = make_cylinder_mesh(radius=R, height=d, max_volume=0.01) else: if periodic: mode = RectangularWaveguideMode(epsilon, mu, (3, 2, 1)) periodicity = (False, False, True) else: periodicity = None mode = RectangularCavityMode(epsilon, mu, (1, 2, 2)) if rcon.is_head_rank: mesh = make_box_mesh(max_volume=0.001, periodicity=periodicity) if rcon.is_head_rank: mesh_data = rcon.distribute_mesh(mesh) else: mesh_data = rcon.receive_mesh() for order in [4, 5, 6]: #for order in [1,2,3,4,5,6]: extra_discr_args.setdefault("debug", []).extend( ["cuda_no_plan", "cuda_dump_kernels"]) op = MaxwellOperator(epsilon, mu, flux_type=flux_type_arg, bdry_flux_type=bdry_flux_type_arg) discr = rcon.make_discretization(mesh_data, order=order, tune_for=op.op_template(), **extra_discr_args) from hedge.visualization import VtkVisualizer if write_output: vis = VtkVisualizer(discr, rcon, "em-%d" % order) mode.set_time(0) def get_true_field(): return discr.convert_volume(to_obj_array( mode(discr).real.astype(discr.default_scalar_type).copy()), kind=discr.compute_kind) fields = get_true_field() if rcon.is_head_rank: print "---------------------------------------------" print "order %d" % order print "---------------------------------------------" print "#elements=", len(mesh.elements) from hedge.timestep.runge_kutta import LSRK4TimeStepper stepper = LSRK4TimeStepper(dtype=discr.default_scalar_type, rcon=rcon) #from hedge.timestep.dumka3 import Dumka3TimeStepper #stepper = Dumka3TimeStepper(3, dtype=discr.default_scalar_type, rcon=rcon) # {{{ diagnostics setup from pytools.log import LogManager, add_general_quantities, \ add_simulation_quantities, add_run_info if write_output: log_file_name = "maxwell-%d.dat" % order else: log_file_name = None logmgr = LogManager(log_file_name, "w", rcon.communicator) add_run_info(logmgr) add_general_quantities(logmgr) add_simulation_quantities(logmgr) discr.add_instrumentation(logmgr) stepper.add_instrumentation(logmgr) from pytools.log import IntervalTimer vis_timer = IntervalTimer("t_vis", "Time spent visualizing") logmgr.add_quantity(vis_timer) from hedge.log import EMFieldGetter, add_em_quantities field_getter = EMFieldGetter(discr, op, lambda: fields) add_em_quantities(logmgr, op, field_getter) logmgr.add_watches( ["step.max", "t_sim.max", ("W_field", "W_el+W_mag"), "t_step.max"]) # }}} # {{{ timestep loop rhs = op.bind(discr) final_time = 0.5e-9 try: from hedge.timestep import times_and_steps step_it = times_and_steps( final_time=final_time, logmgr=logmgr, max_dt_getter=lambda t: op.estimate_timestep( discr, stepper=stepper, t=t, fields=fields)) for step, t, dt in step_it: if step % 50 == 0 and write_output: sub_timer = vis_timer.start_sub_timer() e, h = op.split_eh(fields) visf = vis.make_file("em-%d-%04d" % (order, step)) vis.add_data(visf, [ ("e", discr.convert_volume(e, kind="numpy")), ("h", discr.convert_volume(h, kind="numpy")), ], time=t, step=step) visf.close() sub_timer.stop().submit() fields = stepper(fields, t, dt, rhs) mode.set_time(final_time) eoc_rec.add_data_point(order, discr.norm(fields - get_true_field())) finally: if write_output: vis.close() logmgr.close() discr.close() if rcon.is_head_rank: print print eoc_rec.pretty_print("P.Deg.", "L2 Error") # }}} assert eoc_rec.estimate_order_of_convergence()[0, 1] > 6
def main(write_output=True): from hedge.timestep.runge_kutta import LSRK4TimeStepper from math import sqrt, pi, exp from hedge.backends import guess_run_context rcon = guess_run_context() epsilon0 = 8.8541878176e-12 # C**2 / (N m**2) mu0 = 4 * pi * 1e-7 # N/A**2. epsilon = 1 * epsilon0 mu = 1 * mu0 c = 1 / sqrt(mu * epsilon) pml_width = 0.5 #mesh = make_mesh(a=np.array((-1,-1,-1)), b=np.array((1,1,1)), #mesh = make_mesh(a=np.array((-3,-3)), b=np.array((3,3)), mesh = make_mesh( a=np.array((-1, -1)), b=np.array((1, 1)), #mesh = make_mesh(a=np.array((-2,-2)), b=np.array((2,2)), pml_width=pml_width, max_volume=0.01) if rcon.is_head_rank: mesh_data = rcon.distribute_mesh(mesh) else: mesh_data = rcon.receive_mesh() class Current: def volume_interpolant(self, t, discr): from hedge.tools import make_obj_array result = discr.volume_zeros(kind="numpy", dtype=np.float64) omega = 6 * c if omega * t > 2 * pi: return make_obj_array([result, result, result]) x = make_obj_array(discr.nodes.T) r = np.sqrt(np.dot(x, x)) idx = r < 0.3 result[idx] = (1+np.cos(pi*r/0.3))[idx] \ *np.sin(omega*t)**3 result = discr.convert_volume(result, kind=discr.compute_kind, dtype=discr.default_scalar_type) return make_obj_array([-result, result, result]) order = 3 discr = rcon.make_discretization(mesh_data, order=order, debug=["cuda_no_plan"]) from hedge.visualization import VtkVisualizer if write_output: vis = VtkVisualizer(discr, rcon, "em-%d" % order) from hedge.mesh import TAG_ALL, TAG_NONE from hedge.data import GivenFunction, TimeHarmonicGivenFunction, TimeIntervalGivenFunction from hedge.models.em import MaxwellOperator from hedge.models.pml import \ AbarbanelGottliebPMLMaxwellOperator, \ AbarbanelGottliebPMLTMMaxwellOperator, \ AbarbanelGottliebPMLTEMaxwellOperator op = AbarbanelGottliebPMLTEMaxwellOperator(epsilon, mu, flux_type=1, current=Current(), pec_tag=TAG_ALL, absorb_tag=TAG_NONE, add_decay=True) fields = op.assemble_ehpq(discr=discr) stepper = LSRK4TimeStepper() if rcon.is_head_rank: print "order %d" % order print "#elements=", len(mesh.elements) # diagnostics setup --------------------------------------------------- from pytools.log import LogManager, add_general_quantities, \ add_simulation_quantities, add_run_info if write_output: log_file_name = "maxwell-%d.dat" % order else: log_file_name = None logmgr = LogManager(log_file_name, "w", rcon.communicator) add_run_info(logmgr) add_general_quantities(logmgr) add_simulation_quantities(logmgr) discr.add_instrumentation(logmgr) stepper.add_instrumentation(logmgr) from pytools.log import IntervalTimer vis_timer = IntervalTimer("t_vis", "Time spent visualizing") logmgr.add_quantity(vis_timer) from hedge.log import EMFieldGetter, add_em_quantities field_getter = EMFieldGetter(discr, op, lambda: fields) add_em_quantities(logmgr, op, field_getter) logmgr.add_watches( ["step.max", "t_sim.max", ("W_field", "W_el+W_mag"), "t_step.max"]) from hedge.log import LpNorm class FieldIdxGetter: def __init__(self, whole_getter, idx): self.whole_getter = whole_getter self.idx = idx def __call__(self): return self.whole_getter()[self.idx] # timestep loop ------------------------------------------------------- t = 0 pml_coeff = op.coefficients_from_width(discr, width=pml_width) rhs = op.bind(discr, pml_coeff) try: from hedge.timestep import times_and_steps step_it = times_and_steps( final_time=4 / c, logmgr=logmgr, max_dt_getter=lambda t: op.estimate_timestep( discr, stepper=stepper, t=t, fields=fields)) for step, t, dt in step_it: if step % 10 == 0 and write_output: e, h, p, q = op.split_ehpq(fields) visf = vis.make_file("em-%d-%04d" % (order, step)) #pml_rhs_e, pml_rhs_h, pml_rhs_p, pml_rhs_q = \ #op.split_ehpq(rhs(t, fields)) j = Current().volume_interpolant(t, discr) vis.add_data( visf, [ ("e", discr.convert_volume(e, "numpy")), ("h", discr.convert_volume(h, "numpy")), ("p", discr.convert_volume(p, "numpy")), ("q", discr.convert_volume(q, "numpy")), ("j", discr.convert_volume(j, "numpy")), #("pml_rhs_e", pml_rhs_e), #("pml_rhs_h", pml_rhs_h), #("pml_rhs_p", pml_rhs_p), #("pml_rhs_q", pml_rhs_q), #("max_rhs_e", max_rhs_e), #("max_rhs_h", max_rhs_h), #("max_rhs_p", max_rhs_p), #("max_rhs_q", max_rhs_q), ], time=t, step=step) visf.close() fields = stepper(fields, t, dt, rhs) _, _, energies_data = logmgr.get_expr_dataset("W_el+W_mag") energies = [value for tick_nbr, value in energies_data] assert energies[-1] < max(energies) * 1e-2 finally: logmgr.close() if write_output: vis.close()
def main(write_output=True, flux_type_arg="upwind", dtype=np.float64, debug=[]): from math import sin, cos, pi, exp, sqrt # noqa from hedge.backends import guess_run_context rcon = guess_run_context() if rcon.is_head_rank: from hedge.mesh.reader.gmsh import generate_gmsh mesh = generate_gmsh(GEOMETRY, 2, allow_internal_boundaries=True, force_dimension=2) print "%d elements" % len(mesh.elements) mesh_data = rcon.distribute_mesh(mesh) else: mesh_data = rcon.receive_mesh() discr = rcon.make_discretization(mesh_data, order=4, debug=debug, default_scalar_type=dtype) from hedge.timestep.runge_kutta import LSRK4TimeStepper stepper = LSRK4TimeStepper(dtype=dtype) from hedge.visualization import VtkVisualizer if write_output: vis = VtkVisualizer(discr, rcon, "fld") source_center = 0 source_width = 0.05 source_omega = 3 import hedge.optemplate as sym sym_x = sym.nodes(2) sym_source_center_dist = sym_x - source_center from hedge.models.wave import StrongWaveOperator op = StrongWaveOperator( -1, discr.dimensions, source_f=sym.CFunction("sin")( source_omega * sym.ScalarParameter("t")) * sym.CFunction("exp")( -np.dot(sym_source_center_dist, sym_source_center_dist) / source_width**2), dirichlet_tag="boundary", neumann_tag=TAG_NONE, radiation_tag=TAG_NONE, flux_type=flux_type_arg) from hedge.tools import join_fields fields = join_fields( discr.volume_zeros(dtype=dtype), [discr.volume_zeros(dtype=dtype) for i in range(discr.dimensions)]) # diagnostics setup ------------------------------------------------------- from pytools.log import LogManager, \ add_general_quantities, \ add_simulation_quantities, \ add_run_info if write_output: log_file_name = "wiggly.dat" else: log_file_name = None logmgr = LogManager(log_file_name, "w", rcon.communicator) add_run_info(logmgr) add_general_quantities(logmgr) add_simulation_quantities(logmgr) discr.add_instrumentation(logmgr) stepper.add_instrumentation(logmgr) logmgr.add_watches(["step.max", "t_sim.max", "t_step.max"]) # timestep loop ----------------------------------------------------------- rhs = op.bind(discr) try: from hedge.timestep import times_and_steps step_it = times_and_steps( final_time=4, logmgr=logmgr, max_dt_getter=lambda t: op.estimate_timestep( discr, stepper=stepper, t=t, fields=fields)) for step, t, dt in step_it: if step % 10 == 0 and write_output: visf = vis.make_file("fld-%04d" % step) vis.add_data(visf, [ ("u", fields[0]), ("v", fields[1:]), ], time=t, step=step) visf.close() fields = stepper(fields, t, dt, rhs) assert discr.norm(fields) < 1 assert fields[0].dtype == dtype finally: if write_output: vis.close() logmgr.close() discr.close()
def main(write_output=True, flux_type_arg="central", use_quadrature=True, final_time=20): from math import sin, cos, pi, sqrt from hedge.backends import guess_run_context rcon = guess_run_context() # mesh setup -------------------------------------------------------------- if rcon.is_head_rank: #from hedge.mesh.generator import make_disk_mesh #mesh = make_disk_mesh() from hedge.mesh.generator import make_rect_mesh mesh = make_rect_mesh(a=(-1, -1), b=(1, 1), max_area=0.008) if rcon.is_head_rank: mesh_data = rcon.distribute_mesh(mesh) else: mesh_data = rcon.receive_mesh() # space-time-dependent-velocity-field ------------------------------------- # simple vortex class TimeDependentVField: """ `TimeDependentVField` is a callable expecting `(x, t)` representing space and time `x` is of the length of the spatial dimension and `t` is the time.""" shape = (2, ) def __call__(self, pt, el, t): x, y = pt # Correction-Factor to make the speed zero on the on the boundary #fac = (1-x**2)*(1-y**2) fac = 1. return numpy.array([-y * fac, x * fac]) * cos(pi * t) class VField: """ `VField` is a callable expecting `(x)` representing space `x` is of the length of the spatial dimension.""" shape = (2, ) def __call__(self, pt, el): x, y = pt # Correction-Factor to make the speed zero on the on the boundary #fac = (1-x**2)*(1-y**2) fac = 1. return numpy.array([-y * fac, x * fac]) # space-time-dependent State BC (optional)----------------------------------- class TimeDependentBc_u: """ space and time dependent BC for state u""" def __call__(self, pt, el, t): x, y = pt if t <= 0.5: if x > 0: return 1 else: return 0 else: return 0 class Bc_u: """ Only space dependent BC for state u""" def __call__(seld, pt, el): x, y = pt if x > 0: return 1 else: return 0 # operator setup ---------------------------------------------------------- # In the operator setup it is possible to switch between a only space # dependent velocity field `VField` or a time and space dependent # `TimeDependentVField`. # For `TimeDependentVField`: advec_v=TimeDependentGivenFunction(VField()) # For `VField`: advec_v=TimeConstantGivenFunction(GivenFunction(VField())) # Same for the Bc_u Function! If you don't define Bc_u then the BC for u = 0. from hedge.data import \ ConstantGivenFunction, \ TimeConstantGivenFunction, \ TimeDependentGivenFunction, \ GivenFunction from hedge.models.advection import VariableCoefficientAdvectionOperator op = VariableCoefficientAdvectionOperator( mesh.dimensions, #advec_v=TimeDependentGivenFunction( # TimeDependentVField()), advec_v=TimeConstantGivenFunction(GivenFunction(VField())), #bc_u_f=TimeDependentGivenFunction( # TimeDependentBc_u()), bc_u_f=TimeConstantGivenFunction(GivenFunction(Bc_u())), flux_type=flux_type_arg) # discretization setup ---------------------------------------------------- order = 5 if use_quadrature: quad_min_degrees = {"quad": 3 * order} else: quad_min_degrees = {} discr = rcon.make_discretization( mesh_data, order=order, default_scalar_type=numpy.float64, debug=["cuda_no_plan"], quad_min_degrees=quad_min_degrees, tune_for=op.op_template(), ) vis_discr = discr # visualization setup ----------------------------------------------------- from hedge.visualization import VtkVisualizer if write_output: vis = VtkVisualizer(vis_discr, rcon, "fld") # initial condition ------------------------------------------------------- if True: def initial(pt, el): # Gauss pulse from math import exp x = (pt - numpy.array([0.3, 0.5])) * 8 return exp(-numpy.dot(x, x)) else: def initial(pt, el): # Rectangle x, y = pt if abs(x) < 0.5 and abs(y) < 0.2: return 2 else: return 1 u = discr.interpolate_volume_function(initial) # timestep setup ---------------------------------------------------------- from hedge.timestep.runge_kutta import LSRK4TimeStepper stepper = LSRK4TimeStepper( vector_primitive_factory=discr.get_vector_primitive_factory()) if rcon.is_head_rank: print "%d elements" % len(discr.mesh.elements) # filter setup------------------------------------------------------------- from hedge.discretization import ExponentialFilterResponseFunction from hedge.optemplate.operators import FilterOperator mode_filter = FilterOperator( ExponentialFilterResponseFunction(min_amplification=0.9,order=4))\ .bind(discr) # diagnostics setup ------------------------------------------------------- from pytools.log import LogManager, \ add_general_quantities, \ add_simulation_quantities, \ add_run_info if write_output: log_file_name = "space-dep.dat" else: log_file_name = None logmgr = LogManager(log_file_name, "w", rcon.communicator) add_run_info(logmgr) add_general_quantities(logmgr) add_simulation_quantities(logmgr) discr.add_instrumentation(logmgr) stepper.add_instrumentation(logmgr) from hedge.log import Integral, LpNorm u_getter = lambda: u logmgr.add_quantity(Integral(u_getter, discr, name="int_u")) logmgr.add_quantity(LpNorm(u_getter, discr, p=1, name="l1_u")) logmgr.add_quantity(LpNorm(u_getter, discr, name="l2_u")) logmgr.add_watches(["step.max", "t_sim.max", "l2_u", "t_step.max"]) # Initialize v for data output: v = op.advec_v.volume_interpolant(0, discr) # timestep loop ----------------------------------------------------------- rhs = op.bind(discr) try: from hedge.timestep import times_and_steps step_it = times_and_steps(final_time=final_time, logmgr=logmgr, max_dt_getter=lambda t: op.estimate_timestep( discr, stepper=stepper, t=t, fields=u)) for step, t, dt in step_it: if step % 10 == 0 and write_output: visf = vis.make_file("fld-%04d" % step) vis.add_data(visf, [("u", discr.convert_volume(u, kind="numpy")), ("v", discr.convert_volume(v, kind="numpy"))], time=t, step=step) visf.close() u = stepper(u, t, dt, rhs) # We're feeding in a discontinuity through the BCs. # Quadrature does not help with shock capturing-- # therefore we do need to filter here, regardless # of whether quadrature is enabled. u = mode_filter(u) assert discr.norm(u) < 10 finally: if write_output: vis.close() logmgr.close() discr.close()
def main(write_output=True, flux_type_arg="upwind"): from hedge.tools import mem_checkpoint from math import sin, cos, pi, sqrt from math import floor from hedge.backends import guess_run_context rcon = guess_run_context() def f(x): return sin(pi * x) def u_analytic(x, el, t): return f((-numpy.dot(v, x) / norm_v + t * norm_v)) def boundary_tagger(vertices, el, face_nr, all_v): if numpy.dot(el.face_normals[face_nr], v) < 0: return ["inflow"] else: return ["outflow"] dim = 2 if dim == 1: v = numpy.array([1]) if rcon.is_head_rank: from hedge.mesh.generator import make_uniform_1d_mesh mesh = make_uniform_1d_mesh(0, 2, 10, periodic=True) elif dim == 2: v = numpy.array([2, 0]) if rcon.is_head_rank: from hedge.mesh.generator import make_disk_mesh mesh = make_disk_mesh(boundary_tagger=boundary_tagger) elif dim == 3: v = numpy.array([0, 0, 1]) if rcon.is_head_rank: from hedge.mesh.generator import make_cylinder_mesh, make_ball_mesh, make_box_mesh mesh = make_cylinder_mesh(max_volume=0.04, height=2, boundary_tagger=boundary_tagger, periodic=False, radial_subdivisions=32) else: raise RuntimeError, "bad number of dimensions" norm_v = la.norm(v) if rcon.is_head_rank: mesh_data = rcon.distribute_mesh(mesh) else: mesh_data = rcon.receive_mesh() if dim != 1: mesh_data = mesh_data.reordered_by("cuthill") discr = rcon.make_discretization(mesh_data, order=4) vis_discr = discr from hedge.visualization import VtkVisualizer if write_output: vis = VtkVisualizer(vis_discr, rcon, "fld") # operator setup ---------------------------------------------------------- from hedge.data import \ ConstantGivenFunction, \ TimeConstantGivenFunction, \ TimeDependentGivenFunction from hedge.models.advection import StrongAdvectionOperator, WeakAdvectionOperator op = WeakAdvectionOperator(v, inflow_u=TimeDependentGivenFunction(u_analytic), flux_type=flux_type_arg) u = discr.interpolate_volume_function(lambda x, el: u_analytic(x, el, 0)) # timestep setup ---------------------------------------------------------- from hedge.timestep.runge_kutta import LSRK4TimeStepper stepper = LSRK4TimeStepper() if rcon.is_head_rank: print "%d elements" % len(discr.mesh.elements) # diagnostics setup ------------------------------------------------------- from pytools.log import LogManager, \ add_general_quantities, \ add_simulation_quantities, \ add_run_info if write_output: log_file_name = "advection.dat" else: log_file_name = None logmgr = LogManager(log_file_name, "w", rcon.communicator) add_run_info(logmgr) add_general_quantities(logmgr) add_simulation_quantities(logmgr) discr.add_instrumentation(logmgr) stepper.add_instrumentation(logmgr) from hedge.log import Integral, LpNorm u_getter = lambda: u logmgr.add_quantity(Integral(u_getter, discr, name="int_u")) logmgr.add_quantity(LpNorm(u_getter, discr, p=1, name="l1_u")) logmgr.add_quantity(LpNorm(u_getter, discr, name="l2_u")) logmgr.add_watches(["step.max", "t_sim.max", "l2_u", "t_step.max"]) # timestep loop ----------------------------------------------------------- rhs = op.bind(discr) try: from hedge.timestep import times_and_steps step_it = times_and_steps(final_time=3, logmgr=logmgr, max_dt_getter=lambda t: op.estimate_timestep( discr, stepper=stepper, t=t, fields=u)) for step, t, dt in step_it: if step % 5 == 0 and write_output: visf = vis.make_file("fld-%04d" % step) vis.add_data(visf, [ ("u", discr.convert_volume(u, kind="numpy")), ], time=t, step=step) visf.close() u = stepper(u, t, dt, rhs) true_u = discr.interpolate_volume_function( lambda x, el: u_analytic(x, el, t)) print discr.norm(u - true_u) assert discr.norm(u - true_u) < 1e-2 finally: if write_output: vis.close() logmgr.close() discr.close()
def __init__(self, units): from pyrticle.deposition.shape import \ ShapeFunctionDepositor, \ NormalizedShapeFunctionDepositor from pyrticle.deposition.advective import \ AdvectiveDepositor from pyrticle.deposition.grid import \ GridDepositor from pyrticle.deposition.grid_find import \ GridFindDepositor from pyrticle.deposition.grid_base import \ SingleBrickGenerator, \ FineCoreBrickGenerator from pyrticle.pusher import \ MonomialParticlePusher, \ AverageParticlePusher import pyrticle.geometry import pyrticle.distribution constants = { "numpy": numpy, "la": numpy.linalg, "units": units, "pyrticle": pyrticle, "DepShape": ShapeFunctionDepositor, "DepNormShape": NormalizedShapeFunctionDepositor, "DepAdv": AdvectiveDepositor, "DepGrid": GridDepositor, "DepGridFind": GridFindDepositor, "SingleBrickGenerator": SingleBrickGenerator, "FineCoreBrickGenerator": FineCoreBrickGenerator, "PushMonomial": MonomialParticlePusher, "PushAverage": AverageParticlePusher, } import hedge.data from hedge.timestep.runge_kutta import LSRK4TimeStepper variables = { "pusher": None, "depositor": None, "mesh": None, "dimensions_pos": None, "dimensions_velocity": None, "beam_axis": None, "beam_diag_axis": None, "tube_length": None, "element_order": None, "maxwell_flux_type": "lf", "maxwell_bdry_flux_type": 1, "shape_exponent": 2, "shape_bandwidth": "optimize", "chi": None, "phi_decay": 0, "phi_filter": None, "potential_bc": hedge.data.ConstantGivenFunction(), "final_time": None, "nparticles": 20000, "distribution": None, "vis_interval": 100, "vis_pattern": "pic-%04d", "vis_order": None, "output_path": ".", "debug": set(["ic", "poisson", "shape_bw"]), "dg_debug": set(), "profile_output_filename": None, "watch_vars": [ "step", "t_sim", ("W_field", "W_el+W_mag"), "t_step", "t_eta", "n_part" ], "hook_startup": lambda runner: None, "hook_after_step": lambda runner, state: None, "hook_when_done": lambda runner: None, "hook_vis_quantities": lambda observer: [ ("e", observer.e), ("h", observer.h), ("j", observer.method.deposit_j(observer.state)), ], "hook_visualize": lambda runner, vis, visf, observer: None, "timestepper_maker": lambda dt: LSRK4TimeStepper(), "dt_scale": 1, } doc = { "chi": "relative speed of hyp. cleaning (None for no cleaning)", "nparticles": "how many particles", "vis_interval": "how often a visualization of the fields is written", "max_volume_inner": "max. tet volume in inner mesh [m^3]", "max_volume_outer": "max. tet volume in outer mesh [m^3]", "shape_bandwidth": "either 'optimize', 'guess' or a positive real number", "phi_filter": "a tuple (min_amp, order) or None, describing the filtering applied to phi in hypclean mode", } pytools.CPyUserInterface.__init__(self, variables, constants, doc)
stepper.add_instrumentation(logmgr) try: from hedge.timestep import times_and_steps # for visc=0.01 #stab_fac = 0.1 # RK4 #stab_fac = 1.6 # dumka3(3), central #stab_fac = 3 # dumka3(4), central #stab_fac = 0.01 # RK4 stab_fac = 0.2 # dumka3(3), central #stab_fac = 3 # dumka3(4), central dt = stab_fac * op.estimate_timestep( discr, stepper=LSRK4TimeStepper(), t=0, fields=u) step_it = times_and_steps(final_time=case.final_time, logmgr=logmgr, max_dt_getter=lambda t: dt) from hedge.optemplate import InverseVandermondeOperator inv_vdm = InverseVandermondeOperator().bind(discr) for step, t, dt in step_it: if step % 3 == 0 and write_output: if hasattr(case, "u_exact"): extra_fields = [("u_exact", discr.interpolate_volume_function( lambda x, el: case.u_exact(x[0], t)))] else: extra_fields = []
def main(write_output=True, dtype=np.float32): from hedge.backends import guess_run_context rcon = guess_run_context() from hedge.mesh.generator import make_rect_mesh if rcon.is_head_rank: h_fac = 1 mesh = make_rect_mesh(a=(0, 0), b=(1, 1), max_area=h_fac**2 * 1e-4, periodicity=(True, True), subdivisions=(int(70 / h_fac), int(70 / h_fac))) from hedge.models.gas_dynamics.lbm import \ D2Q9LBMMethod, LatticeBoltzmannOperator op = LatticeBoltzmannOperator(D2Q9LBMMethod(), lbm_delta_t=0.001, nu=1e-4) if rcon.is_head_rank: print "%d elements" % len(mesh.elements) mesh_data = rcon.distribute_mesh(mesh) else: mesh_data = rcon.receive_mesh() discr = rcon.make_discretization(mesh_data, order=3, default_scalar_type=dtype, debug=["cuda_no_plan"]) from hedge.timestep.runge_kutta import LSRK4TimeStepper stepper = LSRK4TimeStepper( dtype=dtype, #vector_primitive_factory=discr.get_vector_primitive_factory() ) from hedge.visualization import VtkVisualizer if write_output: vis = VtkVisualizer(discr, rcon, "fld") from hedge.data import CompiledExpressionData def ic_expr(t, x, fields): from hedge.optemplate import CFunction from pymbolic.primitives import IfPositive from pytools.obj_array import make_obj_array tanh = CFunction("tanh") sin = CFunction("sin") rho = 1 u0 = 0.05 w = 0.05 delta = 0.05 from hedge.optemplate.primitives import make_common_subexpression as cse u = cse( make_obj_array([ IfPositive(x[1] - 1 / 2, u0 * tanh(4 * (3 / 4 - x[1]) / w), u0 * tanh(4 * (x[1] - 1 / 4) / w)), u0 * delta * sin(2 * np.pi * (x[0] + 1 / 4)) ]), "u") return make_obj_array([ op.method.f_equilibrium(rho, alpha, u) for alpha in range(len(op.method)) ]) # timestep loop ----------------------------------------------------------- stream_rhs = op.bind_rhs(discr) collision_update = op.bind(discr, op.collision_update) get_rho = op.bind(discr, op.rho) get_rho_u = op.bind(discr, op.rho_u) f_bar = CompiledExpressionData(ic_expr).volume_interpolant(0, discr) from hedge.discretization import ExponentialFilterResponseFunction from hedge.optemplate.operators import FilterOperator mode_filter = FilterOperator( ExponentialFilterResponseFunction(min_amplification=0.9, order=4))\ .bind(discr) final_time = 1000 try: lbm_dt = op.lbm_delta_t dg_dt = op.estimate_timestep(discr, stepper=stepper) print dg_dt dg_steps_per_lbm_step = int(np.ceil(lbm_dt / dg_dt)) dg_dt = lbm_dt / dg_steps_per_lbm_step lbm_steps = int(final_time // op.lbm_delta_t) for step in xrange(lbm_steps): t = step * lbm_dt if step % 100 == 0 and write_output: visf = vis.make_file("fld-%04d" % step) rho = get_rho(f_bar) rho_u = get_rho_u(f_bar) vis.add_data( visf, [("fbar%d" % i, discr.convert_volume(f_bar_i, "numpy")) for i, f_bar_i in enumerate(f_bar)] + [ ("rho", discr.convert_volume(rho, "numpy")), ("rho_u", discr.convert_volume(rho_u, "numpy")), ], time=t, step=step) visf.close() print "step=%d, t=%f" % (step, t) f_bar = collision_update(f_bar) for substep in range(dg_steps_per_lbm_step): f_bar = stepper(f_bar, t + substep * dg_dt, dg_dt, stream_rhs) #f_bar = mode_filter(f_bar) finally: if write_output: vis.close() discr.close()
def main(write_output=True, allow_features=None, flux_type_arg=1, bdry_flux_type_arg=None, extra_discr_args={}): from math import sqrt, pi from hedge.models.em import TEMaxwellOperator from hedge.backends import guess_run_context rcon = guess_run_context(allow_features) epsilon0 = 8.8541878176e-12 # C**2 / (N m**2) mu0 = 4*pi*1e-7 # N/A**2. c = 1/sqrt(mu0*epsilon0) materials = {"vacuum" : (epsilon0, mu0), "dielectric" : (2*epsilon0, mu0)} output_dir = "2d_cavity" import os if not os.access(output_dir, os.F_OK): os.makedirs(output_dir) # should no tag raise an error or default to free space? def eps_val(x, el): for key in materials.keys(): if el in material_elements[key]: return materials[key][0] raise ValueError, "Element does not belong to any material" def mu_val(x, el): for key in materials.keys(): if el in material_elements[key]: return materials[key][1] raise ValueError, "Element does not belong to any material" # geometry of cavity d = 100e-3 a = 150e-3 # analytical frequency and transverse wavenumbers of resonance f0 = 9.0335649907522321e8 h = 2*pi*f0/c l = -h*sqrt(2) # substitute the following and change materials for a homogeneous cavity #h = pi/a #l =-h def initial_val(discr): # the initial solution for the TE_10-like mode def initial_Hz(x, el): from math import cos, sin if el in material_elements["vacuum"]: return h*cos(h*x[0]) else: return -l*sin(h*d)/sin(l*(a-d))*cos(l*(a-x[0])) from hedge.tools import make_obj_array result_zero = discr.volume_zeros(kind="numpy", dtype=numpy.float64) H_z = make_tdep_given(initial_Hz).volume_interpolant(0, discr) return make_obj_array([result_zero, result_zero, H_z]) if rcon.is_head_rank: from hedge.mesh.reader.gmsh import generate_gmsh mesh = generate_gmsh(CAVITY_GEOMETRY, 2, force_dimension=2) mesh_data = rcon.distribute_mesh(mesh) else: mesh_data = rcon.receive_mesh() # Work out which elements belong to each material material_elements = {} for key in materials.keys(): material_elements[key] = set(mesh_data.tag_to_elements[key]) order = 3 #extra_discr_args.setdefault("debug", []).append("cuda_no_plan") #extra_discr_args.setdefault("debug", []).append("dump_optemplate_stages") from hedge.data import make_tdep_given from hedge.mesh import TAG_ALL op = TEMaxwellOperator(epsilon=make_tdep_given(eps_val), mu=make_tdep_given(mu_val), \ flux_type=flux_type_arg, \ bdry_flux_type=bdry_flux_type_arg, dimensions=2, pec_tag=TAG_ALL) # op = TEMaxwellOperator(epsilon=epsilon0, mu=mu0, # flux_type=flux_type_arg, \ # bdry_flux_type=bdry_flux_type_arg, dimensions=2, pec_tag=TAG_ALL) discr = rcon.make_discretization(mesh_data, order=order, tune_for=op.op_template(), **extra_discr_args) # create the initial solution fields = initial_val(discr) from hedge.visualization import VtkVisualizer if write_output: from os.path import join vis = VtkVisualizer(discr, rcon, join(output_dir, "cav-%d" % order)) # monitor the solution at a point to find the resonant frequency try: point_getter = discr.get_point_evaluator(numpy.array([75e-3, 25e-3, 0])) #[0.25, 0.25, 0.25])) except RuntimeError: point_getter = None if rcon.is_head_rank: print "---------------------------------------------" print "order %d" % order print "---------------------------------------------" print "#elements=", len(mesh.elements) from hedge.timestep.runge_kutta import LSRK4TimeStepper stepper = LSRK4TimeStepper(dtype=discr.default_scalar_type, rcon=rcon) #from hedge.timestep.dumka3 import Dumka3TimeStepper #stepper = Dumka3TimeStepper(3, dtype=discr.default_scalar_type, rcon=rcon) # diagnostics setup --------------------------------------------------- from pytools.log import LogManager, add_general_quantities, \ add_simulation_quantities, add_run_info if write_output: from os.path import join log_file_name = join(output_dir, "cavity-%d.dat" % order) else: log_file_name = None logmgr = LogManager(log_file_name, "w", rcon.communicator) add_run_info(logmgr) add_general_quantities(logmgr) add_simulation_quantities(logmgr) discr.add_instrumentation(logmgr) stepper.add_instrumentation(logmgr) from pytools.log import IntervalTimer vis_timer = IntervalTimer("t_vis", "Time spent visualizing") logmgr.add_quantity(vis_timer) #from hedge.log import EMFieldGetter, add_em_quantities #field_getter = EMFieldGetter(discr, op, lambda: fields) #add_em_quantities(logmgr, op, field_getter) logmgr.add_watches( ["step.max", "t_sim.max", #("W_field", "W_el+W_mag"), "t_step.max"] ) # timestep loop ------------------------------------------------------- rhs = op.bind(discr) final_time = 10e-9 if point_getter is not None: from os.path import join pointfile = open(join(output_dir, "point.txt"), "wt") done_dt = False try: from hedge.timestep import times_and_steps from os.path import join step_it = times_and_steps( final_time=final_time, logmgr=logmgr, max_dt_getter=lambda t: op.estimate_timestep(discr, stepper=stepper, t=t, fields=fields)) for step, t, dt in step_it: if step % 10 == 0 and write_output: sub_timer = vis_timer.start_sub_timer() e, h = op.split_eh(fields) visf = vis.make_file(join(output_dir, "cav-%d-%04d") % (order, step)) vis.add_data(visf, [ ("e", discr.convert_volume(e, kind="numpy")), ("h", discr.convert_volume(h, kind="numpy")),], time=t, step=step ) visf.close() sub_timer.stop().submit() fields = stepper(fields, t, dt, rhs) if point_getter is not None: val = point_getter(fields) #print val if not done_dt: pointfile.write("#%g\n" % dt) done_dt = True pointfile.write("%g\n" %val[0]) finally: if write_output: vis.close() logmgr.close() discr.close() if point_getter is not None: pointfile.close()
def test_kv_with_no_charge(): from random import seed seed(0) from pyrticle.units import SIUnitsWithNaturalConstants units = SIUnitsWithNaturalConstants() # discretization setup ---------------------------------------------------- from hedge.mesh import make_cylinder_mesh from hedge.backends import guess_run_context rcon = guess_run_context([]) tube_length = 100 * units.MM mesh = make_cylinder_mesh(radius=25 * units.MM, height=tube_length, periodic=True) discr = rcon.make_discretization(mesh, order=3) dt = discr.dt_factor(units.VACUUM_LIGHT_SPEED()) / 2 final_time = 1 * units.M / units.VACUUM_LIGHT_SPEED() nsteps = int(final_time / dt) + 1 dt = final_time / nsteps # particles setup --------------------------------------------------------- from pyrticle.cloud import PicMethod from pyrticle.deposition.shape import ShapeFunctionDepositor from pyrticle.pusher import MonomialParticlePusher method = PicMethod(discr, units, ShapeFunctionDepositor(), MonomialParticlePusher(), 3, 3) nparticles = 10000 cloud_charge = 1e-9 * units.C electrons_per_particle = cloud_charge / nparticles / units.EL_CHARGE el_energy = 5.2e6 * units.EV gamma = el_energy / units.EL_REST_ENERGY() beta = (1 - 1 / gamma**2)**0.5 from pyrticle.distribution import KVZIntervalBeam beam = KVZIntervalBeam(units, total_charge=0, p_charge=0, p_mass=electrons_per_particle * units.EL_MASS, radii=2 * [2.5 * units.MM], emittances=2 * [5 * units.MM * units.MRAD], z_length=5 * units.MM, z_pos=10 * units.MM, beta=beta) state = method.make_state() method.add_particles(state, beam.generate_particles(), nparticles) # diagnostics setup ------------------------------------------------------- from pytools.log import LogManager from pyrticle.log import add_beam_quantities, StateObserver observer = StateObserver(method, None) logmgr = LogManager(mode="w") add_beam_quantities(logmgr, observer, axis=0, beam_axis=2) from pyrticle.distribution import KVPredictedRadius logmgr.add_quantity( KVPredictedRadius(dt, beam_v=beta * units.VACUUM_LIGHT_SPEED(), predictor=beam.get_rms_predictor(axis=0), suffix="x_rms")) logmgr.add_quantity( KVPredictedRadius(dt, beam_v=beta * units.VACUUM_LIGHT_SPEED(), predictor=beam.get_total_predictor(axis=0), suffix="x_total")) # timestep loop ----------------------------------------------------------- vel = method.velocities(state) from hedge.tools import join_fields def rhs(t, y): return join_fields([ vel, 0 * vel, 0, # drecon ]) from hedge.timestep.runge_kutta import LSRK4TimeStepper stepper = LSRK4TimeStepper() t = 0 from pyrticle.cloud import TimesteppablePicState ts_state = TimesteppablePicState(method, state) for step in xrange(nsteps): observer.set_fields_and_state(None, ts_state.state) logmgr.tick() ts_state = stepper(ts_state, t, dt, rhs) method.upkeep(ts_state.state) t += dt logmgr.tick() _, _, err_table = logmgr.get_expr_dataset( "(rx_rms-rx_rms_theory)/rx_rms_theory") rel_max_rms_error = max(err for step, err in err_table) assert rel_max_rms_error < 0.01
def main(): import logging logging.basicConfig(level=logging.INFO) from hedge.backends import guess_run_context rcon = guess_run_context() if rcon.is_head_rank: if True: mesh = make_squaremesh() else: from hedge.mesh import make_rect_mesh mesh = make_rect_mesh( boundary_tagger=lambda fvi, el, fn, all_v: ["inflow"], max_area=0.1) mesh_data = rcon.distribute_mesh(mesh) else: mesh_data = rcon.receive_mesh() from pytools import add_python_path_relative_to_script add_python_path_relative_to_script(".") for order in [3]: from gas_dynamics_initials import UniformMachFlow square = UniformMachFlow(gaussian_pulse_at=numpy.array([-2, 2]), pulse_magnitude=0.003) from hedge.models.gas_dynamics import (GasDynamicsOperator, GammaLawEOS) op = GasDynamicsOperator(dimensions=2, equation_of_state=GammaLawEOS(square.gamma), mu=square.mu, prandtl=square.prandtl, spec_gas_const=square.spec_gas_const, bc_inflow=square, bc_outflow=square, bc_noslip=square, inflow_tag="inflow", outflow_tag="outflow", noslip_tag="noslip") discr = rcon.make_discretization( mesh_data, order=order, debug=[ "cuda_no_plan", "cuda_dump_kernels", #"dump_dataflow_graph", #"dump_optemplate_stages", #"dump_dataflow_graph", #"dump_op_code" #"cuda_no_plan_el_local" ], default_scalar_type=numpy.float64, tune_for=op.op_template(), quad_min_degrees={ "gasdyn_vol": 3 * order, "gasdyn_face": 3 * order, }) from hedge.visualization import SiloVisualizer, VtkVisualizer #vis = VtkVisualizer(discr, rcon, "shearflow-%d" % order) vis = SiloVisualizer(discr, rcon) from hedge.timestep.runge_kutta import (LSRK4TimeStepper, ODE23TimeStepper, ODE45TimeStepper) from hedge.timestep.dumka3 import Dumka3TimeStepper #stepper = LSRK4TimeStepper(dtype=discr.default_scalar_type, #vector_primitive_factory=discr.get_vector_primitive_factory()) stepper = ODE23TimeStepper( dtype=discr.default_scalar_type, rtol=1e-6, vector_primitive_factory=discr.get_vector_primitive_factory()) # Dumka works kind of poorly #stepper = Dumka3TimeStepper(dtype=discr.default_scalar_type, #rtol=1e-7, pol_index=2, #vector_primitive_factory=discr.get_vector_primitive_factory()) #from hedge.timestep.dumka3 import Dumka3TimeStepper #stepper = Dumka3TimeStepper(3, rtol=1e-7) # diagnostics setup --------------------------------------------------- from pytools.log import LogManager, add_general_quantities, \ add_simulation_quantities, add_run_info logmgr = LogManager("cns-square-sp-%d.dat" % order, "w", rcon.communicator) add_run_info(logmgr) add_general_quantities(logmgr) discr.add_instrumentation(logmgr) stepper.add_instrumentation(logmgr) from pytools.log import LogQuantity class ChangeSinceLastStep(LogQuantity): """Records the change of a variable between a time step and the previous one""" def __init__(self, name="change"): LogQuantity.__init__(self, name, "1", "Change since last time step") self.old_fields = 0 def __call__(self): result = discr.norm(fields - self.old_fields) self.old_fields = fields return result #logmgr.add_quantity(ChangeSinceLastStep()) add_simulation_quantities(logmgr) logmgr.add_watches(["step.max", "t_sim.max", "t_step.max"]) # filter setup ------------------------------------------------------------ from hedge.discretization import Filter, ExponentialFilterResponseFunction mode_filter = Filter( discr, ExponentialFilterResponseFunction(min_amplification=0.95, order=6)) # timestep loop ------------------------------------------------------- fields = square.volume_interpolant(0, discr) navierstokes_ex = op.bind(discr) max_eigval = [0] def rhs(t, q): ode_rhs, speed = navierstokes_ex(t, q) max_eigval[0] = speed return ode_rhs rhs(0, fields) if rcon.is_head_rank: print "---------------------------------------------" print "order %d" % order print "---------------------------------------------" print "#elements=", len(mesh.elements) try: from hedge.timestep import times_and_steps step_it = times_and_steps( final_time=1000, #max_steps=500, logmgr=logmgr, max_dt_getter=lambda t: next_dt, taken_dt_getter=lambda: taken_dt) model_stepper = LSRK4TimeStepper() next_dt = op.estimate_timestep(discr, stepper=model_stepper, t=0, max_eigenvalue=max_eigval[0]) for step, t, dt in step_it: #if (step % 10000 == 0): #and step < 950000) or (step % 500 == 0 and step > 950000): #if False: if step % 5 == 0: visf = vis.make_file("square-%d-%06d" % (order, step)) #from pyvisfile.silo import DB_VARTYPE_VECTOR vis.add_data(visf, [ ("rho", discr.convert_volume(op.rho(fields), kind="numpy")), ("e", discr.convert_volume(op.e(fields), kind="numpy")), ("rho_u", discr.convert_volume(op.rho_u(fields), kind="numpy")), ("u", discr.convert_volume(op.u(fields), kind="numpy")), ], expressions=[ ("p", "(0.4)*(e- 0.5*(rho_u*u))"), ], time=t, step=step) visf.close() if stepper.adaptive: fields, t, taken_dt, next_dt = stepper(fields, t, dt, rhs) else: taken_dt = dt fields = stepper(fields, t, dt, rhs) dt = op.estimate_timestep(discr, stepper=model_stepper, t=0, max_eigenvalue=max_eigval[0]) #fields = mode_filter(fields) finally: vis.close() logmgr.save() discr.close()