Skip to content

Commit

Permalink
enh: prepare CLI script to run estimation, add --dry-run
Browse files Browse the repository at this point in the history
  • Loading branch information
oesteban committed Nov 28, 2023
1 parent aa86b0b commit d988b05
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 22 deletions.
68 changes: 51 additions & 17 deletions sdcflows/cli/find_estimators.py → sdcflows/cli/main.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,26 @@
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
#
# Copyright 2021 The NiPreps Developers <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# We support and encourage derived works from this project, please read
# about our expectations at
#
# https://www.nipreps.org/community/licensing/
#
"""Standalone command line executable for estimation of fieldmaps."""
import argparse
from pathlib import Path

Expand All @@ -12,6 +35,13 @@ def _parser():
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument("bids_dir", type=Path, help="The input BIDS directory to parse")
parser.add_argument(
"-n",
"--dry-run",
action="store_true",
default=False,
help="only find estimable fieldmaps (that is, estimation is not triggered)",
)
parser.add_argument(
"-s",
"--subjects",
Expand All @@ -30,7 +60,7 @@ def _parser():
metavar="PATH",
type=Path,
help="Path to a PyBIDS database folder, for faster indexing (especially "
"useful for large datasets). Will be created if not present."
"useful for large datasets). Will be created if not present.",
)
parser.add_argument(
"-v",
Expand All @@ -54,14 +84,16 @@ def gen_layout(bids_dir, database_dir=None):
"models",
"derivatives",
re.compile(r"^\."),
re.compile(r"sub-[a-zA-Z0-9]+(/ses-[a-zA-Z0-9]+)?/(beh|eeg|ieeg|meg|micr|perf)"),
re.compile(
r"sub-[a-zA-Z0-9]+(/ses-[a-zA-Z0-9]+)?/(beh|eeg|ieeg|meg|micr|perf)"
),
),
)

layout_kwargs = {'indexer': _indexer}
layout_kwargs = {"indexer": _indexer}

if database_dir:
layout_kwargs['database_path'] = database_dir
layout_kwargs["database_path"] = database_dir

layout = BIDSLayout(bids_dir, **layout_kwargs)
return layout
Expand All @@ -80,7 +112,7 @@ def main(argv=None):
bids_dir = pargs.bids_dir.resolve(strict=True)
layout = gen_layout(bids_dir, pargs.bids_database_dir)
subjects = collect_participants(layout, pargs.subjects)
logger = create_logger('sdcflow.wrangler', level=10 if pargs.verbose else 40)
logger = create_logger("sdcflow.wrangler", level=10 if pargs.verbose else 40)
estimators_record = {}
for subject in subjects:
estimators_record[subject] = find_estimators(
Expand All @@ -91,18 +123,20 @@ def main(argv=None):
)

# pretty print results
print(f"Estimation for <{str(bids_dir)}> complete. Found:")
for subject, estimators in estimators_record.items():
print(f"\tsub-{subject}")
if not estimators:
print("\t\tNo estimators found")
continue
for estimator in estimators:
print(f"\t\t{estimator}")
for fl in estimator.sources:
fl_relpath = fl.path.relative_to(str(bids_dir / f'sub-{subject}'))
pe_dir = fl.metadata.get("PhaseEncodingDirection")
print(f"\t\t\t{pe_dir}\t{fl_relpath}")
if pargs.dry_run:
print(f"Estimation for <{str(bids_dir)}> complete. Found:")
for subject, estimators in estimators_record.items():
print(f"\tsub-{subject}")
if not estimators:
print("\t\tNo estimators found")
continue
for estimator in estimators:
print(f"\t\t{estimator}")
for fl in estimator.sources:
fl_relpath = fl.path.relative_to(str(bids_dir / f"sub-{subject}"))
pe_dir = fl.metadata.get("PhaseEncodingDirection")
print(f"\t\t\t{pe_dir}\t{fl_relpath}")
return


if __name__ == "__main__":
Expand Down
34 changes: 30 additions & 4 deletions sdcflows/cli/tests/test_find_estimators.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,31 @@
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
#
# Copyright 2021 The NiPreps Developers <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# We support and encourage derived works from this project, please read
# about our expectations at
#
# https://www.nipreps.org/community/licensing/
#
"""Check the CLI."""
import pytest
from niworkflows.utils.testing import generate_bids_skeleton

from ..find_estimators import main as find_estimators
from ...fieldmaps import clear_registry
from sdcflows.cli.main import main as find_estimators
from sdcflows.fieldmaps import clear_registry

OUTPUT = """\
Estimation for <{path}> complete. Found:
Expand Down Expand Up @@ -102,12 +125,15 @@

@pytest.mark.parametrize(
"test_id,config,estimator_id",
[("intendedfor", intendedfor_config, "auto_00000"), ("b0field", b0field_config, "pepolar")],
[
("intendedfor", intendedfor_config, "auto_00000"),
("b0field", b0field_config, "pepolar"),
],
)
def test_find_estimators(tmp_path, capsys, test_id, config, estimator_id):
path = tmp_path / test_id
generate_bids_skeleton(path, config)
find_estimators([str(path)])
find_estimators([str(path), "--dry-run"])
output = OUTPUT.format(path=path, estimator_id=estimator_id)
out, _ = capsys.readouterr()
assert out == output
Expand Down
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ sdcflows =

[options.entry_points]
console_scripts =
sdcflows-find-estimators=sdcflows.cli.find_estimators:main
sdcflows=sdcflows.cli.main:main

[flake8]
max-line-length = 99
Expand Down

0 comments on commit d988b05

Please sign in to comment.