# io.py
from __future__ import annotations
import logging
import os
import shutil
import pathlib as pl
from importlib import resources
from configparser import ConfigParser
from typing import Optional, List, Union
import numpy as np
import xarray as xr
import netCDF4 as nc
logger = logging.getLogger(__name__)
[docs]
def copy_instrument_configuration(
instrument: str,
project_name: Optional[str] = None,
aux_config: bool = False,
dst_instrument_config: Optional[Union[str, pl.Path]] = None,
overwrite: bool = False
) -> None:
"""
Copies the specified instrument configuration file and an auxiliary configuration file
from the package resources to the current working directory. If a project name is provided,
it prefixes the copied configuration files with the project name for easy identification.
Current supported Optical Array Probes (OAP):
---------------------------------------------
- 2DC (Two Dimension Cloud particle imaging probe)
- 2DP (Two Dimension Precipitation particle imaging probe)
- 2DS (2D-Stereo, SPEC Inc.)
- CIP (Cloud Imaging Probe, DMT)
- PIP (Precipitation Imaging Probe, DMT)
- HVPS (High Volume Precipitation Spectrometer, SPEC Inc.)
- HVPS4 (SPEC HVPS4)
- Fast2DS (SPEC Fast2DS)
- CIP25 (DMT CIP25)
- CIP_grey (DMT CIP grey)
Parameters:
-----------
- instrument (str): Name of the instrument for which the configuration file is to be copied.
Must correspond to one of the supported OAPs listed above.
- project_name (str, optional): Project name to prefix the configuration file names.
If specified, files are named `<project_name>.<filename>`.
If omitted, files retain their original names.
- aux_config (bool, optional): Flag indicating whether to also copy a general auxiliary
configuration file (`aux_config.ini`). Defaults to False.
- dst_instrument_config (str/Path, optional): Full path of output instrument configuration file.
If omitted, the full path is set to `/path/of/current/working/directory/<project_name>.<filename>`.
- overwrite (bool, optional): If True, overwrites existing destination files. Defaults to False.
Operation Details:
------------------
- The function looks for the instrument-specific configuration file (`<instrument>.ini`)
and, optionally, a general auxiliary configuration file (`aux_config.ini`), within the
`probe_config` subdirectory of the `cops` package.
- If the specified instrument configuration file is not found, a FileNotFoundError is raised.
- If `aux_config` is True and the auxiliary configuration file is not found, a FileNotFoundError is raised.
- If destination files exist and `overwrite` is False, a FileExistsError is raised.
Returns:
--------
None. The function logs success messages or raises errors
if the specified files cannot be found or copied.
Example Usage:
--------------
- Copy just the instrument configuration for '2DS':
.. code-block:: python
copy_instrument_configuration('2DS')
- Copy both the instrument and auxiliary configuration files for '2DS', prefixed with 'ESCAPE':
.. code-block:: python
copy_instrument_configuration('2DS', 'ESCAPE', aux_config=True)
History:
--------
- 2026-07-03: Refactored by Yongjie Huang to add overwrite controls, parent directory handling, and raise FileExistsError/FileNotFoundError.
- 2024-02-24: Created by Yongjie Huang (huangynj@gmail.com)
"""
instrument_config_name = f"{instrument}.ini"
dst_root = pl.Path.cwd()
if dst_instrument_config is None:
dst_instrument_config = dst_root / (f"{project_name}.{instrument_config_name}" if project_name else instrument_config_name)
else:
dst_instrument_config = pl.Path(dst_instrument_config)
dst_aux_config = dst_root / (f"{project_name}.aux_config.ini" if project_name else "aux_config.ini")
# Check overwrite safety
if not overwrite:
if dst_instrument_config.exists():
raise FileExistsError(f"Destination configuration file '{dst_instrument_config}' already exists.")
if aux_config and dst_aux_config.exists():
raise FileExistsError(f"Destination auxiliary configuration file '{dst_aux_config}' already exists.")
# Construct the path to the config file within the package
config_path = resources.files('cops') / f"probe_config/{instrument_config_name}"
if not config_path.exists():
raise FileNotFoundError(f"ERROR: The supplied instrument name '{instrument}' cannot be found in the config list.")
# Ensure parent directory exists
dst_instrument_config.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(config_path, dst_instrument_config)
logger.info("Copied %s to %s", instrument_config_name, dst_instrument_config)
if aux_config:
aux_config_path = resources.files('cops') / 'probe_config/aux_config.ini'
if not aux_config_path.exists():
raise FileNotFoundError("ERROR: Auxiliary config file 'aux_config.ini' cannot be found.")
dst_aux_config.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(aux_config_path, dst_aux_config)
logger.info("Copied aux_config.ini to %s", dst_aux_config)
logger.info("Copied configuration files for %s", instrument)
[docs]
def convert_instrument_raw_data_to_spif(
raw_file_path: str,
config_file_path: str,
output_spif_path: Optional[str] = None
) -> None:
"""
Converts raw data from instruments to Single Particle Image Format (SPIF) using specified configuration settings.
This function takes the path to a raw data file and a configuration file as inputs and converts the raw data into
SPIF format, which is a standardized format for storing and analyzing particle imaging data. The output SPIF file
can either be specified by the user or automatically generated based on the raw file name.
Parameters:
-----------
- raw_file_path (str): The file path to the raw data file that needs to be converted.
- config_file_path (str): The file path to the configuration file that specifies settings and parameters for the
conversion process. This configuration dictates how raw data is interpreted and converted.
- output_spif_path (str, optional): The file path where the converted SPIF file will be saved. If not provided,
the function will automatically generate a file name by appending '.nc' directly
to the raw file name (e.g., 'RF01.2DS' becomes 'RF01.2DS.nc'). The generated
SPIF file will be saved in the same directory as the raw file.
Returns:
--------
None. The function performs the conversion and prints a message indicating the success of the operation, including
the path to the generated SPIF file.
Example Usage:
--------------
.. code-block:: python
convert_instrument_raw_data_to_spif(
raw_file_path='/path/to/raw/data.raw',
config_file_path='/path/to/config/file.ini'
)
This will convert the specified raw data file using the given configuration and automatically generate the output
SPIF file name and location based on the raw file name.
.. code-block:: python
convert_instrument_raw_data_to_spif(
raw_file_path='/path/to/raw/data.raw',
config_file_path='/path/to/config/file.ini',
output_spif_path='/path/to/output/data_spif.nc'
)
This will convert the specified raw data file using the given configuration and save the SPIF file to the specified
output path.
History:
--------
- 2026-06-24: Updated default output naming convention to append '.nc' directly – Yongjie Huang
- 2024-02-24: Created by Yongjie Huang (huangynj@gmail.com)
"""
if output_spif_path is None:
input = pl.Path(raw_file_path)
output_spif_path = input.parent / (input.name + '.nc')
transformed_args = {
'filename': raw_file_path,
'config': config_file_path,
'output': output_spif_path,
}
try:
from nrc_spifpy.scripts.extract import call_spifcore
except ImportError as exc:
raise ImportError(
"Raw OAP decoding requires the optional dependency 'nrc_spifpy'. "
"Install it before calling convert_instrument_raw_data_to_spif() "
"or decode_OAP_raw_data()."
) from exc
spif_core = call_spifcore(transformed_args)
spif_core.process(processors=None)
logger.info("Converted raw data %s to SPIF data %s", raw_file_path, output_spif_path)
[docs]
def decode_OAP_raw_data(
raw_file_list: List[str],
probe_name: str,
project_name: Optional[str] = None,
out_dir: Optional[str] = None,
config_path: Optional[str] = None,
create_config_template: bool = False,
overwrite_config_template: bool = False,
allow_cwd_fallback: bool = False
) -> None:
"""
Decodes raw data files from Optical Array Probes (OAP) into the Single Particle Image Format (SPIF),
applying probe-specific configurations. The function processes each raw file to generate
output in a specified directory.
Parameters:
-----------
- raw_file_list : list
A list of file paths pointing to the raw data files to be processed.
- probe_name : str
The name of the probe, which determines the specific configuration file to use for decoding the raw data.
Current supported Optical Array Probes (OAP):
- 2DC (Two Dimension Cloud particle imaging probe)
- 2DP (Two Dimension Precipitation particle imaging probe)
- 2DS (2D-Stereo, SPEC Inc.)
- CIP (Cloud Imaging Probe, DMT)
- PIP (Precipitation Imaging Probe, DMT)
- HVPS (High Volume Precipitation Spectrometer, SPEC Inc.)
- HVPS4 (SPEC HVPS4)
- Fast2DS (SPEC Fast2DS)
- CIP25 (DMT CIP25)
- CIP_grey (DMT CIP grey)
- project_name : str, optional
The name of the project, which if provided, will be used to
update the 'project' parameter in the 'root' section of the
probe's configuration file. It also prefixes the configuration
file name for easy identification.
- out_dir : str, optional
The directory where the processed files will be saved. If not provided,
the current working directory is used.
- config_path : str, optional
Path to a specific configuration file.
- create_config_template : bool, optional
If True, creates a default config file template.
- overwrite_config_template : bool, optional
If True, overwrites existing config file template.
- allow_cwd_fallback : bool, optional
If True, allows looking for config in current working directory.
Operation Details:
------------------
1. Checks for the existence of the probe's configuration file in the current working directory.
If it exists, reads the configuration; if not, attempts to copy a default configuration file.
2. If a project name is provided and the 'root' section exists in the configuration, updates the
project name in the configuration file.
3. Logs the current configuration settings for verification.
4. Processes each raw data file specified in 'raw_file_list', converting it to a standardized
format and saving the output in 'out_dir'.
5. Skips processing for any raw data file if the output file already exists in the output directory.
Example Usage:
--------------
- Basic usage (defaults to searching adjacent files and falls back to CWD if allowed):
.. code-block:: python
decode_OAP_raw_data(
raw_file_list=['/path/to/raw/file1', '/path/to/raw/file2'],
probe_name='2DS',
project_name='MyProject',
out_dir='/path/to/output'
)
This will process 'file1' and 'file2' using the '2DS' probe configuration, updating
the project name to 'MyProject' in the configuration file, and save the processed files in
'/path/to/output'.
- Production pipeline usage specifying a custom configuration path and disabling CWD fallbacks:
.. code-block:: python
decode_OAP_raw_data(
raw_file_list=['/path/to/raw/file1'],
probe_name='2DS',
config_path='/path/to/custom_config.ini',
allow_cwd_fallback=False
)
- Generating a default configuration template file at a specific path without decoding:
.. code-block:: python
decode_OAP_raw_data(
raw_file_list=['/path/to/raw/file1'],
probe_name='2DS',
config_path='/path/to/generated_config.ini',
create_config_template=True,
overwrite_config_template=True
)
Returns:
--------
None. Logs messages indicating the status of configuration file existence, parameter updates,
and the processing status of each raw data file.
History:
--------
- 2026-07-03: Yongjie Huang, refactored to support resolve_probe_config_path, batch-safety raises,
template copying, and overwrite arguments.
- 2025-12-31: Yongjie Huang, added 'update_ini_param' function to update a parameter in
an INI file while preserving comments and structure.
- 2024-02-24: Created by Yongjie Huang (huangynj@gmail.com)
"""
# -------------------------------------------------------
def update_ini_param(
filepath: str,
section: str,
key: str,
new_value: str,
method: str = 'manual'
) -> None:
"""
Updates a parameter in an INI file while preserving comments and structure.
Parameters:
-----------
- filepath (str): Path to the INI file.
- section (str): Section of the INI file to update.
- key (str): Key of the parameter to update.
- new_value (str): New value for the parameter.
- method : str, optional
Method to use for updating the parameter.
'manual' (default) uses safe string manipulation.
'configupdater' uses the ConfigUpdater library (must be installed).
Returns:
--------
None
History:
--------
- 2025-12-31: Created by Yongjie Huang
"""
if method == 'configupdater':
try:
from configupdater import ConfigUpdater
updater = ConfigUpdater()
updater.read(filepath)
if section in updater and key in updater[section]:
updater[section][key].value = new_value
updater.update_file()
else:
logger.warning(
"Section %r or key %r was not found in %s; configuration was not updated",
section,
key,
filepath,
)
return
except ImportError:
logger.warning("ConfigUpdater is not installed; falling back to the manual INI updater")
except Exception as e:
logger.warning(
"ConfigUpdater failed; falling back to the manual INI updater: %s",
e,
exc_info=True,
)
# Manual method (default or fallback)
with open(filepath, 'r') as f:
lines = f.readlines()
new_lines = []
in_section = False
key_updated = False
for line in lines:
stripped = line.strip()
# Check for section header
if stripped.startswith('[') and stripped.endswith(']'):
current_section = stripped[1:-1]
if current_section == section:
in_section = True
else:
in_section = False
new_lines.append(line)
continue
# Check for key in the correct section
if in_section and not key_updated and '=' in line:
# Split only on first =
# Handle potential comments after value?
# For safety, simplistic check:
param_key = line.split('=', 1)[0].strip()
if param_key == key:
new_lines.append(f"{key} = {new_value}\n")
key_updated = True
continue
new_lines.append(line)
with open(filepath, 'w') as f:
f.writelines(new_lines)
if not key_updated:
logger.warning(
"Section %r or key %r was not found in %s; configuration was not updated",
section,
key,
filepath,
)
def _update_and_print_config(config_file: str, proj_name: Optional[str], prompt_msg: str) -> ConfigParser:
config = ConfigParser()
# ConfigParser lowercases option names by default; keep the spelling used
# in the probe configuration when logging and returning the parser.
config.optionxform = str
config.read(config_file)
# Update the parameter
if proj_name is not None:
if config.has_section('root'):
project_key = next(
(key for key in config['root'] if key.casefold() == 'project'),
'project',
)
config.set('root', project_key, proj_name)
# Preserve comments and the original spelling of the option name.
update_ini_param(config_file, 'root', project_key, proj_name)
separator = '------------------------------------------------------'
config_lines = [prompt_msg, "", separator]
for section in config.sections():
config_lines.append(f"Section: {section}")
for key in config[section]:
config_lines.append(f" {key} = {config[section][key]}")
config_lines.append(f"{separator}\n")
logger.info("%s", "\n".join(config_lines))
return config
# -------------------------------------------------------
if len(raw_file_list) == 0:
logger.warning("No OAP probe raw data files")
return
from cops.config import resolve_probe_config_path
filename = f"{project_name}.{probe_name}.ini" if project_name else f"{probe_name}.ini"
if create_config_template:
probe_config_file = config_path if config_path else os.path.join(os.getcwd(), filename)
copy_instrument_configuration(
probe_name,
project_name=project_name,
dst_instrument_config=probe_config_file,
overwrite=overwrite_config_template
)
_update_and_print_config(
probe_config_file,
project_name,
f"The configuration is as follows. Update parameters in '{probe_config_file}' if necessary and run the program again."
)
return
probe_config_file = resolve_probe_config_path(
raw_file_list[0],
project_name,
probe_name,
config_path=config_path,
allow_cwd_fallback=allow_cwd_fallback
)
if probe_config_file is None:
raise FileNotFoundError(
f"Configuration file '{filename}' not found. Please specify an explicit config_path, "
f"place the configuration file adjacent to raw files, or pass create_config_template=True."
)
logger.info("Probe configuration file '%s' exists!", probe_config_file)
_update_and_print_config(
probe_config_file,
project_name,
f"Here is the configuration. If there is something wrong, stop the program and correct them in '{probe_config_file}'"
)
cwd = os.getcwd()
if out_dir is None:
out_dir = cwd
if not os.path.exists(out_dir):
os.makedirs(out_dir)
# decode raw file
for raw_file_path in raw_file_list:
logger.info("Processing file: %s", raw_file_path)
raw_file_name = os.path.basename(raw_file_path)
output_spif_path = os.path.join(out_dir, f"{raw_file_name}.nc")
if os.path.exists(output_spif_path):
logger.info(" File '%s' already exists!", output_spif_path)
continue
convert_instrument_raw_data_to_spif(raw_file_path, probe_config_file, output_spif_path=output_spif_path)
logger.info("All raw files have been processed. Done!")
return
[docs]
def read_spif_images(
spif_file: str,
group: Optional[str] = None,
decode_times: bool = False
) -> xr.Dataset:
"""
Reads image data from a specified group within a SPIF (Single Particle Image Format)
dataset, using xarray. This function is specifically designed to access image data stored in the
'core' subgroup of the specified group. If no group is specified, it defaults to reading from the
root group.
Parameters:
-----------
- spif_file (str): The file path to the SPIF dataset to be read.
- group (str, optional): The name of the parent group within the SPIF file from which the 'core'
subgroup containing image data will be accessed. If None, the function attempts to read from
the root group's 'core' subgroup, if it exists. Defaults to None.
- decode_times (bool, optional): Whether to decode time variables into datetime objects,
simplifying time series analysis. Defaults to False.
Returns:
--------
- xarray.Dataset: An xarray dataset containing the image data from the specified 'core' subgroup
of the SPIF file, along with associated metadata and variables.
History:
--------
- 2024-02-24: Created by Yongjie Huang (huangynj@gmail.com)
"""
group_core = f'{group}/core' if group is not None else 'core'
images = xr.open_dataset(spif_file, group=group_core, decode_times=decode_times)
return images
[docs]
def read_spif_group(
spif_file: str,
group: Optional[str] = None,
decode_times: bool = False
) -> xr.Dataset:
"""
Reads data from a specified group within a SPIF (Single Particle Image Format)
dataset, using xarray. If no group is specified, it defaults to reading from the
root group.
Parameters:
-----------
- spif_file (str): The file path to the SPIF dataset to be read.
- group (str, optional): The name of the group within the SPIF file.
It can include subgroup, e.g., '2DS-H/level-1'.
If None, the function attempts to read from the root group. Defaults to None.
- decode_times (bool, optional): Whether to decode time variables into datetime objects,
simplifying time series analysis. Defaults to False.
Returns:
--------
- xarray.Dataset: An xarray dataset containing the data from the specified group
of the SPIF file, along with associated metadata and variables.
History:
--------
- 2024-03-21: Created by Yongjie Huang (huangynj@gmail.com)
"""
ds_group = xr.open_dataset(spif_file, group=group, decode_times=decode_times)
return ds_group
[docs]
def get_ith_particle_image(
ds_header: xr.Dataset,
ds_images: xr.Dataset,
ith: int
) -> xr.DataArray:
"""
Extracts the image of the i-th particle from a dataset of images stored in Single Particle Image Format (SPIF).
This function calculates the start and end indices for the ith particle's image data within a larger array of images
based on the cumulative sum of image lengths and the number of diodes (pixels per slice). It then reshapes and returns
this specific image as an xarray DataArray with appropriate dimensions and metadata.
Parameters:
-----------
- ds_header (xarray.Dataset): The dataset containing the header information of the SPIF file, which includes
the number of diodes (pixels) per image slice.
- ds_images (xarray.Dataset): The dataset containing the images and associated metadata, including the lengths
of individual particle images.
- ith (int): The zero-based index of the particle whose image is to be extracted. For example, ith=0 will extract
the first particle's image in the dataset.
Returns:
--------
- xarray.DataArray: A 2D array representing the image of the specified particle. The dimensions of the array are
('slice', 'diode'), where 'slice' represents the image length (number of slices) and 'diode' represents the number
of pixels in each slice.
Note:
-----
The function assumes that the image data is stored linearly in `ds_images.image` and that each particle's image
can be uniquely identified by its position (ith) in the sequence. The image length for each particle, required for
reshaping the image data, is obtained from `ds_images.image_len`.
Performance Warning: This function recomputes `image_len[:ip].sum()` per call. If called in a loop over N particles,
it results in O(N²) time complexity. This is perfectly suitable as an interactive single-particle helper, but for
bulk processing, use the bulk analysis pipeline where cumulative sums (`cumsum`) are precomputed.
History:
--------
- 2024-02-24: Created by Yongjie Huang (huangynj@gmail.com)
"""
diode_num = ds_header.pixels.values # Number of diodes (pixels) per slice
image_len = ds_images.image_len
ip = ith # The ith particle starting from 0
idx_s = int(image_len[:ip].sum().values * diode_num) # Start index of the ith image
idx_e = int(image_len[:ip+1].sum().values * diode_num) # End index of the ith image
ip_len = image_len[ip].values # Length of the ith image
#ip_len = (idx_e - idx_s)//diode_num
# Reshape the linear image data into a 2D array (image) based on the calculated indices and diode number
ith_image = xr.DataArray(ds_images.image[idx_s:idx_e].data.reshape(ip_len, diode_num), dims=('slice', 'diode'))
# Assign a descriptive attribute to the extracted image
ith_image.attrs['long_name'] = f'image data of the {ip}-th particle (starting from 0)'
return ith_image
[docs]
def get_multi_particle_image(
ds_header: xr.Dataset,
ds_images: xr.Dataset,
start_particle: int,
n_particle: int,
plot: bool = False,
show_separators: bool = True
) -> xr.DataArray:
"""
Extracts images of multiple particles from a dataset of images stored in Single Particle Image Format (SPIF).
This function calculates the start and end indices for a range of particles' images within a larger array of images
based on the cumulative sum of image lengths and the number of diodes (pixels per slice). It then reshapes and returns
these specific images as an xarray DataArray with appropriate dimensions and metadata.
Parameters:
-----------
ds_header : xarray.Dataset
The dataset containing the header information of the SPIF file, which includes
the number of diodes (pixels) per image slice.
ds_images : xarray.Dataset
The dataset containing the images and associated metadata, including the lengths
of individual particle images.
start_particle : int
The zero-based index of the particle whose image is to be extracted. For example, `start_particle=0` will extract
the first particle's image in the dataset.
n_particle : int
The number of particles to extract images for, starting from `start_particle`.
plot : bool, optional
If True, plots the extracted images using matplotlib's `pcolormesh`.
show_separators : bool, optional
If True (default), adds vertical lines between particles for visual distinction when plotting.
Only has effect when `plot=True`.
Returns:
--------
xarray.DataArray
A 2D xarray DataArray representing the images of the specified particles. The dimensions
of the array are ('slice', 'diode'), where 'slice' represents the image length (number of slices)
and 'diode' represents the number of pixels in each slice.
Note:
-----
The function assumes that the image data is stored linearly in `ds_images.image` and that each particle's image
can be uniquely identified by its position (ith) in the sequence. The image length for each particle, required for
reshaping the image data, is obtained from `ds_images.image_len`.
History:
--------
- 2026-01-12: Yongjie Huang, added show_separators option for vertical lines between particles.
- 2024-03-28: Created by Yongjie Huang (huangynj@gmail.com)
"""
diode_num = ds_header.pixels.values # Number of diodes (pixels) per slice
image_len = ds_images.image_len
ip = start_particle # The ith particle starting from 0
idx_s = int(image_len[:ip].sum().values * diode_num) # Start index of the ith image
idx_e = int(image_len[:ip+n_particle].sum().values * diode_num) # End index of the ith image
ip_len = (idx_e - idx_s)//diode_num
# Reshape the linear image data into a 2D array (image) based on the calculated indices and diode number
n_image = xr.DataArray(ds_images.image[idx_s:idx_e].data.reshape(ip_len, diode_num), dims=('slice', 'diode'))
# images_all = xr.DataArray(ds_images.image.data.reshape(-1, diode_num), dims=('slice', 'diode'))
# cumsum = image_len.cumsum().values
# slice_starts = np.insert(cumsum, 0, 0)[:-1] # Insert 0 at the beginning and exclude the last value
# slice_ends = cumsum
# slice_s = slice_starts[ip]
# slice_e = slice_ends[ip+n_particle-1]
# n_image = images_all.isel(slice=slice(slice_s, slice_e))
# Assign a descriptive attribute to the extracted image
n_image.attrs['long_name'] = f'Image data of {n_particle} particles starting from {ip}-th particle'
if plot:
import matplotlib.pyplot as plt
n_image.transpose().plot.pcolormesh(add_colorbar=False)
plt.gca().set_aspect('equal', adjustable='box')
plt.title(n_image.attrs['long_name'])
# Add vertical lines between particles for visual distinction
if show_separators:
# Calculate cumulative slice positions where each particle ends
cumsum = image_len[ip:ip+n_particle].cumsum().values
for boundary in cumsum[:-1]: # Skip the last one (end of last particle)
plt.axvline(x=boundary-0.5, color='red', linestyle='--', linewidth=0.5)
return n_image
[docs]
def append_xarrayDataset_to_existing_NetCDF_file(
nc_file_path: str,
ds_appended: xr.Dataset,
new_subgroup_name: str,
parent_group: Optional[str] = None,
UNLIMITED_dims: Optional[Union[str, List[str]]] = None
) -> None:
"""
Appends an xarray Dataset as a new subgroup to an existing NetCDF file.
Parameters:
-----------
- nc_file_path: Path to the existing NetCDF file.
- ds_appended: xarray Dataset to append.
- new_subgroup_name: Name for the new subgroup.
- parent_group: Name of the parent group within the NetCDF file to which the new subgroup will be added. If None, adds to the root group.
- UNLIMITED_dims: Specifies which dimensions should be unlimited. Can be a string (single dimension) or a list of strings (multiple dimensions).
History:
--------
- 2026-07-18: Validate metadata and stage writes before exposing the new subgroup.
- 2024-03-05: Created by Yongjie Huang (huangynj@gmail.com)
"""
# Validate attribute values in memory before modifying the destination file.
# Other write failures are isolated by the staging-group rename below.
attribute_items = list(ds_appended.attrs.items())
for variable in ds_appended.variables.values():
attribute_items.extend(variable.attrs.items())
with nc.Dataset(
'__cops_append_validation__',
'w',
diskless=True,
persist=False,
format='NETCDF4',
) as validation_root:
for index, (attr_name, attr_value) in enumerate(attribute_items):
if attr_name == '_FillValue' and attr_value is None:
continue
validation_root.setncattr(f'attribute_{index}', attr_value)
# Write under a private name and expose the requested subgroup only after
# the complete dataset has been stored. A mid-write failure therefore
# cannot create a subgroup that later processing mistakes for complete.
# Append the new subgroup with variables to the existing NetCDF file
# Open the existing NetCDF file in append mode
with nc.Dataset(nc_file_path, 'a') as root_grp:
#--- Navigate to the specified parent group or stay at the root level if no parent group is specified
if parent_group is not None:
current_grp = root_grp
for path_segment in parent_group.strip('/').split('/'):
if path_segment:
if path_segment in current_grp.groups:
current_grp = current_grp.groups[path_segment]
else:
raise KeyError(
f"Parent group segment '{path_segment}' not found in the NetCDF file. "
f"Complete parent path: '{parent_group}'"
)
grp_initial_group = current_grp
else:
grp_initial_group = root_grp
if new_subgroup_name in grp_initial_group.groups:
raise ValueError(
f"Subgroup '{new_subgroup_name}' already exists under "
f"'{parent_group or '/'}'"
)
# Use one predictable staging group per target. If a previous process
# stopped mid-write, the next attempt can finish that group instead of
# leaving it orphaned and creating another one.
staging_name = f'__cops_staging_{new_subgroup_name}'
#--- Create a staging subgroup under the specified parent group or root group
if staging_name in grp_initial_group.groups:
logger.warning("Resuming interrupted NetCDF append for subgroup %s", new_subgroup_name)
new_subgrp = grp_initial_group.groups[staging_name]
else:
new_subgrp = grp_initial_group.createGroup(staging_name)
#--- Adding attributes to the new subgroup
# new_subgrp.description = "Description of new_subgroup1"
# new_subgrp.creation_date = "YYYY-MM-DD"
# Copy global attributes from the provided xarray Dataset to the new subgroup
for attr_name, attr_value in ds_appended.attrs.items():
setattr(new_subgrp, attr_name, attr_value)
#--- Create dimensions in the new subgroup, setting them as unlimited if specified
# Set dimension to unlimited by using None or nc.UNLIMITED
# for dim_name, dim_length in ds_appended.dims.items():
for dim_name, dim_length in ds_appended.sizes.items():
# Determine if the current dimension should be unlimited based on UNLIMITED_dims argument
unlimited = False
if UNLIMITED_dims is not None:
if isinstance(UNLIMITED_dims, str):
unlimited = dim_name == UNLIMITED_dims
elif isinstance(UNLIMITED_dims, list):
unlimited = dim_name in UNLIMITED_dims
# Create the dimension, making it unlimited if necessary
if dim_name in new_subgrp.dimensions:
existing_dim = new_subgrp.dimensions[dim_name]
if existing_dim.isunlimited() != unlimited or (
not unlimited and len(existing_dim) != dim_length
):
raise ValueError(
f"Interrupted staging dimension '{dim_name}' is incompatible "
f"with subgroup '{new_subgroup_name}'"
)
else:
new_subgrp.createDimension(dim_name, None if unlimited else dim_length)
#--- For each variable in the Dataset, create a corresponding variable in the new subgroup
for name, variable in ds_appended.variables.items():
# Determine the variable's data type and values robustly for string/datetime compatibility
values = variable.values
attrs = dict(variable.attrs)
fill_value = attrs.get('_FillValue', None) # preserve existing _FillValue, or set below for NaT
if variable.dtype.kind in ('U', 'O'):
dtype = str
if variable.dtype.kind == 'O':
values = values.astype(str)
elif variable.dtype.kind in ('M', 'm'):
# datetime64 ('M') / timedelta64 ('m') -> int64 nanoseconds.
# NaT casts to np.iinfo('i8').min; declare it as _FillValue so
# readers mask it back to missing instead of a spurious huge int.
dtype = 'i8'
target = 'datetime64[ns]' if variable.dtype.kind == 'M' else 'timedelta64[ns]'
nat_mask = np.isnat(values)
values = values.astype(target).astype(np.int64)
if nat_mask.any():
fill_value = np.iinfo(np.int64).min
values[nat_mask] = fill_value
if 'units' not in attrs:
attrs['units'] = ('nanoseconds since 1970-01-01T00:00:00Z'
if variable.dtype.kind == 'M' else 'nanoseconds')
else:
dtype = variable.dtype.str.replace('|', '') # Format dtype string for netCDF4 compatibility
# Reuse variables already created by an interrupted append; missing
# variables are created normally.
if name in new_subgrp.variables:
var = new_subgrp.variables[name]
if var.dimensions != variable.dims:
raise ValueError(
f"Interrupted staging variable '{name}' has incompatible dimensions"
)
else:
var = new_subgrp.createVariable(name, dtype, variable.dims, fill_value=fill_value)
# Assign the variable's data from the xarray Dataset
var[:] = values
# Copy variable-specific attributes from the xarray Dataset to the NetCDF variable
# (_FillValue is reserved: it is set via createVariable, not as a plain attribute)
for attr_name, attr_value in attrs.items():
if attr_name == '_FillValue':
continue
setattr(var, attr_name, attr_value)
grp_initial_group.renameGroup(staging_name, new_subgroup_name)
# Notify the user that the process is complete
logger.info("Added xarray Dataset to subgroup %s with attributes", new_subgroup_name)