Skip to content

API Reference

This page provides a high-level overview of the most commonly used MONETIO functions. For a complete reference, see the Code Reference.

Core API

The primary way to load data in MONETIO is the load function.

Universal load function.

Usage: ds = monetio.load("cmaq", files="/path/to/data*.nc") df = monetio.load("airnow", files=["2023-01-01", "2023-01-02"])

Available sources: Models: cmaq, camx, chimere, hysplit, hytraj, icap_mme, ncep_grib, pardump, raqms, ufs, wrfchem, grib2, gfs, gefs, gdas, rrfs Obs: airnow, aeronet, aqs, cems, crn, eprofile, improve, ish, ish_lite, nadp, ndacc, ndbc, openaq, openaq_v2, openaq_aws, pams, pandora, skynet, solrad, surfrad Profile: actris, earlinet, geoms, gml_ozonesonde, iagos, icartt, igra2, mplnet, tolnet, umbc_aerosol Sat: goes, merra2, modis_l2, modis_ornl, mopitt, nasa_modis, nesdis_edr_viirs, nesdis_eps_viirs, nesdis_frp, nesdis_viirs_jrr, omps, omps_nadir, tempo, tropomi, viirs_jrr

Source code in monetio/__init__.py
 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
def load(source: str, files=None, **kwargs):
    """
    Universal load function.

    Usage:
        ds = monetio.load("cmaq", files="/path/to/data*.nc")
        df = monetio.load("airnow", files=["2023-01-01", "2023-01-02"])

    Available sources:
        Models: cmaq, camx, chimere, hysplit, hytraj, icap_mme, ncep_grib, pardump, raqms, ufs, wrfchem, grib2, gfs, gefs, gdas, rrfs
        Obs: airnow, aeronet, aqs, cems, crn, eprofile, improve, ish, ish_lite, nadp, ndacc, ndbc, openaq, openaq_v2, openaq_aws, pams, pandora, skynet, solrad, surfrad
        Profile: actris, earlinet, geoms, gml_ozonesonde, iagos, icartt, igra2, mplnet, tolnet, umbc_aerosol
        Sat: goes, merra2, modis_l2, modis_ornl, mopitt, nasa_modis, nesdis_edr_viirs, nesdis_eps_viirs, nesdis_frp, nesdis_viirs_jrr, omps, omps_nadir, tempo, tropomi, viirs_jrr
    """
    from .readers.base import READER_REGISTRY

    if source not in READER_REGISTRY:
        if source in _READER_MODULES:
            # Lazy import
            importlib.import_module(_READER_MODULES[source], package="monetio")
        else:
            raise ValueError(
                f"Unknown source '{source}'. Available: {list(_READER_MODULES.keys())}"
            )

    if source not in READER_REGISTRY:
        # Should be registered by now if module was valid
        raise RuntimeError(f"Source '{source}' found in lazy index but failed to register itself.")

    # Instantiate the reader class and open data
    reader_cls = READER_REGISTRY[source]
    reader = reader_cls()

    return reader.open_dataset(files=files, **kwargs)

Virtualization

Virtualization is supported via monetio.load with use_virtualizarr=True or via the virtualize function.

Pre-process files into a virtual reference (e.g., Kerchunk JSON or Icechunk repo).

Usage: monetio.virtualize("merra2", files="data/*.nc4", output="merra2_ref.json")

Parameters:

Name Type Description Default
source str

The reader source ID (e.g., "merra2", "gfs").

required
files str or list of str

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

None
output str

Path to save the output reference (required for 'kerchunk' backend).

None
backend str

The virtualization backend. Must be "kerchunk" (default) or "icechunk".

'kerchunk'
**kwargs dict

Additional arguments passed to the reader and driver.

{}
Source code in monetio/__init__.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def virtualize(source: str, files=None, output: str = None, backend: str = "kerchunk", **kwargs):
    """
    Pre-process files into a virtual reference (e.g., Kerchunk JSON or Icechunk repo).

    Usage:
        monetio.virtualize("merra2", files="data/*.nc4", output="merra2_ref.json")

    Parameters
    ----------
    source : str
        The reader source ID (e.g., "merra2", "gfs").
    files : str or list of str, optional
        File path(s) or glob pattern(s).
    output : str, optional
        Path to save the output reference (required for 'kerchunk' backend).
    backend : str, optional
        The virtualization backend. Must be "kerchunk" (default) or "icechunk".
    **kwargs : dict
        Additional arguments passed to the reader and driver.
    """
    if backend == "kerchunk" and output is None:
        raise ValueError("The 'output' parameter is required for the 'kerchunk' backend.")

    return load(
        source,
        files=files,
        use_virtualizarr=True,
        virtualizarr_file=output,
        virtualizarr_backend=backend,
        **kwargs,
    )

Utility Functions

Rename latitude/longitude to 'lat'/'lon'.

Parameters:

Name Type Description Default
ds Dataset
required

Returns:

Type Description
Dataset

Dataset with possibly renamed latitude/longitude.

Source code in monetio/__init__.py
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
def rename_latlon(ds):
    """Rename latitude/longitude to ``'lat'``/``'lon'``.

    Parameters
    ----------
    ds : xarray.Dataset

    Returns
    -------
    xarray.Dataset
        Dataset with possibly renamed latitude/longitude.
    """
    if "latitude" in ds.coords:
        return ds.rename({"latitude": "lat", "longitude": "lon"})
    elif "Latitude" in ds.coords:
        return ds.rename({"Latitude": "lat", "Longitude": "lon"})
    elif "Lat" in ds.coords:
        return ds.rename({"Lat": "lat", "Lon": "lon"})
    else:
        return ds

Rename latitude/longitude to 'latitude'/'longitude'.

Parameters:

Name Type Description Default
ds Dataset
required

Returns:

Type Description
Dataset

Dataset with possibly renamed latitude/longitude.

See Also

rename_latlon : renames to 'lat'/'lon' instead

Source code in monetio/__init__.py
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
def rename_to_monet_latlon(ds):
    """Rename latitude/longitude to ``'latitude'``/``'longitude'``.

    Parameters
    ----------
    ds : xarray.Dataset

    Returns
    -------
    xarray.Dataset
        Dataset with possibly renamed latitude/longitude.

    See Also
    --------
    rename_latlon : renames to ``'lat'``/``'lon'`` instead
    """
    if "lat" in ds.coords:
        return ds.rename({"lat": "latitude", "lon": "longitude"})
    elif "Latitude" in ds.coords:
        return ds.rename({"Latitude": "latitude", "Longitude": "longitude"})
    elif "Lat" in ds.coords:
        return ds.rename({"Lat": "latitude", "Lon": "longitude"})
    elif "grid_lat" in ds.coords:
        return ds.rename({"grid_lat": "latitude", "grid_lon": "longitude"})
    else:
        return ds

Apply :func:coards_to_netcdf if latlon2d is False.

Parameters:

Name Type Description Default
ds Dataset
required
lat_name str

Current latitude and longitude names in ds.

'lat'
lon_name str

Current latitude and longitude names in ds.

'lat'
latlon2d bool

If not provided, the value will be detected by examining .ndim of the latitude variable.

None

Returns:

Type Description
Dataset
Source code in monetio/__init__.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
def dataset_to_monet(ds, *, lat_name="lat", lon_name="lon", latlon2d=None):
    """Apply :func:`coards_to_netcdf` if `latlon2d` is False.

    Parameters
    ----------
    ds : xarray.Dataset
    lat_name, lon_name : str
        Current latitude and longitude names in `ds`.
    latlon2d : bool, optional
        If not provided, the value will be detected by examining ``.ndim``
        of the latitude variable.

    Returns
    -------
    xarray.Dataset
    """
    if latlon2d is None:
        ndim_lat = ds[lat_name].ndim
        assert ndim_lat <= 2
        latlon2d = ndim_lat == 2
    # TODO: apply rename_to_monet_latlon ?
    if latlon2d is False:
        ds = coards_to_netcdf(ds, lat_name=lat_name, lon_name=lon_name)
    return ds

Assign 2-D latitude/longitude grid from 1-D latitude/longitude variables, setting 'x' and 'y' as 1-D zero-based index arrays.

Also normalizes the latitude/longitude names to 'latitude'/'longitude', with dimensions ('y', 'x').

.. note:: The name is a reference to the COARDS conventions.

Parameters:

Name Type Description Default
ds Dataset
required
lat_name str

Current latitude and longitude names in ds.

'lat'
lon_name str

Current latitude and longitude names in ds.

'lat'

Returns:

Type Description
Dataset
Source code in monetio/__init__.py
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
def coards_to_netcdf(ds, *, lat_name="lat", lon_name="lon"):
    """Assign 2-D latitude/longitude grid from 1-D latitude/longitude variables,
    setting ``'x'`` and ``'y'`` as 1-D zero-based index arrays.

    Also normalizes the latitude/longitude names to ``'latitude'``/``'longitude'``,
    with dimensions ``('y', 'x')``.

    .. note::
       The name is a reference to the COARDS conventions.

    Parameters
    ----------
    ds : xarray.Dataset
    lat_name, lon_name : str
        Current latitude and longitude names in `ds`.

    Returns
    -------
    xarray.Dataset
    """
    from numpy import arange, meshgrid

    lon = ds[lon_name]
    lat = ds[lat_name]
    assert lon.ndim == lat.ndim == 1
    lons, lats = meshgrid(lon, lat)
    x = arange(len(lon))
    y = arange(len(lat))
    ds = ds.rename({lon_name: "x", lat_name: "y"})
    ds.coords["longitude"] = (("y", "x"), lons)
    ds.coords["latitude"] = (("y", "x"), lats)
    ds["x"] = x
    ds["y"] = y
    ds = ds.set_coords(["latitude", "longitude"])
    return ds

Readers Base Classes

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

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)

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

Helper class to manage file path expansion (Local + S3 + HTTP).

Source code in monetio/readers/drivers.py
 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
123
124
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
class FileUtility:
    """
    Helper class to manage file path expansion (Local + S3 + HTTP).
    """

    @staticmethod
    def get_fs(path: str):
        """
        Returns the correct filesystem (local, s3, or http) based on the protocol.
        """
        if path.startswith("s3://"):
            # anon=True means public bucket. Use anon=False to use your AWS credentials.
            return fsspec.filesystem("s3", anon=True)
        elif path.startswith("http://") or path.startswith("https://"):
            return fsspec.filesystem("http")
        elif path.startswith("ftp://"):
            return fsspec.filesystem("ftp")
        return fsspec.filesystem("file")

    @staticmethod
    def expand_paths(path_input: str | list[str], fs=None) -> list[str]:
        """
        Converts a string (with wildcards), a single path, or a list of paths
        into a guaranteed list of file paths/objects.
        """
        # Convert Path objects to string
        if hasattr(path_input, "__fspath__"):
            path_input = str(path_input)

        # Case 1: It's a list already
        if isinstance(path_input, list):
            return sorted([str(p) if hasattr(p, "__fspath__") else p for p in path_input])

        # Case 2: It's a single string (S3 or Local)
        if isinstance(path_input, str):
            # If no specific filesystem provided, guess it from the path
            if fs is None:
                fs = FileUtility.get_fs(path_input)

            # Use fsspec/s3fs to glob wildcards (works for s3://bucket/data/*.nc too!)
            if any(char in path_input for char in ["*", "?"]):
                # HTTP globbing is generally not supported by fsspec without specific implementation
                # For S3/Local it works.
                if path_input.startswith("http"):
                    # Fallback: treat as single file if glob chars present but http (unlikely to work)
                    pass

                files = sorted(fs.glob(path_input))
                # fs.glob usually returns paths without the protocol (e.g. 'bucket/file.nc')
                if path_input.startswith("s3://") and files and not files[0].startswith("s3://"):
                    files = [f"s3://{f}" for f in files]

                if not files:
                    raise FileNotFoundError(f"No files found matching pattern: {path_input}")
                return files
            else:
                # It is a specific single file
                if not path_input.startswith("http") and not fs.exists(path_input):
                    raise FileNotFoundError(f"File not found: {path_input}")
                return [path_input]

        raise TypeError(f"Invalid path type: {type(path_input)}. Must be str or list.")

expand_paths(path_input, fs=None) staticmethod

Converts a string (with wildcards), a single path, or a list of paths into a guaranteed list of file paths/objects.

Source code in monetio/readers/drivers.py
116
117
118
119
120
121
122
123
124
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
@staticmethod
def expand_paths(path_input: str | list[str], fs=None) -> list[str]:
    """
    Converts a string (with wildcards), a single path, or a list of paths
    into a guaranteed list of file paths/objects.
    """
    # Convert Path objects to string
    if hasattr(path_input, "__fspath__"):
        path_input = str(path_input)

    # Case 1: It's a list already
    if isinstance(path_input, list):
        return sorted([str(p) if hasattr(p, "__fspath__") else p for p in path_input])

    # Case 2: It's a single string (S3 or Local)
    if isinstance(path_input, str):
        # If no specific filesystem provided, guess it from the path
        if fs is None:
            fs = FileUtility.get_fs(path_input)

        # Use fsspec/s3fs to glob wildcards (works for s3://bucket/data/*.nc too!)
        if any(char in path_input for char in ["*", "?"]):
            # HTTP globbing is generally not supported by fsspec without specific implementation
            # For S3/Local it works.
            if path_input.startswith("http"):
                # Fallback: treat as single file if glob chars present but http (unlikely to work)
                pass

            files = sorted(fs.glob(path_input))
            # fs.glob usually returns paths without the protocol (e.g. 'bucket/file.nc')
            if path_input.startswith("s3://") and files and not files[0].startswith("s3://"):
                files = [f"s3://{f}" for f in files]

            if not files:
                raise FileNotFoundError(f"No files found matching pattern: {path_input}")
            return files
        else:
            # It is a specific single file
            if not path_input.startswith("http") and not fs.exists(path_input):
                raise FileNotFoundError(f"File not found: {path_input}")
            return [path_input]

    raise TypeError(f"Invalid path type: {type(path_input)}. Must be str or list.")

get_fs(path) staticmethod

Returns the correct filesystem (local, s3, or http) based on the protocol.

Source code in monetio/readers/drivers.py
102
103
104
105
106
107
108
109
110
111
112
113
114
@staticmethod
def get_fs(path: str):
    """
    Returns the correct filesystem (local, s3, or http) based on the protocol.
    """
    if path.startswith("s3://"):
        # anon=True means public bucket. Use anon=False to use your AWS credentials.
        return fsspec.filesystem("s3", anon=True)
    elif path.startswith("http://") or path.startswith("https://"):
        return fsspec.filesystem("http")
    elif path.startswith("ftp://"):
        return fsspec.filesystem("ftp")
    return fsspec.filesystem("file")