Repository navigation
|
Hi, I have written a script to solve a simple matrix using "ansys.math.core.math". However, when I execute the script, it opens a Mechanical APDL dialog box that does not close automatically after the execution completes. As a result, I have to manually terminate it each time using the Task Manager. Matrix_solver.txt](https://github.com/user-attachments/files/28143773/Matrix_solver.txt) |
Answered by
germa89
May 26, 2026
Replies: 0 comments 4 replies
|
Extracting content from txt in plain sight import numpy as np
import scipy.sparse as sp
import ansys.math.core.math as pymath
print("--- Starting PyAnsys Math Verification ---")
# 1. Launch the backend engine
try:
sol_mat = pymath.AnsMath(port = 50053)
print("Successfully connected to the Ansys Math backend.")
except Exception as e:
print(f"Initialization failed. Check your Ansys license.\nError: {e}")
exit()
# 2. Build a 3x3 sparse matrix R using SciPy
#R_scipy = sp.csr_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 8]], dtype=np.float64)
R_scipy = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 8]], dtype=np.float64)
# 3. Build a 3x1 vector Q using NumPy
Q_numpy = np.array([5, 1, 0], dtype=np.float64)
print(f"Created R shape: {R_scipy.shape} | Created Q shape: {Q_numpy.shape}")
# 4. Stream data to Ansys Workspace
R_ansys = sol_mat.matrix(R_scipy, name="R_matrix")
Q_ansys = sol_mat.set_vec(Q_numpy, name="Q_vector")
X_ansys = sol_mat.vec(size=3, name="X_sol")
# 5. Direct Factorization and Solving
print("Executing sparse matrix factorization...")
solver = sol_mat.factorize(R_ansys)
print("Solving Rx = Q via Ansys solver backend...")
solver.solve(Q_ansys, X_ansys)
# 6. Extract solution back to Python memory
final_x_vector = X_ansys.asarray()
print("\n--- SOLUTION ---")
print("Target solution vector x:")
print(final_x_vector)
# CORRECTED VALIDATION: The mathematical answer to inv(R) * Q is [-10, 9, -3]
expected_x = np.array([-10.0, 9.0, -3.0])
is_correct = np.allclose(final_x_vector.flatten(), expected_x, atol=1e-5)
print(f"\nIs the solution correct? {is_correct}")
# 7. Corrected Cleanup Routine
# Use the official mapdl reference without an underscore prefix
sol_mat._mapdl.exit()
print("\nAnsys workspace cleared successfully.") |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is duplicated from #4596.
Transfering to PyMAPDL repository.