-
Notifications
You must be signed in to change notification settings - Fork 40
/
fluent_connection.py
309 lines (257 loc) · 10.4 KB
/
fluent_connection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
from ctypes import c_int, sizeof
import itertools
import os
import threading
import time
from typing import Callable, List, Optional, Tuple
import warnings
import weakref
import grpc
from ansys.fluent.core.journaling import Journal
from ansys.fluent.core.services.datamodel_se import (
DatamodelService as DatamodelService_SE,
)
from ansys.fluent.core.services.datamodel_tui import (
DatamodelService as DatamodelService_TUI,
)
from ansys.fluent.core.services.events import EventsService
from ansys.fluent.core.services.field_data import FieldData, FieldDataService, FieldInfo
from ansys.fluent.core.services.health_check import HealthCheckService
from ansys.fluent.core.services.monitor import MonitorsService
from ansys.fluent.core.services.scheme_eval import SchemeEval, SchemeEvalService
from ansys.fluent.core.services.settings import SettingsService
from ansys.fluent.core.streaming_services.events_streaming import EventsManager
from ansys.fluent.core.streaming_services.monitor_streaming import MonitorsManager
from ansys.fluent.core.streaming_services.transcript_streaming import Transcript
def _get_max_c_int_limit() -> int:
"""Get the maximum limit of a C int.
Returns
-------
int
The maximum limit of a C int
"""
return 2 ** (sizeof(c_int) * 8 - 1) - 1
class MonitorThread(threading.Thread):
"""A class used for monitoring a Fluent session.
Daemon thread which will ensure cleanup of session objects, shutdown of
non-deamon threads etc.
Attributes
----------
cbs : List[Callable]
Cleanup/shutdown functions
"""
def __init__(self):
super().__init__(daemon=True)
self.cbs: List[Callable] = []
def run(self) -> None:
main_thread = threading.main_thread()
main_thread.join()
for cb in self.cbs:
cb()
class _IsDataValid:
def __init__(self, scheme_eval):
self._scheme_eval = scheme_eval
def __bool__(self):
return self()
def __call__(self):
return self._scheme_eval.scheme_eval("(data-valid?)")
class _FluentConnection:
"""Encapsulates a Fluent connection.
Methods
-------
get_current_fluent_mode()
Gets the mode of the current instance of Fluent (meshing or
solver).
get_fluent_version()
Gets and returns the fluent version.
exit()
Close the Fluent connection and exit Fluent.
"""
_on_exit_cbs: List[Callable] = []
_id_iter = itertools.count()
_monitor_thread: Optional[MonitorThread] = None
_writing_transcript_to_interpreter = False
def __init__(
self,
start_timeout: int = 100,
ip: str = None,
port: int = None,
password: str = None,
channel: grpc.Channel = None,
cleanup_on_exit: bool = True,
start_transcript: bool = True,
remote_instance=None,
):
"""Instantiate a Session.
Parameters
----------
start_timeout: int, optional
Maximum allowable time in seconds for connecting to the Fluent
server. The default is ``100``.
ip : str, optional
IP address to connect to existing Fluent instance. Used only
when ``channel`` is ``None``. Defaults to ``"127.0.0.1"``
and can also be set by the environment variable
``PYFLUENT_FLUENT_IP=<ip>``.
port : int, optional
Port to connect to existing Fluent instance. Used only
when ``channel`` is ``None``. Defaults value can be set by
the environment variable ``PYFLUENT_FLUENT_PORT=<port>``.
password : str, optional
Password to connect to existing Fluent instance.
channel : grpc.Channel, optional
Grpc channel to use to connect to existing Fluent instance.
ip and port arguments will be ignored when channel is
specified.
cleanup_on_exit : bool, optional
When True, the connected Fluent session will be shut down
when PyFluent is exited or exit() is called on the session
instance, by default True.
start_transcript : bool, optional
The Fluent transcript is started in the client only when
start_transcript is True. It can be started and stopped
subsequently via method calls on the Session object.
remote_instance : ansys.platform.instancemanagement.Instance
The corresponding remote instance when Fluent is launched through
PyPIM. This instance will be deleted when calling
``Session.exit()``.
"""
self._data_valid = False
self._channel_str = None
if channel is not None:
self._channel = channel
else:
if not ip:
ip = os.getenv("PYFLUENT_FLUENT_IP", "127.0.0.1")
if not port:
port = os.getenv("PYFLUENT_FLUENT_PORT")
self._channel_str = f"{ip}:{port}"
if not port:
raise ValueError(
"The port to connect to Fluent session is not provided."
)
# Same maximum message length is used in the server
max_message_length = _get_max_c_int_limit()
self._channel = grpc.insecure_channel(
f"{ip}:{port}",
options=[
("grpc.max_send_message_length", max_message_length),
("grpc.max_receive_message_length", max_message_length),
],
)
self._metadata: List[Tuple[str, str]] = (
[("password", password)] if password else []
)
self.health_check_service = HealthCheckService(self._channel, self._metadata)
counter = 0
while not self.health_check_service.is_serving:
time.sleep(1)
counter += 1
if counter > start_timeout:
raise RuntimeError(
f"The connection to the Fluent server could not be established within the configurable {start_timeout} second time limit."
)
self._id = f"session-{next(_FluentConnection._id_iter)}"
if not _FluentConnection._monitor_thread:
_FluentConnection._monitor_thread = MonitorThread()
_FluentConnection._monitor_thread.start()
self.transcript = Transcript(self._channel, self._metadata)
self._events_service = EventsService(self._channel, self._metadata)
self.events_manager = EventsManager(self._id, self._events_service)
self._monitors_service = MonitorsService(self._channel, self._metadata)
self.monitors_manager = MonitorsManager(self._id, self._monitors_service)
self.events_manager.register_callback(
"InitializedEvent", self.monitors_manager.refresh
)
self.events_manager.register_callback(
"DataReadEvent", self.monitors_manager.refresh
)
self.events_manager.start()
self.datamodel_service_tui = DatamodelService_TUI(self._channel, self._metadata)
self.datamodel_service_se = DatamodelService_SE(self._channel, self._metadata)
self.settings_service = SettingsService(self._channel, self._metadata)
self._scheme_eval_service = SchemeEvalService(self._channel, self._metadata)
self.scheme_eval = SchemeEval(self._scheme_eval_service)
self._field_data_service = FieldDataService(self._channel, self._metadata)
self.field_info = FieldInfo(self._field_data_service)
self.field_data = FieldData(
self._field_data_service, self.field_info, _IsDataValid(self.scheme_eval)
)
self.journal = Journal(self.scheme_eval)
self._cleanup_on_exit = cleanup_on_exit
self.callback_id1 = None
self.callback_id2 = None
if start_transcript:
self.transcript.start()
self._remote_instance = remote_instance
self._finalizer = weakref.finalize(
self,
_FluentConnection._exit,
self._channel,
self._cleanup_on_exit,
self.scheme_eval,
self.transcript,
self.events_manager,
self._remote_instance,
)
_FluentConnection._monitor_thread.cbs.append(self._finalizer)
@property
def id(self) -> str:
"""Return the session id."""
return self._id
def get_current_fluent_mode(self):
"""Gets the mode of the current instance of Fluent (meshing or
solver)."""
if self.scheme_eval.scheme_eval("(cx-solver-mode?)"):
return "solver"
else:
return "meshing"
def start_transcript(
self, file_path: str = None, write_to_interpreter: bool = True
) -> None:
"""Start streaming of Fluent transcript."""
warnings.warn("Use -> transcript.start()", DeprecationWarning)
self.transcript.start(file_path, write_to_interpreter)
def stop_transcript(self) -> None:
"""Stop streaming of Fluent transcript."""
warnings.warn("Use -> transcript.stop()", DeprecationWarning)
self.transcript.stop()
def start_journal(self, file_path: str):
"""Executes tui command to start journal."""
warnings.warn("Use -> journal.start()", DeprecationWarning)
self.journal.start(file_path)
def stop_journal(self):
"""Executes tui command to stop journal."""
warnings.warn("Use -> journal.stop()", DeprecationWarning)
self.journal.stop()
def check_health(self) -> str:
"""Check health of Fluent connection."""
warnings.warn("Use -> health_check_service.status()", DeprecationWarning)
return self.health_check_service.status()
def get_fluent_version(self):
"""Gets and returns the fluent version."""
return self.scheme_eval.version
def exit(self) -> None:
"""Close the Fluent connection and exit Fluent."""
self._finalizer()
@staticmethod
def _exit(
channel,
cleanup_on_exit,
scheme_eval,
transcript,
events_manager,
remote_instance,
) -> None:
if channel:
if cleanup_on_exit:
try:
scheme_eval.exec(("(exit-server)",))
except Exception:
pass
transcript.stop()
events_manager.stop()
channel.close()
channel = None
if remote_instance:
remote_instance.delete()