Add your own class#

[This note-book is in oceantracker/tutorials_how_to/]

Here, we will again use the minimal example but this time we add a “user written class”. We try to provide functionally that cover a range of use-cases. However, many scientific applications attempt to illustrate something “new” - i.e. will require a special functionality that we haven’t implemented yet. In those cases, you might want to add this functionality yourself.

We designed OceanTracker in mind and try to make this process easy. In most scenarios you can make use of python “class inheritance” functionality. I.e. you can use one of the already implemented classes e.g. a particle property class and only tweak one ore two methods - typically the “update”-method.

Here we present an example of this. We create new class in a python file in the same directory as your run script. There are other ways to do this that are more robust, but this one is the simplest. The file we will be using here is “my_part_prop.py” and it looks like this

%pycat my_part_prop.py
from oceantracker.particle_properties._base_particle_properties import (
    CustomParticleProperty,
)

# to avoid accidental parameterization error we use these functions
# where we define "valid input" for each configuration variable
from oceantracker.util.parameter_checking import (
    ParamValueChecker as PVC,
    ParameterTimeChecker as PTC,
    ParameterListChecker as PLC,
    ParameterCoordsChecker as PCC,
)

from oceantracker.util.numpy_util import possible_dtypes
from oceantracker.shared_info import (
    shared_info as si,
)  # proces access to all variables , classes and info
from oceantracker.util.numba_util import (
    njitOT,
    njitOTparallel,
    prange,
)  # numba decorators to make code fast


# user written particle properties have to inherit from CustomParticleProperty,
# as only these have their update method called automatically every time step
class TimeAtStatus(CustomParticleProperty):
    """class to calculate the time each particle spends in a given status"""

    # the init method is what is called during the creation of the class instance
    def __init__(self):
        # this calls the parent class method, to maintain its functionality without copying the code
        super().__init__()
        # we add one new default parameter that tells the class which particles to count
        self.add_default_params(
            required_status=PVC(
                "moving",  # default type
                str,  # required variable type for this input parameter
                possible_values=[
                    key for key, item in si.particle_status_flags.items() if item >= 0
                ],
                doc_str="The particle status to count the time spend",
            ),
            description=PVC(
                # optional description and units are added to part. prop. netcdf variables attributes
                "total time particle spends in a given status",  # description
                str,
                units="seconds",
            ),
            # this will define the data type of the new particle property
            dtype=PVC("float64", str, possible_values=possible_dtypes),
        )

    # during the model setup phase, we run this code
    def initial_setup(self):

        # first we execute the "parent" (CustomParticleProperty) "initial_setup" method again
        super().initial_setup()

        # next we select, based on user input, the status set for which we will calculate this particle property
        # this is stored in self.info, where most of the run time properties are stored
        self.info["status_value"] = si.particle_status_flags[
            self.params["required_status"]
        ]

    # this will be used to initialize the particle property for each particle during its creation
    # in our case "0" for zero seconds within the selected status
    def initial_value_at_birth(self, new_part_IDs):
        self.set_values(0.0, new_part_IDs)

    # the update class is what is called during the "actual" model run.
    # I.e. after every time step.
    # Hence, this function will be called the most frequently.
    # To make it fast, we will create a numba function (_add_time)
    # Alternatively, you can use numpy function for the "heavy lifting".
    # Pure python operations tend to be much slower, and might otherwise
    # slow down your simulation (check the timing information in the caseInfo)
    def update(self, n_time_step, time_sec, active):
        # All we wan't to do here is to accumulate time for each particle in required status
        # which are currently "active" (e.g. exist, in contrast of those not yet released or removed)

        # this just contains a dict of all particle properties
        part_prop = si.class_roles.particle_properties

        # add the time (i.e. time step size) that the selected (required status)
        # particles have been in that state
        self._add_time(
            self.info["status_value"],
            si.settings.time_step,
            part_prop["status"].data,
            self.data,  # the data of this particle property holds the accumulating time in the required status
            active,
        )

        pass

    # Numba code cannot use classes such as self, as Numba only understands basic python variable types and numpy arrays
    # the "@njit" decorator - which we slightly tweaked in @njitOTparallel - speeds up the code using numba and uses parallel threads
    @staticmethod
    @njitOTparallel
    def _add_time(required_status, time_step, status, total_time, active):
        # threaded parallel (prange) for-loop over indices of active particles
        for nn in prange(active.size):
            n = active[nn]
            if status[n] == required_status:
                total_time[n] += time_step
            pass

Note that TimeAtStatus inherits from CustomParticleProperty. OceanTracker decides how to update a particle property based on the class it inherits from:

  • CustomParticleProperty: its update method is called automatically at every time step. Use this for your own particle properties.

  • FieldParticleProperty: interpolated from the hindcast fields; used internally for properties read from the reader.

  • ManuallyUpdatedParticleProperty: only updated when other code calls its update method.

If your class inherits from _BaseParticleProperty directly, its update method is never called. The run will still finish without errors, but the property keeps its initial value.

# Notes for debugging if the scripts below fail:
# * These scripts assume that you already installed oceantracker. If you didn't take a look at https://oceantracker.github.io/oceantracker/_build/html/info/installing.html
# * Paths in this directory are relative to the location of the ipython notebook.
#   I.e. On Linux or Mac, running a cell with "!ls" should return a list containing the notebook you are running.

# Checks if the hindcast data is available and downloads them if not
from oceantracker.util.download_data import download_hindcast_data_for_tutorials
download_hindcast_data_for_tutorials()
Hindcast data found locally at ./demo_hindcast
# here we will again use the minimal example (take a look A_minimal_example.ipynb first, if you haven't already)
from oceantracker.main import OceanTracker
import os

ot = OceanTracker()

ot.settings(
    run_output_dir=os.path.join("output", "add_user_written_class"),
    time_step=120.0,  #  2 min time step as seconds
)

ot.add_class(
    "reader",
    input_dir="./demo_hindcast/schsim3D",
    file_mask="demo_hindcast_schisim3D*.nc",
)

ot.add_class(
    "release_groups",
    points=[
        [1595000, 5482600],
        [1599000, 5486200],
    ],
    release_interval=3600,
    pulse_size=10,
)

# here we add "your class"
# you can add it just like any other class
ot.add_class(
    # you describe its type (e.g. particle property)
    "particle_properties",
    # you point it at your class by using its class name (file_name.ClassName)
    class_name="my_part_prop.TimeAtStatus",
    # and you give it a name (just so you know which one is which in case you have multiple version of it)
    # e.g. if you would like to use the TimeAtStatus class to count both the time stranded on the shore, and the time at bottom of the sea
    name="on_bottom_time"
)

case_info_file_name = ot.run()
prelim:             Starting package set up
prelim:             Starting package set up
helper: ----------------------------------------------------------------------------------------------------
helper: Starting OceanTracker helper class,  version 0.5.3.5, dev build, commit 4c28ad42
helper:              Python version: 3.11.15 | packaged by conda-forge | (main, Mar  5 2026, 16:45:40) [GCC 14.3.0]
helper: ----------------------------------------------------------------------------------------------------
helper: OceanTracker version 0.5.3.5, dev build, commit 4c28ad42  starting setup helper "main.py":
helper: Started
helper: Output is in dir "/home/ls/projects/oceantracker_dev/oceantracker/tutorials_how_to/output/add_user_written_class"
                            Hint: see for copies of screen output and user supplied parameters, plus all other output
helper:             Note >>> to help with debugging, parameters as given by user  are in "params_raw_user_.json"
helper: ----------------------------------------------------------------------------------------------------
helper: Numba setup: applied settings, max threads = 32, physical cores = 32
                            Hint:  cache code = False, fastmath= False
helper: ----------------------------------------------------------------------------------------------------
loading oceantracker read files
helper:                     - Built OceanTracker package tree,        0.831 sec
helper:                     - Built OceanTracker sort name map,       0.000 sec
helper:     - Done package set up to setup ClassImporter,     0.831 sec
setup: ----------------------------------------------------------------------------------------------------
setup:  OceanTracker version 0.5.3.5, dev build, commit 4c28ad42
setup:              Starting user param. runner at 2026-10-20T15:48:31.710464
setup: ----------------------------------------------------------------------------------------------------
setup:      - Start  field group manager and readers setup
setup:      - Building hindcast catalog of files in dir and sub-dirs of "./demo_hindcast/schsim3D"
setup:              - Found  1 files
setup:      - Detected reader class_name = "oceantracker.reader.SCHISM_reader.SCHISMreader"
setup:      - Starting grid setup
setup:              - built node to triangles map,    0.588 sec
setup:              - built triangle adjacency matrix,        0.145 sec
setup:              - found boundary triangles,       0.000 sec
setup:              - built domain and island outlines,       0.771 sec
setup:              - calculated triangle areas,      0.000 sec
setup:      - Finished grid setup
setup: --- Hindcast info ----------------------------------------------------------------------------------
setup:              Hydro-model is "3D", type "SCHISMreader"
                            Hint: Files found in dir and sub-dirs of "./demo_hindcast/schsim3D"
setup:                              Geographic coords = "False"
setup:                              Hindcast start: 2017-01-01T00:30:00  end:  2017-01-01T23:30:00
setup:                                      time step = 0 days 1 hrs 0 min 0 sec, number of time steps= 24
setup:                                      grid bounding box = [1589789.000 5479437.000] to [1603398.000 5501640.000]
setup:                                      has:  A_Z profile=True,  bottom stress=False, regrid to sigma=True
setup:                                      vertical grid type = "LSC", using vertical grid  "Sigma"
setup: ----------------------------------------------------------------------------------------------------
setup:      - Built barycentric-transform matrix,     0.212 sec
setup:      - Loading reader fields ['water_depth', 'water_velocity', 'tide']
setup:      - Finished field group manager and readers setup,         3.042 sec
setup: ----------------------------------------------------------------------------------------------------
setup:      - Added 1 release group(s) and found run start and end times,     1.169 sec
setup:      - Starting initial setup of all classes
setup:              - Done initial setup of all classes,      0.001 sec
setup: ----------------------------------------------------------------------------------------------------
setup:      - Starting "add_user_written_class",  duration: 0 days 23 hrs 0 min 0 sec
setup:                      From 2017-01-01T00:30:00 to  2017-01-01T23:30:00
setup:                      Time step 120.0 sec
setup:                              using: A_Z_profile = False, bottom_stress = False
setup: ----------------------------------------------------------------------------------------------------
setup:      -  Reading 24 time steps,  for hindcast time steps 00:23 into ring buffer offsets 000:023 ,  for run "add_user_written_class"
setup:                      -  read  24 time steps in  1.0 sec, from ./demo_hindcast/schsim3D
setup:      - Starting time stepping: 2017-01-01T00:30:00 to 2017-01-01T23:30:00
setup:              duration  0 days 23 hrs 0 min 0 sec, time step=  0 days 0 hrs 2 min 0 sec
S:  - Opened tracks output and done written first time step in: "tracks_compact_000.nc",      0.088 sec
S: 0000: 00% Day +00 00:00 2017-01-01 00:30:00: Rel:20   : Active:20     Move:20     Bottom:0     Strand:0      Dead:0     Out:   0 Buffer: 4%  step time = 6295.8 ms
S: 0030: 04% Day +00 01:00 2017-01-01 01:30:00: Rel:40   : Active:40     Move:40     Bottom:0     Strand:0      Dead:0     Out:   0 Buffer: 8%  step time =  4.2 ms
S: 0060: 09% Day +00 02:00 2017-01-01 02:30:00: Rel:60   : Active:60     Move:60     Bottom:0     Strand:0      Dead:0     Out:   0 Buffer:12%  step time =  8.0 ms
S: 0090: 13% Day +00 03:00 2017-01-01 03:30:00: Rel:70   : Active:70     Move:60     Bottom:0     Strand:10     Dead:0     Out:   0 Buffer:14%  step time =  7.7 ms
S: 0120: 17% Day +00 04:00 2017-01-01 04:30:00: Rel:80   : Active:80     Move:70     Bottom:0     Strand:10     Dead:0     Out:   0 Buffer:16%  step time =  7.4 ms
S: 0150: 22% Day +00 05:00 2017-01-01 05:30:00: Rel:90   : Active:90     Move:79     Bottom:0     Strand:11     Dead:0     Out:   0 Buffer:18%  step time =  6.9 ms
S: 0180: 26% Day +00 06:00 2017-01-01 06:30:00: Rel:100  : Active:100    Move:89     Bottom:0     Strand:11     Dead:0     Out:   0 Buffer:20%  step time = 10.4 ms
S: 0210: 30% Day +00 07:00 2017-01-01 07:30:00: Rel:110  : Active:110    Move:100    Bottom:0     Strand:10     Dead:0     Out:   0 Buffer:22%  step time = 10.3 ms
S: 0240: 35% Day +00 08:00 2017-01-01 08:30:00: Rel:120  : Active:120    Move:110    Bottom:0     Strand:10     Dead:0     Out:   0 Buffer:25%  step time =  7.5 ms
S: 0270: 39% Day +00 09:00 2017-01-01 09:30:00: Rel:140  : Active:140    Move:140    Bottom:0     Strand:0      Dead:0     Out:   0 Buffer:29%  step time =  8.8 ms
S: 0300: 43% Day +00 10:00 2017-01-01 10:30:00: Rel:160  : Active:160    Move:160    Bottom:0     Strand:0      Dead:0     Out:   0 Buffer:33%  step time =  7.8 ms
S: 0330: 48% Day +00 11:00 2017-01-01 11:30:00: Rel:180  : Active:180    Move:180    Bottom:0     Strand:0      Dead:0     Out:   0 Buffer:37%  step time =  7.6 ms
S: 0360: 52% Day +00 12:00 2017-01-01 12:30:00: Rel:200  : Active:200    Move:200    Bottom:0     Strand:0      Dead:0     Out:   0 Buffer:41%  step time = 10.2 ms
S: 0390: 57% Day +00 13:00 2017-01-01 13:30:00: Rel:220  : Active:220    Move:206    Bottom:0     Strand:14     Dead:0     Out:   0 Buffer:45%  step time =  8.6 ms
S: 0420: 61% Day +00 14:00 2017-01-01 14:30:00: Rel:240  : Active:240    Move:219    Bottom:0     Strand:21     Dead:0     Out:   0 Buffer:50%  step time =  7.0 ms
S: 0450: 65% Day +00 15:00 2017-01-01 15:30:00: Rel:250  : Active:250    Move:188    Bottom:0     Strand:62     Dead:0     Out:   0 Buffer:52%  step time =  8.1 ms
S: 0480: 70% Day +00 16:00 2017-01-01 16:30:00: Rel:260  : Active:260    Move:194    Bottom:0     Strand:66     Dead:0     Out:   0 Buffer:54%  step time = 10.3 ms
S: 0510: 74% Day +00 17:00 2017-01-01 17:30:00: Rel:270  : Active:270    Move:196    Bottom:0     Strand:74     Dead:0     Out:   0 Buffer:56%  step time =  8.0 ms
S: 0540: 78% Day +00 18:00 2017-01-01 18:30:00: Rel:280  : Active:280    Move:206    Bottom:0     Strand:74     Dead:0     Out:   0 Buffer:58%  step time =  8.7 ms
S: 0570: 83% Day +00 19:00 2017-01-01 19:30:00: Rel:290  : Active:290    Move:218    Bottom:0     Strand:72     Dead:0     Out:   0 Buffer:60%  step time =  7.9 ms
S: 0600: 87% Day +00 20:00 2017-01-01 20:30:00: Rel:300  : Active:300    Move:232    Bottom:0     Strand:68     Dead:0     Out:   0 Buffer:62%  step time =  6.7 ms
S: 0630: 91% Day +00 21:00 2017-01-01 21:30:00: Rel:320  : Active:320    Move:299    Bottom:0     Strand:21     Dead:0     Out:   0 Buffer:66%  step time =  7.3 ms
S: 0660: 96% Day +00 22:00 2017-01-01 22:30:00: Rel:340  : Active:340    Move:326    Bottom:0     Strand:14     Dead:0     Out:   0 Buffer:70%  step time =  9.3 ms
S: 0690: 100% Day +00 23:00 2017-01-01 23:30:00: Rel:360  : Active:360    Move:360    Bottom:0     Strand:0      Dead:0     Out:   0 Buffer:75%  step time =  6.4 ms
S: --- Closing all classes ----------------------------------------------------------------------------
S: Converting compact track files to rectangular format (to disable set reader param convert=False)
S:          - Finished "tracks_rectangular_000.nc",   0.087 sec
S:          - Conversion complete,    0.087 sec
S: Removing compact track files output after conversion
end: ----------------------------------------------------------------------------------------------------
end: Finished "add_user_written_class"
end:                Timings: total =  21.1 sec
end:                                                Setup                          0.95 s     4.5%
end:                                                Find initial horizontal cell   0.97 s     4.6%
end:                                                Reading hindcast               0.97 s     4.6%
end:                                                Find horizontal cell           1.83 s     8.7%
end:                                                Find vertical cell             1.14 s     5.4%
end:                                                Interpolate fields             1.20 s     5.7%
end:                                                Update custom particle prop.   0.20 s     0.9%
end:                                                Trajectory modifiers           0.00 s     0.0%
end:                                                Update statistics              0.00 s     0.0%
end:                                                Update event loggers           0.00 s     0.0%
end:                                                Velocity modifiers             0.04 s     0.2%
end:                                                RK integration                 0.34 s     1.6%
end:                                                Releasing particles            0.05 s     0.2%
end:                                                Close down                     3.63 s    17.2%
end:                                                resuspension                   0.28 s     1.3%
end:                                                dispersion                     0.38 s     1.8%
end:                                                tracks_writer                  0.07 s     0.3%
end: ----------------------------------------------------------------------------------------------------
end: Finished "add_user_written_class"
end:         started: 2026-10-20 15:48:30.757055, ended: 2026-10-20 15:48:51.874069
end:                        Computational time = 0:00:21.117025
end:                        Max. memory used 11.29 GB
end: --- Issues    (check above,  any errors repeated below) --------------------------------------------
end:          0 errors,    0 strong warnings,   0 warnings,   1 notes
end: Output in "/home/ls/projects/oceantracker_dev/oceantracker/tutorials_how_to/output/add_user_written_class"
end: ----------------------------------------------------------------------------------------------------
end:
# you will find its output here
print(case_info_file_name)
/home/ls/projects/oceantracker_dev/oceantracker/tutorials_how_to/output/add_user_written_class/caseInfo.json

Read and plot output#

To take a quick look we can visualize the the particle properties in an animation. We can pass the particle property (“on_bottom_time”) to the animtion function color_using_data variable. The color will then represent the amount of time that this particle has spend on the bottom.

from oceantracker.read_output.python import load_output_files
from oceantracker.plot_output import plot_tracks
from IPython.display import HTML


tracks = load_output_files.load_track_data(case_info_file_name)
anim = plot_tracks.animate_particles(
    tracks,
    axis_lims=[1591000, 1601500, 5479500, 5491000],
    colour_using_data=tracks["on_bottom_time"],
    back_ground_depth=True,
    show_grid=True,
    show_dry_cells=True,
    interval=50,
)
# HTML(anim.to_html5_video())  # this is slow to build!
Merging rectangular track files
     Reading rectangular track file "tracks_rectangular_000.nc"
animate_particles: color map limits None None
../../_images/H_add_user_written_class_8_1.png