thetis package

Submodules

thetis.assembledschur module

class thetis.assembledschur.AssembledSchurPC[source]

Bases: firedrake.preconditioners.base.PCBase

Preconditioner for the Schur complement

The preconditioner matrix is assembled by explicitly matrix multiplying \(A10*Minv*A10\).

Here:

  • \(A01\), \(A10\) are the assembled sub-blocks of the saddle point

    system. The form of this system needs to be supplied in the appctx argument to the solver as appctx['a'].

  • \(Minv\) is the inverse of the mass-matrix which is assembled as

    assemble(Tensor(v*u*dx).inv), i.e. the element-wise inverse, where \(v\) and \(u\) are the test and trial of the \(A00\) block. This gives the exact inverse of the mass matrix for a DG discretisation.

Create a PC context suitable for PETSc.

Matrix free preconditioners should inherit from this class and implement:

apply(pc, X, Y)[source]

Apply the preconditioner to X, putting the result in Y.

Both X and Y are PETSc Vecs, Y is not guaranteed to be zero on entry.

applyTranspose(pc, X, Y)[source]

Apply the transpose of the preconditioner to X, putting the result in Y.

Both X and Y are PETSc Vecs, Y is not guaranteed to be zero on entry.

initialize(pc)[source]

Initialize any state in this preconditioner.

update(pc)[source]

Update any state in this preconditioner.

view(pc, viewer=None)[source]

thetis.callback module

Defines custom callback functions used to compute various metrics at runtime.

class thetis.callback.AccumulatorCallback(scalar_callback, solver_obj, **kwargs)[source]

Bases: thetis.callback.DiagnosticCallback

Callback that evaluates a (scalar) functional involving integrals in both time and space.

This callback can also be used to assemble time dependent objective functionals for adjoint simulations. Time integration is achieved using the trapezium rule.

Parameters
  • scalar_callback – Python function that returns a list of values of an objective functional.

  • solver_obj – Thetis solver object

  • kwargs – any additional keyword arguments, see DiagnosticCallback

get_val()[source]
message_str(*args)[source]

A string representation.

Parameters

args – If provided, these will be the return value from __call__().

variable_names = ['spatial integral at current timestep']
class thetis.callback.CallbackManager[source]

Bases: collections.defaultdict

Stores callbacks in different categories and provides methods for evaluating them.

Create callbacks and register them under 'export' mode

cb1 = VolumeConservation3DCallback(...)
cb2 = TracerMassConservationCallback(...)
cm = CallbackManager()
cm.add(cb1, 'export')
cm.add(cb2, 'export')

Evaluate callbacks, calls evaluate() method of all callbacks registered in the given mode.

cm.evaluate('export')
add(callback, mode)[source]

Add a callback under the given mode

Parameters
evaluate(mode, index=None)[source]

Evaluate all callbacks registered under the given mode

Parameters
  • mode (str) – evaluate all callbacks under this mode

  • index (int) – if provided, sets the export index. Default behavior is to append to the file or stream.

class thetis.callback.ConservativeTracerMassConservation2DCallback(tracer_name, solver_obj, **kwargs)[source]

Bases: thetis.callback.ScalarConservationCallback

Checks conservation of conservative tracer mass which is depth integrated.

Parameters
  • tracer_name – Name of the tracer. Use canonical field names as in FieldDict.

  • solver_obj – Thetis solver object

  • kwargs – any additional keyword arguments, see DiagnosticCallback.

name = 'tracer mass'
class thetis.callback.DetectorsCallback(solver_obj, detector_locations, field_names, name, detector_names=None, **kwargs)[source]

Bases: thetis.callback.DiagnosticCallback

Callback that evaluates the specified fields at the specified locations

Parameters
  • solver_obj – Thetis solver object

  • detector_locations – List of x, y locations in which fields are to be interpolated.

  • field_names – List of fields to be interpolated.

  • name – Unique name for this callback and its associated set of detectors. This determines the name of the output h5 file (prefixed with diagnostic_).

  • detector_names – List of names for each of the detectors. If not provided automatic names of the form detectorNNN are created where NNN is the (0-padded) detector number.

  • kwargs – any additional keyword arguments, see DiagnosticCallback.

message_str(*args)[source]

A string representation.

Parameters

args – If provided, these will be the return value from __call__().

property name

The name of the diagnostic

property variable_names

Names of all scalar values

class thetis.callback.DiagnosticCallback(solver_obj, array_dim=1, attrs=None, outputdir=None, export_to_hdf5=True, append_to_log=True, include_time=True, hdf5_dtype='d', start_time=None, end_time=None)[source]

Bases: abc.ABC

A base class for all Callback classes

Parameters
  • solver_obj – Thetis solver object

  • outputdir (str) – Custom directory where hdf5 files will be stored. By default solver’s output directory is used.

  • array_dim – Dimension of the output array. Can be a tuple for multi-dimensional output. Use “1” for scalars.

  • attrs (dict) – Global attributes to be saved in the hdf5 file.

  • export_to_hdf5 (bool) – If True, diagnostics will be stored in hdf5 format

  • append_to_log (bool) – If True, callback output messages will be printed in log

  • include_time (bool) – whether to include time in the hdf5 file

  • hdf5_dtype – Precision to use in hdf5 output: d for double precision (default), and f for single precision

  • start_time – Optional start time for callback evaluation

  • end_time – Optional end time for callback evaluation

evaluate(index=None)[source]

Evaluates callback and pushes values to log and hdf file (if enabled)

abstract message_str(*args)[source]

A string representation.

Parameters

args – If provided, these will be the return value from __call__().

abstract property name

The name of the diagnostic

push_to_hdf5(time, args, index=None)[source]

Append values to HDF5 file.

Parameters
  • time – time stamp of entry

  • args – the return value from __call__().

push_to_log(time, args)[source]

Push callback status message to log

Parameters
  • time – time stamp of entry

  • args – the return value from __call__().

set_write_mode(mode)[source]

Define whether to create a new hdf5 file or append to an existing one

Parameters

mode (str) – Either ‘create’ (default) or ‘append’

abstract property variable_names

Names of all scalar values

class thetis.callback.DiagnosticHDF5(filename, varnames, array_dim=1, attrs=None, var_attrs=None, comm=<mpi4py.MPI.Intracomm object>, new_file=True, dtype='d', include_time=True)[source]

Bases: object

A HDF5 file for storing diagnostic time series arrays.

Parameters
  • filename (str) – Full filename of the HDF5 file.

  • varnames – List of variable names that the diagnostic callback provides

  • array_dim – Dimension of the output array. Can be a tuple for multi-dimensional output. Use “1” for scalars.

  • attrs (dict) – Global attributes to be saved in the hdf5 file.

  • var_attrs (dict) – nested dict of variable specific attributes, e.g. {‘time’: {‘units’: ‘seconds since 1950-01-01’}}

  • comm – MPI communicator

  • new_file (bool) – Define whether to create a new hdf5 file or append to an existing one (if any)

  • dtype – array datatype

  • include_time – whether to include time array in the file

export(variables, time=None, index=None)[source]

Appends a new entry of (time, variables) to the file.

The HDF5 is updated immediately.

Parameters
  • variables (tuple of float) – values of entry

  • time (float) – time stamp of entry

  • index (int) – If provided, defines the time index in the file

class thetis.callback.MinMaxConservationCallback(minmax_callback, solver_obj, **kwargs)[source]

Bases: thetis.callback.DiagnosticCallback

Base class for callbacks that check conservation of a minimum/maximum

Parameters
  • minmax_callback – Python function that takes the solver object as an argument and returns a (min, max) value tuple

  • solver_obj – Thetis solver object

  • kwargs – any additional keyword arguments, see DiagnosticCallback.

message_str(*args)[source]

A string representation.

Parameters

args – If provided, these will be the return value from __call__().

variable_names = ['min_value', 'max_value', 'undershoot', 'overshoot']
class thetis.callback.ScalarConservationCallback(scalar_callback, solver_obj, **kwargs)[source]

Bases: thetis.callback.DiagnosticCallback

Base class for callbacks that check conservation of a scalar quantity

Creates scalar conservation check callback object

Parameters
  • scalar_callback – Python function that takes the solver object as an argument and returns a scalar quantity of interest

  • solver_obj – Thetis solver object

  • kwargs – any additional keyword arguments, see DiagnosticCallback.

message_str(*args)[source]

A string representation.

Parameters

args – If provided, these will be the return value from __call__().

variable_names = ['integral', 'relative_difference']
class thetis.callback.TimeSeriesCallback2D(solver_obj, fieldnames, x, y, location_name, z=None, outputdir=None, export_to_hdf5=True, append_to_log=True, tolerance=0.001, eval_func=None, start_time=None, end_time=None)[source]

Bases: thetis.callback.DiagnosticCallback

Extract a time series of a 2D field at a given (x,y) location

Currently implemented only for the 3D model.

Parameters
  • solver_obj – Thetis FlowSolver object

  • fieldnames – List of fields to extract

  • y (x,) – location coordinates in model coordinate system.

  • location_name – Unique name for this location. This determines the name of the output h5 file (prefixed with diagnostic_).

  • outputdir (str) – Custom directory where hdf5 files will be stored. By default solver’s output directory is used.

  • export_to_hdf5 (bool) – If True, diagnostics will be stored in hdf5 format

  • append_to_log (bool) – If True, callback output messages will be printed in log

  • start_time – Optional start time for timeseries extraction

  • end_time – Optional end time for timeseries extraction

message_str(*args)[source]

A string representation.

Parameters

args – If provided, these will be the return value from __call__().

name = 'timeseries'
variable_names = ['value']
class thetis.callback.TimeSeriesCallback3D(solver_obj, fieldnames, x, y, z, location_name, outputdir=None, export_to_hdf5=True, append_to_log=True, start_time=None, end_time=None)[source]

Bases: thetis.callback.DiagnosticCallback

Extract a time series of a 3D field at a given (x,y,z) location

Currently implemented only for the 3D model.

Parameters
  • solver_obj – Thetis FlowSolver object

  • fieldnames – List of fields to extract

  • z (x, y,) – location coordinates in model coordinate system.

  • location_name – Unique name for this location. This determines the name of the output h5 file (prefixed with diagnostic_).

  • outputdir (str) – Custom directory where hdf5 files will be stored. By default solver’s output directory is used.

  • export_to_hdf5 (bool) – If True, diagnostics will be stored in hdf5 format

  • append_to_log (bool) – If True, callback output messages will be printed in log

  • start_time – Optional start time for timeseries extraction

  • end_time – Optional end time for timeseries extraction

message_str(*args)[source]

A string representation.

Parameters

args – If provided, these will be the return value from __call__().

name = 'timeseries'
variable_names = ['value']
class thetis.callback.TracerMassConservation2DCallback(tracer_name, solver_obj, **kwargs)[source]

Bases: thetis.callback.ScalarConservationCallback

Checks conservation of depth-averaged tracer mass

Depth-averaged tracer mass is defined as the integral of 2D tracer multiplied by total depth.

Parameters
  • tracer_name – Name of the tracer. Use canonical field names as in FieldDict.

  • solver_obj – Thetis solver object

  • kwargs – any additional keyword arguments, see DiagnosticCallback.

name = 'tracer mass'
class thetis.callback.TracerMassConservationCallback(tracer_name, solver_obj, **kwargs)[source]

Bases: thetis.callback.ScalarConservationCallback

Checks conservation of total tracer mass

Parameters
  • tracer_name – Name of the tracer. Use canonical field names as in FieldDict.

  • solver_obj – Thetis solver object

  • kwargs – any additional keyword arguments, see DiagnosticCallback.

name = 'tracer mass'
class thetis.callback.TracerOvershootCallBack(tracer_name, solver_obj, **kwargs)[source]

Bases: thetis.callback.MinMaxConservationCallback

Checks overshoots of the given tracer field.

Parameters
  • tracer_name – Name of the tracer. Use canonical field names as in FieldDict.

  • solver_obj – Thetis solver object

  • kwargs – any additional keyword arguments, see DiagnosticCallback.

name = 'tracer overshoot'
class thetis.callback.TransectCallback(solver_obj, fieldnames, x, y, location_name, n_points_z=48, z_min=None, z_max=None, outputdir=None, export_to_hdf5=True, append_to_log=True)[source]

Bases: thetis.callback.DiagnosticCallback

Extract a vertical transect of a 3D field at a given (x,y) locations.

Only for the 3D model.

Parameters
  • solver_obj – Thetis FlowSolver object

  • fieldnames – List of fields to extract

  • y (x,) – location coordinates in model coordinate system.

  • location_name – Unique name for this location. This determines the name of the output h5 file (prefixed with diagnostic_).

  • n_points_z (int) – Number of points along the vertical axis. The 3D field will be interpolated on these points, ranging from the bottom to the (time dependent) free surface.

  • zmax (float z_min,) – Force min/max value of z coordinate extent. By default, transect will cover entire depth from bed to surface.

  • outputdir (str) – Custom directory where hdf5 files will be stored. By default solver’s output directory is used.

  • export_to_hdf5 (bool) – If True, diagnostics will be stored in hdf5 format

  • append_to_log (bool) – If True, will print extracted min/max values of each field to log

message_str(*args)[source]

A string representation.

Parameters

args – If provided, these will be the return value from __call__().

name = 'transect'
variable_names = ['z_coord', 'value']
class thetis.callback.VerticalProfileCallback(solver_obj, fieldnames, x, y, location_name, npoints=48, outputdir=None, export_to_hdf5=True, append_to_log=True)[source]

Bases: thetis.callback.DiagnosticCallback

Extract a vertical profile of a 3D field at a given (x,y) location

Only for the 3D model.

Parameters
  • solver_obj – Thetis FlowSolver object

  • fieldnames – List of fields to extract

  • y (x,) – location coordinates in model coordinate system.

  • location_name – Unique name for this location. This determines the name of the output h5 file (prefixed with diagnostic_).

  • npoints (int) – Number of points along the vertical axis. The 3D field will be interpolated on these points, ranging from the bottom to the (time dependent) free surface.

  • outputdir (str) – Custom directory where hdf5 files will be stored. By default solver’s output directory is used.

  • export_to_hdf5 (bool) – If True, diagnostics will be stored in hdf5 format

  • append_to_log (bool) – If True, callback output messages will be printed in log

message_str(*args)[source]

A string representation.

Parameters

args – If provided, these will be the return value from __call__().

name = 'vertprofile'
variable_names = ['z_coord', 'value']
class thetis.callback.VolumeConservation2DCallback(solver_obj, **kwargs)[source]

Bases: thetis.callback.ScalarConservationCallback

Checks conservation of 2D volume (integral of water elevation field)

Parameters
  • solver_obj – Thetis solver object

  • kwargs – any additional keyword arguments, see DiagnosticCallback.

name = 'volume2d'
class thetis.callback.VolumeConservation3DCallback(solver_obj, **kwargs)[source]

Bases: thetis.callback.ScalarConservationCallback

Checks conservation of 3D volume (volume of 3D mesh)

Parameters
  • solver_obj – Thetis solver object

  • kwargs – any additional keyword arguments, see DiagnosticCallback.

name = 'volume3d'
thetis.callback.timed_stage()

Log.Stage(type cls, name)

thetis.configuration module

Utility function and extensions to traitlets used for specifying Thetis options

class thetis.configuration.ABCMetaHasTraits(name, bases, namespace, **kwargs)[source]

Bases: abc.ABCMeta, traitlets.traitlets.MetaHasTraits

Combined metaclass of ABCMeta and MetaHasTraits

Finish initializing the HasDescriptors class.

class thetis.configuration.BoundedFloat(default_value=traitlets.Undefined, bounds=None, **kwargs)[source]

Bases: traitlets.traitlets.Float

Declare a traitlet.

If allow_none is True, None is a valid value in addition to any values that are normally valid. The default is up to the subclass. For most trait types, the default value for allow_none is False.

If read_only is True, attempts to directly modify a trait attribute raises a TraitError.

Extra metadata can be associated with the traitlet using the .tag() convenience method or by using the traitlet instance’s .metadata dictionary.

info()[source]
validate(obj, proposal)[source]
class thetis.configuration.BoundedInteger(default_value=traitlets.Undefined, bounds=None, **kwargs)[source]

Bases: traitlets.traitlets.Int

Declare a traitlet.

If allow_none is True, None is a valid value in addition to any values that are normally valid. The default is up to the subclass. For most trait types, the default value for allow_none is False.

If read_only is True, attempts to directly modify a trait attribute raises a TraitError.

Extra metadata can be associated with the traitlet using the .tag() convenience method or by using the traitlet instance’s .metadata dictionary.

info()[source]
validate(obj, proposal)[source]
class thetis.configuration.DatetimeTraitlet(default_value=traitlets.Undefined, allow_none=False, read_only=None, help=None, config=None, **kwargs)[source]

Bases: traitlets.traitlets.TraitType

Declare a traitlet.

If allow_none is True, None is a valid value in addition to any values that are normally valid. The default is up to the subclass. For most trait types, the default value for allow_none is False.

If read_only is True, attempts to directly modify a trait attribute raises a TraitError.

Extra metadata can be associated with the traitlet using the .tag() convenience method or by using the traitlet instance’s .metadata dictionary.

default_value = None
info_text = 'a timezone-aware datetime object'
validate(obj, value)[source]
class thetis.configuration.FiredrakeCoefficient(default_value=traitlets.Undefined, allow_none=False, read_only=None, help=None, config=None, **kwargs)[source]

Bases: traitlets.traitlets.TraitType

Declare a traitlet.

If allow_none is True, None is a valid value in addition to any values that are normally valid. The default is up to the subclass. For most trait types, the default value for allow_none is False.

If read_only is True, attempts to directly modify a trait attribute raises a TraitError.

Extra metadata can be associated with the traitlet using the .tag() convenience method or by using the traitlet instance’s .metadata dictionary.

default_value = None
default_value_repr()[source]
info_text = 'a Firedrake Constant or Function'
validate(obj, value)[source]
class thetis.configuration.FiredrakeConstantTraitlet(default_value=traitlets.Undefined, allow_none=False, read_only=None, help=None, config=None, **kwargs)[source]

Bases: traitlets.traitlets.TraitType

Declare a traitlet.

If allow_none is True, None is a valid value in addition to any values that are normally valid. The default is up to the subclass. For most trait types, the default value for allow_none is False.

If read_only is True, attempts to directly modify a trait attribute raises a TraitError.

Extra metadata can be associated with the traitlet using the .tag() convenience method or by using the traitlet instance’s .metadata dictionary.

default_value = None
default_value_repr()[source]
info_text = 'a Firedrake Constant'
validate(obj, value)[source]
class thetis.configuration.FiredrakeScalarExpression(default_value=traitlets.Undefined, allow_none=False, read_only=None, help=None, config=None, **kwargs)[source]

Bases: traitlets.traitlets.TraitType

Declare a traitlet.

If allow_none is True, None is a valid value in addition to any values that are normally valid. The default is up to the subclass. For most trait types, the default value for allow_none is False.

If read_only is True, attempts to directly modify a trait attribute raises a TraitError.

Extra metadata can be associated with the traitlet using the .tag() convenience method or by using the traitlet instance’s .metadata dictionary.

default_value = None
default_value_repr()[source]
info_text = 'a scalar UFL expression'
validate(obj, value)[source]
class thetis.configuration.FiredrakeVectorExpression(default_value=traitlets.Undefined, allow_none=False, read_only=None, help=None, config=None, **kwargs)[source]

Bases: traitlets.traitlets.TraitType

Declare a traitlet.

If allow_none is True, None is a valid value in addition to any values that are normally valid. The default is up to the subclass. For most trait types, the default value for allow_none is False.

If read_only is True, attempts to directly modify a trait attribute raises a TraitError.

Extra metadata can be associated with the traitlet using the .tag() convenience method or by using the traitlet instance’s .metadata dictionary.

default_value = None
default_value_repr()[source]
info_text = 'a vector UFL expression'
validate(obj, value)[source]
class thetis.configuration.FrozenConfigurable(**kwargs)[source]

Bases: thetis.configuration.OptionsBase, traitlets.config.configurable.Configurable

A Configurable class that only allows adding new attributes in the class definition or when self._isfrozen is False.

class thetis.configuration.FrozenHasTraits(**kwargs)[source]

Bases: thetis.configuration.OptionsBase, traitlets.traitlets.HasTraits

class thetis.configuration.NonNegativeFloat(default_value=traitlets.Undefined, allow_none=False, **kwargs)[source]

Bases: traitlets.traitlets.Float

Declare a traitlet.

If allow_none is True, None is a valid value in addition to any values that are normally valid. The default is up to the subclass. For most trait types, the default value for allow_none is False.

If read_only is True, attempts to directly modify a trait attribute raises a TraitError.

Extra metadata can be associated with the traitlet using the .tag() convenience method or by using the traitlet instance’s .metadata dictionary.

info()[source]
validate(obj, proposal)[source]
class thetis.configuration.NonNegativeInteger(default_value=traitlets.Undefined, allow_none=False, **kwargs)[source]

Bases: traitlets.traitlets.Int

Declare a traitlet.

If allow_none is True, None is a valid value in addition to any values that are normally valid. The default is up to the subclass. For most trait types, the default value for allow_none is False.

If read_only is True, attempts to directly modify a trait attribute raises a TraitError.

Extra metadata can be associated with the traitlet using the .tag() convenience method or by using the traitlet instance’s .metadata dictionary.

info()[source]
validate(obj, proposal)[source]
class thetis.configuration.OptionsBase[source]

Bases: object

Abstract base class for all options classes

abstract property name

Human readable name of the configurable object

update(options)[source]

Assign options from another container

Parameters

options – Either a dictionary of options or another HasTraits object

class thetis.configuration.PETScSolverParameters(value_trait=None, per_key_traits=None, key_trait=None, default_value=traitlets.Undefined, **kwargs)[source]

Bases: traitlets.traitlets.Dict

PETSc solver options dictionary

Create a dict trait type from a Python dict.

The default value is created by doing dict(default_value), which creates a copy of the default_value.

value_traitTraitType [ optional ]

The specified trait type to check and use to restrict the values of the dict. If unspecified, values are not checked.

per_key_traitsDictionary of {keys:trait types} [ optional, keyword-only ]

A Python dictionary containing the types that are valid for restricting the values of the dict on a per-key basis. Each value in this dict should be a Trait for validating

key_traitTraitType [ optional, keyword-only ]

The type for restricting the keys of the dict. If unspecified, the types of the keys are not checked.

default_valueSequenceType [ optional, keyword-only ]

The default value for the Dict. Must be dict, tuple, or None, and will be cast to a dict if not None. If any key or value traits are specified, the default_value must conform to the constraints.

>>> d = Dict(Unicode())
a dict whose values must be text
>>> d2 = Dict(per_key_traits={"n": Integer(), "s": Unicode()})
d2['n'] must be an integer
d2['s'] must be text
>>> d3 = Dict(value_trait=Integer(), key_trait=Unicode())
d3's keys must be text
d3's values must be integers
info_text = 'a PETSc solver options dictionary'
validate(obj, value)[source]
class thetis.configuration.PairedEnum(values, paired_name, default_value=traitlets.Undefined, **kwargs)[source]

Bases: traitlets.traitlets.Enum

A enum whose value must be in a given sequence.

This enum controls a slaved option, with default values provided here.

Parameters
  • values – iterable of (value, HasTraits class) pairs. The HasTraits class will be called (with no arguments) to create default values if necessary.

  • paired_name – trait name this enum is paired with.

  • default_value – default value.

Declare a traitlet.

If allow_none is True, None is a valid value in addition to any values that are normally valid. The default is up to the subclass. For most trait types, the default value for allow_none is False.

If read_only is True, attempts to directly modify a trait attribute raises a TraitError.

Extra metadata can be associated with the traitlet using the .tag() convenience method or by using the traitlet instance’s .metadata dictionary.

info()[source]
class thetis.configuration.PositiveFloat(default_value=traitlets.Undefined, allow_none=False, **kwargs)[source]

Bases: traitlets.traitlets.Float

Declare a traitlet.

If allow_none is True, None is a valid value in addition to any values that are normally valid. The default is up to the subclass. For most trait types, the default value for allow_none is False.

If read_only is True, attempts to directly modify a trait attribute raises a TraitError.

Extra metadata can be associated with the traitlet using the .tag() convenience method or by using the traitlet instance’s .metadata dictionary.

info()[source]
validate(obj, proposal)[source]
class thetis.configuration.PositiveInteger(default_value=traitlets.Undefined, allow_none=False, **kwargs)[source]

Bases: traitlets.traitlets.Int

Declare a traitlet.

If allow_none is True, None is a valid value in addition to any values that are normally valid. The default is up to the subclass. For most trait types, the default value for allow_none is False.

If read_only is True, attempts to directly modify a trait attribute raises a TraitError.

Extra metadata can be associated with the traitlet using the .tag() convenience method or by using the traitlet instance’s .metadata dictionary.

info()[source]
validate(obj, proposal)[source]
thetis.configuration.attach_paired_options(name, name_trait, value_trait)[source]

Attach paired options to a Configurable object.

Parameters
  • name – the name of the enum trait

  • name_trait – the enum trait (a PairedEnum)

  • value_trait – the slaved value trait.

thetis.configuration.indent(s, nspaces)[source]
thetis.configuration.rst_all_options(cls, nspace=0, prefix=None)[source]

Recursively generate rST for a provided Configurable class.

Parameters
  • cls – The Configurable class.

  • nspace – Indentation level.

  • prefix – Prefix to use for new traits.

thetis.coordsys module

Generic methods for converting data between different spatial coordinate systems. Uses pyproj library.

class thetis.coordsys.CoordinateSystem[source]

Bases: abc.ABC

Base class for horizontal coordinate systems

Provides methods for coordinate transformations etc.

abstract get_vector_rotator(x, y)[source]

Returns a vector rotator object.

The rotator converst vector-valued data to/from longitude, latitude coordinates.

abstract to_lonlat(x, y)[source]

Convert coordinates to latitude and longitude

class thetis.coordsys.UTMCoordinateSystem(utm_zone)[source]

Bases: thetis.coordsys.CoordinateSystem

Represents Universal Transverse Mercator coordinate systems

get_mesh_lonlat_function(mesh2d)[source]

Construct a Function holding the mesh coordinates in longitude-latitude coordinates.

Parameters

mesh2d – the 2D mesh

get_vector_rotator(lon, lat)[source]

Returns a vector rotator object.

The rotator converts vector-valued data from longitude, latitude coordinates to mesh coordinate system.

to_lonlat(x, y, positive_lon=False)[source]

Convert (x, y) coordinates to (latitude, longitude)

Parameters
  • x (float or numpy.array_like) – x coordinate

  • y (float or numpy.array_like) – y coordinate

  • positive_lon – should positive longitude be enforced?

Returns

longitude, latitude coordinates

to_xy(lon, lat)[source]

Convert (latitude, longitude) coordinates to (x, y)

Parameters
  • lon – longitude coordinate

  • lat – latitude coordinate

Returns

x, y coordinates

class thetis.coordsys.VectorCoordSysRotation(source_sys, target_sys, x, y)[source]

Bases: object

Rotates vectors defined in source_sys coordinates to a different coordinate system.

Parameters
  • source_sys – pyproj coordinate system where (x, y) are defined in

  • target_sys – target pyproj coordinate system

  • x – x coordinate

  • y – y coordinate

thetis.coordsys.convert_coords(source_sys, target_sys, x, y)[source]

Converts coordinates from source_sys to target_sys

This function extends pyproj.transform method by handling NaNs correctly.

Parameters
  • source_sys – pyproj coordinate system where (x, y) are defined in

  • target_sys – target pyproj coordinate system

  • x (float or numpy.array_like) – x coordinate

  • y (float or numpy.array_like) – y coordinate

thetis.coordsys.get_vector_rotation_matrix(source_sys, target_sys, x, y, delta=None)[source]

Estimate rotation matrix that converts vectors defined in source_sys to target_sys.

Assume that we have a vector field defined in source_sys: vectors located at (x, y) define the x and y components. We can then rotate the vectors to represent x2 and y2 components of the target_sys by applying a local rotation:

R, theta = get_vector_rotation_matrix(source_sys, target_sys, x, lat)
v_xy = numpy.array([[v_x], [v_y]])
v_new = numpy.matmul(R, v_xy)
v_x2, v_y2 = v_new
thetis.coordsys.proj_transform(x, y, trans=None, source=None, destination=None)[source]

Transform coordinates from source to target system.

Parameters
  • x,y – coordinates, float or numpy.array_like

  • trans – pyproj Transformer object (optional)

  • source – source coordinate system, Proj object

  • destination – destination coordinate system, Proj object

thetis.coupled_timeintegrator module

Time integrators for solving coupled 2D-3D system of equations.

class thetis.coupled_timeintegrator.CoupledLeapFrogAM3(solver)[source]

Bases: thetis.coupled_timeintegrator.CoupledTimeIntegrator

Leap-Frog Adams-Moulton 3 time integrator for coupled 2D-3D problem

This is an ALE time integrator. Implementation follows the SLIM time integrator by Karna et al (2013)

Karna, et al. (2013). A baroclinic discontinuous Galerkin finite element model for coastal flows. Ocean Modelling, 61(0):1-20. http://dx.doi.org/10.1016/j.ocemod.2012.09.009

Parameters

solverFlowSolver object

advance(t, update_forcings=None, update_forcings3d=None)[source]

Advances the equations for one time step

Parameters
  • t (float) – simulation time

  • update_forcings – Optional user-defined function that takes simulation time and updates time-dependent boundary conditions of the 2D equations.

  • update_forcings3d – Optional user defined function that updates boundary conditions of the 3D equations

integrator_2d

alias of thetis.rungekutta.DIRK22

integrator_3d

alias of thetis.timeintegrator.LeapFrogAM3

integrator_vert_3d

alias of thetis.rungekutta.BackwardEuler

class thetis.coupled_timeintegrator.CoupledTimeIntegrator(solver)[source]

Bases: thetis.coupled_timeintegrator.CoupledTimeIntegratorBase, abc.ABC

Base class of mode-split time integrators that use 2D, 3D and implicit 3D time integrators.

Parameters

solverFlowSolver object

initialize()[source]

Assign initial conditions to all necessary fields

Initial conditions are read from fields dictionary.

abstract property integrator_2d

time integrator for 2D equations

abstract property integrator_3d

time integrator for explicit 3D equations (momentum, tracers)

abstract property integrator_vert_3d

time integrator for implicit 3D equations (vertical diffusion)

set_dt(dt, dt_2d)[source]

Set time step for the coupled time integrator

Parameters
  • dt (float) – Time step. This is the master (macro) time step used to march the 3D equations.

  • dt_2d (float) – Time step for 2D equations. For consistency dt_2d must be an integer fraction of dt. If 2D solver is implicit set dt_2d equal to dt.

class thetis.coupled_timeintegrator.CoupledTimeIntegratorBase(solver)[source]

Bases: thetis.timeintegrator.TimeIntegratorBase

Base class for coupled 2D-3D time integrators

Provides common functionality for updating diagnostic fields etc.

Parameters

solverFlowSolver object

class thetis.coupled_timeintegrator.CoupledTwoStageRK(solver)[source]

Bases: thetis.coupled_timeintegrator.CoupledTimeIntegrator

Coupled time integrator based on SSPRK(2,2) scheme

This ALE time integration method uses SSPRK(2,2) scheme to advance the 3D equations and a compatible implicit Trapezoid method to advance the 2D equations. Backward Euler scheme is used for vertical diffusion.

Parameters

solverFlowSolver object

advance(t, update_forcings=None, update_forcings3d=None)[source]

Advances the equations for one time step

Parameters
  • t (float) – simulation time

  • update_forcings – Optional user-defined function that takes simulation time and updates time-dependent boundary conditions of the 2D equations.

  • update_forcings3d – Optional user defined function that updates boundary conditions of the 3D equations

compute_mesh_velocity(istage)[source]

Computes mesh velocity for stage i

Must be called after updating the 2D mode.

Parameters

istage (int) – stage of the Runge-Kutta iteration

integrator_2d

alias of thetis.rungekutta.ESDIRKTrapezoid

integrator_3d

alias of thetis.timeintegrator.SSPRK22ALE

integrator_vert_3d

alias of thetis.rungekutta.BackwardEuler

store_elevation(istage)[source]

Store current elevation field for computing mesh velocity

Must be called before updating the 2D mode.

Parameters

istage (int) – stage of the Runge-Kutta iteration

thetis.coupled_timeintegrator.timed_stage()

Log.Stage(type cls, name)

thetis.coupled_timeintegrator_2d module

Time integrators for solving coupled shallow water equations with one tracer or sediment.

class thetis.coupled_timeintegrator_2d.CoupledTimeIntegrator2D(solver)[source]

Bases: thetis.timeintegrator.TimeIntegratorBase, abc.ABC

Base class of time integrator for coupled shallow water and tracer/sediment equations and exner equation

Parameters

solverFlowSolver object

advance(t, update_forcings=None)[source]

Advances equations for one time step

Parameters
  • t (float) – simulation time

  • update_forcings – user-defined function that takes the simulation time and updates any time-dependent boundary conditions

advance_picard(t, update_forcings=None)[source]
exner_integrator()[source]

time integrator for the exner equation

initialize(solution2d)[source]

Assign initial conditions to all necessary fields

Initial conditions are read from fields dictionary.

set_dt(dt)[source]

Set time step for the coupled time integrator

Parameters

dt (float) – Time step.

swe_integrator()[source]

time integrator for the shallow water equations

tracer_integrator()[source]

time integrator for the tracer equation

class thetis.coupled_timeintegrator_2d.GeneralCoupledTimeIntegrator2D(solver, integrators)[source]

Bases: thetis.coupled_timeintegrator_2d.CoupledTimeIntegrator2D

A CoupledTimeIntegrator2D which supports a general set of time integrators for the different components.

Parameters
  • solver – the FlowSolver2d object

  • integrators – dictionary of time integrators to be used for each equation

class thetis.coupled_timeintegrator_2d.NonHydrostaticTimeIntegrator2D(solver, swe_integrator, fs_integrator)[source]

Bases: thetis.coupled_timeintegrator_2d.CoupledTimeIntegrator2D

2D non-hydrostatic time integrator based on Shallow Water time integrator

This time integration method uses SWE time integrator to advance the hydrostatic equations, depth-integrated Poisson solver to be solved for NH pressure, and a free surface integrator to advance the free surface correction. Advancing in serial or in a whole time stepping depends on the selection of time integrators.

Parameters

solverFlowSolver object

advance(t, update_forcings=None)[source]

Advances equations for one time step.

initialize(solution2d)[source]

Assign initial conditions to all necessary fields

Initial conditions are read from fields dictionary.

thetis.coupled_timeintegrator_2d.timed_stage()

Log.Stage(type cls, name)

thetis.diagnostics module

Classes for computing diagnostics.

class thetis.diagnostics.HessianRecoverer2D(**kwargs)[source]

Bases: thetis.diagnostics.DiagnosticCalculator

Linear solver for recovering Hessians.

Hessians are recoved using double \(L^2\) projection, which is implemented using a mixed finite element method.

It is recommended that gradients and Hessians are sought in \(\mathbb P1\) space of appropriate dimension.

Parameters
  • field_2d – scalar expression to recover the Hessian of.

  • hessian_2dFunction to hold recovered Hessian.

  • gradient_2dFunction to hold recovered gradient.

Kwargs

to be passed to the LinearVariationalSolver.

field_2d
solve()[source]
class thetis.diagnostics.KineticEnergyCalculator(**kwargs)[source]

Bases: thetis.diagnostics.DiagnosticCalculator

Class for calculating dynamic pressure (i.e. kinetic energy),

\[E_K = \frac12 \rho \|\mathbf{u}\|^2,\]

where \(\rho\) is the water density and \(\mathbf{u}\) is the velocity.

Parameters
  • uv – scalar expression for the fluid velocity.

  • keFunction to hold calculated kinetic energy.

  • density – fluid density.

  • horizontal – consider the horizontal components of velocity only?

  • project – project, rather than interpolate?

density
solve()[source]
class thetis.diagnostics.VorticityCalculator2D(**kwargs)[source]

Bases: thetis.diagnostics.DiagnosticCalculator

Linear solver for recovering fluid vorticity, interpreted as a scalar field:

\[\omega = -v_x + u_y,\]

for a velocity field \(\mathbf{u} = (u, v)\).

It is recommended that the vorticity is sought in \(\mathbb P1\) space.

Parameters
  • uv_2d – vector expression for the horizontal velocity.

  • vorticity_2dFunction to hold calculated vorticity.

Kwargs

to be passed to the LinearVariationalSolver.

solve()[source]
uv_2d

thetis.equation module

Implements Equation and Term classes.

class thetis.equation.Equation(function_space)[source]

Bases: object

Implements an equation, made out of terms.

Parameters

function_space – the FunctionSpace the solution belongs to

SUPPORTED_LABELS = frozenset({'explicit', 'implicit', 'nonlinear', 'source'})

Valid labels for terms, indicating how they should be treated in the time integrator.

source

The term is a source term, i.e. does not depend on the solution.

explicit

The term should be treated explicitly

implicit

The term should be treated implicitly

nonlinear

The term is nonlinear and should be treated fully implicitly

add_term(term, label, suffix=None)[source]

Adds a term in the equation

Parameters
  • termTerm object to add_term

  • label (string) – Assign a label to the term. Valid labels are given by SUPPORTED_LABELS.

  • suffix – optional custom key suffix

jacobian(label, solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the Jacobian by summing up all the Jacobians of the terms.

Sign convention: all terms are assumed to be on the right hand side of the equation: d(u)/dt = term.

Parameters
  • label – string defining the type of terms to sum up. Currently one of ‘source’|’explicit’|’implicit’|’nonlinear’. Can be a list of multiple labels, or ‘all’ in which case all defined terms are summed.

  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

label_term(term, label)[source]

Assings a label to the given term(s).

Parameters
  • termTerm object, or a tuple of terms

  • label – string label to assign

mass_term(solution)[source]

Returns default mass matrix term for the solution function space.

Returns

UFL form of the mass term

residual(label, solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the residual by summing up all the terms with the desired label.

Sign convention: all terms are assumed to be on the right hand side of the equation: d(u)/dt = term.

Parameters
  • label – string defining the type of terms to sum up. Currently one of ‘source’|’explicit’|’implicit’|’nonlinear’. Can be a list of multiple labels, or ‘all’ in which case all defined terms are summed.

  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

select_terms(label)[source]

Generator function that selects terms by label(s).

label can be a single label (e.g. ‘explicit’), ‘all’ or a tuple of labels.

class thetis.equation.Term(function_space, test_function=None, trial_function=None)[source]

Bases: object

Implements a single term of an equation.

Note

Sign convention: all terms are assumed to be on the right hand side of the equation: d(u)/dt = term.

Parameters
  • function_space – the FunctionSpace the solution belongs to

  • test_function – custom TestFunction.

  • trial_function – custom TrialFunction.

jacobian(solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the Jacobian of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

residual(solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

thetis.equation.timed_stage()

Log.Stage(type cls, name)

thetis.exner_eq module

Exner equation

2D conservation of mass equation describing bed evolution due to sediment transport

The equation reads

(1)\[\frac{\partial z_b}{\partial t} + (m/(1-p)) \nabla_h \cdot \textbf{Q_b} = (m/(1-p)) H ((F_{sink} S) - F_{source})\]

where \(z_b\) is the bedlevel, \(S\) is \(HT\) for conservative (where H is depth and T is the sediment field) and \(T\) for non-conservative (where T is the sediment field), \(\nabla_h\) denotes horizontal gradient, \(m\) is the morphological scale factor, \(p\) is the porosity and \(\textbf{Q_b}\) is the bedload transport vector

class thetis.exner_eq.ExnerBedloadTerm(function_space, depth, sediment_model, depth_integrated_sediment=False)[source]

Bases: thetis.exner_eq.ExnerTerm

Bedload transport term, nabla_h cdot textbf{Q_b}

The weak form is

\[\int_\Omega \nabla_h \cdot \textbf{Q_b} \psi dx = - \int_\Omega (\textbf{Q_b} \cdot \nabla) \psi dx + \int_\Gamma \psi \textbf{Q_b} \cdot \textbf{n} dS\]

where \(\textbf{n}\) is the unit normal of the element interfaces.

Parameters
  • function_spaceFunctionSpace where the solution belongs

  • depthDepthExpression containing depth info

  • sediment_modelSedimentModel containing sediment info

  • depth_integrated_sediment (bool) – whether the sediment field is depth-integrated

residual(solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.exner_eq.ExnerEquation(function_space, depth, sediment_model, depth_integrated_sediment)[source]

Bases: thetis.equation.Equation

Exner equation

2D conservation of mass equation describing bed evolution due to sediment transport

Parameters
  • function_spaceFunctionSpace where the solution belongs

  • depth

    class

    DepthExpression containing depth info

  • sediment_model

    class

    SedimentModel containing sediment info

  • depth_integrated_sediment (bool) – whether to use conservative tracer

class thetis.exner_eq.ExnerSourceTerm(function_space, depth, sediment_model, depth_integrated_sediment=False)[source]

Bases: thetis.exner_eq.ExnerTerm

Source term accounting for suspended sediment transport

The weak form reads

\[F_s = \int_\Omega (\sigma - sediment * \phi) * depth \psi dx\]

where \(\sigma\) is a user defined source scalar field Function and \(\phi\) is a user defined source scalar field Function.

Parameters
  • function_spaceFunctionSpace where the solution belongs

  • depthDepthExpression containing depth info

  • sediment_modelSedimentModel containing sediment info

  • depth_integrated_sediment (bool) – whether the sediment field is depth-integrated

residual(solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.exner_eq.ExnerTerm(function_space, depth, sediment_model, depth_integrated_sediment=False)[source]

Bases: thetis.equation.Term

Generic term in the Exner equations that provides commonly used members There are no boundary conditions for the Exner equation.

Parameters
  • function_spaceFunctionSpace where the solution belongs

  • depthDepthExpression containing depth info

  • sediment_modelSedimentModel containing sediment info

  • depth_integrated_sediment (bool) – whether the sediment field is depth-integrated

thetis.exporter module

Routines for handling file exports.

class thetis.exporter.ExportManager(outputdir, fields_to_export, functions, field_metadata, export_type='vtk', next_export_ix=0, verbose=False, preproc_funcs={})[source]

Bases: object

Helper object for exporting multiple fields simultaneously

from .field_defs import field_metadata
field_dict = {'elev_2d': Function(...), 'uv_3d': Function(...), ...}
e = exporter.ExportManager('mydirectory',
                           ['elev_2d', 'uv_3d', salt_3d'],
                           field_dict,
                           field_metadata,
                           export_type='vtk')
e.export()
Parameters
  • outputdir (string) – directory where files are stored

  • fields_to_export (list of strings) – list of fields to export

  • functions – dict that contains all existing Function s

  • field_metadata – dict of all field metadata. See field_defs

  • export_type (str) – export format, either ‘vtk’ or ‘hdf5’

  • next_export_ix (int) – index for next export (default 0)

  • verbose (bool) – print debug info to stdout

add_export(fieldname, function, export_type='vtk', next_export_ix=0, outputdir=None, shortname=None, filename=None, preproc_func=None)[source]

Adds a new field exporter in the manager.

This method allows exporting both default Thetis fields and user defined fields. In the latter case the user must provide sufficient metadata, i.e. fieldname, shortname and filename.

Parameters
  • fieldname (string) – canonical field name

  • function – Firedrake function to export

  • export_type (str) – export format, either ‘vtk’ or ‘hdf5’

  • next_export_ix (int) – index for next export (default 0)

  • outputdir (string) – optional directory where files are stored

  • shortname (string) – override shortname defined in field_metadata

  • filename (string) – override filename defined in field_metadata

  • preproc_func – optional funtion that will be called prior to exporting. E.g. for computing diagnostic fields.

export()[source]

Export all designated functions to disk

Increments export index by 1.

export_bathymetry(bathymetry_2d)[source]

Special function to export 2D bathymetry data to disk

Parameters

bathymetry_2d – 2D bathymetry Function

set_next_export_ix(next_export_ix)[source]

Set export index to all child exporters

class thetis.exporter.ExporterBase(filename, outputdir, next_export_ix=0, verbose=False)[source]

Bases: object

Base class for exporter objects.

Parameters
  • filename (string) – output file name (without directory)

  • outputdir (string) – directory where file is stored

  • next_export_ix (int) – set the index for next output

  • verbose (bool) – print debug info to stdout

export(function)[source]

Exports given function to disk

set_next_export_ix(next_export_ix)[source]

Sets the index of next export

class thetis.exporter.HDF5Exporter(function_space, outputdir, filename_prefix, next_export_ix=0, verbose=False)[source]

Bases: thetis.exporter.ExporterBase

Stores fields in disk in native discretization using HDF5 containers

Create exporter object for given function.

Parameters
  • function_space (FunctionSpace) – space where the exported functions belong

  • outputdir (string) – directory where outputs will be stored

  • filename_prefix (string) – prefix of output filename. Filename is prefix_nnnnn.h5 where nnnnn is the export number.

  • next_export_ix (int) – index for next export (default 0)

  • verbose (bool) – print debug info to stdout

export(function)[source]

Export function to disk.

Increments export index by 1.

Parameters

functionFunction to export

export_as_index(iexport, function)[source]

Export function to disk using the specified export index number

Parameters
  • iexport (int) – export index >= 0

  • functionFunction to export

gen_filename(iexport)[source]

Generate file name ‘prefix_nnnnn.h5’ for i-th export

Parameters

iexport (int) – export index >= 0

load(iexport, function)[source]

Loads nodal values from disk and assigns to the given function

Parameters
  • iexport (int) – export index >= 0

  • function – target Function

class thetis.exporter.VTKExporter(fs_visu, func_name, outputdir, filename, next_export_ix=0, project_output=False, verbose=False)[source]

Bases: thetis.exporter.ExporterBase

Class that handles Paraview VTK file exports

Parameters
  • fs_visu – function space where input function will be cast before exporting

  • func_name – name of the function

  • outputdir – output directory

  • filename – name of the pvd file

  • next_export_ix (int) – index for next export (default 0)

  • project_output (bool) – project function to output space instead of interpolating

  • verbose (bool) – print debug info to stdout

export(function)[source]

Exports given function to disk

set_next_export_ix(next_export_ix)[source]

Sets the index of next export

thetis.exporter.get_visu_space(fs)[source]

Returns an appropriate VTK visualization space for a function space

Parameters

fs – function space

Returns

function space for VTK visualization

thetis.exporter.is_2d(fs)[source]

Tests wether a function space is 2D or 3D

thetis.exporter.timed_stage()

Log.Stage(type cls, name)

thetis.field_defs module

Definitions and meta data of fields

thetis.field_defs.field_metadata = {'baroc_head_3d': {'filename': 'BaroHead3d', 'name': 'Baroclinic head', 'shortname': 'Baroclinic head', 'unit': 'm'}, 'bathymetry_2d': {'filename': 'bathymetry2d', 'name': 'Bathymetry', 'shortname': 'Bathymetry', 'unit': 'm'}, 'buoy_freq_3d': {'filename': 'BuoyFreq3d', 'name': 'Buoyancy frequency squared', 'shortname': 'Buoyancy frequency squared', 'unit': 's-2'}, 'coriolis_2d': {'filename': 'coriolis_2d', 'name': 'Coriolis parameter', 'shortname': 'Coriolis parameter', 'unit': 's-1'}, 'coriolis_3d': {'filename': 'coriolis_3d', 'name': 'Coriolis parameter', 'shortname': 'Coriolis parameter', 'unit': 's-1'}, 'density_3d': {'filename': 'Density3d', 'name': 'Water density', 'shortname': 'Density', 'unit': 'kg m-3'}, 'eddy_diff_3d': {'filename': 'EddyDiff3d', 'name': 'Eddy diffusivity', 'shortname': 'Eddy diffusivity', 'unit': 'm2 s-1'}, 'eddy_visc_3d': {'filename': 'EddyVisc3d', 'name': 'Eddy Viscosity', 'shortname': 'Eddy Viscosity', 'unit': 'm2 s-1'}, 'elev_2d': {'filename': 'Elevation2d', 'name': 'Water elevation', 'shortname': 'Elevation', 'unit': 'm'}, 'elev_cg_2d': {'filename': 'ElevationCG2d', 'name': 'Water elevation CG', 'shortname': 'Elevation', 'unit': 'm'}, 'elev_domain_2d': {'filename': 'ElevationDomain2d', 'name': 'Surface elevation of domain', 'shortname': 'Elevation', 'unit': 'm'}, 'eps_3d': {'filename': 'TurbEps3d', 'name': 'TKE dissipation rate', 'shortname': 'TKE dissipation rate', 'unit': 'm2 s-3'}, 'h_elem_size_2d': {'filename': 'h_elem_size_2d', 'name': 'Element size in horizontal direction', 'shortname': 'Horizontal element size', 'unit': 'm'}, 'h_elem_size_3d': {'filename': 'h_elem_size_3d', 'name': 'Element size in horizontal direction', 'shortname': 'Horizontal element size', 'unit': 'm'}, 'hcc_metric_3d': {'filename': 'HCCMetric3d', 'name': 'HCC mesh quality', 'shortname': 'HCC metric', 'unit': '-'}, 'int_pg_3d': {'filename': 'IntPG3d', 'name': 'Internal pressure gradient', 'shortname': 'Int. Pressure gradient', 'unit': 'm s-2'}, 'len_3d': {'filename': 'TurbLen3d', 'name': 'Turbulent length scale', 'shortname': 'Turbulent length scale', 'unit': 'm'}, 'max_h_diff': {'filename': 'MaxHDiffusivity3d', 'name': 'Maximum stable horizontal diffusivity', 'shortname': 'Maximum horizontal diffusivity', 'unit': 'm2 s-1'}, 'psi_3d': {'filename': 'TurbPsi3d', 'name': 'Turbulence psi variable', 'shortname': 'Turbulence psi variable', 'unit': ''}, 'q_2d': {'filename': 'NHPressure2d', 'name': 'Non-hydrostatic pressure at bottom', 'shortname': 'NH pressure', 'unit': 'Pa'}, 'salt_3d': {'filename': 'Salinity3d', 'name': 'Water salinity', 'shortname': 'Salinity', 'unit': 'psu'}, 'sediment_2d': {'filename': 'Sediment2d', 'name': 'Sediment', 'shortname': 'Sediment', 'unit': ''}, 'shear_freq_3d': {'filename': 'ShearFreq3d', 'name': 'Vertical shear frequency squared', 'shortname': 'Vertical shear frequency squared', 'unit': 's-2'}, 'smag_visc_3d': {'filename': 'SmagViscosity3d', 'name': 'Smagorinsky viscosity', 'shortname': 'Smagorinsky viscosity', 'unit': 'm2 s-1'}, 'split_residual_2d': {'filename': 'SplitResidual2d', 'name': 'Momentum eq. residual for mode splitting', 'shortname': 'Momentum residual', 'unit': 'm s-2'}, 'temp_3d': {'filename': 'Temperature3d', 'name': 'Water temperature', 'shortname': 'Temperature', 'unit': 'C'}, 'tke_3d': {'filename': 'TurbKEnergy3d', 'name': 'Turbulent Kinetic Energy', 'shortname': 'Turbulent Kinetic Energy', 'unit': 'm2 s-2'}, 'uv_2d': {'filename': 'Velocity2d', 'name': 'Depth averaged velocity', 'shortname': 'Depth averaged velocity', 'unit': 'm s-1'}, 'uv_3d': {'filename': 'Velocity3d', 'name': 'Horizontal velocity', 'shortname': 'Horizontal velocity', 'unit': 'm s-1'}, 'uv_dav_2d': {'filename': 'DAVelocity2d', 'name': 'Depth averaged velocity', 'shortname': 'Depth averaged velocity', 'unit': 'm s-1'}, 'uv_dav_3d': {'filename': 'DAVelocity3d', 'name': 'Depth averaged velocity', 'shortname': 'Depth averaged velocity', 'unit': 'm s-1'}, 'v_elem_size_2d': {'filename': 'VElemSize2d', 'name': 'Element size in vertical direction', 'shortname': 'Vertical element size', 'unit': 'm'}, 'v_elem_size_3d': {'filename': 'VElemSize3d', 'name': 'Element size in vertical direction', 'shortname': 'Vertical element size', 'unit': 'm'}, 'w_2d': {'filename': 'VertVelo2d', 'name': 'Depth averaged vertical velocity', 'shortname': 'Depth averaged vertical velocity', 'unit': 'm s-1'}, 'w_3d': {'filename': 'VertVelo3d', 'name': 'Vertical velocity', 'shortname': 'Vertical velocity', 'unit': 'm s-1'}, 'w_mesh_3d': {'filename': 'MeshVelo3d', 'name': 'Mesh velocity', 'shortname': 'Mesh velocity', 'unit': 'm s-1'}, 'wind_stress_3d': {'filename': 'wind_stress_3d', 'name': 'Wind stress', 'shortname': 'Wind stress', 'unit': 'Pa'}, 'z_coord_3d': {'filename': 'ZCoord3d', 'name': 'Mesh z coordinates', 'shortname': 'Z coordinates', 'unit': 'm'}, 'z_coord_ref_3d': {'filename': 'ZCoordRef3d', 'name': 'Static mesh z coordinates', 'shortname': 'Z coordinates', 'unit': 'm'}}

Dictionary that contains the meta data of each field.

Required meta data entries are:

  • name: human readable description

  • shortname: description used in visualization etc

  • unit: SI unit of the field

  • filename: filename for output files

The naming convention for field keys is snake_case: field_name_3d

thetis.forcing module

Routines for interpolating forcing fields for the 3D solver.

class thetis.forcing.ATMInterpolator(function_space, wind_stress_field, atm_pressure_field, coord_system, ncfile_pattern, init_date, vect_rotator=None, east_wind_var_name='uwind', north_wind_var_name='vwind', pressure_var_name='prmsl', fill_mode=None, fill_value=nan, verbose=False)[source]

Bases: object

Interpolates WRF/NAM atmospheric model data on 2D fields.

Parameters
  • function_space – Target (scalar) FunctionSpace object onto which data will be interpolated.

  • wind_stress_field – A 2D vector Function where the output wind stress will be stored.

  • atm_pressure_field – A 2D scalar Function where the output atmospheric pressure will be stored.

  • coord_systemCoordinateSystem object

  • ncfile_pattern – A file name pattern for reading the atmospheric model output files. E.g. ‘forcings/nam_air.local.2006_*.nc’

  • init_date – A datetime object that indicates the start date/time of the Thetis simulation. Must contain time zone. E.g. ‘datetime(2006, 5, 1, tzinfo=pytz.utc)’

  • vect_rotator – function that rotates vectors from ENU coordinates to target function space (optional).

  • pressure_var_name (east_wind_var_name, north_wind_var_name,) – wind component and pressure field names in netCDF file.

  • fill_mode – Determines how points outside the source grid will be treated. If ‘nearest’, value of the nearest source point will be used. Otherwise a constant fill value will be used (default).

  • fill_value (float) – Set the fill value (default: NaN)

  • verbose (bool) – Se True to print debug information.

set_fields(time)[source]

Evaluates forcing fields at the given time.

Performs interpolation and updates the output wind stress and atmospheric pressure fields in place.

Parameters

time (float) – Thetis simulation time in seconds.

class thetis.forcing.ATMNetCDFTime(filename, max_duration=None, verbose=False)[source]

Bases: thetis.interpolation.NetCDFTimeParser

A TimeParser class for reading atmosphere model output files.

Parameters
  • filename

  • max_duration – Time span to read from each file (in seconds). E.g. forecast files can consist of daily files with > 1 day of data. In this case max_duration should be set to 24 h. If None, all time steps are loaded. Default: None.

  • verbose (bool) – Se True to print debug information.

class thetis.forcing.FES2004TidalBoundaryForcing(elev_field, init_date, coord_system, vect_rotator=None, uv_field=None, constituents=None, boundary_ids=None, data_dir=None)[source]

Bases: thetis.forcing.TidalBoundaryForcing

Tidal boundary interpolator for FES2004 tidal model.

Parameters
  • elev_field – Function where tidal elevation will be interpolated.

  • init_date – Datetime object defining the simulation init time.

  • coord_systemCoordinateSystem object

  • vect_rotator – User-defined vector rotator function

  • uv_field – Function where tidal transport will be interpolated.

  • constituents – list of tidal constituents, e.g. [‘M2’, ‘K1’]

  • boundary_ids – list of boundary_ids where tidal data will be evaluated. If not defined, tides will be in evaluated in the entire domain.

  • data_dir – path to directory where tidal model netCDF files are located.

compute_velocity = False
coord_layout = 'lat,lon'
elev_nc_file = 'tide.fes2004.nc'
grid_nc_file = None
uv_nc_file = None
class thetis.forcing.GenericInterpolator2D(function_space, fields, field_names, ncfile_pattern, init_date, coord_system, vector_field=None, vector_components=None, vector_rotator=None)[source]

Bases: object

Interpolates 2D fields from netCDF files.

The grid latitude, longitude coordinates must be defined in 1D arrays with CF standard_name attributes “latitude” and “longitude”. Time must be defined with cftime compliant units and metadata.

set_fields(time)[source]

Evaluates forcing fields at the given time

class thetis.forcing.GenericSpatialInterpolator2D(function_space, coord_system, fill_mode=None, fill_value=nan)[source]

Bases: thetis.interpolation.SpatialInterpolator2d

Spatial interpolator class for interpolating netCDF 2D fields.

Parameters
  • function_space – target Firedrake FunctionSpace

  • coord_systemCoordinateSystem object

  • fill_mode – Determines how points outside the source grid will be treated. If ‘nearest’, value of the nearest source point will be used. Otherwise a constant fill value will be used (default).

  • fill_value (float) – Set the fill value (default: NaN)

interpolate(nc_filename, variable_list, itime)[source]

Calls the interpolator object

class thetis.forcing.LiveOceanInterpolator(function_space, fields, field_names, ncfile_pattern, init_date, coord_system)[source]

Bases: object

Interpolates LiveOcean (ROMS) model data on 3D fields

set_fields(time)[source]

Evaluates forcing fields at the given time

class thetis.forcing.NCOMInterpolator(function_space_2d, function_space_3d, fields, field_names, field_fnstr, coord_system, basedir, file_pattern, init_date, verbose=False)[source]

Bases: object

Interpolates NCOM model data on 3D fields.

Note

The following NCOM output files must be present: ./forcings/ncom/model_h.nc ./forcings/ncom/model_lat.nc ./forcings/ncom/model_ang.nc ./forcings/ncom/model_lon.nc ./forcings/ncom/model_zm.nc ./forcings/ncom/2006/s3d/s3d.glb8_2f_2006041900.nc ./forcings/ncom/2006/s3d/s3d.glb8_2f_2006042000.nc ./forcings/ncom/2006/t3d/t3d.glb8_2f_2006041900.nc ./forcings/ncom/2006/t3d/t3d.glb8_2f_2006042000.nc ./forcings/ncom/2006/u3d/u3d.glb8_2f_2006041900.nc ./forcings/ncom/2006/u3d/u3d.glb8_2f_2006042000.nc ./forcings/ncom/2006/v3d/v3d.glb8_2f_2006041900.nc ./forcings/ncom/2006/v3d/v3d.glb8_2f_2006042000.nc ./forcings/ncom/2006/ssh/ssh.glb8_2f_2006041900.nc ./forcings/ncom/2006/ssh/ssh.glb8_2f_2006042000.nc

Parameters
  • function_space_2d – Target (scalar) FunctionSpace object onto which 2D data will be interpolated.

  • function_space_3d – Target (scalar) FunctionSpace object onto which 3D data will be interpolated.

  • fields – list of Function objects where data will be stored.

  • field_names – List of netCDF variable names for the fields. E.g. [‘Salinity’, ‘Temperature’].

  • field_fnstr – List of variables in netCDF file names. E.g. [‘s3d’, ‘t3d’].

  • coord_systemCoordinateSystem object

  • basedir – Root dir where NCOM files are stored. E.g. ‘/forcings/ncom’.

  • file_pattern – A file name pattern for reading the NCOM output files (excluding the basedir). E.g. {year:04d}/{fieldstr:}/{fieldstr:}.glb8_2f_{year:04d}{month:02d}{day:02d}00.nc’.

  • init_date – A datetime object that indicates the start date/time of the Thetis simulation. Must contain time zone. E.g. ‘datetime(2006, 5, 1, tzinfo=pytz.utc)’

  • verbose (bool) – Se True to print debug information.

set_fields(time)[source]

Evaluates forcing fields at the given time

class thetis.forcing.SpatialInterpolatorNCOM2d(function_space, coord_system, grid_path)[source]

Bases: thetis.forcing.SpatialInterpolatorNCOMBase

Spatial interpolator class for interpolating NCOM ocean model 2D fields.

Parameters
  • function_space – Target (scalar) FunctionSpace object onto which data will be interpolated.

  • coord_systemCoordinateSystem object

  • grid_path – File path where the NCOM model grid files (‘model_lat.nc’, ‘model_lon.nc’, ‘model_zm.nc’) are located.

interpolate(nc_filename, variable_list, itime)[source]

Calls the interpolator object

class thetis.forcing.SpatialInterpolatorNCOM3d(function_space, coord_system, grid_path)[source]

Bases: thetis.forcing.SpatialInterpolatorNCOMBase

Spatial interpolator class for interpolating NCOM ocean model 3D fields.

Parameters
  • function_space – Target (scalar) FunctionSpace object onto which data will be interpolated.

  • coord_systemCoordinateSystem object

  • grid_path – File path where the NCOM model grid files (‘model_lat.nc’, ‘model_lon.nc’, ‘model_zm.nc’) are located.

interpolate(nc_filename, variable_list, itime)[source]

Calls the interpolator object

class thetis.forcing.SpatialInterpolatorNCOMBase(function_space, coord_system, grid_path)[source]

Bases: thetis.interpolation.SpatialInterpolator

Base class for 2D and 3D NCOM spatial interpolators.

Parameters
  • function_space – Target (scalar) FunctionSpace object onto which data will be interpolated.

  • coord_systemCoordinateSystem object

  • grid_path – File path where the NCOM model grid files (‘model_lat.nc’, ‘model_lon.nc’, ‘model_zm.nc’) are located.

class thetis.forcing.SpatialInterpolatorROMS3d(function_space, coord_system)[source]

Bases: thetis.interpolation.SpatialInterpolator

Abstract spatial interpolator class that can interpolate onto a Function

Parameters
  • function_space – target Firedrake FunctionSpace

  • coord_systemCoordinateSystem object

interpolate(nc_filename, variable_list, itime)[source]

Calls the interpolator object

class thetis.forcing.TPXOTidalBoundaryForcing(elev_field, init_date, coord_system, vect_rotator=None, uv_field=None, constituents=None, boundary_ids=None, data_dir=None, elev_file='h_tpxo9.v5a.nc', uv_file='u_tpxo9.v5a.nc', grid_file='gridtpxo9v5a.nc')[source]

Bases: thetis.forcing.TidalBoundaryForcing

Interpolator for TPXO global tidal model data.

See the TPXO website for data access. By default, this routine assumes the tpxo9v5a data set in NetCDF format. Other versions can be used by setting correct elev_file, uv_file, and grid_file arguments.

Parameters
  • elev_field – Function where tidal elevation will be interpolated.

  • init_date – Datetime object defining the simulation init time.

  • coord_systemCoordinateSystem object

  • vect_rotator – User-defined vector rotator function

  • uv_field – Function where tidal transport will be interpolated.

  • constituents – list of tidal constituents, e.g. [‘M2’, ‘K1’]

  • boundary_ids – list of boundary_ids where tidal data will be evaluated. If not defined, tides will be in evaluated in the entire domain.

  • data_dir – path to directory where tidal model netCDF files are located.

  • elev_file – TPXO tidal elevation file

  • uv_file – TPXO transport/velocity file

  • grid_file – TPXO grid file

compute_velocity = True
coord_layout = 'lon,lat'
class thetis.forcing.TidalBoundaryForcing(elev_field, init_date, coord_system, vect_rotator=None, uv_field=None, constituents=None, boundary_ids=None, data_dir=None)[source]

Bases: abc.ABC

Base class for tidal boundary interpolators.

Parameters
  • elev_field – Function where tidal elevation will be interpolated.

  • init_date – Datetime object defining the simulation init time.

  • coord_systemCoordinateSystem object

  • vect_rotator – User-defined vector rotator function

  • uv_field – Function where tidal transport will be interpolated.

  • constituents – list of tidal constituents, e.g. [‘M2’, ‘K1’]

  • boundary_ids – list of boundary_ids where tidal data will be evaluated. If not defined, tides will be in evaluated in the entire domain.

  • data_dir – path to directory where tidal model netCDF files are located.

abstract property compute_velocity

If True, compute tidal currents as well.

abstract property coord_layout

Data layout in the netcdf files.

Either ‘lon,lat’ or ‘lat,lon’.

set_tidal_field(t)[source]
thetis.forcing.compute_wind_stress(wind_u, wind_v, method='LargeYeager2009')[source]

Compute wind stress from atmospheric 10 m wind.

wind stress is defined as

where \(C_D\) is the drag coefficient, \(\rho_{air}\) is the density of air, and \(U_{10}\) is wind speed 10 m above the sea surface.

In practice C_D depends on the wind speed.

Two formulation are currently implemented:

  • “LargePond1981”:

    Wind stress formulation by [1]

  • “SmithBanke1975”:

    Wind stress formulation by [2]

  • “LargeYeager2009”:

    Wind stress formulation by [3]

[1] Large and Pond (1981). Open Ocean Momentum Flux Measurements in

Moderate to Strong Winds. Journal of Physical Oceanography, 11(3):324-336. https://doi.org/10.1175/1520-0485(1981)011%3C0324:OOMFMI%3E2.0.CO;2

[2] Smith and Banke (1975). Variation of the sea surface drag coefficient

with wind speed. Q J R Meteorol Soc., 101(429):665-673. https://doi.org/10.1002/qj.49710142920

[3] Large and Yeager (2009). The global climatology of an interannually

varying air–sea flux data set. Climate Dynamics, 33:341–364. http://dx.doi.org/10.1007/s00382-008-0441-3

Parameters
  • wind_v (wind_u,) – Wind u and v components as numpy arrays

  • method – Choose the stress formulation. Currently supports: ‘LargeYeager2009’ (default), ‘LargePond1981’, or ‘SmithBanke1975’.

Returns

(tau_x, tau_y) wind stress x and y components as numpy arrays

thetis.implicitexplicit module

Implicit-explicit time integrators

class thetis.implicitexplicit.IMEXEuler(equation, solution, fields, dt, options, bnd_conditions)[source]

Bases: thetis.implicitexplicit.IMEXGeneric

Forward-Backward Euler

Parameters
  • equation (Equation object) – equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

dirk_class

alias of thetis.rungekutta.BackwardEuler

erk_class

alias of thetis.rungekutta.ERKEuler

class thetis.implicitexplicit.IMEXGeneric(equation, solution, fields, dt, options, bnd_conditions)[source]

Bases: thetis.timeintegrator.TimeIntegrator, abc.ABC

Generic implementation of Runge-Kutta Implicit-Explicit schemes

Derived classes must define the implicit dirk_class and explicit erk_class Runge-Kutta time integrator classes.

This method solves the linearized equations: All implicit terms are fed to the implicit solver, while all the other terms are fed to the explicit solver. In case of non-linear terms proper linearization must defined in the equation using the two solution functions (solution, solution_old)

Parameters
  • equation (Equation object) – equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

advance(t, update_forcings=None)[source]

Advances equations for one time step.

abstract property dirk_class

Implicit DIRK class

abstract property erk_class

Explicit Runge-Kutta class

get_final_solution()[source]

Evaluates the final solution.

initialize(solution)[source]

Assigns initial conditions to all required fields.

set_dt(dt)[source]

Update time step

Parameters

dt (float) – time step

solve_stage(i_stage, t, update_forcings=None)[source]

Solves i-th stage

update_solver()[source]

Create solver objects

class thetis.implicitexplicit.IMEXLPUM2(equation, solution, fields, dt, options, bnd_conditions)[source]

Bases: thetis.implicitexplicit.IMEXGeneric

SSP-IMEX RK scheme (20) in Higureras et al. (2014)

CFL coefficient is 2.0

Higueras et al (2014). Optimized strong stability preserving IMEX Runge-Kutta methods. Journal of Computational and Applied Mathematics 272(2014) 116-140. http://dx.doi.org/10.1016/j.cam.2014.05.011

Parameters
  • equation (Equation object) – equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

dirk_class

alias of thetis.rungekutta.DIRKLPUM2

erk_class

alias of thetis.rungekutta.ERKLPUM2

class thetis.implicitexplicit.IMEXLSPUM2(equation, solution, fields, dt, options, bnd_conditions)[source]

Bases: thetis.implicitexplicit.IMEXGeneric

SSP-IMEX RK scheme (17) in Higureras et al. (2014)

CFL coefficient is 2.0

Higueras et al (2014). Optimized strong stability preserving IMEX Runge-Kutta methods. Journal of Computational and Applied Mathematics 272(2014) 116-140. http://dx.doi.org/10.1016/j.cam.2014.05.011

Parameters
  • equation (Equation object) – equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

dirk_class

alias of thetis.rungekutta.DIRKLSPUM2

erk_class

alias of thetis.rungekutta.ERKLSPUM2

class thetis.implicitexplicit.IMEXMidpoint(equation, solution, fields, dt, options, bnd_conditions)[source]

Bases: thetis.implicitexplicit.IMEXGeneric

Implicit-explicit midpoint scheme (1, 2, 2) from Ascher et al. (1997)

Ascher et al. (1997). Implicit-explicit Runge-Kutta methods for time-dependent partial differential equations. Applied Numerical Mathematics, 25:151-167. http://dx.doi.org/10.1137/0732037

Parameters
  • equation (Equation object) – equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

dirk_class

alias of thetis.rungekutta.ESDIRKMidpoint

erk_class

alias of thetis.rungekutta.ERKMidpoint

thetis.implicitexplicit.timed_region()

Log.Event(type cls, name, klass=None)

thetis.implicitexplicit.timed_stage()

Log.Stage(type cls, name)

thetis.interpolation module

Methods for interpolating data from structured data sets on Thetis fields.

Simple example of an atmospheric pressure interpolator:

class WRFInterpolator(object):
    # Interpolates WRF atmospheric model data on 2D fields
    def __init__(self, function_space, atm_pressure_field, ncfile_pattern, init_date):
        self.atm_pressure_field = atm_pressure_field

        # object that interpolates forcing data from structured grid on the local mesh
        self.grid_interpolator = NetCDFLatLonInterpolator2d(function_space, coord_system)
        # reader object that can read fields from netCDF files, applies spatial interpolation
        self.reader = NetCDFSpatialInterpolator(self.grid_interpolator, ['prmsl'])
        # object that can find previous/next time stamps in a collection of netCDF files
        self.timesearch_obj = NetCDFTimeSearch(ncfile_pattern, init_date, NetCDFTimeParser)
        # finally a linear intepolator class that performs linar interpolation in time
        self.interpolator = LinearTimeInterpolator(self.timesearch_obj, self.reader)

    def set_fields(self, time):
        # Evaluates forcing fields at the given time
        pressure = self.interpolator(time)
        self.atm_pressure_field.dat.data_with_halos[:] = pressure

Usage:

atm_pressure_2d = Function(solver_obj.function_spaces.P1_2d, name='atm pressure')
wrf_pattern = 'forcings/atm/wrf/wrf_air.2016_*_*.nc'
wrf_atm = WRFInterpolator(
    solver_obj.function_spaces.P1_2d,
    wind_stress_2d, atm_pressure_2d, wrf_pattern, init_date)
simulation_time = 3600.
wrf_atm.set_fields(simulation_time)
class thetis.interpolation.DailyFileTimeSearch(file_pattern, init_date, verbose=False, center_hour=12, center_timezone=<UTC>)[source]

Bases: thetis.interpolation.TimeSearch

Treats a list of daily files as a time series.

File name pattern must be given as a string where the 4-digit year is tagged with “{year:04d}”, and 2-digit zero-padded month and year are tagged with “{month:02d}” and “{day:02d}”, respectively. The tags can be used multiple times.

Example pattern:

‘ncom/{year:04d}/s3d.glb8_2f_{year:04d}{month:02d}{day:02d}00.nc’

In this time search method the time stamps are parsed solely from the filename, no other metadata is used. By default the data is assumed to be centered at 12:00 UTC every day.

find(simulation_time, previous=False)[source]

Find file that contains the given simulation time

Parameters
  • simulation_time (float) – simulation time in seconds

  • previous (bool) – if True finds previous existing time stamp instead of next (default False).

Returns

(filename, time index, simulation time) of found data

simulation_time_to_datetime(t)[source]
class thetis.interpolation.FileTreeReader[source]

Bases: object

Abstract base class of file tree reader object

class thetis.interpolation.GridInterpolator(grid_xyz, target_xyz, fill_mode=None, fill_value=nan, normalize=False, dont_raise=False)[source]

Bases: object

A reuseable griddata interpolator object.

Usage:

interpolator = GridInterpolator(source_xyz, target_xyz)
vals = interpolator(source_data)

Example:

x0 = numpy.linspace(0, 10, 10)
y0 = numpy.linspace(5, 10, 10)
X, Y = numpy.meshgrid(x, y)
x = X.ravel(); y = Y.ravel()
data = x + 25.*y
x_target = numpy.linspace(1, 10, 20)
y_target = numpy.linspace(5, 10, 20)
interpolator = GridInterpolator(numpy.vstack((x, y)).T, numpy.vstack((target_x, target_y)).T)
vals = interpolator(data)

Based on http://stackoverflow.com/questions/20915502/speedup-scipy-griddata-for-multiple-interpolations-between-two-irregular-grids

Parameters
  • grid_xyz – Array of source grid coordinates, shape (npoints, 2) or (npoints, 3)

  • target_xyz – Array of target grid coordinates, shape (n, 2) or (n, 3)

  • fill_mode – Determines how points outside the source grid will be treated. If ‘nearest’, value of the nearest source point will be used. Otherwise a constant fill value will be used (default).

  • fill_value (float) – Set the fill value (default: NaN)

  • normalize (bool) – If true the data is scaled to unit cube before interpolation. Default: False.

  • dont_raise (bool) – Do not raise a Qhull error if triangulation fails. In this case the data will be set to fill value or nearest neighbor value.

class thetis.interpolation.LinearTimeInterpolator(timesearch_obj, reader)[source]

Bases: object

Interpolates time series in time

User must provide timesearch_obj that finds time stamps from a file tree, and a reader that can read those time stamps into numpy arrays.

Previous/next data sets are cached in memory to avoid hitting disk every time.

Parameters
  • timesearch_obj – TimeSearch object

  • reader – FileTreeReader object

class thetis.interpolation.NetCDFLatLonInterpolator2d(function_space, coord_system, fill_mode=None, fill_value=nan)[source]

Bases: thetis.interpolation.SpatialInterpolator2d

Interpolates netCDF data on a local 2D unstructured mesh

The intepolator is constructed for a single netCDF file that defines the source grid. Once the interpolator has been constructed, data can be read from any file that uses the same grid.

This routine returns the data in numpy arrays.

Usage:

fs = FunctionSpace(...)
myfunc = Function(fs, ...)
ncinterp2d = NetCDFLatLonInterpolator2d(fs, coord_system, nc_filename)
val1, val2 = ncinterp2d.interpolate(nc_filename, ['var1', 'var2'], 10)
myfunc.dat.data_with_halos[:] = val1 + val2
Parameters
  • function_space – target Firedrake FunctionSpace

  • coord_systemCoordinateSystem object

  • fill_mode – Determines how points outside the source grid will be treated. If ‘nearest’, value of the nearest source point will be used. Otherwise a constant fill value will be used (default).

  • fill_value (float) – Set the fill value (default: NaN)

interpolate(nc_filename, variable_list, itime)[source]

Interpolates data from a netCDF file onto Firedrake function space.

Parameters
  • nc_filename (str) – netCDF file to read

  • variable_list – list of netCDF variable names to read

  • itime (int) – time index to read

Returns

list of numpy.arrays corresponding to variable_list

class thetis.interpolation.NetCDFSpatialInterpolator(grid_interpolator, variable_list)[source]

Bases: thetis.interpolation.FileTreeReader

Wrapper class that provides FileTreeReader API for grid interpolators

class thetis.interpolation.NetCDFTimeParser(filename, time_variable_name='time', allow_gaps=False, verbose=False)[source]

Bases: thetis.interpolation.TimeParser

Describes the time stamps stored in a netCDF file.

Construct a new object by scraping data from the given netcdf file.

Parameters
  • filename (str) – name of the netCDF file to read

  • time_variable_name (str) – name of the time variable in the netCDF file (default: ‘time’)

  • allow_gaps (bool) – if False, an error is raised if time step is not constant.

find_time_stamp(t, previous=False)[source]

Given time t, returns index of the next (previous) time stamp

raises IndexError if t is out of range, i.e. t > self.get_end_time() or t < self.get_start_time()

get_end_time()[source]

Returns the last time stamp in the file/data set

get_start_time()[source]

Returns the first time stamp in the file/data set

class thetis.interpolation.NetCDFTimeSearch(file_pattern, init_date, netcdf_class, *args, **kwargs)[source]

Bases: thetis.interpolation.TimeSearch

Finds a nearest time stamp in a collection of netCDF files.

find(simulation_time, previous=False)[source]

Find file that contains the given simulation time

Parameters
  • simulation_time (float) – simulation time in seconds

  • previous (bool) – if True finds previous existing time stamp instead of next (default False).

Returns

(filename, time index, simulation time) of found data

simulation_time_to_datetime(t)[source]
class thetis.interpolation.NetCDFTimeSeriesInterpolator(ncfile_pattern, variable_list, init_date, time_variable_name='time', scalars=None, allow_gaps=False)[source]

Bases: object

Reads and interpolates scalar time series from a sequence of netCDF files.

Parameters
  • ncfile_pattern (str) – file search pattern, e.g. “mydir/foo_*.nc”

  • variable_list – list if netCDF variable names to read

  • init_date (datetime.datetime) – simulation start time

  • scalars – (optional) list of scalars; scale output variables by a factor.

Note

All the variables must have the same dimensions in the netCDF files. If the shapes differ, create separate interpolator instances.

class thetis.interpolation.NetCDFTimeSeriesReader(variable_list, time_variable_name='time')[source]

Bases: thetis.interpolation.FileTreeReader

A simple netCDF reader that returns a time slice of the given variable.

This class does not interpolate the data in any way. Useful for interpolating time series.

class thetis.interpolation.SpatialInterpolator(function_space, coord_system)[source]

Bases: abc.ABC

Abstract base class for spatial interpolators that read data from disk

Parameters
  • function_space – target Firedrake FunctionSpace

  • coord_systemCoordinateSystem object

abstract interpolate(filename, variable_list, itime)[source]

Interpolates data from the given file at given time step

class thetis.interpolation.SpatialInterpolator2d(function_space, coord_system, fill_mode=None, fill_value=nan)[source]

Bases: thetis.interpolation.SpatialInterpolator, abc.ABC

Abstract spatial interpolator class that can interpolate onto a 2D Function

Parameters
  • function_space – target Firedrake FunctionSpace

  • coord_systemCoordinateSystem object

  • fill_mode – Determines how points outside the source grid will be treated. If ‘nearest’, value of the nearest source point will be used. Otherwise a constant fill value will be used (default).

  • fill_value (float) – Set the fill value (default: NaN)

abstract interpolate(filename, variable_list, time)[source]

Calls the interpolator object

class thetis.interpolation.TimeParser[source]

Bases: object

Abstract base class for time definition objects.

Defines the time span that a file (or data set) covers and provides a time index search routine.

abstract find_time_stamp(t, previous=False)[source]

Given time t, returns index of the next (previous) time stamp

raises IndexError if t is out of range, i.e. t > self.get_end_time() or t < self.get_start_time()

abstract get_end_time()[source]

Returns the last time stamp in the file/data set

abstract get_start_time()[source]

Returns the first time stamp in the file/data set

class thetis.interpolation.TimeSearch[source]

Bases: object

Base class for searching nearest time steps in a file tree or database

abstract find(time, previous=False)[source]

Find a next (previous) time stamp from a given time

Parameters
  • time (float) – input time stamp

  • previous (bool) – if True, look for last time stamp before requested time. Otherwise returns next time stamp.

Returns

a (filename, time_index, time) tuple

thetis.interpolation.get_ncvar_name(ncfile, standard_name=None, long_name=None, var_name=None)[source]

Look for variables that match either CF standard_name or long_name attributes.

If both are defined, standard_name takes precedence.

Note that the attributes in the netCDF file converted to lower case prior to checking.

Parameters
  • ncfile – netCDF4 Dataset object

  • standard_name – a target standard_name, or a list of them

  • long_name – a target long_name, or a list of them

  • var_name – a target netCDF variable name, or a list of them

thetis.inversion_tools module

class thetis.inversion_tools.ControlRegularizationCalculator(function, gamma_hessian)[source]

Bases: object

Computes regularization cost function for a control Function.

\[J = \gamma | H(f) |^2\]

where \(H\) is the Hessian of field math:f:.

Parameters
  • function – Control Function

  • gamma_Hessian – Hessian penalty coefficient

eval_cost_function()[source]
class thetis.inversion_tools.ControlRegularizationManager(function_list, gamma_list, J_scalar=None)[source]

Bases: object

Handles regularization of multiple control fields

Parameters
  • function_list – list of control functions

  • gamma_list – list of penalty parameters

  • J_scalar – Penalty term scaling factor

eval_cost_function()[source]
class thetis.inversion_tools.InversionManager(**kwargs)[source]

Bases: thetis.configuration.FrozenHasTraits

Class for handling inversion problems and stashing the progress of the associated optimization routines.

Parameters
  • sta_manager – the StationManager instance

  • output_dir – model output directory

  • no_exports – toggle exports to vtu

  • real – is the inversion in the Real space?

  • penalty_parameters – a list of penalty parameters to pass to the ControlRegularizationManager

  • cost_function_scaling – global scaling for the cost function. As rule of thumb, it’s good to scale the functional to J < 1.

  • test_consistency – toggle testing the correctness with which the ReducedFunctional can recompute values

  • test_gradient – toggle testing the correctness with which the ReducedFunctional can recompute gradients

add_control(f)[source]

Add a control field.

Can be called multiple times in case of multiparameter optimization.

Parameters

f – Function or Constant to be used as a control variable.

consistency_test()[source]

Test that reduced_functional can correctly recompute the objective value, assuming that none of the controls have changed since it was created.

get_cost_function(solver_obj, weight_by_variance=False)[source]

Get a sum of square errors cost function for the problem:

..math::

J(u) = sum_{i=1}^{n_{ts}} sum_{j=1}^{n_{sta}} (u_j^{(i)} - u_{j,o}^{(i)})^2,

where \(u_{j,o}^{(i)}\) and \(u_j^{(i)}\) denote the observed and computed values at timestep \(i\), and \(n_{ts}\) and \(n_{sta}\) are the numbers of timesteps and stations, respectively.

Regularization terms are included if a RegularizationManager instance is provided.

arg solver_obj

the FlowSolver2d instance

kwarg weight_by_variance

should the observation data be weighted by the variance at each station?

get_optimization_callback()[source]

Get a callback for stashing optimization progress after successful line search.

initialize()[source]
minimize(opt_method='BFGS', bounds=None, **opt_options)[source]

Minimize the reduced functional using a given optimization routine.

Parameters
  • opt_method – the optimization routine

  • bounds – a list of bounds to pass to the optimization routine

  • opt_options – other optimization parameters to pass

property reduced_functional

Create a Pyadjoint ReducedFunctional for the optimization.

reset_counters()[source]
property rf_kwargs

Default keyword arguments to pass to the ReducedFunctional class.

set_control_state(j, djdm_list, m_list)[source]

Stores optimization state.

To call whenever variables are updated.

Parameters
  • j – error functional value

  • djdm_list – list of gradient functions

  • m_list – list of control coefficents

set_initial_state(*state)[source]
start_clock()[source]
stop_annotating()[source]

Stop recording operations for the adjoint solver.

This method should be called after the iterate() method of FlowSolver2d.

stop_clock()[source]
taylor_test()[source]

Run a Taylor test to check that the reduced_functional can correctly compute consistent gradients.

Note that the Taylor test is applied on the current control values.

update_progress()[source]

Updates optimization progress and stores variables to disk.

To call after successful line searches.

class thetis.inversion_tools.StationObservationManager(mesh, output_directory='outputs')[source]

Bases: object

Implements error functional based on observation time series.

The functional is the squared sum of error between the model and observations.

This object evaluates the model fields at the station locations, interpolates the observations time series to the model time, computes the error functional, and also stores the model’s time series data to disk.

Parameters
  • mesh – the 2D mesh object.

  • output_directory – directory where model time series are stored.

construct_evaluator()[source]

Builds evaluators needed to compute the error functional.

dump_time_series()[source]

Stores model time series to disk.

Obtains station time series from the last optimization iteration, and stores the data to disk.

The output files are have the format {odir}/diagnostic_timeseries_progress_{station_name}_{variable}.hdf5

The file contains the simulation time in the time array, and the station name and coordinates as attributes. The time series data is stored as a 2D (n_iterations, n_time_steps) array.

eval_cost_function(t)[source]

Evaluate the cost function.

Should be called at every export of the forward model.

eval_observation_at_time(t)[source]

Evaluate observation time series at the given time.

Parameters

t – model simulation time

Returns

list of observation time series values at time t

load_observation_data(observation_data_dir, station_names, variable, start_times=None, end_times=None)[source]

Load observation data from disk.

Assumes that observation data were stored with TimeSeriesCallback2D during the forward run. For generic case, use register_observation_data instead.

Parameters
  • observation_data_dir (str) – directory where observation data is stored

  • station_names (list) – list of station names

  • variable (str) – canonical variable name, e.g. ‘elev’

  • start_times (list) – optional start times for the observation periods

  • end_times (list) – optional end times for the observation periods

register_observation_data(station_names, variable, time, values, x, y, start_times=None, end_times=None)[source]

Add station time series data to the object.

The x, and y coordinates must be such that they allow extraction of model data at the same coordinates.

Parameters
  • station_names (list) – list of station names

  • variable (str) – canonical variable name, e.g. ‘elev’

  • time (list) – array of time stamps, one for each station

  • values (list) – array of observations, one for each station

  • x (list) – list of station x coordinates

  • y (list) – list of station y coordinates

  • start_times (list) – optional start times for the observation periods

  • end_times (list) – optional end times for the observation periods

set_model_field(function)[source]

Set the model field that will be evaluated.

update_stations_in_use(t)[source]

Indicate which stations are in use at the current time.

An entry of unity indicates use, whereas zero indicates disuse.

thetis.limiter module

Slope limiters for discontinuous fields

class thetis.limiter.VertexBasedP1DGLimiter(p1dg_space, time_dependent_mesh=True)[source]

Bases: firedrake.slope_limiter.vertex_based_limiter.VertexBasedLimiter

Vertex based limiter for P1DG tracer fields, see Kuzmin (2010)

Note

Currently only scalar fields are supported

Kuzmin (2010). A vertex-based hierarchical slope limiter for p-adaptive discontinuous Galerkin methods. Journal of Computational and Applied Mathematics, 233(12):3077-3085. http://dx.doi.org/10.1016/j.cam.2009.05.028

Parameters

p1dg_space – P1DG function space

apply(field)[source]

Applies the limiter on the given field (in place)

Parameters

fieldFunction to limit

compute_bounds(field)[source]

Re-compute min/max values of all neighbouring centroids

Parameters

fieldFunction to limit

thetis.limiter.assert_function_space(fs, family, degree)[source]

Checks the family and degree of function space.

Raises AssertionError if function space differs. If the function space lies on an extruded mesh, checks both spaces of the outer product.

Parameters
  • fs – function space

  • family (string) – name of element family

  • degree (int) – polynomial degree of the function space

thetis.limiter.timed_stage()

Log.Stage(type cls, name)

thetis.log module

Loggers for Thetis

Creates two logger instances, one for general model output and one for debug, warning, error etc. messages.

To print to the model output stream, use print_output().

Debug, warning etc. messages are issued with debug(), info(), warning(), error(), critical() methods.

thetis.log.critical(msg, *args, **kwargs)[source]

Log ‘msg % args’ with severity ‘CRITICAL’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.critical(“Houston, we have a %s”, “major disaster”, exc_info=1)

thetis.log.debug(msg, *args, **kwargs)[source]

Log ‘msg % args’ with severity ‘DEBUG’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.debug(“Houston, we have a %s”, “thorny problem”, exc_info=1)

thetis.log.error(msg, *args, **kwargs)[source]

Log ‘msg % args’ with severity ‘ERROR’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.error(“Houston, we have a %s”, “major problem”, exc_info=1)

thetis.log.info(msg, *args, **kwargs)[source]

Log ‘msg % args’ with severity ‘INFO’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.info(“Houston, we have a %s”, “interesting problem”, exc_info=1)

thetis.log.log(level, msg, *args, **kwargs)[source]

Log ‘msg % args’ with the integer severity ‘level’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.log(level, “We have a %s”, “mysterious problem”, exc_info=1)

thetis.log.print_output(msg, *args, **kwargs)

Log ‘msg % args’ with severity ‘INFO’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.info(“Houston, we have a %s”, “interesting problem”, exc_info=1)

thetis.log.set_log_directory(output_directory, comm=<mpi4py.MPI.Intracomm object>, mode='w')[source]

Forward all log output to output_directory/log file.

When called, a new empty log file is created.

If called twice with a different output_directory, a warning is raised, and the new log file location is assigned. The old log file or the output_directory are not removed.

Parameters
  • output_directory – the directory where log file is stored

  • comm – The communicator the handler should be collective over. Only rank-0 on that communicator will write to the log, other ranks will use a logging.NullHandler.

  • mode – write mode, ‘w’ removes previous log file (if any), otherwise appends to it. Default: ‘w’.

thetis.log.set_thetis_loggers(comm=<mpi4py.MPI.Intracomm object>)[source]

Set stream handlers for log messages.

Parameters

comm – The communicator the handler should be collective over. Only rank-0 on that communicator will write to the log, other ranks will use a logging.NullHandler.

thetis.log.thetis_log_level(level)[source]

Set the log level for Thetis logger.

This controls what level of logging messages are printed to stderr. The higher the level, the fewer the number of messages.

Parameters

level – The level to use, one of ‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR’, ‘CRITICAL’.

thetis.log.warning(msg, *args, **kwargs)[source]

Log ‘msg % args’ with severity ‘WARNING’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.warning(“Houston, we have a %s”, “bit of a problem”, exc_info=1)

thetis.momentum_eq module

3D momentum equation for hydrostatic Boussinesq flow.

The three dimensional momentum equation reads

(2)\[\frac{\partial \textbf{u}}{\partial t} + \nabla_h \cdot (\textbf{u} \textbf{u}) + \frac{\partial \left(w\textbf{u} \right)}{\partial z} + f\textbf{e}_z\wedge\textbf{u} + g\nabla_h \eta + g\nabla_h r = \nabla_h \cdot \left( \nu_h \nabla_h \textbf{u} \right) + \frac{\partial }{\partial z}\left( \nu \frac{\partial \textbf{u}}{\partial z}\right)\]

where \(\textbf{u}\) and \(w\) denote horizontal and vertical velocity, \(\nabla_h\) is the horizontal gradient, \(\wedge\) denotes the cross product, \(g\) is the gravitational acceleration, \(f\) is the Coriolis frequency, \(\textbf{e}_z\) is a vertical unit vector, and \(\nu_h, \nu\) stand for horizontal and vertical viscosity. Water density is given by \(\rho = \rho'(T, S, p) + \rho_0\), where \(\rho_0\) is a constant reference density. Above \(r\) denotes the baroclinic head

(3)\[r = \frac{1}{\rho_0} \int_{z}^\eta \rho' d\zeta.\]

The internal pressure gradient is computed as a separate diagnostic field:

(4)\[\mathbf{F}_{pg} = g\nabla_h r.\]

In the case of purely barotropic problems the \(r\) and \(\mathbf{F}_{pg}\) fields are omitted.

When using mode splitting we split the velocity field into a depth average and a deviation, \(\textbf{u} = \bar{\textbf{u}} + \textbf{u}'\). Following Higdon and de Szoeke (1997) we write an equation for the deviation \(\textbf{u}'\):

(5)\[\frac{\partial \textbf{u}'}{\partial t} = + \nabla_h \cdot (\textbf{u} \textbf{u}) + \frac{\partial \left(w\textbf{u} \right)}{\partial z} + f\textbf{e}_z\wedge\textbf{u}' + g\nabla_h r = \nabla_h \cdot \left( \nu_h \nabla_h \textbf{u} \right) + \frac{\partial }{\partial z}\left( \nu \frac{\partial \textbf{u}}{\partial z}\right)\]

In (5) the external pressure gradient \(g\nabla_h \eta\) vanishes and the Coriolis term only contains the deviation \(\textbf{u}'\). Advection and diffusion terms are not changed.

Higdon and de Szoeke (1997). Barotropic-Baroclinic Time Splitting for Ocean Circulation Modeling. Journal of Computational Physics, 135(1):30-53. http://dx.doi.org/10.1006/jcph.1997.5733

class thetis.momentum_eq.BottomFrictionTerm(function_space, bathymetry=None, v_elem_size=None, h_elem_size=None, use_nonlinear_equations=True, use_lax_friedrichs=True, use_bottom_friction=False, sipg_factor=Constant(FiniteElement('Real', None, 0), 6), sipg_factor_vertical=Constant(FiniteElement('Real', None, 0), 7))[source]

Bases: thetis.momentum_eq.MomentumTerm

Quadratic bottom friction term, \(\tau_b = C_D \| \textbf{u}_b \| \textbf{u}_b\)

The weak formulation reads

\[\int_{\Gamma_{bot}} \tau_b \cdot \boldsymbol{\psi} dx = \int_{\Gamma_{bot}} C_D \| \textbf{u}_b \| \textbf{u}_b \cdot \boldsymbol{\psi} dx\]

where \(\textbf{u}_b\) is reconstructed velocity in the middle of the bottom element:

\[\textbf{u}_b = \textbf{u}\Big|_{\Gamma_{bot}} + \frac{\partial \textbf{u}}{\partial z}\Big|_{\Gamma_{bot}} h_b,\]

\(h_b\) being half of the element height. For implicit solvers we linearize the stress as \(\tau_b = C_D \| \textbf{u}_b^{n} \| \textbf{u}_b^{n+1}\)

The drag is computed from the law-of-the wall

\[C_D = \left( \frac{\kappa}{\ln (h_b + z_0)/z_0} \right)^2\]

where \(z_0\) is the bottom roughness length field. The user can override the \(C_D\) value by providing quadratic_drag_coefficient field.

Parameters
  • function_spaceFunctionSpace where the solution belongs

  • bathymetry (3D Function or Constant) – bathymetry of the domain

  • v_elem_size – scalar Function that defines the vertical element size

  • h_elem_size – scalar Function that defines the horizontal element size

  • use_nonlinear_equations (bool) – If False defines the linear shallow water equations

  • use_bottom_friction (bool) – If True includes bottom friction term

  • sipg_factor

    class

    Constant or :class: Function horizontal SIPG penalty scaling factor

  • sipg_factor_vertical

    class

    Constant or :class: Function vertical SIPG penalty scaling factor

residual(solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.momentum_eq.CoriolisTerm(function_space, bathymetry=None, v_elem_size=None, h_elem_size=None, use_nonlinear_equations=True, use_lax_friedrichs=True, use_bottom_friction=False, sipg_factor=Constant(FiniteElement('Real', None, 0), 6), sipg_factor_vertical=Constant(FiniteElement('Real', None, 0), 7))[source]

Bases: thetis.momentum_eq.MomentumTerm

Coriolis term, \(f\textbf{e}_z\wedge \bar{\textbf{u}}\)

Parameters
  • function_spaceFunctionSpace where the solution belongs

  • bathymetry (3D Function or Constant) – bathymetry of the domain

  • v_elem_size – scalar Function that defines the vertical element size

  • h_elem_size – scalar Function that defines the horizontal element size

  • use_nonlinear_equations (bool) – If False defines the linear shallow water equations

  • use_bottom_friction (bool) – If True includes bottom friction term

  • sipg_factor

    class

    Constant or :class: Function horizontal SIPG penalty scaling factor

  • sipg_factor_vertical

    class

    Constant or :class: Function vertical SIPG penalty scaling factor

residual(solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.momentum_eq.HorizontalAdvectionTerm(function_space, bathymetry=None, v_elem_size=None, h_elem_size=None, use_nonlinear_equations=True, use_lax_friedrichs=True, use_bottom_friction=False, sipg_factor=Constant(FiniteElement('Real', None, 0), 6), sipg_factor_vertical=Constant(FiniteElement('Real', None, 0), 7))[source]

Bases: thetis.momentum_eq.MomentumTerm

Horizontal advection term, \(\nabla_h \cdot (\textbf{u} \textbf{u})\)

The weak form reads

\[\int_\Omega \nabla_h \cdot (\textbf{u} \textbf{u}) \cdot \boldsymbol{\psi} dx = - \int_\Omega \nabla_h \boldsymbol{\psi} : (\textbf{u} \textbf{u}) dx + \int_{\mathcal{I}_h \cup \mathcal{I}_v} \textbf{u}^{\text{up}} \cdot \text{jump}(\boldsymbol{\psi} \textbf{n}_h) \cdot \text{avg}(\textbf{u}) dS\]

where the right hand side has been integrated by parts; \(:\) stand for the Frobenius inner product, \(\textbf{n}_h\) is the horizontal projection of the normal vector, \(\textbf{u}^{\text{up}}\) is the upwind value, and \(\text{jump}\) and \(\text{avg}\) denote the jump and average operators across the interface.

Parameters
  • function_spaceFunctionSpace where the solution belongs

  • bathymetry (3D Function or Constant) – bathymetry of the domain

  • v_elem_size – scalar Function that defines the vertical element size

  • h_elem_size – scalar Function that defines the horizontal element size

  • use_nonlinear_equations (bool) – If False defines the linear shallow water equations

  • use_bottom_friction (bool) – If True includes bottom friction term

  • sipg_factor

    class

    Constant or :class: Function horizontal SIPG penalty scaling factor

  • sipg_factor_vertical

    class

    Constant or :class: Function vertical SIPG penalty scaling factor

residual(solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.momentum_eq.HorizontalViscosityTerm(function_space, bathymetry=None, v_elem_size=None, h_elem_size=None, use_nonlinear_equations=True, use_lax_friedrichs=True, use_bottom_friction=False, sipg_factor=Constant(FiniteElement('Real', None, 0), 6), sipg_factor_vertical=Constant(FiniteElement('Real', None, 0), 7))[source]

Bases: thetis.momentum_eq.MomentumTerm

Horizontal viscosity term, \(- \nabla_h \cdot \left( \nu_h \nabla_h \textbf{u} \right)\)

Using the symmetric interior penalty method the weak form becomes

\[\begin{split}\int_\Omega \nabla_h \cdot \left( \nu_h \nabla_h \textbf{u} \right) \cdot \boldsymbol{\psi} dx =& -\int_\Omega \nu_h (\nabla_h \boldsymbol{\psi}) : (\nabla_h \textbf{u})^T dx \\ &+ \int_{\mathcal{I}_h \cup \mathcal{I}_v} \text{jump}(\boldsymbol{\psi} \textbf{n}_h) \cdot \text{avg}( \nu_h \nabla_h \textbf{u}) dS + \int_{\mathcal{I}_h \cup \mathcal{I}_v} \text{jump}(\textbf{u} \textbf{n}_h) \cdot \text{avg}( \nu_h \nabla_h \boldsymbol{\psi}) dS \\ &- \int_{\mathcal{I}_h \cup \mathcal{I}_v} \sigma \text{avg}(\nu_h) \text{jump}(\textbf{u} \textbf{n}_h) \cdot \text{jump}(\boldsymbol{\psi} \textbf{n}_h) dS\end{split}\]

where \(\sigma\) is a penalty parameter, see Hillewaert (2013).

Hillewaert, Koen (2013). Development of the discontinuous Galerkin method for high-resolution, large scale CFD and acoustics in industrial geometries. PhD Thesis. Université catholique de Louvain. https://dial.uclouvain.be/pr/boreal/object/boreal:128254/

Parameters
  • function_spaceFunctionSpace where the solution belongs

  • bathymetry (3D Function or Constant) – bathymetry of the domain

  • v_elem_size – scalar Function that defines the vertical element size

  • h_elem_size – scalar Function that defines the horizontal element size

  • use_nonlinear_equations (bool) – If False defines the linear shallow water equations

  • use_bottom_friction (bool) – If True includes bottom friction term

  • sipg_factor

    class

    Constant or :class: Function horizontal SIPG penalty scaling factor

  • sipg_factor_vertical

    class

    Constant or :class: Function vertical SIPG penalty scaling factor

residual(solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.momentum_eq.InternalPressureGradientCalculator(fields, bathymetry, bnd_functions, internal_pg_scalar=None, solver_parameters=None)[source]

Bases: thetis.momentum_eq.MomentumTerm

Computes the internal pressure gradient term, \(g\nabla_h r\)

where \(r\) is the baroclinic head (3).

If \(r\) belongs to a discontinuous function space, the term is integrated by parts:

\[\int_\Omega g \nabla_h r \cdot \boldsymbol{\psi} dx = - \int_\Omega g r \nabla_h \cdot \boldsymbol{\psi} dx + \int_{\mathcal{I}_h \cup \mathcal{I}_v} g \text{avg}(r) \text{jump}(\boldsymbol{\psi} \cdot \textbf{n}_h) dx\]

Note

Due to the Term sign convention this term is assembled on the right-hand-side.

Parameters
  • solverclass`FlowSolver object

  • solver_parameters (dict) – PETSc solver options

residual(solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

solve()[source]

Computes internal pressure gradient and stores it in int_pg_3d field

class thetis.momentum_eq.LinearDragTerm(function_space, bathymetry=None, v_elem_size=None, h_elem_size=None, use_nonlinear_equations=True, use_lax_friedrichs=True, use_bottom_friction=False, sipg_factor=Constant(FiniteElement('Real', None, 0), 6), sipg_factor_vertical=Constant(FiniteElement('Real', None, 0), 7))[source]

Bases: thetis.momentum_eq.MomentumTerm

Linear drag term, \(\tau_b = D \textbf{u}_b\)

where \(D\) is the drag coefficient, read from linear_drag_coefficient field.

Parameters
  • function_spaceFunctionSpace where the solution belongs

  • bathymetry (3D Function or Constant) – bathymetry of the domain

  • v_elem_size – scalar Function that defines the vertical element size

  • h_elem_size – scalar Function that defines the horizontal element size

  • use_nonlinear_equations (bool) – If False defines the linear shallow water equations

  • use_bottom_friction (bool) – If True includes bottom friction term

  • sipg_factor

    class

    Constant or :class: Function horizontal SIPG penalty scaling factor

  • sipg_factor_vertical

    class

    Constant or :class: Function vertical SIPG penalty scaling factor

residual(solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.momentum_eq.MomentumEquation(function_space, bathymetry=None, v_elem_size=None, h_elem_size=None, use_nonlinear_equations=True, use_lax_friedrichs=True, use_bottom_friction=False, sipg_factor=Constant(FiniteElement('Real', None, 0), 8), sipg_factor_vertical=Constant(FiniteElement('Real', None, 0), 9))[source]

Bases: thetis.equation.Equation

Hydrostatic 3D momentum equation (5) for mode split models

Parameters
  • function_spaceFunctionSpace where the solution belongs

  • bathymetry (3D Function or Constant) – bathymetry of the domain

  • v_elem_size – scalar Function that defines the vertical element size

  • h_elem_size – scalar Function that defines the horizontal element size

  • use_nonlinear_equations (bool) – If False defines the linear shallow water equations

  • use_bottom_friction (bool) – If True includes bottom friction term

  • sipg_factor

    class

    Constant or :class: Function horizontal SIPG penalty scaling factor

  • sipg_factor_vertical

    class

    Constant or :class: Function vertical SIPG penalty scaling factor

class thetis.momentum_eq.MomentumTerm(function_space, bathymetry=None, v_elem_size=None, h_elem_size=None, use_nonlinear_equations=True, use_lax_friedrichs=True, use_bottom_friction=False, sipg_factor=Constant(FiniteElement('Real', None, 0), 6), sipg_factor_vertical=Constant(FiniteElement('Real', None, 0), 7))[source]

Bases: thetis.equation.Term

Generic term for momentum equation that provides commonly used members and mapping for boundary functions.

Parameters
  • function_spaceFunctionSpace where the solution belongs

  • bathymetry (3D Function or Constant) – bathymetry of the domain

  • v_elem_size – scalar Function that defines the vertical element size

  • h_elem_size – scalar Function that defines the horizontal element size

  • use_nonlinear_equations (bool) – If False defines the linear shallow water equations

  • use_bottom_friction (bool) – If True includes bottom friction term

  • sipg_factor

    class

    Constant or :class: Function horizontal SIPG penalty scaling factor

  • sipg_factor_vertical

    class

    Constant or :class: Function vertical SIPG penalty scaling factor

class thetis.momentum_eq.PressureGradientTerm(function_space, bathymetry=None, v_elem_size=None, h_elem_size=None, use_nonlinear_equations=True, use_lax_friedrichs=True, use_bottom_friction=False, sipg_factor=Constant(FiniteElement('Real', None, 0), 6), sipg_factor_vertical=Constant(FiniteElement('Real', None, 0), 7))[source]

Bases: thetis.momentum_eq.MomentumTerm

Internal pressure gradient term, \(g\nabla_h r\)

where \(r\) is the baroclinic head (3). Let \(s\) denote \(r/H\). We can then write

\[F_{IPG} = g\nabla_h((s -\bar{s}) H) + g\nabla_h\left(\frac{1}{H}\right) H^2\bar{s} + g s_{bot}\nabla_h h\]

where \(\bar{s},s_{bot}\) are the depth average and bottom value of \(s\).

If \(s\) belongs to a discontinuous function space, the first term is integrated by parts. Its weak form reads

\[\int_\Omega g\nabla_h((s -\bar{s}) H) \cdot \boldsymbol{\psi} dx = - \int_\Omega g (s -\bar{s}) H \nabla_h \cdot \boldsymbol{\psi} dx + \int_{\mathcal{I}_h \cup \mathcal{I}_v} g (s -\bar{s}) H \boldsymbol{\psi} \cdot \textbf{n}_h dx\]
Parameters
  • function_spaceFunctionSpace where the solution belongs

  • bathymetry (3D Function or Constant) – bathymetry of the domain

  • v_elem_size – scalar Function that defines the vertical element size

  • h_elem_size – scalar Function that defines the horizontal element size

  • use_nonlinear_equations (bool) – If False defines the linear shallow water equations

  • use_bottom_friction (bool) – If True includes bottom friction term

  • sipg_factor

    class

    Constant or :class: Function horizontal SIPG penalty scaling factor

  • sipg_factor_vertical

    class

    Constant or :class: Function vertical SIPG penalty scaling factor

residual(solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.momentum_eq.SourceTerm(function_space, bathymetry=None, v_elem_size=None, h_elem_size=None, use_nonlinear_equations=True, use_lax_friedrichs=True, use_bottom_friction=False, sipg_factor=Constant(FiniteElement('Real', None, 0), 6), sipg_factor_vertical=Constant(FiniteElement('Real', None, 0), 7))[source]

Bases: thetis.momentum_eq.MomentumTerm

Generic momentum source term

The weak form reads

\[F_s = \int_\Omega \sigma \cdot \boldsymbol{\psi} dx\]

where \(\sigma\) is a user defined vector valued Function.

This term also implements the wind stress, \(-\tau_w/(H \rho_0)\). \(\tau_w\) is a user-defined wind stress Function wind_stress. The weak form is

\[F_w = \int_{\Gamma_s} \frac{1}{\rho_0} \tau_w \cdot \boldsymbol{\psi} dx\]

Wind stress is only included if vertical viscosity is provided.

Parameters
  • function_spaceFunctionSpace where the solution belongs

  • bathymetry (3D Function or Constant) – bathymetry of the domain

  • v_elem_size – scalar Function that defines the vertical element size

  • h_elem_size – scalar Function that defines the horizontal element size

  • use_nonlinear_equations (bool) – If False defines the linear shallow water equations

  • use_bottom_friction (bool) – If True includes bottom friction term

  • sipg_factor

    class

    Constant or :class: Function horizontal SIPG penalty scaling factor

  • sipg_factor_vertical

    class

    Constant or :class: Function vertical SIPG penalty scaling factor

residual(solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.momentum_eq.VerticalAdvectionTerm(function_space, bathymetry=None, v_elem_size=None, h_elem_size=None, use_nonlinear_equations=True, use_lax_friedrichs=True, use_bottom_friction=False, sipg_factor=Constant(FiniteElement('Real', None, 0), 6), sipg_factor_vertical=Constant(FiniteElement('Real', None, 0), 7))[source]

Bases: thetis.momentum_eq.MomentumTerm

Vertical advection term, \(\partial \left(w\textbf{u} \right)/(\partial z)\)

The weak form reads

\[\int_\Omega \frac{\partial \left(w\textbf{u} \right)}{\partial z} \cdot \boldsymbol{\psi} dx = - \int_\Omega \left( w \textbf{u} \right) \cdot \frac{\partial \boldsymbol{\psi}}{\partial z} dx + \int_{\mathcal{I}_{h}} \textbf{u}^{\text{up}} \cdot \text{jump}(\boldsymbol{\psi} n_z) \text{avg}(w) dS\]
Parameters
  • function_spaceFunctionSpace where the solution belongs

  • bathymetry (3D Function or Constant) – bathymetry of the domain

  • v_elem_size – scalar Function that defines the vertical element size

  • h_elem_size – scalar Function that defines the horizontal element size

  • use_nonlinear_equations (bool) – If False defines the linear shallow water equations

  • use_bottom_friction (bool) – If True includes bottom friction term

  • sipg_factor

    class

    Constant or :class: Function horizontal SIPG penalty scaling factor

  • sipg_factor_vertical

    class

    Constant or :class: Function vertical SIPG penalty scaling factor

residual(solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.momentum_eq.VerticalViscosityTerm(function_space, bathymetry=None, v_elem_size=None, h_elem_size=None, use_nonlinear_equations=True, use_lax_friedrichs=True, use_bottom_friction=False, sipg_factor=Constant(FiniteElement('Real', None, 0), 6), sipg_factor_vertical=Constant(FiniteElement('Real', None, 0), 7))[source]

Bases: thetis.momentum_eq.MomentumTerm

Vertical viscosity term, \(- \frac{\partial }{\partial z}\left( \nu \frac{\partial \textbf{u}}{\partial z}\right)\)

Using the symmetric interior penalty method the weak form becomes

\[\begin{split}\int_\Omega \frac{\partial }{\partial z}\left( \nu \frac{\partial \textbf{u}}{\partial z}\right) \cdot \boldsymbol{\psi} dx =& -\int_\Omega \nu \frac{\partial \boldsymbol{\psi}}{\partial z} \cdot \frac{\partial \textbf{u}}{\partial z} dx \\ &+ \int_{\mathcal{I}_h} \text{jump}(\boldsymbol{\psi} n_z) \cdot \text{avg}\left(\nu \frac{\partial \textbf{u}}{\partial z}\right) dS + \int_{\mathcal{I}_h} \text{jump}(\textbf{u} n_z) \cdot \text{avg}\left(\nu \frac{\partial \boldsymbol{\psi}}{\partial z}\right) dS \\ &- \int_{\mathcal{I}_h} \sigma \text{avg}(\nu) \text{jump}(\textbf{u} n_z) \cdot \text{jump}(\boldsymbol{\psi} n_z) dS\end{split}\]

where \(\sigma\) is a penalty parameter, see Hillewaert (2013).

Hillewaert, Koen (2013). Development of the discontinuous Galerkin method for high-resolution, large scale CFD and acoustics in industrial geometries. PhD Thesis. Université catholique de Louvain. https://dial.uclouvain.be/pr/boreal/object/boreal:128254/

Parameters
  • function_spaceFunctionSpace where the solution belongs

  • bathymetry (3D Function or Constant) – bathymetry of the domain

  • v_elem_size – scalar Function that defines the vertical element size

  • h_elem_size – scalar Function that defines the horizontal element size

  • use_nonlinear_equations (bool) – If False defines the linear shallow water equations

  • use_bottom_friction (bool) – If True includes bottom friction term

  • sipg_factor

    class

    Constant or :class: Function horizontal SIPG penalty scaling factor

  • sipg_factor_vertical

    class

    Constant or :class: Function vertical SIPG penalty scaling factor

residual(solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

thetis.optimisation module

Some classes to help optimisation problems formulated with thetis_adjoint.

In particular this module contains some OptimisationCallbacks that can be used as callbacks of a ReducedFunctional called at various stages during the optimisation process: - eval_cb_pre(controls) and eval_cb_post(functional, controls) called before and after (re)evaluation of the forward model - derivative_cb_pre(controls) and eval_cb_post(functional, derivative, controls) called before and after the gradient computation using the adjoint of the model - hessian_cb_pre(controls) and eval_cb_post(functional, derivative, controls) called before and after the hessian computation OptimisationCallbacks that (can) use controls, functional and derivative information, work out what is provided by the number of arguments: current control values are always in the last argument; if more than 2 arguments are provided, the first is the latest evaluated functional value.

class thetis.optimisation.ControlsExportOptimisationCallback(solver_obj_or_outputdir, **kwargs)[source]

Bases: thetis.optimisation.DeferredExportManager

A callback that exports the current control values (assumed to all be Function s)

The control values are assumed to be the last argument in the callback (as for all ReducedFunctional callbacks).

Parameters
  • solver_obj_or_outputdir – a FlowSolver2d object, used to determine the output directory. Alternatively, the outputdir can be specified with a string as the first argument.

  • kwargs – any further keyword arguments are passed on to UserExportManager

class thetis.optimisation.DeferredExportManager(solver_obj_or_outputdir, **kwargs)[source]

Bases: object

A wrapper around a UserExportManager that is only created on the first export() call.

In addition the functions provided in the export call are copied into a fixed set of functions, where the functions provided in subsequent calls may be different (they need to be in the same function space). This is used in the ControlsExportOptimisationCallback and DerivativesExportOptimisationCallback.

Parameters
  • solver_obj_or_outputdir – a FlowSolver2d object, used to determine the output directory. Alternatively, the outputdir can be specified with a string as the first argument.

  • kwargs – any further keyword arguments are passed on to UserExportManager

export(functions, suggested_names=None)[source]

Create the UserExportManager (first call only), and call its export() method.

Parameters

functions – a list of Function s that the UserExportManager will be based on. Their values are first copied. The list may contain different functions in subsequent calls, but their function space should remain the same.

class thetis.optimisation.DerivativesExportOptimisationCallback(solver_obj_or_outputdir, **kwargs)[source]

Bases: thetis.optimisation.DeferredExportManager

A callback that exports the derivatives calculated by the adjoint.

The derivatives are assumed to be the second argument in the callback. This can therefore be used as a derivative_cb_post callback in a ReducedFunctional

Parameters
  • solver_obj_or_outputdir – a FlowSolver2d object, used to determine the output directory. Alternatively, the outputdir can be specified with a string as the first argument.

  • kwargs – any further keyword arguments are passed on to UserExportManager

class thetis.optimisation.DiagnosticOptimisationCallback(solver_obj, **kwargs)[source]

Bases: thetis.callback.DiagnosticCallback

An OptimsationCallback similar to DiagnosticCallback that can be used as callback in a ReducedFunctional.

Note that in this case the computing of the values needs to be defined in the compute_values method, not in the __call__ method (as this one is directly called from the ReducedFunctional). In addition, like any DiagnosticCallback, the name and variable_names properties and a message_str method need to be defined.

Parameters
  • solver_obj – Thetis solver object

  • kwargs – keyword arguments passed to DiagnosticCallback

abstract compute_values(*args)[source]

Compute diagnostic values.

This method is to be implemented in concrete subclasses of a DiagnosticOptimisationCallback. The number of arguments varies depending on which of the 6 [eval|derivative|hessian]_cb_[pre|post] callbacks this is used as. The last argument always contains the current controls. In the “pre” callbacks this is the only argument. In all “post” callbacks the 0th argument is the current functional value. eval_cb_post is given two arguments: functional and controls. derivative_cb_post and hessian_cb_post are given three arguments with args[1] being the derivative/hessian just calculated.

evaluate(*args, index=None)[source]

Evaluates callback and pushes values to log and hdf file (if enabled)

class thetis.optimisation.FunctionalOptimisationCallback(solver_obj, **kwargs)[source]

Bases: thetis.optimisation.DiagnosticOptimisationCallback

A simple OptimisationCallback that records the functional value in the log and/or hdf5 file.

Parameters
  • solver_obj – Thetis solver object

  • kwargs – keyword arguments passed to DiagnosticCallback

compute_values(*args)[source]

Compute diagnostic values.

This method is to be implemented in concrete subclasses of a DiagnosticOptimisationCallback. The number of arguments varies depending on which of the 6 [eval|derivative|hessian]_cb_[pre|post] callbacks this is used as. The last argument always contains the current controls. In the “pre” callbacks this is the only argument. In all “post” callbacks the 0th argument is the current functional value. eval_cb_post is given two arguments: functional and controls. derivative_cb_post and hessian_cb_post are given three arguments with args[1] being the derivative/hessian just calculated.

message_str(functional)[source]

A string representation.

Parameters

args – If provided, these will be the return value from __call__().

name = 'functional'
variable_names = ['functional']
class thetis.optimisation.OptimisationCallbackList(iterable=(), /)[source]

Bases: list

A list of callbacks that can be used as a single callback itself.

Calls all callbacks in order.

class thetis.optimisation.UserExportManager(solver_obj_or_outputdir, functions_to_export, filenames=None, filename_prefix='', shortnames=None, **kwargs)[source]

Bases: thetis.exporter.ExportManager

ExportManager for user provided functions (not necessarily known to Thetis)

In the standard ExportManager all provided functions need to have standard names present in field_metadata. Here, any functions can be provided. If function.name() is in field_metadata, the standard filename and shortname are used. If the function.name() is unknown, both are based on function.name() directly (with an optional additional filename_prefix). Filenames and shortnames can be overruled by the shortnames and filenames arguments.

Parameters
  • solver_obj_or_outputdir – a FlowSolver2d object, used to determine the output directory. Alternatively, the outputdir can be specified with a string as the first argument.

  • functions_to_export – a list of Function s

  • filenames – a list of strings that specify the filename for each provided function. If not provided, filenames are based on function.name().

  • filename_prefix – a string prefixed to each filename

  • shortnames – a list of strings with the shortnames used for each provided function. If not provided, shortnames are based on function.name().

  • kwargs – any further keyword arguments are passed on to ExportManager

class thetis.optimisation.UserExportOptimisationCallback(solver_obj_or_outputdir, functions_to_export, **kwargs)[source]

Bases: thetis.optimisation.UserExportManager

A UserExportManager that can be used as a ReducedFunctional callback

Any callback arguments (functional value, derivatives, controls) are ignored

Parameters
  • solver_obj_or_outputdir – a FlowSolver2d object, used to determine the output directory. Alternatively, the outputdir can be specified with a string as the first argument.

  • functions_to_export – a list of Function s

  • kwargs – any further keyword arguments are passed on to UserExportManager

thetis.options module

Thetis options for the 2D and 3D model

All options are type-checked and they are stored in traitlets Configurable objects.

class thetis.options.CommonModelOptions(**kwargs)[source]

Bases: thetis.configuration.FrozenConfigurable

Options that are common for both 2d and 3d models

atmospheric_pressure
cfl_2d
cfl_3d
check_volume_conservation_2d

A boolean (True, False) trait.

coriolis_frequency
element_family

An enum whose value must be in a given sequence.

export_diagnostics

A boolean (True, False) trait.

fields_to_export

An instance of a Python list.

fields_to_export_hdf5

An instance of a Python list.

horizontal_diffusivity_scale
horizontal_velocity_scale
horizontal_viscosity
horizontal_viscosity_scale
lax_friedrichs_tracer_scaling_factor
lax_friedrichs_velocity_scaling_factor
linear_drag_coefficient
log_output

A boolean (True, False) trait.

manning_drag_coefficient
momentum_source_2d
name = 'Model options'
nh_model_options

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

Subclasses can declare default classes by overriding the klass attribute

nikuradse_bed_roughness
no_exports

A boolean (True, False) trait.

norm_smoother
output_directory

A trait for unicode strings.

polynomial_degree
quadratic_drag_coefficient
simulation_end_date
simulation_end_time
simulation_export_time
simulation_initial_date
sipg_factor
sipg_factor_tracer
timestep
use_grad_depth_viscosity_term

A boolean (True, False) trait.

use_grad_div_viscosity_term

A boolean (True, False) trait.

use_lax_friedrichs_tracer

A boolean (True, False) trait.

use_lax_friedrichs_velocity

A boolean (True, False) trait.

use_limiter_for_tracers

A boolean (True, False) trait.

use_nonlinear_equations

A boolean (True, False) trait.

verbose

An int trait.

volume_source_2d
wind_stress
class thetis.options.CrankNicolsonSWETimeStepperOptions2d(**kwargs)[source]

Bases: thetis.options.SemiImplicitSWETimeStepperOptions2d

Options for 2d Crank-Nicolson time integrator applied to shallow water equations

implicitness_theta
class thetis.options.CrankNicolsonTracerTimeStepperOptions2d(**kwargs)[source]

Bases: thetis.options.SemiImplicitTracerTimeStepperOptions2d

Options for 2d Crank-Nicolson time integrator applied to tracer equations

implicitness_theta
class thetis.options.EquationOfStateOptions(**kwargs)[source]

Bases: thetis.configuration.FrozenHasTraits

Base class of equation of state options

name = 'Equation of State'
class thetis.options.ExplicitMomentumTimeStepperOptions3d(**kwargs)[source]

Bases: thetis.options.TimeStepperOptions3d

Options for 3d explicit time integrator momentum component

solver_parameters

PETSc solver options dictionary

class thetis.options.ExplicitSWETimeStepperOptions2d(**kwargs)[source]

Bases: thetis.options.ExplicitTimeStepperOptions2d

Options for 2d explicit time integrator applied to shallow water equations

solver_parameters

PETSc solver options dictionary

class thetis.options.ExplicitTimeStepperOptions(**kwargs)[source]

Bases: thetis.options.TimeStepperOptions

Options for explicit time integrator

use_automatic_timestep

A boolean (True, False) trait.

class thetis.options.ExplicitTimeStepperOptions2d(**kwargs)[source]

Bases: thetis.options.ExplicitTimeStepperOptions

Options for 2d explicit time integrator

class thetis.options.ExplicitTracerTimeStepperOptions2d(**kwargs)[source]

Bases: thetis.options.ExplicitTimeStepperOptions2d

Options for 2d explicit time integrator applied to tracer equations

solver_parameters

PETSc solver options dictionary

class thetis.options.ExplicitTracerTimeStepperOptions3d(**kwargs)[source]

Bases: thetis.options.TimeStepperOptions3d

Options for 3d explicit time integrator applied to tracer equations

solver_parameters

PETSc solver options dictionary

class thetis.options.GLSModelOptions(**kwargs)[source]

Bases: thetis.options.TurbulenceModelOptions

Options for Generic Length Scale turbulence model

apply_defaults(closure_name)[source]

Applies default parameters for given closure name

Parameters

closure_name (string) – name of the turbulence closure model

Sets default values for parameters p, m, n, schmidt_nb_tke, schmidt_nb_psi, c1, c2, c3_plus, c3_minus, f_wall, k_min, psi_min

c1

A float trait.

c2

A float trait.

c3_minus

A float trait.

c3_plus

A float trait.

closure_name

An enum whose value must be in a given sequence.

cmu0
compute_c3_minus

A boolean (True, False) trait.

compute_cmu0

A boolean (True, False) trait.

compute_galperin_clim

A boolean (True, False) trait.

compute_kappa

A boolean (True, False) trait.

compute_len_min

A boolean (True, False) trait.

compute_psi_min

A boolean (True, False) trait.

compute_schmidt_nb_psi

A boolean (True, False) trait.

diff_min
eps_min
f_wall

A float trait.

galperin_clim
k_min
kappa

A float trait.

len_min
limit_eps

A boolean (True, False) trait.

limit_len

A boolean (True, False) trait.

limit_len_min

A boolean (True, False) trait.

limit_psi

A boolean (True, False) trait.

m

A float trait.

n

A float trait.

name = 'Generic Length Scale turbulence closure model'
p

A float trait.

psi_min
ri_st

A float trait.

schmidt_nb_psi
schmidt_nb_tke
stability_function_name

An enum whose value must be in a given sequence.

visc_min
class thetis.options.IMEXSWETimeStepperOptions2d(**kwargs)[source]

Bases: thetis.options.SemiImplicitTimeStepperOptions2d

Options for 2d implicit-explicit time integrators applied to shallow water equations

solver_parameters

PETSc solver options dictionary

class thetis.options.ImplicitMomentumTimeStepperOptions3d(**kwargs)[source]

Bases: thetis.options.TimeStepperOptions3d

Options for 3d implicit time integrator momentum component

solver_parameters

PETSc solver options dictionary

class thetis.options.ImplicitSWETimeStepperOptions3d(**kwargs)[source]

Bases: thetis.options.SWETimeStepperOptions3d

Options for 3d implicit time integrator shallow water component

implicitness_theta
class thetis.options.ImplicitTracerTimeStepperOptions3d(**kwargs)[source]

Bases: thetis.options.TimeStepperOptions3d

Options for 3d implicit time integrator applied to tracer equations

solver_parameters

PETSc solver options dictionary

class thetis.options.LeapFrogTimeStepperOptions3d(**kwargs)[source]

Bases: thetis.options.SSPRKTimeStepperOptions3d

Options for 3d LeapFrog coupled time integrator

swe_options = <thetis.options.ImplicitSWETimeStepperOptions3d object>
class thetis.options.LinearEquationOfStateOptions(**kwargs)[source]

Bases: thetis.options.EquationOfStateOptions

Linear equation of state options

alpha

A float trait.

beta

A float trait.

name = 'Linear Equation of State'
rho_ref
s_ref
th_ref

A float trait.

class thetis.options.ModelOptions2d(**kwargs)[source]

Bases: thetis.options.CommonModelOptions

Options for 2D depth-averaged shallow water model

add_tracer_2d(label, name, filename, shortname=None, unit='-', **kwargs)[source]

Add a 2D tracer field to tracer.

Note that the tracer equations will be solved in the order in which they are added.

Parameters
  • label – field label used internally by Thetis, e.g. ‘tracer_2d’

  • name – human readable name for the tracer field, e.g. ‘Depth averaged tracer’

  • filename – file name for outputs, e.g. ‘Tracer2d’

  • shortname – short version of name, e.g. ‘Tracer’

  • unit – units for field, e.g. ‘-’

  • functionFunction to use for the tracer

  • source – associated source term

  • diffusivity – associated diffusivity coefficient

  • use_conservative_form – should the tracer equation be solved in conservative form?

add_tracer_system_2d(labels, names, filenames, shortnames=None, units=None, function=None, **kwargs)[source]

Add multiple 2D tracer fields to tracer at once.

The equations associated with these fields will be solved as a mixed system.

Parameters
  • labels – a list of field labels used internally by Thetis

  • names – a list of human readable names for the tracer fields

  • filenames – a list of file names for outputs

  • shortnames – a list of short versions of the names

  • units – a list of units for fields

  • functionFunction to use for the mixed tracer

Kwargs

other parameters passed to add_tracer_2d()

check_tracer_conservation

A boolean (True, False) trait.

check_tracer_overshoot

A boolean (True, False) trait.

name = 'Depth-averaged 2D model'
sediment_model_options

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

Subclasses can declare default classes by overriding the klass attribute

set_timestepper_type(timestepper_type, **kwargs)[source]

Set the same timestepper type for all components.

Any keyword arguments are passed through to the associated TimeStepperOptions object.

swe_timestepper_options

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

Subclasses can declare default classes by overriding the klass attribute

swe_timestepper_type

A enum whose value must be in a given sequence.

This enum controls a slaved option, with default values provided here.

Parameters
  • values – iterable of (value, HasTraits class) pairs. The HasTraits class will be called (with no arguments) to create default values if necessary.

  • paired_name – trait name this enum is paired with.

  • default_value – default value.

tidal_turbine_farms

An instance of a Python dict.

One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method.

Changed in version 5.0: Added key_trait for validating dict keys.

Changed in version 5.0: Deprecated ambiguous trait, traits args in favor of value_trait, per_key_traits.

tracer_advective_velocity_factor
tracer_element_family

An enum whose value must be in a given sequence.

tracer_only

A boolean (True, False) trait.

tracer_picard_iterations
tracer_timestepper_options

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

Subclasses can declare default classes by overriding the klass attribute

tracer_timestepper_type

A enum whose value must be in a given sequence.

This enum controls a slaved option, with default values provided here.

Parameters
  • values – iterable of (value, HasTraits class) pairs. The HasTraits class will be called (with no arguments) to create default values if necessary.

  • paired_name – trait name this enum is paired with.

  • default_value – default value.

use_automatic_wetting_and_drying_alpha

A boolean (True, False) trait.

use_supg_tracer

A boolean (True, False) trait.

use_tracer_conservative_form

A boolean (True, False) trait.

use_wetting_and_drying

A boolean (True, False) trait.

wetting_and_drying_alpha
wetting_and_drying_alpha_max
wetting_and_drying_alpha_min
class thetis.options.ModelOptions3d(**kwargs)[source]

Bases: thetis.options.CommonModelOptions

Options for 3D hydrostatic model

bottom_roughness
check_salinity_conservation

A boolean (True, False) trait.

check_salinity_overshoot

A boolean (True, False) trait.

check_temperature_conservation

A boolean (True, False) trait.

check_temperature_overshoot

A boolean (True, False) trait.

check_volume_conservation_3d

A boolean (True, False) trait.

constant_salinity
constant_temperature
equation_of_state_options

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

Subclasses can declare default classes by overriding the klass attribute

equation_of_state_type

A enum whose value must be in a given sequence.

This enum controls a slaved option, with default values provided here.

Parameters
  • values – iterable of (value, HasTraits class) pairs. The HasTraits class will be called (with no arguments) to create default values if necessary.

  • paired_name – trait name this enum is paired with.

  • default_value – default value.

horizontal_diffusivity
internal_pg_scalar
momentum_source_3d
name = '3D hydrostatic model'
salinity_source_3d
sipg_factor_turb
sipg_factor_vertical
sipg_factor_vertical_tracer
sipg_factor_vertical_turb
smagorinsky_coefficient
solve_salinity

A boolean (True, False) trait.

solve_temperature

A boolean (True, False) trait.

temperature_source_3d
timestep_2d
timestepper_options

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

Subclasses can declare default classes by overriding the klass attribute

timestepper_type

A enum whose value must be in a given sequence.

This enum controls a slaved option, with default values provided here.

Parameters
  • values – iterable of (value, HasTraits class) pairs. The HasTraits class will be called (with no arguments) to create default values if necessary.

  • paired_name – trait name this enum is paired with.

  • default_value – default value.

turbulence_model_options

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

Subclasses can declare default classes by overriding the klass attribute

turbulence_model_type

A enum whose value must be in a given sequence.

This enum controls a slaved option, with default values provided here.

Parameters
  • values – iterable of (value, HasTraits class) pairs. The HasTraits class will be called (with no arguments) to create default values if necessary.

  • paired_name – trait name this enum is paired with.

  • default_value – default value.

use_ale_moving_mesh

A boolean (True, False) trait.

use_baroclinic_formulation

A boolean (True, False) trait.

use_bottom_friction

A boolean (True, False) trait.

use_implicit_vertical_diffusion

A boolean (True, False) trait.

use_limiter_for_velocity

A boolean (True, False) trait.

use_quadratic_density

A boolean (True, False) trait.

use_quadratic_pressure

A boolean (True, False) trait.

use_smagorinsky_viscosity

A boolean (True, False) trait.

use_turbulence

A boolean (True, False) trait.

use_turbulence_advection

A boolean (True, False) trait.

vertical_diffusivity
vertical_velocity_scale
vertical_viscosity
class thetis.options.NonhydrostaticModelOptions(**kwargs)[source]

Bases: thetis.configuration.FrozenHasTraits

Options for non-hydrostatic models

free_surface_timestepper_options

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

Subclasses can declare default classes by overriding the klass attribute

free_surface_timestepper_type

A enum whose value must be in a given sequence.

This enum controls a slaved option, with default values provided here.

Parameters
  • values – iterable of (value, HasTraits class) pairs. The HasTraits class will be called (with no arguments) to create default values if necessary.

  • paired_name – trait name this enum is paired with.

  • default_value – default value.

name = 'Non-hydrostatic 2D/3D models'
q_degree
solve_nonhydrostatic_pressure

A boolean (True, False) trait.

solver_parameters

PETSc solver options dictionary

update_free_surface

A boolean (True, False) trait.

class thetis.options.PacanowskiPhilanderModelOptions(**kwargs)[source]

Bases: thetis.options.TurbulenceModelOptions

Options for Pacanowski-Philander turbulence model

alpha
exponent
max_viscosity
name = 'Pacanowski-Philander turbulence closure model'
class thetis.options.PressureProjectionSWETimeStepperOptions2d(**kwargs)[source]

Bases: thetis.options.TimeStepperOptions

Options for 2d pressure-projection time integrator applied to shallow water equations

implicitness_theta
picard_iterations
solver_parameters_momentum

PETSc solver options dictionary

solver_parameters_pressure

PETSc solver options dictionary

use_semi_implicit_linearization

A boolean (True, False) trait.

class thetis.options.SSPRKTimeStepperOptions3d(**kwargs)[source]

Bases: thetis.options.TimeStepperOptions3d

Options for 3d SSPRK coupled time integrator

explicit_momentum_options = <thetis.options.ExplicitMomentumTimeStepperOptions3d object>
explicit_tracer_options = <thetis.options.ExplicitTracerTimeStepperOptions3d object>
implicit_momentum_options = <thetis.options.ImplicitMomentumTimeStepperOptions3d object>
implicit_tracer_options = <thetis.options.ImplicitTracerTimeStepperOptions3d object>
swe_options = <thetis.options.SWETimeStepperOptions3d object>
use_automatic_timestep

A boolean (True, False) trait.

class thetis.options.SWETimeStepperOptions3d(**kwargs)[source]

Bases: thetis.options.TimeStepperOptions3d

Options for 3d time integrator shallow water component

solver_parameters

PETSc solver options dictionary

class thetis.options.SedimentModelOptions(**kwargs)[source]

Bases: thetis.configuration.FrozenHasTraits

average_sediment_size
bed_reference_height
check_sediment_conservation

A boolean (True, False) trait.

check_sediment_overshoot

A boolean (True, False) trait.

exner_timestepper_options

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

Subclasses can declare default classes by overriding the klass attribute

exner_timestepper_type

A enum whose value must be in a given sequence.

This enum controls a slaved option, with default values provided here.

Parameters
  • values – iterable of (value, HasTraits class) pairs. The HasTraits class will be called (with no arguments) to create default values if necessary.

  • paired_name – trait name this enum is paired with.

  • default_value – default value.

horizontal_diffusivity
max_angle
morphological_acceleration_factor
morphological_viscosity
porosity
secondary_current_parameter
sed_slide_length_scale
sediment_density
sediment_model_class

A trait whose value must be a subclass of a specified class.

sediment_timestepper_options

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

Subclasses can declare default classes by overriding the klass attribute

sediment_timestepper_type

A enum whose value must be in a given sequence.

This enum controls a slaved option, with default values provided here.

Parameters
  • values – iterable of (value, HasTraits class) pairs. The HasTraits class will be called (with no arguments) to create default values if necessary.

  • paired_name – trait name this enum is paired with.

  • default_value – default value.

slide_region
slope_effect_angle_parameter
slope_effect_parameter
solve_exner

A boolean (True, False) trait.

solve_suspended_sediment

A boolean (True, False) trait.

use_advective_velocity_correction

A boolean (True, False) trait.

use_angle_correction

A boolean (True, False) trait.

use_bedload

A boolean (True, False) trait.

use_secondary_current

A boolean (True, False) trait.

use_sediment_conservative_form

A boolean (True, False) trait.

use_sediment_slide

A boolean (True, False) trait.

use_slope_mag_correction

A boolean (True, False) trait.

class thetis.options.SemiImplicitSWETimeStepperOptions2d(**kwargs)[source]

Bases: thetis.options.SemiImplicitTimeStepperOptions2d

Options for 2d semi-implicit time integrator applied to shallow water equations

solver_parameters

PETSc solver options dictionary

class thetis.options.SemiImplicitTimeStepperOptions2d(**kwargs)[source]

Bases: thetis.options.TimeStepperOptions

Options for 2d semi-implicit time integrator

use_semi_implicit_linearization

A boolean (True, False) trait.

class thetis.options.SemiImplicitTracerTimeStepperOptions2d(**kwargs)[source]

Bases: thetis.options.SemiImplicitTimeStepperOptions2d

Options for 2d semi-implicit time integrator applied to tracer equations

solver_parameters

PETSc solver options dictionary

class thetis.options.SteadyStateTimeStepperOptions2d(**kwargs)[source]

Bases: thetis.options.TimeStepperOptions

Options for 2d steady state solver

solver_parameters

PETSc solver options dictionary

class thetis.options.TidalTurbineFarmOptions(**kwargs)[source]

Bases: thetis.configuration.FrozenHasTraits, traitlets.traitlets.TraitType

Tidal turbine farm options

break_even_wattage
name = 'Farm options'
turbine_density
turbine_options = <thetis.options.TidalTurbineOptions object>
class thetis.options.TidalTurbineOptions(**kwargs)[source]

Bases: thetis.configuration.FrozenHasTraits

Tidal turbine parameters

diameter
thrust_coefficient
class thetis.options.TimeStepperOptions(**kwargs)[source]

Bases: thetis.configuration.FrozenHasTraits

Base class for all time stepper options

ad_block_tag

A trait for unicode strings.

name = 'Time stepper'
solver_parameters

PETSc solver options dictionary

class thetis.options.TimeStepperOptions3d(**kwargs)[source]

Bases: thetis.configuration.FrozenHasTraits

Options for 3d explicit time integrator

ad_block_tag

A trait for unicode strings.

class thetis.options.TracerFieldOptions(**kwargs)[source]

Bases: thetis.configuration.FrozenHasTraits

Tracer field options

diffusivity
function
metadata

An instance of a Python dict.

One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method.

Changed in version 5.0: Added key_trait for validating dict keys.

Changed in version 5.0: Deprecated ambiguous trait, traits args in favor of value_trait, per_key_traits.

name = 'Tracer options'
source
use_conservative_form

A boolean (True, False) trait.

class thetis.options.TurbulenceModelOptions(**kwargs)[source]

Bases: thetis.configuration.FrozenHasTraits

Abstract base class for all turbulence model options

name = 'Turbulence closure model'

thetis.physical_constants module

Default values for physical constants and parameters

thetis.rungekutta module

Implements Runge-Kutta time integration methods.

The abstract class AbstractRKScheme defines the Runge-Kutta coefficients, and can be used to implement generic time integrators.

class thetis.rungekutta.AbstractRKScheme[source]

Bases: abc.ABC

Abstract class for defining Runge-Kutta schemes.

Derived classes must define the Butcher tableau (arrays a, b, c) and the CFL number (cfl_coeff).

Currently only explicit or diagonally implicit schemes are supported.

abstract property a

Runge-Kutta matrix \(a_{i,j}\) of the Butcher tableau

abstract property b

weights \(b_{i}\) of the Butcher tableau

abstract property c

nodes \(c_{i}\) of the Butcher tableau

abstract property cfl_coeff

CFL number of the scheme

Value 1.0 corresponds to Forward Euler time step.

class thetis.rungekutta.BackwardEuler(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.DIRKGeneric, thetis.rungekutta.BackwardEulerAbstract

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

class thetis.rungekutta.BackwardEulerAbstract[source]

Bases: thetis.rungekutta.AbstractRKScheme

Backward Euler method

a = [[1.0]]
b = [1.0]
c = [1.0]
cfl_coeff = inf
class thetis.rungekutta.BackwardEulerUForm(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.DIRKGenericUForm, thetis.rungekutta.BackwardEulerAbstract

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

class thetis.rungekutta.CrankNicolsonAbstract[source]

Bases: thetis.rungekutta.AbstractRKScheme

Crack-Nicolson scheme

a = [[0.0, 0.0], [0.5, 0.5]]
b = [0.5, 0.5]
c = [0.0, 1.0]
cfl_coeff = inf
class thetis.rungekutta.CrankNicolsonRK(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.DIRKGeneric, thetis.rungekutta.CrankNicolsonAbstract

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

class thetis.rungekutta.DIRK22(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.DIRKGeneric, thetis.rungekutta.DIRK22Abstract

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

class thetis.rungekutta.DIRK22Abstract[source]

Bases: thetis.rungekutta.AbstractRKScheme

2-stage, 2nd order, L-stable Diagonally Implicit Runge Kutta method

This method has the Butcher tableau

\[\begin{split}\begin{array}{c|cc} \gamma & \gamma & 0 \\ 1 & 1-\gamma & \gamma \\ \hline & 1/2 & 1/2 \end{array}\end{split}\]

with \(\gamma = (2 - \sqrt{2})/2\).

From DIRK(2,3,2) IMEX scheme in Ascher et al. (1997)

Ascher et al. (1997). Implicit-explicit Runge-Kutta methods for time-dependent partial differential equations. Applied Numerical Mathematics, 25:151-167. http://dx.doi.org/10.1137/0732037

a = [[0.2928932188134524, 0], [0.7071067811865476, 0.2928932188134524]]
b = [0.7071067811865476, 0.2928932188134524]
c = [0.2928932188134524, 1]
cfl_coeff = inf
gamma = 0.2928932188134524
class thetis.rungekutta.DIRK22UForm(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.DIRKGenericUForm, thetis.rungekutta.DIRK22Abstract

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

class thetis.rungekutta.DIRK23(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.DIRKGeneric, thetis.rungekutta.DIRK23Abstract

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

class thetis.rungekutta.DIRK23Abstract[source]

Bases: thetis.rungekutta.AbstractRKScheme

2-stage, 3rd order Diagonally Implicit Runge Kutta method

This method has the Butcher tableau

\[\begin{split}\begin{array}{c|cc} \gamma & \gamma & 0 \\ 1-\gamma & 1-2\gamma & \gamma \\ \hline & 1/2 & 1/2 \end{array}\end{split}\]

with \(\gamma = (3 + \sqrt{3})/6\).

From DIRK(2,3,3) IMEX scheme in Ascher et al. (1997)

Ascher et al. (1997). Implicit-explicit Runge-Kutta methods for time-dependent partial differential equations. Applied Numerical Mathematics, 25:151-167. http://dx.doi.org/10.1137/0732037

a = [[0.7886751345948128, 0], [-0.5773502691896255, 0.7886751345948128]]
b = [0.5, 0.5]
c = [0.7886751345948128, 0.21132486540518725]
cfl_coeff = inf
gamma = 0.7886751345948128
class thetis.rungekutta.DIRK33(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.DIRKGeneric, thetis.rungekutta.DIRK33Abstract

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

class thetis.rungekutta.DIRK33Abstract[source]

Bases: thetis.rungekutta.AbstractRKScheme

3-stage, 3rd order, L-stable Diagonally Implicit Runge Kutta method

From DIRK(3,4,3) IMEX scheme in Ascher et al. (1997)

Ascher et al. (1997). Implicit-explicit Runge-Kutta methods for time-dependent partial differential equations. Applied Numerical Mathematics, 25:151-167. http://dx.doi.org/10.1137/0732037

a = [[0.4358665215, 0, 0], [0.28206673925000003, 0.4358665215, 0], [1.208496649153235, -0.6443631706532353, 0.4358665215]]
b = [1.208496649153235, -0.6443631706532353, 0.4358665215]
b1 = 1.208496649153235
b2 = -0.6443631706532353
c = [0.4358665215, 0.71793326075, 1]
cfl_coeff = inf
gamma = 0.4358665215
class thetis.rungekutta.DIRK33UForm(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.DIRKGenericUForm, thetis.rungekutta.DIRK33Abstract

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

class thetis.rungekutta.DIRK43(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.DIRKGeneric, thetis.rungekutta.DIRK43Abstract

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

class thetis.rungekutta.DIRK43Abstract[source]

Bases: thetis.rungekutta.AbstractRKScheme

4-stage, 3rd order, L-stable Diagonally Implicit Runge Kutta method

From DIRK(4,4,3) IMEX scheme in Ascher et al. (1997)

Ascher et al. (1997). Implicit-explicit Runge-Kutta methods for time-dependent partial differential equations. Applied Numerical Mathematics, 25:151-167. http://dx.doi.org/10.1137/0732037

a = [[0.5, 0, 0, 0], [0.16666666666666666, 0.5, 0, 0], [-0.5, 0.5, 0.5, 0], [1.5, -1.5, 0.5, 0.5]]
b = [1.5, -1.5, 0.5, 0.5]
c = [0.5, 0.6666666666666666, 0.5, 1.0]
cfl_coeff = inf
class thetis.rungekutta.DIRKGeneric(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.RungeKuttaTimeIntegrator

Generic implementation of Diagonally Implicit Runge Kutta schemes.

All derived classes must define the Butcher tableau coefficients a, b, c.

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

get_final_solution()[source]

Assign final solution to self.solution

initialize(init_cond)[source]

Assigns initial conditions to all required fields.

solve_stage(i_stage, t, update_forcings=None)[source]

Solve i-th stage and assign solution to self.solution.

solve_tendency(i_stage, t, update_forcings=None)[source]

Evaluates the tendency of i-th stage.

update_solution(i_stage)[source]

Updates solution to i_stage sub-stage.

Tendencies must have been evaluated first.

update_solver()[source]

Create solver objects

class thetis.rungekutta.DIRKGenericUForm(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.RungeKuttaTimeIntegrator

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

cfl_coeff = inf
get_final_solution(additive=False)[source]

Evaluates the final solution

initialize(init_cond)[source]

Assigns initial conditions to all required fields.

solve_stage(i_stage, t, update_forcings=None)[source]

Solves a single stage of step from t to t+dt. All functions that the equation depends on must be at right state corresponding to each sub-step.

update_solver()[source]

Create solver objects

class thetis.rungekutta.DIRKLPUM2(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.DIRKGeneric, thetis.rungekutta.DIRKLPUM2Abstract

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

class thetis.rungekutta.DIRKLPUM2Abstract[source]

Bases: thetis.rungekutta.AbstractRKScheme

DIRKLPUM2, 3-stage, 2nd order, L-stable Diagonally Implicit Runge Kutta method

From IMEX RK scheme (20) in Higureras et al. (2014).

Higueras et al (2014). Optimized strong stability preserving IMEX Runge-Kutta methods. Journal of Computational and Applied Mathematics 272(2014) 116-140. http://dx.doi.org/10.1016/j.cam.2014.05.011

a = [[0.18181818181818182, 0, 0], [0.2662337662337662, 0.18181818181818182, 0], [0.3412042502951594, 0.34710743801652894, 0.18181818181818182]]
b = [0.3333333333333333, 0.3333333333333333, 0.3333333333333333]
c = [0.18181818181818182, 0.44805194805194803, 0.8701298701298701]
cfl_coeff = 4.34
class thetis.rungekutta.DIRKLSPUM2(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.DIRKGeneric, thetis.rungekutta.DIRKLSPUM2Abstract

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

class thetis.rungekutta.DIRKLSPUM2Abstract[source]

Bases: thetis.rungekutta.AbstractRKScheme

DIRKLSPUM2, 3-stage, 2nd order, L-stable Diagonally Implicit Runge Kutta method

From IMEX RK scheme (17) in Higureras et al. (2014).

Higueras et al (2014). Optimized strong stability preserving IMEX Runge-Kutta methods. Journal of Computational and Applied Mathematics 272(2014) 116-140. http://dx.doi.org/10.1016/j.cam.2014.05.011

a = [[0.18181818181818182, 0, 0], [0.44372294372294374, 0.18181818181818182, 0], [0.44004329004329007, 0.19090909090909092, 0.18181818181818182]]
b = [0.43636363636363634, 0.2, 0.36363636363636365]
c = [0.18181818181818182, 0.6255411255411255, 0.8127705627705628]
cfl_coeff = 4.34
class thetis.rungekutta.ERKEuler(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.ERKGeneric, thetis.rungekutta.ForwardEulerAbstract

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

class thetis.rungekutta.ERKGeneric(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.RungeKuttaTimeIntegrator

Generic explicit Runge-Kutta time integrator.

Implements the Butcher form. All terms in the equation are treated explicitly.

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

get_final_solution(additive=False)[source]

Assign final solution to self.solution

If additive=False, will overwrite solution function, otherwise will add to it.

initialize(solution)[source]

Assigns initial conditions to all required fields.

solve_stage(i_stage, t, update_forcings=None)[source]

Solve i-th stage and assign solution to self.solution.

solve_tendency(i_stage, t, update_forcings=None)[source]

Evaluates the tendency of i-th stage

update_solution(i_stage, additive=False)[source]

Computes the solution of the i-th stage

Tendencies must have been evaluated first.

If additive=False, will overwrite solution function, otherwise will add to it.

update_solver()[source]
class thetis.rungekutta.ERKGenericShuOsher(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.timeintegrator.TimeIntegrator

Generic explicit Runge-Kutta time integrator.

Implements the Shu-Osher form.

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

advance(t, update_forcings=None)[source]

Advances equations for one time step.

initialize(solution)[source]

Initialize the time integrator

Parameters

init_solution – initial solution

solve_stage(i_stage, t, update_forcings=None)[source]

Solve i-th stage and assign solution to self.solution.

update_solver()[source]
class thetis.rungekutta.ERKLPUM2(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.ERKGeneric, thetis.rungekutta.ERKLPUM2Abstract

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

class thetis.rungekutta.ERKLPUM2Abstract[source]

Bases: thetis.rungekutta.AbstractRKScheme

ERKLPUM2, 3-stage, 2nd order Explicit Runge Kutta method

From IMEX RK scheme (20) in Higureras et al. (2014).

Higueras et al (2014). Optimized strong stability preserving IMEX Runge-Kutta methods. Journal of Computational and Applied Mathematics 272(2014) 116-140. http://dx.doi.org/10.1016/j.cam.2014.05.011

a = [[0, 0, 0], [0.5, 0, 0], [0.5, 0.5, 0]]
b = [0.3333333333333333, 0.3333333333333333, 0.3333333333333333]
c = [0, 0.5, 1.0]
cfl_coeff = 2.0
class thetis.rungekutta.ERKLSPUM2(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.ERKGeneric, thetis.rungekutta.ERKLSPUM2Abstract

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

class thetis.rungekutta.ERKLSPUM2Abstract[source]

Bases: thetis.rungekutta.AbstractRKScheme

ERKLSPUM2, 3-stage, 2nd order Explicit Runge Kutta method

From IMEX RK scheme (17) in Higureras et al. (2014).

Higueras et al (2014). Optimized strong stability preserving IMEX Runge-Kutta methods. Journal of Computational and Applied Mathematics 272(2014) 116-140. http://dx.doi.org/10.1016/j.cam.2014.05.011

a = [[0, 0, 0], [0.8333333333333334, 0, 0], [0.4583333333333333, 0.4583333333333333, 0]]
b = [0.43636363636363634, 0.2, 0.36363636363636365]
c = [0, 0.8333333333333334, 0.9166666666666666]
cfl_coeff = 1.2
class thetis.rungekutta.ERKMidpoint(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.ERKGeneric, thetis.rungekutta.ERKMidpointAbstract

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

class thetis.rungekutta.ERKMidpointAbstract[source]

Bases: thetis.rungekutta.AbstractRKScheme

a = [[0.0, 0.0], [0.5, 0.0]]
b = [0.0, 1.0]
c = [0.0, 0.5]
cfl_coeff = 1.0
class thetis.rungekutta.ESDIRKMidpoint(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.DIRKGeneric, thetis.rungekutta.ESDIRKMidpointAbstract

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

class thetis.rungekutta.ESDIRKMidpointAbstract[source]

Bases: thetis.rungekutta.AbstractRKScheme

a = [[0.0, 0.0], [0.0, 0.5]]
b = [0.0, 1.0]
c = [0.0, 0.5]
cfl_coeff = 1.0
class thetis.rungekutta.ESDIRKTrapezoid(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.DIRKGeneric, thetis.rungekutta.ESDIRKTrapezoidAbstract

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

class thetis.rungekutta.ESDIRKTrapezoidAbstract[source]

Bases: thetis.rungekutta.AbstractRKScheme

a = [[0.0, 0.0], [0.5, 0.5]]
b = [0.5, 0.5]
c = [0.0, 1.0]
cfl_coeff = inf
class thetis.rungekutta.ForwardEulerAbstract[source]

Bases: thetis.rungekutta.AbstractRKScheme

Forward Euler method

a = [[0]]
b = [1.0]
c = [0]
cfl_coeff = 1.0
class thetis.rungekutta.ImplicitMidpoint(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.DIRKGeneric, thetis.rungekutta.ImplicitMidpointAbstract

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

class thetis.rungekutta.ImplicitMidpointAbstract[source]

Bases: thetis.rungekutta.AbstractRKScheme

Implicit midpoint method, second order.

This method has the Butcher tableau

\[\begin{split}\begin{array}{c|c} 0.5 & 0.5 \\ \hline & 1.0 \end{array}\end{split}\]
a = [[0.5]]
b = [1.0]
c = [0.5]
cfl_coeff = inf
class thetis.rungekutta.RungeKuttaTimeIntegrator(equation, solution, fields, dt, options)[source]

Bases: thetis.timeintegrator.TimeIntegrator, abc.ABC

Abstract base class for all Runge-Kutta time integrators

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values

advance(t, update_forcings=None)[source]

Advances equations for one time step.

abstract get_final_solution(additive=False)[source]

Evaluates the final solution

abstract solve_stage(i_stage, t, update_forcings=None)[source]

Solves a single stage of step from t to t+dt. All functions that the equation depends on must be at right state corresponding to each sub-step.

class thetis.rungekutta.SSPRK33(equation, solution, fields, dt, options, bnd_conditions, terms_to_add='all')[source]

Bases: thetis.rungekutta.ERKGenericShuOsher, thetis.rungekutta.SSPRK33Abstract

Parameters
  • equation (Equation object) – the equation to solve

  • solutionFunction where solution will be stored

  • fields (dict of Function or Constant objects) – Dictionary of fields that are passed to the equation

  • dt (float) – time step in seconds

  • optionsTimeStepperOptions instance containing parameter values.

  • bnd_conditions (dict) – Dictionary of boundary conditions passed to the equation

  • terms_to_add ('all' or list of 'implicit', 'explicit', 'source'.) – Defines which terms of the equation are to be added to this solver. Default ‘all’ implies [‘implicit’, ‘explicit’, ‘source’].

class thetis.rungekutta.SSPRK33Abstract[source]

Bases: thetis.rungekutta.AbstractRKScheme

3rd order Strong Stability Preserving Runge-Kutta scheme, SSP(3,3).

This scheme has Butcher tableau

\[\begin{split}\begin{array}{c|ccc} 0 & \\ 1 & 1 \\ 1/2 & 1/4 & 1/4 & \\ \hline & 1/6 & 1/6 & 2/3 \end{array}\end{split}\]

CFL coefficient is 1.0

a = [[0, 0, 0], [1.0, 0, 0], [0.25, 0.25, 0]]
b = [0.16666666666666666, 0.16666666666666666, 0.6666666666666666]
c = [0, 1.0, 0.5]
cfl_coeff = 1.0
thetis.rungekutta.butcher_to_shuosher_form(a, b)[source]

Converts Butcher tableau to Shu-Osher form.

The Shu-Osher form of a s-stage scheme is defined by two s+1 by s+1 arrays \(\alpha\) and \(\beta\):

\[\begin{split}u^{0} &= u^n \\ u^{(i)} &= \sum_{j=0}^s \alpha_{i,j} u^{(j)} + \sum_{j=0}^s \beta_{i,j} F(u^{(j)}) \\ u^{n+1} &= u^{(s)}\end{split}\]

The Shu-Osher form is not unique. Here we construct the form where beta values are the diagonal entries (for DIRK schemes) or sub-diagonal entries (for explicit schemes) of the concatenated Butcher tableau [\(a\); \(b\)].

For more information see Ketchelson et al. (2009) http://dx.doi.org/10.1016/j.apnum.2008.03.034

thetis.rungekutta.timed_region()

Log.Event(type cls, name, klass=None)

thetis.rungekutta.timed_stage()

Log.Stage(type cls, name)

thetis.sediment_eq_2d module

2D advection diffusion equation for sediment transport.

This can be either conservative \(q=HT\) or non-conservative \(T\) sediment and allows for a separate source and sink term. The equation reads

(6)\[\frac{\partial S}{\partial t} + \nabla_h \cdot (\textbf{u} S) = \nabla_h \cdot (\mu_h \nabla_h S) + F_{source} - (F_{sink} S)\]

where \(S\) is \(q\) for conservative and \(T\) for non-conservative, \(\nabla_h\) denotes horizontal gradient, \(\textbf{u}\) are the horizontal velocities, and \(\mu_h\) denotes horizontal diffusivity.

class thetis.sediment_eq_2d.ConservativeSedimentAdvectionTerm(function_space, depth, options, sediment_model, conservative=False)[source]

Bases: thetis.sediment_eq_2d.SedimentTerm, thetis.tracer_eq_2d.ConservativeHorizontalAdvectionTerm

Advection term for sediment equation

Same as ConservativeHorizontalAdvectionTerm but allows for equilibrium boundary condition through get_bnd_conditions() inherited from SedimentTerm.

Parameters
  • function_spaceFunctionSpace where the solution belongs

  • depthDepthExpression containing depth info

  • options – :class`ModelOptions2d` containing parameters

  • conservative (bool) – whether to use conservative tracer

class thetis.sediment_eq_2d.SedimentAdvectionTerm(function_space, depth, options, sediment_model, conservative=False)[source]

Bases: thetis.sediment_eq_2d.SedimentTerm, thetis.tracer_eq_2d.HorizontalAdvectionTerm

Advection term for sediment equation

Same as HorizontalAdvectionTerm but allows for equilibrium boundary condition through get_bnd_conditions() inherited from SedimentTerm.

Parameters
  • function_spaceFunctionSpace where the solution belongs

  • depthDepthExpression containing depth info

  • options – :class`ModelOptions2d` containing parameters

  • conservative (bool) – whether to use conservative tracer

class thetis.sediment_eq_2d.SedimentDepositionTerm(function_space, depth, options, sediment_model, conservative=False)[source]

Bases: thetis.sediment_eq_2d.SedimentTerm

Deposition term for sediment equation

Parameters
  • function_spaceFunctionSpace where the solution belongs

  • depthDepthExpression containing depth info

  • options – :class`ModelOptions2d` containing parameters

  • conservative (bool) – whether to use conservative tracer

residual(solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.sediment_eq_2d.SedimentEquation2D(function_space, depth, options, sediment_model, conservative=False)[source]

Bases: thetis.equation.Equation

2D sediment advection-diffusion equation: (16) or (17) with sediment source and sink term

Parameters
  • function_spaceFunctionSpace where the solution belongs

  • depthDepthExpression containing depth info

  • options – :class`ModelOptions2d` containing parameters

  • conservative (bool) – whether to use conservative tracer

class thetis.sediment_eq_2d.SedimentErosionTerm(function_space, depth, options, sediment_model, conservative=False)[source]

Bases: thetis.sediment_eq_2d.SedimentTerm

Erosion term for sediment equation

Parameters
  • function_spaceFunctionSpace where the solution belongs

  • depthDepthExpression containing depth info

  • options – :class`ModelOptions2d` containing parameters

  • conservative (bool) – whether to use conservative tracer

residual(solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.sediment_eq_2d.SedimentTerm(function_space, depth, options, sediment_model, conservative=False)[source]

Bases: thetis.tracer_eq_2d.TracerTerm

Generic sediment term that provides commonly used members.

Parameters
  • function_spaceFunctionSpace where the solution belongs

  • depthDepthExpression containing depth info

  • options – :class`ModelOptions2d` containing parameters

  • conservative (bool) – whether to use conservative tracer

get_bnd_functions(c_in, uv_in, elev_in, bnd_id, bnd_conditions)[source]

Returns external values of tracer and uv for all supported boundary conditions.

Volume flux (flux) and normal velocity (un) are defined positive out of the domain.

Parameters
  • c_in – Internal value of tracer

  • uv_in – Internal value of horizontal velocity

  • elev_in – Internal value of elevation

  • bnd_id (int) – boundary id

  • bnd_conditions – dict of boundary conditions: {bnd_id: {field: value, ...}, ...}

thetis.sediment_model module

class thetis.sediment_model.CorrectiveVelocityFactor(depth, ksp, settling_velocity, ustar, a)[source]

Bases: object

Set up advective velocity factor self.velocity_correction_factor which accounts for mismatch between depth-averaged product of velocity with sediment and product of depth-averaged velocity with depth-averaged sediment.

Parameters
  • depth (Function) – Depth of fluid

  • ksp (Constant) – Grain roughness coefficient

  • settling_velocity (Constant) – Settling velocity of the sediment particles

  • ustar (Expression of functions) – Shear velocity

  • a (Constant) – Factor of bottom bed reference height

update()[source]

Update self.velocity_correction_factor using the updated values for velocity

class thetis.sediment_model.SedimentModel(options, mesh2d, uv, elev, depth)[source]

Bases: object

Set up a full morphological model simulation based on provided velocity and elevation functions.

Parameters
  • options (ModelOptions2d instance) – Model options.

  • mesh2dMesh object of the 2D mesh

  • uv (Function) – the velocity solution during the simulation

  • elev (Function) – the elevation solution during the simulation

  • depth – a DepthExpression instance to evaluate the current depth

The SedimentModel provides various expressions to be used in a suspended sediment and/or the Exner equation. NOTE that the functions used in these expressions need to be updated with the current values of the uv and elev fields by calling SedimentModel.update(). This is not done in the initialisation of the sediment model, so that the SedimentModel can be created before initial conditions have been assigned to uv and elev. After the initial conditions have been assigned a call to update is required to ensure that the initial values are reflected in the SedimentModel terms.

get_advective_velocity_correction_factor()[source]

Returns correction factor for the advective velocity in the sediment equations

With SedimentModelOptions.use_advective_velocity_correction, this applies a correction to the supplied velocity solution uv to take into account the mismatch between depth-averaged product of velocity with sediment and product of depth-averaged velocity with depth-averaged sediment.

get_bedload_term(bathymetry)[source]

Returns expression for bedload transport \((qbx, qby)\) to be used in the Exner equation. Note bathymetry is the function which is solved for in the exner equation.

Parameters

bathymetry – Bathymetry of the domain. Bathymetry stands for the bedlevel (positive downwards).

get_deposition_coefficient()[source]

Returns coefficient \(C\) such that \(C/H*sediment\) is deposition term in sediment equation

If sediment field is depth-averaged, \(C*sediment\) is (total) deposition (over the column) as it appears in the Exner equation, but deposition term in sediment equation needs averaging: \(C*sediment/H\) If sediment field is depth-integrated, \(C*sediment/H\) is (total) deposition (over the column) as it appears in the Exner equation, and is the same in the sediment equation.

get_equilibrium_tracer()[source]

Returns expression for (depth-averaged) equilibrium tracer.

get_erosion_term()[source]

Returns expression for (depth-integrated) erosion.

get_sediment_slide_term(bathymetry)[source]
update()[source]

Update all functions used by SedimentModel

This repeats all projection and interpolations steps based on the current values of the uv and elev functions, provided in __init__.

thetis.sediment_model.timed_stage()

Log.Stage(type cls, name)

thetis.shallowwater_eq module

Depth averaged shallow water equations

Equations

The state variables are water elevation, \(\eta\), and depth averaged velocity \(\bar{\textbf{u}}\).

Denoting the total water depth by \(H=\eta + h\), the non-conservative form of the free surface equation is

(7)\[\frac{\partial \eta}{\partial t} + \nabla \cdot (H \bar{\textbf{u}}) = 0\]

The non-conservative momentum equation reads

(8)\[\frac{\partial \bar{\textbf{u}}}{\partial t} + \bar{\textbf{u}} \cdot \nabla\bar{\textbf{u}} + f\textbf{e}_z\wedge \bar{\textbf{u}} + g \nabla \eta + \nabla \left(\frac{p_a}{\rho_0} \right) + g \frac{1}{H}\int_{-h}^\eta \nabla r dz = \nabla \cdot \big( \nu_h ( \nabla \bar{\textbf{u}} + (\nabla \bar{\textbf{u}})^T )\big) + \frac{\nu_h \nabla(H)}{H} \cdot ( \nabla \bar{\textbf{u}} + (\nabla \bar{\textbf{u}})^T ),\]

where \(g\) is the gravitational acceleration, \(f\) is the Coriolis frequency, \(\wedge\) is the cross product, \(\textbf{e}_z\) is a vertical unit vector, \(p_a\) is the atmospheric pressure at the free surface, and \(\nu_h\) is viscosity. Water density is given by \(\rho = \rho'(T, S, p) + \rho_0\), where \(\rho_0\) is a constant reference density.

Above \(r\) denotes the baroclinic head

\[r = \frac{1}{\rho_0} \int_{z}^\eta \rho' d\zeta.\]

In the case of purely barotropic problems the \(r\) and the internal pressure gradient are omitted.

If the option ModelOptions.use_nonlinear_equations is False, we solve the linear shallow water equations (i.e. wave equation):

(9)\[\frac{\partial \eta}{\partial t} + \nabla \cdot (h \bar{\textbf{u}}) = 0\]
(10)\[\frac{\partial \bar{\textbf{u}}}{\partial t} + f\textbf{e}_z\wedge \bar{\textbf{u}} + g \nabla \eta = \nabla \cdot \big( \nu_h ( \nabla \bar{\textbf{u}} + (\nabla \bar{\textbf{u}})^T )\big) + \frac{\nu_h \nabla(H)}{H} \cdot ( \nabla \bar{\textbf{u}} + (\nabla \bar{\textbf{u}})^T ).\]

In case of a 3D problem with mode splitting, we use a simplified 2D system that contains nothing but the rotational external gravity waves:

(11)\[\frac{\partial \eta}{\partial t} + \nabla \cdot (H \bar{\textbf{u}}) = 0\]
(12)\[\frac{\partial \bar{\textbf{u}}}{\partial t} + f\textbf{e}_z\wedge \bar{\textbf{u}} + g \nabla \eta = \textbf{G},\]

where \(\textbf{G}\) is a source term used to couple the 2D and 3D momentum equations.

Boundary Conditions

All boundary conditions are imposed weakly by providing external values for \(\eta\) and \(\bar{\textbf{u}}\).

Boundary conditions are set with a dictionary that defines all prescribed variables at each open boundary. For example, to assign elevation and volume flux on boundary 1 we set

swe_bnd_funcs = {}
swe_bnd_funcs[1] = {'elev':myfunc1, 'flux':myfunc2}

where myfunc1 and myfunc2 are Constant or Function objects.

The user can provide \(\eta\) and/or \(\bar{\textbf{u}}\) values. Supported combinations are:

  • unspecified : impermeable (land) boundary, implies symmetric \(\eta\) condition and zero normal velocity

  • 'elev': elevation only, symmetric velocity (usually unstable)

  • 'uv': 2d velocity vector \(\bar{\textbf{u}}=(u, v)\) (in mesh coordinates), symmetric elevation

  • 'un': normal velocity (scalar, positive out of domain), symmetric elevation

  • 'flux': normal volume flux (scalar, positive out of domain), symmetric elevation

  • 'elev' and 'uv': water elevation and 2d velocity vector

  • 'elev' and 'un': water elevation and normal velocity

  • 'elev' and 'flux': water elevation and normal flux

The boundary conditions are assigned to the FlowSolver2d or FlowSolver objects:

solver_obj = solver2d.FlowSolver2d(...)
...
solver_obj.bnd_functions['shallow_water'] = swe_bnd_funcs

Internally the boundary conditions passed to the Term.residual() method of each term:

adv_term = shallowwater_eq.HorizontalAdvectionTerm(...)
adv_form = adv_term.residual(..., bnd_conditions=swe_bnd_funcs)

Wetting and drying

If the option ModelOptions.use_wetting_and_drying is True, then wetting and drying is included through the formulation of Karna et al. (2011).

The method introduces a modified bathymetry \(\tilde{h} = h + f(H)\), which ensures positive total water depth, with \(f(H)\) defined by

\[f(H) = \frac{1}{2}(\sqrt{H^2 + \alpha^2} - H),\]

introducing a wetting-drying parameter \(\alpha\), with dimensions of length. This results in a modified total water depth \(\tilde{H}=H+f(H)\).

The value for \(\alpha\) is specified by the user through the option ModelOptions.wetting_and_drying_alpha, in units of meters. The default value for ModelOptions.wetting_and_drying_alpha is 0.5, but the appropriate value is problem specific and should be set by the user.

An approximate method for selecting a suitable value for \(\alpha\) is suggested by Karna et al. (2011). Defining \(L_x\) as the horizontal length scale of the mesh elements at the wet-dry front, it can be reasoned that \(\alpha \approx |L_x \nabla h|\) yields a suitable choice. Smaller \(\alpha\) leads to a more accurate solution to the shallow water equations in wet regions, but if \(\alpha\) is too small the simulation will become unstable.

When wetting and drying is turned on, two things occur:

  1. All instances of the height, \(H\), are replaced by \(\tilde{H}\) (as defined above);

  2. An additional displacement term \(\frac{\partial \tilde{h}}{\partial t}\) is added to the bathymetry in the free surface equation.

The free surface and momentum equations then become:

(13)\[\frac{\partial \eta}{\partial t} + \frac{\partial \tilde{h}}{\partial t} + \nabla \cdot (\tilde{H} \bar{\textbf{u}}) = 0,\]
(14)\[\frac{\partial \bar{\textbf{u}}}{\partial t} + \bar{\textbf{u}} \cdot \nabla\bar{\textbf{u}} + f\textbf{e}_z\wedge \bar{\textbf{u}} + g \nabla \eta + g \frac{1}{\tilde{H}}\int_{-h}^\eta \nabla r dz = \nabla \cdot \big( \nu_h ( \nabla \bar{\textbf{u}} + (\nabla \bar{\textbf{u}})^T )\big) + \frac{\nu_h \nabla(\tilde{H})}{\tilde{H}} \cdot ( \nabla \bar{\textbf{u}} + (\nabla \bar{\textbf{u}})^T ).\]
class thetis.shallowwater_eq.AtmosphericPressureTerm(u_test, u_space, eta_space, depth, options=None)[source]

Bases: thetis.shallowwater_eq.ShallowWaterMomentumTerm

Atmospheric pressure term, \(\nabla (p_a / \rho_0)\)

Here \(p_a\) is a user-defined atmospheric pressure Function.

Parameters
  • function_space – the FunctionSpace the solution belongs to

  • test_function – custom TestFunction.

  • trial_function – custom TrialFunction.

residual(uv, eta, uv_old, eta_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.shallowwater_eq.BaseShallowWaterEquation(function_space, depth, options)[source]

Bases: thetis.equation.Equation

Abstract base class for ShallowWaterEquations, ShallowWaterMomentumEquation and FreeSurfaceEquation.

Provides common functionality to compute time steps and add either momentum or continuity terms.

Parameters

function_space – the FunctionSpace the solution belongs to

add_continuity_terms(*args)[source]
add_momentum_terms(*args)[source]
residual_uv_eta(label, uv, eta, uv_old, eta_old, fields, fields_old, bnd_conditions)[source]
class thetis.shallowwater_eq.BottomDrag3DTerm(u_test, u_space, eta_space, depth, options=None)[source]

Bases: thetis.shallowwater_eq.ShallowWaterMomentumTerm

Bottom drag term consistent with the 3D mode, \(C_D \| \textbf{u}_b \| \textbf{u}_b\)

Here \(\textbf{u}_b\) is the bottom velocity used in the 3D mode, and \(C_D\) the corresponding bottom drag. These fields are computed in the 3D model.

Parameters
  • function_space – the FunctionSpace the solution belongs to

  • test_function – custom TestFunction.

  • trial_function – custom TrialFunction.

residual(uv, eta, uv_old, eta_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.shallowwater_eq.ContinuitySourceTerm(eta_test, eta_space, u_space, depth, options=None)[source]

Bases: thetis.shallowwater_eq.ShallowWaterContinuityTerm

Generic source term in the depth-averaged continuity equation

The weak form reads

\[F_s = \int_\Omega S \phi dx\]

where \(S\) is a user defined scalar Function.

Parameters
  • function_space – the FunctionSpace the solution belongs to

  • test_function – custom TestFunction.

  • trial_function – custom TrialFunction.

residual(uv, eta, uv_old, eta_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.shallowwater_eq.CoriolisTerm(u_test, u_space, eta_space, depth, options=None)[source]

Bases: thetis.shallowwater_eq.ShallowWaterMomentumTerm

Coriolis term, \(f\textbf{e}_z\wedge \bar{\textbf{u}}\)

Parameters
  • function_space – the FunctionSpace the solution belongs to

  • test_function – custom TestFunction.

  • trial_function – custom TrialFunction.

residual(uv, eta, uv_old, eta_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.shallowwater_eq.ExternalPressureGradientTerm(u_test, u_space, eta_space, depth, options=None)[source]

Bases: thetis.shallowwater_eq.ShallowWaterMomentumTerm

External pressure gradient term, \(g \nabla \eta\)

The weak form reads

\[\int_\Omega g \nabla \eta \cdot \boldsymbol{\psi} dx = \int_\Gamma g \eta^* \text{jump}(\boldsymbol{\psi} \cdot \textbf{n}) dS - \int_\Omega g \eta \nabla \cdot \boldsymbol{\psi} dx\]

where the right hand side has been integrated by parts; \(\textbf{n}\) denotes the unit normal of the element interfaces, \(n^*\) is value at the interface obtained from an approximate Riemann solver.

If \(\eta\) belongs to a discontinuous function space, the form on the right hand side is used.

Parameters
  • function_space – the FunctionSpace the solution belongs to

  • test_function – custom TestFunction.

  • trial_function – custom TrialFunction.

residual(uv, eta, uv_old, eta_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.shallowwater_eq.FreeSurfaceEquation(eta_test, eta_space, u_space, depth, options)[source]

Bases: thetis.shallowwater_eq.BaseShallowWaterEquation

2D free surface equation (7) in non-conservative form.

Parameters
  • eta_test – test function of the elevation function space

  • eta_space – elevation function space

  • u_space – velocity function space

  • function_space – Mixed function space where the solution belongs

  • depth

    class

    DepthExpression containing depth info

  • optionsAttrDict object containing all circulation model options

mass_term(solution)[source]

Returns default mass matrix term for the solution function space.

Returns

UFL form of the mass term

residual(label, solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the residual by summing up all the terms with the desired label.

Sign convention: all terms are assumed to be on the right hand side of the equation: d(u)/dt = term.

Parameters
  • label – string defining the type of terms to sum up. Currently one of ‘source’|’explicit’|’implicit’|’nonlinear’. Can be a list of multiple labels, or ‘all’ in which case all defined terms are summed.

  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.shallowwater_eq.HUDivTerm(eta_test, eta_space, u_space, depth, options=None)[source]

Bases: thetis.shallowwater_eq.ShallowWaterContinuityTerm

Divergence term, \(\nabla \cdot (H \bar{\textbf{u}})\)

The weak form reads

\[\int_\Omega \nabla \cdot (H \bar{\textbf{u}}) \phi dx = \int_\Gamma (H^* \bar{\textbf{u}}^*) \cdot \text{jump}(\phi \textbf{n}) dS - \int_\Omega H (\bar{\textbf{u}}\cdot\nabla \phi) dx\]

where the right hand side has been integrated by parts; \(\textbf{n}\) denotes the unit normal of the element interfaces, and \(\text{jump}\) and \(\text{avg}\) denote the jump and average operators across the interface. \(H^*, \bar{\textbf{u}}^*\) are values at the interface obtained from an approximate Riemann solver.

If \(\bar{\textbf{u}}\) belongs to a discontinuous function space, the form on the right hand side is used.

Parameters
  • function_space – the FunctionSpace the solution belongs to

  • test_function – custom TestFunction.

  • trial_function – custom TrialFunction.

residual(uv, eta, uv_old, eta_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.shallowwater_eq.HorizontalAdvectionTerm(u_test, u_space, eta_space, depth, options=None)[source]

Bases: thetis.shallowwater_eq.ShallowWaterMomentumTerm

Advection of momentum term, \(\bar{\textbf{u}} \cdot \nabla\bar{\textbf{u}}\)

The weak form is

\[\int_\Omega \bar{\textbf{u}} \cdot \nabla\bar{\textbf{u}} \cdot \boldsymbol{\psi} dx = - \int_\Omega \nabla_h \cdot (\bar{\textbf{u}} \boldsymbol{\psi}) \cdot \bar{\textbf{u}} dx + \int_\Gamma \text{avg}(\bar{\textbf{u}}) \cdot \text{jump}(\boldsymbol{\psi} (\bar{\textbf{u}}\cdot\textbf{n})) dS\]

where the right hand side has been integrated by parts; \(\textbf{n}\) is the unit normal of the element interfaces, and \(\text{jump}\) and \(\text{avg}\) denote the jump and average operators across the interface.

Parameters
  • function_space – the FunctionSpace the solution belongs to

  • test_function – custom TestFunction.

  • trial_function – custom TrialFunction.

residual(uv, eta, uv_old, eta_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.shallowwater_eq.HorizontalViscosityTerm(u_test, u_space, eta_space, depth, options=None)[source]

Bases: thetis.shallowwater_eq.ShallowWaterMomentumTerm

Viscosity of momentum term

If option ModelOptions.use_grad_div_viscosity_term is True, we use the symmetric viscous stress \(\boldsymbol{\tau}_\nu = \nu_h ( \nabla \bar{\textbf{u}} + (\nabla \bar{\textbf{u}})^T )\). Using the symmetric interior penalty method the weak form then reads

\[\begin{split}\int_\Omega -\nabla \cdot \boldsymbol{\tau}_\nu \cdot \boldsymbol{\psi} dx =& \int_\Omega (\nabla \boldsymbol{\psi}) : \boldsymbol{\tau}_\nu dx \\ &- \int_\Gamma \text{jump}(\boldsymbol{\psi} \textbf{n}) \cdot \text{avg}(\boldsymbol{\tau}_\nu) dS - \int_\Gamma \text{avg}(\nu_h)\big(\text{jump}(\bar{\textbf{u}} \textbf{n}) + \text{jump}(\bar{\textbf{u}} \textbf{n})^T\big) \cdot \text{avg}(\nabla \boldsymbol{\psi}) dS \\ &+ \int_\Gamma \sigma \text{avg}(\nu_h) \big(\text{jump}(\bar{\textbf{u}} \textbf{n}) + \text{jump}(\bar{\textbf{u}} \textbf{n})^T\big) \cdot \text{jump}(\boldsymbol{\psi} \textbf{n}) dS\end{split}\]

where \(\sigma\) is a penalty parameter, see Hillewaert (2013).

If option ModelOptions.use_grad_div_viscosity_term is False, we use viscous stress \(\boldsymbol{\tau}_\nu = \nu_h \nabla \bar{\textbf{u}}\). In this case the weak form is

\[\begin{split}\int_\Omega -\nabla \cdot \boldsymbol{\tau}_\nu \cdot \boldsymbol{\psi} dx =& \int_\Omega (\nabla \boldsymbol{\psi}) : \boldsymbol{\tau}_\nu dx \\ &- \int_\Gamma \text{jump}(\boldsymbol{\psi} \textbf{n}) \cdot \text{avg}(\boldsymbol{\tau}_\nu) dS - \int_\Gamma \text{avg}(\nu_h)\text{jump}(\bar{\textbf{u}} \textbf{n}) \cdot \text{avg}(\nabla \boldsymbol{\psi}) dS \\ &+ \int_\Gamma \sigma \text{avg}(\nu_h) \text{jump}(\bar{\textbf{u}} \textbf{n}) \cdot \text{jump}(\boldsymbol{\psi} \textbf{n}) dS\end{split}\]

If option ModelOptions.use_grad_depth_viscosity_term is True, we also include the term

\[\boldsymbol{\tau}_{\nabla H} = - \frac{\nu_h \nabla(H)}{H} \cdot ( \nabla \bar{\textbf{u}} + (\nabla \bar{\textbf{u}})^T )\]

as a source term.

Hillewaert, Koen (2013). Development of the discontinuous Galerkin method for high-resolution, large scale CFD and acoustics in industrial geometries. PhD Thesis. Université catholique de Louvain. https://dial.uclouvain.be/pr/boreal/object/boreal:128254/

Parameters
  • function_space – the FunctionSpace the solution belongs to

  • test_function – custom TestFunction.

  • trial_function – custom TrialFunction.

residual(uv, eta, uv_old, eta_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.shallowwater_eq.LinearDragTerm(u_test, u_space, eta_space, depth, options=None)[source]

Bases: thetis.shallowwater_eq.ShallowWaterMomentumTerm

Linear friction term, \(C \bar{\textbf{u}}\)

Here \(C\) is a user-defined drag coefficient.

Parameters
  • function_space – the FunctionSpace the solution belongs to

  • test_function – custom TestFunction.

  • trial_function – custom TrialFunction.

residual(uv, eta, uv_old, eta_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.shallowwater_eq.ModeSplit2DEquations(function_space, depth, options)[source]

Bases: thetis.shallowwater_eq.BaseShallowWaterEquation

2D depth-averaged shallow water equations for mode splitting schemes.

Defines the equations (11) - (12).

Parameters
  • function_space – Mixed function space where the solution belongs

  • depth

    class

    DepthExpression containing depth info

  • optionsAttrDict object containing all circulation model options

add_momentum_terms(*args)[source]
residual(label, solution, solution_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the residual by summing up all the terms with the desired label.

Sign convention: all terms are assumed to be on the right hand side of the equation: d(u)/dt = term.

Parameters
  • label – string defining the type of terms to sum up. Currently one of ‘source’|’explicit’|’implicit’|’nonlinear’. Can be a list of multiple labels, or ‘all’ in which case all defined terms are summed.

  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.shallowwater_eq.MomentumSourceTerm(u_test, u_space, eta_space, depth, options=None)[source]

Bases: thetis.shallowwater_eq.ShallowWaterMomentumTerm

Generic source term in the shallow water momentum equation

The weak form reads

\[F_s = \int_\Omega \boldsymbol{\tau} \cdot \boldsymbol{\psi} dx\]

where \(\boldsymbol{\tau}\) is a user defined vector valued Function.

Parameters
  • function_space – the FunctionSpace the solution belongs to

  • test_function – custom TestFunction.

  • trial_function – custom TrialFunction.

residual(uv, eta, uv_old, eta_old, fields, fields_old, bnd_conditions)[source]

Returns an UFL form of the term.

Parameters
  • solution – solution Function of the corresponding equation

  • solution_old – a time lagged solution Function

  • fields – a dictionary that provides all the remaining fields that the term depends on. The keys of the dictionary should standard field names in field_metadata

  • fields_old – Time lagged dictionary of fields

  • bnd_conditions – A dictionary describing boundary conditions. E.g. {3: {‘elev_2d’: Constant(1.0)}} replaces elev_2d function by a constant on boundary ID 3.

class thetis.shallowwater_eq.QuadraticDragTerm(u_test, u_space, eta_space, depth, options=None)[source]

Bases: thetis.shallowwater_eq.ShallowWaterMomentumTerm

Quadratic Manning bottom friction term \(C_D \| \bar{\textbf{u}} \| \bar{\textbf{u}}\)

where the drag coefficient is computed with the Manning formula

\[C_D = g \frac{\mu^2}{H^{1/3}}\]

if the Manning coefficient \(\mu\) is defined (see field manning_drag_coefficient). Otherwise \(C_D\) is taken as a constant (see field quadratic_drag_coefficient).

Parameters
  • function_space – the FunctionSpace the solution belongs to

  • test_function – custom TestFunction.

  • trial_function – custom TrialFunction.

residual(uv, eta, uv_old, eta_old, fields, fields_old, bnd_con