noaaplotter 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,150 @@
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ # Imports
4
+ import argparse
5
+
6
+ from noaaplotter.utils.config import get_noaa_token
7
+ from noaaplotter.utils.download_utils import download_from_noaa
8
+
9
+
10
+ def main():
11
+ """
12
+ Main Function
13
+ :return:
14
+ """
15
+ ##### Parse arguments #####
16
+ parser = argparse.ArgumentParser(description="Parse arguments.")
17
+
18
+ parser.add_argument(
19
+ "-o",
20
+ dest="output_file",
21
+ type=str,
22
+ required=True,
23
+ default="data/parquet.csv",
24
+ help="parquet file to save results",
25
+ )
26
+
27
+ parser.add_argument(
28
+ "--source",
29
+ dest="source",
30
+ type=str,
31
+ required=False,
32
+ default="noaa",
33
+ choices=["noaa", "open_meteo", "cds"],
34
+ help="data source: noaa (GHCND station), open_meteo (ERA5 by "
35
+ "coordinates, no key) or cds (CDS/ERA5 by coordinates, account required)",
36
+ )
37
+
38
+ parser.add_argument(
39
+ "-t", dest="token", type=str, required=False, default="",
40
+ help="NOAA token (optional; the public NCEI endpoint needs none). Defaults to NOAA_API_TOKEN from environment or .env if set",
41
+ )
42
+
43
+ parser.add_argument(
44
+ "-sid",
45
+ dest="station_id",
46
+ type=str,
47
+ required=False,
48
+ default="",
49
+ help='NOAA Station ID, e.g. "GHCND:USW00026616" for Kotzebue, only if loading through NOAA API',
50
+ )
51
+
52
+ parser.add_argument(
53
+ "-loc",
54
+ dest="loc_name",
55
+ type=str,
56
+ required=False,
57
+ default="",
58
+ help="Location name",
59
+ )
60
+
61
+ parser.add_argument(
62
+ "-lat",
63
+ dest="latitude",
64
+ type=float,
65
+ required=False,
66
+ default=None,
67
+ help="latitude for coordinate-based sources (open_meteo)",
68
+ )
69
+
70
+ parser.add_argument(
71
+ "-lon",
72
+ dest="longitude",
73
+ type=float,
74
+ required=False,
75
+ default=None,
76
+ help="longitude for coordinate-based sources (open_meteo)",
77
+ )
78
+
79
+ parser.add_argument(
80
+ "-dt",
81
+ dest="datatypes",
82
+ type=list,
83
+ required=False,
84
+ default=["TMIN", "TMAX", "PRCP", "SNOW"],
85
+ )
86
+
87
+ parser.add_argument(
88
+ "-start",
89
+ dest="start_date",
90
+ type=str,
91
+ required=True,
92
+ help='start date of plot ("yyyy-mm-dd")',
93
+ )
94
+
95
+ parser.add_argument(
96
+ "-end",
97
+ dest="end_date",
98
+ type=str,
99
+ required=True,
100
+ help='end date of plot ("yyyy-mm-dd")',
101
+ )
102
+
103
+ parser.add_argument(
104
+ "-n_jobs",
105
+ dest="n_jobs",
106
+ type=int,
107
+ required=False,
108
+ default=1,
109
+ help="number of parallel processes",
110
+ )
111
+
112
+ args = parser.parse_args()
113
+
114
+ if args.source in ("open_meteo", "cds"):
115
+ # coordinate-based reanalysis sources (identical interface)
116
+ if args.latitude is None or args.longitude is None:
117
+ parser.error(f"{args.source} source requires -lat and -lon")
118
+ from noaaplotter.sources import get_source
119
+
120
+ name = args.loc_name or f"{args.latitude:.2f},{args.longitude:.2f}"
121
+ df = get_source(args.source)(
122
+ latitude=args.latitude,
123
+ longitude=args.longitude,
124
+ start=args.start_date,
125
+ end=args.end_date,
126
+ name=name,
127
+ )
128
+ from noaaplotter.sources.open_meteo import save_to_parquet
129
+
130
+ save_to_parquet(df, args.output_file)
131
+ print(f"Saved {df.shape[0]} rows ({name}) to {args.output_file}")
132
+ return
133
+
134
+ # NOAA path (default)
135
+ token = get_noaa_token(args.token)
136
+
137
+ download_from_noaa(
138
+ output_file=args.output_file,
139
+ start_date=args.start_date,
140
+ end_date=args.end_date,
141
+ datatypes=args.datatypes,
142
+ noaa_api_token=token,
143
+ loc_name=args.loc_name,
144
+ station_id=args.station_id,
145
+ n_jobs=args.n_jobs,
146
+ )
147
+
148
+
149
+ if __name__ == "__main__":
150
+ main()
@@ -0,0 +1,108 @@
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ from noaaplotter.noaaplotter import NOAAPlotter
4
+ import argparse
5
+
6
+ def main():
7
+ """
8
+ Main Function
9
+ :return:
10
+ """
11
+ ##### Parse arguments #####
12
+ parser = argparse.ArgumentParser(description='Parse arguments.')
13
+
14
+ parser.add_argument('-infile', dest='infile', type=str, required=True,
15
+ default='data/temp.parquet',
16
+ help='input file with climate data')
17
+
18
+ parser.add_argument('-t', dest='token', type=str, required=False,
19
+ default='',
20
+ help='NOAA API token, only if loading through NOAA API')
21
+
22
+ parser.add_argument('-sid', dest='station_id', type=str, required=False,
23
+ default='',
24
+ help='NOAA Station ID, e.g. "GHCND:USW00026616" for Kotzebue, only if loading through NOAA API')
25
+
26
+ parser.add_argument('-start', dest='start_date', type=str, required=True,
27
+ help='start date of plot ("yyyy-mm-dd")')
28
+
29
+ parser.add_argument('-end', dest='end_date', type=str, required=True,
30
+ help='end date of plot ("yyyy-mm-dd")')
31
+
32
+ parser.add_argument('-loc', dest='location', required=False,
33
+ type=str, default=None,
34
+ help='Location name, must be in data file')
35
+
36
+ parser.add_argument('-save_plot', dest='save_path', type=str, required=False,
37
+ default=None,
38
+ help='filepath for plot')
39
+
40
+ parser.add_argument('-t_range', dest='t_range', type=float, nargs=2, required=False,
41
+ default=[None, None],
42
+ help='temperature range in plot')
43
+
44
+ parser.add_argument('-p_range', dest='p_range', type=float, required=False,
45
+ default=None,
46
+ help='maximum precipitation value in plot')
47
+
48
+ parser.add_argument('-s_range', dest='s_range', type=float, required=False,
49
+ default=None,
50
+ help='maximum snow accumulation value in plot')
51
+
52
+ parser.add_argument('-snow_acc', dest='snow_acc', required=False,
53
+ default=False, action='store_true',
54
+ help='show snow accumulation, only useful for plotting winter season (e.g. July to June')
55
+
56
+ parser.add_argument('-filtersize', dest='filtersize', type=int, required=False,
57
+ default=7,
58
+ help='parameter to smooth climate temperature series by n days for smoother visual appearance. '
59
+ 'default value: 7')
60
+
61
+ parser.add_argument('-dpi', dest='dpi', type=float, required=False,
62
+ default=100,
63
+ help='dpi for plot output')
64
+
65
+ parser.add_argument('-plot', dest='show_plot', required=False,
66
+ default=False, action='store_true',
67
+ help='Location name, must be in data file')
68
+
69
+ parser.add_argument('-figsize', dest='figsize', type=float, nargs=2, required=False,
70
+ default=[9, 6],
71
+ help='figure size in inches width x height. 15 10 recommended for 1 year, 30 10 for 2 years ...')
72
+
73
+ parser.add_argument('-title', dest='title', type=str, required=False,
74
+ default=None,
75
+ help='Plot title')
76
+
77
+ parser.add_argument('-engine', dest='engine', type=str, required=False,
78
+ default='matplotlib', choices=['matplotlib', 'plotly'],
79
+ help="rendering engine: 'matplotlib' (static PNG) or "
80
+ "'plotly' (interactive HTML; use -save_plot x.html)")
81
+
82
+ args = parser.parse_args()
83
+
84
+ ##### Download from NOAA #####
85
+
86
+ ##### Run Plotting function #####
87
+ n = NOAAPlotter(args.infile,
88
+ location=args.location,
89
+ climate_filtersize=args.filtersize)
90
+
91
+ n.plot_weather_series(start_date=args.start_date,
92
+ end_date=args.end_date,
93
+ show_snow_accumulation=args.snow_acc,
94
+ #kwargs_fig={'dpi':args.dpi, 'figsize':args.figsize},
95
+ plot_extrema=True,
96
+ show_plot=args.show_plot,
97
+ save_path=args.save_path,
98
+ plot_tmin=args.t_range[0],
99
+ plot_tmax=args.t_range[1],
100
+ plot_pmax=args.p_range,
101
+ plot_snowmax=args.s_range,
102
+ dpi=args.dpi,
103
+ figsize=args.figsize,
104
+ title=args.title,
105
+ engine=args.engine)
106
+
107
+ if __name__ == "__main__":
108
+ main()
@@ -0,0 +1,72 @@
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ from noaaplotter.noaaplotter import NOAAPlotter
4
+ import argparse
5
+
6
+ def main():
7
+ """
8
+ Main Function
9
+ :return:
10
+ """
11
+ ##### Parse arguments #####
12
+ parser = argparse.ArgumentParser(description='Parse arguments.')
13
+
14
+ parser.add_argument('-infile', dest='infile', type=str, required=True,
15
+ help='input file with climate data')
16
+
17
+ parser.add_argument('-start', dest='start_date', type=str, required=True,
18
+ help='start date of plot ("yyyy-mm-dd")')
19
+
20
+ parser.add_argument('-end', dest='end_date', type=str, required=True,
21
+ help='end date of plot ("yyyy-mm-dd")')
22
+
23
+ parser.add_argument('-loc', dest='location', required=False,
24
+ type=str, default=None,
25
+ help='Location name, must be in data file')
26
+
27
+ parser.add_argument('-save_plot', dest='save_path', type=str, required=False,
28
+ default=None,
29
+ help='filepath for plot')
30
+
31
+ parser.add_argument('-type', dest='type', type=str, required=True,
32
+ help='Attribute Type: {Temperature, Precipitation}',
33
+ default='Temperature')
34
+
35
+ parser.add_argument('-trail', dest='trailing_mean', type=int, required=False,
36
+ default=None,
37
+ help='trailing/rolling mean value in months')
38
+
39
+ parser.add_argument('-anomaly', dest='anomaly', required=False,
40
+ default=False, action='store_true',
41
+ help='show anomaly from climate')
42
+
43
+ parser.add_argument('-dpi', dest='dpi', type=float, required=False,
44
+ default=100,
45
+ help='dpi for plot output')
46
+
47
+ parser.add_argument('-plot', dest='show_plot', required=False,
48
+ default=False, action='store_true',
49
+ help='Location name, must be in data file')
50
+
51
+ parser.add_argument('-figsize', dest='figsize', type=float, nargs=2, required=False,
52
+ default=[9, 4],
53
+ help='figure size in inches width x height. 9 4 recommended 30 years')
54
+
55
+ args = parser.parse_args()
56
+
57
+ ##### Run Plotting function #####
58
+ n = NOAAPlotter(args.infile,
59
+ location=args.location)
60
+
61
+ n.plot_monthly_barchart(args.start_date,
62
+ args.end_date,
63
+ information=args.type,
64
+ anomaly=args.anomaly,
65
+ trailing_mean=args.trailing_mean,
66
+ show_plot=args.show_plot,
67
+ dpi=args.dpi,
68
+ figsize=args.figsize,
69
+ save_path=args.save_path)
70
+
71
+ if __name__ == "__main__":
72
+ main()
@@ -0,0 +1,17 @@
1
+ """Data sources: fetch daily weather data into the canonical NOAA schema.
2
+
3
+ from noaaplotter.sources import fetch_open_meteo, fetch_cds_era5
4
+ fetch_open_meteo(lat, lon, start, end) # ERA5 via Open-Meteo, no key
5
+ fetch_cds_era5(lat, lon, start, end) # ERA5 via Copernicus CDS (account)
6
+ """
7
+ from .base import SOURCES, get_source, validate_schema
8
+ from .cds import fetch_cds_era5
9
+ from .open_meteo import fetch_open_meteo
10
+
11
+ __all__ = [
12
+ "SOURCES",
13
+ "get_source",
14
+ "validate_schema",
15
+ "fetch_open_meteo",
16
+ "fetch_cds_era5",
17
+ ]
@@ -0,0 +1,97 @@
1
+ """DataSource registry + canonical schema.
2
+
3
+ Every source fetches daily weather data and maps it into the canonical
4
+ schema (the parquet NOAA downloader already writes), so downstream
5
+ (plotting, climate stats) is schema-agnostic.
6
+ """
7
+ import polars as pl
8
+
9
+ #: canonical schema — all sources must return these columns
10
+ CANONICAL_COLUMNS = [
11
+ "STATION", "NAME", "DATE", "TAVG", "TMAX", "TMIN", "PRCP", "SNOW",
12
+ ]
13
+
14
+
15
+ def validate_schema(df: pl.DataFrame) -> pl.DataFrame:
16
+ """Check that df has the canonical schema; raise if not."""
17
+ missing = [c for c in CANONICAL_COLUMNS if c not in df.columns]
18
+ if missing:
19
+ raise ValueError(f"Source output missing canonical columns: {missing}")
20
+ return df
21
+
22
+
23
+ def _noaa_source(**kwargs):
24
+ """NOAA GHCND source (existing download_from_noaa, incremental parquet).
25
+
26
+ Requires `station_id`, `start`, `end`, `output_file`. The token is
27
+ optional and only used if provided; the NCEI service endpoint is public.
28
+ """
29
+ from noaaplotter.utils.config import get_noaa_token
30
+ from noaaplotter.utils.download_utils import download_from_noaa
31
+
32
+ token = get_noaa_token(kwargs.pop("token", None))
33
+ required = ["station_id", "start", "end"]
34
+ missing = [k for k in required if kwargs.get(k) in (None, "")]
35
+ if missing:
36
+ raise ValueError(f"noaa source missing required kwarg(s): {missing}")
37
+ return download_from_noaa(
38
+ output_file=kwargs.get("output_file") or "noaa_data.parquet",
39
+ start_date=kwargs["start"],
40
+ end_date=kwargs["end"],
41
+ datatypes=kwargs.get("datatypes") or ["TMIN", "TMAX", "PRCP", "SNOW"],
42
+ loc_name=kwargs.get("loc_name") or "",
43
+ station_id=kwargs["station_id"],
44
+ noaa_api_token=token,
45
+ n_jobs=kwargs.get("n_jobs", 1),
46
+ )
47
+
48
+
49
+ def _open_meteo_source(**kwargs):
50
+ """Open-Meteo Archive source (ERA5, no API key).
51
+
52
+ Requires `latitude`, `longitude`, `start`, `end`.
53
+ """
54
+ from noaaplotter.sources.open_meteo import fetch_open_meteo
55
+
56
+ return _coordinate_source(fetch_open_meteo, **kwargs)
57
+
58
+
59
+ def _cds_source(**kwargs):
60
+ """Copernicus CDS source (ERA5, account required).
61
+
62
+ Requires `latitude`, `longitude`, `start`, `end` (same as open_meteo).
63
+ """
64
+ from noaaplotter.sources.cds import fetch_cds_era5
65
+
66
+ return _coordinate_source(fetch_cds_era5, **kwargs)
67
+
68
+
69
+ def _coordinate_source(fetch, **kwargs):
70
+ missing = [
71
+ k
72
+ for k in ("latitude", "longitude", "start", "end")
73
+ if kwargs.get(k) in (None, "")
74
+ ]
75
+ if missing:
76
+ raise ValueError(f"source missing required kwarg(s): {missing}")
77
+ return fetch(
78
+ float(kwargs["latitude"]),
79
+ float(kwargs["longitude"]),
80
+ kwargs["start"],
81
+ kwargs["end"],
82
+ **{k: v for k, v in kwargs.items() if k not in ("latitude", "longitude", "start", "end")},
83
+ )
84
+
85
+
86
+ #: source name -> callable(**kwargs) -> DataFrame / path
87
+ SOURCES = {
88
+ "noaa": _noaa_source,
89
+ "open_meteo": _open_meteo_source,
90
+ "cds": _cds_source,
91
+ }
92
+
93
+
94
+ def get_source(name: str):
95
+ if name not in SOURCES:
96
+ raise ValueError(f"Unknown source '{name}'. Available: {sorted(SOURCES)}")
97
+ return SOURCES[name]
@@ -0,0 +1,168 @@
1
+ """CDS / Copernicus ERA5 source (account required: https://cds.climate.copernicus.eu).
2
+
3
+ Fetches daily reanalysis for a single point (lat/lon) and maps it into the
4
+ canonical NOAA daily-summaries schema, so it plots exactly like a station file.
5
+
6
+ Credentials (see noaaplotter/utils/config.py):
7
+ CDS_API_KEY full "https://...api:token" string for the cdsapi key, OR
8
+ CDS_API_TOKEN token, combined with CDS_API_URL (optional override)
9
+ Get a token at https://cds.climate.copernicus.eu (login -> My Data -> API).
10
+
11
+ Requires: cdsapi, xarray
12
+ Data lag: about 2-5 days.
13
+ """
14
+ import os
15
+ import tempfile
16
+ from datetime import date, timedelta, datetime as dt
17
+
18
+ import polars as pl
19
+
20
+ VARIABLES = ["2m_temperature", "total_precipitation", "snowfall"]
21
+
22
+
23
+ def _key_file():
24
+ """Create a cdsapi key file (path: `url:token`) and return its path."""
25
+ key = os.environ.get("CDS_API_KEY", "")
26
+ if not key:
27
+ from noaaplotter.utils.config import get_cds_credentials
28
+
29
+ token, url = get_cds_credentials()
30
+ if not token:
31
+ raise ValueError(
32
+ "CDS source needs credentials: set CDS_API_KEY ('url:token') or "
33
+ "CDS_API_TOKEN (+ optional CDS_API_URL) in your environment or .env "
34
+ "(see .env.example). Get a token at https://cds.climate.copernicus.eu "
35
+ "(login -> My Data -> API)."
36
+ )
37
+ key = f"{url}:{token}"
38
+ path = os.path.join(tempfile.gettempdir(), "noaaplotter_cds_keyfile")
39
+ with open(path, "w") as f:
40
+ f.write(key)
41
+ os.chmod(path, 0o600)
42
+ return path
43
+
44
+
45
+ def _client():
46
+ """Build a cdsapi client using the key file we wrote."""
47
+ import cdsapi
48
+
49
+ # `Client(key=...)` is the canonical API in cdsapi>=0.7; some builds
50
+ # expose the class as `CDS` for backward compatibility.
51
+ cls = getattr(cdsapi, "Client", None) or getattr(cdsapi, "CDS")
52
+ try:
53
+ return cls(key=_key_file())
54
+ except TypeError:
55
+ # older cdsapi without the `key` argument: copy the key file to the
56
+ # default location and use the parameterless constructor.
57
+ default = os.path.join(
58
+ os.path.expanduser("~"), ".config", "ecmwf", "apiclient"
59
+ )
60
+ os.makedirs(os.path.dirname(default), exist_ok=True)
61
+ os.replace(_key_file(), default)
62
+ return cls()
63
+
64
+
65
+ def fetch_cds_era5(latitude, longitude, start, end, name="CDS ERA5"):
66
+ """Fetch daily ERA5 (CDS) for a single point into the canonical schema.
67
+
68
+ One CDS request per calendar month. Daily statistics derived locally:
69
+ TAVG = mean(t2m) PRCP = sum(total_precipitation)
70
+ TMAX = max (t2m) SNOW = sum(snowfall)
71
+ TMIN = min (t2m)
72
+
73
+ :param latitude: degrees north
74
+ :param longitude: degrees east (negative for W)
75
+ :param start: "yyyy-mm-dd"
76
+ :param end: "yyyy-mm-dd"
77
+ :param name: label for the NAME column
78
+ :return: polars DataFrame with canonical columns
79
+ (STATION, NAME, DATE, TAVG, TMAX, TMIN, PRCP, SNOW)
80
+ """
81
+ client = _client()
82
+ dt_start = dt.strptime(start, "%Y-%m-%d").date()
83
+ dt_end = dt.strptime(end, "%Y-%m-%d").date()
84
+ station_id = f"{latitude:.4f},{longitude:.4f}"
85
+
86
+ frames = []
87
+ month = date(dt_start.year, dt_start.month, 1)
88
+ while month <= dt_end:
89
+ out_path = os.path.join(
90
+ tempfile.gettempdir(),
91
+ f"noaaplotter_era5_{month.year:04d}{month.month:02d}.nc",
92
+ )
93
+ last_day = min(dt_end, month + timedelta(days=31))
94
+ client.retrieve(
95
+ "reanalysis-era5-single-levels",
96
+ {
97
+ "product_type": "reanalysis",
98
+ "variable": VARIABLES,
99
+ "area": [latitude, longitude, latitude, longitude], # single point
100
+ "start_date": month.strftime("%Y-%m-%d"),
101
+ "end_date": last_day.strftime("%Y-%m-%d"),
102
+ "time": ["%02d:00" % h for h in range(24)],
103
+ "format": "netcdf",
104
+ },
105
+ out_path,
106
+ )
107
+
108
+ import xarray as xr
109
+
110
+ with xr.open_dataset(out_path) as ds:
111
+ d = ds.groupby("time.day").agg(
112
+ tmean=("t2m", "mean"),
113
+ tmax=("t2m", "max"),
114
+ tmin=("t2m", "min"),
115
+ prcp=("tp", "sum"),
116
+ snow=("snowfall", "sum"),
117
+ )
118
+ rows = d.reset_index()
119
+ frames.append(
120
+ pl.DataFrame(
121
+ {
122
+ "DATE": [
123
+ r["time"].date() for r in rows.itertuples(index=False)
124
+ ],
125
+ "TAVG": rows["tmean"].tolist(),
126
+ "TMAX": rows["tmax"].tolist(),
127
+ "TMIN": rows["tmin"].tolist(),
128
+ "PRCP": rows["prcp"].tolist(),
129
+ "SNOW": rows["snow"].tolist(),
130
+ }
131
+ )
132
+ )
133
+ os.remove(out_path)
134
+ month = date(
135
+ month.year + (1 if month.month == 12 else 0),
136
+ 1 if month.month == 12 else month.month + 1,
137
+ 1,
138
+ )
139
+
140
+ if not frames:
141
+ return pl.DataFrame(
142
+ {
143
+ "STATION": [None],
144
+ "NAME": [name],
145
+ "DATE": pl.Series([], dtype=pl.Date),
146
+ "TAVG": [None],
147
+ "TMAX": [None],
148
+ "TMIN": [None],
149
+ "PRCP": [None],
150
+ "SNOW": [None],
151
+ }
152
+ )
153
+ df = pl.concat(frames).filter(
154
+ (pl.col("DATE") >= dt_start) & (pl.col("DATE") <= dt_end)
155
+ )
156
+ return df.with_columns(
157
+ pl.lit(station_id).alias("STATION"),
158
+ pl.lit(name).alias("NAME"),
159
+ )
160
+
161
+
162
+ def save_to_parquet(df, output_file):
163
+ """Write a canonical-schema frame to parquet (kept numeric)."""
164
+ for c in ("TAVG", "TMAX", "TMIN", "PRCP", "SNOW"):
165
+ if c in df.columns:
166
+ df = df.with_columns(pl.col(c).cast(pl.Float64, strict=False))
167
+ df.write_parquet(output_file)
168
+ return output_file