AnsMath sparse matrices and SciPy sparse matrices#

This example shows how to get AnsMath sparse matrices into SciPy sparse matrices.

Perform required imports and start PyAnsys#

Perform required imports.

from ansys.mapdl.core.examples import vmfiles
import matplotlib.pylab as plt

import ansys.math.core.math as pymath

# Start PyAnsys Math as a service.
mm = pymath.AnsMath()

Get matrices#

Run the input file from Verification Manual 153 and then get the stiff (k) matrix from the FULL file.

out = mm._mapdl.input(vmfiles["vm153"])
fullfile = mm._mapdl.jobname + ".full"
k = mm.stiff(fname=fullfile)

Copy AnsMath sparse matrix to SciPy CSR matrix and plot#

Copy the AnsMath sparse matrix to a SciPy CSR matrix. Then, plot the graph of the sparse matrix.

pk = k.asarray()
plt.spy(pk, color="orange", markersize=3)
plt.title("AnsMath sparse matrix")
plt.show()
AnsMath sparse matrix

Access vectors#

You can access the three vectors that describe this sparse matrix with:

  • pk.data

  • pk.indices

  • pk.indptr

For more information, see SciPy’s class description for the CSR (compressed sparse row) matrix.

print(pk.data[:10])
print(pk.indices[:10])
print(pk.indptr[:10])
[ 0.20292539  0.00378143 -0.05003569 -0.01392161 -0.05003569 -0.01392161
 -0.05142701  0.02406179 -0.05142701  0.20090661]
[ 0  1  4  7 18 21 30 47 50  1]
[ 0  9 17 29 40 47 57 66 72 79]

Create AnsMath sparse matrix from SciPy sparse CSR matrix#

Create an AnsMath sparse matrix from a SciPy sparse CSR matrix. Then, transfer the SciPy CSR matrix back to PyAnsys Math.

While this code uses a matrix that was originally within MAPDL, you can load any CSR matrix into PyAnsys Math.

my_mat = mm.matrix(pk, "my_mat", triu=True)
my_mat
AnsMath sparse matrix (63, 63)

Check that the matrices k and my_mat are exactly the sames. The norm of the difference should be zero.

msub = k - my_mat
mm.norm(msub)
0.0

Access ID of Python object#

To determine which PyAnsys Math object corresponds to which Python object, access the id property of the Python object.

print("name(k)=" + k.id)
print("name(my_mat)=" + my_mat.id)
print("name(msub)=" + msub.id)
name(k)=HTZSMA
name(my_mat)=my_mat
name(msub)=TYCJNC

Stop PyAnsys Math#

Stop PyAnsys Math.

mm._mapdl.exit()
/home/runner/work/pyansys-math/pyansys-math/.venv/lib/python3.10/site-packages/ansys/mapdl/core/launcher.py:818: UserWarning: The environment variable 'PYMAPDL_START_INSTANCE' is set, hence the argument 'start_instance' is overwritten.
  warnings.warn(

Total running time of the script: (0 minutes 0.628 seconds)

Gallery generated by Sphinx-Gallery