|
| 1 | +import os |
| 2 | +from typing import Union |
| 3 | +from pathlib import Path |
| 4 | +from textwrap import dedent |
| 5 | +from datetime import datetime |
| 6 | + |
| 7 | + |
| 8 | +class EXTRACT_trigger: |
| 9 | + m_template = dedent( |
| 10 | + """ |
| 11 | + % Load Data |
| 12 | + data = load('{scanfile}'); |
| 13 | + M = data.M; |
| 14 | + |
| 15 | + % Input Paramaters |
| 16 | + config = struct(); |
| 17 | + {parameters_list_string} |
| 18 | + |
| 19 | + % Run EXTRACT |
| 20 | + output = extractor(M, config); |
| 21 | + save('{output_fullpath}', 'output'); |
| 22 | + """ |
| 23 | + ) |
| 24 | + |
| 25 | + def __init__( |
| 26 | + self, |
| 27 | + scanfile: Union[str, Path], |
| 28 | + parameters: dict, |
| 29 | + output_dir: Union[str, Path], |
| 30 | + ) -> None: |
| 31 | + """A helper class to trigger EXTRACT analysis in element-calcium-imaging. |
| 32 | +
|
| 33 | + Args: |
| 34 | + scanfile (Union[str, Path]): Full path of the scan |
| 35 | + parameters (dict): EXTRACT input paramaters. |
| 36 | + output_dir (Union[str, Path]): Directory to store the outputs of EXTRACT analysis. |
| 37 | + """ |
| 38 | + assert isinstance(parameters, dict) |
| 39 | + |
| 40 | + self.scanfile = Path(scanfile) |
| 41 | + self.output_dir = Path(output_dir) |
| 42 | + self.parameters = parameters |
| 43 | + |
| 44 | + def write_matlab_run_script(self): |
| 45 | + """Compose a matlab script and save it with the name run_extract.m. |
| 46 | +
|
| 47 | + The composed script is basically the formatted version of the m_template attribute.""" |
| 48 | + |
| 49 | + self.output_fullpath = ( |
| 50 | + self.output_dir / f"{self.scanfile.stem}_extract_output.mat" |
| 51 | + ) |
| 52 | + |
| 53 | + m_file_content = self.m_template.format( |
| 54 | + **dict( |
| 55 | + parameters_list_string="\n".join( |
| 56 | + [ |
| 57 | + f"config.{k} = '{v}';" |
| 58 | + if isinstance(v, str) |
| 59 | + else f"config.{k} = {str(v).lower()};" |
| 60 | + if isinstance(v, bool) |
| 61 | + else f"config.{k} = {v};" |
| 62 | + for k, v in self.parameters.items() |
| 63 | + ] |
| 64 | + ), |
| 65 | + scanfile=self.scanfile.as_posix(), |
| 66 | + output_fullpath=self.output_fullpath.as_posix(), |
| 67 | + ) |
| 68 | + ).lstrip() |
| 69 | + |
| 70 | + self.m_file_fp = self.output_dir / "run_extract.m" |
| 71 | + |
| 72 | + with open(self.m_file_fp, "w") as f: |
| 73 | + f.write(m_file_content) |
| 74 | + |
| 75 | + def run(self): |
| 76 | + """Run the matlab run_extract.m script.""" |
| 77 | + |
| 78 | + self.write_matlab_run_script() |
| 79 | + |
| 80 | + current_dir = Path.cwd() |
| 81 | + os.chdir(self.output_dir) |
| 82 | + |
| 83 | + try: |
| 84 | + import matlab.engine |
| 85 | + |
| 86 | + eng = matlab.engine.start_matlab() |
| 87 | + eng.run_extract() |
| 88 | + except Exception as e: |
| 89 | + raise e |
| 90 | + finally: |
| 91 | + os.chdir(current_dir) |
0 commit comments