rrplot 1.3.0__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.
cycleplot/__init__.py ADDED
@@ -0,0 +1,22 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Compatibility alias for projects that imported the former ``cycleplot`` name."""
3
+ import importlib
4
+ import sys
5
+ import warnings
6
+
7
+ import rrplot as _rrplot
8
+
9
+ warnings.warn(
10
+ "cycleplot is deprecated; use rrplot instead",
11
+ DeprecationWarning,
12
+ stacklevel=2,
13
+ )
14
+
15
+ for _name in ("core", "parts", "hvac", "style", "svgparts", "_primitives"):
16
+ sys.modules[f"{__name__}.{_name}"] = importlib.import_module(
17
+ f"rrplot.{_name}"
18
+ )
19
+
20
+ from rrplot import * # noqa: F401,F403,E402
21
+
22
+ __version__ = _rrplot.__version__
rrplot/__init__.py ADDED
@@ -0,0 +1,29 @@
1
+ # -*- coding: utf-8 -*-
2
+ """rrplot —— 通用制冷循环示意图库。
3
+
4
+ 用法示例::
5
+
6
+ from rrplot import Diagram, parts
7
+ from rrplot.parts import make_heat_exchanger
8
+
9
+ d = Diagram(width=1491, height=1055)
10
+ comp = d.add(parts.compressor, "压缩机", loc=(330, 140))
11
+ cond = d.add(make_heat_exchanger(180, 90, shape="rect_zigzag7"),
12
+ "冷凝器", loc=(945, 140))
13
+
14
+ d.pipe(cond["bottom"], comp["suction"], via=[("e", 200), ("n", 105)],
15
+ states=[("1", 0.5)])
16
+ d.save("out.png") # 也支持 .pdf / .svg 矢量输出
17
+ """
18
+ from . import hvac, parts, style
19
+ from .core import Diagram, Node, Pipe, Port, State, make_partial, use_font
20
+ from .parts import COMPRESSOR_STYLES, HEX_SHAPES
21
+ from .style import FONT, FONT_STACK, LINE, apply_style, context
22
+ from .svgparts import load_svg_part
23
+
24
+ __version__ = "1.3.0"
25
+
26
+ __all__ = ["__version__", "Diagram", "Node", "Pipe", "Port", "State",
27
+ "make_partial", "use_font", "parts", "hvac", "style", "FONT",
28
+ "FONT_STACK", "LINE", "apply_style", "context", "HEX_SHAPES",
29
+ "COMPRESSOR_STYLES", "load_svg_part"]
rrplot/_primitives.py ADDED
@@ -0,0 +1,26 @@
1
+ # -*- coding: utf-8 -*-
2
+ """底层绘制原语:文本、折线、箭头。parts 与 core 共用。"""
3
+ from .style import FONT_STACK, LINE
4
+
5
+
6
+ def txt(ax, x, y, s, size=18, ha="center", va="center", weight="normal",
7
+ rot=0, color=LINE, boxed=False, linespacing=1.2):
8
+ """写一段文本;boxed=True 时垫一层白底,压在管线上也可读。"""
9
+ kw = {}
10
+ if boxed:
11
+ kw["bbox"] = dict(facecolor="white", edgecolor="none", pad=1.5)
12
+ ax.text(x, y, s, fontsize=size, fontfamily=FONT_STACK, ha=ha, va=va,
13
+ color=color, fontweight=weight, rotation=rot,
14
+ linespacing=linespacing, **kw)
15
+
16
+
17
+ def line(ax, pts, lw=1.0, color=LINE, linestyle="solid"):
18
+ xs, ys = zip(*pts)
19
+ ax.plot(xs, ys, color=color, lw=lw, linestyle=linestyle,
20
+ solid_capstyle="round", solid_joinstyle="round")
21
+
22
+
23
+ def arrow(ax, x1, y1, x2, y2, size=8, lw=0.9, color=LINE):
24
+ ax.annotate("", xy=(x2, y2), xytext=(x1, y1),
25
+ arrowprops=dict(arrowstyle="-|>", lw=lw, color=color,
26
+ mutation_scale=size))
rrplot/core.py ADDED
@@ -0,0 +1,519 @@
1
+ # -*- coding: utf-8 -*-
2
+ """示意图引擎:部件放置、走线式连线、随线状态点/传感器标注。
3
+
4
+ 坐标系与旧脚本一致:x 向右, y 向下(ax.set_ylim(H, 0))。
5
+ """
6
+ import io
7
+ import math
8
+
9
+ import matplotlib.pyplot as plt
10
+ from matplotlib.patches import Circle
11
+
12
+ from ._primitives import arrow, txt
13
+ from ._primitives import line as _line
14
+ from .style import FONT_STACK, LINE, LW_PIPE, NUM_SIZE, SENSOR_R, SENSOR_SIZE, use_font
15
+
16
+ _DIR_TOKENS = {
17
+ "e": (1, 0), "w": (-1, 0), "n": (0, -1), "s": (0, 1),
18
+ "right": (1, 0), "left": (-1, 0), "up": (0, -1), "down": (0, 1),
19
+ "右": (1, 0), "左": (-1, 0), "上": (0, -1), "下": (0, 1),
20
+ }
21
+
22
+ SNAP_TOL = 10 # 端口附近小于此值的错位视为笔误,吸附消除接缝碎块
23
+ ARROW_HALF = 20 # 随线箭头线长的一半(px)
24
+
25
+ _DBG_PORT = "#d62728" # debug 叠加层:端口点/法向箭头
26
+ _DBG_PIPE = "#1f77b4" # debug 叠加层:管线拐点
27
+
28
+ _AT_TOKENS = {"start": 0.0, "mid": 0.5, "end": 1.0}
29
+
30
+
31
+ def _fit_end(pts, at_start, port):
32
+ """把端口邻段的小错位吸附到端口坐标,避免接缝处多出小碎块。
33
+
34
+ 管线应沿端口外法向出入:邻段与端口斜接时,先吸附小错位;错位大且
35
+ 在法向正确一侧,则返回走线提示("h"/"v")交给 _orthogonalize 选拐点
36
+ 顺序。返回 None 表示无需提示。
37
+ """
38
+ if len(pts) < 2:
39
+ return None
40
+ d = port.dir
41
+ if not (d[0] or d[1]):
42
+ return None
43
+ iE = 0 if at_start else len(pts) - 1
44
+ iN = 1 if at_start else len(pts) - 2
45
+ E, N = pts[iE], pts[iN]
46
+ n_ax = 0 if d[0] else 1 # 法向轴
47
+ p_ax = 1 - n_ax # 切向轴
48
+ dn = d[n_ax]
49
+
50
+ def set_axis(i, axis, val):
51
+ p = list(pts[i])
52
+ p[axis] = val
53
+ pts[i] = tuple(p)
54
+
55
+ # 斜接:小错位吸附(优先切向,保持沿法向出入)
56
+ if E[p_ax] != N[p_ax] and E[n_ax] != N[n_ax]:
57
+ if abs(N[p_ax] - E[p_ax]) <= SNAP_TOL:
58
+ set_axis(iN, p_ax, E[p_ax])
59
+ elif abs(N[n_ax] - E[n_ax]) <= SNAP_TOL:
60
+ set_axis(iN, n_ax, E[n_ax])
61
+ elif (N[n_ax] - E[n_ax]) * dn > 0: # 法向正确侧才按法向先走
62
+ return "h" if n_ax == 0 else "v"
63
+ return None
64
+ # 切向已对齐:从法向背面近距离接入时,把引管整段吸附到端口坐标
65
+ if E[p_ax] == N[p_ax]:
66
+ off = N[n_ax] - E[n_ax]
67
+ if off * dn < 0 and abs(off) <= SNAP_TOL:
68
+ if at_start:
69
+ set_axis(iN, n_ax, E[n_ax])
70
+ else: # 终点端连同 feeder 竖/横段一起挪
71
+ j = iN
72
+ while j >= 1 and pts[j][n_ax] == N[n_ax]:
73
+ set_axis(j, n_ax, E[n_ax])
74
+ j -= 1
75
+ return None
76
+
77
+
78
+ class Port:
79
+ """节点上的一个接管口,记录绝对坐标与外法向。"""
80
+
81
+ __slots__ = ("point", "dir", "owner")
82
+
83
+ def __init__(self, point, direction, owner):
84
+ self.point = point
85
+ self.dir = direction
86
+ self.owner = owner
87
+
88
+ def __repr__(self):
89
+ name = "-" if self.owner is None \
90
+ else (self.owner.label or self.owner.part.name)
91
+ return f"<Port {name} {self.point}>"
92
+
93
+
94
+ class Node:
95
+ """放置在画布上的部件实例。node["port"] 取得端口。"""
96
+
97
+ def __init__(self, part, loc, label, style=None):
98
+ self.part = part
99
+ self.loc = loc
100
+ self.label = label
101
+ self.style = style or {}
102
+
103
+ def port(self, key):
104
+ dx, dy = self.part.port(key)
105
+ x, y = self.loc
106
+ return Port((x + dx, y + dy), self.part.direction(key), self)
107
+
108
+ def __getitem__(self, key):
109
+ return self.port(key)
110
+
111
+
112
+ class State:
113
+ """随线标注:状态点编号或 T/P 传感器。"""
114
+
115
+ def __init__(self, text, at, side=-1, kind=None, size=None):
116
+ self.text = text
117
+ self.at = at
118
+ self.side = side
119
+ self.kind = kind or ("sensor" if _is_sensor(text) else "num")
120
+ self.size = size
121
+
122
+ @property
123
+ def is_sensor(self):
124
+ return self.kind == "sensor"
125
+
126
+
127
+ def _is_sensor(text):
128
+ t = text.strip().strip("$").strip()
129
+ return bool(t) and t[0].isalpha()
130
+
131
+
132
+ def _resolve_at(at):
133
+ """把 at 归一为 [0,1] 的折线弧长比例。"""
134
+ if isinstance(at, str):
135
+ key = at.lower()
136
+ if key not in _AT_TOKENS:
137
+ raise ValueError(f"at={at!r} 不是合法位置,"
138
+ f"可用:{'/'.join(sorted(_AT_TOKENS))} 或 0~1 的数值")
139
+ at = _AT_TOKENS[key]
140
+ try:
141
+ at = float(at)
142
+ except (TypeError, ValueError):
143
+ raise ValueError(f"at={at!r} 必须是 0~1 的数值") from None
144
+ if not math.isfinite(at) or not 0.0 <= at <= 1.0:
145
+ raise ValueError(f"at={at!r} 超出范围,必须在 0~1 之间")
146
+ return at
147
+
148
+
149
+ def _polyline_span(pts, frac):
150
+ """返回折线上给定弧长比例处的点、局部方向、所在段的弧长区间与总长。"""
151
+ segs = [(pts[i], pts[i + 1]) for i in range(len(pts) - 1)]
152
+ lens = [abs(b[0] - a[0]) + abs(b[1] - a[1]) for a, b in segs]
153
+ total = sum(lens) or 1.0
154
+ target = frac * total
155
+ acc = 0.0
156
+ for (a, b), L in zip(segs, lens):
157
+ if acc + L >= target or (a, b) is segs[-1]:
158
+ t = 0.0 if L == 0 else (target - acc) / L
159
+ x = a[0] + (b[0] - a[0]) * t
160
+ y = a[1] + (b[1] - a[1]) * t
161
+ ux = (b[0] - a[0]) / L if L else 1.0
162
+ uy = (b[1] - a[1]) / L if L else 0.0
163
+ return (x, y), (ux, uy), acc, acc + L, total
164
+ acc += L
165
+ return pts[-1], (1.0, 0.0), total, total, total
166
+
167
+
168
+ def _polyline_point(pts, frac):
169
+ """返回折线上给定弧长比例处的点与局部方向。"""
170
+ (x, y), u, _s0, _s1, _total = _polyline_span(pts, frac)
171
+ return (x, y), u
172
+
173
+
174
+ def _draw_head(ax, pts, frac, color, size=8):
175
+ """在弧长比例 frac 处画随线箭头,整体夹在本段之内不越过拐角。
176
+
177
+ 采样点距段端不足一个箭头长时,先平移让箭头整段放下;段本身比箭头
178
+ 短则缩成与段等长(仍指向下游)。
179
+ """
180
+ (_x, _y), _u, s0, s1, total = _polyline_span(pts, frac)
181
+ if s1 - s0 < 1.0:
182
+ return
183
+ half = min(ARROW_HALF * size / 8.0, (s1 - s0) / 2)
184
+ c = min(max(frac * total, s0 + half), s1 - half)
185
+ (xa, ya), _ = _polyline_point(pts, (c - half) / total)
186
+ (xb, yb), _ = _polyline_point(pts, (c + half) / total)
187
+ arrow(ax, xa, ya, xb, yb, size=size, lw=0.9, color=color)
188
+
189
+
190
+ def _orthogonalize(pts, first_along=None, last_along=None):
191
+ """把任意折线补齐为直角走线:在方向突变处插入拐点。
192
+
193
+ first_along / last_along: "h" 或 "v",指定首/末斜接段先走哪个方向,
194
+ 用于让管线沿端口法向出入(只对与端口相邻的斜接段生效)。
195
+ """
196
+ n = len(pts)
197
+ out = [pts[0]]
198
+ for i, cur in enumerate(pts[1:], 1):
199
+ prev = out[-1]
200
+ if prev[0] == cur[0] or prev[1] == cur[1]:
201
+ out.append(cur)
202
+ continue
203
+ if i == 1 and first_along:
204
+ corner = ((cur[0], prev[1]) if first_along == "h"
205
+ else (prev[0], cur[1])) # 起点斜接:先沿端口法向
206
+ elif i == n - 1 and last_along:
207
+ corner = ((prev[0], cur[1]) if last_along == "h"
208
+ else (cur[0], prev[1])) # 终点斜接:末段沿端口法向
209
+ elif len(out) >= 2 and out[-2][1] == prev[1]:
210
+ corner = (cur[0], prev[1]) # 进入段水平 -> 先横后竖
211
+ else:
212
+ corner = (prev[0], cur[1]) # 进入段竖直 -> 先竖后横
213
+ out.extend([corner, cur])
214
+ return out
215
+
216
+
217
+ class Pipe:
218
+ def __init__(self, diagram, a, b, via, states, lw, head, head_at,
219
+ color=LINE, head_size=8, linestyle="solid"):
220
+ self.d = diagram
221
+ self.a = a
222
+ self.b = b
223
+ self.via = via
224
+ self.states = states
225
+ self.lw = lw
226
+ self.head = head
227
+ self.head_at = head_at
228
+ self.head_size = head_size
229
+ self.color = color
230
+ self.linestyle = linestyle
231
+ self._pts = None
232
+
233
+ def points(self):
234
+ if self._pts is not None:
235
+ return self._pts
236
+ pts = [self.a.point]
237
+ cur = self.a.point
238
+ for i, token in enumerate(self.via):
239
+ if isinstance(token, str) or (isinstance(token, (tuple, list))
240
+ and len(token) == 2
241
+ and isinstance(token[0], str)):
242
+ name = token if isinstance(token, str) else token[0]
243
+ key = str(name).lower()
244
+ if key not in _DIR_TOKENS:
245
+ raise ValueError(
246
+ f"via[{i}] 方向令牌 {name!r} 无效,"
247
+ f"可用:{', '.join(sorted(set(_DIR_TOKENS)))}")
248
+ d = _DIR_TOKENS[key]
249
+ if isinstance(token, str):
250
+ length = self.d.default_step
251
+ nxt = (cur[0] + d[0] * length, cur[1] + d[1] * length)
252
+ else:
253
+ val = token[1]
254
+ nxt = (val, cur[1]) if d[0] else (cur[0], val)
255
+ else:
256
+ try:
257
+ tx, ty = token
258
+ nxt = (float(tx), float(ty))
259
+ except (TypeError, ValueError):
260
+ raise ValueError(
261
+ f"via[{i}]={token!r} 不是合法走点;支持方向令牌 "
262
+ f"('e', 200)、裸字符串 'e' 或坐标 (x, y)") from None
263
+ pts.append(nxt)
264
+ cur = nxt
265
+ pts.append(self.b.point)
266
+ first = _fit_end(pts, True, self.a)
267
+ last = _fit_end(pts, False, self.b)
268
+ self._pts = _orthogonalize(pts, first, last)
269
+ return self._pts
270
+
271
+ def draw(self):
272
+ pts = self.points()
273
+ _line(self.d.ax, pts, lw=self.lw, color=self.color,
274
+ linestyle=self.linestyle)
275
+ if self.head:
276
+ for f in self.head_at:
277
+ _draw_head(self.d.ax, pts, f, self.color, self.head_size)
278
+ for st in self.states:
279
+ self._draw_state(st, pts)
280
+
281
+ def _draw_state(self, st, pts):
282
+ (x, y), (ux, uy) = _polyline_point(pts, _resolve_at(st.at))
283
+ nx, ny = -uy, ux
284
+ off = (SENSOR_SIZE + 22) if st.is_sensor else (NUM_SIZE + 12)
285
+ px = x + nx * off * st.side
286
+ py = y + ny * off * st.side
287
+ if st.is_sensor:
288
+ size = st.size or SENSOR_SIZE
289
+ self.d.ax.add_patch(Circle((px, py), SENSOR_R, facecolor="white",
290
+ edgecolor=LINE, lw=1.0, zorder=5))
291
+ txt(self.d.ax, px, py, st.text, size=size)
292
+ self.d.ax.texts[-1].set_zorder(6)
293
+ else:
294
+ self.d.ax.text(px, py, st.text, fontsize=st.size or NUM_SIZE,
295
+ fontfamily=FONT_STACK, ha="center", va="center",
296
+ color=LINE, zorder=6)
297
+
298
+
299
+ class Diagram:
300
+ """一张示意图。add() 放部件,pipe() 连线,最后 save() 出图。"""
301
+
302
+ def __init__(self, width=800, height=600, default_step=100):
303
+ for name, value, allow_zero in (
304
+ ("width", width, True),
305
+ ("height", height, True),
306
+ ("default_step", default_step, False),
307
+ ):
308
+ try:
309
+ valid = math.isfinite(float(value)) and (
310
+ value >= 0 if allow_zero else value > 0
311
+ )
312
+ except (TypeError, ValueError):
313
+ valid = False
314
+ if not valid:
315
+ bound = ">= 0" if allow_zero else "> 0"
316
+ raise ValueError(f"{name} 必须是有限数值且 {bound}")
317
+ self.W, self.H = width, height
318
+ self.default_step = default_step
319
+ self.fig, self.ax = plt.subplots(figsize=(width / 100, height / 100),
320
+ dpi=100)
321
+ self.fig.subplots_adjust(0, 0, 1, 1) # 画布 1 像素 = 1 画图单位
322
+ # 零尺寸画布:跳过 set_xlim/ylim,避免 matplotlib 的 identical
323
+ # limits 警告(Diagram(0, 0) 是合法的退化输入)
324
+ if width > 0:
325
+ self.ax.set_xlim(0, width)
326
+ if height > 0:
327
+ self.ax.set_ylim(height, 0)
328
+ self.ax.set_aspect("equal")
329
+ self.ax.axis("off")
330
+ self.fig.patch.set_facecolor("white")
331
+ self._nodes = []
332
+ self._pipes = []
333
+ self._drawn_nodes = set() # render 增量绘制:已上屏的不再重画
334
+ self._drawn_pipes = set()
335
+
336
+ # ---------- 组装 ----------
337
+ def add(self, part, label=None, loc=(0, 0), **style):
338
+ node = Node(part, loc, label, style)
339
+ self._nodes.append(node)
340
+ return node
341
+
342
+ def pipe(self, a, b, via=(), states=(), lw=LW_PIPE, head=True,
343
+ head_at=(0.55,), color=LINE, head_size=8, linestyle="solid"):
344
+ """连线。head_size 为随线箭头大小(默认 8,论文粗箭头可用 16~20);
345
+ linestyle 传 matplotlib 线型("solid"/"dashed"/":" 等),虚线管用。
346
+ """
347
+ a, b = _as_port(a), _as_port(b)
348
+ if isinstance(states, State):
349
+ states = (states,)
350
+ norm = []
351
+ for s in states:
352
+ if isinstance(s, State):
353
+ norm.append(s)
354
+ elif isinstance(s, dict):
355
+ s = dict(s)
356
+ norm.append(State(s.pop("text"),
357
+ s.pop("at", "mid"), **s))
358
+ else:
359
+ norm.append(State(s[0], s[1]))
360
+ p = Pipe(self, a, b, list(via), norm, lw, head, head_at, color,
361
+ head_size, linestyle)
362
+ self._pipes.append(p)
363
+ return p
364
+
365
+ # 便捷:直接按坐标放一个 T/P 传感器圆圈
366
+ def sensor(self, x, y, text, r=SENSOR_R, size=SENSOR_SIZE):
367
+ self.ax.add_patch(Circle((x, y), r, facecolor="white",
368
+ edgecolor=LINE, lw=1.0, zorder=5))
369
+ txt(self.ax, x, y, text, size=size)
370
+ self.ax.texts[-1].set_zorder(6)
371
+
372
+ def text(self, x, y, s, **kw):
373
+ txt(self.ax, x, y, s, **kw)
374
+
375
+ def debug(self, ports=True, normals=True, pipe_points=True, names=False):
376
+ """叠加调试层,自查端口位置、法向与走线拐点(随图一起输出)。
377
+
378
+ ports 每个部件的端口画红点
379
+ normals 沿端口外法向画红色短箭头(检查管线出入方向)
380
+ pipe_points 每根管线折线的拐点画蓝色小方块
381
+ names 端口旁标注端口名(写部件端口表时定位用)
382
+
383
+ 只覆盖调用当时已 add()/pipe() 的内容,在 save()/show() 之前调用;
384
+ 正式出图前删掉这行即可。
385
+ """
386
+ self.render()
387
+ if ports:
388
+ for n in self._nodes:
389
+ for key in n.part.ports:
390
+ p = n.port(key)
391
+ self.ax.add_patch(Circle(p.point, 4.5,
392
+ facecolor=_DBG_PORT,
393
+ edgecolor="none", zorder=7))
394
+ if names:
395
+ off = 48 if p.dir != (0, 0) else 14
396
+ self.text(p.point[0] + p.dir[0] * off,
397
+ p.point[1] + p.dir[1] * off, key,
398
+ size=9, color=_DBG_PORT)
399
+ if normals:
400
+ for n in self._nodes:
401
+ for key in n.part.ports:
402
+ p = n.port(key)
403
+ if p.dir == (0, 0):
404
+ continue
405
+ arrow(self.ax, p.point[0], p.point[1],
406
+ p.point[0] + p.dir[0] * 30,
407
+ p.point[1] + p.dir[1] * 30,
408
+ size=10, lw=1.0, color=_DBG_PORT)
409
+ if pipe_points:
410
+ for p in self._pipes:
411
+ xs, ys = zip(*p.points())
412
+ self.ax.plot(xs, ys, linestyle="none", marker="s", ms=4,
413
+ color=_DBG_PIPE, zorder=7)
414
+ return self.fig
415
+
416
+ # ---------- 出图 ----------
417
+ def render(self):
418
+ """画出全部部件与管线;重复调用只补画新增内容,可安全多次调用。"""
419
+ for n in self._nodes:
420
+ if id(n) in self._drawn_nodes:
421
+ continue
422
+ kw = dict(n.style)
423
+ # label=None/"" 一律不画,不回落到部件绘制函数的默认标签
424
+ kw["label"] = n.label
425
+ n.part.draw(self.ax, n.loc[0], n.loc[1], **kw)
426
+ self._drawn_nodes.add(id(n))
427
+ for p in self._pipes:
428
+ if id(p) in self._drawn_pipes:
429
+ continue
430
+ p.draw()
431
+ self._drawn_pipes.add(id(p))
432
+ return self.fig
433
+
434
+ def clear_render(self):
435
+ """清空当前 Matplotlib 图层,保留节点和管线以便重新绘制。
436
+
437
+ ``render()`` 为了支持重复调用会缓存已经绘制的节点和管线。如果
438
+ 修改了 ``Node.loc``、``Node.style`` 或管线参数,先调用本方法再
439
+ ``render()`` 可避免旧图元残留。手工调用 ``sensor()``、``text()``
440
+ 或 ``debug()`` 添加的临时图层也会被清除。
441
+ """
442
+ self.ax.clear()
443
+ self.fig.subplots_adjust(0, 0, 1, 1)
444
+ if self.W > 0:
445
+ self.ax.set_xlim(0, self.W)
446
+ if self.H > 0:
447
+ self.ax.set_ylim(self.H, 0)
448
+ self.ax.set_aspect("equal")
449
+ self.ax.axis("off")
450
+ self.fig.patch.set_facecolor("white")
451
+ self._drawn_nodes.clear()
452
+ self._drawn_pipes.clear()
453
+ return self
454
+
455
+ def save(self, *paths, dpi=100, tight=True):
456
+ """出图。可一次传多个路径输出多种格式,如 ``save("out.png", "out.svg")``。
457
+
458
+ 传单个路径返回该路径字符串,多个则返回路径元组。
459
+ """
460
+ if not paths:
461
+ raise TypeError(
462
+ "save() 至少需要一个输出路径,如 save('out.png')")
463
+ self.render()
464
+ kw = dict(dpi=dpi)
465
+ if tight:
466
+ kw.update(bbox_inches="tight", pad_inches=0.05)
467
+ for path in paths:
468
+ self.fig.savefig(path, **kw)
469
+ return paths[0] if len(paths) == 1 else paths
470
+
471
+ def _repr_svg_(self):
472
+ """Jupyter/IPython 富显示:把整张图作为 SVG 内嵌输出。"""
473
+ self.render()
474
+ buf = io.StringIO()
475
+ self.fig.savefig(buf, format="svg")
476
+ return buf.getvalue()
477
+
478
+ def show(self):
479
+ self.render()
480
+ plt.show()
481
+
482
+ def close(self):
483
+ """关闭底层 figure(plt.close),批量出图/长会话防止 figure 堆积。"""
484
+ plt.close(self.fig)
485
+
486
+ def __enter__(self):
487
+ return self
488
+
489
+ def __exit__(self, *exc):
490
+ self.close()
491
+
492
+
493
+ def _as_port(p):
494
+ """允许把裸坐标 (x, y) 当作固定管路端点(用于画总管/分支点)。"""
495
+ if isinstance(p, Port):
496
+ return p
497
+ return Port((float(p[0]), float(p[1])), (0.0, 0.0), None)
498
+
499
+
500
+ def make_partial(part, ports=None, dirs=None):
501
+ """从已有部件派生一个只改端口定义的新部件(复用同一绘制函数)。
502
+
503
+ 覆盖某个端口位置时,其旧方向声明一并作废(回落到按偏移推断);
504
+ 需要固定方向就显式传 dirs。
505
+ """
506
+ from .part import Part
507
+ new_ports = dict(part.ports)
508
+ new_dirs = dict(part._dirs)
509
+ if ports:
510
+ for k, v in ports.items():
511
+ new_ports[k] = v
512
+ new_dirs.pop(k, None)
513
+ if dirs:
514
+ new_dirs.update(dirs)
515
+ return Part(part.name, part.draw, new_ports, new_dirs)
516
+
517
+
518
+ __all__ = ["Diagram", "Node", "Port", "State", "Pipe", "make_partial",
519
+ "use_font"]