Skip to content

Commit b2406b8

Browse files
committed
Adds feature to use shared matlab for MatlabWrapper
1 parent af8a86a commit b2406b8

File tree

2 files changed

+31
-6
lines changed

2 files changed

+31
-6
lines changed

ratapi/inputs.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
import numpy as np
99

1010
import ratapi
11-
import ratapi.controls
1211
import ratapi.wrappers
1312
from ratapi.rat_core import Checks, Control, NameStore, ProblemDefinition
1413
from ratapi.utils.enums import Calculations, Languages, LayerModels, TypeOptions

ratapi/wrappers.py

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Wrappers for the interface between ratapi and MATLAB custom files."""
22

3+
import os
34
import pathlib
45
from contextlib import suppress
56
from typing import Callable
@@ -20,10 +21,10 @@ def start_matlab():
2021
2122
"""
2223
future = None
23-
with suppress(ImportError):
24-
import matlab.engine
25-
26-
future = matlab.engine.start_matlab(background=True)
24+
if os.environ.get("DELAY_MATLAB_START", '0') == '0':
25+
with suppress(ImportError):
26+
import matlab.engine
27+
future = matlab.engine.start_matlab(background=True)
2728

2829
return future
2930

@@ -39,10 +40,11 @@ class MatlabWrapper:
3940
"""
4041

4142
loader = start_matlab()
43+
loader_error_message = "matlabengine is required to use MatlabWrapper"
4244

4345
def __init__(self, filename: str) -> None:
4446
if self.loader is None:
45-
raise ImportError("matlabengine is required to use MatlabWrapper") from None
47+
raise ImportError(self.loader_error_message) from None
4648

4749
self.engine = self.loader.result()
4850
path = pathlib.Path(filename)
@@ -86,6 +88,30 @@ def handle(*args):
8688
return handle
8789

8890

91+
def use_shared_matlab(name, custom_error_message):
92+
"""Connect asynchronously to shared MATLAB engine instance with the given name.
93+
94+
Parameters
95+
----------
96+
name : str
97+
The name of shared MATLAB engine instance
98+
custom_error_message : str
99+
The custom error message in case of failed connection
100+
101+
Returns
102+
-------
103+
future : matlab.engine.futureresult.FutureResult
104+
A future used to get the actual matlab engine.
105+
106+
"""
107+
with suppress(ImportError):
108+
import matlab.engine
109+
110+
MatlabWrapper.loader = matlab.engine.connect_matlab(name, background=True)
111+
MatlabWrapper.loader_error_message = custom_error_message
112+
return MatlabWrapper.loader
113+
114+
89115
class DylibWrapper:
90116
"""Creates a python callback for a function in dynamic library.
91117

0 commit comments

Comments
 (0)