axial_probe3.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. # -*- coding: utf-8 -*-
  2. """
  3. 第4轮: 图 ID 枚举 + 图名 RPC 试探
  4. ==================================
  5. 第3轮已标定: "Graph name does not exist" = 图不存在; "No points exist" =
  6. 图存在但未求解。get_magnetic_graph_point 的 graph 参数可传数字 ID (variant),
  7. 故枚举 ID 0..N 找出全部存在的图; 再试几个未封装的 RPC 方法名拿 ID→名字映射;
  8. 拿不到名字就求解后读全部波形, 按量级特征辨认轴向力。
  9. 用法: python axial_probe3.py [--quit] [--max-id N]
  10. """
  11. import json
  12. import os
  13. import sys
  14. import time
  15. BASE = os.path.dirname(os.path.abspath(__file__))
  16. MOT_SRC = os.path.join(BASE, "MARS-12S10P_SSSR_D76-C150_V5.0-0819.mot")
  17. OUT_DIR = os.path.join(BASE, "output_motorcad")
  18. NAME_RPCS = ["GetMagneticGraphName", "GetMagneticGraphTitle", "GetGraphName",
  19. "GetMagneticGraphInfo", "GetMagneticGraphCount",
  20. "GetMagneticGraphNames", "GetMagneticGraphYAxisTitle"]
  21. def classify(mc, graph):
  22. try:
  23. x, y = mc.get_magnetic_graph_point(graph, 0)
  24. return "OK", (x, y)
  25. except Exception as e:
  26. msg = str(e)
  27. if "does not exist" in msg:
  28. return "ABSENT", None
  29. if "No points exist" in msg:
  30. return "EXISTS", None
  31. return "ODD", msg
  32. def stats(ys):
  33. if not ys:
  34. return None
  35. return {"mean": sum(ys) / len(ys), "min": min(ys), "max": max(ys),
  36. "pk2pk": max(ys) - min(ys), "n": len(ys)}
  37. def read_graph(mc, graph, maxpts=128):
  38. xs, ys = [], []
  39. for i in range(maxpts):
  40. try:
  41. x, y = mc.get_magnetic_graph_point(graph, i)
  42. except Exception:
  43. break
  44. xs.append(x)
  45. ys.append(y)
  46. return xs, ys
  47. def main(argv):
  48. quit_after = "--quit" in argv
  49. max_id = 400
  50. if "--max-id" in argv:
  51. max_id = int(argv[argv.index("--max-id") + 1])
  52. os.makedirs(OUT_DIR, exist_ok=True)
  53. ts = time.strftime("%m%d_%H%M%S")
  54. from ansys.motorcad.core import MotorCAD
  55. print("启动 Motor-CAD (前台) ...")
  56. mc = MotorCAD()
  57. results = {"when": ts, "probe_round": 4}
  58. try:
  59. mc.load_from_file(MOT_SRC)
  60. # ---- ID 枚举 (无求解) ----
  61. exist_ids, odd = [], {}
  62. for gid in range(max_id + 1):
  63. kind, payload = classify(mc, gid)
  64. if kind in ("EXISTS", "OK"):
  65. exist_ids.append(gid)
  66. elif kind == "ODD":
  67. odd[gid] = payload
  68. print("存在的图 ID (%d 个): %s" % (len(exist_ids), exist_ids))
  69. if odd:
  70. print("异样报错: %s" % json.dumps(odd, ensure_ascii=False))
  71. results["exist_ids"] = exist_ids
  72. results["odd"] = odd
  73. # ---- 图名 RPC 试探 ----
  74. rpc_found = {}
  75. probe_id = exist_ids[0] if exist_ids else 0
  76. for meth in NAME_RPCS:
  77. try:
  78. r = mc.connection.send_and_receive(meth, [probe_id])
  79. rpc_found[meth] = r
  80. print(" [RPC 可用] %s(%s) = %s" % (meth, probe_id, r))
  81. except Exception as e:
  82. print(" [RPC 不可用] %s: %s" % (meth, str(e)[:80]))
  83. results["name_rpcs"] = rpc_found
  84. id_names = {}
  85. name_rpc = next(iter(rpc_found), None)
  86. if name_rpc and rpc_found[name_rpc] not in (None, ""):
  87. for gid in exist_ids:
  88. try:
  89. id_names[gid] = mc.connection.send_and_receive(
  90. name_rpc, [gid])
  91. except Exception:
  92. id_names[gid] = None
  93. results["id_names"] = id_names
  94. print("ID->图名: %s" % json.dumps(id_names, ensure_ascii=False))
  95. # ---- 求解一次, 读全部存在图的波形 ----
  96. for var in ["ElectromagneticForcesCalc_Load",
  97. "ElectromagneticForcesCalc_OC"]:
  98. mc.set_variable(var, True)
  99. print("求解 (负载点, OC/Load 力已开) ...")
  100. t0 = time.time()
  101. mc.do_magnetic_calculation()
  102. print(" 耗时 %.1f s" % (time.time() - t0))
  103. waves = {}
  104. for gid in exist_ids:
  105. xs, ys = read_graph(mc, gid)
  106. if ys:
  107. waves[str(gid)] = {"name": id_names.get(gid),
  108. "stats": stats(ys),
  109. "x0": xs[0], "x_end": xs[-1],
  110. "x": xs, "y": ys}
  111. results["waveforms"] = waves
  112. print("有数据的图 %d 个:" % len(waves))
  113. for gid, w in waves.items():
  114. print(" id=%s name=%s x:[%.3g..%.3g] %s"
  115. % (gid, w["name"], w["x0"], w["x_end"], w["stats"]))
  116. res_path = os.path.join(OUT_DIR, "probe3_results_%s.json" % ts)
  117. with open(res_path, "w", encoding="utf-8") as f:
  118. json.dump(results, f, ensure_ascii=False, indent=2)
  119. print("RESULTS: %s" % res_path)
  120. return 0
  121. finally:
  122. if quit_after:
  123. try:
  124. mc.quit()
  125. except Exception:
  126. pass
  127. else:
  128. print("[提示] Motor-CAD 保持前台打开供检查。")
  129. if __name__ == "__main__":
  130. sys.exit(main(sys.argv[1:]))