Exemple #1
0
def test_export(backend_class, tmp_path):
    # Arrange
    settings = Settings()
    settings.simulation_time = settings.dt
    settings.output_interval = settings.dt

    storage = Storage()
    simulator = Simulation(settings,
                           storage,
                           SpinUp=SpinUp,
                           backend_class=backend_class)
    _, temp_file = tempfile.mkstemp(dir=tmp_path, suffix='.nc')
    sut = NetCDFExporter(storage, settings, simulator, temp_file)

    vtk_exporter = VTKExporter(path=tmp_path)

    simulator.reinit()
    simulator.run(vtk_exporter=vtk_exporter)

    vtk_exporter.write_pvd()

    # Act
    sut.run(controller=DummyController())

    # Assert
    filenames_list = os.listdir(os.path.join(tmp_path, 'output'))
    assert len(list(filter(lambda x: x.endswith('.pvd'), filenames_list))) > 0
    assert len(list(filter(lambda x: x.endswith('.vts'), filenames_list))) > 0
    assert len(list(filter(lambda x: x.endswith('.vtu'), filenames_list))) > 0
Exemple #2
0
def test_spin_up(backend, fastmath, plot=False):
    # Arrange
    settings = Settings(fastmath=fastmath)
    settings.dt = .5 * si.second
    settings.grid = (3, 25)
    settings.simulation_time = 20 * settings.dt
    settings.output_interval = 1 * settings.dt

    storage = DummyStorage()
    simulation = Simulation(settings, storage, SpinUp=SpinUp, backend=backend)
    simulation.reinit()

    # Act
    simulation.run()

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

    # Assert
    step_num = len(storage.profiles) - 1
    for step in range(step_num):
        next = storage.profiles[step + 1]["qv_env"]
        prev = storage.profiles[step]["qv_env"]
        eps = 1e-3
        assert ((prev + eps) >= next).all()
    assert storage.profiles[step_num]["qv_env"][-1] < 7.1
Exemple #3
0
def test_just_do_it():
    settings = ColdCumulus()
    settings.kappa = 0
    for process in settings.processes.keys():
        settings.processes[process] = False
    settings.processes['particle advection'] += 1
    settings.processes['fluid advection'] += 1
    simulation = Simulation(settings, Storage(), None)
    simulation.reinit()
    simulation.run(controller=FlowFieldAsserts(simulation))
Exemple #4
0
def main():
    settings = Settings(Formulae())

    settings.n_sd_per_gridbox = 25
    settings.grid = (25, 25)
    settings.simulation_time = 5400 * si.second

    storage = Storage()
    simulation = Simulation(settings, storage, SpinUp)
    simulation.reinit()
    simulation.run()
    temp_file = TemporaryFile(".nc")
    exporter = NetCDFExporter(storage, settings, simulation, temp_file.absolute_path)
    exporter.run(controller=DummyController())
Exemple #5
0
def test_freezing(singular):
    # Arrange
    settings = Settings(
        Formulae(seed=44,
                 condensation_coordinate='VolumeLogarithm',
                 fastmath=True,
                 freezing_temperature_spectrum='Niemand_et_al_2012',
                 heterogeneous_ice_nucleation_rate='ABIFM',
                 constants={
                     'NIEMAND_A': -0.517,
                     'NIEMAND_B': 8.934,
                     'ABIFM_M': 28.13797,
                     'ABIFM_C': -2.92414
                 }))
    settings.dt = .5 * si.second
    settings.grid = (5, 15)
    settings.n_sd_per_gridbox = 64

    settings.simulation_time = 100 * settings.dt
    settings.spin_up_time = 10 * settings.dt

    settings.output_interval = settings.dt  # settings.simulation_time

    settings.processes['freezing'] = True
    settings.processes['coalescence'] = False

    settings.freezing_singular = singular
    settings.th_std0 -= 35 * si.K
    settings.qv0 -= 7.15 * si.g / si.kg

    storage = DummyStorage()
    simulation = Simulation(settings,
                            storage,
                            SpinUp=SpinUp,
                            backend_class=CPU)
    simulation.reinit()

    # Act
    simulation.run()

    # Assert
    assert (simulation.products['ice water content'].get() > 0).any()
Exemple #6
0
def main():
    settings = Settings(Formulae())

    settings.grid = (25, 25)
    settings.simulation_time = settings.dt * 100
    settings.output_interval = settings.dt * 10
    settings.processes = {
        "particle advection": True,
        "fluid advection": True,
        "coalescence": True,
        "condensation": False,
        "sedimentation": True,
        "freezing": False,
    }

    n_sd = range(14, 16, 1)

    times = {}
    backends = [(CPU, "sync"), (CPU, "async")]
    if GPU.ENABLE:
        backends.append((GPU, "async"))
    for backend, mode in backends:
        if backend is CPU:
            PySDM.backends.impl_numba.conf.NUMBA_PARALLEL = mode
            reload_cpu_backend()
        key = f"{backend} (mode={mode})"
        times[key] = []
        for sd in n_sd:
            settings.n_sd_per_gridbox = sd
            storage = Storage()
            simulation = Simulation(settings, storage, None, backend)
            simulation.reinit(products=[WallTime()])
            simulation.run()
            times[key].append(storage.load("wall time")[-1])

    for parallelization, t in times.items():
        plt.plot(n_sd, t, label=parallelization)
    plt.legend()
    plt.loglog()
    plt.savefig("benchmark.pdf", format="pdf")
def test_environment():
    # Arrange
    settings = Settings()
    settings.simulation_time = -1 * settings.dt
    simulation = Simulation(settings, None, SpinUp=SpinUp)
    simulation.reinit()

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

    # Assert - same in all columns
    for column in range(settings.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(settings.grid[1]):
        rhod_above = rhod[0, level]
        assert rhod_above < rhod_below
        rhod_below = rhod_above
def test_initialisation(backend, plot=False):
    settings = Settings()
    settings.simulation_time = -1 * settings.dt
    settings.grid = (10, 5)
    settings.n_sd_per_gridbox = 5000

    simulation = Simulation(settings, None, SpinUp=SpinUp, backend=backend)

    n_levels = settings.grid[1]
    n_cell = int(np.prod(np.array(settings.grid)))
    n_moments = 1

    r_bins = settings.r_bins_edges

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

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

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

    v_bins = settings.formulae.trivia.volume(settings.r_bins_edges)

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

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

    # Plot
    if plot:
        for level in range(0, n_levels):
            color = str(.75 * (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 - 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 = settings.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,
                                       significant=5)

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