Exemple #1
0
def main(final_time=1, write_output=False):
    from grudge.backends import guess_run_context
    rcon = guess_run_context()

    from grudge.tools import EOCRecorder, to_obj_array
    eoc_rec = EOCRecorder()

    if rcon.is_head_rank:
        from grudge.mesh import make_box_mesh
        mesh = make_box_mesh((0, 0, 0), (10, 10, 10), max_volume=0.5)
        mesh_data = rcon.distribute_mesh(mesh)
    else:
        mesh_data = rcon.receive_mesh()

    for order in [3, 4, 5]:
        discr = rcon.make_discretization(mesh_data,
                                         order=order,
                                         default_scalar_type=numpy.float64)

        from grudge.visualization import SiloVisualizer, VtkVisualizer
        vis = VtkVisualizer(discr, rcon, "sinewave-%d" % order)
        #vis = SiloVisualizer(discr, rcon)

        sinewave = SineWave()
        fields = sinewave.volume_interpolant(0, discr)
        gamma, mu, prandtl, spec_gas_const = sinewave.properties()

        from grudge.mesh import BTAG_ALL
        from grudge.models.gas_dynamics import GasDynamicsOperator
        op = GasDynamicsOperator(dimensions=mesh.dimensions,
                                 gamma=gamma,
                                 mu=mu,
                                 prandtl=prandtl,
                                 spec_gas_const=spec_gas_const,
                                 bc_inflow=sinewave,
                                 bc_outflow=sinewave,
                                 bc_noslip=sinewave,
                                 inflow_tag=BTAG_ALL,
                                 source=None)

        euler_ex = op.bind(discr)

        max_eigval = [0]

        def rhs(t, q):
            ode_rhs, speed = euler_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))

        from grudge.timestep import RK4TimeStepper
        stepper = RK4TimeStepper()

        # diagnostics setup ---------------------------------------------------
        from pytools.log import LogManager, add_general_quantities, \
                add_simulation_quantities, add_run_info

        if write_output:
            log_name = ("euler-sinewave-%(order)d-%(els)d.dat" % {
                "order": order,
                "els": len(mesh.elements)
            })
        else:
            log_name = False
        logmgr = LogManager(log_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 -------------------------------------------------------
        try:
            from grudge.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, max_eigenvalue=max_eigval[0]))

            for step, t, dt in step_it:
                #if step % 10 == 0:
                if write_output:
                    visf = vis.make_file("sinewave-%d-%04d" % (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")),

                            #("true_rho", op.rho(true_fields)),
                            #("true_e", op.e(true_fields)),
                            #("true_rho_u", op.rho_u(true_fields)),
                            #("true_u", op.u(true_fields)),

                            #("rhs_rho", op.rho(rhs_fields)),
                            #("rhs_e", op.e(rhs_fields)),
                            #("rhs_rho_u", op.rho_u(rhs_fields)),
                        ],
                        #expressions=[
                        #("diff_rho", "rho-true_rho"),
                        #("diff_e", "e-true_e"),
                        #("diff_rho_u", "rho_u-true_rho_u", DB_VARTYPE_VECTOR),

                        #("p", "0.4*(e- 0.5*(rho_u*u))"),
                        #],
                        time=t,
                        step=step)
                    visf.close()

                fields = stepper(fields, t, dt, rhs)

        finally:
            vis.close()
            logmgr.close()
            discr.close()

        true_fields = sinewave.volume_interpolant(t, discr)
        eoc_rec.add_data_point(order, discr.norm(fields - true_fields))
        print()
        print(eoc_rec.pretty_print("P.Deg.", "L2 Error"))
Exemple #2
0
def main(write_output=True) :
    from math import sin, cos, pi, exp, sqrt
    from grudge.data import TimeConstantGivenFunction, \
            ConstantGivenFunction

    from grudge.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 grudge.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 grudge.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 grudge.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 grudge.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 logpyle 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 grudge.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 grudge.timestep.runge_kutta import LSRK4TimeStepper, ODE45TimeStepper
    from grudge.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 grudge.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()
Exemple #3
0
                    extra_fields = []

                visf = vis.make_file("fld-%04d" % step)
                vis.add_data(visf, [
                    ("u", u),
                ] + extra_fields,
                             time=t,
                             step=step)
                visf.close()

            u = stepper(u, t, dt, rhs)

        if isinstance(case, ExactTestCase):
            assert discr.norm(u, 1) < 50

    finally:
        if write_output:
            vis.close()

        logmgr.save()


if __name__ == "__main__":
    main()


# entry points for py.test ----------------------------------------------------
@mark_test.long
def test_stability():
    main(write_output=False)
Exemple #4
0
def main(write_output=True):
    from pytools import add_python_path_relative_to_script
    add_python_path_relative_to_script("..")

    from grudge.backends import guess_run_context
    rcon = guess_run_context()

    from grudge.tools import EOCRecorder
    eoc_rec = EOCRecorder()

    if rcon.is_head_rank:
        from grudge.mesh.generator import \
                make_rect_mesh, \
                make_centered_regular_rect_mesh

        refine = 4
        mesh = make_centered_regular_rect_mesh((0, -5), (10, 5),
                                               n=(9, 9),
                                               post_refine_factor=refine)
        mesh_data = rcon.distribute_mesh(mesh)
    else:
        mesh_data = rcon.receive_mesh()

    for order in [3, 4, 5]:
        from gas_dynamics_initials import Vortex
        flow = Vortex()

        from grudge.models.gas_dynamics import (GasDynamicsOperator,
                                                PolytropeEOS, GammaLawEOS)

        from grudge.mesh import BTAG_ALL
        # works equally well for GammaLawEOS
        op = GasDynamicsOperator(dimensions=2,
                                 mu=flow.mu,
                                 prandtl=flow.prandtl,
                                 spec_gas_const=flow.spec_gas_const,
                                 equation_of_state=PolytropeEOS(flow.gamma),
                                 bc_inflow=flow,
                                 bc_outflow=flow,
                                 bc_noslip=flow,
                                 inflow_tag=BTAG_ALL,
                                 source=None)

        discr = rcon.make_discretization(mesh_data,
                                         order=order,
                                         default_scalar_type=numpy.float64,
                                         quad_min_degrees={
                                             "gasdyn_vol": 3 * order,
                                             "gasdyn_face": 3 * order,
                                         },
                                         tune_for=op.sym_operator(),
                                         debug=["cuda_no_plan"])

        from grudge.visualization import SiloVisualizer, VtkVisualizer
        vis = VtkVisualizer(discr, rcon, "vortex-%d" % order)
        #vis = SiloVisualizer(discr, rcon)

        fields = flow.volume_interpolant(0, discr)

        euler_ex = op.bind(discr)

        max_eigval = [0]

        def rhs(t, q):
            ode_rhs, speed = euler_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))

        # limiter ------------------------------------------------------------
        from grudge.models.gas_dynamics import SlopeLimiter1NEuler
        limiter = SlopeLimiter1NEuler(discr, flow.gamma, 2, op)

        from grudge.timestep.runge_kutta import SSP3TimeStepper
        #stepper = SSP3TimeStepper(limiter=limiter)
        stepper = SSP3TimeStepper(
            vector_primitive_factory=discr.get_vector_primitive_factory())

        #from grudge.timestep import RK4TimeStepper
        #stepper = RK4TimeStepper()

        # diagnostics setup ---------------------------------------------------
        from logpyle import LogManager, add_general_quantities, \
                add_simulation_quantities, add_run_info

        if write_output:
            log_file_name = "euler-%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)

        logmgr.add_watches(["step.max", "t_sim.max", "t_step.max"])

        # timestep loop -------------------------------------------------------
        try:
            final_time = flow.final_time
            from grudge.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, max_eigenvalue=max_eigval[0]))

            print("run until t=%g" % final_time)
            for step, t, dt in step_it:
                if step % 10 == 0 and write_output:
                    #if False:
                    visf = vis.make_file("vortex-%d-%04d" % (order, step))

                    #true_fields = vortex.volume_interpolant(t, discr)

                    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")),

                            #("true_rho", discr.convert_volume(op.rho(true_fields), kind="numpy")),
                            #("true_e", discr.convert_volume(op.e(true_fields), kind="numpy")),
                            #("true_rho_u", discr.convert_volume(op.rho_u(true_fields), kind="numpy")),
                            #("true_u", discr.convert_volume(op.u(true_fields), kind="numpy")),

                            #("rhs_rho", discr.convert_volume(op.rho(rhs_fields), kind="numpy")),
                            #("rhs_e", discr.convert_volume(op.e(rhs_fields), kind="numpy")),
                            #("rhs_rho_u", discr.convert_volume(op.rho_u(rhs_fields), kind="numpy")),
                        ],
                        #expressions=[
                        #("diff_rho", "rho-true_rho"),
                        #("diff_e", "e-true_e"),
                        #("diff_rho_u", "rho_u-true_rho_u", DB_VARTYPE_VECTOR),

                        #("p", "0.4*(e- 0.5*(rho_u*u))"),
                        #],
                        time=t,
                        step=step)
                    visf.close()

                fields = stepper(fields, t, dt, rhs)
                #fields = limiter(fields)

                assert not numpy.isnan(numpy.sum(fields[0]))

            true_fields = flow.volume_interpolant(final_time, discr)
            l2_error = discr.norm(fields - true_fields)
            l2_error_rho = discr.norm(op.rho(fields) - op.rho(true_fields))
            l2_error_e = discr.norm(op.e(fields) - op.e(true_fields))
            l2_error_rhou = discr.norm(
                op.rho_u(fields) - op.rho_u(true_fields))
            l2_error_u = discr.norm(op.u(fields) - op.u(true_fields))

            eoc_rec.add_data_point(order, l2_error)
            print()
            print(eoc_rec.pretty_print("P.Deg.", "L2 Error"))

            logmgr.set_constant("l2_error", l2_error)
            logmgr.set_constant("l2_error_rho", l2_error_rho)
            logmgr.set_constant("l2_error_e", l2_error_e)
            logmgr.set_constant("l2_error_rhou", l2_error_rhou)
            logmgr.set_constant("l2_error_u", l2_error_u)
            logmgr.set_constant("refinement", refine)

        finally:
            if write_output:
                vis.close()

            logmgr.close()
            discr.close()

    # after order loop
    assert eoc_rec.estimate_order_of_convergence()[0, 1] > 6
Exemple #5
0
def main(write_output=True, allow_features=None):
    from grudge.timestep import RK4TimeStepper
    from grudge.mesh import make_ball_mesh, make_cylinder_mesh, make_box_mesh
    from grudge.visualization import \
            VtkVisualizer, \
            SiloVisualizer, \
            get_rank_partition
    from math import sqrt, pi

    from grudge.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

    dims = 3

    if rcon.is_head_rank:
        if dims == 2:
            from grudge.mesh import make_rect_mesh
            mesh = make_rect_mesh(a=(-10.5, -1.5), b=(10.5, 1.5), max_area=0.1)
        elif dims == 3:
            from grudge.mesh import make_box_mesh
            mesh = make_box_mesh(a=(-10.5, -1.5, -1.5),
                                 b=(10.5, 1.5, 1.5),
                                 max_volume=0.1)

    if rcon.is_head_rank:
        mesh_data = rcon.distribute_mesh(mesh)
    else:
        mesh_data = rcon.receive_mesh()

    #for order in [1,2,3,4,5,6]:
    discr = rcon.make_discretization(mesh_data, order=3)

    if write_output:
        vis = VtkVisualizer(discr, rcon, "dipole")

    from analytic_solutions import DipoleFarField, SphericalFieldAdapter
    from grudge.data import ITimeDependentGivenFunction

    sph_dipole = DipoleFarField(
        q=1,  #C
        d=1 / 39,
        omega=2 * pi * 1e8,
        epsilon=epsilon0,
        mu=mu0,
    )
    cart_dipole = SphericalFieldAdapter(sph_dipole)

    class PointDipoleSource(ITimeDependentGivenFunction):
        def __init__(self):
            from pyrticle.tools import CInfinityShapeFunction
            sf = CInfinityShapeFunction(0.1 * sph_dipole.wavelength,
                                        discr.dimensions)
            self.num_sf = discr.interpolate_volume_function(
                lambda x, el: sf(x))
            self.vol_0 = discr.volume_zeros()

        def volume_interpolant(self, t, discr):
            from grudge.tools import make_obj_array
            return make_obj_array([
                self.vol_0, self.vol_0,
                sph_dipole.source_modulation(t) * self.num_sf
            ])

    from grudge.mesh import BTAG_ALL, BTAG_NONE
    if dims == 2:
        from grudge.models.em import TMMaxwellOperator as MaxwellOperator
    else:
        from grudge.models.em import MaxwellOperator

    op = MaxwellOperator(
        epsilon,
        mu,
        flux_type=1,
        pec_tag=BTAG_NONE,
        absorb_tag=BTAG_ALL,
        current=PointDipoleSource(),
    )

    fields = op.assemble_eh(discr=discr)

    if rcon.is_head_rank:
        print("#elements=", len(mesh.elements))

    stepper = RK4TimeStepper()

    # diagnostics setup ---------------------------------------------------
    from pytools.log import LogManager, add_general_quantities, \
            add_simulation_quantities, add_run_info

    if write_output:
        log_file_name = "dipole.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 pytools.log import IntervalTimer
    vis_timer = IntervalTimer("t_vis", "Time spent visualizing")
    logmgr.add_quantity(vis_timer)

    from grudge.log import EMFieldGetter, add_em_quantities
    field_getter = EMFieldGetter(discr, op, lambda: fields)
    add_em_quantities(logmgr, op, field_getter)

    from pytools.log import PushLogQuantity
    relerr_e_q = PushLogQuantity("relerr_e", "1",
                                 "Relative error in masked E-field")
    relerr_h_q = PushLogQuantity("relerr_h", "1",
                                 "Relative error in masked H-field")
    logmgr.add_quantity(relerr_e_q)
    logmgr.add_quantity(relerr_h_q)

    logmgr.add_watches([
        "step.max", "t_sim.max", ("W_field", "W_el+W_mag"), "t_step.max",
        "relerr_e", "relerr_h"
    ])

    if write_output:
        point_timeseries = [(open("b-x%d-vs-time.dat" % i,
                                  "w"), open("b-x%d-vs-time-true.dat" % i,
                                             "w"),
                             discr.get_point_evaluator(
                                 numpy.array([i, 0, 0][:dims],
                                             dtype=discr.default_scalar_type)))
                            for i in range(1, 5)]

    # timestep loop -------------------------------------------------------
    mask = discr.interpolate_volume_function(sph_dipole.far_field_mask)

    def apply_mask(field):
        from grudge.tools import log_shape
        ls = log_shape(field)
        result = discr.volume_empty(ls)
        from pytools import indices_in_shape
        for i in indices_in_shape(ls):
            result[i] = mask * field[i]

        return result

    rhs = op.bind(discr)

    t = 0
    try:
        from grudge.timestep import times_and_steps
        step_it = times_and_steps(
            final_time=1e-8,
            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 write_output and step % 10 == 0:
                sub_timer = vis_timer.start_sub_timer()
                e, h = op.split_eh(fields)
                sph_dipole.set_time(t)
                true_e, true_h = op.split_eh(
                    discr.interpolate_volume_function(cart_dipole))
                visf = vis.make_file("dipole-%04d" % step)

                mask_e = apply_mask(e)
                mask_h = apply_mask(h)
                mask_true_e = apply_mask(true_e)
                mask_true_h = apply_mask(true_h)

                from pyvisfile.silo import DB_VARTYPE_VECTOR
                vis.add_data(visf, [("e", e), ("h", h), ("true_e", true_e),
                                    ("true_h", true_h), ("mask_e", mask_e),
                                    ("mask_h", mask_h),
                                    ("mask_true_e", mask_true_e),
                                    ("mask_true_h", mask_true_h)],
                             time=t,
                             step=step)
                visf.close()
                sub_timer.stop().submit()

                from grudge.tools import relative_error
                relerr_e_q.push_value(
                    relative_error(discr.norm(mask_e - mask_true_e),
                                   discr.norm(mask_true_e)))
                relerr_h_q.push_value(
                    relative_error(discr.norm(mask_h - mask_true_h),
                                   discr.norm(mask_true_h)))

                if write_output:
                    for outf_num, outf_true, evaluator in point_timeseries:
                        for outf, ev_h in zip([outf_num, outf_true],
                                              [h, true_h]):
                            outf.write("%g\t%g\n" %
                                       (t, op.mu * evaluator(ev_h[1])))
                            outf.flush()

            fields = stepper(fields, t, dt, rhs)

    finally:
        if write_output:
            vis.close()

        logmgr.save()
        discr.close()
Exemple #6
0
def main(write_output=True, flux_type_arg="upwind"):
    from grudge.tools import mem_checkpoint
    from math import sin, cos, pi, sqrt
    from math import floor

    from grudge.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 grudge.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 grudge.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 grudge.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 grudge.visualization import VtkVisualizer
    if write_output:
        vis = VtkVisualizer(vis_discr, rcon, "fld")

    # operator setup ----------------------------------------------------------
    from grudge.data import \
            ConstantGivenFunction, \
            TimeConstantGivenFunction, \
            TimeDependentGivenFunction
    from grudge.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 grudge.timestep.runge_kutta import LSRK4TimeStepper
    stepper = LSRK4TimeStepper()

    if rcon.is_head_rank:
        print("%d elements" % len(discr.mesh.elements))

    # diagnostics setup -------------------------------------------------------
    from logpyle 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 grudge.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 grudge.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()
Exemple #7
0
def main(write_output=True):
    from math import sqrt, pi, exp
    from os.path import join

    from grudge.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

    output_dir = "maxwell-2d"
    import os
    if not os.access(output_dir, os.F_OK):
        os.makedirs(output_dir)

    from grudge.mesh.generator import make_disk_mesh
    mesh = make_disk_mesh(r=0.5, max_area=1e-3)

    if rcon.is_head_rank:
        mesh_data = rcon.distribute_mesh(mesh)
    else:
        mesh_data = rcon.receive_mesh()

    class CurrentSource:
        shape = (3, )

        def __call__(self, x, el):
            return [0, 0, exp(-80 * la.norm(x))]

    order = 3
    final_time = 1e-8
    discr = rcon.make_discretization(mesh_data,
                                     order=order,
                                     debug=["cuda_no_plan"])

    from grudge.visualization import VtkVisualizer
    if write_output:
        vis = VtkVisualizer(discr, rcon, join(output_dir, "em-%d" % order))

    if rcon.is_head_rank:
        print("order %d" % order)
        print("#elements=", len(mesh.elements))

    from grudge.mesh import BTAG_ALL, BTAG_NONE
    from grudge.models.em import TMMaxwellOperator
    from grudge.data import make_tdep_given, TimeIntervalGivenFunction
    op = TMMaxwellOperator(epsilon,
                           mu,
                           flux_type=1,
                           current=TimeIntervalGivenFunction(
                               make_tdep_given(CurrentSource()),
                               off_time=final_time / 10),
                           absorb_tag=BTAG_ALL,
                           pec_tag=BTAG_NONE)
    fields = op.assemble_eh(discr=discr)

    from grudge.timestep import LSRK4TimeStepper
    stepper = LSRK4TimeStepper()
    from time import time
    last_tstep = time()
    t = 0

    # diagnostics setup ---------------------------------------------------
    from pytools.log import LogManager, add_general_quantities, \
            add_simulation_quantities, add_run_info

    if write_output:
        log_file_name = join(output_dir, "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 grudge.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)

    try:
        from grudge.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 % 10 == 0 and write_output:
                e, h = op.split_eh(fields)
                visf = vis.make_file(
                    join(output_dir, "em-%d-%04d" % (order, step)))
                vis.add_data(visf, [
                    ("e", discr.convert_volume(e, "numpy")),
                    ("h", discr.convert_volume(h, "numpy")),
                ],
                             time=t,
                             step=step)
                visf.close()

            fields = stepper(fields, t, dt, rhs)

        assert discr.norm(fields) < 0.03
    finally:
        if write_output:
            vis.close()

        logmgr.close()
        discr.close()
Exemple #8
0
def main(write_output=True, dtype=np.float32):
    from grudge.backends import guess_run_context
    rcon = guess_run_context()

    from grudge.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 grudge.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 grudge.timestep.runge_kutta import LSRK4TimeStepper
    stepper = LSRK4TimeStepper(
        dtype=dtype,
        #vector_primitive_factory=discr.get_vector_primitive_factory()
    )

    from grudge.visualization import VtkVisualizer
    if write_output:
        vis = VtkVisualizer(discr, rcon, "fld")

    from grudge.data import CompiledExpressionData

    def ic_expr(t, x, fields):
        from grudge.symbolic import FunctionSymbol
        from pymbolic.primitives import IfPositive
        from pytools.obj_array import make_obj_array

        tanh = FunctionSymbol("tanh")
        sin = FunctionSymbol("sin")

        rho = 1
        u0 = 0.05
        w = 0.05
        delta = 0.05

        from grudge.symbolic.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 grudge.discretization import ExponentialFilterResponseFunction
    from grudge.symbolic.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 range(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()
Exemple #9
0
def main(write_output=True):
    from grudge.timestep.runge_kutta import LSRK4TimeStepper
    from math import sqrt, pi, exp

    from grudge.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 grudge.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 grudge.visualization import VtkVisualizer
    if write_output:
        vis = VtkVisualizer(discr, rcon, "em-%d" % order)

    from grudge.mesh import BTAG_ALL, BTAG_NONE
    from grudge.data import GivenFunction, TimeHarmonicGivenFunction, TimeIntervalGivenFunction
    from grudge.models.em import MaxwellOperator
    from grudge.models.pml import \
            AbarbanelGottliebPMLMaxwellOperator, \
            AbarbanelGottliebPMLTMMaxwellOperator, \
            AbarbanelGottliebPMLTEMaxwellOperator

    op = AbarbanelGottliebPMLTEMaxwellOperator(epsilon,
                                               mu,
                                               flux_type=1,
                                               current=Current(),
                                               pec_tag=BTAG_ALL,
                                               absorb_tag=BTAG_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 logpyle 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 logpyle import IntervalTimer
    vis_timer = IntervalTimer("t_vis", "Time spent visualizing")
    logmgr.add_quantity(vis_timer)

    from grudge.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 grudge.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 grudge.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()
Exemple #10
0
def main():
    from grudge.backends import guess_run_context
    rcon = guess_run_context()

    from grudge.tools import to_obj_array

    if rcon.is_head_rank:
        from grudge.mesh.generator import make_rect_mesh
        mesh = make_rect_mesh((-5, -5), (5, 5), max_area=0.01)
        mesh_data = rcon.distribute_mesh(mesh)
    else:
        mesh_data = rcon.receive_mesh()

    for order in [1]:
        discr = rcon.make_discretization(mesh_data,
                                         order=order,
                                         default_scalar_type=numpy.float64)

        from grudge.visualization import SiloVisualizer, VtkVisualizer
        vis = VtkVisualizer(discr, rcon, "Sod2D-%d" % order)
        #vis = SiloVisualizer(discr, rcon)

        sod_field = Sod(gamma=1.4)
        fields = sod_field.volume_interpolant(0, discr)

        from grudge.models.gas_dynamics import GasDynamicsOperator
        from grudge.mesh import BTAG_ALL
        op = GasDynamicsOperator(dimensions=2,
                                 gamma=sod_field.gamma,
                                 mu=0.0,
                                 prandtl=sod_field.prandtl,
                                 bc_inflow=sod_field,
                                 bc_outflow=sod_field,
                                 bc_noslip=sod_field,
                                 inflow_tag=BTAG_ALL,
                                 source=None)

        euler_ex = op.bind(discr)

        max_eigval = [0]

        def rhs(t, q):
            ode_rhs, speed = euler_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))

        # limiter setup ------------------------------------------------------------
        from grudge.models.gas_dynamics import SlopeLimiter1NEuler
        limiter = SlopeLimiter1NEuler(discr, sod_field.gamma, 2, op)

        # integrator setup---------------------------------------------------------
        from grudge.timestep import SSPRK3TimeStepper, RK4TimeStepper
        stepper = SSPRK3TimeStepper(limiter=limiter)
        #stepper = SSPRK3TimeStepper()
        #stepper = RK4TimeStepper()

        # diagnostics setup ---------------------------------------------------
        from pytools.log import LogManager, add_general_quantities, \
                add_simulation_quantities, add_run_info

        logmgr = LogManager("euler-%d.dat" % order, "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"])

        # filter setup-------------------------------------------------------------
        from grudge.discretization import Filter, ExponentialFilterResponseFunction
        mode_filter = Filter(
            discr,
            ExponentialFilterResponseFunction(min_amplification=0.9, order=4))

        # timestep loop -------------------------------------------------------
        try:
            from grudge.timestep import times_and_steps
            step_it = times_and_steps(
                final_time=1.0,
                logmgr=logmgr,
                max_dt_getter=lambda t: op.estimate_timestep(
                    discr, stepper=stepper, t=t, max_eigenvalue=max_eigval[0]))

            for step, t, dt in step_it:
                if step % 5 == 0:
                    #if False:
                    visf = vis.make_file("vortex-%d-%04d" % (order, step))

                    #true_fields = vortex.volume_interpolant(t, discr)

                    #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")),

                            #("true_rho", op.rho(true_fields)),
                            #("true_e", op.e(true_fields)),
                            #("true_rho_u", op.rho_u(true_fields)),
                            #("true_u", op.u(true_fields)),

                            #("rhs_rho", op.rho(rhs_fields)),
                            #("rhs_e", op.e(rhs_fields)),
                            #("rhs_rho_u", op.rho_u(rhs_fields)),
                        ],
                        #expressions=[
                        #("diff_rho", "rho-true_rho"),
                        #("diff_e", "e-true_e"),
                        #("diff_rho_u", "rho_u-true_rho_u", DB_VARTYPE_VECTOR),

                        #("p", "0.4*(e- 0.5*(rho_u*u))"),
                        #],
                        time=t,
                        step=step)
                    visf.close()

                fields = stepper(fields, t, dt, rhs)
                # fields = limiter(fields)
                # fields = mode_filter(fields)

                assert not numpy.isnan(numpy.sum(fields[0]))
        finally:
            vis.close()
            logmgr.close()
            discr.close()

        # not solution, just to check against when making code changes
        true_fields = sod_field.volume_interpolant(t, discr)
        print(discr.norm(fields - true_fields))
def main(write_output=True):
    from pytools import add_python_path_relative_to_script
    add_python_path_relative_to_script("..")

    from grudge.backends import guess_run_context
    rcon = guess_run_context()

    from grudge.tools import EOCRecorder
    eoc_rec = EOCRecorder()

    if rcon.is_head_rank:
        from grudge.mesh.generator import \
                make_rect_mesh, \
                make_centered_regular_rect_mesh

        refine = 4
        mesh = make_centered_regular_rect_mesh((0, -5), (10, 5),
                                               n=(9, 9),
                                               post_refine_factor=refine)
        mesh_data = rcon.distribute_mesh(mesh)
    else:
        mesh_data = rcon.receive_mesh()

    # a second mesh to regrid to
    if rcon.is_head_rank:
        from grudge.mesh.generator import \
                make_rect_mesh, \
                make_centered_regular_rect_mesh

        refine = 4
        mesh2 = make_centered_regular_rect_mesh((0, -5), (10, 5),
                                                n=(8, 8),
                                                post_refine_factor=refine)
        mesh_data2 = rcon.distribute_mesh(mesh2)
    else:
        mesh_data2 = rcon.receive_mesh()

    for order in [3, 4]:
        discr = rcon.make_discretization(mesh_data,
                                         order=order,
                                         default_scalar_type=numpy.float64,
                                         quad_min_degrees={
                                             "gasdyn_vol": 3 * order,
                                             "gasdyn_face": 3 * order,
                                         })

        discr2 = rcon.make_discretization(mesh_data2,
                                          order=order,
                                          default_scalar_type=numpy.float64,
                                          quad_min_degrees={
                                              "gasdyn_vol": 3 * order,
                                              "gasdyn_face": 3 * order,
                                          })

        from grudge.visualization import SiloVisualizer, VtkVisualizer
        vis = VtkVisualizer(discr, rcon, "vortex-%d" % order)
        #vis = SiloVisualizer(discr, rcon)

        from gas_dynamics_initials import Vortex
        vortex = Vortex()
        fields = vortex.volume_interpolant(0, discr)

        from grudge.models.gas_dynamics import GasDynamicsOperator
        from grudge.mesh import BTAG_ALL

        op = GasDynamicsOperator(dimensions=2,
                                 gamma=vortex.gamma,
                                 mu=vortex.mu,
                                 prandtl=vortex.prandtl,
                                 spec_gas_const=vortex.spec_gas_const,
                                 bc_inflow=vortex,
                                 bc_outflow=vortex,
                                 bc_noslip=vortex,
                                 inflow_tag=BTAG_ALL,
                                 source=None)

        euler_ex = op.bind(discr)

        max_eigval = [0]

        def rhs(t, q):
            ode_rhs, speed = euler_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 for mesh 1 =", len(mesh.elements))
            print("#elements for mesh 2 =", len(mesh2.elements))

        # limiter ------------------------------------------------------------
        from grudge.models.gas_dynamics import SlopeLimiter1NEuler
        limiter = SlopeLimiter1NEuler(discr, vortex.gamma, 2, op)

        from grudge.timestep import SSPRK3TimeStepper
        #stepper = SSPRK3TimeStepper(limiter=limiter)
        stepper = SSPRK3TimeStepper()

        #from grudge.timestep import RK4TimeStepper
        #stepper = RK4TimeStepper()

        # diagnostics setup ---------------------------------------------------
        from logpyle import LogManager, add_general_quantities, \
                add_simulation_quantities, add_run_info

        if write_output:
            log_file_name = "euler-%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)

        logmgr.add_watches(["step.max", "t_sim.max", "t_step.max"])

        # timestep loop -------------------------------------------------------
        try:
            final_time = 0.2
            from grudge.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, max_eigenvalue=max_eigval[0]))

            for step, t, dt in step_it:
                if step % 10 == 0 and write_output:
                    #if False:
                    visf = vis.make_file("vortex-%d-%04d" % (order, step))

                    #true_fields = vortex.volume_interpolant(t, discr)

                    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")),

                            #("true_rho", discr.convert_volume(op.rho(true_fields), kind="numpy")),
                            #("true_e", discr.convert_volume(op.e(true_fields), kind="numpy")),
                            #("true_rho_u", discr.convert_volume(op.rho_u(true_fields), kind="numpy")),
                            #("true_u", discr.convert_volume(op.u(true_fields), kind="numpy")),

                            #("rhs_rho", discr.convert_volume(op.rho(rhs_fields), kind="numpy")),
                            #("rhs_e", discr.convert_volume(op.e(rhs_fields), kind="numpy")),
                            #("rhs_rho_u", discr.convert_volume(op.rho_u(rhs_fields), kind="numpy")),
                        ],
                        #expressions=[
                        #("diff_rho", "rho-true_rho"),
                        #("diff_e", "e-true_e"),
                        #("diff_rho_u", "rho_u-true_rho_u", DB_VARTYPE_VECTOR),

                        #("p", "0.4*(e- 0.5*(rho_u*u))"),
                        #],
                        time=t,
                        step=step)
                    visf.close()

                fields = stepper(fields, t, dt, rhs)
                #fields = limiter(fields)

                #regrid to discr2 at some arbitrary time
                if step == 21:

                    #get interpolated fields
                    fields = discr.get_regrid_values(fields,
                                                     discr2,
                                                     dtype=None,
                                                     use_btree=True,
                                                     thresh=1e-8)
                    #get new stepper (old one has reference to discr
                    stepper = SSPRK3TimeStepper()
                    #new bind
                    euler_ex = op.bind(discr2)
                    #new rhs
                    max_eigval = [0]

                    def rhs(t, q):
                        ode_rhs, speed = euler_ex(t, q)
                        max_eigval[0] = speed
                        return ode_rhs

                    rhs(t + dt, fields)
                    #add logmanager
                    #discr2.add_instrumentation(logmgr)
                    #new step_it
                    step_it = times_and_steps(
                        final_time=final_time,
                        logmgr=logmgr,
                        max_dt_getter=lambda t: op.estimate_timestep(
                            discr2,
                            stepper=stepper,
                            t=t,
                            max_eigenvalue=max_eigval[0]))

                    #new visualization
                    vis.close()
                    vis = VtkVisualizer(discr2, rcon,
                                        "vortexNewGrid-%d" % order)
                    discr = discr2

                assert not numpy.isnan(numpy.sum(fields[0]))

            true_fields = vortex.volume_interpolant(final_time, discr)
            l2_error = discr.norm(fields - true_fields)
            l2_error_rho = discr.norm(op.rho(fields) - op.rho(true_fields))
            l2_error_e = discr.norm(op.e(fields) - op.e(true_fields))
            l2_error_rhou = discr.norm(
                op.rho_u(fields) - op.rho_u(true_fields))
            l2_error_u = discr.norm(op.u(fields) - op.u(true_fields))

            eoc_rec.add_data_point(order, l2_error)
            print()
            print(eoc_rec.pretty_print("P.Deg.", "L2 Error"))

            logmgr.set_constant("l2_error", l2_error)
            logmgr.set_constant("l2_error_rho", l2_error_rho)
            logmgr.set_constant("l2_error_e", l2_error_e)
            logmgr.set_constant("l2_error_rhou", l2_error_rhou)
            logmgr.set_constant("l2_error_u", l2_error_u)
            logmgr.set_constant("refinement", refine)

        finally:
            if write_output:
                vis.close()

            logmgr.close()
            discr.close()
Exemple #12
0
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 grudge.models.em import TEMaxwellOperator

    from grudge.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 list(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 list(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 grudge.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 grudge.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 list(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 grudge.data import make_tdep_given
    from grudge.mesh import BTAG_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=BTAG_ALL)
    # op = TEMaxwellOperator(epsilon=epsilon0, mu=mu0,
    # flux_type=flux_type_arg, \
    # bdry_flux_type=bdry_flux_type_arg, dimensions=2, pec_tag=BTAG_ALL)

    discr = rcon.make_discretization(mesh_data,
                                     order=order,
                                     tune_for=op.sym_operator(),
                                     **extra_discr_args)

    # create the initial solution
    fields = initial_val(discr)

    from grudge.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 grudge.timestep.runge_kutta import LSRK4TimeStepper
    stepper = LSRK4TimeStepper(dtype=discr.default_scalar_type, rcon=rcon)
    #from grudge.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 grudge.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 grudge.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()
Exemple #13
0
def main(write_output=True,
         flux_type_arg="upwind",
         dtype=np.float64,
         debug=[]):
    from math import sin, cos, pi, exp, sqrt  # noqa

    from grudge.backends import guess_run_context
    rcon = guess_run_context()

    if rcon.is_head_rank:
        from grudge.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 grudge.timestep.runge_kutta import LSRK4TimeStepper
    stepper = LSRK4TimeStepper(dtype=dtype)

    from grudge.visualization import VtkVisualizer
    if write_output:
        vis = VtkVisualizer(discr, rcon, "fld")

    source_center = 0
    source_width = 0.05
    source_omega = 3

    import grudge.symbolic as sym
    sym_x = sym.nodes(2)
    sym_source_center_dist = sym_x - source_center

    from grudge.models.wave import StrongWaveOperator
    op = StrongWaveOperator(
        -1,
        discr.dimensions,
        source_f=sym.FunctionSymbol("sin")(
            source_omega * sym.ScalarParameter("t")) *
        sym.FunctionSymbol("exp")(
            -np.dot(sym_source_center_dist, sym_source_center_dist) /
            source_width**2),
        dirichlet_tag="boundary",
        neumann_tag=BTAG_NONE,
        radiation_tag=BTAG_NONE,
        flux_type=flux_type_arg)

    from grudge.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 logpyle 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 grudge.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()