Skip to content

Commit

Permalink
Meshing queries using fdl (#1961)
Browse files Browse the repository at this point in the history
* Meshing queries using fdl

* queries as commands

* queries working

* queries crash

* Working in both server and client

* Tests are added

* Tests are added

* Tests fixes

* Tests fixes 2

* Remove old meshing queries

* Revert "Remove old meshing queries"

This reverts commit 5c015f0.

* Handle ols and new meshing queries

* Resolve circular import

* Resolve circular import 2

* Resolve circular import 3

* Resolve circular import 4

* Resolve circular import 5

* Resolve circular import 6

* Resolve circular import 7

* Resolve circular import 8

* Resolve circular import 9

* Resolve circular import 10

* Resolve circular import 11

* Resolve circular import 11

* Resolve circular import 12

* Resolve circular import 13

* Resolve circular import 14

* Resolve circular import 15

* Resolve circular import 16

* Resolve circular import 17

* Resolved meshing_queries attribute error

* Remove query checks

* Remove query checks 2

* rename MeshingQueries

* None return resolved

* Test added for get labels

* Test added for get ids with labels

* Test added for remove labels

* Test added for appendix A.3

* Test added for appendix A.4

* Test added for appendix A.5

* Test added for appendix A.6

* Use single function to build docstring

* Fixes new 1

* Meshing utilities changes 1

* Revert "Meshing utilities changes 1"

This reverts commit 321f962.

* Revert "Revert "Meshing utilities changes 1""

This reverts commit edc6f1b.

* Resolve none issue

* Allowed values test

* Allowed values test 1

* version update

* docformatter

* test update

* test update 1

* test update 2

* test update 3

* version check
  • Loading branch information
hpohekar authored Nov 30, 2023
1 parent 7922254 commit 0f065d4
Show file tree
Hide file tree
Showing 6 changed files with 2,212 additions and 11 deletions.
38 changes: 32 additions & 6 deletions codegen/datamodelgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

_THIS_DIR = Path(__file__).parent


_PY_TYPE_BY_DM_TYPE = {
**dict.fromkeys(["Logical", "Bool"], "bool"),
**dict.fromkeys(["Logical List", "ListBool"], "List[bool]"),
Expand Down Expand Up @@ -66,8 +65,8 @@ def _build_parameter_docstring(name: str, t: str):
return f"Parameter {name} of value type {_PY_TYPE_BY_DM_TYPE[t]}."


def _build_command_docstring(name: str, info: Any, indent: str):
doc = f"{indent}Command {name}.\n\n"
def _build_command_query_docstring(name: str, info: Any, indent: str, is_command: bool):
doc = f"{indent}Command {name}.\n\n" if is_command else f"{indent}Query {name}.\n\n"
if info.args:
doc += f"{indent}Parameters\n"
doc += f"{indent}{'-' * len('Parameters')}\n"
Expand Down Expand Up @@ -146,6 +145,10 @@ def __init__(self, version, pyfluent_path):
if int(self.version) >= 231
else None,
}
if int(self.version) >= 242:
self._static_info["meshing_utilities"] = DataModelStaticInfo(
pyfluent_path, "MeshingUtilities", ("meshing",), self.version
)
if not self._static_info["solverworkflow"]:
del self._static_info["solverworkflow"]
self._delete_generated_files()
Expand Down Expand Up @@ -223,6 +226,9 @@ def _write_static_info(self, name: str, info: Any, f: FileIO, level: int = 0):
singletons = sorted(info.singletons)
parameters = sorted(info.parameters)
commands = sorted(info.commands)
queries = []
if hasattr(info, "queries"):
queries = sorted(info.queries)
for k in named_objects:
f.write(
f"{indent} self.{k} = "
Expand All @@ -245,6 +251,11 @@ def _write_static_info(self, name: str, info: Any, f: FileIO, level: int = 0):
f"{indent} self.{k} = "
f'self.__class__.{k}(service, rules, "{k}", path)\n'
)
for k in queries:
f.write(
f"{indent} self.{k} = "
f'self.__class__.{k}(service, rules, "{k}", path)\n'
)
f.write(f"{indent} super().__init__(service, rules, path)\n\n")
for k in named_objects:
f.write(f"{indent} class {k}(PyNamedObjectContainer):\n")
Expand Down Expand Up @@ -288,13 +299,24 @@ def _write_static_info(self, name: str, info: Any, f: FileIO, level: int = 0):
f.write(f"{indent} class {k}(PyCommand):\n")
f.write(f'{indent} """\n')
f.write(
_build_command_docstring(
k, info.commands[k].commandinfo, f"{indent} "
_build_command_query_docstring(
k, info.commands[k].commandinfo, f"{indent} ", True
)
)
f.write(f'{indent} """\n')
f.write(f"{indent} pass\n\n")
api_tree[k] = "Command"
for k in queries:
f.write(f"{indent} class {k}(PyQuery):\n")
f.write(f'{indent} """\n')
f.write(
_build_command_query_docstring(
k, info.queries[k].queryinfo, f"{indent} ", False
)
)
f.write(f'{indent} """\n')
f.write(f"{indent} pass\n\n")
api_tree[k] = "Query"
return api_tree

def _write_doc_for_model_object(
Expand All @@ -317,6 +339,9 @@ def _write_doc_for_model_object(
singletons = sorted(info.singletons)
parameters = sorted(info.parameters)
commands = sorted(info.commands)
queries = []
if hasattr(info, "queries"):
queries = sorted(info.queries)

f.write(f".. autoclass:: {module_name}.{class_name}\n")
if noindex:
Expand Down Expand Up @@ -388,7 +413,8 @@ def write_static_info(self) -> None:
f.write(" PyNumerical,\n")
f.write(" PyDictionary,\n")
f.write(" PyNamedObjectContainer,\n")
f.write(" PyCommand\n")
f.write(" PyCommand,\n")
f.write(" PyQuery\n")
f.write(")\n\n\n")
api_tree_val = {
name: self._write_static_info("Root", info.static_info, f)
Expand Down
72 changes: 70 additions & 2 deletions src/ansys/fluent/core/services/datamodel_se.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,14 @@ def execute_command(
logger.debug(f"Command: {request.command}")
return self._stub.executeCommand(request, metadata=self._metadata)

@catch_grpc_error
def execute_query(
self, request: DataModelProtoModule.ExecuteQueryRequest
) -> DataModelProtoModule.ExecuteQueryResponse:
"""ExecuteQuery rpc of DataModel service."""
logger.debug(f"Query: {request.query}")
return self._stub.executeQuery(request, metadata=self._metadata)

@catch_grpc_error
def create_command_arguments(
self, request: DataModelProtoModule.CreateCommandArgumentsRequest
Expand Down Expand Up @@ -1044,6 +1052,61 @@ def get_state(self):
return dict(sorted(returned_state.items()))


class PyQuery:
"""Query class using the StateEngine-based DatamodelService as the backend. Use this
class instead of directly calling the DatamodelService's method.
Methods
-------
__call__()
Execute the query.
help()
Print the query help string.
"""

docstring = None
_stored_static_info = {}

def __init__(
self, service: DatamodelService, rules: str, query: str, path: Path = None
):
"""__init__ method of PyQuery class."""
self.service = service
self.rules = rules
self.query = query
if path is None:
self.path = []
else:
self.path = path

def __call__(self, *args, **kwds) -> Any:
"""Execute the query.
Returns
-------
Any
Return value.
"""
request = DataModelProtoModule.ExecuteQueryRequest()
request.rules = self.rules
request.path = convert_path_to_se_path(self.path)
request.query = self.query
_convert_value_to_variant(kwds, request.args)
response = self.service.execute_query(request)
return _convert_variant_to_value(response.result)

def help(self) -> None:
"""Prints help string."""
request = DataModelProtoModule.GetSpecsRequest()
request.rules = self.rules
request.path = convert_path_to_se_path(self.path)
response = self.service.get_specs(request)
help_string = getattr(
response.member, response.member.WhichOneof("as")
).query.helpstring
print(help_string)


class PyCommand:
"""Command class using the StateEngine-based DatamodelService as the backend. Use
this class instead of directly calling the DatamodelService's method.
Expand Down Expand Up @@ -1409,6 +1472,7 @@ def _get_child_names(self) -> tuple[list, list, list]:
singleton_names = []
creatable_type_names = []
command_names = []
query_names = []
for struct_type in ("singleton", "namedobject"):
if response.member.HasField(struct_type):
struct_field = getattr(response.member, struct_type)
Expand All @@ -1417,12 +1481,14 @@ def _get_child_names(self) -> tuple[list, list, list]:
singleton_names.append(member)
creatable_type_names = struct_field.creatabletypes
command_names = [x.name for x in struct_field.commands]
return singleton_names, creatable_type_names, command_names
if hasattr(struct_field, "queries"):
query_names = [x.name for x in struct_field.queries]
return singleton_names, creatable_type_names, command_names, query_names

def _get_child(
self, name: str
) -> Union["PyMenuGeneric", PyNamedObjectContainer, PyCommand]:
singletons, creatable_types, commands = self._get_child_names()
singletons, creatable_types, commands, queries = self._get_child_names()
if name in singletons:
child_path = self.path + [(name, "")]
return PyMenuGeneric(self.service, self.rules, child_path)
Expand All @@ -1431,6 +1497,8 @@ def _get_child(
return PyNamedObjectContainerGeneric(self.service, self.rules, child_path)
elif name in commands:
return PyCommand(self.service, self.rules, name, self.path)
elif name in queries:
return PyQuery(self.service, self.rules, name, self.path)
else:
raise LookupError(
f"{name} is not found at path " f"{convert_path_to_se_path(self.path)}"
Expand Down
28 changes: 27 additions & 1 deletion src/ansys/fluent/core/session_base_meshing.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,14 @@ def __init__(
self._fluent_connection = fluent_connection
self._tui = None
self._meshing = None
self._fluent_version = fluent_version
self._meshing_utilities = None
self._workflow = None
self._part_management = None
self._pm_file_management = None
self._preferences = None
self._session_execute_tui = session_execute_tui
self._version = None
self._fluent_version = fluent_version

def get_fluent_version(self):
"""Gets and returns the fluent version."""
Expand Down Expand Up @@ -92,6 +93,31 @@ def meshing(self):
self._meshing = self._meshing_root
return self._meshing

@property
def _meshing_utilities_root(self):
"""Datamodel root of meshing_utilities."""
try:
if self.get_fluent_version() >= "24.2.0":
meshing_utilities_module = importlib.import_module(
f"ansys.fluent.core.datamodel_{self.version}.MeshingUtilities"
)
meshing_utilities_root = meshing_utilities_module.Root(
self._se_service, "MeshingUtilities", []
)
except ImportError:
datamodel_logger.warning(_CODEGEN_MSG_DATAMODEL)
if self.get_fluent_version() >= "24.2.0":
meshing_utilities_root = PyMenuGeneric(
self._se_service, "meshing_utilities"
)
return meshing_utilities_root

@property
def meshing_utilities(self):
if self._meshing_utilities is None:
self._meshing_utilities = self._meshing_utilities_root
return self._meshing_utilities

@property
def _workflow_se(self):
"""Datamodel root of workflow."""
Expand Down
5 changes: 5 additions & 0 deletions src/ansys/fluent/core/session_meshing.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@ def meshing(self):
"""Datamodel root of meshing."""
return super(Meshing, self).meshing if not self.switched else None

@property
def meshing_utilities(self):
"""Datamodel root of meshing_utilities."""
return super(Meshing, self).meshing_utilities if not self.switched else None

@property
def workflow(self):
"""Datamodel root of workflow."""
Expand Down
22 changes: 20 additions & 2 deletions src/ansys/fluent/core/session_pure_meshing.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,14 @@ class PureMeshing(BaseSession):
in this mode.
"""

rules = ["workflow", "meshing", "PartManagement", "PMFileManagement"]
rules = [
"workflow",
"meshing",
"MeshingUtilities",
"PartManagement",
"PMFileManagement",
]

for r in rules:
DataModelCache.set_config(r, "name_key", NameKey.INTERNAL)

Expand Down Expand Up @@ -55,7 +62,6 @@ def __init__(
self.meshing_queries_service = fluent_connection.create_service(
MeshingQueriesService, self.error_state
)
self.meshing_queries = MeshingQueries(self.meshing_queries_service)

datamodel_service_se = self.datamodel_service_se
self.datamodel_streams = {}
Expand Down Expand Up @@ -83,6 +89,18 @@ def meshing(self):
"""Datamodel root of meshing."""
return self._base_meshing.meshing

@property
def meshing_queries(self):
"""Datamodel root of meshing_queries."""
if float(self.get_fluent_version()[:-2]) >= 23.2:
return MeshingQueries(self.meshing_queries_service)

@property
def meshing_utilities(self):
"""Datamodel root of meshing_utilities."""
if self.get_fluent_version() >= "24.2.0":
return self._base_meshing.meshing_utilities

@property
def workflow(self):
"""Datamodel root of workflow."""
Expand Down
Loading

0 comments on commit 0f065d4

Please sign in to comment.