opendrift.models.basemodel
Submodules
Attributes
Exceptions
Common base class for all non-exit exceptions. |
Classes
Utility class for measuring total time spent in various steps in a class |
|
Utility class for measuring total time spent in various steps in a class |
|
Physics methods to be inherited by OpenDriftSimulation class |
|
Generic trajectory model class, to be extended (subclassed). |
Functions
|
Package Contents
- class opendrift.models.basemodel.Environment(required_variables, _config)[source]
Bases:
opendrift.timer.Timeable
,opendrift.config.Configurable
Utility class for measuring total time spent in various steps in a class throughout program execution.
- readers: OrderedDict
- priority_list: OrderedDict
- required_variables: Dict
- discarded_readers: Dict
- proj_latlon
- __finalized__ = False
- _config
- required_profiles
- desired_variables
- finalize(simulation_extent=None, start=None, end=None)[source]
Prepare environment for simulation.
Args:
simulation_extent: The expected extent of the simulation.
start: Expected start time of simulation.
end: Expected end time of simulation.
- add_readers_from_list(urls, timeout=10, lazy=True, variables=None)[source]
Make readers from a list of URLs or paths to netCDF datasets
- add_reader(readers, variables=None, first=False)[source]
Add one or more readers providing variables used by this model.
Method may be called subsequently to add more readers for other variables.
- Args:
readers: one or more (list) Reader objects.
variables (optional): list of strings of standard_name of variables to be provided by this/these reader(s). first: Set to True if this reader should be set as first option
- get_reader_groups(variables=None)[source]
Find which groups of variables are provided by the same readers.
This function loops through ‘priority_list’ (see above) and groups all variables returned by the same readers in the same order. This allows asking readers for several variables simultaneously, improving performance. Used by method ‘get_environment’.
- Returns:
variable_groups: list of lists of (environment) variables. reader_groups: list of list of reader names, corresponding to each of the variable_groups.
- get_environment(variables, time, lon, lat, z, profiles=None, profiles_depth=None)[source]
Retrieve environmental variables at requested positions.
Args:
variables: list of variable names
time: time to get environment for
lon: array of longitudes
lat: array of latitudes
z: depth to get value for
profiles: list of variables for which profiles are needed
profiles_depth: depth of profiles in meters, as a positive number
- Updates:
- Buffer (raw data blocks) for each reader stored for performance:
[readers].var_block_before (last before requested time) [readers].var_block_after (first after requested time) - lists of one ReaderBlock per variable group: time, x, y, [vars]
- Returns:
- environment: recarray with variables as named attributes,
interpolated to requested positions/time.
- opendrift.models.basemodel.logger
- class opendrift.models.basemodel.Timeable[source]
Utility class for measuring total time spent in various steps in a class throughout program execution.
- __timers__ = None
- __timing__ = None
- property timers
- property timing
- exception opendrift.models.basemodel.WrongMode(expected_mode, real_mode, msg=None)[source]
Bases:
Exception
Common base class for all non-exit exceptions.
Initialize self. See help(type(self)) for accurate signature.
- class opendrift.models.basemodel.PhysicsMethods[source]
Physics methods to be inherited by OpenDriftSimulation class
- static sea_water_density(T=10.0, S=35.0)[source]
The function gives the density of seawater at one atmosphere pressure as given in :
N.P. Fofonoff and R.C. Millard Jr.,1983, Unesco technical papers in marine science no. 44.
S = Salinity in promille of the seawater T = Temperature of the seawater in degrees Celsius
- skillscore_trajectory(lon_obs, lat_obs, time_obs, duration=None, max_time_offset=timedelta(seconds=60), method='liu-weissberg', **kwargs)[source]
Calculate skill-score comparing simulated and observed trajectories
A skill score is calculated for each of the modelled trajectories, starting from the closest time/obs of the given modelled trajectory
Parameters
lon_obs : array_like lat_obs : array_like
The longitude and latitudes of the observed trajectory
- time_obsarray of datetime
The time corresponding to the observed positions
- durationtimedelta
If None, skill score is calculated for the full trajectory, from the start Otherwise, only this sub-part of the trajectory is used.
- max_time_offsettimedelta
The maximum allowed time difference between observed and modelled time Default: 1 minute
- methodstring
Currently available: ‘liu-wessberg’ To be implemented: ‘darpa’
**kwargs : further arguments for skillscore method (e.g. tolerance_threshold)
Returns
- skillscorearray_like
One value for each trajectory
- class opendrift.models.basemodel.Configurable[source]
- _config: Dict | None = None
- _add_config(config, overwrite=True)[source]
Add configuration settings
config is a dictionary where keys are configuration keywords, and values are dictionaries with the following contents:
type (string): ‘float’, ‘int’, ‘str’, ‘bool’ or ‘enum’
- min, max (float/int/None): (only when type is ‘float’ or ‘int’)
The minimum and maximum allowed values for this setting. May also be None if there are no upper/lowe limits.
min_length, max_length (int): minimum and maximum length of string
- units (string): (only when type is ‘float’ or ‘int’)
The units of this config setting.
- enum (list): (only when type is ‘enum’)
A list of possible values for this setting.
- default (number/bool/string/None):
The default value for this setting.
- value (number/bool/string/None): The actual value for this setting.
This is updated with self.set_config(key, value) and retrieved with self.get_config(key)
- description (string):
A description of this config setting, for users/documentation/GUIs.
- level (int): A parameter to determine the level of exposure in GUIs
1 CONFIG_LEVEL_ESSENTIAL: important setting which user has to consider 2 CONFIG_LEVEL_BASIC: setting which many users may consider 3 CONFIG_LEVEL_ADVANCED: setting relevant only to advanced users
- opendrift.models.basemodel.CONFIG_LEVEL_BASIC = 2
- opendrift.models.basemodel.CONFIG_LEVEL_ADVANCED = 3
- opendrift.models.basemodel.CONFIG_LEVEL_ESSENTIAL = 1
- opendrift.models.basemodel.Mode
- opendrift.models.basemodel.rl
- opendrift.models.basemodel.require_mode(mode, post_next_mode=False, error=None)[source]
- Parameters:
mode (Union[Mode, List[Mode]])
- class opendrift.models.basemodel.OpenDriftSimulation(seed=0, iomodule='netcdf', loglevel=logging.DEBUG, logtime='%H:%M:%S', logfile=None)[source]
Bases:
opendrift.models.physics_methods.PhysicsMethods
,opendrift.timer.Timeable
,opendrift.config.Configurable
Generic trajectory model class, to be extended (subclassed).
This as an Abstract Base Class, meaning that only subclasses can be initiated and used. Any specific subclass (‘model’) must contain its own (or shared) specific type of particles (ElementType), whose properties are updated at each time_step using method update() on basis of model physics/chemistry/biology and ‘required_variables’ (environment) which are provided by one or more Reader objects.
- Attributes:
ElementType: the type (class) of particles to be used by this model
elements: object of the class ElementType, storing the specific particle properties (ndarrays and scalars) of all active particles as named attributes. Elements are added by seeding-functions (presently only one implemented: seed_elements).
- elements_deactivated: ElementType object containing particles which
have been deactivated (and removed from ‘elements’)
- elements_scheduled: ElementType object containing particles which
have been scheduled, but not yet activated
- required_variables: list of strings of CF standard_names which is
needed by this model (update function) to update properties of particles (‘elements’) at each time_step. This core class has no required_elements, this is implemented by subclasses/modules.
- environment: recarray storing environment variables (wind, waves,
current etc) as named attributes. Attribute names follow standard_name from CF-convention, allowing any OpenDriftSimulation module/subclass using environment data from any readers which can provide the requested variables. Used in method ‘update’ to update properties of elements every time_step.
- time_step: timedelta object, time interval at which element properties
are updated (including advection).
- time_step_output: timedelta object, time interval at which element
properties are stored in memory and eventually written to file
- readers: Dictionary where values are Reader objects, and names are
unique reference keywords used to access a given reader (typically filename or URL)
- priority_list: OrderedDict where names are variable names,
and values are lists of names (kewywords) of the reader, in the order of priority (user defined) of which the readers shall be called to retrieve environmental data.
Initialise OpenDriftSimulation
- Args:
- seed: integer or None. A given integer will yield identical
random numbers drawn each simulation. Random numbers are e.g. used to distribute particles spatially when seeding, and may be used by modules (subclasses) for e.g. diffusion. Specifying a fixed value (default: 0) is useful for sensitivity tests. With seed = None, different random numbers will be drawn for subsequent runs, even with identical configuration/input.
- iomodule: name of module used to export data
default: netcdf, see
opendrift.io
for more alternatives. iomodule is module/filename without preceeding io_- loglevel: set to 0 (default) to retrieve all debug information.
Provide a higher value (e.g. 20) to receive less output. Use the string ‘custom’ to configure logging from outside.
- logtime: if True, a time stamp is given for each logging line.
logtime can also be given as a python time specifier (e.g. ‘%H:%M:%S’)
- __metaclass__
- mode
- status_categories = ['active']
- status_colors_default
- plot_comparison_colors = ['k', 'r', 'g', 'b', 'm', 'c', 'y', 'crimson', 'indigo', 'lightcoral', 'grey', 'sandybrown',...
- proj_latlon
The environment holds all the readers and the forcing data for the simulation.
- profiles_depth = None
- show_continuous_performance = False
- origin_marker = None
- minvals
- maxvals
- seed_geojson = []
- steps_calculation = 0
- steps_output = 0
- elements_deactivated
- elements
- io_init
- io_write_buffer
- io_close
- io_import_file
- io_import_file_xarray
- history = None
- required_profiles
- desired_variables
- set_config(*args, **kwargs)
- __set_seed_config__(key, value)
This method allows setting config values that are passed as seed arguments. The environment is already prepared before this, so make sure that nothing is changed that requires the environment to be re-initialized.
- Parameters:
key (str)
- add_metadata(key, value)[source]
Add item to metadata dictionary, for export as netCDF global attributes
- add_readers_from_list(*args, **kwargs)[source]
Make readers from a list of URLs or paths to netCDF datasets
- add_readers_from_file(*args, **kwargs)[source]
Make readers from a file containing list of URLs or paths to netCDF datasets
- store_present_positions(IDs=None, lons=None, lats=None)[source]
Store present element positions, in case they shall be moved back
- interact_with_coastline(final=False)[source]
Coastline interaction according to configuration setting
- abstract update()[source]
Any trajectory model implementation must define an update method. This method must/can use environment data (self.environment) to update properties (including position) of its particles (self.elements)
- abstract property ElementType
Any trajectory model implementation must define an ElementType.
- abstract property required_variables
Any trajectory model implementation must list needed variables.
- schedule_elements(elements, time)[source]
Schedule elements to be seeded during runtime.
Also assigns a unique ID to each particle, monotonically increasing.
- seed_elements(lon, lat, time, radius=0, number=None, radius_type='gaussian', **kwargs)[source]
Seed elements with given position(s), time and properties.
- Arguments:
- lon: scalar or array
central longitude(s).
- lat: scalar or array
central latitude(s).
- radius: scalar or array
radius in meters around each lon-lat pair, within which particles will be randomly seeded.
- number: integer, total number of particles to be seeded
If number is None, the number of elements is the length of lon/lat or time if these are arrays. Otherwise the number of elements are obtained from the config-default.
- time: datenum or list
The time at which particles are seeded/released. If time is a list with two elements, elements are seeded continously from start/first to end/last time. If time is a list with more than two elements, the number of elements is equal to len(time) and are seeded as a time series.
- radius_type: string
If ‘gaussian’ (default), the radius is the standard deviation in x-y-directions. If ‘uniform’, elements are spread evenly and always inside a circle with the given radius.
- kwargs:
keyword arguments containing properties/attributes and values corresponding to the actual particle type (ElementType). These are forwarded to the ElementType class. All properties for which there are no default value must be specified.
- seed_cone(lon, lat, time, radius=0, number=None, **kwargs)[source]
Seed elements along a transect/cone between two points/times
- Arguments:
lon: scalar or list with 2 elements [lon0, lon1]
lat: scalar or list with 2 elements [lat0, lat]
time: datetime or list with 2 elements [t0, t1]
radius: scalar or list with 2 elements [r0, r1] Unit: meters
number (int): The number of elements. If this is None, the number of elements is taken from configuration.
- Elements are seeded along a transect from
(lon0, lat0) with uncertainty radius r0 at time t0, towards (lon1, lat1) with uncertainty radius r1 at time t1. If r0 != r1, the unceetainty radius is linearly changed along the transect, thus outlining a “cone”.
- seed_repeated_segment(lons, lats, start_time, end_time, time_interval=None, number_per_segment=None, total_number=None, **kwargs)[source]
Seed elements repeatedly in time along a segment.
The segment goes from lon[0],lat[0] to lon[1],lat[1].
The number of elements should be proved as either:
number_per_segment, in which case total number of elements is number_per_segment * len(times), or
total_number, in which case the number of elements per segment is: total_number / len(times). Any extra elements are duplicated along at the first segment.
- seed_within_polygon(lons, lats, number=None, **kwargs)[source]
Seed a number of elements within given polygon.
- Arguments:
lon: array of longitudes
lat: array of latitudes
number: int, number of elements to be seeded
kwargs: keyword arguments containing properties/attributes and values corresponding to the actual particle type (ElementType). These are forwarded to method seed_elements(). All properties for which there are no default value must be specified.
- seed_from_shapefile(shapefile, number, layername=None, featurenum=None, **kwargs)[source]
Seeds elements within contours read from a shapefile
- seed_from_ladim(ladimfile, roms)[source]
Seed elements from ladim *.rls text file: [time, x, y, z, name]
- horizontal_diffusion()[source]
Move elements with random walk according to given horizontal diffuivity.
- deactivate_elements(indices, reason='deactivated')[source]
Schedule deactivated particles for deletion (at end of step)
- remove_deactivated_elements()[source]
Moving deactivated elements from self.elements to self.elements_deactivated.
- run(time_step=None, steps=None, time_step_output=None, duration=None, end_time=None, outfile=None, export_variables=None, export_buffer_length=100, stop_on_error=False)[source]
Start a trajectory simulation, after initial configuration.
- Performs the main loop:
Obtain environment data for positions of all particles.
Call method ‘update’ to update (incl advect) particle properties.
- until one of the following conditions are met:
Maximum number of steps are reached
- A needed variable can not be obtained by any reader
(outside spatial/temporal domain) and has no fallback (default) value.
All particles have been deactivated (e.g. by stranding)
Occurance of any error, whose trace will be output to terminal.
Before starting a model run, readers must be added for all required variables, unless fallback values have been specified. Some particles/elements must have been scheduled for seeding, and the run will start at the time when the first element has been scheduled..
- Arguments:
- time_step: interval between particles updates, in seconds or as
timedelta. Default: 3600 seconds (1 hour)
- time_step_output: Time step at which element properties are stored
and eventually written to file. Timedelta object or seconds. Default: same as time_step, meaning that all steps are stored
- The length of the simulation is specified by defining one
(and only one) of the following parameters: - steps: integer, maximum number of steps. End of simulation will be self.start_time + steps*self.time_step - duration: timedelta defining the length of the simulation - end_time: datetime object defining the end of the simulation
- export_variables: list of variables and parameter names to be
saved to file. Default is None (all variables are saved)
- increase_age_and_retire()[source]
Increase age of elements, and retire if older than config setting.
- index_of_activation_and_deactivation()[source]
Return the indices when elements were seeded and deactivated.
- set_up_map(corners=None, buffer=0.1, delta_lat=None, lscale=None, fast=False, hide_landmask=False, xlocs=None, ylocs=None, **kwargs)[source]
Generate Figure instance on which trajectories are plotted.
- Parameters:
hide_landmask (bool) – do not plot landmask (default False)
provide corners=[lonmin, lonmax, latmin, latmax] for specific map selection
- animation(buffer=0.2, corners=None, filename=None, compare=None, compare_marker='o', background=None, alpha=1, bgalpha=0.5, vmin=None, vmax=None, drifter=None, shapefiles=None, skip=None, scale=None, color=False, clabel=None, colorbar=True, cmap=None, density=False, show_elements=True, show_trajectories=False, linewidth=1, trajectory_alpha=0.1, hide_landmask=False, density_pixelsize_m=1000, unitfactor=1, lcs=None, surface_only=False, markersize=20, markersize_scaling=None, origin_marker=None, legend=None, legend_loc='best', title='auto', fps=8, lscale=None, fast=False, blit=False, frames=None, xlocs=None, ylocs=None, **kwargs)[source]
Animate last run.
- animation_profile(filename=None, compare=None, markersize=20, markersize_scaling=None, alpha=1, fps=20, color=None, cmap=None, vmin=None, vmax=None, legend=None, legend_loc=None)[source]
Animate vertical profile of the last run.
- plot(background=None, buffer=0.2, corners=None, linecolor=None, filename=None, show=True, vmin=None, vmax=None, compare=None, cmap='jet', lvmin=None, lvmax=None, skip=None, scale=None, show_scalar=True, contourlines=False, drifter=None, colorbar=True, linewidth=1, lcs=None, show_elements=True, show_trajectories=True, show_initial=True, density_pixelsize_m=1000, lalpha=None, bgalpha=1, clabel=None, cpad=0.05, caspect=30, cshrink=0.8, surface_color=None, submerged_color=None, markersize=20, title='auto', legend=True, legend_loc='best', lscale=None, fast=False, hide_landmask=False, xlocs=None, ylocs=None, **kwargs)[source]
Basic built-in plotting function intended for developing/debugging.
Plots trajectories of all particles. Positions marked with colored stars: - green: all start positions - red: deactivated particles - blue: particles still active at end of simulation
Requires availability of Cartopy.
- Arguments:
- background: string, name of variable (standard_name) which will
be plotted as background of trajectories, provided that it can be read with one of the available readers.
- buffer: float; spatial buffer of plot in degrees of
longitude/latitude around particle collection.
background: name of variable to be plotted as background field. Use two element list for vector fields, e.g. [‘x_wind’, ‘y_wind’]
vmin, vmax: minimum and maximum values for colors of background.
linecolor: name of variable to be used for coloring trajectories, or matplotlib color string.
lvmin, lvmax: minimum and maximum values for colors of trajectories.
lscale (string): resolution of land feature (‘c’, ‘l’, ‘i’, ‘h’, ‘f’, ‘auto’). default is ‘auto’.
fast (bool): use some optimizations to speed up plotting at the cost of accuracy
- param hide_landmask:
do not plot landmask (default False).
- type hide_landmask:
bool
- get_density_array_proj(pixelsize_m, density_proj=None, llcrnrlon=None, llcrnrlat=None, urcrnrlon=None, urcrnrlat=None, weight=None)[source]
- write_netcdf_density_map(filename, pixelsize_m='auto')[source]
Write netCDF file with map of particles densities
- write_netcdf_density_map_proj(filename, pixelsize_m='auto', density_proj=None, llcrnrlon=None, llcrnrlat=None, urcrnrlon=None, urcrnrlat=None)[source]
Write netCDF file with map of particles densities for a given projection or area
- write_geotiff(filename, pixelsize_km=0.2)[source]
Write one GeoTiff image per timestep.
filename should contain date identifiers, e.g. ‘img_%Y%m%d_%H%M.tif’ https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
- plot_environment(filename=None, ax=None, show=True)[source]
Plot mean wind and current velocities of element of last run.
- plot_property(prop, filename=None, mean=False)[source]
Basic function to plot time series of any element properties.
- update_positions(x_vel, y_vel)[source]
Move particles according to given velocity components.
This method shall account for projection metrics (a distance on a map projection does not necessarily correspond to the same distance over true ground (not yet implemented).
- Arguments:
- x_vel and v_vel: floats, velocities in m/s of particle along
x- and y-axes of the inherit SRS (proj4).
- calculate_ftle(reader=None, delta=None, domain=None, time=None, time_step=None, duration=None, z=0, RLCS=True, ALCS=True)[source]