Skip to content

NetCDF file target - #116

Open
chpolste wants to merge 12 commits into
developfrom
feature/xarraytarget
Open

chpolste wants to merge 12 commits into
developfrom
feature/xarraytarget

Conversation

@chpolste

@chpolste chpolste commented Aug 13, 2026 •

Copy link
Copy Markdown
Member

Description

Adds a way to write xarray data to NetCDF files.

  1. DatasetBuilder (pproc.common.xr_helpers): a transactional collector for xarray.DataArray/Dataset objects.
  2. NetCDFTarget (pproc.config.targets): a target that writes xarray data as NetCDF to a file.

I intend to use this target for several reduction-type products where the results aren't fields, in particular Hovmöller diagrams and indices for MJO, SSW and weather regimes. The plan is to also provide a CoverageJSONTarget based on the DatasetBuilder in the future.

DatasetBuilder

Method Purpose
stage(ds) Add a named DataArray or a Dataset to the staging area
commit() Merge the staged objects into one dataset if they form a full cube and commit it
reset_staged() Clear the staging area
undo_commit(stage=False) Drop the last commit, optionally re-staging it (required to handle flush failures)
squash_commits() Merge all commits into one
to_dataset() Merge all commits in commit order
enable_parallel(manager) Share the commit list across processes
  • The cube restriction for commits shouldn't present a restriction in practice given how data retrieval is partitioned in pproc. The restriction does not apply to the merged dataset (which is NaN-filled) and could be lifted later if necessary.
  • Commits are merged iteratively with combine_first: values from a later commit take precedence, and earlier commits only supply values and attributes where later ones have none. NaN marks missing values. A later NaN does not replace an earlier value, and an earlier NaN is filled by a later value.
  • Commits over different coordinates are outer-joined with NaN-fills for holes to form the full dataset. This means that integer values become float. A single commit, or commits over identical coordinates, keep their dtype.
  • Commits could gain the ability to auto-convert different inputs in the future, e.g., grib messages or DataFrames into DataArrays.

NetCDFTarget

This mixes format and target but I think it it's too different from the existing file target to merge the two. I'm open to something like netcdf-file as an alternative name.

target:
  type: netcdf
  path: output.nc
  encoding: zlib  # optional, applied to all data variables
  attrs:  # optional, global attributes of the output file
    title: My output
  combine_kwargs:  # optional, passed to xarray.combine_by_coords when merging commits
    combine_attrs: drop_conflicts

The target supports parallel writes and checkpointing/recovery although with some caveats. The whole NetCDF file is rewritten on flush. Race conditions arise in parallel processing when values are set repeatedly over the same coordinates, though I don't expect this to matter in actual workflows.

Tests

The test suite covers the stage/commit transactional behaviour and the NetCDF writing/recovery.

Contributor Declaration

By opening this pull request, I affirm the following:

  • All authors agree to the Contributor License Agreement.
  • The code follows the project's coding standards.
  • I have performed self-review and added comments where needed.
  • I have added or updated tests to verify that my changes are effective and functional.
  • I have run all existing tests and confirmed they pass.

@oiffrig oiffrig left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The implementation looks good to me.

Regarding the design, there are a few things I'm not completely comfortable with, but I'm not sure there is a good solution in the current state (since it's the first time we've been trying to use the Target interface to write something other than GRIB):

  • This is not directly compatible with the currently accepted use of Target.write with a GRIB message
  • When writing more general tabular data, this will for now be the only suitable target
  • The format attribute mixes different concerns, namely the storage format (netcdf, xarray) and the location (file, memory)
  • The type attribute matches the data format passed to write, while other targets use it to specify the location

I don't want this to be a blocker though, so I don't mind merging for now (maybe making these caveats explicit in docstrings / comments, and/or adding safety checks), but I think it would be nice to design an output interface that allows non-GRIB data. Shall we have a think about that and then discuss?

@chpolste

chpolste commented Aug 19, 2026 •

Copy link
Copy Markdown
Member Author

Hi @oiffrig, thanks for the review and your thoughts on the design!

I've pushed another commit to improve the separation of concerns and to bring the implementation a bit closer to the existing targets: the transactional Dataset/DataArray collection functionality is extracted into a new DatasetBuilder class, which a new NetCDFTarget now uses under the hood. The format switch is removed and the "memory" use case is covered by the standalone availability of the DatasetBuilder without any of the file writing baggage. Still, type should really be "file", independent of the encoding, but I'm not particularly keen on mixing the grib writer and the netcdf writer into a common class. Would "netcdf-file" be more appropriate for the new target?

I've split the test accordingly, but they don't cover some of the new methods yet.

For tabular data, this will be the only suitable target for now, as you say. I think the DatasetBuilder could be extended to hold GRIB messages and convert them to xarray Datasets with earthkit-data when committing to the collection.

@chpolste chpolste changed the title XarrayTarget with (optional) NetCDF writing/recovery NetCDF file target Sep 21, 2026
@chpolste

Copy link
Copy Markdown
Member Author

@oiffrig, this PR is ready for review again. I've updated the description at the top to match the current state and my last comment explains the refactoring.

# while the lock is aquired to synchronise the committed
# state of the builder with the actual file content
self._builder.undo_commit(stage=True)
raise

@jinmannwong jinmannwong Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the purpose of calling undo_commit, if you raise afterwards?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In case the calling context handles the exception and wants to retry the flush.

I seemed like a good idea to keep the file contents and committed builder state always in sync, but thinking about it now, I'm not sure anymore that it solves any specific problem. I'll have another look.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, thanks, I understand now. No need to spend too much time on it, happy to leave it as is.

@jinmannwong jinmannwong left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just one small question, but otherwise looks good to me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants