Skip to content

Commit 1e5acc6

Browse files
committed
Run ruff format.
1 parent 379d1e4 commit 1e5acc6

File tree

7 files changed

+115
-20
lines changed

7 files changed

+115
-20
lines changed

src/fmripost_template/cli/parser.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -185,11 +185,11 @@ def _bids_filter(value, parser):
185185
type=BIDSFilter,
186186
metavar='FILE',
187187
help=(
188-
"A JSON file describing custom BIDS input filters using PyBIDS. "
189-
"For further details, please check out "
190-
"https://fmriprep.readthedocs.io/en/"
191-
f"{currentv.base_version if is_release else 'latest'}/faq.html#"
192-
"how-do-I-select-only-certain-files-to-be-input-to-fMRIPrep"
188+
'A JSON file describing custom BIDS input filters using PyBIDS. '
189+
'For further details, please check out '
190+
'https://fmriprep.readthedocs.io/en/'
191+
f'{currentv.base_version if is_release else "latest"}/faq.html#'
192+
'how-do-I-select-only-certain-files-to-be-input-to-fMRIPrep'
193193
),
194194
)
195195
g_bids.add_argument(
@@ -546,8 +546,7 @@ def parse_args(args=None, namespace=None):
546546
from fmripost_template.utils.bids import validate_input_dir
547547

548548
build_log.info(
549-
'Making sure the input data is BIDS compliant '
550-
'(warnings can be ignored in most cases).'
549+
'Making sure the input data is BIDS compliant (warnings can be ignored in most cases).'
551550
)
552551
validate_input_dir(config.environment.exec_env, opts.bids_dir, opts.participant_label)
553552

@@ -567,8 +566,8 @@ def parse_args(args=None, namespace=None):
567566
missing_subjects = participant_label - set(all_subjects)
568567
if missing_subjects:
569568
parser.error(
570-
"One or more participant labels were not found in the BIDS directory: "
571-
f"{', '.join(missing_subjects)}."
569+
'One or more participant labels were not found in the BIDS directory: '
570+
f'{", ".join(missing_subjects)}.'
572571
)
573572

574573
config.execution.participant_label = sorted(participant_label)

src/fmripost_template/cli/workflow.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,11 +58,11 @@ def build_workflow(config_file, retval):
5858
notice_path = Path(pkgrf('fmripost_template', 'data/NOTICE'))
5959
if notice_path.exists():
6060
banner[0] += '\n'
61-
banner += [f"License NOTICE {'#' * 50}"]
61+
banner += [f'License NOTICE {"#" * 50}']
6262
banner += [f'fMRIPost-template {version}']
6363
banner += notice_path.read_text().splitlines(keepends=False)[1:]
6464
banner += ['#' * len(banner[1])]
65-
build_log.log(25, f"\n{' ' * 9}".join(banner))
65+
build_log.log(25, f'\n{" " * 9}'.join(banner))
6666

6767
# warn if older results exist: check for dataset_description.json in output folder
6868
msg = check_pipeline_version(
@@ -110,7 +110,7 @@ def build_workflow(config_file, retval):
110110
if config.execution.derivatives:
111111
init_msg += [f'Searching for derivatives: {config.execution.derivatives}.']
112112

113-
build_log.log(25, f"\n{' ' * 11}* ".join(init_msg))
113+
build_log.log(25, f'\n{" " * 11}* '.join(init_msg))
114114

115115
retval['workflow'] = init_fmripost_template_wf()
116116

src/fmripost_template/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,7 @@ class execution(_Config):
430430
the command line) as spatial references for outputs."""
431431
reports_only = False
432432
"""Only build the reports, based on the reportlets found in a cached working directory."""
433-
run_uuid = f"{strftime('%Y%m%d-%H%M%S')}_{uuid4()}"
433+
run_uuid = f'{strftime("%Y%m%d-%H%M%S")}_{uuid4()}'
434434
"""Unique identifier of this particular run."""
435435
participant_label = None
436436
"""List of participant identifiers that are to be preprocessed."""

src/fmripost_template/tests/run_local_tests.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ def run_command(command, env=None):
8383

8484
if process.returncode != 0:
8585
raise RuntimeError(
86-
f'Non zero return code: {process.returncode}\n' f'{command}\n\n{process.stdout.read()}'
86+
f'Non zero return code: {process.returncode}\n{command}\n\n{process.stdout.read()}'
8787
)
8888

8989

src/fmripost_template/tests/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ def run_command(command, env=None):
131131

132132
if process.returncode != 0:
133133
raise Exception(
134-
f'Non zero return code: {process.returncode}\n' f'{command}\n\n{process.stdout.read()}'
134+
f'Non zero return code: {process.returncode}\n{command}\n\n{process.stdout.read()}'
135135
)
136136

137137

src/fmripost_template/utils/utils.py

Lines changed: 97 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def _get_wf_name(bold_fname, prefix):
4343

4444
fname = split_filename(bold_fname)[1]
4545
fname_nosub = '_'.join(fname.split('_')[1:-1])
46-
return f"{prefix}_{fname_nosub.replace('-', '_')}_wf"
46+
return f'{prefix}_{fname_nosub.replace("-", "_")}_wf'
4747

4848

4949
def update_dict(orig_dict, new_dict):
@@ -70,3 +70,99 @@ def update_dict(orig_dict, new_dict):
7070
updated_dict[key] = value
7171

7272
return updated_dict
73+
74+
75+
def find_shortest_path(space_pairs, start, end):
76+
"""Find the shortest path between two spaces in a list of space pairs.
77+
78+
Parameters
79+
----------
80+
space_pairs : list of tuples
81+
List of tuples where each tuple contains two spaces of the form (from, to).
82+
start : str
83+
The starting space.
84+
end : str
85+
The ending space.
86+
87+
Returns
88+
-------
89+
list
90+
List of indices that represent the shortest path between the two spaces.
91+
92+
Raises
93+
------
94+
ValueError
95+
If no path exists between the two spaces.
96+
97+
Examples
98+
--------
99+
>>> space_pairs = [("a", "b"), ("a", "c"), ("b", "d"), ("c", "d")]
100+
>>> find_shortest_path(space_pairs, "a", "d")
101+
[0, 2]
102+
"""
103+
from collections import deque
104+
105+
# Create a graph from the space pairs and keep track of indices
106+
graph = {}
107+
index_map = {}
108+
for index, (src, dst) in enumerate(space_pairs):
109+
if src not in graph:
110+
graph[src] = []
111+
graph[src].append(dst)
112+
if src not in index_map:
113+
index_map[src] = []
114+
index_map[src].append(index)
115+
116+
# Perform BFS to find the shortest path
117+
queue = deque([(start, [start], [])])
118+
visited = set()
119+
120+
while queue:
121+
current, path, indices = queue.popleft()
122+
if current == end:
123+
return indices
124+
if current not in visited:
125+
visited.add(current)
126+
for neighbor, idx in zip(
127+
graph.get(current, []), index_map.get(current, []), strict=False
128+
):
129+
queue.append((neighbor, path + [neighbor], indices + [idx]))
130+
131+
raise ValueError(f'No path exists between {start} and {end}')
132+
133+
134+
def get_transforms(source, target, local_transforms=None):
135+
"""Get the transforms required to go from source to target space."""
136+
import templateflow.api as tflow
137+
from bids.layout import Entity, parse_file_entities
138+
139+
query = [
140+
Entity('template', 'tpl-([a-zA-Z0-9]+)'),
141+
Entity('from', 'from-([a-zA-Z0-9]+)'),
142+
]
143+
144+
all_transforms = local_transforms or []
145+
146+
templates = tflow.get_templates()
147+
for template in templates:
148+
template_transforms = tflow.get(template, suffix='xfm', extension='h5')
149+
if not isinstance(template_transforms, list):
150+
template_transforms = [template_transforms]
151+
all_transforms += template_transforms
152+
153+
links = []
154+
for transform in all_transforms:
155+
entities = parse_file_entities(transform, entities=query)
156+
link = (entities['from'], entities['template'])
157+
links.append(link)
158+
159+
path = None
160+
try:
161+
path = find_shortest_path(links, source, target)
162+
print('Shortest path:', path)
163+
except ValueError as e:
164+
print(e)
165+
166+
selected_transforms = [all_transforms[i] for i in path]
167+
168+
return selected_transforms

src/fmripost_template/workflows/base.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -182,10 +182,10 @@ def init_single_subject_wf(subject_id: str):
182182
if not subject_data['bold']:
183183
task_id = config.execution.task_id
184184
raise RuntimeError(
185-
f"No BOLD images found for participant {subject_id} and "
186-
f"task {task_id if task_id else '<all>'}. "
187-
"All workflows require BOLD images. "
188-
f"Please check your BIDS filters: {config.execution.bids_filters}."
185+
f'No BOLD images found for participant {subject_id} and '
186+
f'task {task_id if task_id else "<all>"}. '
187+
'All workflows require BOLD images. '
188+
f'Please check your BIDS filters: {config.execution.bids_filters}.'
189189
)
190190

191191
config.loggers.workflow.info(

0 commit comments

Comments
 (0)