shared_tools¶
Todo
add paragraph description of the module
The tools are defined in pyDeltaRCM.shared_tools
.
Shared functions¶
This module defines several functions that are used throughout the model, and so are organized here for convenience.
- pyDeltaRCM.shared_tools.get_random_uniform(limit: float) → float¶
Get a random number from the uniform distribution.
Get a random number from the uniform distribution, defined over the interval
[0, limit]
, where limit is an input parameter (usually1
).Hint
Function returns only a single float. Wrap the call in a simple for loop to get many random numbers.
- Parameters:
limit (
float
) – Upper limit to distribution to draw from.- Returns:
Float value from the random number generator in the interval defined.
- Return type:
float
Examples
>>> get_random_uniform(1) 0.5488135039273248 >>> get_random_uniform(0.1) 0.07151893663724194
- pyDeltaRCM.shared_tools.get_inlet_weights(inlet)¶
Get weight for inlet parcels.
This method is called at the top of water and sediment routing steps by default, as implemented in the methods
get_inlet_weights_water
andget_inlet_weights_sediment
.The function determines the weights describing which inlet cells parcels are fed into the domain. As implemented by default, returns “ones” for all inlet cell locations, so that the input sediment source is balanced across all inlet cells. The returned weight array is typically passed to
get_start_indices
to determine the locations to feed parcels into the domain based on the weights determined by this function.- Parameters:
inlet (
ndarray
of int) – Integer array specifying the inlet cell indices.
- pyDeltaRCM.shared_tools.get_start_indices(inlet: ndarray, inlet_weights: ndarray, num_starts: int) → ndarray¶
Get start indices.
Reutrn a randomly generated list of starting points for parcel routing. These starting points are selected from the inlet array.
- Parameters:
inlet (ndarray) – Array of inlet cells.
inlet_weights (ndarray) – Array of weights to select items from
inlet
. Should have same dimensions.num_starts (int) – Number of starting points to generate.
- Returns:
start_indices –
num_starts
starting points, generated frominlet
according to weights in
inlet_weights
.
- Return type:
ndarray
- pyDeltaRCM.shared_tools.get_steps(new_direction: int, iwalk, jwalk) → Tuple[float, int, int, bool]¶
Find the values given the next step.
Get the steps for updating discharge and velocity arrays based on the direction of each step.
- pyDeltaRCM.shared_tools.random_pick(prob)¶
Pick number from weighted array.
Randomly pick a number weighted by array probabilities (len 9) Return the index of the selected weight in array probs Takes a numpy array that is the precalculated probability around the cell flattened to 1D.
Examples
Todo
Examples needed (pull from tests?).
- pyDeltaRCM.shared_tools.custom_unravel(i: int, shape: Tuple[int, int]) → Tuple[int, int]¶
Unravel indexes for 2D array.
This is a jitted function, equivalent to the numpy implementation of unravel_index, but configured to accept only a single integer as the index to unravel.
- Parameters:
i (
int
) – Integer index to unravel.shape (
tuple
ofint
) – Two element tuple of integers indicating the shape of the two-dimensional array from whichi
will be unravelled.
- Returns:
x (
int
) – x index ofi
into array of shapeshape
.y (
int
) – y index ofi
into array of shapeshape
.
Examples
>>> _shape = (100, 200) # e.g., delta.eta.shape >>> np.unravel_index(5124, _shape) (25, 124) >>> custom_unravel(5124, _shape) (25, 124)
- pyDeltaRCM.shared_tools.custom_ravel(tup: Tuple[int, int], shape: Tuple[int, int]) → int¶
Ravel indexes for 2D array.
This is a jitted function, equivalent to the numpy implementation of ravel_multi_index, but configured to accept only a single tuple as the index to ravel, and only works for two-dimensional array.
- Parameters:
tup (
tuple
ofint
) – Two element tuple with the x and y index into an array of shapeshape
to ravel.shape (
tuple
ofint
) – Two element tuple of integers indicating the shape of the two-dimensional array from whichtup
will be ravelled.
- Returns:
i – Ravelled integer index into array of shape
shape
.- Return type:
int
Examples
>>> _shape = (100, 200) # e.g., delta.eta.shape >>> np.ravel_multi_index((25, 124), _shape) 5124 >>> custom_ravel((25, 124), _shape) 5124
- pyDeltaRCM.shared_tools.custom_pad(arr: ndarray) → ndarray¶
Pad an array.
This is a jitted function, equivalent to the numpy implementation of pad with certain optional parameters:
np.pad(arr, 1, 'edge')
In pyDeltaRCM model fields (e.g., depth) are frequently padded to enable straightforward slicing of the neighbors of a given cell; i.e., padding guarantees that all cells will have 9 neighbors.
- Parameters:
arr (
ndarray
) – Array to pad.- Returns:
pad – Padded array.
- Return type:
ndarray
Examples
Consider a model domain of size (4, 8)
>>> arr = np.arange(32).reshape(4, 8) >>> np_pad = np.pad(arr, 1, 'edge') >>> cust_pad = custom_pad(arr) >>> np.all(np_pad == cust_pad) True >>> cust_pad.shape (6, 10)
which enables all elements of the original (4, 8) array to be safely sliced:
>>> for i in range(4): ... for j in range(8): ... slc = cust_pad[i:i+3, j:j+3] >>> slc.shape # will always be a (3, 3) 9-cell neighborhood (3, 3)
- pyDeltaRCM.shared_tools.get_weight_sfc_int(stage, stage_nbrs, qx, qy, ivec, jvec, distances)¶
Determine random walk weight surfaces.
Determines the surfaces for weighting the random walks based on the stage and discharge fields.
Todo
Expand description. Where is it used? Include an example? Equations? Link to Hydrodyanmics doc?
- pyDeltaRCM.shared_tools.custom_yaml_loader() → Type[SafeLoader]¶
A custom YAML loader to handle scientific notation.
- We are waiting for upstream fix here:
- Returns:
loader
- Return type:
pyyaml.Loader
with custom resolver
Examples
The custom loader can be used as:
>>> loader = pyDeltaRCM.shared_tools.custom_yaml_loader() >>> a_file = open('/path/to/file.yaml', mode='r') >>> yaml_as_dict = yaml.load(a_file, Loader=loader)
Time scaling functions¶
Scaling of real-world time and model time is an important topic covered in detail in Time in pyDeltaRCM. Several functions are defined here which can help with scaling between model and real-world time.
- pyDeltaRCM.shared_tools.scale_model_time(time: float, If: float = 1, units: str = 'seconds') → float¶
Scale the model time to “real” time.
Model time is executed as assumed flooding conditions, and executed at the per-second level, with a multi-second timestep. This model design implicitly assumes that the delta is always receiving a large volume of sediment and water at the inlet. This is unrealistic, given that rivers flood only during a small portion of the year, and this is when morphodynamic activity is largest. See Time in pyDeltaRCM for a complete description of this assumption, and how to work with the assumption in configuring the model.
Using this assumption, it is possible to scale up model time to “real” time, by assuming an intermittency factor. This intermittency factor is the fraction of unit-time that a river is assumed to be flooding.
\[t_r = \dfrac{t}{I_f \cdot S_f}\]where \(t\) is the model time (
time
), \(t_r\) is the “real” scaled time, \(I_f\) is the intermittency factor, and \(S_f\) is the scale factor to convert base units of seconds to units specified as an input argument. Note that this function uses_scale_factor
internally for this conversion.- Parameters:
time (
float
) – The model time, in seconds.If (
float
, optional) – Intermittency factor, fraction of time represented by morphodynamic activity. Should be in interval (0, 1]. Defaults to 1 if not provided, i.e., no scaling is performed.units (
str
, optional) – The units to convert the scaled time to. Default is to return the scaled time in seconds (seconds), but optionally supply argument days or years for unit conversion.
- Returns:
scaled – Scaled time, in
units
, assuming the intermittency factorIf
.- Return type:
float
- Raises:
ValueError – if the value for intermittency is not
0 < If <= 1
.
- pyDeltaRCM.shared_tools._scale_factor(If: float, units: str) → float¶
Scaling factor between model time and “real” time.
The scaling factor relates the model time to a real worl time, by the assumed intermittency factor and the user-specified units for output.
- Parameters:
If (
float
) – Intermittency factor, fraction of time represented by morphodynamic activity. Must be in interval (0, 1].units (
str
) – The units to convert the scaled time to. Must be a string in [‘seconds’, ‘days’, ‘years’].
Utilities¶
Additionally, functions defined in pyDeltaRCM.shared_tools
manage the random state of the model, and help with documentation and version management.
- pyDeltaRCM.shared_tools.set_random_seed(_seed: int) → None¶
Set the random seed from an integer.
Set the seed of the random number generator with a single integer. Importantly, this function will affect the state of the numba random number generator, rather than the numpy generator.
This function is called during model intialization, but is not called during loading a model from checkpoint (
load_checkpoint()
) where the random number generator state is configured via theset_random_state()
function.Important
This function is preferred to setting the random seed directly. If you are working with model subclassing, interacting with the numpy random number generator directly will lead to a model that is not reproducible!
Internally, the method is simply the below line; however it is crucial this happens inside a jitted function, in order to affect the state of the numba random number generator seed.
np.random.seed(_seed)
- Parameters:
_seed (
int
) – Integer to use as the random number generator seed. Should be in interval[0, 2^32]
.
- pyDeltaRCM.shared_tools.get_random_state()¶
Get the random state as a tuple.
Get the random state from a tuple in the form returned by
numba._helperlib.rnd_get_state()
. This tuple contains the necessary information for resuming a checkpoint from the exact same random number generator state.Important
You probably do not need to use this function. Be sure you know exactly how you are affecting the random number generator state before using this function, or you are likely to create a model that cannot be peproduced.
See also
set_random_seed()
.- Returns:
state – Random number generator state as a tuple.
- Return type:
tuple
- pyDeltaRCM.shared_tools.set_random_state(_state_tuple) → None¶
Set the random state from a tuple.
Set the random state from a tuple in the form returned by
numba._helperlib.rnd_get_state()
.Important
You probably do not need to use this function. Be sure you know exactly how you are affecting the random number generator state before using this function, or you are likely to create a model that cannot be peproduced.
See also
set_random_seed()
.- Parameters:
state (
tuple
) – Random number generator state as a tuple.
- pyDeltaRCM.shared_tools._docs_temp_directory() → Iterator[str]¶
Helper for creating and tearing down models in documentation.
This function should be used as a context manager, to create a DeltaModel with a temporary folder as output, rather than anywhere in the project structure.
Examples
>>> with _docs_temp_directory() as output_dir: ... delta = pyDeltaRCM.DeltaModel(out_dir=output_dir)
- pyDeltaRCM.shared_tools._get_version() → str¶
Extract version from file.
Extract version number from single file, and make it availabe everywhere. This function is used to make sure that when the version number is incremented in the pyDeltaRCM._version module, it is properly updated throughout documentation and version-controlled release.
Note
You probably don’t need to use this function.
- Returns:
ver_str – Version number, as a string.
- Return type:
str
Examples
>>> pyDeltaRCM.shared_tools._get_version()