oafuncs 0.0.98.29__py3-none-any.whl → 0.0.98.30__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.
@@ -13,6 +13,28 @@ import oafuncs
13
13
  import xarray as xr
14
14
  from rich import print
15
15
 
16
+ def get_data_name(data: xr.DataArray) -> str:
17
+ """Attempt to get a descriptive name for the DataArray."""
18
+ possible_names = [
19
+ "long_name",
20
+ "standard_name",
21
+ "description",
22
+ "title",
23
+ "var_desc",
24
+ # "units", # Usually not a name, but can be a fallback if desperate
25
+ ]
26
+
27
+ name_attr = getattr(data, "name", None) # xarray's own name for the DataArray
28
+
29
+ for attr in possible_names:
30
+ outname = getattr(data, attr, None)
31
+ if outname is not None and isinstance(outname, str) and outname.strip():
32
+ return outname.strip()
33
+
34
+ if name_attr is not None and isinstance(name_attr, str) and name_attr.strip():
35
+ return name_attr.strip()
36
+
37
+ return "Unnamed DataArray"
16
38
 
17
39
  def plot_1d(data: xr.DataArray, output_path: str, x_dim: str, y_dim: str, z_dim: str, t_dim: str) -> None:
18
40
  """Plot 1D data."""
@@ -32,9 +54,8 @@ def plot_1d(data: xr.DataArray, output_path: str, x_dim: str, y_dim: str, z_dim:
32
54
  plt.plot(x, y, linewidth=2)
33
55
 
34
56
  # Add chart info
35
- long_name = getattr(data, "long_name", "No long_name")
36
57
  units = getattr(data, "units", "")
37
- plt.title(f"{data.name} | {long_name}", fontsize=12)
58
+ plt.title(f"{data.name} | {get_data_name(data)}", fontsize=12)
38
59
  plt.xlabel(x_label)
39
60
  plt.ylabel(f"{data.name} ({units})" if units else data.name)
40
61
 
@@ -126,14 +147,14 @@ def plot_2d(data: xr.DataArray, output_path: str, data_range: Optional[Tuple[flo
126
147
  plt.figure(figsize=(10, 8))
127
148
  mappable = ax.imshow(data.values, cmap="viridis", aspect="auto")
128
149
  colorbar = plt.colorbar(mappable, ax=ax, label=getattr(data, "units", ""))
129
- plt.title(f"{data.name} | {getattr(data, 'long_name', 'No long_name')} (basic plot)", fontsize=12)
150
+ plt.title(f"{data.name} | {get_data_name(data)} (basic plot)", fontsize=12)
130
151
  plt.tight_layout()
131
152
  os.makedirs(os.path.dirname(output_path), exist_ok=True)
132
153
  plt.savefig(output_path, bbox_inches="tight", dpi=600)
133
154
  plt.close()
134
155
  return True
135
156
 
136
- plt.title(f"{data.name} | {getattr(data, 'long_name', 'No long_name')}", fontsize=12)
157
+ plt.title(f"{data.name} | {get_data_name(data)}", fontsize=12)
137
158
  units = getattr(data, "units", "")
138
159
  if units and colorbar:
139
160
  colorbar.set_label(units)
oafuncs/oa_cmap.py CHANGED
@@ -13,62 +13,86 @@ def show(
13
13
  ) -> None:
14
14
  """Helper function to plot data with associated colormap.
15
15
 
16
- This function creates a visualization of one or more colormaps by applying them
17
- to randomly generated data in a pcolormesh plot.
16
+ 此函数为每个颜色映射创建一行两个子图:
17
+ 1. 左侧: 使用 pcolormesh 绘制随机数据
18
+ 2. 右侧: 使用 contourf 绘制双高斯山峰数据以展示发散色图
19
+ 颜色条只在右侧的 contourf 图旁边显示。
18
20
 
19
21
  Parameters
20
22
  ----------
21
23
  colormaps : Union[str, mpl.colors.Colormap, List[Union[str, mpl.colors.Colormap]]]
22
- List of colormaps, or a single colormap; can be a string name or a colormap object.
23
-
24
- Returns
25
- -------
26
- None
27
- This function displays the plot but does not return any value.
28
-
29
- Examples
30
- --------
31
- >>> cmap = matplotlib.colors.ListedColormap(["darkorange", "gold", "lawngreen", "lightseagreen"])
32
- >>> show([cmap])
33
- >>> show("viridis")
34
- >>> show(["viridis", "cividis"])
24
+ 单个颜色映射或颜色映射列表;可以是名称字符串或颜色映射对象。
35
25
  """
36
- # Convert single colormap to list for uniform processing
37
26
  if not isinstance(colormaps, list):
38
27
  colormaps = [colormaps]
39
28
 
40
- # Create a formatted list of colormap names for display
41
- cmap_names = []
42
- for cmap in colormaps:
43
- if isinstance(cmap, str):
44
- cmap_names.append(cmap)
45
- elif hasattr(cmap, "name"):
46
- cmap_names.append(cmap.name)
47
- else:
48
- cmap_names.append("unnamed_colormap")
29
+ if not colormaps:
30
+ print("警告: 没有提供颜色映射")
31
+ return
49
32
 
50
- print(f"Visualizing {len(colormaps)} colormap(s): {', '.join(cmap_names)}")
33
+ valid_colormaps = []
34
+ for i, cmap_item in enumerate(colormaps):
35
+ try:
36
+ if isinstance(cmap_item, str):
37
+ cmap_obj = plt.get_cmap(cmap_item)
38
+ else:
39
+ cmap_obj = cmap_item
40
+ if hasattr(cmap_obj, "__call__") or hasattr(cmap_obj, "colors"):
41
+ valid_colormaps.append((cmap_item, cmap_obj))
42
+ else:
43
+ print(f"警告: 跳过无效的颜色映射 #{i + 1}")
44
+ except Exception as e:
45
+ print(f"警告: 无法加载颜色映射 '{cmap_item}': {str(e)}")
46
+
47
+ num_cmaps = len(valid_colormaps)
48
+ if num_cmaps == 0:
49
+ print("错误: 没有有效的颜色映射可供显示")
50
+ return
51
+
52
+ base_height_per_cmap = 5
53
+ figure_width = 12
54
+ figsize = (figure_width, num_cmaps * base_height_per_cmap)
55
+ fig, axs = plt.subplots(num_cmaps, 2, figsize=figsize)
56
+
57
+ if num_cmaps == 1:
58
+ axs = np.array([axs])
51
59
 
52
- # Generate random data with fixed seed for reproducibility
53
60
  np.random.seed(19680801)
54
- data = np.random.randn(30, 30)
61
+ pcolor_data = np.random.randn(30, 30)
62
+
63
+ ngridx = 100
64
+ ngridy = 100
65
+ xi = np.linspace(-2.1, 2.1, ngridx)
66
+ yi = np.linspace(-2.1, 2.1, ngridy)
67
+ Xi, Yi = np.meshgrid(xi, yi)
68
+
69
+ sigma = 0.6
70
+ zi = np.exp(-((Xi - 0.8) ** 2 + (Yi - 0.8) ** 2) / (2 * sigma**2)) - np.exp(-((Xi + 0.8) ** 2 + (Yi + 0.8) ** 2) / (2 * sigma**2))
71
+
72
+ levels = 14
73
+ contour_kw = {"levels": levels, "linewidths": 0.5, "colors": "k"}
74
+ contourf_kw = {"levels": levels}
75
+
76
+ for i, (cmap_item, cmap_obj) in enumerate(valid_colormaps):
77
+ cmap_name = cmap_item if isinstance(cmap_item, str) else getattr(cmap_obj, "name", f"自定义_{i + 1}")
78
+
79
+ ax_left = axs[i, 0]
80
+ ax_left.pcolormesh(pcolor_data, cmap=cmap_obj, rasterized=True, vmin=-4, vmax=4)
81
+ ax_left.set_title(f"Pcolormesh: {cmap_name}")
82
+ ax_left.set_aspect("equal")
55
83
 
56
- # Create subplots based on number of colormaps
57
- n = len(colormaps)
58
- fig, axs = plt.subplots(1, n, figsize=(n * 2 + 2, 3), constrained_layout=True, squeeze=False)
84
+ ax_right = axs[i, 1]
85
+ ax_right.contour(Xi, Yi, zi, **contour_kw)
86
+ cntr = ax_right.contourf(Xi, Yi, zi, cmap=cmap_obj, **contourf_kw)
59
87
 
60
- # Plot each colormap
61
- for ax, cmap in zip(axs.flat, colormaps):
62
- psm = ax.pcolormesh(data, cmap=cmap, rasterized=True, vmin=-4, vmax=4)
63
- fig.colorbar(psm, ax=ax)
88
+ cbar = fig.colorbar(cntr, ax=ax_right)
89
+ cbar.set_label(f"Colormap: {cmap_name}")
64
90
 
65
- # Set title if colormap has a name
66
- if isinstance(cmap, str):
67
- ax.set_title(cmap)
68
- elif hasattr(cmap, "name") and cmap.name:
69
- ax.set_title(cmap.name)
91
+ ax_right.set(xlim=(-2, 2), ylim=(-2, 2))
92
+ ax_right.set_title(f"Contourf: {cmap_name}")
93
+ ax_right.set_aspect("equal")
70
94
 
71
- print("Displaying colormap visualization...")
95
+ plt.tight_layout(pad=0.5, w_pad=0.5, h_pad=1.0)
72
96
  plt.show()
73
97
 
74
98
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: oafuncs
3
- Version: 0.0.98.29
3
+ Version: 0.0.98.30
4
4
  Summary: Oceanic and Atmospheric Functions
5
5
  Home-page: https://github.com/Industry-Pays/OAFuncs
6
6
  Author: Kun Liu
@@ -1,5 +1,5 @@
1
1
  oafuncs/__init__.py,sha256=T_-VtnWWllV3Q91twT5Yt2sUapeA051QbPNnBxmg9nw,1456
2
- oafuncs/oa_cmap.py,sha256=pUFAGzbIg0WLxObBP2t_--ZIg00Dxdojx0y7OjTeqEo,11551
2
+ oafuncs/oa_cmap.py,sha256=cBPVr61SD5HD1SqmE_bFqdO29DGmJ8jgjCrUXI24Ys4,12545
3
3
  oafuncs/oa_data.py,sha256=Wp7Yn6n-WNddAp1UtwK5CSEdGSrzzgOH5gtaOHBaxtw,8065
4
4
  oafuncs/oa_date.py,sha256=WhM6cyD4G3IeghjLTHhAMtlvJbA7kwQG2sHnxdTgyso,6303
5
5
  oafuncs/oa_draw.py,sha256=IaBGDx-EOxyMM2IuJ4zLZt6ruHHV5qFStPItmUOXoWk,17635
@@ -18,7 +18,7 @@ oafuncs/_script/netcdf_modify.py,sha256=sGRUYNhfGgf9JV70rnBzw3bzuTRSXzBTL_RMDnDP
18
18
  oafuncs/_script/netcdf_write.py,sha256=GvyUyUhzMonzSp3y4pT8ZAfbQrsh5J3dLnmINYJKhuE,21422
19
19
  oafuncs/_script/parallel.py,sha256=07-BJVHxXJNlrOrhrSGt7qCZiKWq6dBvNDBA1AANYnI,8861
20
20
  oafuncs/_script/parallel_test.py,sha256=0GBqZOX7IaCOKF2t1y8N8YYu53GJ33OkfsWgpvZNqM4,372
21
- oafuncs/_script/plot_dataset.py,sha256=Hr4X0BHJ1qmf2YHT40Vu3nF8JS_4MlZ2MK6yeJCSHOg,15642
21
+ oafuncs/_script/plot_dataset.py,sha256=4jhUZNIc2DLHnk5GH0rotzhOq0cAMmB7rhMJKorYObo,16329
22
22
  oafuncs/_script/replace_file_content.py,sha256=eCFZjnZcwyRvy6b4mmIfBna-kylSZTyJRfgXd6DdCjk,5982
23
23
  oafuncs/oa_down/User_Agent-list.txt,sha256=pHaMlElMvZ8TG4vf4BqkZYKqe0JIGkr4kCN0lM1Y9FQ,514295
24
24
  oafuncs/oa_down/__init__.py,sha256=kRX5eTUCbAiz3zTaQM1501paOYS_3fizDN4Pa0mtNUA,585
@@ -38,8 +38,8 @@ oafuncs/oa_sign/__init__.py,sha256=QKqTFrJDFK40C5uvk48GlRRbGFzO40rgkYwu6dYxatM,5
38
38
  oafuncs/oa_sign/meteorological.py,sha256=8091SHo2L8kl4dCFmmSH5NGVHDku5i5lSiLEG5DLnOQ,6489
39
39
  oafuncs/oa_sign/ocean.py,sha256=xrW-rWD7xBWsB5PuCyEwQ1Q_RDKq2KCLz-LOONHgldU,5932
40
40
  oafuncs/oa_sign/scientific.py,sha256=a4JxOBgm9vzNZKpJ_GQIQf7cokkraV5nh23HGbmTYKw,5064
41
- oafuncs-0.0.98.29.dist-info/licenses/LICENSE.txt,sha256=rMtLpVg8sKiSlwClfR9w_Dd_5WubTQgoOzE2PDFxzs4,1074
42
- oafuncs-0.0.98.29.dist-info/METADATA,sha256=V1EJ9J4TUr06OWk13eB8mqLDKwAbCYudtBx4U7HrlIE,4326
43
- oafuncs-0.0.98.29.dist-info/WHEEL,sha256=Nw36Djuh_5VDukK0H78QzOX-_FQEo6V37m3nkm96gtU,91
44
- oafuncs-0.0.98.29.dist-info/top_level.txt,sha256=bgC35QkXbN4EmPHEveg_xGIZ5i9NNPYWqtJqaKqTPsQ,8
45
- oafuncs-0.0.98.29.dist-info/RECORD,,
41
+ oafuncs-0.0.98.30.dist-info/licenses/LICENSE.txt,sha256=rMtLpVg8sKiSlwClfR9w_Dd_5WubTQgoOzE2PDFxzs4,1074
42
+ oafuncs-0.0.98.30.dist-info/METADATA,sha256=NRBInCPeawjfSNZhTLkAaM_xK4sce_dFOllXpbdRFdQ,4326
43
+ oafuncs-0.0.98.30.dist-info/WHEEL,sha256=Nw36Djuh_5VDukK0H78QzOX-_FQEo6V37m3nkm96gtU,91
44
+ oafuncs-0.0.98.30.dist-info/top_level.txt,sha256=bgC35QkXbN4EmPHEveg_xGIZ5i9NNPYWqtJqaKqTPsQ,8
45
+ oafuncs-0.0.98.30.dist-info/RECORD,,