diff --git a/OMPython/ModelicaSystem.py b/OMPython/ModelicaSystem.py index d6a3d654..1a5edff5 100644 --- a/OMPython/ModelicaSystem.py +++ b/OMPython/ModelicaSystem.py @@ -51,9 +51,8 @@ from OMPython.OMCSession import ( OMCSessionException, OMCSessionRunData, - OMCSessionZMQ, - OMCProcess, - OMCProcessLocal, + OMCSession, + OMCSessionLocal, OMCPath, ) @@ -127,7 +126,7 @@ class ModelicaSystemCmd: def __init__( self, - session: OMCSessionZMQ, + session: OMCSession, runpath: OMCPath, modelname: Optional[str] = None, ) -> None: @@ -325,7 +324,7 @@ def parse_simflags(simflags: str) -> dict[str, Optional[str | dict[str, Any] | n class ModelicaSystem: """ - Class to simulate a Modelica model using OpenModelica via OMCSessionZMQ. + Class to simulate a Modelica model using OpenModelica via OMCSession. """ def __init__( @@ -333,7 +332,7 @@ def __init__( command_line_options: Optional[list[str]] = None, work_directory: Optional[str | os.PathLike] = None, omhome: Optional[str] = None, - omc_process: Optional[OMCProcess] = None, + session: Optional[OMCSession] = None, ) -> None: """Create a ModelicaSystem instance. To define the model use model() or convertFmu2Mo(). @@ -344,8 +343,8 @@ def __init__( work_directory: Path to a directory to be used for temporary files like the model executable. If left unspecified, a tmp directory will be created. - omhome: path to OMC to be used when creating the OMC session (see OMCSessionZMQ). - omc_process: definition of a (local) OMC process to be used. If + omhome: path to OMC to be used when creating the OMC session (see OMCSession). + session: definition of a (local) OMC session to be used. If unspecified, a new local session will be created. """ @@ -373,10 +372,10 @@ def __init__( self._linearized_outputs: list[str] = [] # linearization output list self._linearized_states: list[str] = [] # linearization states list - if omc_process is not None: - self._session = OMCSessionZMQ(omc_process=omc_process) + if session is not None: + self._session = session else: - self._session = OMCSessionZMQ(omhome=omhome) + self._session = OMCSessionLocal(omhome=omhome) # set commandLineOptions using default values or the user defined list if command_line_options is None: @@ -461,13 +460,13 @@ def model( if model_file is not None: file_path = pathlib.Path(model_file) # special handling for OMCProcessLocal - consider a relative path - if isinstance(self._session.omc_process, OMCProcessLocal) and not file_path.is_absolute(): + if isinstance(self._session, OMCSessionLocal) and not file_path.is_absolute(): file_path = pathlib.Path.cwd() / file_path if not file_path.is_file(): raise IOError(f"Model file {file_path} does not exist!") self._file_name = self.getWorkDirectory() / file_path.name - if (isinstance(self._session.omc_process, OMCProcessLocal) + if (isinstance(self._session, OMCSessionLocal) and file_path.as_posix() == self._file_name.as_posix()): pass elif self._file_name.is_file(): @@ -482,7 +481,7 @@ def model( if build: self.buildModel(variable_filter) - def session(self) -> OMCSessionZMQ: + def get_session(self) -> OMCSession: """ Return the OMC session used for this class. """ @@ -1197,7 +1196,7 @@ def plot( plot is created by OMC which needs access to the local display. This is not the case for docker and WSL. """ - if not isinstance(self._session.omc_process, OMCProcessLocal): + if not isinstance(self._session, OMCSessionLocal): raise ModelicaSystemError("Plot is using the OMC plot functionality; " "thus, it is only working if OMC is running locally!") @@ -1954,7 +1953,7 @@ def __init__( variable_filter: Optional[str] = None, work_directory: Optional[str | os.PathLike] = None, omhome: Optional[str] = None, - omc_process: Optional[OMCProcess] = None, + session: Optional[OMCSession] = None, # simulation specific input # TODO: add more settings (simulation options, input options, ...) simargs: Optional[dict[str, Optional[str | dict[str, str] | numbers.Number]]] = None, @@ -1974,7 +1973,7 @@ def __init__( command_line_options=command_line_options, work_directory=work_directory, omhome=omhome, - omc_process=omc_process, + session=session, ) self._mod.model( model_file=model_file, @@ -1988,9 +1987,9 @@ def __init__( self._simargs = simargs if resultpath is None: - self._resultpath = self.session().omcpath_tempdir() + self._resultpath = self.get_session().omcpath_tempdir() else: - self._resultpath = self.session().omcpath(resultpath) + self._resultpath = self.get_session().omcpath(resultpath) if not self._resultpath.is_dir(): raise ModelicaSystemError("Argument resultpath must be set to a valid path within the environment used " f"for the OpenModelica session: {resultpath}!") @@ -2003,11 +2002,11 @@ def __init__( self._doe_def: Optional[dict[str, dict[str, Any]]] = None self._doe_cmd: Optional[dict[str, OMCSessionRunData]] = None - def session(self) -> OMCSessionZMQ: + def get_session(self) -> OMCSession: """ Return the OMC session used for this class. """ - return self._mod.session() + return self._mod.get_session() def prepare(self) -> int: """ @@ -2046,7 +2045,7 @@ def prepare(self) -> int: pk_value = pc_structure[idx_structure] if isinstance(pk_value, str): - pk_value_str = self.session().escape_str(pk_value) + pk_value_str = self.get_session().escape_str(pk_value) expression = f"setParameterValue({self._model_name}, {pk_structure}, \"{pk_value_str}\")" elif isinstance(pk_value, bool): pk_value_bool_str = "true" if pk_value else "false" @@ -2167,12 +2166,12 @@ def worker(worker_id, task_queue): raise ModelicaSystemError("Missing simulation definition!") resultfile = cmd_definition.cmd_result_path - resultpath = self.session().omcpath(resultfile) + resultpath = self.get_session().omcpath(resultfile) logger.info(f"[Worker {worker_id}] Performing task: {resultpath.name}") try: - returncode = self.session().run_model_executable(cmd_run_data=cmd_definition) + returncode = self.get_session().run_model_executable(cmd_run_data=cmd_definition) logger.info(f"[Worker {worker_id}] Simulation {resultpath.name} " f"finished with return code: {returncode}") except ModelicaSystemError as ex: diff --git a/OMPython/OMCSession.py b/OMPython/OMCSession.py index ee92ce9f..a60631e4 100644 --- a/OMPython/OMCSession.py +++ b/OMPython/OMCSession.py @@ -99,9 +99,9 @@ class OMCSessionCmd: Implementation of Open Modelica Compiler API functions. Depreciated! """ - def __init__(self, session: OMCSessionZMQ, readonly: bool = False): - if not isinstance(session, OMCSessionZMQ): - raise OMCSessionException("Invalid session definition!") + def __init__(self, session: OMCSession, readonly: bool = False): + if not isinstance(session, OMCSession): + raise OMCSessionException("Invalid OMC process definition!") self._session = session self._readonly = readonly self._omc_cache: dict[tuple[str, bool], Any] = {} @@ -286,14 +286,14 @@ def getClassNames(self, className=None, recursive=False, qualified=False, sort=F class OMCPathReal(pathlib.PurePosixPath): """ - Implementation of a basic (PurePosix)Path object which uses OMC as backend. The connection to OMC is provided via a - OMCSessionZMQ session object. + Implementation of a basic (PurePosix)Path object which uses OMC as backend. The connection to OMC is provided via an + instances of OMCSession* classes. PurePosixPath is selected to cover usage of OMC in docker or via WSL. Usage of specialised function could result in errors as well as usage on a Windows system due to slightly different definitions (PureWindowsPath). """ - def __init__(self, *path, session: OMCProcess) -> None: + def __init__(self, *path, session: OMCSession) -> None: super().__init__(*path) self._session = session @@ -301,7 +301,7 @@ def with_segments(self, *pathsegments): """ Create a new OMCPath object with the given path segments. - The original definition of Path is overridden to ensure session is set. + The original definition of Path is overridden to ensure the OMC session is set. """ return type(self)(*pathsegments, session=self._session) @@ -322,7 +322,7 @@ def is_absolute(self): Check if the path is an absolute path considering the possibility that we are running locally on Windows. This case needs special handling as the definition of is_absolute() differs. """ - if isinstance(self._session, OMCProcessLocal) and platform.system() == 'Windows': + if isinstance(self._session, OMCSessionLocal) and platform.system() == 'Windows': return pathlib.PureWindowsPath(self.as_posix()).is_absolute() return super().is_absolute() @@ -539,14 +539,14 @@ def get_cmd(self) -> list[str]: class OMCSessionZMQ: """ - This class is handling an OMC session. It is a compatibility class for the new schema using OMCProcess* classes. + This class is a compatibility layer for the new schema using OMCSession* classes. """ def __init__( self, timeout: float = 10.00, omhome: Optional[str] = None, - omc_process: Optional[OMCProcess] = None, + omc_process: Optional[OMCSession] = None, ) -> None: """ Initialisation for OMCSessionZMQ @@ -557,8 +557,8 @@ def __init__( stacklevel=2) if omc_process is None: - omc_process = OMCProcessLocal(omhome=omhome, timeout=timeout) - elif not isinstance(omc_process, OMCProcess): + omc_process = OMCSessionLocal(omhome=omhome, timeout=timeout) + elif not isinstance(omc_process, OMCSession): raise OMCSessionException("Invalid definition of the OMC process!") self.omc_process = omc_process @@ -570,11 +570,11 @@ def escape_str(value: str) -> str: """ Escape a string such that it can be used as string within OMC expressions, i.e. escape all double quotes. """ - return OMCProcess.escape_str(value=value) + return OMCSession.escape_str(value=value) def omcpath(self, *path) -> OMCPath: """ - Create an OMCPath object based on the given path segments and the current OMC session. + Create an OMCPath object based on the given path segments and the current OMC process definition. """ return self.omc_process.omcpath(*path) @@ -599,7 +599,7 @@ def run_model_executable(cmd_run_data: OMCSessionRunData) -> int: Run the command defined in cmd_run_data. This class is defined as static method such that there is no need to keep instances of over classes around. """ - return OMCProcess.run_model_executable(cmd_run_data=cmd_run_data) + return OMCSession.run_model_executable(cmd_run_data=cmd_run_data) def execute(self, command: str): return self.omc_process.execute(command=command) @@ -641,7 +641,7 @@ def __call__(cls, *args, **kwargs): return obj -class OMCProcessMeta(abc.ABCMeta, PostInitCaller): +class OMCSessionMeta(abc.ABCMeta, PostInitCaller): """ Helper class to get a combined metaclass of ABCMeta and PostInitCaller. @@ -650,25 +650,24 @@ class OMCProcessMeta(abc.ABCMeta, PostInitCaller): """ -class OMCProcess(metaclass=OMCProcessMeta): +class OMCSession(metaclass=OMCSessionMeta): """ - Base class for an OMC session. This class contains common functionality for all OMC sessions. + Base class for an OMC session started via ZMQ. This class contains common functionality for all variants of an + OMC session definition. The main method is sendExpression() which is used to send commands to the OMC process. - The class expects an OMCProcess* on initialisation. It defines the type of OMC process to use: + The following variants are defined: - * OMCProcessLocal + * OMCSessionLocal - * OMCProcessPort + * OMCSessionPort - * OMCProcessDocker + * OMCSessionDocker - * OMCProcessDockerContainer + * OMCSessionDockerContainer - * OMCProcessWSL - - If no OMC process is defined, a local OMC process is initialized. + * OMCSessionWSL """ def __init__( @@ -677,12 +676,12 @@ def __init__( **kwargs, ) -> None: """ - Initialisation for OMCProcess + Initialisation for OMCSession """ # store variables self._timeout = timeout - # generate a random string for this session + # generate a random string for this instance of OMC self._random_string = uuid.uuid4().hex # get a temporary directory self._temp_dir = pathlib.Path(tempfile.gettempdir()) @@ -766,15 +765,15 @@ def escape_str(value: str) -> str: def omcpath(self, *path) -> OMCPath: """ - Create an OMCPath object based on the given path segments and the current OMC session. + Create an OMCPath object based on the given path segments and the current OMCSession* class. """ # fallback solution for Python < 3.12; a modified pathlib.Path object is used as OMCPath replacement if sys.version_info < (3, 12): - if isinstance(self, OMCProcessLocal): + if isinstance(self, OMCSessionLocal): # noinspection PyArgumentList return OMCPath(*path) - raise OMCSessionException("OMCPath is supported for Python < 3.12 only if OMCProcessLocal is used!") + raise OMCSessionException("OMCPath is supported for Python < 3.12 only if OMCSessionLocal is used!") return OMCPath(*path, session=self) def omcpath_tempdir(self, tempdir_base: Optional[OMCPath] = None) -> OMCPath: @@ -868,7 +867,7 @@ def sendExpression(self, command: str, parsed: bool = True) -> Any: timeout = 1.0 if self._omc_zmq is None: - raise OMCSessionException("No OMC running. Please create a new instance of OMCProcess!") + raise OMCSessionException("No OMC running. Please create a new instance of OMCSession!") logger.debug("sendExpression(%r, parsed=%r)", command, parsed) @@ -998,7 +997,7 @@ def sendExpression(self, command: str, parsed: bool = True) -> Any: def get_port(self) -> Optional[str]: """ - Get the port to connect to the OMC process. + Get the port to connect to the OMC session. """ if not isinstance(self._omc_port, str): raise OMCSessionException(f"Invalid port to connect to OMC process: {self._omc_port}") @@ -1030,7 +1029,7 @@ def _get_portfile_path(self) -> Optional[pathlib.Path]: @abc.abstractmethod def omc_run_data_update(self, omc_run_data: OMCSessionRunData) -> OMCSessionRunData: """ - Update the OMCSessionRunData object based on the selected OMCProcess implementation. + Update the OMCSessionRunData object based on the selected OMCSession implementation. The main point is the definition of OMCSessionRunData.cmd_model_executable which contains the specific command to run depending on the selected system. @@ -1040,9 +1039,9 @@ def omc_run_data_update(self, omc_run_data: OMCSessionRunData) -> OMCSessionRunD raise NotImplementedError("This method must be implemented in subclasses!") -class OMCProcessPort(OMCProcess): +class OMCSessionPort(OMCSession): """ - OMCProcess implementation which uses a port to connect to an already running OMC server. + OMCSession implementation which uses a port to connect to an already running OMC server. """ def __init__( @@ -1054,14 +1053,14 @@ def __init__( def omc_run_data_update(self, omc_run_data: OMCSessionRunData) -> OMCSessionRunData: """ - Update the OMCSessionRunData object based on the selected OMCProcess implementation. + Update the OMCSessionRunData object based on the selected OMCSession implementation. """ - raise OMCSessionException("OMCProcessPort does not support omc_run_data_update()!") + raise OMCSessionException("OMCSessionPort does not support omc_run_data_update()!") -class OMCProcessLocal(OMCProcess): +class OMCSessionLocal(OMCSession): """ - OMCProcess implementation which runs the OMC server locally on the machine (Linux / Windows). + OMCSession implementation which runs the OMC server locally on the machine (Linux / Windows). """ def __init__( @@ -1144,7 +1143,7 @@ def _omc_port_get(self) -> str: def omc_run_data_update(self, omc_run_data: OMCSessionRunData) -> OMCSessionRunData: """ - Update the OMCSessionRunData object based on the selected OMCProcess implementation. + Update the OMCSessionRunData object based on the selected OMCSession implementation. """ # create a copy of the data omc_run_data_copy = dataclasses.replace(omc_run_data) @@ -1185,9 +1184,9 @@ def omc_run_data_update(self, omc_run_data: OMCSessionRunData) -> OMCSessionRunD return omc_run_data_copy -class OMCProcessDockerHelper(OMCProcess): +class OMCSessionDockerHelper(OMCSession): """ - Base class for OMCProcess implementations which run the OMC server in a Docker container. + Base class for OMCSession implementations which run the OMC server in a Docker container. """ def __init__( @@ -1301,7 +1300,7 @@ def get_docker_container_id(self) -> str: def omc_run_data_update(self, omc_run_data: OMCSessionRunData) -> OMCSessionRunData: """ - Update the OMCSessionRunData object based on the selected OMCProcess implementation. + Update the OMCSessionRunData object based on the selected OMCSession implementation. """ omc_run_data_copy = dataclasses.replace(omc_run_data) @@ -1322,7 +1321,7 @@ def omc_run_data_update(self, omc_run_data: OMCSessionRunData) -> OMCSessionRunD return omc_run_data_copy -class OMCProcessDocker(OMCProcessDockerHelper): +class OMCSessionDocker(OMCSessionDockerHelper): """ OMC process running in a Docker container. """ @@ -1465,7 +1464,7 @@ def _docker_omc_start(self) -> Tuple[subprocess.Popen, DockerPopen, str]: return omc_process, docker_process, docker_cid -class OMCProcessDockerContainer(OMCProcessDockerHelper): +class OMCSessionDockerContainer(OMCSessionDockerHelper): """ OMC process running in a Docker container (by container ID). """ @@ -1558,7 +1557,7 @@ def _docker_omc_start(self) -> Tuple[subprocess.Popen, DockerPopen]: return omc_process, docker_process -class OMCProcessWSL(OMCProcess): +class OMCSessionWSL(OMCSession): """ OMC process running in Windows Subsystem for Linux (WSL). """ @@ -1646,7 +1645,7 @@ def _omc_port_get(self) -> str: def omc_run_data_update(self, omc_run_data: OMCSessionRunData) -> OMCSessionRunData: """ - Update the OMCSessionRunData object based on the selected OMCProcess implementation. + Update the OMCSessionRunData object based on the selected OMCSession implementation. """ omc_run_data_copy = dataclasses.replace(omc_run_data) diff --git a/OMPython/__init__.py b/OMPython/__init__.py index 7d571a9b..8831e57a 100644 --- a/OMPython/__init__.py +++ b/OMPython/__init__.py @@ -48,11 +48,11 @@ OMCSessionException, OMCSessionRunData, OMCSessionZMQ, - OMCProcessPort, - OMCProcessLocal, - OMCProcessDocker, - OMCProcessDockerContainer, - OMCProcessWSL, + OMCSessionPort, + OMCSessionLocal, + OMCSessionDocker, + OMCSessionDockerContainer, + OMCSessionWSL, ) # global names imported if import 'from OMPython import *' is used @@ -67,9 +67,9 @@ 'OMCSessionException', 'OMCSessionRunData', 'OMCSessionZMQ', - 'OMCProcessPort', - 'OMCProcessLocal', - 'OMCProcessDocker', - 'OMCProcessDockerContainer', - 'OMCProcessWSL', + 'OMCSessionPort', + 'OMCSessionLocal', + 'OMCSessionDocker', + 'OMCSessionDockerContainer', + 'OMCSessionWSL', ] diff --git a/tests/test_ArrayDimension.py b/tests/test_ArrayDimension.py index 13b3c11b..6e80d53f 100644 --- a/tests/test_ArrayDimension.py +++ b/tests/test_ArrayDimension.py @@ -2,18 +2,18 @@ def test_ArrayDimension(tmp_path): - omc = OMPython.OMCSessionZMQ() + omcs = OMPython.OMCSessionLocal() - omc.sendExpression(f'cd("{tmp_path.as_posix()}")') + omcs.sendExpression(f'cd("{tmp_path.as_posix()}")') - omc.sendExpression('loadString("model A Integer x[5+1,1+6]; end A;")') - omc.sendExpression("getErrorString()") + omcs.sendExpression('loadString("model A Integer x[5+1,1+6]; end A;")') + omcs.sendExpression("getErrorString()") - result = omc.sendExpression("getComponents(A)") + result = omcs.sendExpression("getComponents(A)") assert result[0][-1] == (6, 7), "array dimension does not match" - omc.sendExpression('loadString("model A Integer y = 5; Integer x[y+1,1+9]; end A;")') - omc.sendExpression("getErrorString()") + omcs.sendExpression('loadString("model A Integer y = 5; Integer x[y+1,1+9]; end A;")') + omcs.sendExpression("getErrorString()") - result = omc.sendExpression("getComponents(A)") + result = omcs.sendExpression("getComponents(A)") assert result[-1][-1] == ('y+1', 10), "array dimension does not match" diff --git a/tests/test_FMIRegression.py b/tests/test_FMIRegression.py index b61b8d49..8a91c514 100644 --- a/tests/test_FMIRegression.py +++ b/tests/test_FMIRegression.py @@ -7,21 +7,21 @@ def buildModelFMU(modelName): - omc = OMPython.OMCSessionZMQ() + omcs = OMPython.OMCSessionLocal() tempdir = pathlib.Path(tempfile.mkdtemp()) try: - omc.sendExpression(f'cd("{tempdir.as_posix()}")') + omcs.sendExpression(f'cd("{tempdir.as_posix()}")') - omc.sendExpression("loadModel(Modelica)") - omc.sendExpression("getErrorString()") + omcs.sendExpression("loadModel(Modelica)") + omcs.sendExpression("getErrorString()") fileNamePrefix = modelName.split(".")[-1] exp = f'buildModelFMU({modelName}, fileNamePrefix="{fileNamePrefix}")' - fmu = omc.sendExpression(exp) + fmu = omcs.sendExpression(exp) assert os.path.exists(fmu) finally: - del omc + del omcs shutil.rmtree(tempdir, ignore_errors=True) diff --git a/tests/test_ModelicaSystem.py b/tests/test_ModelicaSystem.py index 8567c426..dd0321ec 100644 --- a/tests/test_ModelicaSystem.py +++ b/tests/test_ModelicaSystem.py @@ -47,14 +47,15 @@ def worker(): ) mod.simulate() mod.convertMo2Fmu(fmuType="me") + for _ in range(10): worker() def test_setParameters(): - omc = OMPython.OMCSessionZMQ() - model_path_str = omc.sendExpression("getInstallationDirectoryPath()") + "/share/doc/omc/testmodels" - model_path = omc.omcpath(model_path_str) + omcs = OMPython.OMCSessionLocal() + model_path_str = omcs.sendExpression("getInstallationDirectoryPath()") + "/share/doc/omc/testmodels" + model_path = omcs.omcpath(model_path_str) mod = OMPython.ModelicaSystem() mod.model( model_file=model_path / "BouncingBall.mo", @@ -87,9 +88,9 @@ def test_setParameters(): def test_setSimulationOptions(): - omc = OMPython.OMCSessionZMQ() - model_path_str = omc.sendExpression("getInstallationDirectoryPath()") + "/share/doc/omc/testmodels" - model_path = omc.omcpath(model_path_str) + omcs = OMPython.OMCSessionLocal() + model_path_str = omcs.sendExpression("getInstallationDirectoryPath()") + "/share/doc/omc/testmodels" + model_path = omcs.omcpath(model_path_str) mod = OMPython.ModelicaSystem() mod.model( model_file=model_path / "BouncingBall.mo", @@ -155,11 +156,9 @@ def test_customBuildDirectory(tmp_path, model_firstorder): @skip_on_windows @skip_python_older_312 def test_getSolutions_docker(model_firstorder): - omcp = OMPython.OMCProcessDocker(docker="openmodelica/openmodelica:v1.25.0-minimal") - omc = OMPython.OMCSessionZMQ(omc_process=omcp) - + omcs = OMPython.OMCSessionDocker(docker="openmodelica/openmodelica:v1.25.0-minimal") mod = OMPython.ModelicaSystem( - omc_process=omc.omc_process, + session=omcs, ) mod.model( model_file=model_firstorder, diff --git a/tests/test_ModelicaSystemCmd.py b/tests/test_ModelicaSystemCmd.py index 7eaf08ba..2480aad9 100644 --- a/tests/test_ModelicaSystemCmd.py +++ b/tests/test_ModelicaSystemCmd.py @@ -24,7 +24,7 @@ def mscmd_firstorder(model_firstorder): model_name="M", ) mscmd = OMPython.ModelicaSystemCmd( - session=mod.session(), + session=mod.get_session(), runpath=mod.getWorkDirectory(), modelname=mod._model_name, ) diff --git a/tests/test_ModelicaSystemDoE.py b/tests/test_ModelicaSystemDoE.py index f9d70011..0e8d6caa 100644 --- a/tests/test_ModelicaSystemDoE.py +++ b/tests/test_ModelicaSystemDoE.py @@ -69,15 +69,14 @@ def test_ModelicaSystemDoE_local(tmp_path, model_doe, param_doe): @skip_on_windows @skip_python_older_312 def test_ModelicaSystemDoE_docker(tmp_path, model_doe, param_doe): - omcp = OMPython.OMCProcessDocker(docker="openmodelica/openmodelica:v1.25.0-minimal") - omc = OMPython.OMCSessionZMQ(omc_process=omcp) - assert omc.sendExpression("getVersion()") == "OpenModelica 1.25.0" + omcs = OMPython.OMCSessionDocker(docker="openmodelica/openmodelica:v1.25.0-minimal") + assert omcs.sendExpression("getVersion()") == "OpenModelica 1.25.0" doe_mod = OMPython.ModelicaSystemDoE( model_file=model_doe, model_name="M", parameters=param_doe, - omc_process=omcp, + session=omcs, simargs={"override": {'stopTime': 1.0}}, ) diff --git a/tests/test_OMCPath.py b/tests/test_OMCPath.py index 4a053287..2ea8b8c8 100644 --- a/tests/test_OMCPath.py +++ b/tests/test_OMCPath.py @@ -15,54 +15,41 @@ ) -def test_OMCPath_OMCSessionZMQ(): - om = OMPython.OMCSessionZMQ() - - _run_OMCPath_checks(om) - - del om - - def test_OMCPath_OMCProcessLocal(): - omp = OMPython.OMCProcessLocal() - om = OMPython.OMCSessionZMQ(omc_process=omp) + omcs = OMPython.OMCSessionLocal() - _run_OMCPath_checks(om) + _run_OMCPath_checks(omcs) - del om + del omcs @skip_on_windows @skip_python_older_312 def test_OMCPath_OMCProcessDocker(): - omcp = OMPython.OMCProcessDocker(docker="openmodelica/openmodelica:v1.25.0-minimal") - om = OMPython.OMCSessionZMQ(omc_process=omcp) - assert om.sendExpression("getVersion()") == "OpenModelica 1.25.0" + omcs = OMPython.OMCSessionDocker(docker="openmodelica/openmodelica:v1.25.0-minimal") + assert omcs.sendExpression("getVersion()") == "OpenModelica 1.25.0" - _run_OMCPath_checks(om) + _run_OMCPath_checks(omcs) - del omcp - del om + del omcs @pytest.mark.skip(reason="Not able to run WSL on github") @skip_python_older_312 def test_OMCPath_OMCProcessWSL(): - omcp = OMPython.OMCProcessWSL( + omcs = OMPython.OMCSessionWSL( wsl_omc='omc', wsl_user='omc', timeout=30.0, ) - om = OMPython.OMCSessionZMQ(omc_process=omcp) - _run_OMCPath_checks(om) + _run_OMCPath_checks(omcs) - del omcp - del om + del omcs -def _run_OMCPath_checks(om: OMPython.OMCSessionZMQ): - p1 = om.omcpath_tempdir() +def _run_OMCPath_checks(omcs: OMPython.OMCSession): + p1 = omcs.omcpath_tempdir() p2 = p1 / 'test' p2.mkdir() assert p2.is_dir() @@ -81,14 +68,14 @@ def _run_OMCPath_checks(om: OMPython.OMCSessionZMQ): def test_OMCPath_write_file(tmpdir): - om = OMPython.OMCSessionZMQ() + omcs = OMPython.OMCSessionLocal() data = "abc # \\t # \" # \\n # xyz" - p1 = om.omcpath_tempdir() + p1 = omcs.omcpath_tempdir() p2 = p1 / 'test.txt' p2.write_text(data=data) assert data == p2.read_text() - del om + del omcs diff --git a/tests/test_OMSessionCmd.py b/tests/test_OMSessionCmd.py index be02136a..d3997ecf 100644 --- a/tests/test_OMSessionCmd.py +++ b/tests/test_OMSessionCmd.py @@ -2,8 +2,8 @@ def test_isPackage(): - omczmq = OMPython.OMCSessionZMQ() - omccmd = OMPython.OMCSessionCmd(session=omczmq) + omcs = OMPython.OMCSessionLocal() + omccmd = OMPython.OMCSessionCmd(session=omcs) assert not omccmd.isPackage('Modelica') @@ -13,7 +13,7 @@ def test_isPackage2(): model_name="Modelica.Electrical.Analog.Examples.CauerLowPassAnalog", libraries=["Modelica"], ) - omccmd = OMPython.OMCSessionCmd(session=mod.session()) + omccmd = OMPython.OMCSessionCmd(session=mod.get_session()) assert omccmd.isPackage('Modelica') diff --git a/tests/test_ZMQ.py b/tests/test_ZMQ.py index 45d517cd..1302a79d 100644 --- a/tests/test_ZMQ.py +++ b/tests/test_ZMQ.py @@ -14,58 +14,55 @@ def model_time_str(): @pytest.fixture -def om(tmp_path): +def omcs(tmp_path): origDir = pathlib.Path.cwd() os.chdir(tmp_path) - om = OMPython.OMCSessionZMQ() + omcs = OMPython.OMCSessionLocal() os.chdir(origDir) - return om + return omcs -def testHelloWorld(om): - assert om.sendExpression('"HelloWorld!"') == "HelloWorld!" +def testHelloWorld(omcs): + assert omcs.sendExpression('"HelloWorld!"') == "HelloWorld!" -def test_Translate(om, model_time_str): - assert om.sendExpression(model_time_str) == ("M",) - assert om.sendExpression('translateModel(M)') is True +def test_Translate(omcs, model_time_str): + assert omcs.sendExpression(model_time_str) == ("M",) + assert omcs.sendExpression('translateModel(M)') is True -def test_Simulate(om, model_time_str): - assert om.sendExpression(f'loadString("{model_time_str}")') is True - om.sendExpression('res:=simulate(M, stopTime=2.0)') - assert om.sendExpression('res.resultFile') +def test_Simulate(omcs, model_time_str): + assert omcs.sendExpression(f'loadString("{model_time_str}")') is True + omcs.sendExpression('res:=simulate(M, stopTime=2.0)') + assert omcs.sendExpression('res.resultFile') -def test_execute(om): +def test_execute(omcs): with pytest.deprecated_call(): - assert om.execute('"HelloWorld!"') == '"HelloWorld!"\n' - assert om.sendExpression('"HelloWorld!"', parsed=False) == '"HelloWorld!"\n' - assert om.sendExpression('"HelloWorld!"', parsed=True) == 'HelloWorld!' + assert omcs.execute('"HelloWorld!"') == '"HelloWorld!"\n' + assert omcs.sendExpression('"HelloWorld!"', parsed=False) == '"HelloWorld!"\n' + assert omcs.sendExpression('"HelloWorld!"', parsed=True) == 'HelloWorld!' -def test_omcprocessport_execute(om): - port = om.omc_process.get_port() - omcp = OMPython.OMCProcessPort(omc_port=port) +def test_omcprocessport_execute(omcs): + port = omcs.get_port() + omcs2 = OMPython.OMCSessionPort(omc_port=port) # run 1 - om1 = OMPython.OMCSessionZMQ(omc_process=omcp) - assert om1.sendExpression('"HelloWorld!"', parsed=False) == '"HelloWorld!"\n' + assert omcs.sendExpression('"HelloWorld!"', parsed=False) == '"HelloWorld!"\n' # run 2 - om2 = OMPython.OMCSessionZMQ(omc_process=omcp) - assert om2.sendExpression('"HelloWorld!"', parsed=False) == '"HelloWorld!"\n' + assert omcs2.sendExpression('"HelloWorld!"', parsed=False) == '"HelloWorld!"\n' - del om1 - del om2 + del omcs2 -def test_omcprocessport_simulate(om, model_time_str): - port = om.omc_process.get_port() - omcp = OMPython.OMCProcessPort(omc_port=port) +def test_omcprocessport_simulate(omcs, model_time_str): + port = omcs.get_port() + omcs2 = OMPython.OMCSessionPort(omc_port=port) - om = OMPython.OMCSessionZMQ(omc_process=omcp) - assert om.sendExpression(f'loadString("{model_time_str}")') is True - om.sendExpression('res:=simulate(M, stopTime=2.0)') - assert om.sendExpression('res.resultFile') != "" - del om + assert omcs2.sendExpression(f'loadString("{model_time_str}")') is True + omcs2.sendExpression('res:=simulate(M, stopTime=2.0)') + assert omcs2.sendExpression('res.resultFile') != "" + + del omcs2 diff --git a/tests/test_docker.py b/tests/test_docker.py index 8d68f11f..f1973599 100644 --- a/tests/test_docker.py +++ b/tests/test_docker.py @@ -10,23 +10,17 @@ @skip_on_windows def test_docker(): - omcp = OMPython.OMCProcessDocker(docker="openmodelica/openmodelica:v1.25.0-minimal") - om = OMPython.OMCSessionZMQ(omc_process=omcp) - assert om.sendExpression("getVersion()") == "OpenModelica 1.25.0" + omcs = OMPython.OMCSessionDocker(docker="openmodelica/openmodelica:v1.25.0-minimal") + assert omcs.sendExpression("getVersion()") == "OpenModelica 1.25.0" - omcpInner = OMPython.OMCProcessDockerContainer(dockerContainer=omcp.get_docker_container_id()) - omInner = OMPython.OMCSessionZMQ(omc_process=omcpInner) - assert omInner.sendExpression("getVersion()") == "OpenModelica 1.25.0" + omcsInner = OMPython.OMCSessionDockerContainer(dockerContainer=omcs.get_docker_container_id()) + assert omcsInner.sendExpression("getVersion()") == "OpenModelica 1.25.0" - omcp2 = OMPython.OMCProcessDocker(docker="openmodelica/openmodelica:v1.25.0-minimal", port=11111) - om2 = OMPython.OMCSessionZMQ(omc_process=omcp2) - assert om2.sendExpression("getVersion()") == "OpenModelica 1.25.0" + omcs2 = OMPython.OMCSessionDocker(docker="openmodelica/openmodelica:v1.25.0-minimal", port=11111) + assert omcs2.sendExpression("getVersion()") == "OpenModelica 1.25.0" - del omcp2 - del om2 + del omcs2 - del omcpInner - del omInner + del omcsInner - del omcp - del om + del omcs diff --git a/tests/test_optimization.py b/tests/test_optimization.py index be6945f3..d7494281 100644 --- a/tests/test_optimization.py +++ b/tests/test_optimization.py @@ -56,7 +56,7 @@ def test_optimization_example(tmp_path): r = mod.optimize() # it is necessary to specify resultfile, otherwise it wouldn't find it. resultfile_str = r["resultFile"] - resultfile_omcpath = mod.session().omcpath(resultfile_str) + resultfile_omcpath = mod.get_session().omcpath(resultfile_str) time, f, v = mod.getSolutions( varList=["time", "f", "v"], resultfile=resultfile_omcpath,