Skip to content

Commit 3a4b922

Browse files
committed
Add function to run directly from MATLAB API
1 parent f405135 commit 3a4b922

2 files changed

Lines changed: 69 additions & 1 deletion

File tree

ratapi/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from ratapi.outputs import BayesResults, Results
1010
from ratapi.project import Project
1111
from ratapi.run import run
12-
from ratapi.utils import convert, plotting
12+
from ratapi.utils import convert, matlab, plotting
1313

1414
with suppress(ImportError): # orsopy is an optional dependency
1515
from ratapi.utils import orso as orso
@@ -26,4 +26,5 @@
2626
"run",
2727
"plotting",
2828
"convert",
29+
"matlab",
2930
]

ratapi/utils/matlab.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
"""Runs RAT from the MATLAB API."""
2+
3+
import os
4+
import tempfile
5+
import warnings
6+
from pathlib import Path
7+
8+
from ..outputs import Results
9+
from ..project import Project
10+
from ..wrappers import MatlabWrapper
11+
12+
RUNNER = """function executeRAT()
13+
project = jsonToProject('{project}');
14+
controls = jsonToControls('{control}');
15+
[project, results] = RAT(project, controls);
16+
17+
projectToJson(project, '{project}');
18+
resultsToJson(results, '{result}');
19+
end
20+
"""
21+
22+
23+
def run_matlab_directly(project, controls, matlab_rat_path):
24+
"""Run User provided MATLAB RAT for the given project and controls inputs.
25+
26+
Parameters
27+
----------
28+
project : RAT.Project
29+
The project model, which defines the physical system under study.
30+
controls : RAT.Controls
31+
The controls model, which defines algorithmic properties.
32+
matlab_rat_path : str
33+
The path to MATLAB RAT folder.
34+
"""
35+
if MatlabWrapper.loader is None:
36+
raise ImportError(MatlabWrapper.loader_error_message) from None
37+
38+
engine = MatlabWrapper.loader.result()
39+
cur_dir = os.getcwd()
40+
41+
with tempfile.TemporaryDirectory() as tmp:
42+
project_file = Path(tmp, "project.json")
43+
control_file = Path(tmp, "controls.json")
44+
result_file = Path(tmp, "results.json")
45+
runner_file = Path(tmp, "executeRAT.m")
46+
47+
with open(runner_file, "w") as f:
48+
f.write(RUNNER.format(project=project_file, control=control_file, result=result_file))
49+
50+
with warnings.catch_warnings(): # Avoid warning about relative paths
51+
warnings.simplefilter("ignore")
52+
project.save(project_file)
53+
controls.save(control_file)
54+
55+
engine.cd(matlab_rat_path, nargout=0)
56+
engine.eval("addPaths", nargout=0)
57+
engine.cd(cur_dir, nargout=0)
58+
59+
engine.addpath(tmp, nargout=0)
60+
for file in project.custom_files:
61+
engine.addpath(str(file.path), nargout=0)
62+
63+
engine.executeRAT(nargout=0)
64+
65+
project = Project.load(project_file)
66+
results = Results.load(result_file)
67+
return project, results

0 commit comments

Comments
 (0)