示例#1
0
def test_adaptive_timestep():
    class VanDerPolOscillator:
        def __init__(self, mu=30):
            self.mu = mu
            self.t_start = 0
            self.t_end = 100

        def ic(self):
            return numpy.array([2, 0], dtype=numpy.float64)

        def __call__(self, t, y):
            u1 = y[0]
            u2 = y[1]
            return numpy.array([
                u2, 
                -self.mu*(u1**2-1)*u2-u1],
                dtype=numpy.float64)

    example = VanDerPolOscillator()
    y = example.ic()

    from hedge.timestep.dumka3 import Dumka3TimeStepper
    stepper = Dumka3TimeStepper(3, rtol=1e-6)

    next_dt = 1e-5
    from hedge.timestep import times_and_steps
    times = []
    hist = []
    dts = []
    for step, t, max_dt in times_and_steps(
            max_dt_getter=lambda t: next_dt,
            taken_dt_getter=lambda: taken_dt,
            start_time=example.t_start, final_time=example.t_end):

        #if step % 100 == 0:
            #print t

        hist.append(y)
        times.append(t)
        y, t, taken_dt, next_dt = stepper(y, t, next_dt, example)
        dts.append(taken_dt)

    if False:
        from matplotlib.pyplot import plot, show
        plot(times, [h_entry[1] for h_entry in hist])
        show()
        plot(times, dts)
        show()

    dts = numpy.array(dts)
    small_step_frac = len(numpy.nonzero(dts < 0.01)[0]) / step
    big_step_frac = len(numpy.nonzero(dts > 0.1)[0]) / step
    assert abs(small_step_frac - 0.6) < 0.1
    assert abs(big_step_frac - 0.2) < 0.1
示例#2
0
def test_adaptive_timestep():
    class VanDerPolOscillator:
        def __init__(self, mu=30):
            self.mu = mu
            self.t_start = 0
            self.t_end = 100

        def ic(self):
            return numpy.array([2, 0], dtype=numpy.float64)

        def __call__(self, t, y):
            u1 = y[0]
            u2 = y[1]
            return numpy.array([
                u2, 
                -self.mu*(u1**2-1)*u2-u1],
                dtype=numpy.float64)

    example = VanDerPolOscillator()
    y = example.ic()

    from hedge.timestep.dumka3 import Dumka3TimeStepper
    stepper = Dumka3TimeStepper(3, rtol=1e-6)

    next_dt = 1e-5
    from hedge.timestep import times_and_steps
    times = []
    hist = []
    dts = []
    for step, t, max_dt in times_and_steps(
            max_dt_getter=lambda t: next_dt,
            taken_dt_getter=lambda: taken_dt,
            start_time=example.t_start, final_time=example.t_end):

        #if step % 100 == 0:
            #print t

        hist.append(y)
        times.append(t)
        y, t, taken_dt, next_dt = stepper(y, t, next_dt, example)
        dts.append(taken_dt)

    if False:
        from matplotlib.pyplot import plot, show
        plot(times, [h_entry[1] for h_entry in hist])
        show()
        plot(times, dts)
        show()

    dts = numpy.array(dts)
    small_step_frac = len(numpy.nonzero(dts < 0.01)[0]) / step
    big_step_frac = len(numpy.nonzero(dts > 0.1)[0]) / step
    assert abs(small_step_frac - 0.6) < 0.1
    assert abs(big_step_frac - 0.2) < 0.1
示例#3
0
def main(write_output=True):
    from pytools import add_python_path_relative_to_script
    add_python_path_relative_to_script("..")

    from hedge.backends import guess_run_context
    rcon = guess_run_context()

    from hedge.tools import EOCRecorder
    eoc_rec = EOCRecorder()


    if rcon.is_head_rank:
        from hedge.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 hedge.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 hedge.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 hedge.models.gas_dynamics import GasDynamicsOperator
        from hedge.mesh import TAG_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=TAG_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 hedge.models.gas_dynamics import SlopeLimiter1NEuler
        limiter = SlopeLimiter1NEuler(discr, vortex.gamma, 2, op)

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

        #from hedge.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_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 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, 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()
示例#4
0
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()
示例#5
0
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()
示例#6
0
def main(final_time=1, write_output=False):
    from hedge.backends import guess_run_context
    rcon = guess_run_context()

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

    if rcon.is_head_rank:
        from hedge.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 hedge.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 hedge.mesh import TAG_ALL
        from hedge.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=TAG_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 hedge.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 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, 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")
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()
示例#8
0
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
    from analytic_solutions import (
        check_time_harmonic_solution,
        RealPartAdapter,
        SplitComplexAdapter,
        CylindricalFieldAdapter,
        CylindricalCavityMode,
        RectangularWaveguideMode,
        RectangularCavityMode,
    )
    from hedge.models.em import MaxwellOperator

    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
示例#9
0
def main(write_output=True):
    from hedge.timestep import RK4TimeStepper
    from hedge.mesh import make_disk_mesh
    from math import sqrt, pi, exp

    from hedge.backends import guess_run_context, FEAT_CUDA
    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)

    cylindrical = False
    periodic = False

    pml_width = 0.5
    #mesh = make_mesh(a=numpy.array((-1,-1,-1)), b=numpy.array((1,1,1)), 
    #mesh = make_mesh(a=numpy.array((-3,-3)), b=numpy.array((3,3)), 
    mesh = make_mesh(a=numpy.array((-1,-1)), b=numpy.array((1,1)), 
    #mesh = make_mesh(a=numpy.array((-2,-2)), b=numpy.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=numpy.float64)

            omega = 6*c
            if omega*t > 2*pi:
                return make_obj_array([result, result, result])

            x = make_obj_array(discr.nodes.T)
            r = numpy.sqrt(numpy.dot(x, x))

            idx = r<0.3
            result[idx] = (1+numpy.cos(pi*r/0.3))[idx] \
                    *numpy.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 = RK4TimeStepper()

    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()
示例#10
0
文件: naca.py 项目: gimac/hedge
def main():
    from hedge.backends import guess_run_context

    rcon = guess_run_context()

    if rcon.is_head_rank:
        mesh = make_nacamesh()
        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 [4]:
        from gas_dynamics_initials import UniformMachFlow

        uniform_flow = UniformMachFlow()

        from hedge.models.gas_dynamics import GasDynamicsOperator, GammaLawEOS

        op = GasDynamicsOperator(
            dimensions=2,
            equation_of_state=GammaLawEOS(uniform_flow.gamma),
            prandtl=uniform_flow.prandtl,
            spec_gas_const=uniform_flow.spec_gas_const,
            mu=uniform_flow.mu,
            bc_inflow=uniform_flow,
            bc_outflow=uniform_flow,
            bc_noslip=uniform_flow,
            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_optemplate_stages",
                # "dump_dataflow_graph",
                # "print_op_code"
            ],
            default_scalar_type=numpy.float32,
            tune_for=op.op_template(),
        )

        from hedge.visualization import SiloVisualizer, VtkVisualizer

        # vis = VtkVisualizer(discr, rcon, "shearflow-%d" % order)
        vis = SiloVisualizer(discr, rcon)

        fields = uniform_flow.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)

        from hedge.timestep.runge_kutta import ODE23TimeStepper, LSRK4TimeStepper

        stepper = ODE23TimeStepper(
            dtype=discr.default_scalar_type, rtol=1e-6, vector_primitive_factory=discr.get_vector_primitive_factory()
        )
        # stepper = LSRK4TimeStepper(dtype=discr.default_scalar_type)

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

        logmgr = LogManager("cns-naca-%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)

        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())

        # filter setup-------------------------------------------------------------
        from hedge.discretization import Filter, ExponentialFilterResponseFunction

        mode_filter = Filter(discr, ExponentialFilterResponseFunction(min_amplification=0.9, order=4))
        # timestep loop -------------------------------------------------------

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

        try:
            from hedge.timestep import times_and_steps

            step_it = times_and_steps(
                final_time=200,
                # 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 % 10 == 0:
                    visf = vis.make_file("naca-%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")),
                            # ("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", 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, t, taken_dt, next_dt = stepper(fields, t, dt, rhs)
                fields = mode_filter(fields)

        finally:
            vis.close()
            logmgr.save()
            discr.close()
示例#11
0
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()
示例#12
0
def main(write_output=True, allow_features=None):
    from hedge.timestep import RK4TimeStepper
    from hedge.mesh import make_ball_mesh, make_cylinder_mesh, make_box_mesh
    from hedge.visualization import \
            VtkVisualizer, \
            SiloVisualizer, \
            get_rank_partition
    from math import sqrt, pi

    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

    dims = 3

    if rcon.is_head_rank:
        if dims == 2:
            from hedge.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 hedge.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 hedge.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 hedge.tools import make_obj_array
            return make_obj_array([
                self.vol_0,
                self.vol_0,
                sph_dipole.source_modulation(t)*self.num_sf
                ])

    from hedge.mesh import TAG_ALL, TAG_NONE
    if dims == 2:
        from hedge.models.em import TMMaxwellOperator as MaxwellOperator
    else:
        from hedge.models.em import MaxwellOperator

    op = MaxwellOperator(
            epsilon, mu,
            flux_type=1,
            pec_tag=TAG_NONE,
            absorb_tag=TAG_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 hedge.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 hedge.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 hedge.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 hedge.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()
示例#13
0
    def inner_run(self):
        t = 0

        setup = self.setup
        setup.hook_startup(self)

        vis_order = setup.vis_order
        if vis_order is None:
            vis_order = setup.element_order

        if vis_order != setup.element_order:
            vis_discr = self.rcon.make_discretization(self.discr.mesh,
                                                      order=vis_order,
                                                      debug=setup.dg_debug)

            from hedge.discretization import Projector
            vis_proj = Projector(self.discr, vis_discr)
        else:
            vis_discr = self.discr

            def vis_proj(f):
                return f

        from hedge.visualization import SiloVisualizer
        vis = SiloVisualizer(vis_discr)

        fields = self.fields
        self.observer.set_fields_and_state(fields, self.state)

        from hedge.tools import make_obj_array
        from pyrticle.cloud import TimesteppablePicState

        def visualize(observer):
            sub_timer = self.vis_timer.start_sub_timer()
            import os.path
            visf = vis.make_file(
                os.path.join(setup.output_path, setup.vis_pattern % step))

            self.method.add_to_vis(vis,
                                   visf,
                                   observer.state,
                                   time=t,
                                   step=step)
            vis.add_data(
                visf, [(name, vis_proj(fld))
                       for name, fld in setup.hook_vis_quantities(observer)],
                time=t,
                step=step)
            setup.hook_visualize(self, vis, visf, observer)

            visf.close()
            sub_timer.stop().submit()

        from hedge.timestep.multirate_ab import TwoRateAdamsBashforthTimeStepper
        if not isinstance(self.stepper, TwoRateAdamsBashforthTimeStepper):

            def rhs(t, fields_and_state):
                fields, ts_state = fields_and_state
                state_f = lambda: ts_state.state
                fields_f = lambda: fields

                fields_rhs = (self.f_rhs_calculator(t, fields_f, state_f) +
                              self.p2f_rhs_calculator(t, fields_f, state_f))
                state_rhs = (self.p_rhs_calculator(t, fields_f, state_f) +
                             self.f2p_rhs_calculator(t, fields_f, state_f))

                return make_obj_array([fields_rhs, state_rhs])

            step_args = (self.dt, rhs)
        else:

            def add_unwrap(rhs):
                def unwrapping_rhs(t, fields, ts_state):
                    return rhs(t, fields, lambda: ts_state().state)

                return unwrapping_rhs

            step_args = ((
                add_unwrap(self.f_rhs_calculator),
                add_unwrap(self.p2f_rhs_calculator),
                add_unwrap(self.f2p_rhs_calculator),
                add_unwrap(self.p_rhs_calculator),
            ), )

        y = make_obj_array(
            [fields, TimesteppablePicState(self.method, self.state)])
        del self.state

        try:
            from hedge.timestep import times_and_steps
            step_it = times_and_steps(max_steps=self.nsteps,
                                      logmgr=self.logmgr,
                                      max_dt_getter=lambda t: self.dt)

            for step, t, dt in step_it:
                self.method.upkeep(y[1].state)

                if step % setup.vis_interval == 0:
                    visualize(self.observer)

                y = self.stepper(y, t, *step_args)

                fields, ts_state = y
                self.observer.set_fields_and_state(fields, ts_state.state)

                setup.hook_after_step(self, self.observer)
        finally:
            vis.close()
            self.discr.close()
            self.logmgr.save()

        setup.hook_when_done(self)
示例#14
0
    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 = []

                visf = vis.make_file("fld-%04d" % step)
示例#15
0
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()
示例#16
0
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

    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 import RK4TimeStepper
    stepper = RK4TimeStepper()

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

    def source_u(x, el):
        x = x - numpy.array([0.7, 0.4])
        return exp(-numpy.dot(x, x)*256)

    def c_speed(x, el):
        if la.norm(x) < 0.4:
            return 1
        else:
            return 0.5

    from hedge.models.wave import VariableVelocityStrongWaveOperator
    from hedge.data import \
            TimeIntervalGivenFunction, \
            make_tdep_given
    from hedge.mesh import TAG_ALL, TAG_NONE
    op = VariableVelocityStrongWaveOperator(
            make_tdep_given(c_speed),
            discr.dimensions, 
            source=TimeIntervalGivenFunction(
                make_tdep_given(source_u),
                0, 0.1),
            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 Integral, 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:
        dt = op.estimate_timestep(discr, stepper=stepper, fields=fields)
        if flux_type_arg == "central":
            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: 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:]), 
                            ("c", op.c.volume_interpolant(0, discr)), 
                        ],
                        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()
示例#17
0
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
示例#18
0
def main():
    from hedge.backends import guess_run_context
    rcon = guess_run_context(["cuda"])

    if rcon.is_head_rank:
        mesh = make_boxmesh()
        #from hedge.mesh import make_rect_mesh
        #mesh = make_rect_mesh(
        #       boundary_tagger=lambda fvi, el, fn, all_v: ["inflow"])
        mesh_data = rcon.distribute_mesh(mesh)
    else:
        mesh_data = rcon.receive_mesh()

    for order in [3]:
        from pytools import add_python_path_relative_to_script
        add_python_path_relative_to_script("..")

        from gas_dynamics_initials import UniformMachFlow
        box = UniformMachFlow(angle_of_attack=0)

        from hedge.models.gas_dynamics import GasDynamicsOperator
        op = GasDynamicsOperator(dimensions=3,
                                 gamma=box.gamma,
                                 mu=box.mu,
                                 prandtl=box.prandtl,
                                 spec_gas_const=box.spec_gas_const,
                                 bc_inflow=box,
                                 bc_outflow=box,
                                 bc_noslip=box,
                                 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",
                #"print_op_code",
                "cuda_no_plan_el_local",
            ],
            default_scalar_type=numpy.float32,
            tune_for=op.op_template())

        from hedge.visualization import SiloVisualizer, VtkVisualizer  # noqa
        #vis = VtkVisualizer(discr, rcon, "shearflow-%d" % order)
        vis = SiloVisualizer(discr, rcon)

        fields = box.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)

        from hedge.timestep import RK4TimeStepper
        stepper = RK4TimeStepper()

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

        logmgr = LogManager("navierstokes-%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"])

        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())

        # timestep loop -------------------------------------------------------
        try:
            from hedge.timestep import times_and_steps
            step_it = times_and_steps(
                final_time=200,
                #max_steps=500,
                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 % 200 == 0:
                    #if False:
                    visf = vis.make_file("box-%d-%06d" % (order, step))

                    #rhs_fields = rhs(t, fields)

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

                            # ("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=[
                            ("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.save()
            discr.close()
示例#19
0
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()
示例#20
0
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()
示例#21
0
def main(write_output=True):
    from math import sqrt, pi, exp
    from os.path import join

    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

    output_dir = "maxwell-2d"
    import os
    if not os.access(output_dir, os.F_OK):
        os.makedirs(output_dir)
    
    from hedge.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 hedge.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 hedge.mesh import TAG_ALL, TAG_NONE
    from hedge.models.em import TMMaxwellOperator
    from hedge.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=TAG_ALL, pec_tag=TAG_NONE)
    fields = op.assemble_eh(discr=discr)

    from hedge.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 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)

    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 % 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()
示例#22
0
def main(final_time=1, write_output=False):
    from hedge.backends import guess_run_context
    rcon = guess_run_context()

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

    if rcon.is_head_rank:
        from hedge.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 hedge.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 hedge.mesh import TAG_ALL
        from hedge.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=TAG_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 hedge.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 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, 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")
示例#23
0
def main(write_output=True, order=6):
    from hedge.data import TimeConstantGivenFunction, \
            GivenFunction
    from os.path import join
    from hedge.backends import guess_run_context
    rcon = guess_run_context()

    dim = 3
    output_dir = "octahedron"
    
    import os
    if not os.access(output_dir, os.F_OK):
        os.makedirs(output_dir)

    if rcon.is_head_rank:
        from hedge.mesh.reader.gmsh import read_gmsh
        mesh = read_gmsh("octahedron.msh", 
                boundary_tagger=lambda x,y,z,w: ["traction"])

    if rcon.is_head_rank:
        print "%d elements" % len(mesh.elements)
        mesh_data = rcon.distribute_mesh(mesh)
    else:
        mesh_data = rcon.receive_mesh()

    class Displacement:
        shape = (3,)
        def __call__(self, x, el):
            R = x[0] + x[1] + x[2]
            return [-R/30, -R/30, -R/30]
    
    final_time = 3
    
    discr = rcon.make_discretization(mesh_data, order=order, 
            debug=[])

    from hedge.visualization import VtkVisualizer
    if write_output:
        vis = VtkVisualizer(discr, rcon, join(output_dir, "test-%d" % order))
        
    if rcon.is_head_rank:
        print "order %d" % order
        print "#elements=", len(mesh.elements)
 
    from hedge.mesh import TAG_NONE, TAG_ALL
    from hedge.models.solid_mechanics import SolidMechanicsOperator
    from hedge.models.solid_mechanics.constitutive_laws import NeoHookean
    
    material = NeoHookean(50, 10, 0.3)
    
    op = SolidMechanicsOperator(material, 
            init_displacement=GivenFunction(Displacement()),
            dimensions=discr.dimensions)
    fields = op.assemble_vars(discr=discr)
    
    from hedge.timestep import LSRK4TimeStepper
    stepper = LSRK4TimeStepper()
    from time import time
    last_tsep = 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, "oct-%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)
    logmgr.add_watches(["step.max", "t_sim.max", "t_step.max"])
    
    p_calc = op.bind_stress_calculator(discr)
    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=fields))

        for step, t, dt in step_it:
            u, v = op.split_vars(fields)
            P    = p_calc(u)
            if step % 5 == 0 and write_output:
                visf = vis.make_file(join(output_dir, "oct-%d-%04d" % (order, step)))
                vis.add_data(visf,
                    [
                        ("u", discr.convert_volume(u, "numpy")),
                        ("v", discr.convert_volume(v, "numpy")),
                        ("P", discr.convert_volume(P, "numpy"))
                        ],
                    time=t, step=step
                    )
                visf.close()
            
            fields = stepper(fields, t, dt, rhs)
    finally:
        if write_output:
            vis.close()
        logmgr.close()
        discr.close()
示例#24
0
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()
示例#25
0
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()
示例#26
0
文件: driver.py 项目: gimac/pyrticle
    def inner_run(self): 
        t = 0
        
        setup = self.setup
        setup.hook_startup(self)

        vis_order = setup.vis_order
        if vis_order is None:
            vis_order = setup.element_order

        if vis_order != setup.element_order:
            vis_discr = self.rcon.make_discretization(self.discr.mesh, 
                            order=vis_order, debug=setup.dg_debug)

            from hedge.discretization import Projector
            vis_proj = Projector(self.discr, vis_discr)
        else:
            vis_discr = self.discr

            def vis_proj(f):
                return f

        from hedge.visualization import SiloVisualizer
        vis = SiloVisualizer(vis_discr)

        fields = self.fields
        self.observer.set_fields_and_state(fields, self.state)

        from hedge.tools import make_obj_array
        from pyrticle.cloud import TimesteppablePicState

        def visualize(observer):
            sub_timer = self.vis_timer.start_sub_timer()
            import os.path
            visf = vis.make_file(os.path.join(
                setup.output_path, setup.vis_pattern % step))

            self.method.add_to_vis(vis, visf, observer.state, time=t, step=step)
            vis.add_data(visf, 
                    [(name, vis_proj(fld))
                        for name, fld in setup.hook_vis_quantities(observer)],
                    time=t, step=step)
            setup.hook_visualize(self, vis, visf, observer)

            visf.close()
            sub_timer.stop().submit()

        from hedge.timestep.multirate_ab import TwoRateAdamsBashforthTimeStepper 
        if not isinstance(self.stepper, TwoRateAdamsBashforthTimeStepper): 
            def rhs(t, fields_and_state):
                fields, ts_state = fields_and_state
                state_f = lambda: ts_state.state
                fields_f = lambda: fields

                fields_rhs = (
                        self.f_rhs_calculator(t, fields_f, state_f)
                        + self.p2f_rhs_calculator(t, fields_f, state_f))
                state_rhs = (
                        self.p_rhs_calculator(t, fields_f, state_f)
                        + self.f2p_rhs_calculator(t, fields_f, state_f))

                return make_obj_array([fields_rhs, state_rhs])
            step_args = (self.dt, rhs)
        else:
            def add_unwrap(rhs):
                def unwrapping_rhs(t, fields, ts_state):
                    return rhs(t, fields, lambda: ts_state().state)
                return unwrapping_rhs

            step_args = ((
                    add_unwrap(self.f_rhs_calculator),
                    add_unwrap(self.p2f_rhs_calculator),
                    add_unwrap(self.f2p_rhs_calculator),
                    add_unwrap(self.p_rhs_calculator),
                    ),)

        y = make_obj_array([
            fields, 
            TimesteppablePicState(self.method, self.state)
            ])
        del self.state

        try:
            from hedge.timestep import times_and_steps
            step_it = times_and_steps(
                    max_steps=self.nsteps,
                    logmgr=self.logmgr,
                    max_dt_getter=lambda t: self.dt)

            for step, t, dt in step_it:
                self.method.upkeep(y[1].state)

                if step % setup.vis_interval == 0:
                    visualize(self.observer)

                y = self.stepper(y, t, *step_args)

                fields, ts_state = y
                self.observer.set_fields_and_state(fields, ts_state.state)

                setup.hook_after_step(self, self.observer)
        finally:
            vis.close()
            self.discr.close()
            self.logmgr.save()

        setup.hook_when_done(self)
示例#27
0
文件: sod-2d.py 项目: gimac/hedge
def main():
    from hedge.backends import guess_run_context

    rcon = guess_run_context()

    from hedge.tools import to_obj_array

    if rcon.is_head_rank:
        from hedge.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 hedge.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 hedge.models.gas_dynamics import GasDynamicsOperator
        from hedge.mesh import TAG_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=TAG_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 hedge.models.gas_dynamics import SlopeLimiter1NEuler

        limiter = SlopeLimiter1NEuler(discr, sod_field.gamma, 2, op)

        # integrator setup---------------------------------------------------------
        from hedge.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 hedge.discretization import Filter, ExponentialFilterResponseFunction

        mode_filter = Filter(discr, ExponentialFilterResponseFunction(min_amplification=0.9, order=4))

        # timestep loop -------------------------------------------------------
        try:
            from hedge.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)
示例#28
0
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()
示例#29
0
def run_convergence_test_advec(dtype, debug_output=False):
    """Test whether 2/3D advection actually converges"""

    from hedge.mesh.generator import make_ball_mesh, make_box_mesh, make_rect_mesh
    from hedge.timestep import RK4TimeStepper
    from hedge.tools import EOCRecorder
    from math import sin, pi, sqrt
    from hedge.models.advection import StrongAdvectionOperator
    from hedge.data import TimeDependentGivenFunction
    from hedge.visualization import SiloVisualizer

    from hedge.backends import guess_run_context
    rcon = guess_run_context(["mpi"])

    # note: x component must remain zero because x-periodicity is used
    v = numpy.array([0.0,0.9,0.3])

    def f(x):
        return sin(x)

    def u_analytic(x, el, t):
        return f((numpy.dot(-v[:dims],x)/la.norm(v[:dims])+t*la.norm(v[:dims])))

    def boundary_tagger(vertices, el, face_nr, points):
        face_normal = el.face_normals[face_nr]
        if numpy.dot(face_normal, v[:len(face_normal)]) < 0:
            return ["inflow"]
        else:
            return ["outflow"]

    for i_mesh, mesh in enumerate([
        # 2D semiperiodic
        make_rect_mesh(b=(2*pi,3), max_area=0.4,
            periodicity=(True, False),
            subdivisions=(5,10),
            boundary_tagger=boundary_tagger, 
            ),
        # 3D x-periodic
        make_box_mesh((0,0,0), (2*pi, 2, 2), max_volume=0.4,
            periodicity=(True, False, False),
            boundary_tagger=boundary_tagger, 
            ),
        # non-periodic
        make_ball_mesh(r=pi, 
            boundary_tagger=boundary_tagger, max_volume=0.7),
        ]):
        for flux_type in StrongAdvectionOperator.flux_types:
            for random_partition in [True, False]:
                eoc_rec = EOCRecorder()

                if random_partition:
                    # Distribute elements randomly across nodes.
                    # This is bad, efficiency-wise, but it puts stress
                    # on the parallel implementation, which is desired here.
                    # Another main point of this is to force the code to split
                    # a periodic face pair across nodes.
                    from random import choice
                    partition = [choice(rcon.ranks) for el in mesh.elements]
                else:
                    partition = None

                for order in [1,2,3,4]:
                    if rcon.is_head_rank:
                        mesh_data = rcon.distribute_mesh(mesh, partition)
                    else:
                        mesh_data = rcon.receive_mesh()

                    dims = mesh.points.shape[1]

                    discr = rcon.make_discretization(mesh_data, order=order,
                            default_scalar_type=dtype)

                    op = StrongAdvectionOperator(v[:dims], 
                            inflow_u=TimeDependentGivenFunction(u_analytic),
                            flux_type=flux_type)
                    if debug_output:
                        vis = SiloVisualizer(discr, rcon)

                    u = discr.interpolate_volume_function(
                            lambda x, el: u_analytic(x, el, 0))
                    ic = u.copy()

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

                    test_name = "test-%s-o%d-m%d-r%s" % (
                            flux_type, order, i_mesh, random_partition)

                    rhs = op.bind(discr)

                    stepper = RK4TimeStepper(dtype=dtype)
                    from hedge.timestep import times_and_steps
                    final_time = 1
                    step_it = times_and_steps(
                            final_time=final_time,
                            max_dt_getter=lambda t: op.estimate_timestep(discr,
                                stepper=stepper, t=t, fields=u))

                    for step, t, dt in step_it:
                        u = stepper(u, t, dt, rhs)

                    assert u.dtype == dtype

                    u_true = discr.interpolate_volume_function(
                            lambda x, el: u_analytic(x, el, final_time))
                    error = u-u_true
                    l2_error = discr.norm(error)

                    if debug_output:
                        visf = vis.make_file(test_name+"-final")
                        vis.add_data(visf, [
                            ("u", u),
                            ("u_true", u_true),
                            ("ic", ic)])
                        visf.close()

                    eoc_rec.add_data_point(order, l2_error)

                if debug_output and rcon.is_head_rank:
                    print "%s\n%s\n" % (flux_type.upper(), "-" * len(flux_type))
                    print eoc_rec.pretty_print(abscissa_label="Poly. Order", 
                            error_label="L2 Error")

                assert eoc_rec.estimate_order_of_convergence()[0,1] > 3
                assert eoc_rec.estimate_order_of_convergence(2)[-1,1] > 7
示例#30
0
def main():
    from hedge.backends import guess_run_context
    rcon = guess_run_context(["cuda"])

    if rcon.is_head_rank:
        mesh = make_boxmesh()
        #from hedge.mesh import make_rect_mesh
        #mesh = make_rect_mesh(
        #       boundary_tagger=lambda fvi, el, fn, all_v: ["inflow"])
        mesh_data = rcon.distribute_mesh(mesh)
    else:
        mesh_data = rcon.receive_mesh()

    for order in [3]:
        from pytools import add_python_path_relative_to_script
        add_python_path_relative_to_script("..")

        from gas_dynamics_initials import UniformMachFlow
        box = UniformMachFlow(angle_of_attack=0)

        from hedge.models.gas_dynamics import GasDynamicsOperator
        op = GasDynamicsOperator(dimensions=3,
                gamma=box.gamma, mu=box.mu,
                prandtl=box.prandtl, spec_gas_const=box.spec_gas_const,
                bc_inflow=box, bc_outflow=box, bc_noslip=box,
                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",
                            #"print_op_code",
                            "cuda_no_plan_el_local",
                            ],
                        default_scalar_type=numpy.float32,
                        tune_for=op.op_template())

        from hedge.visualization import SiloVisualizer, VtkVisualizer  # noqa
        #vis = VtkVisualizer(discr, rcon, "shearflow-%d" % order)
        vis = SiloVisualizer(discr, rcon)

        fields = box.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)

        from hedge.timestep import RK4TimeStepper
        stepper = RK4TimeStepper()

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

        logmgr = LogManager("navierstokes-%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"])

        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())

        # timestep loop -------------------------------------------------------
        try:
            from hedge.timestep import times_and_steps
            step_it = times_and_steps(
                    final_time=200,
                    #max_steps=500,
                    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 % 200 == 0:
                #if False:
                    visf = vis.make_file("box-%d-%06d" % (order, step))

                    #rhs_fields = rhs(t, fields)

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

                                # ("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=[
                                ("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.save()
            discr.close()
示例#31
0
def main():
    from hedge.backends import guess_run_context
    rcon = guess_run_context()

    from hedge.tools import to_obj_array

    if rcon.is_head_rank:
        from hedge.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 hedge.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 hedge.models.gas_dynamics import GasDynamicsOperator
        from hedge.mesh import TAG_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=TAG_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 hedge.models.gas_dynamics import SlopeLimiter1NEuler
        limiter = SlopeLimiter1NEuler(discr, sod_field.gamma, 2, op)

        # integrator setup---------------------------------------------------------
        from hedge.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 hedge.discretization import Filter, ExponentialFilterResponseFunction
        mode_filter = Filter(
            discr,
            ExponentialFilterResponseFunction(min_amplification=0.9, order=4))

        # timestep loop -------------------------------------------------------
        try:
            from hedge.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)
示例#32
0
def main(write_output=True):
    from pytools import add_python_path_relative_to_script
    add_python_path_relative_to_script("..")

    from hedge.backends import guess_run_context
    rcon = guess_run_context()

    from hedge.tools import EOCRecorder
    eoc_rec = EOCRecorder()

    if rcon.is_head_rank:
        from hedge.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 hedge.models.gas_dynamics import (GasDynamicsOperator,
                                               PolytropeEOS, GammaLawEOS)

        from hedge.mesh import TAG_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=TAG_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.op_template(),
                                         debug=["cuda_no_plan"])

        from hedge.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 hedge.models.gas_dynamics import SlopeLimiter1NEuler
        limiter = SlopeLimiter1NEuler(discr, flow.gamma, 2, op)

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

        #from hedge.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_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 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, 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
示例#33
0
def main():
    from hedge.backends import guess_run_context
    rcon = guess_run_context( ["cuda", "mpi"])

    if rcon.is_head_rank:
        mesh = make_wingmesh()
        #from hedge.mesh import make_rect_mesh
        #mesh = make_rect_mesh(
        #       boundary_tagger=lambda fvi, el, fn, all_v: ["inflow"])
        mesh_data = rcon.distribute_mesh(mesh)
    else:
        mesh_data = rcon.receive_mesh()

    for order in [3]:
        from pytools import add_python_path_relative_to_script
        add_python_path_relative_to_script("..")

        from gas_dynamics_initials import UniformMachFlow
        wing = UniformMachFlow(angle_of_attack=0)

        from hedge.models.gas_dynamics import GasDynamicsOperator
        op = GasDynamicsOperator(dimensions=3,
                gamma=wing.gamma, mu=wing.mu,
                prandtl=wing.prandtl, spec_gas_const=wing.spec_gas_const,
                bc_inflow=wing, bc_outflow=wing, bc_noslip=wing,
                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",
                            #"print_op_code"
                            "cuda_no_metis",
                            ],
                        default_scalar_type=numpy.float64,
                        tune_for=op.op_template())

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

        fields = wing.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)

        from hedge.timestep import RK4TimeStepper
        stepper = RK4TimeStepper()

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

        logmgr = LogManager("navierstokes-%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"])

        # timestep loop -------------------------------------------------------
        try:
            from hedge.timestep import times_and_steps
            step_it = times_and_steps(
                    final_time=200,
                    #max_steps=500,
                    logmgr=logmgr,
                    max_dt_getter=lambda t: 0.6 * op.estimate_timestep(discr,
                        stepper=stepper, t=t, max_eigenvalue=max_eigval[0]))

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

                    #rhs_fields = rhs(t, fields)

                    from pyvisfile.silo import DB_VARTYPE_VECTOR
                    from hedge.discretization import ones_on_boundary
                    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")),

                                #("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=[
                                ("p", "(0.4)*(e- 0.5*(rho_u*u))"),
                                ],
                            time=t, step=step
                            )
                    visf.close()

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

        finally:
            vis.close()
            logmgr.save()
            discr.close()
示例#34
0
def main():
    from hedge.backends import guess_run_context
    rcon = guess_run_context(["cuda", "mpi"])

    if rcon.is_head_rank:
        mesh = make_wingmesh()
        #from hedge.mesh import make_rect_mesh
        #mesh = make_rect_mesh(
        #       boundary_tagger=lambda fvi, el, fn, all_v: ["inflow"])
        mesh_data = rcon.distribute_mesh(mesh)
    else:
        mesh_data = rcon.receive_mesh()

    for order in [3]:
        from pytools import add_python_path_relative_to_script
        add_python_path_relative_to_script("..")

        from gas_dynamics_initials import UniformMachFlow
        wing = UniformMachFlow(angle_of_attack=0)

        from hedge.models.gas_dynamics import GasDynamicsOperator
        op = GasDynamicsOperator(dimensions=3,
                                 gamma=wing.gamma,
                                 mu=wing.mu,
                                 prandtl=wing.prandtl,
                                 spec_gas_const=wing.spec_gas_const,
                                 bc_inflow=wing,
                                 bc_outflow=wing,
                                 bc_noslip=wing,
                                 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",
                #"print_op_code"
                "cuda_no_metis",
            ],
            default_scalar_type=numpy.float64,
            tune_for=op.op_template())

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

        fields = wing.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)

        from hedge.timestep import RK4TimeStepper
        stepper = RK4TimeStepper()

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

        logmgr = LogManager("navierstokes-%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"])

        # timestep loop -------------------------------------------------------
        try:
            from hedge.timestep import times_and_steps
            step_it = times_and_steps(
                final_time=200,
                #max_steps=500,
                logmgr=logmgr,
                max_dt_getter=lambda t: 0.6 * op.estimate_timestep(
                    discr, stepper=stepper, t=t, max_eigenvalue=max_eigval[0]))

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

                    #rhs_fields = rhs(t, fields)

                    from pyvisfile.silo import DB_VARTYPE_VECTOR
                    from hedge.discretization import ones_on_boundary
                    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")),

                            #("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=[
                            ("p", "(0.4)*(e- 0.5*(rho_u*u))"),
                        ],
                        time=t,
                        step=step)
                    visf.close()

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

        finally:
            vis.close()
            logmgr.save()
            discr.close()
示例#35
0
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()
示例#36
0
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()
示例#37
0
def main(write_output=True):
    from math import sqrt, pi, exp
    from os.path import join

    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

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

    from hedge.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 hedge.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 hedge.mesh import TAG_ALL, TAG_NONE
    from hedge.models.em import TMMaxwellOperator
    from hedge.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=TAG_ALL,
                           pec_tag=TAG_NONE)
    fields = op.assemble_eh(discr=discr)

    from hedge.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 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)

    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 % 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()
示例#38
0
def main(write_output=True, flux_type_arg="upwind", 
        #case = CenteredStationaryTestCase(),
        #case = OffCenterStationaryTestCase(),
        #case = OffCenterMigratingTestCase(),
        case = ExactTestCase(),
        ):
    from hedge.backends import guess_run_context
    rcon = guess_run_context()

    order = 3
    if rcon.is_head_rank:
        if True:
            from hedge.mesh.generator import make_uniform_1d_mesh
            mesh = make_uniform_1d_mesh(case.a, case.b, 20, periodic=True)
        else:
            from hedge.mesh.generator import make_rect_mesh
            print (pi*2)/(11*5*2)
            mesh = make_rect_mesh((-pi, -1), (pi, 1),
                    periodicity=(True, True),
                    subdivisions=(11,5),
                    max_area=(pi*2)/(11*5*2)
                    )

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

    discr = rcon.make_discretization(mesh_data, order=order,
            quad_min_degrees={"quad": 3*order})

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

    # operator setup ----------------------------------------------------------
    from hedge.second_order import IPDGSecondDerivative

    from hedge.models.burgers import BurgersOperator
    op = BurgersOperator(mesh.dimensions,
            viscosity_scheme=IPDGSecondDerivative())

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

    # exact solution ----------------------------------------------------------
    import pymbolic
    var = pymbolic.var

    u = discr.interpolate_volume_function(lambda x, el: case.u0(x[0]))

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

    if write_output:
        log_file_name = "burgers.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, p=1, name="l1_u"))

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

    # timestep loop -----------------------------------------------------------
    rhs = op.bind(discr)

    from hedge.timestep.runge_kutta import ODE45TimeStepper, LSRK4TimeStepper
    stepper = ODE45TimeStepper()

    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 = []

                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()
示例#39
0
def main():
    from hedge.backends import guess_run_context
    rcon = guess_run_context(
        #["cuda"]
    )

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

    def boundary_tagger(vertices, el, face_nr, all_v):
        return ["inflow"]

    if rcon.is_head_rank:
        from hedge.mesh import make_rect_mesh, \
                               make_centered_regular_rect_mesh
        #mesh = make_rect_mesh((0,0), (10,1), max_area=0.01)
        refine = 1
        mesh = make_centered_regular_rect_mesh(
            (0, 0),
            (10, 1),
            n=(20, 4),
            #periodicity=(True, False),
            post_refine_factor=refine,
            boundary_tagger=boundary_tagger)
        mesh_data = rcon.distribute_mesh(mesh)
    else:
        mesh_data = rcon.receive_mesh()

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

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

        shearflow = SteadyShearFlow()
        fields = shearflow.volume_interpolant(0, discr)
        gamma, mu, prandtl, spec_gas_const = shearflow.properties()

        from hedge.models.gas_dynamics import GasDynamicsOperator
        op = GasDynamicsOperator(dimensions=2,
                                 gamma=gamma,
                                 mu=mu,
                                 prandtl=prandtl,
                                 spec_gas_const=spec_gas_const,
                                 bc_inflow=shearflow,
                                 bc_outflow=shearflow,
                                 bc_noslip=shearflow,
                                 inflow_tag="inflow",
                                 outflow_tag="outflow",
                                 noslip_tag="noslip")

        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

        # needed to get first estimate of maximum eigenvalue
        rhs(0, fields)

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

        from hedge.timestep import RK4TimeStepper
        stepper = RK4TimeStepper()

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

        logmgr = LogManager("navierstokes-cpu-%d-%d.dat" % (order, refine),
                            "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 hedge.timestep import times_and_steps
            step_it = times_and_steps(
                final_time=0.3,
                #max_steps=500,
                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 False:
                    visf = vis.make_file("shearflow-%d-%04d" % (order, step))

                    #true_fields = shearflow.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")),
                        ],
                        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)

            true_fields = shearflow.volume_interpolant(t, discr)
            l2_error = 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)

        finally:
            vis.close()
            logmgr.save()
            discr.close()
示例#40
0
文件: wiggly.py 项目: felipeh/hedge
def main(write_output=True, 
        flux_type_arg="upwind", dtype=numpy.float64, debug=[]):
    from pytools.stopwatch import Job
    from math import sin, cos, pi, exp, sqrt

    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)

        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 import RK4TimeStepper
    stepper = RK4TimeStepper(dtype=dtype)

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

    def source_u(x, el):
        return exp(-numpy.dot(x, x)*128)

    from hedge.models.wave import StrongWaveOperator
    from hedge.mesh import TAG_ALL, TAG_NONE
    from hedge.data import \
            make_tdep_given, \
            TimeHarmonicGivenFunction, \
            TimeIntervalGivenFunction

    op = StrongWaveOperator(-1, discr.dimensions, 
            source_f=TimeIntervalGivenFunction(
                TimeHarmonicGivenFunction(
                    make_tdep_given(source_u), omega=10),
                0, 1),
            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()
示例#41
0
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()
示例#42
0
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()
示例#43
0
def run_convergence_test_advec(dtype,
                               flux_type,
                               random_partition,
                               mesh_gen,
                               debug_output=False):
    """Test whether 2/3D advection actually converges"""

    from hedge.timestep import RK4TimeStepper
    from hedge.tools import EOCRecorder
    from math import sin
    from hedge.data import TimeDependentGivenFunction
    from hedge.visualization import SiloVisualizer

    from hedge.backends import guess_run_context
    rcon = guess_run_context(["mpi"])

    # note: x component must remain zero because x-periodicity is used
    v = np.array([0.0, 0.9, 0.3])

    def f(x):
        return sin(x)

    def u_analytic(x, el, t):
        return f(
            (np.dot(-v[:dims], x) / la.norm(v[:dims]) + t * la.norm(v[:dims])))

    def boundary_tagger(vertices, el, face_nr, points):
        face_normal = el.face_normals[face_nr]
        if np.dot(face_normal, v[:len(face_normal)]) < 0:
            return ["inflow"]
        else:
            return ["outflow"]

    mesh = mesh_gen(boundary_tagger)
    eoc_rec = EOCRecorder()

    if random_partition:
        # Distribute elements randomly across nodes.
        # This is bad, efficiency-wise, but it puts stress
        # on the parallel implementation, which is desired here.
        # Another main point of this is to force the code to split
        # a periodic face pair across nodes.
        from random import choice
        partition = [choice(rcon.ranks) for el in mesh.elements]
    else:
        partition = None

    for order in [1, 2, 3, 4]:
        if rcon.is_head_rank:
            mesh_data = rcon.distribute_mesh(mesh, partition)
        else:
            mesh_data = rcon.receive_mesh()

        dims = mesh.points.shape[1]

        discr = rcon.make_discretization(mesh_data,
                                         order=order,
                                         default_scalar_type=dtype)

        op = StrongAdvectionOperator(
            v[:dims],
            inflow_u=TimeDependentGivenFunction(u_analytic),
            flux_type=flux_type)
        if debug_output:
            vis = SiloVisualizer(discr, rcon)

        u = discr.interpolate_volume_function(
            lambda x, el: u_analytic(x, el, 0))
        ic = u.copy()

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

        test_name = "test-%s-o%d-m%s-r%s" % (
            flux_type, order, mesh_gen.__name__, random_partition)

        rhs = op.bind(discr)

        stepper = RK4TimeStepper(dtype=dtype)
        from hedge.timestep import times_and_steps
        final_time = 1
        step_it = times_and_steps(final_time=final_time,
                                  max_dt_getter=lambda t: op.estimate_timestep(
                                      discr, stepper=stepper, t=t, fields=u))

        for step, t, dt in step_it:
            u = stepper(u, t, dt, rhs)

        assert u.dtype == dtype

        u_true = discr.interpolate_volume_function(
            lambda x, el: u_analytic(x, el, final_time))
        error = u - u_true
        l2_error = discr.norm(error)

        if debug_output:
            visf = vis.make_file(test_name + "-final")
            vis.add_data(visf, [("u", u), ("u_true", u_true), ("ic", ic)])
            visf.close()

        eoc_rec.add_data_point(order, l2_error)

    if debug_output and rcon.is_head_rank:
        print "%s\n%s\n" % (flux_type.upper(), "-" * len(flux_type))
        print eoc_rec.pretty_print(abscissa_label="Poly. Order",
                                   error_label="L2 Error")

    assert eoc_rec.estimate_order_of_convergence()[0, 1] > 3
    assert eoc_rec.estimate_order_of_convergence(2)[-1, 1] > 7
示例#44
0
def main():
    from hedge.backends import guess_run_context
    rcon = guess_run_context(
    #["cuda"]
    )

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

    def boundary_tagger(vertices, el, face_nr, all_v):
        return ["inflow"]

    if rcon.is_head_rank:
        from hedge.mesh import make_rect_mesh, \
                               make_centered_regular_rect_mesh
        #mesh = make_rect_mesh((0,0), (10,1), max_area=0.01)
        refine = 1
        mesh = make_centered_regular_rect_mesh((0,0), (10,1), n=(20,4),
                            #periodicity=(True, False),
                            post_refine_factor=refine,
                            boundary_tagger=boundary_tagger)
        mesh_data = rcon.distribute_mesh(mesh)
    else:
        mesh_data = rcon.receive_mesh()

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

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

        shearflow = SteadyShearFlow()
        fields = shearflow.volume_interpolant(0, discr)
        gamma, mu, prandtl, spec_gas_const = shearflow.properties()

        from hedge.models.gas_dynamics import GasDynamicsOperator
        op = GasDynamicsOperator(dimensions=2, gamma=gamma, mu=mu,
                prandtl=prandtl, spec_gas_const=spec_gas_const,
                bc_inflow=shearflow, bc_outflow=shearflow, bc_noslip=shearflow,
                inflow_tag="inflow", outflow_tag="outflow", noslip_tag="noslip")

        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

        # needed to get first estimate of maximum eigenvalue
        rhs(0, fields)

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

        from hedge.timestep import RK4TimeStepper
        stepper = RK4TimeStepper()

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

        logmgr = LogManager("navierstokes-cpu-%d-%d.dat" % (order, refine),
                            "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 hedge.timestep import times_and_steps
            step_it = times_and_steps(
                    final_time=0.3,
                    #max_steps=500,
                    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 False:
                    visf = vis.make_file("shearflow-%d-%04d" % (order, step))

                    #true_fields = shearflow.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")),
                                ],
                            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)

            true_fields = shearflow.volume_interpolant(t, discr)
            l2_error = 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)

        finally:
            vis.close()
            logmgr.save()
            discr.close()
示例#45
0
def main(write_output=True):
    from pytools import add_python_path_relative_to_script
    add_python_path_relative_to_script("..")

    from hedge.backends import guess_run_context
    rcon = guess_run_context()

    from hedge.tools import EOCRecorder
    eoc_rec = EOCRecorder()

    if rcon.is_head_rank:
        from hedge.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 hedge.models.gas_dynamics import (
                GasDynamicsOperator, PolytropeEOS, GammaLawEOS)

        from hedge.mesh import TAG_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=TAG_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.op_template(),
                        debug=["cuda_no_plan"])

        from hedge.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 hedge.models.gas_dynamics import SlopeLimiter1NEuler
        limiter = SlopeLimiter1NEuler(discr, flow.gamma, 2, op)

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

        #from hedge.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_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 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, 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
示例#46
0
def main(write_output=True, allow_features=None):
    from hedge.timestep import RK4TimeStepper
    from hedge.mesh import make_ball_mesh, make_cylinder_mesh, make_box_mesh
    from hedge.visualization import \
            VtkVisualizer, \
            SiloVisualizer, \
            get_rank_partition
    from math import sqrt, pi

    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

    dims = 3

    if rcon.is_head_rank:
        if dims == 2:
            from hedge.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 hedge.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 hedge.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 hedge.tools import make_obj_array
            return make_obj_array([
                self.vol_0, self.vol_0,
                sph_dipole.source_modulation(t) * self.num_sf
            ])

    from hedge.mesh import TAG_ALL, TAG_NONE
    if dims == 2:
        from hedge.models.em import TMMaxwellOperator as MaxwellOperator
    else:
        from hedge.models.em import MaxwellOperator

    op = MaxwellOperator(
        epsilon,
        mu,
        flux_type=1,
        pec_tag=TAG_NONE,
        absorb_tag=TAG_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 hedge.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 hedge.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 hedge.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 hedge.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()
示例#47
0
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()
示例#48
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 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()
示例#49
0
def main(write_output=True):
    from hedge.backends import guess_run_context
    rcon = guess_run_context(
                    #["cuda"]
                    )

    gamma = 1.4

    # at A=1 we have case of isentropic vortex, source terms 
    # arise for other values
    densityA = 2.0

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

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

        refine = 1
        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 [4,5]:
        discr = rcon.make_discretization(mesh_data, order=order,
                        debug=[#"cuda_no_plan",
                        #"print_op_code"
                        ],
                        default_scalar_type=numpy.float64)

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

        vortex = Vortex(beta=5, gamma=gamma,
                center=[5,0],
                velocity=[1,0], densityA=densityA)
        fields = vortex.volume_interpolant(0, discr)
        sources=SourceTerms(beta=5, gamma=gamma,
                center=[5,0],
                velocity=[1,0], densityA=densityA)

        from hedge.models.gas_dynamics import (
                GasDynamicsOperator, GammaLawEOS)
        from hedge.mesh import TAG_ALL

        op = GasDynamicsOperator(dimensions=2,
                mu=0.0, prandtl=0.72, spec_gas_const=287.1, 
                equation_of_state=GammaLawEOS(vortex.gamma),
                bc_inflow=vortex, bc_outflow=vortex, bc_noslip=vortex,
                inflow_tag=TAG_ALL, source=sources)

        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 hedge.models.gas_dynamics import SlopeLimiter1NEuler
        limiter = SlopeLimiter1NEuler(discr, gamma, 2, op)

        # time stepper --------------------------------------------------------
        from hedge.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

        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 -------------------------------------------------------
        t = 0

        #fields = limiter(fields)

        try:
            from hedge.timestep import times_and_steps
            step_it = times_and_steps(
                    final_time=.1,
                    #max_steps=500,
                    logmgr=logmgr,
                    max_dt_getter=lambda t: 0.4*op.estimate_timestep(discr,
                        stepper=stepper, t=t, max_eigenvalue=max_eigval[0]))

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

                    true_fields = vortex.volume_interpolant(t, discr)

                    #rhs_fields = rhs(t, fields)

                    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)

            true_fields = vortex.volume_interpolant(t, 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_rho)
            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()
def main(write_output=['vtu', 'receivers'],
         allow_features='',
         dim=2,
         order=4,
         stfree_tag=TAG_NONE,
         fix_tag=TAG_ALL,
         op_tag=TAG_NONE,
         flux_type="lf",
         max_steps=None,
         output_dir='output',
         pml=None,
         sources=None,
         source_param={},
         final_time=12,
         quiet_output=True,
         nonlinearity_type=None,
         mesh_file='',
         periodicity=None,
         material_files=None,
         vtu_every=20):
    """
    Parameters:
    @param write_output: output data, among 'vtu', 'receivers' and 'txt'
    @param allow_features: 'mpi' or 'cuda'
    @param dim: 1, 2 or 3
    @param order: the order of the method
    @param stfree_tag: which elements to mark as stress-free boundaries
    @param fix_tag: which elements to mark as fixed boundaries
    @param op_tag: which elements to mark as open boundaries
    @param flux_type: 'lf' (Lax-Freidrich flux) or 'central'
    @param max_steps: None (no limit) or maximum number of steps to compute
    @param output_dir: directory where to write the output
    @param pml: None or NPML widths in this order: [x_l, y_l, z_l, x_r, y_r, z_r]
    @param sources: an array containing the coordinates of the source or None
    @param source_param: a dict containing the parameters for the source functions
    @param final_time: number of seconds of simulations to compute
    @param quiet_output: if True, only the main thread will print information
    @param nonlinearity_type: None (linear) or 'classical' (non-linear)
    @param mesh_file: the file to use as a mesh, or '' in 1D
    @param periodicity: the names of the boundaries to stick together, or None
    @param material_files: array, the material files (.dat) to use
    @param vtu_every: n, to write a vtu file every n steps
    """
    rcon = guess_run_context(allow_features)
    rcon_init = guess_run_context(allow_features)

    debug = ['dump_optemplate_stages']
    dtype = numpy.float64
    if 'cuda' in allow_features:
        dtype = numpy.float32
        debug.append('cuda_no_plan')

    if rcon.is_head_rank and output_dir and not access(output_dir, F_OK):
        makedirs(output_dir)

    if quiet_output:
        print_output = rcon.is_head_rank
    else:
        print_output = True
    if print_output:
        print "Using features:", ', '.join(allow_features).upper()
        nbranks = len(rcon.ranks)
        print "Using", nbranks, "rank" + ('s' if nbranks > 1 else '')
        print "Using", dim, "dimension" + ('s' if dim > 1 else '')
        print "Rank", rcon.rank, "will print its output."
    else:
        print "Rank", rcon.rank, "will be silent."

    class Receiver():
        pass

    assert dim in [1, 2, 3], 'Bad number of dimensions'

    # Define mesh ---

    mesh = None
    if mesh_file != '':
        mesh = read_gmsh(mesh_file,
                         force_dimension=dim,
                         periodicity=periodicity,
                         allow_internal_boundaries=False,
                         tag_mapper=lambda tag: tag)
    elif dim == 1:
        from hedge.mesh.generator import make_uniform_1d_mesh
        mesh = make_uniform_1d_mesh(-10, 10, 500)
    else:
        raise Exception('Error: No mesh file specified!')

    if rcon.is_head_rank:
        print "Using %d elements and order %d" % (len(mesh.elements), order)
        mesh_data = rcon.distribute_mesh(mesh)
        mesh_init = rcon_init.distribute_mesh(mesh)
    else:
        mesh_data = rcon.receive_mesh()
        mesh_init = rcon_init.receive_mesh()

    if mesh_file:
        from libraries.gmsh_reader import GmshReader
        gmsh = GmshReader(mesh_file, dim, print_output)

    # End of mesh definition ---
    # Define sources ---

    source = None

    if sources is not None:
        #FIXME: "Multiple source points are currently unsupported"
        source = sources
        if print_output:
            print "Using specified source", source
    else:
        if print_output:
            print "No source specified",
        if mesh_file:
            if print_output:
                print "trying to find one in", mesh_file
            sources = gmsh.pointSources
            if sources != []:
                source = sources[0]
                if print_output:
                    print "Using source", source, "from", mesh_file
            else:
                if print_output:
                    print "Error: no source!"
        else:
            if print_output:
                print "and no mesh file!"
            raise Exception('Error: Could not find any source!')

    def source_v_x(pos, el):
        pos = pos - source
        #return exp(-numpy.dot(pos, pos) / source_param['sigma'] ** 2)
        return exp(- pos[0]**2 / source_param['sigma'] ** 2)

    def source_v_y(pos, el):
        pos = pos - source
        return 0

    def source_v_z(pos, el):
        pos = pos - source
        return 0

    source_type = None
    if source_param['type'] == 'Sinus':
        from libraries.functions import SinusGivenFunction
        source_type = 'SinusGivenFunction'
    elif source_param['type'] == 'SineBurst':
        from libraries.functions import SineBurstGivenFunction
        source_type = 'SineBurstGivenFunction'
    elif source_param['type'] == 'Modulated_sinus':
        from libraries.functions import ModulatedSinusGivenFunction
        source_type = 'ModulatedSinusGivenFunction'
    elif source_param['type'] == 'Ricker':
        from libraries.functions import TimeRickerWaveletGivenFunction
        source_type = 'TimeRickerWaveletGivenFunction'
    assert source_type is not None, "Failed to define source function!"
    source_function = locals()[source_type]
    print "Using source type:", source_type

    from hedge.data import make_tdep_given, TimeIntervalGivenFunction

    def source_i(source_v_i):
        return TimeIntervalGivenFunction(
                   source_function(make_tdep_given(source_v_i),
                                   source_param['fc'], source_param['td']),
                   source_param['begin'], source_param['end'])

    sources = {'source_x': source_i(source_v_x),
               'source_y': source_i(source_v_y),
               'source_z': source_i(source_v_z)}

    # End of sources definition ---
    # Define materials and link them with elements ---

    materials = []
    constants = ['Density', 'LinearElasticConstants']
    if nonlinearity_type == 'cubic':
        constants.append('ElasticConstant_lambda')
        constants.append('ElasticConstant_mu')
        constants.append('QuadraticElasticConstant_f')
        constants.append('CubicElasticConstant_h')
    elif nonlinearity_type is not None:
        constants.append('NonlinearElasticConstants')
    for material_file in material_files:
        material = Material(material_file, constants, dtype, print_output)
        if nonlinearity_type == 'cubic':
            assert material.lambda_ is not None, "Error: Missing elastic constant lambda in " + file
            assert material.mu is not None, "Error: Missing elastic constant mu in " + file
            assert material.f is not None, "Error: Missing quadratic constant f in " + file
            assert material.h is not None, "Error: Missing cubic constant h in " + file
        elif nonlinearity_type is not None:
            # In the nonlinear mode, materials MUST have a nonlinear constants
            assert material.Cnl is not None, "Error: Missing nonlinear constants in " + file
        materials.append(material)
    assert len(materials) > 0, "Error: You must define at least 1 material."

    # Work out which elements belong to each material
    material_elements = []
    used_materials = []
    speeds = []

    for num, name in [(0, 'mat1'), (1, 'mat2'), (2, 'mat3')]:
        if len(materials) > num:
            if name in mesh_init.tag_to_elements.keys():
                elements_list = [el.id for el in mesh_init.tag_to_elements[name]]
                material_elements.append(elements_list)
        else:
            num = 0
        speed = (materials[num].C[0, 0] / materials[num].rho) ** 0.5
        speeds.append(speed.astype(dtype))
        used_materials.append(materials[num])
        if print_output:
            print "Using", materials[num].filename, "as", name

    speed = max(speeds)

    if print_output:
        print "Using max speed:", speed, "m/s"

    def mat_val(x, el):
        # Will be used in Evaluate(mat, val)
        for i in range(len(material_elements)):
            if el.id in material_elements[i]:
                return i
        return 0

    # End of materials definition ---
    # Define the elastodynamics operator and the discretization ---

    kwargs = {
              'dimensions': dim,
              'speed': speed,
              'material': make_tdep_given(mat_val),
              'sources': sources,
              'boundaryconditions_tag': \
                    {'stressfree': stfree_tag,
                     'fixed': fix_tag,
                     'open': op_tag},
              'materials': used_materials,
              'flux_type': flux_type
              }

    operator = None
    if nonlinearity_type == 'cubic':
        kwargs['nonlinearity_type'] = nonlinearity_type
        if pml:
            from elastodynamic import CubicNPMLElastoDynamicsOperator
            operator = 'CubicNPMLElastoDynamicsOperator'
        else:
            raise NotImplementedError
    elif nonlinearity_type is not None:
        kwargs['nonlinearity_type'] = nonlinearity_type
        if pml:
            from elastodynamic import QuadraticNPMLElastoDynamicsOperator
            operator = 'QuadraticNPMLElastoDynamicsOperator'
        else:
            from elastodynamic import QuadraticElastoDynamicsOperator
            operator = 'QuadraticElastoDynamicsOperator'
    else:
        if pml:
            from elastodynamic import NPMLElastoDynamicsOperator
            operator = "NPMLElastoDynamicsOperator"
        else:
            from elastodynamic import ElastoDynamicsOperator
            operator = "ElastoDynamicsOperator"

    assert operator is not None, "Failed to define operator!"
    op = locals()[operator](**kwargs)
    if print_output:
        print "Using", operator

    discr = rcon.make_discretization(mesh_data, order=order, debug=debug, tune_for=op.op_template())

    # End of elastodynamics operator and discretization definition ---
    # Define receivers ---

    receivers = []
    point_receivers = []
    if write_output and print_output:
        print "Using output dir:", output_dir
    if "receivers" in write_output:
        i = 0
        if mesh_file:
            receivers = gmsh.pointReceivers
        if receivers != []:
            for receiver in receivers:
                try:
                    point_receiver = Receiver()
                    point_receiver.evaluator = discr.get_point_evaluator(numpy.array(receiver))
                    point_receiver.done_dt = False
                    point_receiver.id = i
                    point_receiver.coordinates = receiver
                    point_receiver.filename = "receiver_%s.txt" % repr(point_receiver.coordinates)
                except:
                    if not quiet_output:
                        print "Receiver ignored (point not found):", receiver
                else:
                    point_receivers.append(point_receiver)
                    i += 1
                    print "Using", point_receiver.filename, "for receiver", receiver

    # End of receivers definition ---
    # Define visualization ---

    def write_datafile(filename, variables):
        if rcon is not None and len(rcon.ranks) > 1:
            filename += "-%04d" % rcon.rank
        visfile = open(filename + ".txt", "wt")
        visfile.write("x\ty\t")
        for name, field in variables:
            if name == "m":
                visfile.write("m\t")
            else:
                i = 0
                for subvect in field:
                    i += 1
                    assert len(subvect) == len(discr.nodes), "Wrong length!"
                    visfile.write(name + "_" + format(i) + "\t")
        visfile.write("\n")
        for i in range(len(discr.nodes)):
            for coord in discr.nodes[i]:
                visfile.write(format(coord) + "\t")
            for name, field in variables:
                if name == "m":
                    visfile.write(format(field[i]) + "\t")
                else:
                    for subvect in field:
                        visfile.write(format(subvect[i]) + "\t")
            visfile.write("\n")
        visfile.close()

    if 'vtu' in write_output:
        from hedge.visualization import VtkVisualizer
        vis = VtkVisualizer(discr, rcon, 'fld')

    if output_dir:
        chdir(output_dir)

    if 'receivers' in write_output:
        for point_receiver in point_receivers:
            point_receiver.pointfile = open(point_receiver.filename, "wt")
        #sumfile = open("receiver_%s_sum.txt" % rcon.rank, "wt")

    # End of visualization definition ---
    # Bind the operator to the discretization ---

    if pml:
        coefficients = op.coefficients_from_width(discr, mesh, widths=pml,
                                                  material=materials[0],
                                                  alpha_magnitude=2 * pi * source_param['fc'] / 10)
        rhs = op.bind(discr, coefficients)
    else:
        rhs = op.bind(discr)

    # End of operator binding ---
    # Define the timestep loop ---

    t = 0.0
    max_txt = ''
    try:
        len_fields = op.len_q
        if pml:
            len_fields += op.len_f2
        fields = make_obj_array([discr.volume_zeros(dtype=dtype) for _ in range(len_fields)])

        vector_primitive_factory = None if 'cuda' in allow_features else discr.get_vector_primitive_factory()

        from hedge.timestep import times_and_steps, LSRK4TimeStepper
        stepper = LSRK4TimeStepper(vector_primitive_factory=vector_primitive_factory, dtype=dtype)
        max_dt_getter = lambda t: op.estimate_timestep(discr, stepper=stepper, t=t, fields=fields)
        step_it = times_and_steps(final_time=final_time, logmgr=None, max_dt_getter=max_dt_getter)

        for step, t, dt in step_it:
            if max_steps > 0:
                max_txt = ' on %d' % max_steps
                if step > max_steps:
                    break

            if step % vtu_every == 0:
                variables = [("m", discr.convert_volume(op.m(fields), "numpy")),
                             ("v", discr.convert_volume(op.v(fields), "numpy")),
                             ("F", discr.convert_volume(op.F(fields), "numpy"))]

                if print_output:
                    print time.strftime('[%H:%M:%S] ', time.localtime()) + \
                          'Step: ' + format(step) + max_txt + '; time: ' + format(t)

                if 'vtu' in write_output:
                    visf = vis.make_file("fld-%04d" % step)
                    vis.add_data(visf, variables, time=t, step=step)
                    visf.close()

                if 'txt' in write_output:
                    write_datafile("fld-%04d" % step, variables)

            if 'receivers' in write_output and point_receivers != []:
                variables = discr.convert_volume(fields, "numpy")
                #sum_val = numpy.zeros(len(fields))
                #sumfile.write("\n%s " % format(t))
                for point_receiver in point_receivers:
                    val = point_receiver.evaluator(variables)
                    if not point_receiver.done_dt:
                        point_receiver.pointfile.write("# dt: %g s\n" % dt)
                        point_receiver.pointfile.write("# m: 1 field\n")
                        point_receiver.pointfile.write("# v: %d fields\n" % dim)
                        point_receiver.pointfile.write("# F: %d fields\n" % op.len_f)
                        point_receiver.pointfile.write("# Coordinates: %s\n# t m " % repr(point_receiver.coordinates))
                        for i in range(dim):
                            point_receiver.pointfile.write('v%s ' % i)
                        for i in range(op.len_f):
                            point_receiver.pointfile.write("F%s " % i)
                        point_receiver.done_dt = True
                    point_receiver.pointfile.write("\n%s " % format(t))
                    for i in range(1 + dim + op.len_f):
                        #sum_val[i] += val[i]
                        point_receiver.pointfile.write("%s " % format(val[i]))

                #for i in range(len(val)):
                    #sumfile.write("%s " % format(sum_val[i]))

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

    finally:
        if 'vtu' in write_output:
            vis.close()

        if 'receivers' in write_output:
            for point_receiver in point_receivers:
                point_receiver.pointfile.close()
            #sumfile.close()

        discr.close()
        if output_dir:
            chdir('..')