Skip to content

Commit 4b9f310

Browse files
authored
Fixing mat and vec functions (#115)
1 parent 68aeee7 commit 4b9f310

File tree

8 files changed

+59
-35
lines changed

8 files changed

+59
-35
lines changed

doc/source/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,9 @@
8585
extensions = [
8686
"jupyter_sphinx",
8787
"notfound.extension", # for the not found page.
88+
"numpydoc",
8889
"sphinx.ext.autodoc",
8990
"sphinx.ext.autosummary",
90-
"numpydoc",
9191
"sphinx.ext.coverage",
9292
"sphinx.ext.intersphinx",
9393
"sphinx_copybutton",

doc/source/links.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
.. _grpc: https://grpc.io/
1616
.. _numpy_docs: https://numpy.org/doc/stable/
1717
.. _precommit: https://pre-commit.com/
18-
.. _scipy_docs: https://docs.scipy.org/doc/scipy/reference/
18+
.. _scipy_docs: https://docs.scipy.org/doc/scipy/
1919

2020
.. #Other projects
2121
.. _dpf_post_docs: https://post.docs.pyansys.com/

examples/eigen_solve.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@
3131
# get the stiff (``k``) and mass (``m``) matrices from the FULL file.
3232

3333
out = mm._mapdl.input(vmfiles["vm153"])
34-
35-
k = mm.stiff(fname="PRSMEMB.full")
36-
m = mm.mass(fname="PRSMEMB.full")
34+
fullfile = mm._mapdl.jobname + ".full"
35+
k = mm.stiff(fname=fullfile)
36+
m = mm.mass(fname=fullfile)
3737

3838

3939
###############################################################################

examples/scipy_sparse_matrix.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@
2626
# get the stiff (``k``) matrix from the FULL file.
2727

2828
out = mm._mapdl.input(vmfiles["vm153"])
29-
k = mm.stiff(fname="PRSMEMB.full")
29+
fullfile = mm._mapdl.jobname + ".full"
30+
k = mm.stiff(fname=fullfile)
3031

3132
################################################################################
3233
# Copy AnsMath sparse matrix to SciPy CSR matrix and plot

examples/solve_sparse_matrix.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
# After a solve command, the ``FULL`` file contains the assembled stiffness
2828
# matrix, mass matrix, and load vector.
2929
#
30-
out = mm._mapdl.input(vmfiles["vm153"])
30+
out = mm._mapdl.input(vmfiles["vm152"])
3131

3232
###############################################################################
3333
# List files in current directory
@@ -47,7 +47,8 @@
4747
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4848
# Print the dimensions of the sparse matrix.
4949

50-
k = mm.stiff(fname="PRSMEMB.full", name="K")
50+
fullfile = mm._mapdl.jobname + ".full"
51+
k = mm.stiff(fname=fullfile, name="K")
5152
k
5253

5354
################################################################################
@@ -74,8 +75,7 @@
7475
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7576
# Extract the load vector from the FULL file and print the norm of this
7677
# vector.
77-
78-
b = mm.rhs(fname="PRSMEMB.full", name="B")
78+
b = mm.rhs(fname=fullfile, name="B")
7979
b.norm()
8080

8181
###############################################################################

pyproject.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ dependencies = [
3131
"pyansys-tools-versioning>=0.3.3",
3232
"numpy>=1.14.0",
3333
"importlib-metadata>=4.0,<5; python_version<='3.8'",
34+
"scipy>=1.3.0", # for sparse (consider optional?)
3435
]
3536

3637
[project.optional-dependencies]
@@ -84,7 +85,7 @@ default_section = "THIRDPARTY"
8485
src_paths = ["doc", "src", "tests"]
8586

8687
[tool.coverage.run]
87-
source = ["src"]
88+
source = ["ansys/pyansys-math"]
8889

8990
[tool.coverage.report]
9091
show_missing = true

src/ansys/math/core/math.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,21 @@
88

99
from ansys.api.mapdl.v0 import ansys_kernel_pb2 as anskernel
1010
from ansys.api.mapdl.v0 import mapdl_pb2 as pb_types
11+
from ansys.mapdl.core import VERSION_MAP, launch_mapdl
1112
from ansys.mapdl.core.common_grpc import (
1213
ANSYS_VALUE_TYPE,
1314
DEFAULT_CHUNKSIZE,
1415
DEFAULT_FILE_CHUNK_SIZE,
1516
)
16-
from ansys.mapdl.core.errors import ANSYSDataTypeError, protect_grpc
17-
from ansys.mapdl.core.launcher import launch_mapdl
17+
from ansys.mapdl.core.errors import (
18+
ANSYSDataTypeError,
19+
MapdlRuntimeError,
20+
VersionError,
21+
protect_grpc,
22+
)
1823
from ansys.mapdl.core.misc import load_file
1924
from ansys.mapdl.core.parameters import interp_star_status
2025
from ansys.tools.versioning import requires_version
21-
from ansys.tools.versioning.exceptions import VersionError
2226
from ansys.tools.versioning.utils import server_meets_version
2327
import numpy as np
2428

@@ -165,7 +169,7 @@ def status(self):
165169
"""
166170
print(self._status)
167171

168-
def vec(self, size=0, dtype=np.double, init="zeros", name=None, asarray=False):
172+
def vec(self, size=0, dtype=np.double, init=None, name=None, asarray=False):
169173
"""Create a vector.
170174
171175
Parameters
@@ -209,7 +213,7 @@ def vec(self, size=0, dtype=np.double, init="zeros", name=None, asarray=False):
209213

210214
return vec
211215

212-
def mat(self, nrow=1, ncol=1, dtype=np.double, init="zeros", name=None, asarray=False):
216+
def mat(self, nrow=1, ncol=1, dtype=np.double, init=None, name=None, asarray=False):
213217
"""Create a matrix.
214218
215219
Parameters
@@ -252,7 +256,9 @@ def mat(self, nrow=1, ncol=1, dtype=np.double, init="zeros", name=None, asarray=
252256
mat.rand()
253257
elif init == "ones":
254258
mat.ones()
255-
elif init != "zeros":
259+
elif init == "zeros" or init is None:
260+
mat.zeros()
261+
elif init is not None:
256262
raise ValueError(f"Invalid initialization method '{init}'.")
257263
else:
258264
info = self._mapdl._data_info(name)
@@ -1171,7 +1177,7 @@ def _set_mat(self, mname, arr, sym=False, dtype=None, chunk_size=DEFAULT_CHUNKSI
11711177
else: # must be dense matrix
11721178
self._send_dense(mname, arr, dtype, chunk_size)
11731179

1174-
@requires_version((0, 4, 0))
1180+
@requires_version((0, 4, 0), VERSION_MAP)
11751181
def _send_dense(self, mname, arr, dtype, chunk_size):
11761182
"""Send a dense NumPy array/matrix to MAPDL."""
11771183
if dtype is not None:
@@ -1417,10 +1423,10 @@ def __init__(self, id_, mapdl, dtype=np.double, init=None):
14171423

14181424
@property
14191425
def size(self):
1420-
"""Number of items in the vector."""
1426+
"""Number of items in this vector."""
14211427
sz = self._mapdl.scalar_param(f"{self.id}_DIM")
14221428
if sz is None:
1423-
raise RuntimeError("This vector has been deleted within MAPDL.")
1429+
raise MapdlRuntimeError("This vector has been deleted within MAPDL.")
14241430
return int(sz)
14251431

14261432
def __repr__(self):

tests/test_math.py

Lines changed: 31 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import os
33
import re
44

5-
from ansys.mapdl.core.errors import ANSYSDataTypeError
5+
from ansys.mapdl.core.errors import ANSYSDataTypeError, MapdlRuntimeError
66
from ansys.mapdl.core.launcher import get_start_instance
77
from ansys.mapdl.core.misc import random_string
88
from ansys.tools.versioning.exceptions import VersionError
@@ -107,13 +107,11 @@ def test_vec(mm):
107107
assert isinstance(arr, np.ndarray)
108108

109109

110-
def test_vec_from_name(mm):
111-
vec0 = mm.vec(10)
110+
@pytest.mark.parametrize("vecval", [np.zeros(10), np.array([1.0, 2.0, 8.0, 5.0, 6.2]), np.ones(3)])
111+
def test_vec_from_name(mm, vecval):
112+
vec0 = mm.set_vec(vecval)
112113
vec1 = mm.vec(name=vec0.id)
113-
assert np.allclose(vec0, vec1)
114-
115-
vec1 = mm.vec(name=vec0.id, asarray=True)
116-
assert isinstance(vec1, np.ndarray)
114+
assert np.allclose(vecval, vec1.asarray())
117115

118116

119117
def test_vec__mul__(mm):
@@ -328,17 +326,35 @@ def test_load_matrix_from_file_incorrect_name(mm, cube_solve):
328326
mm.load_matrix_from_file(name=1245)
329327

330328

331-
def test_mat_from_name(mm):
329+
def test_mat_asarray(mm):
330+
mat0 = mm.mat(10, 10, asarray=True)
331+
mat1 = mm.mat(10, 10)
332+
assert np.allclose(mat0, mat1.asarray())
333+
334+
335+
def test_mat_from_name_mapdl(mm):
332336
mat0 = mm.mat(10, 10, init="ones") # The test has to be done with a
333337
# value other than the default one.
334338
mat1 = mm.mat(name=mat0.id)
335339
assert np.allclose(mat0, mat1)
336340

337341

338-
def test_mat_asarray(mm):
339-
mat0 = mm.mat(10, 10, asarray=True)
340-
mat1 = mm.mat(10, 10)
341-
assert np.allclose(mat0, mat1.asarray())
342+
@pytest.mark.parametrize(
343+
"matval",
344+
[
345+
np.zeros((5, 5)),
346+
np.array([[1.0, 2.0, 8.0, 5.0, 6.2], [5.1, 3.8, 8.2, 4.5, 2.0]]),
347+
np.ones((3, 4)),
348+
],
349+
)
350+
def test_mat_from_name_dense(mm, matval):
351+
if not server_meets_version(mm._server_version, (0, 4, 0)):
352+
with pytest.raises(VersionError):
353+
mat0 = mm.matrix(matval)
354+
else:
355+
mat0 = mm.matrix(matval)
356+
mat1 = mm.mat(name=mat0.id)
357+
assert np.allclose(matval, mat1.asarray())
342358

343359

344360
def test_mat_from_name_sparse(mm):
@@ -621,7 +637,7 @@ def test_invalid_sparse_name(mm):
621637
def test_free(mm):
622638
my_mat = mm.ones(10)
623639
mm.free()
624-
with pytest.raises(RuntimeError, match="This vector has been deleted"):
640+
with pytest.raises(MapdlRuntimeError, match="This vector has been deleted"):
625641
my_mat.size
626642

627643

@@ -687,7 +703,7 @@ def test_factorize_inplace_arg(mm):
687703
def test_mult(mapdl, mm):
688704
rand_ = np.random.rand(100, 100)
689705

690-
if not server_meets_version(mapdl._server_version, (0, 4, 0)):
706+
if not server_meets_version(mm._server_version, (0, 4, 0)):
691707
with pytest.raises(VersionError):
692708
AA = mm.matrix(rand_, name="AA")
693709

@@ -708,7 +724,7 @@ def test__parm(mm):
708724
mat = sparse.random(sz, sz, density=0.05, format="csr")
709725

710726
rand_ = np.random.rand(100, 100)
711-
if not server_meets_version(mm._mapdl._server_version, (0, 4, 0)):
727+
if not server_meets_version(mm._server_version, (0, 4, 0)):
712728
with pytest.raises(VersionError):
713729
AA = mm.matrix(rand_, name="AA")
714730

0 commit comments

Comments
 (0)