-
Notifications
You must be signed in to change notification settings - Fork 50
/
MRIProcessingUtility.pm
executable file
·2404 lines (1862 loc) · 81.9 KB
/
MRIProcessingUtility.pm
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package NeuroDB::MRIProcessingUtility;
=pod
=head1 NAME
NeuroDB::MRIProcessingUtility -- Provides an interface for MRI processing
utilities
=head1 SYNOPSIS
use NeuroDB::ProcessingUtility;
my $utility = NeuroDB::MRIProcessingUtility->new(
$db, \$dbh, $debug, $TmpDir,
$logfile, $LogDir, $verbose
);
%tarchiveInfo = $utility->createTarchiveArray($ArchiveLocation);
my ($center_name, $centerID) = $utility->determinePSC(\%tarchiveInfo,0);
my $projectID = $utility->determineProjectID(\%tarchiveInfo);
my $scannerID = $utility->determineScannerID(\%tarchiveInfo, 0, $centerID, $projectID);
my $subjectIDsref = $utility->determineSubjectID(
$scannerID,
\%tarchiveInfo,
0
);
my $CandMismatchError = $utility->validateCandidate(
$subjectIDsref
);
$utility->computeSNR($TarchiveID, $ArchLoc);
$utility->orderModalitiesByAcq($TarchiveID, $ArchLoc);
=head1 DESCRIPTION
Mishmash of MRI processing utility functions used mainly by the insertion
scripts of LORIS.
=head2 Methods
=cut
use English;
use Carp;
use strict;
use warnings;
no warnings 'once';
use Data::Dumper;
use File::Basename;
use NeuroDB::File;
use NeuroDB::MRI;
use NeuroDB::DBI;
use NeuroDB::Notify;
use NeuroDB::ExitCodes;
use NeuroDB::Database;
use NeuroDB::DatabaseException;
use NeuroDB::objectBroker::ObjectBrokerException;
use NeuroDB::objectBroker::MriViolationsLogOB;
use NeuroDB::objectBroker::ConfigOB;
use NeuroDB::objectBroker::TarchiveOB;
use NeuroDB::objectBroker::MriUploadOB;
use Path::Class;
use Scalar::Util qw(blessed);
use DateTime;
use Time::Piece;
## Define Constants ##
my $notify_detailed = 'Y'; # notification_spool message flag for messages to be displayed
# with DETAILED OPTION in the front-end/imaging_uploader
my $notify_notsummary = 'N'; # notification_spool message flag for messages to be displayed
# with SUMMARY Option in the front-end/imaging_uploader
=pod
=head3 new($db, $dbhr, $debug, $TmpDir, $logfile, $verbose, $profile) >> (constructor)
Creates a new instance of this class. The parameter C<$dbhr> is a reference
to a C<DBI> database handle, used to set the object's database handle, so that
all the DB-driven methods will work.
INPUT:
- $db : database object
- $dbhr : DBI database handle reference
- $debug : degug flag (1 for debug, 0 otherwise)
- $TmpDir : temporay directory name (for tarchive extraction)
- $logfile : log file name
- $verbose : boolean flag for verbose behavior (1 lots of messages, 0 otherwise)
- $profile : path of the profile file
RETURNS: new instance of this class.
=cut
sub new {
my $params = shift;
my ($db, $dbhr, $debug, $TmpDir, $logfile, $verbose, $profile) = @_;
unless(defined $dbhr) {
croak(
"Usage: ".$params."->new(\$databaseHandleReference)"
);
}
unless(defined $db && blessed($db) && $db->isa('NeuroDB::Database')) {
croak(
"Usage: ".$params."->new(\$databaseObject)"
);
}
my $self = {};
############################################################
############### Create a settings package ##################
############################################################
{
package Settings;
do "$ENV{LORIS_CONFIG}/.loris_mri/$profile";
}
# ----------------------------------------------------------
## Create the ConfigOB
# ----------------------------------------------------------
my $configOB = NeuroDB::objectBroker::ConfigOB->new(db => $db);
############################################################
#### Create the log file and a Notify Object################
############################################################
my $LogDir = dirname($logfile);
my $file_name = basename($logfile);
my $dir = dir($LogDir);
my $file = $dir->file($file_name);
my $LOG = $file->openw();
my $Notify = NeuroDB::Notify->new( $dbhr );
$LOG->autoflush(1);
$self->{'Notify'} = $Notify;
$self->{'LOG'} = $LOG;
$self->{'verbose'} = $verbose;
$self->{'LogDir'} = $LogDir;
$self->{'dbhr'} = $dbhr;
$self->{'debug'} = $debug;
$self->{'TmpDir'} = $TmpDir;
$self->{'logfile'} = $logfile;
$self->{'db'} = $db;
$self->{'configOB'} = $configOB;
return bless $self, $params;
}
=pod
=head3 writeErrorLog($message, $failStatus, $LogDir)
Writes error log. This is a useful function that will close the log and write
error messages in case of abnormal program termination.
INPUTS:
- $message : notification message
- $failStatus: fail status of the process
- $LogDir : log directory
=cut
sub writeErrorLog {
my $this = shift;
my ($message, $failStatus, $LogDir) = @_;
print STDERR $message;
$this->{LOG}->print($message);
$this->{LOG}->print(
"program exit status: $failStatus"
);
`cat $this->{logfile} >> $this->{LogDir}/error.log`;
close $this->{LOG};
`rm -f $this->{logfile} `;
}
=pod
=head3 lookupNextVisitLabel($CandID, $dbhr)
Will look up for the next visit label of candidate C<CandID>. Useful only if
the visit label IS NOT encoded somewhere in the patient ID or patient name.
INPUTS:
- $CandID: candidate's C<CandID>
- $dbhr : database handle reference
RETURNS: next visit label found for the candidate
=cut
sub lookupNextVisitLabel {
my $this = shift;
my ($CandID, $dbhr) = @_;
my $visitLabel = 1;
my $query = "SELECT Visit_label FROM session".
" WHERE CandID=$CandID AND Active='Y'".
" ORDER BY ID DESC LIMIT 1";
if ($this->{debug}) {
print $query . "\n";
}
my $sth = $${dbhr}->prepare($query);
$sth->execute();
if ($sth->rows > 0) {
my @row = $sth->fetchrow_array();
$visitLabel = $row[0] + 1;
}
return $visitLabel;
}
=pod
=head3 getDICOMFileNamesfromSeriesUID($seriesuid, @alltarfiles)
Will extract from the C<tarchive_files> table a list of DICOM files
matching a given C<SeriesUID>.
INPUTS:
- $seriesUID : C<SeriesUID> to use for matching
- @alltarfiles: list of DICOM files matching the C<SeriesUID>
RETURNS: list of DICOM files corresponding to the C<SeriesUID>
=cut
sub getDICOMFileNamesfromSeriesUID {
# longest common prefix
sub LCP {
return '' unless @_;
my $prefix = shift;
for (@_) {
chop $prefix while (! /^\Q$prefix\E/);
}
return $prefix;
}
my $dbh = &NeuroDB::DBI::connect_to_db(@Settings::db);
my ($seriesuid, @alltarfiles) = @_;
my @filearray;
my $tarstring = ' --wildcards ';
my $query = "select tf.FileName from tarchive_files as tf".
" where tf.TarchiveID = (select distinct ts.tarchiveID from tarchive_series as ts where ts.SeriesUID=?)".
" and tf.SeriesNumber = (select distinct ts.SeriesNumber from tarchive_series as ts where ts.SeriesUID=?)".
" order by tf.FileNumber";
my $sth = $dbh->prepare($query);
$sth->execute($seriesuid, $seriesuid);
while (my $tf = $sth->fetchrow_hashref()) {
push @filearray, $tf->{'FileName'};
$tarstring .= "'*" . $tf->{'FileName'} . "' ";
}
my $lcp = LCP(@alltarfiles);
$tarstring =~ s/$lcp//g;
return $tarstring;
}
=pod
=head3 extract_tarchive($tarchive, $upload_id, $seriesuid)
Extracts the DICOM archive so that data can actually be uploaded.
INPUTS:
- $tarchive : path to the DICOM archive
- $upload_id: upload ID of the study
- $seriesuid: optionally a series UID
RETURNS: the extracted DICOM directory
=cut
sub extract_tarchive {
my $this = shift;
my ($tarchive, $upload_id, $seriesuid) = @_;
my $message = '';
my $tarnames = '';
# get the upload_id from the tarchive source location
# to pass to the notification_spool
$message = "\nExtracting tarchive $tarchive in $this->{TmpDir} \n";
$this->spool($message, 'N', $upload_id, $notify_detailed);
my $cmd = "cd $this->{TmpDir} ; tar -xf $tarchive";
$message = "\n" . $cmd . "\n";
$this->spool($message, 'N', $upload_id, $notify_detailed);
`$cmd`;
opendir TMPDIR, $this->{TmpDir};
my @tars = grep { /\.tar\.gz$/ && -f "$this->{TmpDir}/$_" }
readdir(TMPDIR);
closedir TMPDIR;
if (scalar(@tars) != 1) {
my $message = "Error: Could not find inner tar in $tarchive!\n";
print STDERR $message;
print @tars . "\n";
$this->spool($message, 'Y', $upload_id, $notify_notsummary);
exit $NeuroDB::ExitCodes::EXTRACTION_FAILURE;
}
my $dcmtar = $tars[0];
my $dcmdir = $dcmtar;
$dcmdir =~ s/\.tar\.gz$//;
if (defined($seriesuid)) {
print "seriesuid: $seriesuid\n" if $this->{verbose};
my @alltarfiles = `cd $this->{TmpDir} ; tar -tzf $dcmtar`;
$tarnames = getDICOMFileNamesfromSeriesUID($seriesuid, @alltarfiles);
print "tarnames: $tarnames\n" if $this->{verbose};
}
`cd $this->{TmpDir} ; tar -xzf $dcmtar $tarnames`;
return $dcmdir;
}
=pod
=head3 extractAndParseTarchive($tarchive, $upload_id, $seriesuid)
Extracts and parses the DICOM archive.
INPUTS:
- $tarchive : path to the DICOM archive
- $upload_id: upload ID of the study
- $seriesuid: optionally a series UID
RETURNS:
- $ExtractSuffix: extract suffix
- $study_dir : extracted study directory
- $header : study meta data header
=cut
sub extractAndParseTarchive {
my $this = shift;
my ($tarchive, $upload_id, $seriesuid) = @_;
my $study_dir = $this->{TmpDir} . "/" .
$this->extract_tarchive($tarchive, $upload_id, $seriesuid);
my $ExtractSuffix = basename($tarchive, ".tar");
# get rid of the tarchive Prefix
$ExtractSuffix =~ s/DCM_(\d{4}-\d{2}-\d{2})?_//;
my $info = "head -n 12 $this->{TmpDir}/${ExtractSuffix}.meta";
my $header = `$info`;
my $message = "\n$header\n";
$this->{LOG}->print($message);
$this->spool($message, 'N', $upload_id, $notify_detailed);
return ($ExtractSuffix, $study_dir, $header);
}
=pod
=head3 determineSubjectID($scannerID, $tarchiveInfo, $to_log, $upload_id, $User, $centerID)
This function does:
1) Determine subject's ID based on scanner ID and DICOM archive information.
2) Call the C<CreateMRICandidate> function (will create the candidate if it does
not exists and C<createCandidates> config option is set to yes)
3) Call the C<validateCandidate> to validate the candidate information
(it will return a C<CandMismatchError> if there is one)
INPUTS:
- $dbh : database handle
- $scannerID : scanner ID,
- $tarchiveInfo: DICOM archive information hash ref,
- $to_log : boolean if this step should be logged
- $upload_id : upload ID of the study
- $User : user running the insertion pipeline
- $centerID : center ID of the candidate
RETURNS: subject's ID hash ref containing C<CandID>, C<PSCID>, Visit Label,
ProjectID, CohortID and C<CandMismatchError> information
=cut
sub determineSubjectID {
my $this = shift;
my ($scannerID, $tarchiveInfo, $to_log, $upload_id, $User, $centerID) = @_;
my $dbhr = $this->{dbhr};
$to_log = 1 unless defined $to_log;
if (!defined(&Settings::getSubjectIDs)) {
if ($to_log) {
my $message = "\nERROR: Profile does not contain getSubjectIDs ".
"routine. Upload will exit now.\n\n";
$this->writeErrorLog(
$message, $NeuroDB::ExitCodes::PROJECT_CUSTOMIZATION_FAILURE
);
$this->spool($message, 'Y', $upload_id, $notify_notsummary);
exit $NeuroDB::ExitCodes::PROJECT_CUSTOMIZATION_FAILURE;
}
}
# determine the PSCID, CandID and Visit label based on PatientName or PatientID
my $patientID = $tarchiveInfo->{'PatientID'};
my $patientName = $tarchiveInfo->{'PatientName'};
my $subjectIDsref = Settings::getSubjectIDs(
$patientName, $patientID, $scannerID, $dbhr, $this->{'db'}
);
if (!$subjectIDsref->{'createVisitLabel'}) {
my $configOB = $this->{'configOB'};
$subjectIDsref->{'createVisitLabel'} = $configOB->getCreateVisit();
}
if (!$subjectIDsref->{'ProjectID'}) {
my $projectID = NeuroDB::MRI::getProject($subjectIDsref, $dbhr, $this->{'db'});
$subjectIDsref->{'ProjectID'} = $projectID;
}
if (!$subjectIDsref->{'CohortID'}) {
$subjectIDsref->{'CohortID'} = NeuroDB::MRI::getCohort(
$subjectIDsref, $subjectIDsref->{'ProjectID'}, $dbhr, $this->{'db'}
);
}
# create the candidate if it does not exist
$this->CreateMRICandidates(
$subjectIDsref, $tarchiveInfo, $User, $centerID, $upload_id
);
# check if the candidate information is valid
$subjectIDsref->{'CandMismatchError'} = $this->validateCandidate($subjectIDsref, $upload_id);
if ($to_log) {
my $message = sprintf(
"\n==> Data found for candidate CandID: %s, PSCID %s, Visit %s, Acquisition Date %s\n ",
$subjectIDsref->{'CandID'} // 'UNKNOWN',
$subjectIDsref->{'PSCID'} // 'UNKNOWN',
$subjectIDsref->{'visitLabel'} // 'UNKNOWN',
$tarchiveInfo->{'DateAcquired'} // 'UNKNOWN'
);
$this->{LOG}->print($message);
$this->spool($message, 'N', $upload_id, $notify_detailed);
}
# return the subjectID hash
return $subjectIDsref;
}
=pod
=head3 createTarchiveArray($tarchive)
Creates the DICOM archive information hash ref for the tarchive that has the same
basename as the file path passed as argument. For HRRT scanners, it will do the
same but from the hrrtarchive table.
INPUTS:
- $tarchive: tarchive's path (absolute or relative).
- $hrrt : whether the archive is from an HRRT scanner or not (in
which case, the C<hrrt_archive> table will be read
instead of the C<tarchive> table.
RETURNS: DICOM/HRRT archive information hash ref if exactly one archive was found. Exits
when either no match or multiple matches are found.
=cut
sub createTarchiveArray {
my $this = shift;
my ($tarchive, $hrrt) = @_;
if ($hrrt) {
my %tarchiveInfo;
(my $query = <<QUERY) =~ s/\n/ /gm;
SELECT
PatientName, CenterName, DateAcquired,
Blake2bArchive, ArchiveLocation, HrrtArchiveID
FROM
hrrt_archive
WHERE
ArchiveLocation LIKE ?
QUERY
if ($this->{debug}) {
print $query . "\n";
}
my $sth = ${$this->{'dbhr'}}->prepare($query);
$sth->execute("%".basename($tarchive)."%");
if ($sth->rows > 0) {
my $tarchiveInfoRef = $sth->fetchrow_hashref();
%tarchiveInfo = %$tarchiveInfoRef;
} else {
my $message = "\nERROR: Only archived data can be uploaded.".
"This seems not to be a valid archive for this study!".
"\n\n";
$this->writeErrorLog($message, $NeuroDB::ExitCodes::SELECT_FAILURE);
# no $tarchive can be fetched so $upload_id is undef
# in the notification_spool
$this->spool($message, 'Y', undef, $notify_notsummary);
exit $NeuroDB::ExitCodes::SELECT_FAILURE;
}
return %tarchiveInfo;
} else {
my $tarchiveOB = NeuroDB::objectBroker::TarchiveOB->new(db => $this->{'db'});
my $tarchiveInfoRef = $tarchiveOB->getByTarchiveLocation($tarchive);
if (!@$tarchiveInfoRef) {
my $message = "\nERROR: Only archived data can be uploaded.".
"This seems not to be a valid archive for this study!".
"\n\n";
$this->writeErrorLog($message, $NeuroDB::ExitCodes::SELECT_FAILURE);
# no $tarchive can be fetched so $upload_id is undef
# in the notification_spool
$this->spool($message, 'Y', undef, $notify_notsummary);
exit $NeuroDB::ExitCodes::SELECT_FAILURE;
} elsif (@$tarchiveInfoRef > 1) {
my $message = "\nERROR: Found multiple archives with the same basename ".
" as $tarchive when only one match was expected!".
"\n\n";
$this->writeErrorLog($message, $NeuroDB::ExitCodes::SELECT_FAILURE);
# Since multiple tarchives were found we cannot determine the upload ID
# Set it to undef for this notification
$this->spool($message, 'Y', undef, $notify_notsummary);
exit $NeuroDB::ExitCodes::SELECT_FAILURE;
}
# Only one archive matches: return it as a hash
return %{ $tarchiveInfoRef->[0] };
}
}
=pod
=head3 createMriUploadArray($uploadID)
Creates the MRI upload information hash ref for the uploadID passed as argument.
INPUTS:
- $uploadID: UploadID to query mri_upload
RETURNS: MRI upload information hash ref if found a row for UploadID in mri_upload.
Exits when either no match is found.
=cut
sub createMriUploadArray {
my $this = shift;
my ($uploadID) = @_;
my $mriUploadOB = NeuroDB::objectBroker::MriUploadOB->new(db => $this->{'db'});
my $mriUploadInfoRef = $mriUploadOB->getWithUploadID($uploadID);
if (!@$mriUploadInfoRef) {
my $message = "\nERROR: UploadID $uploadID not found in mri_upload\n\n";
$this->writeErrorLog($message, $NeuroDB::ExitCodes::SELECT_FAILURE);
# no $tarchive can be fetched so $upload_id is undef
# in the notification_spool
$this->spool($message, 'Y', undef, $notify_notsummary);
exit $NeuroDB::ExitCodes::SELECT_FAILURE;
}
# Only one upload: return it as a hash
return %{ $mriUploadInfoRef->[0] };
}
=pod
=head3 determinePSC($tarchiveInfo, $to_log, $upload_id)
Determines the PSC based on the DICOM archive information hash ref.
INPUTS:
- $tarchiveInfo: DICOM archive information hash ref
- $to_log : boolean, whether this step should be logged
- $upload_id : upload ID of the study
RETURNS: array of two elements: center name and center ID
=cut
sub determinePSC {
my $this = shift;
my ($tarchiveInfo, $to_log, $upload_id) = @_;
$to_log = 1 unless defined $to_log;
# ----------------------------------------------------------------
## Get config settings using ConfigOB
# ----------------------------------------------------------------
my $configOB = $this->{'configOB'};
my $lookupCenterNameUsing = $configOB->getLookupCenterNameUsing();
my ($center_name, $centerID) =
NeuroDB::MRI::getPSC(
$tarchiveInfo->{$lookupCenterNameUsing},
$this->{dbhr},
$this->{'db'}
);
if ($to_log) {
if (!$center_name) {
my $message = "\nERROR: No center found for this candidate \n\n";
$this->writeErrorLog(
$message, $NeuroDB::ExitCodes::SELECT_FAILURE
);
$this->spool($message, 'Y', $upload_id, $notify_notsummary);
exit $NeuroDB::ExitCodes::SELECT_FAILURE;
}
my $message = "\n==> Verifying acquisition center\n-> " .
"Center Name : $center_name\n-> CenterID ".
" : $centerID\n";
$this->{LOG}->print($message);
$this->spool($message, 'N', $upload_id, $notify_detailed);
}
return ($center_name, $centerID);
}
=pod
=head3 determineProjectID($tarchiveInfo)
Determines the Project.
INPUTS:
- $tarchiveInfo: archive information hash ref
RETURNS: project ID
=cut
sub determineProjectID {
my $this = shift;
my ($tarchiveInfo) = @_;
my $subjectIDsref = Settings::getSubjectIDs(
$tarchiveInfo->{'PatientName'},
undef,
undef,
$this->{dbhr},
$this->{db}
);
if (defined $subjectIDsref->{'ProjectID'}) {
return $subjectIDsref->{'ProjectID'}
}
return NeuroDB::MRI::getProject($subjectIDsref, $this->{dbhr}, $this->{db});
}
=pod
=head3 determineScannerID($tarchiveInfo, $to_log, $centerID, $projectID, $upload_id)
Determines which scanner ID was used for DICOM acquisitions. Note, if
a scanner ID is not already associated to the scanner information found
in the DICOM headers, then a new scanner will automatically be created.
INPUTS:
- $tarchiveInfo: archive information hash ref
- $to_log : whether this step should be logged
- $centerID : center ID
- $projectID : project ID
- $upload_id : upload ID of the study
RETURNS: scanner ID
=cut
sub determineScannerID {
my $this = shift;
my ($tarchiveInfo, $to_log, $centerID, $projectID, $upload_id) = @_;
my $message = '';
$to_log = 1 unless defined $to_log;
if ($to_log) {
$message = "\n\n==> Trying to determine scanner ID\n";
$this->{LOG}->print($message);
$this->spool($message, 'N', $upload_id, $notify_detailed);
}
my $scannerID =
NeuroDB::MRI::findScannerID(
$tarchiveInfo->{'ScannerManufacturer'},
$tarchiveInfo->{'ScannerModel'},
$tarchiveInfo->{'ScannerSerialNumber'},
$tarchiveInfo->{'ScannerSoftwareVersion'},
$centerID,
$projectID,
$this->{dbhr},
$this->{'db'}
);
if ($scannerID == 0) {
if ($to_log) {
$message = "\nERROR: The ScannerID for this particular scanner ".
"does not exist and could not be created.\n\n";
$this->writeErrorLog(
$message, $NeuroDB::ExitCodes::SELECT_FAILURE
);
$this->spool($message, 'Y', $upload_id, $notify_notsummary);
exit $NeuroDB::ExitCodes::SELECT_FAILURE;
}
}
if ($to_log) {
$message = "==> scanner ID : $scannerID\n\n";
$this->{LOG}->print($message);
$this->spool($message,'N', $upload_id, $notify_detailed);
}
return $scannerID;
}
=pod
=head3 get_acqusitions($study_dir, \@acquisitions)
UNUSED
=cut
sub get_acquisitions {
my $this = shift;
my ($study_dir, $acquisitions) = @_;
@$acquisitions =
split("\n", `find $study_dir -type d -name \\*.ACQ`);
my $message = "Acquisitions: ".join("\n", @$acquisitions)."\n";
if ($this->{verbose}){
$this->{LOG}->print($message);
}
}
=pod
=head3 computeMd5Hash($file, $upload_id)
Computes the MD5 hash of a file and makes sure it is unique.
INPUTS:
- $file : file to use to compute the MD5 hash
- $upload_id: upload ID of the study
RETURNS: 1 if the file is unique, 0 otherwise
=cut
sub computeMd5Hash {
my $this = shift;
my ($file, $upload_id) = @_;
my $message = '';
$message = "\n==> computing md5 hash for MINC body.\n";
$this->{LOG}->print($message);
$this->spool($message, 'N', $upload_id, $notify_detailed);
my $md5hash = &NeuroDB::MRI::compute_hash(\$file);
$message = "\n--> md5: $md5hash\n";
$this->{LOG}->print($message);
$this->spool($message, 'N', $upload_id, $notify_detailed);
$file->setParameter('md5hash', $md5hash);
my $unique = &NeuroDB::MRI::is_unique_hash(\$file);
return $unique;
}
=pod
=head3 getAcquisitionProtocol($file, $subjectIDsref, $tarchiveInfo, $centerID, $minc, $acquisitionProtocol, $bypass_extra_file_checks, $upload_id, $data_dir)
Determines the acquisition protocol and acquisition protocol ID for the MINC
file. If C<$acquisitionProtocol> is not set, it will look for the acquisition
protocol in the C<mri_protocol> table based on the MINC header information
using C<&NeuroDB::MRI::identify_scan_db>. If C<$bypass_extra_file_checks> is
true, then it will bypass the additional protocol checks from the
C<mri_protocol_checks> table using C<&extra_file_checks>.
INPUTS:
- $file : file's information hash ref
- $subjectIDsref : subject's information hash ref
- $tarchiveInfo : DICOM archive's information hash ref
- $centerID : ID of the center where the scan was acquired.
- $minc : absolute path to the MINC file
- $acquisitionProtocol : acquisition protocol if already knows it
- $bypass_extra_file_checks: boolean, if set bypass the extra checks
- $upload_id : upload ID of the study
- $data_dir : path to the LORIS MRI data directory
RETURNS:
- $acquisitionProtocol : acquisition protocol
- $acquisitionProtocolID : acquisition protocol ID
- $extra_validation_status : extra validation status ("pass", "exclude", "warning") or
C<undef> if C<$bypass_extra_file_checks> is set.
=cut
sub getAcquisitionProtocol {
my $this = shift;
my ($file,$subjectIDsref,$tarchiveInfoRef,$centerID,$minc,
$acquisitionProtocol,$bypass_extra_file_checks, $upload_id, $data_dir) = @_;
my $message = '';
############################################################
## get acquisition protocol (identify the volume) ##########
############################################################
if(!defined($acquisitionProtocol)) {
$message = "\n==> verifying acquisition protocol\n";
$this->{LOG}->print($message);
$this->spool($message, 'N', $upload_id, $notify_detailed);
$acquisitionProtocol = &NeuroDB::MRI::identify_scan_db(
$centerID,
$subjectIDsref,
$tarchiveInfoRef,
$file,
$this->{dbhr},
$this->{'db'},
$minc,
$upload_id,
$data_dir
);
}
$message = "\nAcquisition protocol is $acquisitionProtocol\n";
$this->{LOG}->print($message);
$this->spool($message, 'N', $upload_id, $notify_detailed);
my $extra_validation_status;
my $acquisitionProtocolID;
if ($acquisitionProtocol !~ /unknown/) {
$acquisitionProtocolID = NeuroDB::MRI::scan_type_text_to_id(
$acquisitionProtocol, $this->{'db'}
);
# if no acquisition protocol ID returned, look for the 'unknown' protocol ID
unless ($acquisitionProtocolID) {
$acquisitionProtocolID = NeuroDB::MRI::scan_type_text_to_id(
'unknown', $this->{'db'}
);
# if found an ID for 'unknown' scan type, then change protocol
# to be 'unknown', otherwise throw an error
if ($acquisitionProtocolID) {
$acquisitionProtocol = 'unknown';
} else {
NeuroDB::UnexpectedValueException->throw(
errorMessage => sprintf(
"Unknown acquisition protocol %s and scan type 'unknown' does not exist in the database",
$acquisitionProtocol
)
);
}
}
if ($bypass_extra_file_checks == 0) {
$extra_validation_status = $this->extra_file_checks(
$acquisitionProtocolID,
$file,
$subjectIDsref,
$tarchiveInfoRef->{'PatientName'},
$data_dir
);
$message = "\nextra_file_checks from table mri_protocol_check " .
"logged in table mri_violations_log: $extra_validation_status\n";
$this->{LOG}->print($message);
# 'warn' and 'exclude' are errors, while 'pass' is not
# log in the notification_spool_table the $Verbose flag accordingly
if ($extra_validation_status ne 'pass'){
$this->spool($message, 'Y', $upload_id, $notify_notsummary);
}
else {
$this->spool($message, 'N', $upload_id, $notify_detailed);
}
}
} else {
$acquisitionProtocolID = NeuroDB::MRI::scan_type_text_to_id(
$acquisitionProtocol, $this->{'db'}
);
}
return ($acquisitionProtocol, $acquisitionProtocolID, $extra_validation_status);
}
=pod
=head3 extra_file_checks($scan_type, $file, $subjectIdsref, $pname, $data_dir)
Returns the list of MRI protocol checks that failed. Can't directly insert
this information here since the file isn't registered in the database yet.
INPUTS:
- $scan_type : scan type of the file
- $file : file information hash ref
- $subjectIdsref: context information for the scan
- $pname : patient name found in the scan header
- $data_dir : path to the LORIS MRI data directory
RETURNS:
- pass, warn or exclude flag depending on the worst failed check
- array of failed checks if any were failed
=cut
sub extra_file_checks() {
my $this = shift;
my $scan_type = shift;
my $file = shift;
my $subjectIDsref = shift;
my $pname = shift;
my $data_dir = shift;
my $candID = $subjectIDsref->{'CandID'};
my $projectID = $subjectIDsref->{'ProjectID'};
my $cohortID = $subjectIDsref->{'CohortID'};
my $visitLabel = $subjectIDsref->{'visitLabel'};
## Step 1 - select all distinct exclude and warning headers for the scan type
my $query = "SELECT DISTINCT(mpc.Header) FROM mri_protocol_checks mpc "
. "JOIN mri_protocol_checks_group_target mpcgt USING(MriProtocolChecksGroupID) "
. "WHERE Scan_type=? AND Severity=?";
$query .= defined $projectID
? ' AND (mpcgt.ProjectID IS NULL OR mpcgt.ProjectID = ?)'
: ' AND mpcgt.ProjectID IS NULL';
$query .= defined $cohortID
? ' AND (mpcgt.CohortID IS NULL OR mpcgt.CohortID = ?)'
: ' AND mpcgt.CohortID IS NULL';
$query .= defined $visitLabel
? ' AND (mpcgt.Visit_label IS NULL OR mpcgt.Visit_label = ?)'
: ' AND mpcgt.Visit_label IS NULL';
my $sth = ${$this->{'dbhr'}}->prepare($query);
if ($this->{debug}) {
print $query . "\n";
}
# Step 2 - loop through all severities and grep headers, valid fields and
# check if the scan is valid. If the scan is not valid, then, return the
# severity of the failure.
foreach my $severity (qw/exclude warning/) {
my @bindValues = ($scan_type, $severity);
push(@bindValues, $projectID) if defined $projectID;
push(@bindValues, $cohortID) if defined $cohortID;
push(@bindValues, $visitLabel) if defined $visitLabel;
$sth->execute(@bindValues);
my @headers = map { $_->{'Header'} } @{ $sth->fetchall_arrayref({}) };
my %validFields = $this->loop_through_protocol_violations_checks(
$scan_type, $severity, \@headers, $file, $projectID, $cohortID, $visitLabel
);
if (%validFields) {
$this->insert_into_mri_violations_log(
\%validFields, $severity, $pname, $candID, $visitLabel, $file, $data_dir, $scan_type
);
return $severity;
}
}
## Step 3 - if we end up here, then the file passes the extra validation
# checks and return 'pass'
return ('pass');
}
=pod
=head3 update_mri_violations_log_MincFile_path($file_ref)
This function updates the C<MincFile> field of the C<mri_violations_log> table
with the file path present in the files table.
Note: this needs to be updated as by default the path is set to be in the C<trashbin>
directory when inserting into the C<mri_violations_log> table. However, if the
worst violation is set to 'warning', the MINC file will get inserted into the
C<files> table and moved to the C<assembly> directory, therefore it needs to be