robust_motorcad.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  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. self.model_path = model_path
  254. # P5-M6: optional thermal solve (requires model with thermal
  255. # network configured; OFF by default to preserve EM-only behavior)
  256. self.enable_thermal = bool(enable_thermal)
  257. # P5-M6 thermal boundary: when set, Ambient_Temperature is overridden
  258. # before the thermal solve. MARS ships 125 C (abnormal); use 25-40.
  259. # None = leave the model value unchanged.
  260. self.ambient_temperature = ambient_temperature
  261. self.output_dir = output_dir or os.path.join(
  262. os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
  263. "output", f"run_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
  264. )
  265. self.raw_dir = os.path.join(self.output_dir, "raw")
  266. os.makedirs(self.raw_dir, exist_ok=True)
  267. self.point_timeout = point_timeout
  268. self.max_retries = max_retries
  269. self.headless = headless
  270. self.motorcad_version = motorcad_version
  271. self.mc = None
  272. self._popup_suppressed = False
  273. self._csv_path = os.path.join(self.output_dir, "scan_results.csv")
  274. self._json_path = os.path.join(self.output_dir, "scan_results.json")
  275. self._log_path = os.path.join(self.output_dir, "program_log.log")
  276. self._all_results: List[Dict[str, Any]] = []
  277. self._csv_header_written = False
  278. def connect(self) -> None:
  279. """Connect to a new Motor-CAD instance (never connect to existing).
  280. Supports:
  281. - Internal/external scripting context detection
  282. - BlackBox headless mode for server batch execution
  283. - set_visible(True) for /SCRIPTING mode (default hidden)
  284. Reference: Official doc section 2.1 connection modes.
  285. """
  286. ensure_environment()
  287. try:
  288. from ansys.motorcad.core import MotorCAD, is_running_in_internal_scripting
  289. # Detect internal vs external scripting context
  290. if is_running_in_internal_scripting():
  291. self.mc = MotorCAD(open_new_instance=False)
  292. self._log("Connected in internal scripting mode")
  293. else:
  294. # External script: always open new instance
  295. if self.headless:
  296. # BlackBox mode: no GUI, suitable for server batch
  297. self.mc = MotorCAD(open_new_instance=True, keep_instance_open=False)
  298. self._log("Connected in BlackBox headless mode")
  299. else:
  300. self.mc = MotorCAD(open_new_instance=True, keep_instance_open=False)
  301. self.mc.set_visible(True)
  302. self._log("Connected to new visible Motor-CAD instance")
  303. time.sleep(2) # Wait for instance to fully initialize
  304. # Health check: verify connection is responsive
  305. _ = self.mc.get_variable("Motor_Type")
  306. self._log("Connection health check passed")
  307. except MotorCADError as e:
  308. self._log(f"MotorCADError during connection: {e}")
  309. raise
  310. except Exception as e:
  311. self._log(f"Connection failed: {e}")
  312. raise
  313. def disconnect(self) -> None:
  314. """Disconnect from Motor-CAD instance.
  315. Always restores popup state before quitting.
  316. """
  317. if self.mc:
  318. # Restore popup state (critical: MessageDisplayState must be restored)
  319. self._restore_popup_state()
  320. try:
  321. # Reload baseline to leave clean state
  322. self.mc.load_from_file(self.model_path)
  323. except Exception:
  324. pass
  325. try:
  326. self.mc.quit()
  327. except Exception:
  328. pass
  329. self.mc = None
  330. self._log("Disconnected from Motor-CAD")
  331. def _suppress_popups(self) -> None:
  332. """Suppress Motor-CAD popups for batch execution.
  333. MessageDisplayState=2: messages go to independent window, no popups.
  334. Reference: Official doc section 2.3 popup control.
  335. WARNING: This disables critical dialogs (save prompts, overwrite
  336. confirmations). Must be restored with _restore_popup_state().
  337. """
  338. if self.mc and not self._popup_suppressed:
  339. try:
  340. var_name = resolve_variable_name("MessageDisplayState", self.motorcad_version)
  341. self.mc.set_variable(var_name, 2)
  342. self._popup_suppressed = True
  343. self._log("Popup suppression enabled (MessageDisplayState=2)")
  344. except MotorCADError as e:
  345. self._log(f"Failed to suppress popups: {e}")
  346. except Exception as e:
  347. self._log(f"Failed to suppress popups: {e}")
  348. def _restore_popup_state(self) -> None:
  349. """Restore popup state to default (0).
  350. Must be called in finally blocks to ensure restoration even on error.
  351. Reference: Official doc section 2.3 - "script must restore before exit".
  352. """
  353. if self.mc and self._popup_suppressed:
  354. try:
  355. var_name = resolve_variable_name("MessageDisplayState", self.motorcad_version)
  356. self.mc.set_variable(var_name, 0)
  357. self._popup_suppressed = False
  358. self._log("Popup state restored (MessageDisplayState=0)")
  359. except MotorCADError as e:
  360. self._log(f"Failed to restore popup state: {e}")
  361. except Exception as e:
  362. self._log(f"Failed to restore popup state: {e}")
  363. def _write_and_verify(self, variable: str, value: float,
  364. rel_tol: float = 1e-8, abs_tol: float = 1e-7) -> float:
  365. """Write variable and verify with get_variable. Mismatch raises.
  366. Reference: AGENTS.md constraint #4 - parameter must be read-back verified.
  367. Motor-CAD sometimes silently accepts inapplicable parameters.
  368. """
  369. # Resolve version-specific variable name
  370. actual_var = resolve_variable_name(variable, self.motorcad_version)
  371. try:
  372. self.mc.set_variable(actual_var, value)
  373. applied = float(self.mc.get_variable(actual_var))
  374. except MotorCADError as e:
  375. raise RuntimeError(f"MotorCADError writing {actual_var}: {e}")
  376. if not math.isclose(applied, value, rel_tol=rel_tol, abs_tol=abs_tol):
  377. raise RuntimeError(
  378. f"Variable {actual_var} write mismatch: applied={applied}, expected={value}"
  379. )
  380. return applied
  381. def run_preflight(self) -> PreflightResult:
  382. """Run 5-layer preflight self-check before simulation.
  383. Layers (reference: official doc section 3.3 troubleshooting checklist):
  384. 1. Connection: multi-version, Automation registration, port/firewall, Hide command Window
  385. 2. Permission: admin rights, default install path, post-install reboot
  386. 3. License: License Manager service, port, validity, concurrency
  387. 4. Model: region closure, duplicate regions, adaptive geometry reset
  388. 5. Script: MotorCADError handling, variable name mapping, popup state
  389. Returns:
  390. PreflightResult with all layer checks
  391. """
  392. result = PreflightResult()
  393. self._log("Starting 5-layer preflight self-check...")
  394. # Layer 1: Connection
  395. result.add_check("connection", "Motor-CAD instance connected",
  396. self.mc is not None, "Instance is active" if self.mc else "No instance")
  397. result.add_check("connection", "Connection responsive",
  398. self._check_connection_responsive(),
  399. "Instance responds to get_variable" if self._check_connection_responsive() else "Instance not responding")
  400. # Check for common "Hide command Window" issue (GitHub Issue #140)
  401. result.add_warning("connection",
  402. "If connection fails, check Motor-CAD Settings -> 'Hide command Window' is unchecked (known bug #140)")
  403. # Layer 2: Permission
  404. admin = is_running_as_admin()
  405. result.add_check("permission", "Running as administrator",
  406. admin, "Admin privileges active" if admin else "Not running as admin (may cause FE module errors)")
  407. if not admin:
  408. result.add_warning("permission",
  409. "Fault case #5: 'Unable to run FE module' may be solved by running as administrator")
  410. # Check default install path
  411. default_path = r"C:\ANSYS_Motor-CAD"
  412. has_default = os.path.exists(default_path)
  413. result.add_check("permission", "Default install path exists",
  414. has_default, f"Path {default_path} exists" if has_default else f"Default path {default_path} not found (non-default install may cause issues)")
  415. # Layer 3: License
  416. license_ok, license_msg = check_license_server()
  417. result.add_check("license", "License server reachable", license_ok, license_msg)
  418. if not license_ok:
  419. result.add_warning("license",
  420. "Fault case #8: Check Ansys License Manager service, port 1055, license file validity, and concurrency count")
  421. # Layer 4: Model
  422. model_exists = os.path.exists(self.model_path)
  423. result.add_check("model", "Baseline model file exists",
  424. model_exists, f"Model at {self.model_path}" if model_exists else f"Model not found at {self.model_path}")
  425. if model_exists and self.mc:
  426. try:
  427. self.mc.load_from_file(self.model_path)
  428. result.add_check("model", "Model loads successfully", True, "Model loaded without error")
  429. except MotorCADError as e:
  430. result.add_check("model", "Model loads successfully", False, f"MotorCADError: {e}")
  431. except Exception as e:
  432. result.add_check("model", "Model loads successfully", False, str(e))
  433. result.add_warning("model",
  434. "If using adaptive geometry, call reset_adaptive_geometry() before modifications; ensure regions are closed (is_closed()) and counter-clockwise")
  435. # Layer 5: Script
  436. result.add_check("script", "MotorCADError import available",
  437. HAS_MOTORCAD_ERROR,
  438. "ansys.motorcad.core.MotorCADError imported" if HAS_MOTORCAD_ERROR else "MotorCADError not available (using generic Exception fallback)")
  439. result.add_check("script", "Variable name mapping configured",
  440. len(VARIABLE_NAME_MAP) > 0,
  441. f"{len(VARIABLE_NAME_MAP)} variables in mapping table")
  442. result.add_check("script", "Popup state will be restored on disconnect",
  443. True, "try/finally pattern ensures MessageDisplayState restoration")
  444. self._log(result.summary())
  445. return result
  446. def _check_connection_responsive(self) -> bool:
  447. """Check if Motor-CAD instance is responsive."""
  448. if not self.mc:
  449. return False
  450. try:
  451. _ = self.mc.get_variable("Motor_Type")
  452. return True
  453. except Exception:
  454. return False
  455. def run_single_point(self, params: Dict[str, Any], point_index: int = 0,
  456. point_label: str = "",
  457. enable_thermal: Optional[bool] = None) -> Dict[str, Any]:
  458. """Run a single simulation point with full robustness protocol.
  459. Protocol:
  460. 1. Suppress popups (MessageDisplayState=2)
  461. 2. Reload baseline model
  462. 3. Check sampling/mesh compatibility
  463. 4. Write all parameters with write-back verification (version-resolved names)
  464. 5. Handle linked parameters (slot opening -> copper width)
  465. 6. Run magnetic calculation
  466. 7. Export and parse results
  467. 8. Write results to CSV and JSON (flush immediately)
  468. 9. Reload baseline again
  469. 10. Restore popup state (in finally)
  470. All Motor-CAD calls wrapped in try/except MotorCADError.
  471. """
  472. start_time = time.time()
  473. result = {
  474. "point_index": point_index,
  475. "point_label": point_label,
  476. "params": params,
  477. "status": "pending",
  478. "metrics": {},
  479. "error": None,
  480. "duration_s": 0,
  481. }
  482. # Suppress popups for batch execution
  483. self._suppress_popups()
  484. try:
  485. for attempt in range(self.max_retries):
  486. try:
  487. # Step 1: Reload baseline
  488. try:
  489. self.mc.load_from_file(self.model_path)
  490. except MotorCADError as e:
  491. raise RuntimeError(f"Baseline reload failed: {e}")
  492. # Step 2: Check sampling/mesh compatibility if present
  493. if "TorquePointsPerCycle" in params and "AirgapMeshPoints_mesh" in params:
  494. compatible, msg = check_sampling_mesh_compatibility(
  495. int(params["TorquePointsPerCycle"]),
  496. int(params["AirgapMeshPoints_mesh"])
  497. )
  498. if not compatible:
  499. self._log(f"WARNING: {msg}")
  500. result["error"] = msg
  501. result["status"] = "FAILED"
  502. # B5 fix: break instead of return so the point
  503. # is appended to results and written to disk
  504. break
  505. # Step 3: Write all numeric parameters with verification.
  506. # Non-numeric params (materials, grades, strings) are
  507. # skipped because set_variable expects a number. (C1 fix)
  508. for var, val in params.items():
  509. if var in ("point_index", "point_label", "point_id"):
  510. continue
  511. try:
  512. num = float(val)
  513. except (TypeError, ValueError):
  514. self._log(
  515. f"Skipping non-numeric param {var}={val!r}"
  516. )
  517. continue
  518. self._write_and_verify(var, num)
  519. # Step 4: Handle linked parameters
  520. if "Slot_Opening" in params and "Copper_Width" not in params:
  521. copper_w = compute_copper_width(float(params["Slot_Opening"]))
  522. self._write_and_verify("Copper_Width", copper_w)
  523. # Step 5: Run magnetic calculation
  524. try:
  525. self.mc.do_magnetic_calculation()
  526. except MotorCADError as e:
  527. raise RuntimeError(f"Magnetic calculation failed: {e}")
  528. # Step 5b: Optional thermal calculation (P5-M6)
  529. # Best-effort: thermal solve requires a model with thermal
  530. # network configured; failures are warnings, EM results
  531. # remain valid. enable_thermal param overrides instance default.
  532. _thermal_on = (
  533. enable_thermal if enable_thermal is not None
  534. else self.enable_thermal
  535. )
  536. if _thermal_on:
  537. try:
  538. # P5-M6 fix (2026-09-04): pymotorcad has NO
  539. # do_thermal_calculation() method. The steady-state
  540. # thermal solve is do_steady_state_analysis().
  541. # Verified against ansys.motorcad.core sources.
  542. if self.ambient_temperature is not None:
  543. self._write_and_verify(
  544. "Ambient_Temperature",
  545. float(self.ambient_temperature),
  546. )
  547. self._log(
  548. "Ambient_Temperature overridden to %s"
  549. % self.ambient_temperature
  550. )
  551. self.mc.do_steady_state_analysis()
  552. self._log("Steady-state thermal calculation completed")
  553. except Exception as _therr: # noqa: BLE001
  554. self._log(
  555. f"WARNING: thermal calculation failed "
  556. f"(model may lack thermal network): {_therr}"
  557. )
  558. # Step 6: Export and parse
  559. raw_file = os.path.join(
  560. self.raw_dir,
  561. f"result_{point_index:04d}_{point_label or 'point'}_{datetime.now().strftime('%H%M%S')}.csv"
  562. )
  563. try:
  564. self.mc.export_results("EMagnetic", raw_file)
  565. except MotorCADError as e:
  566. raise RuntimeError(f"Results export failed: {e}")
  567. # Verify export file actually exists
  568. if not os.path.exists(raw_file):
  569. raise RuntimeError(f"Export file not created: {raw_file}")
  570. metrics = self._parse_export(raw_file)
  571. # Step 6b: Optional thermal export and metric merge (P5-M6)
  572. # Best-effort: thermal export section name may vary by
  573. # Motor-CAD version; failures do not invalidate EM metrics.
  574. if _thermal_on:
  575. try:
  576. _thermal_file = raw_file.replace(".csv", "_thermal.csv")
  577. # solution_type is "SteadyState" (NOT "Thermal").
  578. # Valid values: EMagnetic / Lab / SteadyState / Transient.
  579. self.mc.export_results("SteadyState", _thermal_file)
  580. if os.path.exists(_thermal_file):
  581. _thermal_metrics = self._parse_export(_thermal_file)
  582. metrics.update(_thermal_metrics)
  583. self._log(
  584. "Thermal metrics merged: %s"
  585. % sorted(_thermal_metrics.keys())
  586. )
  587. except Exception as _texerr: # noqa: BLE001
  588. self._log(
  589. f"WARNING: thermal export/merge failed: {_texerr}"
  590. )
  591. result["metrics"] = metrics
  592. result["status"] = "OK"
  593. break
  594. except MotorCADError as e:
  595. result["error"] = f"MotorCADError: {e}"
  596. self._log(f"Point {point_index} attempt {attempt+1} MotorCADError: {e}")
  597. if attempt < self.max_retries - 1:
  598. self._log(f"Retrying point {point_index}...")
  599. time.sleep(2)
  600. self._reconnect_if_needed()
  601. else:
  602. result["status"] = "FAILED"
  603. except Exception as e:
  604. result["error"] = f"{type(e).__name__}: {e}"
  605. self._log(f"Point {point_index} attempt {attempt+1} failed: {e}")
  606. if attempt < self.max_retries - 1:
  607. self._log(f"Retrying point {point_index}...")
  608. time.sleep(2)
  609. self._reconnect_if_needed()
  610. else:
  611. result["status"] = "FAILED"
  612. finally:
  613. # Restore popup state (CRITICAL: must happen even on error)
  614. self._restore_popup_state()
  615. # Reload baseline to leave clean state
  616. try:
  617. if self.mc:
  618. self.mc.load_from_file(self.model_path)
  619. except Exception:
  620. pass
  621. result["duration_s"] = round(time.time() - start_time, 2)
  622. self._all_results.append(result)
  623. self._write_result_to_disk(result)
  624. return result
  625. def _reconnect_if_needed(self) -> None:
  626. """Check if instance is responsive, reconnect if not."""
  627. if not self._check_connection_responsive():
  628. self._log("Instance unresponsive, reconnecting...")
  629. try:
  630. self.disconnect()
  631. except Exception:
  632. pass
  633. try:
  634. self.connect()
  635. self._suppress_popups()
  636. except Exception as e:
  637. self._log(f"Reconnection failed: {e}")
  638. def read_graph_data(self, graph_name: str, max_points: int = 10000) -> List[Tuple[float, float]]:
  639. """Read graph data using "out-of-bounds = end" idiom.
  640. Motor-CAD API only exposes the most recently displayed curve.
  641. Reading past the end throws MotorCADError, which we use as
  642. the sequence termination signal.
  643. Reference: Official doc section 3.1 point 2 - graph reading idiom.
  644. Args:
  645. graph_name: Name of the graph to read (check in Motor-CAD Help -> Graph Viewer)
  646. max_points: Safety limit to prevent infinite loops
  647. Returns:
  648. List of (x, y) data points
  649. """
  650. points: List[Tuple[float, float]] = []
  651. if not self.mc:
  652. return points
  653. try:
  654. i = 0
  655. while i < max_points:
  656. try:
  657. x = self.mc.get_magnetic_graph_point(graph_name, i)
  658. # get_magnetic_graph_point may return tuple or single value
  659. if isinstance(x, (list, tuple)):
  660. points.append((float(x[0]), float(x[1])))
  661. else:
  662. # Single value return - use index as x
  663. points.append((float(i), float(x)))
  664. i += 1
  665. except MotorCADError:
  666. # Out of bounds = end of data (official idiom)
  667. break
  668. except Exception:
  669. break
  670. except Exception as e:
  671. self._log(f"Graph reading error: {e}")
  672. return points
  673. def _parse_export(self, filepath: str) -> Dict[str, float]:
  674. """Parse Motor-CAD export CSV with normalized bilingual matching.
  675. Delegates to the platform single source of truth
  676. (src/afmcore/metrics.py), which applies full-width -> half-width
  677. normalization. This fixes the historical bug where tavg_nm and
  678. ripple_pct could not be matched due to invisible full-width chars
  679. in exported field names.
  680. """
  681. if not os.path.exists(filepath):
  682. return {}
  683. return _platform_extract_all_metrics(_platform_parse_export(filepath))
  684. def _write_result_to_disk(self, result: Dict[str, Any]) -> None:
  685. """Write result to CSV and JSON immediately (flush + fsync)."""
  686. if not self._csv_header_written:
  687. header = ["point_index", "point_label", "status", "duration_s"]
  688. for md in METRIC_DEFINITIONS:
  689. header.append(md["key"])
  690. if result["params"]:
  691. for k in result["params"]:
  692. if k not in ("point_index", "point_label"):
  693. header.append(f"param_{k}")
  694. with open(self._csv_path, "w", newline="", encoding="utf-8") as f:
  695. writer = csv.writer(f, delimiter=";")
  696. writer.writerow(header)
  697. f.flush()
  698. os.fsync(f.fileno())
  699. self._csv_header_written = True
  700. row = [result["point_index"], result["point_label"],
  701. result["status"], result["duration_s"]]
  702. for md in METRIC_DEFINITIONS:
  703. row.append(result["metrics"].get(md["key"], ""))
  704. if result["params"]:
  705. for k, v in result["params"].items():
  706. if k not in ("point_index", "point_label"):
  707. row.append(v)
  708. with open(self._csv_path, "a", newline="", encoding="utf-8") as f:
  709. writer = csv.writer(f, delimiter=";")
  710. writer.writerow(row)
  711. f.flush()
  712. os.fsync(f.fileno())
  713. with open(self._json_path, "w", encoding="utf-8") as f:
  714. json.dump({"results": self._all_results}, f, ensure_ascii=False, indent=2)
  715. f.flush()
  716. os.fsync(f.fileno())
  717. def _log(self, message: str) -> None:
  718. """Write timestamped log message."""
  719. ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
  720. line = f"[{ts}] {message}\n"
  721. try:
  722. with open(self._log_path, "a", encoding="utf-8") as f:
  723. f.write(line)
  724. f.flush()
  725. except Exception:
  726. pass
  727. def get_summary(self) -> Dict[str, Any]:
  728. """Get run summary."""
  729. ok = [r for r in self._all_results if r["status"] == "OK"]
  730. failed = [r for r in self._all_results if r["status"] == "FAILED"]
  731. return {
  732. "total": len(self._all_results),
  733. "ok": len(ok),
  734. "failed": len(failed),
  735. "output_dir": self.output_dir,
  736. "csv_path": self._csv_path,
  737. "json_path": self._json_path,
  738. "log_path": self._log_path,
  739. "headless_mode": self.headless,
  740. }