Contributing to pelagos-py#

First off, thanks for taking the time to contribute!

All types of contributions are encouraged and valued. Please make sure to read the relevant section of this document before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved.

Table of Contents#

I Have a Question#

Before you ask a question, it is best to search for existing Issues that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first.

If you then still feel the need to ask a question and need clarification, we recommend the following:

  • Open an Issue.

  • Provide as much context as you can about what you’re running into.

  • Provide project, Python version and details of your Python environment (pip/conda and versions of dependencies).

We will then take care of the issue as soon as possible.

Development Workflow#

To maintain code quality and stability, we use a workflow based on pull requests to main. All new features and bug fixes should be submitted to the main branch.

  1. Fork the repository: Create your own copy of the project on GitHub.

  2. Clone your fork: Download the code to your local machine.

  3. Create a branch: Work on a new branch specifically for your changes.

  4. Submit a Pull Request: Direct your Pull Request (PR) from your fork to the main branch of the original repository.

See Common Commands below for the exact git commands.

Reporting Bugs#

Before Submitting a Bug Report#

A good bug report shouldn’t leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible.

  • Make sure that you are using the latest version.

  • Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions.

  • To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the bug tracker.

  • Collect information about the bug:

    • Stack trace (Traceback)

    • OS, Platform and Version (Windows, Linux, macOS, x86, ARM)

    • Version of Python and package manager (conda/pip etc), depending on what seems relevant.

    • Possibly your input, the output and any error messages you are seeing.

    • Can you reliably reproduce the issue?

How Do I Submit a Good Bug Report?#

We use GitHub issues to track bugs and errors. If you run into an issue with the project:

  • Open an Issue. (Since we can’t be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.)

  • Explain the behavior you would expect and the actual behavior.

  • Please provide as much context as possible and describe the reproduction steps that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case.

  • Provide the information you collected in the previous section.

Once it’s filed:

  • The project team will label the issue accordingly.

  • A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps. Bugs will not be addressed until they are reproducible.

Code Quality and Testing#

To ensure pelagos-py remains reliable, we enforce the following requirements:

  • Automated checks: Once a PR is submitted, the tests and the formatting/lint checks run automatically. Code must pass them to be considered for merging.

  • Review Process: A human reviewer must approve the changes before they are merged into main.

The workflow automatically updates the version number upon a successful PR to main. Any manually created release is then automatically published to PyPI.

Formatting and Linting#

Code is formatted and linted with ruff; its settings are in pyproject.toml. CI checks every PR with a pinned ruff version, so run both before pushing:

ruff format .
ruff check .

The dashboard’s JavaScript and HTML are formatted with Prettier (settings in .prettierrc.json; CSS is left as written):

npx prettier@3.3.3 --write "src/pelagos_py/dashboard/static/**/*.{js,html}"

Testing#

We use pytest for testing. The tests live in the tests/ directory at the root of the repository, one file per step or feature.

Installing the test dependencies

The testing tools (pytest and pytest-cov) are an optional dependency group in pyproject.toml. Install pelagos-py in editable mode with the test extra from the root of the repository:

pip install -e ".[test]"

The -e flag means changes to the source are picked up without reinstalling. The quotes around ".[test]" stop some shells (such as zsh) treating the square brackets as a glob pattern.

Running the tests

From the root of the repository:

pytest                                                # full suite
pytest tests/test_impossible_date_qc.py               # one file
pytest tests/test_impossible_date_qc.py::test_dates -v  # one test, verbose
pytest --cov=pelagos_py                               # with a coverage report

Documentation#

Building the docs

The documentation is built with Sphinx from the docs/ folder:

pip install -e .
pip install -r docs/requirements.txt
cd docs
make figures   # draws the user-guide figures (downloads the demo file the first time)
make html      # builds the site into docs/_build/html

The user-guide figures are not committed: make figures draws them from the demo file, and the docs CI does the same before publishing.

API reference

The API reference is generated automatically from the source by sphinx-autoapi, which reads the code statically (it never imports the package). The rule for what appears is simple:

  • Has a docstring → it is shown. Any class, method or function with a docstring is added to the API reference.

  • No docstring → it is hidden. Undocumented members (and imported names, __init__, etc.) are left out automatically, keeping the pages clean.

So to document something, write a docstring; to keep something out of the docs, leave its docstring off. We use NumPy-style docstrings (Parameters, Returns, Examples sections).

If a member has a docstring but you still want to hide it from the docs, add :meta private: anywhere in that docstring:

def helper(self):
    """Do the thing.

    :meta private:
    """

Note: A runtime marker such as a @nodoc decorator will not work, because sphinx-autoapi parses the source without running it and never sees attributes set at runtime. Use the docstring rule (or :meta private:) instead.

Common Commands#

Clone the repository

git clone https://github.com/NOC-OBG-Autonomy/pelagos-py.git

Create a feature branch

Always create a new branch for your work to keep your fork organised:

git checkout -b my-new-feature

Stay updated with main

Before submitting a PR, ensure your local code is up to date with the latest changes from the official main branch:

git fetch upstream
git merge upstream/main

Submitting changes

Push your changes to your fork and then use the GitHub web interface to open a Pull Request. Ensure the base branch is set to main.

git add .
git commit -m "Brief description of changes"
git push origin my-new-feature

Extending pelagos-py#

One of the main goals of pelagos-py is to make adding your own processing as painless as possible. This section explains how to add new steps and QC checks, including the base-class interfaces and how new functionality is registered so the pipeline can discover it.

Templates are provided for both: copy blank_step.py for a new step, or blank_qc.py for a new QC check. It is still recommended that you read the instructions below to avoid common implementation issues.

How to add a new step#

  1. Create a new Python file in the appropriate directory under src/pelagos_py/steps/.

    Note

    If you are creating a step for specific variables, it should go in the variables subdirectory.

  2. Define a new class for your step, inheriting from BaseStep and adding the @register_step decorator. This makes the step discoverable by the Pipeline Manager, while still letting you define other (unregistered) classes in the same file.

  3. Define the step_name attribute. This is the name used in the pipeline config file to refer to the step.

    from pelagos_py.steps.base_step import BaseStep, register_step
    
    @register_step
    class MyNewStep(BaseStep):
    
        step_name = "My New Step"
    
  4. Implement the run method, which contains the logic for your step. It should take no arguments other than self and should return the self.context object.

    from pelagos_py.steps.base_step import BaseStep, register_step
    
    @register_step
    class MyNewStep(BaseStep):
        step_name = "My New Step"
    
        def run(self):
            # Your processing logic here
            return self.context
    
  5. Optionally, implement the generate_diagnostics method if your step produces any diagnostic plots or outputs.

    from pelagos_py.steps.base_step import BaseStep, register_step
    
    @register_step
    class MyNewStep(BaseStep):
        step_name = "My New Step"
    
        def run(self):
            # Your processing logic here
            return self.context
    
        def generate_diagnostics(self):
            # Your diagnostics logic here
            pass
    

    There are already default methods for generating common diagnostics, such as time series and scatter plots. See the diagnostics documentation for more information.

  6. Add the step to your pipeline config file, using the step_name you defined in step 3.

    # Pipeline configuration — only needed once at the top of the file
    pipeline:
      name: "My Pipeline"
      description: "A pipeline for demonstration purposes"
    
    # Steps in the pipeline
    steps:
      - name: "My New Step"
        parameters:
          param1: value1
          param2: value2
    
  7. Any parameters defined in the parameters section of the config file are passed to your step as attributes. You can access them in your run method as self.param1, self.param2, and so on.

    Note

    This is handled automatically by the BaseStep class. More information can be found in the BaseStep documentation.

Adding QC handling to a step#

Some users may want to filter out bad data before a processing step runs. This is implemented through the QCHandlingMixin (see qc_handling.py). The pipeline preserves the original dataset dimensions, so filtered data is either replaced or reinserted once the step completes.

To give your step QC handling, add QCHandlingMixin to the class inheritance and call self.filter_qc(), self.reconstruct_data(), self.update_qc() and — if you add new variables — self.generate_qc({<QC_child>: [*<QC_parents>]}):

from pelagos_py.steps.base_step import BaseStep, register_step
from pelagos_py.utils.qc_handling import QCHandlingMixin

@register_step
class MyNewStep(BaseStep, QCHandlingMixin):
    step_name = "My New Step"

    def run(self):
        # Filter the specified QC out of this step's instance of self.data
        # and store it separately.
        self.filter_qc()

        # Your processing logic here. Always use self.data to access your
        # processing inputs, as this is what has been filtered.
        # --------- EXAMPLE ---------
        self.data["C"] = self.data["A"] * self.data["B"]
        # ---------------------------

        # Add the filtered-out data back in, or retain its replacement
        # depending on the user config.
        self.reconstruct_data()
        # Update the flags of the filtered data.
        self.update_qc()

        # If a new variable was added, give it its own QC column derived from
        # its parents' QC. Not necessary if no new variables were added.
        # --------- EXAMPLE ---------
        self.generate_qc({"C_QC": ["A_QC", "B_QC"]})
        # ---------------------------

        self.context["data"] = self.data
        return self.context

    def generate_diagnostics(self):
        # Your diagnostics logic here
        pass

To use QC filtering, the step config must specify qc_handling_settings:

# Steps in the pipeline
steps:
  - name: "My New Step"
    parameters:
      param1: value1
      param2: value2
      # [qc_handling_settings]:
      #   Can be specified in any step that has the QC filtering functionality.
      qc_handling_settings:
        # [flag_filter_settings]:
        #   {variable: flags to filter} pairs. Data flagged with any of the
        #   specified flags is replaced with a nan internally. All steps
        #   should be designed to operate with nans.
        flag_filter_settings:
          PRES: [3, 4]
        # [reconstruction_behaviour]:
        #   How data is reconstructed after processing (defaults to reinsert):
        #   "replace":  Filtered indices keep their post-processing value and
        #               the original "bad data" is deleted.
        #   "reinsert": The filtered "bad data" is reinserted into the
        #               post-processed data.
        reconstruction_behaviour: "replace"
        # [flag_mapping]:
        #   How flags should change for "bad data" indices when the pre- and
        #   post-processing data differ. E.g. interpolation replaces bad and
        #   missing values (3, 4, 9) with interpolated values (8).
        flag_mapping:
          3: 8
          4: 8
          9: 8
        # [calculation_flag_filter]:
        #   Flags a step's calculations ignore (defaults to [3, 4, 9], or [4, 9]
        #   for CHLA variables, which are flagged 3 until corrected). Unlike
        #   flag_filter_settings this does not remove the data: the samples are
        #   still corrected, they just do not inform the correction. E.g. Deep
        #   Correction leaves bad values out of the dark-value estimate but
        #   still subtracts the dark value from them. Set to [] to opt out.
        #   Steps opt in by calling self.calculation_mask([...]) with the
        #   variables whose flags should gate the calculation.
        calculation_flag_filter: [3, 4, 9]

How to add a new QC check#

QC checks operate exclusively on the QC flags of the data variables. This is useful for researchers post-pipeline who want to remove bad or suspicious data, or to exclude bad data from specific processing steps (see Adding QC handling to a step above). All checks are run through the Apply QC step, which transfers the individual results onto the existing QC columns.

As described on the Quality Control page, there are two types of check:

  • Static checks always operate on the same variable(s) and produce the same QC outputs.

  • Dynamic checks let the user specify which variables they apply to, so the QC output is not pre-determined.

A standard structure for dynamic checks is yet to be settled, so this section covers only the implementation of static checks. Examples of dynamic checks can be found in stuck_value_qc.py and range_qc.py. A template for a static check is provided in blank_qc.py.

  1. Create your QC file in src/pelagos_py/steps/quality_control/.

  2. Import the parent class and define your QC class. It must inherit from BaseQC and carry the @register_qc decorator so the pipeline can find and register it.

  3. Specify the following attributes:

    from pelagos_py.steps.base_qc import BaseQC, register_qc, flag_cols
    
    @register_qc
    class MyNewCheck(BaseQC):
        qc_name = "my new check"  # How you refer to the check in config (see below)
        parameter_schema = {'A_cutoff': {'type': float, 'default': 1}}  # Parameters the user may supply, with type and default
        required_variables = ['A']  # Variables required for execution; cross-referenced against the data vars in context
        provided_variables = []  # Variables this check itself provides, if any
        qc_outputs = ['A_QC']  # QC outputs; references that help "Apply QC" update existing QC in the data
    
  4. Add the return_qc method, which implements your check algorithm. Optionally add plot_diagnostics if the check should generate plots when diagnostics is true in the config.

    from pelagos_py.steps.base_qc import BaseQC, register_qc, flag_cols
    
    @register_qc
    class MyNewCheck(BaseQC):
        qc_name = "my new check"
        parameter_schema = {'A_cutoff': {'type': float, 'default': 1}}
        required_variables = ['A']
        provided_variables = []
        qc_outputs = ['A_QC']
    
        def return_qc(self):
            # IMPORTANT: access the data with self.data.
            # self.flags should be an xarray Dataset whose data_vars hold the
            # "{variable}_QC" columns produced by the check.
            return self.flags
    
        def plot_diagnostics(self):
            # Add your diagnostic plotting here
            ...
    

    Access the data using self.data (an xarray Dataset). The method must return an xarray Dataset (self.flags), which can contain any number of data variables — but those with the _QC suffix must be listed in the qc_outputs attribute.

  5. Finally, add your new check to the config.

    - name: "Apply QC"
      parameters:
        # qc_settings can list multiple checks
        qc_settings:
          # The qc_name
          my new check:
            # Specify the A_cutoff setting
            A_cutoff: 100
        # If you want plotting:
        diagnostics: true