|
| 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