Skip to content

Commit

Permalink
collective code refactory, updated module and class name convention a…
Browse files Browse the repository at this point in the history
…nd polish the code style
  • Loading branch information
dvm-shlee committed Apr 30, 2024
1 parent 87a95cf commit 22a18ba
Show file tree
Hide file tree
Showing 19 changed files with 666 additions and 259 deletions.
4 changes: 3 additions & 1 deletion .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ env

**/__pycache__
**/.pytest_cache
**/.mypy_cache

.idea/**

Expand All @@ -16,4 +17,5 @@ env
tests/*
paper

.DS_Store
.DS_Store

2 changes: 1 addition & 1 deletion .github/pull_request_template.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ Changes proposed in this pull request:
-


@BrkRaw/Bruker
@BrkRaw/brkraw
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

## BrkRaw: A comprehensive tool to access raw Bruker Biospin MRI data
#### Version: 0.3.11

### Description

The ‘BrkRaw’ is a python module designed to provide a comprehensive tool to access raw data acquired from
Expand Down
2 changes: 1 addition & 1 deletion brkraw/api/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .data import Study
from ..config import ConfigManager
from .config import Manager as ConfigManager

__all__ = ['Study', 'ConfigManager']
3 changes: 3 additions & 0 deletions brkraw/api/config/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .manager import Manager

__all__ = ['Manager']
24 changes: 24 additions & 0 deletions brkraw/api/config/config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# default configuration for brkraw
plugin:
repo:
- https://github.com/brkraw/brkraw-plugin.git/plugin
template:
- boilerplate

preset:
repo:
- https://github.com/brkraw/brkraw-plugin.git/preset
template:
- boilerplate

bids:
spec:
repo:
- https://github.com/brkraw/brkraw-bids.git/spec
recipes:
repo:
- https://github.com/brkraw/brkraw-bids.git/recipes

app:
tonifti:
output_format: <study_name>_<scan_name>_<scan_id>_<reco_id>
145 changes: 145 additions & 0 deletions brkraw/api/config/manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
from __future__ import annotations
import yaml
from pathlib import Path
from brkraw import __version__
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Literal

class Manager:
"""
Make this configuration works internally without create file but if user use cli to create, do it so (create on home folder)
Manage the configuration settings.
Notes:
- Provides methods to ensure the existence of the config directory, load or create the configuration,
set configuration values, and retrieve configuration values.
"""
def __init__(self):
"""
Initialize the configuration object.
Notes:
- Sets up the home directory, config directory, and config file paths.
- Ensures the existence of the config directory and loads or creates the configuration.
"""
self.home = Path.home()
self.package = Path(__file__).absolute().parent
self.local_dir = Path.cwd()
self.global_dir = self.home_dir / '.brkraw'
self.fname = 'config.yaml'

def config_file(self, target: Literal['local', 'global'] = 'global'):
dir = self.global_dir if target == 'global' else self.local_dir
if dir.exists() and (dir / self.fname).exists():
return dir / self.fname
else:
return self.package / self.fname

def ensure_config_dir_exists(self):
"""
Ensure the existence of the configuration directory.
Notes:
- Creates the config directory if it does not already exist.
- Also creates 'plugin' and 'bids' directories within the config directory.
"""
if not self.config_dir.exists():
self.config_dir.mkdir()
(self.config_dir / 'plugin').mkdir()
(self.config_dir / 'preset').mkdir()
(self.config_dir / 'bids').mkdir()

def load(self, target: Literal['local', 'global'] = 'global'):
"""
Load an existing configuration file or create a new one if it does not exist.
Notes:
- If the config file does not exist, a default configuration is created and saved.
- Otherwise, the existing configuration is loaded from the file.
"""
if not self.config_file.exists():
with open(self.installed_dir / 'config.yalm') as f:
self.config = yaml.safe_load(f)

def create(self, target: Literal['local', 'global'] = 'global'):
"""_summary_
Returns:
_type_: _description_
"""

# use default config if no configure created,
# for downloading location, if no configuration folder created (~/.brkraw), use local folder
# also check local folder first (plugin, preset, bids), where you run a command
def set(self, key, value):
"""
Set a key-value pair in the configuration and save the updated configuration to the file.
Args:
key: The key to set in the configuration.
value: The value to associate with the key.
Notes:
- Updates the configuration with the provided key-value pair.
- Persists the updated configuration to the config file.
"""
self.config[key] = value
with open(self.config_file, 'w') as f:
yaml.dump(self.config, f, sort_keys=False)

def get(self, key):
"""
Retrieve the value associated with the given key from the configuration.
Args:
key: The key to retrieve the value for.
Returns:
The value associated with the key in the configuration, or None if the key is not found.
Notes:
- Returns the value corresponding to the provided key from the configuration.
"""
return self.config.get(key)

# def get_scan_time(self, visu_pars=None):
# import datetime as dt
# subject_date = get_value(self._subject, 'SUBJECT_date')
# subject_date = subject_date[0] if isinstance(subject_date, list) else subject_date
# pattern_1 = r'(\d{2}:\d{2}:\d{2})\s+(\d+\s\w+\s\d{4})'
# pattern_2 = r'(\d{4}-\d{2}-\d{2})[T](\d{2}:\d{2}:\d{2})'
# if re.match(pattern_1, subject_date):
# # start time
# start_time = dt.time(*map(int, re.sub(pattern_1, r'\1', subject_date).split(':')))
# # date
# date = dt.datetime.strptime(re.sub(pattern_1, r'\2', subject_date), '%d %b %Y').date()
# # end time
# if visu_pars != None:
# last_scan_time = get_value(visu_pars, 'VisuAcqDate')
# last_scan_time = dt.time(*map(int, re.sub(pattern_1, r'\1', last_scan_time).split(':')))
# acq_time = get_value(visu_pars, 'VisuAcqScanTime') / 1000.0
# time_delta = dt.timedelta(0, acq_time)
# scan_time = (dt.datetime.combine(date, last_scan_time) + time_delta).time()
# return dict(date=date,
# start_time=start_time,
# scan_time=scan_time)
# elif re.match(pattern_2, subject_date):
# # start time
# # subject_date = get_value(self._subject, 'SUBJECT_date')[0]
# start_time = dt.time(*map(int, re.sub(pattern_2, r'\2', subject_date).split(':')))
# # date
# date = dt.date(*map(int, re.sub(pattern_2, r'\1', subject_date).split('-')))

# # end date
# if visu_pars != None:
# scan_time = get_value(visu_pars, 'VisuCreationDate')[0]
# scan_time = dt.time(*map(int, re.sub(pattern_2, r'\2', scan_time).split(':')))
# return dict(date=date,
# start_time=start_time,
# scan_time=scan_time)
# else:
# raise Exception(ERROR_MESSAGES['NotIntegrated'])

# return dict(date=date,
# start_time=start_time)
22 changes: 21 additions & 1 deletion brkraw/api/data/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,24 @@
"""Initializes and exports the main components of the MRI study and scan management package.
This package module consolidates and provides easy access to the primary classes involved in managing
and analyzing MRI study and scan data. The classes exported here facilitate the interfacing with MRI
data at both the study and scan levels, supporting detailed data manipulation and analysis.
Exports:
Study: A class that manages MRI study operations, extending functionalities for detailed study data handling.
Scan: A class representing individual MRI scans, capable of detailed scan data analysis and management.
ScanInfo: A class for managing basic information and warnings related to MRI scans.
The `__init__.py` module ensures that these classes are readily accessible when the package is imported,
making the package easier to use and integrate into larger projects or applications.
Example:
from your_package_name import Study, Scan, ScanInfo
This enables straightforward access to these classes for further development and deployment in MRI data analysis tasks.
"""

from .study import Study
from .scan import Scan, ScanInfo

__all__ = ['Study', 'Scan', 'ScanInfo']
__all__ = ['Study', 'Scan', 'ScanInfo']
Loading

0 comments on commit 22a18ba

Please sign in to comment.