dsh-origin-bridge 0.0.0-stage → 0.4.0

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.
package/originlab.py ADDED
@@ -0,0 +1,1506 @@
1
+ """Origin automation engine.
2
+
3
+ Every COM call is marshalled onto one dedicated worker thread: comtypes/COM is
4
+ thread-affine, and driving Origin from the stdio reader thread is what makes
5
+ other bridges hang.
6
+
7
+ Object references handed to the model are opaque handles ("ws-1", "gr-2") backed
8
+ by a registry, because parsing Origin's own [Book]Sheet! range strings back and
9
+ forth is the most common source of silent failures.
10
+ """
11
+
12
+ import os
13
+ import queue
14
+ import re
15
+ import struct
16
+ import sys
17
+ import threading
18
+ import time
19
+
20
+ import asciiio
21
+ import binio
22
+
23
+ MISSING_SENTINEL = -1.23456789e-300
24
+ # Verified against OriginPro 2024 SR1 by exporting each code and looking at the
25
+ # image: 200 line, 201 symbol, 202 line+symbol, 203 column.
26
+ PLOT_CODES = {"line": 200, "scatter": 201, "line_symbol": 202, "column": 203}
27
+ # Same four kinds as the letters add_plot() takes (verified by viewing the export).
28
+ PLOT_LETTERS = {"line": "l", "scatter": "s", "line_symbol": "y", "column": "c"}
29
+ # originpro passes this integer straight to layadd, and the layer's own name is the
30
+ # proof: read back as BottomXLeftY/TopX/RightY/LeftY/TopXRightY/BottomXRightY/Inset.
31
+ LAYER_TYPES = {"bottom_left": 0, "top": 1, "right": 2, "left": 3,
32
+ "top_right": 4, "bottom_right": 5, "inset": 6}
33
+ # What Origin itself calls each layer, read back from layer.name after add_layer.
34
+ LAYER_NAME_BY_CODE = {0: "BottomXLeftY", 1: "TopX", 2: "RightY", 3: "LeftY",
35
+ 4: "TopXRightY", 5: "BottomXRightY", 6: "Inset"}
36
+ # originpro's scale setter takes a name but the getter returns the int.
37
+ SCALE_TYPES = {"linear": 1, "log10": 2, "probability": 3, "probit": 4, "reciprocal": 5,
38
+ "offset_reciprocal": 6, "logit": 7, "ln": 8, "log2": 9}
39
+ # new_graph(template=NAME) accepts these OriginPro 2024 template stems (extension
40
+ # optional) and returns None for an unknown one, which is how they get validated.
41
+ GRAPH_TEMPLATES = ("line", "scatter", "linesymb", "column", "doubley", "dply",
42
+ "heat_map", "cmap", "mesh", "contline", "contgray", "3d",
43
+ "glwireface", "pie", "box", "histdist", "polar", "ternary",
44
+ "vector", "errbar")
45
+ # NLFit(func) raises "Invalid fitting function" for anything not installed, so
46
+ # these were each constructed successfully on OriginPro 2024 SR1.
47
+ FIT_PRESETS = {"gauss": "Gauss", "gaussian": "Gauss", "lorentz": "Lorentz",
48
+ "voigt": "Voigt", "expdec1": "ExpDec1", "expdec2": "ExpDec2",
49
+ "sine": "Sine", "power": "Power", "logistic": "Logistic",
50
+ "boltzmann": "Boltzmann", "doseresp": "DoseResp", "cubic": "Cubic"}
51
+ # Legend anchors are layer DATA coordinates (Legend.x/.y read back exactly), so a
52
+ # position is a fraction of the axis span rather than a page measurement.
53
+ LEGEND_POSITIONS = {
54
+ "top_left": (-0.30, 1.10), "top": (0.50, 1.10), "top_right": (1.30, 1.10),
55
+ "left": (-0.30, 0.50), "right": (1.30, 0.50),
56
+ "bottom_left": (-0.30, -0.10), "bottom": (0.50, -0.10), "bottom_right": (1.30, -0.10),
57
+ "inside_top_left": (0.12, 0.88), "inside_top_right": (0.88, 0.88),
58
+ "inside_bottom_left": (0.12, 0.12), "inside_bottom_right": (0.88, 0.12),
59
+ "inside": (0.75, 0.80),
60
+ }
61
+ IMAGE_MAGIC = {".png": b"\x89PNG\r\n\x1a\n", ".tif": b"II*\x00", ".tiff": b"II*\x00",
62
+ ".pdf": b"%PDF", ".svg": b"<", ".emf": b"\x01\x00\x00\x00"}
63
+ ASCII_EXTS = (".dat", ".csv", ".txt", ".tsv")
64
+
65
+
66
+ class OriginError(Exception):
67
+ def __init__(self, code, message, next_actions=(), **extra):
68
+ super().__init__(message)
69
+ self.code = code
70
+ self.message = message
71
+ self.next_actions = list(next_actions)
72
+ self.extra = extra
73
+
74
+
75
+ # ---------------------------------------------------------------- COM thread
76
+
77
+ _q = queue.Queue()
78
+ _thread = None
79
+ _thread_lock = threading.Lock()
80
+ _op = None
81
+
82
+
83
+ def _worker():
84
+ while True:
85
+ fn, args, kwargs, box = _q.get()
86
+ try:
87
+ box["value"] = fn(*args, **kwargs)
88
+ except BaseException as exc: # re-raised on the caller's thread
89
+ box["error"] = exc
90
+ box["done"].set()
91
+
92
+
93
+ def call(fn, *args, timeout=240, **kwargs):
94
+ global _thread
95
+ with _thread_lock:
96
+ if _thread is None or not _thread.is_alive():
97
+ _thread = threading.Thread(target=_worker, daemon=True, name="origin-com")
98
+ _thread.start()
99
+ box = {"done": threading.Event()}
100
+ _q.put((fn, args, kwargs, box))
101
+ if not box["done"].wait(timeout):
102
+ raise OriginError(
103
+ "com_timeout",
104
+ "Origin 在 %d 秒内没有响应" % timeout,
105
+ ["看 Origin 窗口是否卡在对话框或许可证弹窗", "任务管理器结束 Origin64.exe 后重试"],
106
+ )
107
+ if "error" in box:
108
+ raise box["error"]
109
+ return box["value"]
110
+
111
+
112
+ def origin():
113
+ """Import originpro and force the COM connection (launches Origin if needed)."""
114
+ global _op
115
+ if _op is not None:
116
+ return _op
117
+ try:
118
+ import originpro as op
119
+ except ImportError as exc:
120
+ raise OriginError("missing_originpro", "这个 Python 环境里没有 originpro:%s" % exc,
121
+ ["pip install originpro"])
122
+ try:
123
+ op.path()
124
+ except Exception as exc:
125
+ raise OriginError(
126
+ "connection_error",
127
+ "连不上 Origin 自动化服务器:%s" % exc,
128
+ ["确认装了 Origin/OriginPro 2021 或更高(originpro 的硬性下限)",
129
+ "确认 Origin 与 Python 都是 64 位",
130
+ "若任务管理器里有多个 Origin64.exe,只保留一个",
131
+ "长会话攒页面后桥会坏:先 origin_exit 让插件重启 Origin"],
132
+ )
133
+ _op = op
134
+ return op
135
+
136
+
137
+ # ---------------------------------------------------------------- handles
138
+
139
+ _handles = {}
140
+ _names = {}
141
+ _seq = [0]
142
+ _project_file = ""
143
+
144
+
145
+ def _bind(kind, obj, name=""):
146
+ """Hand back an opaque handle, remembering the page name WITHOUT a COM call.
147
+
148
+ Reading .name later can hit a destroyed page and leave a C-level error pending,
149
+ which then surfaces as a confusing SystemError from an unrelated len() call.
150
+ """
151
+ _seq[0] += 1
152
+ ref = "%s-%d" % (kind, _seq[0])
153
+ _handles[ref] = obj
154
+ _names[ref] = name or ""
155
+ return ref
156
+
157
+
158
+ def _resolve(kind, ref):
159
+ """Handle-table lookup only. Never touches COM: the caller may be on the
160
+ server thread, and origin() must run on the COM thread (see _graph_of)."""
161
+ if ref is None:
162
+ return None
163
+ if not isinstance(ref, str):
164
+ return ref
165
+ return _handles.get(ref)
166
+
167
+
168
+ def _graph_of(op, ref):
169
+ """Resolve a graph handle. Must be called ON the COM thread: _resolve's
170
+ fallback used to call origin() from the caller thread, which initialised COM
171
+ on the wrong apartment while still working by luck."""
172
+ if not ref:
173
+ return _safe(lambda: op.find_graph(""))
174
+ if not isinstance(ref, str):
175
+ return ref
176
+ obj = _handles.get(ref)
177
+ if obj is not None:
178
+ return obj
179
+ if ref.startswith("gr-"):
180
+ # An unknown handle must NOT fall back to the active page: previewing or
181
+ # exporting some other graph while claiming success is worse than failing.
182
+ return None
183
+ return _safe(lambda: op.find_graph(ref))
184
+
185
+
186
+ def sanitize(obj):
187
+ """Origin encodes missing numbers as -1.23456789e-300; never leak that upstream."""
188
+ if isinstance(obj, dict):
189
+ return {k: sanitize(v) for k, v in obj.items()}
190
+ if isinstance(obj, (list, tuple)):
191
+ return [sanitize(v) for v in obj]
192
+ if isinstance(obj, float) and (obj != obj or abs(obj - MISSING_SENTINEL) < 1e-310):
193
+ return None
194
+ return obj
195
+
196
+
197
+ def _safe(fn, default=None):
198
+ try:
199
+ return fn()
200
+ except Exception:
201
+ return default
202
+
203
+
204
+ def _round2(v):
205
+ try:
206
+ return round(float(v), 2)
207
+ except (TypeError, ValueError):
208
+ return None
209
+
210
+
211
+ def _col_index(ws, col):
212
+ ncol = int(_safe(lambda: ws.cols, 0) or 0)
213
+ idx = int(col) if isinstance(col, float) and float(col).is_integer() else (
214
+ int(col) if isinstance(col, int) else None)
215
+ if idx is not None:
216
+ idx = idx - 1 if idx >= 1 else idx
217
+ if 0 <= idx < ncol:
218
+ return idx
219
+ raise OriginError("bad_column", "列号 %s 超出范围(共 %d 列)" % (col, ncol),
220
+ ["列号从 1 开始,或用列名字符串"])
221
+ for i in range(ncol):
222
+ if str(_safe(lambda i=i: ws.get_label(i, "L"), "")).strip().lower() == str(col).strip().lower():
223
+ return i
224
+ names = [_safe(lambda i=i: ws.get_label(i, "L"), "") for i in range(ncol)]
225
+ raise OriginError("bad_column", "找不到列 %r,实际列名:%s" % (col, names))
226
+
227
+
228
+ def _col_exists(ws, col):
229
+ try:
230
+ _col_index(ws, col)
231
+ return True
232
+ except OriginError:
233
+ return False
234
+
235
+
236
+ def _extend_to(ws, col):
237
+ """Add columns up to the requested 1-based index so a formula can create one."""
238
+ if isinstance(col, str):
239
+ raise OriginError("bad_column", "要新建派生列请给列号,不要给列名:%r" % col)
240
+ want = int(col)
241
+ if want < 1:
242
+ raise OriginError("bad_column", "列号从 1 开始,收到 %s" % col)
243
+ have = int(_safe(lambda: ws.cols, 0) or 0)
244
+ if want > have + 10:
245
+ raise OriginError("bad_column", "列号 %d 离现有 %d 列太远" % (want, have))
246
+ ws.cols = want
247
+ return want - 1
248
+
249
+
250
+ def _sheet_info(ws):
251
+ rows = int(_safe(lambda: ws.rows, 0) or 0)
252
+ cols = int(_safe(lambda: ws.cols, 0) or 0)
253
+ nm = _safe(lambda: ws.name, "")
254
+ return {
255
+ "worksheet": _bind("ws", ws, nm),
256
+ "name": nm,
257
+ "rows": rows,
258
+ "cols": cols,
259
+ "columns": [{"index": i + 1,
260
+ "label": _safe(lambda i=i: ws.get_label(i, "L"), ""),
261
+ "units": _safe(lambda i=i: ws.get_label(i, "U"), ""),
262
+ "axis": _safe(lambda i=i: str(ws.get_label(i, "D")), "")} for i in range(cols)],
263
+ }
264
+
265
+
266
+ def _verify_file(path, must_be_image=True):
267
+ size = os.path.getsize(path)
268
+ ext = os.path.splitext(path)[1].lower()
269
+ with open(path, "rb") as fh:
270
+ head = fh.read(24)
271
+ magic = IMAGE_MAGIC.get(ext) if must_be_image else None
272
+ ok = size > 1024 and (magic is None or head.startswith(magic))
273
+ dims = None
274
+ if ext == ".png" and head[12:16] == b"IHDR":
275
+ dims = list(struct.unpack(">II", head[16:24]))
276
+ return {"ok": ok, "path": path, "bytes": size, "dimensions": dims, "head": head[:8].hex()}
277
+
278
+
279
+ # ---------------------------------------------------------------- operations
280
+
281
+
282
+ def status():
283
+ def run():
284
+ op = origin()
285
+ paths = {t: _safe(lambda t=t: op.path(t), "") for t in ("u", "p", "e", "l", "s")}
286
+ return {
287
+ "connected": True,
288
+ "origin_version_raw": _safe(op.org_ver),
289
+ "python": sys.executable,
290
+ "paths": paths,
291
+ "pro_hint": any("originpro" in str(v).lower() for v in paths.values() if v),
292
+ "open_pages": _safe(lambda: [p.name for p in op.pages()], []),
293
+ "note": "pro_hint 只是从安装路径推断;Pro 能力以 origin_fit 能否跑通为准",
294
+ }
295
+
296
+ return call(run)
297
+
298
+
299
+ def read_file(path, comment=None):
300
+ """Parse a data file without touching Origin.
301
+
302
+ Cheap and side-effect free, so the model can look at a messy file before
303
+ deciding what to plot. Origin's own ASCII import is the thing that needs a
304
+ second opinion, not this.
305
+ """
306
+ path = os.path.abspath(os.path.expanduser(path))
307
+ if not os.path.isfile(path):
308
+ raise OriginError("file_not_found", "文件不存在:%s" % path)
309
+ if os.path.splitext(path)[1].lower() == ".bin":
310
+ try:
311
+ decoded = binio.read_bin(path)
312
+ except binio.BinFormatError as exc:
313
+ raise OriginError("parse_failed", str(exc),
314
+ ["这个 .bin 不是电化学工作站导出的格式",
315
+ "工作站二进制没有通用规范,需要按厂商解析"])
316
+ decoded.pop("series", None) # values belong in Origin, not in context
317
+ decoded["proof_level"] = "verified" if decoded["axis"] == "reconstructed" \
318
+ else "readback_only"
319
+ decoded["next_actions"] = [
320
+ "origin_import 会把 X/Y 两列写进 Origin 工作表",
321
+ "axis=none 时先问用户要 X 轴(EIS 的频率表不在文件里)",
322
+ ]
323
+ return sanitize(decoded)
324
+ try:
325
+ parsed = asciiio.parse(path, comment=comment)
326
+ except ValueError as exc:
327
+ raise OriginError("parse_failed", str(exc),
328
+ ["确认文件里有数值行", "给 comment 指定实际的注释前缀"])
329
+ parsed["columns"] = [{k: v for k, v in c.items() if k != "values"}
330
+ for c in parsed["columns"]]
331
+ parsed["proof_level"] = "verified"
332
+ return sanitize(parsed)
333
+
334
+
335
+ def _import_ascii(op, path, book_name, parsed):
336
+ """Fill a fresh sheet from our own parser, keeping long names and units."""
337
+ ws = op.new_sheet(lname=book_name or "")
338
+ ws.cols = max(1, len(parsed["columns"]))
339
+ for i, col in enumerate(parsed["columns"]):
340
+ axis = "X" if i == 0 else "Y"
341
+ ws.from_list(i, col["values"], lname=col["name"], units=col["units"], axis=axis)
342
+ return ws
343
+
344
+
345
+ def import_file(path, book_name=""):
346
+ path = os.path.abspath(os.path.expanduser(path))
347
+ if not os.path.isfile(path):
348
+ raise OriginError("file_not_found", "文件不存在:%s" % path)
349
+ ext = os.path.splitext(path)[1].lower()
350
+ if ext not in (".dat", ".csv", ".txt", ".tsv", ".xls", ".xlsx", ".wks", ".bin"):
351
+ raise OriginError("unsupported_file_type", "不支持的类型 %s" % ext,
352
+ ["支持 .dat/.csv/.txt/.tsv/.xls/.xlsx/.wks/.bin"])
353
+
354
+ def run():
355
+ op = origin()
356
+ if ext == ".bin":
357
+ decoded = binio.read_bin(path)
358
+ series = decoded["series"]
359
+ ws = op.new_sheet(lname=book_name or decoded["technique_name"] or "")
360
+ cols = []
361
+ if series["x"]:
362
+ cols.append((decoded["x"]["name"] or "X", series["x"], "X"))
363
+ cols.append((decoded["y"]["name"] or "Y", series["y"], "Y"))
364
+ ws.cols = len(cols)
365
+ for i, (label, values, axis) in enumerate(cols):
366
+ ws.from_list(i, values, lname=label, axis=axis,
367
+ comments="%s %s" % (decoded["technique"], decoded["technique_name"]))
368
+ info = _sheet_info(ws)
369
+ info.update({"source": path, "format": ext, "channel": "binio",
370
+ "technique": decoded["technique"],
371
+ "technique_name": decoded["technique_name"],
372
+ "method": decoded["method"], "axis": decoded["axis"],
373
+ "warnings": decoded["warnings"],
374
+ "proof_level": "verified" if decoded["axis"] == "reconstructed"
375
+ else "readback_only"})
376
+ if decoded["axis"] != "reconstructed":
377
+ info["next_actions"] = ["没有重建出 X 轴:只有测量列,X 需要用户给参数或另配导出文件"]
378
+ return sanitize(info)
379
+ parsed = None
380
+ if ext in ASCII_EXTS:
381
+ # Origin's ASCII import gives up on space-aligned columns and on
382
+ # multi-row headers by returning an empty sheet, so parse those here.
383
+ try:
384
+ parsed = asciiio.parse(path)
385
+ except ValueError as exc:
386
+ parsed = {"fallback_reason": str(exc)}
387
+ if parsed is not None and "columns" in parsed:
388
+ ws = _import_ascii(op, path, book_name, parsed)
389
+ info = _sheet_info(ws)
390
+ info.update({"source": path, "format": ext, "channel": "asciiio",
391
+ "delimiter": parsed["delimiter"], "encoding": parsed["encoding"],
392
+ "warnings": parsed["warnings"],
393
+ "units": [c["units"] for c in parsed["columns"]]})
394
+ return sanitize(info)
395
+
396
+ ws = op.new_sheet(lname=book_name or "")
397
+ ws.from_file(path)
398
+ info = _sheet_info(ws)
399
+ if not info["rows"]:
400
+ raise OriginError("import_empty", "读进来了但是 0 行:%s" % path,
401
+ ["自研解析器也失败了:%s" % (parsed or {}).get("fallback_reason", "见上"),
402
+ "确认文件里有数值行,或改用 origin_read_file 先看结构"])
403
+ info.update({"source": path, "format": ext, "channel": "origin_from_file"})
404
+ return sanitize(info)
405
+
406
+ return call(run)
407
+
408
+
409
+ def write_columns(columns, book_name=""):
410
+ if not isinstance(columns, dict) or not columns:
411
+ raise OriginError("bad_arguments", "columns 必须是非空 dict:{列名: [数值...]}")
412
+ lengths = {len(v) for v in columns.values() if isinstance(v, (list, tuple))}
413
+ if len(lengths) > 1:
414
+ raise OriginError("bad_arguments", "各列长度不一致:%s" % sorted(lengths))
415
+
416
+ def run():
417
+ op = origin()
418
+ ws = op.new_sheet(lname=book_name or "")
419
+ for i, (name, values) in enumerate(columns.items()):
420
+ try:
421
+ nums = [float(v) for v in values]
422
+ except (TypeError, ValueError) as exc:
423
+ raise OriginError("bad_arguments", "列 %r 里有非数值项:%s" % (name, exc),
424
+ ["数值列只接受数字或 null;文本请放 Notes 页,或先把分类编码成数字"])
425
+ ws.from_list(i, nums, str(name))
426
+ return sanitize(_sheet_info(ws))
427
+
428
+ return call(run)
429
+
430
+
431
+ def write_block(headers, rows, book_name=""):
432
+ """Wide table in one shot. from_list costs one COM round trip per column,
433
+ which is why a 40-column sheet is slow; from_list2 writes the block at once."""
434
+ if not rows or not isinstance(rows, (list, tuple)):
435
+ raise OriginError("bad_arguments", "rows 必须是非空的二维列表")
436
+ ncol = max(len(r) for r in rows)
437
+ if headers and len(headers) != ncol:
438
+ raise OriginError("bad_arguments", "headers 有 %d 项,但 rows 最宽 %d 列" % (len(headers), ncol))
439
+
440
+ def run():
441
+ op = origin()
442
+ ws = op.new_sheet(lname=book_name or "")
443
+ try:
444
+ if int(ws.cols) < ncol:
445
+ ws.cols = ncol
446
+ except Exception:
447
+ pass
448
+ # originpro's from_list2 takes a list of COLUMNS, not of rows.
449
+ cols_major = [[r[i] if i < len(r) else None for r in rows] for i in range(ncol)]
450
+ ws.from_list2(cols_major)
451
+ if headers:
452
+ _safe(lambda: ws.set_labels([str(h) for h in headers], "L"))
453
+ info = _sheet_info(ws)
454
+ if not info["rows"]:
455
+ raise OriginError("write_empty", "写入后 0 行,可能被 Origin 拒收",
456
+ ["确认每个值都是数字或空,不要塞字符串进数值列"])
457
+ return sanitize(info)
458
+
459
+ return call(run)
460
+
461
+
462
+ def column_formula(worksheet, col, formula, label="", units=""):
463
+ """Set a column formula (Fx) so the column recomputes from its siblings."""
464
+ ws = _resolve("ws", worksheet)
465
+ if ws is None:
466
+ raise OriginError("worksheet_not_found", "工作表句柄无效:%s" % worksheet)
467
+ if not str(formula).strip():
468
+ raise OriginError("bad_arguments", "formula 不能为空")
469
+
470
+ def run():
471
+ idx = _col_index(ws, col) if _col_exists(ws, col) else _extend_to(ws, col)
472
+ # originpro 1.1.15 documents set_formula's column as 1-offset, but it is
473
+ # 0-based here: passing idx+1 grabs a non-existent column and the library
474
+ # dies inside SetStrProp on a None object.
475
+ ws.set_formula(idx, str(formula))
476
+ if label:
477
+ _safe(lambda: ws.set_label(idx, label, "L"))
478
+ if units:
479
+ _safe(lambda: ws.set_label(idx, units, "U"))
480
+ vals = _safe(lambda: [v for v in ws.to_list(idx) if v is not None], [])
481
+ info = _sheet_info(ws)
482
+ if not vals:
483
+ raise OriginError("formula_no_effect",
484
+ "公式设了但这一列还是空的:%s" % formula,
485
+ ["LabTalk 里底 10 对数是 log() 不是 log10()",
486
+ "跨列引用要先绑定 range,不能内联 [Book]Sheet!col(N)",
487
+ "列号用 Col(1) 这种当前表写法试试"])
488
+ return sanitize({"column": idx + 1, "formula": str(formula),
489
+ "computed_rows": len(vals), "first": vals[0], "last": vals[-1],
490
+ "columns": info["columns"], "proof_level": "verified"})
491
+
492
+ return call(run)
493
+
494
+
495
+ def plot(worksheet, x=1, y=2, plot_type="line", graph_name="", title="",
496
+ graph="", layer=0, template=""):
497
+ """Draw one or more series.
498
+
499
+ A single x/y pair on a fresh page goes through LabTalk plotxy, which is the
500
+ path Origin's own toolbar uses and therefore gets the default theme. Anything
501
+ else (several y columns, a second layer, a named template) uses
502
+ layer.add_plot + rescale, which is the only way that provably targets a given
503
+ layer: plotxy with a qualified range returned True while drawing somewhere else.
504
+ """
505
+ if plot_type not in PLOT_CODES:
506
+ raise OriginError("bad_plot_type", "plot_type 只能是 %s" % sorted(PLOT_CODES))
507
+ ws = _resolve("ws", worksheet)
508
+ if ws is None:
509
+ raise OriginError("worksheet_not_found", "句柄无效:%s(用 origin_import 返回的 worksheet)" % worksheet)
510
+ ys = [y] if isinstance(y, (int, float, str)) else list(y or [])
511
+ if not ys:
512
+ raise OriginError("bad_arguments", "y 不能为空")
513
+ tpl = str(template or "").strip()
514
+ if tpl and tpl.lower() not in GRAPH_TEMPLATES:
515
+ raise OriginError("bad_template", "没有这个图模模板:%r" % template,
516
+ ["可用:%s" % ", ".join(sorted(GRAPH_TEMPLATES))])
517
+
518
+ def run():
519
+ op = origin()
520
+ xi = _col_index(ws, x)
521
+ yis = [_col_index(ws, c) for c in ys]
522
+ book = ws.get_book().name
523
+ # plotxy resolves its range against the ACTIVE worksheet, so activate the
524
+ # book first or it silently plots the wrong sheet.
525
+ op.lt_exec("win -a %s;" % book)
526
+ if len(yis) == 1 and not layer and not tpl:
527
+ before = {g.name for g in _safe(lambda: op.graph_list(), []) or []}
528
+ if not op.lt_exec("plotxy iy:=(%d,%d) plot:=%d;"
529
+ % (xi + 1, yis[0] + 1, PLOT_CODES[plot_type])):
530
+ raise OriginError("plot_failed", "plotxy 返回 False,图没有画出来",
531
+ ["确认两列都有数值(不是文本列)", "先用 origin_inspect 看列情况"])
532
+ fresh = [g for g in op.graph_list() if g.name not in before]
533
+ gr = fresh[-1] if fresh else op.find_graph("")
534
+ if gr is None:
535
+ raise OriginError("plot_failed", "plotxy 说成功了但项目里找不到新图页",
536
+ ["origin_inspect 看当前页面清单"])
537
+ channel = "plotxy"
538
+ else:
539
+ if layer:
540
+ gr = _graph_of(op, graph)
541
+ if gr is None:
542
+ raise OriginError("graph_not_found",
543
+ "往第 %d 层画之前要先有图页:给 graph 句柄" % layer,
544
+ ["origin_inspect 看现有图页", "或先 origin_plot 建第 0 层"])
545
+ elif tpl:
546
+ gr = op.new_graph(graph_name or "", template=tpl)
547
+ if gr is None:
548
+ raise OriginError("bad_template", "Origin 拒绝用模板 %r 建图页" % tpl,
549
+ ["模板名不区分大小写、可不带扩展名",
550
+ "可用:%s" % ", ".join(sorted(GRAPH_TEMPLATES))])
551
+ else:
552
+ gr = op.new_graph(graph_name or "")
553
+ try:
554
+ lay = gr[int(layer)]
555
+ except Exception:
556
+ raise OriginError("bad_layer", "图页 %s 没有第 %d 层" % (gr.name, int(layer)),
557
+ ["先 origin_add_layer 加层"])
558
+ letter = PLOT_LETTERS[plot_type]
559
+ for yi in yis:
560
+ lay.add_plot(ws, yi, xi, type=letter)
561
+ lay.rescale()
562
+ channel = "add_plot"
563
+
564
+ if graph_name and channel == "plotxy":
565
+ _safe(lambda: setattr(gr, "lname", graph_name))
566
+ if title:
567
+ _safe(lambda: setattr(gr[0], "title", title))
568
+
569
+ lay = gr[int(layer)]
570
+ drawn = len(_safe(lambda: lay.plot_list(), []) or [])
571
+ # Read the axes back rather than trusting the command's return value: the
572
+ # add_plot path used to return a Plot object and still draw an empty 0..1 axis.
573
+ x_from = _safe(lambda: lay.xlim[0])
574
+ x_to = _safe(lambda: lay.xlim[1])
575
+ xvals = _safe(lambda: [v for v in ws.to_list(xi) if v is not None], [])
576
+ span = {"x_axis_from": x_from, "x_axis_to": x_to, "graph_page": gr.name,
577
+ "layer": int(layer), "plots_in_layer": drawn}
578
+ if xvals and x_from is not None and x_to is not None:
579
+ want = max(xvals) - min(xvals)
580
+ got = abs(x_to - x_from)
581
+ span["x_data_span"] = want
582
+ if want > 0 and got < want * 0.5:
583
+ raise OriginError(
584
+ "plot_axis_degenerate",
585
+ "X 轴读回 %g..%g 与数据范围 %g..%g 不符,图是空的" % (x_from, x_to, min(xvals), max(xvals)),
586
+ ["确认 x 指定的列是数值列且非空"],
587
+ )
588
+ if drawn < len(yis):
589
+ raise OriginError("plot_incomplete",
590
+ "要求 %d 条曲线,层里只有 %d 条" % (len(yis), drawn),
591
+ ["origin_inspect 看该层,或改用 origin_view 目视确认"])
592
+ return sanitize({"graph": _bind("gr", gr, gr.name), "plot_type": plot_type,
593
+ "channel": channel, "template": tpl,
594
+ "source_sheet": _safe(lambda: ws.name, ""),
595
+ "x_column": xi + 1, "y_columns": [c + 1 for c in yis],
596
+ "proof_level": "verified" if xvals else "readback_only", **span})
597
+
598
+ return call(run)
599
+
600
+
601
+ def style(graph, layer=0, series=None, x_title="", y_title="", x_scale="", y_scale="",
602
+ xlim=None, ylim=None, xtick=0.0, ytick=0.0, color="", symbol_kind=0,
603
+ symbol_size=0.0, symbol_interior=0, line_width=0.0, transparency=0.0,
604
+ fill_area=False):
605
+ """Apply edits and read every one of them back.
606
+
607
+ Plot exposes getters (color/symbol_kind/symbol_size/...), so a style op is
608
+ only reported as applied when the value comes back; the old version trusted
609
+ setattr and could claim success on a silent no-op.
610
+ """
611
+ series = 0 if series is None else int(series)
612
+
613
+ def run():
614
+ op = origin()
615
+ gr = _graph_of(op, graph)
616
+ if gr is None:
617
+ raise OriginError("graph_not_found", "图页句柄无效:%s" % graph)
618
+ try:
619
+ lay = gr[layer]
620
+ except Exception:
621
+ raise OriginError("bad_layer", "图页 %s 没有第 %d 层" % (gr.name, layer),
622
+ ["先用 origin_inspect 看层数"])
623
+ applied, failed = [], []
624
+
625
+ def attempt(desc, setter, getter=None, expect=None):
626
+ try:
627
+ setter()
628
+ except Exception as exc:
629
+ failed.append({"op": desc, "error": str(exc)[:120]})
630
+ return
631
+ if getter is None:
632
+ applied.append({"op": desc, "readback": None})
633
+ return
634
+ got = _safe(getter)
635
+ ok = True if expect is None else (got == expect)
636
+ (applied if ok else failed).append({"op": desc, "readback": got,
637
+ **({} if ok else {"wanted": expect})})
638
+
639
+ if x_title:
640
+ attempt("x_title", lambda: setattr(lay.axis("x"), "title", x_title),
641
+ lambda: lay.axis("x").title, x_title)
642
+ if y_title:
643
+ attempt("y_title", lambda: setattr(lay.axis("y"), "title", y_title),
644
+ lambda: lay.axis("y").title, y_title)
645
+ if x_scale:
646
+ want = SCALE_TYPES.get(str(x_scale).lower())
647
+ if want is None:
648
+ raise OriginError("bad_scale", "未知刻度类型:%r" % x_scale,
649
+ ["可选 %s" % sorted(SCALE_TYPES)])
650
+ attempt("x_scale", lambda: setattr(lay, "xscale", x_scale), lambda: lay.xscale, want)
651
+ if y_scale:
652
+ want = SCALE_TYPES.get(str(y_scale).lower())
653
+ if want is None:
654
+ raise OriginError("bad_scale", "未知刻度类型:%r" % y_scale,
655
+ ["可选 %s" % sorted(SCALE_TYPES)])
656
+ attempt("y_scale", lambda: setattr(lay, "yscale", y_scale), lambda: lay.yscale, want)
657
+ if xlim:
658
+ attempt("xlim", lambda: lay.set_xlim(*_pair(xlim)), lambda: lay.xlim)
659
+ if ylim:
660
+ attempt("ylim", lambda: lay.set_ylim(*_pair(ylim)), lambda: lay.ylim)
661
+ if xtick:
662
+ attempt("xtick", lambda: lay.set_xlim(step=xtick), lambda: lay.xlim)
663
+ if ytick:
664
+ attempt("ytick", lambda: lay.set_ylim(step=ytick), lambda: lay.ylim)
665
+
666
+ if series is not None and (color or symbol_kind or symbol_size or symbol_interior
667
+ or line_width or transparency or fill_area):
668
+ plots = _safe(lambda: lay.plot_list(), []) or []
669
+ if not plots:
670
+ failed.append({"op": "series", "error": "这一层里没有任何曲线(plot_list 为空)"})
671
+ elif series >= len(plots):
672
+ raise OriginError("bad_series", "series=%d 超出范围(本层 %d 条曲线)" % (series, len(plots)),
673
+ ["origin_inspect 会返回每层的曲线数"])
674
+ else:
675
+ p = plots[series]
676
+ if color:
677
+ attempt("p%d.color" % series, lambda: setattr(p, "color", color),
678
+ lambda: p.color)
679
+ if line_width:
680
+ # set_cmd("w=...") reads back unchanged: it is a dialog command,
681
+ # not a property write. set_float('line.width') is the real one.
682
+ attempt("p%d.line.width" % series,
683
+ lambda w=float(line_width): p.set_float("line.width", w),
684
+ lambda: _round2(_safe(lambda: p.get_float("line.width"))),
685
+ round(float(line_width), 2))
686
+ if symbol_kind:
687
+ attempt("p%d.symbol_kind" % series, lambda: setattr(p, "symbol_kind", symbol_kind),
688
+ lambda: p.symbol_kind, symbol_kind)
689
+ if symbol_size:
690
+ attempt("p%d.symbol_size" % series, lambda: setattr(p, "symbol_size", symbol_size),
691
+ lambda: p.symbol_size)
692
+ if symbol_interior:
693
+ attempt("p%d.symbol_interior" % series,
694
+ lambda: setattr(p, "symbol_interior", symbol_interior),
695
+ lambda: p.symbol_interior, symbol_interior)
696
+ if transparency:
697
+ attempt("p%d.transparency" % series, lambda: setattr(p, "transparency", transparency),
698
+ lambda: p.transparency)
699
+ if fill_area:
700
+ attempt("p%d.fill_area" % series, lambda: p.set_fill_area(9, 9))
701
+
702
+ out = {"graph": gr.name, "layer": layer, "series": series,
703
+ "applied": applied, "failed": failed,
704
+ "proof_level": "verified" if applied and not failed else
705
+ ("unverified" if not applied else "partial")}
706
+ if failed:
707
+ out["next_actions"] = ["读回不一致的项改用 origin_labtalk 走 LabTalk,或 origin_view 目视确认"]
708
+ return sanitize(out)
709
+
710
+ return call(run)
711
+
712
+
713
+ def _pair(v):
714
+ """Accept [begin,end] / [begin,end,step] / (begin,end)."""
715
+ vals = list(v)
716
+ while len(vals) < 3:
717
+ vals.append(None)
718
+ return vals[:3]
719
+
720
+
721
+ def annotate(graph, labels=(), lines=(), layer=0):
722
+ """Text labels and reference lines in data coordinates."""
723
+ if not labels and not lines:
724
+ raise OriginError("bad_arguments", "labels 和 lines 至少给一个")
725
+
726
+ def run():
727
+ gr = _graph_of(origin(), graph)
728
+ if gr is None:
729
+ raise OriginError("graph_not_found", "图页句柄无效:%s" % graph)
730
+ lay = gr[layer]
731
+ done = []
732
+ for item in labels or ():
733
+ text = str(item.get("text", ""))
734
+ x, y = item.get("x"), item.get("y")
735
+ lab = _safe(lambda: lay.add_label(text, x, y))
736
+ done.append({"kind": "label", "text": text, "at": [x, y], "ok": lab is not None})
737
+ for item in lines or ():
738
+ coords = [item.get(k) for k in ("x1", "y1", "x2", "y2")]
739
+ ln = _safe(lambda: lay.add_line(*coords))
740
+ done.append({"kind": "line", "coords": coords, "ok": ln is not None,
741
+ "width": _safe(lambda: ln.width) if ln is not None else None,
742
+ "type": _safe(lambda: ln.type) if ln is not None else None})
743
+ ok_all = all(d["ok"] for d in done)
744
+ return sanitize({"graph": gr.name, "layer": layer, "items": done,
745
+ "proof_level": "readback_only" if ok_all else "unverified",
746
+ "note": "标注没有值可读回,要确证请 origin_view 看图",
747
+ **({} if ok_all else {"next_actions": ["有项没加上:确认坐标落在轴范围内"]})})
748
+
749
+ return call(run)
750
+
751
+
752
+ def legend_entries(graph="", layer=0, entries=None, position="", show=True):
753
+ """Add-Modify the layer's legend, with readbacks.
754
+
755
+ `legend -r` regenerates one row per plot using each Y column's long name
756
+ (rendered from the %(i) tokens), which is what makes the names appear instead
757
+ of the "111" that `legend 1` produces. Position is written as layer DATA
758
+ coordinates because that is the only legend geometry that reads back.
759
+ """
760
+ if position and position.lower() not in LEGEND_POSITIONS:
761
+ raise OriginError("bad_position", "图例位置不认识:%r" % position,
762
+ ["可用:%s" % ", ".join(sorted(LEGEND_POSITIONS))])
763
+
764
+ def run():
765
+ op = origin()
766
+ gr = _graph_of(op, graph)
767
+ if gr is None:
768
+ raise OriginError("graph_not_found", "图页句柄无效:%s" % (graph or ""),
769
+ ["先 origin_plot 建图,或 origin_inspect 看现有图页"])
770
+ try:
771
+ lay = gr[int(layer)]
772
+ except Exception:
773
+ raise OriginError("bad_layer", "图页 %s 没有第 %d 层" % (gr.name, int(layer)))
774
+ op.lt_exec("win -a %s;" % gr.name)
775
+ _safe(lambda: lay.activate())
776
+ lab = _safe(lambda: lay.label("Legend"))
777
+ if lab is None:
778
+ _safe(lambda: op.lt_exec("legend -r;"))
779
+ lab = _safe(lambda: lay.label("Legend"))
780
+ if lab is None:
781
+ raise OriginError("legend_failed", "这一层里没有 Legend 对象,也建不出来",
782
+ ["确认层里已经画了曲线(origin_inspect 看 plots 数)"])
783
+ applied, failed = [], []
784
+
785
+ def attempt(desc, setter, getter=None, expect=None):
786
+ try:
787
+ setter()
788
+ except Exception as exc:
789
+ failed.append({"op": desc, "error": str(exc)[:120]})
790
+ return
791
+ got = _safe(getter) if getter else None
792
+ ok = True if expect is None else (got == expect)
793
+ (applied if ok else failed).append({"op": desc, "readback": got,
794
+ **({} if ok else {"wanted": expect})})
795
+
796
+ attempt("show", lambda: op.lt_exec("Legend.Show = %d;" % (1 if show else 0)),
797
+ lambda: op.lt_int("Legend.Show"), 1 if show else 0)
798
+ if entries:
799
+ text = "\r".join(str(e) for e in entries)
800
+ attempt("text", lambda: setattr(lab, "text", text),
801
+ lambda: str(_safe(lambda: lab.text, "")).replace("\r\n", "\r"), text)
802
+ else:
803
+ attempt("auto_from_columns", lambda: op.lt_exec("legend -r;"),
804
+ lambda: _safe(lambda: len(str(_safe(lambda: lab.text, "")).splitlines())))
805
+ placed = None
806
+ if position:
807
+ fx, fy = LEGEND_POSITIONS[position.lower()]
808
+ x0, x1 = _safe(lambda: lay.xlim[:2], (0, 1)) or (0, 1)
809
+ y0, y1 = _safe(lambda: lay.ylim[:2], (0, 1)) or (0, 1)
810
+ tx, ty = x0 + fx * (x1 - x0), y0 + fy * (y1 - y0)
811
+ placed = [tx, ty]
812
+ try:
813
+ op.lt_exec("Legend.x = %g; Legend.y = %g;" % (tx, ty))
814
+ # Origin round-trips these through page units, so compare with a
815
+ # tolerance: 78.0 written comes back as 78.01.
816
+ got = [_safe(lambda: op.lt_float("Legend.x")), _safe(lambda: op.lt_float("Legend.y"))]
817
+ tol = max(0.05, 0.005 * max(abs(tx), abs(ty)))
818
+ ok = all(g is not None and abs(g - w) <= tol for g, w in zip(got, (tx, ty)))
819
+ (applied if ok else failed).append(
820
+ {"op": "position:%s" % position, "readback": got,
821
+ **({} if ok else {"wanted": [tx, ty]})})
822
+ except Exception as exc:
823
+ failed.append({"op": "position:%s" % position, "error": str(exc)[:120]})
824
+ return sanitize({"graph": gr.name, "layer": int(layer),
825
+ "text": _safe(lambda: lab.text, ""),
826
+ "wanted_position": position, "anchor_data_coords": placed,
827
+ "applied": applied, "failed": failed,
828
+ "proof_level": "verified" if applied and not failed else
829
+ ("unverified" if not applied else "partial"),
830
+ "note": "图例锚点是图例中心,坐标为该层的数据坐标"})
831
+
832
+ return call(run)
833
+
834
+
835
+ def add_layer(graph, layer_type="right"):
836
+ """Add a layer to an existing graph page (dual-Y, stacked panels).
837
+
838
+ The layer's own name is the proof: Origin derives it from the position, so a
839
+ right-Y layer reads back as 'RightY'. Filling it is left to origin_plot with
840
+ layer=<index>, which is the only path measured to draw into a chosen layer.
841
+ """
842
+ if isinstance(layer_type, str) and layer_type.lower() in LAYER_TYPES:
843
+ code = LAYER_TYPES[layer_type.lower()]
844
+ elif isinstance(layer_type, int) and layer_type in LAYER_TYPES.values():
845
+ code = layer_type
846
+ else:
847
+ raise OriginError("bad_layer_type", "layer_type 不认识:%r" % (layer_type,),
848
+ ["可用:%s" % ", ".join(sorted(LAYER_TYPES))])
849
+
850
+ def run():
851
+ gr = _graph_of(origin(), graph)
852
+ if gr is None:
853
+ raise OriginError("graph_not_found", "图页句柄无效:%s" % graph)
854
+ before = _layer_count(gr)
855
+ lay = _safe(lambda: gr.add_layer(code))
856
+ after = _layer_count(gr)
857
+ if lay is None and after <= before:
858
+ raise OriginError("add_layer_failed", "加层失败(layer_type=%d)" % code,
859
+ ["layer_type 见 originlab.com/doc/X-Function/ref/layadd",
860
+ "可用名称:%s" % ", ".join(sorted(LAYER_TYPES))])
861
+ made = _safe(lambda: lay.name, "") or ""
862
+ return sanitize({"graph": _bind("gr", gr, gr.name), "graph_page": gr.name,
863
+ "layers_before": before, "layers_after": after,
864
+ "layer_type": code, "layer_type_name": LAYER_NAME_BY_CODE.get(code, "?"),
865
+ "layer_name_from_origin": made,
866
+ "layer_index": after - 1,
867
+ "proof_level": "verified" if made and made.endswith(
868
+ LAYER_NAME_BY_CODE.get(code, "?")) else "readback_only",
869
+ "next_actions": ["origin_plot 时给 graph 和 layer=%d 往这层画曲线" % (after - 1)]})
870
+
871
+ return call(run)
872
+
873
+
874
+ def _layer_count(gr):
875
+ n = 0
876
+ while n < 16:
877
+ if _safe(lambda i=n: gr[i]) is None:
878
+ break
879
+ n += 1
880
+ return n
881
+
882
+
883
+ def view(graph, width=900):
884
+ """Render the graph to a small PNG and hand the bytes back for visual check."""
885
+ def run():
886
+ import base64
887
+ import tempfile
888
+ op = origin()
889
+ page = _graph_of(op, graph)
890
+ if page is None:
891
+ raise OriginError("graph_not_found", "没有可预览的图页;先 origin_inspect 看页面")
892
+ # Unique name: a fixed path would let two dsh sessions overwrite each
893
+ # other's preview mid-read.
894
+ fd, tmp = tempfile.mkstemp(prefix="optima_plot_view_", suffix=".png")
895
+ os.close(fd)
896
+ os.remove(tmp)
897
+ # save_fig rejects a type that disagrees with the extension, and its
898
+ # width only applies when a type is given, so try explicit then fall back.
899
+ _safe(lambda: page.save_fig(tmp, "png", width=int(width)))
900
+ if not os.path.isfile(tmp):
901
+ _safe(lambda: page.save_fig(tmp))
902
+ if not os.path.isfile(tmp):
903
+ raise OriginError("preview_failed", "预览图没生成:%s" % tmp,
904
+ ["改用 origin_export 指定 ASCII 路径"])
905
+ info = _verify_file(tmp)
906
+ if not info["ok"]:
907
+ raise OriginError("preview_suspect", "预览图异常:%s" % info)
908
+ with open(tmp, "rb") as fh:
909
+ b64 = base64.b64encode(fh.read()).decode("ascii")
910
+ _safe(lambda: os.remove(tmp)) # previews accumulate in %TEMP% otherwise
911
+ return {"graph": _safe(lambda: page.name, ""), "mime": "image/png",
912
+ "image_base64": b64, "bytes": info["bytes"], "dimensions": info["dimensions"]}
913
+
914
+ return call(run)
915
+
916
+
917
+ LABTALK_DENY = ("doc -s", "doc -c", "saveas", "quit", "exitloop", "type -m", "openb", "run.x")
918
+
919
+
920
+ def labtalk(script, readback=(), numeric=()):
921
+ """Escape hatch: run raw LabTalk, then read the variables you name.
922
+
923
+ Destructive statements are refused because a mis-targeted command is the #1
924
+ way these bridges corrupt a session, and because a bare script with no
925
+ readback proves nothing.
926
+ """
927
+ if not str(script).strip():
928
+ raise OriginError("bad_arguments", "script 不能为空")
929
+ # Advisory guardrail, not a sandbox: it stops the model from wiping the
930
+ # session by accident, not from trying hard. Whitespace is collapsed so
931
+ # 'doc -s' does not slip past the literal match.
932
+ low = re.sub(r"\s+", " ", str(script).lower())
933
+ blocked = [p for p in LABTALK_DENY if p in low]
934
+ if blocked:
935
+ raise OriginError("labtalk_denied", "这些命令不允许通过 origin_labtalk 执行:%s" % blocked,
936
+ ["关工程/退 Origin 请用 origin_exit 或 origin_save_project"])
937
+
938
+ def run():
939
+ op = origin()
940
+ ret = op.lt_exec(str(script))
941
+ strs = {}
942
+ for name in readback or ():
943
+ strs[str(name)] = _safe(lambda n=name: op.get_lt_str(n), None)
944
+ nums = {}
945
+ for name in numeric or ():
946
+ nums[str(name)] = _safe(lambda n=name: op.lt_float(n), None)
947
+ return sanitize({"script": str(script), "returned": bool(ret),
948
+ "readback": strs, "numeric": nums,
949
+ "proof_level": "verified" if (ret and (strs or nums)) else
950
+ ("readback_only" if ret else "unverified"),
951
+ **({} if ret else {"next_actions": [
952
+ "LabTalk 返回 False:多半是命令本身报错或作用在不活动的窗口",
953
+ "先 win -a <页面短名>; 激活目标页再执行"]})})
954
+
955
+ return call(run)
956
+
957
+
958
+ FIT_STATS = ("chisqr", "cod", "cor", "r", "adjr", "dof", "niter", "pts", "ssr", "rmse",
959
+ "fitstatus", "func", "nfuncparams", "nderivparams", "confc", "confp")
960
+ FIT_PREFIXES = ("f", "s", "e", "u", "l", "ub", "lb", "ubon", "lbon", "ubx", "lbx", "d", "n")
961
+
962
+
963
+ def _trim_linear(res):
964
+ p = res.get("Parameters") or {}
965
+ st = (res.get("RegStats") or {}).get("C1") or {}
966
+
967
+ def pv(name):
968
+ d = p.get(name) or {}
969
+ return {"value": d.get("Value"), "error": d.get("Error")}
970
+
971
+ return {"equation": (res.get("Notes") or {}).get("Equation"),
972
+ "slope": pv("Slope"), "intercept": pv("Intercept"),
973
+ "r_squared": st.get("RSqCOD") or st.get("Rvalue"),
974
+ "adj_r_squared": st.get("AdjRSq"), "n": st.get("N"),
975
+ "dof": st.get("DOF"), "rmse": st.get("RMSESD")}
976
+
977
+
978
+ def _trim_nlfitsing(res):
979
+ stats = {k: res[k] for k in FIT_STATS if k in res}
980
+ params = {}
981
+ for k, v in res.items():
982
+ if k in stats or "_" in k:
983
+ continue
984
+ params[k] = v
985
+ return {"parameters": params, "stats": stats}
986
+
987
+
988
+ def fit(worksheet, x=1, y=2, kind="linear", func="", fixed=None, starts=None,
989
+ bounds=None, make_report=False, full=False):
990
+ """Fit a curve. fixed/starts/bounds are {param_name: value} for NLFit.
991
+
992
+ bounds value is [lo, hi] (either end may be null to leave it open).
993
+ """
994
+ ws = _resolve("ws", worksheet)
995
+ if ws is None:
996
+ raise OriginError("worksheet_not_found", "工作表句柄无效:%s" % worksheet)
997
+ kind = str(kind).lower()
998
+ if kind in FIT_PRESETS:
999
+ func, kind = FIT_PRESETS[kind], "nlfitsing"
1000
+ if kind not in ("linear", "nlfitsing", "nlfit"):
1001
+ raise OriginError("bad_kind", "kind 只能是 linear、nlfitsing,或内置预设 %s"
1002
+ % sorted(FIT_PRESETS))
1003
+ if kind == "nlfitsing" and str(func).lower() in FIT_PRESETS:
1004
+ func = FIT_PRESETS[str(func).lower()]
1005
+
1006
+ def run():
1007
+ op = origin()
1008
+ xi, yi = _col_index(ws, x), _col_index(ws, y)
1009
+ if kind == "linear":
1010
+ lf = op.LinearFit()
1011
+ lf.set_data(ws, xi, yi)
1012
+ notes = []
1013
+ if starts and "Slope" in starts:
1014
+ notes.append({"fix_slope": _safe(lambda v=starts["Slope"]: lf.fix_slope(float(v)), "err") != "err"})
1015
+ if starts and "Intercept" in starts:
1016
+ notes.append({"fix_intercept": _safe(lambda v=starts["Intercept"]: lf.fix_intercept(float(v)), "err") != "err"})
1017
+ res = lf.result()
1018
+ if make_report:
1019
+ _safe(lf.report)
1020
+ body = res if full else _trim_linear(res)
1021
+ return sanitize({"kind": "linear", "constraints": notes,
1022
+ "trimmed": not full, **({"result": body} if full else {"fit": body})})
1023
+ if not func:
1024
+ raise OriginError("bad_arguments", "非线性拟合必须给 func",
1025
+ ["预设名:%s" % ", ".join(sorted(FIT_PRESETS)),
1026
+ "或直接给 Origin 的函数名(区分大小写,如 Gauss 而不是 gauss1)"])
1027
+ try:
1028
+ nl = op.NLFit(func)
1029
+ except Exception as exc:
1030
+ raise OriginError("fit_function_unavailable", "函数 %r 不可用:%s" % (func, exc),
1031
+ ["NLFit 需要 OriginPro 授权",
1032
+ "本机实测可用的名字:%s" % ", ".join(sorted(set(FIT_PRESETS.values())))])
1033
+ nl.set_data(ws, xi, yi)
1034
+ notes = []
1035
+ for name, val in (starts or {}).items():
1036
+ notes.append({"set_param": name, "ok": _safe(lambda n=name, v=val: nl.set_param(n, float(v)), "err") != "err"})
1037
+ for name, val in (fixed or {}).items():
1038
+ notes.append({"fix_param": name, "ok": _safe(lambda n=name, v=val: nl.fix_param(n, float(v)), "err") != "err"})
1039
+ for name, pair in (bounds or {}).items():
1040
+ lo, hi = (pair + [None, None])[:2] if isinstance(pair, (list, tuple)) else (None, None)
1041
+ if lo is not None:
1042
+ _safe(lambda n=name, v=lo: nl.set_lbound(n, None, float(v)))
1043
+ if hi is not None:
1044
+ _safe(lambda n=name, v=hi: nl.set_ubound(n, None, float(v)))
1045
+ notes.append({"bounds": name, "lo": lo, "hi": hi})
1046
+ nl.fit()
1047
+ res = nl.result()
1048
+ if make_report:
1049
+ _safe(nl.report)
1050
+ _safe(nl.__del__)
1051
+ r2 = res.get("cod") if isinstance(res, dict) else None
1052
+ body = res if full else _trim_nlfitsing(res)
1053
+ return sanitize({"kind": "nlfitsing", "func": func, "r_squared": r2,
1054
+ "fit_status": res.get("fitstatus") if isinstance(res, dict) else None,
1055
+ "constraints": notes, "trimmed": not full,
1056
+ **({"result": body} if full else {"fit": body})})
1057
+
1058
+ return call(run, timeout=300)
1059
+
1060
+
1061
+ def export(graph, path="", fmt="png", width=1600):
1062
+ fmt = str(fmt).lstrip(".").lower()
1063
+ if fmt not in ("png", "tif", "tiff", "svg", "pdf", "emf"):
1064
+ raise OriginError("bad_format", "fmt 只支持 png/tif/svg/pdf/emf,收到 %s" % fmt)
1065
+
1066
+ def run():
1067
+ op = origin()
1068
+ page = _graph_of(op, graph)
1069
+ if page is None:
1070
+ raise OriginError("graph_not_found", "找不到图页:%s(项目里可能还没有图)" % (graph or ""))
1071
+ name = _safe(lambda: page.name, "Graph1")
1072
+ target_path = os.path.abspath(path or os.path.join(os.getcwd(), "%s.%s" % (name, fmt)))
1073
+ os.makedirs(os.path.dirname(target_path) or ".", exist_ok=True)
1074
+ _safe(lambda: page.save_fig(target_path))
1075
+ if not os.path.isfile(target_path):
1076
+ raise OriginError("export_failed", "Origin 说导出了但文件不存在:%s" % target_path,
1077
+ ["路径必须可写且最好是 ASCII", "先 origin_inspect 确认图页非空"])
1078
+ info = _verify_file(target_path)
1079
+ if not info["ok"]:
1080
+ raise OriginError("export_suspect", "导出文件过小或文件头不对:%s" % info,
1081
+ ["图页可能是空的:origin_inspect 看 plots 数"])
1082
+ return sanitize(dict(info, channel="originpro.save_fig", graph=name))
1083
+
1084
+ return call(run)
1085
+
1086
+
1087
+ def _save_project(path=""):
1088
+ """Runs ON the COM thread. Call via save_project(); never from another run()."""
1089
+ def run():
1090
+ global _project_file
1091
+ op = origin()
1092
+ if path:
1093
+ target = os.path.abspath(path)
1094
+ elif _project_file:
1095
+ target = _project_file
1096
+ else:
1097
+ # Never default to the process CWD: under dsh that is the plugin's
1098
+ # node_modules folder, so an unnamed save would litter the install.
1099
+ target = os.path.join(_safe(lambda: op.path("u"), "") or os.getcwd(),
1100
+ time.strftime("optima_plot_%Y%m%d_%H%M%S.opju"))
1101
+ if not target.lower().endswith((".opju", ".opj")):
1102
+ target += ".opju"
1103
+ os.makedirs(os.path.dirname(target) or ".", exist_ok=True)
1104
+
1105
+ # op.save(file) is Origin's Save-As: once the project is bound to that
1106
+ # file, saving the same name again returns False without meaning failure.
1107
+ # Note originpro's path('p') is the project *folder*, so the bound file
1108
+ # has to be tracked here rather than asked from Origin.
1109
+ same_file = bool(_project_file) and os.path.normcase(_project_file) == os.path.normcase(target)
1110
+ mtime_before = os.path.getmtime(target) if os.path.isfile(target) else 0
1111
+ ok = bool(op.save()) if same_file else bool(op.save(target))
1112
+
1113
+ if not os.path.isfile(target):
1114
+ raise OriginError("save_failed", "保存工程失败:%s (ok=%s)" % (target, ok),
1115
+ ["确认目录可写、路径为 ASCII",
1116
+ "换一个不冲突的文件名,或省略 path 用自动时间戳命名"])
1117
+ fresh = os.path.getmtime(target) > mtime_before
1118
+ if not ok and not (same_file and not fresh):
1119
+ raise OriginError("save_failed", "保存工程失败:%s (ok=%s)" % (target, ok),
1120
+ ["该文件可能正被 Origin 占用(工程绑定后会加锁)",
1121
+ "换一个不冲突的文件名,或省略 path 用自动时间戳命名"])
1122
+ info = _verify_file(target, must_be_image=False)
1123
+ if not info["ok"]:
1124
+ raise OriginError("save_suspect", "工程文件过小:%s" % info,
1125
+ ["项目里得先有工作表或图页再保存"])
1126
+ _project_file = target
1127
+ out = dict(info, editable=True, saved=bool(ok),
1128
+ note="可在 Origin 里继续编辑的 .opju,不是图片快照")
1129
+ if same_file and not ok:
1130
+ out["unchanged"] = True
1131
+ out["note"] = "项目已绑定在该文件上且无待写变更,文件保持原样"
1132
+ return sanitize(out)
1133
+
1134
+ return run()
1135
+
1136
+
1137
+ def save_project(path=""):
1138
+ return call(_save_project, path)
1139
+
1140
+
1141
+ def open_project(path):
1142
+ path = os.path.abspath(os.path.expanduser(path))
1143
+ if not os.path.isfile(path):
1144
+ raise OriginError("file_not_found", "工程文件不存在:%s" % path)
1145
+
1146
+ def run():
1147
+ global _project_file
1148
+ op = origin()
1149
+ if not op.open(path):
1150
+ raise OriginError("open_failed", "Origin 拒绝打开这个工程:%s" % path,
1151
+ ["确认文件是 .opju/.opj 且没被另一个 Origin 实例锁住",
1152
+ "Origin 版本低于该工程保存版本时也打不开"])
1153
+ _project_file = path
1154
+ return sanitize({"opened": path, "open_pages": [p.name for p in op.pages()]})
1155
+
1156
+ return call(run)
1157
+
1158
+
1159
+ def inspect(graph=""):
1160
+ def run():
1161
+ op = origin()
1162
+ pages = [{"name": p.name, "kind": type(p).__name__,
1163
+ "lname": _safe(lambda p=p: p.lname, "")} for p in op.pages()]
1164
+ out = {"pages": pages, "handles": sorted(_handles)}
1165
+ page = _graph_of(op, graph)
1166
+ if page is not None:
1167
+ layers = []
1168
+ i = 0
1169
+ while i < 8:
1170
+ lay = _safe(lambda i=i: page[i])
1171
+ if lay is None:
1172
+ break
1173
+ layers.append({"layer": i,
1174
+ "x_title": _safe(lambda l=lay: l.axis("x").title, ""),
1175
+ "y_title": _safe(lambda l=lay: l.axis("y").title, ""),
1176
+ "plots": _safe(lambda l=lay: len(l.plots()), 0)})
1177
+ i += 1
1178
+ out.update({"graph": _safe(lambda: page.name, ""), "layers": layers})
1179
+ return sanitize(out)
1180
+
1181
+ return call(run)
1182
+
1183
+
1184
+ def exit_origin(save_to=""):
1185
+ def run():
1186
+ global _op, _project_file
1187
+ op = origin()
1188
+ saved = _save_project(save_to)["path"] if save_to else ""
1189
+ _safe(op.exit)
1190
+ _handles.clear()
1191
+ _names.clear()
1192
+ _project_file = ""
1193
+ _op = None
1194
+ return sanitize({"exited": True, "saved": saved})
1195
+
1196
+ return call(run)
1197
+
1198
+
1199
+ def figure(source="", columns=None, x=1, y=1, plot_type="line", title="",
1200
+ x_title="", y_title="", fmt="png", width=1600, output_dir="",
1201
+ export_path="", project_path="", do_project=None,
1202
+ template="", legend=False):
1203
+ """One call: data in -> graph -> styled -> image + editable .opju on disk.
1204
+
1205
+ Files only land on disk when the caller gives a destination (output_dir /
1206
+ export_path / project_path); otherwise Origin keeps the graph in its session
1207
+ and we say so instead of writing next to the server's CWD.
1208
+ """
1209
+ t0 = time.time()
1210
+ steps = []
1211
+ if source:
1212
+ info = import_file(source)
1213
+ steps.append({"step": "import", "rows": info["rows"], "source": info["source"],
1214
+ "channel": info.get("channel", ""), "warnings": info.get("warnings", [])})
1215
+ elif columns:
1216
+ info = write_columns(columns)
1217
+ steps.append({"step": "write", "rows": info["rows"]})
1218
+ else:
1219
+ raise OriginError("bad_arguments", "figure 需要 source(文件路径)或 columns(内联数据)")
1220
+
1221
+ p = plot(info["worksheet"], x=x, y=y, plot_type=plot_type, title=title, template=template)
1222
+ steps.append({"step": "plot", "graph": p["graph_page"], "type": plot_type,
1223
+ "channel": p.get("channel", ""), "plots": p.get("plots_in_layer")})
1224
+ if x_title or y_title:
1225
+ st = style(p["graph"], x_title=x_title, y_title=y_title)
1226
+ steps.append({"step": "style", **st})
1227
+ else:
1228
+ st = {}
1229
+ lg = {}
1230
+ if legend:
1231
+ lg = legend_entries(p["graph"], entries=legend if isinstance(legend, list) else None)
1232
+ steps.append({"step": "legend", "proof_level": lg.get("proof_level")})
1233
+
1234
+ out = {"data": info, "plot": p, "style": st, "legend": lg}
1235
+ deliver = {}
1236
+ if export_path or output_dir:
1237
+ base = export_path or os.path.join(output_dir, "%s.%s" % (p["graph_page"], fmt))
1238
+ e = export(p["graph"], base, fmt=fmt, width=width)
1239
+ deliver["image"] = e["path"]
1240
+ steps.append({"step": "export", "file": e["path"], "bytes": e["bytes"],
1241
+ "dimensions": e.get("dimensions")})
1242
+ out["export"] = e
1243
+ if do_project or project_path or output_dir:
1244
+ proj = project_path or (os.path.join(
1245
+ output_dir, "%s_%s.opju" % (p["graph_page"], time.strftime("%H%M%S")))
1246
+ if output_dir else "")
1247
+ s = save_project(proj)
1248
+ deliver["project"] = s["path"]
1249
+ steps.append({"step": "save_project", "file": s["path"], "bytes": s["bytes"]})
1250
+ out["project"] = s
1251
+ elif not deliver:
1252
+ out["note"] = ("没给 output_dir/export_path/project_path,只建了图和曲线、没有落盘文件;"
1253
+ "要交付物请至少给一个 output_dir")
1254
+ out["delivered"] = deliver
1255
+ out["proof_level"] = "verified" if deliver.get("image") else "readback_only"
1256
+ out["steps"] = steps
1257
+ out["duration_ms"] = int((time.time() - t0) * 1000)
1258
+ return out
1259
+
1260
+
1261
+ # ------------------------------------------------------- matrix / 3D / heat maps
1262
+
1263
+ MATRIX_TEMPLATES = ("heat_map", "cmap", "mesh", "contline", "contgray", "3d",
1264
+ "glwireface", "glwirefrm", "bar3d")
1265
+
1266
+
1267
+ def matrix_plot(rows, template="heat_map", book_name="", graph_name="",
1268
+ xy_range=None, title="", export_path="", project_path=""):
1269
+ """Grid data in -> Origin matrix sheet -> a template-driven matrix graph.
1270
+
1271
+ type='?' on add_plot is what lets the .otp template choose the plot kind: with
1272
+ an explicit type Origin drew contour lines on top of the Heat_Map template.
1273
+ """
1274
+ tpl = str(template or "heat_map").lower()
1275
+ if tpl not in MATRIX_TEMPLATES:
1276
+ raise OriginError("bad_template", "矩阵图模板不认识:%r" % template,
1277
+ ["可用:%s" % ", ".join(sorted(MATRIX_TEMPLATES))])
1278
+ if not isinstance(rows, (list, tuple)) or not rows:
1279
+ raise OriginError("bad_arguments", "rows 必须是二维数值列表(矩阵网格)")
1280
+ widths = {len(r) for r in rows if isinstance(r, (list, tuple))}
1281
+ if len(widths) != 1 or not widths.pop():
1282
+ raise OriginError("bad_arguments", "矩阵每行宽度必须一致且非空")
1283
+
1284
+ def run():
1285
+ import numpy as np
1286
+ op = origin()
1287
+ arr = np.array([[float(v) if v is not None else np.nan for v in r] for r in rows],
1288
+ dtype=float)
1289
+ mb = op.new_book("m", book_name or "")
1290
+ ms = mb[0]
1291
+ ms.from_np(arr, mv=np.nan)
1292
+ if xy_range:
1293
+ xy = [float(v) for v in xy_range]
1294
+ if len(xy) != 4:
1295
+ raise OriginError("bad_arguments", "xy_range 要 4 个数:[x1,x2,y1,y2]")
1296
+ ms.xymap = xy
1297
+ mapped = _safe(lambda: list(ms.xymap), [])
1298
+ gr = op.new_graph(graph_name or "", template=tpl)
1299
+ if gr is None:
1300
+ raise OriginError("bad_template", "Origin 拒绝用模板 %r 建图页" % tpl)
1301
+ lay = gr[0]
1302
+ lay.add_plot(ms, colz=0, type="?")
1303
+ _safe(lay.rescale)
1304
+ if title:
1305
+ _safe(lambda: setattr(lay, "title", title))
1306
+ drawn = len(_safe(lambda: lay.plot_list(), []) or [])
1307
+ if drawn < 1:
1308
+ raise OriginError("plot_failed", "矩阵图里一条曲线都没有(模板 %s)" % tpl,
1309
+ ["origin_inspect 看页面", "换 heat_map / cmap 模板试试"])
1310
+ out = {"matrix_book": _safe(lambda: mb.name, ""), "shape": list(arr.shape),
1311
+ "z_min": float(np.nanmin(arr)), "z_max": float(np.nanmax(arr)),
1312
+ "xymap": mapped, "template": tpl,
1313
+ "graph": _bind("gr", gr, gr.name), "graph_page": gr.name,
1314
+ "plots_in_layer": drawn,
1315
+ "xlim": _safe(lambda: list(lay.xlim)), "ylim": _safe(lambda: list(lay.ylim)),
1316
+ "zlim": _safe(lambda: list(lay.zlim)),
1317
+ "proof_level": "verified"}
1318
+ if export_path:
1319
+ out["export"] = _export_on_com_thread(gr, export_path)
1320
+ if project_path:
1321
+ out["project"] = _save_project(project_path)
1322
+ return sanitize(out)
1323
+
1324
+ return call(run)
1325
+
1326
+
1327
+ def _export_on_com_thread(page, path):
1328
+ """export() body, for reuse inside another run() that is already on the thread."""
1329
+ ext = os.path.splitext(path)[1].lower() or ".png"
1330
+ target = os.path.abspath(path)
1331
+ os.makedirs(os.path.dirname(target) or ".", exist_ok=True)
1332
+ _safe(lambda: page.save_fig(target))
1333
+ if not os.path.isfile(target):
1334
+ raise OriginError("export_failed", "矩阵图导出没落盘:%s" % target)
1335
+ info = _verify_file(target, must_be_image=ext in IMAGE_MAGIC)
1336
+ if not info["ok"]:
1337
+ raise OriginError("export_suspect", "导出文件异常:%s" % info)
1338
+ return info
1339
+
1340
+
1341
+ # ------------------------------------------------------------- page garbage
1342
+
1343
+ PAGE_KINDS = {"graph": ("GPage", "g"), "worksheet": ("WBook", "w"), "workbook": ("WBook", "w"),
1344
+ "matrix": ("MBook", "m"), "notes": ("Notes", "n")}
1345
+
1346
+
1347
+ def close_pages(kind="graph", names=None, dry_run=False):
1348
+ """Close pages so a long dsh session does not choke Origin.
1349
+
1350
+ Accumulated pages are what makes Origin's COM bridge start answering
1351
+ "无效指针"; this gives the model a way to reclaim them by name or by type.
1352
+
1353
+ The proof is a fresh enumeration in its own COM call: is_open() only reports
1354
+ "not hidden/minimised", so it can never show that a page is gone.
1355
+ """
1356
+ from collections import Counter
1357
+ want = PAGE_KINDS.get(str(kind).lower())
1358
+ if kind and not want:
1359
+ raise OriginError("bad_kind", "kind 不认识:%r" % kind,
1360
+ ["可用:%s" % ", ".join(sorted(PAGE_KINDS))])
1361
+ want_cls, want_letter = want or ("", "")
1362
+ keep = None if not names else [str(n) for n in names]
1363
+
1364
+ def collect():
1365
+ op = origin()
1366
+ # op.pages() is a GENERATOR: iterating it twice silently yields nothing
1367
+ # the second time, which is how this first reported "no matching pages".
1368
+ pages_now = list(_safe(lambda: op.pages(want_letter), []) or [])
1369
+ counts = Counter(_safe(lambda p=p: p.name, "?") for p in pages_now)
1370
+ targets = []
1371
+ for p in pages_now:
1372
+ if want_cls and type(p).__name__ != want_cls:
1373
+ continue
1374
+ if keep and _safe(lambda p=p: p.name, "") not in keep and \
1375
+ _safe(lambda p=p: p.lname, "") not in keep:
1376
+ continue
1377
+ targets.append(p)
1378
+ return targets, counts
1379
+
1380
+ def destroy(targets):
1381
+ errors = {}
1382
+ for p in targets:
1383
+ try:
1384
+ p.destroy()
1385
+ except Exception as exc:
1386
+ errors[_safe(lambda p=p: p.name, "?")] = str(exc)[:160]
1387
+ return errors
1388
+
1389
+ def enumerate_pages():
1390
+ op = origin()
1391
+ return [_safe(lambda p=p: p.name, "?")
1392
+ for p in list(_safe(lambda: op.pages(), []) or [])]
1393
+
1394
+ targets, had = call(collect)
1395
+ wanted = [_safe(lambda p=p: p.name, "?") for p in targets]
1396
+ if not targets:
1397
+ return sanitize({"closed": [], "asked": [], "note": "没有匹配的页面"})
1398
+ if dry_run:
1399
+ return sanitize({"would_close": wanted, "dry_run": True})
1400
+ errors = call(destroy, targets)
1401
+ alive = call(enumerate_pages)
1402
+ for _ in range(10):
1403
+ now = Counter(alive)
1404
+ if all(now.get(n, 0) < had.get(n, 0) for n in wanted):
1405
+ break
1406
+ time.sleep(0.2)
1407
+ alive = call(enumerate_pages)
1408
+ now = Counter(alive)
1409
+ closed, expected = [], dict(had)
1410
+ for nm in wanted:
1411
+ if now.get(nm, 0) < expected.get(nm, 0):
1412
+ closed.append(nm)
1413
+ expected[nm] = now.get(nm, 0)
1414
+ for ref in [r for r, nm in _names.items() if nm and nm in closed]:
1415
+ _handles.pop(ref, None)
1416
+ _names.pop(ref, None)
1417
+ return sanitize({"asked": wanted, "closed": closed,
1418
+ "refused": [n for n in wanted if n not in closed],
1419
+ "errors": errors,
1420
+ "remaining_pages": alive,
1421
+ "proof_level": "verified" if len(closed) == len(wanted) else
1422
+ ("partial" if closed else "unverified"),
1423
+ "note": "以关闭后重新枚举的页面名单为证据"})
1424
+
1425
+
1426
+ # ------------------------------------------------- scientific chart presets
1427
+
1428
+ def _catalog():
1429
+ try:
1430
+ import templates_catalog
1431
+ except Exception as exc:
1432
+ raise OriginError("catalog_missing", "图表预设目录加载失败:%s" % exc)
1433
+ return templates_catalog
1434
+
1435
+
1436
+ def chart_presets(category=""):
1437
+ cat = _catalog()
1438
+ items = cat.list_templates(category or None)
1439
+ return sanitize({"n_templates": len(items),
1440
+ "categories": sorted({t["category"] for t in cat.TEMPLATES}),
1441
+ "templates": items})
1442
+
1443
+
1444
+ def chart_preset(name):
1445
+ cat = _catalog()
1446
+ tpl = cat.describe_template(name)
1447
+ if tpl is None:
1448
+ raise OriginError("preset_not_found", "没有这个图表预设:%r" % name,
1449
+ ["origin_chart_presets 看全部 %d 个" % len(cat.TEMPLATES)])
1450
+ return sanitize(tpl)
1451
+
1452
+
1453
+ def chart_check(name, data=None, columns=None):
1454
+ """Dry-run a preset against real data without touching Origin."""
1455
+ cat = _catalog()
1456
+ tpl = cat.describe_template(name)
1457
+ if tpl is None:
1458
+ raise OriginError("preset_not_found", "没有这个图表预设:%r" % name)
1459
+ if data and not columns:
1460
+ columns = [c["name"] for c in read_file(data)["columns"]]
1461
+ detected = list(columns or [])
1462
+ issues = []
1463
+ for req in tpl["required_columns"] or ():
1464
+ norm = str(req).lower().replace("_", "").replace(" ", "")
1465
+ if not any(norm in str(c).lower().replace("_", "").replace(" ", "") for c in detected):
1466
+ issues.append("缺少列:%s" % req)
1467
+ return sanitize({"status": "ok" if not issues else "warning", "template": name,
1468
+ "required_columns": tpl["required_columns"],
1469
+ "optional_columns": tpl.get("optional_columns") or [],
1470
+ "columns_detected": detected, "issues": issues,
1471
+ "suggested_fit": tpl.get("suggested_fit"),
1472
+ "default_axis_titles": tpl.get("default_axis_titles"),
1473
+ "default_plot_kind": tpl.get("default_plot_kind"),
1474
+ "extra": tpl.get("extra", "")})
1475
+
1476
+
1477
+ def chart_render(name, source="", columns=None, x=1, y=2, output_dir="",
1478
+ x_title=None, y_title=None, title=None, plot_type=None,
1479
+ with_legend=True, fmt="png", width=1600):
1480
+ """Render a scientific preset with the verified plot/style/legend path.
1481
+
1482
+ Only the preset's metadata is taken from the catalog: axis titles, plot kind
1483
+ and the suggested fit. Its own render_template() calls op.new(), which would
1484
+ throw away whatever project the user has open in Origin.
1485
+ """
1486
+ checked = chart_check(name, data=source) if not columns else chart_check(name, columns=columns)
1487
+ preset = chart_preset(name)
1488
+ kind = str(plot_type or preset.get("default_plot_kind") or "line").lower()
1489
+ if kind not in PLOT_CODES:
1490
+ kind = "line"
1491
+ titles = preset.get("default_axis_titles") or {}
1492
+ xt = x_title if x_title is not None else titles.get("x", "")
1493
+ yt = y_title if y_title is not None else titles.get("y", "")
1494
+ out = figure(source=source, columns=columns, x=x, y=y, plot_type=kind,
1495
+ title=title if title is not None else preset.get("description", "")[:60],
1496
+ x_title=xt, y_title=yt, fmt=fmt, width=width,
1497
+ output_dir=output_dir, legend=with_legend)
1498
+ out["preset"] = {"name": name, "category": preset.get("category", ""),
1499
+ "plot_type": kind, "x_title": xt, "y_title": yt}
1500
+ out["check"] = checked
1501
+ if preset.get("suggested_fit"):
1502
+ out["hint"] = "这个预设建议拟合函数:%s(origin_fit kind=%s)" % (
1503
+ preset["suggested_fit"], preset["suggested_fit"])
1504
+ if preset.get("extra"):
1505
+ out["preset_note"] = preset["extra"]
1506
+ return out