Skip to content

Adding database notes and some improvements #1392

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Aug 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 112 additions & 0 deletions doc/source/user_guide/database.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
Accessing MAPDL Database
========================

.. warning:: This feature is still in beta. Please report any errors or suggestions to [email protected].


From PyMAPDL v0.61.2, you can access elements and nodes data from the MAPDL database using the DB module.


Usage
~~~~~

Getting the elems and nodes objects:

.. code:: py

>>> from ansys.mapdl.core import launch_mapdl
>>> from ansys.mapdl.core.examples import vmfiles

>>> mapdl = launch_mapdl()
>>> mapdl.input(vmfiles['vm271']

>>> elems = mapdl.db.elems
>>> elems
MAPDL Database Elements
Number of elements: 3459
Number of selected elements: 3459
Maximum element number: 3459

>>> nodes = mapdl.db.nodes
MAPDL Database Nodes
Number of nodes: 3652
Number of selected nodes: 3652
Maximum node number: 3652

To obtain the first element:

.. code:: py

>>> elems = mapdl.db.elems
>>> elems.first()
1


Check if the element is selected or not:

.. code:: py

>>> from ansys.mapdl.core.database import DBDef
>>> elems.info(1, DBDef.DB_SELECTED)

Return the element information of element 1.

.. code:: py

>>> elems = mapdl.db.elems
>>> elem_info = elems.get(1)
>>> elem_info
ielem: 1
elmdat: 1
elmdat: 1
elmdat: 1
elmdat: 1
elmdat: 0
elmdat: 0
elmdat: 12
elmdat: 0
elmdat: 0
elmdat: 0
nnod: 2
nodes: 1
nodes: 3

Return the nodes belonging to the element.

.. code:: py

>>> elem_info.nodes
[1, 3]

Return the element data.

.. code:: py

>>> elem_info.elmdat
[1, 1, 1, 1, 0, 0, 12, 0, 0, 0]

Return the selection status and the coordinates of node 22.

.. code:: py

>>> nodes = mapdl.db.nodes
>>> sel, coord = nodes.coord(22)
>>> coord
(-0.0014423144202849985, 0.010955465718673852, 0.0, 0.0, 0.0, 0.0)

.. note:: The coordenates returned by the method ``coord`` contains the following: X, Y, Z, THXY, THYZ, and THZX.


Requirements
~~~~~~~~~~~~

To use ``DB`` feature, you need to meet the following requirements:

* ``ansys.api.mapdl`` package version should be 0.5.1 or higher.
* ANSYS MAPDL version should be 2021R1 or newer.

.. warning:: This feature does not work in the latest Ansys 2023R1.




1 change: 1 addition & 0 deletions doc/source/user_guide/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ PyMAPDL library.
mesh_geometry
post
parameters
database
convert
math
pool
Expand Down
7 changes: 6 additions & 1 deletion src/ansys/mapdl/core/database/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
"""The mapdl database module, allowing the access to the MAPDL database from Python."""

from .database import DBDef, MapdlDb, check_mapdl_db_is_alive # noqa: F401
from .database import ( # noqa: F401
VALID_MAPDL_VERSIONS,
DBDef,
MapdlDb,
check_mapdl_db_is_alive,
)
38 changes: 28 additions & 10 deletions src/ansys/mapdl/core/database/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,13 @@
from warnings import warn
import weakref

try:
from ansys.api.mapdl.v0 import mapdl_db_pb2_grpc
except ImportError: # pragma: no cover
raise ImportError(
"Please upgrade the 'ansys.api.mapdl' package to at least v0.5.1."
"You can use 'pip install ansys-api-mapdl --upgrade"
)

from ansys.api.mapdl.v0 import mapdl_db_pb2_grpc
import grpc

from ..mapdl_grpc import MapdlGrpc

VALID_MAPDL_VERSIONS = [21.1, 21.2, 22.1, 22.2]


class WithinBeginLevel:

Expand Down Expand Up @@ -205,11 +200,34 @@ def start(self, timeout=10):
--------
>>> mapdl.db.start()
"""
if self._mapdl._server_version != (0, 4, 1): # pragma: no cover
# checking MAPDL API
from ansys.api.mapdl import __version__ as api_version

api_version = tuple(int(each) for each in api_version.split("."))

if api_version < (0, 5, 1): # pragma: no cover
raise ImportError(
"Please upgrade the 'ansys.api.mapdl' package to at least v0.5.1."
"You can use 'pip install ansys-api-mapdl --upgrade"
)

## Checking MAPDL versions
mapdl_version = self._mapdl.version
if mapdl_version not in VALID_MAPDL_VERSIONS: # pragma: no cover
from ansys.mapdl.core.errors import MapdlVersionError

raise MapdlVersionError(
f"This MAPDL version ({mapdl_version}) is not compatible with the Database module."
"Please check the online documentation regarding Database Module at 'mapdl.docs.pyansys.com'."
)

if self._mapdl._server_version < (0, 4, 1):
from ansys.mapdl.core.errors import MapdlVersionError

ver_ = ".".join([str(each) for each in self._mapdl._server_version])
raise MapdlVersionError(
"This version of MAPDL is not compatible with 'database' module."
f"This version of MAPDL gRPC API version ('ansys.api.mapdl' == {ver_}) is not compatible with 'database' module.\n"
"Please check the online documentation at 'mapdl.docs.pyansys.com' "
)

# only start if not already running
Expand Down
3 changes: 3 additions & 0 deletions src/ansys/mapdl/core/database/elems.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ def __str__(self):
lines.append(f" Maximum element number: {self.max_num}")
return "\n".join(lines)

def __repr__(self) -> str:
return self.__str__()

@check_mapdl_db_is_alive
def first(self, ielm=0):
"""
Expand Down
3 changes: 3 additions & 0 deletions src/ansys/mapdl/core/database/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,9 @@ def __str__(self):
lines.append(f" Maximum node number: {self.max_num}")
return "\n".join(lines)

def __repr__(self) -> str:
return self.__str__()

@property
def _db(self):
"""Return the weakly referenced instance of db."""
Expand Down
4 changes: 1 addition & 3 deletions src/ansys/mapdl/core/mapdl_grpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ def __init__(
self._exited = None
self._mute = False
self._db = None
self.__server_version = None

# saving for later use (for example open_gui)
start_parm["ip"] = ip
Expand Down Expand Up @@ -534,8 +535,6 @@ def _connect(self, timeout=5, set_no_abort=True, enable_health_check=False):
if enable_health_check:
self._enable_health_check()

self.__server_version = None

# HOUSEKEEPING:
# Set to not abort after encountering errors. Otherwise, many
# failures in a row will cause MAPDL to exit without returning
Expand Down Expand Up @@ -2037,7 +2036,6 @@ def math(self):
return MapdlMath(self)

@property
@check_version.version_requires((0, 4, 1))
def db(self):
"""
MAPDL database interface.
Expand Down
72 changes: 68 additions & 4 deletions tests/test_database.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,43 @@
import os
import re

import numpy as np
import pytest

from ansys.mapdl.core.database import DBDef, MapdlDb
## Checking MAPDL versions
from ansys.mapdl.core.database import VALID_MAPDL_VERSIONS, DBDef, MapdlDb
from ansys.mapdl.core.misc import random_string

ON_CI = "PYMAPDL_START_INSTANCE" in os.environ and "PYMAPDL_PORT" in os.environ

if ON_CI: # Docker image seems to not support DB, but local does.
VALID_MAPDL_VERSIONS.remove(22.2)

# We are skipping all these test until 0.5.X gets fixed.


@pytest.fixture(scope="session")
def db(mapdl):
if mapdl._server_version != (0, 4, 1): # 2021R2
pytest.skip("requires 2021R2 or newer")
from ansys.api.mapdl import __version__ as api_version

api_version = tuple(int(each) for each in api_version.split("."))
if api_version < (0, 5, 1):
pytest.skip("Requires 'ansys.api.mapdl' package to at least v0.5.1.")

## Checking MAPDL versions

mapdl_version = mapdl.version
if mapdl_version not in VALID_MAPDL_VERSIONS:
pytest.skip(
f"This MAPDL version ({mapdl_version}) is not compatible with the Database module."
)

if mapdl._server_version < (0, 4, 1): # 2021R2
ver_ = ".".join([str(each) for each in mapdl._server_version])
pytest.skip(
f"This version of MAPDL gRPC API version ('ansys.api.mapdl' == {ver_}) is not compatible with 'database' module."
)

return mapdl.db


Expand All @@ -38,9 +63,15 @@ def elems(gen_block, db):


def test_database_start_stop(mapdl):
if mapdl._server_version != (0, 4, 1): # 2021R2
if mapdl._server_version < (0, 4, 1): # 2021R2
pytest.skip("requires 2021R2 or newer")

mapdl_version = mapdl.version
if mapdl_version not in VALID_MAPDL_VERSIONS:
pytest.skip(
f"This MAPDL version ({mapdl_version}) is not compatible with the Database module."
)

# verify it can be created twice
mapdl.prep7()
for _ in range(2):
Expand Down Expand Up @@ -224,3 +255,36 @@ def test_off_db(mapdl, db):
assert not mapdl.db.active
assert mapdl.db.nodes is None
assert mapdl.db.elems is None


def test_wrong_api_version(mapdl, db):
mapdl.db.stop()
mapdl.__server_version = (0, 1, 1)
mapdl._MapdlGrpc__server_version = (0, 1, 1)

from ansys.mapdl.core.errors import MapdlVersionError

with pytest.raises(MapdlVersionError):
mapdl.db.start()

mapdl.__sever_version = None
mapdl._MapdlGrpc__server_version = None

mapdl._server_version # resetting
mapdl.db.start()

assert "is currently running" in mapdl.db._status()


def test_repr(mapdl, db):
elems = mapdl.db.elems
nodes = mapdl.db.nodes

assert elems
assert nodes

assert isinstance(elems.__repr__(), str)
assert isinstance(nodes.__repr__(), str)

assert isinstance(elems.__str__(), str)
assert isinstance(nodes.__str__(), str)