oafuncs 0.0.97.1__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,1309 @@
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ """
4
+ Author: Liu Kun && 16031215@qq.com
5
+ Date: 2025-01-29 19:05:09
6
+ LastEditors: Liu Kun && 16031215@qq.com
7
+ LastEditTime: 2025-01-29 19:05:10
8
+ FilePath: \\Python\\My_Funcs\\OAFuncs\\oafuncs\\oa_down\\hycom_3hourly_20250129 copy.py
9
+ Description:
10
+ EditPlatform: vscode
11
+ ComputerInfo: XPS 15 9510
12
+ SystemInfo: Windows 11
13
+ Python Version: 3.12
14
+ """
15
+
16
+
17
+
18
+
19
+ import datetime
20
+ import os
21
+ import random
22
+ import re
23
+ import time
24
+ import warnings
25
+ from concurrent.futures import ThreadPoolExecutor, as_completed
26
+ from pathlib import Path
27
+ from threading import Lock
28
+
29
+ import matplotlib.pyplot as plt
30
+ import netCDF4 as nc
31
+ import numpy as np
32
+ import pandas as pd
33
+ import requests
34
+ import xarray as xr
35
+ from rich import print
36
+ from rich.progress import Progress
37
+
38
+ from oafuncs.oa_down.idm import downloader as idm_downloader
39
+ from oafuncs.oa_down.user_agent import get_ua
40
+ from oafuncs.oa_file import file_size, mean_size
41
+ from oafuncs.oa_nc import check as check_nc
42
+ from oafuncs.oa_nc import modify as modify_nc
43
+
44
+ warnings.filterwarnings("ignore", category=RuntimeWarning, message="Engine '.*' loading failed:.*")
45
+
46
+ __all__ = ["draw_time_range", "download", "how_to_use", "get_time_list"]
47
+
48
+
49
+ def _get_initial_data():
50
+ global variable_info, data_info, var_group, single_var_group
51
+ # ----------------------------------------------
52
+ # variable
53
+ variable_info = {
54
+ "u": {"var_name": "water_u", "standard_name": "eastward_sea_water_velocity"},
55
+ "v": {"var_name": "water_v", "standard_name": "northward_sea_water_velocity"},
56
+ "temp": {"var_name": "water_temp", "standard_name": "sea_water_potential_temperature"},
57
+ "salt": {"var_name": "salinity", "standard_name": "sea_water_salinity"},
58
+ "ssh": {"var_name": "surf_el", "standard_name": "sea_surface_elevation"},
59
+ "u_b": {"var_name": "water_u_bottom", "standard_name": "eastward_sea_water_velocity_at_sea_floor"},
60
+ "v_b": {"var_name": "water_v_bottom", "standard_name": "northward_sea_water_velocity_at_sea_floor"},
61
+ "temp_b": {"var_name": "water_temp_bottom", "standard_name": "sea_water_potential_temperature_at_sea_floor"},
62
+ "salt_b": {"var_name": "salinity_bottom", "standard_name": "sea_water_salinity_at_sea_floor"},
63
+ }
64
+ # ----------------------------------------------
65
+ # time resolution
66
+ data_info = {"yearly": {}, "monthly": {}, "daily": {}, "hourly": {}}
67
+
68
+ # hourly data
69
+ # dataset: GLBv0.08, GLBu0.08, GLBy0.08
70
+ data_info["hourly"]["dataset"] = {"GLBv0.08": {}, "GLBu0.08": {}, "GLBy0.08": {}, "ESPC_D": {}}
71
+
72
+ # version
73
+ # version of GLBv0.08: 53.X, 56.3, 57.2, 92.8, 57.7, 92.9, 93.0
74
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"] = {"53.X": {}, "56.3": {}, "57.2": {}, "92.8": {}, "57.7": {}, "92.9": {}, "93.0": {}}
75
+ # version of GLBu0.08: 93.0
76
+ data_info["hourly"]["dataset"]["GLBu0.08"]["version"] = {"93.0": {}}
77
+ # version of GLBy0.08: 93.0
78
+ data_info["hourly"]["dataset"]["GLBy0.08"]["version"] = {"93.0": {}}
79
+ # version of ESPC_D: V02
80
+ data_info["hourly"]["dataset"]["ESPC_D"]["version"] = {"V02": {}}
81
+
82
+ # info details
83
+ # time range
84
+ # GLBv0.08
85
+ # 在网页上提交超过范围的时间,会返回该数据集实际时间范围,从而纠正下面的时间范围
86
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["53.X"]["time_range"] = {"time_start": "1994010112", "time_end": "2015123109"}
87
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["56.3"]["time_range"] = {"time_start": "2014070112", "time_end": "2016093009"}
88
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["57.2"]["time_range"] = {"time_start": "2016050112", "time_end": "2017020109"}
89
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["92.8"]["time_range"] = {"time_start": "2017020112", "time_end": "2017060109"}
90
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["57.7"]["time_range"] = {"time_start": "2017060112", "time_end": "2017100109"}
91
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["92.9"]["time_range"] = {"time_start": "2017100112", "time_end": "2018032009"}
92
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["93.0"]["time_range"] = {"time_start": "2018010112", "time_end": "2020021909"}
93
+ # GLBu0.08
94
+ data_info["hourly"]["dataset"]["GLBu0.08"]["version"]["93.0"]["time_range"] = {"time_start": "2018091912", "time_end": "2018120909"}
95
+ # GLBy0.08
96
+ data_info["hourly"]["dataset"]["GLBy0.08"]["version"]["93.0"]["time_range"] = {"time_start": "2018120412", "time_end": "2024090509"}
97
+ # ESPC-D
98
+ data_info["hourly"]["dataset"]["ESPC_D"]["version"]["V02"]["time_range"] = {"time_start": "2024081012", "time_end": "2030010100"}
99
+
100
+ # classification method
101
+ # year_different: the data of different years is stored in different files
102
+ # same_path: the data of different years is stored in the same file
103
+ # var_different: the data of different variables is stored in different files
104
+ # var_year_different: the data of different variables and years is stored in different files
105
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["53.X"]["classification"] = "year_different"
106
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["56.3"]["classification"] = "same_path"
107
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["57.2"]["classification"] = "same_path"
108
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["92.8"]["classification"] = "var_different"
109
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["57.7"]["classification"] = "same_path"
110
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["92.9"]["classification"] = "var_different"
111
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["93.0"]["classification"] = "var_different"
112
+ data_info["hourly"]["dataset"]["GLBu0.08"]["version"]["93.0"]["classification"] = "var_different"
113
+ data_info["hourly"]["dataset"]["GLBy0.08"]["version"]["93.0"]["classification"] = "var_year_different"
114
+ data_info["hourly"]["dataset"]["ESPC_D"]["version"]["V02"]["classification"] = "single_var_year_different"
115
+
116
+ # download info
117
+ # base url
118
+ # GLBv0.08 53.X
119
+ url_53x = {}
120
+ for y_53x in range(1994, 2016):
121
+ # r'https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_53.X/data/2013?'
122
+ url_53x[str(y_53x)] = rf"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_53.X/data/{y_53x}?"
123
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["53.X"]["url"] = url_53x
124
+ # GLBv0.08 56.3
125
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["56.3"]["url"] = r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_56.3?"
126
+ # GLBv0.08 57.2
127
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["57.2"]["url"] = r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_57.2?"
128
+ # GLBv0.08 92.8
129
+ url_928 = {
130
+ "uv3z": r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_92.8/uv3z?",
131
+ "ts3z": r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_92.8/ts3z?",
132
+ "ssh": r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_92.8/ssh?",
133
+ }
134
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["92.8"]["url"] = url_928
135
+ # GLBv0.08 57.7
136
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["57.7"]["url"] = r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_57.7?"
137
+ # GLBv0.08 92.9
138
+ url_929 = {
139
+ "uv3z": r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_92.9/uv3z?",
140
+ "ts3z": r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_92.9/ts3z?",
141
+ "ssh": r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_92.9/ssh?",
142
+ }
143
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["92.9"]["url"] = url_929
144
+ # GLBv0.08 93.0
145
+ url_930_v = {
146
+ "uv3z": r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_93.0/uv3z?",
147
+ "ts3z": r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_93.0/ts3z?",
148
+ "ssh": r"https://ncss.hycom.org/thredds/ncss/GLBv0.08/expt_93.0/ssh?",
149
+ }
150
+ data_info["hourly"]["dataset"]["GLBv0.08"]["version"]["93.0"]["url"] = url_930_v
151
+ # GLBu0.08 93.0
152
+ url_930_u = {
153
+ "uv3z": r"https://ncss.hycom.org/thredds/ncss/GLBu0.08/expt_93.0/uv3z?",
154
+ "ts3z": r"https://ncss.hycom.org/thredds/ncss/GLBu0.08/expt_93.0/ts3z?",
155
+ "ssh": r"https://ncss.hycom.org/thredds/ncss/GLBu0.08/expt_93.0/ssh?",
156
+ }
157
+ data_info["hourly"]["dataset"]["GLBu0.08"]["version"]["93.0"]["url"] = url_930_u
158
+ # GLBy0.08 93.0
159
+ uv3z_930_y = {}
160
+ ts3z_930_y = {}
161
+ ssh_930_y = {}
162
+ for y_930_y in range(2018, 2025):
163
+ uv3z_930_y[str(y_930_y)] = rf"https://ncss.hycom.org/thredds/ncss/GLBy0.08/expt_93.0/uv3z/{y_930_y}?"
164
+ ts3z_930_y[str(y_930_y)] = rf"https://ncss.hycom.org/thredds/ncss/GLBy0.08/expt_93.0/ts3z/{y_930_y}?"
165
+ ssh_930_y[str(y_930_y)] = rf"https://ncss.hycom.org/thredds/ncss/GLBy0.08/expt_93.0/ssh/{y_930_y}?"
166
+ # GLBy0.08 93.0 data time range in each year: year-01-01 12:00 to year+1-01-01 09:00
167
+ url_930_y = {
168
+ "uv3z": uv3z_930_y,
169
+ "ts3z": ts3z_930_y,
170
+ "ssh": ssh_930_y,
171
+ }
172
+ data_info["hourly"]["dataset"]["GLBy0.08"]["version"]["93.0"]["url"] = url_930_y
173
+ # ESPC-D-V02
174
+ u3z_espc_d_v02_y = {}
175
+ v3z_espc_d_v02_y = {}
176
+ t3z_espc_d_v02_y = {}
177
+ s3z_espc_d_v02_y = {}
178
+ ssh_espc_d_v02_y = {}
179
+ for y_espc_d_v02 in range(2024, 2030):
180
+ 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}?"
181
+ 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}?"
182
+ 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}?"
183
+ 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}?"
184
+ 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}?"
185
+ url_espc_d_v02_y = {
186
+ "u3z": u3z_espc_d_v02_y,
187
+ "v3z": v3z_espc_d_v02_y,
188
+ "t3z": t3z_espc_d_v02_y,
189
+ "s3z": s3z_espc_d_v02_y,
190
+ "ssh": ssh_espc_d_v02_y,
191
+ }
192
+ data_info["hourly"]["dataset"]["ESPC_D"]["version"]["V02"]["url"] = url_espc_d_v02_y
193
+ # ----------------------------------------------
194
+ var_group = {
195
+ "uv3z": ["u", "v", "u_b", "v_b"],
196
+ "ts3z": ["temp", "salt", "temp_b", "salt_b"],
197
+ "ssh": ["ssh"],
198
+ }
199
+ # ----------------------------------------------
200
+ single_var_group = {
201
+ "u3z": ["u"],
202
+ "v3z": ["v"],
203
+ "t3z": ["temp"],
204
+ "s3z": ["salt"],
205
+ "ssh": ["ssh"],
206
+ }
207
+
208
+ return variable_info, data_info, var_group, single_var_group
209
+
210
+
211
+ def draw_time_range(pic_save_folder=None):
212
+ if pic_save_folder is not None:
213
+ os.makedirs(pic_save_folder, exist_ok=True)
214
+ # Converting the data into a format suitable for plotting
215
+ data = []
216
+ for dataset, versions in data_info["hourly"]["dataset"].items():
217
+ for version, time_range in versions["version"].items():
218
+ t_s = time_range["time_range"]["time_start"]
219
+ t_e = time_range["time_range"]["time_end"]
220
+ if len(t_s) == 8:
221
+ t_s = t_s + "00"
222
+ if len(t_e) == 8:
223
+ t_e = t_e + "21"
224
+ t_s, t_e = t_s + "0000", t_e + "0000"
225
+ data.append(
226
+ {
227
+ "dataset": dataset,
228
+ "version": version,
229
+ "start_date": pd.to_datetime(t_s),
230
+ "end_date": pd.to_datetime(t_e),
231
+ }
232
+ )
233
+
234
+ # Creating a DataFrame
235
+ df = pd.DataFrame(data)
236
+
237
+ # Plotting with combined labels for datasets and versions on the y-axis
238
+ plt.figure(figsize=(12, 6))
239
+
240
+ # Combined labels for datasets and versions
241
+ combined_labels = [f"{dataset}_{version}" for dataset, version in zip(df["dataset"], df["version"])]
242
+
243
+ colors = plt.cm.viridis(np.linspace(0, 1, len(combined_labels)))
244
+
245
+ # Assigning a color to each combined label
246
+ label_colors = {label: colors[i] for i, label in enumerate(combined_labels)}
247
+
248
+ # Plotting each time range
249
+ k = 1
250
+ for _, row in df.iterrows():
251
+ plt.plot([row["start_date"], row["end_date"]], [k, k], color=label_colors[f"{row['dataset']}_{row['version']}"], linewidth=6)
252
+ # plt.text(row['end_date'], k,
253
+ # f"{row['version']}", ha='right', color='black')
254
+ ymdh_s = row["start_date"].strftime("%Y-%m-%d %H")
255
+ ymdh_e = row["end_date"].strftime("%Y-%m-%d %H")
256
+ # if k == 1 or k == len(combined_labels):
257
+ if k == 1:
258
+ plt.text(row["start_date"], k + 0.125, f"{ymdh_s}", ha="left", color="black")
259
+ plt.text(row["end_date"], k + 0.125, f"{ymdh_e}", ha="right", color="black")
260
+ else:
261
+ plt.text(row["start_date"], k + 0.125, f"{ymdh_s}", ha="right", color="black")
262
+ plt.text(row["end_date"], k + 0.125, f"{ymdh_e}", ha="left", color="black")
263
+ k += 1
264
+
265
+ # Setting the y-axis labels
266
+ plt.yticks(range(1, len(combined_labels) + 1), combined_labels)
267
+ plt.xlabel("Time")
268
+ plt.ylabel("Dataset - Version")
269
+ plt.title("Time Range of Different Versions of Datasets")
270
+ plt.xticks(rotation=45)
271
+ plt.grid(True)
272
+ plt.tight_layout()
273
+ if pic_save_folder:
274
+ plt.savefig(Path(pic_save_folder) / "HYCOM_time_range.png")
275
+ print(f"[bold green]HYCOM_time_range.png has been saved in {pic_save_folder}")
276
+ else:
277
+ plt.savefig("HYCOM_time_range.png")
278
+ print("[bold green]HYCOM_time_range.png has been saved in the current folder")
279
+ print(f"Curren folder: {os.getcwd()}")
280
+ # plt.show()
281
+ plt.close()
282
+
283
+
284
+ def get_time_list(time_s, time_e, delta, interval_type="hour"):
285
+ """
286
+ Description: get a list of time strings from time_s to time_e with a specified interval
287
+ Args:
288
+ time_s: start time string, e.g. '2023080203' for hours or '20230802' for days
289
+ time_e: end time string, e.g. '2023080303' for hours or '20230803' for days
290
+ delta: interval of hours or days
291
+ interval_type: 'hour' for hour interval, 'day' for day interval
292
+ Returns:
293
+ dt_list: a list of time strings
294
+ """
295
+ time_s, time_e = str(time_s), str(time_e)
296
+ if interval_type == "hour":
297
+ time_format = "%Y%m%d%H"
298
+ delta_type = "hours"
299
+ elif interval_type == "day":
300
+ time_format = "%Y%m%d"
301
+ delta_type = "days"
302
+ # Ensure time strings are in the correct format for days
303
+ time_s = time_s[:8]
304
+ time_e = time_e[:8]
305
+ else:
306
+ raise ValueError("interval_type must be 'hour' or 'day'")
307
+
308
+ dt = datetime.datetime.strptime(time_s, time_format)
309
+ dt_list = []
310
+ while dt.strftime(time_format) <= time_e:
311
+ dt_list.append(dt.strftime(time_format))
312
+ dt += datetime.timedelta(**{delta_type: delta})
313
+ return dt_list
314
+
315
+
316
+ def _transform_time(time_str):
317
+ # old_time = '2023080203'
318
+ # time_new = '2023-08-02T03%3A00%3A00Z'
319
+ time_new = f"{time_str[:4]}-{time_str[4:6]}-{time_str[6:8]}T{time_str[8:10]}%3A00%3A00Z"
320
+ return time_new
321
+
322
+
323
+ 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):
324
+ query_dict = {
325
+ "var": variable_info[var]["var_name"],
326
+ "north": lat_max,
327
+ "west": lon_min,
328
+ "east": lon_max,
329
+ "south": lat_min,
330
+ "horizStride": 1,
331
+ "time": None,
332
+ "time_start": None,
333
+ "time_end": None,
334
+ "timeStride": None,
335
+ "vertCoord": None,
336
+ "vertStride": None,
337
+ "addLatLon": "true",
338
+ "accept": "netcdf4",
339
+ }
340
+
341
+ if time_str_end is not None:
342
+ query_dict["time_start"] = _transform_time(time_str_ymdh)
343
+ query_dict["time_end"] = _transform_time(time_str_end)
344
+ query_dict["timeStride"] = 1
345
+ else:
346
+ query_dict["time"] = _transform_time(time_str_ymdh)
347
+
348
+ def get_nearest_level_index(depth):
349
+ 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]
350
+ return min(range(len(level_depth)), key=lambda i: abs(level_depth[i] - depth))
351
+
352
+ if var not in ["ssh", "u_b", "v_b", "temp_b", "salt_b"] and var in ["u", "v", "temp", "salt"]:
353
+ if mode == "depth":
354
+ if depth < 0 or depth > 5000:
355
+ print("Please ensure the depth is in the range of 0-5000 m")
356
+ query_dict["vertCoord"] = get_nearest_level_index(depth) + 1
357
+ elif mode == "level":
358
+ if level_num < 1 or level_num > 40:
359
+ print("Please ensure the level_num is in the range of 1-40")
360
+ query_dict["vertCoord"] = max(1, min(level_num, 40))
361
+ elif mode == "full":
362
+ query_dict["vertStride"] = 1
363
+ else:
364
+ raise ValueError("Invalid mode. Choose from 'depth', 'level', or 'full'")
365
+
366
+ query_dict = {k: v for k, v in query_dict.items() if v is not None}
367
+
368
+ return query_dict
369
+
370
+
371
+ def _check_time_in_dataset_and_version(time_input, time_end=None):
372
+ # 判断是处理单个时间点还是时间范围
373
+ is_single_time = time_end is None
374
+
375
+ # 如果是单个时间点,初始化时间范围
376
+ if is_single_time:
377
+ time_start = int(time_input)
378
+ time_end = time_start
379
+ time_input_str = str(time_input)
380
+ else:
381
+ time_start = int(time_input)
382
+ time_end = int(time_end)
383
+ time_input_str = f"{time_input}-{time_end}"
384
+
385
+ # 根据时间长度补全时间格式
386
+ if len(str(time_start)) == 8:
387
+ time_start = str(time_start) + "00"
388
+ if len(str(time_end)) == 8:
389
+ time_end = str(time_end) + "21"
390
+ time_start, time_end = int(time_start), int(time_end)
391
+
392
+ d_list = []
393
+ v_list = []
394
+ trange_list = []
395
+ have_data = False
396
+
397
+ # 遍历数据集和版本
398
+ for dataset_name in data_info["hourly"]["dataset"].keys():
399
+ for version_name in data_info["hourly"]["dataset"][dataset_name]["version"].keys():
400
+ time_s, time_e = list(data_info["hourly"]["dataset"][dataset_name]["version"][version_name]["time_range"].values())
401
+ time_s, time_e = str(time_s), str(time_e)
402
+ if len(time_s) == 8:
403
+ time_s = time_s + "00"
404
+ if len(time_e) == 8:
405
+ time_e = time_e + "21"
406
+ # 检查时间是否在数据集的时间范围内
407
+ if is_single_time:
408
+ if time_start >= int(time_s) and time_start <= int(time_e):
409
+ d_list.append(dataset_name)
410
+ v_list.append(version_name)
411
+ trange_list.append(f"{time_s}-{time_e}")
412
+ have_data = True
413
+ else:
414
+ if time_start >= int(time_s) and time_end <= int(time_e):
415
+ d_list.append(dataset_name)
416
+ v_list.append(version_name)
417
+ trange_list.append(f"{time_s}-{time_e}")
418
+ have_data = True
419
+
420
+ # 输出结果
421
+ print(f"[bold red]{time_input_str} is in the following dataset and version:")
422
+ if have_data:
423
+ for d, v, trange in zip(d_list, v_list, trange_list):
424
+ print(f"[bold blue]{d} {v} {trange}")
425
+ if is_single_time:
426
+ return True
427
+ else:
428
+ base_url_s = _get_base_url(d_list[0], v_list[0], "u", str(time_start))
429
+ base_url_e = _get_base_url(d_list[0], v_list[0], "u", str(time_end))
430
+ if base_url_s == base_url_e:
431
+ return True
432
+ else:
433
+ print(f"[bold red]{time_start} to {time_end} is in different datasets or versions, so you can't download them together")
434
+ return False
435
+ else:
436
+ print(f"[bold red]{time_input_str} is not in any dataset and version")
437
+ return False
438
+
439
+
440
+ def _ensure_time_in_specific_dataset_and_version(dataset_name, version_name, time_input, time_end=None):
441
+ # 根据时间长度补全时间格式
442
+ if len(str(time_input)) == 8:
443
+ time_input = str(time_input) + "00"
444
+ time_start = int(time_input)
445
+ if time_end is not None:
446
+ if len(str(time_end)) == 8:
447
+ time_end = str(time_end) + "21"
448
+ time_end = int(time_end)
449
+ else:
450
+ time_end = time_start
451
+
452
+ # 检查指定的数据集和版本是否存在
453
+ if dataset_name not in data_info["hourly"]["dataset"]:
454
+ print(f"[bold red]Dataset {dataset_name} not found.")
455
+ return False
456
+ if version_name not in data_info["hourly"]["dataset"][dataset_name]["version"]:
457
+ print(f"[bold red]Version {version_name} not found in dataset {dataset_name}.")
458
+ return False
459
+
460
+ # 获取指定数据集和版本的时间范围
461
+ time_range = data_info["hourly"]["dataset"][dataset_name]["version"][version_name]["time_range"]
462
+ time_s, time_e = list(time_range.values())
463
+ time_s, time_e = str(time_s), str(time_e)
464
+ if len(time_s) == 8:
465
+ time_s = time_s + "00"
466
+ if len(time_e) == 8:
467
+ time_e = time_e + "21"
468
+ time_s, time_e = int(time_s), int(time_e)
469
+
470
+ # 检查时间是否在指定数据集和版本的时间范围内
471
+ if time_start >= time_s and time_end <= time_e:
472
+ print(f"[bold blue]Time {time_input} to {time_end} is within dataset {dataset_name} and version {version_name}.")
473
+ return True
474
+ else:
475
+ print(f"[bold red]Time {time_input} to {time_end} is not within dataset {dataset_name} and version {version_name}.")
476
+ return False
477
+
478
+
479
+ def _direct_choose_dataset_and_version(time_input, time_end=None):
480
+ # 假设 data_info 是一个字典,包含了数据集和版本的信息
481
+ # 示例结构:data_info['hourly']['dataset'][dataset_name]['version'][version_name]['time_range']
482
+
483
+ if len(str(time_input)) == 8:
484
+ time_input = str(time_input) + "00"
485
+
486
+ # 如果 time_end 是 None,则将 time_input 的值赋给它
487
+ if time_end is None:
488
+ time_end = time_input
489
+
490
+ # 处理开始和结束时间,确保它们是完整的 ymdh 格式
491
+ time_start, time_end = int(str(time_input)[:10]), int(str(time_end)[:10])
492
+
493
+ dataset_name_out, version_name_out = None, None
494
+
495
+ for dataset_name in data_info["hourly"]["dataset"].keys():
496
+ for version_name in data_info["hourly"]["dataset"][dataset_name]["version"].keys():
497
+ [time_s, time_e] = list(data_info["hourly"]["dataset"][dataset_name]["version"][version_name]["time_range"].values())
498
+ time_s, time_e = str(time_s), str(time_e)
499
+ if len(time_s) == 8:
500
+ time_s = time_s + "00"
501
+ if len(time_e) == 8:
502
+ time_e = time_e + "21"
503
+ time_s, time_e = int(time_s), int(time_e)
504
+
505
+ # 检查时间是否在数据集版本的时间范围内
506
+ if time_start >= time_s and time_end <= time_e:
507
+ # print(f'[bold purple]dataset: {dataset_name}, version: {version_name} is chosen')
508
+ # return dataset_name, version_name
509
+ dataset_name_out, version_name_out = dataset_name, version_name
510
+
511
+ if dataset_name_out is not None and version_name_out is not None:
512
+ print(f"[bold purple]dataset: {dataset_name_out}, version: {version_name_out} is chosen")
513
+
514
+ # 如果没有找到匹配的数据集和版本,会返回 None
515
+ return dataset_name_out, version_name_out
516
+
517
+
518
+ def _get_base_url(dataset_name, version_name, var, ymdh_str):
519
+ year_str = int(ymdh_str[:4])
520
+ url_dict = data_info["hourly"]["dataset"][dataset_name]["version"][version_name]["url"]
521
+ classification_method = data_info["hourly"]["dataset"][dataset_name]["version"][version_name]["classification"]
522
+ if classification_method == "year_different":
523
+ base_url = url_dict[str(year_str)]
524
+ elif classification_method == "same_path":
525
+ base_url = url_dict
526
+ elif classification_method == "var_different":
527
+ base_url = None
528
+ for key, value in var_group.items():
529
+ if var in value:
530
+ base_url = url_dict[key]
531
+ break
532
+ if base_url is None:
533
+ print("Please ensure the var is in [u,v,temp,salt,ssh,u_b,v_b,temp_b,salt_b]")
534
+ elif classification_method == "var_year_different":
535
+ if dataset_name == "GLBy0.08" and version_name == "93.0":
536
+ mdh_str = ymdh_str[4:]
537
+ # GLBy0.08 93.0
538
+ # data time range in each year: year-01-01 12:00 to year+1-01-01 09:00
539
+ if "010100" <= mdh_str <= "010109":
540
+ year_str = int(ymdh_str[:4]) - 1
541
+ else:
542
+ year_str = int(ymdh_str[:4])
543
+ base_url = None
544
+ for key, value in var_group.items():
545
+ if var in value:
546
+ base_url = url_dict[key][str(year_str)]
547
+ break
548
+ if base_url is None:
549
+ print("Please ensure the var is in [u,v,temp,salt,ssh,u_b,v_b,temp_b,salt_b]")
550
+ elif classification_method == "single_var_year_different":
551
+ base_url = None
552
+ if dataset_name == "ESPC_D" and version_name == "V02":
553
+ mdh_str = ymdh_str[4:]
554
+ # ESPC-D-V02
555
+ if "010100" <= mdh_str <= "010109":
556
+ year_str = int(ymdh_str[:4]) - 1
557
+ else:
558
+ year_str = int(ymdh_str[:4])
559
+ for key, value in single_var_group.items():
560
+ if var in value:
561
+ base_url = url_dict[key][str(year_str)]
562
+ break
563
+ if base_url is None:
564
+ print("Please ensure the var is in [u,v,temp,salt,ssh]")
565
+ return base_url
566
+
567
+
568
+ def _get_submit_url(dataset_name, version_name, var, ymdh_str, query_dict):
569
+ base_url = _get_base_url(dataset_name, version_name, var, ymdh_str)
570
+ if isinstance(query_dict["var"], str):
571
+ query_dict["var"] = [query_dict["var"]]
572
+ 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")
573
+ return target_url
574
+
575
+
576
+ def _clear_existing_file(file_full_path):
577
+ if os.path.exists(file_full_path):
578
+ os.remove(file_full_path)
579
+ print(f"{file_full_path} has been removed")
580
+
581
+
582
+ def _check_existing_file(file_full_path, avg_size):
583
+ if os.path.exists(file_full_path):
584
+ print(f"[bold #FFA54F]{file_full_path} exists")
585
+ fsize = file_size(file_full_path)
586
+ delta_size_ratio = (fsize - avg_size) / avg_size
587
+ if abs(delta_size_ratio) > 0.025:
588
+ if check_nc(file_full_path):
589
+ # print(f"File size is abnormal but can be opened normally, file size: {fsize:.2f} KB")
590
+ return True
591
+ else:
592
+ print(f"File size is abnormal and cannot be opened, {file_full_path}: {fsize:.2f} KB")
593
+ return False
594
+ else:
595
+ return True
596
+ else:
597
+ return False
598
+
599
+
600
+ def _get_mean_size30(store_path, same_file):
601
+ if same_file not in fsize_dict.keys():
602
+ # print(f'Same file name: {same_file}')
603
+ fsize_dict[same_file] = {"size": 0, "count": 0}
604
+
605
+ if fsize_dict[same_file]["count"] < 30 or fsize_dict[same_file]["size"] == 0:
606
+ # 更新30次文件最小值,后续认为可以代表所有文件,不再更新占用时间
607
+ fsize_mean = mean_size(store_path, same_file, max_num=30)
608
+ set_min_size = fsize_mean * 0.95
609
+ fsize_dict[same_file]["size"] = set_min_size
610
+ fsize_dict[same_file]["count"] += 1
611
+ else:
612
+ set_min_size = fsize_dict[same_file]["size"]
613
+ return set_min_size
614
+
615
+
616
+ def _get_mean_size_move(same_file, current_file):
617
+ # 获取锁
618
+ with fsize_dict_lock: # 全局锁,确保同一时间只能有一个线程访问
619
+ # 初始化字典中的值,如果文件不在字典中
620
+ if same_file not in fsize_dict.keys():
621
+ fsize_dict[same_file] = {"size_list": [], "mean_size": 1.0}
622
+
623
+ tolerance_ratio = 0.025 # 容忍的阈值比例
624
+ current_file_size = file_size(current_file)
625
+
626
+ # 如果列表不为空,则计算平均值,否则保持为1
627
+ if fsize_dict[same_file]["size_list"]:
628
+ fsize_dict[same_file]["mean_size"] = sum(fsize_dict[same_file]["size_list"]) / len(fsize_dict[same_file]["size_list"])
629
+ fsize_dict[same_file]["mean_size"] = max(fsize_dict[same_file]["mean_size"], 1.0)
630
+ else:
631
+ fsize_dict[same_file]["mean_size"] = 1.0
632
+
633
+ size_difference_ratio = (current_file_size - fsize_dict[same_file]["mean_size"]) / fsize_dict[same_file]["mean_size"]
634
+
635
+ if abs(size_difference_ratio) > tolerance_ratio:
636
+ if check_nc(current_file):
637
+ # print(f"File size is abnormal but can be opened normally, file size: {current_file_size:.2f} KB")
638
+ # 文件可以正常打开,但大小异常,保留当前文件大小
639
+ fsize_dict[same_file]["size_list"] = [current_file_size]
640
+ fsize_dict[same_file]["mean_size"] = current_file_size
641
+ else:
642
+ _clear_existing_file(current_file)
643
+ print(f"File size is abnormal, may need to be downloaded again, file size: {current_file_size:.2f} KB")
644
+ else:
645
+ # 添加当前文件大小到列表中,并更新计数
646
+ fsize_dict[same_file]["size_list"].append(current_file_size)
647
+
648
+ # 返回调整后的平均值,这里根据您的需求,返回的是添加新值之前的平均值
649
+ return fsize_dict[same_file]["mean_size"]
650
+
651
+
652
+ def _check_ftime(nc_file, tname="time", if_print=False):
653
+ if not os.path.exists(nc_file):
654
+ return False
655
+ nc_file = str(nc_file)
656
+ try:
657
+ ds = xr.open_dataset(nc_file)
658
+ real_time = ds[tname].values[0]
659
+ ds.close()
660
+ real_time = str(real_time)[:13]
661
+ real_time = real_time.replace("-", "").replace("T", "")
662
+ # -----------------------------------------------------
663
+ f_time = re.findall(r"\d{10}", nc_file)[0]
664
+ if real_time == f_time:
665
+ return True
666
+ else:
667
+ if if_print:
668
+ print(f"[bold #daff5c]File time error, file/real time: [bold blue]{f_time}/{real_time}")
669
+ return False
670
+ except Exception as e:
671
+ if if_print:
672
+ print(f"[bold #daff5c]File time check failed, {nc_file}: {e}")
673
+ return False
674
+
675
+
676
+ def _correct_time(nc_file):
677
+ # 打开NC文件
678
+ dataset = nc.Dataset(nc_file)
679
+
680
+ # 读取时间单位
681
+ time_units = dataset.variables["time"].units
682
+
683
+ # 关闭文件
684
+ dataset.close()
685
+
686
+ # 解析时间单位字符串以获取时间原点
687
+ origin_str = time_units.split("since")[1].strip()
688
+ origin_datetime = datetime.datetime.strptime(origin_str, "%Y-%m-%d %H:%M:%S")
689
+
690
+ # 从文件名中提取日期字符串
691
+ given_date_str = re.findall(r"\d{10}", str(nc_file))[0]
692
+
693
+ # 将提取的日期字符串转换为datetime对象
694
+ given_datetime = datetime.datetime.strptime(given_date_str, "%Y%m%d%H")
695
+
696
+ # 计算给定日期与时间原点之间的差值(以小时为单位)
697
+ time_difference = (given_datetime - origin_datetime).total_seconds()
698
+ if "hours" in time_units:
699
+ time_difference /= 3600
700
+ elif "days" in time_units:
701
+ time_difference /= 3600 * 24
702
+
703
+ # 修改NC文件中的时间变量
704
+ modify_nc(nc_file, "time", None, time_difference)
705
+
706
+
707
+ def _download_file(target_url, store_path, file_name, check=False):
708
+ # Check if the file exists
709
+ fname = Path(store_path) / file_name
710
+ file_name_split = file_name.split("_")
711
+ file_name_split = file_name_split[:-1]
712
+ # same_file = f"{file_name_split[0]}_{file_name_split[1]}*nc"
713
+ same_file = "_".join(file_name_split) + "*nc"
714
+
715
+ if match_time is not None:
716
+ if check_nc(fname):
717
+ if not _check_ftime(fname, if_print=True):
718
+ if match_time:
719
+ _correct_time(fname)
720
+ count_dict['skip'] += 1
721
+ else:
722
+ _clear_existing_file(fname)
723
+ # print(f"[bold #ffe5c0]File time error, {fname}")
724
+ count_dict["no_data"] += 1
725
+ else:
726
+ count_dict["skip"] += 1
727
+ print(f"[bold green]{file_name} is correct")
728
+ return
729
+
730
+ if check:
731
+ if same_file not in fsize_dict.keys(): # 对第一个文件单独进行检查,因为没有大小可以对比
732
+ check_nc(fname, delete_switch=True)
733
+
734
+ # set_min_size = _get_mean_size30(store_path, same_file) # 原方案,只30次取平均值;若遇变化,无法判断
735
+ get_mean_size = _get_mean_size_move(same_file, fname)
736
+
737
+ if _check_existing_file(fname, get_mean_size):
738
+ count_dict["skip"] += 1
739
+ return
740
+ _clear_existing_file(fname)
741
+
742
+ if not use_idm:
743
+ # -----------------------------------------------
744
+ print(f"[bold #f0f6d0]Requesting {file_name} ...")
745
+ # 创建会话
746
+ s = requests.Session()
747
+ download_success = False
748
+ request_times = 0
749
+
750
+ def calculate_wait_time(time_str, target_url):
751
+ # 定义正则表达式,匹配YYYYMMDDHH格式的时间
752
+ time_pattern = r"\d{10}"
753
+
754
+ # 定义两个字符串
755
+ # str1 = 'HYCOM_water_u_2018010100-2018010112.nc'
756
+ # str2 = 'HYCOM_water_u_2018010100.nc'
757
+
758
+ # 使用正则表达式查找时间
759
+ times_in_str = re.findall(time_pattern, time_str)
760
+
761
+ # 计算每个字符串中的时间数量
762
+ num_times_str = len(times_in_str)
763
+
764
+ if num_times_str > 1:
765
+ delta_t = datetime.datetime.strptime(times_in_str[1], "%Y%m%d%H") - datetime.datetime.strptime(times_in_str[0], "%Y%m%d%H")
766
+ delta_t = delta_t.total_seconds() / 3600
767
+ delta_t = delta_t / 3 + 1
768
+ else:
769
+ delta_t = 1
770
+ # 单个要素最多等待5分钟,不宜太短,太短可能请求失败;也不宜太长,太长可能会浪费时间
771
+ num_var = int(target_url.count("var="))
772
+ if num_var <= 0:
773
+ num_var = 1
774
+ return int(delta_t * 5 * 60 * num_var)
775
+
776
+ max_timeout = calculate_wait_time(file_name, target_url)
777
+ print(f"[bold #912dbc]Max timeout: {max_timeout} seconds")
778
+
779
+ # print(f'Download_start_time: {datetime.datetime.now()}')
780
+ download_time_s = datetime.datetime.now()
781
+ order_list = ["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th"]
782
+ while not download_success:
783
+ if request_times >= 10:
784
+ # print(f'下载失败,已重试 {request_times} 次\n可先跳过,后续再试')
785
+ print(f"[bold #ffe5c0]Download failed after {request_times} times\nYou can skip it and try again later")
786
+ count_dict["fail"] += 1
787
+ break
788
+ if request_times > 0:
789
+ # print(f'\r正在重试第 {request_times} 次', end="")
790
+ print(f"[bold #ffe5c0]Retrying the {order_list[request_times - 1]} time...")
791
+ # 尝试下载文件
792
+ try:
793
+ headers = {"User-Agent": get_ua()}
794
+ """ response = s.get(target_url, headers=headers, timeout=random.randint(5, max_timeout))
795
+ response.raise_for_status() # 如果请求返回的不是200,将抛出HTTPError异常
796
+
797
+ # 保存文件
798
+ with open(filename, 'wb') as f:
799
+ f.write(response.content) """
800
+
801
+ response = s.get(target_url, headers=headers, stream=True, timeout=random.randint(5, max_timeout)) # 启用流式传输
802
+ response.raise_for_status() # 如果请求返回的不是200,将抛出HTTPError异常
803
+ # 保存文件
804
+ with open(fname, "wb") as f:
805
+ print(f"[bold #96cbd7]Downloading {file_name} ...")
806
+ for chunk in response.iter_content(chunk_size=1024):
807
+ if chunk:
808
+ f.write(chunk)
809
+
810
+ f.close()
811
+
812
+ # print(f'\r文件 {fname} 下载成功', end="")
813
+ if os.path.exists(fname):
814
+ download_success = True
815
+ download_time_e = datetime.datetime.now()
816
+ download_delta = download_time_e - download_time_s
817
+ print(f"[#3dfc40]File [bold #dfff73]{fname} [#3dfc40]has been downloaded successfully, Time: [#39cbdd]{download_delta}")
818
+ count_dict["success"] += 1
819
+ # print(f'Download_end_time: {datetime.datetime.now()}')
820
+
821
+ except requests.exceptions.HTTPError as errh:
822
+ print(f"Http Error: {errh}")
823
+ except requests.exceptions.ConnectionError as errc:
824
+ print(f"Error Connecting: {errc}")
825
+ except requests.exceptions.Timeout as errt:
826
+ print(f"Timeout Error: {errt}")
827
+ except requests.exceptions.RequestException as err:
828
+ print(f"OOps: Something Else: {err}")
829
+
830
+ time.sleep(3)
831
+ request_times += 1
832
+ else:
833
+ idm_downloader(target_url, store_path, file_name, given_idm_engine)
834
+ idm_download_list.append(fname)
835
+ print(f"[bold #3dfc40]File [bold #dfff73]{fname} [#3dfc40]has been submit to IDM for downloading")
836
+
837
+
838
+ def _check_hour_is_valid(ymdh_str):
839
+ # hour should be 00, 03, 06, 09, 12, 15, 18, 21
840
+ hh = int(str(ymdh_str[-2:]))
841
+ if hh in [0, 3, 6, 9, 12, 15, 18, 21]:
842
+ return True
843
+ else:
844
+ return False
845
+
846
+
847
+ def _check_dataset_version(dataset_name, version_name, download_time, download_time_end=None):
848
+ if dataset_name is not None and version_name is not None:
849
+ just_ensure = _ensure_time_in_specific_dataset_and_version(dataset_name, version_name, download_time, download_time_end)
850
+ if just_ensure:
851
+ return dataset_name, version_name
852
+ else:
853
+ return None, None
854
+
855
+ # 确保下载时间是一个字符串
856
+ download_time_str = str(download_time)
857
+
858
+ if len(download_time_str) == 8:
859
+ download_time_str = download_time_str + "00"
860
+
861
+ # 检查小时是否有效(如果需要的话)
862
+ if download_time_end is None and not _check_hour_is_valid(download_time_str):
863
+ print("Please ensure the hour is 00, 03, 06, 09, 12, 15, 18, 21")
864
+ raise ValueError("The hour is invalid")
865
+
866
+ # 根据是否检查整个天来设置时间范围
867
+ if download_time_end is not None:
868
+ if len(str(download_time_end)) == 8:
869
+ download_time_end = str(download_time_end) + "21"
870
+ have_data = _check_time_in_dataset_and_version(download_time_str, download_time_end)
871
+ if have_data:
872
+ return _direct_choose_dataset_and_version(download_time_str, download_time_end)
873
+ else:
874
+ have_data = _check_time_in_dataset_and_version(download_time_str)
875
+ if have_data:
876
+ return _direct_choose_dataset_and_version(download_time_str)
877
+
878
+ return None, None
879
+
880
+
881
+ 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):
882
+ # year_str = str(download_time)[:4]
883
+ ymdh_str = str(download_time)
884
+ if depth is not None and level_num is not None:
885
+ print("Please ensure the depth or level_num is None")
886
+ print("Progress will use the depth")
887
+ which_mode = "depth"
888
+ elif depth is not None and level_num is None:
889
+ print(f"Data of single depth (~{depth} m) will be downloaded...")
890
+ which_mode = "depth"
891
+ elif level_num is not None and depth is None:
892
+ print(f"Data of single level ({level_num}) will be downloaded...")
893
+ which_mode = "level"
894
+ else:
895
+ # print("Full depth or full level data will be downloaded...")
896
+ which_mode = "full"
897
+ query_dict = _get_query_dict(var, lon_min, lon_max, lat_min, lat_max, download_time, download_time_end, which_mode, depth, level_num)
898
+ submit_url = _get_submit_url(dataset_name, version_name, var, ymdh_str, query_dict)
899
+ return submit_url
900
+
901
+
902
+ 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, check=False):
903
+ print("[bold #ecdbfe]-" * 160)
904
+ download_time = str(download_time)
905
+ if download_time_end is not None:
906
+ download_time_end = str(download_time_end)
907
+ dataset_name, version_name = _check_dataset_version(dataset_name, version_name, download_time, download_time_end)
908
+ else:
909
+ dataset_name, version_name = _check_dataset_version(dataset_name, version_name, download_time)
910
+ if dataset_name is None and version_name is None:
911
+ count_dict["no_data"] += 1
912
+ if download_time_end is not None:
913
+ count_dict["no_data_list"].append(f"{download_time}-{download_time_end}")
914
+ else:
915
+ count_dict["no_data_list"].append(download_time)
916
+ return
917
+
918
+ if isinstance(var, str):
919
+ var = [var]
920
+
921
+ if isinstance(var, list):
922
+ if len(var) == 1:
923
+ var = var[0]
924
+ 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)
925
+ file_name = f"HYCOM_{variable_info[var]['var_name']}_{download_time}.nc"
926
+ if download_time_end is not None:
927
+ file_name = f"HYCOM_{variable_info[var]['var_name']}_{download_time}-{download_time_end}.nc" # 这里时间不能用下划线,不然后续处理查找同一变量文件会出问题
928
+ _download_file(submit_url, store_path, file_name, check)
929
+ else:
930
+ if download_time < "2024081012":
931
+ varlist = [_ for _ in var]
932
+ for key, value in var_group.items():
933
+ current_group = []
934
+ for v in varlist:
935
+ if v in value:
936
+ current_group.append(v)
937
+ if len(current_group) == 0:
938
+ continue
939
+
940
+ var = current_group[0]
941
+ 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)
942
+ file_name = f"HYCOM_{variable_info[var]['var_name']}_{download_time}.nc"
943
+ old_str = f"var={variable_info[var]['var_name']}"
944
+ new_str = f"var={variable_info[var]['var_name']}"
945
+ if len(current_group) > 1:
946
+ for v in current_group[1:]:
947
+ new_str = f"{new_str}&var={variable_info[v]['var_name']}"
948
+ submit_url = submit_url.replace(old_str, new_str)
949
+ # file_name = f'HYCOM_{'-'.join([variable_info[v]["var_name"] for v in current_group])}_{download_time}.nc'
950
+ file_name = f"HYCOM_{key}_{download_time}.nc"
951
+ if download_time_end is not None:
952
+ file_name = f"HYCOM_{key}_{download_time}-{download_time_end}.nc" # 这里时间不能用下划线,不然后续处理查找同一变量文件会出问题
953
+ _download_file(submit_url, store_path, file_name, check)
954
+ else:
955
+ for v in var:
956
+ 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)
957
+ file_name = f"HYCOM_{variable_info[v]['var_name']}_{download_time}.nc"
958
+ if download_time_end is not None:
959
+ file_name = f"HYCOM_{variable_info[v]['var_name']}_{download_time}-{download_time_end}.nc"
960
+ _download_file(submit_url, store_path, file_name, check)
961
+
962
+
963
+ def _convert_full_name_to_short_name(full_name):
964
+ for var, info in variable_info.items():
965
+ if full_name == info["var_name"] or full_name == info["standard_name"] or full_name == var:
966
+ return var
967
+ 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")
968
+ print("or")
969
+ print("[bold blue]water_u, water_v, water_temp, salinity, surf_el, water_u_bottom, water_v_bottom, water_temp_bottom, salinity_bottom")
970
+ return False
971
+
972
+
973
+ 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, check):
974
+ """
975
+ # 并行下载任务
976
+ # 这个函数是为了并行下载而设置的,是必须的,直接调用direct_download并行下载会出问题
977
+
978
+ 任务封装:将每个任务需要的数据和操作封装在一个函数中,这样每个任务都是独立的,不会相互干扰。
979
+ 本情况下,download_task函数的作用是将每个下载任务封装起来,包括它所需的所有参数。
980
+ 这样,每个任务都是独立的,有自己的参数和数据,不会与其他任务共享或修改任何数据。
981
+ 因此,即使多个任务同时执行,也不会出现数据交互错乱的问题。
982
+ """
983
+
984
+ _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, check)
985
+
986
+
987
+ def _done_callback(future, progress, task, total, counter_lock):
988
+ """
989
+ # 并行下载任务的回调函数
990
+ # 这个函数是为了并行下载而设置的,是必须的,直接调用direct_download并行下载会出问题
991
+
992
+ 回调函数:当一个任务完成后,会调用这个函数,这样可以及时更新进度条,显示任务的完成情况。
993
+ 本情况下,done_callback函数的作用是当一个任务完成后,更新进度条的进度,显示任务的完成情况。
994
+ 这样,即使多个任务同时执行,也可以及时看到每个任务的完成情况,不会等到所有任务都完成才显示。
995
+ """
996
+
997
+ global parallel_counter
998
+ with counter_lock:
999
+ parallel_counter += 1
1000
+ progress.update(task, advance=1, description=f"[cyan]Downloading... {parallel_counter}/{total}")
1001
+
1002
+
1003
+ 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, check=False, ftimes=1):
1004
+ """
1005
+ Description:
1006
+ Download the data of single time or a series of time
1007
+
1008
+ Parameters:
1009
+ var: str, the variable name, such as 'u', 'v', 'temp', 'salt', 'ssh', 'u_b', 'v_b', 'temp_b', 'salt_b' or 'water_u', 'water_v', 'water_temp', 'salinity', 'surf_el', 'water_u_bottom', 'water_v_bottom', 'water_temp_bottom', 'salinity_bottom'
1010
+ time_s: str, the start time, such as '2024110100' or '20241101', if add hour, the hour should be 00, 03, 06, 09, 12, 15, 18, 21
1011
+ time_e: str, the end time, such as '2024110221' or '20241102', if add hour, the hour should be 00, 03, 06, 09, 12, 15, 18, 21
1012
+ lon_min: float, the minimum longitude, default is 0
1013
+ lon_max: float, the maximum longitude, default is 359.92
1014
+ lat_min: float, the minimum latitude, default is -80
1015
+ lat_max: float, the maximum latitude, default is 90
1016
+ depth: float, the depth, default is None
1017
+ level: int, the level number, default is None
1018
+ store_path: str, the path to store the data, default is None
1019
+ dataset_name: str, the dataset name, default is None, example: 'GLBv0.08', 'GLBu0.08', 'GLBy0.08'
1020
+ version_name: str, the version name, default is None, example: '53.X', '56.3'
1021
+ num_workers: int, the number of workers, default is None
1022
+
1023
+ Returns:
1024
+ None
1025
+ """
1026
+ ymdh_time_s, ymdh_time_e = str(time_s), str(time_e)
1027
+ if num_workers is not None and num_workers > 1: # 如果使用多线程下载,用于进度条显示
1028
+ global parallel_counter
1029
+ parallel_counter = 0
1030
+ counter_lock = Lock() # 创建一个锁,线程安全的计数器
1031
+ if ymdh_time_s == ymdh_time_e:
1032
+ _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, check)
1033
+ elif int(ymdh_time_s) < int(ymdh_time_e):
1034
+ print("Downloading a series of files...")
1035
+ time_list = get_time_list(ymdh_time_s, ymdh_time_e, 3, "hour")
1036
+ with Progress() as progress:
1037
+ task = progress.add_task("[cyan]Downloading...", total=len(time_list))
1038
+ if ftimes == 1:
1039
+ if num_workers is None or num_workers <= 1:
1040
+ # 串行方式
1041
+ for i, time_str in enumerate(time_list):
1042
+ _prepare_url_to_download(var, lon_min, lon_max, lat_min, lat_max, time_str, None, depth, level, store_path, dataset_name, version_name, check)
1043
+ progress.update(task, advance=1, description=f"[cyan]Downloading... {i + 1}/{len(time_list)}")
1044
+ else:
1045
+ # 并行方式
1046
+ with ThreadPoolExecutor(max_workers=num_workers) as executor:
1047
+ 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, check) for time_str in time_list]
1048
+ """ for i, future in enumerate(futures):
1049
+ future.add_done_callback(lambda _: progress.update(task, advance=1, description=f"[cyan]Downloading... {i+1}/{len(time_list)}")) """
1050
+ for feature in as_completed(futures):
1051
+ _done_callback(feature, progress, task, len(time_list), counter_lock)
1052
+ else:
1053
+ new_time_list = get_time_list(ymdh_time_s, ymdh_time_e, 3 * ftimes, "hour")
1054
+ total_num = len(new_time_list)
1055
+ if num_workers is None or num_workers <= 1:
1056
+ # 串行方式
1057
+ for i, time_str in enumerate(new_time_list):
1058
+ time_str_end_index = int(min(len(time_list) - 1, int(i * ftimes + ftimes - 1)))
1059
+ time_str_end = time_list[time_str_end_index]
1060
+ _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, check)
1061
+ progress.update(task, advance=1, description=f"[cyan]Downloading... {i + 1}/{total_num}")
1062
+ else:
1063
+ # 并行方式
1064
+ with ThreadPoolExecutor(max_workers=num_workers) as executor:
1065
+ futures = [executor.submit(_download_task, var, new_time_list[i], time_list[int(min(len(time_list) - 1, int(i * ftimes + ftimes - 1)))], lon_min, lon_max, lat_min, lat_max, depth, level, store_path, dataset_name, version_name, check) for i in range(total_num)]
1066
+ """ for i, future in enumerate(futures):
1067
+ future.add_done_callback(lambda _: progress.update(task, advance=1, description=f"[cyan]Downloading... {i+1}/{total_num}")) """
1068
+ for feature in as_completed(futures):
1069
+ _done_callback(feature, progress, task, len(time_list), counter_lock)
1070
+ else:
1071
+ print("[bold red]Please ensure the time_s is no more than time_e")
1072
+
1073
+
1074
+ def download(var, time_s, time_e=None, 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, check=False, ftimes=1, idm_engine=None, fill_time=None):
1075
+ """
1076
+ Description:
1077
+ Download the data of single time or a series of time
1078
+
1079
+ Parameters:
1080
+ var: str or list, the variable name, such as 'u', 'v', 'temp', 'salt', 'ssh', 'u_b', 'v_b', 'temp_b', 'salt_b' or 'water_u', 'water_v', 'water_temp', 'salinity', 'surf_el', 'water_u_bottom', 'water_v_bottom', 'water_temp_bottom', 'salinity_bottom'
1081
+ time_s: str, the start time, such as '2024110100' or '20241101', if add hour, the hour should be 00, 03, 06, 09, 12, 15, 18, 21
1082
+ time_e: str, the end time, such as '2024110221' or '20241102', if add hour, the hour should be 00, 03, 06, 09, 12, 15, 18, 21; default is None, if not set, the data of single time will be downloaded; or same as time_s, the data of single time will be downloaded
1083
+ lon_min: float, the minimum longitude, default is 0
1084
+ lon_max: float, the maximum longitude, default is 359.92
1085
+ lat_min: float, the minimum latitude, default is -80
1086
+ lat_max: float, the maximum latitude, default is 90
1087
+ depth: float, the depth, default is None, if you wanna get the data of single depth, you can set the depth, suggest to set the depth in [0, 5000]
1088
+ level: int, the level number, default is None, if you wanna get the data of single level, you can set the level, suggest to set the level in [1, 40]
1089
+ store_path: str, the path to store the data, default is None, if not set, the data will be stored in the current working directory
1090
+ dataset_name: str, the dataset name, default is None, example: 'GLBv0.08', 'GLBu0.08', 'GLBy0.08', if not set, the dataset will be chosen according to the download_time
1091
+ version_name: str, the version name, default is None, example: '53.X', '56.3', if not set, the version will be chosen according to the download_time
1092
+ num_workers: int, the number of workers, default is None, if not set, the number of workers will be 1; suggest not to set the number of workers too large
1093
+ check: bool, whether to check the existing file, default is False, if set to True, the existing file will be checked and not downloaded again; else, the existing file will be covered
1094
+ ftimes: int, the number of time in one file, default is 1, if set to 1, the data of single time will be downloaded; the maximum is 8, if set to 8, the data of 8 times will be downloaded in one file
1095
+ idm_engine: str, the IDM engine, default is None, if set, the IDM will be used to download the data; example: "D:\\Programs\\Internet Download Manager\\IDMan.exe"
1096
+ fill_time: bool or None, the mode to fill the time, default is None. None: only download the data; True: modify the real time of data to the time in the file name; False: check the time in the file name and the real time of data, if not match, delete the file
1097
+
1098
+ Returns:
1099
+ None
1100
+ """
1101
+ _get_initial_data()
1102
+
1103
+ # 打印信息并处理数据集和版本名称
1104
+ if dataset_name is None and version_name is None:
1105
+ print("The dataset_name and version_name are None, so the dataset and version will be chosen according to the download_time.\nIf there is more than one dataset and version in the time range, the first one will be chosen.")
1106
+ print("If you wanna choose the dataset and version by yourself, please set the dataset_name and version_name together.")
1107
+ elif dataset_name is None and version_name is not None:
1108
+ print("Please ensure the dataset_name is not None")
1109
+ print("If you do not add the dataset_name, both the dataset and version will be chosen according to the download_time.")
1110
+ elif dataset_name is not None and version_name is None:
1111
+ print("Please ensure the version_name is not None")
1112
+ print("If you do not add the version_name, both the dataset and version will be chosen according to the download_time.")
1113
+ else:
1114
+ print("The dataset_name and version_name are both set by yourself.")
1115
+ print("Please ensure the dataset_name and version_name are correct.")
1116
+
1117
+ if isinstance(var, list):
1118
+ if len(var) == 1:
1119
+ var = _convert_full_name_to_short_name(var[0])
1120
+ else:
1121
+ var = [_convert_full_name_to_short_name(v) for v in var]
1122
+ elif isinstance(var, str):
1123
+ var = _convert_full_name_to_short_name(var)
1124
+ else:
1125
+ raise ValueError("The var is invalid")
1126
+ if var is False:
1127
+ raise ValueError("The var is invalid")
1128
+ if lon_min < 0 or lon_min > 359.92 or lon_max < 0 or lon_max > 359.92 or lat_min < -80 or lat_min > 90 or lat_max < -80 or lat_max > 90:
1129
+ print("Please ensure the lon_min, lon_max, lat_min, lat_max are in the range")
1130
+ print("The range of lon_min, lon_max is 0~359.92")
1131
+ print("The range of lat_min, lat_max is -80~90")
1132
+ raise ValueError("The lon or lat is invalid")
1133
+
1134
+ if ftimes != 1:
1135
+ print("Please ensure the ftimes is in [1, 8]")
1136
+ ftimes = max(min(ftimes, 8), 1)
1137
+
1138
+ if store_path is None:
1139
+ store_path = str(Path.cwd())
1140
+ else:
1141
+ os.makedirs(str(store_path), exist_ok=True)
1142
+
1143
+ if num_workers is not None:
1144
+ num_workers = max(min(num_workers, 10), 1) # 暂时不限制最大值,再检查的时候可以多开一些线程
1145
+ # num_workers = int(max(num_workers, 1))
1146
+ time_s = str(time_s)
1147
+ if len(time_s) == 8:
1148
+ time_s += "00"
1149
+ if time_e is None:
1150
+ time_e = time_s[:]
1151
+ else:
1152
+ time_e = str(time_e)
1153
+ if len(time_e) == 8:
1154
+ time_e += "21"
1155
+
1156
+ global count_dict
1157
+ count_dict = {"success": 0, "fail": 0, "skip": 0, "no_data": 0, "total": 0, "no_data_list": []}
1158
+
1159
+ """ global current_platform
1160
+ current_platform = platform.system() """
1161
+
1162
+ global fsize_dict
1163
+ fsize_dict = {}
1164
+
1165
+ global fsize_dict_lock
1166
+ fsize_dict_lock = Lock()
1167
+
1168
+ if fill_time is not None:
1169
+ num_workers = 1
1170
+
1171
+ global use_idm, given_idm_engine, idm_download_list
1172
+ if idm_engine is not None:
1173
+ use_idm = True
1174
+ num_workers = 1
1175
+ given_idm_engine = idm_engine
1176
+ idm_download_list = []
1177
+ else:
1178
+ use_idm = False
1179
+
1180
+ global match_time
1181
+ match_time = fill_time
1182
+
1183
+ _download_hourly_func(var, time_s, time_e, lon_min, lon_max, lat_min, lat_max, depth, level, store_path, dataset_name, version_name, num_workers, check, ftimes)
1184
+
1185
+ if idm_engine is not None:
1186
+ if idm_download_list:
1187
+ for f in idm_download_list:
1188
+ wait_success = 0
1189
+ success = False
1190
+ while not success:
1191
+ if check_nc(f):
1192
+ count_dict["success"] += 1
1193
+ success = True
1194
+ else:
1195
+ wait_success += 1
1196
+ time.sleep(3)
1197
+ if wait_success >= 20:
1198
+ success = True
1199
+ # print(f'{f} download failed')
1200
+ count_dict["fail"] += 1
1201
+
1202
+ count_dict["total"] = count_dict["success"] + count_dict["fail"] + count_dict["skip"] + count_dict["no_data"]
1203
+ print("[bold #ecdbfe]-" * 160)
1204
+ 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']}")
1205
+ print("[bold #ecdbfe]-" * 160)
1206
+ if count_dict["fail"] > 0:
1207
+ print("[bold #be5528]Please try again to download the failed data later")
1208
+ if count_dict["no_data"] > 0:
1209
+ if count_dict["no_data"] == 1:
1210
+ print(f"[bold #f90000]There is {count_dict['no_data']} data that does not exist in any dataset and version")
1211
+ else:
1212
+ print(f"[bold #f90000]These are {count_dict['no_data']} data that do not exist in any dataset and version")
1213
+ for no_data in count_dict["no_data_list"]:
1214
+ print(f"[bold #d81b60]{no_data}")
1215
+ print("[bold #ecdbfe]-" * 160)
1216
+
1217
+
1218
+ def how_to_use():
1219
+ print("""
1220
+ # 1. Choose the dataset and version according to the time:
1221
+ # 1.1 Use function to query
1222
+ You can use the function check_time_in_dataset_and_version(time_input=20241101) to find the dataset and version according to the time.
1223
+ Then, you can see the dataset and version in the output.
1224
+ # 1.2 Draw a picture to see
1225
+ You can draw a picture to see the time range of each dataset and version.
1226
+ Using the function draw_time_range(pic_save_folder=None) to draw the picture.
1227
+
1228
+ # 2. Get the base url according to the dataset, version, var and year:
1229
+ # 2.1 Dataset and version were found in step 1
1230
+ # 2.2 Var: u, v, temp, salt, ssh, u_b, v_b, temp_b, salt_b
1231
+ # 2.3 Year: 1994-2024(current year)
1232
+
1233
+ # 3. Get the query_dict according to the var, lon_min, lon_max, lat_min, lat_max, depth, level_num, time_str_ymdh:
1234
+ # 3.1 Var: u, v, temp, salt, ssh, u_b, v_b, temp_b, salt_b
1235
+ # 3.2 Lon_min, lon_max, lat_min, lat_max: float
1236
+ # 3.3 Depth: 0-5000m, if you wanna get single depth data, you can set the depth
1237
+ # 3.4 Level_num: 1-40, if you wanna get single level data, you can set the level_num
1238
+ # 3.5 Time_str_ymdh: '2024110112', the hour normally is 00, 03, 06, 09, 12, 15, 18, 21, besides 1 hourly data
1239
+ # 3.6 Use the function to get the query_dict
1240
+ # 3.7 Note: If you wanna get the full depth or full level data, you can needn't set the depth or level_num
1241
+
1242
+ # 4. Get the submit url according to the dataset, version, var, year, query_dict:
1243
+ # 4.1 Use the function to get the submit url
1244
+ # 4.2 You can use the submit url to download the data
1245
+
1246
+ # 5. Download the data according to the submit url:
1247
+ # 5.1 Use the function to download the data
1248
+ # 5.2 You can download the data of single time or a series of time
1249
+ # 5.3 Note: If you wanna download a series of data, you can set the ymdh_time_s and ymdh_time_e different
1250
+ # 5.4 Note: The time resolution is 3 hours
1251
+
1252
+ # 6. Direct download the data:
1253
+ # 6.1 Use the function to direct download the data
1254
+ # 6.2 You can set the dataset_name and version_name by yourself
1255
+ # 6.3 Note: If you do not set the dataset_name and version_name, the dataset and version will be chosen according to the download_time
1256
+ # 6.4 Note: If you set the dataset_name and version_name, please ensure the dataset_name and version_name are correct
1257
+ # 6.5 Note: If you just set one of the dataset_name and version_name, both the dataset and version will be chosen according to the download_time
1258
+
1259
+ # 7. Simple use:
1260
+ # 7.1 You can use the function: download(var, ymdh_time_s, ymdh_time_e, lon_min=0, lon_max=359.92, lat_min=-80, lat_max=90, depth=None, level_num=None, store_path=None, dataset_name=None, version_name=None)
1261
+ # 7.2 You can download the data of single time or a series of time
1262
+ # 7.3 The parameters you must set are var, ymdh_time_s, ymdh_time_e
1263
+ # 7.4 Example: download('u', '2024110112', '2024110212', lon_min=0, lon_max=359.92, lat_min=-80, lat_max=90, depth=None, level_num=None, store_path=None, dataset_name=None, version_name=None)
1264
+ """)
1265
+
1266
+
1267
+ if __name__ == "__main__":
1268
+ download_dict = {
1269
+ "water_u": {"simple_name": "u", "download": 1},
1270
+ "water_v": {"simple_name": "v", "download": 1},
1271
+ "surf_el": {"simple_name": "ssh", "download": 1},
1272
+ "water_temp": {"simple_name": "temp", "download": 1},
1273
+ "salinity": {"simple_name": "salt", "download": 1},
1274
+ "water_u_bottom": {"simple_name": "u_b", "download": 0},
1275
+ "water_v_bottom": {"simple_name": "v_b", "download": 0},
1276
+ "water_temp_bottom": {"simple_name": "temp_b", "download": 0},
1277
+ "salinity_bottom": {"simple_name": "salt_b", "download": 0},
1278
+ }
1279
+
1280
+ var_list = [var_name for var_name in download_dict.keys() if download_dict[var_name]["download"]]
1281
+
1282
+ single_var = False
1283
+
1284
+ # draw_time_range(pic_save_folder=r'I:\Delete')
1285
+
1286
+ options = {
1287
+ "var": var_list,
1288
+ "time_s": "2025010300",
1289
+ "time_e": "2025010321",
1290
+ "store_path": r"I:\Data\HYCOM\3hourly",
1291
+ "lon_min": 105,
1292
+ "lon_max": 130,
1293
+ "lat_min": 15,
1294
+ "lat_max": 45,
1295
+ "num_workers": 3,
1296
+ "check": True,
1297
+ "depth": None, # or 0-5000 meters
1298
+ "level": None, # or 1-40 levels
1299
+ "ftimes": 1,
1300
+ # "idm_engine": r"D:\Programs\Internet Download Manager\IDMan.exe", # 查漏补缺不建议开启
1301
+ "fill_time": None,
1302
+ }
1303
+
1304
+ if single_var:
1305
+ for var_name in var_list:
1306
+ options["var"] = var_name
1307
+ download(**options)
1308
+ else:
1309
+ download(**options)