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/registry.py ADDED
@@ -0,0 +1,213 @@
1
+ """Web/JSON 图纸可编辑部件的注册表,不影响原有 parts API。"""
2
+ import copy
3
+ import math
4
+
5
+ from . import parts
6
+
7
+
8
+ def number(label, default, low=1, high=1000):
9
+ return dict(label=label, default=default, min=low, max=high, kind="number")
10
+
11
+
12
+ def choice(label, default, values):
13
+ return dict(label=label, default=default, options=list(values), kind="select")
14
+
15
+
16
+ def boolean(label, default=False):
17
+ return dict(label=label, default=default, kind="boolean", type="checkbox")
18
+
19
+
20
+ def integer(label, default, low, high):
21
+ return dict(number(label, default, low, high), kind="integer", step=1)
22
+
23
+
24
+ REGISTRY = {
25
+ "compressor": dict(label="压缩机", factory=parts.make_compressor, fields={
26
+ "r": number("半径", 42, 8, 250),
27
+ "style": choice("机身", "圆形", parts.COMPRESSOR_STYLES)}),
28
+ "heat_exchanger": dict(label="换热器", factory=parts.make_heat_exchanger,
29
+ fields={
30
+ "w": number("宽度", 160, 16, 700),
31
+ "h": number("高度", 56, 16, 700),
32
+ "shape": dict(choice("画法", "rect_x", parts.HEX_SHAPES),
33
+ optionLabels={"rect_diag": "单对角线",
34
+ "rect_x": "对角交叉",
35
+ "rect_zigzag7": "折线盘管",
36
+ "fan_coil": "风机盘管"}),
37
+ "orient": choice("折线盘管方向", "h", ["h", "v"]),
38
+ "stub": number("左右接管长度", 0, 0, 100)}),
39
+ "expansion_valve": dict(label="膨胀阀", factory=parts.make_expansion_valve_x,
40
+ fields={
41
+ "r": number("阀体半径 / 半宽", 10, 4, 80),
42
+ "orient": choice("连接方向", "v", ["h", "v"]),
43
+ "style": dict(choice("阀体样式", "circle_x", ["circle_x", "dome"]),
44
+ optionLabels={"circle_x": "圆圈 X",
45
+ "dome": "对顶三角+半圆穹顶"})}),
46
+ "vessel": dict(label="闪蒸罐", factory=parts.make_vessel, fields={
47
+ "w": number("宽度", 66, 16, 300),
48
+ "h": number("高度", 130, 20, 600),
49
+ "liquid": number("液位比例", 0.42, 0, 1)}),
50
+ "separator_utube": dict(label="气液分离器", factory=parts.make_separator_utube,
51
+ fields={
52
+ "w": number("宽度", 120, 40, 500),
53
+ "h": number("高度", 118, 40, 600),
54
+ "stub": number("接管长度", 16, 4, 100),
55
+ "flip": boolean("镜像进出管")}),
56
+ "intermediate_hex": dict(label="中间换热器",
57
+ factory=parts.make_intermediate_hex, fields={
58
+ "w": number("宽度", 80, 20, 500),
59
+ "h": number("高度", 190, 20, 600),
60
+ "drop": number("通道偏移", 0.275, 0.05, 0.45),
61
+ "orient": choice("通道方向", "v", ["h", "v"])}),
62
+ "four_way_valve": dict(label="四通换向阀",
63
+ factory=parts.make_four_way_round, fields={
64
+ "r": number("半径", 28, 8, 150),
65
+ "mark": boolean("显示 D/C/E/S 口标", True)}),
66
+ "globe_valve": dict(label="截止阀", factory=parts.make_globe_valve, fields={
67
+ "w": number("阀体宽度", 40, 16, 300),
68
+ "h": number("阀体高度", 24, 12, 180),
69
+ "stem": number("阀杆长度", 14, 4, 100),
70
+ "handle": number("手轮宽度", 28, 8, 240)}),
71
+ "solenoid_valve": dict(label="电磁阀",
72
+ factory=parts.make_solenoid_valve, fields={
73
+ "r": number("阀体半径 / 半宽", 16, 6, 120),
74
+ "stem": number("引线长度", 12, 4, 100),
75
+ "handle": number("线圈横杠宽度", 26, 8, 240),
76
+ "style": dict(choice("阀体样式", "circle_x", ["circle_x", "bowtie"]),
77
+ optionLabels={"circle_x": "圆圈 X+横杆",
78
+ "bowtie": "对顶三角+横杆+Σ 折线"})}),
79
+ "check_valve": dict(label="单向阀", factory=parts.make_check_valve, fields={
80
+ "w": number("阀体宽度", 40, 16, 300),
81
+ "h": number("阀体高度", 24, 12, 180),
82
+ "stub": number("接管长度", 10, 4, 100),
83
+ "point": choice("流通方向(e 右 / w 左)", "e", ["e", "w"]),
84
+ "style": dict(choice("阀体样式", "solid", ["solid", "hollow"]),
85
+ optionLabels={"solid": "黑色实心", "hollow": "空心黑框"})}),
86
+ "filter": dict(label="过滤器", factory=parts.make_filter, fields={
87
+ "w": number("宽度", 48, 16, 300),
88
+ "h": number("高度", 26, 12, 180),
89
+ "stub": number("接管长度", 10, 4, 100),
90
+ "n": integer("网格线数", 7, 3, 25)}),
91
+ "oil_separator": dict(label="油分离器", factory=parts.make_oil_separator,
92
+ fields={
93
+ "w": number("宽度", 40, 16, 300),
94
+ "h": number("高度", 100, 20, 600),
95
+ "stub": number("接管长度", 12, 4, 100)}),
96
+ "capillary": dict(label="毛细管", factory=parts.make_capillary, fields={
97
+ "w": number("宽度", 18, 6, 100),
98
+ "h": number("高度", 80, 16, 400),
99
+ "n": integer("圈数", 5, 1, 25)}),
100
+ "fan_coil": dict(label="室内风机盘管", factory=parts.make_fan_coil,
101
+ legacy=True, fields={
102
+ "w": number("宽度", 120, 40, 600),
103
+ "h": number("高度", 64, 24, 400),
104
+ "stub": number("接管长度", 12, 4, 100)}),
105
+ "muffler": dict(label="消音器", factory=parts.make_muffler, fields={
106
+ "w": number("宽度", 36, 12, 200),
107
+ "h": number("高度", 72, 16, 400),
108
+ "stub": number("接管长度", 12, 4, 100)}),
109
+ "sensor": dict(label="温度/压力传感器", factory=parts.make_sensor, fields={
110
+ "r": number("半径", 14, 8, 80),
111
+ "stub": number("测量接管长度", 12, 4, 100),
112
+ "mark": choice("测量类型", "T", ["T", "P"])}),
113
+ }
114
+
115
+
116
+ def catalog():
117
+ """仅返回 JSON 可序列化的描述。"""
118
+ return [dict(type=key, label=item["label"],
119
+ fields=copy.deepcopy(item["fields"]))
120
+ for key, item in REGISTRY.items() if not item.get("legacy")]
121
+
122
+
123
+ def normalize_params(kind, params):
124
+ if not isinstance(kind, str) or kind not in REGISTRY:
125
+ raise ValueError(f"未知图元: {kind}")
126
+ if not isinstance(params, dict):
127
+ raise ValueError("params 必须是对象")
128
+ fields = REGISTRY[kind]["fields"]
129
+ if set(params) - set(fields):
130
+ raise ValueError(f"未知参数: {', '.join(sorted(set(params) - set(fields)))}")
131
+ result = {}
132
+ for key, field in fields.items():
133
+ value = params.get(key, field["default"])
134
+ if field["kind"] == "boolean":
135
+ if not isinstance(value, bool):
136
+ raise ValueError(f"{key} 必须为布尔值")
137
+ elif field["kind"] == "select":
138
+ if value not in field["options"]:
139
+ raise ValueError(f"{key} 必须为 {field['options']} 之一")
140
+ elif (isinstance(value, bool) or not isinstance(value, (int, float))
141
+ or not math.isfinite(value)
142
+ or not field["min"] <= value <= field["max"]):
143
+ raise ValueError(f"{key} 必须在 {field['min']}~{field['max']} 之间")
144
+ elif field["kind"] == "integer":
145
+ if int(value) != value:
146
+ raise ValueError(f"{key} 必须为整数")
147
+ value = int(value)
148
+ result[key] = value
149
+ if kind == "vessel" and result["h"] < result["w"]:
150
+ raise ValueError("闪蒸罐高度不能小于宽度")
151
+ return result
152
+
153
+
154
+ def make_registered(kind, params):
155
+ return REGISTRY[kind]["factory"](**normalize_params(kind, params))
156
+
157
+
158
+ def describe(kind, params):
159
+ """返回以中心为原点的尺寸、端口和法向;SVG 由 renderer 生成。"""
160
+ params = normalize_params(kind, params)
161
+ part = make_registered(kind, params)
162
+ if kind in ("compressor", "expansion_valve", "four_way_valve",
163
+ "solenoid_valve", "sensor"):
164
+ w = 2 * params["r"]
165
+ h = w
166
+ if kind == "compressor" and params["style"] == "方形":
167
+ w = params["r"]
168
+ else:
169
+ w, h = params["w"], params["h"]
170
+ left, top, right, bottom = -w / 2, -h / 2, w / 2, h / 2
171
+ if kind == "expansion_valve" and params["style"] == "dome":
172
+ if params["orient"] == "h":
173
+ top = -1.65 * params["r"]
174
+ bottom = -top
175
+ else:
176
+ right = 1.65 * params["r"]
177
+ left = -right
178
+ elif kind == "separator_utube":
179
+ top -= params["stub"]
180
+ elif kind == "four_way_valve" and params["mark"]:
181
+ left -= 30
182
+ right += 30
183
+ top -= 30
184
+ bottom += 30
185
+ elif kind == "solenoid_valve" and params["style"] == "bowtie":
186
+ extent = max(params["r"] + 12, params["handle"] * 26/48)
187
+ left, right = -extent, extent
188
+ top = -params["r"] - params["stem"]
189
+ bottom = -top
190
+ elif kind in ("globe_valve", "solenoid_valve"):
191
+ left = min(left - 12, -params["handle"] / 2)
192
+ right = max(right + 12, params["handle"] / 2)
193
+ top -= params["stem"]
194
+ elif kind in ("check_valve", "filter"):
195
+ left -= params["stub"]
196
+ right += params["stub"]
197
+ elif kind == "oil_separator":
198
+ left -= params["stub"]
199
+ top -= params["stub"]
200
+ bottom += params["stub"]
201
+ elif kind in ("fan_coil", "heat_exchanger"):
202
+ left -= params["stub"]
203
+ right += params["stub"]
204
+ elif kind == "muffler":
205
+ top -= params["stub"]
206
+ bottom += params["stub"]
207
+ elif kind == "sensor":
208
+ bottom += params["stub"]
209
+ return dict(width=w, height=h, box=[left - 3, top - 3,
210
+ right - left + 6, bottom - top + 6],
211
+ ports={key: dict(point=list(point),
212
+ direction=list(part.direction(key)))
213
+ for key, point in part.ports.items()})
rrplot/scene.py ADDED
@@ -0,0 +1,255 @@
1
+ """版本化图纸模型和纯几何解析;不改动原有 Port 快照语义。"""
2
+ import copy
3
+ import json
4
+ import math
5
+ from importlib.resources import files
6
+
7
+ from matplotlib.colors import is_color_like
8
+
9
+ from .core import _orthogonalize, _polyline_point
10
+ from .registry import describe, normalize_params
11
+
12
+ SCHEMA_VERSION = 1
13
+ MOUNT_TYPES = {"expansion_valve", "globe_valve", "solenoid_valve",
14
+ "check_valve", "filter", "capillary", "muffler"}
15
+ TEMPLATES = {
16
+ "evi_ftvi": "EVI 过冷器喷气增焓",
17
+ "ftvi": "FTVI 闪蒸罐喷气增焓",
18
+ "heat_pump": "普通热泵循环",
19
+ "heat_pump_receiver": "带气液分离器的普通热泵",
20
+ "evi_intermediate": "EVI 中间换热器喷气增焓",
21
+ "reversible_heat_pump_heating": "四通阀热泵(制热)",
22
+ "reversible_heat_pump_cooling": "四通阀热泵(制冷)",
23
+ "vrf_multisplit_cooling": "VRF 多联机(制冷)",
24
+ "vrf_multisplit_evi_heating": "VRF 多联机(EVI 制热)",
25
+ }
26
+
27
+
28
+ def load_template(name):
29
+ if name not in TEMPLATES:
30
+ raise ValueError(f"未知模板: {name}")
31
+ raw = files("rrplot").joinpath("templates").joinpath(name + ".json").read_text(
32
+ encoding="utf-8")
33
+ return validate_scene(json.loads(raw))
34
+
35
+
36
+ def finite(value, label, low=-100000, high=100000):
37
+ if (isinstance(value, bool) or not isinstance(value, (int, float))
38
+ or not math.isfinite(value) or not low <= value <= high):
39
+ raise ValueError(f"{label} 必须为 {low}~{high} 的有限数字")
40
+ return value
41
+
42
+
43
+ def color(value, label):
44
+ if not isinstance(value, str) or not is_color_like(value):
45
+ raise ValueError(f"{label} 必须是有效颜色,如 #111111")
46
+
47
+
48
+ def validate_scene(document):
49
+ """复制并规范图纸;无效引用明确报错,不静默丢弃数据。"""
50
+ if not isinstance(document, dict) or document.get("schemaVersion") != 1:
51
+ raise ValueError("仅支持 schemaVersion=1 的图纸")
52
+ d = copy.deepcopy(document)
53
+ if not isinstance(d.get("title", ""), str):
54
+ raise ValueError("图纸名称必须是文字")
55
+ d.setdefault("title", "未命名图纸")
56
+ page = d.setdefault("page", {})
57
+ if not isinstance(page, dict):
58
+ raise ValueError("page 必须为对象")
59
+ for key, default in (("width", 760), ("height", 580)):
60
+ finite(page.setdefault(key, default), "页面 " + key, 100, 4000)
61
+ ids = set()
62
+ for collection in ("nodes", "edges", "junctions", "labels"):
63
+ items = d.setdefault(collection, [])
64
+ if not isinstance(items, list) or len(items) > 2000:
65
+ raise ValueError(f"{collection} 必须为数组且不超过 2000 项")
66
+ for item in items:
67
+ if not isinstance(item, dict):
68
+ raise ValueError(f"{collection} 各项必须为对象")
69
+ key = item.get("id")
70
+ if not isinstance(key, str) or not key or key in ids:
71
+ raise ValueError("对象 ID 必须为非空、不重复的字符串")
72
+ ids.add(key)
73
+ nodes = {n["id"]: n for n in d["nodes"]}
74
+ junctions = {j["id"]: j for j in d["junctions"]}
75
+ edge_ids = {edge["id"] for edge in d["edges"]}
76
+ descriptions = {}
77
+ legacy_fan_coils = set()
78
+ for node in d["nodes"]:
79
+ if node.get("type") == "fan_coil":
80
+ params = normalize_params("fan_coil", node.get("params", {}))
81
+ node["type"] = "heat_exchanger"
82
+ node["params"] = dict(params, shape="fan_coil", orient="h")
83
+ legacy_fan_coils.add(node["id"])
84
+ node["params"] = normalize_params(node.get("type"), node.get("params", {}))
85
+ descriptions[node["id"]] = describe(node["type"], node["params"])
86
+ if not isinstance(node.setdefault("title", node["type"]), str):
87
+ raise ValueError("设备名称必须是文字")
88
+ for axis in ("x", "y"):
89
+ finite(node.get(axis), "设备 " + axis)
90
+ angle = node.setdefault("rotation", 0)
91
+ if angle not in (0, 90, 180, 270):
92
+ raise ValueError("旋转角必须为 0、90、180、270")
93
+ for junction in d["junctions"]:
94
+ for axis in ("x", "y"):
95
+ finite(junction.get(axis), "三通 " + axis)
96
+ for edge in d["edges"]:
97
+ for side in ("source", "target"):
98
+ ref = edge.get(side)
99
+ if (isinstance(ref, dict) and isinstance(ref.get("nodeId"), str)
100
+ and ref["nodeId"] in legacy_fan_coils):
101
+ ref["portId"] = {"in": "left", "out": "right"}.get(
102
+ ref.get("portId"), ref.get("portId"))
103
+ if not isinstance(ref, dict):
104
+ raise ValueError("管路必须引用设备端口或三通")
105
+ if "junctionId" in ref and set(ref) == {"junctionId"}:
106
+ if ref["junctionId"] not in junctions:
107
+ raise ValueError("管路引用了不存在的三通")
108
+ elif set(ref) == {"nodeId", "portId"} and ref["nodeId"] in nodes:
109
+ if nodes[ref["nodeId"]].get("mount") is not None:
110
+ raise ValueError("挂接阀件属于管路附件,不能同时作为独立管路端点")
111
+ if ref["portId"] not in descriptions[ref["nodeId"]]["ports"]:
112
+ raise ValueError("管路引用了不存在的端口")
113
+ else:
114
+ raise ValueError("管路引用了不存在的设备或端口")
115
+ vertices = edge.setdefault("vertices", [])
116
+ if not isinstance(vertices, list) or len(vertices) > 100:
117
+ raise ValueError("每条管路顶点必须为数组,最多 100 项")
118
+ for point in vertices:
119
+ if not isinstance(point, list) or len(point) != 2:
120
+ raise ValueError("顶点必须为 [x,y]")
121
+ for val in point:
122
+ finite(val, "顶点")
123
+ finite(edge.setdefault("width", 1.8), "线宽", 0.2, 8)
124
+ color(edge.setdefault("color", "#111111"), "管路颜色")
125
+ if edge.setdefault("linestyle", "solid") not in ("solid", "dashed"):
126
+ raise ValueError("线型必须为 solid 或 dashed")
127
+ if not isinstance(edge.setdefault("head", True), bool):
128
+ raise ValueError("箭头选项必须为布尔值")
129
+ heads = edge.setdefault("headAt", [0.55])
130
+ if not isinstance(heads, list) or len(heads) > 10:
131
+ raise ValueError("箭头位置必须为数组,最多 10 项")
132
+ for head in heads:
133
+ finite(head, "箭头位置", 0, 1)
134
+ mounted = [n for n in d["nodes"] if "mount" in n]
135
+ for node in mounted:
136
+ mount = node["mount"]
137
+ if (node["type"] not in MOUNT_TYPES or not isinstance(mount, dict)
138
+ or set(mount) - {"edgeId", "at", "reverse"}):
139
+ raise ValueError("无效的阀件挂接配置")
140
+ if not isinstance(mount.get("edgeId"), str) or mount["edgeId"] not in edge_ids:
141
+ raise ValueError("挂接管路不存在")
142
+ finite(mount.setdefault("at", 0.5), "挂接位置", 0, 1)
143
+ if not isinstance(mount.setdefault("reverse", False), bool):
144
+ raise ValueError("挂接反向必须为布尔值")
145
+ if mounted:
146
+ geometry_nodes = {key: dict(n, geometry=descriptions[key])
147
+ for key, n in nodes.items()}
148
+ paths = {e["id"]: route(endpoint(e["source"], geometry_nodes, junctions),
149
+ endpoint(e["target"], geometry_nodes, junctions),
150
+ e["vertices"]) for e in d["edges"]}
151
+ for node in mounted:
152
+ node.update(mount_pose(node, descriptions[node["id"]],
153
+ paths[node["mount"]["edgeId"]]))
154
+ for label in d["labels"]:
155
+ if not isinstance(label.get("text"), str) or len(label["text"]) > 1000:
156
+ raise ValueError("标签内容必须为不超过 1000 字的文字")
157
+ for axis in ("x", "y"):
158
+ finite(label.setdefault(axis, 0), "标签 " + axis)
159
+ finite(label.setdefault("size", 15), "字号", 6, 72)
160
+ if label.setdefault("ha", "center") not in ("left", "center", "right"):
161
+ raise ValueError("标签对齐方式无效")
162
+ if not isinstance(label.setdefault("boxed", False), bool):
163
+ raise ValueError("标签背景必须为布尔值")
164
+ color(label.setdefault("color", "#111111"), "标签颜色")
165
+ if "nodeId" in label and label["nodeId"] not in nodes:
166
+ raise ValueError("标签引用了不存在的设备")
167
+ if "edgeId" in label:
168
+ if "nodeId" in label:
169
+ raise ValueError("标签不能同时附着于设备和管路")
170
+ if (not isinstance(label["edgeId"], str)
171
+ or label["edgeId"] not in edge_ids):
172
+ raise ValueError("标签引用了不存在的管路")
173
+ finite(label.setdefault("at", 0.5), "状态点位置", 0, 1)
174
+ return d
175
+
176
+
177
+ def rotate(point, angle):
178
+ c = round(math.cos(math.radians(angle)), 12)
179
+ s = round(math.sin(math.radians(angle)), 12)
180
+ x, y = point
181
+ return [round(c * x - s * y, 8), round(s * x + c * y, 8)]
182
+
183
+
184
+ def mount_pose(node, geometry, points):
185
+ """附件按管路弧长定位,in→out 跟随管路方向;不拆分父管路。"""
186
+ if not any(a != b for a, b in zip(points, points[1:])):
187
+ raise ValueError("管路长度为零,无法挂接阀件")
188
+ point, direction = _polyline_point(points, node["mount"]["at"])[0:2]
189
+ a, b = (geometry["ports"][p]["point"] for p in ("in", "out"))
190
+ native = math.degrees(math.atan2(b[1] - a[1], b[0] - a[0]))
191
+ tangent = math.degrees(math.atan2(direction[1], direction[0]))
192
+ angle = round((tangent - native) / 90) * 90
193
+ if node["mount"]["reverse"]:
194
+ angle += 180
195
+ return dict(x=point[0], y=point[1], rotation=angle % 360)
196
+
197
+
198
+ def endpoint(ref, nodes, junctions):
199
+ if "junctionId" in ref:
200
+ j = junctions[ref["junctionId"]]
201
+ return dict(point=[j["x"], j["y"]], direction=[0, 0])
202
+ node = nodes[ref["nodeId"]]
203
+ port = node["geometry"]["ports"][ref["portId"]]
204
+ offset = rotate(port["point"], node["rotation"])
205
+ return dict(point=[node["x"] + offset[0], node["y"] + offset[1]],
206
+ direction=rotate(port["direction"], node["rotation"]))
207
+
208
+
209
+ def route(source, target, vertices):
210
+ """带法向引管的正交路径;正式输出和浏览器临时几何共用规则。"""
211
+ a, b = source["point"], target["point"]
212
+ ad, bd = source["direction"], target["direction"]
213
+ delta = [b[0] - a[0], b[1] - a[1]]
214
+ if not vertices and (a[0] == b[0] or a[1] == b[1]):
215
+ if (sum(x * y for x, y in zip(ad, delta)) >= 0
216
+ and sum(x * y for x, y in zip(bd, delta)) <= 0):
217
+ return [a, b]
218
+ pts = [a]
219
+ if any(ad):
220
+ pts.append([a[i] + ad[i] * 20 for i in (0, 1)])
221
+ pts.extend(vertices)
222
+ if any(bd):
223
+ pts.append([b[i] + bd[i] * 20 for i in (0, 1)])
224
+ pts.append(b)
225
+ result = []
226
+ for point in _orthogonalize(pts):
227
+ point = list(point)
228
+ if not result or point != result[-1]:
229
+ result.append(point)
230
+ return result if len(result) > 1 else [a, b]
231
+
232
+
233
+ def resolve_scene(document):
234
+ d = validate_scene(document)
235
+ nodes = {n["id"]: dict(n, geometry=describe(n["type"], n["params"]))
236
+ for n in d["nodes"]}
237
+ junctions = {j["id"]: j for j in d["junctions"]}
238
+ edges = []
239
+ for edge in d["edges"]:
240
+ a = endpoint(edge["source"], nodes, junctions)
241
+ b = endpoint(edge["target"], nodes, junctions)
242
+ edges.append(dict(edge, points=route(a, b, edge["vertices"])))
243
+ labels = []
244
+ edge_points = {edge["id"]: edge["points"] for edge in edges}
245
+ for label in d["labels"]:
246
+ x, y = label["x"], label["y"]
247
+ if "nodeId" in label:
248
+ node = nodes[label["nodeId"]]
249
+ x, y = rotate([x, y], node["rotation"])
250
+ x, y = x + node["x"], y + node["y"]
251
+ elif "edgeId" in label:
252
+ px, py = _polyline_point(edge_points[label["edgeId"]], label["at"])[0]
253
+ x, y = x + px, y + py
254
+ labels.append(dict(label, position=[x, y]))
255
+ return dict(document=d, nodes=list(nodes.values()), edges=edges, labels=labels)
@@ -0,0 +1,137 @@
1
+ """将可编辑 JSON 图纸适配为现有 Matplotlib 绘图。"""
2
+ import base64
3
+ import io
4
+ import json
5
+ from functools import lru_cache
6
+
7
+ import matplotlib as mpl
8
+ from matplotlib.patches import Circle, Rectangle
9
+ from matplotlib.transforms import Affine2D
10
+
11
+ from .core import Diagram
12
+ from .registry import describe, make_registered
13
+ from .scene import resolve_scene
14
+ from .style import FONT_STACK
15
+
16
+
17
+ @lru_cache(maxsize=256)
18
+ def _glyph(kind, params_json):
19
+ params = json.loads(params_json)
20
+ geometry = describe(kind, params)
21
+ x, y, w, h = geometry["box"]
22
+ with Diagram(width=w, height=h) as diagram:
23
+ diagram.add(make_registered(kind, params), None, loc=(-x, -y))
24
+ diagram.render()
25
+ out = io.BytesIO()
26
+ with mpl.rc_context({"svg.hashsalt": "rrplot-web"}):
27
+ diagram.fig.savefig(out, format="svg", transparent=True,
28
+ metadata={"Date": None})
29
+ return "data:image/svg+xml;base64," + base64.b64encode(out.getvalue()).decode()
30
+
31
+
32
+ def resolve_for_editor(document):
33
+ result = resolve_scene(document)
34
+ for node in result["nodes"]:
35
+ node["geometry"]["image"] = _glyph(
36
+ node["type"], json.dumps(node["params"], sort_keys=True))
37
+ result["fontFamily"] = ", ".join(FONT_STACK)
38
+ result["features"] = ["edgeLabels", "pipeMounts"]
39
+ return result
40
+
41
+
42
+ def _rotated(part, angle):
43
+ if angle == 0:
44
+ return part
45
+
46
+ def draw(ax, x, y, label=None, **kw):
47
+ before_lines, before_patches = len(ax.lines), len(ax.patches)
48
+ before_texts = len(ax.texts)
49
+ part.draw(ax, x, y, label=None)
50
+ transform = Affine2D().rotate_deg_around(x, y, angle) + ax.transData
51
+ for artist in (list(ax.lines)[before_lines:]
52
+ + list(ax.patches)[before_patches:]):
53
+ artist.set_transform(transform)
54
+ for text in list(ax.texts)[before_texts:]:
55
+ text.set_transform(transform)
56
+ text.set_rotation(text.get_rotation() - angle)
57
+ text.set_rotation_mode("anchor")
58
+
59
+ from .part import Part
60
+ return Part(part.name, draw, {})
61
+
62
+
63
+ def _node_part(node):
64
+ """只校正阀顶执行机构朝向,保留场景端口、挂接及标签旋转。"""
65
+ params = node["params"]
66
+ angle = node["rotation"]
67
+ if node["type"] == "expansion_valve" and params["style"] == "dome":
68
+ if (angle + (90 if params["orient"] == "v" else 0)) % 360 >= 180:
69
+ angle = (angle + 180) % 360
70
+ elif node["type"] == "solenoid_valve" and params["style"] == "bowtie":
71
+ angle %= 180
72
+ return _rotated(make_registered(node["type"], params), angle)
73
+
74
+
75
+ def build_scene(document):
76
+ resolved = resolve_scene(document)
77
+ d = resolved["document"]
78
+ diagram = Diagram(width=d["page"]["width"], height=d["page"]["height"])
79
+ try:
80
+ for node in resolved["nodes"]:
81
+ if node.get("mount"):
82
+ continue
83
+ diagram.add(_node_part(node), None,
84
+ loc=(node["x"], node["y"]))
85
+ for edge in resolved["edges"]:
86
+ points = edge["points"]
87
+ diagram.pipe(points[0], points[-1], via=points[1:-1],
88
+ head=edge["head"], head_at=edge["headAt"],
89
+ lw=edge["width"], color=edge["color"],
90
+ linestyle=edge["linestyle"])
91
+ diagram.render()
92
+ # Accessories sit above their parent pipe in both editor and exports.
93
+ # An opaque body mask removes the pipe and arrow beneath the symbol.
94
+ for node in resolved["nodes"]:
95
+ if not node.get("mount"):
96
+ continue
97
+ x, y = node["x"], node["y"]
98
+ p = node["params"]
99
+ w, h = (2*p["r"], 2*p["r"]) if "r" in p else (p["w"], p["h"])
100
+ transform = Affine2D().rotate_deg_around(x, y, node["rotation"])
101
+ mask = Rectangle((x-w/2, y-h/2), w, h, facecolor="white",
102
+ edgecolor="none", zorder=8,
103
+ transform=transform + diagram.ax.transData)
104
+ diagram.ax.add_patch(mask)
105
+ lines, patches = len(diagram.ax.lines), len(diagram.ax.patches)
106
+ _node_part(node).draw(diagram.ax, x, y, label=None)
107
+ artists = (list(diagram.ax.lines)[lines:]
108
+ + list(diagram.ax.patches)[patches:])
109
+ for artist in artists:
110
+ artist.set_zorder(9)
111
+ for junction in d["junctions"]:
112
+ diagram.ax.add_patch(Circle((junction["x"], junction["y"]), 4,
113
+ facecolor="#111111", edgecolor="none",
114
+ zorder=6))
115
+ for label in resolved["labels"]:
116
+ diagram.text(*label["position"], label["text"], size=label["size"],
117
+ ha=label["ha"], color=label["color"], boxed=label["boxed"])
118
+ return diagram
119
+ except Exception:
120
+ diagram.close()
121
+ raise
122
+
123
+
124
+ def export_scene(document, fmt="svg", dpi=140):
125
+ if fmt not in ("svg", "png", "pdf"):
126
+ raise ValueError("导出格式仅支持 SVG、PNG、PDF")
127
+ if (isinstance(dpi, bool) or not isinstance(dpi, (int, float))
128
+ or not 72 <= dpi <= 600):
129
+ raise ValueError("DPI 必须在 72~600 之间")
130
+ with build_scene(document) as diagram:
131
+ if fmt == "png" and diagram.W * diagram.H * (dpi / 100) ** 2 > 40000000:
132
+ raise ValueError("位图尺寸过大,请减小页面或 DPI")
133
+ out = io.BytesIO()
134
+ with mpl.rc_context({"svg.hashsalt": "rrplot-web"}):
135
+ options = {"metadata": {"Date": None}} if fmt == "svg" else {}
136
+ diagram.fig.savefig(out, format=fmt, dpi=dpi, **options)
137
+ return out.getvalue()