From 4ee44abfccbc67f938021bb903f3d138774d583d Mon Sep 17 00:00:00 2001 From: German <28149841+germa89@users.noreply.github.com> Date: Sun, 17 Nov 2024 13:29:05 +0500 Subject: [PATCH 1/7] refactor: adding type ints to misc --- src/ansys/mapdl/core/misc.py | 75 ++++++++++++++++++------------------ 1 file changed, 37 insertions(+), 38 deletions(-) diff --git a/src/ansys/mapdl/core/misc.py b/src/ansys/mapdl/core/misc.py index 138eb23522..9ea71f0c13 100644 --- a/src/ansys/mapdl/core/misc.py +++ b/src/ansys/mapdl/core/misc.py @@ -33,13 +33,13 @@ import string import tempfile from threading import Thread -from typing import Union +from typing import Union, Tuple, Callable, Dict, Iterable from warnings import warn import numpy as np from ansys.mapdl import core as pymapdl -from ansys.mapdl.core import _HAS_PYVISTA, LOG +from ansys.mapdl.core import _HAS_PYVISTA, LOG, Mapdl # path of this module MODULE_PATH = os.path.dirname(inspect.getfile(inspect.currentframe())) @@ -59,7 +59,7 @@ class ROUTINES(Enum): AUX15 = 65 -def check_valid_routine(routine): +def check_valid_routine(routine: ROUTINES) -> bool: """Check if a routine is valid. Acceptable aliases for "Begin level" include "begin". @@ -98,7 +98,7 @@ def check_valid_routine(routine): return True -def is_float(input_string): +def is_float(input_string: str) -> bool: """Returns true when a string can be converted to a float""" try: float(input_string) @@ -107,14 +107,14 @@ def is_float(input_string): return False -def random_string(stringLength=10, letters=string.ascii_lowercase): +def random_string(stringLength:int=10, letters:str=string.ascii_lowercase)->str: """Generate a random string of fixed length""" import secrets return "".join(secrets.choice(letters) for _ in range(stringLength)) -def _check_has_ansys(): +def _check_has_ansys() -> bool: """Safely wraps check_valid_ansys Returns @@ -131,7 +131,7 @@ def _check_has_ansys(): return False -def supress_logging(func): +def supress_logging(func: Callable) -> Callable: """Decorator to suppress logging for a MAPDL instance""" @wraps(func) @@ -151,7 +151,7 @@ def wrapper(*args, **kwargs): return wrapper -def run_as_prep7(func): +def run_as_prep7(func: Callable) -> Callable: """Run a MAPDL method at PREP7 and always revert to the prior processor""" @wraps(func) @@ -175,7 +175,7 @@ def wrapper(*args, **kwargs): return wrapper -def threaded(func): +def threaded(func: Callable) -> Callable: """Decorator to call a function using a thread""" @wraps(func) @@ -188,7 +188,7 @@ def wrapper(*args, **kwargs): return wrapper -def threaded_daemon(func): +def threaded_daemon(func: Callable) -> Callable: """Decorator to call a function using a daemon thread.""" @wraps(func) @@ -204,18 +204,18 @@ def wrapper(*args, **kwargs): return wrapper -def unique_rows(a): - """Returns unique rows of a and indices of those rows""" - if not a.flags.c_contiguous: - a = np.ascontiguousarray(a) +def unique_rows(arr: np.ndarray) -> Tuple(Union[np.ndarray, np.ndarray, np.ndarray]): + """Returns unique rows of `arr` and indices of those rows""" + if not arr.flags.c_contiguous: + arr = np.ascontiguousarray(arr) - b = a.view(np.dtype((np.void, a.dtype.itemsize * a.shape[1]))) + b = arr.view(np.dtype((np.void, arr.dtype.itemsize * arr.shape[1]))) _, idx, idx2 = np.unique(b, True, True) - return a[idx], idx, idx2 + return arr[idx], idx, idx2 -def creation_time(path_to_file): +def creation_time(path_to_file: str) -> float: """The file creation time. Try to get the date that a file was created, falling back to when @@ -227,14 +227,14 @@ def creation_time(path_to_file): else: stat = os.stat(path_to_file) try: - return stat.st_birthtime + return float(stat.st_birthtime) except AttributeError: # We're probably on Linux. No easy way to get creation dates here, # so we'll settle for when its content was last modified. return stat.st_mtime -def last_created(filenames): +def last_created(filenames: List[str]) -> str: """Return the last created file given a list of filenames If all filenames have the same creation time, then return the last @@ -248,7 +248,7 @@ def last_created(filenames): return filenames[idx] -def create_temp_dir(tmpdir=None, name=None): +def create_temp_dir(tmpdir:str=None, name:str=None) -> str: """Create a new unique directory at a given temporary directory""" if tmpdir is None: tmpdir = tempfile.gettempdir() @@ -273,7 +273,7 @@ def get_name(): return path -def no_return(func): +def no_return(func: Callable) -> Callable: """Decorator to return nothing from the wrapped function""" @wraps(func) @@ -283,14 +283,14 @@ def wrapper(*args, **kwargs): return wrapper -def get_bounding_box(nodes_xyz): +def get_bounding_box(nodes_xyz: np.ndarray) -> np.ndarray: min_ = np.min(nodes_xyz, axis=0) max_ = np.max(nodes_xyz, axis=0) return max_ - min_ -def load_file(mapdl, fname, priority_mapdl_file=None): +def load_file(mapdl:Mapdl, fname:str, priority_mapdl_file:bool=None) -> str: """ Provide a file to the MAPDL instance. @@ -363,26 +363,24 @@ def load_file(mapdl, fname, priority_mapdl_file=None): return os.path.basename(fname) -def check_valid_ip(ip): +def check_valid_ip(ip: str) -> None: """Check for valid IP address""" if ip.lower() != "localhost": ip = ip.replace('"', "").replace("'", "") socket.inet_aton(ip) -def check_valid_port(port, lower_bound=1000, high_bound=60000): +def check_valid_port(port: int, lower_bound:int=1000, high_bound:int=60000) -> None: if not isinstance(port, int): raise ValueError("The 'port' parameter should be an integer.") - if lower_bound < port < high_bound: - return - else: + if not (lower_bound < port < high_bound): raise ValueError( f"'port' values should be between {lower_bound} and {high_bound}." ) -def write_array(filename: Union[str, bytes], array: np.ndarray): +def write_array(filename: Union[str, bytes], array: np.ndarray) -> None: """ Write an array to a file. @@ -401,7 +399,7 @@ def write_array(filename: Union[str, bytes], array: np.ndarray): np.savetxt(filename, array, fmt="%20.12f") -def requires_package(package_name, softerror=False): +def requires_package(package_name: str, softerror:bool =False) -> Callable: """ Decorator check whether a package is installed or not. @@ -439,7 +437,7 @@ def wrapper(self, *args, **kwargs): return decorator -def _get_args_xsel(*args, **kwargs): +def _get_args_xsel(*args: Tuple[str], **kwargs: Dict[str, str]) -> Tuple[str]: type_ = kwargs.pop("type_", str(args[0]) if len(args) else "").upper() item = kwargs.pop("item", str(args[1]) if len(args) > 1 else "").upper() comp = kwargs.pop("comp", str(args[2]) if len(args) > 2 else "").upper() @@ -450,7 +448,7 @@ def _get_args_xsel(*args, **kwargs): return type_, item, comp, vmin, vmax, vinc, kabs, kwargs -def allow_pickable_entities(entity="node", plot_function="nplot"): +def allow_pickable_entities(entity: str="node", plot_function: str="nplot")-> Callable: """ This wrapper opens a window with the NPLOT or KPLOT, and get the selected points (Nodes or kp), and feed them as a list to the NSEL. @@ -515,8 +513,8 @@ def wrapper(self, *args, **kwargs): return decorator -def allow_iterables_vmin(entity="node"): - def decorator(original_sel_func): +def allow_iterables_vmin(entity:str="node") -> Callable: + def decorator(original_sel_func: Callable) -> Callable: """ This function wraps a NSEL or KSEL function to allow using a list/tuple/array for vmin argument. @@ -582,7 +580,7 @@ def wrapper(self, *args, **kwargs): return decorator -def get_active_branch_name(): +def get_active_branch_name() -> str: head_dir = Path(".") / ".git" / "HEAD" if os.path.exists(head_dir): @@ -602,11 +600,12 @@ def get_active_branch_name(): return kind -def only_numbers_and_dots(s): - return bool(re.fullmatch(r"[0-9.]+", s)) +def only_numbers_and_dots(st:str) -> bool: + """Return if a string contains only numbers and dots""" + return bool(re.fullmatch(r"[0-9.]+", st)) -def stack(*decorators): +def stack(*decorators: Iterable[Callable]) -> Callable: """Stack multiple decorators on top of each other""" def deco(f): From f7bcb00c39b38d3bb0bf0d087d63f898b61d2af0 Mon Sep 17 00:00:00 2001 From: German <28149841+germa89@users.noreply.github.com> Date: Sun, 17 Nov 2024 13:31:37 +0500 Subject: [PATCH 2/7] refactor: remove unused function --- src/ansys/mapdl/core/misc.py | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/src/ansys/mapdl/core/misc.py b/src/ansys/mapdl/core/misc.py index 9ea71f0c13..bdb96aa690 100644 --- a/src/ansys/mapdl/core/misc.py +++ b/src/ansys/mapdl/core/misc.py @@ -580,26 +580,6 @@ def wrapper(self, *args, **kwargs): return decorator -def get_active_branch_name() -> str: - head_dir = Path(".") / ".git" / "HEAD" - - if os.path.exists(head_dir): - with head_dir.open("r") as f: - content = f.read().splitlines() - - for line in content: - if line[0:4] == "ref:": - return line.partition("refs/heads/")[2] - - # In case the previous statements return None - if "dev" in pymapdl.__version__: - kind = "main" - else: # pragma: no cover - kind = f"release/{'.'.join(pymapdl.__version__.split('.')[:2])}" - - return kind - - def only_numbers_and_dots(st:str) -> bool: """Return if a string contains only numbers and dots""" return bool(re.fullmatch(r"[0-9.]+", st)) From 8d625a0a12c986e3ef0db30e7feae891b26f4a2c Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 18 Nov 2024 11:53:03 +0000 Subject: [PATCH 3/7] ci: auto fixes from pre-commit.com hooks. for more information, see https://pre-commit.ci --- src/ansys/mapdl/core/misc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ansys/mapdl/core/misc.py b/src/ansys/mapdl/core/misc.py index bdb96aa690..cc4519c9eb 100644 --- a/src/ansys/mapdl/core/misc.py +++ b/src/ansys/mapdl/core/misc.py @@ -33,7 +33,7 @@ import string import tempfile from threading import Thread -from typing import Union, Tuple, Callable, Dict, Iterable +from typing import Callable, Dict, Iterable, Tuple, Union from warnings import warn import numpy as np From 6c39b16a40ccb321c40fb0e1186cc5769693ba3a Mon Sep 17 00:00:00 2001 From: pyansys-ci-bot <92810346+pyansys-ci-bot@users.noreply.github.com> Date: Mon, 18 Nov 2024 11:54:15 +0000 Subject: [PATCH 4/7] chore: adding changelog file 3553.added.md [dependabot-skip] --- doc/changelog.d/3553.added.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 doc/changelog.d/3553.added.md diff --git a/doc/changelog.d/3553.added.md b/doc/changelog.d/3553.added.md new file mode 100644 index 0000000000..252e997f3f --- /dev/null +++ b/doc/changelog.d/3553.added.md @@ -0,0 +1 @@ +refactor: adding-type-ints-to-misc \ No newline at end of file From 7890daba968aa82d8187a2b553e590491b90061a Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 18 Nov 2024 11:54:39 +0000 Subject: [PATCH 5/7] ci: auto fixes from pre-commit.com hooks. for more information, see https://pre-commit.ci --- src/ansys/mapdl/core/misc.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/ansys/mapdl/core/misc.py b/src/ansys/mapdl/core/misc.py index cc4519c9eb..4858f6990c 100644 --- a/src/ansys/mapdl/core/misc.py +++ b/src/ansys/mapdl/core/misc.py @@ -107,7 +107,7 @@ def is_float(input_string: str) -> bool: return False -def random_string(stringLength:int=10, letters:str=string.ascii_lowercase)->str: +def random_string(stringLength: int = 10, letters: str = string.ascii_lowercase) -> str: """Generate a random string of fixed length""" import secrets @@ -248,7 +248,7 @@ def last_created(filenames: List[str]) -> str: return filenames[idx] -def create_temp_dir(tmpdir:str=None, name:str=None) -> str: +def create_temp_dir(tmpdir: str = None, name: str = None) -> str: """Create a new unique directory at a given temporary directory""" if tmpdir is None: tmpdir = tempfile.gettempdir() @@ -290,7 +290,7 @@ def get_bounding_box(nodes_xyz: np.ndarray) -> np.ndarray: return max_ - min_ -def load_file(mapdl:Mapdl, fname:str, priority_mapdl_file:bool=None) -> str: +def load_file(mapdl: Mapdl, fname: str, priority_mapdl_file: bool = None) -> str: """ Provide a file to the MAPDL instance. @@ -370,7 +370,9 @@ def check_valid_ip(ip: str) -> None: socket.inet_aton(ip) -def check_valid_port(port: int, lower_bound:int=1000, high_bound:int=60000) -> None: +def check_valid_port( + port: int, lower_bound: int = 1000, high_bound: int = 60000 +) -> None: if not isinstance(port, int): raise ValueError("The 'port' parameter should be an integer.") @@ -399,7 +401,7 @@ def write_array(filename: Union[str, bytes], array: np.ndarray) -> None: np.savetxt(filename, array, fmt="%20.12f") -def requires_package(package_name: str, softerror:bool =False) -> Callable: +def requires_package(package_name: str, softerror: bool = False) -> Callable: """ Decorator check whether a package is installed or not. @@ -448,7 +450,9 @@ def _get_args_xsel(*args: Tuple[str], **kwargs: Dict[str, str]) -> Tuple[str]: return type_, item, comp, vmin, vmax, vinc, kabs, kwargs -def allow_pickable_entities(entity: str="node", plot_function: str="nplot")-> Callable: +def allow_pickable_entities( + entity: str = "node", plot_function: str = "nplot" +) -> Callable: """ This wrapper opens a window with the NPLOT or KPLOT, and get the selected points (Nodes or kp), and feed them as a list to the NSEL. @@ -513,7 +517,7 @@ def wrapper(self, *args, **kwargs): return decorator -def allow_iterables_vmin(entity:str="node") -> Callable: +def allow_iterables_vmin(entity: str = "node") -> Callable: def decorator(original_sel_func: Callable) -> Callable: """ This function wraps a NSEL or KSEL function to allow using a list/tuple/array for vmin argument. @@ -580,7 +584,7 @@ def wrapper(self, *args, **kwargs): return decorator -def only_numbers_and_dots(st:str) -> bool: +def only_numbers_and_dots(st: str) -> bool: """Return if a string contains only numbers and dots""" return bool(re.fullmatch(r"[0-9.]+", st)) From d503b2eaa849213c04898cdba0efa0d6a8668867 Mon Sep 17 00:00:00 2001 From: German <28149841+germa89@users.noreply.github.com> Date: Mon, 18 Nov 2024 12:57:18 +0100 Subject: [PATCH 6/7] fix: style --- src/ansys/mapdl/core/misc.py | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/ansys/mapdl/core/misc.py b/src/ansys/mapdl/core/misc.py index cc4519c9eb..2ec71102fc 100644 --- a/src/ansys/mapdl/core/misc.py +++ b/src/ansys/mapdl/core/misc.py @@ -26,7 +26,6 @@ import importlib import inspect import os -from pathlib import Path import platform import re import socket @@ -38,7 +37,6 @@ import numpy as np -from ansys.mapdl import core as pymapdl from ansys.mapdl.core import _HAS_PYVISTA, LOG, Mapdl # path of this module @@ -107,7 +105,7 @@ def is_float(input_string: str) -> bool: return False -def random_string(stringLength:int=10, letters:str=string.ascii_lowercase)->str: +def random_string(stringLength: int = 10, letters: str = string.ascii_lowercase) -> str: """Generate a random string of fixed length""" import secrets @@ -248,7 +246,7 @@ def last_created(filenames: List[str]) -> str: return filenames[idx] -def create_temp_dir(tmpdir:str=None, name:str=None) -> str: +def create_temp_dir(tmpdir: str = None, name: str = None) -> str: """Create a new unique directory at a given temporary directory""" if tmpdir is None: tmpdir = tempfile.gettempdir() @@ -290,7 +288,7 @@ def get_bounding_box(nodes_xyz: np.ndarray) -> np.ndarray: return max_ - min_ -def load_file(mapdl:Mapdl, fname:str, priority_mapdl_file:bool=None) -> str: +def load_file(mapdl: Mapdl, fname: str, priority_mapdl_file: bool = None) -> str: """ Provide a file to the MAPDL instance. @@ -370,7 +368,9 @@ def check_valid_ip(ip: str) -> None: socket.inet_aton(ip) -def check_valid_port(port: int, lower_bound:int=1000, high_bound:int=60000) -> None: +def check_valid_port( + port: int, lower_bound: int = 1000, high_bound: int = 60000 +) -> None: if not isinstance(port, int): raise ValueError("The 'port' parameter should be an integer.") @@ -399,7 +399,7 @@ def write_array(filename: Union[str, bytes], array: np.ndarray) -> None: np.savetxt(filename, array, fmt="%20.12f") -def requires_package(package_name: str, softerror:bool =False) -> Callable: +def requires_package(package_name: str, softerror: bool = False) -> Callable: """ Decorator check whether a package is installed or not. @@ -448,7 +448,9 @@ def _get_args_xsel(*args: Tuple[str], **kwargs: Dict[str, str]) -> Tuple[str]: return type_, item, comp, vmin, vmax, vinc, kabs, kwargs -def allow_pickable_entities(entity: str="node", plot_function: str="nplot")-> Callable: +def allow_pickable_entities( + entity: str = "node", plot_function: str = "nplot" +) -> Callable: """ This wrapper opens a window with the NPLOT or KPLOT, and get the selected points (Nodes or kp), and feed them as a list to the NSEL. @@ -513,7 +515,7 @@ def wrapper(self, *args, **kwargs): return decorator -def allow_iterables_vmin(entity:str="node") -> Callable: +def allow_iterables_vmin(entity: str = "node") -> Callable: def decorator(original_sel_func: Callable) -> Callable: """ This function wraps a NSEL or KSEL function to allow using a list/tuple/array for vmin argument. @@ -580,7 +582,7 @@ def wrapper(self, *args, **kwargs): return decorator -def only_numbers_and_dots(st:str) -> bool: +def only_numbers_and_dots(st: str) -> bool: """Return if a string contains only numbers and dots""" return bool(re.fullmatch(r"[0-9.]+", st)) From b7447d2d9925734b286ea67467a8a6949a4d9728 Mon Sep 17 00:00:00 2001 From: German <28149841+germa89@users.noreply.github.com> Date: Mon, 18 Nov 2024 13:50:02 +0100 Subject: [PATCH 7/7] fix: tests --- src/ansys/mapdl/core/misc.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/ansys/mapdl/core/misc.py b/src/ansys/mapdl/core/misc.py index 2ec71102fc..f819d3f383 100644 --- a/src/ansys/mapdl/core/misc.py +++ b/src/ansys/mapdl/core/misc.py @@ -32,12 +32,12 @@ import string import tempfile from threading import Thread -from typing import Callable, Dict, Iterable, Tuple, Union +from typing import Callable, Dict, Iterable, List, Tuple, Union from warnings import warn import numpy as np -from ansys.mapdl.core import _HAS_PYVISTA, LOG, Mapdl +from ansys.mapdl.core import _HAS_PYVISTA, LOG # path of this module MODULE_PATH = os.path.dirname(inspect.getfile(inspect.currentframe())) @@ -202,7 +202,7 @@ def wrapper(*args, **kwargs): return wrapper -def unique_rows(arr: np.ndarray) -> Tuple(Union[np.ndarray, np.ndarray, np.ndarray]): +def unique_rows(arr: np.ndarray) -> Tuple[Union[np.ndarray, np.ndarray, np.ndarray]]: """Returns unique rows of `arr` and indices of those rows""" if not arr.flags.c_contiguous: arr = np.ascontiguousarray(arr) @@ -288,7 +288,7 @@ def get_bounding_box(nodes_xyz: np.ndarray) -> np.ndarray: return max_ - min_ -def load_file(mapdl: Mapdl, fname: str, priority_mapdl_file: bool = None) -> str: +def load_file(mapdl: "Mapdl", fname: str, priority_mapdl_file: bool = None) -> str: """ Provide a file to the MAPDL instance.