Ejemplo n.º 1
0
def get_params_from_input_file(filename):
    """Fetch parameter values from input file."""
    from landlab.core import load_params

    mpd_params = load_params(filename)

    return mpd_params
Ejemplo n.º 2
0
def get_params_from_input_file(filename):
    """Fetch parameter values from input file."""
    from landlab.core import load_params
    
    mpd_params = load_params(filename)

    return mpd_params
Ejemplo n.º 3
0
def test_from_yaml_path(tmpdir):
    """Load parameters from YAML-formatted string."""
    with tmpdir.as_cwd():
        with open('params.txt', 'w') as fp:
            fp.write(MPD_PARAMS_STR)
        params = load_params('./params.txt')
    assert params == MPD_PARAMS
    assert isinstance(params['x'], float)
    assert isinstance(params['y'], int)
Ejemplo n.º 4
0
def test_from_yaml_path():
    """Load parameters from YAML-formatted string."""
    with cdtemp() as dir:
        with open('params.txt', 'w') as fp:
            fp.write(MPD_PARAMS_STR)
        params = load_params('./params.txt')
    assert_dict_equal(params, MPD_PARAMS)
    assert_is_instance(params['x'], float)
    assert_is_instance(params['y'], int)
Ejemplo n.º 5
0
def test_from_yaml_path():
    """Load parameters from YAML-formatted string."""
    with cdtemp() as dir:
        with open('params.txt', 'w') as fp:
            fp.write(MPD_PARAMS_STR)
        params = load_params('./params.txt')
    assert_dict_equal(params, MPD_PARAMS)
    assert_is_instance(params['x'], float)
    assert_is_instance(params['y'], int)
Ejemplo n.º 6
0
def test_from_mpd_path(tmpdir):
    """Load parameters from YAML-formatted string."""
    with tmpdir.as_cwd():
        with open("params.txt", "w") as fp:
            fp.write(MPD_PARAMS_STR)
        params = load_params("./params.txt")
    assert params == MPD_PARAMS
    assert isinstance(params["x"], float)
    assert isinstance(params["y"], int)
Ejemplo n.º 7
0
def test_marmara(tmpdir, datadir):
    with tmpdir.as_cwd():
        for fname in datadir.iterdir():
            shutil.copy(str(datadir / fname), ".")
        params = load_params("marmara.yaml")
        model = SequenceModel(**params)
        model.run()

        assert os.path.isfile("marmara.nc")
Ejemplo n.º 8
0
def load_model_params(param_file=None, defaults=None, dotted_params=()):
    params = defaults or {}

    if param_file:
        params_from_file = load_params(param_file)
        dotted_params += dict_to_dots(params_from_file) + dotted_params
        for group in params.keys():
            params[group].update(params_from_file.get(group, {}))

    params_from_cl = load_params_from_strings(dotted_params)
    for group in params.keys():
        params[group].update(params_from_cl.get(group, {}))

    return params
Ejemplo n.º 9
0
def test_from_mpd_file_like():
    """Load parameters from YAML-formatted string."""
    params = load_params(StringIO(MPD_PARAMS_STR))
    assert params == MPD_PARAMS
    assert isinstance(params["x"], float)
    assert isinstance(params["y"], int)
Ejemplo n.º 10
0
def test_from_yaml_string():
    """Load parameters from YAML-formatted string."""
    params = load_params(YAML_PARAMS_STR)
    assert params == YAML_PARAMS
    assert isinstance(params["x"], float)
    assert isinstance(params["y"], int)
Ejemplo n.º 11
0
    def initialize(self, input_file_name):
        """Initialize by reading parameters from input file."""
        params = load_params(input_file_name)
        settling_rate = np.sqrt(
            params['cell_size'] * params['grav_accel'] / 2.0) * SEC_PER_YEAR
        self.run_duration = params['run_duration']
        self.output_name = params['output_name']
        if 'uplift_duration' in params:
            self.uplift_duration = params['uplift_duration']
        else:
            self.uplift_duration = self.run_duration

        if 'include_blocks' in params and params['include_blocks']:
            if 'y0_top' in params:
                y0_top = params['y0_top']
            else:
                y0_top = 0.0
            if 'layer_left_x' in params:
                layer_left_x = params['layer_left_x']
            else:
                layer_left_x = 0.0
            self.model = BlockHill(
                (params['number_of_node_rows'],
                 params['number_of_node_columns']),
                report_interval=params['report_interval'],
                run_duration=self.run_duration,
                output_interval=params['output_interval'],
                settling_rate=settling_rate,
                disturbance_rate=params['disturbance_rate'],
                weathering_rate=params['weathering_rate'],
                uplift_interval=params['uplift_interval'],
                plot_interval=params['plot_interval'],
                friction_coef=params['friction_coef'],
                rock_state_for_uplift=params['rock_state_for_uplift'],
                opt_rock_collapse=params['opt_rock_collapse'],
                show_plots=params['show_plots'],
                initial_state_grid=None,
                opt_track_grains=params['opt_track_grains'],
                block_layer_dip_angle=params['block_layer_dip_angle'],
                block_layer_thickness=params['block_layer_thickness'],
                y0_top=y0_top,
                layer_left_x=layer_left_x,
                cmap=get_block_hill_colormap())
            self.cmap = get_block_hill_colormap()  # use special colormap
        else:
            self.model = GrainHill(
                (params['number_of_node_rows'],
                 params['number_of_node_columns']),
                report_interval=params['report_interval'],
                run_duration=self.run_duration,
                output_interval=params['output_interval'],
                settling_rate=settling_rate,
                disturbance_rate=params['disturbance_rate'],
                weathering_rate=params['weathering_rate'],
                uplift_interval=params['uplift_interval'],
                plot_interval=params['plot_interval'],
                friction_coef=params['friction_coef'],
                rock_state_for_uplift=params['rock_state_for_uplift'],
                opt_rock_collapse=params['opt_rock_collapse'],
                show_plots=params['show_plots'],
                initial_state_grid=None,
                opt_track_grains=params['opt_track_grains'])
            self.cmap = None  # use default GrainHill colormap

        if params['plot_to_file']:
            self.file_plot_interval = params['plot_interval']
        else:
            self.file_plot_interval = self.run_duration
        self.plot_number = 0

        self.find_or_create_output_folder()

        self.initialized = True
Ejemplo n.º 12
0
def test_from_yaml_file_like():
    """Load parameters from YAML-formatted string."""
    params = load_params(StringIO(MPD_PARAMS_STR))
    assert_dict_equal(params, MPD_PARAMS)
    assert_is_instance(params['x'], float)
    assert_is_instance(params['y'], int)
Ejemplo n.º 13
0
def test_from_yaml_file_like():
    """Load parameters from YAML-formatted string."""
    params = load_params(StringIO(YAML_PARAMS_STR))
    assert params == YAML_PARAMS
    assert isinstance(params['x'], float)
    assert isinstance(params['y'], int)
def two_node_diff(a):
    """Calculate and return diffs over two nodes instead of one."""
    N = len(a)
    return a[2:] - a[:(N - 2)]


dx = 0.1  # assumed node spacing, m

input_file_template = '../my_inputs.template'
input_file = 'my_inputs.txt'

# Run dprepro to get right value into the file my_inputs.txt
call(['dprepro', sys.argv[1], input_file_template, input_file])

# Read parameters from the input file
params = load_params(input_file)

domain_length = 10.0**params['number_of_node_columns']
num_cols = int(np.round(domain_length / (dx * 0.866) + 1))
num_rows = int(np.round(0.5 * domain_length / dx))
params['number_of_node_columns'] = num_cols
params['number_of_node_rows'] = num_rows
params['disturbance_rate'] = 10.0**params['disturbance_rate']
params['uplift_interval'] = 10.0**params['uplift_interval']
params['run_duration'] = 0.5 * domain_length * params['uplift_interval'] / dx
params['plot_interval'] = 1.1 * params['run_duration']
params['output_interval'] = params['run_duration']

print params

# Run the model
Ejemplo n.º 15
0
def test_from_yaml_file_like():
    """Load parameters from YAML-formatted string."""
    params = load_params(StringIO(MPD_PARAMS_STR))
    assert_dict_equal(params, MPD_PARAMS)
    assert_is_instance(params['x'], float)
    assert_is_instance(params['y'], int)
Ejemplo n.º 16
0
def test_from_mpd_string():
    """Load parameters from YAML-formatted string."""
    params = load_params(MPD_PARAMS_STR)
    assert_dict_equal(params, MPD_PARAMS)
    assert_is_instance(params['x'], float)
    assert_is_instance(params['y'], int)
Ejemplo n.º 17
0
def test_from_mpd_string():
    """Load parameters from YAML-formatted string."""
    params = load_params(MPD_PARAMS_STR)
    assert params == MPD_PARAMS
    assert isinstance(params['x'], float)
    assert isinstance(params['y'], int)
Ejemplo n.º 18
0
def create_grid(file_like):
    """Create grid, initialize fields, and set boundary conditions.

    **create_grid** expects a dictionary with three keys: "grid", "fields", and
    "boundary_conditions".

    **Dictionary Section "grid"**

    The value associated with the "grid" key should itself be a dictionary
    containing the name of a Landlab model grid type as its only key. The
    following grid types are valid:

        -  :py:class:`~landlab.grid.raster.RasterModelGrid`
        -  :py:class:`~landlab.grid.voronoi.VoronoiDelaunayGrid`
        -  :py:class:`~landlab.grid.hex.HexModelGrid`
        -  :py:class:`~landlab.grid.radial.RadialModelGrid`
        -  :py:class:`~landlab.grid.network.NetworkModelGrid`

    The value associated with the grid name key is a list containing the
    arguments. If any keyword arguments are passed, they should be passed as
    the last element of the list. For example the following code block is a
    yaml file indicating a RasterModelGrid with shape (4, 5) and xy-spacing of
    (3, 4).

    .. code-block:: yaml

        grid:
          RasterModelGrid:
            - [4, 5]
            - xy_spacing: [3, 4]

    These arguments and keyword arguments will be passed to the ``__init__``
    constructor of the specified model grid. Refer to the documentation for
    each grid to determine its requirements.

    **Dictionary Section "fields"**

    Fields can be created by reading from files or by creating synthetic
    values.

    The value associated with the "fields" key is a nested set of dictionaries
    indicating where the fields are created, what the field names are, and how
    to create the fields. At the highest hierachical level, the value
    associated with the "fields" key must be a dictionary with keys indicating
    at which grid elements fields should be created (e.g. to create fields at
    node, use "at_node").

    The value associated with each "at_xxx" value is itself a dictionary
    indicating the name of the field an how it should be created. A field can
    either be created by reading from a file or creating synthetic values. The
    :py:func:`~landlab.io.netcdf.read.read_netcdf` and
    :py:func:`~landlab.io.esri_ascii.read_esri_ascii` functions, and the
    :py:mod:`synthetic fields <landlab.values.synthetic>`
    package are currently supported methods to create fields. These may be
    chained together (as is shown in the Example section below). If these
    functions do not meet your needs, we welcome contributions that extend the
    capabilities of this function.

    The following example would uses the
    :py:func:`~landlab.values.synthetic.plane` function from the synthetic
    values package to create an at_node value for the field
    topographic__elevation. The plane function adds values to a Landlab model
    grid field that lie on a plane specified by a point and a normal vector. In
    the below example the plane goes through the point (1.0, 1.0, 1.0) and has
    a normal of (-2.0, -1.0, 1.0).

    .. code-block:: yaml

        fields:
          at_node:
            topographic__elevation:
              plane:
                - point: [1, 1, 1]
                  normal: [-2, -1, 1]

    **Dictionary Section "boundary_conditions"**

    The final portion of the input dictionary calls bound functions of the
    model grid to set boundary conditions. Any valid bound function can be
    called. The specified functions are provided in a list, and called in
    order. If required, multiple functions may be called.

    Each entry to the list is a dictionary with a single key, the name of the
    bound function. The value associated with that key is a list of arguments
    and keyword arguments, similar in structure to those described above.

    For example, the following sets closed boundaries at all sides of the grid.

    .. code-block:: yaml

        boundary_conditions:
          - set_closed_boundaries_at_grid_edges:
            - True
            - True
            - True
            - True

    Parameters
    ----------
    file_like : file_like or str
        Dictionary, contents of a dictionary as a string, a file-like object,
        or the path to a file containing a YAML dictionary.

    Examples
    --------
    >>> import numpy as np
    >>> np.random.seed(42)
    >>> from landlab import create_grid
    >>> p = {'grid': {'RasterModelGrid': [(4,5),
    ...                                   {'xy_spacing': (3, 4)}]
    ...               },
    ...      'fields': {'at_node': {'spam': {'plane': [{'point': (1, 1, 1),
    ...                                                'normal': (-2, -1, 1)}],
    ...                                      'random': [{'distribution': 'uniform',
    ...                                                 'low': 1,
    ...                                                 'high': 4}]
    ...                                      },
    ...                             },
    ...                 'at_link': {'eggs': {'constant': [{'where': 'ACTIVE_LINK',
    ...                                                    'constant': 12}],
    ...                                       },
    ...                             },
    ...                 },
    ...      'boundary_conditions': [
    ...                     {'set_closed_boundaries_at_grid_edges':
    ...                                         [True, True, True, True]
    ...                      }]
    ...      }
    >>> mg = create_grid(p)
    >>> mg.number_of_nodes
    20
    >>> "spam" in mg.at_node
    True
    >>> "eggs" in mg.at_link
    True
    >>> mg.x_of_node
    array([  0.,   3.,   6.,   9.,  12.,
             0.,   3.,   6.,   9.,  12.,
             0.,   3.,   6.,   9.,  12.,
             0.,   3.,   6.,   9.,  12.])
    >>> mg.status_at_node
    array([4, 4, 4, 4, 4,
           4, 0, 0, 0, 4,
           4, 0, 0, 0, 4,
           4, 4, 4, 4, 4], dtype=uint8)
    >>> np.round(mg.at_node['spam'].reshape(mg.shape), decimals=2)
    array([[  0.12,   7.85,  13.2 ,  18.8 ,  23.47],
           [  3.47,   9.17,  17.6 ,  22.8 ,  29.12],
           [  7.06,  15.91,  21.5 ,  25.64,  31.55],
           [ 11.55,  17.91,  24.57,  30.3 ,  35.87]])
    """
    # part 0, parse input
    if isinstance(file_like, dict):
        dict_like = file_like
    else:
        dict_like = load_params(file_like)

    # part 1 create grid
    grid_dict = dict_like.pop("grid", None)
    if grid_dict is None:
        msg = "create_grid: no grid dictionary provided. This is required."
        raise ValueError(msg)

    for grid_type in grid_dict:
        if grid_type in _MODEL_GRIDS:
            grid_class = _MODEL_GRIDS[grid_type]
        else:
            msg = "create_grid: provided grid type not supported."
            raise ValueError

    if len(grid_dict) != 1:
        msg = ("create_grid: two entries to grid dictionary provided. "
               "This is not supported.")
        raise ValueError

    args, kwargs = _parse_args_kwargs(grid_dict.pop(grid_type))
    grid = grid_class(*args, **kwargs)

    # part two, create fields
    fields_dict = dict_like.pop("fields", {})

    # for each grid element:
    for at_group in fields_dict:
        at = at_group[3:]
        if at not in grid.groups:
            msg = (
                "create_grid: No field location ",
                "{at} ".format(at=at),
                "exists for grid types",
                "{grid}. ".format(grid=grid_type),
            )
            raise ValueError(msg)

        at_dict = fields_dict[at_group]
        # for field at grid element
        for name in at_dict:
            name_dict = at_dict[name]

            # for each function, add values.
            for func in name_dict:
                args, kwargs = _parse_args_kwargs(name_dict[func])
                if func in _SYNTHETIC_FIELD_CONSTRUCTORS:
                    # if any args, raise an error, there shouldn't be any.
                    synth_function = _SYNTHETIC_FIELD_CONSTRUCTORS[func]
                    synth_function(grid, name, at=at, **kwargs)
                elif func == "read_esri_ascii":
                    read_esri_ascii(*args, grid=grid, name=name, **kwargs)
                elif func == "read_netcdf":
                    read_netcdf(*args, grid=grid, name=name, **kwargs)
                else:
                    msg = (
                        "create_grid: Bad function ",
                        "{func} ".format(func=func),
                        "for creating a field.",
                    )
                    raise ValueError(msg)

    # part three, set boundary conditions
    bc_list = dict_like.pop("boundary_conditions", [])
    for bc_function_dict in bc_list:
        if len(bc_function_dict) != 1:
            msg = ("create_grid: two entries to a boundary condition function "
                   "dictionary were provided. This is not supported.")
            raise ValueError(msg)
        for bc_function in bc_function_dict:
            args, kwargs = _parse_args_kwargs(bc_function_dict[bc_function])
            methods = dict(inspect.getmembers(grid, inspect.ismethod))
            if bc_function in methods:
                methods[bc_function](*args, **kwargs)
            else:
                msg = (
                    "create_grid: No function ",
                    "{func} ".format(func=bc_function),
                    "exists for grid types ",
                    "{grid}. ".format(grid=grid_type),
                    "If you think this type of grid should have such a ",
                    "function. Please create a GitHub Issue to discuss ",
                    "contributing it to the Landlab codebase.",
                )
                raise ValueError(msg)

    return grid
Ejemplo n.º 19
0
def test_from_mpd_string():
    """Load parameters from YAML-formatted string."""
    params = load_params(MPD_PARAMS_STR)
    assert_dict_equal(params, MPD_PARAMS)
    assert_is_instance(params['x'], float)
    assert_is_instance(params['y'], int)