-
Notifications
You must be signed in to change notification settings - Fork 51
/
MRI.pm
executable file
·1711 lines (1330 loc) · 57.4 KB
/
MRI.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::MRI;
=pod
=head1 NAME
NeuroDB::MRI -- A set of utility functions for performing common tasks
relating to MRI data (particularly with regards to registering MRI
files into the LORIS system)
=head1 SYNOPSIS
use NeuroDB::File;
use NeuroDB::MRI;
use NeuroDB::DBI;
my $dbh = NeuroDB::DBI::connect_to_db();
my $file = NeuroDB::File->new(\$dbh);
$file->loadFileFromDisk('/path/to/some/file');
$file->setFileData('CoordinateSpace', 'nonlinear');
$file->setParameter('patient_name', 'Larry Wall');
my $parameterTypeID = $file->getParameterTypeID('patient_name');
my $parameterTypeCategoryID = $file->getParameterTypeCategoryID('MRI Header');
=head1 DESCRIPTION
Really a mishmash of utility functions, primarily used by C<process_uploads> and
all of its children.
=head2 Methods
=cut
use Exporter();
use Math::Round;
use Time::JulianDay;
use File::Temp qw(tempdir);
use File::Basename;
use Data::Dumper;
use Carp;
use Time::Local;
use FindBin;
use Encode;
use DICOM::DICOM;
use NeuroDB::objectBroker::MriScanTypeOB;
use NeuroDB::objectBroker::MriScannerOB;
use NeuroDB::objectBroker::PSCOB;
use NeuroDB::UnexpectedValueException;
use NeuroDB::Notify;
$VERSION = 0.2;
@ISA = qw(Exporter);
# Number of decimals considered when testing if two floats are equal
$FLOAT_EQUALS_NB_DECIMALS = 4;
@EXPORT = qw();
@EXPORT_OK = qw(identify_scan in_range get_headers get_info get_ids get_objective identify_scan_db scan_type_text_to_id scan_type_id_to_text register_db get_header_hash get_scanner_id get_psc compute_hash is_unique_hash make_pics select_volume);
=pod
=head3 subjectIDExists($ID_type, ID_value, $dbhr)
Verifies that the subject ID (C<CandID> or C<PSCID>) exists.
INPUTS:
- $ID_type : type of candidate ID (C<CandID> or C<PSCID>)
- $ID_value: value of the candidate ID
- $dbhr : the database handle reference
RETURNS: 1 if the ID exists in the candidate table, 0 otherwise
=cut
sub subjectIDExists {
my ($ID_type, $ID_value, $dbhr) = @_;
# check if ID already exists in the candidate table
my $query = "SELECT COUNT(*) AS idExists FROM candidate WHERE $ID_type=?";
my $sth = $${dbhr}->prepare($query);
$sth->execute($ID_value);
my $rowhd = $sth->fetchrow_hashref();
return $rowhd->{'idExists'} > 0;
}
=pod
=head3 getScannerCandID($scannerID, $db)
Retrieves the candidate (C<CandID>) for the given scanner.
INPUTS: the scanner ID and the database object
RETURNS: the C<CandID> or (if none exists) undef
=cut
sub getScannerCandID {
my ($scannerID, $db) = @_;
my $mriScannerOB =
NeuroDB::objectBroker::MriScannerOB->new(db => $db);
my $resultRef = $mriScannerOB->get({ID => $scannerID});
return @$resultRef ? $resultRef->[0]->{'CandID'} : undef;
}
=pod
=head3 getSessionInformation($subjectIDref, $studyDate, $dbh, $db)
Gets information for the session with the given CandID and visitLabel
(contained inside the hashref C<$subjectIDref>). If no such session
exists, the method will try to create it using the supplied parameters.
INPUTS:
- $subjectIDref: hash reference of subject IDs
- $studyDate : study date
- $dbh : database handle
- $db : database object
RETURNS: an array of 2 elements:
- A reference to a hash containing the session properties:
C<ID> => session ID.
C<ProjectID> => project ID for the session.
C<SubprojectID> => sub-project ID for the session.
C<CandID> => candidate ID for the session.
C<Visit_label> => session visit label.
The reference will be C<undef> if the session cannot be retrieved/created.
- An error message (C<''> if no errors occured while retrieving/creating the session)
=cut
sub getSessionInformation {
my ($subjectIDref, $studyDate, $dbh, $db) = @_;
my ($sessionID, $studyDateJD);
my ($query, $sth);
# find a matching timepoint
$query = "SELECT ID, ProjectID, SubprojectID, CandID, Visit_label "
. "FROM session "
. "WHERE CandID=? "
. "AND LOWER(Visit_label)=LOWER(?) "
. "AND Active='Y'";
$sth = $dbh->prepare($query);
$sth->execute($subjectIDref->{'CandID'}, $subjectIDref->{'visitLabel'});
##### if it finds an existing session it does this:
if($sth->rows > 0) {
my $timepoint = $sth->fetchrow_hashref();
my %session = (
ID => $timepoint->{'ID'},
ProjectID => $timepoint->{'ProjectID'},
SubprojectID => $timepoint->{'SubprojectID'},
CandID => $timepoint->{'CandID'},
Visit_label => $timepoint->{'Visit_label'},
);
$sth->finish();
return (\%session, '');
}
if (!$subjectIDref->{'createVisitLabel'}) {
my $msg = sprintf(
"Visit %s for candidate %d does not exist.",
$subjectIDref->{'visitLabel'},
$subjectIDref->{'CandID'}
);
return (undef, $msg);
}
# Since we'll be creating a visit, ensure that the subprojectID and ProjectID
# have been defined in the profile file
if (!defined $subjectIDref->{'SubprojectID'}) {
return (undef, "Cannot create visit: profile file does not define the visit's SubprojectID");
}
if (!defined $subjectIDref->{'ProjectID'}) {
return (undef, "Cannot create visit: profile file does not define the visit's ProjectID");
}
# Ensure relationship between ProjectID and SubprojectID is legit
# according to project_subproject_rel. This also validates the existence
# of ProjectID and SubprojectID in tables Project and subproject respectively.
$query = "SELECT ProjectID, SubprojectID "
. "FROM project_subproject_rel "
. "WHERE ProjectID=? "
. "AND SubprojectID=?";
$sth = $dbh->prepare($query);
$sth->execute($subjectIDref->{'ProjectID'}, $subjectIDref->{'SubprojectID'});
# If there's no entry in project_subproject_rel for (ProjectID, SubprojectID)
if ($sth->rows == 0) {
my $msg = sprintf(
"Cannot create visit with project ID %d and sub-project ID %d: no such association in table %s",
$subjectIDref->{'ProjectID'},
$subjectIDref->{'SubprojectID'},
'project_subproject_rel'
);
return (undef, $msg);
}
# determine the visit number and centerID for the next session
my $newVisitNo = 0;
my $centerID = 0;
if($subjectIDref->{'isPhantom'}) {
# calibration data (PHANTOM_site_date | LIVING_PHANTOM_site_date | *test*)
my @pscInfo = getPSC($subjectIDref->{'visitLabel'}, $dbhr, $db);
$centerID = $pscInfo[1];
}
# determine the centerID and new visit number (which is now deprecated) if getPSC() failed.
if($centerID == 0) {
$query = "SELECT IFNULL(MAX(VisitNo), 0)+1 AS newVisitNo, CenterID "
. "FROM session "
. "WHERE CandID = ? "
. "GROUP BY CandID, CenterID";
$sth = $dbh->prepare($query);
$sth->execute($subjectIDref->{'CandID'});
if($sth->rows > 0) {
my $rowref = $sth->fetchrow_hashref();
$newVisitNo = $rowref->{'newVisitNo'};
$centerID = $rowref->{'CenterID'};
# fixme add some debug messages if this is to be kept
print "Set newVisitNo = $newVisitNo and centerID = $centerID\n";
} else {
$query = "SELECT RegistrationCenterID AS CenterID FROM candidate "
. "WHERE CandID=" . $dbh->quote($subjectIDref->{'CandID'});
$sth = $dbh->prepare($query);
$sth->execute();
if($sth->rows > 0) {
my $rowref = $sth->fetchrow_hashref();
$centerID = $rowref->{'CenterID'};
print "Set centerID = $centerID\n";
} else {
$centerID = 0;
print "No centerID\n";
}
}
}
$newVisitNo = 1 unless $newVisitNo;
$centerID = 0 unless $centerID;
# Insert the new session setting Current_stage to 'Not started' because that column is important
# to the behavioural data entry gui.
$query = "INSERT INTO session "
. "SET CandID = ?, "
. " Visit_label = ?, "
. " CenterID = ?, "
. " VisitNo = ?, "
. " Current_stage = 'Not Started', "
. " Scan_done = 'Y', "
. " Submitted = 'N', "
. " SubprojectID = ?, "
. " ProjectID = ?";
$dbh->do(
$query, undef,
$subjectIDref->{'CandID'},
$subjectIDref->{'visitLabel'},
$centerID,
$newVisitNo,
$subjectIDref->{'SubprojectID'},
$subjectIDref->{'ProjectID'}
);
$sessionID = $dbh->{'mysql_insertid'}; # retain id of inserted row
my %session = (
ID => $sessionID,
ProjectID => $subjectIDref->{'ProjectID'},
SubprojectID => $subjectIDref->{'SubprojectID'},
Visit_label => $subjectIDref->{'visitLabel'},
CandID => $subjectIDref->{'CandID'}
);
return (\%session, '');
}
=pod
=head3 identify_scan_db($psc, $subjectref, $tarchiveInfoRef, $fileref, $dbhr, $db, $minc_location, $uploadID)
Determines the type of the scan described by MINC headers based on
C<mri_protocol> table in the database.
INPUTS:
- $psc : center's name
- $subjectref : reference on the hash that contains the subject information
- $tarchiveInfoRef: reference on the tarchive
- $fileref : file hash ref
- $dbhr : database handle reference
- $db : database object
- $minc_location : location of the MINC files
- $uploadID : ID of the upload containing the scan
RETURNS: textual name of scan type from the C<mri_scan_type> table
=cut
sub identify_scan_db {
my ($psc, $subjectref, $tarchiveInfoRef, $fileref, $dbhr, $db, $minc_location, $uploadID) = @_;
my $candid = ${subjectref}->{'CandID'};
my $pscid = ${subjectref}->{'PSCID'};
my $visitLabel = ${subjectref}->{'visitLabel'};
my $projectID = ${subjectref}->{'ProjectID'};
my $subprojectID = ${subjectref}->{'SubprojectID'};
my $tarchiveID = $tarchiveInfoRef->{'TarchiveID'};
# get parameters from minc header
my $patient_name = ${fileref}->getParameter('patient_name');
my $xstep = ${fileref}->getParameter('xstep');
my $ystep = ${fileref}->getParameter('ystep');
my $zstep = ${fileref}->getParameter('zstep');
my $xspace = ${fileref}->getParameter('xspace');
my $yspace = ${fileref}->getParameter('yspace');
my $zspace = ${fileref}->getParameter('zspace');
my $slice_thickness = ${fileref}->getParameter('slice_thickness');
my $seriesUID = ${fileref}->getParameter('series_instance_uid');
my $series_description = ${fileref}->getParameter('series_description');
my $image_type = ${fileref}->getParameter('acquisition:image_type');
my $mriProtocolGroupID;
# get parameters specific to MRIs
my ($tr, $te, $ti, $time);
if ($fileref->{parameters}{modality} eq "MR") {
$tr = ${fileref}->getParameter('repetition_time');
$te = ${fileref}->getParameter('echo_time');
$ti = ${fileref}->getParameter('inversion_time');
if (defined($tr)) { $tr = &Math::Round::nearest(0.01, $tr*1000); }
if (defined($te)) { $te = &Math::Round::nearest(0.01, $te*1000); }
if (defined($ti)) { $ti = &Math::Round::nearest(0.01, $ti*1000); }
$time = ${fileref}->getParameter('time');
} elsif ($fileref->{parameters}{modality} eq "PT") {
# Place to add stuff specific to PET images
}
if(0) {
if ($fileref->{parameters}{modality} eq "MR") {
print "\ntr:\t$tr\nte:\t$te\nti:\t$ti\nst:\t$slice_thickness\n";
}
print "time;\t$time\n";
print "xspace:\t$xspace\nyspace:\t$yspace\nzspace:\t$zspace\n";
print "xstep:\t$xstep\nystep:\t$ystep\nzstep:\t$zstep\n";
}
# compute n_slices from DIMnele's
my $n_slices = 0;
# get ScannerID from DB
my $mriScannerOB = NeuroDB::objectBroker::MriScannerOB->new( db => $db );
my $resultsRef = $mriScannerOB->get( {
Manufacturer => $fileref->getParameter('manufacturer'),
Model => $fileref->getParameter('manufacturer_model_name'),
Serial_number => $fileref->getParameter('device_serial_number'),
Software => $fileref->getParameter('software_versions')
});
# default ScannerID to NULL if we have no better clue.
my $ScannerID = @$resultsRef> 0 ? $resultsRef->[0]->{'ID'} : undef;
#===========================================================#
# Get the list of lines in the mri_protocol table that #
# apply to the given scan based on the center name #
#===========================================================#
$query = "SELECT *
FROM mri_protocol
JOIN mri_protocol_group_target mpgt USING (MriProtocolGroupID)
WHERE (
(Center_name = ? AND ScannerID = ?)
OR ((Center_name='ZZZZ' OR Center_name='AAAA') AND ScannerID IS NULL))";
#============================================================#
# Add to the query the clause related to the Project ID, the #
# subproject ID and visit label. #
#============================================================#
$query .= defined $projectID
? ' AND (mpgt.ProjectID IS NULL OR mpgt.ProjectID = ?)'
: ' AND mpgt.ProjectID IS NULL';
$query .= defined $subprojectID
? ' AND (mpgt.SubprojectID IS NULL OR mpgt.SubprojectID = ?)'
: ' AND mpgt.SubprojectID IS NULL';
$query .= defined $visitLabel
? ' AND (mpgt.Visit_label IS NULL OR mpgt.Visit_label = ?)'
: ' AND mpgt.Visit_label IS NULL';
$query .= ' ORDER BY Center_name ASC, ScannerID DESC';
my @bindValues = ($psc, $ScannerID);
push(@bindValues, $projectID) if defined $projectID;
push(@bindValues, $subprojectID) if defined $subprojectID;
push(@bindValues, $visitLabel) if defined $visitLabel;
$sth = $${dbhr}->prepare($query);
$sth->execute(@bindValues);
my @rows = @{ $sth->fetchall_arrayref({}) };
# If no lines in the mri_protocol_group_target matches the ProjectID/SubprojectID/VisitLabel
# then no lines of the mri_protocol table can be used to identify the scan type. This is most
# likely a setup issue: mri_protocol/mri_protocol_group/mri_protocol_group_target do not cover
# all the cases. Warn.
if(@rows == 0) {
my $msg = "Warning! No protocol group can be used to determine the scan type "
. "of $minc_location.\nIncorrect/incomplete setup of table mri_protocol_group_target: "
. " setting scan type to 'unknown'";
print "$msg\n";
my $notify = NeuroDB::Notify->new( $dbhr );
$notify->spool('mri upload processing class', $msg, 0, 'MRI.pm', $uploadID, 'N', 'Y');
} else {
# If more than one line in the mri_protocol_group_target matches the ProjectID/SubprojectID/VisitLabel
# then table mri_protocol_group_target was not setup properly. Warn.
my %mriProtocolGroupIDs = map { $_->{'MriProtocolGroupID'} => 1 } @rows;
if(keys %mriProtocolGroupIDs > 1) {
my $msg = "Warning! More than one protocol group can be used to identify the scan type of $minc_location\n"
. "Ambiguous setup of table mri_protocol_group_target: setting scan type to 'unknown'";
print "$msg\n";
my $notify = NeuroDB::Notify->new( $dbhr );
$notify->spool('mri upload processing class', $msg, 0, 'MRI.pm', $uploadID, 'N', 'Y');
} else {
$mriProtocolGroupID = [ keys %mriProtocolGroupIDs ]->[0];
# check against all possible scan types
foreach my $rowref (@rows) {
my $sd_regex = $rowref->{'series_description_regex'};
my $tr_min = $rowref->{'TR_min'};
my $tr_max = $rowref->{'TR_max'};
my $te_min = $rowref->{'TE_min'};
my $te_max = $rowref->{'TE_max'};
my $ti_min = $rowref->{'TI_min'};
my $ti_max = $rowref->{'TI_max'};
my $xspace_min = $rowref->{'xspace_min'};
my $xspace_max = $rowref->{'xspace_max'};
my $yspace_min = $rowref->{'yspace_min'};
my $yspace_max = $rowref->{'yspace_max'};
my $zspace_min = $rowref->{'zspace_min'};
my $zspace_max = $rowref->{'zspace_max'};
my $xstep_min = $rowref->{'xstep_min'};
my $xstep_max = $rowref->{'xstep_max'};
my $ystep_min = $rowref->{'ystep_min'};
my $ystep_max = $rowref->{'ystep_max'};
my $zstep_min = $rowref->{'zstep_min'};
my $zstep_max = $rowref->{'zstep_max'};
my $time_min = $rowref->{'time_min'};
my $time_max = $rowref->{'time_max'};
my $slice_thick_min = $rowref->{'slice_thickness_min'};
my $slice_thick_max = $rowref->{'slice_thickness_max'};
if(0) {
print "\tChecking ".&scan_type_id_to_text($rowref->{'Scan_type'}, $db)." ($rowref->{'Scan_type'}) ($series_description =~ $sd_regex)\n";
print "\t";
if($sd_regex && ($series_description =~ /$sd_regex/i)) {
print "series_description\t";
}
print &in_range($tr, "$tr_min-$tr_max") ? "TR\t" : '';
print &in_range($te, "$te_min-$te_max") ? "TE\t" : '';
print &in_range($ti, "$ti_min-$ti_max") ? "TI\t" : '';
print &in_range($xspace, "$xspace_min-$xspace_max") ? "xspace\t" : '';
print &in_range($yspace, "$yspace_min-$yspace_max") ? "yspace\t" : '';
print &in_range($zspace, "$zspace_min-$zspace_max") ? "zspace\t" : '';
print &in_range($xstep, "$xstep_min-$xstep_max") ? "xstep\t" : '';
print &in_range($ystep, "$ystep_min-$ystep_max") ? "ystep\t" : '';
print &in_range($zstep, "$zstep_min-$zstep_max") ? "zstep\t" : '';
print &in_range($time, "$time_min-$time_max") ? "time\t" : '';
print &in_range($slice_thickness, "$slice_thick_min-$slice_thick_max") ? "ST\t" : '';
print "\n";
}
if ($sd_regex) {
if ($series_description =~ /$sd_regex/i) {
return &scan_type_id_to_text($rowref->{'Scan_type'}, $db);
}
} else {
if ( &in_range($tr, "$tr_min-$tr_max" )
&& &in_range($te, "$te_min-$te_max" )
&& &in_range($ti, "$ti_min-$ti_max" )
&& &in_range($xspace, "$xspace_min-$xspace_max" )
&& &in_range($yspace, "$yspace_min-$yspace_max" )
&& &in_range($zspace, "$zspace_min-$zspace_max" )
&& &in_range($xstep, "$xstep_min-$xstep_max" )
&& &in_range($ystep, "$ystep_min-$ystep_max" )
&& &in_range($zstep, "$zstep_min-$zstep_max" )
&& &in_range($time, "$time_min-$time_max" )
&& &in_range($slice_thickness, "$slice_thick_min-$slice_thick_max")
&& (!$rowref->{'image_type'} || $image_type =~ /\Q$rowref->{'image_type'}\E/i)
) {
return &scan_type_id_to_text($rowref->{'Scan_type'}, $db);
}
} # if ($sd_regex) .... else...
} # foreach my $rowref (@rows)....
} # if(keys %mriProtocolGroupIDs > 1)...else...
} # if (@rows==0)....else...
# if we got here, we're really clueless: insert scan in mri_protocol_violated_scans
# table. Note that $mriProtocolGroupID will be undef unless exactly one protocol
# group was used to try to identify the scan
insert_violated_scans(
$dbhr, $series_description, $minc_location, $patient_name,
$candid, $pscid, $tr, $te,
$ti, $slice_thickness, $xstep, $ystep,
$zstep, $xspace, $yspace, $zspace,
$time, $seriesUID, $tarchiveID, $image_type,
$mriProtocolGroupID
);
return 'unknown';
}
=pod
=head3 insert_violated_scans($dbhr, $series_desc, $minc_location, $patient_name, $candid, $pscid, $visit, $tr, $te, $ti, $slice_thickness, $xstep, $ystep, $zstep, $xspace, $yspace, $zspace, $time, $seriesUID)
Inserts scans that do not correspond to any of the defined protocol from the
C<mri_protocol> table into the C<mri_protocol_violated_scans> table of the
database.
INPUTS:
- $dbhr : database handle reference
- $series_desc : series description of the scan
- $minc_location : location of the MINC file
- $patient_name : patient name of the scan
- $candid : candidate's C<CandID>
- $pscid : candidate's C<PSCID>
- $visit : visit of the scan
- $tr : repetition time of the scan
- $te : echo time of the scan
- $ti : inversion time of the scan
- $slice_thickness: slice thickness of the image
- $xstep : C<x-step> of the image
- $ystep : C<y-step> of the image
- $zstep : C<z-step> of the image
- $xspace : C<x-space> of the image
- $yspace : C<y-space> of the image
- $zspace : C<z-space> of the image
- $time : time dimension of the scan
- $seriesUID : C<SeriesUID> of the scan
- $tarchiveID : C<TarchiveID> of the DICOM archive from which this file is derived
- $image_type : the C<image_type> header value of the image
- $mriProtocolGroupID : ID of the protocol group used to try to identify the scan.
=cut
sub insert_violated_scans {
my ($dbhr, $series_description, $minc_location, $patient_name,
$candid, $pscid, $tr, $te,
$ti, $slice_thickness, $xstep, $ystep,
$zstep, $xspace, $yspace, $zspace,
$time, $seriesUID, $tarchiveID, $image_type,
$mriProtocolGroupID) = @_;
# determine the future relative path when the file will be moved to
# data_dir/trashbin at the end of the script's execution
my $file_rel_path = get_trashbin_file_rel_path($minc_location);
(my $query = <<QUERY) =~ s/\n//gm;
INSERT INTO mri_protocol_violated_scans (
CandID, PSCID, TarchiveID, time_run,
series_description, minc_location, PatientName, TR_range,
TE_range, TI_range, slice_thickness_range, xspace_range,
yspace_range, zspace_range, xstep_range, ystep_range,
zstep_range, time_range, SeriesUID, image_type,
MriProtocolGroupID
) VALUES (
?, ?, ?, now(),
?, ?, ?, ?,
?, ?, ?, ?,
?, ?, ?, ?,
?, ?, ?, ?,
?
)
QUERY
my $sth = $${dbhr}->prepare($query);
my $success = $sth->execute(
$candid, $pscid, $tarchiveID, $series_description,
$file_rel_path, $patient_name, $tr, $te,
$ti, $slice_thickness, $xspace, $yspace,
$zspace, $xstep, $ystep, $zstep,
$time, $seriesUID, $image_type, $mriProtocolGroupID
);
}
=pod
=head3 scan_type_id_to_text($typeID, $db)
Determines the type of the scan identified by its scan type ID.
INPUTS:
- $typeID: scan type ID
- $db : database object
RETURNS: Textual name of scan type
=cut
sub scan_type_id_to_text {
my ($typeID, $db) = @_;
my $mriScanTypeOB = NeuroDB::objectBroker::MriScanTypeOB->new(
db => $db
);
my $mriScanTypeRef = $mriScanTypeOB->get(0, { ID => $typeID });
# This is just to make sure that there is a scan type in the DB
# with name 'unknown' in case we can't find the one with ID $ID
$mriScanTypeOB->get(0, { Scan_type => 'unknown' }) if !@$mriScanTypeRef;
if(!@$mriScanTypeRef) {
NeuroDB::UnexpectedValueException->throw(
errorMessage => sprintf(
"Unknown acquisition protocol ID %d and scan type 'unknown' does not exist in the database",
$typeID
)
);
}
return $mriScanTypeRef->[0]->{'Scan_type'};
}
=pod
=head3 scan_type_text_to_id($type, $db)
Determines the type of the scan identified by scan type.
INPUTS:
- $type: scan type
- $db : database object
RETURNS: ID of the scan type
=cut
sub scan_type_text_to_id {
my($type, $db) = @_;
my $mriScanTypeOB = NeuroDB::objectBroker::MriScanTypeOB->new(
db => $db
);
my $mriScanTypeRef = $mriScanTypeOB->get(
0, { Scan_type => $type }
);
$mriScanTypeRef = $mriScanTypeOB->get(0, { Scan_type => 'unknown' }) if !@$mriScanTypeRef;
if(!@$mriScanTypeRef) {
NeuroDB::UnexpectedValueException->throw(
errorMessage => sprintf(
"Unknown acquisition protocol %s and scan type 'unknown' does not exist in the database",
$type
)
);
}
return $mriScanTypeRef->[0]->{'ID'};
}
=pod
=head3 in_range($value, $range_string)
Determines whether numerical value falls within the range described by range
string. Range string is a single range unit which follows the syntax
"X" or "X-Y".
Note that if C<$range_string>="-", it means that the value in the database are
NULL for both the MIN and MAX columns, therefore we do not want to restrict the
range for this field and the function will return 1.
INPUTS:
- $value : numerical value to evaluate
- $range_string: the range to use
RETURNS: 1 if the value is in range or the range is undef, 0 otherwise
=cut
sub in_range
{
my ($value, $range_string) = @_;
chomp($value);
# return 1 if the range_string = "-" as it means that max & min values were undef
# when calling the in_range function and we should not restrict on that field
return 1 if $range_string eq "-";
# grep the min and max values of the range
my @range = split(/-/, $range_string);
my $min = $range[0];
my $max = $range[1];
# returns 1 if both $min and $max are undefined as in infinity range
return 1 if (!defined $min && !defined $max);
# returns 1 if min & max are defined and value is within the range [min-max]
return 1 if (defined $min && defined $max)
&& ( ($min <= $value && $value <= $max)
|| &floats_are_equal($value, $min, $FLOAT_EQUALS_NB_DECIMALS)
|| &floats_are_equal($value, $max, $FLOAT_EQUALS_NB_DECIMALS)
);
# returns 1 if only min is defined and value is <= to $min
return 1 if (defined $min and !defined $max)
&& ($min <= $value || &floats_are_equal($value, $min, $FLOAT_EQUALS_NB_DECIMALS));
# returns 1 if only max is defined and value is >= to $max
return 1 if (defined $max and !defined $min)
&& ($value <= $max || &floats_are_equal($value, $max, $FLOAT_EQUALS_NB_DECIMALS));
## if we've gotten this far, we're out of range.
return 0;
}
=pod
=head3 floats_are_equal($f1, $f2, $nb_decimals)
Checks whether float 1 and float 2 are equal (considers only the first
C<$nb_decimals> decimals).
INPUTS:
- $f1 : float 1
- $f2 : float 2
- $nb_decimals: the number of first decimals
RETURNS: 1 if the numbers are relatively equal, 0 otherwise
=cut
sub floats_are_equal {
my($f1, $f2, $nb_decimals) = @_;
return sprintf("%.${nb_decimals}g", $f1) eq sprintf("%.${nb_decimals}g", $f2);
}
=pod
=head3 register_db($file_ref)
Registers the C<NeuroDB::File> object referenced by C<$file_ref> into the
database.
INPUT: file hash ref
RETURNS: 0 if the file is already registered, the new C<FileID> otherwise
=cut
sub register_db {
my ($file_ref) = @_;
my $file = $$file_ref;
# get the database handle
my $dbh = ${$file->getDatabaseHandleRef()};
# retrieve the file's data
my $fileData = $file->getFileData();
# make sure this file isn't registered
if(defined($fileData->{'FileID'}) && $fileData->{'FileID'} > 0) {
return 0;
}
# build the insert query
my $query = "INSERT INTO files SET ";
my @field_array = (
'File', 'SessionID', 'EchoTime',
'CoordinateSpace', 'OutputType', 'AcquisitionProtocolID',
'FileType', 'InsertedByUserID', 'Caveat',
'SeriesUID', 'TarchiveSource', 'HrrtArchiveID',
'SourcePipeline', 'PipelineDate', 'SourceFileID',
'ScannerID', 'AcquisitionDate'
);
foreach my $key (@field_array) {
# add the key=value pair to the query
$query .= "$key=".$dbh->quote($${fileData{$key}}).", ";
}
$query .= "InsertTime=UNIX_TIMESTAMP()";
# run the query
$dbh->do($query);
my $fileID = $dbh->{'mysql_insertid'};
$file->setFileData('FileID', $fileID);
# retrieve the file's parameters
my $params = $file->getParameters();
# if there are any parameters to save
if(scalar(keys(%$params)) > 0) {
# build the insert query
$query = "INSERT INTO parameter_file (FileID, ParameterTypeID, Value, InsertTime) VALUES ";
foreach my $key (keys %$params) {
# skip the parameter if it is not defined
next unless defined $${params{$key}};
# add the parameter to the query
my $typeID = $file->getParameterTypeID($key);
my $value = '';
$value = $dbh->quote(encode_utf8($${params{$key}}));
if($query =~ /\)$/) { $query .= ",\n"; }
$query .= "($fileID, $typeID, $value, UNIX_TIMESTAMP())";
}
# run query
$dbh->do($query);
}
return $fileID;
}
=pod
=head3 mapDicomParameters($file_ref)
Maps DICOM parameters to more meaningful names in the C<NeuroDB::File> object
referenced by C<$file_ref>.
INPUT: file hash ref
=cut
sub mapDicomParameters {
my ($file_ref) = @_;
my $file = $$file_ref;
my (%map_hash);
%map_hash=
(
xstep => 'xspace:step',
ystep => 'yspace:step',
zstep => 'zspace:step',
xstart => 'xspace:start',
ystart => 'yspace:start',
zstart => 'zspace:start',
study_date => 'dicom_0x0008:el_0x0020',
series_date => 'dicom_0x0008:el_0x0021',
acquisition_date => 'dicom_0x0008:el_0x0022',
image_date => 'dicom_0x0008:el_0x0023',
study_time => 'dicom_0x0008:el_0x0030',
series_time => 'dicom_0x0008:el_0x0031',
acquisition_time => 'dicom_0x0008:el_0x0032',
image_time => 'dicom_0x0008:el_0x0033',
modality => 'dicom_0x0008:el_0x0060',
manufacturer => 'dicom_0x0008:el_0x0070',
institution_name =>'dicom_0x0008:el_0x0080',
study_description => 'dicom_0x0008:el_0x1030',
series_description => 'dicom_0x0008:el_0x103e',
operator_name => 'dicom_0x0008:el_0x1070',
manufacturer_model_name => 'dicom_0x0008:el_0x1090',
patient_name => 'dicom_0x0010:el_0x0010',
patient_id => 'dicom_0x0010:el_0x0020',
patient_dob => 'dicom_0x0010:el_0x0030',
patient_sex => 'dicom_0x0010:el_0x0040',
scanning_sequence => 'dicom_0x0018:el_0x0020',
mr_acquisition_type => 'dicom_0x0018:el_0x0023',
sequence_name => 'dicom_0x0018:el_0x0024',
sequence_variant => 'dicom_0x0018:el_0x0021',
slice_thickness => 'dicom_0x0018:el_0x0050',
effective_series_duration => 'dicom_0x0018:el_0x0072',
repetition_time => 'acquisition:repetition_time',
echo_time => 'acquisition:echo_time',
inversion_time => 'acquisition:inversion_time',
number_of_averages => 'dicom_0x0018:el_0x0083',
imaging_frequency => 'dicom_0x0018:el_0x0084',
imaged_nucleus => 'dicom_0x0018:el_0x0085',
echo_numbers => 'dicom_0x0018:el_0x0086',
magnetic_field_strength => 'dicom_0x0018:el_0x0087',
spacing_between_slices => 'dicom_0x0018:el_0x0088',
number_of_phase_encoding_steps => 'dicom_0x0018:el_0x0089',
echo_train_length => 'dicom_0x0018:el_0x0091',
percent_sampling => 'dicom_0x0018:el_0x0093',
percent_phase_field_of_view => 'dicom_0x0018:el_0x0094',
pixel_bandwidth => 'dicom_0x0018:el_0x0095',
device_serial_number => 'dicom_0x0018:el_0x1000',
software_versions => 'dicom_0x0018:el_0x1020',
protocol_name => 'dicom_0x0018:el_0x1030',
spatial_resolution => 'dicom_0x0018:el_0x1050',
fov_dimensions => 'dicom_0x0018:el_0x1149',
receiving_coil => 'dicom_0x0018:el_0x1250',
transmitting_coil => 'dicom_0x0018:el_0x1251',
acquisition_matrix => 'dicom_0x0018:el_0x1310',
phase_encoding_direction => 'dicom_0x0018:el_0x1312',
variable_flip_angle_flag => 'dicom_0x0018:el_0x1315',
sar => 'dicom_0x0018:el_0x1316',
patient_position => 'dicom_0x0018:el_0x5100',
study_instance_uid => 'dicom_0x0020:el_0x000d',
series_instance_uid => 'dicom_0x0020:el_0x000e',
study_id => 'dicom_0x0020:el_0x0010',
series_number => 'dicom_0x0020:el_0x0011',
acquisition_number => 'dicom_0x0020:el_0x0012',
instance_number => 'dicom_0x0020:el_0x0013',
image_position_patient => 'dicom_0x0020:el_0x0032',
image_orientation_patient => 'dicom_0x0020:el_0x0037',
frame_of_reference_uid => 'dicom_0x0020:el_0x0052',
laterality => 'dicom_0x0020:el_0x0060',
position_reference_indicator => 'dicom_0x0020:el_0x1040',
slice_location => 'dicom_0x0020:el_0x1041',
image_comments => 'dicom_0x0020:el_0x4000',
rows => 'dicom_0x0028:el_0x0010',
cols => 'dicom_0x0028:el_0x0011',
pixel_spacing => 'dicom_0x0028:el_0x0030',
bits_allocated => 'dicom_0x0028:el_0x0100',
bits_stored => 'dicom_0x0028:el_0x0101',
high_bit => 'dicom_0x0028:el_0x0102',
pixel_representation => 'dicom_0x0028:el_0x0103',
smallest_pixel_image_value => 'dicom_0x0028:el_0x0106',
largest_pixel_image_value => 'dicom_0x0028:el_0x0107',
pixel_padding_value => 'dicom_0x0028:el_0x0120',
window_center => 'dicom_0x0028:el_0x1050',
window_width => 'dicom_0x0028:el_0x1051',
window_center_width_explanation => 'dicom_0x0028:el_0x1055'
);
# map parameters, removing the old params if they start with 'dicom'
foreach my $key (keys %map_hash) {
my $value = $file->getParameter($map_hash{$key});
if(defined $value) {
$file->setParameter($key, $value);
$file->removeParameter($map_hash{$key}) if($map_hash{$key} =~ /^dicom/);
}
}
my $patientName = $file->getParameter('patient_name');
$patientName =~ s/[\?\(\)\\\/\^]//g;
$file->setParameter('patient_name', $patientName);
$patientName = $file->getParameter('patient:full_name');
$patientName =~ s/[\?\(\)\\\/\^]//g;
$file->setParameter('patient:full_name', $patientName);
}
=pod
=head3 findScannerID($manufacturer, $model, $serialNumber, $softwareVersion, $centerID, $dbhr, $db)
Finds the scanner ID for the scanner as defined by C<$manufacturer>, C<$model>,
C<$serialNumber>, C<$softwareVersion>, using the database attached to the DBI
database handle reference C<$dbhr>. If no scanner ID exists, one will be
created.
INPUTS:
- $manufacturer : scanner's manufacturer
- $model : scanner's model
- $serialNumber : scanner's serial number
- $softwareVersion: scanner's software version
- $centerID : scanner's center ID
- $dbhr : database handle reference
- $db : database object
RETURNS: (int) scanner ID
=cut
sub findScannerID {
my ($manufacturer, $model, $serialNumber, $softwareVersion, $centerID, $dbhr, $db) = @_;
my $mriScannerOB = NeuroDB::objectBroker::MriScannerOB->new( db => $db );
my $resultsRef = $mriScannerOB->get( {
Manufacturer => $manufacturer,
Model => $model,
Software => $softwareVersion,
Serial_number => $serialNumber
});
# Scanner exists
return $resultsRef->[0]->{'ID'} if @$resultsRef;
# register new scanners
my $scanner_id = registerScanner($manufacturer, $model, $serialNumber, $softwareVersion, $centerID, $dbhr, $db);
return $scanner_id;
}
=pod
=head3 registerScanner($manufacturer, $model, $serialNumber, $softwareVersion, $centerID, $dbhr, $db)
Registers the scanner as defined by C<$manufacturer>, C<$model>,
C<$serialNumber>, C<$softwareVersion>, into the database attached to the DBI
database handle reference C<$dbhr>.
INPUTS:
- $manufacturer : scanner's manufacturer
- $model : scanner's model
- $serialNumber : scanner's serial number
- $softwareVersion: scanner's software version
- $centerID : scanner's center ID
- $dbhr : database handle reference