Пример #1
0
    def test_plot_domain_cell_type_no_grid(self, tmp_path):
        p = utilities.yaml_from_dict(tmp_path, 'input.yaml')
        _delta = DeltaModel(input_file=p)

        fig, ax = plt.subplots(figsize=(5, 4))
        _delta.show_attribute('cell_type', grid=False)
        return plt.gcf()
Пример #2
0
    def test_subsidence_in_update(self, tmp_path):
        # create a delta with subsidence parameters
        p = utilities.yaml_from_dict(
            tmp_path, 'input.yaml', {
                'toggle_subsidence': True,
                'subsidence_rate': 1e-8,
                'start_subsidence': 0,
                'save_eta_grids': True,
                'seed': 0
            })
        _delta = DeltaModel(input_file=p)

        # mock the timestep computations
        _delta.solve_water_and_sediment_timestep = mock.MagicMock()

        assert _delta.dt == 25000
        assert _delta.subsidence_rate == 1e-8
        assert np.all(
            _delta.sigma[:_delta.L0, :] == 0.0)  # outside the sigma mask
        assert np.all(
            _delta.sigma[_delta.L0:, :] == 0.00025)  # inside the sigma mask
        assert np.all(_delta.eta[_delta.L0:, :] == -_delta.h0)

        _delta.update()
        assert np.all(_delta.eta[_delta.L0 - 1, :25] == 0.0)
        assert np.all(_delta.eta[_delta.L0:, :] == pytest.approx(-_delta.h0 -
                                                                 0.00025))
        _delta.output_netcdf.close()
Пример #3
0
    def test_plot_domain_velocity(self, tmp_path):
        p = utilities.yaml_from_dict(tmp_path, 'input.yaml')
        _delta = DeltaModel(input_file=p)

        fig, ax = plt.subplots(figsize=(5, 4))
        _delta.show_attribute('ux')
        return plt.gcf()
Пример #4
0
    def test_setting_getting_bedload_fraction(self, tmp_path):
        p = utilities.yaml_from_dict(tmp_path, 'input.yaml')
        _delta = DeltaModel(input_file=p)

        assert _delta.bedload_fraction == 0.5
        _delta.bedload_fraction = 0.25
        assert _delta.bedload_fraction == 0.25
Пример #5
0
    def test_setting_getting_sea_surface_elevation_change(self, tmp_path):
        p = utilities.yaml_from_dict(tmp_path, 'input.yaml')
        _delta = DeltaModel(input_file=p)

        assert _delta.sea_surface_elevation_change == 0
        _delta.sea_surface_elevation_change = 0.002
        assert _delta.sea_surface_elevation_change == 0.002
Пример #6
0
    def test_solve_water_and_sediment_timestep_itermax_10(self, tmp_path):
        # create a delta with different itermax
        p = utilities.yaml_from_dict(tmp_path, 'input.yaml', {'itermax': 10})
        delta = DeltaModel(input_file=p)

        # mock top-level methods, verify call was made to each
        delta.log_info = mock.MagicMock()
        delta.init_water_iteration = mock.MagicMock()
        delta.run_water_iteration = mock.MagicMock()
        delta.compute_free_surface = mock.MagicMock()
        delta.finalize_water_iteration = mock.MagicMock()
        delta.route_sediment = mock.MagicMock()

        # run the timestep
        delta.solve_water_and_sediment_timestep()

        # assert that methods are called
        assert delta.init_water_iteration.called is True
        assert delta.run_water_iteration.called is True
        assert delta.compute_free_surface.called is True
        assert delta.finalize_water_iteration.called is True
        _calls = [mock.call(i) for i in range(10)]
        delta.finalize_water_iteration.assert_has_calls(_calls,
                                                        any_order=False)
        assert delta.finalize_water_iteration.call_count == 10
        assert (delta.route_sediment.called is True)
        assert (delta._is_finalized is False)
Пример #7
0
    def test_save_sedflux_grids(self, tmp_path):
        p = utilities.yaml_from_dict(tmp_path, 'input.yaml', {
            'save_dt': 1,
            'save_sedflux_grids': True
        })
        _delta = DeltaModel(input_file=p)

        # mock the log_info
        _delta.log_info = mock.MagicMock()

        exp_path_nc = os.path.join(tmp_path / 'out_dir',
                                   'pyDeltaRCM_output.nc')
        assert os.path.isfile(exp_path_nc)

        for _t in range(0, 6):
            _delta.save_grids('sedflux', _delta.qs, _delta._save_iter)
            _delta._save_iter += 1

        # close the file and connect
        _delta.output_netcdf.close()
        ds = netCDF4.Dataset(exp_path_nc, "r", format="NETCDF4")

        # assertions
        assert (_delta.log_info.call_count == 6)
        _arr = ds.variables['sedflux']
        assert _arr.shape[1] == _delta.qs.shape[0]
        assert _arr.shape[2] == _delta.qs.shape[1]
        assert ('meta' in ds.groups)  # if any grids, save meta too
Пример #8
0
    def test_plot_domain_withlabel(self, tmp_path):
        p = utilities.yaml_from_dict(tmp_path, 'input.yaml')
        _delta = DeltaModel(input_file=p)

        fig, ax = plt.subplots(figsize=(5, 4))
        # This is a weak test, but it triggers coverage of the label lines.
        _delta.show_attribute('ux', label='')
        return plt.gcf()
Пример #9
0
    def test_h0(self, tmp_path):
        p = utilities.yaml_from_dict(tmp_path, 'input.yaml', {'h0': 7.5})
        _delta = DeltaModel(input_file=p)
        assert _delta.h0 == 7.5

        p = utilities.yaml_from_dict(tmp_path, 'input.yaml', {'h0': int(7)})
        _delta = DeltaModel(input_file=p)
        assert _delta.h0 == 7
Пример #10
0
    def test_plot_attribute_bad_shape_3d(self, tmp_path):
        p = utilities.yaml_from_dict(tmp_path, 'input.yaml')
        _delta = DeltaModel(input_file=p)

        # not sure if there are any 3d arrays actually, so just make a fake one
        _delta.threedeearray = np.zeros((10, 10, 2))
        with pytest.raises(ValueError):
            _delta.show_attribute('threedeearray')
Пример #11
0
    def test_plot_domain_cell_type_single_index(self, tmp_path):
        p = utilities.yaml_from_dict(tmp_path, 'input.yaml')
        _delta = DeltaModel(input_file=p)

        fig, ax = plt.subplots(figsize=(5, 4))
        ax.imshow(_delta.cell_type, interpolation='none')
        ax.autoscale(False)
        _delta.show_ind(2200)
        return plt.gcf()
Пример #12
0
    def test_plot_domain_cell_type_list_mix_tuple_index(self, tmp_path):
        p = utilities.yaml_from_dict(tmp_path, 'input.yaml')
        _delta = DeltaModel(input_file=p)

        fig, ax = plt.subplots(figsize=(5, 4))
        ax.imshow(_delta.cell_type, interpolation='none')
        ax.autoscale(False)
        _delta.show_ind([(15, 55), (15, 65), 1275, 1295, 2250])
        return plt.gcf()
Пример #13
0
 def test_no_clobber_error(self, tmp_path):
     p = utilities.yaml_from_dict(tmp_path, 'input.yaml',
                                  {'save_eta_grids': True})
     _model_1 = DeltaModel(input_file=p)
     _model_1.output_netcdf.close()
     # assert that model could not have clobbered a netcdf
     assert _model_1._clobber_netcdf is False
     # make a second model which raises error
     with pytest.raises(FileExistsError):
         _ = DeltaModel(input_file=p)
Пример #14
0
    def test_save_no_figs_no_grids(self, tmp_path):
        p = utilities.yaml_from_dict(tmp_path, 'input.yaml', {'save_dt': 1})
        _delta = DeltaModel(input_file=p)

        # mock the log_info
        _delta.log_info = mock.MagicMock()

        # mock the actual output routines
        _delta.make_figure = mock.MagicMock()
        _delta.save_figure = mock.MagicMock()
        _delta.save_grids = mock.MagicMock()

        # check nothing created at the start
        _delta.make_figure.call_count == 0
        _delta.save_figure.call_count == 0
        _delta.save_grids.call_count == 0

        # update the delta a few times
        for _t in range(0, 4):
            _delta._time = (_t * _delta._dt)
            _delta.save_grids_and_figs()

        # check nothing after a number of iterations, greater than dt
        assert _delta._time > _delta.save_dt
        _delta.make_figure.call_count == 0
        _delta.save_figure.call_count == 0
        _delta.save_grids.call_count == 0
Пример #15
0
    def test_getter_nosetter_water_depth(self, tmp_path):
        p = utilities.yaml_from_dict(tmp_path, 'input.yaml')
        _delta = DeltaModel(input_file=p)

        # check that one is alias of other
        assert np.all(_delta.water_depth == _delta.depth)
        assert (_delta.water_depth is _delta.depth)

        # setter should return error, not allowed
        with pytest.raises(AttributeError):
            _delta.water_depth = np.random.uniform(0, 1, size=_delta.eta.shape)
Пример #16
0
def test_time_from_log_new(tmp_path):
    """Generate run+logfile and then read runtime from it."""
    from pyDeltaRCM.model import DeltaModel
    delta = DeltaModel(out_dir=str(tmp_path))  # init delta to make log file
    time.sleep(1)
    delta.finalize()  # finalize and end log file
    log_path = os.path.join(tmp_path, os.listdir(tmp_path)[0])  # path to log
    elapsed_time = utils.runtime_from_log(log_path)
    # elapsed time should exceed 0, but exact time will vary
    assert isinstance(elapsed_time, float)
    assert elapsed_time > 0
Пример #17
0
    def test_update_is_finalized(self, tmp_path):
        # create a delta with different itermax
        p = utilities.yaml_from_dict(tmp_path, 'input.yaml')
        _delta = DeltaModel(input_file=p)

        # change state to finalized
        _delta._is_finalized = True

        # run the timestep
        with pytest.raises(RuntimeError):
            _delta.update()
Пример #18
0
    def test_show_line_set_points(self, tmp_path):
        p = utilities.yaml_from_dict(tmp_path, 'input.yaml')
        _delta = DeltaModel(input_file=p)

        fig, ax = plt.subplots(figsize=(5, 4))
        np.random.seed(0)
        _delta.free_surf_walk_inds = np.tile(
            np.arange(100, 2900, step=_delta.eta.shape[1]), (12, 1))
        _shape = _delta.free_surf_walk_inds.shape
        _delta.free_surf_walk_inds += np.random.randint(-5, 5, size=_shape)

        _delta.show_line(_delta.free_surf_walk_inds.T, multiline=True, ax=ax)
        return plt.gcf()
Пример #19
0
    def test_save_metadata_no_grids(self, tmp_path):
        p = utilities.yaml_from_dict(tmp_path, 'input.yaml', {
            'save_dt': 1,
            'save_metadata': True
        })
        _delta = DeltaModel(input_file=p)

        # mock the log_info
        _delta.log_info = mock.MagicMock()

        # mock the actual output routines
        _delta.make_figure = mock.MagicMock()
        _delta.save_figure = mock.MagicMock()
        _delta.save_grids = mock.MagicMock()

        exp_path_nc = os.path.join(tmp_path / 'out_dir',
                                   'pyDeltaRCM_output.nc')
        assert os.path.isfile(exp_path_nc)

        for _t in range(0, 3):
            _delta.save_grids_and_figs()
            _delta._save_iter += 1

        # close the file and connect
        _delta.output_netcdf.close()
        ds = netCDF4.Dataset(exp_path_nc, "r", format="NETCDF4")

        # assertions
        assert not ('eta' in ds.variables)
        assert ds['meta']['H_SL'].shape[0] == 4  # init + 3
        assert ds['meta']['L0'][:] == 3
Пример #20
0
 def test_clobbering(self, tmp_path):
     p = utilities.yaml_from_dict(tmp_path, 'input.yaml', {
         'clobber_netcdf': True,
         'save_eta_grids': True
     })
     _model_1 = DeltaModel(input_file=p)
     _model_1.output_netcdf.close()
     # assert that model could have clobbered a netcdf
     assert _model_1._clobber_netcdf is True
     # make a second model which clobbers, raising eyebrows (and warning)
     with pytest.warns(UserWarning):
         _model_2 = DeltaModel(input_file=p)
     _model_2.output_netcdf.close()
     assert _model_2._clobber_netcdf is True
Пример #21
0
    def test_save_one_fig_no_grids(self, tmp_path):
        p = utilities.yaml_from_dict(tmp_path, 'input.yaml', {
            'save_dt': 1,
            'save_eta_figs': True
        })
        _delta = DeltaModel(input_file=p)

        # mock the log_info
        _delta.log_info = mock.MagicMock()

        # mock the actual output routines
        _delta.make_figure = mock.MagicMock()
        _delta.save_figure = mock.MagicMock()
        _delta.save_grids = mock.MagicMock()

        # check nothing created at the start
        _delta.make_figure.call_count == 0
        _delta.save_figure.call_count == 0
        _delta.save_grids.call_count == 0

        assert (len(_delta._save_fig_list) > 0)
        assert (_delta._save_eta_figs is True)

        # update the delta a few times
        for _t in range(0, 5):
            _delta.save_grids_and_figs()
            _delta._save_iter += 1

        _delta.make_figure.call_count == 5
        _delta.save_figure.call_count == 5
        _delta.save_grids.call_count == 0
Пример #22
0
    def test_save_one_fig_one_grid(self, tmp_path):
        p = utilities.yaml_from_dict(tmp_path, 'input.yaml', {
            'save_dt': 1,
            'save_eta_grids': True,
            'save_discharge_figs': True
        })
        _delta = DeltaModel(input_file=p)

        # mock the log_info
        _delta.log_info = mock.MagicMock()

        # mock the actual output routines
        _delta.make_figure = mock.MagicMock()
        _delta.save_figure = mock.MagicMock()
        _delta.save_grids = mock.MagicMock()

        assert (_delta._save_eta_grids is True)
        assert (_delta._save_metadata is True)

        # check for the netcdf file
        exp_path_nc = os.path.join(tmp_path / 'out_dir',
                                   'pyDeltaRCM_output.nc')
        assert os.path.isfile(exp_path_nc)
        nc_size_before = os.path.getsize(exp_path_nc)
        assert nc_size_before > 0  # saved once already / inited

        # update a couple times, should increase on each save
        for _t in range(0, 5):
            _delta.save_grids_and_figs()
            _delta._save_iter += 1

        _delta.make_figure.call_count == 5
        _delta.save_figure.call_count == 5
        _delta.save_grids.call_count == 5
Пример #23
0
 def test_W(self, tmp_path):
     p = utilities.yaml_from_dict(tmp_path, 'input.yaml', {
         'Width': 1200,
         'dx': 20
     })
     _delta = DeltaModel(input_file=p)
     assert _delta.W == 60
Пример #24
0
    def test_logger_random_seed_always_recorded(self, tmp_path):
        file_name = 'user_parameters.yaml'
        p, f = utilities.create_temporary_file(tmp_path, file_name)
        utilities.write_parameter_to_file(f, 'out_dir', tmp_path / 'out_dir')
        utilities.write_parameter_to_file(f, 'verbose', 0)
        # do not set the seed explicitly, let it be set by the model
        f.close()
        delta = DeltaModel(input_file=p)
        _logs = glob.glob(os.path.join(delta.prefix, '*.log'))
        assert len(_logs) == 1  # log file exists
        with open(_logs[0], 'r') as _logfile:
            _lines = _logfile.readlines()
            _joinedlines = ' '.join(_lines)  # collapse to a single string
            assert 'Random seed is: ' in _joinedlines

            # determine the index of the line
            _idx = ['Random seed is: ' in _l for _l in _lines]
            assert sum(_idx) == 1  # one and only one True in list
            _idx = _idx.index(True)

            # try to covert to int, otherwise fail
            _seed = _lines[_idx].split(':')[-1]  # pull the seed value
            try:
                _intseed = int(_seed)
            except ValueError:
                raise ValueError('Could not convert the seed to int')

            assert _intseed >= 0
Пример #25
0
    def test_subsidence_changed_with_timestep(self, tmp_path):
        # create a delta with subsidence parameters
        p = utilities.yaml_from_dict(
            tmp_path, 'input.yaml', {
                'toggle_subsidence': True,
                'save_eta_grids': True,
                'subsidence_rate': 1e-8
            })
        _delta = DeltaModel(input_file=p)

        assert _delta.dt == 25000
        assert np.all(_delta.sigma[_delta.L0:, :] == 0.00025)
        # use the model setter to adjust the timestep
        _delta.time_step = 86400
        assert np.all(_delta.sigma[_delta.L0:, :] == 0.000864)
        _delta.output_netcdf.close()
Пример #26
0
 def test_V0(self, tmp_path):
     p = utilities.yaml_from_dict(tmp_path, 'input.yaml', {
         'h0': 3,
         'dx': 15
     })
     _delta = DeltaModel(input_file=p)
     assert _delta.V0 == 675
Пример #27
0
 def test_U_ero_mud(self, tmp_path):
     p = utilities.yaml_from_dict(tmp_path, 'input.yaml', {
         'coeff_U_ero_mud': 1.67,
         'u0': 2.2
     })
     _delta = DeltaModel(input_file=p)
     assert _delta.U_ero_mud == 3.674
Пример #28
0
    def test_logger_has_initialization_lines(self, tmp_path):
        file_name = 'user_parameters.yaml'
        p, f = utilities.create_temporary_file(tmp_path, file_name)
        utilities.write_parameter_to_file(f, 'out_dir', tmp_path / 'out_dir')
        utilities.write_parameter_to_file(f, 'verbose', 1)
        utilities.write_parameter_to_file(f, 'seed', 10)
        f.close()
        _delta = DeltaModel(input_file=p)

        _logs = glob.glob(os.path.join(_delta.prefix, '*.log'))
        assert len(_logs) == 1  # log file exists
        with open(_logs[0], 'r') as _logfile:
            _lines = _logfile.readlines()
            _lines = ' '.join(_lines)  # collapse to a single string
            assert 'Setting model constants' in _lines
            assert 'Random seed is: 10' in _lines
            assert 'Creating model domain' in _lines
            assert 'Initializing output NetCDF4 file' in _lines
            assert 'Model initialization complete' in _lines

            if sys.platform.startswith('linux'):
                assert 'Platform: Linux-' in _lines
            elif sys.platform == 'darwin':
                guess1 = 'Platform: Darwin-' in _lines
                guess2 = 'Platform: macOS-' in _lines
                assert (guess1 | guess2)
            elif sys.platform.startswith('win'):
                assert 'Platform: Windows-' in _lines
            else:
                raise RuntimeError('Platform type not recognized.')
        assert not os.path.isfile(
            os.path.join(tmp_path, 'out_dir', 'discharge_0.0.png'))
        assert not os.path.isfile(
            os.path.join(tmp_path, 'out_dir', 'eta_0.0.png'))
Пример #29
0
 def test_L(self, tmp_path):
     p = utilities.yaml_from_dict(tmp_path, 'input.yaml', {
         'Length': 1600,
         'dx': 20
     })
     _delta = DeltaModel(input_file=p)
     assert _delta.L == 80
Пример #30
0
 def test_qw0(self, tmp_path):
     p = utilities.yaml_from_dict(tmp_path, 'input.yaml', {
         'u0': 0.8,
         'h0': 3
     })
     _delta = DeltaModel(input_file=p)
     assert _delta.qw0 == pytest.approx(2.4)