Module Contents



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)[source]

Bases: opendrift.models.physics_methods.PhysicsMethods, opendrift.timer.Timeable

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.

Initialise OpenDriftSimulation

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 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’)

status_categories = ['active']
max_speed = 1
plot_comparison_colors = ['k', 'r', 'g', 'b', 'm', 'c', 'y']
classmethod SRS(cls)[source]
list_config(self, prefix='')[source]

List all possible configuration settings with values

list_configspec(self, prefix='')[source]

Readable formatting of config specification

get_configspec(self, prefix='', level=[1, 2, 3])[source]
_add_config(self, 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’, ‘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(self, key, value)[source]
_set_config_default(self, key, value)[source]

Update both default and actual value of a config setting

get_config(self, key)[source]
add_metadata(self, key, value)[source]

Add item to metadata dictionary, for export as netCDF global attributes

store_present_positions(self, IDs=None, lons=None, lats=None)[source]

Store present element positions, in case they shall be moved back


Store some environment variables, for access at next time step

interact_with_coastline(self, final=False)[source]

Coastline interaction according to configuration setting


Seafloor interaction according to configuration setting

abstract update(self)[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)

property ElementType(self)

Any trajectory model implementation must define an ElementType.

property required_variables(self)

Any trajectory model implementation must list needed variables.


Report the time spent on various tasks

add_reader(self, 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.


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(self, urls, timeout=10, lazy=True)[source]

Make readers from a list of URLs or paths to netCDF datasets

add_readers_from_file(self, filename, timeout=10, lazy=True)[source]

Return list of all variables provided by the added readers.


Return list of all variables for which no reader has been added.

get_reader_groups(self, 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’.


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_if_not_relevant(self, reader)[source]
discard_reader(self, reader)[source]
get_environment(self, variables, time, lon, lat, z, profiles)[source]

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.


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(self, elements, time)[source]

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(self, lon, lat)[source]

Return the closest ocean points for given lon, lat

seed_elements(self, lon, lat, time, radius=0, number=None, radius_type='gaussian', **kwargs)[source]

Seed elements with given position(s), time and properties.

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.


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(self, lon, lat, time, radius=0, number=None, **kwargs)[source]

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_from_geojson(self, gjson)[source]

Under development

seed_repeated_segment(self, 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:

  1. number_per_segment, in which case total number of elements is number_per_segment * len(times), or

  2. 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(self, lons, lats, number=None, **kwargs)[source]

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(self, wkt, number=None, **kwargs)[source]

Seeds elements within (multi)polygons from WKT

seed_from_shapefile(self, shapefile, number, layername=None, featurenum=None, **kwargs)[source]

Seeds elements within contours read from a shapefile

seed_letters(self, text, lon, lat, time, number, scale=1.2)[source]

Seed elements within text polygons

seed_from_ladim(self, ladimfile, roms)[source]

Seed elements from ladim *.rls text file: [time, x, y, z, name]


Move elements with random walk according to given horizontal diffuivity.

deactivate_elements(self, indices, reason='deactivated')[source]

Schedule deactivated particles for deletion (at end of step)


Moving deactivated elements from self.elements to self.elements_deactivated.

set_fallback_values(self, refresh=False)[source]
run(self, 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..

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(self, corners=None, buffer=0.1, delta_lat=None, lscale=None, fast=False, hide_landmask=False, **kwargs)[source]

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(self, buffer=0.2, corners=None, filename=None, compare=None, background=None, bgalpha=0.5, vmin=None, vmax=None, drifter=None, skip=5, scale=10, 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', fps=8, lscale=None, fast=False, **kwargs)[source]

Animate last run.

animation_profile(self, filename=None, compare=None, legend=['', ''], markersize=5, fps=20, color=None, cmap=None, vmin=None, vmax=None, legend_loc=None)[source]

Animate vertical profile of the last run.

_get_comparison_xy_for_plots(self, compare)[source]
plot(self, 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=2, scale=10, show_scalar=True, contourlines=False, trajectory_dict=None, colorbar=True, linewidth=1, lcs=None, show_particles=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)[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.

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_trajectory_dict(self, ax, trajectory_dict)[source]

Plot provided trajectory along with simulated

get_map_background(self, ax, background, time=None)[source]
get_density_xarray(self, pixelsize_m, weights=None, per_origin_marker=False)[source]
get_density_array(self, pixelsize_m, weight=None)[source]
get_density_array_proj(self, pixelsize_m, density_proj=None, llcrnrlon=None, llcrnrlat=None, urcrnrlon=None, urcrnrlat=None, weight=None)[source]
get_residence_time(self, pixelsize_m)[source]
write_netcdf_density_map(self, filename, pixelsize_m='auto')[source]

Write netCDF file with map of particles densities

write_netcdf_density_map_proj(self, 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(self, 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’


Return a list of output times of last run.

plot_environment(self, filename=None, ax=None, show=True)[source]

Plot mean wind and current velocities of element of last run.

plot_property(self, prop, filename=None, mean=False)[source]

Basic function to plot time series of any element properties.

get_property(self, propname)[source]

Get property from history, sorted by status.


Calculate lengths and speeds along trajectories.

update_positions(self, 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).

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_message(self, message)[source]

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(self, anim, filename, fps)[source]
calculate_ftle(self, reader=None, delta=None, domain=None, time=None, time_step=None, duration=None, z=0, RLCS=True, ALCS=True)[source]
center_of_gravity(self, onlysurface=False)[source]

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