Skip to content

Commit

Permalink
Keep working.
Browse files Browse the repository at this point in the history
  • Loading branch information
tsalo committed Nov 15, 2024
1 parent 6c8f9d8 commit a70d88f
Show file tree
Hide file tree
Showing 11 changed files with 66 additions and 39 deletions.
12 changes: 5 additions & 7 deletions qsiprep/cli/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,9 +211,9 @@ def _bids_filter(value, parser):
metavar='FILE',
help='A JSON file describing custom BIDS input filters using PyBIDS. '
'For further details, please check out '
'https://fmriprep.readthedocs.io/en/%s/faq.html#'
'https://fmriprep.readthedocs.io/en/'
f'{currentv.base_version if is_release else "latest"}/faq.html#'
'how-do-I-select-only-certain-files-to-be-input-to-fMRIPrep'
% (currentv.base_version if is_release else 'latest'),
)
g_bids.add_argument(
'--bids-database-dir',
Expand Down Expand Up @@ -710,12 +710,10 @@ def parse_args(args=None, namespace=None):

# Ensure input and output folders are not the same
if output_dir == bids_dir:
rec_path = output_dir / 'derivatives' / f"qsiprep-{version.split('+')[0]}"
parser.error(
'The selected output folder is the same as the input BIDS folder. '
'Please modify the output path (suggestion: %s).'
% bids_dir
/ 'derivatives'
/ ('qsiprep-%s' % version.split('+')[0])
f'Please modify the output path (suggestion: {rec_path}).'
)

if bids_dir in work_dir.parents:
Expand Down Expand Up @@ -755,7 +753,7 @@ def parse_args(args=None, namespace=None):
if missing_subjects:
parser.error(
'One or more participant labels were not found in the BIDS directory: '
'%s.' % ', '.join(missing_subjects)
f"{', '.join(missing_subjects)}."
)

# Determine which sessions to process and group them
Expand Down
2 changes: 1 addition & 1 deletion qsiprep/cli/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def main():

config.loggers.workflow.log(
15,
'\n'.join(['QSIPrep config:'] + ['\t\t%s' % s for s in config.dumps().splitlines()]),
'\n'.join(['QSIPrep config:'] + [f'\t\t{s}' for s in config.dumps().splitlines()]),
)
config.loggers.workflow.log(25, 'QSIPrep started!')
errno = 1 # Default is error exit unless otherwise set
Expand Down
50 changes: 34 additions & 16 deletions qsiprep/cli/version.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,34 @@
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
#
# Copyright 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/
#
"""Version CLI helpers."""

from datetime import datetime
from contextlib import suppress
from datetime import datetime, timezone
from pathlib import Path

import requests

from .. import __version__
from qsiprep import __version__

RELEASE_EXPIRY_DAYS = 14
DATE_FMT = '%Y%m%d'
Expand All @@ -20,6 +41,7 @@ def check_latest():
latest = None
date = None
outdated = None
now = datetime.now(tz=timezone.utc)
cachefile = Path.home() / '.cache' / 'qsiprep' / 'latest'
try:
cachefile.parent.mkdir(parents=True, exist_ok=True)
Expand All @@ -29,23 +51,22 @@ def check_latest():
if cachefile and cachefile.exists():
try:
latest, date = cachefile.read_text().split('|')
except Exception:
except Exception: # noqa: S110, BLE001
pass
else:
try:
latest = Version(latest)
date = datetime.strptime(date, DATE_FMT)
date = datetime.strptime(date, DATE_FMT).astimezone(timezone.utc)
except (InvalidVersion, ValueError):
latest = None
else:
if abs((datetime.now() - date).days) > RELEASE_EXPIRY_DAYS:
if abs((now - date).days) > RELEASE_EXPIRY_DAYS:
outdated = True

if latest is None or outdated is True:
try:
response = None
with suppress(Exception):
response = requests.get(url='https://pypi.org/pypi/qsiprep/json', timeout=1.0)
except Exception:
response = None

if response and response.status_code == 200:
versions = [Version(rel) for rel in response.json()['releases'].keys()]
Expand All @@ -56,26 +77,23 @@ def check_latest():
latest = None

if cachefile is not None and latest is not None:
try:
cachefile.write_text('|'.join(('%s' % latest, datetime.now().strftime(DATE_FMT))))
except Exception:
pass
with suppress(OSError):
cachefile.write_text(f'{latest}|{now.strftime(DATE_FMT)}')

return latest


def is_flagged():
"""Check whether current version is flagged."""
# https://raw.githubusercontent.com/pennlinc/qsiprep/master/.versions.json
flagged = tuple()
try:
flagged = ()
response = None
with suppress(Exception):
response = requests.get(
url="""\
https://raw.githubusercontent.com/pennlinc/qsiprep/master/.versions.json""",
timeout=1.0,
)
except Exception:
response = None

if response and response.status_code == 200:
flagged = response.json().get('flagged', {}) or {}
Expand Down
2 changes: 1 addition & 1 deletion qsiprep/cli/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def build_boilerplate(config_file, workflow):
logs_path = config.execution.output_dir / 'logs'
boilerplate = workflow.visit_desc()
citation_files = {
ext: logs_path / ('CITATION.%s' % ext) for ext in ('bib', 'tex', 'md', 'html')
ext: logs_path / f'CITATION.{ext}' for ext in ('bib', 'tex', 'md', 'html')
}

if boilerplate:
Expand Down
8 changes: 4 additions & 4 deletions qsiprep/interfaces/ants.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,14 +120,14 @@ def _list_outputs(self):
if isinstance(input_image, list):
input_image = input_image[0]
path, fname, ext = split_filename(input_image)
affine = '%s/%s%s%d0GenericAffine.mat' % (cwd, prefix, fname, num)
warp = '%s/%s%s%d1Warp.nii.gz' % (cwd, prefix, fname, num)
inv_warp = '%s/%s%s%d1InverseWarp.nii.gz' % (cwd, prefix, fname, num)
affine = f'{cwd}/{prefix}{fname}{num}0GenericAffine.mat'
warp = f'{cwd}/{prefix}{fname}{num}1Warp.nii.gz'
inv_warp = f'{cwd}/{prefix}{fname}{num}1InverseWarp.nii.gz'
forward_transforms.append([affine, warp])
reverse_transforms.append([inv_warp, affine])

templates = [
'%s/%stemplate%s.nii.gz' % (cwd, prefix, tnum)
f'{cwd}/{prefix}template{tnum}.nii.gz'
for tnum in range(self.inputs.num_modalities)
]
outputs = self.output_spec().get()
Expand Down
10 changes: 5 additions & 5 deletions qsiprep/tests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,10 @@ def check_generated_files(output_dir, output_list_file, optional_output_list_fil
found_files = [os.path.relpath(f, output_dir) for f in found_files]

# Ignore figures
found_files = sorted(list(set([f for f in found_files if 'figures' not in f])))
found_files = sorted(set([f for f in found_files if 'figures' not in f]))

# Ignore logs
found_files = sorted(list(set([f for f in found_files if 'log' not in f.split(os.path.sep)])))
found_files = sorted(set([f for f in found_files if 'log' not in f.split(os.path.sep)]))

with open(output_list_file) as fo:
expected_files = fo.readlines()
Expand All @@ -110,8 +110,8 @@ def check_generated_files(output_dir, output_list_file, optional_output_list_fil
optional_files = [f.rstrip() for f in optional_files]

if sorted(found_files) != sorted(expected_files):
expected_not_found = sorted(list(set(expected_files) - set(found_files)))
found_not_expected = sorted(list(set(found_files) - set(expected_files)))
expected_not_found = sorted(set(expected_files) - set(found_files))
found_not_expected = sorted(set(found_files) - set(expected_files))

msg = ''
if expected_not_found:
Expand Down Expand Up @@ -143,7 +143,7 @@ def reorder_expected_outputs():
with open(expected_output_file) as fo:
file_contents = fo.readlines()

file_contents = sorted(list(set(file_contents)))
file_contents = sorted(set(file_contents))

with open(expected_output_file, 'w') as fo:
fo.writelines(file_contents)
4 changes: 2 additions & 2 deletions qsiprep/viz/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def plot_denoise(
# Find and replace the figure_1 id.
xml_data = etree.fromstring(svg)
find_text = etree.ETXPath("//{%s}g[@id='figure_1']" % SVGNS)
find_text(xml_data)[0].set('id', '%s-%s-%s' % (div_id, mode, uuid4()))
find_text(xml_data)[0].set('id', f'{div_id}-{mode}-{uuid4()}')

svg_fig = SVGFigure()
svg_fig.root = xml_data
Expand Down Expand Up @@ -144,7 +144,7 @@ def plot_acpc(
# Find and replace the figure_1 id.
xml_data = etree.fromstring(svg)
find_text = etree.ETXPath("//{%s}g[@id='figure_1']" % SVGNS)
find_text(xml_data)[0].set('id', '%s-%s-%s' % (div_id, mode, uuid4()))
find_text(xml_data)[0].set('id', f'{div_id}-{mode}-{uuid4()}')

svg_fig = SVGFigure()
svg_fig.root = xml_data
Expand Down
2 changes: 2 additions & 0 deletions qsiprep/workflows/anatomical/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
from .volume import init_anat_preproc_wf, init_synthseg_wf, init_synthstrip_wf

__all__ = ['init_anat_preproc_wf', 'init_synthseg_wf', 'init_synthstrip_wf']
9 changes: 9 additions & 0 deletions qsiprep/workflows/fieldmap/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,12 @@
from .pepolar import init_pepolar_unwarp_wf
from .syn import init_syn_sdc_wf
from .unwarp import init_fmap_unwarp_report_wf, init_sdc_unwarp_wf

__all__ = [
'init_sdc_wf',
'init_drbuddi_wf',
'init_pepolar_unwarp_wf',
'init_syn_sdc_wf',
'init_fmap_unwarp_report_wf',
'init_sdc_unwarp_wf',
]
4 changes: 2 additions & 2 deletions qsiprep/workflows/fieldmap/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def init_sdc_wf(fieldmap_info, dwi_meta):
# PEPOLAR path
if fieldmap_info['suffix'] in ('epi', 'rpe_series', 'dwi'):
outputnode.inputs.method = (
'PEB/PEPOLAR (phase-encoding based / PE-POLARity): %s' % fieldmap_info['suffix']
f'PEB/PEPOLAR (phase-encoding based / PE-POLARity): {fieldmap_info["suffix"]}'
)

epi_fmaps = fieldmap_info[fieldmap_info['suffix']]
Expand All @@ -189,7 +189,7 @@ def init_sdc_wf(fieldmap_info, dwi_meta):

# FIELDMAP path
if fieldmap_info['suffix'] == 'fieldmap' or fieldmap_info['suffix'].startswith('phase'):
outputnode.inputs.method = 'FMB (%s-based)' % fieldmap_info['suffix']
outputnode.inputs.method = f'FMB ({fieldmap_info["suffix"]}-based)'
# Import specific workflows here, so we don't break everything with one
# unused workflow.
if fieldmap_info['suffix'] == 'fieldmap':
Expand Down
2 changes: 1 addition & 1 deletion qsiprep/workflows/fieldmap/drbuddi.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def init_drbuddi_wf(
)

outputnode.inputs.method = (
'PEB/PEPOLAR (phase-encoding based / PE-POLARity): %s' % fieldmap_info['suffix']
f'PEB/PEPOLAR (phase-encoding based / PE-POLARity): {fieldmap_info["suffix"]}'
)

gather_drbuddi_inputs = pe.Node(
Expand Down

0 comments on commit a70d88f

Please sign in to comment.