test_robust_solver.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. """Test script for RobustMotorCADSolver - Step 1: Connection and variable probing.
  2. This script tests:
  3. 1. Motor-CAD connection (open_new_instance=True + set_visible=True)
  4. 2. Model loading
  5. 3. Variable probing (get common variable names)
  6. 4. Parameter write-back verification
  7. 5. Single magnetic calculation
  8. 6. Result export and parsing
  9. All source is ASCII only.
  10. """
  11. import os
  12. import sys
  13. import time
  14. import json
  15. # Add project root to path
  16. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  17. from scripts.robust_motorcad import (
  18. RobustMotorCADSolver,
  19. ensure_environment,
  20. is_running_as_admin,
  21. check_license_server,
  22. )
  23. def main():
  24. print("=" * 60)
  25. print("RobustMotorCADSolver Test - Step 1: Connection & Probing")
  26. print("=" * 60)
  27. # Pre-checks
  28. print("\n[Pre-checks]")
  29. print(f" Running as admin: {is_running_as_admin()}")
  30. license_ok, license_msg = check_license_server()
  31. print(f" License server: {license_msg}")
  32. ensure_environment()
  33. print(f" MOTORCAD_ACTIVEX: {os.environ.get('MOTORCAD_ACTIVEX', 'not set')}")
  34. print(f" ANSYSLMD_LICENSE_FILE: {os.environ.get('ANSYSLMD_LICENSE_FILE', 'not set')}")
  35. # Model path
  36. model_path = os.path.join(
  37. os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
  38. "models", "MARS-12S10P_SSSR_D76-C150_V5.0-0819.mot"
  39. )
  40. print(f"\n Model path: {model_path}")
  41. print(f" Model exists: {os.path.exists(model_path)}")
  42. if not os.path.exists(model_path):
  43. print("ERROR: Model file not found!")
  44. return 1
  45. # Create solver
  46. print("\n[Creating solver]")
  47. solver = RobustMotorCADSolver(
  48. model_path=model_path,
  49. output_dir=os.path.join(
  50. os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
  51. "output", f"test_connect_{time.strftime('%Y%m%d_%H%M%S')}"
  52. ),
  53. point_timeout=120,
  54. max_retries=2,
  55. headless=False,
  56. )
  57. print(f" Output dir: {solver.output_dir}")
  58. # Connect
  59. print("\n[Step 1: Connecting to Motor-CAD]")
  60. try:
  61. solver.connect()
  62. print(" Connection SUCCESS")
  63. except Exception as e:
  64. print(f" Connection FAILED: {e}")
  65. return 1
  66. # Run preflight
  67. print("\n[Step 2: Running preflight self-check]")
  68. try:
  69. preflight = solver.run_preflight()
  70. print(preflight.summary())
  71. except Exception as e:
  72. print(f" Preflight error: {e}")
  73. # Probe variables
  74. print("\n[Step 3: Probing common variables]")
  75. common_vars = [
  76. "Motor_Type",
  77. "Stator_Number_Of_Slots",
  78. "Rotor_Number_Of_Poles",
  79. "Airgap",
  80. "Magnet_Arc_[ED]",
  81. "MagnetCentralArc_HalbachRing",
  82. "Slot_Opening",
  83. "Slot_Width",
  84. "Copper_Width",
  85. "TorquePointsPerCycle",
  86. "AirgapMeshPoints_mesh",
  87. "AirgapMeshPoints_layers",
  88. "Shaft_Speed",
  89. "Peak_Phase_Current",
  90. ]
  91. probed = {}
  92. for var in common_vars:
  93. try:
  94. value = solver.mc.get_variable(var)
  95. probed[var] = value
  96. print(f" {var} = {value}")
  97. except Exception as e:
  98. print(f" {var} = ERROR: {e}")
  99. # Save probed variables
  100. probe_file = os.path.join(solver.output_dir, "probed_variables.json")
  101. with open(probe_file, "w", encoding="utf-8") as f:
  102. json.dump(probed, f, indent=2, default=str)
  103. print(f"\n Probed variables saved to: {probe_file}")
  104. # Test parameter write-back verification
  105. print("\n[Step 4: Testing parameter write-back verification]")
  106. test_var = "TorquePointsPerCycle"
  107. if test_var in probed:
  108. original_value = float(probed[test_var])
  109. test_value = 60 # Test with 60 points
  110. print(f" Original {test_var} = {original_value}")
  111. print(f" Testing write {test_var} = {test_value}")
  112. try:
  113. applied = solver._write_and_verify(test_var, test_value)
  114. print(f" Write-back verification SUCCESS: applied={applied}")
  115. # Restore original
  116. solver._write_and_verify(test_var, original_value)
  117. print(f" Restored {test_var} = {original_value}")
  118. except Exception as e:
  119. print(f" Write-back verification FAILED: {e}")
  120. else:
  121. print(f" {test_var} not available, skipping write test")
  122. # Test single magnetic calculation
  123. print("\n[Step 5: Testing single magnetic calculation]")
  124. try:
  125. start = time.time()
  126. solver.mc.do_magnetic_calculation()
  127. elapsed = time.time() - start
  128. print(f" Magnetic calculation SUCCESS in {elapsed:.1f}s")
  129. except Exception as e:
  130. print(f" Magnetic calculation FAILED: {e}")
  131. # Test result export
  132. print("\n[Step 6: Testing result export]")
  133. try:
  134. export_file = os.path.join(solver.raw_dir, "test_export.csv")
  135. solver.mc.export_results("EMagnetic", export_file)
  136. if os.path.exists(export_file):
  137. file_size = os.path.getsize(export_file)
  138. print(f" Export SUCCESS: {export_file} ({file_size} bytes)")
  139. # Parse and show metrics
  140. metrics = solver._parse_export(export_file)
  141. print(f" Parsed {len(metrics)} metrics:")
  142. for k, v in metrics.items():
  143. print(f" {k} = {v}")
  144. else:
  145. print(" Export file not created!")
  146. except Exception as e:
  147. print(f" Export FAILED: {e}")
  148. # Disconnect
  149. print("\n[Step 7: Disconnecting]")
  150. solver.disconnect()
  151. print(" Disconnected")
  152. # Summary
  153. print("\n" + "=" * 60)
  154. print("Test Summary")
  155. print("=" * 60)
  156. print(f" Output directory: {solver.output_dir}")
  157. print(f" Probed variables: {len(probed)}")
  158. print(f" Log file: {solver._log_path}")
  159. print("\n Test completed successfully!")
  160. return 0
  161. if __name__ == "__main__":
  162. sys.exit(main())