From ecf5e33a72b93c27ff6d312d68f798fae9c0a54b Mon Sep 17 00:00:00 2001 From: Taylor Salo Date: Mon, 13 Jan 2025 10:05:39 -0500 Subject: [PATCH] Run ruff format (#484) --- .maint/update_authors.py | 6 ++--- aslprep/_warnings.py | 2 +- aslprep/cli/parser.py | 19 +++++++-------- aslprep/cli/workflow.py | 6 ++--- aslprep/config.py | 4 ++-- aslprep/interfaces/cbf.py | 2 +- aslprep/interfaces/reports.py | 40 ++++++++++++++++---------------- aslprep/tests/run_local_tests.py | 2 +- aslprep/tests/test_cli.py | 36 ++++++++++++++-------------- aslprep/tests/utils.py | 2 +- aslprep/utils/bids.py | 8 +++---- aslprep/utils/cbf.py | 6 ++--- aslprep/workflows/asl/cbf.py | 2 +- aslprep/workflows/base.py | 10 ++++---- 14 files changed, 72 insertions(+), 73 deletions(-) diff --git a/.maint/update_authors.py b/.maint/update_authors.py index 55e526e92..46e07b5be 100755 --- a/.maint/update_authors.py +++ b/.maint/update_authors.py @@ -132,7 +132,7 @@ def get_git_lines(fname='line-contributors.txt'): def _namelast(inlist): retval = [] for i in inlist: - i['name'] = (f"{i.pop('name', '')} {i.pop('lastname', '')}").strip() + i['name'] = (f'{i.pop("name", "")} {i.pop("lastname", "")}').strip() retval.append(i) return retval @@ -187,7 +187,7 @@ def zenodo( misses = set(miss_creators).intersection(miss_contributors) if misses: print( - f"Some people made commits, but are missing in .maint/ files: {', '.join(misses)}", + f'Some people made commits, but are missing in .maint/ files: {", ".join(misses)}', file=sys.stderr, ) @@ -268,7 +268,7 @@ def _aslist(value): if misses: print( - f"Some people made commits, but are missing in .maint/ files: {', '.join(misses)}", + f'Some people made commits, but are missing in .maint/ files: {", ".join(misses)}', file=sys.stderr, ) diff --git a/aslprep/_warnings.py b/aslprep/_warnings.py index ef4677f04..7b71b1672 100644 --- a/aslprep/_warnings.py +++ b/aslprep/_warnings.py @@ -13,7 +13,7 @@ def _warn(message, category=None, stacklevel=1, source=None): category = type(category).__name__ category = category.replace('type', 'WARNING') - logging.getLogger('py.warnings').warning(f"{category or 'WARNING'}: {message}") + logging.getLogger('py.warnings').warning(f'{category or "WARNING"}: {message}') def _showwarning(message, category, filename, lineno, file=None, line=None): diff --git a/aslprep/cli/parser.py b/aslprep/cli/parser.py index facd22503..89c7fd469 100644 --- a/aslprep/cli/parser.py +++ b/aslprep/cli/parser.py @@ -171,11 +171,11 @@ def _bids_filter(value, parser): type=BIDSFilter, metavar='FILE', help=( - "A JSON file describing custom BIDS input filters using PyBIDS. " - "For further details, please check out " - "https://aslprep.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-ASLPrep" + 'A JSON file describing custom BIDS input filters using PyBIDS. ' + 'For further details, please check out ' + 'https://aslprep.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-ASLPrep' ), ) g_bids.add_argument( @@ -771,7 +771,7 @@ def parse_args(args=None, namespace=None): # Ensure input and output folders are not the same if output_dir == bids_dir: - rec_path = bids_dir / 'derivatives' / f"aslprep-{version.split('+')[0]}" + rec_path = bids_dir / 'derivatives' / f'aslprep-{version.split("+")[0]}' parser.error( 'The selected output folder is the same as the input BIDS folder. ' f'Please modify the output path (suggestion: {rec_path}).' @@ -788,8 +788,7 @@ def parse_args(args=None, namespace=None): from fmriprep.utils.bids import validate_input_dir build_log.info( - 'Making sure the input data is BIDS compliant (warnings can be ignored in most ' - 'cases).' + 'Making sure the input data is BIDS compliant (warnings can be ignored in most cases).' ) validate_input_dir( config.environment.exec_env, @@ -815,8 +814,8 @@ def parse_args(args=None, namespace=None): missing_subjects = participant_label - set(all_subjects) if missing_subjects: parser.error( - "One or more participant labels were not found in the BIDS directory: " - f"{', '.join(missing_subjects)}." + 'One or more participant labels were not found in the BIDS directory: ' + f'{", ".join(missing_subjects)}.' ) config.execution.participant_label = sorted(participant_label) diff --git a/aslprep/cli/workflow.py b/aslprep/cli/workflow.py index 310119c9c..805e029c6 100644 --- a/aslprep/cli/workflow.py +++ b/aslprep/cli/workflow.py @@ -33,11 +33,11 @@ def build_workflow(config_file, retval): notice_path = data.load.readable('NOTICE') if notice_path.exists(): banner[0] += '\n' - banner += [f"License NOTICE {'#' * 50}"] + banner += [f'License NOTICE {"#" * 50}'] banner += [f'ASLPrep {version}'] banner += notice_path.read_text().splitlines(keepends=False)[1:] banner += ['#' * len(banner[1])] - build_log.log(25, f"\n{' ' * 9}".join(banner)) + build_log.log(25, f'\n{" " * 9}'.join(banner)) # warn if older results exist: check for dataset_description.json in output folder msg = check_pipeline_version( @@ -96,7 +96,7 @@ def build_workflow(config_file, retval): if config.execution.fs_subjects_dir: init_msg += [f"Pre-run FreeSurfer's SUBJECTS_DIR: {config.execution.fs_subjects_dir}."] - build_log.log(25, f"\n{' ' * 11}* ".join(init_msg)) + build_log.log(25, f'\n{" " * 11}* '.join(init_msg)) retval['workflow'] = init_aslprep_wf() diff --git a/aslprep/config.py b/aslprep/config.py index 2f048c5ce..7052e3ff2 100644 --- a/aslprep/config.py +++ b/aslprep/config.py @@ -199,7 +199,7 @@ if _proc_oc_kbytes.exists(): _oc_limit = _proc_oc_kbytes.read_text().strip() if _oc_limit in ('0', 'n/a') and Path('/proc/sys/vm/overcommit_ratio').exists(): - _oc_limit = f"{Path('/proc/sys/vm/overcommit_ratio').read_text().strip()}%" + _oc_limit = f'{Path("/proc/sys/vm/overcommit_ratio").read_text().strip()}%' except Exception: # noqa: S110, BLE001 pass @@ -420,7 +420,7 @@ class execution(_Config): the command line) as spatial references for outputs.""" reports_only = False """Only build the reports, based on the reportlets found in a cached working directory.""" - run_uuid = f"{strftime('%Y%m%d-%H%M%S')}_{uuid4()}" + run_uuid = f'{strftime("%Y%m%d-%H%M%S")}_{uuid4()}' """Unique identifier of this particular run.""" participant_label = None """List of participant identifiers that are to be preprocessed.""" diff --git a/aslprep/interfaces/cbf.py b/aslprep/interfaces/cbf.py index 11fd383e2..8a78b4204 100644 --- a/aslprep/interfaces/cbf.py +++ b/aslprep/interfaces/cbf.py @@ -587,7 +587,7 @@ def _run_interface(self, runtime): else: raise ValueError( - f"Unknown BolusCutOffTechnique {metadata['BolusCutOffTechnique']}" + f'Unknown BolusCutOffTechnique {metadata["BolusCutOffTechnique"]}' ) # Q2TIPS uses TI2 instead of w (PLD), see Noguchi 2015 for this info. diff --git a/aslprep/interfaces/reports.py b/aslprep/interfaces/reports.py index 52fb922e2..8d33b9155 100644 --- a/aslprep/interfaces/reports.py +++ b/aslprep/interfaces/reports.py @@ -229,36 +229,36 @@ class CBFSummary(SummaryInterface): def _generate_segment(self): qcfile = pd.read_table(self.inputs.qc_file) motionparam = ( - f"FD : {round(qcfile['mean_fd'][0], 4)}, rmsd: {round(qcfile['rmsd'][0], 4)} " + f'FD : {round(qcfile["mean_fd"][0], 4)}, rmsd: {round(qcfile["rmsd"][0], 4)} ' ) coregindex = ( - f" Dice Index: {round(qcfile['coreg_dice'][0], 4)}, " - f"Correlation: {round(qcfile['coreg_correlation'][0], 4)}, " - f"Coverage: {round(qcfile['coreg_overlap'][0], 4)} " + f' Dice Index: {round(qcfile["coreg_dice"][0], 4)}, ' + f'Correlation: {round(qcfile["coreg_correlation"][0], 4)}, ' + f'Coverage: {round(qcfile["coreg_overlap"][0], 4)} ' ) normindex = ( - f" Dice Index: {round(qcfile['norm_dice'][0], 4)}, " - f"Correlation: {round(qcfile['norm_correlation'][0], 4)}, " - f"Coverage: {round(qcfile['norm_overlap'][0], 4)} " + f' Dice Index: {round(qcfile["norm_dice"][0], 4)}, ' + f'Correlation: {round(qcfile["norm_correlation"][0], 4)}, ' + f'Coverage: {round(qcfile["norm_overlap"][0], 4)} ' ) qei = ( - f"cbf: {round(qcfile['qei_cbf'][0], 4)}, " - f"score: {round(qcfile['qei_cbf_score'][0], 4)}, " - f"scrub: {round(qcfile['qei_cbf_scrub'][0], 4)}, " - f"basil: {round(qcfile['qei_cbf_basil'][0], 4)}, " - f"pvc: {round(qcfile['qei_cbf_basil_gm'][0], 4)} " + f'cbf: {round(qcfile["qei_cbf"][0], 4)}, ' + f'score: {round(qcfile["qei_cbf_score"][0], 4)}, ' + f'scrub: {round(qcfile["qei_cbf_scrub"][0], 4)}, ' + f'basil: {round(qcfile["qei_cbf_basil"][0], 4)}, ' + f'pvc: {round(qcfile["qei_cbf_basil_gm"][0], 4)} ' ) mean_cbf = ( - f"GM CBF: {round(qcfile['mean_gm_cbf'][0], 2)}, " - f"WM CBF: {round(qcfile['mean_wm_cbf'][0], 2)}, " - f"GM/WM CBF ratio: {round(qcfile['ratio_gm_wm_cbf'][0], 2)} " + f'GM CBF: {round(qcfile["mean_gm_cbf"][0], 2)}, ' + f'WM CBF: {round(qcfile["mean_wm_cbf"][0], 2)}, ' + f'GM/WM CBF ratio: {round(qcfile["ratio_gm_wm_cbf"][0], 2)} ' ) negvoxel = ( - f"cbf: {round(qcfile['percentage_negative_cbf'][0], 2)}, " - f"score: {round(qcfile['percentage_negative_cbf_score'][0], 2)}, " - f"scrub: {round(qcfile['percentage_negative_cbf_scrub'][0], 2)}, " - f"basil: {round(qcfile['percentage_negative_cbf_basil'][0], 2)}, " - f"pvc: {round(qcfile['percentage_negative_cbf_basil_gm'][0], 2)} " + f'cbf: {round(qcfile["percentage_negative_cbf"][0], 2)}, ' + f'score: {round(qcfile["percentage_negative_cbf_score"][0], 2)}, ' + f'scrub: {round(qcfile["percentage_negative_cbf_scrub"][0], 2)}, ' + f'basil: {round(qcfile["percentage_negative_cbf_basil"][0], 2)}, ' + f'pvc: {round(qcfile["percentage_negative_cbf_basil_gm"][0], 2)} ' ) if isdefined(self.inputs.confounds_file): diff --git a/aslprep/tests/run_local_tests.py b/aslprep/tests/run_local_tests.py index 5df27c389..da9dbcf10 100755 --- a/aslprep/tests/run_local_tests.py +++ b/aslprep/tests/run_local_tests.py @@ -60,7 +60,7 @@ def run_command(command, env=None): if process.returncode != 0: raise RuntimeError( - f'Non zero return code: {process.returncode}\n' f'{command}\n\n{process.stdout.read()}' + f'Non zero return code: {process.returncode}\n{command}\n\n{process.stdout.read()}' ) diff --git a/aslprep/tests/test_cli.py b/aslprep/tests/test_cli.py index a2b432bb3..a8c08db07 100644 --- a/aslprep/tests/test_cli.py +++ b/aslprep/tests/test_cli.py @@ -50,9 +50,9 @@ def test_examples_pasl_multipld(data_dir, output_dir, working_dir): '--use-syn-sdc', '--m0_scale=10', '--fs-no-reconall', - f"--fs-subjects-dir={os.path.join(data_dir, 'anatomical/freesurfer')}", + f'--fs-subjects-dir={os.path.join(data_dir, "anatomical/freesurfer")}', '--derivatives', - f"{os.path.join(data_dir, 'anatomical/smriprep')}", + f'{os.path.join(data_dir, "anatomical/smriprep")}', ] _run_and_fail(parameters) @@ -86,9 +86,9 @@ def test_examples_pcasl_multipld(data_dir, output_dir, working_dir): '--basil', '--m0_scale=10', '--fs-no-reconall', - f"--fs-subjects-dir={os.path.join(data_dir, 'anatomical/freesurfer')}", + f'--fs-subjects-dir={os.path.join(data_dir, "anatomical/freesurfer")}', '--derivatives', - f"{os.path.join(data_dir, 'anatomical/smriprep')}", + f'{os.path.join(data_dir, "anatomical/smriprep")}', ] _run_and_generate(TEST_NAME, PARTICIPANT_LABEL, parameters, out_dir) @@ -124,9 +124,9 @@ def test_examples_pcasl_singlepld_ge(data_dir, output_dir, working_dir): '--basil', '--m0_scale=96', '--fs-no-reconall', - f"--fs-subjects-dir={os.path.join(data_dir, 'anatomical/freesurfer')}", + f'--fs-subjects-dir={os.path.join(data_dir, "anatomical/freesurfer")}', '--derivatives', - f"{os.path.join(data_dir, 'anatomical/smriprep')}", + f'{os.path.join(data_dir, "anatomical/smriprep")}', ] _run_and_generate(TEST_NAME, PARTICIPANT_LABEL, parameters, out_dir) @@ -163,9 +163,9 @@ def test_examples_pcasl_singlepld_philips(data_dir, output_dir, working_dir): 'fsaverage:den-10k', '--scorescrub', '--basil', - f"--fs-subjects-dir={os.path.join(data_dir, 'anatomical/freesurfer')}", + f'--fs-subjects-dir={os.path.join(data_dir, "anatomical/freesurfer")}', '--derivatives', - f"{os.path.join(data_dir, 'anatomical/smriprep')}", + f'{os.path.join(data_dir, "anatomical/smriprep")}', ] _run_and_generate(TEST_NAME, PARTICIPANT_LABEL, parameters, out_dir) @@ -201,9 +201,9 @@ def test_examples_pcasl_singlepld_siemens(data_dir, output_dir, working_dir): '--basil', '--m0_scale=10', '--fs-no-reconall', - f"--fs-subjects-dir={os.path.join(data_dir, 'anatomical/freesurfer')}", + f'--fs-subjects-dir={os.path.join(data_dir, "anatomical/freesurfer")}', '--derivatives', - f"{os.path.join(data_dir, 'anatomical/smriprep')}", + f'{os.path.join(data_dir, "anatomical/smriprep")}', ] _run_and_generate(TEST_NAME, PARTICIPANT_LABEL, parameters, out_dir) @@ -239,9 +239,9 @@ def test_qtab(data_dir, output_dir, working_dir): '--use-syn-sdc', '--force-no-ge', '--fs-no-reconall', - f"--fs-subjects-dir={os.path.join(data_dir, 'anatomical/freesurfer')}", + f'--fs-subjects-dir={os.path.join(data_dir, "anatomical/freesurfer")}', '--derivatives', - f"{os.path.join(data_dir, 'anatomical/smriprep')}", + f'{os.path.join(data_dir, "anatomical/smriprep")}', ] _run_and_generate(TEST_NAME, PARTICIPANT_LABEL, parameters, out_dir) @@ -276,9 +276,9 @@ def test_test_001(data_dir, output_dir, working_dir): '--scorescrub', '--force-no-ge', '--fs-no-reconall', - f"--fs-subjects-dir={os.path.join(data_dir, 'anatomical/freesurfer')}", + f'--fs-subjects-dir={os.path.join(data_dir, "anatomical/freesurfer")}', '--derivatives', - f"{os.path.join(data_dir, 'anatomical/smriprep')}", + f'{os.path.join(data_dir, "anatomical/smriprep")}', ] _run_and_generate(TEST_NAME, PARTICIPANT_LABEL, parameters, out_dir) @@ -315,9 +315,9 @@ def test_test_002(data_dir, output_dir, working_dir): '--m0_scale=96', '--force-ge', '--fs-no-reconall', - f"--fs-subjects-dir={os.path.join(data_dir, 'anatomical/freesurfer')}", + f'--fs-subjects-dir={os.path.join(data_dir, "anatomical/freesurfer")}', '--derivatives', - f"{os.path.join(data_dir, 'anatomical/smriprep')}", + f'{os.path.join(data_dir, "anatomical/smriprep")}', ] _run_and_generate(TEST_NAME, PARTICIPANT_LABEL, parameters, out_dir) @@ -385,9 +385,9 @@ def base_test_003(data_dir, output_dir, working_dir, level, extra_params): 'asl', '--use-syn-sdc', '--m0_scale=10', - f"--fs-subjects-dir={os.path.join(data_dir, 'anatomical/freesurfer')}", + f'--fs-subjects-dir={os.path.join(data_dir, "anatomical/freesurfer")}', '--derivatives', - f"{os.path.join(data_dir, 'anatomical/smriprep')}", + f'{os.path.join(data_dir, "anatomical/smriprep")}', f'--level={level}', ] parameters += extra_params diff --git a/aslprep/tests/utils.py b/aslprep/tests/utils.py index bd3271b07..b4f4bc80c 100644 --- a/aslprep/tests/utils.py +++ b/aslprep/tests/utils.py @@ -45,7 +45,7 @@ def download_test_data(dset, data_dir=None): return if dset not in URLS: - raise ValueError(f"dset ({dset}) must be one of: {', '.join(URLS.keys())}") + raise ValueError(f'dset ({dset}) must be one of: {", ".join(URLS.keys())}') if not data_dir: data_dir = os.path.join(os.path.dirname(get_test_data_path()), 'test_data') diff --git a/aslprep/utils/bids.py b/aslprep/utils/bids.py index 74f840f73..4e23f47c1 100644 --- a/aslprep/utils/bids.py +++ b/aslprep/utils/bids.py @@ -101,11 +101,11 @@ def collect_run_data(layout, asl_file): elif asl_metadata['M0Type'] == 'Separate': m0scan_metadata = layout.get_file(run_data['m0scan']).get_metadata() if not m0scan_metadata: - raise Exception(f"No metadata for m0scan: {run_data['m0scan']}") + raise Exception(f'No metadata for m0scan: {run_data["m0scan"]}') elif run_data['m0scan']: raise ValueError( - f"M0Type is {run_data['asl_metadata']['M0Type']}, " - f"but an M0 scan was found at {run_data['m0scan']}" + f'M0Type is {run_data["asl_metadata"]["M0Type"]}, ' + f'but an M0 scan was found at {run_data["m0scan"]}' ) config.loggers.workflow.info( @@ -222,7 +222,7 @@ def write_derivative_description(bids_dir, deriv_dir): orig_desc = json.load(fobj) if 'DatasetDOI' in orig_desc: - desc['SourceDatasetsURLs'] = [f"https://doi.org/{orig_desc['DatasetDOI']}"] + desc['SourceDatasetsURLs'] = [f'https://doi.org/{orig_desc["DatasetDOI"]}'] if 'License' in orig_desc: desc['License'] = orig_desc['License'] diff --git a/aslprep/utils/cbf.py b/aslprep/utils/cbf.py index db80c8372..3545be7c3 100644 --- a/aslprep/utils/cbf.py +++ b/aslprep/utils/cbf.py @@ -806,8 +806,8 @@ def estimate_t1(metadata): t1blood = T1BLOOD_DICT.get(metadata['MagneticFieldStrength']) if not t1blood: config.loggers.interface.warning( - f"T1blood cannot be inferred for {metadata['MagneticFieldStrength']}T data. " - "Defaulting to formula from Zhang et al. (2013)." + f'T1blood cannot be inferred for {metadata["MagneticFieldStrength"]}T data. ' + 'Defaulting to formula from Zhang et al. (2013).' ) t1blood = (110 * metadata['MagneticFieldStrength'] + 1316) / 1000 @@ -820,7 +820,7 @@ def estimate_t1(metadata): t1tissue = T1TISSUE_DICT.get(metadata['MagneticFieldStrength']) if not t1tissue: raise ValueError( - f"T1tissue cannot be inferred for {metadata['MagneticFieldStrength']}T data." + f'T1tissue cannot be inferred for {metadata["MagneticFieldStrength"]}T data.' ) return t1blood, t1tissue diff --git a/aslprep/workflows/asl/cbf.py b/aslprep/workflows/asl/cbf.py index dbad344a8..6a3304ada 100644 --- a/aslprep/workflows/asl/cbf.py +++ b/aslprep/workflows/asl/cbf.py @@ -140,7 +140,7 @@ def init_cbf_wf( ) elif m0type == 'Estimate': m0_str = ( - f"A single M0 estimate of {metadata['M0Estimate']} was used to produce a calibration " + f'A single M0 estimate of {metadata["M0Estimate"]} was used to produce a calibration ' f"'image' and was scaled by {m0_scale}." ) else: diff --git a/aslprep/workflows/base.py b/aslprep/workflows/base.py index 6f8eaa91a..e27495dbc 100644 --- a/aslprep/workflows/base.py +++ b/aslprep/workflows/base.py @@ -58,7 +58,7 @@ def init_aslprep_wf(): spaces=config.workflow.spaces.get_fs_spaces(), minimum_fs_version='7.0.0', ), - name=f"fsdir_run_{config.execution.run_uuid.replace('-', '_')}", + name=f'fsdir_run_{config.execution.run_uuid.replace("-", "_")}', run_without_submitting=True, ) if config.execution.fs_subjects_dir is not None: @@ -190,9 +190,9 @@ def init_single_subject_wf(subject_id: str): if subject_data['roi']: warnings.warn( - f"Lesion mask {subject_data['roi']} found. " - "Future versions of fMRIPrep will use alternative conventions. " - "Please refer to the documentation before upgrading.", + f'Lesion mask {subject_data["roi"]} found. ' + 'Future versions of fMRIPrep will use alternative conventions. ' + 'Please refer to the documentation before upgrading.', FutureWarning, stacklevel=1, ) @@ -802,7 +802,7 @@ def map_fieldmap_estimation( for bold_file, estimator_key in all_estimators.items(): if len(estimator_key) > 1: config.loggers.workflow.warning( - f"Several fieldmaps <{', '.join(estimator_key)}> are " + f'Several fieldmaps <{", ".join(estimator_key)}> are ' f"'IntendedFor' <{bold_file}>, using {estimator_key[0]}" ) estimator_key[1:] = []