Skip to content

pandora

Pandora Reader.

PandoraReader

Bases: GEOMSReader

Pandora (Pandonia Global Network) Reader. Pandora data follows the GEOMS (Generic Earth Observation Metadata Standard).

Source code in monetio/readers/pandora.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
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
@register_reader("pandora")
class PandoraReader(GEOMSReader):
    """
    Pandora (Pandonia Global Network) Reader.
    Pandora 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,
        product: str | None = "no2",
        as_xarray: bool = True,
        **kwargs: Any,
    ) -> xr.Dataset | pd.DataFrame:
        """
        Retrieve and load Pandora 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 Pandora site name (e.g. 'BoulderCO').
        instrument : str, optional
            Specific instrument name (e.g. 'Pandora57s1').
        product : str, optional
            Product type (e.g. 'no2', 'o3', 'h2co', 'so2'), by default 'no2'.
        as_xarray : bool, optional
            Whether to return an xarray.Dataset, by default True.
        **kwargs : Any
            Additional arguments passed to the driver.

        Returns
        -------
        xr.Dataset | pd.DataFrame
            The processed Pandora 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, product=product, **kwargs
            )

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

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

        # Apply harmonization explicitly as GEOMSReader.open_dataset calls geoms_preprocess
        # but doesn't call a reader-specific harmonize method from the base class properly
        # if not overridden in a specific way.
        ds = self.harmonize(ds)

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

        # Update history
        ds = update_history(ds, "Read Pandora 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,
        product: str | None = "no2",
        **kwargs: Any,
    ) -> list[str]:
        """
        Construct Pandora URLs.
        Note: Pandora data is hosted on https://data.pandonia-global-network.org/

        Parameters
        ----------
        dates : Union[pd.DatetimeIndex, List[datetime], datetime, str]
            Dates to build URLs for.
        siteid : str, optional
            Specific site folder name (e.g. 'BoulderCO').
        instrument : str, optional
            Specific instrument name (e.g. 'Pandora57s1').
        product : str, optional
            Product type (e.g. 'no2', 'o3', 'h2co', 'so2'), by default 'no2'.

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

            warnings.warn(
                "Pandora retrieval requires 'siteid' (folder name) and 'instrument'. "
                "See https://data.pandonia-global-network.org/ for options."
            )
            return []

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

        # PGN Archive: https://data.pandonia-global-network.org/{site}/{instrument}/L2_geoms/
        base_url = f"https://data.pandonia-global-network.org/{siteid}/{instrument}/L2_geoms"

        import fsspec

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

            urls = []
            for f in all_files:
                if not f.endswith(".h5"):
                    continue

                f_lower = f.lower()
                if product and f"{product.lower()}_" not in f_lower:
                    continue

                # Pandora filenames contain start and end times:
                # groundbased_uvvis.doas.directsun.no2_noaa.esrl057_rd.rnvs3.1.8_boulder.co_20180430t232018z_20221222t223120z_001.h5
                # Extract dates from filename
                parts = f_lower.split("_")
                try:
                    # Usually the last two parts before .h5 are dates
                    start_str = parts[-3].split("t")[0]
                    end_str = parts[-2].split("t")[0]

                    f_start = pd.to_datetime(start_str, format="%Y%m%d")
                    f_end = pd.to_datetime(end_str, format="%Y%m%d")

                    for d in dates:
                        if f_start <= d <= f_end:
                            urls.append(
                                f if f.startswith("http") else f"{base_url}/{f.split('/')[-1]}"
                            )
                            break
                except Exception:
                    # Fallback to simple string match
                    for d in dates:
                        if d.strftime("%Y%m%d") in f_lower:
                            urls.append(
                                f if f.startswith("http") else f"{base_url}/{f.split('/')[-1]}"
                            )
                            break

            return sorted(list(set(urls)))
        except Exception as e:
            import warnings

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

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

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

        Returns
        -------
        xr.Dataset
            Harmonized dataset.
        """
        # Call GEOMS/GriddedReader harmonization first
        # GEOMS Reader already converted GEOMS names to lowercase and replaced . with _
        # e.g. NO2.COLUMN_ABSORPTION.SOLAR -> no2_column_absorption_solar

        # Pandora-specific additions: map GEOMS names to MONETIO names
        rename_dict = {
            "no2_column_absorption_solar": "nitrogen_dioxide",
            "o3_column_absorption_solar": "ozone",
            "h2co_column_absorption_solar": "formaldehyde",
            "so2_column_absorption_solar": "sulfur_dioxide",
        }

        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)

        # Map GEOMS metadata to standard MONETIO attributes
        for vn in ds.data_vars:
            if "VAR_UNITS" in ds[vn].attrs and "units" not in ds[vn].attrs:
                ds[vn].attrs["units"] = ds[vn].attrs["VAR_UNITS"]
            if "VAR_DESCRIPTION" in ds[vn].attrs and "long_name" not in ds[vn].attrs:
                ds[vn].attrs["long_name"] = ds[vn].attrs["VAR_DESCRIPTION"]

        return ds

build_urls(dates, siteid=None, instrument=None, product='no2', **kwargs)

Construct Pandora URLs. Note: Pandora data is hosted on https://data.pandonia-global-network.org/

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. 'BoulderCO').

None
instrument str

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

None
product str

Product type (e.g. 'no2', 'o3', 'h2co', 'so2'), by default 'no2'.

'no2'

Returns:

Type Description
List[str]

List of matching Pandora URLs.

Source code in monetio/readers/pandora.py
 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
def build_urls(
    self,
    dates: pd.DatetimeIndex | list[datetime.datetime] | datetime.datetime | str,
    siteid: str | None = None,
    instrument: str | None = None,
    product: str | None = "no2",
    **kwargs: Any,
) -> list[str]:
    """
    Construct Pandora URLs.
    Note: Pandora data is hosted on https://data.pandonia-global-network.org/

    Parameters
    ----------
    dates : Union[pd.DatetimeIndex, List[datetime], datetime, str]
        Dates to build URLs for.
    siteid : str, optional
        Specific site folder name (e.g. 'BoulderCO').
    instrument : str, optional
        Specific instrument name (e.g. 'Pandora57s1').
    product : str, optional
        Product type (e.g. 'no2', 'o3', 'h2co', 'so2'), by default 'no2'.

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

        warnings.warn(
            "Pandora retrieval requires 'siteid' (folder name) and 'instrument'. "
            "See https://data.pandonia-global-network.org/ for options."
        )
        return []

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

    # PGN Archive: https://data.pandonia-global-network.org/{site}/{instrument}/L2_geoms/
    base_url = f"https://data.pandonia-global-network.org/{siteid}/{instrument}/L2_geoms"

    import fsspec

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

        urls = []
        for f in all_files:
            if not f.endswith(".h5"):
                continue

            f_lower = f.lower()
            if product and f"{product.lower()}_" not in f_lower:
                continue

            # Pandora filenames contain start and end times:
            # groundbased_uvvis.doas.directsun.no2_noaa.esrl057_rd.rnvs3.1.8_boulder.co_20180430t232018z_20221222t223120z_001.h5
            # Extract dates from filename
            parts = f_lower.split("_")
            try:
                # Usually the last two parts before .h5 are dates
                start_str = parts[-3].split("t")[0]
                end_str = parts[-2].split("t")[0]

                f_start = pd.to_datetime(start_str, format="%Y%m%d")
                f_end = pd.to_datetime(end_str, format="%Y%m%d")

                for d in dates:
                    if f_start <= d <= f_end:
                        urls.append(
                            f if f.startswith("http") else f"{base_url}/{f.split('/')[-1]}"
                        )
                        break
            except Exception:
                # Fallback to simple string match
                for d in dates:
                    if d.strftime("%Y%m%d") in f_lower:
                        urls.append(
                            f if f.startswith("http") else f"{base_url}/{f.split('/')[-1]}"
                        )
                        break

        return sorted(list(set(urls)))
    except Exception as e:
        import warnings

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

harmonize(ds)

Standardize Pandora/GEOMS variable names and units.

Parameters:

Name Type Description Default
ds Dataset

Input dataset.

required

Returns:

Type Description
Dataset

Harmonized dataset.

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

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

    Returns
    -------
    xr.Dataset
        Harmonized dataset.
    """
    # Call GEOMS/GriddedReader harmonization first
    # GEOMS Reader already converted GEOMS names to lowercase and replaced . with _
    # e.g. NO2.COLUMN_ABSORPTION.SOLAR -> no2_column_absorption_solar

    # Pandora-specific additions: map GEOMS names to MONETIO names
    rename_dict = {
        "no2_column_absorption_solar": "nitrogen_dioxide",
        "o3_column_absorption_solar": "ozone",
        "h2co_column_absorption_solar": "formaldehyde",
        "so2_column_absorption_solar": "sulfur_dioxide",
    }

    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)

    # Map GEOMS metadata to standard MONETIO attributes
    for vn in ds.data_vars:
        if "VAR_UNITS" in ds[vn].attrs and "units" not in ds[vn].attrs:
            ds[vn].attrs["units"] = ds[vn].attrs["VAR_UNITS"]
        if "VAR_DESCRIPTION" in ds[vn].attrs and "long_name" not in ds[vn].attrs:
            ds[vn].attrs["long_name"] = ds[vn].attrs["VAR_DESCRIPTION"]

    return ds

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

Retrieve and load Pandora 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 Pandora site name (e.g. 'BoulderCO').

None
instrument str

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

None
product str

Product type (e.g. 'no2', 'o3', 'h2co', 'so2'), by default 'no2'.

'no2'
as_xarray bool

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

True
**kwargs Any

Additional arguments passed to the driver.

{}

Returns:

Type Description
Dataset | DataFrame

The processed Pandora dataset.

Source code in monetio/readers/pandora.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
78
79
80
81
82
83
84
85
86
87
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,
    product: str | None = "no2",
    as_xarray: bool = True,
    **kwargs: Any,
) -> xr.Dataset | pd.DataFrame:
    """
    Retrieve and load Pandora 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 Pandora site name (e.g. 'BoulderCO').
    instrument : str, optional
        Specific instrument name (e.g. 'Pandora57s1').
    product : str, optional
        Product type (e.g. 'no2', 'o3', 'h2co', 'so2'), by default 'no2'.
    as_xarray : bool, optional
        Whether to return an xarray.Dataset, by default True.
    **kwargs : Any
        Additional arguments passed to the driver.

    Returns
    -------
    xr.Dataset | pd.DataFrame
        The processed Pandora 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, product=product, **kwargs
        )

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

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

    # Apply harmonization explicitly as GEOMSReader.open_dataset calls geoms_preprocess
    # but doesn't call a reader-specific harmonize method from the base class properly
    # if not overridden in a specific way.
    ds = self.harmonize(ds)

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

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

    return ds