Skip to content

Commit

Permalink
fix: Use _search() for failed calls and disable printing of API objec…
Browse files Browse the repository at this point in the history
…ts during codegen (#2901)

* fix: Disable printing of API objects during codegen

* return results

* update tests

* fix: Use pyfluent.search() for failed calls

* update warning message

* version fix

* remove function

* use _search

* use _search 1

* set 24.2 version

* Revert "set 24.2 version"

This reverts commit fa7a761.

* Reapply "set 24.2 version"

This reverts commit a3d9546.

* use list instead of set

* test fix search_root

* test fix conduction

* write_api_tree_data bool

* skip 23.2 test

* skip 24.1

* update package
  • Loading branch information
hpohekar authored Jun 12, 2024
1 parent 0e97f28 commit 2316f7a
Show file tree
Hide file tree
Showing 10 changed files with 124 additions and 132 deletions.
2 changes: 1 addition & 1 deletion codegen/allapigen.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,4 @@
allapigen.generate(version, static_infos)
t2 = time()
print(f"Time to generate APIs: {t2 - t1:.2f} seconds")
_search("", version=version)
_search("", version=version, write_api_tree_data=True)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ include = [
{ path = "src/ansys/fluent/core/generated/solver/settings_*/*.py", format = ["sdist", "wheel"] },
{ path = "src/ansys/fluent/core/generated/solver/settings_*/*.pyi", format = ["sdist", "wheel"] },
{ path = "src/ansys/fluent/core/generated/*.pickle", format = ["sdist", "wheel"] },
{ path = "src/ansys/fluent/core/generated/api_tree/*.txt", format = ["sdist", "wheel"] },
{ path = "src/ansys/fluent/core/generated/api_tree/*.json", format = ["sdist", "wheel"] },
]

packages = [
Expand Down
4 changes: 2 additions & 2 deletions src/ansys/fluent/core/session_base_meshing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import logging

import ansys.fluent.core as pyfluent
from ansys.fluent.core.fluent_connection import FluentConnection
from ansys.fluent.core.meshing.meshing_workflow import (
CreateWorkflow,
Expand All @@ -14,7 +15,6 @@
_make_datamodel_module,
_make_tui_module,
)
from ansys.fluent.core.utils import load_module
from ansys.fluent.core.utils.fluent_version import (
FluentVersion,
get_version_for_file_name,
Expand Down Expand Up @@ -91,7 +91,7 @@ def _meshing_utilities_root(self):
if self.get_fluent_version() >= FluentVersion.v242:
from ansys.fluent.core import CODEGEN_OUTDIR

meshing_utilities_module = load_module(
meshing_utilities_module = pyfluent.utils.load_module(
f"MeshingUtilities_{self._version}",
CODEGEN_OUTDIR
/ f"datamodel_{self._version}"
Expand Down
6 changes: 3 additions & 3 deletions src/ansys/fluent/core/session_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

import logging

import ansys.fluent.core as pyfluent
from ansys.fluent.core.services.datamodel_se import PyMenuGeneric
from ansys.fluent.core.services.datamodel_tui import TUIMenu
from ansys.fluent.core.utils import load_module

_CODEGEN_MSG_DATAMODEL = (
"Currently calling the datamodel API in a generic manner. "
Expand All @@ -26,7 +26,7 @@ def _make_tui_module(session, module_name):
try:
from ansys.fluent.core import CODEGEN_OUTDIR

tui_module = load_module(
tui_module = pyfluent.utils.load_module(
f"{module_name}_tui_{session._version}",
CODEGEN_OUTDIR / module_name / f"tui_{session._version}.py",
)
Expand All @@ -42,7 +42,7 @@ def _make_datamodel_module(session, module_name):
try:
from ansys.fluent.core import CODEGEN_OUTDIR

module = load_module(
module = pyfluent.utils.load_module(
f"{module_name}_{session._version}",
CODEGEN_OUTDIR / f"datamodel_{session._version}" / f"{module_name}.py",
)
Expand Down
7 changes: 6 additions & 1 deletion src/ansys/fluent/core/solver/error_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@ def closest_allowed_names(trial_name: str, allowed_names: str) -> List[str]:


def allowed_name_error_message(
allowed_values: Any,
allowed_values: Optional[Any] = None,
context: Optional[str] = None,
trial_name: Optional[str] = None,
message: Optional[str] = None,
search_results: Optional[list] = None,
) -> str:
"""Provide an error message with the closest names matching the 'trial_name' from
the 'allowed_values' list."""
Expand All @@ -30,6 +31,10 @@ def allowed_name_error_message(
message += f"The most similar names are: {', '.join(matches)}."
else:
message += f"The allowed values are: {allowed_values}."
elif search_results:
message = message + "\nThe most similar API names are:\n"
for search_result in search_results:
message += search_result + "\n"

return message

Expand Down
35 changes: 11 additions & 24 deletions src/ansys/fluent/core/solver/flobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@
PyFluentDeprecationWarning = FutureWarning
PyFluentUserWarning = UserWarning

import ansys.fluent.core as pyfluent

from .error_message import allowed_name_error_message, allowed_values_error
from .settings_external import expand_api_file_argument

Expand Down Expand Up @@ -1036,28 +1038,6 @@ def get_completer_info(self, prefix="", excluded=None) -> List[List[str]]:
ret.extend(items)
return ret

def _get_parent_of_active_child_names(self, name):
with warnings.catch_warnings():
warnings.filterwarnings(action="ignore", category=UnstableSettingWarning)
parents = ""
path_list = []
for parent in self.get_active_child_names():
try:
if hasattr(getattr(self, parent), str(name)):
path_list.append(f" {self.python_path}.{parent}.{str(name)}")
if len(parents) != 0:
parents += ", " + parent
else:
parents += parent
except AttributeError:
pass
if len(path_list):
print(f"\n {str(name)} can be accessed from the following paths: \n")
for path in path_list:
print(path)
if len(parents):
return f"\n {name} is a child of {parents} \n"

def __getattribute__(self, name):
if name in super().__getattribute__("child_names"):
if self.is_active() is False:
Expand All @@ -1077,11 +1057,18 @@ def __getattribute__(self, name):
attr._check_stable()
return attr
except AttributeError as ex:
self._get_parent_of_active_child_names(name)
modified_search_results = []
for search_result in pyfluent.utils._search(
word=name, search_root=self, match_case=False, match_whole_word=False
):
search_result = search_result.replace(
"<search_root>", self.__class__.__name__
)
modified_search_results.append(search_result)
error_msg = allowed_name_error_message(
trial_name=name,
allowed_values=super().__getattribute__("child_names"),
message=ex.args[0],
search_results=modified_search_results,
)
ex.args = (error_msg,)
raise
Expand Down
2 changes: 2 additions & 0 deletions src/ansys/fluent/core/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

logger = logging.getLogger("pyfluent.general")

from .search import _search # noqa: F401


def load_module(module_name, file_path):
"""Load a module from a file path."""
Expand Down
28 changes: 15 additions & 13 deletions src/ansys/fluent/core/utils/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ def _search(
match_case: bool = False,
version: Optional[str] = None,
search_root: Optional[Any] = None,
write_api_tree_data: Optional[bool] = False,
):
"""Search for a word through the Fluent's object hierarchy.
Expand All @@ -167,6 +168,8 @@ def _search(
The root object within which the search is performed.
It can be a session object or any API object within a session.
The default is ``None``. If ``None``, it searches everything.
write_api_tree_data: bool, optional
Whether to write the API tree data.
Examples
--------
Expand All @@ -189,14 +192,13 @@ def _search(
"""
api_objects = []
api_tui_objects = []
api_object_names = set()
api_object_names = []
results = []
if version:
version = get_version_for_file_name(version)
root_version, root_path, prefix = _get_version_path_prefix_from_obj(search_root)
if search_root and not prefix:
return
if not version:
version = root_version
if not version:
for fluent_version in FluentVersion:
version = get_version_for_file_name(fluent_version.value)
Expand Down Expand Up @@ -245,13 +247,13 @@ def inner(tree, path, root_path):
else:
next_path = f"{path}.{k}"
type_ = "Object" if isinstance(v, Mapping) else v
api_object_names.add(k)
api_object_names.append(k)
if "tui" in next_path:
api_tui_objects.append(f"{next_path} ({type_})")
else:
api_objects.append(f"{next_path} ({type_})")
if _match(k, word, match_whole_word, match_case):
print(f"{next_path} ({type_})")
results.append(f"{next_path} ({type_})")
if isinstance(v, Mapping):
inner(v, next_path, root_path)

Expand Down Expand Up @@ -286,9 +288,11 @@ def _write_api_tree_file(api_tree_data: dict, api_object_names: list):
with open(api_tree_file, "w") as json_file:
json.dump(api_tree_data, json_file)

_write_api_tree_file(
api_tree_data=api_tree_data, api_object_names=list(api_object_names)
)
if write_api_tree_data:
_write_api_tree_file(
api_tree_data=api_tree_data, api_object_names=list(api_object_names)
)
return results


@functools.cache
Expand Down Expand Up @@ -643,17 +647,17 @@ def search(
)
elif language and match_whole_word:
warnings.warn(
"``match_whole_word=True`` matches the given word, and it's capitalize case.",
"``match_whole_word=True`` matches the whole word (case insensitive).",
UserWarning,
)
elif match_whole_word:
warnings.warn(
"``match_whole_word=True`` matches the given word, and it's capitalize case.",
"``match_whole_word=True`` matches the whole word (case insensitive).",
UserWarning,
)
elif match_case:
warnings.warn(
"``match_case=True`` matches the given word.",
"``match_case=True`` matches the whole word (case sensitive).",
UserWarning,
)

Expand All @@ -678,8 +682,6 @@ def search(
root_version, root_path, prefix = _get_version_path_prefix_from_obj(search_root)
if search_root and not prefix:
return
if not version:
version = root_version
if not version:
for fluent_version in FluentVersion:
version = get_version_for_file_name(fluent_version.value)
Expand Down
Loading

0 comments on commit 2316f7a

Please sign in to comment.