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.
rrplot/style.py ADDED
@@ -0,0 +1,74 @@
1
+ # -*- coding: utf-8 -*-
2
+ """字体、颜色、线宽等全局样式常量。"""
3
+ from contextlib import contextmanager
4
+
5
+ import matplotlib
6
+ from matplotlib import font_manager as fm
7
+
8
+ FONT_CANDIDATES = [
9
+ "Times New Roman", "SimSun", "FangSong", "KaiTi",
10
+ "Songti SC", "Noto Serif CJK SC", "Source Han Serif SC", "STSong",
11
+ "DejaVu Serif",
12
+ ]
13
+
14
+ _installed = {f.name for f in fm.fontManager.ttflist}
15
+ FONT = next((c for c in FONT_CANDIDATES if c in _installed), "DejaVu Serif")
16
+ # 交给 matplotlib 做逐字回退:西文用 Times,汉字回退到宋体
17
+ FONT_STACK = [c for c in FONT_CANDIDATES if c in _installed] or [FONT]
18
+
19
+ STYLE_PARAMS = {
20
+ "font.family": "serif",
21
+ "font.serif": FONT_CANDIDATES,
22
+ # 数学文本(如 EEV$_1$ 的下标)用 STIX,与 Times 风格一致
23
+ "mathtext.fontset": "stix",
24
+ "axes.unicode_minus": False,
25
+ }
26
+
27
+
28
+ def apply_style(**overrides):
29
+ """把 rrplot 样式应用到 Matplotlib 全局配置并返回配置副本。
30
+
31
+ 该函数保留旧版的全局样式行为;嵌入其他绘图库时优先使用
32
+ :func:`context` 让配置在代码块结束后自动恢复。
33
+ """
34
+ params = dict(STYLE_PARAMS)
35
+ params.update(overrides)
36
+ matplotlib.rcParams.update(params)
37
+ return params
38
+
39
+
40
+ @contextmanager
41
+ def context(**overrides):
42
+ """在上下文中临时启用 rrplot 样式,退出后恢复调用方配置。"""
43
+ params = dict(STYLE_PARAMS)
44
+ params.update(overrides)
45
+ with matplotlib.rc_context(params):
46
+ yield
47
+
48
+
49
+ apply_style()
50
+
51
+ LINE = "#000000"
52
+ FILL = "white" # 部件填充(论文风格:纯白)
53
+ COIL = "#333333" # 部件内盘管/结构线
54
+ GRID = "#555555" # 部件内格栅/细结构线
55
+
56
+ LW_PIPE = 1.2 # 管路
57
+ LW_OUTLINE = 1.2 # 部件外壳/盘管轮廓
58
+ LW_PART = 1.0 # 部件内部结构线
59
+ LW_STRONG = 1.5 # 强调线(壳体主轮廓、接管短管)
60
+ LW_FINE = 0.6 # 内部细节线(格栅、液位)
61
+ NUM_SIZE = 24
62
+ SENSOR_SIZE = 15
63
+ SENSOR_R = 18 # 随线 T/P 传感器圆圈半径
64
+
65
+
66
+ def use_font():
67
+ """打印实际生效的字体(逐字回退栈),便于排查中文方框字。"""
68
+ print("使用字体:", FONT)
69
+ if len(FONT_STACK) > 1:
70
+ print("回退栈:", " -> ".join(FONT_STACK))
71
+ else:
72
+ print("警告:仅匹配到", FONT,
73
+ ",未安装中文字体时汉字会渲染成方框")
74
+ return FONT
rrplot/svgparts.py ADDED
@@ -0,0 +1,230 @@
1
+ # -*- coding: utf-8 -*-
2
+ """把 hvacsvg 式的 SVG 符号加载成 rrplot 部件(路线一)。
3
+
4
+ 只解析本仓库 ``symbols/`` 用到的 SVG 子集:``path`` 指令
5
+ M/m/L/l/H/h/V/v/C/c/Z/z,以及标签 circle / ellipse / rect / g。
6
+
7
+ 连接点读根属性 ``data-connection-points``,转成相对锚点的 (dx, dy) 偏移;
8
+ ``class="connection-point"`` 的圆是元数据标记,默认跳过
9
+ (``show_ports=True`` 可见)。
10
+ """
11
+ import json
12
+ import re
13
+ import xml.etree.ElementTree as ET
14
+ from pathlib import Path as FilePath
15
+
16
+ from matplotlib.patches import Circle, Ellipse, FancyBboxPatch, PathPatch, Rectangle
17
+ from matplotlib.path import Path as MplPath
18
+
19
+ from ._primitives import line, txt
20
+ from .part import Part
21
+ from .style import LINE, LW_PIPE
22
+
23
+ _NS = "{http://www.w3.org/2000/svg}"
24
+ _TOKEN = re.compile(r"[MmLlHhVvCcZz]|[-+]?(?:\d*\.\d+|\d+)(?:[eE][-+]?\d+)?")
25
+ _ARITY = {"M": 2, "L": 2, "H": 1, "V": 1, "C": 6, "Z": 0}
26
+ # SVG 默认 fill=black,但 hvacsvg 里的纯描边 path 常不写 fill —— 落成 none 更符合画意
27
+ _DEFAULT_STYLE = {"fill": "none", "stroke": "black", "stroke-width": "1"}
28
+ _MAX_SVG_BYTES = 10 * 1024 * 1024
29
+ _UNSAFE_XML = re.compile(br"<!\s*(?:DOCTYPE|ENTITY)\b", re.IGNORECASE)
30
+
31
+
32
+ def _tag(el):
33
+ return el.tag.replace(_NS, "") if isinstance(el.tag, str) else ""
34
+
35
+
36
+ def _style(el, inherited):
37
+ st = dict(inherited)
38
+ for item in el.get("style", "").split(";"):
39
+ if ":" in item:
40
+ k, v = item.split(":", 1)
41
+ st[k.strip()] = v.strip()
42
+ for k in ("fill", "stroke", "stroke-width"):
43
+ if el.get(k) is not None:
44
+ st[k] = el.get(k)
45
+ return st
46
+
47
+
48
+ def _path_verts(d):
49
+ """path 的 d 串编译成 (verts, codes)。相对指令在 y 向下画布上无需翻转。"""
50
+ toks = _TOKEN.findall(d)
51
+ verts, codes = [], []
52
+ x = y = sx = sy = 0.0
53
+ i = 0
54
+ cmd = None
55
+ while i < len(toks):
56
+ t = toks[i]
57
+ if t.isalpha():
58
+ cmd = t
59
+ i += 1
60
+ if cmd in "Zz":
61
+ verts.append((0.0, 0.0))
62
+ codes.append(MplPath.CLOSEPOLY)
63
+ x, y = sx, sy
64
+ continue
65
+ if cmd is None:
66
+ i += 1
67
+ continue
68
+ rel = cmd.islower()
69
+ op = cmd.upper()
70
+ n = _ARITY[op]
71
+ nums = [float(v) for v in toks[i:i + n]]
72
+ if len(nums) < n:
73
+ break
74
+ i += n
75
+ if op == "M":
76
+ nx, ny = nums
77
+ if rel:
78
+ nx, ny = x + nx, y + ny
79
+ x, y = sx, sy = nx, ny
80
+ verts.append((x, y))
81
+ codes.append(MplPath.MOVETO)
82
+ cmd = "l" if rel else "L" # M 后的裸坐标对是隐式 L
83
+ elif op == "L":
84
+ nx, ny = nums
85
+ if rel:
86
+ nx, ny = x + nx, y + ny
87
+ x, y = nx, ny
88
+ verts.append((x, y))
89
+ codes.append(MplPath.LINETO)
90
+ elif op == "H":
91
+ x = nums[0] + (x if rel else 0)
92
+ verts.append((x, y))
93
+ codes.append(MplPath.LINETO)
94
+ elif op == "V":
95
+ y = nums[0] + (y if rel else 0)
96
+ verts.append((x, y))
97
+ codes.append(MplPath.LINETO)
98
+ elif op == "C":
99
+ x1, y1, x2, y2, nx, ny = nums
100
+ if rel:
101
+ x1, y1, x2, y2, nx, ny = (x + x1, y + y1, x + x2, y + y2,
102
+ x + nx, y + ny)
103
+ verts += [(x1, y1), (x2, y2), (nx, ny)]
104
+ codes += [MplPath.CURVE4, MplPath.CURVE4, MplPath.CURVE4]
105
+ x, y = nx, ny
106
+ else:
107
+ break
108
+ return verts, codes
109
+
110
+
111
+ def _draw(ax, el, inherited, dx, dy, s):
112
+ """递归画一个 SVG 元素,(dx,dy) 为平移、s 为缩放(y 向下同向,不翻转)。"""
113
+ tag = _tag(el)
114
+ if "connection-point" in (el.get("class") or "").split():
115
+ return
116
+ st = _style(el, inherited)
117
+ face = st.get("fill", "none") or "none"
118
+ edge = st.get("stroke", "none") or "none"
119
+ face = "none" if face == "transparent" else face
120
+ edge = "none" if edge == "transparent" else edge
121
+ lw = float(st.get("stroke-width", 1) or 1) * max(s, 0.5)
122
+ if tag == "path":
123
+ verts, codes = _path_verts(el.get("d", ""))
124
+ if verts:
125
+ verts = [(vx * s + dx, vy * s + dy) for vx, vy in verts]
126
+ ax.add_patch(PathPatch(MplPath(verts, codes), facecolor=face,
127
+ edgecolor=edge, linewidth=lw,
128
+ joinstyle="round", capstyle="round",
129
+ zorder=1))
130
+ elif tag == "circle":
131
+ cx, cy, r = (float(el.get("cx", 0)), float(el.get("cy", 0)),
132
+ float(el.get("r", 0)))
133
+ ax.add_patch(Circle((cx * s + dx, cy * s + dy), r * s,
134
+ facecolor=face, edgecolor=edge, linewidth=lw,
135
+ zorder=1))
136
+ elif tag == "ellipse":
137
+ cx, cy = float(el.get("cx", 0)), float(el.get("cy", 0))
138
+ rx, ry = float(el.get("rx", 0)), float(el.get("ry", 0))
139
+ ax.add_patch(Ellipse((cx * s + dx, cy * s + dy), 2 * rx * s, 2 * ry * s,
140
+ facecolor=face, edgecolor=edge, linewidth=lw,
141
+ zorder=1))
142
+ elif tag == "rect":
143
+ x, y = float(el.get("x", 0)), float(el.get("y", 0))
144
+ w, h = float(el.get("width", 0)), float(el.get("height", 0))
145
+ rx = el.get("rx")
146
+ if rx:
147
+ r = float(rx) * s
148
+ ax.add_patch(FancyBboxPatch(
149
+ (x * s + dx + r, y * s + dy + r), w * s - 2 * r, h * s - 2 * r,
150
+ boxstyle=f"round,pad={r}", facecolor=face, edgecolor=edge,
151
+ linewidth=lw, zorder=1))
152
+ else:
153
+ ax.add_patch(Rectangle((x * s + dx, y * s + dy), w * s, h * s,
154
+ facecolor=face, edgecolor=edge,
155
+ linewidth=lw, zorder=1))
156
+ for child in el:
157
+ _draw(ax, child, st, dx, dy, s)
158
+
159
+
160
+ def load_svg_part(file, ports=None, name=None, scale=1.0, bridge=0, moves=None,
161
+ label_dy=None):
162
+ """读一个 hvacsvg 风格 SVG,返回可 ``d.add`` 的 Part。
163
+
164
+ :param ports: ``{连接点 id: 端口名}``,省略时原名收进端口表。
165
+ :param moves: ``{连接点 id: (x, y)}`` 覆盖连接点在 viewBox 里的坐标
166
+ (改接管位置)。端口偏移与 bridge 引管都按覆盖后的坐标算。
167
+ :param label_dy: 标签相对锚点的竖直偏移;None 画在符号下方(默认),
168
+ 传 0 表示画在符号中心(如风机盘管、水箱把字压在图元上)。
169
+ :param bridge: hvacsvg 的连接点落在 viewBox 边缘、符号图形并不画到边,
170
+ 给一个正数就从每个连接点沿边缘法向朝内补一段引管(符号单位),
171
+ 让 rrplot 的管路与符号图形接上。
172
+
173
+ 锚点取 viewBox 中心,端口偏移 = (x-w/2, y-h/2) * scale。
174
+ 标签按 Part 惯例画制;传 label=None/"" 时不画。
175
+ """
176
+ path = FilePath(file)
177
+ try:
178
+ raw_svg = path.read_bytes()
179
+ except OSError as exc:
180
+ raise OSError(f"无法读取 SVG 文件: {path}") from exc
181
+ if len(raw_svg) > _MAX_SVG_BYTES:
182
+ raise ValueError(
183
+ f"SVG 文件过大({len(raw_svg)} bytes),上限为 {_MAX_SVG_BYTES} bytes"
184
+ )
185
+ if _UNSAFE_XML.search(raw_svg):
186
+ raise ValueError("SVG 不允许包含 DOCTYPE 或 ENTITY 声明")
187
+ try:
188
+ root = ET.fromstring(raw_svg)
189
+ except ET.ParseError as exc:
190
+ raise ValueError(f"SVG XML 无法解析: {path}") from exc
191
+ vb = root.get("viewBox", "0 0 160 100").split()
192
+ w, h = float(vb[2]), float(vb[3])
193
+ cx, cy = w / 2.0, h / 2.0
194
+
195
+ raw = root.get("data-connection-points", "").strip() or "[]"
196
+ pts = []
197
+ for p in json.loads(raw): # ElementTree 已把 &quot; 反转义
198
+ pid, px, py = p["id"], float(p["x"]), float(p["y"])
199
+ if moves and pid in moves:
200
+ px, py = moves[pid]
201
+ pts.append((pid, px, py))
202
+ want = ports or {pid: pid for pid, _, _ in pts}
203
+
204
+ port_off = {want[pid]: ((px - cx) * scale, (py - cy) * scale)
205
+ for pid, px, py in pts if pid in want}
206
+ label = root.get("data-title", "") if name is None else name
207
+ default_dy = cy * scale + 24 if label_dy is None else label_dy
208
+
209
+ def draw(ax, x, y, label=None, **style):
210
+ ox, oy = x - cx * scale, y - cy * scale
211
+ for el in root:
212
+ _draw(ax, el, _DEFAULT_STYLE, ox, oy, scale)
213
+ if bridge:
214
+ for pid, px, py in pts:
215
+ if pid not in want:
216
+ continue
217
+ if px <= 0:
218
+ seg = ((px, py), (px + bridge, py))
219
+ elif px >= w:
220
+ seg = ((px, py), (px - bridge, py))
221
+ elif py <= 0:
222
+ seg = ((px, py), (px, py + bridge))
223
+ else:
224
+ seg = ((px, py), (px, py - bridge))
225
+ line(ax, [(vx * scale + ox, vy * scale + oy) for vx, vy in seg],
226
+ lw=LW_PIPE, color=LINE)
227
+ if label:
228
+ txt(ax, x, y + default_dy, label, size=17)
229
+
230
+ return Part(label, draw, port_off, {})