Bladeren bron

fix: export_results requires solution_type parameter for pymotorcad 0.8.8

carlin 1 week geleden
bovenliggende
commit
f3b492a
2 gewijzigde bestanden met toevoegingen van 187 en 1 verwijderingen
  1. 1 1
      scripts/robust_motorcad.py
  2. 186 0
      scripts/test_robust_solver.py

+ 1 - 1
scripts/robust_motorcad.py

@@ -607,7 +607,7 @@ class RobustMotorCADSolver:
                         f"result_{point_index:04d}_{point_label or 'point'}_{datetime.now().strftime('%H%M%S')}.csv"
                     )
                     try:
-                        self.mc.export_results(raw_file)
+                        self.mc.export_results("EMagnetic", raw_file)
                     except MotorCADError as e:
                         raise RuntimeError(f"Results export failed: {e}")
 

+ 186 - 0
scripts/test_robust_solver.py

@@ -0,0 +1,186 @@
+"""Test script for RobustMotorCADSolver - Step 1: Connection and variable probing.
+
+This script tests:
+1. Motor-CAD connection (open_new_instance=True + set_visible=True)
+2. Model loading
+3. Variable probing (get common variable names)
+4. Parameter write-back verification
+5. Single magnetic calculation
+6. Result export and parsing
+
+All source is ASCII only.
+"""
+import os
+import sys
+import time
+import json
+
+# Add project root to path
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from scripts.robust_motorcad import (
+    RobustMotorCADSolver,
+    ensure_environment,
+    is_running_as_admin,
+    check_license_server,
+)
+
+
+def main():
+    print("=" * 60)
+    print("RobustMotorCADSolver Test - Step 1: Connection & Probing")
+    print("=" * 60)
+
+    # Pre-checks
+    print("\n[Pre-checks]")
+    print(f"  Running as admin: {is_running_as_admin()}")
+    license_ok, license_msg = check_license_server()
+    print(f"  License server: {license_msg}")
+
+    ensure_environment()
+    print(f"  MOTORCAD_ACTIVEX: {os.environ.get('MOTORCAD_ACTIVEX', 'not set')}")
+    print(f"  ANSYSLMD_LICENSE_FILE: {os.environ.get('ANSYSLMD_LICENSE_FILE', 'not set')}")
+
+    # Model path
+    model_path = os.path.join(
+        os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
+        "models", "MARS-12S10P_SSSR_D76-C150_V5.0-0819.mot"
+    )
+    print(f"\n  Model path: {model_path}")
+    print(f"  Model exists: {os.path.exists(model_path)}")
+
+    if not os.path.exists(model_path):
+        print("ERROR: Model file not found!")
+        return 1
+
+    # Create solver
+    print("\n[Creating solver]")
+    solver = RobustMotorCADSolver(
+        model_path=model_path,
+        output_dir=os.path.join(
+            os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
+            "output", f"test_connect_{time.strftime('%Y%m%d_%H%M%S')}"
+        ),
+        point_timeout=120,
+        max_retries=2,
+        headless=False,
+    )
+    print(f"  Output dir: {solver.output_dir}")
+
+    # Connect
+    print("\n[Step 1: Connecting to Motor-CAD]")
+    try:
+        solver.connect()
+        print("  Connection SUCCESS")
+    except Exception as e:
+        print(f"  Connection FAILED: {e}")
+        return 1
+
+    # Run preflight
+    print("\n[Step 2: Running preflight self-check]")
+    try:
+        preflight = solver.run_preflight()
+        print(preflight.summary())
+    except Exception as e:
+        print(f"  Preflight error: {e}")
+
+    # Probe variables
+    print("\n[Step 3: Probing common variables]")
+    common_vars = [
+        "Motor_Type",
+        "Stator_Number_Of_Slots",
+        "Rotor_Number_Of_Poles",
+        "Airgap",
+        "Magnet_Arc_[ED]",
+        "MagnetCentralArc_HalbachRing",
+        "Slot_Opening",
+        "Slot_Width",
+        "Copper_Width",
+        "TorquePointsPerCycle",
+        "AirgapMeshPoints_mesh",
+        "AirgapMeshPoints_layers",
+        "Shaft_Speed",
+        "Peak_Phase_Current",
+    ]
+
+    probed = {}
+    for var in common_vars:
+        try:
+            value = solver.mc.get_variable(var)
+            probed[var] = value
+            print(f"  {var} = {value}")
+        except Exception as e:
+            print(f"  {var} = ERROR: {e}")
+
+    # Save probed variables
+    probe_file = os.path.join(solver.output_dir, "probed_variables.json")
+    with open(probe_file, "w", encoding="utf-8") as f:
+        json.dump(probed, f, indent=2, default=str)
+    print(f"\n  Probed variables saved to: {probe_file}")
+
+    # Test parameter write-back verification
+    print("\n[Step 4: Testing parameter write-back verification]")
+    test_var = "TorquePointsPerCycle"
+    if test_var in probed:
+        original_value = float(probed[test_var])
+        test_value = 60  # Test with 60 points
+        print(f"  Original {test_var} = {original_value}")
+        print(f"  Testing write {test_var} = {test_value}")
+        try:
+            applied = solver._write_and_verify(test_var, test_value)
+            print(f"  Write-back verification SUCCESS: applied={applied}")
+            # Restore original
+            solver._write_and_verify(test_var, original_value)
+            print(f"  Restored {test_var} = {original_value}")
+        except Exception as e:
+            print(f"  Write-back verification FAILED: {e}")
+    else:
+        print(f"  {test_var} not available, skipping write test")
+
+    # Test single magnetic calculation
+    print("\n[Step 5: Testing single magnetic calculation]")
+    try:
+        start = time.time()
+        solver.mc.do_magnetic_calculation()
+        elapsed = time.time() - start
+        print(f"  Magnetic calculation SUCCESS in {elapsed:.1f}s")
+    except Exception as e:
+        print(f"  Magnetic calculation FAILED: {e}")
+
+    # Test result export
+    print("\n[Step 6: Testing result export]")
+    try:
+        export_file = os.path.join(solver.raw_dir, "test_export.csv")
+        solver.mc.export_results("EMagnetic", export_file)
+        if os.path.exists(export_file):
+            file_size = os.path.getsize(export_file)
+            print(f"  Export SUCCESS: {export_file} ({file_size} bytes)")
+            # Parse and show metrics
+            metrics = solver._parse_export(export_file)
+            print(f"  Parsed {len(metrics)} metrics:")
+            for k, v in metrics.items():
+                print(f"    {k} = {v}")
+        else:
+            print("  Export file not created!")
+    except Exception as e:
+        print(f"  Export FAILED: {e}")
+
+    # Disconnect
+    print("\n[Step 7: Disconnecting]")
+    solver.disconnect()
+    print("  Disconnected")
+
+    # Summary
+    print("\n" + "=" * 60)
+    print("Test Summary")
+    print("=" * 60)
+    print(f"  Output directory: {solver.output_dir}")
+    print(f"  Probed variables: {len(probed)}")
+    print(f"  Log file: {solver._log_path}")
+    print("\n  Test completed successfully!")
+
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main())