oafuncs 0.0.98.2__tar.gz → 0.0.98.3__tar.gz

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.
Files changed (50) hide show
  1. {oafuncs-0.0.98.2/oafuncs.egg-info → oafuncs-0.0.98.3}/PKG-INFO +1 -1
  2. oafuncs-0.0.98.3/oafuncs/_script/netcdf_write.py +203 -0
  3. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3/oafuncs.egg-info}/PKG-INFO +1 -1
  4. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/setup.py +1 -1
  5. oafuncs-0.0.98.2/oafuncs/_script/netcdf_write.py +0 -116
  6. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/LICENSE.txt +0 -0
  7. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/MANIFEST.in +0 -0
  8. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/README.md +0 -0
  9. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/__init__.py +0 -0
  10. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/_data/hycom.png +0 -0
  11. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/_data/oafuncs.png +0 -0
  12. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/_script/cprogressbar.py +0 -0
  13. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/_script/email.py +0 -0
  14. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/_script/netcdf_merge.py +0 -0
  15. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/_script/netcdf_modify.py +0 -0
  16. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/_script/parallel.py +0 -0
  17. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/_script/parallel_example_usage.py +0 -0
  18. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/_script/plot_dataset.py +0 -0
  19. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/_script/replace_file_content.py +0 -0
  20. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_cmap.py +0 -0
  21. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_data.py +0 -0
  22. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_date.py +0 -0
  23. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_down/User_Agent-list.txt +0 -0
  24. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_down/__init__.py +0 -0
  25. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_down/hycom_3hourly.py +0 -0
  26. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_down/hycom_3hourly_20250407.py +0 -0
  27. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_down/idm.py +0 -0
  28. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_down/literature.py +0 -0
  29. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_down/test_ua.py +0 -0
  30. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_down/user_agent.py +0 -0
  31. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_draw.py +0 -0
  32. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_file.py +0 -0
  33. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_help.py +0 -0
  34. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_model/__init__.py +0 -0
  35. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_model/roms/__init__.py +0 -0
  36. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_model/roms/test.py +0 -0
  37. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_model/wrf/__init__.py +0 -0
  38. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_model/wrf/little_r.py +0 -0
  39. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_nc.py +0 -0
  40. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_python.py +0 -0
  41. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_sign/__init__.py +0 -0
  42. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_sign/meteorological.py +0 -0
  43. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_sign/ocean.py +0 -0
  44. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_sign/scientific.py +0 -0
  45. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs/oa_tool.py +0 -0
  46. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs.egg-info/SOURCES.txt +0 -0
  47. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs.egg-info/dependency_links.txt +0 -0
  48. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs.egg-info/requires.txt +0 -0
  49. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/oafuncs.egg-info/top_level.txt +0 -0
  50. {oafuncs-0.0.98.2 → oafuncs-0.0.98.3}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: oafuncs
3
- Version: 0.0.98.2
3
+ Version: 0.0.98.3
4
4
  Summary: Oceanic and Atmospheric Functions
5
5
  Home-page: https://github.com/Industry-Pays/OAFuncs
6
6
  Author: Kun Liu
@@ -0,0 +1,203 @@
1
+ import os
2
+
3
+ import netCDF4 as nc
4
+ import numpy as np
5
+ import xarray as xr
6
+ import warnings
7
+
8
+ warnings.filterwarnings("ignore", category=RuntimeWarning)
9
+
10
+
11
+ def _numpy_to_nc_type(numpy_type):
12
+ """将 NumPy 数据类型映射到 NetCDF 数据类型"""
13
+ numpy_to_nc = {
14
+ "float32": "f4",
15
+ "float64": "f8",
16
+ "int8": "i1",
17
+ "int16": "i2",
18
+ "int32": "i4",
19
+ "int64": "i8",
20
+ "uint8": "u1",
21
+ "uint16": "u2",
22
+ "uint32": "u4",
23
+ "uint64": "u8",
24
+ }
25
+ numpy_type_str = str(numpy_type) if not isinstance(numpy_type, str) else numpy_type
26
+ return numpy_to_nc.get(numpy_type_str, "f4")
27
+
28
+
29
+ def _calculate_scale_and_offset(data, n=16):
30
+ """
31
+ 计算数值型数据的 scale_factor 与 add_offset,
32
+ 将数据映射到 [0, 2**n - 1] 的范围。
33
+
34
+ 要求 data 为数值型的 NumPy 数组,不允许全 NaN 值。
35
+ """
36
+ if not isinstance(data, np.ndarray):
37
+ raise ValueError("Input data must be a NumPy array.")
38
+
39
+ data_min = np.nanmin(data)
40
+ data_max = np.nanmax(data)
41
+
42
+ if np.isnan(data_min) or np.isnan(data_max):
43
+ raise ValueError("Input data contains NaN values.")
44
+
45
+ if data_max == data_min:
46
+ scale_factor = 1.0
47
+ add_offset = data_min
48
+ else:
49
+ scale_factor = (data_max - data_min) / (2**n - 1)
50
+ add_offset = data_min + 2 ** (n - 1) * scale_factor
51
+ return scale_factor, add_offset
52
+
53
+
54
+ def _data_to_scale_offset(data, scale, offset):
55
+ """
56
+ 将数据转换为 scale_factor 和 add_offset 的形式。
57
+ 此处同时替换 NaN、正无穷和负无穷为填充值 -32767,
58
+ 以确保转换后的数据可安全转为 int16。
59
+ """
60
+ if not isinstance(data, np.ndarray):
61
+ raise ValueError("Input data must be a NumPy array.")
62
+
63
+ # 先计算转换后的数据
64
+ result = np.around((data - offset) / scale)
65
+ # 替换 NaN, 正负无穷(posinf, neginf)为 -32767
66
+ result = np.nan_to_num(result, nan=-32767, posinf=-32767, neginf=-32767)
67
+ result = np.clip(result, -32767, 32767) # 限制范围在 int16 的有效范围内
68
+ result = np.where(np.isfinite(result), result, -32767) # 替换无效值为 -32767
69
+ new_data = result.astype(np.int16)
70
+ return new_data
71
+
72
+
73
+ def save_to_nc(file, data, varname=None, coords=None, mode="w", scale_offset_switch=True, compile_switch=True):
74
+ """
75
+ 保存数据到 NetCDF 文件,支持 xarray 对象(DataArray 或 Dataset)和 numpy 数组。
76
+
77
+ 仅对数据变量中数值型数据进行压缩转换(利用 scale_factor/add_offset 转换后转为 int16),
78
+ 非数值型数据以及所有坐标变量将禁用任何压缩,直接保存原始数据。
79
+
80
+ 参数:
81
+ - file: 保存文件的路径
82
+ - data: xarray.DataArray、xarray.Dataset 或 numpy 数组
83
+ - varname: 变量名(仅适用于传入 numpy 数组或 DataArray 时)
84
+ - coords: 坐标字典(numpy 数组分支时使用),所有坐标变量均不压缩
85
+ - mode: "w"(覆盖)或 "a"(追加)
86
+ - scale_offset_switch: 是否对数值型数据变量进行压缩转换
87
+ - compile_switch: 是否启用 NetCDF4 的 zlib 压缩(仅针对数值型数据有效)
88
+ """
89
+ # 处理 xarray 对象(DataArray 或 Dataset)的情况
90
+ if isinstance(data, (xr.DataArray, xr.Dataset)):
91
+ encoding = {} # 用于保存数据变量的编码信息
92
+
93
+ if isinstance(data, xr.DataArray):
94
+ if data.name is None:
95
+ data = data.rename("data")
96
+ varname = data.name if varname is None else varname
97
+ # 判断数据是否为数值型
98
+ if np.issubdtype(data.values.dtype, np.number) and scale_offset_switch:
99
+ scale, offset = _calculate_scale_and_offset(data.values)
100
+ new_values = _data_to_scale_offset(data.values, scale, offset)
101
+ # 生成新 DataArray,保留原坐标和属性,同时写入转换参数到属性中
102
+ new_da = data.copy(data=new_values)
103
+ new_da.attrs["scale_factor"] = float(scale)
104
+ new_da.attrs["add_offset"] = float(offset)
105
+ encoding[varname] = {
106
+ "zlib": compile_switch,
107
+ "complevel": 4,
108
+ "dtype": "int16",
109
+ "_FillValue": -32767,
110
+ }
111
+ new_da.to_dataset(name=varname).to_netcdf(file, mode=mode, encoding=encoding)
112
+ else:
113
+ data.to_dataset(name=varname).to_netcdf(file, mode=mode)
114
+ return
115
+
116
+ else:
117
+ # 处理 Dataset 的情况,仅处理 data_vars 数据变量,坐标变量保持原样
118
+ new_vars = {}
119
+ encoding = {}
120
+ for var in data.data_vars:
121
+ da = data[var]
122
+ if np.issubdtype(np.asarray(da.values).dtype, np.number) and scale_offset_switch:
123
+ scale, offset = _calculate_scale_and_offset(da.values)
124
+ new_values = _data_to_scale_offset(da.values, scale, offset)
125
+ new_da = xr.DataArray(new_values, dims=da.dims, coords=da.coords, attrs=da.attrs)
126
+ new_da.attrs["scale_factor"] = float(scale)
127
+ new_da.attrs["add_offset"] = float(offset)
128
+ new_vars[var] = new_da
129
+ encoding[var] = {
130
+ "zlib": compile_switch,
131
+ "complevel": 4,
132
+ "dtype": "int16",
133
+ "_FillValue": -32767,
134
+ }
135
+ else:
136
+ new_vars[var] = da
137
+ new_ds = xr.Dataset(new_vars, coords=data.coords)
138
+ if encoding:
139
+ new_ds.to_netcdf(file, mode=mode, encoding=encoding)
140
+ else:
141
+ new_ds.to_netcdf(file, mode=mode)
142
+ return
143
+
144
+ # 处理纯 numpy 数组情况
145
+ if mode == "w" and os.path.exists(file):
146
+ os.remove(file)
147
+ elif mode == "a" and not os.path.exists(file):
148
+ mode = "w"
149
+ data = np.asarray(data)
150
+ is_numeric = np.issubdtype(data.dtype, np.number)
151
+ try:
152
+ with nc.Dataset(file, mode, format="NETCDF4") as ncfile:
153
+ # 坐标变量直接写入,不做压缩
154
+ if coords is not None:
155
+ for dim, values in coords.items():
156
+ if dim not in ncfile.dimensions:
157
+ ncfile.createDimension(dim, len(values))
158
+ var_obj = ncfile.createVariable(dim, _numpy_to_nc_type(np.asarray(values).dtype), (dim,))
159
+ var_obj[:] = values
160
+
161
+ dims = list(coords.keys()) if coords else []
162
+ if is_numeric and scale_offset_switch:
163
+ scale, offset = _calculate_scale_and_offset(data)
164
+ new_data = _data_to_scale_offset(data, scale, offset)
165
+ var = ncfile.createVariable(varname, "i2", dims, fill_value=-32767, zlib=compile_switch)
166
+ var.scale_factor = scale
167
+ var.add_offset = offset
168
+ # Ensure no invalid values in new_data before assignment
169
+ var[:] = new_data
170
+ else:
171
+ # 非数值型数据,禁止压缩
172
+ dtype = _numpy_to_nc_type(data.dtype)
173
+ var = ncfile.createVariable(varname, dtype, dims, zlib=False)
174
+ var[:] = data
175
+ except Exception as e:
176
+ raise RuntimeError(f"netCDF4 保存失败: {str(e)}") from e
177
+
178
+
179
+ # 测试用例
180
+ if __name__ == "__main__":
181
+ # --------------------------------
182
+ # dataset
183
+ file = r"F:\roms_rst.nc"
184
+ ds = xr.open_dataset(file)
185
+ outfile = r"F:\roms_rst_test.nc"
186
+ save_to_nc(outfile, ds)
187
+ ds.close()
188
+ # --------------------------------
189
+ # dataarray
190
+ data = np.random.rand(4, 3, 2)
191
+ coords = {"x": np.arange(4), "y": np.arange(3), "z": np.arange(2)}
192
+ varname = "test_var"
193
+ data = xr.DataArray(data, dims=("x", "y", "z"), coords=coords, name=varname)
194
+ outfile = r"F:\test_dataarray.nc"
195
+ save_to_nc(outfile, data)
196
+ # --------------------------------
197
+ # numpy array
198
+ data = np.random.rand(4, 3, 2)
199
+ coords = {"x": np.arange(4), "y": np.arange(3), "z": np.arange(2)}
200
+ varname = "test_var"
201
+ outfile = r"F:\test_numpy.nc"
202
+ save_to_nc(outfile, data, varname=varname, coords=coords)
203
+ # --------------------------------
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: oafuncs
3
- Version: 0.0.98.2
3
+ Version: 0.0.98.3
4
4
  Summary: Oceanic and Atmospheric Functions
5
5
  Home-page: https://github.com/Industry-Pays/OAFuncs
6
6
  Author: Kun Liu
@@ -18,7 +18,7 @@ URL = "https://github.com/Industry-Pays/OAFuncs"
18
18
  EMAIL = "liukun0312@stu.ouc.edu.cn"
19
19
  AUTHOR = "Kun Liu"
20
20
  REQUIRES_PYTHON = ">=3.9.0" # 2025/03/13
21
- VERSION = "0.0.98.2"
21
+ VERSION = "0.0.98.3"
22
22
 
23
23
  # What packages are required for this module to be executed?
24
24
  REQUIRED = [
@@ -1,116 +0,0 @@
1
- import os
2
- import netCDF4 as nc
3
- import numpy as np
4
- import xarray as xr
5
-
6
-
7
- def _numpy_to_nc_type(numpy_type):
8
- """将NumPy数据类型映射到NetCDF数据类型"""
9
- numpy_to_nc = {
10
- "float32": "f4",
11
- "float64": "f8",
12
- "int8": "i1",
13
- "int16": "i2",
14
- "int32": "i4",
15
- "int64": "i8",
16
- "uint8": "u1",
17
- "uint16": "u2",
18
- "uint32": "u4",
19
- "uint64": "u8",
20
- }
21
- numpy_type_str = str(numpy_type) if not isinstance(numpy_type, str) else numpy_type
22
- return numpy_to_nc.get(numpy_type_str, "f4")
23
-
24
-
25
- def _calculate_scale_and_offset(data, n=16):
26
- if not isinstance(data, np.ndarray):
27
- raise ValueError("Input data must be a NumPy array.")
28
-
29
- data_min = np.nanmin(data)
30
- data_max = np.nanmax(data)
31
-
32
- if np.isnan(data_min) or np.isnan(data_max):
33
- raise ValueError("Input data contains NaN values.")
34
-
35
- scale_factor = (data_max - data_min) / (2**n - 1)
36
- add_offset = data_min + 2 ** (n - 1) * scale_factor
37
- return scale_factor, add_offset
38
-
39
-
40
- def save_to_nc(file, data, varname=None, coords=None, mode="w", scale_offset_switch=True, compile_switch=True):
41
- # 处理xarray对象的情况(当varname和coords都为None时)
42
- if varname is None and coords is None:
43
- if not isinstance(data, (xr.DataArray, xr.Dataset)):
44
- raise ValueError("When varname and coords are not provided, data must be an xarray object")
45
-
46
- encoding = {}
47
- if isinstance(data, xr.DataArray):
48
- if data.name is None:
49
- data = data.rename("data")
50
- varname = data.name
51
- encoding[varname] = {"zlib": compile_switch, "complevel": 4}
52
- if scale_offset_switch:
53
- scale, offset = _calculate_scale_and_offset(data.values)
54
- encoding[varname].update({"dtype": "int16", "scale_factor": scale, "add_offset": offset, "_FillValue": -32767})
55
- else:
56
- encoding[varname].update({"dtype": "float32", "_FillValue": np.nan})
57
- else: # Dataset情况
58
- for var in data.data_vars:
59
- encoding[var] = {"zlib": compile_switch, "complevel": 4}
60
- if scale_offset_switch:
61
- scale, offset = _calculate_scale_and_offset(data[var].values)
62
- encoding[var].update({"dtype": "int16", "scale_factor": scale, "add_offset": offset, "_FillValue": -32767})
63
- else:
64
- encoding[var].update({"dtype": "float32", "_FillValue": np.nan})
65
-
66
- try:
67
- data.to_netcdf(file, mode=mode, encoding=encoding)
68
- return
69
- except Exception as e:
70
- raise RuntimeError(f"Failed to save xarray object: {str(e)}") from e
71
-
72
- # 处理普通numpy数组的情况
73
- if mode == "w" and os.path.exists(file):
74
- os.remove(file)
75
- elif mode == "a" and not os.path.exists(file):
76
- mode = "w"
77
-
78
- try:
79
- with nc.Dataset(file, mode, format="NETCDF4") as ncfile:
80
- # 创建维度并写入坐标
81
- if coords is not None:
82
- for dim, values in coords.items():
83
- if dim not in ncfile.dimensions:
84
- ncfile.createDimension(dim, len(values))
85
- var = ncfile.createVariable(dim, _numpy_to_nc_type(values.dtype), (dim,))
86
- var[:] = values
87
-
88
- # 创建变量
89
- dims = list(coords.keys()) if coords else []
90
- if scale_offset_switch:
91
- scale, offset = _calculate_scale_and_offset(data)
92
- var = ncfile.createVariable(varname, "i2", dims, fill_value=-32767, zlib=compile_switch)
93
- var.scale_factor = scale
94
- var.add_offset = offset
95
- else:
96
- dtype = _numpy_to_nc_type(data.dtype)
97
- var = ncfile.createVariable(varname, dtype, dims, zlib=compile_switch)
98
-
99
- var[:] = data
100
- except Exception as e:
101
- raise RuntimeError(f"Failed to save netCDF4 file: {str(e)}") from e
102
-
103
-
104
- if __name__ == "__main__":
105
- # Example usage
106
- data = xr.open_dataset(r"F:\roms_rst.nc")["u"]
107
- save_to_nc(r"F:\test.nc", data)
108
-
109
- # xarray测试
110
- data = xr.DataArray(np.random.rand(10, 20), dims=("x", "y"), name="temperature")
111
- save_to_nc(r"F:\test_xarray.nc", data)
112
-
113
- # numpy测试
114
- arr = np.random.rand(5, 3)
115
- coords = {"x": np.arange(5), "y": np.arange(3)}
116
- save_to_nc(r"F:\test_numpy.nc", arr, varname="data", coords=coords)
File without changes
File without changes
File without changes
File without changes
File without changes