Skip to content
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

Improving cmlist to allow to_list #2571

Merged
merged 8 commits into from
Dec 22, 2023
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
9 changes: 9 additions & 0 deletions src/ansys/mapdl/core/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -832,6 +832,15 @@ def to_dataframe(self):
return df


class ComponentListing(CommandListingOutput):
@property
def _parsed(self):
from ansys.mapdl.core.component import _parse_cmlist

# To keep same API as commands
return np.array(list(_parse_cmlist(self).keys()))


class StringWithLiteralRepr(str):
def __repr__(self):
return self.__str__()
122 changes: 67 additions & 55 deletions src/ansys/mapdl/core/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@
def _comp(self) -> UNDERLYING_DICT:
"""Dictionary with components names and types."""
if self.__comp is None or self._update_always:
self.__comp = self._parse_cmlist()
self.__comp = self._mapdl._parse_cmlist()
return self.__comp

@_comp.setter
Expand Down Expand Up @@ -308,7 +308,7 @@
f"The component named '{key}' does not exist in the MAPDL instance."
)

output = self._parse_cmlist_indiv(key, cmtype)
output = self._mapdl._parse_cmlist_indiv(key, cmtype)
if forced_to_select:
# Unselect to keep the state of the things as before calling this method.
self._mapdl.cmsel("U", key)
Expand Down Expand Up @@ -515,60 +515,72 @@
dict_[each_comp] = i_items
return dict_

def _parse_cmlist(self, cmlist: Optional[str] = None) -> Dict[str, Any]:
if not cmlist:
cmlist = self._mapdl.cmlist()

if "NAME" in cmlist and "SUBCOMPONENTS" in cmlist:
# header
# "NAME TYPE SUBCOMPONENTS"
blocks = re.findall(
r"(?s)NAME\s+TYPE\s+SUBCOMPONENTS\s+(.*?)\s*(?=\n\s*\n|\Z)",
cmlist,
flags=re.DOTALL,
)
elif "LIST ALL SELECTED COMPONENTS":
blocks = cmlist.splitlines()[1:]
else:
raise ValueError("The format of the CMLIST output is not recognaised.")

cmlist = "\n".join(blocks)

def extract(each_line, ind):
return each_line.split()[ind].strip()

return {
extract(each_line, 0): extract(each_line, 1)
for each_line in cmlist.splitlines()
if each_line
}

def _parse_cmlist_indiv(
self, cmname: str, cmtype: str, cmlist: Optional[str] = None
) -> List[int]:
if not cmlist:
cmlist = self._mapdl.cmlist(cmname, 1)
# Capturing blocks
if "NAME" in cmlist and "SUBCOMPONENTS" in cmlist:
header = r"NAME\s+TYPE\s+SUBCOMPONENTS"

elif "LIST COMPONENT" in cmlist:
header = ""

cmlist = "\n\n".join(
re.findall(
r"(?s)" + header + r"\s+(.*?)\s*(?=\n\s*\n|\Z)",
cmlist,
flags=re.DOTALL,
)

def _parse_cmlist_indiv(
cmname: str, cmtype: str, cmlist: Optional[str] = None
) -> List[int]:
# Capturing blocks
if "NAME" in cmlist and "SUBCOMPONENTS" in cmlist:
header = r"NAME\s+TYPE\s+SUBCOMPONENTS"

elif "LIST COMPONENT" in cmlist:
header = ""

Check warning on line 527 in src/ansys/mapdl/core/component.py

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/component.py#L526-L527

Added lines #L526 - L527 were not covered by tests

cmlist = "\n\n".join(
re.findall(
r"(?s)" + header + r"\s+(.*?)\s*(?=\n\s*\n|\Z)",
cmlist,
flags=re.DOTALL,
)
)

# Capturing items in each block
rg = cmname.upper() + r"\s+" + cmtype.upper() + r"\s+(.*?)\s*(?=\n\s*\n|\Z)"
items = "\n".join(re.findall(rg, cmlist, flags=re.DOTALL))

# Joining them together and giving them format.
items = items.replace("\n", " ").split()
items = [int(each) for each in items]

# Capturing items in each block
rg = cmname.upper() + r"\s+" + cmtype.upper() + r"\s+(.*?)\s*(?=\n\s*\n|\Z)"
items = "\n".join(re.findall(rg, cmlist, flags=re.DOTALL))
return items

# Joining them together and giving them format.
items = items.replace("\n", " ").split()
items = [int(each) for each in items]

return items
def _parse_cmlist(cmlist: Optional[str] = None) -> Dict[str, Any]:
include_selection = False
if re.search(r"NAME\s+TYPE\s+SUBCOMPONENTS", cmlist):
# header
# "NAME TYPE SUBCOMPONENTS"
blocks = re.findall(
r"(?s)NAME\s+TYPE\s+SUBCOMPONENTS\s+(.*?)\s*(?=\n\s*\n|\Z)",
cmlist,
flags=re.DOTALL,
)
elif re.search(r"NAME\s+SELE\s+TYPE\s+SUBCOMPONENTS", cmlist):
blocks = re.findall(
r"(?s)NAME\s+SELE\s+TYPE\s+SUBCOMPONENTS\s+(.*?)\s*(?=\n\s*\n|\Z)",
cmlist,
flags=re.DOTALL,
)
# Using `cmlist,all` which also includes selection
include_selection = True
elif "LIST ALL SELECTED COMPONENTS":
blocks = cmlist.splitlines()[1:]
else:
raise ValueError("The format of the CMLIST output is not recognaised.")

cmlist = "\n".join(blocks)

def extract(each_line, ind):
return each_line.split()[ind].strip()

def extract_line(each_line):
if include_selection:
return [extract(each_line, 1), extract(each_line, 2)]
else:
return extract(each_line, 1)

return {
extract(each_line, 0): extract_line(each_line)
for each_line in cmlist.splitlines()
if each_line
}
20 changes: 19 additions & 1 deletion src/ansys/mapdl/core/mapdl_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from subprocess import DEVNULL, call
import tempfile
import time
from typing import TYPE_CHECKING, Any, Dict, Literal, Optional, Tuple, Union
from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Tuple, Union
import warnings
from warnings import warn
import weakref
Expand Down Expand Up @@ -2831,3 +2831,21 @@ def __exit__(self, *args):
if self._in_nopr:
self._parent()._run("/nopr")
self._parent()._mute = self._previous_mute

def _parse_cmlist(self, cmlist: Optional[str] = None) -> Dict[str, Any]:
from ansys.mapdl.core.component import _parse_cmlist

if not cmlist:
cmlist = self.cmlist()

return _parse_cmlist(cmlist)

def _parse_cmlist_indiv(
self, cmname: str, cmtype: str, cmlist: Optional[str] = None
) -> List[int]:
from ansys.mapdl.core.component import _parse_cmlist_indiv

if not cmlist:
cmlist = self.cmlist(cmname, 1)

return _parse_cmlist_indiv(cmname, cmtype, cmlist)
6 changes: 6 additions & 0 deletions src/ansys/mapdl/core/mapdl_extended.py
Original file line number Diff line number Diff line change
Expand Up @@ -2002,6 +2002,12 @@ def get(
except ValueError:
return value

@wraps(_MapdlCore.cmlist)
def cmlist(self, *args, **kwargs):
from ansys.mapdl.core.commands import ComponentListing

return ComponentListing(super().cmlist(*args, **kwargs))


class _MapdlExtended(_MapdlCommandExtended):
"""Extend Mapdl class with new functions"""
Expand Down
33 changes: 33 additions & 0 deletions tests/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -710,3 +710,36 @@ def test_nlist_to_array(mapdl, beam_solve):
assert len(nlist.to_list()) == len(mapdl.mesh.nodes)
assert len(nlist.to_array()) == len(mapdl.mesh.nodes)
assert np.allclose(nlist.to_array()[:, 1:4], mapdl.mesh.nodes)


def test_cmlist(mapdl):
mapdl.clear()

mapdl.prep7()
# setup the full file
mapdl.block(0, 1, 0, 1, 0, 1)
mapdl.et(1, 186)
mapdl.esize(0.5)
mapdl.vmesh("all")

mapdl.cm("myComp", "node")
mapdl.cm("_myComp", "node")
mapdl.cm("_myComp_", "node")

cmlist = mapdl.cmlist()
assert "MYCOMP" in cmlist

cmlist_all = mapdl.cmlist("all")
assert "_MYCOMP_" in cmlist_all
assert "_MYCOMP" in cmlist_all
assert "MYCOMP" in cmlist_all

assert ["MYCOMP"] == mapdl.cmlist().to_list()

assert "_MYCOMP_" in cmlist_all.to_list()
assert "_MYCOMP" in cmlist_all.to_list()
assert "MYCOMP" in cmlist_all.to_list()

assert len(cmlist_all.to_array()) == len(cmlist_all.to_list())
for each_ in cmlist_all.to_list():
assert each_ in cmlist_all
Loading