oafuncs 0.0.81__py2.py3-none-any.whl → 0.0.83__py2.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.
- oafuncs/data_store/OAFuncs.png +0 -0
- oafuncs/oa_cmap.py +1 -0
- oafuncs/oa_data.py +107 -28
- oafuncs/oa_down/__init__.py +5 -4
- oafuncs/oa_down/hycom_3hourly.py +152 -35
- oafuncs/oa_down/user_agent.py +34 -0
- oafuncs/oa_draw.py +165 -103
- oafuncs/oa_file.py +66 -53
- oafuncs/oa_help.py +19 -16
- oafuncs/oa_nc.py +82 -114
- oafuncs-0.0.83.dist-info/METADATA +91 -0
- oafuncs-0.0.83.dist-info/RECORD +26 -0
- oafuncs/oa_down/test.py +0 -151
- oafuncs/oa_s/__init__.py +0 -23
- oafuncs/oa_s/oa_cmap.py +0 -163
- oafuncs/oa_s/oa_data.py +0 -187
- oafuncs/oa_s/oa_draw.py +0 -451
- oafuncs/oa_s/oa_file.py +0 -332
- oafuncs/oa_s/oa_help.py +0 -39
- oafuncs/oa_s/oa_nc.py +0 -410
- oafuncs/oa_s/oa_python.py +0 -107
- oafuncs - /321/205/320/231/320/277/321/206/320/254/320/274/__init__.py" +0 -26
- oafuncs - /321/205/320/231/320/277/321/206/320/254/320/274/oa_cmap.py" +0 -163
- oafuncs - /321/205/320/231/320/277/321/206/320/254/320/274/oa_data.py" +0 -187
- oafuncs - /321/205/320/231/320/277/321/206/320/254/320/274/oa_down/__init__.py" +0 -20
- oafuncs - /321/205/320/231/320/277/321/206/320/254/320/274/oa_down/hycom_3hourly.py" +0 -1176
- oafuncs - /321/205/320/231/320/277/321/206/320/254/320/274/oa_down/literature.py" +0 -332
- oafuncs - /321/205/320/231/320/277/321/206/320/254/320/274/oa_down/test_ua.py" +0 -151
- oafuncs - /321/205/320/231/320/277/321/206/320/254/320/274/oa_draw.py" +0 -451
- oafuncs - /321/205/320/231/320/277/321/206/320/254/320/274/oa_file.py" +0 -332
- oafuncs - /321/205/320/231/320/277/321/206/320/254/320/274/oa_help.py" +0 -39
- oafuncs - /321/205/320/231/320/277/321/206/320/254/320/274/oa_nc.py" +0 -410
- oafuncs - /321/205/320/231/320/277/321/206/320/254/320/274/oa_python.py" +0 -107
- oafuncs - /321/205/320/231/320/277/321/206/320/254/320/274/oa_sign/__init__.py" +0 -21
- oafuncs - /321/205/320/231/320/277/321/206/320/254/320/274/oa_sign/meteorological.py" +0 -168
- oafuncs - /321/205/320/231/320/277/321/206/320/254/320/274/oa_sign/ocean.py" +0 -158
- oafuncs - /321/205/320/231/320/277/321/206/320/254/320/274/oa_sign/scientific.py" +0 -139
- oafuncs - /321/205/320/231/320/277/321/206/320/254/320/274/oa_tool/__init__.py" +0 -18
- oafuncs - /321/205/320/231/320/277/321/206/320/254/320/274/oa_tool/email.py" +0 -114
- oafuncs-0.0.81.dist-info/METADATA +0 -918
- oafuncs-0.0.81.dist-info/RECORD +0 -51
- {oafuncs-0.0.81.dist-info → oafuncs-0.0.83.dist-info}/LICENSE.txt +0 -0
- {oafuncs-0.0.81.dist-info → oafuncs-0.0.83.dist-info}/WHEEL +0 -0
- {oafuncs-0.0.81.dist-info → oafuncs-0.0.83.dist-info}/top_level.txt +0 -0
oafuncs/oa_s/oa_nc.py
DELETED
@@ -1,410 +0,0 @@
|
|
1
|
-
#!/usr/bin/env python
|
2
|
-
# coding=utf-8
|
3
|
-
"""
|
4
|
-
Author: Liu Kun && 16031215@qq.com
|
5
|
-
Date: 2024-09-17 14:58:50
|
6
|
-
LastEditors: Liu Kun && 16031215@qq.com
|
7
|
-
LastEditTime: 2024-12-06 14:16:56
|
8
|
-
FilePath: \\Python\\My_Funcs\\OAFuncs\\oafuncs\\oa_nc.py
|
9
|
-
Description:
|
10
|
-
EditPlatform: vscode
|
11
|
-
ComputerInfo: XPS 15 9510
|
12
|
-
SystemInfo: Windows 11
|
13
|
-
Python Version: 3.11
|
14
|
-
"""
|
15
|
-
|
16
|
-
import os
|
17
|
-
|
18
|
-
import netCDF4 as nc
|
19
|
-
import numpy as np
|
20
|
-
import xarray as xr
|
21
|
-
|
22
|
-
__all__ = ["get_var", "extract5nc", "write2nc", "merge5nc", "modify_var_value", "modify_var_attr", "rename_var_or_dim", "check_ncfile", "longitude_change", "nc_isel"]
|
23
|
-
|
24
|
-
|
25
|
-
def get_var(file, *vars):
|
26
|
-
"""
|
27
|
-
description: 读取nc文件中的变量
|
28
|
-
param {file: 文件路径, *vars: 变量名}
|
29
|
-
example: datas = get_var(file_ecm, 'h', 't', 'u', 'v')
|
30
|
-
return {datas: 变量数据}
|
31
|
-
"""
|
32
|
-
ds = xr.open_dataset(file)
|
33
|
-
datas = []
|
34
|
-
for var in vars:
|
35
|
-
data = ds[var]
|
36
|
-
datas.append(data)
|
37
|
-
ds.close()
|
38
|
-
return datas
|
39
|
-
|
40
|
-
|
41
|
-
def extract5nc(file, varname, only_value=True):
|
42
|
-
"""
|
43
|
-
描述:
|
44
|
-
1、提取nc文件中的变量
|
45
|
-
2、将相应维度提取,建立字典
|
46
|
-
return:返回变量及坐标字典
|
47
|
-
参数:
|
48
|
-
file: 文件路径
|
49
|
-
varname: 变量名
|
50
|
-
only_value: 变量和维度是否只保留数值
|
51
|
-
example: data, dimdict = extract5nc(file_ecm, 'h')
|
52
|
-
"""
|
53
|
-
ds = xr.open_dataset(file)
|
54
|
-
vardata = ds[varname]
|
55
|
-
ds.close()
|
56
|
-
dims = vardata.dims
|
57
|
-
dimdict = {}
|
58
|
-
for dim in dims:
|
59
|
-
if only_value:
|
60
|
-
dimdict[dim] = vardata[dim].values
|
61
|
-
else:
|
62
|
-
dimdict[dim] = ds[dim]
|
63
|
-
if only_value:
|
64
|
-
vardata = np.array(vardata)
|
65
|
-
return vardata, dimdict
|
66
|
-
|
67
|
-
|
68
|
-
def _numpy_to_nc_type(numpy_type):
|
69
|
-
"""将NumPy数据类型映射到NetCDF数据类型"""
|
70
|
-
numpy_to_nc = {
|
71
|
-
"float32": "f4",
|
72
|
-
"float64": "f8",
|
73
|
-
"int8": "i1",
|
74
|
-
"int16": "i2",
|
75
|
-
"int32": "i4",
|
76
|
-
"int64": "i8",
|
77
|
-
"uint8": "u1",
|
78
|
-
"uint16": "u2",
|
79
|
-
"uint32": "u4",
|
80
|
-
"uint64": "u8",
|
81
|
-
}
|
82
|
-
return numpy_to_nc.get(str(numpy_type), "f4") # 默认使用 'float32'
|
83
|
-
|
84
|
-
|
85
|
-
def write2nc(file, data, varname=None, coords=None, mode='w'):
|
86
|
-
"""
|
87
|
-
description: 写入数据到nc文件
|
88
|
-
参数:
|
89
|
-
file: 文件路径
|
90
|
-
data: 数据
|
91
|
-
varname: 变量名
|
92
|
-
coords: 坐标,字典,键为维度名称,值为坐标数据
|
93
|
-
mode: 写入模式,'w'为写入,'a'为追加
|
94
|
-
example: write2nc(r'test.nc', data, 'data', {'time': np.linspace(0, 120, 100), 'lev': np.linspace(0, 120, 50)}, 'a')
|
95
|
-
"""
|
96
|
-
# 判断mode是写入还是追加
|
97
|
-
if mode == "w":
|
98
|
-
if os.path.exists(file):
|
99
|
-
os.remove(file)
|
100
|
-
print("Warning: File already exists. Deleting it.")
|
101
|
-
elif mode == "a":
|
102
|
-
if not os.path.exists(file):
|
103
|
-
print("Warning: File doesn't exist. Creating a new file.")
|
104
|
-
mode = "w"
|
105
|
-
|
106
|
-
complete = False
|
107
|
-
if varname is None and coords is None:
|
108
|
-
try:
|
109
|
-
data.to_netcdf(file)
|
110
|
-
complete = True
|
111
|
-
# 不能在这里return
|
112
|
-
except AttributeError:
|
113
|
-
raise ValueError("If varname and coords are None, data must be a DataArray.")
|
114
|
-
|
115
|
-
if complete:
|
116
|
-
return
|
117
|
-
|
118
|
-
# kwargs = {'zlib': True, 'complevel': 4} # 压缩参数
|
119
|
-
kwargs = {"compression": 'zlib', "complevel": 9} # 压缩参数
|
120
|
-
|
121
|
-
# 打开 NetCDF 文件
|
122
|
-
with nc.Dataset(file, mode, format="NETCDF4") as ncfile:
|
123
|
-
# 处理坐标
|
124
|
-
for dim, coord_data in coords.items():
|
125
|
-
add_coords = True
|
126
|
-
# 判断坐标是否存在,若存在,则替换/报错
|
127
|
-
if ncfile.dimensions:
|
128
|
-
# 返回字典,字典、列表、元组若为空,都表示False
|
129
|
-
if dim in ncfile.dimensions:
|
130
|
-
# del nc.dimensions[dim]
|
131
|
-
if len(coord_data) != len(ncfile.dimensions[dim]):
|
132
|
-
raise ValueError("Length of coordinate does not match the dimension length.")
|
133
|
-
else:
|
134
|
-
add_coords = False
|
135
|
-
print(f"Warning: Coordinate '{dim}' already exists. Replacing it.")
|
136
|
-
ncfile.variables[dim][:] = np.array(coord_data)
|
137
|
-
if add_coords:
|
138
|
-
# 创建新坐标
|
139
|
-
ncfile.createDimension(dim, len(coord_data))
|
140
|
-
ncfile.createVariable(dim, _numpy_to_nc_type(coord_data.dtype), (dim,), **kwargs)
|
141
|
-
ncfile.variables[dim][:] = np.array(coord_data)
|
142
|
-
|
143
|
-
if isinstance(coord_data, xr.DataArray):
|
144
|
-
current_var = ncfile.variables[dim]
|
145
|
-
if coord_data.attrs:
|
146
|
-
for key, value in coord_data.attrs.items():
|
147
|
-
current_var.setncattr(key, value)
|
148
|
-
|
149
|
-
# 判断变量是否存在,若存在,则删除原变量
|
150
|
-
add_var = True
|
151
|
-
if varname in ncfile.variables:
|
152
|
-
print(f"Warning: Variable '{varname}' already exists.")
|
153
|
-
if data.shape != ncfile.variables[varname].shape:
|
154
|
-
raise ValueError("Shape of data does not match the variable shape.")
|
155
|
-
else:
|
156
|
-
# 写入数据
|
157
|
-
ncfile.variables[varname][:] = np.array(data)
|
158
|
-
add_var = False
|
159
|
-
print(f"Warning: Variable '{varname}' already exists. Replacing it.")
|
160
|
-
|
161
|
-
if add_var:
|
162
|
-
# 创建变量及其维度
|
163
|
-
dim_names = tuple(coords.keys()) # 使用coords传入的维度名称
|
164
|
-
ncfile.createVariable(varname, _numpy_to_nc_type(data.dtype), dim_names, **kwargs)
|
165
|
-
# ncfile.createVariable('data', 'f4', ('time','lev'))
|
166
|
-
|
167
|
-
# 写入数据
|
168
|
-
ncfile.variables[varname][:] = np.array(data)
|
169
|
-
|
170
|
-
# 判断维度是否匹配
|
171
|
-
if len(data.shape) != len(coords):
|
172
|
-
raise ValueError("Number of dimensions does not match the data shape.")
|
173
|
-
# 判断data是否带有属性信息,如果有,写入属性信息
|
174
|
-
if isinstance(data, xr.DataArray):
|
175
|
-
current_var = ncfile.variables[varname]
|
176
|
-
if data.attrs:
|
177
|
-
for key, value in data.attrs.items():
|
178
|
-
current_var.setncattr(key, value)
|
179
|
-
|
180
|
-
|
181
|
-
def merge5nc(file_list, var_name=None, dim_name=None, target_filename=None):
|
182
|
-
"""
|
183
|
-
批量提取 nc 文件中的变量,按照某一维度合并后写入新的 nc 文件。
|
184
|
-
如果 var_name 是字符串,则认为是单变量;如果是列表,且只有一个元素,也是单变量;
|
185
|
-
如果列表元素大于1,则是多变量;如果 var_name 是 None,则合并所有变量。
|
186
|
-
|
187
|
-
参数:
|
188
|
-
file_list:nc 文件路径列表
|
189
|
-
var_name:要提取的变量名或变量名列表,默认为 None,表示提取所有变量
|
190
|
-
dim_name:用于合并的维度名
|
191
|
-
target_filename:合并后的目标文件名
|
192
|
-
|
193
|
-
example:
|
194
|
-
merge5nc(file_list, var_name='data', dim_name='time', target_filename='merged.nc')
|
195
|
-
merge5nc(file_list, var_name=['data1', 'data2'], dim_name='time', target_filename='merged.nc')
|
196
|
-
merge5nc(file_list, var_name=None, dim_name='time', target_filename='merged.nc')
|
197
|
-
"""
|
198
|
-
# 初始化变量名列表
|
199
|
-
var_names = None
|
200
|
-
|
201
|
-
# 判断 var_name 是单变量、多变量还是合并所有变量
|
202
|
-
if var_name is None:
|
203
|
-
# 获取第一个文件中的所有变量名
|
204
|
-
ds = xr.open_dataset(file_list[0])
|
205
|
-
var_names = list(ds.variables.keys())
|
206
|
-
ds.close()
|
207
|
-
elif isinstance(var_name, str):
|
208
|
-
var_names = [var_name]
|
209
|
-
elif isinstance(var_name, list):
|
210
|
-
var_names = var_name
|
211
|
-
else:
|
212
|
-
raise ValueError("var_name must be a string, a list of strings, or None")
|
213
|
-
|
214
|
-
# 初始化合并数据字典
|
215
|
-
merged_data = {}
|
216
|
-
|
217
|
-
# 遍历文件列表
|
218
|
-
for i, file in enumerate(file_list):
|
219
|
-
print(f"\rReading file {i + 1}/{len(file_list)}...", end="")
|
220
|
-
ds = xr.open_dataset(file)
|
221
|
-
for var_name in var_names:
|
222
|
-
var = ds[var_name]
|
223
|
-
# 如果变量包含合并维度,则合并它们
|
224
|
-
if dim_name in var.dims:
|
225
|
-
if var_name not in merged_data:
|
226
|
-
merged_data[var_name] = [var]
|
227
|
-
else:
|
228
|
-
merged_data[var_name].append(var)
|
229
|
-
# 如果变量不包含合并维度,则仅保留第一个文件中的值
|
230
|
-
else:
|
231
|
-
if var_name not in merged_data:
|
232
|
-
merged_data[var_name] = var
|
233
|
-
ds.close()
|
234
|
-
|
235
|
-
print("\nMerging data...")
|
236
|
-
for var_name in merged_data:
|
237
|
-
if isinstance(merged_data[var_name], list):
|
238
|
-
merged_data[var_name] = xr.concat(merged_data[var_name], dim=dim_name)
|
239
|
-
|
240
|
-
merged_data = xr.Dataset(merged_data)
|
241
|
-
|
242
|
-
print("Writing data to file...")
|
243
|
-
if os.path.exists(target_filename):
|
244
|
-
print("Warning: The target file already exists.")
|
245
|
-
print("Removing existing file...")
|
246
|
-
os.remove(target_filename)
|
247
|
-
merged_data.to_netcdf(target_filename)
|
248
|
-
print(f'File "{target_filename}" has been created.')
|
249
|
-
|
250
|
-
|
251
|
-
def modify_var_value(nc_file_path, variable_name, new_value):
|
252
|
-
"""
|
253
|
-
使用 netCDF4 库修改 NetCDF 文件中特定变量的值
|
254
|
-
|
255
|
-
参数:
|
256
|
-
nc_file_path (str): NetCDF 文件路径
|
257
|
-
variable_name (str): 要修改的变量名
|
258
|
-
new_value (numpy.ndarray): 新的变量值
|
259
|
-
|
260
|
-
example: modify_var_value('test.nc', 'data', np.random.rand(100, 50))
|
261
|
-
"""
|
262
|
-
try:
|
263
|
-
# Open the NetCDF file
|
264
|
-
dataset = nc.Dataset(nc_file_path, "r+")
|
265
|
-
# Get the variable to be modified
|
266
|
-
variable = dataset.variables[variable_name]
|
267
|
-
# Modify the value of the variable
|
268
|
-
variable[:] = new_value
|
269
|
-
dataset.close()
|
270
|
-
print(f"Successfully modified variable {variable_name} in {nc_file_path}.")
|
271
|
-
except Exception as e:
|
272
|
-
print(f"An error occurred while modifying variable {variable_name} in {nc_file_path}: {e}")
|
273
|
-
|
274
|
-
|
275
|
-
def modify_var_attr(nc_file_path, variable_name, attribute_name, attribute_value):
|
276
|
-
"""
|
277
|
-
使用 netCDF4 库添加或修改 NetCDF 文件中特定变量的属性。
|
278
|
-
|
279
|
-
参数:
|
280
|
-
nc_file_path (str): NetCDF 文件路径
|
281
|
-
variable_name (str): 要操作的变量名
|
282
|
-
attribute_name (str): 属性名
|
283
|
-
attribute_value (任意类型): 属性值
|
284
|
-
example: modify_var_attr('test.nc', 'data', 'long_name', 'This is a test variable.')
|
285
|
-
"""
|
286
|
-
try:
|
287
|
-
ds = nc.Dataset(nc_file_path, "r+")
|
288
|
-
if variable_name not in ds.variables:
|
289
|
-
raise ValueError(f"Variable '{variable_name}' not found in the NetCDF file.")
|
290
|
-
|
291
|
-
variable = ds.variables[variable_name]
|
292
|
-
if attribute_name in variable.ncattrs():
|
293
|
-
print(f"Warning: Attribute '{attribute_name}' already exists. Replacing it.")
|
294
|
-
variable.setncattr(attribute_name, attribute_value)
|
295
|
-
else:
|
296
|
-
print(f"Adding attribute '{attribute_name}'...")
|
297
|
-
variable.setncattr(attribute_name, attribute_value)
|
298
|
-
|
299
|
-
ds.close()
|
300
|
-
except Exception as e:
|
301
|
-
raise RuntimeError(f"An error occurred: {e}")
|
302
|
-
|
303
|
-
|
304
|
-
def rename_var_or_dim(ncfile_path, old_name, new_name):
|
305
|
-
"""
|
306
|
-
Rename a variable and/or dimension in a NetCDF file.
|
307
|
-
|
308
|
-
Parameters:
|
309
|
-
ncfile_path (str): The path to the NetCDF file.
|
310
|
-
old_name (str): The name of the variable or dimension to be renamed.
|
311
|
-
new_name (str): The new name for the variable or dimension.
|
312
|
-
|
313
|
-
example: rename_var_or_dim('test.nc', 'time', 'ocean_time')
|
314
|
-
"""
|
315
|
-
try:
|
316
|
-
with nc.Dataset(ncfile_path, "r+") as dataset:
|
317
|
-
# If the old name is not found as a variable or dimension, print a message
|
318
|
-
if old_name not in dataset.variables and old_name not in dataset.dimensions:
|
319
|
-
print(f"Variable or dimension {old_name} not found in the file.")
|
320
|
-
|
321
|
-
# Attempt to rename the variable
|
322
|
-
if old_name in dataset.variables:
|
323
|
-
dataset.renameVariable(old_name, new_name)
|
324
|
-
print(f"Successfully renamed variable {old_name} to {new_name}.")
|
325
|
-
|
326
|
-
# Attempt to rename the dimension
|
327
|
-
if old_name in dataset.dimensions:
|
328
|
-
# Check if the new dimension name already exists
|
329
|
-
if new_name in dataset.dimensions:
|
330
|
-
raise ValueError(f"Dimension name {new_name} already exists in the file.")
|
331
|
-
dataset.renameDimension(old_name, new_name)
|
332
|
-
print(f"Successfully renamed dimension {old_name} to {new_name}.")
|
333
|
-
|
334
|
-
except Exception as e:
|
335
|
-
print(f"An error occurred: {e}")
|
336
|
-
|
337
|
-
|
338
|
-
def check_ncfile(ncfile, if_delete=False):
|
339
|
-
if not os.path.exists(ncfile):
|
340
|
-
return False
|
341
|
-
|
342
|
-
try:
|
343
|
-
with nc.Dataset(ncfile, "r") as f:
|
344
|
-
# 确保f被使用,这里我们检查文件中变量的数量
|
345
|
-
if len(f.variables) > 0:
|
346
|
-
return True
|
347
|
-
else:
|
348
|
-
# 如果没有变量,我们可以认为文件是损坏的
|
349
|
-
raise ValueError("File is empty or corrupted.")
|
350
|
-
except OSError as e:
|
351
|
-
# 捕获文件打开时可能发生的OSError
|
352
|
-
print(f"An error occurred while opening the file: {e}")
|
353
|
-
if if_delete:
|
354
|
-
os.remove(ncfile)
|
355
|
-
print(f"File {ncfile} has been deleted.")
|
356
|
-
return False
|
357
|
-
except Exception as e:
|
358
|
-
# 捕获其他可能的异常
|
359
|
-
print(f"An unexpected error occurred: {e}")
|
360
|
-
if if_delete:
|
361
|
-
os.remove(ncfile)
|
362
|
-
print(f"File {ncfile} has been deleted.")
|
363
|
-
return False
|
364
|
-
|
365
|
-
|
366
|
-
def longitude_change(ds, lon_name="longitude", to_which="180"):
|
367
|
-
"""
|
368
|
-
将经度转换为 -180 到 180 之间
|
369
|
-
|
370
|
-
参数:
|
371
|
-
lon (numpy.ndarray): 经度数组
|
372
|
-
|
373
|
-
返回值:
|
374
|
-
numpy.ndarray: 转换后的经度数组
|
375
|
-
"""
|
376
|
-
# return (lon + 180) % 360 - 180
|
377
|
-
# ds = ds.assign_coords(longitude=(((ds.longitude + 180) % 360) - 180)).sortby("longitude")
|
378
|
-
if to_which == "180":
|
379
|
-
# ds = ds.assign_coords(**{lon_name: (((ds[lon_name] + 180) % 360) - 180)}).sortby(lon_name)
|
380
|
-
ds = ds.assign_coords(**{lon_name: (ds[lon_name] + 180) % 360 - 180}).sortby(lon_name)
|
381
|
-
elif to_which == "360":
|
382
|
-
# -180 to 180 to 0 to 360
|
383
|
-
ds = ds.assign_coords(**{lon_name: (ds[lon_name] + 360) % 360}).sortby(lon_name)
|
384
|
-
return ds
|
385
|
-
|
386
|
-
|
387
|
-
def nc_isel(ncfile, dim_name, slice_list):
|
388
|
-
"""
|
389
|
-
Description: Choose the data by the index of the dimension
|
390
|
-
|
391
|
-
Parameters:
|
392
|
-
ncfile: str, the path of the netCDF file
|
393
|
-
dim_name: str, the name of the dimension
|
394
|
-
slice_list: list, the index of the dimension
|
395
|
-
|
396
|
-
slice_list example: slice_list = [[y*12+m for m in range(11,14)] for y in range(84)]
|
397
|
-
or
|
398
|
-
slice_list = [y * 12 + m for y in range(84) for m in range(11, 14)]
|
399
|
-
"""
|
400
|
-
ds = xr.open_dataset(ncfile)
|
401
|
-
slice_list = np.array(slice_list).flatten()
|
402
|
-
slice_list = [int(i) for i in slice_list]
|
403
|
-
ds_new = ds.isel(**{dim_name: slice_list})
|
404
|
-
ds.close()
|
405
|
-
return ds_new
|
406
|
-
|
407
|
-
|
408
|
-
if __name__ == "__main__":
|
409
|
-
data = np.random.rand(100, 50)
|
410
|
-
write2nc(r"test.nc", data, "data", {"time": np.linspace(0, 120, 100), "lev": np.linspace(0, 120, 50)}, "a")
|
oafuncs/oa_s/oa_python.py
DELETED
@@ -1,107 +0,0 @@
|
|
1
|
-
#!/usr/bin/env python
|
2
|
-
# coding=utf-8
|
3
|
-
'''
|
4
|
-
Author: Liu Kun && 16031215@qq.com
|
5
|
-
Date: 2024-10-11 21:02:07
|
6
|
-
LastEditors: Liu Kun && 16031215@qq.com
|
7
|
-
LastEditTime: 2024-11-21 10:59:53
|
8
|
-
FilePath: \\Python\\My_Funcs\\OAFuncs\\oafuncs\\oa_python.py
|
9
|
-
Description:
|
10
|
-
EditPlatform: vscode
|
11
|
-
ComputerInfo: XPS 15 9510
|
12
|
-
SystemInfo: Windows 11
|
13
|
-
Python Version: 3.11
|
14
|
-
'''
|
15
|
-
|
16
|
-
import os
|
17
|
-
|
18
|
-
__all__ = ['install_lib', 'upgrade_lib']
|
19
|
-
|
20
|
-
|
21
|
-
def install_lib(libs=None, python_exe='python'):
|
22
|
-
'''
|
23
|
-
libs: list, 需要安装的库
|
24
|
-
python_exe: str, python版本;如在windows下,将python.exe复制为python312.exe,然后python_exe='python312'
|
25
|
-
'''
|
26
|
-
os.system(python_exe + " -m ensurepip")
|
27
|
-
os.system(python_exe + " -m pip install --upgrade pip")
|
28
|
-
if libs is None:
|
29
|
-
libs = [
|
30
|
-
# "oafuncs", # 自己的库,在这个函数不宜操作,避免报错
|
31
|
-
"requests", # 网页
|
32
|
-
"xlwt", # excel文件
|
33
|
-
"xlrd", # excel文件
|
34
|
-
"openpyxl", # excel文件
|
35
|
-
"netCDF4", # nc文件
|
36
|
-
"numpy", # 数组
|
37
|
-
"pandas", # 数据
|
38
|
-
"xarray", # 数组
|
39
|
-
"scipy", # 科学计算
|
40
|
-
# "scikit-learn", # 机器学习
|
41
|
-
"matplotlib", # 绘图
|
42
|
-
# "seaborn",
|
43
|
-
"imageio", # 图像
|
44
|
-
# "pylustrator", # 绘图
|
45
|
-
"Cartopy", # 绘图 #cartopy已经支持python3.11并且可以直接pip安装
|
46
|
-
"seawater", # 海洋计算
|
47
|
-
"cmaps", # 颜色
|
48
|
-
"colorcet", # 颜色
|
49
|
-
"cmasher", # 颜色
|
50
|
-
"tqdm", # 进度条
|
51
|
-
# "taichi", # 加速
|
52
|
-
"icecream", # 打印调试
|
53
|
-
# "pyperclip", # 系统剪切板
|
54
|
-
"rich", # 精美文本终端
|
55
|
-
# "stratify", # 大气海洋数据垂直插值
|
56
|
-
"dask", # 并行计算
|
57
|
-
"bs4", # 网页
|
58
|
-
"pathlib", # 路径
|
59
|
-
"opencv-contrib-python", # 图像处理
|
60
|
-
# "pydap", # 网络数据xarray下载
|
61
|
-
"gsw", # 海洋计算
|
62
|
-
"global_land_mask", # 陆地海洋掩码
|
63
|
-
# "cfgrib", # grib文件
|
64
|
-
# "ecmwflibs", # grib文件, 两个库都需要安装
|
65
|
-
"geopandas", # 矢量数据,shp文件
|
66
|
-
# "geopy", # 地理位置
|
67
|
-
# "flask", # 网页
|
68
|
-
"cdsapi", # 网络数据下载(era5)
|
69
|
-
# 以下不太重要
|
70
|
-
"lxml", # 网页
|
71
|
-
"keyboard", # 键盘
|
72
|
-
"zhdate", # 中国农历
|
73
|
-
"python-pptx", # ppt
|
74
|
-
"python-docx", # word
|
75
|
-
"ipywidgets", # jupyter显示进度条插件
|
76
|
-
"salem", # 地图投影,可部分替代wrf-python
|
77
|
-
"meteva", # 气象数据处理,中国气象局开发
|
78
|
-
"wget", # 下载
|
79
|
-
"pyautogui", # 鼠标键盘,自动连点脚本需要
|
80
|
-
]
|
81
|
-
try:
|
82
|
-
installed_libs = os.popen(python_exe + ' -m pip list').read()
|
83
|
-
lib_num = len(libs)
|
84
|
-
for i, lib in enumerate(libs):
|
85
|
-
# 判断库是否已经安装,已安装跳过
|
86
|
-
if lib in installed_libs:
|
87
|
-
print(lib, "早已安装")
|
88
|
-
continue
|
89
|
-
else:
|
90
|
-
os.system(python_exe + " -m " + "pip install " + lib)
|
91
|
-
print('-'*100)
|
92
|
-
print("安装成功", lib, "({}/{})".format(i+1, lib_num))
|
93
|
-
print('-'*100)
|
94
|
-
except Exception as e:
|
95
|
-
print("安装失败:", str(e))
|
96
|
-
|
97
|
-
|
98
|
-
def upgrade_lib(libs=None, python_exe='python'):
|
99
|
-
if libs is None:
|
100
|
-
installed_libs = os.popen(python_exe + ' -m pip list').read()
|
101
|
-
libs = installed_libs
|
102
|
-
try:
|
103
|
-
for lib in libs:
|
104
|
-
os.system(python_exe + " -m " + "pip install --upgrade " + lib)
|
105
|
-
print("升级成功")
|
106
|
-
except Exception as e:
|
107
|
-
print("升级失败:", str(e))
|
@@ -1,26 +0,0 @@
|
|
1
|
-
#!/usr/bin/env python
|
2
|
-
# coding=utf-8
|
3
|
-
'''
|
4
|
-
Author: Liu Kun && 16031215@qq.com
|
5
|
-
Date: 2024-09-17 16:09:20
|
6
|
-
LastEditors: Liu Kun && 16031215@qq.com
|
7
|
-
LastEditTime: 2024-10-14 17:08:57
|
8
|
-
FilePath: \\Python\\My_Funcs\\OAFuncs\\OAFuncs\\__init__.py
|
9
|
-
Description:
|
10
|
-
EditPlatform: vscode
|
11
|
-
ComputerInfo: XPS 15 9510
|
12
|
-
SystemInfo: Windows 11
|
13
|
-
Python Version: 3.11
|
14
|
-
'''
|
15
|
-
|
16
|
-
# 会导致OAFuncs直接导入所有函数,不符合模块化设计
|
17
|
-
from .oa_cmap import *
|
18
|
-
from .oa_data import *
|
19
|
-
from .oa_down import *
|
20
|
-
from .oa_draw import *
|
21
|
-
from .oa_file import *
|
22
|
-
from .oa_help import *
|
23
|
-
from .oa_nc import *
|
24
|
-
from .oa_python import *
|
25
|
-
from .oa_sign import *
|
26
|
-
from .oa_tool import *
|