osis-python 0.7.5__py3-none-any.whl → 0.7.7__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: osis-python
3
- Version: 0.7.5
3
+ Version: 0.7.7
4
4
  Summary: A Python client library for Osis APDL
5
5
  Author-email: "CCCC Highway Consultant Co. Ltd." <support@osisbim.com>
6
6
  License-Expression: MIT
@@ -1,24 +1,25 @@
1
- osis_python-0.7.5.dist-info/licenses/LICENSE,sha256=T4mkSYliXdU9mYe-NfHkqg6GPhzoYaIQO_a630UzpS4,1088
2
- pyosis/__init__.py,sha256=fO35LAwXFLKagoQ9zSbK1hfIydGGkAcGsEkAMj__GeA,440
1
+ osis_python-0.7.7.dist-info/licenses/LICENSE,sha256=T4mkSYliXdU9mYe-NfHkqg6GPhzoYaIQO_a630UzpS4,1088
2
+ pyosis/__init__.py,sha256=PwZ7FI6uNm_Z4VbsfGg14SObscbjJi2WJhHY5J8odWs,440
3
3
  pyosis/boundary/__init__.py,sha256=W5LfF-jugWa-YI8pnfELZaz0pXLa-D8TiGnBn12HGGQ,102
4
4
  pyosis/boundary/interface.py,sha256=obqQUVFuQK9I7S8IaBZ2VBYfyXgNVBS0PQa9LzRlaAc,8990
5
5
  pyosis/boundary/manager.py,sha256=AAGdkp0sLV85enT9TQT9iqvWzjJyLzjiw0rC-tajSrI,39576
6
6
  pyosis/control/__init__.py,sha256=98UAXB9Wkf93pGUKIjoGBBrSCblVeAwc_MXeaAB-UIA,119
7
7
  pyosis/control/control.py,sha256=4bX92TDJnf1D5A3YY7ZZrU7iUeAxKCjQe9z_F_SEHBs,2816
8
8
  pyosis/control/io.py,sha256=buaut3-W8kwJIe3PgjtgOU0JCSgDfOEd2cS3mxYsfuc,591
9
- pyosis/control/manager.py,sha256=NhxM-geF-STaUATMZgMac8A93hQ7OkN2cFMI7WRPm1Q,10800
9
+ pyosis/control/manager.py,sha256=EZEOlsgsg2rmOPIVjNFIdgwgxo9c0ZpKfjAr4wmx73Q,11610
10
10
  pyosis/control/nonlinear.py,sha256=26W_2GhD_0cn3YQxJjgbPR1oEopJWyuFWGlgx0q023I,1604
11
- pyosis/core/__init__.py,sha256=mte3tkLHfFIJq6HWpE54aM_D7ARvYBVGkM0Qv4H0uGE,629
11
+ pyosis/core/__init__.py,sha256=ZQ2WNmC4r8JTduK33j5iendyLb0UW3l0Sjr2qdcAjQs,696
12
12
  pyosis/core/all_func.py,sha256=VhvAeMJMCQJ1redjqdkm7meTw1PJNDoRdmXXh2LzkVo,521
13
- pyosis/core/apdl_sync.py,sha256=rW5Ot6FLpmUzpfMlrbemstnfhxD_0qtPrWgDfj9_4XY,5312
13
+ pyosis/core/apdl_sync.py,sha256=SMBUwTdBCdQMQAPnC7gV1RS1Lp2XAVeHjQKEvFnkf54,5559
14
14
  pyosis/core/basic_manager.py,sha256=z3Qh5LpHg4AOyTrGffC09mPnW-yUT-UuhKnFe4GLUOM,7204
15
15
  pyosis/core/batch.py,sha256=jPA9U3ahGRZdY8y1wCSZyVpBPmGOtQtvM3vfDgqM2sM,6851
16
- pyosis/core/client.py,sha256=6i0q-yPosip5IzSESvpCxuF-v8iojRuFXyPulMKO8Ac,3285
16
+ pyosis/core/client.py,sha256=_9NxTf1D_3BFgt7A73v5C-Qk3KORku_Sq85RnNi3ZxQ,4849
17
17
  pyosis/core/command.py,sha256=bZ5nS1wvwhjwIsogWQh5-1dAcbsJoyB8MR85WUprZ0s,8863
18
- pyosis/core/engine.py,sha256=UnpE_CUQjNk62aFWRQ62lNA9hqaoBcefOmKnua7IE9A,15829
18
+ pyosis/core/engine.py,sha256=ZAclt7GSIlZ8-DWH1Q9Tr7Jb4Jwza88-pNW4OiMCDCc,16880
19
19
  pyosis/core/exceptions.py,sha256=x0I0Emooejy8wF1ZBWGz7Yc1N70MitsnhhQv9txJQj8,1093
20
20
  pyosis/core/references.py,sha256=JQ8260aqVB5PhhGrqMt7W7fmrsmE69dFdrE6EyyLADg,2755
21
- pyosis/core/solver.py,sha256=f0vJ1w_r2n8vjiOzfD05sU6qD838nV7R22zmQAbI0lQ,5194
21
+ pyosis/core/sdk.py,sha256=LXNftRkaPOtIUu51u3UmhcBy8BtA28z4DEO08aAzjFA,2489
22
+ pyosis/core/solver.py,sha256=M7RZpGsQ17mOHJ4aKoXa2LnDlCEUM83vjzcMeA6JTTY,6014
22
23
  pyosis/core/sync_apdl_cli.py,sha256=xlRDhtR4fOebLvyVZT9joUp6Q0H55gIt0YDy9Cb4HB4,874
23
24
  pyosis/display/__init__.py,sha256=POxWZ8I5Qanj4ETpHBZMhXNOMlsLMYRamXwP_JjSDUo,161
24
25
  pyosis/display/interface.py,sha256=-ekocpi2DEieGrE34R_BjEGW3p6yZkXxlaxteT06XzE,3907
@@ -43,15 +44,15 @@ pyosis/live/lane.py,sha256=i1-mnKQuo_XLimtcX2ZV4PBC_A0FBneWxJU198X1MMc,5487
43
44
  pyosis/live/manager.py,sha256=q0w9RVfuwLUqPYo4CS8kc9NchyF7mCiczcrWEzD31NQ,49319
44
45
  pyosis/load/__init__.py,sha256=AdCBsdf4QPVzbKwbj2C24Fnl9sPmlB9h542LjLFcqHM,135
45
46
  pyosis/load/loadcase.py,sha256=5DOty5OBtxHPguw_gYUqL3FFbXRkCjA2IVpCdAzJSJU,2457
46
- pyosis/load/manager.py,sha256=NVXXxW44eHhAElWSTi9IWjQbvOh9rblcQANzcTf31vg,81453
47
+ pyosis/load/manager.py,sha256=0pE04fb5FpsU9Dypu73cqBxSt4d-vYJs9HQIf0REVyQ,82137
47
48
  pyosis/load/static.py,sha256=vvwx5WmXUL-M3GvlH9GA-oaTZQmvLaawR76dFNVrwgc,22773
48
49
  pyosis/load/tendon.py,sha256=2AJxvYJU8PEJ-rH-vbLUjd0CwmhIeSFEx9asuWpT_0s,11528
49
50
  pyosis/material/__init__.py,sha256=W0oDx9SY_zngAcrMCO_0sF773-OxCfL1B-w2IeWlZ_g,79
50
51
  pyosis/material/interface.py,sha256=SiHWjLPUDR1f3EMObGlYQUlKgpfoh1VuGJgVAQfariA,5729
51
- pyosis/material/manager.py,sha256=4zPVD03QOZ7sSPk4VpZgf1Ug5TTVpqsAIZb4Phj4Ftg,16061
52
+ pyosis/material/manager.py,sha256=2ZmrviYsD8b09CvMUyvCXrsPr6cfNYIquy-ep_Xgcw4,16790
52
53
  pyosis/node/__init__.py,sha256=6BKMR_HhFuvf-wr_U1H4njEj95pqgiHh6ApFl2JWMQ0,71
53
54
  pyosis/node/interface.py,sha256=T0lL1pHD069Qw3PTxufUF6cJl9fAKiclAL_ISgboaz8,1208
54
- pyosis/node/manager.py,sha256=fXkmeILs_LUvyv45wKBwzDFB2ssNO4In-bP71Dbrlow,8877
55
+ pyosis/node/manager.py,sha256=qqY1hIbIfK0NeAoimsqks0GCl32GVucGeKkcXa7bvnk,9578
55
56
  pyosis/post/__init__.py,sha256=Zh8Jvy6715tCZxwlTfV86-8cyh0OqqK2vCTlG_VARYY,120
56
57
  pyosis/post/combine.py,sha256=0EajaRAJK3d_rkW7t9Cmxc4wHM87TOBYroWnnBK2ldM,4587
57
58
  pyosis/post/design_check.py,sha256=vJzpu63yBjU4QDUIxvLOhUvqPrZ56q301ADCgHdu0eA,11257
@@ -69,16 +70,17 @@ pyosis/property/manager.py,sha256=7wHj0PC38hC42i0S36JDAeU8TUrjIQF0cubRgNUNpAI,33
69
70
  pyosis/property/pu_curve.py,sha256=E3oUfe7ERYKX6q9v1U-HnNP1LRbWobNYB8dUC26s8aQ,1534
70
71
  pyosis/quick_building/__init__.py,sha256=QiWapgiZk6pkAdiznKI0bVIc16UcFOIALQuLhupLkqw,48
71
72
  pyosis/quick_building/interface.py,sha256=xdQrORabxmnlhi537pspFokQBaXSmnZMIxA_kxSo_cE,13951
72
- pyosis/result/__init__.py,sha256=DYZe8miR9Fj2Rnbdjyi97h1Egr_kVm2bbHyIffJ2Yk8,114
73
+ pyosis/result/__init__.py,sha256=jfMtPk8RK72gPj87vDpUYmfG30XGvBOBms_taCKcqNo,289
73
74
  pyosis/result/check.py,sha256=CuPjCx54AQlg9oTM71tMbW7pTDfolkYPbpb9iOc7bIM,4922
74
75
  pyosis/result/env.py,sha256=PjvBpaZOPEjm4TVfolpQEssoXXtMSnMZ7dUmt9w3Glo,1425
76
+ pyosis/result/headless.py,sha256=bTwjML7CMdtc8LKz5TronLaEVtc3WdZld_UofhNWtXA,4750
75
77
  pyosis/result/loadcase.py,sha256=Z5tGpesD-8o_l1iS6tLn6u8aty3QtDNsyKXsbvbkOV4,2351
76
- pyosis/result/manager.py,sha256=Q4aoRX0LB8y3q5TdqV_JPYFRWTWuygzyNnhCcJpUveY,9808
78
+ pyosis/result/manager.py,sha256=APCryMMXo4W1eDuet3xikGy53LBLB7ZfjJFdyV1PrEI,12272
77
79
  pyosis/result/result.py,sha256=wUyRaHSwyijLpodWIHPFQVEOn6LP8MfYp7xLhC-RiIo,1194
78
80
  pyosis/section/__init__.py,sha256=VjNbQWgWHtLO6la39oXgbQMnQPR0-b1DPIM52Cj--jg,179
79
81
  pyosis/section/common.py,sha256=yI61YQH8btfkoBGnXF7wp3kFhZVW06XABIJZnvkDk3E,26616
80
82
  pyosis/section/composite.py,sha256=CWNcPagXbL4D8uUouRk8ux7Xv41bE2dXM8JfWX77pBI,9353
81
- pyosis/section/manager.py,sha256=WED3yj01gb0gOJ1pwDEJcEFpZhWwLBy62ETQayTEPYM,94343
83
+ pyosis/section/manager.py,sha256=eWGAKmjVpZ7YGrWQfbdGuILOi7Xy-a7phJLOIPzfwpU,95053
82
84
  pyosis/section/numeric.py,sha256=lDO1KvSTmzBE56wkfDw5xxDhWi-kM0szXPx6CIymIyQ,1479
83
85
  pyosis/section/param.py,sha256=E4ZyJqyPn1xhNchb82ar6K36a_ah8R_66-FruOMlbBM,4944
84
86
  pyosis/section/rebar.py,sha256=9ibcOoMd7HYfzSaO6dMpZFwp1ugmwayOmDqIoWUijNc,8337
@@ -98,13 +100,14 @@ pyosis/thickness/__init__.py,sha256=YGYmUPc9TvAlw4eFuEjxaG7HjvwLQJelU_Mx2M6RhW0,
98
100
  pyosis/thickness/interface.py,sha256=o9fwAnPtincBvNB7KZ-Cw67V4mSvoMYgcuLqD_FMLs0,1311
99
101
  pyosis/thickness/manager.py,sha256=JfKNKQnAaqEVnFyr3UwCj9cl4qhHYT_9Pp7HVBYNx6M,5048
100
102
  pyosis/transfer/__init__.py,sha256=OZVxVnjhDGe4fHC6pjtOaKPzAKuoDp3-XkNFzDWepsE,623
101
- pyosis/transfer/generator.py,sha256=sVcmOfXp9_Xx0_Rk_BrSgIdK5CL47m6sBeIWCC-22XU,3869
103
+ pyosis/transfer/generator.py,sha256=VEK_od-buUfHLav39ldR6o-ibKBd1iWdjNQ0T_Zfhyg,5473
104
+ pyosis/transfer/introspect.py,sha256=auOKh6KJrT3dZckNnTA59zuGm9kzSsVNiSkpvDo1G9Q,5125
102
105
  pyosis/transfer/matrix.py,sha256=sHw9X34-PUeY1EdoNklgK0LUHwbBPnhkhk0R9ME0XG0,3378
103
- pyosis/transfer/out_to_python.py,sha256=wiU58lQvdfugxebizO91wPwFWVk8x1Q7LgKyScFNqZA,15706
106
+ pyosis/transfer/out_to_python.py,sha256=69UnwkmkQiAZvpB0RLZqXlj9I0hItWgvTZRY5dWN2lY,17880
104
107
  pyosis/transfer/parser.py,sha256=R_aBlYJTe53hD1sX5PBv86bhj88NQwANFRN4pGYudQ8,6774
105
- pyosis/transfer/routes.py,sha256=l1EdTAWeyvhkQSbK3jMKwn2SeXJHF9Lf2AdEDV6X0l4,10798
108
+ pyosis/transfer/routes.py,sha256=fBHDt53F5YxNpttPwW_jm6bjxcW7T1P8WAiEv7Xn90E,12748
106
109
  pyosis/transfer/split.py,sha256=hpBe9D9WbjbKsovx4hM3X5RjTrruWNkuFmZt2ed0fME,1284
107
- osis_python-0.7.5.dist-info/METADATA,sha256=u0ZbbySda6s0zZ2X4IKvJhK2mo6FfASB5QYfJ5HER-o,20180
108
- osis_python-0.7.5.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
109
- osis_python-0.7.5.dist-info/top_level.txt,sha256=6VDNySkQKwipRXcN8ayKVci4vAXi4oPyWLqFhNVcIfM,7
110
- osis_python-0.7.5.dist-info/RECORD,,
110
+ osis_python-0.7.7.dist-info/METADATA,sha256=Dv7Zrp-C0Iuqorf9dfsZLH1i1X8Jjpx6NHJP8TReYr0,20180
111
+ osis_python-0.7.7.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
112
+ osis_python-0.7.7.dist-info/top_level.txt,sha256=6VDNySkQKwipRXcN8ayKVci4vAXi4oPyWLqFhNVcIfM,7
113
+ osis_python-0.7.7.dist-info/RECORD,,
pyosis/__init__.py CHANGED
@@ -7,7 +7,7 @@ A library for extending OSIS functionality.
7
7
  A library that allows users to use CAE with great flexibility.
8
8
  """
9
9
 
10
- __version__ = "0.7.5"
10
+ __version__ = "0.7.7"
11
11
 
12
12
  from .core.engine import OSISEngine
13
13
  from .core.batch import batch, flush, batch_state, BatchError
pyosis/control/manager.py CHANGED
@@ -18,6 +18,7 @@ from __future__ import annotations
18
18
  from typing import Literal
19
19
 
20
20
  from ..core import osis_run
21
+ from ..core.client import osis_client
21
22
  from .control import (
22
23
  osis_acel,
23
24
  osis_calc_tendon,
@@ -373,6 +374,25 @@ class ControlManager:
373
374
  if not ok:
374
375
  raise RuntimeError(f"设置模态分析参数失败: {err}")
375
376
 
377
+ # ── 查询 ────────────────────────────────────
378
+
379
+ def summary(self) -> list[dict]:
380
+ '''获取分析控制摘要(走 GetAnalysisControlSummary 端点)
381
+
382
+ 汇总当前模型将要执行的分析类型(特征值分析、施工阶段分析等),
383
+ 每项含 name/type/summary/count。
384
+
385
+ Returns:
386
+ list[dict]: 分析控制摘要列表,未定义分析时为空列表
387
+
388
+ Raises:
389
+ RuntimeError: 查询失败时抛出异常
390
+ '''
391
+ resp = osis_client("GetAnalysisControlSummary", {})
392
+ if not resp.get("success"):
393
+ raise RuntimeError(f"{resp.get('error')}")
394
+ return list(resp.get("data") or [])
395
+
376
396
  def __repr__(self) -> str:
377
397
  return "ControlManager()"
378
398
 
pyosis/core/__init__.py CHANGED
@@ -14,3 +14,4 @@ from .batch import batch, flush, batch_state, BatchError
14
14
  from .basic_manager import BasicManager, LazyRef
15
15
  from .exceptions import DependencyError
16
16
  from .references import get_references, raise_if_occupied
17
+ from .sdk import health, sdk_version, list_commands, instance_info
pyosis/core/apdl_sync.py CHANGED
@@ -51,8 +51,11 @@ class ApdlSessionStore:
51
51
 
52
52
 
53
53
  # 读取 .out 文件内容
54
+ # 实测 5.1(2026-10 构建)export_apdl 导出为 UTF-8(无 BOM);UTF-8 中文可能
55
+ # 恰好是合法 GBK,GBK 优先会静默乱码,所以 UTF-8 在前。旧版若导出 GBK,
56
+ # 按 UTF-8 解码通常直接抛错并回落到 GBK,不会误判。
54
57
  def _read_out_text(path: Path) -> str:
55
- for encoding in ("gbk", "utf-8", "gb2312", "gb18030", "latin-1"):
58
+ for encoding in ("utf-8-sig", "utf-8", "gbk", "gb18030", "latin-1"):
56
59
  try:
57
60
  return path.read_text(encoding=encoding)
58
61
  except UnicodeDecodeError:
pyosis/core/client.py CHANGED
@@ -102,4 +102,54 @@ def osis_client(
102
102
 
103
103
  except requests.RequestException as e:
104
104
  return {"success": False, "error": f"调用失败: {str(e)}"}
105
+
106
+
107
+ def osis_get(
108
+ path: str,
109
+ base_url=None,
110
+ timeout: float | None = None,
111
+ ) -> dict:
112
+ """
113
+ 通用 OSIS GET 客户端(复用连接池)
114
+
115
+ 用于只绑定 GET 的端点(如 /instance);/health、/sdk/* 同时支持
116
+ GET/POST,查询类调用统一走本函数。
117
+
118
+ Args:
119
+ path: 端点路径(如 "instance",无需前导斜杠)
120
+ Returns:
121
+ 成功时返回端点 JSON;失败时返回 {"success": False, "error": ...}
122
+ """
123
+ from .batch import batch_state, flush as _flush
124
+ if batch_state.active and batch_state.buffer and not batch_state.flushing:
125
+ _flush()
126
+
127
+ base_url = base_url or os.environ.get("OSIS_URL", f"{DEFAULT_URL}:{DEFAULT_PORT}")
128
+ url = f"{base_url}/{path.lstrip('/')}"
129
+
130
+ try:
131
+ response = session.get(
132
+ url,
133
+ timeout=timeout if timeout is not None else DEFAULT_TIMEOUT,
134
+ )
135
+
136
+ data = None
137
+ if response.content:
138
+ try:
139
+ data = response.json()
140
+ except ValueError:
141
+ pass
142
+
143
+ if response.status_code == 404:
144
+ return {"success": False, "error": f"接口不存在: {path}"}
145
+
146
+ if response.ok: # 200-299
147
+ if data is not None:
148
+ return data
149
+ return {"success": False, "error": f"接口返回空数据: {path}"}
150
+
151
+ return {"success": False, "error": f"HTTP {response.status_code}: {response.text[:200]}"}
152
+
153
+ except requests.RequestException as e:
154
+ return {"success": False, "error": f"调用失败: {str(e)}"}
105
155
 
pyosis/core/engine.py CHANGED
@@ -52,6 +52,7 @@ from ..general.interface import (
52
52
  )
53
53
  from .command import osis_run
54
54
  from .client import set_osis_port, set_osis_url
55
+ from .sdk import sdk_version, list_commands, instance_info, health as _sdk_health
55
56
 
56
57
 
57
58
  class OSISEngine:
@@ -329,6 +330,30 @@ class OSISEngine:
329
330
  """输出计算书所需结果"""
330
331
  return output_result_for_calc_book()
331
332
 
333
+ # ──────────────────────────────────────────
334
+ # 服务端元信息(/sdk/*、/instance)
335
+ # ──────────────────────────────────────────
336
+
337
+ def sdk_version(self) -> dict:
338
+ """查询 SDK/OSIS 版本与 ABI
339
+
340
+ Returns:
341
+ {"success": True, "sdk": 版本串, "osis": 版本串, "abi": ABI, "port": 端口}
342
+ """
343
+ return sdk_version()
344
+
345
+ def list_commands(self) -> list[str]:
346
+ """查询运行时可用命令名(GUI 书册命令不列出)"""
347
+ return list_commands()
348
+
349
+ def instance_info(self) -> dict:
350
+ """查询 OSIS 实例信息(pid/port/project/version/state)"""
351
+ return instance_info()
352
+
353
+ def is_alive(self) -> bool:
354
+ """存活探测(POST /health,不碰工程状态)"""
355
+ return _sdk_health()
356
+
332
357
  # ──────────────────────────────────────────
333
358
  # 便捷方法(委托给 project manager)
334
359
  # ──────────────────────────────────────────
pyosis/core/sdk.py ADDED
@@ -0,0 +1,76 @@
1
+ """SDK 元信息与服务端实例查询
2
+
3
+ 对应 PySolver 端点 /health、/sdk/version、/sdk/commands、GET /instance。
4
+ 这些端点同时支持 GET/POST(/instance 仅 GET),不依赖工程状态。
5
+
6
+ 用法:
7
+ from pyosis.core.sdk import sdk_version, list_commands, instance_info
8
+ sdk_version() # {"success": True, "sdk": "5.1.x", "osis": ..., "abi": ..., "port": ...}
9
+ list_commands() # 运行时可用的命令名列表
10
+ instance_info() # {"pid": ..., "port": ..., "project": ..., "version": ..., "state": ...}
11
+ """
12
+ from __future__ import annotations
13
+
14
+ from .client import osis_client, osis_get
15
+
16
+
17
+ def health(base_url=None) -> bool:
18
+ """存活探测(POST /health)。
19
+
20
+ 只证明 HTTP server 在跑,不碰工程/command 状态。
21
+
22
+ Returns:
23
+ bool: server 存活返回 True
24
+ """
25
+ resp = osis_client("health", {}, base_url=base_url)
26
+ return bool(resp.get("success"))
27
+
28
+
29
+ def sdk_version(base_url=None) -> dict:
30
+ """查询 SDK/OSIS 版本与 ABI(POST/GET /sdk/version)。
31
+
32
+ Returns:
33
+ {"success": True, "sdk": 版本串, "osis": 版本串, "abi": ABI, "port": 端口}
34
+
35
+ Raises:
36
+ RuntimeError: 查询失败时抛出
37
+ """
38
+ resp = osis_client("sdk/version", {}, base_url=base_url)
39
+ if not resp.get("success"):
40
+ raise RuntimeError(f"查询 SDK 版本失败: {resp.get('error')}")
41
+ return resp
42
+
43
+
44
+ def list_commands(base_url=None) -> list[str]:
45
+ """查询运行时可用命令名(POST/GET /sdk/commands)。
46
+
47
+ 返回当前工程命令流可识别的命令名(GUI 书册命令不列出)。
48
+
49
+ Returns:
50
+ list[str]: 命令名列表
51
+
52
+ Raises:
53
+ RuntimeError: 查询失败时抛出
54
+ """
55
+ resp = osis_client("sdk/commands", {}, base_url=base_url)
56
+ if not resp.get("success"):
57
+ raise RuntimeError(f"查询命令列表失败: {resp.get('error')}")
58
+ return list(resp.get("commands") or [])
59
+
60
+
61
+ def instance_info(base_url=None) -> dict:
62
+ """查询 OSIS 实例信息(GET /instance)。
63
+
64
+ broker 登记实例时用它确认端口实际归属。
65
+
66
+ Returns:
67
+ {"pid": 进程号, "port": HTTP 端口, "project": 工程路径,
68
+ "version": 版本, "state": 实例状态}
69
+
70
+ Raises:
71
+ RuntimeError: 查询失败时抛出
72
+ """
73
+ resp = osis_get("instance", base_url=base_url)
74
+ if not isinstance(resp, dict) or resp.get("error"):
75
+ raise RuntimeError(f"查询实例信息失败: {resp.get('error', resp)}")
76
+ return resp
pyosis/core/solver.py CHANGED
@@ -22,7 +22,8 @@ class OSISSolver:
22
22
 
23
23
  Args:
24
24
  osis_install_path: OSIS 安装根目录,根目录下需有 PySolver.dll。
25
- port: HTTP server 端口;<0 用 PySolver 默认 18080。端口被占会失败。
25
+ port: HTTP server 端口;<=0 由系统随机分配(bind :0),实际端口
26
+ 回写 self.port;默认 18080。指定端口被占会失败。
26
27
  host: 监听地址,默认 127.0.0.1。
27
28
 
28
29
  Raises:
@@ -83,7 +84,18 @@ class OSISSolver:
83
84
  self._add_dll_search_dir(os.path.dirname(path))
84
85
 
85
86
  try:
86
- lib = ctypes.CDLL(path)
87
+ # Debug 构建的依赖(如 HPDI.OSIS.IO 的 DebugWnd)会在 DLL 静态初始化里
88
+ # AllocConsole + freopen 劫持 stdio——python 宿主的输出被抢走、
89
+ # 解释器退出码变 120。加载前 dup 一份标准流,加载完立刻恢复。
90
+ saved_out = os.dup(1)
91
+ saved_err = os.dup(2)
92
+ try:
93
+ lib = ctypes.CDLL(path)
94
+ finally:
95
+ os.dup2(saved_out, 1)
96
+ os.dup2(saved_err, 2)
97
+ os.close(saved_out)
98
+ os.close(saved_err)
87
99
  except OSError as e:
88
100
  raise RuntimeError(f"OSISSolver: 加载 {path} 失败: {e}")
89
101
 
@@ -102,6 +114,10 @@ class OSISSolver:
102
114
 
103
115
  self._lib = lib
104
116
  self._started = True
117
+ # port<=0(随机分配)时 AutoBootstrap 返回系统分配的实际端口,回写,
118
+ # self.url / engine 连接才指向正确地址
119
+ if actual_port > 0:
120
+ self._port = actual_port
105
121
  self._wait_ready()
106
122
  return self
107
123
 
pyosis/load/manager.py CHANGED
@@ -1873,6 +1873,23 @@ class TendonManager:
1873
1873
  "shapes": self.shape.count()
1874
1874
  }
1875
1875
 
1876
+ def prestress_loads(self) -> list[dict]:
1877
+ """获取所有预应力荷载(走 GetAllPrestressedLoadInfo 端点)
1878
+
1879
+ 遍历所有荷载工况下的预应力荷载(钢束张拉信息)。
1880
+
1881
+ Returns:
1882
+ list[dict]: 每条含 name/tensionMethod/tensionMethodName/
1883
+ tensionForce/tensionForceName/beg/end/relatedLoadCase/loadCase
1884
+
1885
+ Raises:
1886
+ RuntimeError: 查询失败时抛出异常
1887
+ """
1888
+ resp = osis_client("GetAllPrestressedLoadInfo", {})
1889
+ if not resp.get("success"):
1890
+ raise RuntimeError(f"{resp.get('error')}")
1891
+ return [d for d in resp.get("data") or [] if isinstance(d, dict) and d]
1892
+
1876
1893
  def clear(self) -> None:
1877
1894
  """清空所有钢束形状和钢束特性(先清空形状,再清空特性)"""
1878
1895
  self.shape.clear()
@@ -121,6 +121,26 @@ class MaterialManager(BasicManager):
121
121
 
122
122
  return materials
123
123
 
124
+ def all_prestressed(self) -> list[Material]:
125
+ """获取所有预应力材料(走 GetAllPrestressedMaterialInfo 端点)
126
+
127
+ 与 all() 的区别:只返回材料类型为预应力(PRESTRESSED)的材料,
128
+ 服务端按类型过滤,不需要客户端再筛。
129
+
130
+ Returns:
131
+ list[Material]: 预应力材料列表
132
+
133
+ Raises:
134
+ RuntimeError: 查询失败时抛出异常
135
+ """
136
+ resp = osis_client("GetAllPrestressedMaterialInfo", {})
137
+ if not resp.get("success"):
138
+ raise RuntimeError(f"{resp.get('error')}")
139
+ return [
140
+ Material._from_dict(d) for d in resp.get("data", [])
141
+ if isinstance(d, dict) and "no" in d
142
+ ]
143
+
124
144
  def get_dependencies(self, no: int) -> dict[str, list]:
125
145
  """查询材料被谁引用"""
126
146
  return get_references("Material", no=no)
pyosis/node/manager.py CHANGED
@@ -111,6 +111,26 @@ class NodeManager(BasicManager):
111
111
  raise RuntimeError(f"{resp['error']}")
112
112
  nodes = [Node._from_dict(d) for d in resp.get("data", []) if "no" in d]
113
113
  return nodes
114
+
115
+ def coordinates(self) -> dict[int, tuple[float, float, float]]:
116
+ """获取所有节点坐标(走 GetCoordinate 端点)
117
+
118
+ 比 all() 更轻量——只要坐标不要分组等附加信息时用这个。
119
+
120
+ Returns:
121
+ dict: {节点编号: (x, y, z)}
122
+
123
+ Raises:
124
+ RuntimeError: 查询失败时抛出异常
125
+ """
126
+ resp = osis_client("GetCoordinate", {})
127
+ if not resp.get("success"):
128
+ raise RuntimeError(f"{resp.get('error')}")
129
+ return {
130
+ d["id"]: (d.get("x", 0.0), d.get("y", 0.0), d.get("z", 0.0))
131
+ for d in resp.get("data") or []
132
+ if isinstance(d, dict) and "id" in d
133
+ }
114
134
 
115
135
  # ── 增删改 ────────────────────────────────
116
136
 
pyosis/result/__init__.py CHANGED
@@ -1,4 +1,12 @@
1
1
  from .loadcase import *
2
2
  from .check import *
3
3
  from .env import *
4
- from .manager import ResultManager, result_manager
4
+ from .manager import ResultManager, result_manager
5
+ from .headless import (
6
+ get_node_displacement,
7
+ get_element_force,
8
+ get_support_reaction,
9
+ node_displacement_df,
10
+ element_force_df,
11
+ support_reaction_df,
12
+ )
@@ -0,0 +1,122 @@
1
+ """求解后结果的无头查询
2
+
3
+ 对应 PySolver 端点(v0.2 新增,优先从结果文件读,文件失败回落内存):
4
+ - /GetAllNodeDisplacement、/GetNodeDisplacementByNames 节点位移
5
+ - /GetAllElementForce、/GetElementForceByNames 单元内力
6
+ - /GetAllSupportReaction、/GetSupportReactionByNames 支座反力
7
+
8
+ 与 loadcase/env 走 OSIS_Run 命令流 + txt 导出的路径不同,这组端点
9
+ 直接读求解器结果,无需 GUI 参与,适合无头批量提取。
10
+
11
+ 返回结构(每个工况一个对象):
12
+ {"loadCase": 工况名, "source": "file"|"memory",
13
+ "nodes": [...] / "elements": [...]}
14
+ """
15
+ from __future__ import annotations
16
+
17
+ from ..core.client import osis_client
18
+
19
+ try:
20
+ import pandas as pd
21
+ _HAS_PANDAS = True
22
+ except ImportError:
23
+ _HAS_PANDAS = False
24
+
25
+
26
+ def _query_all(endpoint: str) -> list[dict]:
27
+ resp = osis_client(endpoint, {})
28
+ if not resp.get("success"):
29
+ raise RuntimeError(f"{resp.get('error', endpoint + ' 失败')}")
30
+ return [d for d in resp.get("data") or [] if isinstance(d, dict) and d]
31
+
32
+
33
+ def _query_by_names(endpoint: str, names: str | list[str]) -> list[dict]:
34
+ if isinstance(names, str):
35
+ names = [names]
36
+ resp = osis_client(endpoint, {"name": [str(n) for n in names]})
37
+ if not resp.get("success"):
38
+ raise RuntimeError(f"{resp.get('error', endpoint + ' 失败')}")
39
+ # C++ 端查不到的工况返回空对象,过滤掉
40
+ return [d for d in resp.get("data") or [] if isinstance(d, dict) and d]
41
+
42
+
43
+ # ═════════════════════════════════════════════
44
+ # 原始 dict 查询
45
+ # ═════════════════════════════════════════════
46
+
47
+ def get_node_displacement(name: str | list[str] | None = None) -> list[dict]:
48
+ """查询求解后节点位移
49
+
50
+ Args:
51
+ name: 工况名(str 或 list[str]);None 时返回全部工况
52
+
53
+ Returns:
54
+ list[dict]: 每个工况 {"loadCase", "source", "nodes": [{no, ux..rz, rw}]}
55
+ """
56
+ if name is None:
57
+ return _query_all("GetAllNodeDisplacement")
58
+ return _query_by_names("GetNodeDisplacementByNames", name)
59
+
60
+
61
+ def get_element_force(name: str | list[str] | None = None) -> list[dict]:
62
+ """查询求解后单元内力
63
+
64
+ Args:
65
+ name: 工况名(str 或 list[str]);None 时返回全部工况
66
+
67
+ Returns:
68
+ list[dict]: 每个工况 {"loadCase", "source",
69
+ "elements": [{ele, node, fx..mz, mw}]}
70
+ """
71
+ if name is None:
72
+ return _query_all("GetAllElementForce")
73
+ return _query_by_names("GetElementForceByNames", name)
74
+
75
+
76
+ def get_support_reaction(name: str | list[str] | None = None) -> list[dict]:
77
+ """查询求解后支座反力
78
+
79
+ Args:
80
+ name: 工况名(str 或 list[str]);None 时返回全部工况
81
+
82
+ Returns:
83
+ list[dict]: 每个工况 {"loadCase", "source",
84
+ "nodes": [{no, sys, fx..mz, mw}]}
85
+ """
86
+ if name is None:
87
+ return _query_all("GetAllSupportReaction")
88
+ return _query_by_names("GetSupportReactionByNames", name)
89
+
90
+
91
+ # ═════════════════════════════════════════════
92
+ # DataFrame 展平
93
+ # ═════════════════════════════════════════════
94
+
95
+ def _flatten(cases: list[dict], rows_key: str) -> "pd.DataFrame":
96
+ """把 [{loadCase, source, rows_key: [...]}, ...] 展平成单表。
97
+
98
+ 行内附带 loadCase/source 两列,便于多工况合并分析。
99
+ """
100
+ if not _HAS_PANDAS:
101
+ raise ImportError("结果导出功能依赖 pandas,请先安装:pip install pandas")
102
+ rows = []
103
+ for case in cases:
104
+ meta = {"loadCase": case.get("loadCase"), "source": case.get("source")}
105
+ for r in case.get(rows_key) or []:
106
+ rows.append({**meta, **r})
107
+ return pd.DataFrame(rows)
108
+
109
+
110
+ def node_displacement_df(name: str | list[str] | None = None) -> "pd.DataFrame":
111
+ """节点位移 DataFrame(列: loadCase, source, no, ux, uy, uz, rx, ry, rz, rw)"""
112
+ return _flatten(get_node_displacement(name), "nodes")
113
+
114
+
115
+ def element_force_df(name: str | list[str] | None = None) -> "pd.DataFrame":
116
+ """单元内力 DataFrame(列: loadCase, source, ele, node, fx, fy, fz, mx, my, mz, mw)"""
117
+ return _flatten(get_element_force(name), "elements")
118
+
119
+
120
+ def support_reaction_df(name: str | list[str] | None = None) -> "pd.DataFrame":
121
+ """支座反力 DataFrame(列: loadCase, source, no, sys, fx, fy, fz, mx, my, mz, mw)"""
122
+ return _flatten(get_support_reaction(name), "nodes")
pyosis/result/manager.py CHANGED
@@ -28,6 +28,11 @@ except ImportError:
28
28
  from .loadcase import osis_loadcase_result
29
29
  from .env import osis_env_result
30
30
  from .check import osis_check_result
31
+ from .headless import (
32
+ node_displacement_df,
33
+ element_force_df,
34
+ support_reaction_df,
35
+ )
31
36
 
32
37
 
33
38
  class ResultManager:
@@ -197,6 +202,67 @@ class ResultManager:
197
202
  )
198
203
  return df
199
204
 
205
+ # ═══════════════════════════════════════════
206
+ # 求解后无头查询(直接读求解器结果,不经 GUI 导出)
207
+ # ═══════════════════════════════════════════
208
+
209
+ def node_displacement(self, name: str | list[str] | None = None) -> pd.DataFrame:
210
+ """查询求解后节点位移
211
+
212
+ 走 /GetAllNodeDisplacement、/GetNodeDisplacementByNames 端点,
213
+ 优先从结果文件读,文件失败回落内存。
214
+
215
+ Args:
216
+ name: 工况名(str 或 list[str]);None 时返回全部工况
217
+
218
+ Returns:
219
+ 结果 DataFrame(列: loadCase, source, no, ux, uy, uz, rx, ry, rz, rw)
220
+
221
+ Raises:
222
+ ImportError: 未安装 pandas 时抛出
223
+ RuntimeError: 查询失败时抛出异常
224
+ """
225
+ self._ensure_pandas()
226
+ return node_displacement_df(name)
227
+
228
+ def element_force(self, name: str | list[str] | None = None) -> pd.DataFrame:
229
+ """查询求解后单元内力
230
+
231
+ 走 /GetAllElementForce、/GetElementForceByNames 端点,
232
+ 优先从结果文件读,文件失败回落内存。
233
+
234
+ Args:
235
+ name: 工况名(str 或 list[str]);None 时返回全部工况
236
+
237
+ Returns:
238
+ 结果 DataFrame(列: loadCase, source, ele, node, fx, fy, fz, mx, my, mz, mw)
239
+
240
+ Raises:
241
+ ImportError: 未安装 pandas 时抛出
242
+ RuntimeError: 查询失败时抛出异常
243
+ """
244
+ self._ensure_pandas()
245
+ return element_force_df(name)
246
+
247
+ def support_reaction(self, name: str | list[str] | None = None) -> pd.DataFrame:
248
+ """查询求解后支座反力
249
+
250
+ 走 /GetAllSupportReaction、/GetSupportReactionByNames 端点,
251
+ 优先从结果文件读,文件失败回落内存。
252
+
253
+ Args:
254
+ name: 工况名(str 或 list[str]);None 时返回全部工况
255
+
256
+ Returns:
257
+ 结果 DataFrame(列: loadCase, source, no, sys, fx, fy, fz, mx, my, mz, mw)
258
+
259
+ Raises:
260
+ ImportError: 未安装 pandas 时抛出
261
+ RuntimeError: 查询失败时抛出异常
262
+ """
263
+ self._ensure_pandas()
264
+ return support_reaction_df(name)
265
+
200
266
  # ═══════════════════════════════════════════
201
267
  # 验算结果全量导出
202
268
  # ═══════════════════════════════════════════
pyosis/section/manager.py CHANGED
@@ -1135,6 +1135,23 @@ class SectionManager(BasicManager):
1135
1135
  sections = [Section._from_dict(d) for d in data if isinstance(d, dict) and "no" in d]
1136
1136
  return sections
1137
1137
 
1138
+ def all_longitudinal_rebar(self) -> list[Rebar]:
1139
+ """获取所有截面的纵向钢筋信息(走 GetAllLongitudinalRebarInfo 端点)
1140
+
1141
+ 按截面内部映射顺序返回,与 all() 相比数据更轻量——
1142
+ 只有钢筋标志位与纵筋明细,不含截面几何/属性。
1143
+
1144
+ Returns:
1145
+ list[Rebar]: 各截面的钢筋信息列表
1146
+
1147
+ Raises:
1148
+ RuntimeError: 查询失败时抛出异常
1149
+ """
1150
+ resp = osis_client("GetAllLongitudinalRebarInfo", {})
1151
+ if not resp.get("success"):
1152
+ raise RuntimeError(f"{resp.get('error')}")
1153
+ return [Rebar._from_dict(d) for d in resp.get("data", []) if isinstance(d, dict) and d]
1154
+
1138
1155
  def _next_no(self) -> int:
1139
1156
  """分配新截面编号"""
1140
1157
  sections = self._load()
@@ -4,18 +4,28 @@
4
4
  - direct: engine.method(args...)
5
5
  - chain: engine.get(key).method(reordered args...)
6
6
 
7
+ 长参数列表(≥ KWARGS_MIN 个形参、签名可内省、无 *args)的调用生成为
8
+ 关键字实参——命令流字段重排不再静默错位到别的形参上。
7
9
  矩阵 *dim / 赋值仍由 MatrixAccumulator 合并为 engine.matrix(...)。
8
10
  未注册命令 → engine.run("原始命令流")。
11
+
12
+ generate_lines(commands, ctx=None) 的 ctx 为跨命令下文:
13
+ ctx["creep_grades"]: 编号 → CONC 材料等级集合(由 out_to_python 预扫描)
14
+ ctx["warnings"]: fixer 追加的告警,作为注释行插在对应调用前
9
15
  """
10
16
 
11
17
  from __future__ import annotations
12
18
 
13
19
  from typing import List
14
20
 
21
+ from .introspect import positional_param_names, resolve_chain_method, resolve_callable
15
22
  from .matrix import MatrixAccumulator
16
23
  from .parser import ParsedCommand
17
24
  from .routes import CMD_ALIASES, REST_FIXERS, ROUTES
18
25
 
26
+ # 形参个数达到该值的调用才生成关键字实参;短调用保持位置实参(生成的代码更紧凑)
27
+ KWARGS_MIN = 5
28
+
19
29
  _ROUTE_ALIASES = {
20
30
  "clear": "Clear",
21
31
  "clc": "Clc",
@@ -52,46 +62,64 @@ def _fallback_run(cmd: ParsedCommand) -> str:
52
62
  return f'engine.run("{raw}")'
53
63
 
54
64
 
55
- def _render_route(cmd: ParsedCommand) -> str:
65
+ def _join_args(fields: list[str], func) -> str:
66
+ """按目标方法签名渲染实参:长签名用关键字实参,其余位置实参。"""
67
+ formatted = [_format_value(v) for v in fields]
68
+ if not formatted:
69
+ return ""
70
+ if len(formatted) >= KWARGS_MIN and func is not None:
71
+ names = positional_param_names(func)
72
+ # 实参个数须不超过形参个数(逐位对应),否则映射不可靠,退回位置实参
73
+ if names and len(formatted) <= len(names):
74
+ return ", ".join(f"{n}={v}" for n, v in zip(names, formatted))
75
+ return ", ".join(formatted)
76
+
77
+
78
+ def _render_route(cmd: ParsedCommand, ctx: dict | None) -> str:
56
79
  """按 ROUTES 生成单行 Python 调用,无 per-command 特殊分支。"""
57
- route = ROUTES.get(_route_key(cmd.name))
80
+ key = _route_key(cmd.name)
81
+ route = ROUTES.get(key)
58
82
  if route is None:
59
83
  return _fallback_run(cmd)
60
84
 
85
+ engine = ctx.get("engine") if ctx else None
86
+
61
87
  fields = cmd.fields[1:]
62
88
 
63
89
  if isinstance(route, str):
64
- fixer = REST_FIXERS.get(_route_key(cmd.name))
90
+ fixer = REST_FIXERS.get(key)
65
91
  if fixer is not None:
66
- fields = fixer(fields)
67
- formatted = [_format_value(v) for v in fields]
68
- if not formatted:
69
- return f"{route}()"
70
- return f"{route}({', '.join(formatted)})"
92
+ fields = fixer(fields, ctx)
93
+ args = _join_args(fields, resolve_callable(engine, route) if engine else None)
94
+ return f"{route}({args})"
71
95
 
72
96
  if isinstance(route, tuple) and route[0] == "chain":
73
97
  _, get_path, method_name, skip = route[:4]
74
98
  rest_prefix = route[4] if len(route) > 4 else 0
75
99
  if len(fields) <= skip:
76
100
  return f"{get_path}().{method_name}()"
77
- key = fields[skip]
101
+ key_field = fields[skip]
78
102
  rest_fields = list(fields[:rest_prefix]) + list(fields[skip + 1:])
79
- fixer = REST_FIXERS.get(_route_key(cmd.name))
103
+ fixer = REST_FIXERS.get(key)
80
104
  if fixer is not None:
81
- rest_fields = fixer(rest_fields)
82
- formatted_key = _format_value(key)
83
- formatted_rest = [_format_value(v) for v in rest_fields]
84
- if formatted_rest:
85
- return f"{get_path}({formatted_key}).{method_name}({', '.join(formatted_rest)})"
86
- return f"{get_path}({formatted_key}).{method_name}()"
105
+ rest_fields = fixer(rest_fields, ctx)
106
+ method = resolve_chain_method(engine, get_path, method_name) if engine else None
107
+ args = _join_args(rest_fields, method)
108
+ formatted_key = _format_value(key_field)
109
+ return f"{get_path}({formatted_key}).{method_name}({args})"
87
110
 
88
111
  return _fallback_run(cmd)
89
112
 
90
113
 
91
- def generate_lines(commands: List[ParsedCommand]) -> List[str]:
92
- """生成 Python 调用行;矩阵命令合并为 engine.matrix(...)。"""
114
+ def generate_lines(commands: List[ParsedCommand], ctx: dict | None = None) -> List[str]:
115
+ """生成 Python 调用行;矩阵命令合并为 engine.matrix(...)。
116
+
117
+ ctx 同时传 engine 实例时可启用关键字实参;fixer 告警以注释行形式
118
+ 插在对应调用前。
119
+ """
93
120
  lines: List[str] = []
94
121
  accumulator = MatrixAccumulator()
122
+ warnings = ctx.setdefault("warnings", []) if ctx is not None else None
95
123
 
96
124
  for cmd in commands:
97
125
  if cmd.name in _SKIP_COMMANDS:
@@ -111,7 +139,11 @@ def generate_lines(commands: List[ParsedCommand]) -> List[str]:
111
139
  if flushed:
112
140
  lines.append(flushed)
113
141
 
114
- lines.append(_render_route(cmd))
142
+ rendered = _render_route(cmd, ctx)
143
+ if warnings:
144
+ lines.extend(f"# 注意: {w}" for w in warnings)
145
+ warnings.clear()
146
+ lines.append(rendered)
115
147
 
116
148
  flushed = accumulator.flush()
117
149
  if flushed:
@@ -120,5 +152,5 @@ def generate_lines(commands: List[ParsedCommand]) -> List[str]:
120
152
  return lines
121
153
 
122
154
 
123
- def generate(commands: List[ParsedCommand]) -> str:
124
- return "\n".join(generate_lines(commands)) + "\n"
155
+ def generate(commands: List[ParsedCommand], ctx: dict | None = None) -> str:
156
+ return "\n".join(generate_lines(commands, ctx)) + "\n"
@@ -0,0 +1,149 @@
1
+ """engine 方法签名内省(transfer 专用)。
2
+
3
+ 供两处使用:
4
+ - generator: 把长参数列表的调用生成为关键字实参,参数重排不再破坏生成的脚本
5
+ - out_to_python: 取方法 docstring 首行作为生成代码的注释
6
+
7
+ engine 属性是 property 描述符,链式调用中间还有 .get(...) 返回的实体对象,
8
+ 所以这里按" property 返回注解 → 管理器类 → get 注解 → 实体类"逐层解析,
9
+ 全程不实例化任何管理器。
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import inspect
15
+ import sys
16
+ from typing import Any
17
+
18
+
19
+ def _eval_annotation(target: Any, owner: Any = None) -> list[type]:
20
+ """把返回注解规整成类列表(展开 Optional/Union/list 等泛型)。
21
+
22
+ target 为字符串注解时(from __future__ annotations 下必然如此),
23
+ 在 owner 函数所属模块的命名空间里求值。
24
+ """
25
+ ann = target
26
+ if isinstance(ann, str):
27
+ mod = sys.modules.get(getattr(owner, "__module__", "")) if owner is not None else None
28
+ ns = dict(vars(mod)) if mod is not None else {}
29
+ try:
30
+ ann = eval(ann, ns) # noqa: S307 - 注解来自本仓库代码
31
+ except Exception:
32
+ return []
33
+ out: list[type] = []
34
+ if isinstance(ann, type):
35
+ out.append(ann)
36
+ else:
37
+ for arg in getattr(ann, "__args__", ()) or ():
38
+ if isinstance(arg, type):
39
+ out.append(arg)
40
+ else:
41
+ for inner in getattr(arg, "__args__", ()) or ():
42
+ if isinstance(inner, type):
43
+ out.append(inner)
44
+ return out
45
+
46
+
47
+ def _walk_class(cls: type, name: str) -> Any:
48
+ """在类(含基类)上找属性;property 描述符取其 fget 继续向下解析。"""
49
+ attr = vars(cls).get(name)
50
+ if attr is None:
51
+ return None
52
+ if isinstance(attr, property):
53
+ return attr.fget
54
+ return attr
55
+
56
+
57
+ def _return_class_of(func: Any) -> type | None:
58
+ """取函数返回注解中的第一个类(property.fget → 管理器类等)。"""
59
+ try:
60
+ sig = inspect.signature(func)
61
+ except (ValueError, TypeError):
62
+ return None
63
+ if sig.return_annotation is inspect.Parameter.empty:
64
+ return None
65
+ for cls in _eval_annotation(sig.return_annotation, func):
66
+ return cls
67
+ return None
68
+
69
+
70
+ def resolve_callable(engine: object, dotted: str) -> Any:
71
+ """解析 'engine.section.get' / 'engine.prop.creep_shrink.create' 等点路径。
72
+
73
+ 实例属性直接 getattr(property 已实例化解析);类级回退按
74
+ "property → fget → 返回注解类" 逐层下钻,全程不实例化。失败返回 None。
75
+ """
76
+ parts = dotted.split(".")
77
+ if len(parts) < 2 or parts[0] != "engine":
78
+ return None
79
+
80
+ # 1) 实例直取
81
+ try:
82
+ obj: Any = engine
83
+ for p in parts[1:]:
84
+ obj = getattr(obj, p)
85
+ if callable(obj):
86
+ return obj
87
+ except AttributeError:
88
+ pass
89
+
90
+ # 2) 类级解析(OSISEngine 上的 property 需经 fget → 返回注解类下钻)
91
+ from pyosis.core.engine import OSISEngine
92
+
93
+ obj: Any = OSISEngine
94
+ for p in parts[1:]:
95
+ if isinstance(obj, type):
96
+ obj = _walk_class(obj, p)
97
+ else:
98
+ # 上一段解析出的是 getter 函数:落到其返回注解类上继续找
99
+ cls = _return_class_of(obj) if callable(obj) else None
100
+ obj = _walk_class(cls, p) if cls is not None else None
101
+ if obj is None:
102
+ return None
103
+ if isinstance(obj, (staticmethod, classmethod)):
104
+ obj = obj.__func__
105
+ return obj if callable(obj) else None
106
+
107
+
108
+ def resolve_chain_method(engine: object, get_path: str, method_name: str) -> Any:
109
+ """解析链式路由的终点方法: engine.<mgr>.get(k).<method>。
110
+
111
+ get 的返回注解给出实体类(Section/LoadCase/...),再在其上找 method。
112
+ """
113
+ get_func = resolve_callable(engine, get_path)
114
+ if get_func is None:
115
+ return None
116
+ try:
117
+ sig = inspect.signature(get_func)
118
+ except (ValueError, TypeError):
119
+ return None
120
+ if sig.return_annotation is inspect.Parameter.empty:
121
+ return None
122
+ for cls in _eval_annotation(sig.return_annotation, get_func):
123
+ target = vars(cls).get(method_name)
124
+ if target is not None and callable(target):
125
+ return target
126
+ return None
127
+
128
+
129
+ def positional_param_names(func: Any) -> tuple[str, ...] | None:
130
+ """取函数的显式位置参数名;带 *args/**kwargs 或解析失败时返回 None。
131
+
132
+ 类上取到的方法带 self,跳过;返回 None 表示调用方应保持位置实参生成。
133
+ """
134
+ try:
135
+ sig = inspect.signature(func)
136
+ except (ValueError, TypeError):
137
+ return None
138
+ names: list[str] = []
139
+ for p in sig.parameters.values():
140
+ if p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD):
141
+ return None
142
+ if p.kind is p.POSITIONAL_ONLY:
143
+ return None
144
+ if p.kind is p.KEYWORD_ONLY:
145
+ continue
146
+ names.append(p.name)
147
+ if names and names[0] in ("self", "cls"):
148
+ names = names[1:]
149
+ return tuple(names)
@@ -138,8 +138,12 @@ def _split_by_module(text: str) -> tuple[list[ParsedCommand], dict[str, list[Par
138
138
 
139
139
 
140
140
  # 读取 .out 文件内容(容错编码)
141
+ # 实测 5.1(2026-10 构建)export_apdl 导出为 UTF-8(无 BOM,"混"=e6b7b7);
142
+ # 该文件按 GBK 解码会失败,但部分 UTF-8 中文恰好是合法 GBK → 会静默乱码,
143
+ # 所以 UTF-8 必须在前。旧版(≤5.01)若导出 GBK:GBK 双字节第二字节常为
144
+ # 0x40-0x7E,不是合法 UTF-8 连续字节,按 UTF-8 解码会抛错并正确回落到 GBK。
141
145
  def _read_out_text(path: Path) -> str:
142
- for encoding in ("gbk", "utf-8", "gb2312", "gb18030", "latin-1"):
146
+ for encoding in ("utf-8-sig", "utf-8", "gbk", "gb18030", "latin-1"):
143
147
  try:
144
148
  return path.read_text(encoding=encoding)
145
149
  except UnicodeDecodeError:
@@ -300,6 +304,40 @@ def _insert_method_doc_comments(lines: list[str]) -> list[str]:
300
304
  return out
301
305
 
302
306
 
307
+ # ── 跨命令下文:CONC 材料 → 收缩徐变引用 ────────────────────────────
308
+
309
+ def _strip_quotes(raw: str) -> str:
310
+ return raw.strip().strip("\"'")
311
+
312
+
313
+ def _scan_creep_grades(commands: Iterable[ParsedCommand]) -> dict[str, set[str]]:
314
+ """预扫描 Material 命令,建立 {收缩徐变编号: {混凝土等级, ...}}。
315
+
316
+ 命令流: Material,No,Name,CONC,Code,Grade,CrepShrk[,Dmp]
317
+ .out 中 PROPERTY(CrpShrk) 段在 MATERIAL 段之前,前向引用必须先扫全量。
318
+ """
319
+ grades: dict[str, set[str]] = {}
320
+ for cmd in commands:
321
+ if _route_key(cmd.name) != "Material":
322
+ continue
323
+ f = cmd.fields
324
+ for i in range(1, len(f)):
325
+ if _strip_quotes(f[i]).upper() != "CONC":
326
+ continue
327
+ grade = _strip_quotes(f[i + 2]) if i + 2 < len(f) else ""
328
+ creep = _strip_quotes(f[i + 3]) if i + 3 < len(f) else ""
329
+ if grade and creep:
330
+ grades.setdefault(creep, set()).add(grade)
331
+ break
332
+ return grades
333
+
334
+
335
+ def _route_key(name: str) -> str:
336
+ """与 generator._route_key 一致的命令名归一(此处避免循环导入,本地实现)。"""
337
+ from pyosis.transfer.routes import CMD_ALIASES
338
+ return CMD_ALIASES.get(name, name)
339
+
340
+
303
341
  # 写入 prep 模块
304
342
  def _write_prep_module(prep_dir: Path, module: str, lines: list[str]) -> Path:
305
343
  """写入 prep 模块;lines 为空时写 pass stub。
@@ -401,17 +439,25 @@ def write_prep_outputs(out_path: Path, prep_dir: Path) -> tuple[int, list[Path]]
401
439
  text = _read_out_text(out_path)
402
440
  preamble, by_module = _split_by_module(text)
403
441
 
442
+ # 跨命令下文:先扫全量命令拿到 CONC 材料等级 → 收缩徐变编号 的引用关系,
443
+ # _fix_creep_shrk 升级旧 CrpShrk 时据此推断 fcuk(而不是写死 50MPa)。
444
+ # engine 只用于方法签名内省(生成关键字实参),不产生连接。
445
+ all_cmds: list[ParsedCommand] = list(preamble)
446
+ for cmds in by_module.values():
447
+ all_cmds.extend(cmds)
448
+ ctx: dict = {"engine": _get_engine(), "creep_grades": _scan_creep_grades(all_cmds)}
449
+
404
450
  code_line_count = 0
405
451
  prep_paths: list[Path] = []
406
452
 
407
453
  for module in MODULE_ORDER:
408
454
  cmds = by_module.get(module, [])
409
- lines = generate_lines(cmds) if cmds else []
455
+ lines = generate_lines(cmds, ctx) if cmds else []
410
456
  code_line_count += len(lines)
411
457
  prep_paths.append(_write_prep_module(prep_dir, module, lines))
412
458
 
413
459
  # 前言(典型 clear/clc)放到 main.py 顶部;无前言时为空列表
414
- preamble_lines = generate_lines(preamble) if preamble else []
460
+ preamble_lines = generate_lines(preamble, ctx) if preamble else []
415
461
 
416
462
  (prep_dir / "_0_engine.py").write_text(
417
463
  '"""模块级单例 OSISEngine,供同包内其他 prep 模块 import 使用。\n\n'
pyosis/transfer/routes.py CHANGED
@@ -8,8 +8,15 @@
8
8
  "chain": (engine_get_path, obj_method_name, skip_fields)
9
9
  Cmd,fields[skip_fields=0]=key, fields[skip_fields+1:]=args
10
10
  生成: engine.get(key).method(args...)
11
+
12
+ fixer 签名: fixer(rest, ctx=None) -> list[str]
13
+ ctx 为生成器下文(dict),无跨命令信息时忽略;key 约定:
14
+ ctx["creep_grades"]: {收缩徐变编号(str): {"C40", ...}} 引用它的 CONC 材料等级
15
+ ctx["warnings"]: list[str],fixer 追加、生成器作为注释行输出
11
16
  """
12
17
 
18
+ import re
19
+
13
20
  # 5.01 版 .out 使用缩写命令名,生成代码前统一归一化为全名
14
21
  CMD_ALIASES = {
15
22
  "N": "Node",
@@ -24,7 +31,7 @@ CMD_ALIASES = {
24
31
  }
25
32
 
26
33
  # 命令流字段顺序 ≠ 方法形参顺序的命令,按字段名重排后再生成调用
27
- def _fix_section_mesh(rest: list[str]) -> list[str]:
34
+ def _fix_section_mesh(rest: list[str], ctx=None) -> list[str]:
28
35
  """SectionMesh 字段序 → set_mesh(mesh_method, mesh_size, part_id)
29
36
 
30
37
  新格式: PartID, MeshMethod, MeshSize → MeshMethod, MeshSize, PartID
@@ -36,7 +43,7 @@ def _fix_section_mesh(rest: list[str]) -> list[str]:
36
43
  return rest
37
44
 
38
45
 
39
- def _fix_section_part(rest: list[str]) -> list[str]:
46
+ def _fix_section_part(rest: list[str], ctx=None) -> list[str]:
40
47
  """SectionPart 字段序 → add_part(type, part_index, mat_type, e, mu, density, *matrices)
41
48
 
42
49
  命令流: PartIndex, PartMatType, PartE, PartMu, PartDensity, PartGeoType, Matrices...
@@ -46,7 +53,42 @@ def _fix_section_part(rest: list[str]) -> list[str]:
46
53
  return rest
47
54
 
48
55
 
49
- def _fix_creep_shrk(rest: list[str]) -> list[str]:
56
+ _GRADE_RE = re.compile(r"^C(\d+)$", re.IGNORECASE)
57
+
58
+
59
+ def _resolve_fcuk(index: str, ctx: dict | None) -> str:
60
+ """从引用该收缩徐变特性的 CONC 材料等级推断 fcuk(如 C50 → 5e7,单位随工程)。
61
+
62
+ 软件侧 UpdatePreviousCommand 与本转换器旧逻辑都硬编码 50MPa——C40/C55 的
63
+ 旧模型会静默算错收缩徐变,这里改为按材料等级取值;多等级共用/无引用时
64
+ 保持 50MPa 并追加告警注释。
65
+ """
66
+ default = "50000000"
67
+ if not ctx:
68
+ return default
69
+ grades = (ctx.get("creep_grades") or {}).get(index.strip().strip('"\'')) or set()
70
+ if not grades:
71
+ (ctx.setdefault("warnings", [])).append(
72
+ f"CrpShrk {index}: 未找到引用它的 CONC 材料,fcuk 保持默认 50MPa"
73
+ "(旧命令流未记录强度,请核对该特性参数)"
74
+ )
75
+ return default
76
+ if len(grades) > 1:
77
+ (ctx.setdefault("warnings", [])).append(
78
+ f"CrpShrk {index}: 被 {'/'.join(sorted(grades))} 多种强度等级共用,"
79
+ f"无法唯一推断 fcuk,保持默认 50MPa;请核对该特性参数"
80
+ )
81
+ return default
82
+ m = _GRADE_RE.match(next(iter(grades)).strip())
83
+ if not m:
84
+ (ctx.setdefault("warnings", [])).append(
85
+ f"CrpShrk {index}: 材料等级 {next(iter(grades))!r} 无法换算 fcuk,保持默认 50MPa"
86
+ )
87
+ return default
88
+ return f"{int(m.group(1))}e6"
89
+
90
+
91
+ def _fix_creep_shrk(rest: list[str], ctx=None) -> list[str]:
50
92
  """CrpShrk 旧命令流 → 新 9 字段序(同软件侧 UpdatePreviousCommand 的升级逻辑)
51
93
 
52
94
  新: Index, Name, Code, Fcuk, AVG.Humidity, ComponentApproximateSize,
@@ -56,7 +98,8 @@ def _fix_creep_shrk(rest: list[str]) -> list[str]:
56
98
  4.9.6: Index, Name, Humidity, Birth, Type.Coeff, BirthByShrinking (6 字段)
57
99
 
58
100
  旧格式的 Birth(加载龄期)在新命令流里已取消,直接丢弃;
59
- Code/Fcuk/尺寸/粉煤灰补齐为软件升级时写入的默认值。
101
+ Code 固定 JTG3362_2018;Fcuk 优先按引用材料的混凝土强度等级取值
102
+ (C40→4e7),取不到时回退软件升级用的默认值 50MPa 并追加告警。
60
103
  """
61
104
  n = len(rest)
62
105
  if n == 9:
@@ -68,7 +111,8 @@ def _fix_creep_shrk(rest: list[str]) -> list[str]:
68
111
  index, name, humidity, _birth, type_coeff, shrink_age, fly_ash, size = rest
69
112
  else:
70
113
  return rest
71
- return [index, name, "JTG3362_2018", "50000000", humidity, size,
114
+ fcuk = _resolve_fcuk(index, ctx)
115
+ return [index, name, "JTG3362_2018", fcuk, humidity, size,
72
116
  type_coeff, shrink_age, fly_ash]
73
117
 
74
118