雷达山脊融合图
来源与编码 · 完整源码
1 """Radar-ridgeline fusion reconstructed from a user reference image.
2
3 Each ring has a fixed radial baseline. Local Gaussian ridges at the category
4 spokes encode scalar values on one shared scale. They are not KDE estimates.
5 """
6 from pathlib import Path
7 import argparse
8 import csv
9 import sys
10
11 import numpy as np
12 import matplotlib
13 matplotlib.use('Agg')
14 import matplotlib.pyplot as plt
15 from matplotlib.patches import Patch
16
17 for base in (Path.cwd(), *Path.cwd().parents, *Path(__file__).resolve().parents):
18 found = next((p for p in (base/'_utils', base/'original/resources/assets/shared-scripts')
19 if (p/'vivid_config.py').is_file()), None)
20 if found is not None:
21 sys.path.insert(0, str(found)); break
22 else:
23 raise RuntimeError('Run Vivid bootstrap in the workspace before using this recipe.')
24 from plot_utils import PALETTE, COLORS, setup_style
25
26
27 def read_wide_csv(path):
28 """Read category + 2–4 layer columns from a rectangular wide CSV."""
29 with Path(path).open(encoding='utf-8-sig', newline='') as stream:
30 rows = list(csv.reader(stream))
31 if len(rows) < 2 or len(rows[0]) < 3 or any(len(row) != len(rows[0]) for row in rows):
32 raise ValueError('CSV must be rectangular: category plus 2–4 value columns.')
33 categories = [row[0].strip() for row in rows[1:]]
34 layer_names = [name.strip() for name in rows[0][1:]]
35 if any(not item for item in categories + layer_names):
36 raise ValueError('Category and layer labels must be nonempty.')
37 values = np.array([[float(value) for value in row[1:]] for row in rows[1:]], dtype=float).T
38 return categories, layer_names, values
39
40
41 def validate_data(categories, layer_names, values):
42 values = np.asarray(values, dtype=float)
43 if not 5 <= len(categories) <= 16:
44 raise ValueError('Use 5–16 ordered categories for a readable radial layout.')
45 if not 2 <= len(layer_names) <= 4 or values.shape != (len(layer_names), len(categories)):
46 raise ValueError('Values must match 2–4 layers by all categories.')
47 if (len(set(categories)) != len(categories) or len(set(layer_names)) != len(layer_names)
48 or not np.isfinite(values).all()):
49 raise ValueError('Labels must be unique and all values finite.')
50 return values
51
52
53 def wrapped_delta(theta, center):
54 return np.angle(np.exp(1j * (theta - center)))
55
56
57 def ridge_curve(theta, centers, normalized, baseline, width):
58 """Add smooth local peaks to one circular baseline."""
59 curve = np.full_like(theta, baseline, dtype=float)
60 heights = .18 + .55 * normalized
61 for center, height in zip(centers, heights):
62 curve += height * np.exp(-.5 * (wrapped_delta(theta, center) / width) ** 2)
63 return curve
64
65
66 def label_alignment(theta):
67 horizontal = np.sin(theta)
68 return 'left' if horizontal > .25 else 'right' if horizontal < -.25 else 'center'
69
70
71 def plot_chart(categories, layer_names, values, *, value_suffix='%', value_format='.1f'):
72 """Draw 2–4 concentric ridgeline rings on a radar spoke skeleton.
73
74 All values use one global min/max normalization for comparable peak heights.
75 Preprocess cost-type indicators so every category has the same direction.
76 """
77 values = validate_data(categories, layer_names, values)
78 setup_style()
79 n_categories, n_layers = len(categories), len(layer_names)
80 centers = np.linspace(0, 2*np.pi, n_categories, endpoint=False)
81 theta = np.linspace(0, 2*np.pi, 1800, endpoint=True)
82 span = float(np.ptp(values))
83 normalized = np.full_like(values, .5) if span == 0 else (values-values.min())/span
84 baselines = .82 + 1.20*np.arange(n_layers)
85 width = .23 * (2*np.pi/n_categories)
86 color_order = [1, 3, 0, 4]
87 colors = [PALETTE[color_order[i] % len(PALETTE)] for i in range(n_layers)]
88
89 fig = plt.figure(figsize=(9.0, 7.7), facecolor='white')
90 ax = fig.add_subplot(111, projection='polar')
91 ax.set_theta_zero_location('N'); ax.set_theta_direction(-1); ax.set_facecolor('white')
92 curves = []
93 for row, (name, baseline, color) in enumerate(zip(layer_names, baselines, colors)):
94 curve = ridge_curve(theta, centers, normalized[row], baseline, width)
95 curves.append(curve)
96 ax.fill_between(theta, baseline, curve, color=color, alpha=.72, linewidth=0, zorder=2)
97 ax.plot(theta, curve, color=color, linewidth=1.35, alpha=.95, zorder=3)
98 ax.plot(theta, np.full_like(theta, baseline), color=color, linewidth=.65,
99 alpha=.38, zorder=1)
100
101 outer_label_radius = baselines[-1] + .18 + .55 + .42
102 for angle in centers:
103 ax.plot([angle, angle], [.16, outer_label_radius-.17], color=COLORS['ref_line'],
104 linewidth=.7, linestyle=(0, (3, 4)), alpha=.72, zorder=0)
105
106 for row, curve in enumerate(curves):
107 for column, angle in enumerate(centers):
108 idx = int(round(angle/(2*np.pi)*(len(theta)-1)))
109 ax.text(angle, curve[idx]+.055,
110 f'{values[row, column]:{value_format}}{value_suffix}', fontsize=6.8,
111 ha='center', va='bottom', color='#30343B', zorder=5)
112
113 for angle, category in zip(centers, categories):
114 ax.text(angle, outer_label_radius, category, fontsize=10.2, fontweight='medium',
115 ha=label_alignment(angle), va='center', color=COLORS['text'], zorder=6)
116
117 ax.set_ylim(0, outer_label_radius+.38)
118 ax.set_xticks([]); ax.set_yticks([]); ax.grid(False); ax.spines['polar'].set_visible(False)
119 handles = [Patch(facecolor=color, edgecolor='none', alpha=.78, label=name)
120 for name, color in zip(layer_names, colors)]
121 ax.legend(handles=handles, title='数据层', loc='center left', bbox_to_anchor=(1.03, .52),
122 frameon=False, handlelength=1.25, handleheight=1.25, labelspacing=.65,
123 fontsize=9.2, title_fontsize=10.2)
124 fig.subplots_adjust(left=.04, right=.82, top=.97, bottom=.04)
125 return fig
126
127
128 def main():
129 parser = argparse.ArgumentParser(description=__doc__)
130 parser.add_argument('--data', type=Path, help='Wide CSV: category plus 2–4 comparable layers')
131 parser.add_argument('--output', type=Path, default=Path('figures/fig_radar_ridgeline'))
132 parser.add_argument('--suffix', default='%', help='Visible value suffix; use an empty string for none')
133 parser.add_argument('--format', default='.1f', help='Python numeric format without braces')
134 args = parser.parse_args()
135 if args.data:
136 categories, layer_names, values = read_wide_csv(args.data)
137 else:
138 categories = ['精度','效率','鲁棒','泛化','稳定','响应','能耗','成本','扩展','安全']
139 layer_names = ['测试组','训练组','总体']
140 values = np.array([[32.8,25.4,29.7,18.9,24.6,21.3,16.8,22.5,27.9,19.7],
141 [38.6,31.1,35.8,27.6,33.2,29.5,25.1,28.7,34.6,26.4],
142 [44.7,36.2,42.1,34.5,39.8,37.4,31.6,35.2,41.3,33.8]])
143 fig = plot_chart(categories, layer_names, values,
144 value_suffix=args.suffix, value_format=args.format)
145 args.output.parent.mkdir(parents=True, exist_ok=True)
146 for suffix in ('png', 'pdf'):
147 fig.savefig(args.output.with_suffix('.'+suffix), dpi=320, facecolor='white',
148 bbox_inches='tight', pad_inches=.18)
149 plt.close(fig)
150 print('Saved PNG and PDF:', args.output)
151
152
153 if __name__ == '__main__': main()