Skip to content

Commit

Permalink
- Move run_command() to __init__()
Browse files Browse the repository at this point in the history
- Rename updatemetadata() to poolmetadata()
- Add/update documentation
  • Loading branch information
marcelzwiers committed Oct 2, 2024
1 parent 3c97c1b commit 754a7c7
Show file tree
Hide file tree
Showing 16 changed files with 284 additions and 428 deletions.
23 changes: 23 additions & 0 deletions bidscoin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,11 @@
import shutil
import warnings
import tempfile
import subprocess
from pathlib import Path
from importlib import metadata
from typing import Tuple, Union, List
from logging import getLogger
from .due import due, Doi
try:
import tomllib
Expand All @@ -40,6 +42,8 @@
with open(Path(__file__).parents[1]/'pyproject.toml', 'rb') as fid:
__version__ = tomllib.load(fid)['project']['version']

LOGGER = getLogger(__name__)

# Add license metadata
__license__ = 'GNU General Public License v3.0 or later (GPLv3+)'
__copyright__ = f"2018-{datetime.date.today().year}, Marcel Zwiers"
Expand Down Expand Up @@ -142,6 +146,25 @@ def lsdirs(folder: Path, wildcard: str='*') -> List[Path]:
return sorted([item for item in sorted(folder.glob(wildcard)) if item.is_dir() and not is_hidden(item.relative_to(folder))])


def run_command(command: str, success: tuple=(0,None)) -> int:
"""
Runs a command in a shell using subprocess.run(command, ..)
:param command: The command that is executed
:param success: The return codes for successful operation (e,g, for dcm2niix it is (0,3))
:return: The return code (e.g. 0 if the command was successfully executed (no errors), > 0 otherwise)
"""

LOGGER.verbose(f"Command:\n{command}")
process = subprocess.run(command, shell=True, capture_output=True, text=True)
if process.stderr or process.returncode not in success:
LOGGER.error(f"Failed to run:\n{command}\nErrorcode {process.returncode}:\n{process.stdout}\n{process.stderr}")
else:
LOGGER.verbose(f"Output:\n{process.stdout}")

return process.returncode


def trackusage(event: str, dryrun: bool=False) -> dict:
"""Sends a url GET request with usage data parameters (if tracking is allowed and we are not asleep)
Expand Down
24 changes: 1 addition & 23 deletions bidscoin/bcoin.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,8 @@
import os
import types
import coloredlogs
import inspect
import logging
import shutil
import subprocess
import sys
import urllib.request
import time
Expand Down Expand Up @@ -221,25 +219,6 @@ def reporterrors() -> str:
return errors


def run_command(command: str, success: tuple=(0,None)) -> int:
"""
Runs a command in a shell using subprocess.run(command, ..)
:param command: The command that is executed
:param success: The return codes for successful operation (e,g, for dcm2niix it is (0,3))
:return: The return code (e.g. 0 if the command was successfully executed (no errors), > 0 otherwise)
"""

LOGGER.verbose(f"Command:\n{command}")
process = subprocess.run(command, shell=True, capture_output=True, text=True)
if process.stderr or process.returncode not in success:
LOGGER.error(f"Failed to run:\n{command}\nErrorcode {process.returncode}:\n{process.stdout}\n{process.stderr}")
else:
LOGGER.verbose(f"Output:\n{process.stdout}")

return process.returncode


def list_executables(show: bool=False) -> list:
"""
:param show: Print the installed console scripts if True
Expand Down Expand Up @@ -454,8 +433,7 @@ def test_plugin(plugin: Union[Path,str], options: dict) -> int:

# First test to see if we can import the plugin
module = import_plugin(plugin, ('bidsmapper_plugin','bidscoiner_plugin'))
if not inspect.ismodule(module):
LOGGER.error(f"Invalid plugin: '{plugin}'")
if module is None:
return 1

# Then run the plugin's own 'test' routine (if implemented)
Expand Down
2 changes: 1 addition & 1 deletion bidscoin/bids.py
Original file line number Diff line number Diff line change
Expand Up @@ -2530,7 +2530,7 @@ def addmetadata(bidsses: Path):
json.dump(jsondata, sidecar, indent=4)


def updatemetadata(datasource: DataSource, targetmeta: Path, usermeta: Meta, extensions: Iterable, sourcemeta: Path=Path()) -> Meta:
def poolmetadata(datasource: DataSource, targetmeta: Path, usermeta: Meta, extensions: Iterable, sourcemeta: Path=Path()) -> Meta:
"""
Load the metadata from the target (json sidecar), then add metadata from the source (json sidecar) and finally add
the user metadata (meta table). Source metadata other than json sidecars are copied over to the target folder. Special
Expand Down
2 changes: 1 addition & 1 deletion bidscoin/bidsapps/fixmeta.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def fixmeta(bidsfolder: str, pattern: str, metadata: dict, participant: list, bi

# Load/copy over the source meta-data
jsonfile = target.with_suffix('').with_suffix('.json')
jsondata = bids.updatemetadata(datasource, jsonfile, bids.Meta({}), ['.json'])
jsondata = bids.poolmetadata(datasource, jsonfile, bids.Meta({}), ['.json'])
for key, value in metadata.items():
if isinstance(value, list):
for n in range(0, len(value), 2):
Expand Down
4 changes: 2 additions & 2 deletions bidscoin/bidsapps/skullstrip.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from importlib.util import find_spec
if find_spec('bidscoin') is None:
sys.path.append(str(Path(__file__).parents[2]))
from bidscoin import bcoin, bids, lsdirs, trackusage, DEBUG
from bidscoin import bcoin, bids, lsdirs, trackusage, run_command, DEBUG
from bidscoin.due import due, Doi


Expand Down Expand Up @@ -141,7 +141,7 @@ def skullstrip(bidsfolder: str, pattern: str, participant: list, masked: str, ou
jt.outputPath = f"{os.getenv('HOSTNAME')}:{Path.cwd() if DEBUG else tempfile.gettempdir()}/{jt.jobName}.out"
jobids.append(pbatch.runJob(jt))
LOGGER.info(f"Your skullstrip job has been submitted with ID: {jobids[-1]}")
elif bcoin.run_command(f"mri_synthstrip -i {srcimg} -o {outputimg} -m {maskimg} {args}"):
elif run_command(f"mri_synthstrip -i {srcimg} -o {outputimg} -m {maskimg} {args}"):
continue

# Add a json sidecar-file with the "SkullStripped" field
Expand Down
175 changes: 0 additions & 175 deletions bidscoin/plugins/README

This file was deleted.

Loading

0 comments on commit 754a7c7

Please sign in to comment.