Skip to content

ndacc

NDACC Reader.

NDACCReader

Bases: GEOMSReader

NDACC (Network for the Detection of Atmospheric Composition Change) Reader. NDACC data follows the GEOMS (Generic Earth Observation Metadata Standard).

Source code in monetio/readers/ndacc.py
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 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
 68
 69
 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
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
@register_reader("ndacc")
class NDACCReader(GEOMSReader):
    """
    NDACC (Network for the Detection of Atmospheric Composition Change) Reader.
    NDACC data follows the GEOMS (Generic Earth Observation Metadata Standard).
    """

    def open_dataset(
        self,
        files: str | list[str] | None = None,
        dates: pd.DatetimeIndex | list[datetime.datetime] | datetime.datetime | str | None = None,
        siteid: str | None = None,
        instrument: str | None = None,
        as_xarray: bool = True,
        **kwargs: Any,
    ) -> xr.Dataset | pd.DataFrame:
        """
        Retrieve and load NDACC data.

        Parameters
        ----------
        files : Union[str, List[str]], optional
            File path, list of paths, or glob pattern.
        dates : Union[pd.DatetimeIndex, List[datetime], datetime, str], optional
            Dates to retrieve if files are not provided.
        siteid : str, optional
            Specific NDACC site folder name (e.g. 'mauna.loa.hi').
        instrument : str, optional
            Specific instrument name (e.g. 'lidar', 'ftir', 'uvvis.doas').
        as_xarray : bool, optional
            Whether to return an xarray.Dataset, by default True.
        **kwargs : Any
            Additional arguments passed to the driver.

        Returns
        -------
        Union[xr.Dataset, pd.DataFrame]
            The processed NDACC dataset.
        """
        if files is None:
            if dates is None:
                raise ValueError("Must provide either 'files' or 'dates'.")
            files = self.build_urls(dates, siteid=siteid, instrument=instrument, **kwargs)

        if not files:
            if as_xarray:
                return xr.Dataset()
            return pd.DataFrame()

        ds = super().open_dataset(files, **kwargs)

        if not as_xarray:
            return ds.to_dataframe().reset_index()

        # Update history
        ds = update_history(ds, "Read NDACC data using standardized preprocessing.")

        return ds

    def build_urls(
        self,
        dates: pd.DatetimeIndex | list[datetime.datetime] | datetime.datetime | str,
        siteid: str | None = None,
        instrument: str | None = None,
        **kwargs: Any,
    ) -> list[str]:
        """
        Construct NDACC URLs.
        Note: NDACC data is primarily hosted on the NASA LaRC DHF server.

        Parameters
        ----------
        dates : Union[pd.DatetimeIndex, List[datetime], datetime, str]
            Dates to build URLs for.
        siteid : str, optional
            Specific site folder name (e.g. 'mauna.loa.hi').
        instrument : str, optional
            Specific instrument name (e.g. 'ftir').

        Returns
        -------
        List[str]
            List of matching NDACC URLs.
        """
        if siteid is None or instrument is None:
            import warnings

            warnings.warn(
                "NDACC retrieval requires 'siteid' (folder name) and 'instrument'. "
                "See https://www-air.larc.nasa.gov/pub/NDACC/PUBLIC/stations/ for options."
            )
            return []

        dates = pd.DatetimeIndex(np.atleast_1d(pd.to_datetime(dates)))

        # NDACC Public Archive: https://www-air.larc.nasa.gov/pub/NDACC/PUBLIC/stations/
        base_url = f"https://www-air.larc.nasa.gov/pub/NDACC/PUBLIC/stations/{siteid}/{instrument}"

        # We use fsspec to list files in the directory
        import fsspec

        try:
            fs = fsspec.filesystem("https")
            all_files = fs.ls(base_url)

            # Filter by dates in filename (usually YYYYMMDD or similar)
            # Filenames: h2o_ftir_maunaloa_20230101t120000z_001.h5
            urls = []
            for f in all_files:
                if not f.endswith((".h5", ".hdf", ".hdf5", ".nc")):
                    continue

                # Check if any requested date matches the filename
                # This is a broad match; can be refined.
                f_lower = f.lower()
                for d in dates:
                    d_str = d.strftime("%Y%m%d")
                    if d_str in f_lower:
                        urls.append(f if f.startswith("http") else f"{base_url}/{f.split('/')[-1]}")
                        break
            return urls
        except Exception as e:
            import warnings

            warnings.warn(f"Failed to list NDACC files at {base_url}: {e}")
            return []

    def harmonize(self, ds: xr.Dataset) -> xr.Dataset:
        """
        Standardize NDACC/GEOMS variable names.

        Parameters
        ----------
        ds : xr.Dataset
            Input dataset.

        Returns
        -------
        xr.Dataset
            Harmonized dataset.
        """
        # Call GEOMS harmonization first
        ds = super().harmonize(ds)

        # NDACC-specific additions: map GEOMS names to MONETIO names
        rename_dict = {
            "o3_mixing_ratio_volume": "ozone",
            "co_mixing_ratio_volume": "carbon_monoxide",
            "no2_mixing_ratio_volume": "nitrogen_dioxide",
            "no_mixing_ratio_volume": "nitrogen_monoxide",
            "ch4_mixing_ratio_volume": "methane",
        }

        actual_rename = {}
        for k, v in rename_dict.items():
            if k in ds.variables and v not in ds.variables:
                actual_rename[k] = v

        if actual_rename:
            ds = ds.rename(actual_rename)

        return ds

build_urls(dates, siteid=None, instrument=None, **kwargs)

Construct NDACC URLs. Note: NDACC data is primarily hosted on the NASA LaRC DHF server.

Parameters:

Name Type Description Default
dates Union[DatetimeIndex, List[datetime], datetime, str]

Dates to build URLs for.

required
siteid str

Specific site folder name (e.g. 'mauna.loa.hi').

None
instrument str

Specific instrument name (e.g. 'ftir').

None

Returns:

Type Description
List[str]

List of matching NDACC URLs.

Source code in monetio/readers/ndacc.py
 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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def build_urls(
    self,
    dates: pd.DatetimeIndex | list[datetime.datetime] | datetime.datetime | str,
    siteid: str | None = None,
    instrument: str | None = None,
    **kwargs: Any,
) -> list[str]:
    """
    Construct NDACC URLs.
    Note: NDACC data is primarily hosted on the NASA LaRC DHF server.

    Parameters
    ----------
    dates : Union[pd.DatetimeIndex, List[datetime], datetime, str]
        Dates to build URLs for.
    siteid : str, optional
        Specific site folder name (e.g. 'mauna.loa.hi').
    instrument : str, optional
        Specific instrument name (e.g. 'ftir').

    Returns
    -------
    List[str]
        List of matching NDACC URLs.
    """
    if siteid is None or instrument is None:
        import warnings

        warnings.warn(
            "NDACC retrieval requires 'siteid' (folder name) and 'instrument'. "
            "See https://www-air.larc.nasa.gov/pub/NDACC/PUBLIC/stations/ for options."
        )
        return []

    dates = pd.DatetimeIndex(np.atleast_1d(pd.to_datetime(dates)))

    # NDACC Public Archive: https://www-air.larc.nasa.gov/pub/NDACC/PUBLIC/stations/
    base_url = f"https://www-air.larc.nasa.gov/pub/NDACC/PUBLIC/stations/{siteid}/{instrument}"

    # We use fsspec to list files in the directory
    import fsspec

    try:
        fs = fsspec.filesystem("https")
        all_files = fs.ls(base_url)

        # Filter by dates in filename (usually YYYYMMDD or similar)
        # Filenames: h2o_ftir_maunaloa_20230101t120000z_001.h5
        urls = []
        for f in all_files:
            if not f.endswith((".h5", ".hdf", ".hdf5", ".nc")):
                continue

            # Check if any requested date matches the filename
            # This is a broad match; can be refined.
            f_lower = f.lower()
            for d in dates:
                d_str = d.strftime("%Y%m%d")
                if d_str in f_lower:
                    urls.append(f if f.startswith("http") else f"{base_url}/{f.split('/')[-1]}")
                    break
        return urls
    except Exception as e:
        import warnings

        warnings.warn(f"Failed to list NDACC files at {base_url}: {e}")
        return []

harmonize(ds)

Standardize NDACC/GEOMS variable names.

Parameters:

Name Type Description Default
ds Dataset

Input dataset.

required

Returns:

Type Description
Dataset

Harmonized dataset.

Source code in monetio/readers/ndacc.py
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
def harmonize(self, ds: xr.Dataset) -> xr.Dataset:
    """
    Standardize NDACC/GEOMS variable names.

    Parameters
    ----------
    ds : xr.Dataset
        Input dataset.

    Returns
    -------
    xr.Dataset
        Harmonized dataset.
    """
    # Call GEOMS harmonization first
    ds = super().harmonize(ds)

    # NDACC-specific additions: map GEOMS names to MONETIO names
    rename_dict = {
        "o3_mixing_ratio_volume": "ozone",
        "co_mixing_ratio_volume": "carbon_monoxide",
        "no2_mixing_ratio_volume": "nitrogen_dioxide",
        "no_mixing_ratio_volume": "nitrogen_monoxide",
        "ch4_mixing_ratio_volume": "methane",
    }

    actual_rename = {}
    for k, v in rename_dict.items():
        if k in ds.variables and v not in ds.variables:
            actual_rename[k] = v

    if actual_rename:
        ds = ds.rename(actual_rename)

    return ds

open_dataset(files=None, dates=None, siteid=None, instrument=None, as_xarray=True, **kwargs)

Retrieve and load NDACC data.

Parameters:

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

File path, list of paths, or glob pattern.

None
dates Union[DatetimeIndex, List[datetime], datetime, str]

Dates to retrieve if files are not provided.

None
siteid str

Specific NDACC site folder name (e.g. 'mauna.loa.hi').

None
instrument str

Specific instrument name (e.g. 'lidar', 'ftir', 'uvvis.doas').

None
as_xarray bool

Whether to return an xarray.Dataset, by default True.

True
**kwargs Any

Additional arguments passed to the driver.

{}

Returns:

Type Description
Union[Dataset, DataFrame]

The processed NDACC dataset.

Source code in monetio/readers/ndacc.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
68
69
70
71
72
73
74
75
76
77
def open_dataset(
    self,
    files: str | list[str] | None = None,
    dates: pd.DatetimeIndex | list[datetime.datetime] | datetime.datetime | str | None = None,
    siteid: str | None = None,
    instrument: str | None = None,
    as_xarray: bool = True,
    **kwargs: Any,
) -> xr.Dataset | pd.DataFrame:
    """
    Retrieve and load NDACC data.

    Parameters
    ----------
    files : Union[str, List[str]], optional
        File path, list of paths, or glob pattern.
    dates : Union[pd.DatetimeIndex, List[datetime], datetime, str], optional
        Dates to retrieve if files are not provided.
    siteid : str, optional
        Specific NDACC site folder name (e.g. 'mauna.loa.hi').
    instrument : str, optional
        Specific instrument name (e.g. 'lidar', 'ftir', 'uvvis.doas').
    as_xarray : bool, optional
        Whether to return an xarray.Dataset, by default True.
    **kwargs : Any
        Additional arguments passed to the driver.

    Returns
    -------
    Union[xr.Dataset, pd.DataFrame]
        The processed NDACC dataset.
    """
    if files is None:
        if dates is None:
            raise ValueError("Must provide either 'files' or 'dates'.")
        files = self.build_urls(dates, siteid=siteid, instrument=instrument, **kwargs)

    if not files:
        if as_xarray:
            return xr.Dataset()
        return pd.DataFrame()

    ds = super().open_dataset(files, **kwargs)

    if not as_xarray:
        return ds.to_dataframe().reset_index()

    # Update history
    ds = update_history(ds, "Read NDACC data using standardized preprocessing.")

    return ds