### Prepare Run Source: https://opendrift.github.io/autoapi/opendrift/models/openoil/index.html Performs any necessary setup before starting the simulation run. ```python prepare_run() ``` -------------------------------- ### Download All Examples Source: https://opendrift.github.io/gallery/index.html Links to download all gallery examples as Python source code or Jupyter notebooks. ```text Download all examples in Python source code: gallery_python.zip ``` ```text Download all examples in Jupyter notebooks: gallery_jupyter.zip ``` -------------------------------- ### Custom Wave Packet Size Configuration Source: https://opendrift.github.io/trajan/gallery/example_omb_csv_reader.html This example demonstrates how to configure custom wave packet sizes and set a start time to ignore older messages. This is useful when firmware has been modified. ```python # example 2: custom size of wave packets; for users who have changed the firmware to transmit and using a set start time: ignore messages before it more or less spectrum bins ``` -------------------------------- ### Download Example Files Source: https://opendrift.github.io/gallery/example_water_column_stretching.html Links to download the Jupyter notebook, Python source code, and a zipped archive for the water column stretching example. ```text Download Jupyter notebook: example_water_column_stretching.ipynb Download Python source code: example_water_column_stretching.py Download zipped: example_water_column_stretching.zip ``` -------------------------------- ### Install Trajan from Source Source: https://opendrift.github.io/trajan/_sources/index.rst.txt Recommended for developers contributing to Trajan. Requires navigating to the source directory and installing. ```console $ cd trajan # move to the location of the trajan root, containing the pyproject.toml file $ pip install . ``` -------------------------------- ### Start OpenDrift GUI Source: https://opendrift.github.io/_sources/gui.rst.txt Launch the OpenDrift Graphical User Interface. This command assumes OpenDrift is installed or its scripts directory is in the PATH. Alternatively, run 'python opendrift_gui.py' from the scripts folder. ```bash $ opendrift_gui.py ``` -------------------------------- ### Install and Configure Coloredlogs Source: https://opendrift.github.io/trajan/_downloads/e91a213efe083c695858d56cefa37cd1/example_omb_csv_reader.ipynb Imports necessary libraries and installs coloredlogs for debugging output. Adjust the log level as needed. ```python from pathlib import Path from trajan.readers.omb import read_omb_csv import coloredlogs import datetime # adjust the level of information printed # coloredlogs.install(level='error') coloredlogs.install(level='debug') ``` -------------------------------- ### Install and configure OpenDrift on WEkEO and EDITO Source: https://opendrift.github.io/_sources/install.rst.txt Installs OpenDrift in the JupyterHub workspace and configures Copernicus credentials. ```bash $ mamba install opendrift ``` ```bash $ export COPERNICUSMARINE_SERVICE_USERNAME= $ export COPERNICUSMARINE_SERVICE_PASSWORD= ``` ```bash COPERNICUSMARINE_SERVICE_USERNAME= COPERNICUSMARINE_SERVICE_PASSWORD= ``` -------------------------------- ### Logging Setup Source: https://opendrift.github.io/_sources/autoapi/opendrift/models/eulerdrift/index.rst.txt Function to set up colorful logging for the application. ```APIDOC ## install_logs(level=logging.DEBUG) ### Description Set up fanzy, colorful, logging. ### Args - **level** (logging level) - Optional - Log level. ``` -------------------------------- ### Simulation log output Source: https://opendrift.github.io/gallery/example_oil_thickness.html Example of the initialization log output from OpenDrift. ```text 08:27:48 INFO opendrift:568: OpenDriftSimulation initialised (version 1.14.9 / v1.14.9-9-gcde0dcf) ``` -------------------------------- ### Get Model Configuration Parameter Source: https://opendrift.github.io/tutorial.html Retrieve the current value of a specific configuration parameter. This example gets the 'wind_drift_factor'. ```python wind_drift_factor = o.get_config('seed:wind_drift_factor') ``` -------------------------------- ### Get Git Description Source: https://opendrift.github.io/_sources/autoapi/opendrift/version/index.rst.txt Retrieve the git description if the library was installed from a git repository. ```APIDOC ## GET opendrift.version.git_describe ### Description Returns the git version description if available. This is useful for identifying specific development builds. ### Method GET ### Endpoint `opendrift.version.git_describe()` ### Response #### Success Response (200) - **git_describe** (string) - The git description string, or an empty string if not available. #### Response Example ```json { "git_describe": "v1.14.9-5-gabcdef12" } ``` ``` -------------------------------- ### Define Seeding Particle Times Source: https://opendrift.github.io/gallery/example_generic.html Defines the time instances for seeding particles. This example shows how to set a list of times, including the start time of the atmospheric reader and an offset, or a single start time. ```python time = [reader_arome.start_time, reader_arome.start_time + timedelta(hours=30)] #time = reader_arome.start_time ``` -------------------------------- ### Environment Setup Log Source: https://opendrift.github.io/gallery/example_openoil_sample_output.html Log output showing ADIOS database query and fallback environment values. ```text 08:35:12 INFO opendrift.models.openoil.adios.dirjs:86: Querying ADIOS database for oil: TAU 1999 08:35:12 INFO opendrift.models.openoil.openoil:1726: Using density 851.002835 and viscosity 0.0012492557043601948 of oiltype TAU 1999 08:35:12 INFO opendrift.models.basemodel.environment:203: Adding a global landmask from GSHHG 08:35:16 INFO opendrift.models.basemodel.environment:227: Fallback values will be used for the following variables which have no readers: 08:35:16 INFO opendrift.models.basemodel.environment:230: sea_surface_height: 0.000000 08:35:16 INFO opendrift.models.basemodel.environment:230: upward_sea_water_velocity: 0.000000 08:35:16 INFO opendrift.models.basemodel.environment:230: sea_surface_wave_significant_height: 0.000000 08:35:16 INFO opendrift.models.basemodel.environment:230: sea_surface_wave_stokes_drift_x_velocity: 0.000000 08:35:16 INFO opendrift.models.basemodel.environment:230: sea_surface_wave_stokes_drift_y_velocity: 0.000000 08:35:16 INFO opendrift.models.basemodel.environment:230: sea_surface_wave_period_at_variance_spectral_density_maximum: 0.000000 08:35:16 INFO opendrift.models.basemodel.environment:230: sea_surface_wave_mean_period_from_variance_spectral_density_second_frequency_moment: 0.000000 08:35:16 INFO opendrift.models.basemodel.environment:230: sea_ice_area_fraction: 0.000000 08:35:16 INFO opendrift.models.basemodel.environment:230: sea_ice_x_velocity: 0.000000 08:35:16 INFO opendrift.models.basemodel.environment:230: sea_ice_y_velocity: 0.000000 08:35:16 INFO opendrift.models.basemodel.environment:230: sea_water_temperature: 10.000000 08:35:16 INFO opendrift.models.basemodel.environment:230: sea_water_salinity: 34.000000 08:35:16 INFO opendrift.models.basemodel.environment:230: sea_floor_depth_below_sea_level: 10000.000000 08:35:16 INFO opendrift.models.basemodel.environment:230: horizontal_diffusivity: 0.000000 08:35:16 INFO opendrift.models.basemodel.environment:230: ocean_vertical_diffusivity: 0.020000 08:35:16 INFO opendrift.models.basemodel.environment:230: ocean_mixed_layer_thickness: 50.000000 ``` -------------------------------- ### Import necessary libraries for OpenDrift and CMEMS Source: https://opendrift.github.io/_downloads/ca52802bcb80e8e9a1418baa21d21889/example_long_cmems_currents.ipynb Imports required modules for data handling, CMEMS integration, and OpenDrift model setup. Ensure these libraries are installed. ```python from datetime import datetime, timedelta import cf_xarray import copernicusmarine from opendrift.models.oceandrift import OceanDrift from opendrift.readers.reader_netCDF_CF_generic import Reader ``` -------------------------------- ### OpenDrift Initialization Logs Source: https://opendrift.github.io/gallery/example_LCS_norkyst.html Example log output showing the initialization of the OpenDrift simulation and reader detection. ```text 08:24:22 INFO opendrift:568: OpenDriftSimulation initialised (version 1.14.9 / v1.14.9-9-gcde0dcf) 08:24:22 INFO opendrift.readers:64: Opening file with xr.open_dataset 08:24:22 INFO opendrift.readers.reader_netCDF_CF_generic:340: Detected dimensions: {'x': 'X', 'y': 'Y', 'z': 'depth', 'time': 'time'} ``` -------------------------------- ### Logging Setup Function Source: https://opendrift.github.io/_modules/opendrift/models/eulerdrift.html The install_logs function configures colorful and informative logging for the OpenDrift simulation. ```APIDOC ## install_logs ### Description Set up fanzy, colorful, logging. ### Parameters #### Arguments - **level** (int) - Optional - Log level. Defaults to logging.DEBUG. ``` -------------------------------- ### Execute a basic simulation Source: https://opendrift.github.io/tutorial.html Starts the simulation using default settings. ```python o.run() ``` -------------------------------- ### Get Ocean Current Velocity Source: https://opendrift.github.io/_modules/opendrift/models/eulerdrift/simulation.html Retrieves the ocean current velocities (Ux, Uy) at a given time `t` relative to the simulation's start time `t0`. It iterates through registered readers to find velocity data. ```python def U(self, t): """ Get U (ocean current) for t0 + t """ Ux, Uy = None, None t = self.t0 + timedelta(seconds = t) for r in self.readers: vv = r.variables() if 'x_sea_water_velocity' in vv and 'y_sea_water_velocity' in vv: Ux, Uy = r.read_grid(self.grid, ['x_sea_water_velocity', 'y_sea_water_velocity'], t) if Ux is not None and Uy is not None: break return Ux, Uy ``` -------------------------------- ### Initialize Simulation Environment Source: https://opendrift.github.io/_downloads/1f273572d35a01780a354710d35e2a1a/example_river_runoff.ipynb Import necessary libraries and define output file paths for the simulation. ```python import os from datetime import datetime, timedelta import numpy as np import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter import opendrift from opendrift.models.oceandrift import OceanDrift from opendrift.readers import reader_oscillating outfile = 'runoff.nc' # Raw simulation output histogram_file = 'runoff_histogram.nc' ``` -------------------------------- ### Run Docker Container and Import OpenDrift Source: https://opendrift.github.io/docker.html Execute the OpenDrift Docker image to get an interactive shell. The working directory is set to /code, where the repository is cloned. This example also shows importing and checking the OpenDrift version within the container. ```bash $ docker run -it opendrift/opendrift Unable to find image 'opendrift/opendrift:latest' locally latest: Pulling from opendrift/opendrift cc1a78bfd46b: Already exists bad124d5894e: Pull complete ab2b0b173074: Pull complete 018d53043894: Pull complete 4987762b1e47: Pull complete d58a7f3e3615: Pull complete 86f53a067a28: Pull complete 4c17ec80ca72: Pull complete aae597ea9e38: Pull complete Digest: sha256:33807a79ced6ca9c0960bd942e9d12381c7f1066feb75c5c6992ae5b8802f94c Status: Downloaded newer image for opendrift/opendrift:latest (base) root@d7ca5fe730b8:/code# python Python 2.7.15 |Anaconda, Inc.| (default, May 1 2018, 23:32:55) [GCC 7.2.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import opendrift >>> opendrift.__version__ '1.0.4' ``` -------------------------------- ### Environment Setup Logs Source: https://opendrift.github.io/gallery/example_checkerboard.html Log output detailing the environment configuration and fallback values used. ```text 08:23:56 INFO opendrift.models.basemodel.environment:203: Adding a global landmask from GSHHG 08:24:01 INFO opendrift.models.basemodel.environment:227: Fallback values will be used for the following variables which have no readers: 08:24:01 INFO opendrift.models.basemodel.environment:230: sea_surface_height: 0.000000 08:24:01 INFO opendrift.models.basemodel.environment:230: x_wind: 0.000000 08:24:01 INFO opendrift.models.basemodel.environment:230: y_wind: 0.000000 08:24:01 INFO opendrift.models.basemodel.environment:230: upward_sea_water_velocity: 0.000000 08:24:01 INFO opendrift.models.basemodel.environment:230: ocean_vertical_diffusivity: 0.000000 08:24:01 INFO opendrift.models.basemodel.environment:230: horizontal_diffusivity: 0.000000 08:24:01 INFO opendrift.models.basemodel.environment:230: sea_surface_wave_significant_height: 0.000000 08:24:01 INFO opendrift.models.basemodel.environment:230: sea_surface_wave_stokes_drift_x_velocity: 0.000000 08:24:01 INFO opendrift.models.basemodel.environment:230: sea_surface_wave_stokes_drift_y_velocity: 0.000000 08:24:01 INFO opendrift.models.basemodel.environment:230: ocean_mixed_layer_thickness: 50.000000 08:24:01 INFO opendrift.models.basemodel.environment:230: sea_floor_depth_below_sea_level: 10000.000000 ``` -------------------------------- ### Install Trajan using Pip Source: https://opendrift.github.io/trajan/_sources/index.rst.txt Alternative installation method for users using Pip. Installs the package from PyPI. ```console $ pip install trajan ``` -------------------------------- ### Install Logging Source: https://opendrift.github.io/_sources/autoapi/opendrift/models/eulerdrift/index.rst.txt Sets up fanzy, colorful logging. Use this to configure the verbosity of OpenDrift's output. ```python import logging install_logs(level=logging.DEBUG) ``` -------------------------------- ### Initialize environment and imports Source: https://opendrift.github.io/_downloads/328bb9a2268c424591c715d1fd64b02c/example_wind_measurements.ipynb Sets up necessary libraries and configures Matplotlib parameters for plotting. ```python from datetime import datetime, timedelta, date from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.openoil import OceanDrift from opendrift.readers import reader_timeseries from opendrift.readers.operators import ops import opendrift.models.physics_methods as phy import xarray as xr import trajan as _ import numpy as np import pyproj import matplotlib.pyplot as plt import matplotlib as mpl # Preparation of figsize, dpi, fontsize and font style # Could also be done using mpl style sheet # https://matplotlib.org/stable/users/explain/customizing.html mpl.rcParams['figure.figsize'] = (5, 5) mpl.rcParams['savefig.dpi'] = 300 mpl.rcParams['font.family'] = "sans-serif" mpl.rcParams['font.sans-serif'] = "DejaVu Sans" mpl.rcParams['font.size'] = 22 mpl.rcParams['mathtext.fontset'] = "dejavusans" ``` -------------------------------- ### Install Trajan using Conda Source: https://opendrift.github.io/trajan/_sources/index.rst.txt Recommended installation method for users using Conda. Installs the package from the conda-forge channel. ```console $ conda install -c conda-forge trajan ``` -------------------------------- ### opendrift.readers.basereader.consts.vector_pairs_xy Example Source: https://opendrift.github.io/autoapi/opendrift/readers/basereader/consts/index.html An example showing the structure and content of the `vector_pairs_xy` constant. ```APIDOC ## opendrift.readers.basereader.consts.vector_pairs_xy ### Description This constant defines pairs of x and y components for vector quantities, along with their magnitudes and directions. ### Value Example ```json [ ["x_wind", "y_wind", "wind_speed", "wind_to_direction", "wind_from_direction"], ... ] ``` ``` -------------------------------- ### Initialize Simulation with Regular Grid Source: https://opendrift.github.io/_modules/opendrift/models/eulerdrift/simulation.html Creates a new simulation instance with a `RegularGrid`. This is the primary way to set up a simulation environment. ```python import logging logger = logging.getLogger(__name__) from .grid import RegularGrid from . import srs from .interp import vec_nearest from abc import abstractmethod import numpy as np from datetime import timedelta, datetime class Simulation: r""" The simulation. It contains the problem to be simulated, means to read necessary input variables, and the physics for modeling the convection of the initial conditions. Convection: Convection consists of advection and diffusion. Diffusion is given by: .. math:: \frac{\partial U}{\partial t} = D \left( \frac{\partial^2 U}{\partial x^2} + \frac{\partial^2 U}{\partial y^2} \right) The convection equation is (`wiki `_): .. math:: \frac{\partial c}{\partial t} = ... with the assumptions that: * the diffusion constant `D` is constant for the field, * and that the flow `u` is incompressible (i.e. has *no divergence*). the equation simplifies to: .. math:: \frac{\partial c}{\partial t} = D \nabla^2 c - \mathbf{v} \cdot \nabla T where :math:`\nabla^2 = \triangle` is the Laplacian. """ """The model grid.""" grid = None """Reference time `datetime.Datetime`""" t0 = None """Current time offset after `t0`""" t = 0. """ Diffusivity (:math:`m^2/s`). E.g. between 0.01 and 0.1 for oil on the surface of the ocean (`Matsuzakia et. al., 2017 `_). Decreasing diffusivity places stricter stability criteria on time step. """ D = 0.1 """Porosity, rate of liquid volume to total volume (fraction of flux)""" rho = 1. """List of readers""" readers = None def __init__(self, grid): self.grid = grid self.readers = [] self.t0 = datetime.now() @classmethod def new(cls, lon0 = 10., lat0 = 65., res = 10., shape=(100, 100)): """ New simulation on a :class:`.grid.RegularGrid`. Args: lon0: lower-left corner longitude lat0: lower-left corner latitude res: resolution (dx and dy) shape: shape (size) of grid """ s = cls(grid=RegularGrid.new(lon0, lat0, res, shape)) logger.info("New %s with Regular Grid" % (cls.__name__)) return s ``` -------------------------------- ### Install OpenDrift via Mamba Source: https://opendrift.github.io/_sources/install.rst.txt Installs OpenDrift into a new Python 3 environment. ```bash $ mamba create -n opendrift python=3 opendrift $ conda activate opendrift ``` -------------------------------- ### Initialize and Run OceanDrift with SCHISM Reader Source: https://opendrift.github.io/_sources/gallery/example_schism_native.rst.txt Demonstrates setting up the OceanDrift model, adding a SCHISM native reader with a custom projection, and seeding particles for simulation. ```Python import numpy as np from datetime import timedelta, datetime from opendrift.readers import reader_schism_native from opendrift.readers import reader_global_landmask from opendrift.models.oceandrift import OceanDrift o = OceanDrift(loglevel=20) # Set loglevel to 0 for debug information try: # NZTM proj4 string found at https://spatialreference.org/ref/epsg/nzgd2000-new-zealand-transverse-mercator-2000/ proj4str_nztm = '+proj=tmerc +lat_0=0 +lon_0=173 +k=0.9996 +x_0=1600000 +y_0=10000000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' schism_native = reader_schism_native.Reader( filename = 'https://thredds.met.no/thredds/dodsC/metusers/knutfd/thredds/netcdf_unstructured_samples/schism_marl20080101_00z_3D.nc', proj4 = proj4str_nztm, use_3d = True) except: print('Thredds server not available, cannot run example') schism_native = None if schism_native is not None: o.add_reader([schism_native]) # Seed elements at defined positions, depth and time o.seed_elements(lon=174.046669, lat=-40.928116, radius=20, number=100, z=np.linspace(0,-10, 100), time=schism_native.start_time) o.seed_elements(lon= 173.8839, lat=-40.9160, radius=20, number=100, z=np.linspace(0,-10, 100), time=schism_native.start_time) o.seed_elements(lon=174.2940, lat=-41.0888, radius=20, number=100, z=np.linspace(0,-10, 100), time=schism_native.start_time) #%% # Running model o.run(time_step=900, ``` -------------------------------- ### Example Buoy List Source: https://opendrift.github.io/trajan/gallery/example_indepth_omb_use.html An example representation of the list of buoys that might be present in the dataset. ```python list_buoys = [np.str_('drifter_1'), np.str_('drifter_2'), np.str_('drifter_3')] ``` -------------------------------- ### POST /run Source: https://opendrift.github.io/_modules/opendrift/models/basemodel.html Starts the trajectory simulation loop after initial configuration. ```APIDOC ## POST /run ### Description Starts a trajectory simulation, performing the main loop to obtain environment data and update particle properties until completion conditions are met. ### Method POST ### Endpoint /run ### Parameters #### Request Body - **time_step** (float) - Optional - Time step for the simulation. - **steps** (int) - Optional - Number of steps to run. - **time_step_output** (float) - Optional - Output interval. - **duration** (float) - Optional - Total duration of the simulation. - **end_time** (datetime) - Optional - Specific end time for the simulation. - **outfile** (string) - Optional - Path to the output file. - **export_variables** (list) - Optional - List of variables to export. - **export_buffer_length** (int) - Optional - Buffer length for exports. - **stop_on_error** (boolean) - Optional - Whether to stop on error. ``` -------------------------------- ### Import Required Libraries Source: https://opendrift.github.io/trajan/_downloads/475e861854270bc30e5e26e6c561a88a/example_drifter_csv.ipynb Initial setup for data manipulation and visualization. ```python import pandas as pd import trajan as ta import matplotlib.pyplot as plt ``` -------------------------------- ### Initialize Sea Lice Model Run Source: https://opendrift.github.io/_modules/opendrift/models/sealice.html The prepare_run method initializes model variables by retrieving configuration values and setting up initial population dynamics. ```python [docs] def prepare_run(self): logger.info("preparing the run...") ### need to find a better way of initialising the variables... self.prefix="lice:" self.vertical_migration_speed=self.get_config(self.prefix+'vertical_migration_speed') \ *self.time_step.total_seconds() self.sensing_distance=2*self.vertical_migration_speed self.tau= np.pi+2*np.deg2rad(self.get_config(self.prefix+'twilight')) #width of solar irridation distribution self.nu=self.get_config(self.prefix+'nu') self.sinking_velocity=self.get_config(self.prefix+'sinking_velocity') \ *self.time_step.total_seconds() self.freezing_salinity=self.get_config(self.prefix+'freezing_salinity') self.avoided_salinity=self.get_config(self.prefix+'avoided_salinity') self.k_water=self.get_config(self.prefix+'k_water') self.Nauplii_light_trigger=self.get_config(self.prefix+'Nauplii_light_trigger') self.Copepodid_light_trigger=self.get_config(self.prefix+'Copepodid_light_trigger') self.new_born() self.population() self.ref_date = datetime(1,1,1,0,0) super(SeaLice, self).prepare_run() ``` -------------------------------- ### Z Variable Example Source: https://opendrift.github.io/gallery/example_entrainment_rate_oil_types.html Example numpy array for 'z', representing the vertical position of trajectories in meters. ```python array([[ 0. , -3.478036 , -25.606453 , ..., -28.828886 , -4.016286 , -10.813123 ], [ 0. , -3.5911233 , -0.3178709 , ..., -10.856451 , -32.934574 , -8.29962 ], [ 0. , -20.060175 , -19.434288 , ..., -3.3366625 , -16.211443 , -0.17564589], ..., [ 0. , -6.370093 , -11.591485 , ..., -7.2642117 , -10.766642 , -1.8030005 ], [ 0. , -2.8007238 , -17.953928 , ..., 0. , -4.529121 , -16.282986 ], [ 0. , -5.265363 , -20.021646 , ..., -21.785057 , -15.9200115 , -3.97356 ]], shape=(1000, 13), dtype=float32) ``` -------------------------------- ### Initialize OpenOil simulation parameters Source: https://opendrift.github.io/_downloads/743ab0cf4d1677920b0ee8cfc13df382/example_oil_thickness.ipynb Sets up the initial constants and imports required for the OpenOil simulation. ```python from datetime import datetime, timedelta import matplotlib.pyplot as plt import numpy as np from opendrift.models.openoil import OpenOil number = 10000 timestep = timedelta(minutes=10) timestep_output = timedelta(minutes=60) duration = timedelta(hours=20) mass_oil = 2000 # mass oil per particle oil_type = 'GENERIC DIESEL' #oil_type = 'GENERIC BUNKER C' ``` -------------------------------- ### Age Seconds Variable Example Source: https://opendrift.github.io/gallery/example_entrainment_rate_oil_types.html Example numpy array for 'age_seconds', representing the age of trajectories in seconds. ```python array([[ 0., 3600., 7200., ..., 36000., 39600., 43200.], [ 0., 3600., 7200., ..., 36000., 39600., 43200.], [ 0., 3600., 7200., ..., 36000., 39600., 43200.], ..., [ 0., 3600., 7200., ..., 36000., 39600., 43200.], [ 0., 3600., 7200., ..., 36000., 39600., 43200.], [ 0., 3600., 7200., ..., 36000., 39600., 43200.]]], shape=(1000, 13), dtype=float32) ``` -------------------------------- ### Status Variable Example Source: https://opendrift.github.io/gallery/example_entrainment_rate_oil_types.html Example numpy array for the 'status' variable, indicating the active state of trajectories. ```python array([[0., 0., 0., ..., 0., 0., 0.], [0., 0., 0., ..., 0., 0., 0.], [0., 0., 0., ..., 0., 0., 0.], ..., [0., 0., 0., ..., 0., 0., 0.], [0., 0., 0., ..., 0., 0., 0.], [0., 0., 0., ..., 0., 0., 0.]], shape=(1000, 13), dtype=float32) ``` -------------------------------- ### POST /simulation/new Source: https://opendrift.github.io/_modules/opendrift/models/eulerdrift/simulation.html Initializes a new simulation instance on a RegularGrid. ```APIDOC ## POST /simulation/new ### Description Creates a new simulation instance configured with a RegularGrid based on provided geographic coordinates and resolution. ### Parameters #### Query Parameters - **lon0** (float) - Required - Lower-left corner longitude - **lat0** (float) - Required - Lower-left corner latitude - **res** (float) - Required - Resolution (dx and dy) - **shape** (tuple) - Required - Shape (size) of the grid ### Response #### Success Response (200) - **simulation** (object) - The initialized simulation instance ``` -------------------------------- ### Modify existing installation to editable mode Source: https://opendrift.github.io/_sources/install.rst.txt Converts a standard installation to an editable one for source code development. ```bash $ mamba remove --force opendrift ``` ```bash $ pip install --no-deps -e . ``` -------------------------------- ### Initialize OceanDrift and Readers Source: https://opendrift.github.io/_sources/gallery/example_grid_time.rst.txt Sets up the simulation environment and loads the necessary NetCDF data and landmask reader. ```Python from datetime import timedelta import numpy as np from opendrift import test_data_folder as tdf from opendrift.readers import reader_global_landmask from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.oceandrift import OceanDrift # Seeding at a grid at regular interval o = OceanDrift(loglevel=20) # Set loglevel to 0 for debug information reader_norkyst = reader_netCDF_CF_generic.Reader(tdf + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') ``` ```none 08:31:03 INFO opendrift:568: OpenDriftSimulation initialised (version 1.14.9 / v1.14.9-9-gcde0dcf) 08:31:03 INFO opendrift.readers:64: Opening file with xr.open_dataset 08:31:03 INFO opendrift.readers.reader_netCDF_CF_generic:340: Detected dimensions: {'x': 'X', 'y': 'Y', 'z': 'depth', 'time': 'time'} ``` -------------------------------- ### Initialize OceanDrift Model Source: https://opendrift.github.io/_downloads/032bc03d5e69e556134ea47d9f6caed7/example_double_gyre_LCS.ipynb Sets up the OceanDrift environment and configures the land binary mask. ```python from datetime import datetime, timedelta import matplotlib.pyplot as plt from opendrift.readers import reader_double_gyre from opendrift.models.oceandrift import OceanDrift o = OceanDrift(loglevel=20) # Set loglevel to 0 for debug information o.set_config('environment:fallback:land_binary_mask', 0) ``` -------------------------------- ### Latitude Variable Example Source: https://opendrift.github.io/gallery/example_entrainment_rate_oil_types.html Example numpy array for 'lat', representing the latitude coordinates of trajectories in degrees north. ```python array([[60.0005 , 60.002075, 60.002937, ..., 60.002808, 60.002804, 60.003265], [60.0008 , 60.000973, 60.000946, ..., 60.00001 , 59.998016, 59.999126], [59.999622, 59.999508, 59.997215, ..., 59.998936, 59.998573, 59.998222], ..., [60.00014 , 59.9992 , 59.999397, ..., 59.9981 , 59.997295, 59.997482], [59.998974, 59.999462, 59.999477, ..., 59.996986, 59.99567 , 59.99584 ], [59.998825, 59.9987 , 59.99904 , ..., 60.000134, 59.99921 , 59.998894]], shape=(1000, 13), dtype=float32) ``` -------------------------------- ### Longitude Variable Example Source: https://opendrift.github.io/gallery/example_entrainment_rate_oil_types.html Example numpy array for 'lon', representing the longitude coordinates of trajectories in degrees east. ```python array([[4.0031614, 4.0010514, 3.9868023, ..., 3.8897908, 3.8765304, 3.8665862], [4.000717 , 3.9920855, 3.9843001, ..., 3.9423246, 3.9285328, 3.9190435], [4.001754 , 3.9898474, 3.9770355, ..., 3.9119923, 3.910552 , 3.909527 ], ..., [4.000169 , 3.9860523, 3.9695342, ..., 3.880206 , 3.8645267, 3.8530736], [3.9979434, 3.9901185, 3.9843402, ..., 3.9321027, 3.948563 , 3.93515 ], [3.9993582, 3.9876788, 3.9727552, ..., 3.8718767, 3.8583548, 3.848155 ]], shape=(1000, 13), dtype=float32) ``` -------------------------------- ### Initialize PelagicEggDrift model Source: https://opendrift.github.io/gallery/example_codegg.html Sets up the simulation environment for pelagic egg drift. Requires the opendrift library and specific model imports. ```python from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.pelagicegg import PelagicEggDrift from datetime import datetime, timedelta o = PelagicEggDrift(loglevel=20) # Set loglevel to 0 for debug information ``` -------------------------------- ### Moving Variable Example Source: https://opendrift.github.io/gallery/example_entrainment_rate_oil_types.html Example numpy array for the 'moving' variable, indicating whether trajectories are actively moving. ```python array([[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.], ..., [1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], shape=(1000, 13), dtype=float32) ``` -------------------------------- ### Prepare Run Initialization Source: https://opendrift.github.io/_modules/opendrift/models/oceandrift.html Initializes the run process by calling the superclass's prepare_run method. This is a standard setup step for the simulation. ```python def prepare_run(self): super(OceanDrift, self).prepare_run() ``` -------------------------------- ### Log Error for Invalid Transfer Setup Source: https://opendrift.github.io/_modules/opendrift/models/chemicaldrift.html Logs an error message if an invalid or unrecognized transfer setup configuration is provided. ```python logger.error('No valid transfer_setup {}'.format(self.get_config('chemical:transfer_setup'))) ``` -------------------------------- ### Initialize Reader with different data sources Source: https://opendrift.github.io/_modules/opendrift/readers/reader_netCDF_CF_generic.html Demonstrates how to instantiate the Reader class using a single file, a file pattern, an OPeNDAP URL, or an xarray Dataset. ```python from opendrift.readers.reader_netCDF_CF_generic import Reader r = Reader("arome_subset_16Nov2015.nc") ``` ```python from opendrift.readers.reader_netCDF_CF_generic import Reader r = Reader("*.nc") ``` ```python from opendrift.readers.reader_netCDF_CF_generic import Reader r = Reader('https://thredds.met.no/thredds/dodsC/mepslatest/meps_lagged_6_h_latest_2_5km_latest.nc') ``` ```python from opendrift.readers.reader_netCDF_CF_generic import Reader r = Reader(ds, zarr_storage_options) ``` -------------------------------- ### Shift reader start time Source: https://opendrift.github.io/_modules/opendrift/readers/basereader.html Adjusts the temporal coverage of a reader by shifting the start time and updating the associated time list. ```python def shift_start_time(self, start_time): """Shift the time coverage of reader to match given start_time""" if self.start_time is None: logger.warning('Reader has no time coverage, cannot shift times') return shift_time = self.start_time - start_time self.start_time = start_time self.end_time = self.end_time - shift_time self.times = [t - shift_time for t in self.times] ``` -------------------------------- ### Initialize Euler Simulation Source: https://opendrift.github.io/_downloads/3ed80f5391ce56914ddb1ac1bcc4e196/example_eulerdrift_gauss_blob.ipynb Sets up the simulation environment and adds a constant reader to the grid. ```python import matplotlib.pyplot as plt from opendrift.models import eulerdrift eulerdrift.install_logs() #remove s = eulerdrift.ExplSimulation.new(shape = (200, 200)) s.readers.append( eulerdrift.readers.ConstantReader.new_xy(5, 5)) ``` -------------------------------- ### Initialize NorKyst Reader and Configuration Source: https://opendrift.github.io/gallery/example_grid.html Sets up the NorKyst reader and configures simulation parameters like vertical mixing. ```python reader_norkyst = reader_netCDF_CF_generic.Reader(tdf + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') o.add_reader(reader_norkyst) #o.set_config('environment:fallback:land_binary_mask', 0) o.set_config('drift:vertical_mixing', False) ``` -------------------------------- ### Modify Element Properties Example Source: https://opendrift.github.io/_sources/writing_a_new_model.rst.txt Example demonstrating direct modification of element properties. Here, element length is set to half the seawater temperature. ```python self.elements.length = self.environment.sea_water_temperature / 2 ``` -------------------------------- ### Initialize Species for Custom Transfer Setup Source: https://opendrift.github.io/_modules/opendrift/models/chemicaldrift.html Handles the 'custom' transfer setup by doing nothing, implying that species must be set manually by the user. ```python # Do nothing, species must be set manually pass ``` -------------------------------- ### Initialize OceanDrift and Run Simulation Source: https://opendrift.github.io/_downloads/7f4b8d6252a4db6f69a9ca62023651e2/example_convolve_input.ipynb Sets up the OceanDrift model with a NorKyst reader and runs the initial simulation. ```python from datetime import datetime, timedelta import matplotlib.pyplot as plt from opendrift import test_data_folder as tdf from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.oceandrift import OceanDrift lon = 4.9; lat = 60.0 o = OceanDrift(loglevel=20) reader_norkyst = reader_netCDF_CF_generic.Reader(tdf + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') time = reader_norkyst.start_time o.add_reader([reader_norkyst]) o.seed_elements(lon, lat, radius=1000, number=1000, time=time) o.run(steps=20) ``` -------------------------------- ### Initialize Species for 137Cs_rev Transfer Setup Source: https://opendrift.github.io/_modules/opendrift/models/chemicaldrift.html Initializes chemical species configurations for the '137Cs_rev' transfer setup, enabling LMM and particle/sediment reversible states. ```python self.set_config('chemical:species:LMM',True) self.set_config('chemical:species:Particle_reversible', True) self.set_config('chemical:species:Sediment_reversible', True) ``` -------------------------------- ### Configure and Run OpenDrift Simulation Source: https://opendrift.github.io/_sources/gallery/example_coastline_options.rst.txt Sets up the reader, configures coastline actions, seeds elements, and executes the simulation. ```python o.add_reader([reader_osc]) o.set_config('environment:fallback:y_sea_water_velocity', .2) o.set_config('general:coastline_action', 'none') o.seed_elements(lon=12.2, lat=67.7, radius=5000, number=number, time=reader_osc.zero_time) o.run(duration=duration, time_step=time_step) print(f'Calculation time: {o.timing["total time"]}') o.animation() ```