Example #1
0
    def verify_timestep_order(stepper_getter, order, setup=None, dtmul=1):
        eocrec = EOCRecorder()
        for n in range(4,9):
            dt = 2**(-n) * dtmul
            stepper = stepper_getter()
            if setup is not None:
                setup(stepper, dt)

            error = get_error(stepper,dt)
            eocrec.add_data_point(1/dt, error)

        print "------------------------------------------------------"
        print "ORDER %d, %s" % (order, stepper)
        print "------------------------------------------------------"
        print eocrec.pretty_print()

        orderest = eocrec.estimate_order_of_convergence()[0,1]
        #print orderest, order
        assert orderest > order*0.95
Example #2
0
    def __call__(self):
        from hedge.tools import EOCRecorder
        eocrec = EOCRecorder()
        for n in range(4,7):
            dt = 2**(-n)

            from hedge.timestep.multirate_ab import TwoRateAdamsBashforthTimeStepper

            stepper = TwoRateAdamsBashforthTimeStepper(
                    self.method, dt, self.step_ratio, self.order)

            error = self.get_error(stepper, dt, "mrab-%d.dat" % self.order)

            eocrec.add_data_point(1/dt, error)

        print "------------------------------------------------------"
        print "ORDER %d" % self.order
        print "------------------------------------------------------"
        print eocrec.pretty_print()

        orderest = eocrec.estimate_order_of_convergence()[0,1]
        assert orderest > self.order*0.70
Example #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()

    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
Example #4
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
Example #5
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
Example #6
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()
Example #7
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
def test_convergence_advec_2d():
    """Test whether 2D advection actually converges"""

    import pyublas  # noqa
    from hedge.mesh.generator import make_disk_mesh, make_regular_rect_mesh
    from hedge.discretization.local import TriangleDiscretization
    from hedge.timestep import RK4TimeStepper
    from hedge.tools import EOCRecorder
    from math import sin, pi
    from hedge.models.advection import StrongAdvectionOperator
    from hedge.data import TimeDependentGivenFunction

    v = numpy.array([0.27, 0])
    norm_a = la.norm(v)

    from numpy import dot

    def f(x):
        return sin(x)

    def u_analytic(x, el, t):
        return f((-dot(v, x) / norm_a + t * norm_a))

    def boundary_tagger(vertices, el, face_nr, all_v):
        if dot(el.face_normals[face_nr], v) < 0:
            return ["inflow"]
        else:
            return ["outflow"]

    for mesh in [
            # non-periodic
            make_disk_mesh(r=pi, boundary_tagger=boundary_tagger,
                           max_area=0.5),
            # periodic
            make_regular_rect_mesh(
                a=(0, 0),
                b=(2 * pi, 1),
                n=(8, 4),
                periodicity=(True, False),
                boundary_tagger=boundary_tagger,
            )
    ]:
        for flux_type in StrongAdvectionOperator.flux_types:
            eoc_rec = EOCRecorder()

            for order in [1, 2, 3, 4, 5, 6]:
                discr = discr_class(
                    mesh,
                    TriangleDiscretization(order),
                    debug=discr_class.noninteractive_debug_flags())
                op = StrongAdvectionOperator(
                    v,
                    inflow_u=TimeDependentGivenFunction(u_analytic),
                    flux_type=flux_type)

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

                stepper = RK4TimeStepper()
                dt = op.estimate_timestep(discr, stepper=stepper)
                nsteps = int(1 / dt)
                rhs = op.bind(discr)
                for step in range(nsteps):
                    u = stepper(u, step * dt, dt, rhs)

                u_true = discr.interpolate_volume_function(
                    lambda x, el: u_analytic(x, el, nsteps * dt))
                error = u - u_true
                error_l2 = discr.norm(error)
                eoc_rec.add_data_point(order, error_l2)

            if False:
                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] > 4
            assert eoc_rec.estimate_order_of_convergence(2)[-1, 1] > 10
Example #9
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")
Example #10
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()
Example #11
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
Example #12
0
def test_elliptic():
    """Test various properties of elliptic operators."""

    from hedge.tools import unit_vector

    def matrix_rep(op):
        h, w = op.shape
        mat = numpy.zeros(op.shape)
        for j in range(w):
            mat[:, j] = op(unit_vector(w, j))
        return mat

    def check_grad_mat():
        import pyublas

        if not pyublas.has_sparse_wrappers():
            return

        grad_mat = op.grad_matrix()

        # print len(discr), grad_mat.nnz, type(grad_mat)
        for i in range(10):
            u = numpy.random.randn(len(discr))

            mat_result = grad_mat * u
            op_result = numpy.hstack(op.grad(u))

            err = la.norm(mat_result - op_result) * la.norm(op_result)
            assert la.norm(mat_result - op_result) * la.norm(op_result) < 1e-5

    def check_matrix_tgt():
        big = num.zeros((20, 20), flavor=num.SparseBuildMatrix)
        small = num.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
        print small
        from hedge._internal import MatrixTarget

        tgt = MatrixTarget(big, 4, 4)
        tgt.begin(small.shape[0], small.shape[1])
        print "YO"
        tgt.add_coefficients(4, 4, small)
        print "DUDE"
        tgt.finalize()
        print big

    import pymbolic

    v_x = pymbolic.var("x")
    truesol = pymbolic.parse("math.sin(x[0]**2*x[1]**2)")
    truesol_c = pymbolic.compile(truesol, variables=["x"])
    rhs = pymbolic.simplify(pymbolic.laplace(truesol, [v_x[0], v_x[1]]))
    rhs_c = pymbolic.compile(rhs, variables=["x", "el"])

    from hedge.mesh import TAG_ALL, TAG_NONE
    from hedge.mesh.generator import make_disk_mesh

    mesh = make_disk_mesh(r=0.5, max_area=0.1, faces=20)
    mesh = mesh.reordered_by("cuthill")

    from hedge.backends import CPURunContext

    rcon = CPURunContext()

    from hedge.tools import EOCRecorder

    eocrec = EOCRecorder()
    for order in [1, 2, 3, 4, 5]:
        for flux in ["ldg", "ip"]:
            from hedge.discretization.local import TriangleDiscretization

            discr = rcon.make_discretization(
                mesh, TriangleDiscretization(order), debug=discr_class.noninteractive_debug_flags()
            )

            from hedge.data import GivenFunction
            from hedge.models.poisson import PoissonOperator

            op = PoissonOperator(
                discr.dimensions,
                dirichlet_tag=TAG_ALL,
                dirichlet_bc=GivenFunction(lambda x, el: truesol_c(x)),
                neumann_tag=TAG_NONE,
            )

            bound_op = op.bind(discr)

            if order <= 3:
                mat = matrix_rep(bound_op)
                sym_err = la.norm(mat - mat.T)
                # print sym_err
                assert sym_err < 1e-12
                # check_grad_mat()

            from hedge.iterative import parallel_cg

            truesol_v = discr.interpolate_volume_function(lambda x, el: truesol_c(x))
            sol_v = -parallel_cg(
                rcon,
                -bound_op,
                bound_op.prepare_rhs(discr.interpolate_volume_function(rhs_c)),
                tol=1e-10,
                max_iterations=40000,
            )

            eocrec.add_data_point(order, discr.norm(sol_v - truesol_v))

    # print eocrec.pretty_print()
    assert eocrec.estimate_order_of_convergence()[0, 1] > 8
Example #13
0
def test_convergence_advec_2d():
    """Test whether 2D advection actually converges"""

    import pyublas
    from hedge.mesh.generator import make_disk_mesh, make_regular_rect_mesh
    from hedge.discretization.local import TriangleDiscretization
    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

    v = numpy.array([0.27, 0])
    norm_a = la.norm(v)

    from numpy import dot

    def f(x):
        return sin(x)

    def u_analytic(x, el, t):
        return f((-dot(v, x) / norm_a + t * norm_a))

    def boundary_tagger(vertices, el, face_nr, all_v):
        if dot(el.face_normals[face_nr], v) < 0:
            return ["inflow"]
        else:
            return ["outflow"]

    for mesh in [
        # non-periodic
        make_disk_mesh(r=pi, boundary_tagger=boundary_tagger, max_area=0.5),
        # periodic
        make_regular_rect_mesh(
            a=(0, 0), b=(2 * pi, 1), n=(8, 4), periodicity=(True, False), boundary_tagger=boundary_tagger
        ),
    ]:
        for flux_type in StrongAdvectionOperator.flux_types:
            eoc_rec = EOCRecorder()

            for order in [1, 2, 3, 4, 5, 6]:
                discr = discr_class(mesh, TriangleDiscretization(order), debug=discr_class.noninteractive_debug_flags())
                op = StrongAdvectionOperator(v, inflow_u=TimeDependentGivenFunction(u_analytic), flux_type=flux_type)

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

                stepper = RK4TimeStepper()
                dt = op.estimate_timestep(discr, stepper=stepper)
                nsteps = int(1 / dt)
                rhs = op.bind(discr)
                for step in range(nsteps):
                    u = stepper(u, step * dt, dt, rhs)

                u_true = discr.interpolate_volume_function(lambda x, el: u_analytic(x, el, nsteps * dt))
                error = u - u_true
                error_l2 = discr.norm(error)
                eoc_rec.add_data_point(order, error_l2)

            if False:
                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] > 4
            assert eoc_rec.estimate_order_of_convergence(2)[-1, 1] > 10
Example #14
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()
Example #15
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 test_elliptic():
    """Test various properties of elliptic operators."""

    from hedge.tools import unit_vector

    def matrix_rep(op):
        h, w = op.shape
        mat = numpy.zeros(op.shape)
        for j in range(w):
            mat[:, j] = op(unit_vector(w, j))
        return mat

    def check_grad_mat():
        import pyublas
        if not pyublas.has_sparse_wrappers():
            return

        grad_mat = op.grad_matrix()

        #print len(discr), grad_mat.nnz, type(grad_mat)
        for i in range(10):
            u = numpy.random.randn(len(discr))

            mat_result = grad_mat * u
            op_result = numpy.hstack(op.grad(u))

            err = la.norm(mat_result - op_result) * la.norm(op_result)
            assert err < 1e-5

    def check_matrix_tgt():
        big = numpy.zeros((20, 20), flavor=numpy.SparseBuildMatrix)
        small = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
        print small
        from hedge._internal import MatrixTarget
        tgt = MatrixTarget(big, 4, 4)
        tgt.begin(small.shape[0], small.shape[1])
        print "YO"
        tgt.add_coefficients(4, 4, small)
        print "DUDE"
        tgt.finalize()
        print big

    import pymbolic
    v_x = pymbolic.var("x")
    truesol = pymbolic.parse("math.sin(x[0]**2*x[1]**2)")
    truesol_c = pymbolic.compile(truesol, variables=["x"])

    def laplace(expression, variables):
        return sum(
            pymbolic.diff(pymbolic.diff(expression, var), var)
            for var in variables)

    rhs = laplace(truesol, [v_x[0], v_x[1]])
    rhs_c = pymbolic.compile(rhs, variables=["x", "el"])

    from hedge.mesh import TAG_ALL, TAG_NONE
    from hedge.mesh.generator import make_disk_mesh
    mesh = make_disk_mesh(r=0.5, max_area=0.1, faces=20)
    mesh = mesh.reordered_by("cuthill")

    from hedge.backends import CPURunContext
    rcon = CPURunContext()

    from hedge.tools import EOCRecorder
    eocrec = EOCRecorder()
    for order in [1, 2, 3, 4, 5]:
        for flux in ["ldg", "ip"]:
            from hedge.discretization.local import TriangleDiscretization
            discr = rcon.make_discretization(
                mesh,
                TriangleDiscretization(order),
                debug=discr_class.noninteractive_debug_flags())

            from hedge.data import GivenFunction
            from hedge.models.poisson import PoissonOperator
            op = PoissonOperator(
                discr.dimensions,
                dirichlet_tag=TAG_ALL,
                dirichlet_bc=GivenFunction(lambda x, el: truesol_c(x)),
                neumann_tag=TAG_NONE)

            bound_op = op.bind(discr)

            if order <= 3:
                mat = matrix_rep(bound_op)
                sym_err = la.norm(mat - mat.T)
                #print sym_err
                assert sym_err < 1e-12
                #check_grad_mat()

            from hedge.iterative import parallel_cg
            truesol_v = discr.interpolate_volume_function(
                lambda x, el: truesol_c(x))
            sol_v = -parallel_cg(rcon,
                                 -bound_op,
                                 bound_op.prepare_rhs(
                                     discr.interpolate_volume_function(rhs_c)),
                                 tol=1e-10,
                                 max_iterations=40000)

            eocrec.add_data_point(order, discr.norm(sol_v - truesol_v))

    #print eocrec.pretty_print()
    assert eocrec.estimate_order_of_convergence()[0, 1] > 8
Example #17
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()
Example #18
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