Coverage for graphica/gui/export_settings.py: 84.0%

239 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-25 19:22 +0000

1"""書き出しの経路で共有するもの。matplotlib の rcParams は、書き出しの経路すべてがこれを使うこと。""" 

2from contextlib import ExitStack, contextmanager 

3 

4import numpy as np 

5from matplotlib.cbook import STEP_LOOKUP_MAP 

6from matplotlib.collections import LineCollection, PathCollection, PolyCollection 

7from matplotlib.lines import Line2D 

8from matplotlib.patches import Polygon, Rectangle 

9from matplotlib.path import Path 

10from matplotlib.transforms import Bbox 

11 

12# 枠を切り落とすのはベクター形式だけ(ラスタは枠の外を描かないので同じ) 

13CROPPABLE_FORMATS = ('svg', 'pdf', 'eps', 'ps') 

14 

15 

16def export_rc_params(fmt, svg_text_as_path=False): 

17 """mpl.rc_context() に渡す辞書。 

18 

19 SVG は文字をテキストのまま残すか、パスにするか。PDF はフォントを TrueType(Type 42)で埋め込む 

20 (既定の Type 3 だとベクター編集ソフトで文字を編集できない)。ラスタは何もしない。 

21 fmt の先頭のドットと大文字小文字は無視する。 

22 """ 

23 fmt = (fmt or '').lower().lstrip('.') 

24 if fmt == 'svg': 

25 return {'svg.fonttype': 'path' if svg_text_as_path else 'none'} 

26 if fmt in ('pdf', 'ps', 'eps'): 

27 return {'pdf.fonttype': 42, 'ps.fonttype': 42} 

28 return {} 

29 

30 

31def is_croppable_format(fmt): 

32 return (fmt or '').lower().lstrip('.') in CROPPABLE_FORMATS 

33 

34 

35@contextmanager 

36def outside_frame_cropped(figure, enabled=True): 

37 """プロット枠の外にはみ出す部分を削って書き出す(抜けたら元に戻す。画面の図にも使う)。 

38 

39 ベクター形式は枠の外もデータを持ち、クリッピングマスクで隠している。PowerPoint の「図形に変換」などは 

40 マスクを捨てるので、枠の外の線や点が出てしまう。線は枠の縁で切り、点は枠の外のものを除き、塗りと棒は 

41 枠の形に切り取って、マスクも使わない。削り方が決められないもの(2D マップなど)はマスクのまま残す。 

42 """ 

43 if not enabled: 

44 yield 

45 return 

46 figure.draw_without_rendering() 

47 with ExitStack() as restore: 

48 for ax in list(_all_axes(figure)): 

49 _freeze_limits(ax, restore) 

50 box = ax.bbox 

51 for artist in list(ax.get_children()): 

52 if not artist.get_clip_on() or not _clipped_by_frame(artist, ax): 52 ↛ 53line 52 didn't jump to line 53 because the condition on line 52 was never true

53 continue 

54 cropper = _cropper_for(artist) 

55 if cropper is None: 

56 continue 

57 cropper(artist, ax, box, restore) 

58 artist.set_clip_on(False) 

59 restore.callback(artist.set_clip_on, True) 

60 yield 

61 

62 

63def _all_axes(figure): 

64 """図の軸と、その中の拡大図(child_axes)。""" 

65 stack = list(figure.axes) 

66 while stack: 

67 ax = stack.pop() 

68 yield ax 

69 stack.extend(getattr(ax, 'child_axes', [])) 

70 

71 

72def _clipped_by_frame(artist, ax): 

73 """枠(軸の背景)で切り抜かれているか。別の形で切り抜いているもの(グラデーションの塗りなど)は触らない。""" 

74 clip_path = artist.get_clip_path() 

75 return clip_path is None or getattr(clip_path, '_patch', None) is ax.patch 

76 

77 

78def _freeze_limits(ax, restore): 

79 """データを削ると自動の範囲が変わるので、今の範囲で止めておく。""" 

80 x_auto, y_auto = ax.get_autoscalex_on(), ax.get_autoscaley_on() 

81 ax.set_xlim(ax.get_xlim()) 

82 ax.set_ylim(ax.get_ylim()) 

83 restore.callback(ax.set_autoscaley_on, y_auto) 

84 restore.callback(ax.set_autoscalex_on, x_auto) 

85 

86 

87def _box(box): 

88 return Bbox([[box.x0, box.y0], [box.x1, box.y1]]) 

89 

90 

91def _inside(points, box): 

92 return ((points[:, 0] >= box.x0) & (points[:, 0] <= box.x1) 

93 & (points[:, 1] >= box.y0) & (points[:, 1] <= box.y1)) 

94 

95 

96def _clip_segment(start, end, box): 

97 """線分を枠で切る(Liang–Barsky)。枠の中に何も残らなければ None。""" 

98 x0, y0 = start 

99 dx, dy = end[0] - x0, end[1] - y0 

100 t0, t1 = 0.0, 1.0 

101 for p, q in ((-dx, x0 - box.x0), (dx, box.x1 - x0), (-dy, y0 - box.y0), (dy, box.y1 - y0)): 

102 if p == 0: 

103 if q < 0: 103 ↛ 104line 103 didn't jump to line 104 because the condition on line 103 was never true

104 return None 

105 continue 

106 r = q / p 

107 if p < 0: 

108 t0 = max(t0, r) 

109 else: 

110 t1 = min(t1, r) 

111 if t0 > t1: 

112 return None 

113 return (np.array([x0 + t0 * dx, y0 + t0 * dy]), np.array([x0 + t1 * dx, y0 + t1 * dy])) 

114 

115 

116def _clip_polyline(points, box): 

117 """折れ線を枠で切った区間のリスト(画面の座標)。縁との交点まで残す。""" 

118 pieces, current = [], [] 

119 

120 def close(): 

121 if len(current) > 1: 

122 pieces.append(list(current)) 

123 current.clear() 

124 

125 for start, end in zip(points[:-1], points[1:]): 

126 clipped = None 

127 if np.isfinite(start).all() and np.isfinite(end).all(): 127 ↛ 129line 127 didn't jump to line 129 because the condition on line 127 was always true

128 clipped = _clip_segment(start, end, box) 

129 if clipped is None: 

130 close() 

131 continue 

132 a, b = clipped 

133 if not (current and np.allclose(current[-1], a)): 

134 close() 

135 current.append(a) 

136 current.append(b) 

137 if not np.allclose(b, end): 

138 close() 

139 close() 

140 return pieces 

141 

142 

143def _pieces_to_xy(pieces, inverse): 

144 """区間を NaN で区切った1本のデータ(元の座標)に戻す。""" 

145 rows = [] 

146 for piece in pieces: 

147 if rows: 

148 rows.append([np.nan, np.nan]) 

149 rows.extend(piece) 

150 if not rows: 150 ↛ 151line 150 didn't jump to line 151 because the condition on line 150 was never true

151 return np.empty(0), np.empty(0) 

152 data = np.array(rows, dtype=float) 

153 finite = np.isfinite(data).all(axis=1) 

154 data[finite] = inverse.transform(data[finite]) 

155 return data[:, 0], data[:, 1] 

156 

157 

158def _visible_style(value): 

159 return value not in ('None', 'none', '', ' ', None) 

160 

161 

162def _crop_line(line, ax, box, restore): 

163 restore.callback(line.set_data, line.get_xdata(orig=True), line.get_ydata(orig=True)) 

164 restore.callback(line.set_drawstyle, line.get_drawstyle()) 

165 transform = line.get_transform() 

166 xy = np.asarray(line.get_xydata(), dtype=float).reshape(-1, 2) 

167 has_line = _visible_style(line.get_linestyle()) 

168 marker = line.get_marker() 

169 inside_points = xy[_inside(transform.transform(xy), box)] 

170 if not has_line: 170 ↛ 171line 170 didn't jump to line 171 because the condition on line 170 was never true

171 line.set_data(inside_points[:, 0], inside_points[:, 1]) 

172 return 

173 drawn = xy 

174 drawstyle = line.get_drawstyle() 

175 if drawstyle != 'default' and drawstyle in STEP_LOOKUP_MAP: 175 ↛ 176line 175 didn't jump to line 176 because the condition on line 175 was never true

176 drawn = np.asarray(STEP_LOOKUP_MAP[drawstyle](xy[:, 0], xy[:, 1]), dtype=float).T 

177 line.set_drawstyle('default') 

178 line.set_data(*_pieces_to_xy(_clip_polyline(transform.transform(drawn), box), transform.inverted())) 

179 if _visible_style(marker): 

180 # 線を縁で切ると交点が増えるので、点は枠の中のものだけを別の線で描く 

181 restore.callback(line.set_marker, marker) 

182 markers = Line2D(inside_points[:, 0], inside_points[:, 1]) 

183 markers.update_from(line) 

184 line.set_marker('None') 

185 markers.set_linestyle('None') 

186 markers.set_marker(marker) 

187 markers.set_transform(transform) 

188 markers.set_clip_on(False) 

189 ax.add_line(markers) 

190 restore.callback(markers.remove) 

191 

192 

193def _crop_scatter(collection, ax, box, restore): 

194 offsets = np.asarray(collection.get_offsets(), dtype=float).reshape(-1, 2) 

195 count = len(offsets) 

196 if not count: 196 ↛ 197line 196 didn't jump to line 197 because the condition on line 196 was never true

197 return 

198 keep = _inside(collection.get_offset_transform().transform(offsets), box) 

199 if keep.all(): 199 ↛ 200line 199 didn't jump to line 200 because the condition on line 199 was never true

200 return 

201 restore.callback(collection.set_offsets, offsets) 

202 collection.set_offsets(offsets[keep]) 

203 array = collection.get_array() 

204 if array is not None and np.size(array) == count: 204 ↛ 205line 204 didn't jump to line 205 because the condition on line 204 was never true

205 restore.callback(collection.set_array, array) 

206 collection.set_array(np.asarray(array)[keep]) 

207 else: 

208 for getter, setter in ((collection.get_facecolor, collection.set_facecolor), 

209 (collection.get_edgecolor, collection.set_edgecolor)): 

210 colors = getter() 

211 if len(colors) == count: 211 ↛ 212line 211 didn't jump to line 212 because the condition on line 211 was never true

212 restore.callback(setter, colors) 

213 setter(colors[keep]) 

214 sizes = collection.get_sizes() 

215 if len(sizes) == count: 215 ↛ 216line 215 didn't jump to line 216 because the condition on line 215 was never true

216 restore.callback(collection.set_sizes, sizes) 

217 collection.set_sizes(sizes[keep]) 

218 

219 

220def _crop_polygons(collection, ax, box, restore): 

221 transform = collection.get_transform() 

222 inverse = transform.inverted() 

223 paths = list(collection.get_paths()) 

224 cropped = [] 

225 for path in paths: 

226 clipped = transform.transform_path(path).clip_to_bbox(_box(box)) 

227 # 消えた多角形も空のまま残す(色の並びと数を合わせる) 

228 cropped.append(inverse.transform_path(clipped) if len(clipped.vertices) else Path(np.empty((0, 2)))) 

229 # PolyCollection は Path ではなく頂点と命令の並びで受け取る 

230 restore.callback(_set_polygon_paths, collection, paths) 

231 _set_polygon_paths(collection, cropped) 

232 

233 

234def _set_polygon_paths(collection, paths): 

235 verts = [path.vertices for path in paths] 

236 codes = [path.codes if path.codes is not None else _polyline_codes(len(path.vertices)) for path in paths] 

237 collection.set_verts_and_codes(verts, codes) 

238 

239 

240def _polyline_codes(count): 

241 codes = np.full(count, Path.LINETO, dtype=Path.code_type) 

242 if count: 

243 codes[0] = Path.MOVETO 

244 return codes 

245 

246 

247def _crop_segments(collection, ax, box, restore): 

248 transform = collection.get_transform() 

249 inverse = transform.inverted() 

250 segments = collection.get_segments() 

251 count = len(segments) 

252 new_segments, source = [], [] 

253 for index, segment in enumerate(segments): 

254 for piece in _clip_polyline(transform.transform(np.asarray(segment, dtype=float).reshape(-1, 2)), box): 

255 new_segments.append(inverse.transform(np.array(piece))) 

256 source.append(index) 

257 source = np.array(source, dtype=int) 

258 array = collection.get_array() 

259 colors = collection.get_color() 

260 widths = collection.get_linewidth() 

261 restore.callback(collection.set_segments, segments) 

262 collection.set_segments(new_segments) 

263 # 区間ごとの色(グラデーションの線など)は、切って増えた区間にも元の区間の色を付ける 

264 if array is not None and np.size(array) == count: 264 ↛ 265line 264 didn't jump to line 265 because the condition on line 264 was never true

265 restore.callback(collection.set_array, array) 

266 collection.set_array(np.asarray(array)[source]) 

267 elif len(colors) == count: 267 ↛ 270line 267 didn't jump to line 270 because the condition on line 267 was always true

268 restore.callback(collection.set_color, colors) 

269 collection.set_color(colors[source]) 

270 if len(widths) == count: 270 ↛ exitline 270 didn't return from function '_crop_segments' because the condition on line 270 was always true

271 restore.callback(collection.set_linewidth, widths) 

272 collection.set_linewidth(np.asarray(widths)[source]) 

273 

274 

275def _crop_rectangle(rect, ax, box, restore): 

276 transform = rect.get_transform() 

277 corners = transform.transform(rect.get_path().vertices[:4]) 

278 x0, x1 = max(corners[:, 0].min(), box.x0), min(corners[:, 0].max(), box.x1) 

279 y0, y1 = max(corners[:, 1].min(), box.y0), min(corners[:, 1].max(), box.y1) 

280 xy, width, height, visible = rect.get_xy(), rect.get_width(), rect.get_height(), rect.get_visible() 

281 

282 def put_back(): 

283 rect.set_xy(xy) 

284 rect.set_width(width) 

285 rect.set_height(height) 

286 rect.set_visible(visible) 

287 restore.callback(put_back) 

288 if x0 >= x1 or y0 >= y1: 288 ↛ 289line 288 didn't jump to line 289 because the condition on line 288 was never true

289 rect.set_visible(False) 

290 return 

291 # 棒は (左下, 幅, 高さ) をデータの座標で持つ。軸が反転していても、枠の中の長方形は同じ 

292 (dx0, dy0), (dx1, dy1) = rect.get_data_transform().inverted().transform([[x0, y0], [x1, y1]]) 

293 rect.set_xy((min(dx0, dx1), min(dy0, dy1))) 

294 rect.set_width(abs(dx1 - dx0)) 

295 rect.set_height(abs(dy1 - dy0)) 

296 

297 

298def _crop_polygon_patch(polygon, ax, box, restore): 

299 clipped = polygon.get_transform().transform_path(polygon.get_path()).clip_to_bbox(_box(box)) 

300 xy, visible = polygon.get_xy(), polygon.get_visible() 

301 

302 def put_back(): 

303 polygon.set_xy(xy) 

304 polygon.set_visible(visible) 

305 restore.callback(put_back) 

306 if len(clipped.vertices) < 3: 

307 polygon.set_visible(False) 

308 return 

309 polygon.set_xy(polygon.get_data_transform().inverted().transform(clipped.vertices)) 

310 

311 

312# 種類ごとの削り方。いちばん近い種類のものを使う(LineCollection は PolyCollection より前) 

313_CROPPERS = ( 

314 (Line2D, _crop_line), 

315 (PathCollection, _crop_scatter), 

316 (LineCollection, _crop_segments), 

317 (PolyCollection, _crop_polygons), 

318 (Rectangle, _crop_rectangle), 

319 (Polygon, _crop_polygon_patch), 

320) 

321 

322 

323def _cropper_for(artist): 

324 return next((crop for kind, crop in _CROPPERS if isinstance(artist, kind)), None) 

325 

326 

327def project_has_raster_gradient_fill(project): 

328 """グラデーションの塗り(imshow で描くのでベクター形式でもラスタになる)を使う系列があるか。""" 

329 return any( 

330 ds.plot_type == 'Area' and ds.gradient_enabled and ds.gradient_target in ('fill', 'both') 

331 for ds in project.datasets 

332 )