-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfetch-dicom
executable file
·520 lines (511 loc) · 22.8 KB
/
fetch-dicom
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
#!/bin/bash# Extract a Single Subject's DICOM from CFMI File-Systems
## TODO -- make it a single date input and parse the date into yyyy/mm/dd
## -- IMPORTANT :: check all sessions for ID EXHAUSTIVELY! you can miss data this way
## -- take wild card as date input to search all days in month or all months in year
## -- provide option to ask user if he wants data
## -- what about extracting specific tasks?
## -- build database (update regularly)
# Default Arguments
## Output Data Here
o=$(pwd)
## Raw Data Directory Here (should be directory with ./years/mos/days)
r=${CFMIDICOMDIR}
## Subject Name
s=''
## Subject Scan Date
y=''
m=''
d=''
## Extract Specific Sequence?
t=''
## Exclude subject identifiers?
private=''
# Function Definitions
## Show the help documentation
function fetchdicom_help(){
[ ! -z ${DEBUG} ] && echo "fetchdicom_help"
helpstr=$(cat <<-EOF
Usage :: ${0##*/} [-h|--help] [-r|--rawdatadir PATH] [-o|--outputdir PATH] [-s|--subject]
\t\t\t[-y|--year YYYY] [-m|--month MM] [-d|--day DD] [-t|--tasks LIST]
Search for Seimens .IMA files in the raw data directory for a subject scanned on YYYY-MM-DD. User can specify tasks
for extraction, or leave blank to extract everything. Dicoms are placed in the output directory.
Required Arguments
\t-r --rawdatadir\t\tpath to dicoms (subdirectory tree must follow ./YYYY/MM/DD)
\t-o --outputdir\t\t\textract dicoms here
\t-s --subject\t\t\tsearch for subject ID
Optional Arguments
\t-y --year\t\t\tyear of scan date
\t-m --month\t\t\tmonth of scan date
\t-d --day\t\t\tday of scan date
\t-t --tasks\t\t\tlist of tasks to extract data for (series description)
\t-prv --private\t\t\tomit identifiers from meta data text file (will still be present in dcm headers)
Other Arguments
\t-h --help\t\t\tdisplays this message\n\n
EOF
)
echo -e "${helpstr}"
}
# Define Function
## Parse Input Arguments
function fetchdicom_parseoptions(){
[ ! -z ${DEBUG} ] && echo "fetchdicom_parseoptions"
while :; do
case ${1} in
-h|--help)
fetchdicom_help
exit
;;
-prv|--private)
private='omit identifiers'
;;
--debug)
DEBUG='debuggin'
;;
-r|--rawdatadir)
if [ -n "${2}" ]; then
r=${2}
shift
else
echo -e "ERROR -r --rawdatadir requires a non-empty option argument.\n" >&2
exit
fi
;;
-o|--outputdir)
if [ -n "${2}" ]; then
o=${2}
shift
else
echo -e "ERROR -o --outputdir requires a non-empty option argument.\n" >&2
exit
fi
;;
-s|--subject)
if [ -n "${2}" ]; then
s=${2}
shift
else
echo -e "Error -s --subject requires a non-empty option argument.\n" >2&
exit
fi
;;
-p|--pi)
if [ -n "${2}" ]; then
s=${2}
shift
else
echo -e "Error -p --pi requires a non-empty option argument.\n" >2&
exit
fi
;;
-y|--year)
if [ -n "${2}" ]; then
y=${2}
shift
else
echo -e "ERROR: -y --year requires a non-empty option argument.\n" >&2
exit
fi
;;
-m|--month)
if [ -n "${2}" ]; then
m=${2}
shift
else
echo "ERROR: -m --month requires a non-empty option argument.\n" >&2
exit
fi
;;
-d|--day)
if [ -n "${2}" ]; then
d=${2}
shift
else
echo -e "ERROR: -d --day requires a non-empty option argument.\n" >&2
exit
fi
;;
-t|--tasks)
if [ -n "${2}" ]; then
t=${2}
shift
else
echo -e "ERROR: -t --tasks requires a non-empty option argument.\n" >&2
exit
fi
;;
-?*)
printf 'WARN: Unknown option (ignored): %s\n' "$1" >&2
;;
*)
break
esac
shift
done
}
# Define Function
## Check for dependencies
function fetchdicom_dependencies(){
[ ! -z ${DEBUG} ] && echo "fetchdicom_dependencies"
# Check for AFNI
[ -z "$(which dicom_hdr)" ] && echo -e "\n❗️❗️ ERROR ❗️❗️ AFNI does not appear to be properly installed.. exiting..." && exit
# Check for GNU Parallel
[ -z "$(which parallel)" ] && echo -e "\n❗️❗️ ERROR ❗️❗️ GNU parallel does not appear to be properly installed.. exiting..." && exit
}
## TODO WORK IN PROGRESS ##
function fetchdicom_builddatabase(){
[ ! -z ${DEBUG} ] && echo "fetchdicom_builddatabase"
DBname=$(echo $(hostname)${r} | sed 's_/_|_g')
[ ! -d ${HOME}/.fetch-dicom.db ] && mkdir -pv ${HOME}/.fetch-dicom.db
# check if ${r} is found in existing DB
[ ! -f ${DBname} ] && tree --du --si -C -D ${r} -J | sed 's/},]/}]/g' > ${HOME}/.fetch-dicom.db/${DBname}.json
# now manipulate json file...
## 1. Add PI, Scan Date, SubjectID Scanner to Session
## 2. Add protocol and parameters to series
}
function fetchdicom_traversetree(){
[ ! -z ${DEBUG} ] && echo "fetchdicom_traversetree"
echo -e "\n🔍 Traversing DICOM Directory Tree: $(tree --du --si -C -D -L 1 ${r}) 📂 Searching for Session Data"
## TODO THIS METHOD IS NOT EFFICIENT
## -- BUILD DATABSE OF FOLDER TREE, STORE IN GLOBAL FETCH-DICOM DATABASE.. QUERY DATABASE TO SEARCH AND FIND DATA
## -- see above function fetchdicom_builddatabase
#basedirs=$(ls -ld * | awk '{print $NF}') # old code.. look in current directory for subject ID
#[ $(echo "${basedirs}" | grep "${s}") ] && studies=$(pwd)/$(ls -ld * | awk {'print $NF}' | grep "${s}")
#[ ! $(echo "${basedirs}" | grep "${s}") ] && studies=$(find ${r} -type d -name "*.STU" -print | xargs)
echo -e "\n🔍 Searching DICOM Directory Tree for *.STU Directories.. (this might take a while ☕️)" && studies=$(find ${r} -type d -name "*.STU" -print | xargs)
[ ! "${studies}" ] && echo -e "\n🚩 Session Folders *.STU Not Found... " && exit
#[ ! "${studies}" ] && echo -e "\n🚩 Session Folders *.STU Not Found, Searching for Series *.SER" && studies=$(find ${r} -type d -name "*.SER" -print | xargs)
studies_array=($(find ${r} -name "${studies}" -type d))
# check for existence of sessions if date and subject name is given
echo -e "\n📂 Searching ${#studies_array[*]} Session(s) for *.SER Data for Subject ${s}\n"
# echo "${studies}"
}
function fetchdicom_traversetreebydate(){
[ ! -z ${DEBUG} ] && echo "fetchdicom_traversetreebydate"
# Search for DICOM Assuming Date Organized File Hierarchy
## substitute year, month or day with wildcard if missing
[ ! ${y} ] && y='*'
[ ! ${m} ] && m='*'
[ ! ${d} ] && d='*'
## build local variables of absolute path to year, month and day
local year="${r}/${y}"
local month="${r}/${y}/${m}"
local day="${r}/${y}/${m}/${d}"
##
echo -e "\n🔍 Searching DICOM Directory Tree for Sessions Acquired on $y-$m-$d\n$(tree -d -L 1 ${day} --noreport)"
[ ! -d "${year}" ] && echo -e "\n❗️❗️ ERROR ❗️❗️ Raw Data Does Not Exist for Specified Year ${y}.. exiting..." && exit
[ ! -d "${month}" ] && echo -e "\n❗️❗️ ERROR ❗️❗️ Raw Data Does Not Exist for Specified Month ${m}.. exiting..." && exit
[ ! -d "${day}" ] && echo -e "\n❗️❗️ ERROR ❗️❗️ Raw Data Does Not Exist for Specified Day ${y}-${m}-${d}.. exiting..." && exit
## Create array of all studies in yyyy-mm-dd (wildcard compatible)
studies=$(find ${day}/ -name '*.STU' -type d -d 1)
studies_array=($(find ${day}/ -name '*.STU' -type d -d 1))
# check for existence of sessions if date and subject name is given
echo -e "\n📂 Searching ${#studies_array[*]} Session(s) for Subject ${s} on date(s) $y-$m-$d\n"
}
# Define Function
## Check if subject data exists
function fetchdicom_checkdataexists(){
[ ! -z ${DEBUG} ] && echo "fetchdicom_checkdataexists"
# Search for input subject
# TODO what if there is no input subject?
#[ -z "${s}" ] && echo "📌 Must specify subject ID -- dev TODO: show list of PIs, Projects, Subjects & Dates to choose from" && fetchdicom_help && exit
# Check if raw data directory exists, if individual years, months and days also exist (if input)
[ ! -d "${r}" ] && echo -e "\n❗️❗️ ERROR ❗️❗️ Raw Data Directory (${r}) Cannot be Found.. exiting..." && exit
# Traverse tree and find all .STUs
## by date
[ "${d}" ] || [ "${m}" ] || [ "${y}" ] && fetchdicom_traversetreebydate
## without date input
[ ! "${d}" ] || [ ! "${m}" ] || [ ! "${y}" ] && fetchdicom_traversetree
# Exception
[ -z "${studies}" ] && echo -e "\n❗️❗️ ERROR ❗️❗️ No Study Folders Ending in *.STU Can Be Found ... exiting.." && exit
##
}
# Define Function
##
function fetchdicom_parsedcmheader(){
[ ! -z ${DEBUG} ] && echo "fetchdicom_parsedcmheader"
# Takes path to dicom file as input and cds to dicom file directory (dicom_hdr only works if dicom file is in cwd)
## TODO - make this just take the first folder in the list
if [ -d ${1}/1.ACQ ]; then
acqs=${1}/1.ACQ
else
acqs=$(find ${1} -d 1 head -1)
fi
cd "${acqs}"
# No need to loop through .IMAs.. just grab meta data from first file in list
# local dicomfile=$(ls -dl *.IMA | tail -n +1 | head -1 | awk '{print $NF}')
local dicomfile=$(find . -name '*.IMA' | head -n 1)
dicom_header=$(dicom_hdr ${dicomfile})
# Get Subject Name
subject=$(dicom_hdr $dicomfile | grep 'Patient Name' | sed 's/.*\[.*\/\/\(.*\)/\1/')
# Get Series Name
seriesname=$(dicom_hdr $dicomfile | grep 'ID Series Description' | sed 's/.*\[.*\/\/\(.*\)/\1/')
# Get Subject Information Unless Private Information is Censored
[ -z ${private} ] && local age=$(dicom_hdr $dicomfile | grep 'Patient Age' | sed 's/.*\[.*\/\/\(.*\)/\1/')
[ -z ${private} ] && local sex=$(dicom_hdr $dicomfile | grep 'Patient Sex' | sed 's/.*\[.*\/\/\(.*\)/\1/')
[ -z ${private} ] && local wgt=$(dicom_hdr $dicomfile | grep 'Patient Weight' | sed 's/.*\[.*\/\/\(.*\)/\1/')
# Get PI Name
local piname=$(dicom_hdr $dicomfile | grep 'ID Study Description' | sed 's/.*\[.*\/\/\(.*\)/\1/')
# Get Type of Scanner
local hardware=$(dicom_hdr $dicomfile | grep 'ID Manufacturer Model Name' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local manufacturer=$(dicom_hdr $dicomfile | grep 'ID Manufacturer' | sed 's/.*\[.*\/\/\(.*\)/\1/') && manufacturer=$(echo ${manufacturer}) #<--uhh wut?
# Get Date & time
local scandate=$(dicom_hdr $dicomfile | grep 'ID Image Date' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local sesstime=$(dicom_hdr $dicomfile | grep 'PRC PPS Start Time' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local scantime=$(dicom_hdr $dicomfile | grep 'ID Image Time' | sed 's/.*\[.*\/\/\(.*\)/\1/')
# Get Information About Sequence Acquisition
local studydesc=$(dicom_hdr $dicomfile | grep 'ID Study Description' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local seqname=$(dicom_hdr $dicomfile | grep 'ACQ Sequence Name' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local thk=$(dicom_hdr $dicomfile | grep 'ACQ Slice Thickness' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local rt=$(dicom_hdr $dicomfile | grep 'ACQ Repetition Time' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local et=$(dicom_hdr $dicomfile | grep 'ACQ Echo Time' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local inversiontime=$(dicom_hdr $dicomfile | grep 'ACQ Inversion Time' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local imgf=$(dicom_hdr $dicomfile | grep 'ACQ Imaging Frequency' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local imgnuc=$(dicom_hdr $dicomfile | grep 'ACQ Imaged Nucleus' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local echnum=$(dicom_hdr $dicomfile | grep 'ACQ Echo Number' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local tesla=$(dicom_hdr $dicomfile | grep 'ACQ Magnetic Field Strength' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local slcspacing=$(dicom_hdr $dicomfile | grep 'ACQ Spacing Between Slices' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local phaseencstps=$(dicom_hdr $dicomfile | grep 'ACQ Number of Phase Encoding Steps' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local echtrl=$(dicom_hdr $dicomfile | grep 'ACQ Echo Train Length' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local persamp=$(dicom_hdr $dicomfile | grep 'ACQ Percent Sampling' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local perfov=$(dicom_hdr $dicomfile | grep 'ACQ Percent Phase Field of View' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local phzencd=$(dicom_hdr $dicomfile | grep 'ACQ Phase Encoding Direction' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local flipang=$(dicom_hdr $dicomfile | grep 'ACQ Flip Angle' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local sar=$(dicom_hdr $dicomfile | grep 'ACQ SAR' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local soundb=$(dicom_hdr $dicomfile | grep 'ACQ DB' | sed 's/.*\[.*\/\/\(.*\)/\1/')
local vers=$(dicom_hdr $dicomfile | grep 'ACQ Software Version' | sed 's/.*\[.*\/\/\(.*\)/\1/')
# Create Text
metadatum=$(cat <<-EOF
\n\n
--------------------------------------------------------------\n
${seriesname}\n
${ser}\n
PI\t\t\t${piname##PI\'s^}\n
Study Description\t${studydesc}\n
Scan Date\t\t${scandate}\n
Session Start Time\t${sesstime}\n
Sequence Start Time\t${scantime}\n
\n
Subject ID\t\t${subject}\n
Age\t\t\t${age}\n
Sex\t\t\t${sex}\n
Weight(kg)\t\t${wgt}\n
\n
\n
Acquisition Hardware -- ${manufacturer}\n
Acquisition Software -- ${vers}\n
\n
Internal Sequence Name\t\t${seqname}\n
Scanning Parameters ::\n
\n
\tMagnetic Field Str\t${tesla}T\n
\tRepetition Time\t\t${rt} ms\n
\tEcho Time\t\t${et} ms\n
\tInversion Time\t\t${inversiontime} ms\n
\tEcho Number\t\t${echnum}\n
\tEcho Train Length\t${echtrl}\n
\tPercent Sampling\t${persamp} %\n
\n
\tFlip Angle\t\t${flipang} deg\n
\tPhase Encoding\t\t${phzencd}\n
\tPhase Encoding Steps\t${phaseencstps}\n
\tPercent Phase FOV\t${perfov}%\n
\n
\tSlice Thickness\t\t${thk}mm\n
\tSlice Spacing\t\t${slcspacing}mm\n
\n
\tImaging Frequency\t${imgf}Hz\n
\tImaging Atom\t\t${imgnuc}\n
\n
Patient Safety ::\n
\tSAR\t\t${sar}\n
\tSound (dB)\t\t${soundb}\n
Sequence Description\t${seriesname}\n
;
EOF
)
## Print metadatum out to be captured as output from parallel
echo ${metadatum}
#
#
#end function
}
# Export Function for Parallelization
export -f fetchdicom_parsedcmheader
##
# Define Function
## Retrieve Meta Data About Studies on This Day
function fetchdicom_parsestudies(){
[ ! -z ${DEBUG} ] && echo "fetchdicom_parsestudies"
# array of series (equals -> num studies * (num series study 1 + num series study 2 + .. num series study N) )
series_array=()
# keep list of number of series for each study, number of series per study are counted in the for loop
numseries_array=()
# list of meta data for each acquired series (i.e MoCo, Localizer, MPRAGE, rest, etc.)
metadata_array=()
# index for loop
study_index=0
#printf "::\n"
# Begin loop over studies
while [ "${study_index}" -lt "${numstudies}" ]; do
## TODO
## Make this dependent on .IMA file NOT the .SER or .ACQ directory naming convention
## - use a find operation to find paths to .IMA then breakdown then iterate over those?
## - figure out how to parse output to parse dcmheader (should be doable.. and simpler!)
# check for existence of series in session
series=$(find ${studies_array[study_index]}/ -name '*.SER' -type d -d 1)
if [ -z "${series}" ]; then
echo -e "\n -- WARNING -- No Series Exist for Study ${studies_array[study_index]}.. skipping ${studies_array[study_index]}"
else
# build an indexed array of studies
series_array+=($(find ${studies_array[study_index]}/ -name '*.SER' -type d)) # ${studies_array[study_index]} works because it's within ${ ... } brackets.
# how many series are in each study? build an array we can index by study number (in alphanumeric order)
numseries_array+=("$(find ${studies_array[study_index]}/ -type d -name '*.SER' | wc -l) ")
# what are the total number of series that have been added to the series array thus far? use this with number of series in each study to only get series belonging to study number.. simple subtraction yo!
series_array_size=$(echo ${#series_array[*]})
# what is the current position in the series array? i.e. how many series in this study (use with series_array_size to get index for series belonging just to the study in the current loop cycle)
numseries_in_this_study=${numseries_array[*]:study_index}
# now that we have a list of series belonging to the study, let's loop across them in parallel and fetch their metadata
# -- capture output of fetchdicom_parsedcmheader as an array
## TODO ;; optimize parallel
capture_output=$(parallel -k fetchdicom_parsedcmheader {} ::: ${series_array[*]:series_array_size-numseries_in_this_study})
##
echo -en " ➤ ${studies_array[study_index]} :: ${numseries_in_this_study} series found\n"
# -- in order to add each set of metadata as an array we must modify the default field seperator to something that specifies a delimitation between each entry
local SAVEIFS=${IFS} && local IFS=$';' && metadata_array+=(${capture_output}) && local IFS=${SAVEIFS}
((study_index++))
fi
done
#
# end function
}
# Define Function
## Retrieve & Format Meta Data for Study
function fetchdicom_parsestudy(){
[ ! -z ${DEBUG} ] && echo "fetchdicom_parsestudy"
local study="${stu}"
# capture series
local series=$(echo -e ${metadata_array[*]:running_total:numseries_array[study_index]} | sed -n 's/Sequence Description//p')
# capture age
local age=$(echo -e ${metadata_array[*]:running_total:numseries_array[study_index]} | sed -n 's/Age//p' | uniq)
# capture sex
local sex=$(echo -e ${metadata_array[*]:running_total:numseries_array[study_index]} | sed -n 's/Sex//p' | uniq)
# capture weight
local weight=$(echo -e ${metadata_array[*]:running_total:numseries_array[study_index]} | sed -n 's/Weight(kg)//p' | uniq)
# capture PI
local PI=$(echo -e ${metadata_array[*]:running_total:numseries_array[study_index]} | sed -n "s/PI s^//p" | awk '{print $NF}' | uniq)
# capture scandate
local scandate=$(echo -e ${metadata_array[*]:running_total:numseries_array[study_index]} | sed -n 's/Scan Date//p' | uniq)
# capture session time
local sessionstarttime=$(echo -e ${metadata_array[*]:running_total:numseries_array[study_index]} | sed -n "s/Session Start Time//p" | uniq | sed 's/\..*//' | sed 's/.\{4\}/&:/; s/.\{7\}/&:/')
[ -z "${PI}" ] && PI="<unknown>"
local subject_info=$(cat <<-EOF
\n
♔ Study PI: ${PI}\n
✎ SID: ${subjects[study_index]}\n
✎ Session Date: $(date -d ${scandate} '+%b %d %Y')\n
\n
✎ Age:${age}\n
✎ Sex:${sex}\n
✎ Wgt:${weight}\n
✎ Series (In Order Acquired) ‣ Session Start Time: ${sessionstarttime}
EOF
)
echo -e ${subject_info}
echo "${series}" | nl
#echo -e ${metadata_array[*]:running_total:numseries_array[study_index]}
}
# Define Function
## Select Desired Series
function fetchdicom_selectseries(){
[ ! -z ${DEBUG} ] && echo "fetchdicom_selectseries"
echo 'work in progress'
}
# Define Function
## Copy Data in Parallel
function fetchdicom_copydata(){
[ ! -z ${DEBUG} ] && echo "fetchdicom_copydata"
# get name of desired series (this should be an input from fetchdicom_selectseries )
## note how all leading tabs, trailing spaces and commas are removed and replaced with underscores.. numers are prepended to indicate order and prevent merging
# task selection would have to happen somewhere before here
series=$(echo -e ${metadata_array[*]:running_total:numseries_array[study_index]} | sed -n 's/Sequence Description//p' | nl | awk '{$1=$1};1' | tr -s ',' ' ' | tr -s ' ' '_')
# first create folders
parallel -k mkdir -p "${o}"/"${p}"/"${s}"/"{}" ::: "${series}"
# now copy all series into correct folder
## TODO :: add functionality for session
parallel -k --link --bar rsync -aHAXv --delete "{1} ${o}/${p}/${s}/{2}/" > /dev/null ::: "${series_files[@]}" ::: "${series}"
}
# Define Function
## Parse Meta-Data
function fetchdicom_dataseek(){
[ ! -z ${DEBUG} ] && echo "fetchdicom_dataseek"
# count number of eleements
numstudies=${#studies_array[*]}
# Parse the Studies
fetchdicom_parsestudies
#echo -e "🗒 ${numstudies} Studies Found..." # print number of studies found on this date
# get list of subjects acquired on this day
subjects=()
pis=()
running_total=0
for study_index in $(seq 0 $(expr ${numstudies} - 1)); do
subjects+=($(echo -e ${metadata_array[*]:running_total:numseries_array[study_index]} | grep 'Subject ID' | awk '{print $NF}' | uniq | head -n 1))
pis+=($(echo -e ${metadata_array[*]:running_total:numseries_array[study_index]} | grep 'PI' | awk '{print $NF}' | uniq | head -n 1 | sed 's|^s||g'))
((running_total+=${numseries_array[study_index]}))
done
# echo found ... ${subjects[@]}
# echo in sessions ${studies_array[@]}
# index for loop
study_index=0
# running total of num series elapsed (used to index metadata array)
running_total=0
# print all subjects scanned on this date if no specific subject is input
if [ -z "${s}" ]; then
#echo 'Printing List of Subjects Scanned on This Day'
# loop over studies and print information
for stu in "${studies_array[@]}"; do # need to use @ instead of * to get delimited output (each sub as opposed to all subs on one line)
fetchdicom_parsestudy ${stu} # would be great to keep variables local and pass as arguments (need to figure out arrays)
((running_total+=${numseries_array[study_index]}))
((study_index++))
done
# index for loop
study_index=0 && running_total=0
fi
# cross reference subject list with the subject you are looking for
if [ ! -z "${s}" ]; then
# loop over subjects and find indices
## TODO - add ability to select specific series (use enumeration)
for sub in "${subjects[@]}"; do
if [ "${s}" = "${sub}" ]; then
### TODO make this part cleaner.. so that information about subject is printed
fetchdicom_parsestudy && series_files=(${series_array[*]:running_total:numseries_array[study_index]}) && fetchdicom_copydata && flag='subjectfound'
echo -e "$(fetchdicom_parsestudy)${metadata_array[*]:running_total:numseries_array[study_index]}\n\nThis file was generated on $(date) by $(whoami)@$(hostname)\n\n" > ${o}/${p}/${s}/session-info.txt
#break
elif [[ "{s}" = 'all' ]]; then
fetchdicom_parsestudy && series_files=(${series_array[*]:running_total:numseries_array[study_index]}) && fetchdicom_copydata && flag='subjectfound'
echo -e "$(fetchdicom_parsestudy)${metadata_array[*]:running_total:numseries_array[study_index]}\n\nThis file was generated on $(date) by $(whoami)@$(hostname)\n\n" > ${o}/${p}/${s}/session-info.txt
fi
((running_total+=numseries_array[study_index]))
((study_index++))
done
#[ -z "${flag}" ] && echo "ERROR SUBJECT NOT FOUND ON ${y}-${m}-${d}" && exit
fi
##
##
}
# Define Function
## Run sequence of functions for getting data
function fetchdicom_run(){
[ ! -z ${DEBUG} ] && echo "fetchdicom_run"
# Parse Options
fetchdicom_parseoptions "$@"
# Check that all dependencies are installed
fetchdicom_dependencies
# Check that the raw data path exists
fetchdicom_checkdataexists
# Traverse raw data tree and find dicom paths
fetchdicom_dataseek
}
# Redirect all standard input ($@) to run function and execute program
fetchdicom_run "$@"
#
##