forked from fvpolpeta/ADCmap.hpg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathADCmapFilter.m
1867 lines (1484 loc) · 70.5 KB
/
ADCmapFilter.m
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
//
// ADCmapFilter.m
// ADCmap
//
// Copyright (c) 2010 Brian. All rights reserved.
//
//
#import "ADCmapFilter.h"
#import "Horos/Wait.h"
#include "Horos/Notifications.h"
// To Do List:
// -Add "help" buttons
// -List image number, b-value for user.
// -Gray-out "Calculate" button unless enough b-values?
// KYUNG: I just added "gray-out" funtionality using KVC.
// Please look at "enableButton"!
// -Sort the b-values up front to simplify "non-neg" stuff.
//
#pragma mark-
#pragma mark Initialization Functions
@implementation ADCmapFilter
- (void) initPlugin
{
//NSLog(@"ADCmap Plugin Initiated.");
}
- (long) filterImage:(NSString*) menuName
{
NSString *msgstring;
NSLog(@"ADCmapFilter filterImage started.");
enableButton = YES;
nbvalues = [viewerController maxMovieIndex]; // Initially get all possible b values from 4D viewer.
//[bValueTable setDataSource:self]; // Set data-source, probably already done in IB.
// This Plugin gets b-values from DICOM header (GE) and then calculates ADC map from 4D viewer.
if (nbvalues >= 2) {
//NSRunInformationalAlertPanel(@"ADC map: (Test Version).",@"Currently expects b=600 and b=0 images - later will read this info from DICOM fields.",@"Continue", nil, nil);
// Initialize and show window.
//window = [[NSWindowController alloc] initWithWindowNibName:@"ADCwindow" owner:self];
//[window showWindow:self];
// Initialize and show window.
[NSBundle loadNibNamed:@"ADCwindow" owner:self];
//[NSApp beginSheet: ADCwindow
// modalForWindow: [NSApp keyWindow]
// modalDelegate: self
// didEndSelector: nil
// contextInfo: nil];
// Initialize threshold value
threshold = 0;
[thresholdField setStringValue:[NSString stringWithFormat:@"%g",threshold]];
showresidual=1;
// Initialize initial-guess values (mm^2/s)
initFp = 20;
[initFpField setStringValue:[NSString stringWithFormat:@"%g",initFp]];
initDt = 0.001;
[initDtField setStringValue:[NSString stringWithFormat:@"%g",initDt]];
initDp = 0.02;
[initDpField setStringValue:[NSString stringWithFormat:@"%g",initDp]];
ivimCutoff = 200;
[ivimCutoffField setStringValue:[NSString stringWithFormat:@"%g",ivimCutoff]];
// Check number of b-values, and limit if necessary.
if (nbvalues > MAXNBVALUES) {
msgstring = [[NSString alloc] initWithFormat:
@"Found %d B-Values, using only %d.",nbvalues, MAXNBVALUES ];
NSRunInformationalAlertPanel(@"ADCmap: ", msgstring, @"OK", nil, nil);
nbvalues = MAXNBVALUES;
}
// Get x,y,z size for 3D/multislice images at each b-value (assume they are the same)
zsize = [[viewerController pixList:0] count]; // #slices
DCMPix *curPix = [[ viewerController pixList:0] objectAtIndex:0]; // Get first slice, to get x,y sizes.
nxypts = [curPix pwidth] * [curPix pheight]; // #pts per slice
// Try to Get B values from DICOM header. (May vary with vendor...)
[self getBValues];
[bValueTable reloadData];
} else {
NSRunInformationalAlertPanel(@"Error:",@"ADC map requires 2 series/echoes/b-values in 4D viewer", @"OK", nil, nil);
}
// roiImageList is from "current slice" & "current time point"
imageView = [viewerController imageView];
roiImageList = [[viewerController roiList:[viewerController curMovieIndex]] objectAtIndex: [imageView curImage]];
[self drawGraph:self];
return 0; // Not sure what else we should do here?!
}
- (void) getBValues
// Attempt to read b values from DICOM header.
// This is be tricky with different vendors, and the fact that
// for a given vendor, there are often different ways these are
// encoded.
{
// This site helps: http://wiki.na-mic.org/Wiki/index.php/NAMIC_Wiki:DTI:DICOM_for_DWI_and_DTI#DICOM_for_DWI
//
DCMObject *dcmObject;
DCMPix *thisPix;
NSString *vendor;
int count;
double bvaldoubleprec;
// Get Vendor
thisPix = [[ viewerController pixList:0] objectAtIndex:0];
dcmObject = [DCMObject objectWithContentsOfFile:[thisPix sourceFile] decodingPixelData:NO];
vendor = [[[dcmObject attributeForTag:[DCMAttributeTag tagWithTagString:@"0008,0070"]] value] description];
//NSRunInformationalAlertPanel(@"Vendor:",vendor, @"OK", nil, nil);
NSLog(@"Vendor is %@",vendor);
NSString *bvaltag;
for (count=0; count < nbvalues; count++) {
thisPix = [[ viewerController pixList:count] objectAtIndex:0];
dcmObject = [DCMObject objectWithContentsOfFile:[thisPix sourceFile] decodingPixelData:NO];
// Read the b-value tag, based on vendor.
if ([vendor hasPrefix:@"GE"]) { // GE (See below also.)
bvaltag = [NSString stringWithFormat:@"0043,1039"];
// GE seems to encode multiple b-value scans with 1e9 added to bvalue.
// This seems to be addressed below.
}
else if ([vendor hasPrefix:@"S"]) { // Siemens
// Note web is 0019,000c, but images seem to show 0019,100c
bvaltag = [NSString stringWithFormat:@"0019,100C"];
}
// Based on Geoff Charles-Edwards' sample images Jan 5. Philips seems to follow 0018,9087 *AND* 2001,1003
else if ([vendor hasPrefix:@"P"]) { // Philips
bvaltag = [NSString stringWithFormat:@"2001,1003"];
}
else { // DICOM Recommendation (Note different from all 3 above!!)
bvaltag = [NSString stringWithFormat:@"0018,9087"];
}
NSLog(@"Vendor is %@, bvalue tag is %@",vendor,bvaltag);
NSLog(@"B value is %12g",bvaldoubleprec);
bvaldoubleprec = [[[[dcmObject attributeForTag:[DCMAttributeTag tagWithTagString:bvaltag]] value] description] doubleValue];
// GE seems to encode multiple b-value scans with 1e9 added to bvalue.
// Need double precision to capture/remove this, hence bvaldoubleprec.
if (bvaldoubleprec>=1000000000) {
bvaldoubleprec -= 1000000000;
}
bvals[count] = (float) bvaldoubleprec;
}
}
- (void) awakeFromNib
{
NSLog(@"ADCmapFilter awakeFromNib");
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(textChanged:)
name: NSTextViewDidChangeTypingAttributesNotification
object: nil];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(roiChanged:)
name: OsirixROIChangeNotification
object: nil];
//Set window to always be on top
[ADCwindow setLevel:NSFloatingWindowLevel];
}
#pragma mark-
#pragma mark GUI Response Functions
-(void)roiChanged:(NSNotification *) note
{
NSLog(@"ROI Changed!");
roiImageList = [[viewerController roiList:[viewerController curMovieIndex]] objectAtIndex: [imageView curImage]];
if( ([[note name] isEqualToString:@"roiChange"]) && ([[viewerController roiList] count ]>0))
{
//NSLog(@"name is %@",[note name]);
[self drawGraph: self];
}
}
- (IBAction)updateThreshold:(id)sender
// Updates the threshold value when set by user in GUI.
{
float threshVal = (float)([thresholdField floatValue]);
if ((threshVal > 0) && (threshVal <=100))
threshold = (float)((int)(threshVal*10))/10.0;
else
threshold = 0.0;
[thresholdField setStringValue:[NSString stringWithFormat:@"%g",threshold]];
}
- (IBAction)updateSynthBValue:(id)sender
// Updates the B-value for an image to synthesize when changed by user in GUI.
{
//NSLog(@"Synthesize Field Length = %u",[[synthBField stringValue] length]);
if (([[synthBField stringValue] length] > 0) && ([synthBField floatValue] >=0 ))
synthbvalue = [synthBField floatValue];
else
synthbvalue = -1; // Skip (don't synthesize an image)
NSLog(@"Synthesize B value = %g",synthbvalue);
}
- (IBAction)updateInitGuesses:(id)sender
// Updates the initial-guess values for biexponential fitting.
{
if (([[initFpField stringValue] length] > 0) && ([initFpField floatValue] >=0 ))
initFp = [initFpField floatValue]/100.0; // Convert from percent.
if (([[initDtField stringValue] length] > 0) && ([initDtField floatValue] >=0 ))
initDt = [initDtField floatValue];
if (([[initDpField stringValue] length] > 0) && ([initDpField floatValue] >=0 ))
initDp = [initDpField floatValue];
}
- (IBAction)updateIVIMCutoff:(id)sender
{
if (([[ivimCutoffField stringValue] length] > 0) && ([ivimCutoffField floatValue] >=0 ))
ivimCutoff = [ivimCutoffField floatValue];
[self drawGraph:self];
}
- (IBAction) negateBvalues:(id)sender
{
int count;
for (count=0; count < nbvalues; count++) {
bvals[count] = -bvals[count];
}
[bValueTable reloadData];
[self drawGraph:self];
}
- (IBAction) negateSelBvalues:(id)sender
// Negate b values for selected rows in table.
{
//NSLog(@"%ld Rows Selected",(long)[bValueTable numberOfSelectedRows]);
int count;
for (count = 0; count < nbvalues; count++) {
if ([[bValueTable selectedRowIndexes] containsIndex:count])
bvals[count]=-bvals[count];
}
[bValueTable reloadData];
[self drawGraph:self];
}
-(void) textChanged:(NSNotification *) note
{
NSLog(@"Text Changed!");
}
- (ViewerController*) copyFirstViewerWindow:(ViewerController*)currentViewer
{
// This was taken from copyViewerWindow in ViewerController.m
ViewerController *new2DViewer = nil;
// We will read our current series, and duplicate it by creating a new series!
//for( int v = 0; v < currentViewer.maxMovieIndex; v++)
for( int v = 0; v < 1; v++) // Just do 1st frame.
{
NSData *vD = nil;
NSMutableArray *newPixList = nil;
[currentViewer copyVolumeData: &vD andDCMPix:&newPixList forMovieIndex: v];
if( vD)
{
// We don't need to duplicate the DicomFile array, because it is identical!
// A 2D Viewer window needs 3 things:
// A mutable array composed of DCMPix objects
// A mutable array composed of DicomFile objects
// Number of DCMPix and DicomFile has to be EQUAL !
// NSData volumeData contains the images, represented in the DCMPix objects
if( new2DViewer == nil)
{
new2DViewer = [currentViewer newWindow:newPixList :[currentViewer fileList: v] :vD];
[new2DViewer roiDeleteAll: currentViewer];
}
else
[new2DViewer addMovieSerie:newPixList :[currentViewer fileList: v] :vD];
}
}
return new2DViewer;
}
#pragma mark-
#pragma mark Main Diffusion Fits
-(IBAction) calcBiExpMaps:(id)sender // Initially this is a copy of calcADC.
// Some consolidation would be good.
// !!! Would be nice to offer "Use IVIM fit for initial guess"
{
int minbind; // Index of minimum b-value
int cutoffindex=-1;
[self updateThreshold:sender];
[self updateSynthBValue:sender];
[self updateInitGuesses:sender];
nonnegconstraint = ([constraintOn state] == NSOnState);
showresidual = ([residualOn state] == NSOnState);
useIVIMinitguess = ([useIVIMguessOn state] == NSOnState);
float nonnegbvalues[MAXNBVALUES]; // Array of non-negative b-values (negative would be ignored)
int numnonnegbvalues = 0; // Number of non-negative b-values
int nonnegindices[MAXNBVALUES]; // Indices of images with non-negative b-values, in order.
int count1, count2;
// First get number of non-negative B values (eligible for ADC fit) Sorting is optional here, but easy.
numnonnegbvalues = sortbvalues(nbvalues, bvals, nonnegindices, nonnegbvalues);
// Check there are >= 3 non-negative B values
if (numnonnegbvalues >= 3) {
// Create new 2D viewers.
ViewerController *newDtViewer = [self copyFirstViewerWindow:self->viewerController];
ViewerController *newDpViewer = [self copyFirstViewerWindow:self->viewerController];
ViewerController *newFpViewer = [self copyFirstViewerWindow:self->viewerController];
ViewerController *newS0Viewer = [self copyFirstViewerWindow:self->viewerController];
ViewerController *residViewer = [self copyFirstViewerWindow:self->viewerController];
ViewerController *synthViewer;
NSMutableArray *synthImage;
float *synthpix = NULL;
int count;
float* bpixels[MAXNBVALUES]; // Pointer to pixels (images) for each b-value, for current slice.
// If synthesizing an image for given B-value, make another viewer.
if (synthbvalue >= 0) {
synthViewer = [self copyFirstViewerWindow:self->viewerController];
synthImage = [synthViewer pixList];
NSString *synthTitle = [NSString stringWithFormat:@"Synthesized b=%g",synthbvalue];
[[[synthViewer pixList] objectAtIndex:0] setGeneratedName:synthTitle];
}
if (nonnegconstraint) {
[[[newDtViewer pixList] objectAtIndex:0] setGeneratedName:@"Tissue Diffusion (x1e-6mm^2/s)c"];
[[[newDpViewer pixList] objectAtIndex:0] setGeneratedName:@"Pseudodiffusion (x1e-4mm^2/s)c"];
[[[newFpViewer pixList] objectAtIndex:0] setGeneratedName:@"Perfusion Fraction (%)c"];
} else {
[[[newDtViewer pixList] objectAtIndex:0] setGeneratedName:@"Tissue Diffusion (x1e-6mm^2/s)"];
[[[newDpViewer pixList] objectAtIndex:0] setGeneratedName:@"Pseudodiffusion (x1e-4mm^2/s)"];
[[[newFpViewer pixList] objectAtIndex:0] setGeneratedName:@"Perfusion Fraction (%)"];
}
[[[newS0Viewer pixList] objectAtIndex:0] setGeneratedName:@"Fitted Base Signal"];
[[[residViewer pixList] objectAtIndex:0] setGeneratedName:@"Fit Residual"];
// Initialize Wait window
Wait *splash = [[Wait alloc] initWithString:NSLocalizedString(@"Computing Biexponential Fit", nil)];
[splash showWindow:self];
[[splash progress] setMaxValue:zsize];
[splash setCancel: YES];
// Get pixel value from threshold percentage of max pixel in min-b-value image.
float thresholdPixVal = [self getThresholdPixValue:numnonnegbvalues
withindices:nonnegindices
withbvalues:nonnegbvalues];
NSMutableArray *newDtImage = [newDtViewer pixList]; // Get pointer to newly-allocated viewer.
NSMutableArray *newDpImage = [newDpViewer pixList]; // Get pointer to newly-allocated viewer.
NSMutableArray *newFpImage = [newFpViewer pixList]; // Get pointer to newly-allocated viewer.
NSMutableArray *newS0Image = [newS0Viewer pixList]; // Get pointer to newly-allocated viewer.
NSMutableArray *residImage = [residViewer pixList]; // Get pointer to newly-allocated viewer.
float *fittedDtPix;
float *fittedDpPix;
float *fittedFpPix;
float *fittedS0Pix;
float *residPix;
// Now calculate the biexponential fit.
for (count=0; count < zsize; count++) { // Repeat for each 2D slice in image.
for (count1=0; count1 < numnonnegbvalues; count1++) {
// Set pointer for ith non-negative B-value image to pass to calculation.
bpixels[count1] = [[[viewerController pixList:nonnegindices[count1]] objectAtIndex:count] fImage];
}
NSLog(@"%d non-negative b-values",numnonnegbvalues);
// Get pointers to current slice for each output.
fittedDtPix = [[newDtImage objectAtIndex:count] fImage];
fittedDpPix = [[newDpImage objectAtIndex:count] fImage];
fittedFpPix = [[newFpImage objectAtIndex:count] fImage];
fittedS0Pix = [[newS0Image objectAtIndex:count] fImage];
residPix = [[residImage objectAtIndex:count] fImage];
if (useIVIMinitguess) {
// Set initial estimates from IVIM fit
cutoffindex=-1; // Index of first b value over cutoff.
// First get number of non-negative B values and sort.
numnonnegbvalues = sortbvalues(nbvalues, bvals, nonnegindices, nonnegbvalues);
// Find where the cutoff B value for IVIM is in the list, and make sure there is at least
// one B=0 image, one image below cutoff, and 2 at/above cutoff.
count2=1; // Start at 1, need at least one value for Dp fit.
while ((count2<numnonnegbvalues-1) && (nonnegbvalues[count2]<ivimCutoff)) {
count2++;
}
if ((count2<numnonnegbvalues-1) && (nonnegbvalues[0]<1)) { // Found cutoff, and also B=0 image exists
cutoffindex = count2;
}
calcIvimFit(bpixels,nxypts, numnonnegbvalues, nonnegbvalues, cutoffindex, thresholdPixVal, fittedDtPix, fittedDpPix, fittedFpPix, fittedS0Pix, NULL, -1, NULL);
// These estimates are put in DICOM-friendly units by above, so need to convert back to physical.
for (count2=0; count2< nxypts; count2++) {
fittedFpPix[count2] /= 100.0; // Percentage to fraction 0-1
fittedDtPix[count2] /= DTCONVERT;
fittedDpPix[count2] /= DPCONVERT;
}
} else {
// Set initial estimates from UI (note S0Pix is not done this way).
fittedFpPix[0] = initFp;
fittedDtPix[0] = initDt;
fittedDpPix[0] = initDp;
// Set S0 estimate from minimum b-value image.
minbind = minind(nonnegbvalues, numnonnegbvalues);
fittedS0Pix[0] = bpixels[minbind][0]; // Get lowest b-val image as init guess
}
if (synthbvalue >= 0) {
synthpix = [[synthImage objectAtIndex:count] fImage];
}
calcBiExpFit(bpixels,nxypts, numnonnegbvalues, nonnegbvalues, thresholdPixVal, fittedDtPix, fittedDpPix, fittedFpPix, fittedS0Pix, residPix, synthbvalue, synthpix,nonnegconstraint,1-useIVIMinitguess);
[splash incrementBy: 1];
//if([splash aborted])
// count = zsize;
}
[newDtViewer refresh]; // Refresh viewer, since pixel values have been replaced
[newDpViewer refresh]; // Refresh viewer, since pixel values have been replaced
[newFpViewer refresh]; // Refresh viewer, since pixel values have been replaced
[newS0Viewer refresh]; // Refresh viewer, since pixel values have been replaced
[residViewer refresh]; // Refresh viewer, since pixel values have been replaced
// Update the current displayed WL & WW (automatic window)
[[newDtViewer imageView] setWLWW:1000 :2000];
[[newDpViewer imageView] setWLWW:1000 :2000];
[[newFpViewer imageView] setWLWW:50 :100];
if (synthbvalue >= 0) {
[synthViewer refresh]; // Refresh synthesized image viewer.
}
[splash close];
[splash release];
[self closeSheet:sender];
} else { // Not enough B-values, so display an error dialog box.
NSString *msgString = [NSString stringWithFormat:@"(%d found, up to %d expected)",numnonnegbvalues,nbvalues];
NSRunInformationalAlertPanel(@"Not Enough non-negative B-values (3 required)",msgString,@"Continue", nil, nil);
}
}
- (float)getThresholdPixValue:(int)numindices
withindices:(int *)indices
withbvalues:(float *)bvalues
{
int count, count1;
float *bpixels[MAXNBVALUES];
float thresholdPixVal=0.0;
float thresholdThisSlice;
for (count=0; count < zsize; count++) { // Repeat for each 2D slice in image.
for (count1=0; count1 < numindices; count1++) { // Repeat over all (non-negative) b-values
// Set pointer for ith non-negative B-value image to pass to calculation.
bpixels[count1] = [[[viewerController pixList:indices[count1]] objectAtIndex:count] fImage];
}
thresholdThisSlice = getThresholdPixValue(bpixels,nxypts,numindices, bvalues, threshold/100);
NSLog(@"Threshold for slice %d is %g",count+1,thresholdThisSlice);
if (thresholdThisSlice > thresholdPixVal)
thresholdPixVal = thresholdThisSlice;
}
return thresholdPixVal;
}
- (IBAction) calcADC:(id)sender
{
[self updateThreshold:sender];
[self updateSynthBValue:sender];
showresidual = ([residualOn state] == NSOnState);
float nonnegbvalues[MAXNBVALUES]; // Array of non-negative b-values (negative would be ignored)
int numnonnegbvalues = 0; // Number of non-negative b-values
int nonnegindices[MAXNBVALUES]; // Indices of images with non-negative b-values, in order.
int count1;
// First get number of non-negative B values (eligible for ADC fit) Sorting is optional here, but easy.
numnonnegbvalues = sortbvalues(nbvalues, bvals, nonnegindices, nonnegbvalues);
// Check there are >= 2 non-negative B values
if (numnonnegbvalues >= 2) {
// Create new 2D viewer.
ViewerController *new2DViewer = [self copyFirstViewerWindow:self->viewerController];
ViewerController *synthViewer;
ViewerController *residViewer;
NSMutableArray *adcImage = [new2DViewer pixList]; // Get pointer to newly-allocated viewer.
float *adcpix;
NSMutableArray *synthImage;
float *synthpix = NULL;
NSMutableArray *residImage;
float *residpix = NULL;
int count;
float* bpixels[MAXNBVALUES]; // Pointer to pixels (images) for each b-value, for current slice.
// If synthesizing an image for given B-value, make another viewer
if (synthbvalue >= 0) {
synthViewer = [self copyFirstViewerWindow:self->viewerController];
synthImage = [synthViewer pixList];
NSString *synthTitle = [NSString stringWithFormat:@"Synthesized b=%g",synthbvalue];
[[[synthViewer pixList] objectAtIndex:0] setGeneratedName:synthTitle];
}
// If synthesizing an image for given B-value, make another viewer
if (showresidual != 0) {
residViewer = [self copyFirstViewerWindow:self->viewerController];
residImage = [residViewer pixList];
NSString *residTitle = [NSString stringWithFormat:@"Residual"];
[[[residViewer pixList] objectAtIndex:0] setGeneratedName:residTitle];
}
// ** NONE OF THESE WORK!
//[[new2DViewer window] setTitle:@"ADC Map (x1e-6mm^2/s)"];
new2DViewer.windowTitle = @"ADC Map (x1e-6mm^2/s)";
//[[new2DViewer window] setTitle:@"ADC Map (x1e-6mm^2/s)"];
//[[new2DViewer imageView] checkCursor];
[[[new2DViewer pixList] objectAtIndex:0] setGeneratedName:@"ADC Map (x1e-6mm^2/s)"];
//NSRunInformationalAlertPanel(@"B-value Input: ",[[bValueList textStorage] string],@"Continue", nil, nil);
// Initialize Wait window
Wait *splash = [[Wait alloc] initWithString:NSLocalizedString(@"Computing ADC Map", nil)];
[splash showWindow:self];
[[splash progress] setMaxValue:zsize];
[splash setCancel: YES];
// Get pixel value from threshold percentage of max pixel in min-b-value image.
float thresholdPixVal = [self getThresholdPixValue:numnonnegbvalues
withindices:nonnegindices
withbvalues:nonnegbvalues];
// Now calculate the ADC map.
for (count=0; count < zsize; count++) { // Repeat for each 2D slice in image.
for (count1=0; count1 < numnonnegbvalues; count1++) {
// Set pointer for ith non-negative B-value image to pass to calculation.
bpixels[count1] = [[[viewerController pixList:nonnegindices[count1]] objectAtIndex:count] fImage];
}
NSLog(@"%d non-negative b-values",numnonnegbvalues);
adcpix = [[adcImage objectAtIndex:count] fImage];
if (synthbvalue >= 0) {
synthpix = [[synthImage objectAtIndex:count] fImage];
}
if (showresidual != 0) {
residpix = [[residImage objectAtIndex:count] fImage];
}
calcADCfit(bpixels,nxypts, numnonnegbvalues, nonnegbvalues, adcpix, residpix, thresholdPixVal, NULL, synthbvalue, synthpix);
[splash incrementBy: 1];
//if([splash aborted])
// count = zsize;
}
[new2DViewer refresh]; // Refresh viewer, since pixel values have been replaced with ADC map.
// Update the current displayed WL & WW (automatic window)
[[new2DViewer imageView] setWLWW:1000 :2000];
if (synthbvalue >= 0) {
[synthViewer refresh]; // Refresh synthesized image viewer.
}
[splash close];
[splash release];
[self closeSheet:sender];
} else { // Not enough B-values, so display an error dialog box.
NSString *msgString = [NSString stringWithFormat:@"(%d found, up to %d expected)",numnonnegbvalues,nbvalues];
NSRunInformationalAlertPanel(@"Not Enough non-negative B-values (2 required)",msgString,@"Continue", nil, nil);
}
}
- (IBAction) calcIVIM:(id)sender
{
[self updateIVIMCutoff:sender];
[self updateThreshold:sender];
[self updateSynthBValue:sender];
showresidual = ([residualOn state] == NSOnState);
float nonnegbvalues[MAXNBVALUES]; // Array of non-negative b-values (negative would be ignored)
int numnonnegbvalues = 0; // Number of non-negative b-values
int nonnegindices[MAXNBVALUES]; // Indices of images with non-negative b-values, in order.
int count1, count2;
int cutoffindex=-1; // Index of first b value over cutoff.
// First get number of non-negative B values and sort.
numnonnegbvalues = sortbvalues(nbvalues, bvals, nonnegindices, nonnegbvalues);
// Find where the cutoff B value for IVIM is in the list, and make sure there is at least
// one B=0 image, one image below cutoff, and 2 at/above cutoff.
count2=1; // Start at 1, need at least one value for Dp fit.
while ((count2<numnonnegbvalues-1) && (nonnegbvalues[count2]<ivimCutoff)) {
count2++;
}
if ((count2<numnonnegbvalues-1) && (nonnegbvalues[0]<1)) { // Found cutoff, and also B=0 image exists
cutoffindex = count2;
}
// *** ADD CHECKS HERE: (1) >=2 B values above cutoff, and (2) a B=0 image
if (cutoffindex > 0){
// Create new 2D viewers.
ViewerController *newDtViewer = [self copyFirstViewerWindow:self->viewerController];
ViewerController *newDpViewer = [self copyFirstViewerWindow:self->viewerController];
ViewerController *newFpViewer = [self copyFirstViewerWindow:self->viewerController];
ViewerController *synthViewer;
ViewerController *residViewer;
NSMutableArray *synthImage;
NSMutableArray *residImage;
float *synthpix = NULL;
float *residpix = NULL;
int count;
float* bpixels[MAXNBVALUES]; // Pointer to pixels (images) for each b-value, for current slice.
// If synthesizing an image for given B-value, make another viewer.
if (synthbvalue >= 0) {
synthViewer = [self copyFirstViewerWindow:self->viewerController];
synthImage = [synthViewer pixList];
NSString *synthTitle = [NSString stringWithFormat:@"Synthesized b=%g",synthbvalue];
[[[synthViewer pixList] objectAtIndex:0] setGeneratedName:synthTitle];
}
// If showing residual, make another viewer
if (showresidual != 0) {
residViewer = [self copyFirstViewerWindow:self->viewerController];
residImage = [residViewer pixList];
NSString *residTitle = [NSString stringWithFormat:@"IVIM Residual"];
[[[residViewer pixList] objectAtIndex:0] setGeneratedName:residTitle];
}
[[[newDtViewer pixList] objectAtIndex:0] setGeneratedName:@"Tissue Diffusion (x1e-6mm^2/s)"];
[[[newDpViewer pixList] objectAtIndex:0] setGeneratedName:@"Pseudodiffusion (x1e-4mm^2/s)"];
[[[newFpViewer pixList] objectAtIndex:0] setGeneratedName:@"Perfusion Fraction (%)"];
// Initialize Wait window
Wait *splash = [[Wait alloc] initWithString:NSLocalizedString(@"Computing Two-Stage IVIM Fit", nil)];
[splash showWindow:self];
[[splash progress] setMaxValue:zsize];
[splash setCancel: YES];
// Get pixel value from threshold percentage of max pixel in min-b-value image.
float thresholdPixVal = [self getThresholdPixValue:numnonnegbvalues
withindices:nonnegindices
withbvalues:nonnegbvalues];
NSMutableArray *newDtImage = [newDtViewer pixList]; // Get pointer to newly-allocated viewer.
NSMutableArray *newDpImage = [newDpViewer pixList]; // Get pointer to newly-allocated viewer.
NSMutableArray *newFpImage = [newFpViewer pixList]; // Get pointer to newly-allocated viewer.
float *fittedDtPix;
float *fittedDpPix;
float *fittedFpPix;
// Now calculate the IVIM maps.
for (count=0; count < zsize; count++) { // Repeat for each 2D slice in image.
for (count1=0; count1 < numnonnegbvalues; count1++) {
// Set pointer for ith non-negative B-value image to pass to calculation.
bpixels[count1] = [[[viewerController pixList:nonnegindices[count1]] objectAtIndex:count] fImage];
}
NSLog(@"%d b-values",numnonnegbvalues);
fittedDtPix = [[newDtImage objectAtIndex:count] fImage];
fittedDpPix = [[newDpImage objectAtIndex:count] fImage];
fittedFpPix = [[newFpImage objectAtIndex:count] fImage];
if (synthbvalue >= 0) {
synthpix = [[synthImage objectAtIndex:count] fImage];
}
if (showresidual != 0) {
residpix = [[residImage objectAtIndex:count] fImage];
}
calcIvimFit(bpixels,nxypts, numnonnegbvalues, nonnegbvalues, cutoffindex, thresholdPixVal, fittedDtPix, fittedDpPix, fittedFpPix, NULL, residpix, synthbvalue, synthpix);
[splash incrementBy: 1];
//if([splash aborted])
// count = zsize;
}
[newDtViewer refresh]; // Refresh viewer, since pixel values have been replaced
[newDpViewer refresh]; // Refresh viewer, since pixel values have been replaced
[newFpViewer refresh]; // Refresh viewer, since pixel values have been replaced
// Update the current displayed WL & WW (automatic window)
[[newDtViewer imageView] setWLWW:1000 :2000];
[[newDpViewer imageView] setWLWW:1000 :2000];
[[newFpViewer imageView] setWLWW:50 :100];
if (synthbvalue >= 0) {
[synthViewer refresh]; // Refresh synthesized image viewer.
}
[splash close];
[splash release];
[self closeSheet:sender];
} else {
NSString *msgString = [NSString stringWithFormat:@"(%d found, up to %d expected)",numnonnegbvalues,nbvalues];
NSRunInformationalAlertPanel(@"Need B=0 image, and at least 2 images above cutoff B-value",msgString,@"Continue", nil, nil);
}
}
- (IBAction) endSetupSheet:(id) sender
{
[self closeSheet:sender];
}
- (void) closeSheet:(id) sender
{
//NSRunInformationalAlertPanel(@"Closing Sheet: ",@" ",@"Continue", nil, nil);
[ADCwindow orderOut:sender];
[NSApp endSheet: ADCwindow returnCode: NSCancelButton];
[ADCwindow orderOut:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (IBAction)drawGraph: (id)sender
{
int idroi;
int numTraces=2; // Ultimately make based on selection;
int numROIs=0;
int i;
int count;
int count2;
float minValueY, maxValueY;
int minValueX, maxValueX;
int cutoffindex;
float sbvalues[MAXNBVALUES];
int sindices[MAXNBVALUES];
float svalues[MAXNBVALUES];
float *svalpointers[MAXNBVALUES];
int nbvaluesplot;
float adc, b0fit;
float thresholdvalue; // Value to threshold at in fits.
float maxDataVal;
float Dp, Dt, Fp, S0, resid;
NSString *description;
NSString *residLabel;
maxDataVal=0;
if ([roiImageList count] >= 1) {
numROIs = 1;
}
// If only showing signal, reduce numTraces
if ([resultView plotContentType] == 0) {
numTraces = 1;
}
NSLog(@"Number of traces is %d",numTraces);
// B-values may be in arbitrary order, so sort from low to high
// for plotting, and also remove any negative b-values, which indicate
// to not include the image/bvalue.
nbvaluesplot = sortbvalues(nbvalues, bvals, sindices, sbvalues);
// Get options from UI.
nonnegconstraint = ([constraintOn state] == NSOnState);
showresidual = ([residualOn state] == NSOnState);
useIVIMinitguess = ([useIVIMguessOn state] == NSOnState);
NSLog(@"Constraint Flag = %d",nonnegconstraint);
if (numROIs > 0) {
// Calculate Mean
float meanY[nbvalues], stdY[nbvalues], minimumY[nbvalues], maximumY[nbvalues];
float meanYTotal[nbvalues*numTraces], stdYTotal[nbvalues*numTraces], minimumYTotal[nbvalues*numTraces], maximumYTotal[nbvalues*numTraces];
NSMutableArray *roiNameList = [[NSMutableArray alloc] init];
NSMutableArray *roiColorList = [[NSMutableArray alloc] init];
for (idroi = 0; idroi < numROIs; idroi++)
{
[self calculateMean:meanY :stdY :minimumY :maximumY :idroi];
for (i = 0; i < nbvaluesplot; i++)
{
meanYTotal[idroi*numTraces*nbvaluesplot+i] = meanY[sindices[i]];
stdYTotal[idroi*numTraces*nbvaluesplot+i] = stdY[sindices[i]];
minimumYTotal[idroi*numTraces*nbvaluesplot+i] = minimumY[sindices[i]];
maximumYTotal[idroi*numTraces*nbvaluesplot+i] = maximumY[sindices[i]];
svalues[i]=meanY[sindices[i]]; // Keep array of y values for later
if (svalues[i]>maxDataVal) maxDataVal=svalues[i];
}
NSLog(@"Getting ROI information");
[roiNameList addObject:roiName]; // !!! Need to get this right?
[roiColorList addObject:roiColor];
NSLog(@"name of ROI is %@",roiName);
if (numTraces>1) { // Also showing mono- or bi-exponential fit
for (i=0; i< nbvaluesplot; i++)
svalpointers[i] = &svalues[i]; // Array of pointers, to be compatible with calcADCfit.
thresholdvalue = threshold * maxDataVal/100.0;
[resultView setPlotTitle:@"Signal vs B value"];
if ([resultView plotContentType] == 1) { // Mono-Exponential
if (nbvaluesplot > 1) {
for (count=0; count < nbvaluesplot; count++) {
NSLog(@"Mono-fit bvalue %d of %d is %g",count,nbvaluesplot,sbvalues[count]);
}
calcADCfit(svalpointers, 1, nbvaluesplot, sbvalues, &adc, &resid, thresholdvalue, &b0fit, -1, NULL);
NSLog(@"MonoExp fit S0=%g, ADC=%g, #bvalues = %d",b0fit,adc,nbvaluesplot);
//synthBImage(adc, b0fit, sbvalues, nbvaluesplot, &(meanYTotal[(idroi*numTraces+1)*nbvaluesplot]));
synthBiExpImage(adc, 0.0, 0.0, b0fit, sbvalues, nbvaluesplot, &(meanYTotal[(idroi*numTraces+1)*nbvaluesplot]));
for (count=0; count < nbvaluesplot; count++) {
NSLog(@"Mono-fit bvalue %d of %d is %g. Sig=%g, PlotSig=%g, Fitted(%d)=%g",count,nbvaluesplot,sbvalues[count],svalpointers[count][0],meanYTotal[count],(idroi*numTraces+1)*nbvaluesplot+count,meanYTotal[(idroi*numTraces+1)*nbvaluesplot+count]);
}
residLabel = [[NSString alloc] initWithFormat:@", res=%ld",(long)resid ];
description = [[NSString alloc] initWithFormat:@"ADC=%.5f, S0=%.0f",adc/DTCONVERT,b0fit];
}
else {
description = [[NSString alloc] initWithFormat:@"Not Enough B-Values for Fit"];
residLabel = [[NSString alloc] initWithFormat:@"" ];
numTraces = 1;
}
}
else if ([resultView plotContentType] == 2) { // Two-stage fit
// Find where the cutoff B value for IVIM is in the list, and make sure there is at least
// one B=0 image, one image below cutoff, and 2 at/above cutoff.
count2=1; // Start at 1, need at least one value for Dp fit.
while ((count2<nbvaluesplot-1) && (sbvalues[count2]<ivimCutoff)) {
count2++;
}
if ((count2<nbvaluesplot-1) && (sbvalues[0]<1)) { // Found cutoff, and also B=0 image exists
cutoffindex = count2;
} else cutoffindex = -1;
if ((nbvaluesplot > 3) && (cutoffindex > 0)) {
calcIvimFit(svalpointers, 1, nbvaluesplot, sbvalues, cutoffindex, thresholdvalue, &Dt, &Dp, &Fp, &S0, &resid, -1, NULL);
synthBiExpImage(Dt, Dp, Fp, S0, sbvalues, nbvaluesplot, &(meanYTotal[(idroi*numTraces+1)*nbvaluesplot]));
description = [[NSString alloc] initWithFormat:@"Dt=%.5f*,Dp=%.5f*,Fp=%.0f%%,S0=%.0f",Dt/DTCONVERT,Dp/DPCONVERT,Fp,S0];
residLabel = [[NSString alloc] initWithFormat:@", res=%ld",(long)resid ];
}
else {
description = [[NSString alloc] initWithFormat:@"Need b=0 image and 2+ b-values above cutoff"];
residLabel = [[NSString alloc] initWithFormat:@"" ];
numTraces = 1;
}
}
else { // Bi-Exponential
Dt = initDt;
Dp = initDp;
Fp = initFp;
S0 = svalues[0]; // Initial guess as lowest b image.
if (nbvaluesplot > 4) {
if (useIVIMinitguess) {
// !Repeated code from above...!!
// Find where the cutoff B value for IVIM is in the list, and make sure there is at least
// one B=0 image, one image below cutoff, and 2 at/above cutoff.
count2=1; // Start at 1, need at least one value for Dp fit.
while ((count2<nbvaluesplot-1) && (sbvalues[count2]<ivimCutoff)) {
count2++;
}
if ((count2<nbvaluesplot-1) && (sbvalues[0]<1)) { // Found cutoff, and also B=0 image exists
cutoffindex = count2;
} else cutoffindex = -1;
calcIvimFit(svalpointers, 1, nbvaluesplot, sbvalues, cutoffindex, thresholdvalue, &Dt, &Dp, &Fp, &S0, NULL, -1, NULL);
Dt /= DTCONVERT;
Dp /= DPCONVERT;
Fp /= 100.0;
NSLog(@"BiExp IVIM initial guess S0=%g, Dt=%g, Dp=%g, Fp=%g",S0,Dt,Dp,Fp);
}
calcBiExpFit(svalpointers,1, nbvaluesplot,sbvalues,thresholdvalue, &Dt,&Dp,&Fp,&S0, &resid, -1, NULL, nonnegconstraint,1);
NSLog(@"BiExp fit S0=%g, Dt=%g, Dp=%g, Fp=%g",S0,Dt,Dp,Fp);
synthBiExpImage(Dt, Dp, Fp, S0, sbvalues, nbvaluesplot, &(meanYTotal[(idroi*numTraces+1)*nbvaluesplot]));
if (nonnegconstraint==0) {
description = [[NSString alloc] initWithFormat:@"Dt=%.5f*,Dp=%.5f*,Fp=%.0f%%,S0=%.0f",Dt/DTCONVERT,Dp/DPCONVERT,Fp,S0];
} else {
description = [[NSString alloc] initWithFormat:@"Dt=%.5f*,Dp=%.5f*,Fp=%.0f%%,S0=%.0f(bc)",Dt/DTCONVERT,Dp/DPCONVERT,Fp,S0];
}
residLabel = [[NSString alloc] initWithFormat:@", res=%ld",(long)resid ];
} else {
numTraces = 1; // Don't plot trace!
description = [[NSString alloc] initWithFormat:@"Not Enough B-Values for Fit"];
residLabel = [[NSString alloc] initWithFormat:@"" ];
}
}
[roiNameList addObject:@"Fitted"];
[roiColorList addObject:roiColor];
}
else {
description = [[NSString alloc] initWithFormat:@"(Signal Only)"];
}
}