Source code

Here you can find the documentation with direct links to the actual AeoLiS code. You can click on the green [source] button next to the classes and modules below to access the specific source code. You can use ctr-f to look for a specific functionality or variable. It still may be a bit difficult to browse through, in addition you can find an overview of all module code here

Model classes

The AeoLiS model is based on two main model classes: AeoLiS and AeoLiSRunner. The former is the actual, low-level, BMI-compatible class that implements the basic model functions and numerical schemes. The latter is a convenience class that implements a time loop, netCDF4 output, a progress indicator and a callback function that allows the used to interact with the model during runtime.

The additional WindGenerator class to generate realistic wind time series is available from the same module.

AeoLiS

AeoLiSRunner

WindGenerator

Physics modules

Bathymetry and bed composition

Wind velocity and direction

class shear.WindShear(x, y, z, dx, dy, L, l, z0, buffer_width, buffer_relaxation=None)[source]

Class for computation of 2DH wind shear perturbations over a topography.

The class implements a 2D FFT solution to the wind shear perturbation on curvilinear grids. As the FFT solution is only defined on an equidistant rectilinear grid with circular boundary conditions that is aligned with the wind direction, a rotating computational grid is automatically defined for the computation. The computational grid is extended in all directions using a logistic sigmoid function as to ensure full coverage of the input grid for all wind directions, circular boundaries and preservation of the alongshore uniformity. An extra buffer distance can be used as to minimize the disturbence from the borders in the input grid. The results are interpolated back to the input grid when necessary.

Frequencies related to wave lengths smaller than a computational grid cell are filtered from the 2D spectrum of the topography using a logistic sigmoid tapering. The filtering aims to minimize the disturbance as a result of discontinuities in the topography that may physically exists, but cannot be solved for in the computational grid used.

Example

>>> w = WindShear(x, y, z)
>>> w(u0=10., udir=30.).add_shear(taux, tauy)

Notes

To do:

  • Actual resulting values are still to be compared with the results

    from Kroy et al. (2002)

  • Grid interpolation can still be optimized

  • Separation bubble is still to be improved

add_shear()[source]

Add wind shear perturbations to a given wind shear field

Parameters:
  • taux (numpy.ndarray) – Wind shear in x-direction

  • tauy (numpy.ndarray) – Wind shear in y-direction

Returns:

  • taux (numpy.ndarray) – Wind shear including perturbations in x-direction

  • tauy (numpy.ndarray) – Wind shear including perturbations in y-direction

compute_shear(u0, nfilter=(1.0, 2.0))[source]

Compute wind shear perturbation for given free-flow wind speed on computational grid

Parameters:
  • u0 (float) – Free-flow wind speed

  • nfilter (2-tuple) – Wavenumber range used for logistic sigmoid filter. See filter_highfrequencies()

filter_highfrequenies(kx, ky, hs, nfilter=(1, 2))[source]

Filter high frequencies from a 2D spectrum

A logistic sigmoid filter is used to taper higher frequencies from the 2D spectrum. The range over which the sigmoid runs from 0 to 1 with a precision p is given by the 2-tuple nfilter. The range is defined as wavenumbers in terms of gridcells, i.e. a value 1 corresponds to a wave with length dx.

Parameters:
  • kx (numpy.ndarray) – Wavenumbers in x-direction

  • ky (numpy.ndarray) – Wavenumbers in y-direction

  • hs (numpy.ndarray) – 2D spectrum

  • nfilter (2-tuple) – Wavenumber range used for logistic sigmoid filter

  • p (float) – Precision of sigmoid range definition

Returns:

hs – Filtered 2D spectrum

Return type:

numpy.ndarray

static get_borders(x)[source]

Returns borders of a grid as one-dimensional array

static get_exact_grid(xmin, xmax, ymin, ymax, dx, dy)[source]

Returns a grid with given gridsizes approximately within given bounding box

get_separation()[source]

Returns difference in height between z-coordinate of the separation polynomial and of the bed level

Returns:

hsep – Height of seperation bubble

Return type:

numpy.ndarray

get_shear()[source]

Returns wind shear perturbation field

Returns:

  • taux (numpy.ndarray) – Wind shear perturbation in x-direction

  • tauy (numpy.ndarray) – Wind shear perturbation in y-direction

interpolate(x, y, z, xi, yi, z0)[source]

Interpolate one grid to an other

plot(ax=None, cmap='Reds', stride=10, computational_grid=False, **kwargs)[source]

Plot wind shear perturbation

Parameters:
  • ax (matplotlib.pyplot.Axes, optional) – Axes to plot onto

  • cmap (matplotlib.cm.Colormap or string, optional) – Colormap for topography (default: Reds)

  • stride (int, optional) – Stride to apply to wind shear vectors (default: 10)

  • computational_grid (bool, optional) – Plot on computational grid rather than input grid (default: False)

  • kwargs (dict) – Additional arguments to matplotlib.pyplot.quiver()

Returns:

ax – Axes used for plotting

Return type:

matplotlib.pyplot.Axes

static rotate(x, y, alpha, origin=(0, 0))[source]

Rotate a matrix over given angle around given origin

separation_shear(hsep)[source]

Reduces the computed wind shear perturbation below the separation surface to mimic the turbulence effects in the separation bubble

Parameters:

hsep (numpy.ndarray) – Height of seperation bubble (in x direction)

set_computational_grid(udir)[source]

Define computational grid

The computational grid is square with dimensions equal to the diagonal of the bounding box of the input grid, plus twice the buffer width.

Wind velocity threshold

threshold.compute(s, p)[source]

Compute wind velocity threshold based on bed surface properties

Computes wind velocity threshold based on grain size fractions, bed slope, soil moisture content, air humidity, the presence of roughness elements and a non-erodible layer. All bed surface properties increase the current wind velocity threshold, except for the grain size fractions. Therefore, the computation is initialized by the grain size fractions and subsequently altered by the other bed surface properties.

Parameters:
  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

Returns:

Spatial grids

Return type:

dict

threshold.compute_bedslope(s, p)[source]

Modify wind velocity threshold based on bed slopes following Dyer (1986)

Parameters:
  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

Returns:

Spatial grids

Return type:

dict

threshold.compute_grainsize(s, p)[source]

Compute wind velocity threshold based on grain size fractions following Bagnold (1937)

Parameters:
  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

Returns:

Spatial grids

Return type:

dict

threshold.compute_moisture(s, p)[source]

Modify wind velocity threshold based on soil moisture content following Belly (1964) or Hotta (1984)

Parameters:
  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

Returns:

Spatial grids

Return type:

dict

threshold.compute_salt(s, p)[source]

Modify wind velocity threshold based on salt content following Nickling and Ecclestone (1981)

Parameters:
  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

Returns:

Spatial grids

Return type:

dict

threshold.compute_sheltering(s, p)[source]

Modify wind velocity threshold based on the presence of roughness elements following Raupach (1993)

Raupach (1993) presents the following amplification factor for the shear velocity threshold due to the presence of roughness elements.

\[R_t = \frac{u_{*,th,s}}{u_{*,th,r}} = \sqrt{\frac{\tau_s''}{\tau}} = \frac{1}{\sqrt{\left( 1 - m \sigma \lambda \right) \left( 1 + m \beta \lambda \right)}}\]

\(m\) is a constant smaller or equal to unity that accounts for the difference between the average stress on the bed surface \(\tau_s\) and the maximum stress on the bed surface \(\tau_s''\).

\(\beta\) is the stress partition coefficient defined as the ratio between the drag coefficient of the roughness element itself \(C_r\) and the drag coefficient of the bare surface without roughness elements \(C_s\).

\(\sigma\) is the shape coefficient defined as the basal area divided by the frontal area: \(\frac{A_b}{A_f}\). For hemispheres \(\sigma = 2\), for spheres \(\sigma = 1\).

\(\lambda\) is the roughness density defined as the number of elements per surface area \(\frac{n}{S}\) multiplied by the frontal area of a roughness element \(A_f\), also known as the frontal area index:

\[\lambda = \frac{n b h}{S} = \frac{n A_f}{S}\]

If multiplied by \(\sigma\) the equation simplifies to the mass fraction of non-erodible elements:

\[\sigma \lambda = \frac{n A_b}{S} = \sum_{k=n_0}^{n_k} \hat{w}^{\mathrm{bed}}_k\]

where \(k\) is the fraction index, \(n_0\) is the smallest non-erodible fraction, \(n_k\) is the largest non-erodible fraction and \(\hat{w}^{\mathrm{bed}}_k\) is the mass fraction of sediment fraction \(k\). It is assumed that the fractions are ordered by increasing size.

Substituting the derivation in the Raupach (1993) equation gives the formulation implemented in this function:

\[u_{*,th,r} = u_{*,th,s} * \sqrt{\left( 1 - m \sum_{k=n_0}^{n_k} \hat{w}^{\mathrm{bed}}_k \right) \left( 1 + m \frac{\beta}{\sigma} \sum_{k=n_0}^{n_k} \hat{w}^{\mathrm{bed}}_k \right)}\]
Parameters:
  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

Returns:

Spatial grids

Return type:

dict

threshold.non_erodible(s, p)[source]

Modify wind velocity threshold based on the presence of a non-erodible layer.

Parameters:
  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

Returns:

Spatial grids

Return type:

dict

Tides, meteorology and soil moisture content

hydro.Boussinesq(GW, DSWL, ds, GW_stat, K_gw, ne_gw, D_gw, shl_ix, bound, zb, process_seepage_face)[source]

Boussinesq equation for groundwater level change

Parameters:
  • GW (numpy.ndarray) – Groundwater level

  • DSWL (numpy.ndarray) – Dynamic seawater level

  • ds (numpy.ndarray) – Cell size

  • GW_stat (float) – Static groundwater level

  • K_gw (float) – Hydraulic conductivity

  • ne_gw (float) – Effective porosity

  • D_gw (float) – Aquifer depth

  • shl_ix (numpy.ndarray) – Index of shoreline location

  • bound (int) – Landward boundary condition

  • zb (numpy.ndarray) – Bed level

  • process_seepage_face (bool) – Process seepage face

Returns:

Groundwater level change

Return type:

numpy.ndarray

hydro.SWR_curve(wetting, gw, gw_prev, scan_w, moist_swr, w_h, scan_d, scan_w_moist, d_h, scan_d_moist)[source]

Compute moisture content due to capillary processes

Parameters:
  • wetting (numpy.ndarray) – Flag indicating wetting or drying of soil profile

  • gw (numpy.ndarray) – Groundwater level

  • gw_prev (numpy.ndarray) – Groundwater level in previous timestep

  • scan_w (numpy.ndarray) – Flag indicating that the moisture is calculated on the wetting scanning curve

  • moist_swr (numpy.ndarray) – Moisture content due to capillary processes

  • w_h (numpy.ndarray) – Moisture content on wetting curve

  • scan_d (numpy.ndarray) – Flag indicating that the moisture is calculated on the drying scanning curve

  • scan_w_moist (numpy.ndarray) – Moisture content on wetting scanning curve

  • d_h (numpy.ndarray) – Moisture content on drying curve

  • scan_d_moist (numpy.ndarray) – Moisture content on drying scanning curve

Returns:

Moisture content due to capillary processes

Return type:

numpy.ndarray

hydro.calc_runup_stockdon(Ho, Tp, beta)[source]

Calculate runup according to /Stockdon et al 2006.

Parameters:
  • Ho (float or numpy.ndarray) – Significant wave height

  • Tp (float or numpy.ndarray) – Peak period

  • beta (float) – Beach slope

Returns:

  • eta (float or numpy.ndarray) – Runup height

  • sigma_s (float or numpy.ndarray) – Setup height

  • R (float or numpy.ndarray) – Total runup height

hydro.evaporation(s, p, met)[source]

Compute evaporation according to the Penman equation (Shuttleworth, 1993)

Parameters:
  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

  • met (dict) – meteorologial parameters T: Temperature, degrees Celsius Q : Global radiation, MJ/m2/d P : Atmospheric pressure, kPa U: Relative humidity, %

Returns:

Evaporation (mm/day)

Return type:

float

hydro.hdelta(wetting, scan_w, gw, gw_prev, scan_d, h_delta, zb, scan_w_moist, scan_d_moist, w_h, satd_moist, d_h, satw_moist, alfaw_moist, alfad_moist, resw_moist, resd_moist, mw_moist, md_moist, nw_moist, nd_moist)[source]

Compute suction at reversal between wetting/drying conditions

Parameters:
  • wetting (numpy.ndarray) – Flag indicating wetting or drying of soil profile

  • scan_w (numpy.ndarray) – Flag indicating that the moisture is calculated on the wetting scanning curve

  • gw (numpy.ndarray) – Groundwater level

  • gw_prev (numpy.ndarray) – Groundwater level in previous timestep

  • scan_d (numpy.ndarray) – Flag indicating that the moisture is calculated on the drying scanning curve

  • h_delta (numpy.ndarray) – Suction at reversal between wetting/drying conditions

  • zb (numpy.ndarray) – Bed level

  • scan_w_moist (numpy.ndarray) – Moisture content on wetting scanning curve

  • scan_d_moist (numpy.ndarray) – Moisture content on drying scanning curve

  • w_h (numpy.ndarray) – Moisture content on wetting curve

  • satd_moist (float) – Moisture content at saturation on drying curve

  • d_h (numpy.ndarray) – Moisture content on drying curve

  • satw_moist (float) – Moisture content at saturation on wetting curve

  • alfaw_moist (float) – Inverse of the air-entry value for a wetting branch of the soil water retention function

  • alfad_moist (float) – Inverse of the air-entry value for a drying branch of the soil water retention function

  • resw_moist (float) – Residual moisture content on wetting curve

  • resd_moist (float) – Residual moisture content on drying curve

  • mw_moist (float) – Shape parameter for the wetting branch of the soil water retention function

  • md_moist (float) – Shape parameter for the drying branch of the soil water retention function

  • nw_moist (float) – Pore-size distribution index in the soil water retention function, wetting branch

  • nd_moist (float) – Pore-size distribution index in the soil water retention function, drying branch

Returns:

Suction at reversal between wetting/drying conditions

Return type:

numpy.ndarray

hydro.interpolate(s, p, t)[source]

Interpolate hydrodynamic and meteorological conditions to current time step

Interpolates the hydrodynamic and meteorological time series to the current time step, if available. Meteorological parameters are stored as dictionary rather than a single value.

Parameters:
  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

  • t (float) – Current time

Returns:

Spatial grids

Return type:

dict

hydro.runup_overheight_distr(fx, fx_ix, shl_ix, runup_ix, x)[source]

Compute distribution of infiltrated water due to wave runup according to Nielsen (1990)

Parameters:
  • fx (numpy.ndarray) – Distribution of infiltrated water

  • fx_ix (numpy.ndarray) – Index of peak f(x)

  • shl_ix (numpy.ndarray) – Index of shoreline location

  • runup_ix (numpy.ndarray) – Index of runup limit

  • x (numpy.ndarray) – x-coordinate

Returns:

Distribution of infiltrated water

Return type:

numpy.ndarray

hydro.saturation_pressure(T)[source]

Compute saturation pressure based on air temperature, Tetens equation

Parameters:

T (float) – Air temperature in degrees Celcius

Returns:

Saturation pressure

Return type:

float

hydro.update(s, p, dt, t)[source]

Update soil moisture content

Updates soil moisture content in all cells. The soil moisure content is computed either with the infiltration-method or surface_moist method. The infiltration method accounts for surface moisture as a function of runup and the subsequent infiltration and evaporation. The surface_moist method takes into account the effect of wave runup, precipitation, evaporation, infiltration, and capillary rise from the groundwater table.

Parameters:
  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

  • dt (float) – Current time step

Returns:

Spatial grids

Return type:

dict

hydro.vaporation_pressure_slope(T)[source]

Compute vaporation pressure slope based on air temperature

Parameters:

T (float) – Air temperature in degrees Celcius

Returns:

Vaporation pressure slope

Return type:

float

Sediment transport

transport.compute_weights(s, p)[source]

Compute weights for sediment fractions

Multi-fraction sediment transport needs to weigh the transport of each sediment fraction to prevent the sediment transport to increase with an increasing number of sediment fractions. The weighing is not uniform over all sediment fractions, but depends on the sediment availibility in the air and the bed and the bed interaction parameter bi.

Parameters:
  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

Returns:

Array with weights for each sediment fraction

Return type:

numpy.ndarray

transport.constant_grainspeed(s, p)[source]

Define saltation velocity u [m/s]

Parameters:
  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

Returns:

Spatial grids

Return type:

dict

transport.duran_grainspeed(s, p)[source]

Compute grain speed according to Duran 2007 (p. 42)

Parameters:
  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

Returns:

Spatial grids

Return type:

dict

transport.equilibrium(s, p)[source]

Compute equilibrium sediment concentration following Bagnold (1937)

Parameters:
  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

Returns:

Spatial grids

Return type:

dict

transport.renormalize_weights(w, ix)[source]

Renormalizes weights for sediment fractions

Renormalizes weights for sediment fractions such that the sum of all weights is unity. To ensure that the erosion of specific fractions does not exceed the sediment availibility in the bed, the normalization only modifies the weights with index equal or larger than ix.

Parameters:
  • w (numpy.ndarray) – Array with weights for each sediment fraction

  • ix (int) – Minimum index to be modified

Returns:

Array with weights for each sediment fraction

Return type:

numpy.ndarray

Avalanching

avalanching.angele_of_repose(s, p)[source]

Determine the dynamic and static angle of repose.

Both the critical dynamic and static angle of repose are spatial varying and depend on surface moisture content and roots of present vegetation and ….

Parameters:
  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

Returns:

Spatial grids

Return type:

dict

avalanching.avalanche(s, p)[source]

Avalanching occurs if bed slopes exceed critical slopes.

Simulates the process of avalanching that is triggered by the exceedence of a critical static slope theta_stat by the bed slope. The iteration stops if the bed slope does not exceed the dynamic critical slope theta_dyn.

Parameters:
  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

Returns:

Spatial grids

Return type:

dict

Vegetation

Fences

Marine Erosion

Helper modules

Input/Output

inout.backup(fname)[source]

Creates a backup file of the provided file, if it exists

inout.check_configuration(p)[source]

Check model configuration validity

Checks if required parameters are set and if the references files for bathymetry, wind, tide and meteorological input are valid. Throws an error if one or more requirements are not met.

Parameters:

p (dict) – Model configuration dictionary with parsed files

See also

read_configfile

inout.get_backupfilename(fname)[source]

Returns a non-existing backup filename

inout.output_sedtrails(s, p)[source]

Create additional output for SedTRAILS and save as mat-files. Chosen for seperate files, such that only relevant (Ct > 0) cells are exported for memory and speed efficiency

inout.parse_value(val, parse_files=True, force_list=False)[source]

Casts a string to the most appropriate variable type

Parameters:
  • val (str) – String representation of value

  • parse_files (bool) – If True, files referred to by string parameters are parsed by numpy.loadtxt

  • force_list – If True, interpret the value as a list, even if it consists of a single value

Returns:

Casted value

Return type:

misc

Examples

>>> type(parse_value('T'))
    bool
>>> type(parse_value('F'))
    bool
>>> type(parse_value('123'))
    int
>>> type(parse_value('123.2'))
    float
>>> type(parse_value('euler_forward'))
    str
>>> type(parse_value(''))
    NoneType
>>> type(parse_value('zb zs Ct'))
    numpy.ndarray
>>> type(parse_value('zb', force_list=True))
    numpy.ndarray
>>> type(parse_value('0.1 0.2 0.3')[0])
    float
>>> type(parse_value('wind.txt'), parse_files=True)
    numpy.ndarray
>>> type(parse_value('wind.txt'), parse_files=False)
    str
inout.read_configfile(configfile, parse_files=True, load_defaults=True)[source]

Read model configuration file

Updates default model configuration based on a model configuration file. The model configuration file should be a text file with one parameter on each line. The parameter name and value are seperated by an equal sign (=). Any lines that start with a percent sign (%) or do not contain an equal sign are omitted.

Parameters are casted into the best matching variable type. If the variable type is str it is optionally interpreted as a filename. If the corresponding file is found it is parsed using the numpy.loadtxt function.

Parameters:
  • configfile (str) – Model configuration file

  • parse_files (bool) – If True, files referred to by string parameters are parsed

  • load_defaults (bool) – If True, default settings are loaded and overwritten by the settings from the configuration file

Returns:

Dictionary with casted and optionally parsed model configuration parameters

Return type:

dict

inout.visualize_grid(s, p)[source]

Create figures and tables for the user to check whether the grid-input is correctly interpreted

inout.visualize_spatial(s, p)[source]

Create figures and tables for the user to check whether the input is correctly interpreted

inout.visualize_timeseries(p, t)[source]

Create figures and tables for the user to check whether the timeseries-input is correctly interpreted

inout.write_configfile(configfile, p=None)[source]

Write model configuration file

Writes model configuration to file. If no model configuration is given, the default configuration is written to file. Any parameters with a name ending with _file and holding a matrix are treated as separate files. The matrix is then written to an ASCII file using the numpy.savetxt function and the parameter value is replaced by the name of the ASCII file.

Parameters:
  • configfile (str) – Model configuration file

  • p (dict, optional) – Dictionary with model configuration parameters

Returns:

Dictionary with casted and optionally parsed model configuration parameters

Return type:

dict

See also

read_configfile

netCDF4 output

netcdf.append(outputfile, variables)[source]

Append variables to existing netCDF4 output file

Increments the time axis length with one and appends the provided spatial grids along the time axis. The variables dictionary should at least have the time field indicating the current simulation time. The CF time bounds are updated accordingly.

Parameters:
  • outputfile (str) – Name of netCDF4 output file

  • variables (dict) – Dictionary with spatial grids and time

Examples

>>> netcdf.append('aeolis.nc', {'time', 3600.,
...                             'Ct', np.array([[0.,0., ... ,0.]]),
...                             'Cu', np.array([[1.,1., ... ,1.]]))

See also

set_bounds

netcdf.dump(outputfile, dumpfile, var='mass', ix=-1)[source]

Dumps time slice from netCDF4 output file to ASCII file

This function can be used to use a specific time slice from a netCDF4 output file as input file for another AeoLiS model run. For example, the bed composition from a spinup run can be used as initial composition for other runs reducing the spinup time.

Parameters:
  • outputfile (str) – Name of netCDF4 output file

  • dumpfile (str) – Name of ASCII dump file

  • var (str, optional) – Name of spatial grid to be dumped (default: mass)

  • ix (int) – Time slice index to be dumped (default: -1)

Examples

>>> # use bedcomp_file = bedcomp.txt in model configuration file
... netcdf.dump('aeolis.nc', 'bedcomp.txt', var='mass')
netcdf.initialize(outputfile, outputvars, s, p, dimensions)[source]

Create empty CF-compatible netCDF4 output file

Parameters:
  • outputfile (str) – Name of netCDF4 output file

  • outputvars (dictionary) – Spatial grids to be written to netCDF4 output file

  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

  • dimensions (dict) – Dictionary that specifies a tuple with the named dimensions for each spatial grid (e.g. (‘ny’, ‘nx’, ‘nfractions’))

Examples

>>> netcdf.initialize('aeolis.nc',
...                   ['Ct', 'Cu', 'zb'],
...                   ['avg', 'max'],
...                   s, p, {'Ct':('ny','nx','nfractions'),
...                          'Cu':('ny','nx','nfractions'),
...                          'zb':('ny','nx')})
netcdf.parse_metadata(outputvars)[source]

Parse metadata from constants.py

Parses the Python comments in constants.py to extract meta data, like units, for the model state variables that can be used as netCDF4 meta data.

Parameters:

outputvars (dictionary) – Spatial grids to be written to netCDF4 output file

Returns:

meta – Dictionary with meta data for the output variables

Return type:

dict

netcdf.set_bounds(outputfile)[source]

Sets CF time bounds

Parameters:

outputfile (str) – Name of netCDF4 output file

Plotting

Command-line tools

Debugging

Miscellaneous

utils.apply_mask(arr, mask)[source]

Apply complex mask

The real part of the complex mask is multiplied with the input array. Subsequently the imaginary part is added and the result returned.

The shape of the mask is assumed to match the first few dimensions of the input array. If the input array is larger than the mask, the mask is repeated for any additional dimensions.

Parameters:
  • arr (numpy.ndarray) – Array or matrix to which the mask needs to be applied

  • mask (numpy.ndarray) – Array or matrix with complex mask values

Returns:

arr – Array or matrix to which the mask is applied

Return type:

numpy.ndarray

utils.calc_grain_size(p, s, percent)[source]

Calculate grain size characteristics based on mass in each fraction

Calculate grain size distribution for each cell based on weight distribution over the fractions. Interpolates to the requested percentage in the grain size distribution. For example, percent=50 will result in calculation of the D50. Calculation is only executed for the top layer

Parameters:
  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

  • percent (float) – Requested percentage in grain size dsitribution

Returns:

grain size per grid cell

Return type:

array

utils.calc_mean_grain_size(p, s)[source]

Calculate mean grain size based on mass in each fraction

Calculate mean grain size for each cell based on weight distribution over the fractions. Calculation is only executed for the top layer.

Parameters:
  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

  • percent (float) – Requested percentage in grain size dsitribution

Returns:

mean grain size per grid cell

Return type:

array

utils.format_log(msg, ncolumns=2, **props)[source]

Format log message into columns

Prints log message and additional data into a column format that fits into a 70 character terminal.

Parameters:
  • msg (str) – Main log message

  • ncolumns (int) – Number of columns

  • props (key/value pairs) – Properties to print in column format

Returns:

Formatted log message

Return type:

str

Note

Properties names starting with min, max or nr are respectively replaced by min., max. or #.

utils.interp_array(x: ndarray, xp: ndarray, fp: ndarray, circular: bool = False, **kwargs: dict) ndarray[source]

Interpolate multiple time series at once

Parameters:
  • x (array_like) – The x-coordinates of the interpolated values.

  • xp (1-D sequence of floats) – The x-coordinates of the data points, must be increasing.

  • fp (2-D sequence of floats) – The y-coordinates of the data points, same length as xp.

  • circular (bool) – Use the interp_circular() function rather than the numpy.interp() function.

  • kwargs (dict) – Keyword options to the numpy.interp() function

Returns:

The interpolated values, same length as second dimension of fp.

Return type:

ndarray

utils.interp_circular(x: ndarray, xp: ndarray, fp: ndarray, **kwargs) ndarray[source]

One-dimensional linear interpolation.

Returns the one-dimensional piecewise linear interpolant to a function with given values at discrete data-points. Values beyond the limits of x are interpolated in circular manner. For example, a value of x > x.max() evaluates as f(x-x.max()) assuming that x.max() - x < x.max().

Parameters:
  • x (array_like) – The x-coordinates of the interpolated values.

  • xp (1-D sequence of floats) – The x-coordinates of the data points, must be increasing.

  • fp (1-D sequence of floats) – The y-coordinates of the data points, same length as xp.

  • kwargs (dict) – Keyword options to the numpy.interp() function

Returns:

y – The interpolated values, same shape as x.

Return type:

{float, ndarray}

Raises:

ValueError – If xp and fp have different length

utils.interp_circular_nearest(x: ndarray, xp: ndarray, fp: ndarray) ndarray[source]

One-dimensional linear interpolation to nearest neighbor.

Returns the one-dimensional piecewise linear interpolant to a function with given values at discrete data-points. Values beyond the limits of x are interpolated in circular manner. For example, a value of x > x.max() evaluates as f(x-x.max()) assuming that x.max() - x < x.max().

Parameters:
  • x (array_like) – The x-coordinates of the interpolated values.

  • xp (1-D sequence of floats) – The x-coordinates of the data points, must be increasing.

  • fp (1-D sequence of floats) – The y-coordinates of the data points, same length as xp.

  • kwargs (dict) – Keyword options to the numpy.interp() function

Returns:

y – The interpolated values, same shape as x.

Return type:

{float, ndarray}

Raises:

ValueError – If xp and fp have different length

utils.isarray(x)[source]

Check if variable is an array

utils.isiterable(x)[source]

Check if variable is iterable

utils.makeiterable(x)[source]

Ensure that variable is iterable

utils.normalize(x: ndarray, ref: ndarray | None = None, axis: int = 0, fill: float = 0.0)[source]

Normalize array

Normalizes an array to make it sum to unity over a specific axis. The procedure is safe for dimensions that sum to zero. These dimensions return the fill value instead.

Parameters:
  • x (array_like) – The array to be normalized

  • ref (array_like, optional) – Alternative normalization reference, if not specified, the sum of x is used

  • axis (optional) – The normalization axis (default: 0)

  • fill (optional) – The return value for all-zero dimensions (default: 0.)

utils.prevent_tiny_negatives(x: ndarray, max_error: float = 1e-10, replacement: float = 0.0) ndarray[source]

Replace tiny negative values in array

Parameters:
  • x (np.ndarray) – Array with potential tiny negative values

  • max_error (float) – Maximum absolute value to be replaced

  • replacement (float) – Replacement value

Returns:

Array with tiny negative values removed

Return type:

np.ndarray

utils.print_value(val, fill='<novalue>')[source]

Construct a string representation from an arbitrary value

Parameters:
  • val (misc) – Value to be represented as string

  • fill (str, optional) – String representation used in case no value is given

Returns:

String representation of value

Return type:

str

utils.rotate(x, y, alpha, origin=(0, 0))[source]

Rotate a matrix over given angle around given origin

gridparams.initialize(s: Dict, p: Dict) Tuple[Dict, Dict][source]

Initializes a grid and a checks if the grid is properly defined based on the x and y input files. Grid distance and grid surface are also initialized, and then broadcasted to the s-dictionary for use by other modules.

Parameters:
  • s (dict) – Spatial grids

  • p (dict) – Model configuration parameters

Returns:

Initialized spatial grids as a tuple containing the s-dictionary and the p-dictionary.

Return type:

tuple [dict, dict]

Note

Sierd’s favorite function is: aeolis.bed.prevent_tiny_negatives