robust_motorcad.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. """Robust Motor-CAD simulation core (P4-M3 + reference doc enhancement).
  2. Integrates all robustness practices from reference projects and
  3. official Motor-CAD automation reference documentation:
  4. Connection & Lifecycle:
  5. - open_new_instance=True + set_visible(True) (never connect to existing)
  6. - BlackBox headless mode support for server batch execution
  7. - Internal/external scripting context detection (is_running_in_internal_scripting)
  8. - Environment variable fallback (MOTORCAD_ACTIVEX, ANSYSLMD_LICENSE_FILE)
  9. Error Handling:
  10. - MotorCADError first-catch (PyMotorCAD throws on failure, no silent success)
  11. - Per-point timeout + retry (max 3 attempts) + auto-reconnect
  12. - Instance crash detection and auto-restart
  13. Batch Safety:
  14. - MessageDisplayState=2 popup suppression with try/finally restore
  15. - Parameter write-back verification (set then get, mismatch = FAILED)
  16. - Per-point baseline reload (load_from_file before and after each point)
  17. - Sampling point / mesh compatibility check (avoid 120pt+840mesh popup)
  18. - Slot opening / PCB copper width linkage formula
  19. Data Integrity:
  20. - Result export parsing: semicolon CSV, bilingual field aliases, E-Magnetics priority
  21. - Per-point dual write (CSV + JSON) with flush + fsync
  22. - Graph data reading with "out-of-bounds = end" idiom (while + try/except MotorCADError)
  23. Preflight Self-Check (5 layers):
  24. - Connection layer: multi-version, Automation registration, port/firewall, Hide command Window
  25. - Permission layer: admin rights, default install path, post-install reboot
  26. - License layer: License Manager service, port, validity, concurrency
  27. - Model layer: region closure (is_closed), duplicate regions, adaptive geometry reset
  28. - Script layer: MotorCADError handling, variable name version mapping, popup state
  29. Variable Name Version Mapping:
  30. - Configurable mapping table (not hardcoded) for version-specific name changes
  31. - e.g. MagWindingType -> MagneticWindingType across versions
  32. All source is ASCII only; Chinese field names use \\uXXXX escapes.
  33. """
  34. from __future__ import annotations
  35. import csv
  36. import json
  37. import math
  38. import os
  39. import platform
  40. import socket
  41. import sys
  42. import time
  43. import traceback
  44. from datetime import datetime
  45. from pathlib import Path
  46. from typing import Any, Dict, List, Optional, Tuple
  47. # MotorCADError may not be available if pymotorcad is not installed
  48. try:
  49. from ansys.motorcad.core import MotorCADError
  50. HAS_MOTORCAD_ERROR = True
  51. except ImportError:
  52. MotorCADError = Exception # type: ignore
  53. HAS_MOTORCAD_ERROR = False
  54. # ---------------------------------------------------------------------------
  55. # Platform core import (single source of truth for metrics / parsing).
  56. # This replaces the historical per-file METRIC_DEFINITIONS copies, fixing the
  57. # drift bug (three inconsistent metric lists) and the tavg_nm / ripple_pct
  58. # parsing bug (normalized matching handles full-width chars in exports).
  59. # ---------------------------------------------------------------------------
  60. _ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  61. _SRC_DIR = os.path.join(_ROOT_DIR, "src")
  62. if _SRC_DIR not in sys.path:
  63. sys.path.insert(0, _SRC_DIR)
  64. from afmcore.metrics import ( # noqa: E402
  65. METRIC_DEFINITIONS,
  66. METRIC_KEYS,
  67. METRIC_LABELS,
  68. REQUIRED_METRICS,
  69. extract_all_metrics as _platform_extract_all_metrics,
  70. parse_export as _platform_parse_export,
  71. )
  72. # Known incompatible sampling point / mesh combinations that cause popups
  73. INCOMPATIBLE_SAMPLING_MESH = [
  74. (120, 840), # Motor-CAD warns mesh/time step mismatch, blocks batch
  75. ]
  76. # Recommended compatible combinations
  77. RECOMMENDED_SAMPLING_MESH = [
  78. (30, 840), # Fast trend scan
  79. (120, 960), # Medium confidence
  80. (180, 1680), # High confidence final
  81. ]
  82. # ---------------------------------------------------------------------------
  83. # Variable name version mapping (not hardcoded, configurable).
  84. # Reference: GitHub Issue #319 - parameter names change across versions
  85. # e.g. MagWindingType -> MagneticWindingType
  86. # ---------------------------------------------------------------------------
  87. VARIABLE_NAME_MAP: Dict[str, Dict[str, str]] = {
  88. # canonical_name: {version_range: actual_variable_name}
  89. # Business alias -> Motor-CAD actual variable name.
  90. # L0 / plan_schema use airgap_mm; Motor-CAD calls it Airgap.
  91. # Confirmed by variable probing (TEST-002, KNOWLEDGE_BASE).
  92. "airgap_mm": {
  93. "default": "Airgap",
  94. },
  95. "MagneticWindingType": {
  96. "default": "MagneticWindingType",
  97. "legacy": "MagWindingType", # pre-2023 versions
  98. },
  99. "TorquePointsPerCycle": {
  100. "default": "TorquePointsPerCycle",
  101. },
  102. "AirgapMeshPoints_mesh": {
  103. "default": "AirgapMeshPoints_mesh",
  104. },
  105. "AirgapMeshPoints_layers": {
  106. "default": "AirgapMeshPoints_layers",
  107. },
  108. "Slot_Opening": {
  109. "default": "Slot_Opening",
  110. },
  111. "Slot_Width": {
  112. "default": "Slot_Width",
  113. },
  114. "Copper_Width": {
  115. "default": "Copper_Width",
  116. },
  117. "MagnetCentralArc_HalbachRing": {
  118. "default": "MagnetCentralArc_HalbachRing",
  119. },
  120. "Magnet_Arc_[ED]": {
  121. "default": "Magnet_Arc_[ED]",
  122. },
  123. "MessageDisplayState": {
  124. "default": "MessageDisplayState",
  125. },
  126. }
  127. def resolve_variable_name(canonical_name: str, motorcad_version: Optional[str] = None) -> str:
  128. """Resolve canonical variable name to version-specific actual name.
  129. Args:
  130. canonical_name: Canonical parameter name (key in VARIABLE_NAME_MAP)
  131. motorcad_version: Motor-CAD version string, e.g. "2024.2.3"
  132. Returns:
  133. Actual variable name for this Motor-CAD version
  134. """
  135. mapping = VARIABLE_NAME_MAP.get(canonical_name, {})
  136. if not mapping:
  137. return canonical_name
  138. # For now, use default. Version-specific logic can be added here.
  139. return mapping.get("default", canonical_name)
  140. def ensure_environment() -> None:
  141. """Ensure Motor-CAD environment variables are set (non-login shell trap).
  142. Reference: AGENTS.md environment variable traps.
  143. Non-login shell may not inherit machine-level env vars:
  144. - MOTORCAD_ACTIVEX empty -> pymotorcad cannot find Motor-CAD
  145. - ANSYSLMD_LICENSE_FILE empty -> Motor-CAD silently exits after ~30s
  146. """
  147. if not os.environ.get("MOTORCAD_ACTIVEX"):
  148. try:
  149. from ansys.motorcad.core import set_motorcad_exe
  150. candidate = r"D:\Program Files\ANSYS Inc\v261\motorcad\MotorCAD.exe"
  151. if os.path.exists(candidate):
  152. set_motorcad_exe(candidate)
  153. except Exception:
  154. pass
  155. if not os.environ.get("ANSYSLMD_LICENSE_FILE"):
  156. os.environ["ANSYSLMD_LICENSE_FILE"] = "1055@localhost"
  157. def check_sampling_mesh_compatibility(torque_points: int, airgap_mesh: int) -> Tuple[bool, str]:
  158. """Check if sampling point / mesh combination is compatible.
  159. Returns (compatible, message). Incompatible combinations cause
  160. Motor-CAD popups that block unattended batch execution.
  161. Reference: MOTORCAD_SCAN_KNOWLEDGE_BASE.md section 6.2
  162. """
  163. for pts, mesh in INCOMPATIBLE_SAMPLING_MESH:
  164. if torque_points == pts and airgap_mesh == mesh:
  165. return False, (
  166. f"TorquePoints={torque_points} + AirgapMesh={airgap_mesh} "
  167. f"causes Motor-CAD popup. Use {RECOMMENDED_SAMPLING_MESH[1]} instead."
  168. )
  169. return True, "OK"
  170. def compute_copper_width(slot_opening_mm: float, clearance_mm: float = 0.2,
  171. conductor_count: int = 1) -> float:
  172. """Compute PCB copper width from slot opening (linkage formula).
  173. Copper_Width = (Slot_Opening - clearance) / 2 / conductor_count
  174. Reference: MOTORCAD_SCAN_KNOWLEDGE_BASE.md section 4.3
  175. """
  176. return round((slot_opening_mm - clearance_mm) / 2.0 / conductor_count, 3)
  177. def is_running_as_admin() -> bool:
  178. """Check if running with administrator privileges (Windows).
  179. Reference: Fault case #5 - "Unable to run FE module" solved by
  180. running as administrator.
  181. """
  182. try:
  183. if platform.system() == "Windows":
  184. import ctypes
  185. return ctypes.windll.shell32.IsUserAnAdmin() != 0
  186. return os.geteuid() == 0 # type: ignore
  187. except Exception:
  188. return False
  189. def check_license_server(host: str = "localhost", port: int = 1055, timeout: float = 3.0) -> Tuple[bool, str]:
  190. """Check if Ansys License Manager server is reachable.
  191. Reference: Fault case #8 - cannot get license.
  192. """
  193. try:
  194. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  195. sock.settimeout(timeout)
  196. result = sock.connect_ex((host, port))
  197. sock.close()
  198. if result == 0:
  199. return True, f"License server {host}:{port} reachable"
  200. return False, f"License server {host}:{port} not reachable (error code {result})"
  201. except Exception as e:
  202. return False, f"License server check failed: {e}"
  203. class PreflightResult:
  204. """Result of 5-layer preflight self-check."""
  205. def __init__(self):
  206. self.layers: Dict[str, Dict[str, Any]] = {
  207. "connection": {"passed": True, "checks": [], "warnings": []},
  208. "permission": {"passed": True, "checks": [], "warnings": []},
  209. "license": {"passed": True, "checks": [], "warnings": []},
  210. "model": {"passed": True, "checks": [], "warnings": []},
  211. "script": {"passed": True, "checks": [], "warnings": []},
  212. }
  213. def add_check(self, layer: str, name: str, passed: bool, message: str = "") -> None:
  214. if layer in self.layers:
  215. self.layers[layer]["checks"].append({"name": name, "passed": passed, "message": message})
  216. if not passed:
  217. self.layers[layer]["passed"] = False
  218. def add_warning(self, layer: str, message: str) -> None:
  219. if layer in self.layers:
  220. self.layers[layer]["warnings"].append(message)
  221. @property
  222. def all_passed(self) -> bool:
  223. return all(layer["passed"] for layer in self.layers.values())
  224. def to_dict(self) -> Dict[str, Any]:
  225. return {"all_passed": self.all_passed, "layers": self.layers}
  226. def summary(self) -> str:
  227. lines = ["Preflight Self-Check Summary:"]
  228. for layer_name, layer in self.layers.items():
  229. status = "PASS" if layer["passed"] else "FAIL"
  230. lines.append(f" [{status}] {layer_name} layer")
  231. for check in layer["checks"]:
  232. cs = "OK" if check["passed"] else "FAIL"
  233. lines.append(f" [{cs}] {check['name']}: {check['message']}")
  234. for warning in layer["warnings"]:
  235. lines.append(f" [WARN] {warning}")
  236. return "\n".join(lines)
  237. class RobustMotorCADSolver:
  238. """Robust Motor-CAD simulation solver with all best practices.
  239. Usage:
  240. solver = RobustMotorCADSolver(model_path="base.mot")
  241. solver.connect()
  242. preflight = solver.run_preflight()
  243. if preflight.all_passed:
  244. for params in parameter_list:
  245. result = solver.run_single_point(params, point_index=0)
  246. solver.disconnect()
  247. """
  248. def __init__(self, model_path: str, output_dir: Optional[str] = None,
  249. point_timeout: int = 300, max_retries: int = 3,
  250. headless: bool = False, motorcad_version: Optional[str] = None,
  251. enable_thermal: bool = False,
  252. ambient_temperature: Optional[float] = None,
  253. thermal_mode: Optional[str] = None):
  254. self.model_path = model_path
  255. # P5-M6: optional thermal solve (requires model with thermal
  256. # network configured; OFF by default to preserve EM-only behavior)
  257. self.enable_thermal = bool(enable_thermal)
  258. # P5-M6 thermal boundary: when set, Ambient_Temperature is overridden
  259. # before the thermal solve. MARS ships 125 C (abnormal); use 25-40.
  260. # None = leave the model value unchanged.
  261. self.ambient_temperature = ambient_temperature
  262. # P6 thermal modes (task-level): "off" (EM only) / "steady" (EM +
  263. # steady-state thermal) / "coupled" (magnetic-thermal coupled). None
  264. # = derive from enable_thermal at run time (backwards compatible).
  265. self.thermal_mode = thermal_mode
  266. self.output_dir = output_dir or os.path.join(
  267. os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
  268. "output", f"run_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
  269. )
  270. self.raw_dir = os.path.join(self.output_dir, "raw")
  271. os.makedirs(self.raw_dir, exist_ok=True)
  272. self.point_timeout = point_timeout
  273. self.max_retries = max_retries
  274. self.headless = headless
  275. self.motorcad_version = motorcad_version
  276. self.mc = None
  277. self._popup_suppressed = False
  278. self._csv_path = os.path.join(self.output_dir, "scan_results.csv")
  279. self._json_path = os.path.join(self.output_dir, "scan_results.json")
  280. self._log_path = os.path.join(self.output_dir, "program_log.log")
  281. self._all_results: List[Dict[str, Any]] = []
  282. self._csv_header_written = False
  283. def connect(self) -> None:
  284. """Connect to a new Motor-CAD instance (never connect to existing).
  285. Supports:
  286. - Internal/external scripting context detection
  287. - BlackBox headless mode for server batch execution
  288. - set_visible(True) for /SCRIPTING mode (default hidden)
  289. Reference: Official doc section 2.1 connection modes.
  290. """
  291. ensure_environment()
  292. try:
  293. from ansys.motorcad.core import MotorCAD, is_running_in_internal_scripting
  294. # Detect internal vs external scripting context
  295. if is_running_in_internal_scripting():
  296. self.mc = MotorCAD(open_new_instance=False)
  297. self._log("Connected in internal scripting mode")
  298. else:
  299. # External script: always open new instance
  300. if self.headless:
  301. # BlackBox mode: no GUI, suitable for server batch
  302. self.mc = MotorCAD(open_new_instance=True, keep_instance_open=False)
  303. self._log("Connected in BlackBox headless mode")
  304. else:
  305. self.mc = MotorCAD(open_new_instance=True, keep_instance_open=False)
  306. self.mc.set_visible(True)
  307. self._log("Connected to new visible Motor-CAD instance")
  308. time.sleep(2) # Wait for instance to fully initialize
  309. # Health check: verify connection is responsive
  310. _ = self.mc.get_variable("Motor_Type")
  311. self._log("Connection health check passed")
  312. except MotorCADError as e:
  313. self._log(f"MotorCADError during connection: {e}")
  314. raise
  315. except Exception as e:
  316. self._log(f"Connection failed: {e}")
  317. raise
  318. def disconnect(self) -> None:
  319. """Disconnect from Motor-CAD instance.
  320. Always restores popup state before quitting.
  321. """
  322. if self.mc:
  323. # Restore popup state (critical: MessageDisplayState must be restored)
  324. self._restore_popup_state()
  325. try:
  326. # Reload baseline to leave clean state
  327. self.mc.load_from_file(self.model_path)
  328. except Exception:
  329. pass
  330. try:
  331. self.mc.quit()
  332. except Exception:
  333. pass
  334. self.mc = None
  335. self._log("Disconnected from Motor-CAD")
  336. def _suppress_popups(self) -> None:
  337. """Suppress Motor-CAD popups for batch execution.
  338. MessageDisplayState=2: messages go to independent window, no popups.
  339. Reference: Official doc section 2.3 popup control.
  340. WARNING: This disables critical dialogs (save prompts, overwrite
  341. confirmations). Must be restored with _restore_popup_state().
  342. """
  343. if self.mc and not self._popup_suppressed:
  344. try:
  345. var_name = resolve_variable_name("MessageDisplayState", self.motorcad_version)
  346. self.mc.set_variable(var_name, 2)
  347. self._popup_suppressed = True
  348. self._log("Popup suppression enabled (MessageDisplayState=2)")
  349. except MotorCADError as e:
  350. self._log(f"Failed to suppress popups: {e}")
  351. except Exception as e:
  352. self._log(f"Failed to suppress popups: {e}")
  353. def _restore_popup_state(self) -> None:
  354. """Restore popup state to default (0).
  355. Must be called in finally blocks to ensure restoration even on error.
  356. Reference: Official doc section 2.3 - "script must restore before exit".
  357. """
  358. if self.mc and self._popup_suppressed:
  359. try:
  360. var_name = resolve_variable_name("MessageDisplayState", self.motorcad_version)
  361. self.mc.set_variable(var_name, 0)
  362. self._popup_suppressed = False
  363. self._log("Popup state restored (MessageDisplayState=0)")
  364. except MotorCADError as e:
  365. self._log(f"Failed to restore popup state: {e}")
  366. except Exception as e:
  367. self._log(f"Failed to restore popup state: {e}")
  368. def _write_and_verify(self, variable: str, value: float,
  369. rel_tol: float = 1e-8, abs_tol: float = 1e-7) -> float:
  370. """Write variable and verify with get_variable. Mismatch raises.
  371. Reference: AGENTS.md constraint #4 - parameter must be read-back verified.
  372. Motor-CAD sometimes silently accepts inapplicable parameters.
  373. """
  374. # Resolve version-specific variable name
  375. actual_var = resolve_variable_name(variable, self.motorcad_version)
  376. try:
  377. self.mc.set_variable(actual_var, value)
  378. applied = float(self.mc.get_variable(actual_var))
  379. except MotorCADError as e:
  380. raise RuntimeError(f"MotorCADError writing {actual_var}: {e}")
  381. if not math.isclose(applied, value, rel_tol=rel_tol, abs_tol=abs_tol):
  382. raise RuntimeError(
  383. f"Variable {actual_var} write mismatch: applied={applied}, expected={value}"
  384. )
  385. return applied
  386. def run_preflight(self) -> PreflightResult:
  387. """Run 5-layer preflight self-check before simulation.
  388. Layers (reference: official doc section 3.3 troubleshooting checklist):
  389. 1. Connection: multi-version, Automation registration, port/firewall, Hide command Window
  390. 2. Permission: admin rights, default install path, post-install reboot
  391. 3. License: License Manager service, port, validity, concurrency
  392. 4. Model: region closure, duplicate regions, adaptive geometry reset
  393. 5. Script: MotorCADError handling, variable name mapping, popup state
  394. Returns:
  395. PreflightResult with all layer checks
  396. """
  397. result = PreflightResult()
  398. self._log("Starting 5-layer preflight self-check...")
  399. # Layer 1: Connection
  400. result.add_check("connection", "Motor-CAD instance connected",
  401. self.mc is not None, "Instance is active" if self.mc else "No instance")
  402. result.add_check("connection", "Connection responsive",
  403. self._check_connection_responsive(),
  404. "Instance responds to get_variable" if self._check_connection_responsive() else "Instance not responding")
  405. # Check for common "Hide command Window" issue (GitHub Issue #140)
  406. result.add_warning("connection",
  407. "If connection fails, check Motor-CAD Settings -> 'Hide command Window' is unchecked (known bug #140)")
  408. # Layer 2: Permission
  409. admin = is_running_as_admin()
  410. result.add_check("permission", "Running as administrator",
  411. admin, "Admin privileges active" if admin else "Not running as admin (may cause FE module errors)")
  412. if not admin:
  413. result.add_warning("permission",
  414. "Fault case #5: 'Unable to run FE module' may be solved by running as administrator")
  415. # Check default install path
  416. default_path = r"C:\ANSYS_Motor-CAD"
  417. has_default = os.path.exists(default_path)
  418. result.add_check("permission", "Default install path exists",
  419. has_default, f"Path {default_path} exists" if has_default else f"Default path {default_path} not found (non-default install may cause issues)")
  420. # Layer 3: License
  421. license_ok, license_msg = check_license_server()
  422. result.add_check("license", "License server reachable", license_ok, license_msg)
  423. if not license_ok:
  424. result.add_warning("license",
  425. "Fault case #8: Check Ansys License Manager service, port 1055, license file validity, and concurrency count")
  426. # Layer 4: Model
  427. model_exists = os.path.exists(self.model_path)
  428. result.add_check("model", "Baseline model file exists",
  429. model_exists, f"Model at {self.model_path}" if model_exists else f"Model not found at {self.model_path}")
  430. if model_exists and self.mc:
  431. try:
  432. self.mc.load_from_file(self.model_path)
  433. result.add_check("model", "Model loads successfully", True, "Model loaded without error")
  434. except MotorCADError as e:
  435. result.add_check("model", "Model loads successfully", False, f"MotorCADError: {e}")
  436. except Exception as e:
  437. result.add_check("model", "Model loads successfully", False, str(e))
  438. result.add_warning("model",
  439. "If using adaptive geometry, call reset_adaptive_geometry() before modifications; ensure regions are closed (is_closed()) and counter-clockwise")
  440. # Layer 5: Script
  441. result.add_check("script", "MotorCADError import available",
  442. HAS_MOTORCAD_ERROR,
  443. "ansys.motorcad.core.MotorCADError imported" if HAS_MOTORCAD_ERROR else "MotorCADError not available (using generic Exception fallback)")
  444. result.add_check("script", "Variable name mapping configured",
  445. len(VARIABLE_NAME_MAP) > 0,
  446. f"{len(VARIABLE_NAME_MAP)} variables in mapping table")
  447. result.add_check("script", "Popup state will be restored on disconnect",
  448. True, "try/finally pattern ensures MessageDisplayState restoration")
  449. self._log(result.summary())
  450. return result
  451. def _check_connection_responsive(self) -> bool:
  452. """Check if Motor-CAD instance is responsive."""
  453. if not self.mc:
  454. return False
  455. try:
  456. _ = self.mc.get_variable("Motor_Type")
  457. return True
  458. except Exception:
  459. return False
  460. def run_single_point(self, params: Dict[str, Any], point_index: int = 0,
  461. point_label: str = "",
  462. enable_thermal: Optional[bool] = None,
  463. thermal_mode: Optional[str] = None) -> Dict[str, Any]:
  464. """Run a single simulation point with full robustness protocol.
  465. Protocol:
  466. 1. Suppress popups (MessageDisplayState=2)
  467. 2. Reload baseline model
  468. 3. Check sampling/mesh compatibility
  469. 4. Write all parameters with write-back verification (version-resolved names)
  470. 5. Handle linked parameters (slot opening -> copper width)
  471. 6. Run magnetic calculation
  472. 7. Export and parse results
  473. 8. Write results to CSV and JSON (flush immediately)
  474. 9. Reload baseline again
  475. 10. Restore popup state (in finally)
  476. All Motor-CAD calls wrapped in try/except MotorCADError.
  477. """
  478. start_time = time.time()
  479. result = {
  480. "point_index": point_index,
  481. "point_label": point_label,
  482. "params": params,
  483. "status": "pending",
  484. "metrics": {},
  485. "error": None,
  486. "duration_s": 0,
  487. }
  488. # Suppress popups for batch execution
  489. self._suppress_popups()
  490. try:
  491. for attempt in range(self.max_retries):
  492. try:
  493. # Step 1: Reload baseline
  494. try:
  495. self.mc.load_from_file(self.model_path)
  496. except MotorCADError as e:
  497. raise RuntimeError(f"Baseline reload failed: {e}")
  498. # Step 2: Check sampling/mesh compatibility if present
  499. if "TorquePointsPerCycle" in params and "AirgapMeshPoints_mesh" in params:
  500. compatible, msg = check_sampling_mesh_compatibility(
  501. int(params["TorquePointsPerCycle"]),
  502. int(params["AirgapMeshPoints_mesh"])
  503. )
  504. if not compatible:
  505. self._log(f"WARNING: {msg}")
  506. result["error"] = msg
  507. result["status"] = "FAILED"
  508. # B5 fix: break instead of return so the point
  509. # is appended to results and written to disk
  510. break
  511. # Step 3: Write all numeric parameters with verification.
  512. # Non-numeric params (materials, grades, strings) are
  513. # skipped because set_variable expects a number. (C1 fix)
  514. for var, val in params.items():
  515. if var in ("point_index", "point_label", "point_id"):
  516. continue
  517. try:
  518. num = float(val)
  519. except (TypeError, ValueError):
  520. self._log(
  521. f"Skipping non-numeric param {var}={val!r}"
  522. )
  523. continue
  524. self._write_and_verify(var, num)
  525. # Step 4: Handle linked parameters
  526. if "Slot_Opening" in params and "Copper_Width" not in params:
  527. copper_w = compute_copper_width(float(params["Slot_Opening"]))
  528. self._write_and_verify("Copper_Width", copper_w)
  529. # Step 5: Resolve thermal mode, then run EM / thermal solve.
  530. # Precedence: per-call thermal_mode > instance thermal_mode
  531. # > legacy enable_thermal boolean. Modes:
  532. # "off" = EM only
  533. # "steady" = EM then steady-state thermal (losses as source)
  534. # "coupled" = do_magnetic_thermal_calculation (EM<->thermal iterate)
  535. _mode = thermal_mode
  536. if _mode is None:
  537. _mode = self.thermal_mode
  538. if _mode is None:
  539. _legacy = (
  540. enable_thermal if enable_thermal is not None
  541. else self.enable_thermal
  542. )
  543. _mode = "steady" if _legacy else "off"
  544. self._log("Thermal mode: %s" % _mode)
  545. if _mode == "coupled":
  546. # Coupled solve runs EM + thermal iteration in one call.
  547. try:
  548. if self.ambient_temperature is not None:
  549. self._write_and_verify(
  550. "Ambient_Temperature",
  551. float(self.ambient_temperature),
  552. )
  553. self._log(
  554. "Ambient_Temperature overridden to %s"
  555. % self.ambient_temperature
  556. )
  557. self.mc.do_magnetic_thermal_calculation()
  558. self._log("Magnetic-thermal coupled solve completed")
  559. except MotorCADError as e:
  560. raise RuntimeError(f"Coupled solve failed: {e}")
  561. else:
  562. try:
  563. self.mc.do_magnetic_calculation()
  564. except MotorCADError as e:
  565. raise RuntimeError(f"Magnetic calculation failed: {e}")
  566. # Optional steady-state thermal (P5-M6). Best-effort:
  567. # failures are warnings, EM results remain valid.
  568. if _mode == "steady":
  569. try:
  570. if self.ambient_temperature is not None:
  571. self._write_and_verify(
  572. "Ambient_Temperature",
  573. float(self.ambient_temperature),
  574. )
  575. self._log(
  576. "Ambient_Temperature overridden to %s"
  577. % self.ambient_temperature
  578. )
  579. self.mc.do_steady_state_analysis()
  580. self._log("Steady-state thermal calculation completed")
  581. except Exception as _therr: # noqa: BLE001
  582. self._log(
  583. f"WARNING: thermal calculation failed "
  584. f"(model may lack thermal network): {_therr}"
  585. )
  586. # Step 6: Export and parse
  587. raw_file = os.path.join(
  588. self.raw_dir,
  589. f"result_{point_index:04d}_{point_label or 'point'}_{datetime.now().strftime('%H%M%S')}.csv"
  590. )
  591. try:
  592. self.mc.export_results("EMagnetic", raw_file)
  593. except MotorCADError as e:
  594. raise RuntimeError(f"Results export failed: {e}")
  595. # Verify export file actually exists
  596. if not os.path.exists(raw_file):
  597. raise RuntimeError(f"Export file not created: {raw_file}")
  598. metrics = self._parse_export(raw_file)
  599. # Step 6b: thermal export and metric merge for steady/coupled.
  600. # solution_type is "SteadyState" (NOT "Thermal").
  601. # Valid values: EMagnetic / Lab / SteadyState / Transient.
  602. if _mode in ("steady", "coupled"):
  603. try:
  604. _thermal_file = raw_file.replace(".csv", "_thermal.csv")
  605. self.mc.export_results("SteadyState", _thermal_file)
  606. if os.path.exists(_thermal_file):
  607. _thermal_metrics = self._parse_export(_thermal_file)
  608. metrics.update(_thermal_metrics)
  609. self._log(
  610. "Thermal metrics merged: %s"
  611. % sorted(_thermal_metrics.keys())
  612. )
  613. except Exception as _texerr: # noqa: BLE001
  614. self._log(
  615. f"WARNING: thermal export/merge failed: {_texerr}"
  616. )
  617. result["metrics"] = metrics
  618. result["status"] = "OK"
  619. break
  620. except MotorCADError as e:
  621. result["error"] = f"MotorCADError: {e}"
  622. self._log(f"Point {point_index} attempt {attempt+1} MotorCADError: {e}")
  623. if attempt < self.max_retries - 1:
  624. self._log(f"Retrying point {point_index}...")
  625. time.sleep(2)
  626. self._reconnect_if_needed()
  627. else:
  628. result["status"] = "FAILED"
  629. except Exception as e:
  630. result["error"] = f"{type(e).__name__}: {e}"
  631. self._log(f"Point {point_index} attempt {attempt+1} failed: {e}")
  632. if attempt < self.max_retries - 1:
  633. self._log(f"Retrying point {point_index}...")
  634. time.sleep(2)
  635. self._reconnect_if_needed()
  636. else:
  637. result["status"] = "FAILED"
  638. finally:
  639. # Restore popup state (CRITICAL: must happen even on error)
  640. self._restore_popup_state()
  641. # Reload baseline to leave clean state
  642. try:
  643. if self.mc:
  644. self.mc.load_from_file(self.model_path)
  645. except Exception:
  646. pass
  647. result["duration_s"] = round(time.time() - start_time, 2)
  648. self._all_results.append(result)
  649. self._write_result_to_disk(result)
  650. return result
  651. def _reconnect_if_needed(self) -> None:
  652. """Check if instance is responsive, reconnect if not."""
  653. if not self._check_connection_responsive():
  654. self._log("Instance unresponsive, reconnecting...")
  655. try:
  656. self.disconnect()
  657. except Exception:
  658. pass
  659. try:
  660. self.connect()
  661. self._suppress_popups()
  662. except Exception as e:
  663. self._log(f"Reconnection failed: {e}")
  664. def read_graph_data(self, graph_name: str, max_points: int = 10000) -> List[Tuple[float, float]]:
  665. """Read graph data using "out-of-bounds = end" idiom.
  666. Motor-CAD API only exposes the most recently displayed curve.
  667. Reading past the end throws MotorCADError, which we use as
  668. the sequence termination signal.
  669. Reference: Official doc section 3.1 point 2 - graph reading idiom.
  670. Args:
  671. graph_name: Name of the graph to read (check in Motor-CAD Help -> Graph Viewer)
  672. max_points: Safety limit to prevent infinite loops
  673. Returns:
  674. List of (x, y) data points
  675. """
  676. points: List[Tuple[float, float]] = []
  677. if not self.mc:
  678. return points
  679. try:
  680. i = 0
  681. while i < max_points:
  682. try:
  683. x = self.mc.get_magnetic_graph_point(graph_name, i)
  684. # get_magnetic_graph_point may return tuple or single value
  685. if isinstance(x, (list, tuple)):
  686. points.append((float(x[0]), float(x[1])))
  687. else:
  688. # Single value return - use index as x
  689. points.append((float(i), float(x)))
  690. i += 1
  691. except MotorCADError:
  692. # Out of bounds = end of data (official idiom)
  693. break
  694. except Exception:
  695. break
  696. except Exception as e:
  697. self._log(f"Graph reading error: {e}")
  698. return points
  699. def _parse_export(self, filepath: str) -> Dict[str, float]:
  700. """Parse Motor-CAD export CSV with normalized bilingual matching.
  701. Delegates to the platform single source of truth
  702. (src/afmcore/metrics.py), which applies full-width -> half-width
  703. normalization. This fixes the historical bug where tavg_nm and
  704. ripple_pct could not be matched due to invisible full-width chars
  705. in exported field names.
  706. """
  707. if not os.path.exists(filepath):
  708. return {}
  709. return _platform_extract_all_metrics(_platform_parse_export(filepath))
  710. def _write_result_to_disk(self, result: Dict[str, Any]) -> None:
  711. """Write result to CSV and JSON immediately (flush + fsync)."""
  712. if not self._csv_header_written:
  713. header = ["point_index", "point_label", "status", "duration_s"]
  714. for md in METRIC_DEFINITIONS:
  715. header.append(md["key"])
  716. if result["params"]:
  717. for k in result["params"]:
  718. if k not in ("point_index", "point_label"):
  719. header.append(f"param_{k}")
  720. with open(self._csv_path, "w", newline="", encoding="utf-8") as f:
  721. writer = csv.writer(f, delimiter=";")
  722. writer.writerow(header)
  723. f.flush()
  724. os.fsync(f.fileno())
  725. self._csv_header_written = True
  726. row = [result["point_index"], result["point_label"],
  727. result["status"], result["duration_s"]]
  728. for md in METRIC_DEFINITIONS:
  729. row.append(result["metrics"].get(md["key"], ""))
  730. if result["params"]:
  731. for k, v in result["params"].items():
  732. if k not in ("point_index", "point_label"):
  733. row.append(v)
  734. with open(self._csv_path, "a", newline="", encoding="utf-8") as f:
  735. writer = csv.writer(f, delimiter=";")
  736. writer.writerow(row)
  737. f.flush()
  738. os.fsync(f.fileno())
  739. with open(self._json_path, "w", encoding="utf-8") as f:
  740. json.dump({"results": self._all_results}, f, ensure_ascii=False, indent=2)
  741. f.flush()
  742. os.fsync(f.fileno())
  743. def _log(self, message: str) -> None:
  744. """Write timestamped log message."""
  745. ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
  746. line = f"[{ts}] {message}\n"
  747. try:
  748. with open(self._log_path, "a", encoding="utf-8") as f:
  749. f.write(line)
  750. f.flush()
  751. except Exception:
  752. pass
  753. def get_summary(self) -> Dict[str, Any]:
  754. """Get run summary."""
  755. ok = [r for r in self._all_results if r["status"] == "OK"]
  756. failed = [r for r in self._all_results if r["status"] == "FAILED"]
  757. return {
  758. "total": len(self._all_results),
  759. "ok": len(ok),
  760. "failed": len(failed),
  761. "output_dir": self.output_dir,
  762. "csv_path": self._csv_path,
  763. "json_path": self._json_path,
  764. "log_path": self._log_path,
  765. "headless_mode": self.headless,
  766. }