Skip to content

Commit f1894d5

Browse files
committed
(B004) define OMCSession:OMSessionABC
[OMCSession] update OMCSession* to use OMSessionABC as baseline and further cleanup [ModelicaSystem] shortcut to use OMCSession = OMSessionABC for now [ModelicaSystem] fix usage of OMCSession; replace by OMSessionABC fix usage of OMCSession [OMSessionABC] fix OMCPath; rename to OMPathABC
1 parent 402555f commit f1894d5

File tree

4 files changed

+114
-22
lines changed

4 files changed

+114
-22
lines changed

OMPython/ModelicaSystem.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,11 @@
2626
ModelExecutionException,
2727

2828
OMCSessionException,
29-
OMCSession,
3029
OMCSessionLocal,
3130

3231
OMPathABC,
32+
33+
OMSessionABC,
3334
)
3435

3536
# define logger using the current module name as ID
@@ -347,7 +348,7 @@ class ModelicaSystemABC(metaclass=abc.ABCMeta):
347348

348349
def __init__(
349350
self,
350-
session: OMCSession,
351+
session: OMSessionABC,
351352
work_directory: Optional[str | os.PathLike] = None,
352353
) -> None:
353354
"""Create a ModelicaSystem instance. To define the model use model() or convertFmu2Mo().
@@ -397,7 +398,7 @@ def __init__(
397398
self._file_name: Optional[OMPathABC] = None
398399
self._variable_filter: Optional[str] = None
399400

400-
def get_session(self) -> OMCSession:
401+
def get_session(self) -> OMSessionABC:
401402
"""
402403
Return the OMC session used for this class.
403404
"""
@@ -1498,7 +1499,7 @@ def __init__(
14981499
command_line_options: Optional[list[str]] = None,
14991500
work_directory: Optional[str | os.PathLike] = None,
15001501
omhome: Optional[str] = None,
1501-
session: Optional[OMCSession] = None,
1502+
session: Optional[OMSessionABC] = None,
15021503
) -> None:
15031504
"""Create a ModelicaSystem instance. To define the model use model() or convertFmu2Mo().
15041505
@@ -2221,7 +2222,7 @@ def __init__(
22212222
self._doe_def: Optional[dict[str, dict[str, Any]]] = None
22222223
self._doe_cmd: Optional[dict[str, ModelExecutionData]] = None
22232224

2224-
def get_session(self) -> OMCSession:
2225+
def get_session(self) -> OMSessionABC:
22252226
"""
22262227
Return the OMC session used for this class.
22272228
"""

OMPython/OMCSession.py

Lines changed: 105 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,8 @@ class OMCSessionCmd:
7070
Implementation of Open Modelica Compiler API functions. Depreciated!
7171
"""
7272

73-
def __init__(self, session: OMCSession, readonly: bool = False):
74-
if not isinstance(session, OMCSession):
73+
def __init__(self, session: OMSessionABC, readonly: bool = False):
74+
if not isinstance(session, OMSessionABC):
7575
raise OMCSessionException("Invalid OMC process definition!")
7676
self._session = session
7777
self._readonly = readonly
@@ -301,7 +301,7 @@ class OMPathABC(pathlib.PurePosixPath, metaclass=abc.ABCMeta):
301301
limited compared to standard pathlib.Path objects.
302302
"""
303303

304-
def __init__(self, *path, session: OMCSession) -> None:
304+
def __init__(self, *path, session: OMSessionABC) -> None:
305305
super().__init__(*path)
306306
self._session = session
307307

@@ -610,7 +610,7 @@ def __init__(
610610
self,
611611
timeout: float = 10.00,
612612
omhome: Optional[str] = None,
613-
omc_process: Optional[OMCSession] = None,
613+
omc_process: Optional[OMCSessionABC] = None,
614614
) -> None:
615615
"""
616616
Initialisation for OMCSessionZMQ
@@ -622,7 +622,7 @@ def __init__(
622622

623623
if omc_process is None:
624624
omc_process = OMCSessionLocal(omhome=omhome, timeout=timeout)
625-
elif not isinstance(omc_process, OMCSession):
625+
elif not isinstance(omc_process, OMCSessionABC):
626626
raise OMCSessionException("Invalid definition of the OMC process!")
627627
self.omc_process = omc_process
628628

@@ -634,7 +634,7 @@ def escape_str(value: str) -> str:
634634
"""
635635
Escape a string such that it can be used as string within OMC expressions, i.e. escape all double quotes.
636636
"""
637-
return OMCSession.escape_str(value=value)
637+
return OMCSessionABC.escape_str(value=value)
638638

639639
def omcpath(self, *path) -> OMPathABC:
640640
"""
@@ -689,7 +689,7 @@ def __call__(cls, *args, **kwargs):
689689
return obj
690690

691691

692-
class OMCSessionMeta(abc.ABCMeta, PostInitCaller):
692+
class OMSessionMeta(abc.ABCMeta, PostInitCaller):
693693
"""
694694
Helper class to get a combined metaclass of ABCMeta and PostInitCaller.
695695
@@ -698,7 +698,98 @@ class OMCSessionMeta(abc.ABCMeta, PostInitCaller):
698698
"""
699699

700700

701-
class OMCSession(metaclass=OMCSessionMeta):
701+
class OMSessionABC(metaclass=OMSessionMeta):
702+
"""
703+
This class implements the basic structure a OMPython session definition needs. It provides the structure for an
704+
implementation using OMC as backend (via ZMQ) or a dummy implementation which just runs a model executable.
705+
"""
706+
707+
def __init__(
708+
self,
709+
timeout: float = 10.00,
710+
**kwargs,
711+
) -> None:
712+
"""
713+
Initialisation for OMSessionBase
714+
"""
715+
716+
# some helper data
717+
self.model_execution_windows = platform.system() == "Windows"
718+
self.model_execution_local = False
719+
720+
# store variables
721+
self._timeout = timeout
722+
723+
def __post_init__(self) -> None:
724+
"""
725+
Post initialisation method.
726+
"""
727+
728+
@staticmethod
729+
def escape_str(value: str) -> str:
730+
"""
731+
Escape a string such that it can be used as string within OMC expressions, i.e. escape all double quotes.
732+
"""
733+
return value.replace("\\", "\\\\").replace('"', '\\"')
734+
735+
@abc.abstractmethod
736+
def model_execution_prefix(self, cwd: Optional[OMPathABC] = None) -> list[str]:
737+
"""
738+
Helper function which returns a command prefix.
739+
"""
740+
741+
@abc.abstractmethod
742+
def get_version(self) -> str:
743+
"""
744+
Get the OM version.
745+
"""
746+
747+
@abc.abstractmethod
748+
def set_workdir(self, workdir: OMPathABC) -> None:
749+
"""
750+
Set the workdir for this session.
751+
"""
752+
753+
@abc.abstractmethod
754+
def omcpath(self, *path) -> OMPathABC:
755+
"""
756+
Create an OMPathBase object based on the given path segments and the current class.
757+
"""
758+
759+
@abc.abstractmethod
760+
def omcpath_tempdir(self, tempdir_base: Optional[OMPathABC] = None) -> OMPathABC:
761+
"""
762+
Get a temporary directory based on the specific definition for this session.
763+
"""
764+
765+
@staticmethod
766+
def _tempdir(tempdir_base: OMPathABC) -> OMPathABC:
767+
names = [str(uuid.uuid4()) for _ in range(100)]
768+
769+
tempdir: Optional[OMPathABC] = None
770+
for name in names:
771+
# create a unique temporary directory name
772+
tempdir = tempdir_base / name
773+
774+
if tempdir.exists():
775+
continue
776+
777+
tempdir.mkdir(parents=True, exist_ok=False)
778+
break
779+
780+
if tempdir is None or not tempdir.is_dir():
781+
raise FileNotFoundError(f"Cannot create a temporary directory in {tempdir_base}!")
782+
783+
return tempdir
784+
785+
@abc.abstractmethod
786+
def sendExpression(self, expr: str, parsed: bool = True) -> Any:
787+
"""
788+
Function needed to send expressions to the OMC server via ZMQ.
789+
"""
790+
791+
792+
class OMCSessionABC(OMSessionABC, metaclass=abc.ABCMeta):
702793
"""
703794
Base class for an OMC session started via ZMQ. This class contains common functionality for all variants of an
704795
OMC session definition.
@@ -1104,7 +1195,7 @@ def _get_portfile_path(self) -> Optional[pathlib.Path]:
11041195
return portfile_path
11051196

11061197

1107-
class OMCSessionPort(OMCSession):
1198+
class OMCSessionPort(OMCSessionABC):
11081199
"""
11091200
OMCSession implementation which uses a port to connect to an already running OMC server.
11101201
"""
@@ -1117,7 +1208,7 @@ def __init__(
11171208
self._omc_port = omc_port
11181209

11191210

1120-
class OMCSessionLocal(OMCSession):
1211+
class OMCSessionLocal(OMCSessionABC):
11211212
"""
11221213
OMCSession implementation which runs the OMC server locally on the machine (Linux / Windows).
11231214
"""
@@ -1198,7 +1289,7 @@ def _omc_port_get(self) -> str:
11981289
return port
11991290

12001291

1201-
class OMCSessionDockerHelper(OMCSession):
1292+
class OMCSessionDockerABC(OMCSessionABC, metaclass=abc.ABCMeta):
12021293
"""
12031294
Base class for OMCSession implementations which run the OMC server in a Docker container.
12041295
"""
@@ -1326,7 +1417,7 @@ def model_execution_prefix(self, cwd: Optional[OMPathABC] = None) -> list[str]:
13261417
return docker_cmd
13271418

13281419

1329-
class OMCSessionDocker(OMCSessionDockerHelper):
1420+
class OMCSessionDocker(OMCSessionDockerABC):
13301421
"""
13311422
OMC process running in a Docker container.
13321423
"""
@@ -1468,7 +1559,7 @@ def _docker_omc_start(self) -> Tuple[subprocess.Popen, DockerPopen, str]:
14681559
return omc_process, docker_process, docker_cid
14691560

14701561

1471-
class OMCSessionDockerContainer(OMCSessionDockerHelper):
1562+
class OMCSessionDockerContainer(OMCSessionDockerABC):
14721563
"""
14731564
OMC process running in a Docker container (by container ID).
14741565
"""
@@ -1561,7 +1652,7 @@ def _docker_omc_start(self) -> Tuple[subprocess.Popen, DockerPopen]:
15611652
return omc_process, docker_process
15621653

15631654

1564-
class OMCSessionWSL(OMCSession):
1655+
class OMCSessionWSL(OMCSessionABC):
15651656
"""
15661657
OMC process running in Windows Subsystem for Linux (WSL).
15671658
"""

OMPython/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
OMPathABC,
2727
OMCPath,
2828

29-
OMCSession,
29+
OMCSessionABC,
3030

3131
ModelExecutionData,
3232
ModelExecutionException,
@@ -58,7 +58,7 @@
5858
'OMPathABC',
5959
'OMCPath',
6060

61-
'OMCSession',
61+
'OMCSessionABC',
6262

6363
'doe_get_solutions',
6464

tests/test_OMCPath.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def test_OMCPath_OMCProcessWSL():
4949
del omcs
5050

5151

52-
def _run_OMCPath_checks(omcs: OMPython.OMCSession):
52+
def _run_OMCPath_checks(omcs: OMPython.OMCSessionABC):
5353
p1 = omcs.omcpath_tempdir()
5454
p2 = p1 / 'test'
5555
p2.mkdir()

0 commit comments

Comments
 (0)