-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlaunch
More file actions
executable file
·344 lines (296 loc) · 13.4 KB
/
launch
File metadata and controls
executable file
·344 lines (296 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#!/usr/bin/env python3
import os
import sys
import subprocess
import shutil
from pathlib import Path
SCRIPT_DIR = Path(__file__).parent
def load_ascii_art():
return """
███████╗███╗ ███╗██████╗ ██╗██████╗ ██████╗ ███████╗██████╗
██╔════╝████╗ ████║██╔══██╗██║██╔══██╗██╔══██╗██╔════╝██╔══██╗
█████╗ ██╔████╔██║██████╔╝██║██████╔╝██████╔╝█████╗ ██████╔╝
██╔══╝ ██║╚██╔╝██║██╔══██╗██║██╔═══╝ ██╔══██╗██╔══╝ ██╔═══╝
██║ ██║ ╚═╝ ██║██║ ██║██║██║ ██║ ██║███████╗██║
╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝
██╗ ██╗ ██████╗ ██████╗ ██╗ ██╗██████╗ ███████╗███╗ ██╗ ██████╗██╗ ██╗
██║ ██║██╔═══██╗██╔══██╗██║ ██╔╝██╔══██╗██╔════╝████╗ ██║██╔════╝██║ ██║
██║ █╗ ██║██║ ██║██████╔╝█████╔╝ ██████╔╝█████╗ ██╔██╗ ██║██║ ███████║
██║███╗██║██║ ██║██╔══██╗██╔═██╗ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██╔══██║
╚███╔███╔╝╚██████╔╝██║ ██║██║ ██╗██████╔╝███████╗██║ ╚████║╚██████╗██║ ██║
╚══╝╚══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚══════╝╚═╝ ╚═══╝ ╚═════╝╚═╝ ╚═╝
"""
class Colors:
HEADER = '\033[95m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def clear_screen():
"""Clear the screen using ANSI escape sequences for better compatibility with headless systems."""
# Flush stdout to ensure any pending output is written
sys.stdout.flush()
# Use ANSI escape sequences for more reliable clearing on headless systems
# \033[2J clears the entire screen
# \033[H moves cursor to home position (0,0)
sys.stdout.write('\033[2J\033[H')
sys.stdout.flush()
def get_terminal_size():
try:
columns, rows = shutil.get_terminal_size()
return columns, rows
except:
return 80, 24 # default fallback
def print_centered(text, color=None):
columns, _ = get_terminal_size()
text = text.strip()
if color:
formatted_text = f"{color}{text}{Colors.ENDC}"
else:
formatted_text = text
print(formatted_text.center(columns))
def print_header():
columns, _ = get_terminal_size()
print('\n')
print('=' * columns)
print_centered("FMRIPREP WORKBENCH: Main Menu", Colors.BOLD + Colors.BLUE)
print('=' * columns)
print('\n')
def display_ascii_art():
ascii_art = load_ascii_art()
print(ascii_art)
input(f"\n{Colors.GREEN}Press Enter to continue...{Colors.ENDC}")
clear_screen()
def get_user_input(prompt, options=None, default=None, yes_no=False):
if yes_no:
while True:
if default is not None:
default_text = "Y/n" if default else "y/N"
user_input = input(f"{prompt} [{default_text}]: ").strip().lower()
if user_input == "":
return default
else:
user_input = input(f"{prompt} [y/n]: ").strip().lower()
if user_input in ['y', 'yes']:
return True
elif user_input in ['n', 'no']:
return False
else:
print(f"{Colors.YELLOW}Please enter 'y' or 'n'.{Colors.ENDC}")
else:
while True:
if default is not None:
user_input = input(f"{prompt} [{default}]: ").strip()
if user_input == "":
return default
else:
user_input = input(f"{prompt}: ").strip()
if options is None:
if user_input: # ensure non-empty input
return user_input
else:
print(f"{Colors.YELLOW}Input cannot be empty.{Colors.ENDC}")
elif user_input in [str(o) for o in options]:
return user_input
else:
print(f"{Colors.YELLOW}Invalid input. Please enter one of: {', '.join([str(o) for o in options])}{Colors.ENDC}")
def display_menu():
print_header()
menu_items = [
("1", "Step 1: Download from FlyWheel -> Server"),
("2", "Step 2: Run dcm2niix (DICOM -> BIDS format conversion)"),
("3", "Step 3: Prep for fMRIPrep (remove dummy scans, update fmap JSON metadata, config fmap SDC)"),
("4", "Step 4: QC - Verify dcm -> nii -> bids metadata"),
("5", "Step 5: QC - Verify number of volumes per scan file"),
("6", "Step 6: Run fMRIPrep anatomical workflows only (if doing manual edits, otherwise skip to step 9)"),
("7", "Step 7: Download Freesurfer outputs for manual editing"),
("8", "Step 8: Upload edited Freesurfer outputs back to server"),
("9", "Step 9: Run remaining fMRIPrep steps (full anatomical + functional workflows)"),
("10", "FSL GLM: Setup new statistical model"),
("11", "FSL GLM: Run Level 1 analysis (individual runs)"),
("12", "FSL GLM: Run Level 2 analysis (subject-level)"),
("13", "FSL GLM: Run Level 3 analysis (group-level)"),
("14", "Utilities: Tarball/Untar utility for sourcedata/ BIDS directories")
]
print(f"{Colors.BOLD}Select the prep step you want to run:{Colors.ENDC}\n")
for key, description in menu_items:
print(f"{Colors.GREEN}{key}.{Colors.ENDC} {description}")
print()
options = [item[0] for item in menu_items]
step_choice = get_user_input("Enter your choice", options)
return step_choice
def get_parameters(step_choice):
step_params = {
"1": { # Step 1 (Flywheel Downloader)
"keys": ["fw_subid", "fw_session_id"],
"prompts": ["Subject ID on Flywheel?", "Session ID on Flywheel?"]
},
"2": { # Step 2 (dcm2niix BIDS)
"keys": ["fw_session_id", "new_bids_id_number", "skip_tar"],
"prompts": ["Session ID on Flywheel?", "What subject ID number would you like to assign for BIDS?", "Skip tar extraction (for manually configured scan directories)?"]
},
"3": { # Step 3 (Prep for fMRIPrep)
"keys": [],
"prompts": []
},
"4": { # Step 4 (QC metadata)
"keys": [],
"prompts": []
},
"5": { # Step 5 (QC volumes)
"keys": [],
"prompts": []
},
"6": { # Step 6 (fmriprep --anat-only)
"keys": [],
"prompts": []
},
"7": { # Freesurfer download
"keys": [],
"prompts": []
},
"8": { # Freesurfer upload
"keys": [],
"prompts": []
},
"9": { # Step 9 (fmriprep full)
"keys": [],
"prompts": []
},
"10": { # FSL GLM: Setup model
"keys": [],
"prompts": []
},
"11": { # FSL GLM: Level 1
"keys": ["model_name", "no_feat"],
"prompts": ["Model name?", "Only create FSF files without running FEAT?"]
},
"12": { # FSL GLM: Level 2
"keys": ["model_name", "no_feat"],
"prompts": ["Model name?", "Only create FSF files without running FEAT?"]
},
"13": { # FSL GLM: Level 3
"keys": ["model_name", "no_feat"],
"prompts": ["Model name?", "Only create FSF files without running FEAT?"]
},
"14": { # Tarball/Untar utility
"keys": ["operation", "sourcedata_dir", "subjects_spec", "keep_original"],
"prompts": [
"Operation (1=tar-all, 2=tar-subjects, 3=untar-all, 4=untar-subjects)",
"Path to sourcedata directory",
"Subject list (comma-separated IDs or file path, press Enter to skip for tar-all/untar-all)",
"Keep original directories after tarballing? (only for tar operations)"
]
}
}
param_keys = step_params[step_choice]["keys"]
param_prompts = step_params[step_choice]["prompts"]
user_inputs = []
# Special handling for tarball utility
if step_choice == "14":
# Get operation type
operation = get_user_input(param_prompts[0], options=["1", "2", "3", "4"])
operation_map = {
"1": "--tar-all",
"2": "--tar-subjects",
"3": "--untar-all",
"4": "--untar-subjects"
}
# Build command based on operation
if operation in ["2", "4"]:
# For tar-subjects/untar-subjects, need subject list
subjects_spec = get_user_input(param_prompts[2])
user_inputs.extend([operation_map[operation], subjects_spec])
else:
# For tar-all/untar-all
user_inputs.append(operation_map[operation])
# Get sourcedata directory
sourcedata_dir = get_user_input(param_prompts[1])
user_inputs.extend(["--sourcedata-dir", sourcedata_dir])
# Ask about keeping original only for tar operations
if operation in ["1", "2"]:
keep_original = get_user_input(param_prompts[3], yes_no=True, default=False)
if keep_original:
user_inputs.append("--keep-original")
return user_inputs, param_keys
# Regular parameter handling for other steps
for i in range(len(param_keys)):
key = param_keys[i]
prompt = param_prompts[i]
# special case for anat-only yes/no
if key == "anat_only":
response = get_user_input(prompt, yes_no=True)
if response:
user_inputs.append("--anat-only")
# special case for skip-tar yes/no
elif key == "skip_tar":
response = get_user_input(prompt, yes_no=True, default=False)
if response:
user_inputs.append("--skip-tar")
# special case for no_feat yes/no (FSL GLM)
elif key == "no_feat":
response = get_user_input(prompt, yes_no=True, default=False)
if response:
user_inputs.append("--no-feat")
else:
input_value = get_user_input(prompt)
user_inputs.append(input_value)
return user_inputs, param_keys
def confirm_parameters(user_inputs, param_keys):
if not user_inputs:
return True
print(f"\n{Colors.BOLD}You have entered the following parameters:{Colors.ENDC}")
for i, value in enumerate(user_inputs):
if i < len(param_keys):
key = param_keys[i]
print(f" {key}: {value}")
else:
print(f" Parameter {i}: {value}")
print()
return get_user_input("Proceed with execution?", yes_no=True, default=True)
def run_script(step_choice, user_inputs):
# map step choice to script name
scripts = {
"1": "01-run.sbatch",
"2": "02-run.sbatch",
"3": "03-run.sbatch",
"4": "04-run.sbatch",
"5": "05-run.sbatch",
"6": "06-run.sbatch",
"7": "toolbox/download_freesurfer.sh",
"8": "toolbox/upload_freesurfer.sh",
"9": "09-run.sbatch",
"10": "10-fsl-glm/setup_glm.sh",
"11": "11-run.sbatch",
"12": "12-run.sbatch",
"13": "13-run.sbatch",
"14": "toolbox/tarball_sourcedata.sh"
}
selected_script = scripts[step_choice]
cmd = ["bash", selected_script] + user_inputs
print(f"\n{Colors.BOLD}Executing:{Colors.ENDC} {' '.join(cmd)}")
try:
subprocess.run(cmd)
except Exception as e:
print(f"{Colors.RED}Error running script: {e}{Colors.ENDC}")
return False
return True
def main():
clear_screen()
display_ascii_art()
step_choice = display_menu()
clear_screen()
user_inputs, param_keys = get_parameters(step_choice)
if confirm_parameters(user_inputs, param_keys):
success = run_script(step_choice, user_inputs)
if success:
print(f"\n{Colors.GREEN}Script executed successfully.{Colors.ENDC}")
else:
print(f"\n{Colors.RED}Script execution failed.{Colors.ENDC}")
else:
print(f"\n{Colors.YELLOW}Operation cancelled.{Colors.ENDC}")
if __name__ == "__main__":
main()