Generic trajectory model class, to be extended (subclassed).
- class opendrift.models.basemodel.OpenDriftSimulation(seed=0, iomodule='netcdf', loglevel=logging.DEBUG, logtime='%H:%M:%S', logfile=None)
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.
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.
- 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.iofor 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’)
- status_categories = ['active']
- CONFIG_LEVEL_ESSENTIAL = 1
- CONFIG_LEVEL_BASIC = 2
- CONFIG_LEVEL_ADVANCED = 3
- max_speed = 1
- plot_comparison_colors = ['k', 'r', 'g', 'b', 'm', 'c', 'y', 'crimson', 'indigo', 'lightcoral', 'grey', 'sandybrown',...
- classmethod SRS()
List all possible configuration settings with values
Readable formatting of config specification
- get_configspec(prefix='', level=[1, 2, 3])
- _add_config(config, overwrite=True)
Add configuration settings
config is a dictionary where keys are configuration keywords, and values are dictionaries with the following contents:
type (string): ‘float’, ‘int’, ‘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.
- 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 self.CONFIG_LEVEL_ESSENTIAL: important setting which user has to consider 2 self.CONFIG_LEVEL_BASIC: setting which many users may consider 3 self.CONFIG_LEVEL_ADVANCED: setting relevant only to advanced users
- set_config(key, value)
- _set_config_default(key, value)
Update both default and actual value of a config setting
- add_metadata(key, value)
Add item to metadata dictionary, for export as netCDF global attributes
- store_present_positions(IDs=None, lons=None, lats=None)
Store present element positions, in case they shall be moved back
Store some environment variables, for access at next time step
Coastline interaction according to configuration setting
Seafloor interaction according to configuration setting
- abstract update()
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)
- property ElementType
Any trajectory model implementation must define an ElementType.
- property required_variables
Any trajectory model implementation must list needed variables.
Report the time spent on various tasks
- add_reader(readers, variables=None, first=False)
Add one or more readers providing variables used by this model.
Method may be called subsequently to add more readers for other variables.
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
- add_readers_from_list(urls, timeout=10, lazy=True, variables=None)
Make readers from a list of URLs or paths to netCDF datasets
- add_readers_from_file(filename, timeout=10, lazy=True)
Return list of all variables provided by the added readers.
Return list of all variables for which no reader has been added.
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’.
variable_groups: list of lists of (environment) variables. reader_groups: list of list of reader names, corresponding to each of the variable_groups.
Returns reader if successful and None if no more readers
- discard_reader(reader, reason)
- get_environment(variables, time, lon, lat, z, profiles)
Retrieve environmental variables at requested positions.
- 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]
- environment: recarray with variables as named attributes,
interpolated to requested positions/time.
- get_variables_along_trajectory(variables, lons, lats, times)
The number of active elements.
The number of deactivated elements.
The total number of scheduled, active and deactivated elements.
The total number of active and deactivated elements.
- schedule_elements(elements, time)
Schedule elements to be seeded during runtime.
Also assigns a unique ID to each particle, monotonically increasing.
Activate elements which are scheduled within following timestep.
- closest_ocean_points(lon, lat)
Return the closest ocean points for given lon, lat
- seed_elements(lon, lat, time, radius=0, number=None, radius_type='gaussian', **kwargs)
Seed elements with given position(s), time and properties.
- lon: scalar or array
- lat: scalar or array
- 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.
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)
Seed elements along a transect/cone between two points/times
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)
Seed elements repeatedly in time along a segment.
The segment goes from lon,lat to lon,lat.
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)
Seed a number of elements within given polygon.
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_wkt(wkt, number=None, **kwargs)
Seeds elements within (multi)polygons from WKT
- seed_from_shapefile(shapefile, number, layername=None, featurenum=None, **kwargs)
Seeds elements within contours read from a shapefile
- seed_letters(text, lon, lat, time, number, scale=1.2)
Seed elements within text polygons
- seed_from_ladim(ladimfile, roms)
Seed elements from ladim *.rls text file: [time, x, y, z, name]
Move elements with random walk according to given horizontal diffuivity.
- deactivate_elements(indices, reason='deactivated')
Schedule deactivated particles for deletion (at end of step)
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)
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..
- 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 of elements, and retire if older than config setting.
Append present state (elements and environment) to recarray.
Issue warning if some environment variables missing.
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, **kwargs)
Generate Figure instance on which trajectories are plotted.
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, bgalpha=0.5, vmin=None, vmax=None, drifter=None, skip=None, scale=None, color=False, clabel=None, colorbar=True, cmap=None, density=False, show_elements=True, show_trajectories=False, trajectory_alpha=0.1, hide_landmask=False, density_pixelsize_m=1000, unitfactor=1, lcs=None, surface_only=False, markersize=20, origin_marker=None, legend=None, legend_loc='best', title='auto', fps=8, lscale=None, fast=False, blit=False, **kwargs)
Animate last run.
- __save_or_plot_animation__(figure, plot_timestep, filename, frames, fps, interval, blit)
- animation_profile(filename=None, compare=None, legend=['', ''], markersize=5, fps=20, color=None, cmap=None, vmin=None, vmax=None, legend_loc=None)
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, bgalpha=1, clabel=None, surface_color=None, submerged_color=None, markersize=20, title='auto', legend=True, legend_loc='best', lscale=None, fast=False, hide_landmask=False, **kwargs)
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.
- 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
- _plot_drifter(ax, gcrs, drifter)
Plot provided trajectory along with simulated
- get_map_background(ax, background, crs, time=None)
- get_histogram(pixelsize_m, **kwargs)
- get_density_array(pixelsize_m, weight=None)
- get_density_array_proj(pixelsize_m, density_proj=None, llcrnrlon=None, llcrnrlat=None, urcrnrlon=None, urcrnrlat=None, weight=None)
- write_netcdf_density_map(filename, pixelsize_m='auto')
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)
Write netCDF file with map of particles densities for a given projection or area
- write_geotiff(filename, pixelsize_km=0.2)
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
Return a list of output times of last run.
- plot_environment(filename=None, ax=None, show=True)
Plot mean wind and current velocities of element of last run.
- plot_property(prop, filename=None, mean=False)
Basic function to plot time series of any element properties.
Get property from history, sorted by status.
Calculate lengths and speeds along trajectories.
- update_positions(x_vel, y_vel)
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).
- x_vel and v_vel: floats, velocities in m/s of particle along
x- and y-axes of the inherit SRS (proj4).
String representation providing overview of model status.
Store important messages to be displayed to user at end.
Report any messages stored during simulation.
Adding some Thredds and file readers in prioritised order
- __save_animation__(fig, plot_timestep, filename, frames, fps, blit, interval)
- calculate_ftle(reader=None, delta=None, domain=None, time=None, time_step=None, duration=None, z=0, RLCS=True, ALCS=True)
calculate center of mass and variance of all elements returns (lon,lat), variance where (lon,lat) are the coordinates of the center of mass as function of time
Preparing OpenDrift object for new run
To be overloaded by subclasses