-
Notifications
You must be signed in to change notification settings - Fork 3
/
fwdmodel_cest.cc
2073 lines (1819 loc) · 62.2 KB
/
fwdmodel_cest.cc
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
/* fwdmodel_cest_devel.cc - Developement CEST APT model
Michael Chappell, IBME PUMMA & FMRIB Image Analysis Group
Copyright (C) 2010 University of Oxford */
/* CCOPYRIGHT */
#include "fwdmodel_cest.h"
#include "spline_interpolator.h"
#include "miscmaths/miscprob.h"
#include "newimage/newimageall.h"
#include "armawrap/newmat.h"
#include <iostream>
#include <stdexcept>
#include "fabber_core/easylog.h"
using namespace NEWIMAGE;
using NEWMAT::RowVector;
using NEWMAT::ColumnVector;
using NEWMAT::Matrix;
using NEWMAT::IdentityMatrix;
using NEWMAT::DiagonalMatrix;
using NEWMAT::SymmetricMatrix;
using NEWMAT::ReturnMatrix;
using MISCMATHS::read_ascii_matrix;
FactoryRegistration<FwdModelFactory, CESTFwdModel> CESTFwdModel::registration("cest");
static OptionSpec OPTIONS[] = {
{ "spec", OPT_MATRIX, "ASCII matrix containing data specification", OPT_REQ, "" },
{ "pools", OPT_MATRIX, "ASCII matrix containing pool specification", OPT_REQ, "" },
{ "expools", OPT_MATRIX, "ASCII matrix containing extra pool specification", OPT_NONREQ, "" },
{ "ptrain", OPT_MATRIX, "ASCII matrix containing pulsed saturation specification", OPT_NONREQ, "" },
{ "t12prior", OPT_BOOL, "Include uncertainty in T1 and T2 values", OPT_NONREQ, "" },
{ "inferdrift", OPT_BOOL, "Infer drift in Z spectrum frequencies", OPT_NONREQ, "" },
{ "b1off", OPT_BOOL, "Compatibility option - infers B1 correction as an offset as in previous versions of model", OPT_NONREQ, "" },
{ "lorentz", OPT_BOOL, "Alternative to Matrix exponential solution to Bloch equations", OPT_NONREQ, "" },
{ "steadystate", OPT_BOOL, "Alternative to Matrix exponential solution to Bloch equations", OPT_NONREQ, "" },
{ "tr", OPT_FLOAT, "TR in seconds for use with steady-state solution", OPT_NONREQ, "" },
{ "fa", OPT_FLOAT, "Excitation flip angle in degrees for use with steady-state solution", OPT_NONREQ, "" },
{ "satspoil", OPT_BOOL, "Perform saturation interpulse spoiling for saturation pulse trains", OPT_NONREQ, "" },
{ "pvimg", OPT_IMAGE,
"Tissue partial volume image. Should be 3D image containing tissue partial volumes, i.e. sum of GM and WM "
"partial volumes",
OPT_NONREQ, "" },
{ "pv-threshold", OPT_FLOAT, "Partial volume threshold for including tissue contribution", OPT_NONREQ, "0.5" },
{ "csf-tiss-m0ratio", OPT_FLOAT, "Used for fixing CSF M0 when using partial volume correction", OPT_NONREQ, "0.5269" },
{ "lineshape", OPT_STR, "Saturation lineshape for the MT pool (which must be the last pool specified). Options: gaussian, superlorentzian, lorentzian, none", OPT_NONREQ, "none" },
{ "t1-rstar", OPT_FLOAT, "Water T1 value for use in CESTR* calculation - if not specified poolmat value is used", OPT_NONREQ, "" },
{ "t2-rstar", OPT_FLOAT, "Water T2 value for use in CESTR* calculation - if not specified poolmat value is used", OPT_NONREQ, "" },
{ "" },
};
void CESTFwdModel::GetOptions(vector<OptionSpec> &opts) const
{
for (int i = 0; OPTIONS[i].name != ""; i++)
{
opts.push_back(OPTIONS[i]);
}
}
std::string CESTFwdModel::GetDescription() const
{
return "Model for Chemical Exchange Saturation transfer, with correction for partial volume effects using a tissue "
"PV map";
}
string CESTFwdModel::ModelVersion() const
{
string version = "fwdmodel_cest.cc";
#ifdef GIT_SHA1
version += string(" Revision ") + GIT_SHA1;
#endif
#ifdef GIT_DATE
version += string(" Last commit ") + GIT_DATE;
#endif
return version;
}
void CESTFwdModel::HardcodedInitialDists(MVNDist &prior, MVNDist &posterior) const
{
assert(prior.means.Nrows() == NumParams());
SymmetricMatrix precisions = IdentityMatrix(NumParams()) * 1e-12;
// Set priors
int place = 1;
// M0
prior.means.Rows(1, npool) = 0.0;
precisions(place, place) = 1e-12;
place++;
if (npool > 1)
{
for (int i = 2; i <= npool; i++)
{
if (setconcprior)
{
// priors have been specified via the poolmat
prior.means(place)
= poolcon(place - 1); // NB poolcon vec doesn't have water in so entry 1 is pool 2 etc
precisions(place, place) = poolconprec(place - 1);
}
else
{
// hardcoded default of zero mean and (relatively) uniformative precision
// prior mean of zero set above
precisions(place, place) = 1e2;
}
place++;
}
}
// exchnage consts (these are log_e)
if (npool > 1)
{
for (int i = 2; i <= npool; i++)
{
prior.means(place) = poolk(i - 1); // NOTE these shoudl already be log in poolk
precisions(place, place) = 1;
place++;
}
}
// frequency offsets (ppm)
prior.means(place) = 0; // water centre offset
precisions(place, place) = 1;
place++;
if (npool > 1)
{
for (int i = 2; i <= npool; i++)
{
prior.means(place) = poolppm(i - 1);
precisions(place, place) = 1e12; // 1e6;
place++;
}
}
// B1 Correction (fractional)
if (use_b1off)
{
// Compatibility mode. Note that the high
// precision here is probably an error but we
// preserve it to give the option of runninng the
// model exactly how it used to be
prior.means(place) = 0.0;
precisions(place, place) = 1e12;
}
else
{
prior.means(place) = 1.0;
precisions(place, place) = 1;
}
place++;
if (inferdrift)
{
// Drift (ppm/sample)
prior.means(place) = 0;
precisions(place, place) = 1e17;
place++;
}
if (t12soft)
{
// T1 values
for (int i = 1; i <= npool; i++)
{
prior.means(place) = T12master(1, i);
precisions(place, place) = 44.4; // all T1s have same prior uncertainty
place++;
}
// T12 values
for (int i = 1; i <= npool; i++)
{
float T12 = T12master(2, i);
prior.means(place) = T12;
precisions(place, place) = 1 / std::pow(T12 / 5, 2); // prior has std dev of 1/5 of the
// value, to try and get the
// scaling about right
place++;
}
}
if (m_pvcorr)
{
// CSF pool T1 and T2 priors
prior.means(place) = 1.9;
precisions(place, place) = 44.4;
place++;
prior.means(place) = 0.25;
precisions(place, place) = 1 / std::pow(prior.means(place) / 5, 2);
place++;
}
// Extra ('indepdnent') pools
if (nexpool > 0)
{
for (int i = 1; i <= nexpool; i++)
{
prior.means(place) = 1;
precisions(place, place) = 1;
place++;
prior.means(place) = expoolppm(i);
precisions(place, place) = 1e12;
place++;
prior.means(place) = expoolR(i);
precisions(place, place) = 1;
}
}
// Set precsions on priors
prior.SetPrecisions(precisions);
// Set initial posterior
posterior = prior;
// For parameters with uniformative prior chosoe more sensible inital posterior
// now done in initialise!
// posterior.means(1) = 1000;
// precisions(1,1) = 10;
// posterior.SetPrecisions(precisions);
}
void CESTFwdModel::InitParams(MVNDist &posterior) const
{
// Check out dataspec is the right size
int nt = data.Nrows();
if (wvec.Nrows() != nt)
{
throw InvalidOptionValue(
"dataspec", "", "Incorrect number of frequencies - should match number of data volumes");
}
// load the existing precisions as the basis for any update
SymmetricMatrix precisions;
precisions = posterior.GetPrecisions();
// init the M0a value - to max value in the z-spectrum
posterior.means(1) = data.Maximum();
precisions(1, 1) = 10;
// init the pool concentraitons
if (npool > 1)
{
for (int i = 2; i <= npool; i++)
{
// NB poolcon vec doesn't have water in so entry 1 is pool 2 etc
posterior.means(i) = poolcon(i - 1);
precisions(i, i) = 1e6;
}
}
// init the ppmoff value - by finding the freq where the min of z-spectrum is
int ind;
float val;
val = data.Minimum1(ind); // find the minimum in the z-spectrum
val = wvec(ind) * 1e6 / wlam; // frequency of the minimum in ppm
if (val > 2.5)
val = 2.5; // put a limit on the value
if (val < -2.5)
val = -2.5;
int ppmind = 2 * npool;
posterior.means(ppmind) = val;
posterior.SetPrecisions(precisions);
}
void CESTFwdModel::GetOutputs(std::vector<std::string> &outputs) const
{
for (int p = 1; p < npool; p++)
{
char pool_char = char(int('a') + p);
outputs.push_back(string("cest_rstar_") + pool_char);
}
}
struct by_x {
bool operator()(const pair<double, double> &c1, const pair<double, double> &c2) const {
return c1.first < c2.first;
}
};
double lin_interp(const ColumnVector &x, const ColumnVector &y, double pos)
{
// Determine the value of the function given by (x, y) co-ordinates at
// the position pos, using a linear interpolation metho
// This is complicated by the fact that sometimes x is not strictly
// increasing which makes interpolation impossible. So we start out
// by sorting x/y coords into increasing x order
vector<pair<double, double> > coords;
for (int i=1; i<=x.Nrows(); i++) {
pair<double, double> c(x(i), y(i));
coords.push_back(c);
}
std::sort(coords.begin(), coords.end(), by_x());
// Quick-and-dumb linear interpolation. Assume x, pos > 0
// and function starts at 0, 0
double prev_val = 0;
double prev_x = 0;
for (unsigned int i = 0; i<coords.size(); i++)
{
double x = coords[i].first;
double y = coords[i].second;
if (pos < x)
{
double frac = (pos - prev_x) / (x - prev_x);
return prev_val + frac * (y - prev_val);
}
prev_val = y;
prev_x = x;
}
// pos beyond last x value - just return last y value
return coords[coords.size()-1].second;
}
void CESTFwdModel::EvaluateModel(const ColumnVector ¶ms, ColumnVector &result, const std::string &key) const
{
if (key == "")
{
Evaluate(params, result);
}
else
{
// Outputting CEST R* - need to know pool number which is encoded by the letter
// at the end of the key (a=water, b=pool 2, etc). This will always be > 1
int pool_num = 1 + int(key[key.length() - 1]) - int('a');
assert(pool_num > 1);
EvaluateCestRstar(params, result, pool_num);
}
}
void CESTFwdModel::EvaluateCestRstar(const ColumnVector ¶ms, ColumnVector &result, int pool_num) const
{
assert(pool_num > 1);
// LOG << "Outputting CESTRstar for pool " << pool_num << endl;
// For this calculation, we use default T1/T2, NOT any inferred values or
// image priors. Note that we may have special T1/T2 values for water
// (t1_rstar/t2_rstar) which may differ from the values in T12master
ColumnVector mod_params = params;
if (t12soft)
{
int t12_idx = (npool - 1) * 3 + 3 + (inferdrift ? 1 : 0);
mod_params(t12_idx + 1) = t1_rstar;
mod_params(t12_idx + npool + 1) = t2_rstar;
for (int i = 2; i <= npool; i++)
{
mod_params(t12_idx + i) = T12master(1, i);
mod_params(t12_idx + npool + i) = T12master(2, i);
}
}
// We also do not use a water ppm offset
int ppm_off_idx = (npool - 1) * 2 + 2;
mod_params(ppm_off_idx) = 0;
// Determine the Z spectrum for water only, and then in the presence of this pool only
ColumnVector water_only, with_pool;
Evaluate(mod_params, water_only, 1);
Evaluate(mod_params, with_pool, pool_num);
//LOG << "freq: " << wvec.t();
//LOG << "water only: " << water_only.t();
//LOG << "With pool: " << with_pool.t();
// We evaluate the Z spectrum at a fixed PPM from the poolmat file, unless
// the value is 0 in which case we use 50ppm (works for semisolid pool)
double ppm_eval = 50;
if (poolppm(pool_num - 1) != 0)
{
ppm_eval = poolppm(pool_num - 1);
}
//LOG << "Evaluating at " << ppm_eval << ", " << (ppm_eval* wlam / 1e6) << endl;
// Evaluate at fixed PPM by linear interpolation. Note freq transformation
// same as transformation applied to wvec
double water = lin_interp(wvec, water_only, ppm_eval * wlam / 1e6);
double pool = lin_interp(wvec, with_pool, ppm_eval * wlam / 1e6);
//LOG << "Lin interp" << endl;
//LOG << "water " << water << endl;
//LOG << "pool " << pool << endl;
//LOG << "frac " << pool/water << endl;
result.ReSize(1);
result(1) = 100 * (water - pool) / params(1);
// LOG << "res " << result.t() << endl;
}
/**
* To evaluate only with single pool or 2-pool, need to restrict matrices to the relevant pools
*
* This is used in order to calculate CEST R* in the final output stage
*
* wvec - no change, this is vector of size nsamp
* w1 - no change, this is vector of size nsamp
* tsatvec - no change, this is vector of size nsamp
* M0 - need to restrict to rows 1 and poolnum
* wimat - need to restric to rows 1 and poolnum
* kij - need to restict to rows/columns 1 and poolnum
* T12 - need to restrict to rows 1 and poolnum
*/
void CESTFwdModel::RestrictPools(ColumnVector &M0, Matrix &wimat, Matrix &kij, Matrix &T12, int pool) const
{
if (pool == 1)
{
// Restrict solution to water pool only
ColumnVector M0_res(1);
M0_res(1) = M0(1);
M0 = M0_res;
Matrix wimat_res(1, wimat.Ncols());
wimat_res.Row(1) = wimat.Row(1);
wimat = wimat_res;
Matrix kij_res(1, 1);
kij_res(1, 1) = kij(1, 1);
kij = kij_res;
Matrix T12_res(2, 1);
T12_res.Column(1) = T12.Column(1);
T12 = T12_res;
}
else if (pool > 1)
{
// Restrict solution to water pool + other specified pool
ColumnVector M0_res(2);
M0_res(1) = M0(1);
M0_res(2) = M0(pool);
M0 = M0_res;
Matrix wimat_res(2, wimat.Ncols());
wimat_res.Row(1) = wimat.Row(1);
wimat_res.Row(2) = wimat.Row(pool);
wimat = wimat_res;
Matrix kij_res(2, 2);
kij_res(1, 1) = kij(1, 1);
kij_res(1, 2) = kij(1, pool);
kij_res(2, 1) = kij(pool, 1);
kij_res(2, 2) = kij(pool, pool);
kij = kij_res;
Matrix T12_res(2, 2);
T12_res.Column(1) = T12.Column(1);
T12_res.Column(2) = T12.Column(pool);
T12 = T12_res;
}
}
void CESTFwdModel::Evaluate(const ColumnVector ¶ms, ColumnVector &result, int restrict_pool) const
{
// ensure that values are reasonable
// negative check
ColumnVector paramcpy = params;
for (int i = 1; i <= NumParams(); i++)
{
if (params(i) < 0)
{
paramcpy(i) = 0;
}
}
// model matrices
ColumnVector M0(npool);
Matrix kij(npool, npool);
Matrix T12(2, npool);
ColumnVector ppmvec(npool);
// MT pool
ColumnVector mtparams(5);
// Extra pools
ColumnVector exI(nexpool);
ColumnVector exppmvec(nexpool);
ColumnVector exR(nexpool);
// extract values from params
// M0 comes first
int place = 1;
M0(1) = paramcpy(place); // this is the 'master' M0 value of water
if (M0(1) < 1e-4)
M0(1) = 1e-4; // M0 of water cannot disapear all together
place++;
// values in the parameters are ratios of M0_water
float M0ratio;
for (int j = 2; j <= npool; j++)
{
M0ratio = paramcpy(place);
if (M0ratio > 1.0)
{ // dont expect large ratios
M0ratio = 1.0;
}
M0(j) = M0ratio * M0(1);
place++;
}
// now exchange - we assume that only significant exchnage occurs with water
kij = 0.0; // float ktemp;
for (int j = 2; j <= npool; j++)
{
kij(j, 1) = exp(params(place)); // non-linear transformation
if (kij(j, 1) > 1e6)
kij(j, 1) = 1e6; // exclude really extreme values
kij(1, j) = kij(j, 1) * M0(j) / M0(1);
place++;
}
// frequency offset next
ppmvec = params.Rows(place, place + npool);
place += npool;
// now B1 Correction Factor
// This now a multiplicative factor, more in line with what is output from scanners
double B1corr = paramcpy(place);
if (use_b1off) {
// Compatibility mode - B1 correction is additive
B1corr = (1 + B1corr*1e6);
}
place++;
// Drift
float drift = 0;
if (inferdrift)
{
drift = params(place) * 1e6; // scale this parameters like B1 offset
place++;
}
// T12 parameter values
if (t12soft)
{
// T12 values
for (int i = 1; i <= npool; i++)
{
T12(1, i) = paramcpy(place);
if (T12(1, i) < 1e-12)
T12(1, i) = 1e-12; // 0 is no good for a T1 value
if (T12(1, i) > 10)
T12(1, i) = 10; // Prevent convergence issues causing T1 to blow up
place++;
}
for (int i = 1; i <= npool; i++)
{
T12(2, i) = paramcpy(place);
if (T12(2, i) < 1e-12)
T12(2, i) = 1e-12; // 0 is no good for a T2 value
if (T12(2, i) > 1)
T12(2, i) = 1; // Prevent convergence issues causing T2 to blow up
place++;
}
}
else
{
T12 = T12master;
}
// PVC parameters
double t1csf = 0;
double t2csf = 0;
if (m_pvcorr)
{
t1csf = paramcpy(place++);
t2csf = paramcpy(place++);
}
// Extra pools
if (nexpool > 0)
{
for (int i = 1; i <= nexpool; i++)
{
exI(i) = params(place);
place++;
exppmvec(i) = params(place);
place++;
exR(i) = params(place);
place++;
}
}
// MODEL - CEST
// deal with frequencies
int nsamp = wvec.Nrows();
Matrix wimat(npool, nsamp);
for (int j = 1; j <= nsamp; j++)
{
wimat(1, j) = wlam * (ppmvec(1) + (j - 1) * drift) / 1e6;
}
if (npool > 1)
{
for (int i = 2; i <= npool; i++)
{
for (int j = 1; j <= nsamp; j++)
{
wimat(i, j)
= wlam * ppmvec(i) / 1e6 + wlam * (ppmvec(1) + (j - 1) * drift) / 1e6 * (1 + ppmvec(i) / 1e6);
}
}
}
// species b is at ppm*wlam, but also include offset of main field
// Correct B1 Inhomogeneities
// B1 cannot be negative
if (B1corr < 0.0)
B1corr = 0.0;
// unlikely to get this big (hardlimit in case of convergence problems)
if (B1corr > 5.0)
B1corr = 5.0;
ColumnVector w1 = w1vec * B1corr; // w1 in radians!
// frequencies for the extra pools
Matrix exwimat(nexpool, nsamp);
if (nexpool > 0)
{
for (int i = 1; i <= nexpool; i++)
{
for (int j = 1; j <= nsamp; j++)
{
exwimat(i, j)
= wlam * ppmvec(i) / 1e6 + wlam * (ppmvec(1) + (j - 1) * drift) / 1e6 * (1 + exppmvec(i) / 1e6);
}
}
}
if (restrict_pool > 0)
{
// We are restriction the solution to the water pool + possibly one other pool
RestrictPools(M0, wimat, kij, T12, restrict_pool);
}
float pv_val = 1.0;
if (m_pvcorr)
{
pv_val = m_pv_img(voxel);
}
// Generate tissue z spectrum if pv > threshold (otherwise we're doing csf-only fit)
ColumnVector Mztissue(wvec);
if (pv_val >= m_pv_threshold)
{
// We have enough tissue in the voxel to include a tissue component - note that
// when PVC is not enabled the partial volume value is fixed at 1.0 so this is
// always included
if (lorentz)
{
// PV correction supports lorentz option for 'tissue' spectrum
Mztissue = Mz_spectrum_lorentz(wvec, w1, tsatvec, M0, wimat, kij, T12);
}
else if (m_new_ss)
{
// Call to Steady State CEST Model
// Only need to fix w1EX if using SS CEST
double w1EX = m_fa * B1corr;
Mz_spectrum_SS(Mztissue, wvec, w1, tsatvec, M0, wimat, kij, T12, w1EX, restrict_pool);
}
else
{
// The complete tissue spectrum
Mz_spectrum(Mztissue, wvec, w1, tsatvec, M0, wimat, kij, T12);
}
}
if (m_pvcorr)
{
// Partial volume correction is enabled - include a CSF component based on
// the tissue/CSF partial volume
ColumnVector M0csf(1);
M0csf(1) = M0(1) * m_pv_csf_tiss_m0ratio;
if (M0csf(1) < 1e-4)
{
M0csf(1) = 1e-4;
}
Matrix T12csf(2, 1);
T12csf(1, 1) = t1csf;
T12csf(2, 1) = t2csf;
Matrix kij_csf(1, 1);
kij_csf(1, 1) = 0.0;
Matrix wimat_csf(1, nsamp);
for (int j = 1; j <= nsamp; j++)
{
wimat_csf(1, j) = wlam * (ppmvec(1) + (j - 1) * drift) / 1e6;
}
ColumnVector Mzcsf(wvec);
Mz_spectrum(Mzcsf, wvec, w1, tsatvec, M0csf, wimat_csf, kij_csf, T12csf);
if (pv_val >= m_pv_threshold)
{
// We have enough tissue in the voxel to include a tissue component as well
result = Mztissue * pv_val + Mzcsf * (1.0 - pv_val);
}
else
{
result = Mzcsf;
}
}
else
{
result = Mztissue;
}
// extra pools
ColumnVector Mz_extrapools(nsamp);
Mz_extrapools = 0.0;
ColumnVector Mzc(nsamp);
Mzc = 0.0;
if (nexpool > 0)
{
for (int i = 1; i <= nexpool; i++)
{
Mz_contribution_lorentz_simple(Mzc, wvec, exI(i), (exwimat.SubMatrix(i, i, 1, nsamp)).t(), exR(i));
Mz_extrapools += Mzc;
}
}
result = result - M0(1) * Mz_extrapools;
}
FwdModel *CESTFwdModel::NewInstance()
{
return new CESTFwdModel();
}
void CESTFwdModel::Initialize(ArgsType &args)
{
// Matrix containing spec for each datapoint
// 3 columns: Freq (ppm), B1 (T), tsat (s)
// Nrows = number data points
Matrix dataspec;
// Matrix containing setup information for the pools
// 4 columns: res. freq (rel. to water) (ppm), rate (species-> water), T1, T2.
// 1st row is water, col 1 interpreted as the actaul centre freq of water if > 0, col 2 ignored.
// Further rows for pools to be modelled.
Matrix poolmat;
// Matrix for the 'extra' pools
Matrix expoolmat;
string expoolmatfile;
string pulsematfile;
t12soft = false;
m_inter_spoil = false;
// read data specification from file
dataspec = read_ascii_matrix(args.Read("spec"));
// read pool specification from file
poolmat = read_ascii_matrix(args.Read("pools"));
// read extra pool specification from file
expoolmatfile = args.ReadWithDefault("expools", "none");
// read pulsed saturation specification
pulsematfile = args.ReadWithDefault("ptrain", "none");
t12soft = args.ReadBool("t12prior");
inferdrift = args.ReadBool("inferdrift");
use_b1off = args.ReadBool("b1off");
// alternatives to Matrix exponential solution to Bloch equations
lorentz = args.ReadBool("lorentz"); // NB only compatible with single pool
steadystate = args.ReadBool("steadystate");
// Use Interpulse Spoiling
m_inter_spoil = args.GetBool("satspoil");
// Use Lineshape for MT pool
m_lineshape = args.GetStringDefault("lineshape", "none");
// Use Readout Parameters
m_tr = args.GetDoubleDefault("tr", args.GetDoubleDefault("TR", -1.0));
m_fa = args.GetDoubleDefault("fa", args.GetDoubleDefault("EXFA", -1.0));
// Deal with the specification of the pools
npool = poolmat.Nrows();
if (poolmat.Ncols() < 4 || poolmat.Ncols() > 6)
{
throw invalid_argument("Incorrect number of columns in pool specification file");
}
// water centre
float wdefault = 42.58e6 * 3 * 2 * M_PI; // the default centre freq. (3T)
if (poolmat(1, 1) > 0)
wlam = poolmat(1, 1) * 2 * M_PI;
else
wlam = wdefault;
// ppm ofsets
poolppm = poolmat.SubMatrix(2, npool, 1, 1);
// exchange rate
poolk = MISCMATHS::log(poolmat.SubMatrix(2, npool, 2, 2)); // NOTE the log_e transformation
// T1 and T2 values
T12master = (poolmat.SubMatrix(1, npool, 3, 4)).t();
t1_rstar = args.GetDoubleDefault("t1-rstar", T12master(1, 1));
t2_rstar = args.GetDoubleDefault("t2-rstar", T12master(2, 1));
if (poolmat.Ncols() > 4)
{
// pool ratios (concetrations) - these are used for initialisaiton, but may also be used as
// prior means if precisions are provided
poolcon = poolmat.SubMatrix(2, npool, 5, 5); // ignore water pool
}
else
{
poolcon.ReSize(npool);
poolcon = 0;
}
setconcprior = false;
if (poolmat.Ncols() > 5)
{
// pool ratio precisions - this overrides the inbuilt priors for the concentrations using
// these precision and the means in poolcon
poolconprec = poolmat.SubMatrix(2, npool, 6, 6); // ingore water pool
setconcprior = true;
}
// check that the method chosen is possible
if ((npool > 1) & lorentz)
throw invalid_argument("Lorentzian (analytic) solution only compatible with single pool");
if (expoolmatfile != "none")
{
// process the Extra pool specification matrix
expoolmat = read_ascii_matrix(expoolmatfile);
nexpool = expoolmat.Nrows();
// cout << "nexpool: " << nexpool << endl;
if (expoolmat.Ncols() != 2)
throw invalid_argument("Incorrect number of columns in extra pool spefication file");
// ppm ofsets
expoolppm = expoolmat.SubMatrix(1, nexpool, 1, 1);
// (prior) R values
expoolR = expoolmat.SubMatrix(1, nexpool, 2, 2);
}
else
{
nexpool = 0;
}
// setup vectors that specify deatils of each data point
// sampling frequency
wvec = dataspec.Column(1) * wlam / 1e6;
// B1 value, convert to radians equivalent
w1vec = dataspec.Column(2) * 42.58e6 * 2 * M_PI;
// Saturation time
tsatvec = dataspec.Column(3);
LOG << "CESTFwdModel::Pools: " << endl;
LOG << " - Water - freq. (MHz) = " << wlam / 2 / M_PI << endl;
LOG << " - T1 (s) = " << T12master(1, 1) << endl;
LOG << " - T2 (s) = " << T12master(2, 1) << endl;
LOG << " - T1 (CESTR*) = " << t1_rstar << endl;
LOG << " - T2 (CESTR*) = " << t2_rstar << endl;
for (int i = 2; i <= npool; i++)
{
LOG << " - Pool " << i << " - freq. (ppm) = " << poolppm(i - 1) << endl;
LOG << " - kiw (s^-1) = " << exp(poolk(i - 1)) << endl;
LOG << " - T1 (s) = " << T12master(1, i) << endl;
LOG << " - T2 (s) = " << T12master(2, i) << endl;
}
LOG << "CESTFwdModel::Sampling frequencies (ppm):" << endl
<< (dataspec.Column(1)).t() << endl
<< "CESTFwdModel::Sampling frequencies (rad/s):" << endl
<< wvec.t() << endl;
LOG << "CESTFwdModel::B1 values (uT):" << endl
<< (dataspec.Column(2)).t() * 1e6 << endl
<< "CESTFwdModel::B1 values (rad/s):" << endl
<< w1vec.t() << endl;
// Pulsed saturation modelling
// For pulsed saturation the B1 values are taken as peak values
if (pulsematfile == "none")
{
cout << "WARNGING! - you should supply a pulsemat file, in future the calling of this "
"model without one (to get continuous saturation) will be depreceated"
<< endl;
nseg = 1;
pmagvec.ReSize(1);
ptvec.ReSize(1);
pmagvec = 1.0;
ptvec = 1e12; // a very long value for continuous saturation
LOG << "CESTFwdModel::Saturation times (s):" << endl << tsatvec.t() << endl;
}
else
{
Matrix pulsemat;
pulsemat = read_ascii_matrix(pulsematfile);
// vector of (relative) magnitude values for each segment
pmagvec = pulsemat.Column(1);
// vector of time durations for each segment
// note that we are loding in a vector of times for the end of each segment
ColumnVector pttemp = pulsemat.Column(2);
ColumnVector nought(1);
nought = 0.0;
ptvec = pttemp - (nought & pttemp.Rows(1, pttemp.Nrows() - 1));
nseg = pulsemat.Nrows();
LOG << "CESTFwdModel::Pulse repeats:" << endl << tsatvec.t() << endl;
LOG << "CESTFwdModel::Pulse shape:" << endl
<< " - Number of segments: " << nseg << endl
<< " - Magnitudes (relative): " << pmagvec.t()
<< " - Durations (s): " << ptvec.t();
}
// Steady State Modeling
// For Modeling the steady state Signal according to Listerud, Magn Reson Med 1997; 37: 693–705.
// Initializing m_t2m
m_t2m = 1e-5;
if (m_tr > 0.0 && m_fa > 0.0)
{
m_new_ss = true;
LOG << "\nRunning Steady State CEST Model Based upon Listerud, MRM: 37 (1997)\n" << endl;
LOG << "TR (s): \t" << m_tr << endl;
LOG << "Excitation Flip Angle (Degrees):\t" << m_fa << endl << endl;
m_fa *= M_PI / 180;
LOG << "Using Lineshape: " << m_lineshape << endl << endl;
}
else if (m_tr > 0.0 && m_fa <= 0.0)
{
LOG << "WARNING! - you supplied a TR, but no Excitation flip angle (--fa). Will run Original Fabber CEST "
"Model" << endl;
m_new_ss = false;
LOG << "Running Original Fabber CEST Method" << endl;
}
else if (m_tr <= 0.0 && m_fa > 0.0)
{
LOG << "WARNING! - you supplied an Excitation flip angle, but no TR (--tr). Will run Original Fabber CEST "
"Model" << endl;
m_new_ss = false;
LOG << "Running Original Fabber CEST Method" << endl;
}
else
{
m_new_ss = false;
LOG << "Running Original Fabber CEST Method" << endl;
}
// Partial volume correction
m_pv_threshold = 0.0;
try
{
// Partial volume image should be 3D map
Matrix pvimg = args.GetVoxelData("pvimg");
LOG << "Tissue partial volume image found - using partial volume correction" << endl;
m_pvcorr = true;
if (pvimg.Nrows() > 1)
{
throw InvalidOptionValue("pvimg", "4D data set", "3D data set");
}
m_pv_img = pvimg.Row(1).t();
m_pv_threshold = args.GetDoubleDefault("pv-threshold", 0.5, 0, 1);
m_pv_csf_tiss_m0ratio = args.GetDoubleDefault("csf-tiss-m0ratio", 0.5269);
}
catch (DataNotFound &e)
{
m_pvcorr = false;
LOG << "Tissue partial volume image not found - will not use partial volume correction" << endl;
}
}
void CESTFwdModel::DumpParameters(const ColumnVector &vec, const string &indent) const
{
// cout << vec.t() << endl;
}
void CESTFwdModel::NameParams(vector<string> &names) const
{
names.clear();
// name the parameters for the pools using letters
string lettervec[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w", "x", "y", "z" };