Skip to content

base

BaseReader

Bases: ABC

The interface that ALL readers must implement.

Source code in monetio/readers/base.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class BaseReader(abc.ABC):
    """
    The interface that ALL readers must implement.
    """

    @abc.abstractmethod
    def open_dataset(self, files: str | list[str], **kwargs) -> xr.Dataset | pd.DataFrame:
        """
        Main entry point to read data.

        Args:
            files: File path, list of paths, or glob pattern.
            **kwargs: Reader-specific arguments.

        Returns:
            xarray.Dataset (for models/sat) or pandas.DataFrame (for point obs).
        """
        pass

    def harmonize(self, ds):
        """
        Optional: Apply standard naming conventions (middleware).
        Can be overridden by specific readers.
        """
        return ds

harmonize(ds)

Optional: Apply standard naming conventions (middleware). Can be overridden by specific readers.

Source code in monetio/readers/base.py
62
63
64
65
66
67
def harmonize(self, ds):
    """
    Optional: Apply standard naming conventions (middleware).
    Can be overridden by specific readers.
    """
    return ds

open_dataset(files, **kwargs) abstractmethod

Main entry point to read data.

Args: files: File path, list of paths, or glob pattern. **kwargs: Reader-specific arguments.

Returns: xarray.Dataset (for models/sat) or pandas.DataFrame (for point obs).

Source code in monetio/readers/base.py
48
49
50
51
52
53
54
55
56
57
58
59
60
@abc.abstractmethod
def open_dataset(self, files: str | list[str], **kwargs) -> xr.Dataset | pd.DataFrame:
    """
    Main entry point to read data.

    Args:
        files: File path, list of paths, or glob pattern.
        **kwargs: Reader-specific arguments.

    Returns:
        xarray.Dataset (for models/sat) or pandas.DataFrame (for point obs).
    """
    pass

DiagnosticSpec

Bases: NamedTuple

Specification for a derived diagnostic variable.

Source code in monetio/readers/base.py
18
19
20
21
22
23
24
25
class DiagnosticSpec(NamedTuple):
    """Specification for a derived diagnostic variable."""

    variables: list[str]
    weights: list[float] | None = None
    units: str = "unknown"
    long_name: str = "unknown"
    name: str = "unknown"

GriddedReader

Bases: BaseReader

Base class for gridded data (Models, Satellites) that utilizes XarrayDriver.

Source code in monetio/readers/base.py
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
class GriddedReader(BaseReader):
    """
    Base class for gridded data (Models, Satellites) that utilizes XarrayDriver.
    """

    def __init__(self):
        self.driver = XarrayDriver()

    def open_dataset(
        self,
        files: str | list[str],
        use_virtualizarr: bool = False,
        virtualizarr_file: str | None = None,
        virtualizarr_backend: str = "kerchunk",
        icechunk_repo: str | None = None,
        use_dask: bool = False,
        **kwargs,
    ) -> xr.Dataset:
        """
        Uses XarrayDriver to open files. VirtualiZarr options are forwarded to the driver.

        Parameters
        ----------
        files : str or list[str]
            File path(s), URL(s), or glob pattern.
        use_virtualizarr : bool, optional
            Whether to use VirtualiZarr to create a virtual Zarr dataset, by default False.
        virtualizarr_file : str or None, optional
            Path to save/load the VirtualiZarr reference JSON file, by default None.
        virtualizarr_backend : str, optional
            Backend for VirtualiZarr references ("kerchunk" or "icechunk"), by default "kerchunk".
        icechunk_repo : str or None, optional
            Path to the Icechunk repository, by default None.
        use_dask : bool, optional
            Whether to use Dask for lazy loading, by default False.
        **kwargs : dict
            Additional arguments passed to the driver.

        Returns
        -------
        xr.Dataset
            The loaded dataset.
        """
        ds = self.driver.open(
            files,
            use_virtualizarr=use_virtualizarr,
            virtualizarr_file=virtualizarr_file,
            virtualizarr_backend=virtualizarr_backend,
            icechunk_repo=icechunk_repo,
            use_dask=use_dask,
            **kwargs,
        )
        return self.harmonize(ds)

open_dataset(files, use_virtualizarr=False, virtualizarr_file=None, virtualizarr_backend='kerchunk', icechunk_repo=None, use_dask=False, **kwargs)

Uses XarrayDriver to open files. VirtualiZarr options are forwarded to the driver.

Parameters:

Name Type Description Default
files str or list[str]

File path(s), URL(s), or glob pattern.

required
use_virtualizarr bool

Whether to use VirtualiZarr to create a virtual Zarr dataset, by default False.

False
virtualizarr_file str or None

Path to save/load the VirtualiZarr reference JSON file, by default None.

None
virtualizarr_backend str

Backend for VirtualiZarr references ("kerchunk" or "icechunk"), by default "kerchunk".

'kerchunk'
icechunk_repo str or None

Path to the Icechunk repository, by default None.

None
use_dask bool

Whether to use Dask for lazy loading, by default False.

False
**kwargs dict

Additional arguments passed to the driver.

{}

Returns:

Type Description
Dataset

The loaded dataset.

Source code in monetio/readers/base.py
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def open_dataset(
    self,
    files: str | list[str],
    use_virtualizarr: bool = False,
    virtualizarr_file: str | None = None,
    virtualizarr_backend: str = "kerchunk",
    icechunk_repo: str | None = None,
    use_dask: bool = False,
    **kwargs,
) -> xr.Dataset:
    """
    Uses XarrayDriver to open files. VirtualiZarr options are forwarded to the driver.

    Parameters
    ----------
    files : str or list[str]
        File path(s), URL(s), or glob pattern.
    use_virtualizarr : bool, optional
        Whether to use VirtualiZarr to create a virtual Zarr dataset, by default False.
    virtualizarr_file : str or None, optional
        Path to save/load the VirtualiZarr reference JSON file, by default None.
    virtualizarr_backend : str, optional
        Backend for VirtualiZarr references ("kerchunk" or "icechunk"), by default "kerchunk".
    icechunk_repo : str or None, optional
        Path to the Icechunk repository, by default None.
    use_dask : bool, optional
        Whether to use Dask for lazy loading, by default False.
    **kwargs : dict
        Additional arguments passed to the driver.

    Returns
    -------
    xr.Dataset
        The loaded dataset.
    """
    ds = self.driver.open(
        files,
        use_virtualizarr=use_virtualizarr,
        virtualizarr_file=virtualizarr_file,
        virtualizarr_backend=virtualizarr_backend,
        icechunk_repo=icechunk_repo,
        use_dask=use_dask,
        **kwargs,
    )
    return self.harmonize(ds)

PointReader

Bases: BaseReader

Base class for point/tabular data (Observations) that utilizes PandasDriver.

Source code in monetio/readers/base.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
class PointReader(BaseReader):
    """
    Base class for point/tabular data (Observations) that utilizes PandasDriver.
    """

    fixed_location = True

    def __init__(self):
        self.driver = PandasDriver()

    def open_dataset(
        self,
        files: str | list[str],
        # VirtualiZarr kwargs accepted but silently ignored for PointReaders
        use_virtualizarr: bool = False,
        virtualizarr_file: str | None = None,
        virtualizarr_backend: str = "kerchunk",
        icechunk_repo: str | None = None,
        # Standard PointReader kwargs
        read_method: str = "read_csv",
        as_xarray: bool = True,
        lazy: bool = False,
        meta: pd.DataFrame | pd.Series | dict | tuple | None = None,
        **kwargs,
    ) -> Union[pd.DataFrame, xr.Dataset, "dd.DataFrame"]:
        """
        Retrieve and load point data.

        Parameters
        ----------
        files : Union[str, List[str]]
            File path, list of paths, or glob pattern.
        use_virtualizarr : bool, optional
            Accepted but ignored for PointReaders (VirtualiZarr only applies to gridded data).
        virtualizarr_file : str or None, optional
            Accepted but ignored for PointReaders.
        virtualizarr_backend : str, optional
            Accepted but ignored for PointReaders.
        icechunk_repo : str or None, optional
            Accepted but ignored for PointReaders.
        read_method : str, optional
            The pandas/dask reading method to use, by default "read_csv".
        as_xarray : bool, optional
            If True, return an xarray.Dataset, by default True.
        lazy : bool, optional
            If True, return a dask-backed object, by default False.
        meta : pd.DataFrame, pd.Series, dict, or tuple, optional
            Dask metadata to use for lazy loading, by default None.
        **kwargs : dict
            Additional arguments passed to the reader and driver.

        Returns
        -------
        Union[pd.DataFrame, xr.Dataset, dd.DataFrame]
            The loaded dataset.
        """
        # VirtualiZarr kwargs (use_virtualizarr, virtualizarr_file,
        # virtualizarr_backend, icechunk_repo) are silently discarded here
        # and NOT forwarded to PandasDriver.
        df = self.driver.open(files, read_method=read_method, lazy=lazy, meta=meta, **kwargs)

        df = self.harmonize(df)

        # Consistently force object strings to avoid nullable string issues in Pandas/Dask
        df = force_object_strings(df)

        if as_xarray:
            return self.to_xarray(df, **kwargs)

        return df

    def harmonize(
        self, df: Union[pd.DataFrame, "dd.DataFrame"]
    ) -> Union[pd.DataFrame, "dd.DataFrame"]:
        """
        Harmonize the dataset (standard naming, dropping NaNs).

        Parameters
        ----------
        df : Union[pd.DataFrame, "dd.DataFrame"]
            Input dataframe.

        Returns
        -------
        Union[pd.DataFrame, "dd.DataFrame"]
            Harmonized dataframe.
        """
        if "latitude" in df.columns and "longitude" in df.columns:
            df = df.dropna(subset=["latitude", "longitude"])

        # Update history if attributes exist (backend-agnostic)
        df = update_history(df, "Harmonized and dropped NaN locations.")

        return super().harmonize(df)

    def to_xarray(
        self, df: Union[pd.DataFrame, "dd.DataFrame"], expand2d: bool = True, **kwargs
    ) -> xr.Dataset:
        """
        Convert the DataFrame to an xarray Dataset in UGRID convention.
        By default, returns a 2D dataset (time, node) if expand2d=True.

        Parameters
        ----------
        df : Union[pd.DataFrame, dd.DataFrame]
            Input dataframe.
        expand2d : bool, optional
            Whether to expand to 2D (time, node) structure, by default True.
        **kwargs : dict
            Additional arguments passed to ds_to_2d (e.g. pivot).

        Returns
        -------
        xr.Dataset
            The dataset in UGRID convention.
        """
        # 1. Identify backend
        try:
            import dask.dataframe as dd

            is_dask = isinstance(df, dd.DataFrame)
        except ImportError:
            is_dask = False

        # 2. Prepare DataFrame (ensure time and siteid are columns)
        if is_dask:
            temp_df = df
        else:
            temp_df = df.copy()

        for name in ["time", "siteid"]:
            try:
                names = temp_df.index.names
            except AttributeError:
                names = [temp_df.index.name]

            if name in names:
                temp_df = temp_df.reset_index()

        # 3. Handle Backends
        # Consistently force object strings for both backends to avoid nullable string issues.
        temp_df = force_object_strings(temp_df)

        if is_dask:
            # 3a. Lazy Path
            ds = xr.Dataset()
            # Exception to "No Hidden Computes": lengths=True is required by Xarray
            # to determine dimension sizes for the Dataset structure.
            for col in temp_df.columns:
                ds[col] = (("node",), temp_df[col].to_dask_array(lengths=True))
        else:
            # 3b. Eager Path
            # Consistently use 1D for both Eager and Lazy by default.
            ds = temp_df.reset_index(drop=True).to_xarray()
            if "index" in ds.dims:
                ds = ds.rename({"index": "node"})

        # Set standard coordinates
        coords = [
            c for c in ["time", "siteid", "latitude", "longitude", "elevation"] if c in ds.data_vars
        ]
        ds = ds.set_coords(coords)

        # Ensure node coordinate is a simple integer range for both
        if "node" in ds.dims:
            ds.coords["node"] = (("node",), np.arange(ds.sizes["node"]))

        # 4. Standard Path (Consistently try 2D expansion by default)
        # The user requested 2D UGRID as default.
        if expand2d:
            # We pass kwargs to allow control over pivoting (wide_fmt or pivot)
            pivot = kwargs.get("wide_fmt", kwargs.get("pivot", True))
            ds = ds_to_2d(ds, pivot=pivot, fixed_location=self.fixed_location)

        # Add UGRID metadata
        if "node" in ds.dims:
            node_coords = []
            for c in ["longitude", "latitude", "elevation"]:
                if c in ds.coords:
                    node_coords.append(c)

            if node_coords:
                ds["mesh"] = xr.DataArray(
                    data=np.int32(0),
                    attrs={
                        "cf_role": "mesh_topology",
                        "topology_dimension": 0,
                        "node_coordinates": " ".join(node_coords),
                    },
                )

            if "latitude" in ds.coords:
                ds.coords["latitude"].attrs.update(
                    {"units": "degrees_north", "standard_name": "latitude"}
                )
            if "longitude" in ds.coords:
                ds.coords["longitude"].attrs.update(
                    {"units": "degrees_east", "standard_name": "longitude"}
                )
            if "elevation" in ds.coords:
                ds.coords["elevation"].attrs.update(
                    {"units": "m", "standard_name": "height_above_mean_sea_level"}
                )

            for var in ds.data_vars:
                if "node" in ds[var].dims:
                    ds[var].attrs.update({"mesh": "mesh", "location": "node"})

        # Copy attributes from DataFrame if they exist (e.g. history).
        # Dask DataFrames don't support .attrs the same way as pandas, so
        # we guard with getattr to avoid AttributeError.
        df_attrs = getattr(df, "attrs", {}) or {}
        for k, v in df_attrs.items():
            if k not in ds.attrs:
                ds.attrs[k] = v
            elif k == "history":
                ds.attrs[k] = f"{v}\n{ds.attrs[k]}"

        # Add Global Attributes
        if "Conventions" not in ds.attrs:
            ds.attrs["Conventions"] = "CF-1.8 UGRID-1.0"
        elif "UGRID-1.0" not in ds.attrs["Conventions"]:
            ds.attrs["Conventions"] += " UGRID-1.0"

        # Update history
        ds = update_history(ds, "Converted to xarray Dataset with UGRID convention.")

        return ds

harmonize(df)

Harmonize the dataset (standard naming, dropping NaNs).

Parameters:

Name Type Description Default
df Union[DataFrame, DataFrame]

Input dataframe.

required

Returns:

Type Description
Union[DataFrame, DataFrame]

Harmonized dataframe.

Source code in monetio/readers/base.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def harmonize(
    self, df: Union[pd.DataFrame, "dd.DataFrame"]
) -> Union[pd.DataFrame, "dd.DataFrame"]:
    """
    Harmonize the dataset (standard naming, dropping NaNs).

    Parameters
    ----------
    df : Union[pd.DataFrame, "dd.DataFrame"]
        Input dataframe.

    Returns
    -------
    Union[pd.DataFrame, "dd.DataFrame"]
        Harmonized dataframe.
    """
    if "latitude" in df.columns and "longitude" in df.columns:
        df = df.dropna(subset=["latitude", "longitude"])

    # Update history if attributes exist (backend-agnostic)
    df = update_history(df, "Harmonized and dropped NaN locations.")

    return super().harmonize(df)

open_dataset(files, use_virtualizarr=False, virtualizarr_file=None, virtualizarr_backend='kerchunk', icechunk_repo=None, read_method='read_csv', as_xarray=True, lazy=False, meta=None, **kwargs)

Retrieve and load point data.

Parameters:

Name Type Description Default
files Union[str, List[str]]

File path, list of paths, or glob pattern.

required
use_virtualizarr bool

Accepted but ignored for PointReaders (VirtualiZarr only applies to gridded data).

False
virtualizarr_file str or None

Accepted but ignored for PointReaders.

None
virtualizarr_backend str

Accepted but ignored for PointReaders.

'kerchunk'
icechunk_repo str or None

Accepted but ignored for PointReaders.

None
read_method str

The pandas/dask reading method to use, by default "read_csv".

'read_csv'
as_xarray bool

If True, return an xarray.Dataset, by default True.

True
lazy bool

If True, return a dask-backed object, by default False.

False
meta pd.DataFrame, pd.Series, dict, or tuple

Dask metadata to use for lazy loading, by default None.

None
**kwargs dict

Additional arguments passed to the reader and driver.

{}

Returns:

Type Description
Union[DataFrame, Dataset, DataFrame]

The loaded dataset.

Source code in monetio/readers/base.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def open_dataset(
    self,
    files: str | list[str],
    # VirtualiZarr kwargs accepted but silently ignored for PointReaders
    use_virtualizarr: bool = False,
    virtualizarr_file: str | None = None,
    virtualizarr_backend: str = "kerchunk",
    icechunk_repo: str | None = None,
    # Standard PointReader kwargs
    read_method: str = "read_csv",
    as_xarray: bool = True,
    lazy: bool = False,
    meta: pd.DataFrame | pd.Series | dict | tuple | None = None,
    **kwargs,
) -> Union[pd.DataFrame, xr.Dataset, "dd.DataFrame"]:
    """
    Retrieve and load point data.

    Parameters
    ----------
    files : Union[str, List[str]]
        File path, list of paths, or glob pattern.
    use_virtualizarr : bool, optional
        Accepted but ignored for PointReaders (VirtualiZarr only applies to gridded data).
    virtualizarr_file : str or None, optional
        Accepted but ignored for PointReaders.
    virtualizarr_backend : str, optional
        Accepted but ignored for PointReaders.
    icechunk_repo : str or None, optional
        Accepted but ignored for PointReaders.
    read_method : str, optional
        The pandas/dask reading method to use, by default "read_csv".
    as_xarray : bool, optional
        If True, return an xarray.Dataset, by default True.
    lazy : bool, optional
        If True, return a dask-backed object, by default False.
    meta : pd.DataFrame, pd.Series, dict, or tuple, optional
        Dask metadata to use for lazy loading, by default None.
    **kwargs : dict
        Additional arguments passed to the reader and driver.

    Returns
    -------
    Union[pd.DataFrame, xr.Dataset, dd.DataFrame]
        The loaded dataset.
    """
    # VirtualiZarr kwargs (use_virtualizarr, virtualizarr_file,
    # virtualizarr_backend, icechunk_repo) are silently discarded here
    # and NOT forwarded to PandasDriver.
    df = self.driver.open(files, read_method=read_method, lazy=lazy, meta=meta, **kwargs)

    df = self.harmonize(df)

    # Consistently force object strings to avoid nullable string issues in Pandas/Dask
    df = force_object_strings(df)

    if as_xarray:
        return self.to_xarray(df, **kwargs)

    return df

to_xarray(df, expand2d=True, **kwargs)

Convert the DataFrame to an xarray Dataset in UGRID convention. By default, returns a 2D dataset (time, node) if expand2d=True.

Parameters:

Name Type Description Default
df Union[DataFrame, DataFrame]

Input dataframe.

required
expand2d bool

Whether to expand to 2D (time, node) structure, by default True.

True
**kwargs dict

Additional arguments passed to ds_to_2d (e.g. pivot).

{}

Returns:

Type Description
Dataset

The dataset in UGRID convention.

Source code in monetio/readers/base.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
def to_xarray(
    self, df: Union[pd.DataFrame, "dd.DataFrame"], expand2d: bool = True, **kwargs
) -> xr.Dataset:
    """
    Convert the DataFrame to an xarray Dataset in UGRID convention.
    By default, returns a 2D dataset (time, node) if expand2d=True.

    Parameters
    ----------
    df : Union[pd.DataFrame, dd.DataFrame]
        Input dataframe.
    expand2d : bool, optional
        Whether to expand to 2D (time, node) structure, by default True.
    **kwargs : dict
        Additional arguments passed to ds_to_2d (e.g. pivot).

    Returns
    -------
    xr.Dataset
        The dataset in UGRID convention.
    """
    # 1. Identify backend
    try:
        import dask.dataframe as dd

        is_dask = isinstance(df, dd.DataFrame)
    except ImportError:
        is_dask = False

    # 2. Prepare DataFrame (ensure time and siteid are columns)
    if is_dask:
        temp_df = df
    else:
        temp_df = df.copy()

    for name in ["time", "siteid"]:
        try:
            names = temp_df.index.names
        except AttributeError:
            names = [temp_df.index.name]

        if name in names:
            temp_df = temp_df.reset_index()

    # 3. Handle Backends
    # Consistently force object strings for both backends to avoid nullable string issues.
    temp_df = force_object_strings(temp_df)

    if is_dask:
        # 3a. Lazy Path
        ds = xr.Dataset()
        # Exception to "No Hidden Computes": lengths=True is required by Xarray
        # to determine dimension sizes for the Dataset structure.
        for col in temp_df.columns:
            ds[col] = (("node",), temp_df[col].to_dask_array(lengths=True))
    else:
        # 3b. Eager Path
        # Consistently use 1D for both Eager and Lazy by default.
        ds = temp_df.reset_index(drop=True).to_xarray()
        if "index" in ds.dims:
            ds = ds.rename({"index": "node"})

    # Set standard coordinates
    coords = [
        c for c in ["time", "siteid", "latitude", "longitude", "elevation"] if c in ds.data_vars
    ]
    ds = ds.set_coords(coords)

    # Ensure node coordinate is a simple integer range for both
    if "node" in ds.dims:
        ds.coords["node"] = (("node",), np.arange(ds.sizes["node"]))

    # 4. Standard Path (Consistently try 2D expansion by default)
    # The user requested 2D UGRID as default.
    if expand2d:
        # We pass kwargs to allow control over pivoting (wide_fmt or pivot)
        pivot = kwargs.get("wide_fmt", kwargs.get("pivot", True))
        ds = ds_to_2d(ds, pivot=pivot, fixed_location=self.fixed_location)

    # Add UGRID metadata
    if "node" in ds.dims:
        node_coords = []
        for c in ["longitude", "latitude", "elevation"]:
            if c in ds.coords:
                node_coords.append(c)

        if node_coords:
            ds["mesh"] = xr.DataArray(
                data=np.int32(0),
                attrs={
                    "cf_role": "mesh_topology",
                    "topology_dimension": 0,
                    "node_coordinates": " ".join(node_coords),
                },
            )

        if "latitude" in ds.coords:
            ds.coords["latitude"].attrs.update(
                {"units": "degrees_north", "standard_name": "latitude"}
            )
        if "longitude" in ds.coords:
            ds.coords["longitude"].attrs.update(
                {"units": "degrees_east", "standard_name": "longitude"}
            )
        if "elevation" in ds.coords:
            ds.coords["elevation"].attrs.update(
                {"units": "m", "standard_name": "height_above_mean_sea_level"}
            )

        for var in ds.data_vars:
            if "node" in ds[var].dims:
                ds[var].attrs.update({"mesh": "mesh", "location": "node"})

    # Copy attributes from DataFrame if they exist (e.g. history).
    # Dask DataFrames don't support .attrs the same way as pandas, so
    # we guard with getattr to avoid AttributeError.
    df_attrs = getattr(df, "attrs", {}) or {}
    for k, v in df_attrs.items():
        if k not in ds.attrs:
            ds.attrs[k] = v
        elif k == "history":
            ds.attrs[k] = f"{v}\n{ds.attrs[k]}"

    # Add Global Attributes
    if "Conventions" not in ds.attrs:
        ds.attrs["Conventions"] = "CF-1.8 UGRID-1.0"
    elif "UGRID-1.0" not in ds.attrs["Conventions"]:
        ds.attrs["Conventions"] += " UGRID-1.0"

    # Update history
    ds = update_history(ds, "Converted to xarray Dataset with UGRID convention.")

    return ds

add_lazy_diagnostic(ds, name, spec, aliases=None)

Adds a lazy diagnostic variable to the dataset if constituent variables exist.

Parameters:

Name Type Description Default
ds Dataset

Input dataset.

required
name str

Name of the diagnostic variable.

required
spec DiagnosticSpec

Specification for the diagnostic.

required
aliases Dict[str, List[str]]

Mapping of diagnostic names to potential existing variables in the file to use instead of calculating from constituents.

None

Returns:

Type Description
Dataset

Dataset with diagnostic added if possible.

Source code in monetio/readers/base.py
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
def add_lazy_diagnostic(
    ds: xr.Dataset,
    name: str,
    spec: DiagnosticSpec,
    aliases: dict[str, list[str]] | None = None,
) -> xr.Dataset:
    """
    Adds a lazy diagnostic variable to the dataset if constituent variables exist.

    Parameters
    ----------
    ds : xarray.Dataset
        Input dataset.
    name : str
        Name of the diagnostic variable.
    spec : DiagnosticSpec
        Specification for the diagnostic.
    aliases : Dict[str, List[str]], optional
        Mapping of diagnostic names to potential existing variables in the file
        to use instead of calculating from constituents.

    Returns
    -------
    xarray.Dataset
        Dataset with diagnostic added if possible.
    """
    # 1. Check if name already exists as a data variable
    if name in ds.data_vars:
        return ds

    # 2. Check for pre-calculated summary variables to prevent regressions
    # Comprehensive default aliases for common model outputs
    default_aliases = {
        "PM25": ["PM25_TOT", "PM2_5", "PM2_5_DRY"],
        "PM10": ["PMC_TOT", "PM10", "PM_TOT", "PM10_DRY", "PM10_TOT"],
        "NOx": ["NOX"],
        "NOy": ["NOY"],
        "O3": ["OZONE"],
    }
    if aliases is not None:
        # Merge user aliases with defaults
        for k, v in aliases.items():
            if k in default_aliases:
                default_aliases[k] = list(set(default_aliases[k] + v))
            else:
                default_aliases[k] = v

    for alias in default_aliases.get(name, []):
        if alias in ds.data_vars:
            ds[name] = ds[alias].copy()
            ds[name].attrs.update(
                {"units": spec.units, "name": spec.name, "long_name": spec.long_name}
            )
            # Update history
            ds = update_history(ds, f"Added lazy diagnostic: {name} (using alias {alias}).")
            return ds

    # 3. Identify constituent variables available in the dataset
    available_vars = [v for v in spec.variables if v in ds.data_vars]
    if not available_vars:
        return ds

    # If weights are provided, they must match the full variable list in spec
    if spec.weights is not None:
        weights_map = dict(zip(spec.variables, spec.weights))
        weights = [weights_map[v] for v in available_vars]
    else:
        weights = [1.0] * len(available_vars)

    # 4. Compute lazy sum with unit synchronization
    with xr.set_options(keep_attrs=True):
        # Use first variable as base
        v0 = available_vars[0]
        new_var = ds[v0] * weights[0]
        base_units = ds[v0].attrs.get("units", "").lower()

        for i in range(1, len(available_vars)):
            v = available_vars[i]
            v_var = ds[v]
            v_units = v_var.attrs.get("units", "").lower()

            # Unit synchronization (e.g. ppmV vs ppbV)
            if v_units != base_units:
                if "ppm" in v_units and "ppb" in base_units:
                    v_var = v_var * 1000.0
                elif "ppb" in v_units and "ppm" in base_units:
                    v_var = v_var / 1000.0

            new_var = new_var + v_var * weights[i]

    # Inherit units from constituent variables if available, otherwise use spec
    units = ds[v0].attrs.get("units", spec.units)

    ds[name] = new_var.assign_attrs(
        {"units": units, "name": spec.name, "long_name": spec.long_name}
    )

    # Update history
    ds = update_history(ds, f"Added lazy diagnostic: {name} (sum of {', '.join(available_vars)}).")

    return ds

register_reader(name)

Decorator to register a reader class.

Source code in monetio/readers/base.py
32
33
34
35
36
37
38
39
def register_reader(name):
    """Decorator to register a reader class."""

    def _register(cls):
        READER_REGISTRY[name] = cls
        return cls

    return _register