oafuncs 0.0.98.33__py3-none-any.whl → 0.0.98.35__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.
@@ -1,1213 +0,0 @@
1
- import asyncio
2
- import datetime
3
- import logging
4
- import os
5
- import random
6
- import re
7
- import time
8
- import warnings
9
- from concurrent.futures import ThreadPoolExecutor, as_completed
10
- from pathlib import Path
11
- from threading import Lock
12
-
13
- import httpx
14
- import matplotlib.pyplot as plt
15
- import netCDF4 as nc
16
- import numpy as np
17
- import pandas as pd
18
- import xarray as xr
19
- from rich import print
20
- from rich.progress import Progress
21
-
22
- from oafuncs.oa_down.idm import downloader as idm_downloader
23
- from oafuncs.oa_down.user_agent import get_ua
24
- from oafuncs.oa_file import file_size
25
- from oafuncs.oa_nc import check as check_nc
26
- from oafuncs.oa_nc import modify as modify_nc
27
-
28
- logging.getLogger("httpx").setLevel(logging.WARNING) # 关闭 httpx 的 INFO 日志,只显示 WARNING 及以上
29
-
30
-
31
- warnings.filterwarnings("ignore", category=RuntimeWarning, message="Engine '.*' loading failed:.*")
32
-
33
- __all__ = ["draw_time_range", "download"]
34
-
35
-
36
- def _get_initial_data():
37
- global variable_info, data_info, var_group, single_var_group
38
- # ----------------------------------------------
39
- # variable
40
- variable_info = {
41
- "u": {"var_name": "water_u", "standard_name": "eastward_sea_water_velocity"},
42
- "v": {"var_name": "water_v", "standard_name": "northward_sea_water_velocity"},
43
- "temp": {"var_name": "water_temp", "standard_name": "sea_water_potential_temperature"},
44
- "salt": {"var_name": "salinity", "standard_name": "sea_water_salinity"},
45
- "ssh": {"var_name": "surf_el", "standard_name": "sea_surface_elevation"},
46
- "u_b": {"var_name": "water_u_bottom", "standard_name": "eastward_sea_water_velocity_at_sea_floor"},
47
- "v_b": {"var_name": "water_v_bottom", "standard_name": "northward_sea_water_velocity_at_sea_floor"},
48
- "temp_b": {"var_name": "water_temp_bottom", "standard_name": "sea_water_potential_temperature_at_sea_floor"},
49
- "salt_b": {"var_name": "salinity_bottom", "standard_name": "sea_water_salinity_at_sea_floor"},
50
- }
51
- # ----------------------------------------------
52
- # time resolution
53
- data_info = {"yearly": {}, "monthly": {}, "daily": {}, "hourly": {}}
54
-
55
- # hourly data
56
- # dataset: GLBv0.08, GLBu0.08, GLBy0.08
57
- data_info["hourly"]["dataset"] = {"GLBv0.08": {}, "GLBu0.08": {}, "GLBy0.08": {}, "ESPC_D": {}}
58
-
59
- # version
60
- # version of GLBv0.08: 53.X, 56.3, 57.2, 92.8, 57.7, 92.9, 93.0
61
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"] = {"53.X": {}, "56.3": {}, "57.2": {}, "92.8": {}, "57.7": {}, "92.9": {}, "93.0": {}}
62
- # version of GLBu0.08: 93.0
63
- data_info["hourly"]["dataset"]["GLBu0.08"]["version"] = {"93.0": {}}
64
- # version of GLBy0.08: 93.0
65
- data_info["hourly"]["dataset"]["GLBy0.08"]["version"] = {"93.0": {}}
66
- # version of ESPC_D: V02
67
- data_info["hourly"]["dataset"]["ESPC_D"]["version"] = {"V02": {}}
68
-
69
- # info details
70
- # time range
71
- # GLBv0.08
72
- # 在网页上提交超过范围的时间,会返回该数据集实际时间范围,从而纠正下面的时间范围
73
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["53.X"]["time_range"] = {"time_start": "1994010112", "time_end": "2015123109"}
74
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["56.3"]["time_range"] = {"time_start": "2014070112", "time_end": "2016093009"}
75
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["57.2"]["time_range"] = {"time_start": "2016050112", "time_end": "2017020109"}
76
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["92.8"]["time_range"] = {"time_start": "2017020112", "time_end": "2017060109"}
77
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["57.7"]["time_range"] = {"time_start": "2017060112", "time_end": "2017100109"}
78
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["92.9"]["time_range"] = {"time_start": "2017100112", "time_end": "2018032009"}
79
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["93.0"]["time_range"] = {"time_start": "2018010112", "time_end": "2020021909"}
80
- # GLBu0.08
81
- data_info["hourly"]["dataset"]["GLBu0.08"]["version"]["93.0"]["time_range"] = {"time_start": "2018091912", "time_end": "2018120909"}
82
- # GLBy0.08
83
- data_info["hourly"]["dataset"]["GLBy0.08"]["version"]["93.0"]["time_range"] = {"time_start": "2018120412", "time_end": "2024090509"}
84
- # ESPC-D
85
- data_info["hourly"]["dataset"]["ESPC_D"]["version"]["V02"]["time_range"] = {"time_start": "2024081012", "time_end": "2030010100"}
86
-
87
- # classification method
88
- # year_different: the data of different years is stored in different files
89
- # same_path: the data of different years is stored in the same file
90
- # var_different: the data of different variables is stored in different files
91
- # var_year_different: the data of different variables and years is stored in different files
92
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["53.X"]["classification"] = "year_different"
93
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["56.3"]["classification"] = "same_path"
94
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["57.2"]["classification"] = "same_path"
95
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["92.8"]["classification"] = "var_different"
96
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["57.7"]["classification"] = "same_path"
97
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["92.9"]["classification"] = "var_different"
98
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["93.0"]["classification"] = "var_different"
99
- data_info["hourly"]["dataset"]["GLBu0.08"]["version"]["93.0"]["classification"] = "var_different"
100
- data_info["hourly"]["dataset"]["GLBy0.08"]["version"]["93.0"]["classification"] = "var_year_different"
101
- data_info["hourly"]["dataset"]["ESPC_D"]["version"]["V02"]["classification"] = "single_var_year_different"
102
-
103
- # download info
104
- # base url
105
- # GLBv0.08 53.X
106
- url_53x = {}
107
- for y_53x in range(1994, 2016):
108
- # r'https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_53.X/data/2013?'
109
- url_53x[str(y_53x)] = rf"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_53.X/data/{y_53x}?"
110
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["53.X"]["url"] = url_53x
111
- # GLBv0.08 56.3
112
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["56.3"]["url"] = r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_56.3?"
113
- # GLBv0.08 57.2
114
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["57.2"]["url"] = r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_57.2?"
115
- # GLBv0.08 92.8
116
- url_928 = {
117
- "uv3z": r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_92.8/uv3z?",
118
- "ts3z": r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_92.8/ts3z?",
119
- "ssh": r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_92.8/ssh?",
120
- }
121
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["92.8"]["url"] = url_928
122
- # GLBv0.08 57.7
123
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["57.7"]["url"] = r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_57.7?"
124
- # GLBv0.08 92.9
125
- url_929 = {
126
- "uv3z": r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_92.9/uv3z?",
127
- "ts3z": r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_92.9/ts3z?",
128
- "ssh": r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_92.9/ssh?",
129
- }
130
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["92.9"]["url"] = url_929
131
- # GLBv0.08 93.0
132
- url_930_v = {
133
- "uv3z": r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_93.0/uv3z?",
134
- "ts3z": r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_93.0/ts3z?",
135
- "ssh": r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_93.0/ssh?",
136
- }
137
- data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["93.0"]["url"] = url_930_v
138
- # GLBu0.08 93.0
139
- url_930_u = {
140
- "uv3z": r"https://ncss.hycom.org/thredds/ncss/GLBu0.08/expt_93.0/uv3z?",
141
- "ts3z": r"https://ncss.hycom.org/thredds/ncss/GLBu0.08/expt_93.0/ts3z?",
142
- "ssh": r"https://ncss.hycom.org/thredds/ncss/GLBu0.08/expt_93.0/ssh?",
143
- }
144
- data_info["hourly"]["dataset"]["GLBu0.08"]["version"]["93.0"]["url"] = url_930_u
145
- # GLBy0.08 93.0
146
- uv3z_930_y = {}
147
- ts3z_930_y = {}
148
- ssh_930_y = {}
149
- for y_930_y in range(2018, 2025):
150
- uv3z_930_y[str(y_930_y)] = rf"https://ncss.hycom.org/thredds/ncss/GLBy0.08/expt_93.0/uv3z/{y_930_y}?"
151
- ts3z_930_y[str(y_930_y)] = rf"https://ncss.hycom.org/thredds/ncss/GLBy0.08/expt_93.0/ts3z/{y_930_y}?"
152
- ssh_930_y[str(y_930_y)] = rf"https://ncss.hycom.org/thredds/ncss/GLBy0.08/expt_93.0/ssh/{y_930_y}?"
153
- # GLBy0.08 93.0 data time range in each year: year-01-01 12:00 to year+1-01-01 09:00
154
- url_930_y = {
155
- "uv3z": uv3z_930_y,
156
- "ts3z": ts3z_930_y,
157
- "ssh": ssh_930_y,
158
- }
159
- data_info["hourly"]["dataset"]["GLBy0.08"]["version"]["93.0"]["url"] = url_930_y
160
- # ESPC-D-V02
161
- u3z_espc_d_v02_y = {}
162
- v3z_espc_d_v02_y = {}
163
- t3z_espc_d_v02_y = {}
164
- s3z_espc_d_v02_y = {}
165
- ssh_espc_d_v02_y = {}
166
- for y_espc_d_v02 in range(2024, 2030):
167
- u3z_espc_d_v02_y[str(y_espc_d_v02)] = rf"https://ncss.hycom.org/thredds/ncss/ESPC-D-V02/u3z/{y_espc_d_v02}?"
168
- v3z_espc_d_v02_y[str(y_espc_d_v02)] = rf"https://ncss.hycom.org/thredds/ncss/ESPC-D-V02/v3z/{y_espc_d_v02}?"
169
- t3z_espc_d_v02_y[str(y_espc_d_v02)] = rf"https://ncss.hycom.org/thredds/ncss/ESPC-D-V02/t3z/{y_espc_d_v02}?"
170
- s3z_espc_d_v02_y[str(y_espc_d_v02)] = rf"https://ncss.hycom.org/thredds/ncss/ESPC-D-V02/s3z/{y_espc_d_v02}?"
171
- ssh_espc_d_v02_y[str(y_espc_d_v02)] = rf"https://ncss.hycom.org/thredds/ncss/ESPC-D-V02/ssh/{y_espc_d_v02}?"
172
- url_espc_d_v02_y = {
173
- "u3z": u3z_espc_d_v02_y,
174
- "v3z": v3z_espc_d_v02_y,
175
- "t3z": t3z_espc_d_v02_y,
176
- "s3z": s3z_espc_d_v02_y,
177
- "ssh": ssh_espc_d_v02_y,
178
- }
179
- data_info["hourly"]["dataset"]["ESPC_D"]["version"]["V02"]["url"] = url_espc_d_v02_y
180
- # ----------------------------------------------
181
- var_group = {
182
- "uv3z": ["u", "v", "u_b", "v_b"],
183
- "ts3z": ["temp", "salt", "temp_b", "salt_b"],
184
- "ssh": ["ssh"],
185
- }
186
- # ----------------------------------------------
187
- single_var_group = {
188
- "u3z": ["u"],
189
- "v3z": ["v"],
190
- "t3z": ["temp"],
191
- "s3z": ["salt"],
192
- "ssh": ["ssh"],
193
- }
194
-
195
- return variable_info, data_info, var_group, single_var_group
196
-
197
-
198
- def draw_time_range(pic_save_folder=None):
199
- if pic_save_folder is not None:
200
- os.makedirs(pic_save_folder, exist_ok=True)
201
- # Converting the data into a format suitable for plotting
202
- data = []
203
- for dataset, versions in data_info["hourly"]["dataset"].items():
204
- for version, time_range in versions["version"].items():
205
- t_s = time_range["time_range"]["time_start"]
206
- t_e = time_range["time_range"]["time_end"]
207
- if len(t_s) == 8:
208
- t_s = t_s + "00"
209
- if len(t_e) == 8:
210
- t_e = t_e + "21"
211
- t_s, t_e = t_s + "0000", t_e + "0000"
212
- data.append(
213
- {
214
- "dataset": dataset,
215
- "version": version,
216
- "start_date": pd.to_datetime(t_s),
217
- "end_date": pd.to_datetime(t_e),
218
- }
219
- )
220
-
221
- # Creating a DataFrame
222
- df = pd.DataFrame(data)
223
-
224
- # Plotting with combined labels for datasets and versions on the y-axis
225
- plt.figure(figsize=(12, 6))
226
-
227
- # Combined labels for datasets and versions
228
- combined_labels = [f"{dataset}_{version}" for dataset, version in zip(df["dataset"], df["version"])]
229
-
230
- colors = plt.cm.viridis(np.linspace(0, 1, len(combined_labels)))
231
-
232
- # Assigning a color to each combined label
233
- label_colors = {label: colors[i] for i, label in enumerate(combined_labels)}
234
-
235
- # Plotting each time range
236
- k = 1
237
- for _, row in df.iterrows():
238
- plt.plot([row["start_date"], row["end_date"]], [k, k], color=label_colors[f"{row['dataset']}_{row['version']}"], linewidth=6)
239
- # plt.text(row['end_date'], k,
240
- # f"{row['version']}", ha='right', color='black')
241
- ymdh_s = row["start_date"].strftime("%Y-%m-%d %H")
242
- ymdh_e = row["end_date"].strftime("%Y-%m-%d %H")
243
- # if k == 1 or k == len(combined_labels):
244
- if k == 1:
245
- plt.text(row["start_date"], k + 0.125, f"{ymdh_s}", ha="left", color="black")
246
- plt.text(row["end_date"], k + 0.125, f"{ymdh_e}", ha="right", color="black")
247
- else:
248
- plt.text(row["start_date"], k + 0.125, f"{ymdh_s}", ha="right", color="black")
249
- plt.text(row["end_date"], k + 0.125, f"{ymdh_e}", ha="left", color="black")
250
- k += 1
251
-
252
- # Setting the y-axis labels
253
- plt.yticks(range(1, len(combined_labels) + 1), combined_labels)
254
- plt.xlabel("Time")
255
- plt.ylabel("Dataset - Version")
256
- plt.title("Time Range of Different Versions of Datasets")
257
- plt.xticks(rotation=45)
258
- plt.grid(True)
259
- plt.tight_layout()
260
- if pic_save_folder:
261
- plt.savefig(Path(pic_save_folder) / "HYCOM_time_range.png")
262
- print(f"[bold green]HYCOM_time_range.png has been saved in {pic_save_folder}")
263
- else:
264
- plt.savefig("HYCOM_time_range.png")
265
- print("[bold green]HYCOM_time_range.png has been saved in the current folder")
266
- print(f"Curren folder: {os.getcwd()}")
267
- # plt.show()
268
- plt.close()
269
-
270
-
271
- def _get_time_list(time_s, time_e, delta, interval_type="hour"):
272
- """
273
- Description: get a list of time strings from time_s to time_e with a specified interval
274
- Args:
275
- time_s: start time string, e.g. '2023080203' for hours or '20230802' for days
276
- time_e: end time string, e.g. '2023080303' for hours or '20230803' for days
277
- delta: interval of hours or days
278
- interval_type: 'hour' for hour interval, 'day' for day interval
279
- Returns:
280
- dt_list: a list of time strings
281
- """
282
- time_s, time_e = str(time_s), str(time_e)
283
- if interval_type == "hour":
284
- time_format = "%Y%m%d%H"
285
- delta_type = "hours"
286
- elif interval_type == "day":
287
- time_format = "%Y%m%d"
288
- delta_type = "days"
289
- # Ensure time strings are in the correct format for days
290
- time_s = time_s[:8]
291
- time_e = time_e[:8]
292
- else:
293
- raise ValueError("interval_type must be 'hour' or 'day'")
294
-
295
- dt = datetime.datetime.strptime(time_s, time_format)
296
- dt_list = []
297
- while dt.strftime(time_format) <= time_e:
298
- dt_list.append(dt.strftime(time_format))
299
- dt += datetime.timedelta(**{delta_type: delta})
300
- return dt_list
301
-
302
-
303
- def _transform_time(time_str):
304
- # old_time = '2023080203'
305
- # time_new = '2023-08-02T03%3A00%3A00Z'
306
- time_new = f"{time_str[:4]}-{time_str[4:6]}-{time_str[6:8]}T{time_str[8:10]}%3A00%3A00Z"
307
- return time_new
308
-
309
-
310
- def _get_query_dict(var, lon_min, lon_max, lat_min, lat_max, time_str_ymdh, time_str_end=None, mode="single_depth", depth=None, level_num=None):
311
- query_dict = {
312
- "var": variable_info[var]["var_name"],
313
- "north": lat_max,
314
- "west": lon_min,
315
- "east": lon_max,
316
- "south": lat_min,
317
- "horizStride": 1,
318
- "time": None,
319
- "time_start": None,
320
- "time_end": None,
321
- "timeStride": None,
322
- "vertCoord": None,
323
- "vertStride": None,
324
- "addLatLon": "true",
325
- "accept": "netcdf4",
326
- }
327
-
328
- if time_str_end is not None:
329
- query_dict["time_start"] = _transform_time(time_str_ymdh)
330
- query_dict["time_end"] = _transform_time(time_str_end)
331
- query_dict["timeStride"] = 1
332
- else:
333
- query_dict["time"] = _transform_time(time_str_ymdh)
334
-
335
- def get_nearest_level_index(depth):
336
- level_depth = [0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 15.0, 20.0, 25.0, 30.0, 35.0, 40.0, 45.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 125.0, 150.0, 200.0, 250.0, 300.0, 350.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0, 1250.0, 1500.0, 2000.0, 2500.0, 3000.0, 4000.0, 5000]
337
- return min(range(len(level_depth)), key=lambda i: abs(level_depth[i] - depth))
338
-
339
- if var not in ["ssh", "u_b", "v_b", "temp_b", "salt_b"] and var in ["u", "v", "temp", "salt"]:
340
- if mode == "depth":
341
- if depth < 0 or depth > 5000:
342
- print("Please ensure the depth is in the range of 0-5000 m")
343
- query_dict["vertCoord"] = get_nearest_level_index(depth) + 1
344
- elif mode == "level":
345
- if level_num < 1 or level_num > 40:
346
- print("Please ensure the level_num is in the range of 1-40")
347
- query_dict["vertCoord"] = max(1, min(level_num, 40))
348
- elif mode == "full":
349
- query_dict["vertStride"] = 1
350
- else:
351
- raise ValueError("Invalid mode. Choose from 'depth', 'level', or 'full'")
352
-
353
- query_dict = {k: v for k, v in query_dict.items() if v is not None}
354
-
355
- return query_dict
356
-
357
-
358
- def _check_time_in_dataset_and_version(time_input, time_end=None):
359
- # 判断是处理单个时间点还是时间范围
360
- is_single_time = time_end is None
361
-
362
- # 如果是单个时间点,初始化时间范围
363
- if is_single_time:
364
- time_start = int(time_input)
365
- time_end = time_start
366
- time_input_str = str(time_input)
367
- else:
368
- time_start = int(time_input)
369
- time_end = int(time_end)
370
- time_input_str = f"{time_input}-{time_end}"
371
-
372
- # 根据时间长度补全时间格式
373
- if len(str(time_start)) == 8:
374
- time_start = str(time_start) + "00"
375
- if len(str(time_end)) == 8:
376
- time_end = str(time_end) + "21"
377
- time_start, time_end = int(time_start), int(time_end)
378
-
379
- d_list = []
380
- v_list = []
381
- trange_list = []
382
- have_data = False
383
-
384
- # 遍历数据集和版本
385
- for dataset_name in data_info["hourly"]["dataset"].keys():
386
- for version_name in data_info["hourly"]["dataset"][dataset_name]["version"].keys():
387
- time_s, time_e = list(data_info["hourly"]["dataset"][dataset_name]["version"][version_name]["time_range"].values())
388
- time_s, time_e = str(time_s), str(time_e)
389
- if len(time_s) == 8:
390
- time_s = time_s + "00"
391
- if len(time_e) == 8:
392
- time_e = time_e + "21"
393
- # 检查时间是否在数据集的时间范围内
394
- if is_single_time:
395
- if time_start >= int(time_s) and time_start <= int(time_e):
396
- d_list.append(dataset_name)
397
- v_list.append(version_name)
398
- trange_list.append(f"{time_s}-{time_e}")
399
- have_data = True
400
- else:
401
- if time_start >= int(time_s) and time_end <= int(time_e):
402
- d_list.append(dataset_name)
403
- v_list.append(version_name)
404
- trange_list.append(f"{time_s}-{time_e}")
405
- have_data = True
406
-
407
- if have_data:
408
- if match_time is None:
409
- print(f"[bold red]Time {time_input_str} included in:")
410
- dv_num = 1
411
- for d, v, trange in zip(d_list, v_list, trange_list):
412
- print(f"{dv_num} -> [bold blue]{d} - {v} : {trange}")
413
- dv_num += 1
414
- if is_single_time:
415
- return True
416
- else:
417
- base_url_s = _get_base_url(d_list[0], v_list[0], "u", str(time_start))
418
- base_url_e = _get_base_url(d_list[0], v_list[0], "u", str(time_end))
419
- if base_url_s == base_url_e:
420
- return True
421
- else:
422
- print(f"[bold red]{time_start} to {time_end} is in different datasets or versions, so you can't download them together")
423
- return False
424
- else:
425
- print(f"[bold red]Time {time_input_str} has no data")
426
- return False
427
-
428
-
429
- def _ensure_time_in_specific_dataset_and_version(dataset_name, version_name, time_input, time_end=None):
430
- # 根据时间长度补全时间格式
431
- if len(str(time_input)) == 8:
432
- time_input = str(time_input) + "00"
433
- time_start = int(time_input)
434
- if time_end is not None:
435
- if len(str(time_end)) == 8:
436
- time_end = str(time_end) + "21"
437
- time_end = int(time_end)
438
- else:
439
- time_end = time_start
440
-
441
- # 检查指定的数据集和版本是否存在
442
- if dataset_name not in data_info["hourly"]["dataset"]:
443
- print(f"[bold red]Dataset {dataset_name} not found.")
444
- return False
445
- if version_name not in data_info["hourly"]["dataset"][dataset_name]["version"]:
446
- print(f"[bold red]Version {version_name} not found in dataset {dataset_name}.")
447
- return False
448
-
449
- # 获取指定数据集和版本的时间范围
450
- time_range = data_info["hourly"]["dataset"][dataset_name]["version"][version_name]["time_range"]
451
- time_s, time_e = list(time_range.values())
452
- time_s, time_e = str(time_s), str(time_e)
453
- if len(time_s) == 8:
454
- time_s = time_s + "00"
455
- if len(time_e) == 8:
456
- time_e = time_e + "21"
457
- time_s, time_e = int(time_s), int(time_e)
458
-
459
- # 检查时间是否在指定数据集和版本的时间范围内
460
- if time_start >= time_s and time_end <= time_e:
461
- print(f"[bold blue]Time {time_input} to {time_end} is within dataset {dataset_name} and version {version_name}.")
462
- return True
463
- else:
464
- print(f"[bold red]Time {time_input} to {time_end} is not within dataset {dataset_name} and version {version_name}.")
465
- return False
466
-
467
-
468
- def _direct_choose_dataset_and_version(time_input, time_end=None):
469
- # 假设 data_info 是一个字典,包含了数据集和版本的信息
470
- # 示例结构:data_info['hourly']['dataset'][dataset_name]['version'][version_name]['time_range']
471
-
472
- if len(str(time_input)) == 8:
473
- time_input = str(time_input) + "00"
474
-
475
- # 如果 time_end 是 None,则将 time_input 的值赋给它
476
- if time_end is None:
477
- time_end = time_input
478
-
479
- # 处理开始和结束时间,确保它们是完整的 ymdh 格式
480
- time_start, time_end = int(str(time_input)[:10]), int(str(time_end)[:10])
481
-
482
- dataset_name_out, version_name_out = None, None
483
-
484
- for dataset_name in data_info["hourly"]["dataset"].keys():
485
- for version_name in data_info["hourly"]["dataset"][dataset_name]["version"].keys():
486
- [time_s, time_e] = list(data_info["hourly"]["dataset"][dataset_name]["version"][version_name]["time_range"].values())
487
- time_s, time_e = str(time_s), str(time_e)
488
- if len(time_s) == 8:
489
- time_s = time_s + "00"
490
- if len(time_e) == 8:
491
- time_e = time_e + "21"
492
- time_s, time_e = int(time_s), int(time_e)
493
-
494
- # 检查时间是否在数据集版本的时间范围内
495
- if time_start >= time_s and time_end <= time_e:
496
- dataset_name_out, version_name_out = dataset_name, version_name
497
-
498
- if dataset_name_out is not None and version_name_out is not None:
499
- if match_time is None:
500
- # print(f"[bold purple]dataset: {dataset_name_out}, version: {version_name_out} is chosen")
501
- print(f"[bold purple]Chosen dataset: {dataset_name_out} - {version_name_out}")
502
-
503
- # 如果没有找到匹配的数据集和版本,会返回 None
504
- return dataset_name_out, version_name_out
505
-
506
-
507
- def _get_base_url(dataset_name, version_name, var, ymdh_str):
508
- year_str = int(ymdh_str[:4])
509
- url_dict = data_info["hourly"]["dataset"][dataset_name]["version"][version_name]["url"]
510
- classification_method = data_info["hourly"]["dataset"][dataset_name]["version"][version_name]["classification"]
511
- if classification_method == "year_different":
512
- base_url = url_dict[str(year_str)]
513
- elif classification_method == "same_path":
514
- base_url = url_dict
515
- elif classification_method == "var_different":
516
- base_url = None
517
- for key, value in var_group.items():
518
- if var in value:
519
- base_url = url_dict[key]
520
- break
521
- if base_url is None:
522
- print("Please ensure the var is in [u,v,temp,salt,ssh,u_b,v_b,temp_b,salt_b]")
523
- elif classification_method == "var_year_different":
524
- if dataset_name == "GLBy0.08" and version_name == "93.0":
525
- mdh_str = ymdh_str[4:]
526
- # GLBy0.08 93.0
527
- # data time range in each year: year-01-01 12:00 to year+1-01-01 09:00
528
- if "010100" <= mdh_str <= "010109":
529
- year_str = int(ymdh_str[:4]) - 1
530
- else:
531
- year_str = int(ymdh_str[:4])
532
- base_url = None
533
- for key, value in var_group.items():
534
- if var in value:
535
- base_url = url_dict[key][str(year_str)]
536
- break
537
- if base_url is None:
538
- print("Please ensure the var is in [u,v,temp,salt,ssh,u_b,v_b,temp_b,salt_b]")
539
- elif classification_method == "single_var_year_different":
540
- base_url = None
541
- if dataset_name == "ESPC_D" and version_name == "V02":
542
- mdh_str = ymdh_str[4:]
543
- # ESPC-D-V02
544
- if "010100" <= mdh_str <= "010109":
545
- year_str = int(ymdh_str[:4]) - 1
546
- else:
547
- year_str = int(ymdh_str[:4])
548
- for key, value in single_var_group.items():
549
- if var in value:
550
- base_url = url_dict[key][str(year_str)]
551
- break
552
- if base_url is None:
553
- print("Please ensure the var is in [u,v,temp,salt,ssh]")
554
- return base_url
555
-
556
-
557
- def _get_submit_url(dataset_name, version_name, var, ymdh_str, query_dict):
558
- base_url = _get_base_url(dataset_name, version_name, var, ymdh_str)
559
- if isinstance(query_dict["var"], str):
560
- query_dict["var"] = [query_dict["var"]]
561
- target_url = base_url + "&".join(f"var={var}" for var in query_dict["var"]) + "&" + "&".join(f"{key}={value}" for key, value in query_dict.items() if key != "var")
562
- return target_url
563
-
564
-
565
- def _clear_existing_file(file_full_path):
566
- if os.path.exists(file_full_path):
567
- os.remove(file_full_path)
568
- print(f"{file_full_path} has been removed")
569
-
570
-
571
- def _check_existing_file(file_full_path, avg_size):
572
- if os.path.exists(file_full_path):
573
- print(f"[bold #FFA54F]{file_full_path} exists")
574
- fsize = file_size(file_full_path)
575
- delta_size_ratio = (fsize - avg_size) / avg_size
576
- if abs(delta_size_ratio) > 0.025:
577
- if check_nc(file_full_path):
578
- return True
579
- else:
580
- # print(f"File size is abnormal and cannot be opened, {file_full_path}: {fsize:.2f} KB")
581
- return False
582
- else:
583
- return True
584
- else:
585
- return False
586
-
587
-
588
- def _get_mean_size_move(same_file, current_file):
589
- with fsize_dict_lock:
590
- if same_file not in fsize_dict.keys():
591
- fsize_dict[same_file] = {"size_list": [], "mean_size": 1.0}
592
-
593
- tolerance_ratio = 0.025
594
- current_file_size = file_size(current_file)
595
-
596
- if fsize_dict[same_file]["size_list"]:
597
- fsize_dict[same_file]["mean_size"] = sum(fsize_dict[same_file]["size_list"]) / len(fsize_dict[same_file]["size_list"])
598
- fsize_dict[same_file]["mean_size"] = max(fsize_dict[same_file]["mean_size"], 1.0)
599
- else:
600
- fsize_dict[same_file]["mean_size"] = 1.0
601
-
602
- size_difference_ratio = (current_file_size - fsize_dict[same_file]["mean_size"]) / fsize_dict[same_file]["mean_size"]
603
-
604
- if abs(size_difference_ratio) > tolerance_ratio:
605
- if check_nc(current_file, print_messages=False):
606
- fsize_dict[same_file]["size_list"] = [current_file_size]
607
- fsize_dict[same_file]["mean_size"] = current_file_size
608
- else:
609
- _clear_existing_file(current_file)
610
- # print(f"File size is abnormal, may need to be downloaded again, file size: {current_file_size:.2f} KB")
611
- else:
612
- fsize_dict[same_file]["size_list"].append(current_file_size)
613
-
614
- return fsize_dict[same_file]["mean_size"]
615
-
616
-
617
- def _check_ftime(nc_file, tname="time", if_print=False):
618
- if not os.path.exists(nc_file):
619
- return False
620
- nc_file = str(nc_file)
621
- try:
622
- ds = xr.open_dataset(nc_file)
623
- real_time = ds[tname].values[0]
624
- ds.close()
625
- real_time = str(real_time)[:13]
626
- real_time = real_time.replace("-", "").replace("T", "")
627
- f_time = re.findall(r"\d{10}", nc_file)[0]
628
- if real_time == f_time:
629
- return True
630
- else:
631
- if if_print:
632
- print(f"[bold #daff5c]File time error, file/real time: [bold blue]{f_time}/{real_time}")
633
- return False
634
- except Exception as e:
635
- if if_print:
636
- print(f"[bold #daff5c]File time check failed, {nc_file}: {e}")
637
- return False
638
-
639
-
640
- def _correct_time(nc_file):
641
- dataset = nc.Dataset(nc_file)
642
- time_units = dataset.variables["time"].units
643
- dataset.close()
644
- origin_str = time_units.split("since")[1].strip()
645
- origin_datetime = datetime.datetime.strptime(origin_str, "%Y-%m-%d %H:%M:%S")
646
- given_date_str = re.findall(r"\d{10}", str(nc_file))[0]
647
- given_datetime = datetime.datetime.strptime(given_date_str, "%Y%m%d%H")
648
- time_difference = (given_datetime - origin_datetime).total_seconds()
649
- if "hours" in time_units:
650
- time_difference /= 3600
651
- elif "days" in time_units:
652
- time_difference /= 3600 * 24
653
- modify_nc(nc_file, "time", None, time_difference)
654
-
655
-
656
- class _HycomDownloader:
657
- def __init__(self, tasks, delay_range=(3, 6), timeout_factor=120, max_var_count=5, max_retries=3):
658
- """
659
- :param tasks: List of (url, save_path)
660
- """
661
- self.tasks = tasks
662
- self.delay_range = delay_range
663
- self.timeout_factor = timeout_factor
664
- self.max_var_count = max_var_count
665
- self.max_retries = max_retries
666
- self.count = {"success": 0, "fail": 0}
667
-
668
- def user_agent(self):
669
- return get_ua()
670
-
671
- async def _download_one(self, url, save_path):
672
- file_name = os.path.basename(save_path)
673
- headers = {"User-Agent": self.user_agent()}
674
- var_count = min(max(url.count("var="), 1), self.max_var_count)
675
- timeout_max = self.timeout_factor * var_count
676
- timeout = random.randint(timeout_max // 2, timeout_max)
677
-
678
- retry = 0
679
- while retry <= self.max_retries:
680
- if proxy_txt_path:
681
- from .read_proxy import get_valid_proxy
682
-
683
- proxy_one = get_valid_proxy(proxy_txt_path)
684
- if proxy_one:
685
- if proxy_one.startswith("http://"):
686
- proxy_one = proxy_one[7:]
687
- elif proxy_one.startswith("https://"):
688
- proxy_one = proxy_one[8:]
689
- else:
690
- proxy_one = None
691
- if proxy_one:
692
- proxy = f"http://{proxy_one}"
693
- mounts = {
694
- "http://": httpx.AsyncHTTPTransport(proxy=proxy),
695
- "https://": httpx.AsyncHTTPTransport(proxy=proxy),
696
- }
697
- else:
698
- proxy = None
699
- mounts = None
700
- try:
701
- await asyncio.sleep(random.uniform(*self.delay_range))
702
- start = datetime.datetime.now()
703
-
704
- async with httpx.AsyncClient(
705
- timeout=httpx.Timeout(timeout),
706
- limits=httpx.Limits(max_connections=2, max_keepalive_connections=2),
707
- transport=httpx.AsyncHTTPTransport(retries=2),
708
- # proxy=proxy,
709
- mounts=mounts,
710
- ) as client:
711
- print(f"[bold #f0f6d0]Requesting {file_name} (Attempt {retry + 1}) ...")
712
- response = await client.get(url, headers=headers, follow_redirects=True)
713
- response.raise_for_status()
714
- if not response.content:
715
- raise ValueError("Empty response received")
716
-
717
- print(f"[bold #96cbd7]Downloading {file_name} ...")
718
- with open(save_path, "wb") as f:
719
- async for chunk in response.aiter_bytes(32 * 1024):
720
- f.write(chunk)
721
-
722
- elapsed = datetime.datetime.now() - start
723
- print(f"[#3dfc40]File [bold #dfff73]{file_name} [#3dfc40]downloaded, Time: [#39cbdd]{elapsed}")
724
- self.count["success"] += 1
725
- count_dict["success"] += 1
726
- return
727
-
728
- except Exception as e:
729
- print(f"[bold red]Failed ({type(e).__name__}): {e}")
730
- if retry < self.max_retries:
731
- backoff = 2**retry
732
- print(f"[yellow]Retrying in {backoff:.1f}s ...")
733
- await asyncio.sleep(backoff)
734
- retry += 1
735
- else:
736
- print(f"[red]Giving up on {file_name}")
737
- self.count["fail"] += 1
738
- count_dict["fail"] += 1
739
- return
740
-
741
- async def run(self):
742
- print(f"📥 Starting download of {len(self.tasks)} files ...")
743
- for url, save_path in self.tasks:
744
- await self._download_one(url, save_path)
745
-
746
- print("\n✅ All tasks completed.")
747
- print(f"✔️ Success: {self.count['success']} | ❌ Fail: {self.count['fail']}")
748
-
749
-
750
- def _download_file(target_url, store_path, file_name, cover=False):
751
- save_path = Path(store_path) / file_name
752
- file_name_split = file_name.split("_")
753
- file_name_split = file_name_split[:-1]
754
- same_file = "_".join(file_name_split) + "*nc"
755
-
756
- if match_time is not None:
757
- if check_nc(save_path, print_messages=False):
758
- if not _check_ftime(save_path, if_print=True):
759
- if match_time:
760
- _correct_time(save_path)
761
- count_dict["skip"] += 1
762
- else:
763
- _clear_existing_file(save_path)
764
- count_dict["no_data"] += 1
765
- else:
766
- count_dict["skip"] += 1
767
- print(f"[bold green]{file_name} is correct")
768
- return
769
-
770
- if not cover and os.path.exists(save_path):
771
- print(f"[bold #FFA54F]{save_path} exists, skipping ...")
772
- count_dict["skip"] += 1
773
- return
774
-
775
- if same_file not in fsize_dict.keys():
776
- check_nc(save_path, delete_if_invalid=True, print_messages=False)
777
-
778
- get_mean_size = _get_mean_size_move(same_file, save_path)
779
-
780
- if _check_existing_file(save_path, get_mean_size):
781
- count_dict["skip"] += 1
782
- return
783
-
784
- _clear_existing_file(save_path)
785
-
786
- if not use_idm:
787
- python_downloader = _HycomDownloader([(target_url, save_path)])
788
- asyncio.run(python_downloader.run())
789
- time.sleep(3 + random.uniform(0, 10))
790
- else:
791
- idm_downloader(target_url, store_path, file_name, given_idm_engine)
792
- idm_download_list.append(save_path)
793
- # print(f"[bold #3dfc40]File [bold #dfff73]{save_path} [#3dfc40]has been submit to IDM for downloading")
794
- time.sleep(3 + random.uniform(0, 10))
795
-
796
-
797
- def _check_hour_is_valid(ymdh_str):
798
- hh = int(str(ymdh_str[-2:]))
799
- if hh in [0, 3, 6, 9, 12, 15, 18, 21]:
800
- return True
801
- else:
802
- return False
803
-
804
-
805
- def _check_dataset_version(dataset_name, version_name, download_time, download_time_end=None):
806
- if dataset_name is not None and version_name is not None:
807
- just_ensure = _ensure_time_in_specific_dataset_and_version(dataset_name, version_name, download_time, download_time_end)
808
- if just_ensure:
809
- return dataset_name, version_name
810
- else:
811
- return None, None
812
-
813
- download_time_str = str(download_time)
814
-
815
- if len(download_time_str) == 8:
816
- download_time_str = download_time_str + "00"
817
-
818
- if download_time_end is None and not _check_hour_is_valid(download_time_str):
819
- print("Please ensure the hour is 00, 03, 06, 09, 12, 15, 18, 21")
820
- raise ValueError("The hour is invalid")
821
-
822
- if download_time_end is not None:
823
- if len(str(download_time_end)) == 8:
824
- download_time_end = str(download_time_end) + "21"
825
- have_data = _check_time_in_dataset_and_version(download_time_str, download_time_end)
826
- if have_data:
827
- return _direct_choose_dataset_and_version(download_time_str, download_time_end)
828
- else:
829
- have_data = _check_time_in_dataset_and_version(download_time_str)
830
- if have_data:
831
- return _direct_choose_dataset_and_version(download_time_str)
832
-
833
- return None, None
834
-
835
-
836
- def _get_submit_url_var(var, depth, level_num, lon_min, lon_max, lat_min, lat_max, dataset_name, version_name, download_time, download_time_end=None):
837
- ymdh_str = str(download_time)
838
- if depth is not None and level_num is not None:
839
- print("Please ensure the depth or level_num is None")
840
- print("Progress will use the depth")
841
- which_mode = "depth"
842
- elif depth is not None and level_num is None:
843
- print(f"Data of single depth (~{depth} m) will be downloaded...")
844
- which_mode = "depth"
845
- elif level_num is not None and depth is None:
846
- print(f"Data of single level ({level_num}) will be downloaded...")
847
- which_mode = "level"
848
- else:
849
- which_mode = "full"
850
- query_dict = _get_query_dict(var, lon_min, lon_max, lat_min, lat_max, download_time, download_time_end, which_mode, depth, level_num)
851
- submit_url = _get_submit_url(dataset_name, version_name, var, ymdh_str, query_dict)
852
- return submit_url
853
-
854
-
855
- def _prepare_url_to_download(var, lon_min=0, lon_max=359.92, lat_min=-80, lat_max=90, download_time="2024083100", download_time_end=None, depth=None, level_num=None, store_path=None, dataset_name=None, version_name=None, cover=False):
856
- print("[bold #ecdbfe]-" * mark_len)
857
- download_time = str(download_time)
858
- if download_time_end is not None:
859
- download_time_end = str(download_time_end)
860
- dataset_name, version_name = _check_dataset_version(dataset_name, version_name, download_time, download_time_end)
861
- else:
862
- dataset_name, version_name = _check_dataset_version(dataset_name, version_name, download_time)
863
- if dataset_name is None and version_name is None:
864
- count_dict["no_data"] += 1
865
- if download_time_end is not None:
866
- count_dict["no_data_list"].append(f"{download_time}-{download_time_end}")
867
- else:
868
- count_dict["no_data_list"].append(download_time)
869
- return
870
-
871
- if isinstance(var, str):
872
- var = [var]
873
-
874
- if isinstance(var, list):
875
- if len(var) == 1:
876
- var = var[0]
877
- submit_url = _get_submit_url_var(var, depth, level_num, lon_min, lon_max, lat_min, lat_max, dataset_name, version_name, download_time, download_time_end)
878
- file_name = f"HYCOM_{variable_info[var]['var_name']}_{download_time}.nc"
879
- if download_time_end is not None:
880
- file_name = f"HYCOM_{variable_info[var]['var_name']}_{download_time}-{download_time_end}.nc"
881
- _download_file(submit_url, store_path, file_name, cover)
882
- else:
883
- if download_time < "2024081012":
884
- varlist = [_ for _ in var]
885
- for key, value in var_group.items():
886
- current_group = []
887
- for v in varlist:
888
- if v in value:
889
- current_group.append(v)
890
- if len(current_group) == 0:
891
- continue
892
-
893
- var = current_group[0]
894
- submit_url = _get_submit_url_var(var, depth, level_num, lon_min, lon_max, lat_min, lat_max, dataset_name, version_name, download_time, download_time_end)
895
- file_name = f"HYCOM_{variable_info[var]['var_name']}_{download_time}.nc"
896
- old_str = f"var={variable_info[var]['var_name']}"
897
- new_str = f"var={variable_info[var]['var_name']}"
898
- if len(current_group) > 1:
899
- for v in current_group[1:]:
900
- new_str = f"{new_str}&var={variable_info[v]['var_name']}"
901
- submit_url = submit_url.replace(old_str, new_str)
902
- file_name = f"HYCOM_{key}_{download_time}.nc"
903
- if download_time_end is not None:
904
- file_name = f"HYCOM_{key}_{download_time}-{download_time_end}.nc"
905
- _download_file(submit_url, store_path, file_name, cover)
906
- else:
907
- for v in var:
908
- submit_url = _get_submit_url_var(v, depth, level_num, lon_min, lon_max, lat_min, lat_max, dataset_name, version_name, download_time, download_time_end)
909
- file_name = f"HYCOM_{variable_info[v]['var_name']}_{download_time}.nc"
910
- if download_time_end is not None:
911
- file_name = f"HYCOM_{variable_info[v]['var_name']}_{download_time}-{download_time_end}.nc"
912
- _download_file(submit_url, store_path, file_name, cover)
913
-
914
-
915
- def _convert_full_name_to_short_name(full_name):
916
- for var, info in variable_info.items():
917
- if full_name == info["var_name"] or full_name == info["standard_name"] or full_name == var:
918
- return var
919
- print("[bold #FFE4E1]Please ensure the var is in:\n[bold blue]u,v,temp,salt,ssh,u_b,v_b,temp_b,salt_b")
920
- print("or")
921
- print("[bold blue]water_u, water_v, water_temp, salinity, surf_el, water_u_bottom, water_v_bottom, water_temp_bottom, salinity_bottom")
922
- return False
923
-
924
-
925
- def _download_task(var, time_str, time_str_end, lon_min, lon_max, lat_min, lat_max, depth, level, store_path, dataset_name, version_name, cover):
926
- _prepare_url_to_download(var, lon_min, lon_max, lat_min, lat_max, time_str, time_str_end, depth, level, store_path, dataset_name, version_name, cover)
927
-
928
-
929
- def _done_callback(future, progress, task, total, counter_lock):
930
- global parallel_counter
931
- with counter_lock:
932
- parallel_counter += 1
933
- progress.update(task, advance=1, description=f"[cyan]{bar_desc} {parallel_counter}/{total}")
934
-
935
-
936
- def _download_hourly_func(var, time_s, time_e, lon_min=0, lon_max=359.92, lat_min=-80, lat_max=90, depth=None, level=None, store_path=None, dataset_name=None, version_name=None, num_workers=None, cover=False, interval_hour=3):
937
- ymdh_time_s, ymdh_time_e = str(time_s), str(time_e)
938
- if num_workers is not None and num_workers > 1:
939
- global parallel_counter
940
- parallel_counter = 0
941
- counter_lock = Lock()
942
- if ymdh_time_s == ymdh_time_e:
943
- _prepare_url_to_download(var, lon_min, lon_max, lat_min, lat_max, ymdh_time_s, None, depth, level, store_path, dataset_name, version_name, cover)
944
- elif int(ymdh_time_s) < int(ymdh_time_e):
945
- if match_time is None:
946
- print("*" * mark_len)
947
- print("Downloading a series of files...")
948
- time_list = _get_time_list(ymdh_time_s, ymdh_time_e, interval_hour, "hour")
949
- with Progress() as progress:
950
- task = progress.add_task(f"[cyan]{bar_desc}", total=len(time_list))
951
- if num_workers is None or num_workers <= 1:
952
- for i, time_str in enumerate(time_list):
953
- _prepare_url_to_download(var, lon_min, lon_max, lat_min, lat_max, time_str, None, depth, level, store_path, dataset_name, version_name, cover)
954
- progress.update(task, advance=1, description=f"[cyan]{bar_desc} {i + 1}/{len(time_list)}")
955
- else:
956
- with ThreadPoolExecutor(max_workers=num_workers) as executor:
957
- futures = [executor.submit(_download_task, var, time_str, None, lon_min, lon_max, lat_min, lat_max, depth, level, store_path, dataset_name, version_name, cover) for time_str in time_list]
958
- for feature in as_completed(futures):
959
- _done_callback(feature, progress, task, len(time_list), counter_lock)
960
- else:
961
- print("[bold red]Please ensure the time_s is no more than time_e")
962
-
963
-
964
- def download(
965
- variables,
966
- start_time,
967
- end_time=None,
968
- lon_min=0,
969
- lon_max=359.92,
970
- lat_min=-80,
971
- lat_max=90,
972
- depth=None,
973
- level=None,
974
- output_dir=None,
975
- dataset=None,
976
- version=None,
977
- workers=None,
978
- overwrite=False,
979
- idm_path=None,
980
- validate_time=None,
981
- interval_hours=3,
982
- proxy_txt=None,
983
- ):
984
- """
985
- Download data for a single time or a series of times.
986
-
987
- Parameters:
988
- variables (str or list): Variable names to download. Examples include:
989
- 'u', 'v', 'temp', 'salt', 'ssh', 'u_b', 'v_b', 'temp_b', 'salt_b'
990
- or their full names like 'water_u', 'water_v', etc.
991
- start_time (str): Start time in the format 'YYYYMMDDHH' or 'YYYYMMDD'.
992
- If hour is included, it must be one of [00, 03, 06, 09, 12, 15, 18, 21].
993
- end_time (str, optional): End time in the format 'YYYYMMDDHH' or 'YYYYMMDD'.
994
- If not provided, only data for the start_time will be downloaded.
995
- lon_min (float, optional): Minimum longitude. Default is 0.
996
- lon_max (float, optional): Maximum longitude. Default is 359.92.
997
- lat_min (float, optional): Minimum latitude. Default is -80.
998
- lat_max (float, optional): Maximum latitude. Default is 90.
999
- depth (float, optional): Depth in meters. If specified, data for a single depth
1000
- will be downloaded. Suggested range: [0, 5000].
1001
- level (int, optional): Vertical level number. If specified, data for a single
1002
- level will be downloaded. Suggested range: [1, 40].
1003
- output_dir (str, optional): Directory to save downloaded files. If not provided,
1004
- files will be saved in the current working directory.
1005
- dataset (str, optional): Dataset name. Examples: 'GLBv0.08', 'GLBu0.08', etc.
1006
- If not provided, the dataset will be chosen based on the time range.
1007
- version (str, optional): Dataset version. Examples: '53.X', '56.3', etc.
1008
- If not provided, the version will be chosen based on the time range.
1009
- workers (int, optional): Number of parallel workers. Default is 1. Maximum is 10.
1010
- overwrite (bool, optional): Whether to overwrite existing files. Default is False.
1011
- idm_path (str, optional): Path to the Internet Download Manager (IDM) executable.
1012
- If provided, IDM will be used for downloading.
1013
- validate_time (bool, optional): Time validation mode. Default is None.
1014
- - None: Only download data.
1015
- - True: Modify the real time in the data to match the file name.
1016
- - False: Check if the real time matches the file name. If not, delete the file.
1017
- interval_hours (int, optional): Time interval in hours for downloading data.
1018
- Default is 3. Examples: 3, 6, etc.
1019
-
1020
- Returns:
1021
- None
1022
-
1023
- Example:
1024
- >>> download(
1025
- variables='u',
1026
- start_time='2024083100',
1027
- end_time='2024090100',
1028
- lon_min=0,
1029
- lon_max=359.92,
1030
- lat_min=-80,
1031
- lat_max=90,
1032
- depth=None,
1033
- level=None,
1034
- output_dir=None,
1035
- dataset=None,
1036
- version=None,
1037
- workers=4,
1038
- overwrite=False,
1039
- idm_path=None,
1040
- validate_time=None,
1041
- interval_hours=3,
1042
- )
1043
- """
1044
- from oafuncs.oa_tool import pbar
1045
-
1046
- _get_initial_data()
1047
-
1048
- if dataset is None and version is None:
1049
- if validate_time is None:
1050
- print("Dataset and version will be chosen based on the time range.")
1051
- print("If multiple datasets or versions exist, the latest one will be used.")
1052
- elif dataset is None:
1053
- print("Please provide a dataset name if specifying a version.")
1054
- elif version is None:
1055
- print("Please provide a version if specifying a dataset name.")
1056
- else:
1057
- print("Using the specified dataset and version.")
1058
-
1059
- if isinstance(variables, list):
1060
- if len(variables) == 1:
1061
- variables = _convert_full_name_to_short_name(variables[0])
1062
- else:
1063
- variables = [_convert_full_name_to_short_name(v) for v in variables]
1064
- elif isinstance(variables, str):
1065
- variables = _convert_full_name_to_short_name(variables)
1066
- else:
1067
- raise ValueError("Invalid variable(s) provided.")
1068
- if variables is False:
1069
- raise ValueError("Invalid variable(s) provided.")
1070
- if not (0 <= lon_min <= 359.92 and 0 <= lon_max <= 359.92 and -80 <= lat_min <= 90 and -80 <= lat_max <= 90):
1071
- raise ValueError("Longitude or latitude values are out of range.")
1072
-
1073
- if output_dir is None:
1074
- output_dir = str(Path.cwd())
1075
- else:
1076
- os.makedirs(output_dir, exist_ok=True)
1077
-
1078
- if workers is not None:
1079
- workers = max(min(workers, 10), 1)
1080
- start_time = str(start_time)
1081
- if len(start_time) == 8:
1082
- start_time += "00"
1083
- if end_time is None:
1084
- end_time = start_time[:]
1085
- else:
1086
- end_time = str(end_time)
1087
- if len(end_time) == 8:
1088
- end_time += "21"
1089
-
1090
- global count_dict
1091
- count_dict = {"success": 0, "fail": 0, "skip": 0, "no_data": 0, "total": 0, "no_data_list": []}
1092
-
1093
- global fsize_dict
1094
- fsize_dict = {}
1095
-
1096
- global fsize_dict_lock
1097
- fsize_dict_lock = Lock()
1098
-
1099
- global use_idm, given_idm_engine, idm_download_list, bar_desc
1100
- if idm_path is not None:
1101
- use_idm = True
1102
- workers = 1
1103
- given_idm_engine = idm_path
1104
- idm_download_list = []
1105
- bar_desc = "Submitting to IDM ..."
1106
- else:
1107
- use_idm = False
1108
- bar_desc = "Downloading ..."
1109
-
1110
- global match_time
1111
- match_time = validate_time
1112
-
1113
- global mark_len
1114
- mark_len = 100
1115
-
1116
- global proxy_txt_path
1117
- proxy_txt_path = proxy_txt
1118
-
1119
- if validate_time is not None:
1120
- workers = 1
1121
- print("*" * mark_len)
1122
- print("[bold red]Only checking the time of existing files.")
1123
- bar_desc = "Checking time ..."
1124
-
1125
- _download_hourly_func(
1126
- variables,
1127
- start_time,
1128
- end_time,
1129
- lon_min,
1130
- lon_max,
1131
- lat_min,
1132
- lat_max,
1133
- depth,
1134
- level,
1135
- output_dir,
1136
- dataset,
1137
- version,
1138
- workers,
1139
- overwrite,
1140
- int(interval_hours),
1141
- )
1142
-
1143
- if idm_path is not None:
1144
- print("[bold #ecdbfe]*" * mark_len)
1145
- print(f"[bold #3dfc40]{'All files have been submitted to IDM for downloading'.center(mark_len, '*')}")
1146
- print("[bold #ecdbfe]*" * mark_len)
1147
- if idm_download_list:
1148
- remain_list = idm_download_list.copy()
1149
- for _ in pbar(range(len(idm_download_list)), cmap="diverging_1", description="Downloading: "):
1150
- success = False
1151
- while not success:
1152
- for f in remain_list:
1153
- if check_nc(f, print_messages=False):
1154
- count_dict["success"] += 1
1155
- success = True
1156
- remain_list.remove(f)
1157
- break
1158
-
1159
- count_dict["total"] = count_dict["success"] + count_dict["fail"] + count_dict["skip"] + count_dict["no_data"]
1160
- print("[bold #ecdbfe]=" * mark_len)
1161
- print(f"[bold #ff80ab]Total: {count_dict['total']}\nSuccess: {count_dict['success']}\nFail: {count_dict['fail']}\nSkip: {count_dict['skip']}\nNo data: {count_dict['no_data']}")
1162
- print("[bold #ecdbfe]=" * mark_len)
1163
- if count_dict["fail"] > 0:
1164
- print("[bold #be5528]Please try again to download the failed data later.")
1165
- if count_dict["no_data"] > 0:
1166
- print(f"[bold #f90000]{count_dict['no_data']} data entries do not exist in any dataset or version.")
1167
- for no_data in count_dict["no_data_list"]:
1168
- print(f"[bold #d81b60]{no_data}")
1169
- print("[bold #ecdbfe]=" * mark_len)
1170
-
1171
-
1172
- if __name__ == "__main__":
1173
- download_dict = {
1174
- "water_u": {"simple_name": "u", "download": 1},
1175
- "water_v": {"simple_name": "v", "download": 1},
1176
- "surf_el": {"simple_name": "ssh", "download": 1},
1177
- "water_temp": {"simple_name": "temp", "download": 1},
1178
- "salinity": {"simple_name": "salt", "download": 1},
1179
- "water_u_bottom": {"simple_name": "u_b", "download": 0},
1180
- "water_v_bottom": {"simple_name": "v_b", "download": 0},
1181
- "water_temp_bottom": {"simple_name": "temp_b", "download": 0},
1182
- "salinity_bottom": {"simple_name": "salt_b", "download": 0},
1183
- }
1184
-
1185
- var_list = [var_name for var_name in download_dict.keys() if download_dict[var_name]["download"]]
1186
-
1187
- single_var = False
1188
-
1189
- options = {
1190
- "variables": var_list,
1191
- "start_time": "2018010100",
1192
- "end_time": "2019063000",
1193
- "output_dir": r"G:\Data\HYCOM\china_sea\hourly_24",
1194
- "lon_min": 105,
1195
- "lon_max": 135,
1196
- "lat_min": 10,
1197
- "lat_max": 45,
1198
- "workers": 1,
1199
- "overwrite": False,
1200
- "depth": None,
1201
- "level": None,
1202
- "validate_time": None,
1203
- # "idm_path": r"D:\Programs\Internet Download Manager\IDMan.exe",
1204
- "interval_hours": 24,
1205
- "proxy_txt": None,
1206
- }
1207
-
1208
- if single_var:
1209
- for var_name in var_list:
1210
- options["variables"] = var_name
1211
- download(**options)
1212
- else:
1213
- download(**options)