Particles and particle sets#

parcels.particle module#

class parcels.particle.JITParticle(*args, **kwargs)[source]#

Bases: ScipyParticle

Particle class for JIT-based (Just-In-Time) Particle objects.

Parameters
  • lon (float) – Initial longitude of particle

  • lat (float) – Initial latitude of particle

  • fieldset (parcels.fieldset.FieldSet) – mod:parcels.fieldset.FieldSet object to track this particle on

  • dt – Execution timestep for this particle

  • time – Current time of the particle

Notes

Additional Variables can be added via the :Class Variable: objects

Users should use JITParticles for faster advection computation.

Attributes
depth
depth_nextloop
dt
id
lat
lat_nextloop
lon
lon_nextloop
obs_written
state
time
time_nextloop

Methods

add_variable(var, *args, **kwargs)

Add a new variable to the Particle class

add_variables(variables)

Add multiple new variables to the Particle class

getPType

setLastID

set_lonlatdepth_dtype

parcels.particle.ScipyInteractionParticle[source]#

alias of NewParticle

class parcels.particle.ScipyParticle(lon, lat, pid, fieldset=None, ngrids=None, depth=0.0, time=0.0, cptr=None)[source]#

Bases: object

Class encapsulating the basic attributes of a particle, to be executed in SciPy mode.

Parameters
  • lon (float) – Initial longitude of particle

  • lat (float) – Initial latitude of particle

  • depth (float) – Initial depth of particle

  • fieldset (parcels.fieldset.FieldSet) – mod:parcels.fieldset.FieldSet object to track this particle on

  • time (float) – Current time of the particle

Notes

Additional Variables can be added via the :Class Variable: objects

Attributes
depth
depth_nextloop
dt
id
lat
lat_nextloop
lon
lon_nextloop
obs_written
state
time
time_nextloop

Methods

add_variable(var, *args, **kwargs)

Add a new variable to the Particle class

add_variables(variables)

Add multiple new variables to the Particle class

getPType

setLastID

set_lonlatdepth_dtype

classmethod add_variable(var, *args, **kwargs)[source]#

Add a new variable to the Particle class

Parameters

var (str, Variable or list of Variables) – Variable object to be added. Can be the name of the Variable, a Variable object, or a list of Variable objects

classmethod add_variables(variables)[source]#

Add multiple new variables to the Particle class

Parameters

variables (list of Variable) – Variable objects to be added. Has to be a list of Variable objects

class parcels.particle.Variable(name, dtype=<class 'numpy.float32'>, initial=0, to_write=True)[source]#

Bases: object

Descriptor class that delegates data access to particle data.

Parameters
  • name (str) – Variable name as used within kernels

  • dtype – Data type (numpy.dtype) of the variable

  • initial – Initial value of the variable. Note that this can also be a Field object, which will then be sampled at the location of the particle

  • to_write (bool, 'once', optional) – Boolean or ‘once’. Controls whether Variable is written to NetCDF file. If to_write = ‘once’, the variable will be written as a time-independent 1D array

Methods

is64bit()

Check whether variable is 64-bit.

is64bit()[source]#

Check whether variable is 64-bit.

parcels.particleset module#

class parcels.particleset.ParticleSet(fieldset=None, pclass=<class 'parcels.particle.JITParticle'>, lon=None, lat=None, depth=None, time=None, repeatdt=None, lonlatdepth_dtype=None, pid_orig=None, interaction_distance=None, periodic_domain_zonal=None, **kwargs)[source]#

Bases: ABC

Class for storing particle and executing kernel over them.

Please note that this currently only supports fixed size particle sets, meaning that the particle set only holds the particles defined on construction. Individual particles can neither be added nor deleted individually, and individual particles can only be deleted as a set procedurally (i.e. by ‘particle.delete()’-call during kernel execution).

Parameters
  • fieldset – mod:parcels.fieldset.FieldSet object from which to sample velocity. While fieldset=None is supported, this will throw a warning as it breaks most Parcels functionality

  • pclass (parcels.particle.JITParticle or parcels.particle.ScipyParticle) – Optional parcels.particle.JITParticle or parcels.particle.ScipyParticle object that defines custom particle

  • lon – List of initial longitude values for particles

  • lat – List of initial latitude values for particles

  • depth – Optional list of initial depth values for particles. Default is 0m

  • time – Optional list of initial time values for particles. Default is fieldset.U.grid.time[0]

  • repeatdt (datetime.timedelta or float, optional) – Optional interval on which to repeat the release of the ParticleSet. Either timedelta object, or float in seconds.

  • lonlatdepth_dtype – Floating precision for lon, lat, depth particle coordinates. It is either np.float32 or np.float64. Default is np.float32 if fieldset.U.interp_method is ‘linear’ and np.float64 if the interpolation method is ‘cgrid_velocity’

  • pid_orig – Optional list of (offsets for) the particle IDs

  • partition_function – Function to use for partitioning particles over processors. Default is to use kMeans

  • periodic_domain_zonal

    Zonal domain size, used to apply zonally periodic boundaries for particle-particle interaction. If None, no zonally periodic boundaries are applied

    Other Variables can be initialised using further arguments (e.g. v=… for a Variable named ‘v’)

Attributes
ctypes_struct
error_particles

Get an iterator over all particles that are in an error state.

num_error_particles

Get the number of particles that are in an error state.

size

Methods

Kernel(pyfunc[, c_include, delete_cfiles])

Wrapper method to convert a pyfunc into a parcels.kernel.Kernel object.

ParticleFile(*args, **kwargs)

Wrapper method to initialise a parcels.particlefile.ParticleFile object from the ParticleSet.

add(particles)

Add particles to the ParticleSet.

data_indices(variable_name, compare_values)

Get the indices of all particles where the value of variable_name equals (one of) compare_values.

execute([pyfunc, pyfunc_inter, endtime, ...])

Execute a given kernel function over the particle set for multiple timesteps.

from_field(fieldset, pclass, start_field, size)

Initialise the ParticleSet randomly drawn according to distribution from a field.

from_line(fieldset, pclass, start, finish, size)

Create a particleset in the shape of a line (according to a cartesian grid).

from_list(fieldset, pclass, lon, lat[, ...])

Initialise the ParticleSet from lists of lon and lat.

from_particlefile(fieldset, pclass, filename)

Initialise the ParticleSet from a zarr ParticleFile.

monte_carlo_sample(start_field, size[, mode])

Converts a starting field into a monte-carlo sample of lons and lats.

populate_indices()

Pre-populate guesses of particle xi/yi indices using a kdtree.

remove_booleanvector(indices)

Method to remove particles from the ParticleSet, based on an array of booleans.

remove_indices(indices)

Method to remove particles from the ParticleSet, based on their indices.

set_variable_write_status(var, write_status)

Method to set the write status of a Variable.

InteractionKernel

active_particles_mask

compute_neighbor_tree

cstruct

iterator

lonlatdepth_dtype_from_field_interp_method

neighbors_by_coor

neighbors_by_index

Kernel(pyfunc, c_include='', delete_cfiles=True)[source]#

Wrapper method to convert a pyfunc into a parcels.kernel.Kernel object.

Conversion is based on fieldset and ptype of the ParticleSet.

Parameters
  • pyfunc (function or list of functions) – Python function to convert into kernel. If a list of functions is provided, the functions will be converted to kernels and combined into a single kernel.

  • delete_cfiles (bool) – Whether to delete the C-files after compilation in JIT mode (default is True)

  • pyfunc

  • c_include – (Default value = “”)

ParticleFile(*args, **kwargs)[source]#

Wrapper method to initialise a parcels.particlefile.ParticleFile object from the ParticleSet.

add(particles)[source]#

Add particles to the ParticleSet. Note that this is an incremental add, the particles will be added to the ParticleSet on which this function is called.

Parameters

particles – Another ParticleSet containing particles to add to this one.

Returns

The current ParticleSet

Return type

type

data_indices(variable_name, compare_values, invert=False)[source]#

Get the indices of all particles where the value of variable_name equals (one of) compare_values.

Parameters
  • variable_name (str) – Name of the variable to check.

  • compare_values – Value or list of values to compare to.

  • invert – Whether to invert the selection. I.e., when True, return all indices that do not equal (one of) compare_values. (Default value = False)

Returns

Numpy array of indices that satisfy the test.

Return type

np.ndarray

property error_particles[source]#

Get an iterator over all particles that are in an error state.

Returns

ParticleDataIterator over error particles.

Return type

iterator

execute(pyfunc=<function AdvectionRK4>, pyfunc_inter=None, endtime=None, runtime=None, dt=1.0, output_file=None, verbose_progress=True, postIterationCallbacks=None, callbackdt=None)[source]#

Execute a given kernel function over the particle set for multiple timesteps.

Optionally also provide sub-timestepping for particle output.

Parameters
  • pyfunc – Kernel function to execute. This can be the name of a defined Python function or a parcels.kernel.Kernel object. Kernels can be concatenated using the + operator (Default value = AdvectionRK4)

  • endtime – End time for the timestepping loop. It is either a datetime object or a positive double. (Default value = None)

  • runtime – Length of the timestepping loop. Use instead of endtime. It is either a timedelta object or a positive double. (Default value = None)

  • dt – Timestep interval to be passed to the kernel. It is either a timedelta object or a double. Use a negative value for a backward-in-time simulation. (Default value = 1.)

  • output_file – mod:parcels.particlefile.ParticleFile object for particle output (Default value = None)

  • verbose_progress (bool) – Boolean for providing a progress bar for the kernel execution loop. (Default value = True)

  • postIterationCallbacks – Optional) Array of functions that are to be called after each iteration (post-process, non-Kernel) (Default value = None)

  • callbackdt – Optional, in conjecture with ‘postIterationCallbacks’, timestep interval to (latest) interrupt the running kernel and invoke post-iteration callbacks from ‘postIterationCallbacks’ (Default value = None)

  • pyfunc_inter – (Default value = None)

classmethod from_field(fieldset, pclass, start_field, size, mode='monte_carlo', depth=None, time=None, repeatdt=None, lonlatdepth_dtype=None)[source]#

Initialise the ParticleSet randomly drawn according to distribution from a field.

Parameters
  • fieldset (parcels.fieldset.FieldSet) – mod:parcels.fieldset.FieldSet object from which to sample velocity

  • pclass (parcels.particle.JITParticle or parcels.particle.ScipyParticle) – Particle class. May be a particle class as defined in parcels, or a subclass defining a custom particle.

  • start_field (parcels.field.Field) – Field for initialising particles stochastically (horizontally) according to the presented density field.

  • size – Initial size of particle set

  • mode – Type of random sampling. Currently only ‘monte_carlo’ is implemented (Default value = ‘monte_carlo’)

  • depth – Optional list of initial depth values for particles. Default is 0m

  • time – Optional start time value for particles. Default is fieldset.U.time[0]

  • repeatdt – Optional interval (in seconds) on which to repeat the release of the ParticleSet (Default value = None)

  • lonlatdepth_dtype – Floating precision for lon, lat, depth particle coordinates. It is either np.float32 or np.float64. Default is np.float32 if fieldset.U.interp_method is ‘linear’ and np.float64 if the interpolation method is ‘cgrid_velocity’

classmethod from_line(fieldset, pclass, start, finish, size, depth=None, time=None, repeatdt=None, lonlatdepth_dtype=None, **kwargs)[source]#

Create a particleset in the shape of a line (according to a cartesian grid).

Initialise the ParticleSet from start/finish coordinates with equidistant spacing Note that this method uses simple numpy.linspace calls and does not take into account great circles, so may not be a exact on a globe

Parameters
  • fieldset – mod:parcels.fieldset.FieldSet object from which to sample velocity

  • pclass (parcels.particle.JITParticle or parcels.particle.ScipyParticle) – Particle class. May be a particle class as defined in parcels, or a subclass defining a custom particle.

  • start – Start point (longitude, latitude) for initialisation of particles on a straight line.

  • finish – End point (longitude, latitude) for initialisation of particles on a straight line.

  • size – Initial size of particle set

  • depth – Optional list of initial depth values for particles. Default is 0m

  • time – Optional start time value for particles. Default is fieldset.U.time[0]

  • repeatdt – Optional interval (in seconds) on which to repeat the release of the ParticleSet (Default value = None)

  • lonlatdepth_dtype – Floating precision for lon, lat, depth particle coordinates. It is either np.float32 or np.float64. Default is np.float32 if fieldset.U.interp_method is ‘linear’ and np.float64 if the interpolation method is ‘cgrid_velocity’

classmethod from_list(fieldset, pclass, lon, lat, depth=None, time=None, repeatdt=None, lonlatdepth_dtype=None, **kwargs)[source]#

Initialise the ParticleSet from lists of lon and lat.

Parameters
  • fieldset – mod:parcels.fieldset.FieldSet object from which to sample velocity

  • pclass (parcels.particle.JITParticle or parcels.particle.ScipyParticle) – Particle class. May be a particle class as defined in parcels, or a subclass defining a custom particle.

  • lon – List of initial longitude values for particles

  • lat – List of initial latitude values for particles

  • depth – Optional list of initial depth values for particles. Default is 0m

  • time – Optional list of start time values for particles. Default is fieldset.U.time[0]

  • repeatdt – Optional interval (in seconds) on which to repeat the release of the ParticleSet (Default value = None)

  • lonlatdepth_dtype – Floating precision for lon, lat, depth particle coordinates. It is either np.float32 or np.float64. Default is np.float32 if fieldset.U.interp_method is ‘linear’ and np.float64 if the interpolation method is ‘cgrid_velocity’ Other Variables can be initialised using further arguments (e.g. v=… for a Variable named ‘v’)

  • **kwargs – Keyword arguments passed to the particleset constructor.

classmethod from_particlefile(fieldset, pclass, filename, restart=True, restarttime=None, repeatdt=None, lonlatdepth_dtype=None, **kwargs)[source]#

Initialise the ParticleSet from a zarr ParticleFile. This creates a new ParticleSet based on locations of all particles written in a zarr ParticleFile at a certain time. Particle IDs are preserved if restart=True

Parameters
  • fieldset (parcels.fieldset.FieldSet) – mod:parcels.fieldset.FieldSet object from which to sample velocity

  • pclass (parcels.particle.JITParticle or parcels.particle.ScipyParticle) – Particle class. May be a particle class as defined in parcels, or a subclass defining a custom particle.

  • filename (str) – Name of the particlefile from which to read initial conditions

  • restart (bool) – BSignal if pset is used for a restart (default is True). In that case, Particle IDs are preserved.

  • restarttime – time at which the Particles will be restarted. Default is the last time written. Alternatively, restarttime could be a time value (including np.datetime64) or a callable function such as np.nanmin. The last is useful when running with dt < 0.

  • repeatdt (datetime.timedelta or float, optional) – Optional interval on which to repeat the release of the ParticleSet. Either timedelta object, or float in seconds.

  • lonlatdepth_dtype – Floating precision for lon, lat, depth particle coordinates. It is either np.float32 or np.float64. Default is np.float32 if fieldset.U.interp_method is ‘linear’ and np.float64 if the interpolation method is ‘cgrid_velocity’

  • **kwargs – Keyword arguments passed to the particleset constructor.

classmethod monte_carlo_sample(start_field, size, mode='monte_carlo')[source]#

Converts a starting field into a monte-carlo sample of lons and lats.

Parameters
  • start_field (parcels.field.Field) – mod:parcels.fieldset.Field object for initialising particles stochastically (horizontally) according to the presented density field.

  • size

  • mode – (Default value = ‘monte_carlo’)

Returns

  • list of float – A list of longitude values.

  • list of float – A list of latitude values.

property num_error_particles[source]#

Get the number of particles that are in an error state.

Returns

Number of error particles.

Return type

int

populate_indices()[source]#

Pre-populate guesses of particle xi/yi indices using a kdtree.

This is only intended for curvilinear grids, where the initial index search may be quite expensive.

remove_booleanvector(indices)[source]#

Method to remove particles from the ParticleSet, based on an array of booleans.

remove_indices(indices)[source]#

Method to remove particles from the ParticleSet, based on their indices.

set_variable_write_status(var, write_status)[source]#

Method to set the write status of a Variable.

Parameters
  • var – Name of the variable (string)

  • write_status – Write status of the variable (True, False or ‘once’)