diff --git a/.ci/start_fluent.py b/.ci/start_fluent.py index 2c783bceda71..3ba71ebfe205 100644 --- a/.ci/start_fluent.py +++ b/.ci/start_fluent.py @@ -17,14 +17,30 @@ def start_fluent_container(args): port = os.environ["PYFLUENT_FLUENT_PORT"] try: - subprocess.run(["docker", "run", "--name", "fluent_server", "-d", - "--rm", "-p", f"{port}:{port}", - "-v", f"{EXAMPLES_PATH}:{EXAMPLES_PATH}", - "-e", f"ANSYSLMD_LICENSE_FILE={license_server}", - "-e", f"REMOTING_PORTS={port}/portspan=2", - "-e", "FLUENT_LAUNCHED_FROM_PYFLUENT=1", - "ghcr.io/pyansys/pyfluent", - "-g", f"-sifile={sifile}"] + args) + subprocess.run( + [ + "docker", + "run", + "--name", + "fluent_server", + "-d", + "--rm", + "-p", + f"{port}:{port}", + "-v", + f"{EXAMPLES_PATH}:{EXAMPLES_PATH}", + "-e", + f"ANSYSLMD_LICENSE_FILE={license_server}", + "-e", + f"REMOTING_PORTS={port}/portspan=2", + "-e", + "FLUENT_LAUNCHED_FROM_PYFLUENT=1", + "ghcr.io/pyansys/pyfluent", + "-g", + f"-sifile={sifile}", + ] + + args + ) sifile_last_mtime = os.stat(sifile).st_mtime while True: diff --git a/.flake8 b/.flake8 deleted file mode 100644 index 1e85f7543085..000000000000 --- a/.flake8 +++ /dev/null @@ -1,9 +0,0 @@ -[flake8] -exclude = venv, tui.py, ansys/api/fluent, ansys/fluent/core/solver/settings.py -per-file-ignores = - ansys/fluent/post/post_object_defns.py # noqa: N801 -select = W191, W291, W293, W391, E115, E117, E122, E124, E125, E225, E231, E301, E303, E501, F401, F403, N801, N802, N803, N804, N805, N806 -count = True -max-complexity = 10 -max-line-length = 79 -statistics = True diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2825022a0164..3cee5b294d34 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,14 +27,14 @@ jobs: with: python-version: 3.9 - - name: Install Style Requirements + - name: Install pre-commit run: | - pip install -r requirements_style.txt --disable-pip-version-check + python -m pip install pre-commit - - name: Run flake8 + - name: Run pre-commit if: always() run: | - make flake8 + pre-commit run --all-files --show-diff-on-failure - name: Run protolint uses: plexsystems/protolint-action@v0.6.0 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 000000000000..04f87ffe3874 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,69 @@ +repos: + +- repo: https://github.com/psf/black + rev: 22.3.0 + hooks: + - id: black + args: [ + --line-length, "79", + --force-exclude, ansys/api/fluent/v0/|ansys/fluent/core/meshing/tui.py|ansys/fluent/core/solver/tui.py|ansys/fluent/core/solver/settings.py, + ansys, codegen, doc, examples, tests + ] + +- repo: https://github.com/pycqa/isort + rev: 5.10.1 + hooks: + - id: isort + args: [ + --profile, black, + --skip, ansys/fluent/core/meshing/tui.py, + --skip, ansys/fluent/core/solver/tui.py, + --skip, ansys/fluent/core/solver/settings.py, + --skip-glob, ansys/api/fluent/v0/*, + --force-sort-within-sections, + --line-length, "79", + --section-default, THIRDPARTY, + --filter-files, + ansys, codegen, doc, examples, tests + ] + +- repo: https://github.com/PyCQA/flake8 + rev: 4.0.1 + hooks: + - id: flake8 + args: [ + --exclude, ansys/api/fluent/v0/* ansys/fluent/core/meshing/tui.py ansys/fluent/core/solver/tui.py ansys/fluent/core/solver/settings.py, + --select, W191 W291 W293 W391 E115 E117 E122 E124 E125 E225 E231 E301 E303 F401 F403 N801 N802 N803 N804 N805 N806, + --count, + --statistics, + --max-complexity, "10", + --max-line-length, "79", + ansys, codegen, doc, examples, tests + ] + +- repo: https://github.com/codespell-project/codespell + rev: v2.1.0 + hooks: + - id: codespell + args: [ + --skip, "ansys/api/fluent/v0/*,ansys/fluent/core/meshing/tui.py,ansys/fluent/core/solver/tui.py,ansys/fluent/core/solver/settings.py", + ] + +- repo: https://github.com/myint/docformatter + rev: v1.3.1 + hooks: + - id: docformatter + exclude: ^(tests\/|ansys\/api\/fluent\/v0\/|ansys\/fluent\/core\/meshing\/tui.py|ansys\/fluent\/core\/solver\/tui.py|ansys\/fluent\/core\/solver\/settings.py) + args: [-r, --in-place] + +#- repo: https://github.com/pycqa/pydocstyle +# rev: 6.1.1 +# hooks: +# - id: pydocstyle +# additional_dependencies: [toml] +# exclude: ^(tests\/|ansys\/api\/fluent\/v0\/|ansys\/fluent\/core\/meshing\/tui.py|ansys\/fluent\/core\/solver\/tui.py|ansys\/fluent\/core\/solver\/settings.py) +# args: [ +# # Error codes: http://www.pydocstyle.org/en/stable/error_codes.html +# --ignore, "D107,D105,D4", +# --count, +# ] diff --git a/pylintrc b/.pylintrc similarity index 100% rename from pylintrc rename to .pylintrc diff --git a/Makefile b/Makefile index 95e79d8cf1d1..0e772eae5963 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ -flake8: - @echo "Running flake8" - @flake8 . +style: + @echo "Running code style" + @pre-commit run --all-files --show-diff-on-failure install: @pip install -r requirements_build.txt diff --git a/ansys/fluent/core/__init__.py b/ansys/fluent/core/__init__.py index bd7078d9f7d1..61700fa5fe3b 100644 --- a/ansys/fluent/core/__init__.py +++ b/ansys/fluent/core/__init__.py @@ -1,12 +1,13 @@ """A package providing Fluent's Solver and Meshing capabilities in Python.""" -import appdirs import os +import appdirs + +from ansys.fluent.core._version import __version__ # noqa: F401 from ansys.fluent.core.launcher.launcher import launch_fluent # noqa: F401 from ansys.fluent.core.session import Session from ansys.fluent.core.utils.logging import LOG -from ansys.fluent.core._version import __version__ # noqa: F401 try: from ansys.fluent.core.meshing import tui as meshing_tui @@ -19,8 +20,7 @@ def set_log_level(level): - """ - Set logging level. + """Set logging level. Parameters ---------- @@ -42,8 +42,7 @@ def disable_logging_to_stdout(): def enable_logging_to_file(filepath: str = None): - """ - Enable logging to file. + """Enable logging to file. Parameters ---------- diff --git a/ansys/fluent/core/examples/downloads.py b/ansys/fluent/core/examples/downloads.py index 5fd1876aa130..c238e4974e36 100644 --- a/ansys/fluent/core/examples/downloads.py +++ b/ansys/fluent/core/examples/downloads.py @@ -1,5 +1,4 @@ -""" -Functions to download sample datasets from the pyansys data repository. +"""Functions to download sample datasets from the pyansys data repository. Example ------- @@ -8,7 +7,6 @@ >>> filename = examples.download_file("bracket.iges", "geometry") >>> filename '/home/user/.local/share/ansys_fluent_core/examples/bracket.iges' - """ import os import shutil @@ -19,13 +17,13 @@ def get_ext(filename): - """Extract the extension of the filename""" + """Extract the extension of the filename.""" ext = os.path.splitext(filename)[1].lower() return ext def delete_downloads(): - """Delete all downloaded examples to free space or update the files""" + """Delete all downloaded examples to free space or update the files.""" shutil.rmtree(pyfluent.EXAMPLES_PATH) os.makedirs(pyfluent.EXAMPLES_PATH) return True diff --git a/ansys/fluent/core/launcher/launcher.py b/ansys/fluent/core/launcher/launcher.py index 9b15b143886b..c586094ce804 100644 --- a/ansys/fluent/core/launcher/launcher.py +++ b/ansys/fluent/core/launcher/launcher.py @@ -1,21 +1,20 @@ -""" -Provide a module for launching Fluent. +"""Provide a module for launching Fluent. -This module supports both starting Fluent locally or connecting to a remote -instance with gRPC. +This module supports both starting Fluent locally or connecting to a +remote instance with gRPC. """ import json import os +from pathlib import Path import platform import subprocess import tempfile import time -from pathlib import Path from typing import Any, Dict -from ansys.fluent.core.utils.logging import LOG from ansys.fluent.core.session import Session +from ansys.fluent.core.utils.logging import LOG _THIS_DIR = os.path.dirname(__file__) _OPTIONS_FILE = os.path.join(_THIS_DIR, "fluent_launcher_options.json") diff --git a/ansys/fluent/core/meta.py b/ansys/fluent/core/meta.py index 69cdcead1291..52ab3215720c 100644 --- a/ansys/fluent/core/meta.py +++ b/ansys/fluent/core/meta.py @@ -123,9 +123,7 @@ def wrapper(self, obj=None): return wrapper def __new__(cls, name, bases, attrs): - attrs[ - "_get_parent_by_type" - ] = cls.__create_get_parent_by_type() + attrs["_get_parent_by_type"] = cls.__create_get_parent_by_type() attrs["_get_top_most_parent"] = cls.__create_get_top_most_parent() return super(PyLocalBaseMeta, cls).__new__(cls, name, bases, attrs) diff --git a/ansys/fluent/core/services/datamodel_se.py b/ansys/fluent/core/services/datamodel_se.py index 83ae0c4a794d..24f9b01c062c 100644 --- a/ansys/fluent/core/services/datamodel_se.py +++ b/ansys/fluent/core/services/datamodel_se.py @@ -1,25 +1,24 @@ """Wrappers over StateEngine based datamodel grpc service of Fluent.""" -import itertools from enum import Enum +import itertools from typing import Any, Iterator, List, Tuple import grpc from ansys.api.fluent.v0 import datamodel_se_pb2 as DataModelProtoModule from ansys.api.fluent.v0 import datamodel_se_pb2_grpc as DataModelGrpcModule -from ansys.fluent.core.utils.async_execution import asynchronous from ansys.fluent.core.services.error_handler import catch_grpc_error from ansys.fluent.core.services.interceptors import TracingInterceptor +from ansys.fluent.core.utils.async_execution import asynchronous Path = List[Tuple[str, str]] class Attribute(Enum): - """ - Class containing the standard names of data model attributes - associated with the datamodel service - """ + """Class containing the standard names of data model attributes associated + with the datamodel service.""" + IS_ACTIVE = "isActive" EXPOSURE_LEVEL = "exposureLevel" IS_READ_ONLY = "isReadOnly" @@ -52,9 +51,9 @@ class Attribute(Enum): class DatamodelService: - """ - Class wrapping the StateEngine based datamodel grpc service of - Fluent. It is suggested to use the methods from PyMenu class. + """Class wrapping the StateEngine based datamodel grpc service of Fluent. + + It is suggested to use the methods from PyMenu class. """ def __init__(self, channel: grpc.Channel, metadata): @@ -99,7 +98,7 @@ def get_specs(self, request): def _convert_value_to_variant(val, var): - """Convert Python datatype to Fluent's Variant type""" + """Convert Python datatype to Fluent's Variant type.""" if isinstance(val, bool): var.bool_state = val @@ -122,7 +121,7 @@ def _convert_value_to_variant(val, var): def _convert_variant_to_value(var): - """Convert Fluent's Variant to Python datatype""" + """Convert Fluent's Variant to Python datatype.""" if var.HasField("bool_state"): return var.bool_state @@ -153,8 +152,7 @@ def _convert_variant_to_value(var): def _convert_path_to_se_path(path: Path) -> str: - """ - Convert path structure to a StateEngine path + """Convert path structure to a StateEngine path. Parameters ---------- @@ -175,10 +173,8 @@ def _convert_path_to_se_path(path: Path) -> str: class PyMenu: - """ - Object class using StateEngine based DatamodelService as backend. - Use this class instead of directly calling DatamodelService's - method. + """Object class using StateEngine based DatamodelService as backend. Use + this class instead of directly calling DatamodelService's method. Methods ------- @@ -280,7 +276,7 @@ def set_state(self, state): setState = set_state - def update_dict(self, dict_state : dict): + def update_dict(self, dict_state: dict): request = DataModelProtoModule.UpdateDictRequest() request.rules = self.rules request.path = _convert_path_to_se_path(self.path) @@ -290,7 +286,7 @@ def update_dict(self, dict_state : dict): updateDict = update_dict def __dir__(self) -> List[str]: - """Returns list of child object names + """Returns list of child object names. Returns ------- @@ -300,7 +296,7 @@ def __dir__(self) -> List[str]: return list(itertools.chain(*self.__get_child_names())) def __getattr__(self, name: str) -> Any: - """Returns the child object + """Returns the child object. Parameters ---------- @@ -318,7 +314,7 @@ def __getattr__(self, name: str) -> Any: return self.__get_child(name) def __setattr__(self, name: str, value: Any): - """Set state of the child object + """Set state of the child object. Parameters ---------- @@ -333,7 +329,7 @@ def __setattr__(self, name: str, value: Any): self.__get_child(name).set_state(value) def __call__(self, *args, **kwds) -> Any: - """Get state of the current object + """Get state of the current object. Returns ------- @@ -343,7 +339,7 @@ def __call__(self, *args, **kwds) -> Any: return self.get_state() def get_attrib_value(self, attrib: str) -> Any: - """Get attribute value of the current object + """Get attribute value of the current object. Parameters ---------- @@ -378,15 +374,13 @@ def get_docstring(self): getDocstring = get_docstring def help(self): - """Prints command help string""" + """Prints command help string.""" print(self.get_docstring()) class PyNamedObjectContainer: - """ - Container class using StateEngine based DatamodelService as backend. - Use this class instead of directly calling DatamodelService's - method. + """Container class using StateEngine based DatamodelService as backend. Use + this class instead of directly calling DatamodelService's method. Methods ------- @@ -400,7 +394,6 @@ class PyNamedObjectContainer: Set state of the child object by name __delitem__(key) Deletes the child object by name - """ def __init__( @@ -443,7 +436,7 @@ def __get_child_object_display_names(self): return child_object_display_names def __len__(self) -> int: - """Returns count of child objects + """Returns count of child objects. Returns ------- @@ -453,7 +446,7 @@ def __len__(self) -> int: return len(self.__get_child_object_display_names()) def __iter__(self) -> Iterator[PyMenu]: - """Returns the next child object + """Returns the next child object. Yields ------- @@ -491,7 +484,7 @@ def __del_item(self, key: str): ) def __getitem__(self, key: str) -> PyMenu: - """Returns the child object by key + """Returns the child object by key. Parameters ---------- @@ -506,7 +499,7 @@ def __getitem__(self, key: str) -> PyMenu: return self.__get_item(key) def __setitem__(self, key: str, value: Any): - """Set state of the child object by name + """Set state of the child object by name. Parameters ---------- @@ -518,7 +511,7 @@ def __setitem__(self, key: str, value: Any): self.__get_item(key).set_state(value) def __delitem__(self, key: str): - """Deletes the child object by name + """Deletes the child object by name. Parameters ---------- @@ -529,10 +522,8 @@ def __delitem__(self, key: str): class PyCommand: - """ - Command class using StateEngine based DatamodelService as backend. - Use this class instead of directly calling DatamodelService's - method. + """Command class using StateEngine based DatamodelService as backend. Use + this class instead of directly calling DatamodelService's method. Methods ------- @@ -540,7 +531,6 @@ class PyCommand: Executes the command help() Prints command help string - """ docstring = None @@ -562,7 +552,7 @@ def __init__( @asynchronous def __call__(self, *args, **kwds) -> Any: - """Executes the command + """Executes the command. Returns ------- @@ -594,5 +584,5 @@ def get_docstring(self): getDocstring = get_docstring def help(self): - """Prints command help string""" + """Prints command help string.""" print(self.get_docstring()) diff --git a/ansys/fluent/core/services/datamodel_tui.py b/ansys/fluent/core/services/datamodel_tui.py index 04adcb71ae09..fe2fd29a6719 100644 --- a/ansys/fluent/core/services/datamodel_tui.py +++ b/ansys/fluent/core/services/datamodel_tui.py @@ -7,16 +7,16 @@ from ansys.api.fluent.v0 import datamodel_tui_pb2 as DataModelProtoModule from ansys.api.fluent.v0 import datamodel_tui_pb2_grpc as DataModelGrpcModule -from ansys.fluent.core.utils.async_execution import asynchronous from ansys.fluent.core.services.error_handler import catch_grpc_error from ansys.fluent.core.services.interceptors import TracingInterceptor +from ansys.fluent.core.utils.async_execution import asynchronous Path = List[Tuple[str, str]] class DatamodelService: - """ - Class wrapping the TUI-based datamodel grpc service of Fluent. + """Class wrapping the TUI-based datamodel grpc service of Fluent. + It is suggested to use the methods from PyMenu class. """ @@ -50,10 +50,8 @@ def execute_query(self, request): def _convert_value_to_gvalue(val, gval): - """ - Convert Python datatype to Value type of - google/protobuf/struct.proto - """ + """Convert Python datatype to Value type of + google/protobuf/struct.proto.""" if isinstance(val, bool): gval.bool_value = val elif isinstance(val, int) or isinstance(val, float): @@ -73,10 +71,8 @@ def _convert_value_to_gvalue(val, gval): def _convert_gvalue_to_value(gval): - """ - Convert Value type of google/protobuf/struct.proto to Python - datatype - """ + """Convert Value type of google/protobuf/struct.proto to Python + datatype.""" if gval.HasField("bool_value"): return gval.bool_value elif gval.HasField("number_value"): @@ -96,8 +92,7 @@ def _convert_gvalue_to_value(gval): class PyMenu: - """ - Pythonic wrapper of TUI-based DatamodelService class. Use this class + """Pythonic wrapper of TUI-based DatamodelService class. Use this class instead of directly calling DatamodelService's method. Methods @@ -125,7 +120,6 @@ class PyMenu: Create or set state of child object within contanier at menu del_item() Delete the child object at menu - """ def __init__(self, service: DatamodelService, path: Union[Path, str]): @@ -134,10 +128,8 @@ def __init__(self, service: DatamodelService, path: Union[Path, str]): path if isinstance(path, str) else convert_path_to_grpc_path(path) ) - def is_extended_tui( - self, include_unavailable: bool = False - ) -> bool: - """Check if menu is in extended TUI + def is_extended_tui(self, include_unavailable: bool = False) -> bool: + """Check if menu is in extended TUI. Parameters ---------- @@ -158,10 +150,8 @@ def is_extended_tui( response = self._service.get_attribute_value(request) return _convert_gvalue_to_value(response.value) - def is_container( - self, include_unavailable: bool = False - ) -> bool: - """Check if menu is a container + def is_container(self, include_unavailable: bool = False) -> bool: + """Check if menu is a container. Parameters ---------- @@ -183,10 +173,8 @@ def is_container( _convert_gvalue_to_value(response.value) == "NamedObjectContainer" ) - def get_child_names( - self, include_unavailable: bool = False - ) -> List[str]: - """Get child menu names + def get_child_names(self, include_unavailable: bool = False) -> List[str]: + """Get child menu names. Parameters ---------- @@ -207,7 +195,7 @@ def get_child_names( return _convert_gvalue_to_value(response.value) def get_state(self) -> Any: - """Get state of the object at menu + """Get state of the object at menu. Returns ------- @@ -220,7 +208,7 @@ def get_state(self) -> Any: return _convert_gvalue_to_value(response.state) def set_state(self, value: Any) -> None: - """Set state of the object at menu + """Set state of the object at menu. Parameters ---------- @@ -246,8 +234,7 @@ def _execute_query( return _convert_gvalue_to_value(ret.result) def execute(self, *args, **kwargs) -> Any: - """Execute command/query at path with positional or keyword - arguments + """Execute command/query at path with positional or keyword arguments. Parameters ---------- @@ -270,10 +257,8 @@ def execute(self, *args, **kwargs) -> Any: else: return self._execute_command(request) - def get_doc_string( - self, include_unavailable: bool = False - ) -> str: - """Get docstring for menu + def get_doc_string(self, include_unavailable: bool = False) -> str: + """Get docstring for menu. Parameters ---------- @@ -294,7 +279,7 @@ def get_doc_string( return _convert_gvalue_to_value(response.value) def rename(self, new_name: str) -> None: - """Rename the object at menu + """Rename the object at menu. Parameters ---------- @@ -308,7 +293,7 @@ def rename(self, new_name: str) -> None: self._service.set_state(request) def get_child_object_names(self) -> List[str]: - """Get child object names of the container at menu + """Get child object names of the container at menu. Returns ------- @@ -321,7 +306,7 @@ def get_child_object_names(self) -> List[str]: return _convert_gvalue_to_value(response.value) def set_item(self, name: str, value: Any) -> None: - """Create or set state of child object within contanier at menu + """Create or set state of child object within contanier at menu. Parameters ---------- @@ -336,15 +321,14 @@ def set_item(self, name: str, value: Any) -> None: self._service.set_state(request) def del_item(self) -> None: - """Delete the child object at path""" + """Delete the child object at path.""" request = DataModelProtoModule.SetStateRequest() request.path = self._path self._service.set_state(request) def convert_func_name_to_tui_menu(func_name: str) -> str: - """ - Convert Python function name to TUI menu string. + """Convert Python function name to TUI menu string. Parameters ---------- @@ -360,8 +344,7 @@ def convert_func_name_to_tui_menu(func_name: str) -> str: def convert_tui_menu_to_func_name(menu: str) -> str: - """ - Convert TUI menu string to Python function name. + """Convert TUI menu string to Python function name. Parameters ---------- @@ -379,9 +362,8 @@ def convert_tui_menu_to_func_name(menu: str) -> str: def convert_path_to_grpc_path(path: Path) -> str: - """ - Convert path structure to a string which can be passed to - datamodel grpc service + """Convert path structure to a string which can be passed to datamodel grpc + service. Parameters ---------- diff --git a/ansys/fluent/core/services/error_handler.py b/ansys/fluent/core/services/error_handler.py index 5d5b881361b6..a07b64331994 100644 --- a/ansys/fluent/core/services/error_handler.py +++ b/ansys/fluent/core/services/error_handler.py @@ -6,9 +6,7 @@ def catch_grpc_error(f): - """ - Decorator to catch gRPC errors - """ + """Decorator to catch gRPC errors.""" @functools.wraps(f) def func(*args, **kwargs): diff --git a/ansys/fluent/core/services/events.py b/ansys/fluent/core/services/events.py index 7875cff6a29c..cf607546b24c 100644 --- a/ansys/fluent/core/services/events.py +++ b/ansys/fluent/core/services/events.py @@ -7,23 +7,18 @@ class EventsService: - """ - Class wrapping the events grpc service of Fluent. - - """ + """Class wrapping the events grpc service of Fluent.""" def __init__(self, channel: grpc.Channel, metadata): self.__stub = EventsGrpcModule.EventsStub(channel) self.__metadata = metadata def begin_streaming(self): - """ - Begin events streaming from Fluent. + """Begin events streaming from Fluent. Yields ------ Event - """ request = EventsProtoModule.BeginStreamingRequest() self.__streams = self.__stub.BeginStreaming( diff --git a/ansys/fluent/core/services/field_data.py b/ansys/fluent/core/services/field_data.py index 9eb4766f7e61..efda9cff20a2 100644 --- a/ansys/fluent/core/services/field_data.py +++ b/ansys/fluent/core/services/field_data.py @@ -44,8 +44,7 @@ def get_fields(self, request): class FieldInfo: - """ - Provides access to Fluent field info. + """Provides access to Fluent field info. Methods ------- @@ -61,7 +60,6 @@ class FieldInfo: get_surfaces_info(self) -> dict Get surfaces information i.e. surface name, id and type. - """ def __init__(self, service: FieldDataService): @@ -119,8 +117,7 @@ def get_surfaces_info(self) -> dict: class FieldData: - """ - Provides access to Fluent field data on surfaces. + """Provides access to Fluent field data on surfaces. Methods ------- @@ -144,7 +141,6 @@ class FieldData: ) -> Dict[int, Dict]: Get vector field data i.e. surface data and associated scalar and vector field values. - """ # data mapping diff --git a/ansys/fluent/core/services/health_check.py b/ansys/fluent/core/services/health_check.py index bba75d7353d9..ee69851412e2 100644 --- a/ansys/fluent/core/services/health_check.py +++ b/ansys/fluent/core/services/health_check.py @@ -10,14 +10,12 @@ class HealthCheckService: - """ - Class wrapping the health check grpc service of Fluent. + """Class wrapping the health check grpc service of Fluent. Methods ------- check_health Check health of Fluent connection - """ class Status(Enum): @@ -32,8 +30,7 @@ def __init__(self, channel: grpc.Channel, metadata): @catch_grpc_error def check_health(self) -> str: - """ - Check health of Fluent connection + """Check health of Fluent connection. Returns ------- diff --git a/ansys/fluent/core/services/interceptors.py b/ansys/fluent/core/services/interceptors.py index 06b1317c2aa4..5fe91d232706 100644 --- a/ansys/fluent/core/services/interceptors.py +++ b/ansys/fluent/core/services/interceptors.py @@ -1,14 +1,14 @@ +"""Interceptor classes to use with gRPC services.""" -"""Interceptor classes to use with gRPC services""" - -import grpc from google.protobuf.json_format import MessageToDict +import grpc from ansys.fluent.core.utils.logging import LOG class TracingInterceptor(grpc.UnaryUnaryClientInterceptor): - """Interceptor class to trace gRPC calls""" + """Interceptor class to trace gRPC calls.""" + def _intercept_call( self, continuation, @@ -16,7 +16,7 @@ def _intercept_call( request, ): LOG.debug( - "GRPC_TRACE: rpc = %s, resquest = %s", + "GRPC_TRACE: rpc = %s, request = %s", client_call_details.method, MessageToDict(request), ) diff --git a/ansys/fluent/core/services/scheme_eval.py b/ansys/fluent/core/services/scheme_eval.py index aa1e77ae15b0..065334cc9d6e 100644 --- a/ansys/fluent/core/services/scheme_eval.py +++ b/ansys/fluent/core/services/scheme_eval.py @@ -1,5 +1,4 @@ -""" -Wrappers over SchemeEval grpc service of Fluent. +"""Wrappers over SchemeEval grpc service of Fluent. Example ------- @@ -18,7 +17,6 @@ 5 >>> session.scheme_eval.scheme_eval("(rpgetvar 'mom/relax)") 0.7 - """ from typing import Any, List, Sequence, Tuple @@ -31,9 +29,9 @@ class SchemeEvalService: - """ - Class wrapping the SchemeEval grpc service of Fluent. It is - suggested to use the methods from SchemeEval class. + """Class wrapping the SchemeEval grpc service of Fluent. + + It is suggested to use the methods from SchemeEval class. """ def __init__(self, channel: grpc.Channel, metadata): @@ -51,8 +49,7 @@ def string_eval(self, request): class Symbol: - """ - Class to represent symbol datatype in scheme + """Class to represent symbol datatype in scheme. Attributes ---------- @@ -78,7 +75,7 @@ def _convert_list_of_pairs_to_scheme_pointer( def _convert_py_value_to_scheme_pointer(val: Any, p: SchemePointer): - """Convert Python datatype to Scheme pointer""" + """Convert Python datatype to Scheme pointer.""" if isinstance(val, bool): p.b = val elif isinstance(val, int): @@ -130,7 +127,7 @@ def _convert_scheme_pointer_to_py_list(p: SchemePointer): def _convert_scheme_pointer_to_py_value(p: SchemePointer): - """Convert Scheme pointer to Python datatype""" + """Convert Scheme pointer to Python datatype.""" if p.HasField("b"): return p.b elif p.HasField("fixednum"): @@ -159,8 +156,7 @@ def _convert_scheme_pointer_to_py_value(p: SchemePointer): class SchemeEval: - """ - Class on which Fluent's scheme code can be executed + """Class on which Fluent's scheme code can be executed. Methods ------- @@ -180,8 +176,7 @@ def __init__(self, service: SchemeEvalService): self.service = service def eval(self, val: Any) -> Any: - """ - Evaluates a scheme expression + """Evaluates a scheme expression. Parameters ---------- @@ -201,8 +196,7 @@ def eval(self, val: Any) -> Any: def exec( self, commands: Sequence[str], wait: bool = True, silent: bool = True ) -> str: - """ - Executes a sequence of scheme commands + """Executes a sequence of scheme commands. Parameters ---------- @@ -227,8 +221,7 @@ def exec( return response.output def string_eval(self, input_: str) -> str: - """ - Evaluates a scheme expression in string format + """Evaluates a scheme expression in string format. Parameters ---------- @@ -246,8 +239,7 @@ def string_eval(self, input_: str) -> str: return response.output def scheme_eval(self, input_: str) -> Any: - """ - Evaluates a scheme expression in string format + """Evaluates a scheme expression in string format. Parameters ---------- @@ -264,7 +256,7 @@ def scheme_eval(self, input_: str) -> Any: val = ( S("eval"), (S("with-input-from-string"), input_, S("read")), - S("user-initial-environment") + S("user-initial-environment"), ) _convert_py_value_to_scheme_pointer(val, request) response = self.service.eval(request) diff --git a/ansys/fluent/core/services/settings.py b/ansys/fluent/core/services/settings.py index 2652711d0ff8..e70c9cf995f5 100644 --- a/ansys/fluent/core/services/settings.py +++ b/ansys/fluent/core/services/settings.py @@ -1,6 +1,4 @@ -""" -Wrapper to settings grpc service of Fluent -""" +"""Wrapper to settings grpc service of Fluent.""" from typing import Any, List import grpc @@ -60,9 +58,7 @@ def get_obj_static_info(self, request): @catch_grpc_error def get_static_info(self, request): - return self.__stub.GetStaticInfo( - request, metadata=self.__metadata - ) + return self.__stub.GetStaticInfo(request, metadata=self.__metadata) @catch_grpc_error def execute_cmd(self, request): @@ -72,9 +68,11 @@ def execute_cmd(self, request): def get_attrs(self, request): return self.__stub.GetAttrs(request, metadata=self.__metadata) + trace = False _indent = 0 + def _trace(fn): def _fn(self, *args, **kwds): global _indent @@ -101,9 +99,7 @@ def _get_request_instance_for_path(request_class, path): class SettingsService: - """ - Service for accessing and modifying Fluent settings - """ + """Service for accessing and modifying Fluent settings.""" def __init__(self, channel, metadata): self.__service_impl = _SettingsServiceImpl(channel, metadata) @@ -150,9 +146,7 @@ def _get_state_from_value(self, state): @_trace def set_var(self, path: str, value: Any): - """ - Set the value for the given path - """ + """Set the value for the given path.""" request = _get_request_instance_for_path( SettingsModule.SetVarRequest, path ) @@ -161,9 +155,7 @@ def set_var(self, path: str, value: Any): @_trace def get_var(self, path: str) -> Any: - """ - Get the value for the given path - """ + """Get the value for the given path.""" request = _get_request_instance_for_path( SettingsModule.GetVarRequest, path ) @@ -172,9 +164,7 @@ def get_var(self, path: str) -> Any: @_trace def rename(self, path: str, new: str, old: str): - """ - Rename the object at the given path - """ + """Rename the object at the given path.""" request = _get_request_instance_for_path( SettingsModule.RenameRequest, path ) @@ -185,9 +175,7 @@ def rename(self, path: str, new: str, old: str): @_trace def create(self, path: str, name: str): - """ - Create a new named object child for the given path - """ + """Create a new named object child for the given path.""" request = _get_request_instance_for_path( SettingsModule.CreateRequest, path ) @@ -197,9 +185,7 @@ def create(self, path: str, name: str): @_trace def delete(self, path: str, name: str): - """ - Delete the object with the given name at the give path - """ + """Delete the object with the given name at the give path.""" request = _get_request_instance_for_path( SettingsModule.DeleteRequest, path ) @@ -209,9 +195,7 @@ def delete(self, path: str, name: str): @_trace def get_object_names(self, path: str) -> List[int]: - """ - Get the list of named objects - """ + """Get the list of named objects.""" request = _get_request_instance_for_path( SettingsModule.GetObjectNamesRequest, path ) @@ -219,20 +203,15 @@ def get_object_names(self, path: str) -> List[int]: @_trace def get_list_size(self, path: str) -> int: - """ - Get the number of elements in a list object - """ + """Get the number of elements in a list object.""" request = _get_request_instance_for_path( - SettingsModule.GetListSizeRequest, - path) - return self.__stub.GetListSize(request, - metadata=self.__metadata).size + SettingsModule.GetListSizeRequest, path + ) + return self.__stub.GetListSize(request, metadata=self.__metadata).size @_trace def resize_list_object(self, path: str, size: int): - """ - Resize a list object - """ + """Resize a list object.""" request = _get_request_instance_for_path( SettingsModule.ResizeListObjectRequest, path ) @@ -311,9 +290,8 @@ def get_static_info(self): @_trace def execute_cmd(self, path: str, command: str, **kwds) -> Any: - """ - Execute a command of given name with the provided keyword arguments - """ + """Execute a command of given name with the provided keyword + arguments.""" request = _get_request_instance_for_path( SettingsModule.ExecuteCommandRequest, path ) @@ -350,10 +328,8 @@ def _parse_attrs(self, response): return ret @_trace - def get_attrs(self, path: str, attrs: List[str], recursive = False) -> Any: - """ - Return values of given attributes - """ + def get_attrs(self, path: str, attrs: List[str], recursive=False) -> Any: + """Return values of given attributes.""" request = _get_request_instance_for_path( SettingsModule.GetAttrsRequest, path ) @@ -361,6 +337,6 @@ def get_attrs(self, path: str, attrs: List[str], recursive = False) -> Any: request.recursive = recursive response = self.__service_impl.get_attrs(request) - if(recursive): + if recursive: return self._parse_attrs(response) return self._get_state_from_value(response.values) diff --git a/ansys/fluent/core/services/transcript.py b/ansys/fluent/core/services/transcript.py index 8c351d65d580..a3f60f409893 100644 --- a/ansys/fluent/core/services/transcript.py +++ b/ansys/fluent/core/services/transcript.py @@ -7,14 +7,12 @@ class TranscriptService: - """ - Class wrapping the transcript grpc service of Fluent. + """Class wrapping the transcript grpc service of Fluent. Methods ------- begin_streaming Begin transcript streaming from Fluent - """ def __init__(self, channel: grpc.Channel, metadata): @@ -23,8 +21,7 @@ def __init__(self, channel: grpc.Channel, metadata): self.__streams = None def begin_streaming(self): - """ - Begin transcript streaming from Fluent + """Begin transcript streaming from Fluent. Yields ------ diff --git a/ansys/fluent/core/session.py b/ansys/fluent/core/session.py index b86015cd8979..a808cee42f23 100644 --- a/ansys/fluent/core/session.py +++ b/ansys/fluent/core/session.py @@ -8,7 +8,6 @@ import grpc -from ansys.fluent.core.utils.logging import LOG from ansys.fluent.core.services.datamodel_se import ( DatamodelService as DatamodelService_SE, ) @@ -17,10 +16,11 @@ DatamodelService as DatamodelService_TUI, ) from ansys.fluent.core.services.datamodel_tui import PyMenu as PyMenu_TUI +from ansys.fluent.core.services.events import EventsService from ansys.fluent.core.services.field_data import ( - FieldInfo, FieldData, FieldDataService, + FieldInfo, ) from ansys.fluent.core.services.health_check import HealthCheckService from ansys.fluent.core.services.scheme_eval import ( @@ -29,9 +29,9 @@ ) from ansys.fluent.core.services.settings import SettingsService from ansys.fluent.core.services.transcript import TranscriptService -from ansys.fluent.core.solver.flobject import get_root as settings_get_root -from ansys.fluent.core.services.events import EventsService from ansys.fluent.core.solver.events_manager import EventsManager +from ansys.fluent.core.solver.flobject import get_root as settings_get_root +from ansys.fluent.core.utils.logging import LOG def _parse_server_info_file(filename: str): @@ -47,7 +47,7 @@ def _parse_server_info_file(filename: str): class MonitorThread(threading.Thread): """A class used for monitoring a Fluent session. - Deamon thread which will ensure cleanup of session objects, shutdown of + Daemon thread which will ensure cleanup of session objects, shutdown of non-deamon threads etc. Attributes @@ -68,8 +68,7 @@ def run(self): class Session: - """ - Encapsulates a Fluent connection. + """Encapsulates a Fluent connection. Attributes ---------- @@ -105,7 +104,6 @@ class Session: exit() Close the Fluent connection and exit Fluent. - """ _on_exit_cbs: List[Callable] = [] @@ -120,8 +118,7 @@ def __init__( channel: grpc.Channel = None, cleanup_on_exit: bool = True, ): - """ - Instantiate a Session. + """Instantiate a Session. Parameters ---------- @@ -216,8 +213,7 @@ def __init__( def create_from_server_info_file( cls, server_info_filepath: str, cleanup_on_exit: bool = True ) -> "Session": - """ - Create a Session instance from server-info file. + """Create a Session instance from server-info file. Parameters ---------- diff --git a/ansys/fluent/core/solver/events_manager.py b/ansys/fluent/core/solver/events_manager.py index 7d755a8e0df7..c30b0659e25b 100644 --- a/ansys/fluent/core/solver/events_manager.py +++ b/ansys/fluent/core/solver/events_manager.py @@ -1,15 +1,14 @@ """Module for events management.""" +from functools import partial import itertools import threading -from functools import partial from typing import Callable, List from ansys.api.fluent.v0 import events_pb2 as EventsProtoModule class EventsManager: - """ - Manages the server side events. + """Manages the server side events. Allows client to register/unregister callbacks with server events. @@ -65,8 +64,7 @@ def events_list(self) -> List[str]: def register_callback( self, event_name: str, call_back: Callable, *args, **kwargs ) -> str: - """ - Register Callback. + """Register Callback. Parameters ---------- @@ -85,7 +83,6 @@ def register_callback( ------- str Registered callback Id. - """ if not event_name in self.events_list: raise RuntimeError(f"{event_name} is not a valid event.") @@ -102,13 +99,12 @@ def register_callback( return id def unregister_callback(self, callback_id: str): - """ - Unregister Callback. + """Unregister Callback. Parameters ---------- callback_id : str - Registered callbak Id. + Registered callback Id. """ with self.__lock: for callbacks_map in self.__events_to_callbacks_map.values(): diff --git a/ansys/fluent/core/solver/flobject.py b/ansys/fluent/core/solver/flobject.py index 86e09a7190d0..1ef1661e2b6c 100644 --- a/ansys/fluent/core/solver/flobject.py +++ b/ansys/fluent/core/solver/flobject.py @@ -1,5 +1,4 @@ -""" -Module for accessing and modifying hierarchy of Fluent settings. +"""Module for accessing and modifying hierarchy of Fluent settings. The only useful method is 'get_root' which returns the root object for accessing Fluent settings. @@ -22,40 +21,53 @@ import pickle import string import sys +from typing import Dict, Generic, List, NewType, Tuple, TypeVar, Union import weakref -from typing import Union, List, Tuple, Dict, Generic, TypeVar, NewType + from ansys.fluent.core.utils.logging import LOG # Type hints -RealType = NewType('real', Union[float, str]) # constant or expression +RealType = NewType("real", Union[float, str]) # constant or expression RealListType = List[RealType] RealVectorType = Tuple[RealType, RealType, RealType] IntListType = List[int] StringListType = List[str] BoolListType = List[bool] -PrimitiveStateType = Union[str, RealType, int, bool, - RealListType, IntListType, StringListType, BoolListType] -DictStateType = Dict[str, 'StateType'] -ListStateType = List['StateType'] +PrimitiveStateType = Union[ + str, + RealType, + int, + bool, + RealListType, + IntListType, + StringListType, + BoolListType, +] +DictStateType = Dict[str, "StateType"] +ListStateType = List["StateType"] StateType = Union[PrimitiveStateType, DictStateType, ListStateType] -_ttable = str.maketrans(string.punctuation, '_'*len(string.punctuation), "?'") +_ttable = str.maketrans( + string.punctuation, "_" * len(string.punctuation), "?'" +) + def to_python_name(scheme_name: str) -> str: """Convert a scheme string to python variable name. - The function does this by replacing symbols with _. `?`s are ignored. + The function does this by replacing symbols with _. `?`s are + ignored. """ if not scheme_name: return scheme_name name = scheme_name.translate(_ttable) while name in keyword.kwlist: - name = name + '_' + name = name + "_" return name + class Base: - """ - Base class for settings and command objects. + """Base class for settings and command objects. Parameters ---------- @@ -69,12 +81,11 @@ class Base: flproxy obj_name scheme_name - """ _initialized = False - def __init__(self, name: str = None, parent = None): + def __init__(self, name: str = None, parent=None): self._parent = weakref.proxy(parent) if parent is not None else None if name is not None: self._name = name @@ -104,8 +115,8 @@ def flproxy(self): def obj_name(self) -> str: """Scheme name of this object. - By default, this returns the object's static name. If the object is a - named-object child, the object's name is returned. + By default, this returns the object's static name. If the object + is a named-object child, the object's name is returned. """ if self._name is None: return self.scheme_name @@ -122,24 +133,26 @@ def path(self) -> str: ppath = self._parent.path if not ppath: return self.obj_name - return ppath + '/' + self.obj_name + return ppath + "/" + self.obj_name def get_attrs(self, attrs) -> DictStateType: return self.flproxy.get_attrs(self.path, attrs) def get_attr(self, attr) -> StateType: attrs = self.get_attrs([attr]) - if attr != 'active?' and attrs.get('active?', True) is False: - raise RuntimeError('Object is not active') + if attr != "active?" and attrs.get("active?", True) is False: + raise RuntimeError("Object is not active") return attrs[attr] def is_active(self) -> bool: - return self.get_attr('active?') + return self.get_attr("active?") + + +StateT = TypeVar("StateT") + -StateT = TypeVar('StateT') class SettingsBase(Base, Generic[StateT]): - """ - Base class for settings objects. + """Base class for settings objects. Methods ------- @@ -181,84 +194,98 @@ def set_state(self, state: StateT): @staticmethod def _print_state_helper(state, out=sys.stdout, indent=0, indent_factor=2): if isinstance(state, dict): - out.write('\n') + out.write("\n") for key, value in state.items(): if value is not None: out.write(f'{indent*indent_factor*" "}{key} : ') - SettingsBase._print_state_helper(value, out, indent+1, - indent_factor) + SettingsBase._print_state_helper( + value, out, indent + 1, indent_factor + ) elif isinstance(state, list): - out.write('\n') + out.write("\n") for index, value in enumerate(state): out.write(f'{indent*indent_factor*" "}{index} : ') - SettingsBase._print_state_helper(value, out, indent+1, - indent_factor) + SettingsBase._print_state_helper( + value, out, indent + 1, indent_factor + ) else: - out.write(f'{state}\n') + out.write(f"{state}\n") def print_state(self, out=sys.stdout, indent_factor=2): """Print the state of this object.""" - self._print_state_helper(self.get_state(), out, - indent_factor=indent_factor) + self._print_state_helper( + self.get_state(), out, indent_factor=indent_factor + ) + class Integer(SettingsBase[int]): """An Integer object represents an integer value setting.""" _state_type = int + class Real(SettingsBase[RealType]): """A Real object represents a real value setting. - Some Real objects also accept string arguments representing expression - values. + Some Real objects also accept string arguments representing + expression values. """ _state_type = RealType + class String(SettingsBase[str]): """A String object represents a string value setting.""" _state_type = str + class Filename(SettingsBase[str]): """A Filename object represents a file name.""" _state_type = str + class Boolean(SettingsBase[bool]): """A Boolean object represents a boolean value setting.""" _state_type = bool + class RealList(SettingsBase[RealListType]): """A RealList object represents a real list setting.""" _state_type = RealListType + class IntegerList(SettingsBase[IntListType]): """An Integer object represents a integer list setting.""" _state_type = IntListType + class RealVector(SettingsBase[RealVectorType]): """An object to represent a 3D vector. - A RealVector object represents a real vector setting consisting of - 3 real values. + A RealVector object represents a real vector setting consisting of 3 + real values. """ _state_type = RealVectorType + class StringList(SettingsBase[StringListType]): """A StringList object represents a string list setting.""" _state_type = StringListType + class BooleanList(SettingsBase[BoolListType]): """A BooleanList object represents a boolean list setting.""" _state_type = BoolListType + class Group(SettingsBase[DictStateType]): """A Group container object. @@ -275,7 +302,7 @@ class Group(SettingsBase[DictStateType]): _state_type = DictStateType - def __init__(self, name: str = None, parent = None): + def __init__(self, name: str = None, parent=None): super().__init__(name, parent) for child in self.child_names: cls = getattr(self.__class__, child) @@ -335,17 +362,18 @@ def get_active_command_names(self): return ret def __getattribute__(self, name): - if name in super().__getattribute__('child_names'): + if name in super().__getattribute__("child_names"): if not self.is_active(): raise RuntimeError(f"'{self.path}' is currently not active") return super().__getattribute__(name) def __setattr__(self, name: str, value): - if not self._initialized or name[0] == '_': + if not self._initialized or name[0] == "_": super().__setattr__(name, value) else: getattr(self, name).set_state(value) + class NamedObject(SettingsBase[DictStateType]): """A NamedObject container. @@ -360,7 +388,7 @@ class NamedObject(SettingsBase[DictStateType]): # New objects could get inserted by other operations, so we cannot assume # that the local cache in self._objects is always up-to-date - def __init__(self, name: str = None, parent = None): + def __init__(self, name: str = None, parent=None): super().__init__(name, parent) self._objects = {} for cmd in self.command_names: @@ -393,7 +421,7 @@ def to_python_keys(cls, value): def _create_child_object(self, cname: str): ret = self._objects.get(cname) if not ret: - #pylint: disable=no-member + # pylint: disable=no-member cls = self.__class__.child_object_type ret = self._objects[cname] = cls(cname, self) return ret @@ -408,8 +436,7 @@ def _update_objects(self): self._create_child_object(name) def rename(self, new: str, old: str): - """ - Rename a named object. + """Rename a named object. Parameters: ---------- @@ -488,6 +515,7 @@ def __setitem__(self, name: str, value): child = self._create_child_object(name) child.set_state(value) + class ListObject(SettingsBase[ListStateType]): """A ListObject container. @@ -510,7 +538,7 @@ class ListObject(SettingsBase[ListStateType]): # New objects could get inserted by other operations, so we cannot assume # that the local cache in self._objects is always up-to-date - def __init__(self, name = None, parent = None): + def __init__(self, name=None, parent=None): super().__init__(name, parent) self._objects = [] for cmd in self.command_names: @@ -548,8 +576,7 @@ def __iter__(self): return iter(self._objects) def get_size(self) -> int: - """ - Return the number of elements in a list object. + """Return the number of elements in a list object. Returns ------- @@ -558,8 +585,7 @@ def get_size(self) -> int: return self.flproxy.get_list_size(self.path) def resize(self, size: int): - """ - Resize the list object. + """Resize the list object. Parameters ---------- @@ -580,9 +606,11 @@ def __setitem__(self, index: int, value): child = self[index] child.set_state(value) + class Map(SettingsBase[DictStateType]): """A Map object represents key-value settings.""" + class Command(Base): """Command object.""" @@ -595,113 +623,123 @@ def __call__(self, **kwds): newkwds[ccls.scheme_name] = ccls.to_scheme_keys(v) else: raise RuntimeError("Argument '" + str(k) + "' is invalid") - return self.flproxy.execute_cmd(self._parent.path, - self.obj_name, - **newkwds) + return self.flproxy.execute_cmd( + self._parent.path, self.obj_name, **newkwds + ) + _baseTypes = { - 'group' : Group, - 'integer' : Integer, - 'real' : Real, - 'string/symbol': String, - 'string' : String, - 'boolean' : Boolean, - 'real-list' : RealList, - 'integer-list' : IntegerList, - 'string-list' : StringList, - 'boolean-list' : BooleanList, - 'named-object' : NamedObject, - 'vector' : RealVector, - 'command' : Command, - 'material-property' : String, - 'thread-var' : String, - 'list-object' : ListObject, - 'file' : Filename, - 'map' : Map - } - -def get_cls(name, info, parent = None): + "group": Group, + "integer": Integer, + "real": Real, + "string/symbol": String, + "string": String, + "boolean": Boolean, + "real-list": RealList, + "integer-list": IntegerList, + "string-list": StringList, + "boolean-list": BooleanList, + "named-object": NamedObject, + "vector": RealVector, + "command": Command, + "material-property": String, + "thread-var": String, + "list-object": ListObject, + "file": Filename, + "map": Map, +} + + +def get_cls(name, info, parent=None): """Create a class for the object identified by "path".""" try: - if name == '': - pname = 'root' + if name == "": + pname = "root" else: pname = to_python_name(name) - obj_type = info['type'] + obj_type = info["type"] base = _baseTypes.get(obj_type) if base is None: - LOG.error(f"Unable to find base class for '{name}' " - f"(type = '{obj_type}'). " - f"Falling back to String.") + LOG.error( + f"Unable to find base class for '{name}' " + f"(type = '{obj_type}'). " + f"Falling back to String." + ) base = String - dct = { 'scheme_name' : name } - helpinfo = info.get('help') + dct = {"scheme_name": name} + helpinfo = info.get("help") if helpinfo: - dct['__doc__'] = helpinfo + dct["__doc__"] = helpinfo else: if parent is None: - dct['__doc__'] = 'root object' + dct["__doc__"] = "root object" else: - if obj_type == 'command': - dct['__doc__'] = \ - f"'{pname}' command of '{parent.__name__}' object" + if obj_type == "command": + dct[ + "__doc__" + ] = f"'{pname}' command of '{parent.__name__}' object" else: - dct['__doc__'] = \ - f"'{pname}' child of '{parent.__name__}' object" + dct[ + "__doc__" + ] = f"'{pname}' child of '{parent.__name__}' object" cls = type(pname, (base,), dct) - children = info.get('children') + children = info.get("children") if children: cls.child_names = [] for cname, cinfo in children.items(): ccls = get_cls(cname, cinfo, cls) - #pylint: disable=no-member + # pylint: disable=no-member cls.child_names.append(ccls.__name__) setattr(cls, ccls.__name__, ccls) - commands = info.get('commands') + commands = info.get("commands") if commands: cls.command_names = [] for cname, cinfo in commands.items(): ccls = get_cls(cname, cinfo, cls) - #pylint: disable=no-member + # pylint: disable=no-member cls.command_names.append(ccls.__name__) setattr(cls, ccls.__name__, ccls) - arguments = info.get('arguments') + arguments = info.get("arguments") if arguments: doc = cls.__doc__ - doc += '\n\n' - doc += 'Parameters\n' - doc += '----------\n' + doc += "\n\n" + doc += "Parameters\n" + doc += "----------\n" cls.argument_names = [] for aname, ainfo in arguments.items(): ccls = get_cls(aname, ainfo, cls) th = ccls._state_type - th = th.__name__ if hasattr(th, '__name__') else str(th) - doc += f' {ccls.__name__} : {th}\n' - doc += f' {ccls.__doc__}\n' - #pylint: disable=no-member + th = th.__name__ if hasattr(th, "__name__") else str(th) + doc += f" {ccls.__name__} : {th}\n" + doc += f" {ccls.__doc__}\n" + # pylint: disable=no-member cls.argument_names.append(ccls.__name__) setattr(cls, ccls.__name__, ccls) cls.__doc__ = doc - object_type = info.get('object-type') + object_type = info.get("object-type") if object_type: - cls.child_object_type = \ - get_cls('child-object-type', object_type, cls) + cls.child_object_type = get_cls( + "child-object-type", object_type, cls + ) except Exception: - print (f"Unable to construct class for '{name}' of " - f"'{parent.scheme_name if parent else None}'") + print( + f"Unable to construct class for '{name}' of " + f"'{parent.scheme_name if parent else None}'" + ) raise return cls + def _gethash(obj_info): dhash = hashlib.sha256() dhash.update(pickle.dumps(obj_info)) return dhash.hexdigest() + def get_root(flproxy) -> Group: - """ - Get the root settings object. + """Get the root settings object. Parameters ---------- @@ -715,14 +753,17 @@ def get_root(flproxy) -> Group: obj_info = flproxy.get_static_info() try: from ansys.fluent.core.solver import settings + if settings.SHASH != _gethash(obj_info): - LOG.warning("Mismatch between generated file and server object " - "info. Dynamically created settings classes will " - "be used.") + LOG.warning( + "Mismatch between generated file and server object " + "info. Dynamically created settings classes will " + "be used." + ) raise RuntimeError("Mismatch in hash values") cls = settings.root except Exception: - cls = get_cls('', obj_info) - #pylint: disable=no-member + cls = get_cls("", obj_info) + # pylint: disable=no-member cls.set_flproxy(flproxy) return cls() diff --git a/ansys/fluent/core/utils/async_execution.py b/ansys/fluent/core/utils/async_execution.py index 84a2b84b6564..b945eb369b56 100644 --- a/ansys/fluent/core/utils/async_execution.py +++ b/ansys/fluent/core/utils/async_execution.py @@ -1,11 +1,12 @@ """Module providing asynchronous execution functionality.""" -import functools from concurrent.futures import ThreadPoolExecutor +import functools def asynchronous(f): """Use for decorating functions to execute asynchronously.""" + @functools.wraps(f) def func(*args, **kwargs): return ThreadPoolExecutor(max_workers=1).submit(f, *args, **kwargs) diff --git a/ansys/fluent/core/utils/dump_session_data.py b/ansys/fluent/core/utils/dump_session_data.py index b23b4d31a9ea..e180b0ae13e9 100644 --- a/ansys/fluent/core/utils/dump_session_data.py +++ b/ansys/fluent/core/utils/dump_session_data.py @@ -5,8 +5,7 @@ def dump_session_data( session, file_path: str, fields: list = [], surfaces: list = [] ): - """ - Dump session data. + """Dump session data. Parameters ---------- diff --git a/ansys/fluent/core/utils/generic.py b/ansys/fluent/core/utils/generic.py index b7cb1c06613d..8f92b5786fd5 100644 --- a/ansys/fluent/core/utils/generic.py +++ b/ansys/fluent/core/utils/generic.py @@ -1,9 +1,9 @@ """Module providing generic functionality.""" -import asyncio -import time from abc import ABCMeta +import asyncio from functools import partial +import time loop = asyncio.get_event_loop() diff --git a/ansys/fluent/core/utils/logging.py b/ansys/fluent/core/utils/logging.py index 6a7cfb86d94f..051afe2c341e 100644 --- a/ansys/fluent/core/utils/logging.py +++ b/ansys/fluent/core/utils/logging.py @@ -1,18 +1,16 @@ -""" -Logging module. +"""Logging module. This module supplies a general framework for logging in PyFluent. """ import logging import os -import tempfile from pathlib import Path +import tempfile class Logger: - """ - Logger class. + """Logger class. Methods ------- @@ -48,8 +46,7 @@ def __init__(self, level=logging.ERROR): self.log = self.logger.log def set_level(self, level): - """ - Set logging level. + """Set logging level. Parameters ---------- @@ -80,8 +77,7 @@ def disable_logging_to_stdout(self): self.logger.removeHandler(self.stream_handler) def enable_logging_to_file(self, filepath=None): - """ - Enable logging to file. + """Enable logging to file. Parameters ---------- diff --git a/ansys/fluent/parametric/__init__.py b/ansys/fluent/parametric/__init__.py index c2e4ea0a9735..05032479a876 100644 --- a/ansys/fluent/parametric/__init__.py +++ b/ansys/fluent/parametric/__init__.py @@ -1,5 +1,4 @@ -""" -Classes for running a parametric study in Fluent. +"""Classes for running a parametric study in Fluent. Example ------- @@ -54,11 +53,10 @@ >>> session1.studies['elbow_params_2-Solve'].design_points['Base DP'].input_parameters # noqa: E501 >>> study2 = session1.new_study() >>> session2 = ParametricSession(project_filepath="nozzle_para_named.flprj") - """ -import tempfile from pathlib import Path +import tempfile from typing import Dict, List import ansys.fluent.core as pyfluent @@ -68,8 +66,7 @@ class DesignPoint: - """ - Design point in a parametric study. + """Design point in a parametric study. Attributes ---------- @@ -83,7 +80,6 @@ class DesignPoint: Whether to write data for the design point. capture_simulation_report_data_enabled : bool Whether to capture simulation report data for the design point. - """ def __init__(self, name: str, dp_settings): @@ -182,7 +178,6 @@ class ParametricStudy: Update all design points. update_selected_design_points(design_points) Update a list of design points. - """ _all_studies: Dict[int, "ParametricStudy"] = {} @@ -199,8 +194,7 @@ def __init__(self, parametric_studies, name=None, design_points=None): @classmethod def get_all_studies(cls) -> Dict[str, "ParametricStudy"]: - """ - Get all currently active studies. + """Get all currently active studies. Returns ------- @@ -241,8 +235,7 @@ def initialize(self): LOG.error("initialize is not available") def rename(self, new_name: str) -> None: - """ - Rename the parametric study. + """Rename the parametric study. Parameters ---------- @@ -270,8 +263,7 @@ def set_as_current(self) -> None: ParametricStudy.current_study_name = self.name def duplicate(self, copy_design_points: bool = True) -> "ParametricStudy": - """ - Duplicate the current study. + """Duplicate the current study. Parameters ---------- @@ -329,8 +321,7 @@ def use_base_data(self) -> None: self.__parametric_studies.use_base_data() def import_design_table(self, filepath: str) -> None: - """ - Import the design table for the parametric study. + """Import the design table for the parametric study. Parameters ---------- @@ -340,8 +331,7 @@ def import_design_table(self, filepath: str) -> None: self.__parametric_studies.import_design_table(filepath=filepath) def export_design_table(self, filepath: str) -> None: - """ - Export the design table for the parametric study. + """Export the design table for the parametric study. Parameters ---------- @@ -354,8 +344,8 @@ def export_design_table(self, filepath: str) -> None: def current_design_point(self) -> DesignPoint: """Return the current design point. - Current design point within the design points under the parametric - study. + Current design point within the design points under the + parametric study. """ dp_name = self.__parametric_studies[self.name].current_design_point() return self.design_points[dp_name] @@ -365,8 +355,7 @@ def add_design_point( write_data: bool = False, capture_simulation_report_data: bool = True, ) -> DesignPoint: - """ - Add a new design point under the parametric study. + """Add a new design point under the parametric study. Parameters ---------- @@ -399,8 +388,7 @@ def add_design_point( return design_point def delete_design_points(self, design_points: List[DesignPoint]) -> None: - """ - Delete a list of design points. + """Delete a list of design points. Parameters ---------- @@ -422,8 +410,7 @@ def delete_design_points(self, design_points: List[DesignPoint]) -> None: del design_point def duplicate_design_point(self, design_point: DesignPoint) -> DesignPoint: - """ - Duplicate the design point. + """Duplicate the design point. Parameters ---------- @@ -448,8 +435,7 @@ def duplicate_design_point(self, design_point: DesignPoint) -> DesignPoint: return new_dp def save_journals(self, separate_journals: bool) -> None: - """ - Save journals. + """Save journals. Parameters ---------- @@ -460,8 +446,7 @@ def save_journals(self, separate_journals: bool) -> None: dp_settings.save_journals(separate_journals=separate_journals) def clear_generated_data(self, design_points: List[DesignPoint]) -> None: - """ - Clear generated data for a list of design points. + """Clear generated data for a list of design points. Parameters ---------- @@ -491,8 +476,7 @@ def update_all_design_points(self) -> None: def update_selected_design_points( self, design_points: List[DesignPoint] ) -> None: - """ - Update a list of design points. + """Update a list of design points. Parameters ---------- @@ -506,8 +490,7 @@ def update_selected_design_points( class ParametricProject: - """ - Parametric project workflow. + """Parametric project workflow. Attributes ---------- @@ -526,7 +509,6 @@ class ParametricProject: Save project as a copy. archive(archive_name) Archive project. - """ def __init__( @@ -545,8 +527,7 @@ def __init__( def open( self, project_filepath: str = "default.flprj", load_case: bool = True ) -> None: - """ - Open a project. + """Open a project. Parameters ---------- @@ -557,7 +538,7 @@ def open( """ self.__parametric_project.open( project_filename=str(Path(project_filepath).resolve()), - load_case=load_case + load_case=load_case, ) self.project_filepath = project_filepath for study_name in self.__parametric_studies.get_object_names(): @@ -573,8 +554,7 @@ def save(self) -> None: self.__parametric_project.save() def save_as(self, project_filepath: str) -> None: - """ - Save as project. + """Save as project. Parameters ---------- @@ -586,8 +566,7 @@ def save_as(self, project_filepath: str) -> None: def export( self, project_filepath: str, convert_to_managed: bool = False ) -> None: - """ - Save project as a copy. + """Save project as a copy. Parameters ---------- @@ -602,8 +581,7 @@ def export( ) def archive(self, archive_path: str = None) -> None: - """ - Archive project. + """Archive project. Parameters ---------- @@ -618,14 +596,12 @@ def archive(self, archive_path: str = None) -> None: class ParametricSessionLauncher: - """ - Launches fluent for parametric sessions. + """Launches fluent for parametric sessions. Methods ------- __call__(*args, **kwargs) Launch a session. - """ def __init__(self, *args, **kwargs): @@ -637,8 +613,7 @@ def __call__(self): class ParametricSession: - """ - ParametricSession class which encapsulates studies and project. + """ParametricSession class which encapsulates studies and project. Attributes ---------- @@ -666,10 +641,9 @@ def __init__( case_filepath: str = None, project_filepath: str = None, launcher=ParametricSessionLauncher(), - start_transcript: bool = False + start_transcript: bool = False, ): - """ - Instantiate a ParametricSession. + """Instantiate a ParametricSession. Parameters ---------- @@ -699,7 +673,7 @@ def __init__( parametric_project=self.__root.file.parametric_project, parametric_studies=self.__root.parametric_studies, project_filepath=str(study.project_filepath), - open_project=False + open_project=False, ) elif project_filepath is not None: self.project = ParametricProject( @@ -721,8 +695,7 @@ def __init__( ) def new_study(self) -> ParametricStudy: - """ - Create new study. + """Create new study. Returns ------- @@ -734,8 +707,7 @@ def new_study(self) -> ParametricStudy: return study def delete_study(self, study_name: str) -> None: - """ - Delete study. + """Delete study. Parameters ---------- @@ -750,8 +722,7 @@ def delete_study(self, study_name: str) -> None: self.studies.pop(study_name) def rename_study(self, new_name: str, old_name: str) -> None: - """ - Rename study. + """Rename study. Parameters ---------- diff --git a/ansys/fluent/post/__init__.py b/ansys/fluent/post/__init__.py index 1c416234ae48..600b0f4f13fc 100644 --- a/ansys/fluent/post/__init__.py +++ b/ansys/fluent/post/__init__.py @@ -1,9 +1,10 @@ """Python post processing integrations for the Fluent solver.""" -import pkg_resources import platform import struct import sys +import pkg_resources + required_libraries = { "vtk": "9.1.0", "pyvista": "0.33.2", diff --git a/ansys/fluent/post/_config.py b/ansys/fluent/post/_config.py index cbef3608fc7c..c6fc3472faf1 100644 --- a/ansys/fluent/post/_config.py +++ b/ansys/fluent/post/_config.py @@ -14,8 +14,7 @@ def _get_threadlocal_config(): def get_config() -> dict: - """ - Retrieve post configuration. + """Retrieve post configuration. Returns ------- @@ -26,8 +25,7 @@ def get_config() -> dict: def set_config(blocking: bool = False): - """ - Set post configuration. + """Set post configuration. Parameters ---------- diff --git a/ansys/fluent/post/matplotlib/__init__.py b/ansys/fluent/post/matplotlib/__init__.py index 3a7876666924..4bedcf553079 100644 --- a/ansys/fluent/post/matplotlib/__init__.py +++ b/ansys/fluent/post/matplotlib/__init__.py @@ -1,5 +1,6 @@ """A package that provides interfacing Fluent with Matplotlib.""" -from ansys.fluent.post.matplotlib.\ - matplot_windows_manager import matplot_windows_manager # noqa: F401 from ansys.fluent.post.matplotlib.matplot_objects import Plots # noqa: F401 +from ansys.fluent.post.matplotlib.matplot_windows_manager import ( # noqa: F401 + matplot_windows_manager, +) diff --git a/ansys/fluent/post/matplotlib/matplot_objects.py b/ansys/fluent/post/matplotlib/matplot_objects.py index dcfc2d65ee18..658933089629 100644 --- a/ansys/fluent/post/matplotlib/matplot_objects.py +++ b/ansys/fluent/post/matplotlib/matplot_objects.py @@ -14,8 +14,7 @@ class Plots: _sessions_state = {} def __init__(self, session, local_surfaces_provider=None): - """ - Instantiate Plots, container of plot objects. + """Instantiate Plots, container of plot objects. Parameters ---------- @@ -53,14 +52,12 @@ class XYPlot(XYPlotDefn): """XY Plot.""" def plot(self, window_id: Optional[str] = None): - """ - Draw XYPlot. + """Draw XYPlot. Parameters ---------- window_id : str, optional Window id. If not specified unique id is used. - """ self._pre_display() matplot_windows_manager.plot(self, window_id) diff --git a/ansys/fluent/post/matplotlib/matplot_windows_manager.py b/ansys/fluent/post/matplotlib/matplot_windows_manager.py index b4772067053f..89725c8b138a 100644 --- a/ansys/fluent/post/matplotlib/matplot_windows_manager.py +++ b/ansys/fluent/post/matplotlib/matplot_windows_manager.py @@ -68,8 +68,7 @@ class MatplotWindow(PostWindow): """Class for MatplotWindow.""" def __init__(self, id: str, post_object: Union[GraphicsDefn, PlotDefn]): - """ - Instantiate a MatplotWindow. + """Instantiate a MatplotWindow. Parameters ---------- @@ -175,8 +174,7 @@ def __init__(self): self._post_windows: Dict[str, MatplotWindow] = {} def open_window(self, window_id: Optional[str] = None) -> str: - """ - Open new window. + """Open new window. Parameters ---------- @@ -196,8 +194,7 @@ def open_window(self, window_id: Optional[str] = None) -> str: def set_object_for_window( self, object: Union[PlotDefn, GraphicsDefn], window_id: str ) -> None: - """ - Associate post object with running window instance. + """Associate post object with running window instance. Parameters ---------- @@ -223,8 +220,7 @@ def plot( object: Union[PlotDefn, GraphicsDefn], window_id: Optional[str] = None, ) -> None: - """ - Draw plot. + """Draw plot. Parameters ---------- @@ -252,8 +248,7 @@ def save_graphic( window_id: str, format: str, ) -> None: - """ - Save graphics. + """Save graphics. Parameters ---------- @@ -277,8 +272,7 @@ def refresh_windows( session_id: Optional[str] = "", windows_id: Optional[List[str]] = [], ) -> None: - """ - Refresh windows. + """Refresh windows. Parameters ---------- @@ -303,8 +297,7 @@ def animate_windows( session_id: Optional[str] = "", windows_id: Optional[List[str]] = [], ) -> None: - """ - Animate windows. + """Animate windows. Parameters ---------- @@ -329,8 +322,7 @@ def close_windows( session_id: Optional[str] = "", windows_id: Optional[List[str]] = [], ) -> None: - """ - Close windows. + """Close windows. Parameters ---------- diff --git a/ansys/fluent/post/matplotlib/plotter_defns.py b/ansys/fluent/post/matplotlib/plotter_defns.py index 80173336da6e..3bab3c5d8d81 100644 --- a/ansys/fluent/post/matplotlib/plotter_defns.py +++ b/ansys/fluent/post/matplotlib/plotter_defns.py @@ -1,8 +1,9 @@ """Module providing matplotlib plotter functionality.""" -import numpy as np -from typing import Optional, List +from typing import List, Optional + import matplotlib.pyplot as plt +import numpy as np class Plotter: @@ -17,8 +18,7 @@ def __init__( ylabel: Optional[str] = "", remote_process: Optional[bool] = False, ): - """ - Instantiate a matplotlib plotter. + """Instantiate a matplotlib plotter. Parameters ---------- @@ -56,8 +56,7 @@ def __init__( self.ax = self.fig.add_subplot(111) def plot(self, data: dict) -> None: - """ - Draw plot in window. + """Draw plot in window. Parameters ---------- @@ -113,8 +112,7 @@ def is_closed(self): return self._closed def save_graphic(self, file_name: str): - """ - Save graphics. + """Save graphics. Parameters ---------- @@ -124,8 +122,7 @@ def save_graphic(self, file_name: str): plt.savefig(file_name) def set_properties(self, properties: dict): - """ - Set plot properties. + """Set plot properties. Parameters ---------- @@ -166,10 +163,9 @@ def _reset(self): class ProcessPlotter(Plotter): - """ - Class for matplotlib process plotter. + """Class for matplotlib process plotter. - Opens matplotlib window in a seprate process. + Opens matplotlib window in a separate process. """ def __init__( @@ -180,8 +176,7 @@ def __init__( xlabel="position", ylabel="", ): - """ - Instantiate a matplotlib process plotter. + """Instantiate a matplotlib process plotter. Parameters ---------- diff --git a/ansys/fluent/post/post_object_defns.py b/ansys/fluent/post/post_object_defns.py index 781115167d2a..306a5b81629b 100644 --- a/ansys/fluent/post/post_object_defns.py +++ b/ansys/fluent/post/post_object_defns.py @@ -49,8 +49,7 @@ class GraphicsDefn( @abstractmethod def display(self, plotter_id: Optional[str] = None): - """ - Display graphics. + """Display graphics. Parameters ---------- @@ -65,14 +64,12 @@ class PlotDefn(BasePostObjectDefn, metaclass=PyLocalNamedObjectMetaAbstract): @abstractmethod def plot(self, plotter_id: Optional[str] = None): - """ - Draw plot. + """Draw plot. Parameters ---------- window_id : str, optional Window id. If not specified unique id is used. - """ pass diff --git a/ansys/fluent/post/post_windows_manager.py b/ansys/fluent/post/post_windows_manager.py index aff61aedade4..e51ca8d6e2a9 100644 --- a/ansys/fluent/post/post_windows_manager.py +++ b/ansys/fluent/post/post_windows_manager.py @@ -1,10 +1,10 @@ -""" -Module providing PostWindow and PostWindowManager abstract classes. +"""Module providing PostWindow and PostWindowManager abstract classes. -PostWindowManager is containter for PostWindow. +PostWindowManager is container for PostWindow. """ -from abc import abstractmethod, ABCMeta +from abc import ABCMeta, abstractmethod from typing import List, Optional, Union + from ansys.fluent.post.post_object_defns import GraphicsDefn, PlotDefn @@ -22,8 +22,7 @@ class PostWindowsManager(metaclass=ABCMeta): @abstractmethod def open_window(self, window_id: Optional[str] = None) -> str: - """ - Open new window. + """Open new window. Parameters ---------- @@ -41,8 +40,7 @@ def open_window(self, window_id: Optional[str] = None) -> str: def set_object_for_window( self, object: Union[GraphicsDefn, PlotDefn], window_id: str ) -> None: - """ - Associate post object with running window instance. + """Associate post object with running window instance. Parameters ---------- @@ -65,8 +63,7 @@ def plot( object: Union[GraphicsDefn, PlotDefn], window_id: Optional[str] = None, ) -> None: - """ - Draw plot. + """Draw plot. Parameters ---------- @@ -89,8 +86,7 @@ def save_graphic( window_id: str, format: str, ) -> None: - """ - Save graphics. + """Save graphics. Parameters ---------- @@ -112,8 +108,7 @@ def refresh_windows( session_id: Optional[str] = "", windows_id: Optional[List[str]] = [], ) -> None: - """ - Refresh windows. + """Refresh windows. Parameters ---------- @@ -134,8 +129,7 @@ def animate_windows( session_id: Optional[str] = "", windows_id: Optional[List[str]] = [], ) -> None: - """ - Animate windows. + """Animate windows. Parameters ---------- @@ -161,8 +155,7 @@ def close_windows( session_id: Optional[str] = "", windows_id: Optional[List[str]] = [], ) -> None: - """ - Close windows. + """Close windows. Parameters ---------- diff --git a/ansys/fluent/post/pyvista/__init__.py b/ansys/fluent/post/pyvista/__init__.py index 6ed1de06aaf6..242f86c83740 100644 --- a/ansys/fluent/post/pyvista/__init__.py +++ b/ansys/fluent/post/pyvista/__init__.py @@ -1,6 +1,6 @@ """A package that provides interfacing Fluent with PyVista.""" +from ansys.fluent.post.pyvista.pyvista_objects import Graphics # noqa: F401 from ansys.fluent.post.pyvista.pyvista_windows_manager import ( # noqa: F401 pyvista_windows_manager, ) -from ansys.fluent.post.pyvista.pyvista_objects import Graphics # noqa: F401 diff --git a/ansys/fluent/post/pyvista/pyvista_objects.py b/ansys/fluent/post/pyvista/pyvista_objects.py index c540151784b0..d86f888ba1af 100644 --- a/ansys/fluent/post/pyvista/pyvista_objects.py +++ b/ansys/fluent/post/pyvista/pyvista_objects.py @@ -22,8 +22,7 @@ class Graphics: _sessions_state = {} def __init__(self, session, local_surfaces_provider=None): - """ - Instantiate Graphics, containter of graphics objects. + """Instantiate Graphics, container of graphics objects. Parameters ---------- @@ -65,8 +64,7 @@ class Mesh(MeshDefn): """Mesh graphics.""" def display(self, window_id: Optional[str] = None): - """ - Display mesh graphics. + """Display mesh graphics. Parameters ---------- @@ -82,8 +80,7 @@ class Surface(SurfaceDefn): """Surface graphics.""" def display(self, window_id: Optional[str] = None): - """ - Display surface graphics. + """Display surface graphics. Parameters ---------- @@ -97,8 +94,7 @@ class Contour(ContourDefn): """Contour graphics.""" def display(self, window_id: Optional[str] = None): - """ - Display contour graphics. + """Display contour graphics. Parameters ---------- @@ -114,8 +110,7 @@ class Vector(VectorDefn): """Vector graphics.""" def display(self, window_id: Optional[str] = None): - """ - Display vector graphics. + """Display vector graphics. Parameters ---------- diff --git a/ansys/fluent/post/pyvista/pyvista_windows_manager.py b/ansys/fluent/post/pyvista/pyvista_windows_manager.py index ad9fcf9a4f32..90a12637b1f3 100644 --- a/ansys/fluent/post/pyvista/pyvista_windows_manager.py +++ b/ansys/fluent/post/pyvista/pyvista_windows_manager.py @@ -4,8 +4,8 @@ from typing import List, Optional, Union import numpy as np -from pyvistaqt import BackgroundPlotter import pyvista as pv +from pyvistaqt import BackgroundPlotter from ansys.fluent.core.session import Session from ansys.fluent.core.utils.generic import AbstractSingletonMeta, in_notebook @@ -21,8 +21,7 @@ class PyVistaWindow(PostWindow): """Class for PyVista window.""" def __init__(self, id: str, post_object: Union[GraphicsDefn, PlotDefn]): - """ - Instantiate a PyVistaWindow. + """Instantiate a PyVistaWindow. Parameters ---------- @@ -403,8 +402,7 @@ def __init__(self): self._app = None def open_window(self, window_id: Optional[str] = None) -> str: - """ - Open new window. + """Open new window. Parameters ---------- @@ -428,8 +426,7 @@ def open_window(self, window_id: Optional[str] = None) -> str: def set_object_for_window( self, object: Union[GraphicsDefn, PlotDefn], window_id: str ) -> None: - """ - Associate post object with running window instance. + """Associate post object with running window instance. Parameters ---------- @@ -456,8 +453,7 @@ def plot( object: Union[GraphicsDefn, PlotDefn], window_id: Optional[str] = None, ) -> None: - """ - Draw plot. + """Draw plot. Parameters ---------- @@ -487,8 +483,7 @@ def save_graphic( window_id: str, format: str, ) -> None: - """ - Save graphics. + """Save graphics. Parameters ---------- @@ -512,8 +507,7 @@ def refresh_windows( session_id: Optional[str] = "", windows_id: Optional[List[str]] = [], ) -> None: - """ - Refresh windows. + """Refresh windows. Parameters ---------- @@ -539,8 +533,7 @@ def animate_windows( session_id: Optional[str] = "", windows_id: Optional[List[str]] = [], ) -> None: - """ - Animate windows. + """Animate windows. Parameters ---------- @@ -571,8 +564,7 @@ def close_windows( session_id: Optional[str] = "", windows_id: Optional[List[str]] = [], ) -> None: - """ - Close windows. + """Close windows. Parameters ---------- diff --git a/codegen/pyprotogen.py b/codegen/pyprotogen.py index 0511f9da4373..285c5c4eff45 100644 --- a/codegen/pyprotogen.py +++ b/codegen/pyprotogen.py @@ -1,19 +1,17 @@ -""" -Builds *.py source interface files from *.protos files. +"""Builds *.py source interface files from *.protos files. Usage ----- `python codegen/pyprotogen.py` - """ import glob import os +from pathlib import Path import re import shutil import sys -from pathlib import Path _THIS_DIRNAME = os.path.dirname(__file__) _PROTOS_PATH = os.path.abspath( @@ -28,8 +26,8 @@ def build_python_grpc(protos_path=_PROTOS_PATH, out_path=_PY_OUT_PATH): """Build the Python gRPC interface files. - Given a path containing the .proto files this function builds the .py - source interface files. + Given a path containing the .proto files this function builds the + .py source interface files. """ # verify proto tools are installed try: diff --git a/codegen/settingsgen.py b/codegen/settingsgen.py index 10d97900f016..98d1e4c8b671 100644 --- a/codegen/settingsgen.py +++ b/codegen/settingsgen.py @@ -1,5 +1,4 @@ -""" -Provide a module to generate the Fluent settings tree. +"""Provide a module to generate the Fluent settings tree. Running this module generates a python module with the definition of the Fluent settings classes. The out is placed at: @@ -19,72 +18,90 @@ import pickle import pprint from typing import IO + from ansys.fluent.core.solver import flobject + def _gethash(obj_info): dhash = hashlib.sha256() dhash.update(pickle.dumps(obj_info)) return dhash.hexdigest() + def _get_indent_str(indent): return f"{' '*indent*4}" -def _write_cls_helper(out, cls, indent = 0): + +def _write_cls_helper(out, cls, indent=0): try: istr = _get_indent_str(indent) - istr1 = _get_indent_str(indent+1) - istr2 = _get_indent_str(indent+2) - out.write('\n') - out.write(f'{istr}class {cls.__name__}' - f'({", ".join(c.__name__ for c in cls.__bases__)}):\n') - - doc = ('\n' + istr1).join(cls.__doc__.split('\n')) + istr1 = _get_indent_str(indent + 1) + istr2 = _get_indent_str(indent + 2) + out.write("\n") + out.write( + f"{istr}class {cls.__name__}" + f'({", ".join(c.__name__ for c in cls.__bases__)}):\n' + ) + + doc = ("\n" + istr1).join(cls.__doc__.split("\n")) out.write(f'{istr1}"""\n') - out.write(f'{istr1}{doc}') + out.write(f"{istr1}{doc}") out.write(f'\n{istr1}"""\n') out.write(f'{istr1}scheme_name = "{cls.scheme_name}"\n') - child_names = getattr(cls, 'child_names', None) + child_names = getattr(cls, "child_names", None) if child_names: - out.write(f'{istr1}child_names = \\\n') + out.write(f"{istr1}child_names = \\\n") strout = io.StringIO() - pprint.pprint(child_names, stream=strout, compact=True, - width=80-indent*4-10) - mn = ('\n' + istr2).join(strout.getvalue().strip().split('\n')) - out.write(f'{istr2}{mn}\n') + pprint.pprint( + child_names, + stream=strout, + compact=True, + width=80 - indent * 4 - 10, + ) + mn = ("\n" + istr2).join(strout.getvalue().strip().split("\n")) + out.write(f"{istr2}{mn}\n") for child in child_names: - _write_cls_helper(out, getattr(cls, child), indent+1) + _write_cls_helper(out, getattr(cls, child), indent + 1) - command_names = getattr(cls, 'command_names', None) + command_names = getattr(cls, "command_names", None) if command_names: - out.write(f'{istr1}command_names = \\\n') + out.write(f"{istr1}command_names = \\\n") strout = io.StringIO() - pprint.pprint(command_names, stream=strout, compact=True, - width=80-indent*4-10) - mn = ('\n' + istr2).join(strout.getvalue().strip().split('\n')) - out.write(f'{istr2}{mn}\n') + pprint.pprint( + command_names, + stream=strout, + compact=True, + width=80 - indent * 4 - 10, + ) + mn = ("\n" + istr2).join(strout.getvalue().strip().split("\n")) + out.write(f"{istr2}{mn}\n") for command in command_names: - _write_cls_helper(out, getattr(cls, command), indent+1) + _write_cls_helper(out, getattr(cls, command), indent + 1) - arguments = getattr(cls, 'argument_names', None) + arguments = getattr(cls, "argument_names", None) if arguments: - out.write(f'{istr1}argument_names = \\\n') + out.write(f"{istr1}argument_names = \\\n") strout = io.StringIO() - pprint.pprint(arguments, stream=strout, compact=True, - width=80-indent*4-10) - mn = ('\n' + istr2).join(strout.getvalue().strip().split('\n')) - out.write(f'{istr2}{mn}\n') + pprint.pprint( + arguments, + stream=strout, + compact=True, + width=80 - indent * 4 - 10, + ) + mn = ("\n" + istr2).join(strout.getvalue().strip().split("\n")) + out.write(f"{istr2}{mn}\n") for argument in arguments: - _write_cls_helper(out, getattr(cls, argument), indent+1) - child_object_type = getattr(cls, 'child_object_type', None) + _write_cls_helper(out, getattr(cls, argument), indent + 1) + child_object_type = getattr(cls, "child_object_type", None) if child_object_type: - _write_cls_helper(out, child_object_type, indent+1) + _write_cls_helper(out, child_object_type, indent + 1) except Exception: raise + def write_settings_classes(out: IO, cls, obj_info): - """ - Write the settings classes in 'out' stream. + """Write the settings classes in 'out' stream. Parameters ---------- @@ -93,24 +110,26 @@ def write_settings_classes(out: IO, cls, obj_info): Object that interfaces with the Fluent backend """ hash = _gethash(obj_info) - out.write('#\n') - out.write('# This is an auto-generated file. DO NOT EDIT!\n') - out.write('#\n') + out.write("#\n") + out.write("# This is an auto-generated file. DO NOT EDIT!\n") + out.write("#\n") out.write("\n") - out.write('from ansys.fluent.core.solver.flobject import *\n\n') + out.write("from ansys.fluent.core.solver.flobject import *\n\n") out.write(f'SHASH = "{hash}"\n') _write_cls_helper(out, cls) -if __name__ == '__main__': + +if __name__ == "__main__": from ansys.fluent.core.launcher.launcher import launch_fluent dirname = os.path.dirname(__file__) filepath = os.path.normpath( - os.path.join(dirname, "..", "ansys", "fluent", "core", - "solver", "settings.py") - ) + os.path.join( + dirname, "..", "ansys", "fluent", "core", "solver", "settings.py" + ) + ) session = launch_fluent() sinfo = session.get_settings_service().get_static_info() - cls = flobject.get_cls('', sinfo); - with open(filepath, 'w') as f: + cls = flobject.get_cls("", sinfo) + with open(filepath, "w") as f: write_settings_classes(f, cls, sinfo) diff --git a/codegen/tuigen.py b/codegen/tuigen.py index c3f9c6914887..c5978a0ae7cb 100644 --- a/codegen/tuigen.py +++ b/codegen/tuigen.py @@ -1,5 +1,4 @@ -""" -Provide a module to generate explicit Fluent TUI menu classes. +"""Provide a module to generate explicit Fluent TUI menu classes. This module starts up Fluent and calls the underlying gRPC APIs to generate the following TUI Python modules: @@ -11,25 +10,29 @@ ----- `python codegen/tuigen.py` - """ import os from pathlib import Path +from ansys.fluent.core.launcher.launcher import launch_fluent from ansys.fluent.core.services.datamodel_tui import ( PyMenu, convert_path_to_grpc_path, convert_tui_menu_to_func_name, ) -from ansys.fluent.core.launcher.launcher import launch_fluent _THIS_DIRNAME = os.path.dirname(__file__) -_MESHING_TUI_FILE = os.path.normpath(os.path.join( - _THIS_DIRNAME, "..", "ansys", "fluent", "core", "meshing", "tui.py") +_MESHING_TUI_FILE = os.path.normpath( + os.path.join( + _THIS_DIRNAME, "..", "ansys", "fluent", "core", "meshing", "tui.py" + ) +) +_SOLVER_TUI_FILE = os.path.normpath( + os.path.join( + _THIS_DIRNAME, "..", "ansys", "fluent", "core", "solver", "tui.py" + ) ) -_SOLVER_TUI_FILE = os.path.normpath(os.path.join( - _THIS_DIRNAME, "..", "ansys", "fluent", "core", "solver", "tui.py")) _INDENT_STEP = 4 @@ -75,7 +78,7 @@ def __init__( self, meshing_tui_file=_MESHING_TUI_FILE, solver_tui_file=_SOLVER_TUI_FILE, - meshing=False + meshing=False, ): self._tui_file = meshing_tui_file if meshing else solver_tui_file if Path(self._tui_file).exists(): @@ -153,7 +156,7 @@ def generate(self): if self._tui_file == _SOLVER_TUI_FILE: self._write_code_to_tui_file( '"""Fluent Solver TUI Commands"""\n' - ) + ) else: self._write_code_to_tui_file( '"""Fluent Meshing TUI Commands"""\n' @@ -170,6 +173,7 @@ def generate(self): ) self._write_menu_to_tui_file(self._main_menu) + if __name__ == "__main__": TUIGenerator(meshing=True).generate() TUIGenerator(meshing=False).generate() diff --git a/codegen/write_settings_yaml.py b/codegen/write_settings_yaml.py index a1ea941dcebd..72eb0c842c92 100644 --- a/codegen/write_settings_yaml.py +++ b/codegen/write_settings_yaml.py @@ -1,40 +1,43 @@ -""" -Utility to write YAML file for the current settings hierarchy. +"""Utility to write YAML file for the current settings hierarchy. Usage: write_settings_yaml.py [outfile] """ import sys + import ansys.fluent as pyfluent from ansys.fluent.core.services import settings indent_factor = 2 -def write_yaml(out, obj, indent = 0): - type = obj['type'] + + +def write_yaml(out, obj, indent=0): + type = obj["type"] out.write(f"{' '*indent*indent_factor}type: {type}\n") - for ctype in ['children', 'commands', 'arguments']: + for ctype in ["children", "commands", "arguments"]: children = obj.get(ctype) if children: out.write(f"{' '*indent*indent_factor}{ctype}:\n") for child, cobj in children.items(): out.write(f"{' '*(indent+1)*indent_factor}{child}:\n") write_yaml(out, cobj, indent + 2) - cobj = obj.get('object-type') + cobj = obj.get("object-type") if cobj: out.write(f"{' '*indent*indent_factor}child-object-type:\n") write_yaml(out, cobj, indent + 1) - help_ = obj.get('help') + help_ = obj.get("help") if help_: out.write(f"{' '*indent*indent_factor}help: {help_}\n") -if '__main__' == __name__: + +if "__main__" == __name__: if len(sys.argv) > 2: - print ("Usage: write_settings_yaml.py [outfile]") + print("Usage: write_settings_yaml.py [outfile]") else: session = pyfluent.launch_fluent() settings = session.get_settings_service().get_obj_static_info() if len(sys.argv) == 2: - with open(sys.argv[1], 'w') as f: + with open(sys.argv[1], "w") as f: write_yaml(f, settings) elif len(sys.argv) == 1: write_yaml(sys.stdout, settings) diff --git a/doc/source/api/post/index.rst b/doc/source/api/post/index.rst index e8ecb11032bf..cbfd3bc8f682 100644 --- a/doc/source/api/post/index.rst +++ b/doc/source/api/post/index.rst @@ -78,7 +78,7 @@ environment and PyVista is used to visualze the extracted data. mesh1.display() surface1.display() - # To display in specifc window e.g. window-2 + # To display in specific window e.g. window-2 contour1.display("window-2") MatplotLib Example (XYPlots) @@ -116,4 +116,4 @@ environment and data is plotted in MatplotLib. :maxdepth: 2 :hidden: - pyvista_objects \ No newline at end of file + pyvista_objects diff --git a/doc/source/conf.py b/doc/source/conf.py index 21b07d10f6dd..94c90a985ec6 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -32,7 +32,7 @@ "sphinx_autodoc_typehints", "sphinx_copybutton", "sphinx_gallery.gen_gallery", - 'sphinxemoji.sphinxemoji', + "sphinxemoji.sphinxemoji", ] # Intersphinx mapping @@ -109,12 +109,16 @@ def _start_or_stop_fluent_container(gallery_conf, fname, when): start_instance = bool(int(os.getenv("PYFLUENT_START_INSTANCE", "1"))) if not start_instance: if when == "before": - if fname in ["mixing_elbow_settings_api.py", - "mixing_elbow_tui_api.py"]: + if fname in [ + "mixing_elbow_settings_api.py", + "mixing_elbow_tui_api.py", + ]: args = ["3ddp", "-t4", "-meshing"] - elif fname in ["parametric_static_mixer_1.py", - "parametric_static_mixer_2.py", - "parametric_static_mixer_3.py"]: + elif fname in [ + "parametric_static_mixer_1.py", + "parametric_static_mixer_2.py", + "parametric_static_mixer_3.py", + ]: args = ["3ddp", "-t4"] subprocess.run([sys.executable, _START_FLUENT_FILE] + args) elif when == "after": @@ -124,7 +128,7 @@ def _start_or_stop_fluent_container(gallery_conf, fname, when): # -- Sphinx Gallery Options --------------------------------------------------- sphinx_gallery_conf = { # convert rst to md for ipynb - #"pypandoc": True, + # "pypandoc": True, # path to your examples scripts "examples_dirs": ["../../examples/"], # path where to save gallery generated examples @@ -141,8 +145,8 @@ def _start_or_stop_fluent_container(gallery_conf, fname, when): "doc_module": "ansys-fluent-core", "ignore_pattern": "flycheck*", "thumbnail_size": (350, 350), - 'reset_modules_order': 'both', - 'reset_modules': (_start_or_stop_fluent_container), + "reset_modules_order": "both", + "reset_modules": (_start_or_stop_fluent_container), } @@ -187,8 +191,13 @@ def _start_or_stop_fluent_container(gallery_conf, fname, when): # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - (master_doc, "ansys.fluent.core", - "ansys.fluent.core Documentation", [author], 1) + ( + master_doc, + "ansys.fluent.core", + "ansys.fluent.core Documentation", + [author], + 1, + ) ] diff --git a/doc/source/contributing.rst b/doc/source/contributing.rst index 377cec7baa62..2271127d8f0a 100644 --- a/doc/source/contributing.rst +++ b/doc/source/contributing.rst @@ -35,7 +35,7 @@ directory of the repository: cd doc make html -After the build completes the html documentaion is located in the +After the build completes the html documentation is located in the ``_builds/html`` directory and you can load the ``index.html`` into a web browser. To clean the documentation you can execute this command: @@ -51,7 +51,24 @@ submit questions, report bugs, and request new features. Code Style ---------- -PyFluent follows PEP8 standard as outlined in the `PyAnsys Development Guide -`_ and implements style checking using `flake8 -`_. +PyFluent is compliant with `PyAnsys Development Code Style Guide +`_. Code style is checked +by making use of `pre-commit `_. Install this tool and +activate it executing the following commands: +.. code:: bash + + python -m pip install pre-commit + pre-commit install + +Then, you can use the ``style`` rule defined in the ``Makefile``: + +.. code:: bash + + make style + +Or directly execute `pre-commit `_: + +.. code:: bash + + pre-commit run --all-files --show-diff-on-failure diff --git a/doc/validate_png.py b/doc/validate_png.py index b09c8e9ae215..820ecce23860 100644 --- a/doc/validate_png.py +++ b/doc/validate_png.py @@ -1,18 +1,18 @@ -"""Validate the PNG images in the build/latex/ directory +"""Validate the PNG images in the build/latex/ directory. Removes invalid PNGs (probably GIF) - """ -import os from glob import glob +import os + from PIL import Image this_path = os.path.dirname(os.path.abspath(__file__)) -check_path = os.path.join(this_path, 'build', 'latex') +check_path = os.path.join(this_path, "build", "latex") if not os.path.isdir(check_path): raise FileNotFoundError(f"Invalid path {check_path}") for filename in glob(os.path.join(check_path, "*.png")): im = Image.open(filename) im.save(filename, format="png") - im.close() #reload is necessary in my case + im.close() # reload is necessary in my case diff --git a/examples/00-fluent/mixing_elbow_settings_api.py b/examples/00-fluent/mixing_elbow_settings_api.py index 121f134a7a55..6355e01d0240 100644 --- a/examples/00-fluent/mixing_elbow_settings_api.py +++ b/examples/00-fluent/mixing_elbow_settings_api.py @@ -1,5 +1,4 @@ -""" -.. _ref_mixing_elbow_settings_api: +""".. _ref_mixing_elbow_settings_api: Fluid Flow and Heat Transfer in a Mixing Elbow ---------------------------------------------- @@ -15,7 +14,7 @@ - Use the Watertight Geometry guided workflow to: - Import a CAD geometry - Generate a surface mesh - - Decribe the geometry + - Describe the geometry - Generate a volume mesh - Launch Ansys Fluent. - Read an existing mesh file into Ansys Fluent. @@ -33,7 +32,6 @@ the elbow. The pipe dimensions are in inches and the fluid properties and boundary conditions are given in SI units. The Reynolds number for the flow at the larger inlet is 50, 800, so a turbulent flow model will be required. - """ @@ -45,7 +43,6 @@ import ansys.fluent.core as pyfluent from ansys.fluent.core import examples - import_filename = examples.download_file( "mixing_elbow.pmdb", "pyfluent/mixing_elbow" ) @@ -523,7 +520,7 @@ # "0", # "z=0_outlet", # "()", -#).result() +# ).result() ############################################################################### diff --git a/examples/00-fluent/mixing_elbow_tui_api.py b/examples/00-fluent/mixing_elbow_tui_api.py index 6a615b55ce91..bf82867925da 100644 --- a/examples/00-fluent/mixing_elbow_tui_api.py +++ b/examples/00-fluent/mixing_elbow_tui_api.py @@ -1,5 +1,4 @@ -""" -.. _ref_mixing_elbow_tui_api: +""".. _ref_mixing_elbow_tui_api: Fluid Flow and Heat Transfer in a Mixing Elbow ---------------------------------------------- @@ -15,7 +14,7 @@ - Use the Watertight Geometry guided workflow to: - Import a CAD geometry - Generate a surface mesh - - Decribe the geometry + - Describe the geometry - Generate a volume mesh - Launch Ansys Fluent. - Read an existing mesh file into Ansys Fluent. @@ -33,7 +32,6 @@ the elbow. The pipe dimensions are in inches and the fluid properties and boundary conditions are given in SI units. The Reynolds number for the flow at the larger inlet is 50, 800, so a turbulent flow model will be required. - """ ############################################################################### @@ -44,7 +42,6 @@ import ansys.fluent.core as pyfluent from ansys.fluent.core import examples - import_filename = examples.download_file( "mixing_elbow.pmdb", "pyfluent/mixing_elbow" ) diff --git a/examples/01-parametric/parametric_static_mixer_1.py b/examples/01-parametric/parametric_static_mixer_1.py index af7c9e5fd06e..f56a9745852e 100755 --- a/examples/01-parametric/parametric_static_mixer_1.py +++ b/examples/01-parametric/parametric_static_mixer_1.py @@ -1,5 +1,4 @@ -""" -.. _ref_parametric_static_mixer_1: +""".. _ref_parametric_static_mixer_1: Parametric Study Workflow ------------------------------ @@ -15,17 +14,16 @@ - Accesses output parameters of the base DP - Creates, updates, and deletes more DPs - Creates, renames, and deletes parametric studies - """ -############################################################################ -# Import the pyfluent module -import ansys.fluent.core as pyfluent - ############################################################################ # Import the path module from pathlib import Path +############################################################################ +# Import the pyfluent module +import ansys.fluent.core as pyfluent + ############################################################################ # Launch Fluent in 3D and double precision diff --git a/examples/01-parametric/parametric_static_mixer_2.py b/examples/01-parametric/parametric_static_mixer_2.py index 9a42c4e60c80..416f761aa7b1 100755 --- a/examples/01-parametric/parametric_static_mixer_2.py +++ b/examples/01-parametric/parametric_static_mixer_2.py @@ -1,5 +1,4 @@ -""" -.. _ref_parametric_static_mixer_2: +""".. _ref_parametric_static_mixer_2: Parametric Project-Based Workflow ---------------------------------------------------- @@ -13,8 +12,6 @@ - Exports the current project - Archives the current project - Exits the parametric project-based workflow - - """ ######################################################################### @@ -23,13 +20,14 @@ ######################################################################### # Import the parametric project module and the parametric study module +from pathlib import Path + +import ansys.fluent.core as pyfluent from ansys.fluent.parametric import ParametricProject ############################################################################ # Import the pyfluent module and path -import ansys.fluent.core as pyfluent -from pathlib import Path ######################################################################### # Launch Fluent and enable the settings API (Beta) diff --git a/examples/01-parametric/parametric_static_mixer_3.py b/examples/01-parametric/parametric_static_mixer_3.py index 7bc3f9cce5c3..419d3a2175c2 100755 --- a/examples/01-parametric/parametric_static_mixer_3.py +++ b/examples/01-parametric/parametric_static_mixer_3.py @@ -1,5 +1,4 @@ -""" -.. _ref_parametric_static_mixer_3: +""".. _ref_parametric_static_mixer_3: Parametric Session Workflow ---------------------------------------------- @@ -11,21 +10,20 @@ - Creates a new study in a parametric session - Renames this newly created study - Creates a new parametric session using the flprj saved earlier - - """ ######################################################################### # Parametric session workflow # Import the parametric session workflow +from pathlib import Path + +import ansys.fluent.core as pyfluent from ansys.fluent.parametric import ParametricSession ############################################################################ # Import the pyfluent module and path -import ansys.fluent.core as pyfluent -from pathlib import Path ######################################################################### # Launch parametric session using the hopper/mixer case File diff --git a/requirements_style.txt b/requirements_style.txt deleted file mode 100644 index 8843f5f5fe72..000000000000 --- a/requirements_style.txt +++ /dev/null @@ -1,2 +0,0 @@ -flake8==4.0.1 -pep8-naming==0.12.1 \ No newline at end of file diff --git a/setup.py b/setup.py index f9b76c501eaf..a6fa2373d600 100644 --- a/setup.py +++ b/setup.py @@ -1,4 +1,4 @@ -"""Setup file for ansys-fluent-solver""" +"""Setup file for ansys-fluent-solver.""" import os from setuptools import find_namespace_packages, setup @@ -17,7 +17,7 @@ "grpcio>=1.30.0", "numpy>=1.21.5", "protobuf>=3.12.2", - "appdirs>=1.4.0" + "appdirs>=1.4.0", ] install_requires_post = [ diff --git a/tests/test_flobject.py b/tests/test_flobject.py index cd0f1315efcb..0a2d0465285e 100644 --- a/tests/test_flobject.py +++ b/tests/test_flobject.py @@ -1,43 +1,44 @@ """ Unit tests for flobject module """ +# import codegen.settingsgen +from collections.abc import MutableMapping import io -import pytest import weakref + +import pytest + from ansys.fluent.core.solver import flobject -#import codegen.settingsgen -from collections.abc import MutableMapping + class Setting: """Base class for setting objects""" + def __init__(self, parent): self.parent = None if parent is None else weakref.proxy(parent) def get_attr(self, attr): attrs = self.get_attrs([attr]) - if attrs.get('active?'): + if attrs.get("active?"): return attrs[attr] else: raise RuntimeError("Object is not active") def get_attrs(self, attrs): - active = self.attrs.get('active?', lambda self: True)(self) + active = self.attrs.get("active?", lambda self: True)(self) if active: - return { - attr : self.attrs[attr](self) - for attr in attrs - } + return {attr: self.attrs[attr](self) for attr in attrs} else: - return { - 'active?' : False - } + return {"active?": False} attrs = { - 'active?' : lambda self: True, - } + "active?": lambda self: True, + } + class PrimitiveSetting(Setting): """Primitive setting objects""" + value = None def get_state(self): @@ -48,51 +49,60 @@ def set_state(self, value): @classmethod def get_static_info(cls): - ret = { 'type' : cls.objtype } + ret = {"type": cls.objtype} if cls.__doc__: - ret['help'] = cls.__doc__ + ret["help"] = cls.__doc__ return ret + class Bool(PrimitiveSetting): - objtype = 'boolean' + objtype = "boolean" + class Int(PrimitiveSetting): - objtype = 'integer' + objtype = "integer" + class Real(PrimitiveSetting): - objtype = 'real' + objtype = "real" + class String(PrimitiveSetting): - objtype = 'string/symbol' + objtype = "string/symbol" + class BoolList(PrimitiveSetting): - objtype = 'boolean-list' + objtype = "boolean-list" + class IntList(PrimitiveSetting): - objtype = 'integer-list' + objtype = "integer-list" + class RealList(PrimitiveSetting): - objtype = 'real-list' + objtype = "real-list" + class StringList(PrimitiveSetting): - objtype = 'string-list' + objtype = "string-list" + class Group(Setting): """Group objects""" - objtype = 'group' + objtype = "group" children = {} commands = {} def __init__(self, parent): super().__init__(parent) - self.objs = { c : v(self) for c, v in self.children.items() } + self.objs = {c: v(self) for c, v in self.children.items()} def get_state(self): ret = {} for c in self.children: cobj = self.objs[c] - if cobj.get_attr('active?'): + if cobj.get_attr("active?"): ret[c] = cobj.get_state() return ret @@ -110,25 +120,24 @@ def get_command(self, c): @classmethod def get_static_info(cls): - ret = { 'type' : cls.objtype } + ret = {"type": cls.objtype} if cls.__doc__: - ret['help'] = cls.__doc__ + ret["help"] = cls.__doc__ if cls.children: - ret['children'] = { - c: v.get_static_info() - for c, v in cls.children.items() - } + ret["children"] = { + c: v.get_static_info() for c, v in cls.children.items() + } if cls.commands: - ret['commands'] = { - c: v.get_static_info() - for c, v in cls.commands.items() - } + ret["commands"] = { + c: v.get_static_info() for c, v in cls.commands.items() + } return ret + class NamedObject(Setting, MutableMapping): """NamedObject class""" - objtype = 'named-object' + objtype = "named-object" commands = {} # To be overridden by child classes # child_object_type = None @@ -159,9 +168,8 @@ def get_child(self, c): def rename(self, new, old): self._objs = { - (new if k == old else k) : v - for k, v in self._objs.items() - } + (new if k == old else k): v for k, v in self._objs.items() + } def get_object_names(self): return list(self._objs.keys()) @@ -170,7 +178,7 @@ def get_command(self, c): return self.commands[c](self) def get_state(self): - return { c : v.get_state() for c, v in self._objs.items() } + return {c: v.get_state() for c, v in self._objs.items()} def set_state(self, state): for k, v in state.items(): @@ -178,22 +186,21 @@ def set_state(self, state): @classmethod def get_static_info(cls): - ret = { 'type' : cls.objtype } + ret = {"type": cls.objtype} if cls.__doc__: - ret['help'] = cls.__doc__ - ret['object-type'] = cls.child_object_type.get_static_info() + ret["help"] = cls.__doc__ + ret["object-type"] = cls.child_object_type.get_static_info() if cls.commands: - ret['commands'] = { - c: v.get_static_info() - for c, v in cls.commands.items() - } + ret["commands"] = { + c: v.get_static_info() for c, v in cls.commands.items() + } return ret class ListObject(Setting): """ListObject class""" - objtype = 'list-object' + objtype = "list-object" commands = {} # To be overridden by child classes # child_object_type = None @@ -232,7 +239,7 @@ def get_command(self, c): return self.commands[c](self) def get_state(self): - return [ x.get_state() for x in self._objs ] + return [x.get_state() for x in self._objs] def set_state(self, value): self.resize(len(value)) @@ -241,21 +248,21 @@ def set_state(self, value): @classmethod def get_static_info(cls): - ret = { 'type' : cls.objtype } + ret = {"type": cls.objtype} if cls.__doc__: - ret['help'] = cls.__doc__ - ret['object-type'] = cls.child_object_type.get_static_info() + ret["help"] = cls.__doc__ + ret["object-type"] = cls.child_object_type.get_static_info() if cls.commands: - ret['commands'] = { - c: v.get_static_info() - for c, v in cls.commands.items() - } + ret["commands"] = { + c: v.get_static_info() for c, v in cls.commands.items() + } return ret + class Command(Setting): """Command class""" - objtype = 'command' + objtype = "command" # To be overridden by child classes # arguments = None # cb = None @@ -269,51 +276,56 @@ def __call__(self, **kwds): @classmethod def get_static_info(cls): - ret = { 'type' : cls.objtype } + ret = {"type": cls.objtype} if cls.__doc__: - ret['help'] = cls.__doc__ + ret["help"] = cls.__doc__ if cls.arguments: - ret['arguments'] = { - c: v.get_static_info() - for c, v in cls.arguments.items() - } + ret["arguments"] = { + c: v.get_static_info() for c, v in cls.arguments.items() + } return ret + class Root(Group): """Root class""" + class G1(Group): class S1(String): attrs = { - 'active?' : - lambda self: not self.parent.objs['b-3'].get_state(), - 'allowed-values' : lambda self: ["foo", "bar"], - } + "active?": lambda self: not self.parent.objs[ + "b-3" + ].get_state(), + "allowed-values": lambda self: ["foo", "bar"], + } + children = { - 'r-1' : Real, - 'i-2' : Int, - 'b-3' : Bool, - 's-4' : S1, - } + "r-1": Real, + "i-2": Int, + "b-3": Bool, + "s-4": S1, + } class N1(NamedObject): class NC(Group): children = { - 'rl-1' : RealList, - 'sl-1' : StringList, - } + "rl-1": RealList, + "sl-1": StringList, + } child_object_type = NC class L1(ListObject): class LC(Group): children = { - 'il-1' : IntList, - 'bl-1' : BoolList, - } + "il-1": IntList, + "bl-1": BoolList, + } + child_object_type = LC class Command1(Command): """Command1 class""" + class A1(Real): value = 2.3 @@ -321,25 +333,26 @@ class A2(Bool): value = True arguments = { - 'a-1' : A1, - 'a-2' : A2, - } + "a-1": A1, + "a-2": A2, + } def cb(self, a1, a2): if a2 is True: - self.parent.objs['g-1'].objs['r-1'].value += a1 + self.parent.objs["g-1"].objs["r-1"].value += a1 else: - self.parent.objs['g-1'].objs['r-1'].value -= a1 + self.parent.objs["g-1"].objs["r-1"].value -= a1 children = { - 'g-1' : G1, - 'n-1' : N1, - 'l-1' : L1, - } + "g-1": G1, + "n-1": N1, + "l-1": L1, + } commands = { - 'c-1' : Command1, - } + "c-1": Command1, + } + class Proxy: """Proxy class""" @@ -353,7 +366,7 @@ def get_obj(self, path): if not path: return self.r obj = self.r - for c in path.split('/'): + for c in path.split("/"): obj = obj.get_child(c) return obj @@ -391,6 +404,7 @@ def get_attrs(self, path, attrs): def get_static_info(cls): return cls.root.get_static_info() + def test_primitives(): r = flobject.get_root(Proxy()) r.g_1.r_1 = 3.2 @@ -401,40 +415,43 @@ def test_primitives(): assert r.g_1.b_3() is True r.g_1.b_3 = False assert r.g_1.b_3() is False - r.g_1.s_4 = 'foo' - assert r.g_1.s_4() == 'foo' + r.g_1.s_4 = "foo" + assert r.g_1.s_4() == "foo" return True + def test_group(): r = flobject.get_root(Proxy()) - r.g_1 = {'r_1' : 3.2, 'i_2' : -3, 'b_3' : False, 's_4' : 'foo' } - assert r.g_1() == { 'r_1': 3.2, 'i_2' : -3, 'b_3' : False, 's_4' : 'foo' } - r.g_1 = {'s_4' : 'bar'} - assert r.g_1() == { 'r_1': 3.2, 'i_2' : -3, 'b_3' : False, 's_4' : 'bar' } + r.g_1 = {"r_1": 3.2, "i_2": -3, "b_3": False, "s_4": "foo"} + assert r.g_1() == {"r_1": 3.2, "i_2": -3, "b_3": False, "s_4": "foo"} + r.g_1 = {"s_4": "bar"} + assert r.g_1() == {"r_1": 3.2, "i_2": -3, "b_3": False, "s_4": "bar"} r.g_1.i_2 = 4 - assert r.g_1() == { 'r_1': 3.2, 'i_2' : 4, 'b_3' : False, 's_4' : 'bar' } + assert r.g_1() == {"r_1": 3.2, "i_2": 4, "b_3": False, "s_4": "bar"} return True + def test_named_object(): r = flobject.get_root(Proxy()) assert r.n_1.get_object_names() == [] - r.n_1['n1'] = {} - r.n_1['n2'] = {} - assert r.n_1.get_object_names() == ['n1', 'n2'] - r.n_1.rename('n3', 'n1') - assert r.n_1.get_object_names() == ['n3', 'n2'] - r.n_1.create('n4') - assert r.n_1.get_object_names() == ['n3', 'n2', 'n4'] - del r.n_1['n3'] - assert r.n_1.get_object_names() == ['n2', 'n4'] - r.n_1['n1'] = { 'rl_1' : [1.2, 3.4], 'sl_1' : ['foo', 'bar']} - assert r.n_1['n1']() == { 'rl_1' : [1.2, 3.4], 'sl_1' : ['foo', 'bar']} - r.n_1 = {'n5' : { 'rl_1' : [4.3, 2.1], 'sl_1' : ['oof', 'rab']} } - assert r.n_1.get_object_names() == ['n2', 'n4', 'n1', 'n5'] - assert r.n_1['n5']() == { 'rl_1' : [4.3, 2.1], 'sl_1' : ['oof', 'rab']} + r.n_1["n1"] = {} + r.n_1["n2"] = {} + assert r.n_1.get_object_names() == ["n1", "n2"] + r.n_1.rename("n3", "n1") + assert r.n_1.get_object_names() == ["n3", "n2"] + r.n_1.create("n4") + assert r.n_1.get_object_names() == ["n3", "n2", "n4"] + del r.n_1["n3"] + assert r.n_1.get_object_names() == ["n2", "n4"] + r.n_1["n1"] = {"rl_1": [1.2, 3.4], "sl_1": ["foo", "bar"]} + assert r.n_1["n1"]() == {"rl_1": [1.2, 3.4], "sl_1": ["foo", "bar"]} + r.n_1 = {"n5": {"rl_1": [4.3, 2.1], "sl_1": ["oof", "rab"]}} + assert r.n_1.get_object_names() == ["n2", "n4", "n1", "n5"] + assert r.n_1["n5"]() == {"rl_1": [4.3, 2.1], "sl_1": ["oof", "rab"]} return True + def test_list_object(): r = flobject.get_root(Proxy()) assert r.l_1.get_size() == 0 @@ -442,46 +459,55 @@ def test_list_object(): assert r.l_1.get_size() == 3 r.l_1.resize(2) assert r.l_1.get_size() == 2 - assert r.l_1() == [{'il_1' : None, 'bl_1' : None}, - {'il_1' : None, 'bl_1' : None}] + assert r.l_1() == [ + {"il_1": None, "bl_1": None}, + {"il_1": None, "bl_1": None}, + ] r.l_1[1].il_1 = [1, 2] - assert r.l_1() == [{'il_1' : None, 'bl_1' : None}, - {'il_1' : [1, 2], 'bl_1' : None}] - r.l_1 = [{'il_1' : [3], 'bl_1' : [True, False]}] - assert r.l_1() == [{'il_1' : [3], 'bl_1' : [True, False]}] + assert r.l_1() == [ + {"il_1": None, "bl_1": None}, + {"il_1": [1, 2], "bl_1": None}, + ] + r.l_1 = [{"il_1": [3], "bl_1": [True, False]}] + assert r.l_1() == [{"il_1": [3], "bl_1": [True, False]}] return True + def test_command(): r = flobject.get_root(Proxy()) r.g_1.r_1 = 2.4 r.c_1() assert r.g_1.r_1() == 2.4 + 2.3 - r.c_1(a_2 = False) + r.c_1(a_2=False) assert r.g_1.r_1() == 2.4 + 2.3 - 2.3 - r.c_1(a_1 = 3.2, a_2 = True) + r.c_1(a_1=3.2, a_2=True) assert r.g_1.r_1() == 2.4 + 2.3 - 2.3 + 3.2 - r.c_1(a_1 = 4.5, a_2 = False) + r.c_1(a_1=4.5, a_2=False) assert r.g_1.r_1() == 2.4 + 2.3 - 2.3 + 3.2 - 4.5 + def test_attrs(): r = flobject.get_root(Proxy()) - assert r.g_1.s_4.get_attr('active?') - assert r.g_1.s_4.get_attr('allowed-values') == ['foo', 'bar'] + assert r.g_1.s_4.get_attr("active?") + assert r.g_1.s_4.get_attr("allowed-values") == ["foo", "bar"] r.g_1.b_3 = True - assert not r.g_1.s_4.get_attr('active?') + assert not r.g_1.s_4.get_attr("active?") with pytest.raises(RuntimeError) as einfo: - r.g_1.s_4.get_attr('allowed-values') == ['foo', 'bar'] + r.g_1.s_4.get_attr("allowed-values") == ["foo", "bar"] assert einfo.value.args == ("Object is not active",) + # The following test is commented out as codegen module is not packaged in the # install def _disabled_test_settings_gen(): info = Proxy().get_static_info() - cls = flobject.get_cls('', info) + cls = flobject.get_cls("", info) f = io.StringIO() codegen.settingsgen.write_settings_classes(f, cls, info) - assert f.getvalue() == '''### + assert ( + f.getvalue() + == '''### ### THIS FILE IS AUTOGENERATED! DO NOT MODIFY! ### @@ -586,14 +612,14 @@ class bl_1(BooleanList): class c_1(Command): """ Command1 class - + Parameters ---------- a_1 : real 'a_1' child of 'c_1' object a_2 : bool 'a_2' child of 'c_1' object - + """ scheme_name = "c-1" argument_names = \\ @@ -610,4 +636,5 @@ class a_2(Boolean): 'a_2' child of 'c_1' object """ scheme_name = "a-2" -''' # noqa: W293 +''' + ) # noqa: W293 diff --git a/tests/test_parametric.py b/tests/test_parametric.py index 37b85d24718a..9c84899176cb 100644 --- a/tests/test_parametric.py +++ b/tests/test_parametric.py @@ -1,10 +1,11 @@ -import pytest from pathlib import Path + +import pytest from pytest_mock import MockerFixture -from ansys.fluent.parametric import ParametricProject from ansys.fluent.core.solver.flobject import Command, NamedObject from ansys.fluent.core.solver.settings import root +from ansys.fluent.parametric import ParametricProject @pytest.fixture(autouse=True) @@ -21,7 +22,6 @@ def fixture_parametric_project(): class TestParamtericProject: - def test_open( self, mocker: MockerFixture, @@ -32,7 +32,7 @@ def test_open( parametric_project.open(project_filepath=project_filepath) spy.assert_called_once_with( project_filename=str(Path(project_filepath).resolve()), - load_case=True + load_case=True, ) def test_save( diff --git a/tests/test_post.py b/tests/test_post.py index 892301cd404a..7beb8bab0a1b 100644 --- a/tests/test_post.py +++ b/tests/test_post.py @@ -1,9 +1,11 @@ -from typing import Dict, List, Optional +from pathlib import Path import pickle +from typing import Dict, List, Optional + import pytest -from pathlib import Path -from ansys.fluent.post.pyvista import Graphics + from ansys.fluent.post.matplotlib import Plots +from ansys.fluent.post.pyvista import Graphics @pytest.fixture(autouse=True) diff --git a/tests/test_scheme_eval.py b/tests/test_scheme_eval.py index cdd186ec514b..df5cff359acd 100644 --- a/tests/test_scheme_eval.py +++ b/tests/test_scheme_eval.py @@ -1,5 +1,5 @@ -import pytest from google.protobuf.json_format import MessageToDict, ParseDict +import pytest from ansys.api.fluent.v0.scheme_pointer_pb2 import SchemePointer from ansys.fluent.core.services.scheme_eval import ( diff --git a/tests/test_session.py b/tests/test_session.py index 0e5852c8cd7b..9952126672c0 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -1,13 +1,13 @@ -import os from concurrent import futures +import os import grpc import pytest from ansys.api.fluent.v0 import health_pb2, health_pb2_grpc +from ansys.fluent.core import launch_fluent from ansys.fluent.core.services.health_check import HealthCheckService from ansys.fluent.core.session import Session -from ansys.fluent.core import launch_fluent class MockHealthServicer(health_pb2_grpc.HealthServicer):