Skip to content

Commit

Permalink
Switch to using pathlib for path handling in acq_engine (#76)
Browse files Browse the repository at this point in the history
* switch to `pathlib` for path handling in `acq_engine`

* bump version

* bug fixes
  • Loading branch information
ieivanov authored Aug 5, 2023
1 parent 42c6cf2 commit 8457ff7
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 23 deletions.
2 changes: 1 addition & 1 deletion mantis/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.0.2"
__version__ = "0.1.0"
33 changes: 15 additions & 18 deletions mantis/acquisition/acq_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
from dataclasses import asdict
from datetime import datetime
from functools import partial
from typing import Iterable
from pathlib import Path
from typing import Iterable, Union

import nidaqmx
import numpy as np
Expand Down Expand Up @@ -239,7 +240,7 @@ class MantisAcquisition(object):
Parameters
----------
acquisition_directory : str
acquisition_directory : str or PathLike
Directory where acquired data will be saved
acquisition_name : str
Name of the acquisition
Expand Down Expand Up @@ -276,7 +277,7 @@ class MantisAcquisition(object):

def __init__(
self,
acquisition_directory: str,
acquisition_directory: Union[str, os.PathLike],
acquisition_name: str,
mm_app_path: str = r'C:\\Program Files\\Micro-Manager-nightly',
mm_config_file: str = r'C:\\CompMicro_MMConfigs\\mantis\\mantis-LS.cfg',
Expand All @@ -286,7 +287,7 @@ def __init__(
verbose: bool = False,
) -> None:

self._root_dir = acquisition_directory
self._root_dir = Path(acquisition_directory).resolve()
self._acq_name = acquisition_name
self._demo_run = demo_run
self._verbose = verbose
Expand All @@ -296,12 +297,12 @@ def __init__(

# Create acquisition directory and log directory
self._acq_dir = _create_acquisition_directory(self._root_dir, self._acq_name)
self._logs_dir = os.path.join(self._acq_dir, 'logs')
os.mkdir(self._logs_dir)
self._logs_dir = self._acq_dir / 'logs'
self._logs_dir.mkdir()

# Setup logger
timestamp = datetime.now().strftime("%Y%m%dT%H%M%S")
acq_log_path = os.path.join(self._logs_dir, f'mantis_acquisition_log_{timestamp}.txt')
acq_log_path = self._logs_dir / f'mantis_acquisition_log_{timestamp}.txt'
configure_logger(acq_log_path)

if self._demo_run:
Expand All @@ -310,7 +311,7 @@ def __init__(

# Log conda environment
outs, errs = log_conda_environment(
os.path.join(self._logs_dir, f'conda_environment_log_{timestamp}.txt')
self._logs_dir / f'conda_environment_log_{timestamp}.txt'
)
if errs is None:
logger.debug(outs.decode('ascii').strip())
Expand All @@ -333,9 +334,7 @@ def __init__(
mm_app_path=mm_app_path,
mm_config_file=mm_config_file,
zmq_port=LS_ZMQ_PORT,
core_log_path=os.path.join(
mm_app_path, 'CoreLogs', f'CoreLog{timestamp}_headless.txt'
),
core_log_path=Path(mm_app_path) / 'CoreLogs' / f'CoreLog{timestamp}_headless.txt',
)

@property
Expand Down Expand Up @@ -729,7 +728,7 @@ def refocus_ls_path(self):
# Save acquired stacks in logs
timestamp = datetime.now().strftime("%Y%m%dT%H%M%S")
tifffile.imwrite(
os.path.join(self._logs_dir, f'ls_refocus_data_{timestamp}.ome.tif'),
self._logs_dir / f'ls_refocus_data_{timestamp}.ome.tif',
np.expand_dims(data, -3).astype('uint16'),
)

Expand All @@ -747,9 +746,7 @@ def refocus_ls_path(self):
lambda_ill=wavelength,
pixel_size=LS_PIXEL_SIZE,
threshold_FWHM=threshold_FWHM,
plot_path=os.path.join(
self._logs_dir, f'ls_refocus_plot_{timestamp}_Pos{stack_idx}.png'
),
plot_path=self._logs_dir / f'ls_refocus_plot_{timestamp}_Pos{stack_idx}.png',
)
focus_indices.append(idx)
logger.debug(
Expand Down Expand Up @@ -1001,10 +998,10 @@ def _generate_channel_slice_acq_events(channel_settings, slice_settings):
return events


def _create_acquisition_directory(root_dir, acq_name, idx=1):
acq_dir = os.path.join(root_dir, f'{acq_name}_{idx}')
def _create_acquisition_directory(root_dir: Path, acq_name: str, idx=1) -> Path:
acq_dir = root_dir / f'{acq_name}_{idx}'
try:
os.mkdir(acq_dir)
acq_dir.mkdir(parents=False, exist_ok=False)
except OSError:
return _create_acquisition_directory(root_dir, acq_name, idx + 1)
return acq_dir
9 changes: 6 additions & 3 deletions mantis/acquisition/logger.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import logging
import os

from pathlib import Path
from subprocess import PIPE, STDOUT, Popen
from typing import Union


def log_conda_environment(log_path: str):
def log_conda_environment(log_path: Union[str, os.PathLike]):
"""Save a log of the current conda environment as defined in the
`compmicro-docs/hpc/log_environment.ps1` PowerShell script. A copy of the
script is kept in a separate location, given in `log_script_path` to avoid
Expand All @@ -13,7 +15,7 @@ def log_conda_environment(log_path: str):
Parameters
----------
log_path : str
log_path : str or PathLike
Path where the environment log file will be written
Returns
Expand All @@ -23,12 +25,13 @@ def log_conda_environment(log_path: str):
"""

# Validate log_path input
log_path = str(Path(log_path).absolute())
assert log_path.endswith('.txt'), 'Log path must point to a .txt file'

# get current conda environment
conda_environment = os.environ['CONDA_DEFAULT_ENV']
# define absolute path to log_environment.ps1 script
log_script_path = 'C:\\Users\\labelfree\\log_environment.ps1'
log_script_path = str(Path.home() / "log_environment.ps1")

# `pwsh` command launches PowerShell 7. Do not use `powershell` as it
# launches PowerShell 6 which is not configured with conda
Expand Down
2 changes: 1 addition & 1 deletion mantis/cli/run_acquisition.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def run_acquisition(
ls_microscope_settings = MicroscopeSettings(**raw_settings.get('ls_microscope_settings'))

with MantisAcquisition(
acquisition_directory=str(acq_directory),
acquisition_directory=acq_directory,
acquisition_name=acq_name,
mm_app_path=mm_app_path,
mm_config_file=mm_config_filepath,
Expand Down

0 comments on commit 8457ff7

Please sign in to comment.