Example #1
0
def test_initialize_fneq(Case, dtype_device):
    dtype, device = dtype_device
    lattice = Lattice(D2Q9, device, dtype)
    if "3D" in Case.__name__:
        lattice = Lattice(D3Q27, dtype=dtype, device=device)
    flow = Case(resolution=40, reynolds_number=1000, mach_number=0.1, lattice=lattice)
    collision = BGKCollision(lattice, tau=flow.units.relaxation_parameter_lu)
    streaming = StandardStreaming(lattice)
    simulation_neq = Simulation(flow=flow, lattice=lattice, collision=collision, streaming=streaming)

    pre_rho = lattice.rho(simulation_neq.f)
    pre_u = lattice.u(simulation_neq.f)
    pre_ke = lattice.incompressible_energy(simulation_neq.f)

    simulation_neq.initialize_f_neq()

    post_rho = lattice.rho(simulation_neq.f)
    post_u = lattice.u(simulation_neq.f)
    post_ke = lattice.incompressible_energy(simulation_neq.f)
    tol = 1e-6
    assert torch.allclose(pre_rho, post_rho, rtol=0.0, atol=tol)
    assert torch.allclose(pre_u, post_u, rtol=0.0, atol=tol)
    assert torch.allclose(pre_ke, post_ke, rtol=0.0, atol=tol)

    if Case is TaylorGreenVortex2D:
        error_reporter_neq = ErrorReporter(lattice, flow, interval=1, out=None)
        error_reporter_eq = ErrorReporter(lattice, flow, interval=1, out=None)
        simulation_eq = Simulation(flow=flow, lattice=lattice, collision=collision, streaming=streaming)
        simulation_neq.reporters.append(error_reporter_neq)
        simulation_eq.reporters.append(error_reporter_eq)

        simulation_neq.step(10)
        simulation_eq.step(10)
        error_u, error_p = np.mean(np.abs(error_reporter_neq.out), axis=0).tolist()
        error_u_eq, error_p_eq = np.mean(np.abs(error_reporter_eq.out), axis=0).tolist()

        assert error_u < error_u_eq
Example #2
0
def test_generic_reporters(Observable, Case, dtype_device):
    dtype, device = dtype_device
    lattice = Lattice(D2Q9, dtype=dtype, device=device)
    flow = Case(32, 10000, 0.05, lattice=lattice)
    if Case == TaylorGreenVortex3D:
        lattice = Lattice(D3Q27, dtype=dtype, device=device)
    collision = BGKCollision(lattice, tau=flow.units.relaxation_parameter_lu)
    streaming = StandardStreaming(lattice)
    simulation = Simulation(flow=flow,
                            lattice=lattice,
                            collision=collision,
                            streaming=streaming)
    reporter = ObservableReporter(Observable(lattice, flow),
                                  interval=1,
                                  out=None)
    simulation.reporters.append(reporter)
    simulation.step(2)
    values = np.asarray(reporter.out)
    if Observable is EnergySpectrum:
        assert values[1, 2:] == pytest.approx(values[0, 2:],
                                              rel=0.0,
                                              abs=values[0, 2:].sum() / 10)
    else:
        assert values[1, 2] == pytest.approx(values[0, 2], rel=0.05)
Example #3
0
def test_torch_gradient_2d(order):
    lattice = Lattice(
        D2Q9,
        device='cpu',
    )
    flow = TaylorGreenVortex2D(resolution=100,
                               reynolds_number=1,
                               mach_number=0.05,
                               lattice=lattice)
    grid = flow.grid
    p, u = flow.initial_solution(grid)
    dx = flow.units.convert_length_to_pu(1.0)
    u0_grad = torch_gradient(lattice.convert_to_tensor(u[0]),
                             dx=dx,
                             order=order).numpy()
    u0_grad_np = np.array(np.gradient(u[0], dx))
    u0_grad_analytic = np.array([
        -np.sin(grid[0]) * np.sin(grid[1]),
        np.cos(grid[0]) * np.cos(grid[1]),
    ])
    assert (u0_grad_analytic == pytest.approx(u0_grad, rel=0.0, abs=1e-3))
    assert (u0_grad_np[:, 2:-2, 2:-2] == pytest.approx(u0_grad[:, 2:-2, 2:-2],
                                                       rel=0.0,
                                                       abs=1e-3))
Example #4
0
def convergence(ctx, init_f_neq):
    """Use Taylor Green 2D for convergence test in diffusive scaling."""
    device, dtype = ctx.obj['device'], ctx.obj['dtype']
    lattice = Lattice(D2Q9, device, dtype)
    error_u_old = None
    error_p_old = None
    print(("{:>15} " * 5).format("resolution", "error (u)", "order (u)",
                                 "error (p)", "order (p)"))

    for i in range(4, 9):
        resolution = 2**i
        mach_number = 8 / resolution

        # Simulation
        flow = TaylorGreenVortex2D(resolution=resolution,
                                   reynolds_number=10000,
                                   mach_number=mach_number,
                                   lattice=lattice)
        collision = BGKCollision(lattice,
                                 tau=flow.units.relaxation_parameter_lu)
        streaming = StandardStreaming(lattice)
        simulation = Simulation(flow=flow,
                                lattice=lattice,
                                collision=collision,
                                streaming=streaming)
        if (init_f_neq):
            simulation.initialize_f_neq()
        error_reporter = ErrorReporter(lattice, flow, interval=1, out=None)
        simulation.reporters.append(error_reporter)
        for _ in range(10 * resolution):
            simulation.step(1)
        error_u, error_p = np.mean(np.abs(error_reporter.out), axis=0).tolist()
        factor_u = 0 if error_u_old is None else error_u_old / error_u
        factor_p = 0 if error_p_old is None else error_p_old / error_p
        error_u_old = error_u
        error_p_old = error_p
        print("{:15} {:15.2e} {:15.1f} {:15.2e} {:15.1f}".format(
            resolution, error_u, factor_u / 2, error_p, factor_p / 2))
    if factor_u / 2 < 1.9:
        print("Velocity convergence order < 2.")
    if factor_p / 2 < 0.9:
        print("Velocity convergence order < 1.")
    if factor_u / 2 < 1.9 or factor_p / 2 < 0.9:
        sys.exit(1)
    else:
        return 0
Example #5
0
def benchmark(ctx, steps, resolution, profile_out, flow, vtk_out):
    """Run a short simulation and print performance in MLUPS.
    """
    # start profiling
    if profile_out:
        profile = cProfile.Profile()
        profile.enable()

    # setup and run simulation
    device, dtype = ctx.obj['device'], ctx.obj['dtype']
    flow_class, stencil = flow_by_name[flow]
    lattice = Lattice(stencil, device, dtype)
    flow = flow_class(resolution=resolution,
                      reynolds_number=1,
                      mach_number=0.05,
                      lattice=lattice)
    force = Guo(lattice,
                tau=flow.units.relaxation_parameter_lu,
                acceleration=flow.units.convert_acceleration_to_lu(
                    flow.force)) if hasattr(flow, "acceleration") else None
    collision = BGKCollision(lattice,
                             tau=flow.units.relaxation_parameter_lu,
                             force=force)
    streaming = StandardStreaming(lattice)
    simulation = Simulation(flow=flow,
                            lattice=lattice,
                            collision=collision,
                            streaming=streaming)
    if vtk_out:
        simulation.reporters.append(VTKReporter(lattice, flow, interval=10))
    mlups = simulation.step(num_steps=steps)

    # write profiling output
    if profile_out:
        profile.disable()
        stats = pstats.Stats(profile)
        stats.sort_stats('cumulative')
        stats.print_stats()
        profile.dump_stats(profile_out)
        click.echo(f"Saved profiling information to {profile_out}.")

    click.echo("Finished {} steps in {} bit precision. MLUPS: {:10.2f}".format(
        steps,
        str(dtype).replace("torch.float", ""), mlups))
    return 0
Example #6
0
def test_initialization(dtype_device):
    dtype, device = dtype_device
    lattice = Lattice(D2Q9, device, dtype)
    flow = TaylorGreenVortex2D(resolution=16, reynolds_number=10, mach_number=0.05, lattice=lattice)
    collision = BGKCollision(lattice, tau=flow.units.relaxation_parameter_lu)
    streaming = StandardStreaming(lattice)
    simulation = Simulation(flow=flow, lattice=lattice, collision=collision, streaming=streaming)
    # set initial pressure to 0 everywhere
    p, u = flow.initial_solution(flow.grid)
    u0 = lattice.convert_to_tensor(flow.units.convert_velocity_to_lu(u))
    rho0 = lattice.convert_to_tensor(np.ones_like(u0[0,...].cpu()))
    simulation.f = lattice.equilibrium(rho0, u0)
    num_iterations = simulation.initialize(500, 0.001)
    piter = lattice.convert_to_numpy(flow.units.convert_density_lu_to_pressure_pu(lattice.rho(simulation.f)))
    # assert that pressure is converged up to 0.05 (max p
    assert piter == pytest.approx(p, abs=5e-2)
    assert num_iterations < 500
Example #7
0
def test_vtk_reporter_no_mask(tmpdir):
    lattice = Lattice(D2Q9, "cpu")
    flow = TaylorGreenVortex2D(resolution=16,
                               reynolds_number=10,
                               mach_number=0.05,
                               lattice=lattice)
    collision = BGKCollision(lattice, tau=flow.units.relaxation_parameter_lu)
    streaming = StandardStreaming(lattice)
    simulation = Simulation(flow=flow,
                            lattice=lattice,
                            collision=collision,
                            streaming=streaming)
    vtk_reporter = VTKReporter(lattice,
                               flow,
                               interval=1,
                               filename_base=tmpdir / "output")
    simulation.reporters.append(vtk_reporter)
    simulation.step(2)
    assert os.path.isfile(tmpdir / "output_00000000.vtr")
    assert os.path.isfile(tmpdir / "output_00000001.vtr")
Example #8
0
def lattice(request, dtype_device):
    """Run a test for all lattices (all stencils, devices and data types available on the device.)"""
    dtype, device = dtype_device
    return Lattice(request.param, device=device, dtype=dtype)
Example #9
0
    def grid(self):
        grid = [
            np.linspace(0, 2 * np.pi, num=self.resolution, endpoint=False)
            for _ in range(self.units.lattice.D)
        ]
        return np.meshgrid(*grid)

    @property
    def boundaries(self):
        return []


print('Generates reference data on fine grid')
torch.cuda.empty_cache()

lattice = Lattice(D2Q9, device=device, dtype=torch.double)
flow_fine = flowclass(
    resolution=2 * resolution,
    reynolds_number=reynolds,
    mach_number=mach,
    lattice=lattice,
)
tau_fine = flow_fine.units.relaxation_parameter_lu
flow_coarse = flowclass(
    resolution=resolution,
    reynolds_number=reynolds,
    mach_number=mach,
    lattice=lattice,
)

collision = BGKCollision(lattice, tau=tau_fine)