Exemplo n.º 1
0
def main():
    setup = Setup()

    setup.grid = (75, 75)
    setup.steps = [1] + list(range(10, 100, 10))  #[100, 3600]
    setup.processes = {
        "advection": True,
        "coalescence": True,
        "condensation": True
    }
    setup.condensation_dt_max = .2

    n_sd = range(50, 51, 10)

    times = {}
    for parallel in (False, ):
        PySDM.backends.numba.conf.NUMBA_PARALLEL = parallel
        reload_backend()
        for method in ('local', ):
            key = f"{method} (parallel={parallel})"
            times[key] = []
            for sd in n_sd:
                setup.n_sd_per_gridbox = sd
                storage = Storage()
                simulation = Simulation(setup, storage)
                # simulation.particles.croupier = method
                stats = simulation.run()
                times[key].append(stats.wall_times[-1])

    from matplotlib import pyplot as plt
    for method, t in times.items():
        plt.plot(n_sd, t, label=method)
    plt.legend()
    plt.loglog()
    plt.show()
Exemplo n.º 2
0
def test_environment(plot=False):
    # Arrange
    setup = Setup()
    setup.n_steps = -1
    simulation = Simulation(setup, None)
    simulation.reinit()

    # Act
    simulation.run()
    rhod = setup.backend.to_ndarray(simulation.particles.environment["rhod"]).reshape(setup.grid)

    # Plot
    if plot:
        fig, ax = pyplot.subplots(1, 1)
        plotter.image(ax, rhod, setup.size, label='rho_d [kg/m^3]')
        pyplot.show()

    # Assert - same in all columns
    for column in range(setup.grid[0]):
        np.testing.assert_array_equal(
            rhod[column, :], rhod[0, :]
        )

    # Assert - decreasing with altitude
    rhod_below = 2 * si.kilograms / si.metre**3
    for level in range(setup.grid[1]):
        rhod_above = rhod[0, level]
        assert rhod_above < rhod_below
        rhod_below = rhod_above
Exemplo n.º 3
0
def test_multi_timestep(plot=False):
    # Arrange
    setup = Setup()
    setup.n_steps = 20
    setup.outfreq = 1

    for key in setup.processes.keys():
        setup.processes[key] = False
    setup.processes["condensation"] = True
    setup.processes["fluid advection"] = True

    storage = DummyStorage()
    simulation = Simulation(setup, storage)
    simulation.reinit()

    # Act
    simulation.run()

    # Plot
    if plot:
        levels = np.arange(setup.grid[1])
        for step, datum in storage.profiles.items():
            pyplot.plot(datum["qv"], levels, label=str(step))
        pyplot.legend()
        pyplot.show()

    # Assert
    for step in range(len(storage.profiles) - 1):
        next = storage.profiles[step + 1]["qv"]
        prev = storage.profiles[step]["qv"]
        eps = 1e-5
        assert ((prev + eps) >= next).all()
Exemplo n.º 4
0
def test_single_timestep():
    # Arrange
    setup = Setup()
    setup.n_steps = 1
    simulation = Simulation(setup, DummyStorage())
    simulation.reinit()

    # Act
    simulation.run()
Exemplo n.º 5
0
def test_single_timestep():
    # Arrange
    Setup.n_steps = 1
    Setup.outfreq = 1
    setup = Setup()
    for key in setup.processes.keys():
        setup.processes[key] = True
    setup.processes["condensation"] = True
    setup.processes["relaxation"] = False

    simulation = Simulation(setup, DummyStorage())
    simulation.reinit()

    # Act
    simulation.run()
Exemplo n.º 6
0
def test_export():
    # Arrange
    setup = Setup()
    setup.n_steps = 1
    setup.outfreq = 1

    storage = Storage()
    simulator = Simulation(setup, storage)
    sut = netCDF(storage, setup, simulator)
    controller = DummyController()

    simulator.reinit()
    simulator.run(controller)

    # Act
    sut.run(controller=controller)
Exemplo n.º 7
0
def main():
    with np.errstate(all='ignore'):
        setup = Setup()

        setup.n_sd_per_gridbox = 25
        setup.grid = (25, 25)
        setup.processes["coalescence"] = True
        setup.processes["condensation"] = True
        setup.condensation_rtol_lnv = 1e-8
        setup.condensation_rtol_thd = 1e-8
        setup.mpdata_iters = 2

        storage = Storage()
        simulation = Simulation(setup, storage)
        simulation.reinit()
        simulation.run()
Exemplo n.º 8
0
def test_environment():
    # Arrange
    setup = Setup()
    setup.n_steps = -1
    simulation = Simulation(setup, None)
    simulation.reinit()

    # Act
    simulation.run()
    rhod = simulation.core.environment["rhod"].to_ndarray().reshape(setup.grid)

    # Assert - same in all columns
    for column in range(setup.grid[0]):
        np.testing.assert_array_equal(rhod[column, :], rhod[0, :])

    # Assert - decreasing with altitude
    rhod_below = 2 * si.kilograms / si.metre**3
    for level in range(setup.grid[1]):
        rhod_above = rhod[0, level]
        assert rhod_above < rhod_below
        rhod_below = rhod_above
Exemplo n.º 9
0
def test_initialisation(plot=False):
    # TODO: seed as a part of setup?
    setup = Setup()
    setup.n_steps = -1
    setup.grid = (10, 5)
    setup.n_sd_per_gridbox = 2000

    simulation = Simulation(setup, None)

    n_bins = 32
    n_levels = setup.grid[1]
    n_cell = np.prod(np.array(setup.grid))
    n_moments = 1

    v_bins = np.logspace((np.log10(phys.volume(radius=setup.r_min))),
                         (np.log10(phys.volume(radius=10 * setup.r_max))),
                         num=n_bins,
                         endpoint=True)
    r_bins = phys.radius(volume=v_bins)

    histogram_dry = np.empty((len(r_bins) - 1, n_levels))
    histogram_wet = np.empty_like(histogram_dry)

    moment_0 = setup.backend.array(n_cell, dtype=int)
    moments = setup.backend.array((n_moments, n_cell), dtype=float)
    tmp = np.empty(n_cell)
    simulation.reinit()

    # Act (moments)
    simulation.run()
    particles = simulation.particles
    environment = simulation.particles.environment
    rhod = setup.backend.to_ndarray(environment["rhod"]).reshape(
        setup.grid).mean(axis=0)

    for i in range(len(histogram_dry)):
        particles.state.moments(moment_0,
                                moments,
                                specs={},
                                attr_name='dry volume',
                                attr_range=(v_bins[i], v_bins[i + 1]))
        particles.backend.download(moment_0, tmp)
        histogram_dry[i, :] = tmp.reshape(
            setup.grid).sum(axis=0) / (particles.mesh.dv * setup.grid[0])

        particles.state.moments(moment_0,
                                moments,
                                specs={},
                                attr_name='volume',
                                attr_range=(v_bins[i], v_bins[i + 1]))
        particles.backend.download(moment_0, tmp)
        histogram_wet[i, :] = tmp.reshape(
            setup.grid).sum(axis=0) / (particles.mesh.dv * setup.grid[0])

    # Plot
    if plot:
        for level in range(0, n_levels):
            color = str(.5 * (2 + (level / (n_levels - 1))))
            pyplot.step(r_bins[:-1] * si.metres / si.micrometres,
                        histogram_dry[:, level] / si.metre**3 *
                        si.centimetre**3,
                        where='post',
                        color=color,
                        label="level " + str(level))
            pyplot.step(r_bins[:-1] * si.metres / si.micrometres,
                        histogram_wet[:, level] / si.metre**3 *
                        si.centimetre**3,
                        where='post',
                        color=color,
                        linestyle='--')
        pyplot.grid()
        pyplot.xscale('log')
        pyplot.xlabel('particle radius [µm]')
        pyplot.ylabel('concentration per bin [cm^{-3}]')
        pyplot.legend()
        pyplot.show()

    # Assert - location of maximum
    for level in range(n_levels):
        real_max = setup.spectrum_per_mass_of_dry_air.distribution_params[2]
        idx_max_dry = np.argmax(histogram_dry[:, level])
        idx_max_wet = np.argmax(histogram_wet[:, level])
        assert r_bins[idx_max_dry] < real_max < r_bins[idx_max_dry + 1]
        assert idx_max_dry < idx_max_wet

    # Assert - total number
    for level in reversed(range(n_levels)):
        mass_conc_dry = np.sum(histogram_dry[:, level]) / rhod[level]
        mass_conc_wet = np.sum(histogram_wet[:, level]) / rhod[level]
        mass_conc_STP = setup.spectrum_per_mass_of_dry_air.norm_factor
        assert .5 * mass_conc_STP < mass_conc_dry < 1.5 * mass_conc_STP
        np.testing.assert_approx_equal(mass_conc_dry, mass_conc_wet)

    # Assert - decreasing number density
    total_above = 0
    for level in reversed(range(n_levels)):
        total_below = np.sum(histogram_dry[:, level])
        assert total_below > total_above
        total_above = total_below