-
Notifications
You must be signed in to change notification settings - Fork 17
Loader and Trigger for EXTRACT #65
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
358c0d6
add extract_utils.py for EXTRACT
tdincer c3cd4b2
Merge branch 'main' of https://github.com/tdincer/element-interface
tdincer 210bd9a
Merge branch 'datajoint:main' into main
tdincer 87afa22
add docstring
tdincer 74c2781
Merge branch 'main' of https://github.com/tdincer/element-interface
tdincer 99c4fb8
fix ugly template style
tdincer 4fd50a7
remove return run_status
tdincer 6ebf019
switch from write to save
tdincer 04b8f69
add loader and trigger
tdincer e8d5b0a
update changelog
tdincer 7cffc25
add creation_time
tdincer d2eb1e8
Update element_interface/extract_loader.py
tdincer 2ab366d
Update element_interface/extract_loader.py
tdincer e3ff2ad
Update element_interface/extract_loader.py
tdincer c18aa11
Update element_interface/extract_loader.py
tdincer e5ed418
Update element_interface/extract_trigger.py
tdincer d93c2de
Update element_interface/extract_loader.py
tdincer 3517d13
Update element_interface/extract_loader.py
tdincer 1796c52
Update element_interface/extract_trigger.py
tdincer 8554cc3
Update element_interface/extract_trigger.py
tdincer bca1a5a
Update element_interface/extract_trigger.py
tdincer f25669e
Update element_interface/extract_loader.py
tdincer caa89c8
update changelog
tdincer 6115c2e
Merge branch 'main' of https://github.com/tdincer/element-interface
tdincer bb1f15f
Update element_interface/extract_trigger.py
tdincer 1bf75cc
Update element_interface/extract_trigger.py
tdincer 0b5dc06
Update element_interface/extract_loader.py
tdincer e03c967
final touches
tdincer 1583e02
Merge branch 'main' of https://github.com/tdincer/element-interface
tdincer File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| import os | ||
| import numpy as np | ||
tdincer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| from pathlib import Path | ||
| from datetime import datetime | ||
|
|
||
|
|
||
| class EXTRACT_loader: | ||
| def __init__(self, extract_dir: str): | ||
| """Initialize EXTRACT loader class | ||
|
|
||
| Args: | ||
| extract_dir (str): string, absolute file path to EXTRACT directory | ||
|
|
||
| Raises: | ||
| FileNotFoundError: Could not find EXTRACT results | ||
| """ | ||
| from scipy.io import loadmat | ||
|
|
||
| try: | ||
| extract_file = next(Path(extract_dir).glob("*_extract_output.mat")) | ||
| except StopInteration: | ||
| raise FileNotFoundError( | ||
| f"EXTRACT output result file is not found at {extract_dir}." | ||
| ) | ||
|
|
||
| results = loadmat(extract_file) | ||
|
|
||
| self.creation_time = datetime.fromtimestamp(os.stat(extract_file).st_ctime) | ||
| self.S = results["output"][0]["spatial_weights"][0] # (Height, Width, MaskId) | ||
| self.T = results["output"][0]["temporal_weights"][0] # (Time, MaskId) | ||
|
|
||
| def load_results(self): | ||
| """Load the EXTRACT results | ||
|
|
||
| Returns: | ||
| masks (dict): Details of the masks identified with the EXTRACT segmentation package. | ||
| """ | ||
| from scipy.sparse import find | ||
|
|
||
| S_transposed = self.S.transpose([2, 0, 1]) # MaskId, Height, Width | ||
|
|
||
| masks = [] | ||
|
|
||
| for mask_id, s in enumerate(S_transposed): | ||
| ypixels, xpixels, weights = find(s) | ||
| masks.append( | ||
| dict( | ||
| mask_id=mask_id, | ||
| mask_npix=len(weights), | ||
| mask_weights=weights, | ||
| mask_center_x=int(np.average(xpixels, weights=weights) + 0.5), | ||
| mask_center_y=int(np.average(ypixels, weights=weights) + 0.5), | ||
| mask_center_z=None, | ||
| mask_xpix=xpixels, | ||
| mask_ypix=ypixels, | ||
| mask_zpix=None, | ||
kabilar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ) | ||
| ) | ||
| return masks | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| import os | ||
| from typing import Union | ||
| from pathlib import Path | ||
| from textwrap import dedent | ||
| from datetime import datetime | ||
|
|
||
|
|
||
| class EXTRACT_trigger: | ||
| m_template = dedent( | ||
| """ | ||
| % Load Data | ||
| data = load('{scanfile}'); | ||
| M = data.M; | ||
|
|
||
| % Input Paramaters | ||
| config = struct(); | ||
| {parameters_list_string} | ||
|
|
||
| % Run EXTRACT | ||
| output = extractor(M, config); | ||
| save('{output_fullpath}', 'output'); | ||
| """ | ||
| ) | ||
|
|
||
| def __init__( | ||
| self, | ||
| scanfile: Union[str, Path], | ||
| parameters: dict, | ||
| output_dir: Union[str, Path], | ||
| ) -> None: | ||
| """A helper class to trigger EXTRACT analysis in element-calcium-imaging. | ||
|
|
||
| Args: | ||
| scanfile (Union[str, Path]): Full path of the scan | ||
| parameters (dict): EXTRACT input paramaters. | ||
| output_dir (Union[str, Path]): Directory to store the outputs of EXTRACT analysis. | ||
| """ | ||
| assert isinstance(parameters, dict) | ||
|
|
||
| self.scanfile = Path(scanfile) | ||
| self.output_dir = Path(output_dir) | ||
| self.parameters = parameters | ||
|
|
||
| def write_matlab_run_script(self): | ||
| """Compose a matlab script and save it with the name run_extract.m. | ||
|
|
||
| The composed script is basically the formatted version of the m_template attribute.""" | ||
|
|
||
| self.output_fullpath = ( | ||
| self.output_dir / f"{self.scanfile.stem}_extract_output.mat" | ||
| ) | ||
|
|
||
| m_file_content = self.m_template.format( | ||
| **dict( | ||
| parameters_list_string="\n".join( | ||
| [ | ||
| f"config.{k} = '{v}';" | ||
| if isinstance(v, str) | ||
| else f"config.{k} = {str(v).lower()};" | ||
| if isinstance(v, bool) | ||
| else f"config.{k} = {v};" | ||
| for k, v in self.parameters.items() | ||
| ] | ||
| ), | ||
| scanfile=self.scanfile.as_posix(), | ||
| output_fullpath=self.output_fullpath.as_posix(), | ||
| ) | ||
| ).lstrip() | ||
|
|
||
| self.m_file_fp = self.output_dir / "run_extract.m" | ||
|
|
||
| with open(self.m_file_fp, "w") as f: | ||
| f.write(m_file_content) | ||
|
|
||
| def run(self): | ||
| """Run the matlab run_extract.m script.""" | ||
|
|
||
| self.write_matlab_run_script() | ||
|
|
||
| current_dir = Path.cwd() | ||
| os.chdir(self.output_dir) | ||
|
|
||
| try: | ||
| import matlab.engine | ||
|
|
||
| eng = matlab.engine.start_matlab() | ||
| eng.run_extract() | ||
| except Exception as e: | ||
| raise e | ||
| finally: | ||
| os.chdir(current_dir) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,3 @@ | ||
| """Package metadata""" | ||
|
|
||
| __version__ = "0.3.1" | ||
| __version__ = "0.4.0" |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.