Skip to content

fix: improve code quality and numpydoc documentation #4125

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

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 11 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
1 change: 1 addition & 0 deletions doc/changelog.d/4125.miscellaneous.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix: improve code quality and numpydoc documentation
20 changes: 16 additions & 4 deletions src/ansys/mapdl/core/common_grpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,23 @@


class GrpcError(MapdlRuntimeError):
"""Raised when gRPC fails"""
"""Raised when gRPC fails.

Parameters
----------
msg : str, optional
Error message, by default "".
"""

def __init__(self, msg: str = "") -> None:
super().__init__(self, msg)
"""Initialize GrpcError.

Parameters
----------
msg : str, optional
Error message, by default "".
"""
super().__init__(self, msg=msg)


def check_vget_input(entity: str, item: str, itnum: str) -> str:
Expand Down Expand Up @@ -174,7 +187,7 @@ def check_vget_input(entity: str, item: str, itnum: str) -> str:
def parse_chunks(
chunks: Iterable[anskernel.Chunk], dtype: Optional[np.typing.DTypeLike] = None
) -> np.ndarray:
"""Deserialize gRPC chunks into a numpy array
"""Deserialize gRPC chunks into a numpy array.

Parameters
----------
Expand All @@ -188,7 +201,6 @@ def parse_chunks(
-------
np.ndarray
Deserialized numpy array.

"""
timeout = 3 # seconds
time_step = 0.01
Expand Down
99 changes: 84 additions & 15 deletions src/ansys/mapdl/core/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from collections import UserList
from logging import Logger, StreamHandler
import os
import re
Expand Down Expand Up @@ -167,7 +168,7 @@ def convert_script(
``True``.

line_ending : str, optional
When None, automatically is ``\n.``
When None, automatically is ``\\n``.

exec_file : str, optional
Specify the location of the ANSYS executable and include
Expand Down Expand Up @@ -218,13 +219,17 @@ def convert_script(
and exit commands are NOT included (``auto_exit=False``).
Overrides ``header``, ``add_imports`` and ``auto_exit``.

graphics_backend : bool, optional
graphics_backend : GraphicsBackend, optional
It sets the `mapdl.graphics_backend` argument equals True or False depending on
this value.

clear_at_start : bool, optional
Add a `mapdl.clear()` after the Mapdl object initialization.

check_parameter_names : bool, optional
Check if parameter names are valid MAPDL parameter names.
Defaults to ``True``.

Returns
-------
list
Expand Down Expand Up @@ -253,7 +258,6 @@ def convert_script(
>>> with open(out_file, 'r') as fid:
... cmds = fid.read()
>>> mapdl.input_strings(cmds.splitlines()[2:10])

"""
with open(filename_in, "r") as fid:
apdl_strings = fid.readlines()
Expand Down Expand Up @@ -312,7 +316,7 @@ def convert_apdl_block(

Parameters
----------
apdl_string : str
apdl_strings : str
APDL strings or list of strings to convert.

loglevel : str, optional
Expand All @@ -325,6 +329,10 @@ def convert_apdl_block(
line_ending : str, optional
When None, automatically determined by OS being used.

exec_file : str, optional
Specify the location of the ANSYS executable and include
it in the converter output ``launch_mapdl`` call.

macros_as_functions : bool, optional
Attempt to convert MAPDL macros to python functions.

Expand Down Expand Up @@ -403,7 +411,6 @@ def convert_apdl_block(
>>> cmds = cmds.replace('solve', '!solve')
>>> mapdl = launch_mapdl()
>>> mapdl.input_strings(cmds.splitlines()[2:10])

"""

translator = _convert(
Expand Down Expand Up @@ -431,10 +438,6 @@ def convert_apdl_block(
return translator.lines


from collections import UserList
from typing import Any


class Lines(UserList[str]):
def __init__(self, *args: Any, mute: bool = False, **kwargs: Any) -> None:
self._log = Logger("convert_logger")
Expand Down Expand Up @@ -561,6 +564,10 @@ def format_using_autopep8(self, text: str | None = None) -> str | None:
text : str, optional
Text to format instead of `self.lines`. For development use.

Returns
-------
str or None
The formatted text string, or None if no text provided.
"""
if self.cleanup_output:
try:
Expand All @@ -581,7 +588,13 @@ def format_using_autopep8(self, text: str | None = None) -> str | None:
return autopep8.fix_code(text)

def save(self, filename: str) -> None:
"""Saves lines to file"""
"""Saves lines to file.

Parameters
----------
filename : str
The filename to save the lines to.
"""
if os.path.isfile(filename):
os.remove(filename)

Expand All @@ -602,7 +615,15 @@ def save(self, filename: str) -> None:
f.write(self.line_ending.join(self.lines))

def initialize_mapdl_object(self, loglevel: str, exec_file: Optional[str]) -> None:
"""Initializes ansys object as lines"""
"""Initializes ansys object as lines

Parameters
----------
loglevel : str
Logging level for the MAPDL object.
exec_file : str, optional
Path to the ANSYS executable file.
"""
core_module = "ansys.mapdl.core" # shouldn't change
self.lines.append(f"from {core_module} import launch_mapdl")

Expand Down Expand Up @@ -639,7 +660,18 @@ def line_ending(self, line_ending: str) -> None:
self._line_ending = line_ending

def translate_line(self, line: str) -> Optional[str]:
"""Converts a single line from an ANSYS APDL script"""
"""Converts a single line from an ANSYS APDL script

Parameters
----------
line : str
The APDL line to convert.

Returns
-------
str, optional
The converted Python line, or None if no conversion needed.
"""

if "$" in line:
# these are chained commands.
Expand Down Expand Up @@ -993,6 +1025,13 @@ def store_under_scored_run_command(self, command: str) -> None:
def store_run_command(self, command: str, run_underscored: bool = False) -> None:
"""Stores pyansys.ANSYS command that cannot be broken down
into a function and parameters.

Parameters
----------
command : str
The ANSYS command to store.
run_underscored : bool, optional
Whether to use underscored run method. Default is False.
"""
if run_underscored:
underscore = "_"
Expand Down Expand Up @@ -1068,7 +1107,15 @@ def _parse_arguments(self, parameters: List[str]) -> str:
return ", ".join(parsed_parameters)

def store_command(self, function: str, parameters: List[str]) -> None:
"""Stores a valid pyansys function with parameters"""
"""Stores a valid pyansys function with parameters

Parameters
----------
function : str
The function name to store.
parameters : List[str]
List of parameters to pass to the function.
"""
parameter_str = self._parse_arguments(parameters)
parameters_dict = {
"indentation": self.indent,
Expand Down Expand Up @@ -1119,7 +1166,18 @@ def end_chained_commands(self) -> None:
self.chained_commands = False

def output_to_file(self, line: str) -> bool:
"""Return if an APDL line is redirecting to a file."""
"""Return if an APDL line is redirecting to a file.

Parameters
----------
line : str
The APDL line to check.

Returns
-------
bool
True if redirecting to a file, False otherwise.
"""
if line[:4].upper() == "/OUT":
# We are redirecting the output to somewhere, probably a file.
# Because of the problem with the ansys output, we need to execute
Expand Down Expand Up @@ -1159,7 +1217,18 @@ def output_to_default(self, line: str) -> bool:
return False

def _get_items(self, line_: str) -> List[str]:
"""Parse the line items (comma separated elements) but ignoring the ones inside parenthesis, or brackets"""
"""Parse the line items (comma separated elements) but ignoring the ones inside parenthesis, or brackets.

Parameters
----------
line_ : str
The line to parse.

Returns
-------
List[str]
List of parsed items.
"""

parenthesis_count = 0

Expand Down
Loading
Loading