Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: launcher code refactoring #2702

Merged
merged 20 commits into from
Apr 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/ansys/fluent/core/launcher/container_launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@
FluentMode,
FluentWindowsGraphicsDriver,
UIMode,
_get_graphics_driver,
_get_mode,
_validate_gpu,
)
import ansys.fluent.core.launcher.watchdog as watchdog
from ansys.fluent.core.utils.file_transfer_service import RemoteFileTransferStrategy
Expand Down Expand Up @@ -144,6 +147,9 @@ def __init__(
The allocated machines and core counts are queried from the scheduler environment and
passed to Fluent.
"""
_validate_gpu(gpu, version)
graphics_driver = _get_graphics_driver(graphics_driver)
mode = _get_mode(mode)
argvals = locals().copy()
del argvals["self"]
if argvals["start_timeout"] is None:
Expand Down
41 changes: 4 additions & 37 deletions src/ansys/fluent/core/launcher/launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,11 @@
import logging
import os
from typing import Any, Dict, Optional, Union
import warnings

from ansys.fluent.core.fluent_connection import FluentConnection
from ansys.fluent.core.launcher.container_launcher import DockerLauncher
from ansys.fluent.core.launcher.error_handler import (
GPUSolverSupportError,
_process_invalid_args,
)
from ansys.fluent.core.launcher.launcher_utils import (
_confirm_watchdog_start,
is_windows,
)
from ansys.fluent.core.launcher.error_handler import _process_invalid_args
from ansys.fluent.core.launcher.launcher_utils import _confirm_watchdog_start
from ansys.fluent.core.launcher.pim_launcher import PIMLauncher
from ansys.fluent.core.launcher.pyfluent_enums import (
FluentLinuxGraphicsDriver,
Expand All @@ -27,7 +20,6 @@
LaunchMode,
UIMode,
_get_fluent_launch_mode,
_get_mode,
_get_running_session_mode,
)
from ansys.fluent.core.launcher.server_info import _get_server_info
Expand All @@ -39,7 +31,6 @@
from ansys.fluent.core.session_solver import Solver
from ansys.fluent.core.session_solver_icing import SolverIcing
from ansys.fluent.core.utils.fluent_version import FluentVersion
from ansys.fluent.core.warnings import PyFluentDeprecationWarning

_THIS_DIR = os.path.dirname(__file__)
_OPTIONS_FILE = os.path.join(_THIS_DIR, "fluent_launcher_options.json")
Expand All @@ -65,6 +56,7 @@ def create_launcher(fluent_launch_mode: LaunchMode = None, **kwargs):
DisallowedValuesError
If an unknown Fluent launch mode is passed.
"""
_process_invalid_args(kwargs["dry_run"], fluent_launch_mode, kwargs)
if fluent_launch_mode == LaunchMode.STANDALONE:
return StandaloneLauncher(
mode=kwargs["mode"],
Expand All @@ -80,6 +72,7 @@ def create_launcher(fluent_launch_mode: LaunchMode = None, **kwargs):
env=kwargs["env"],
cleanup_on_exit=kwargs["cleanup_on_exit"],
start_transcript=kwargs["start_transcript"],
show_gui=kwargs["show_gui"],
case_file_name=kwargs["case_file_name"],
case_data_file_name=kwargs["case_data_file_name"],
lightweight_mode=kwargs["lightweight_mode"],
Expand Down Expand Up @@ -302,39 +295,13 @@ def launch_fluent(
The allocated machines and core counts are queried from the scheduler environment and
passed to Fluent.
"""
if version == "2d" and gpu:
raise GPUSolverSupportError()
if show_gui is not None:
warnings.warn(
"'show_gui' is deprecated, use 'ui_mode' instead",
PyFluentDeprecationWarning,
)
if show_gui or os.getenv("PYFLUENT_SHOW_SERVER_GUI") == "1":
ui_mode = UIMode.GUI
del show_gui
if ui_mode is None:
# Not using NO_GUI in windows as it opens a new cmd or
# shows Fluent output in the current cmd if start <launch_string> is not used
ui_mode = UIMode.HIDDEN_GUI if is_windows() else UIMode.NO_GUI
if isinstance(ui_mode, str):
ui_mode = UIMode(ui_mode)
if graphics_driver is None:
graphics_driver = "auto"
graphics_driver = str(graphics_driver)
graphics_driver = (
FluentWindowsGraphicsDriver(graphics_driver)
if is_windows()
else FluentLinuxGraphicsDriver(graphics_driver)
)
fluent_launch_mode = _get_fluent_launch_mode(
start_container=start_container,
container_dict=container_dict,
scheduler_options=scheduler_options,
)
del start_container
mode = _get_mode(mode)
argvals = locals().copy()
_process_invalid_args(dry_run, fluent_launch_mode, argvals)
fluent_launch_mode = argvals.pop("fluent_launch_mode")
launcher = create_launcher(fluent_launch_mode, **argvals)
return launcher()
Expand Down
6 changes: 6 additions & 0 deletions src/ansys/fluent/core/launcher/pim_launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
FluentMode,
FluentWindowsGraphicsDriver,
UIMode,
_get_graphics_driver,
_get_mode,
_validate_gpu,
)
from ansys.fluent.core.session_meshing import Meshing
from ansys.fluent.core.session_pure_meshing import PureMeshing
Expand Down Expand Up @@ -131,6 +134,9 @@ def __init__(
The allocated machines and core counts are queried from the scheduler environment and
passed to Fluent.
"""
_validate_gpu(gpu, version)
graphics_driver = _get_graphics_driver(graphics_driver)
mode = _get_mode(mode)
argvals = locals().copy()
del argvals["self"]
if argvals["start_timeout"] is None:
Expand Down
4 changes: 3 additions & 1 deletion src/ansys/fluent/core/launcher/process_launch_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from pathlib import Path

from ansys.fluent.core.launcher import launcher_utils
from ansys.fluent.core.launcher.pyfluent_enums import FluentMode
from ansys.fluent.core.launcher.pyfluent_enums import FluentMode, UIMode
from ansys.fluent.core.scheduler import build_parallel_options, load_machines
from ansys.fluent.core.utils.fluent_version import FluentVersion

Expand Down Expand Up @@ -66,6 +66,8 @@ def _build_fluent_launch_args_string(**kwargs) -> str:
elif isinstance(gpu, list):
launch_args_string += f" -gpu={','.join(map(str, gpu))}"
ui_mode = kwargs.get("ui_mode")
if isinstance(ui_mode, str):
ui_mode = UIMode(ui_mode)
if ui_mode and ui_mode.value[0]:
launch_args_string += f" -{ui_mode.value[0]}"
graphics_driver = kwargs.get("graphics_driver")
Expand Down
122 changes: 92 additions & 30 deletions src/ansys/fluent/core/launcher/pyfluent_enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,18 @@
from functools import total_ordering
import os
from typing import Optional, Union
import warnings

from ansys.fluent.core.exceptions import DisallowedValuesError
from ansys.fluent.core.fluent_connection import FluentConnection
import ansys.fluent.core.launcher.error_handler as exceptions
from ansys.fluent.core.launcher.launcher_utils import check_docker_support
from ansys.fluent.core.launcher.launcher_utils import check_docker_support, is_windows
from ansys.fluent.core.session_meshing import Meshing
from ansys.fluent.core.session_pure_meshing import PureMeshing
from ansys.fluent.core.session_solver import Solver
from ansys.fluent.core.session_solver_icing import SolverIcing
from ansys.fluent.core.utils.fluent_version import FluentVersion
from ansys.fluent.core.warnings import PyFluentDeprecationWarning
import ansys.platform.instancemanagement as pypim


Expand Down Expand Up @@ -143,35 +145,6 @@ class FluentLinuxGraphicsDriver(FluentEnum):
AUTO = ("",)


def _get_mode(mode: Optional[Union[FluentMode, str, None]] = None):
"""Update the session information."""
if mode is None:
mode = FluentMode.SOLVER

if isinstance(mode, str):
mode = FluentMode.get_mode(mode)

return mode


def _get_running_session_mode(
fluent_connection: FluentConnection, mode: Optional[FluentMode] = None
):
"""Get the mode of the running session if the mode has not been explicitly given."""
if mode:
session_mode = mode
else:
try:
session_mode = FluentMode.get_mode(
"solver"
if fluent_connection._connection_interface.is_solver_mode()
else "meshing"
)
except Exception as ex:
raise exceptions.InvalidPassword() from ex
return session_mode.value[0]


def _get_fluent_launch_mode(start_container, container_dict, scheduler_options):
"""Get the Fluent launch mode.

Expand Down Expand Up @@ -204,6 +177,49 @@ def _get_fluent_launch_mode(start_container, container_dict, scheduler_options):
return fluent_launch_mode


def _get_graphics_driver(
graphics_driver: Union[FluentWindowsGraphicsDriver, FluentLinuxGraphicsDriver, str]
):
if graphics_driver is None:
graphics_driver = "auto"
graphics_driver = str(graphics_driver)
graphics_driver = (
FluentWindowsGraphicsDriver(graphics_driver)
if is_windows()
else FluentLinuxGraphicsDriver(graphics_driver)
)
return graphics_driver


def _get_mode(mode: Optional[Union[FluentMode, str, None]] = None):
"""Update the session information."""
if mode is None:
mode = FluentMode.SOLVER

if isinstance(mode, str):
mode = FluentMode.get_mode(mode)

return mode


def _get_running_session_mode(
fluent_connection: FluentConnection, mode: Optional[FluentMode] = None
):
"""Get the mode of the running session if the mode has not been explicitly given."""
if mode:
session_mode = mode
else:
try:
session_mode = FluentMode.get_mode(
"solver"
if fluent_connection._connection_interface.is_solver_mode()
else "meshing"
)
except Exception as ex:
raise exceptions.InvalidPassword() from ex
return session_mode.value[0]


def _get_standalone_launch_fluent_version(
product_version: Union[FluentVersion, None]
) -> Optional[FluentVersion]:
Expand Down Expand Up @@ -233,3 +249,49 @@ def _get_standalone_launch_fluent_version(

# 2. the latest ANSYS version from AWP_ROOT environment variables
return FluentVersion.get_latest_installed()


def _get_ui_mode(
show_gui: Optional[bool] = None,
):
"""Get the graphics driver.

Parameters
----------
show_gui: bool
Whether to show the Fluent GUI.

Returns
-------
ui_mode: UIMode
Fluent GUI mode.
"""
ui_mode = None
if show_gui is not None:
warnings.warn(
"'show_gui' is deprecated. Use 'ui_mode' instead.",
PyFluentDeprecationWarning,
)
if show_gui or os.getenv("PYFLUENT_SHOW_SERVER_GUI") == "1":
ui_mode = UIMode.GUI
if ui_mode is None:
# Not using NO_GUI in windows as it opens a new cmd or
# shows Fluent output in the current cmd if start <launch_string> is not used
ui_mode = UIMode.HIDDEN_GUI if is_windows() else UIMode.NO_GUI
if isinstance(ui_mode, str):
ui_mode = UIMode(ui_mode)
return ui_mode


def _validate_gpu(gpu: Union[bool, list], version: str):
"""Raise an exception if the GPU Solver is unsupported.

Parameters
----------
gpu : bool or list, optional
This option will start Fluent with the GPU Solver.
version : str, optional
Geometric dimensionality of the Fluent simulation.
"""
if version == "2d" and gpu:
raise exceptions.GPUSolverSupportError()
21 changes: 19 additions & 2 deletions src/ansys/fluent/core/launcher/standalone_launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,11 @@
FluentMode,
FluentWindowsGraphicsDriver,
UIMode,
_get_graphics_driver,
_get_mode,
_get_standalone_launch_fluent_version,
_get_ui_mode,
_validate_gpu,
)
from ansys.fluent.core.launcher.server_info import (
_get_server_info,
Expand Down Expand Up @@ -67,6 +71,7 @@ def __init__(
env: Optional[Dict[str, Any]] = None,
cleanup_on_exit: bool = True,
start_transcript: bool = True,
show_gui: Optional[bool] = None,
case_file_name: Optional[str] = None,
case_data_file_name: Optional[str] = None,
lightweight_mode: Optional[bool] = None,
Expand Down Expand Up @@ -123,10 +128,17 @@ def __init__(
default is ``True``. You can stop and start the streaming of the
Fluent transcript subsequently via the method calls, ``transcript.start()``
and ``transcript.stop()`` on the session object.
hpohekar marked this conversation as resolved.
Show resolved Hide resolved
show_gui : bool, optional
Whether to display the Fluent GUI. The default is ``None``,
in which case the GUI is not shown. If ``False`` is
not explicitly provided, the GUI is shown if
the ``PYFLUENT_SHOW_SERVER_GUI`` environment
variable is set to 1.
case_file_name : str, optional
If provided, the case file at ``case_file_name`` is read into the Fluent session.
Name of the case file to read into the
Fluent session. The default is ``None``.
case_data_file_name : str, optional
If provided, the case and data files at ``case_data_file_name`` are read into the Fluent session.
Name of the case data file. If names of both a case file and case data file are provided, they are read into the Fluent session.
lightweight_mode : bool, optional
Whether to run in lightweight mode. In lightweight mode, the lightweight settings are read into the
current Fluent solver session. The mesh is read into a background Fluent solver session which will
Expand Down Expand Up @@ -172,6 +184,11 @@ def __init__(
The allocated machines and core counts are queried from the scheduler environment and
passed to Fluent.
"""
_validate_gpu(gpu, version)
graphics_driver = _get_graphics_driver(graphics_driver)
ui_mode = _get_ui_mode(show_gui)
del show_gui
mode = _get_mode(mode)
argvals = locals().copy()
del argvals["self"]
if argvals["start_timeout"] is None:
Expand Down
5 changes: 3 additions & 2 deletions tests/test_launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,8 +401,9 @@ def test_build_journal_argument(topy, journal_file_names, result, raises):

@pytest.mark.filterwarnings("error::FutureWarning")
def test_show_gui_raises_warning():
with pytest.raises(PyFluentDeprecationWarning):
pyfluent.launch_fluent(show_gui=True)
if not check_docker_support() and not pypim.is_configured():
with pytest.raises(PyFluentDeprecationWarning):
pyfluent.launch_fluent(show_gui=True)


def test_fluent_enums():
Expand Down