LongECModels.cpp 36.3 KB
Newer Older
wangkx1's avatar
init  
wangkx1 committed
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
// Declarations of classes that implements a hirearchy
// of models for long-time constant fields from eddy 
// currents induced by diffusion gradients.
//
// LongECModels.h
//
// Jesper Andersson, FMRIB Image Analysis Group
//
// Copyright (C) 2022 University of Oxford
//

#include <cstdlib>
#include <string>
#include <vector>
#include <cmath>
#include <iostream>
#include <fstream>
#include <time.h>
#include "nlohmann/json.hpp"
#include "armawrap/newmat.h"
#ifndef EXPOSE_TREACHEROUS
#define EXPOSE_TREACHEROUS           // To allow us to use .set_sform etc
#endif
#include "newimage/newimageall.h"
#include "miscmaths/miscmaths.h"
#include "EddyHelperClasses.h"
#include "LongECModels.h"
#include "ECScanClasses.h"

using namespace EDDY;

// Initial value for eddy current time constant (half-life in seconds).
// small enough to result in little time dependence, but large enough to have a derivative
double const TC_INITIAL_VALUE = 0.1;
double const INTCPT_INITIAL_VALUE = 0.01;

//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//
// Class EC_TimeAndIntercept2Weights
//
// This class translates an EC time constant and intercept to weights
//
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
arma::colvec EC_TimeAndIntercept2Weights::GetWeightsForPrevious(double Thl,            
								double Intcpt) const EddyTry
{
  arma::colvec weights(_mbg.NGroups());
  for (int i=0; i<weights.n_rows; i++) {
    weights(i) = Intcpt * std::exp(-(i)*(_TR/_mbg.NGroups())*std::log(2.0)/Thl);
  }
  return(weights);
} EddyCatch  

arma::colvec EC_TimeAndIntercept2Weights::GetWeightsForCurrent(double Thl,            
							       double Intcpt) const EddyTry
{
  arma::colvec weights(_mbg.NGroups());
  for (int i=0; i<weights.n_rows; i++) {
    weights(i) = 1.0 - Intcpt * std::exp(-(i)*(_TR/_mbg.NGroups())*std::log(2.0)/Thl);
  }
  return(weights);  
} EddyCatch  

//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//
// Class EC_TimeConst2Weights
//
// This class translates an EC time constant to weights
//
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
arma::colvec EC_TimeConst2Weights::GetWeightsForPrevious(double Thl) const EddyTry
{
  arma::colvec prev(_mbg.NGroups());
  arma::colvec curr(_mbg.NGroups());
  this->calculate_weights(Thl,prev,curr);
  return(prev);
} EddyCatch

arma::colvec EC_TimeConst2Weights::GetWeightsForCurrent(double Thl) const EddyTry
{
  arma::colvec prev(_mbg.NGroups());
  arma::colvec curr(_mbg.NGroups());
  this->calculate_weights(Thl,prev,curr);
  return(curr);  
} EddyCatch

void EC_TimeConst2Weights::calculate_weights(double Thl,
					     arma::colvec& prev,
					     arma::colvec& curr) const EddyTry
{
  arma::colvec gtimes(_mbg.NGroups());       // Times at which diffusion gradients are played out
  arma::colvec otimes(2*_mbg.NGroups());     // Times at which eddy currents are observed
  arma::colvec all(2*_mbg.NGroups(),0.0);    // The effects at all times in order [curr prev]
  for (int i=0; i<gtimes.n_rows; i++) gtimes(i) = i*(_TR/_mbg.NGroups());
  for (int i=0; i<otimes.n_rows; i++) otimes(i) = i*(_TR/_mbg.NGroups());
  for (int i=0; i<otimes.n_rows; i++) {
    for (int j=0; j<gtimes.n_rows; j++) {
      if (gtimes(j)-otimes(i) > 1e-6) { // Only count contribution from gradients in the past
	break;
      }
      all(i) += std::exp(-(otimes(i)-gtimes(j))*std::log(2.0)/Thl);
    }
  }
  // Normalise the weights so that they are 1 for the end of current volume
  auto nf = all(_mbg.NGroups()-1);
  std::transform(all.begin(),all.end(),all.begin(),[nf](auto& c){return(c/nf);});
  // Finally divide it up into prev and curr
  curr = all.head_rows(_mbg.NGroups());
  prev = all.tail_rows(_mbg.NGroups());
  return;
} EddyCatch

//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//
// Class IndividualWeightsModel
//
// This class models the weights directly on a volume-by-volume
// basis.
//
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

IndividualWeightsModel::IndividualWeightsModel(ECScanManager& sm) EddyTry
: _nscans(sm.NScans()), _ngroups(sm.MultiBand().NGroups()), 
_prev(sm.NScans(),arma::colvec(sm.MultiBand().NGroups(),arma::fill::zeros)), 
_curr(sm.NScans(),arma::colvec(sm.MultiBand().NGroups(),arma::fill::ones)), 
_ll(sm.NScans(),1e-6) // Start with very little regularisation
{
  if (!sm.IsDiffusion()) throw EddyException("IndividualWeightsModel::IndividualWeightsModel: sm is not diffusion");

  for (unsigned int s=0; s<sm.NScans(); s++) {
    sm.Scan(s).set_previous(_prev[s]);
    sm.Scan(s).set_current(_curr[s]);
  }
} EddyCatch

double IndividualWeightsModel::GetDerivParam(const EDDY::ECScan& sc, 
					     unsigned int        i,
					     unsigned int        s) const EddyTry
{
  if (s >= _nscans) throw EddyException("IndividualWeightsModel::GetDerivParam: s is out of range");
  if (i >= NDerivs()) throw EddyException("IndividualWeightsModel::GetDerivParam: i is out of range");
  if (i < _ngroups) return(sc.GetWeightsForPrevious()(i));
  else return(sc.GetWeightsForCurrent()(i-_ngroups));
} EddyCatch

double IndividualWeightsModel::GetDerivScale(unsigned int i) const EddyTry 
{
  if (i >= NDerivs()) throw EddyException("IndividualWeightsModel::GetDerivScale: i is out of range");
  return(1e-5); 
} EddyCatch

void IndividualWeightsModel::SetDerivParam(EDDY::ECScan&       sc, 
					   unsigned int        i,
					   unsigned int        s,  // Not needed, but checked anyway
					   double              val) const EddyTry
{
  if (i >= NDerivs()) throw EddyException("IndividualWeightsModel::SetDerivParam: i is out of range");
  if (s >= _nscans) throw EddyException("IndividualWeightsModel::SetDerivParam: s is out of range");
  if (i < _ngroups) {
    arma::colvec p = sc.GetWeightsForPrevious();
    p(i) = val;
    sc.set_previous(p);
  }
  else {
    arma::colvec p = sc.GetWeightsForCurrent();
    p(i-_ngroups) = val;
    sc.set_current(p);
  }
  return;
} EddyCatch

double IndividualWeightsModel::GetLevenbergLambda(unsigned int s) const EddyTry {
  if (s >= _nscans) throw EddyException("IndividualWeightsModel::GetLevenbergLambda: s is out of range");
  return(_ll[s]);
} EddyCatch

void IndividualWeightsModel::SetLevenbergLambda(unsigned int s, double lambda) EddyTry {
  if (s >= _nscans) throw EddyException("IndividualWeightsModel::SetLevenbergLambda: s is out of range");
  _ll[s] = lambda;
  return;
} EddyCatch

std::vector<arma::colvec> IndividualWeightsModel::GetParameters(const ECScanManager& sm) const EddyTry
{
  // First verify that the parameters are consistent
  for (unsigned int s=0; s<sm.NScans(); s++) {
    if (!model_and_scan_agree(sm.Scan(s),s)) {
      char message[256]; sprintf(message,"IndividualWeightsModel::GetParameters(sm): mismatch between model and scan %u",s);
      throw EddyException(std::string(message));
    }
  }
  std::vector<arma::colvec> rval(_nscans);
  for (unsigned int s=0; s<_nscans; s++) rval[s] = arma::join_cols(_prev[s],_curr[s]);
  return(rval);
} EddyCatch

arma::colvec IndividualWeightsModel::GetParameters(const ECScan& sc, unsigned int s) const EddyTry
{
  // First verify that the parameters are consistent
  if (s >= _nscans) throw EddyException("IndividualWeightsModel::GetParameters(sc,s): s out of bounds");
  if (!model_and_scan_agree(sc,s)) {
    char message[256]; sprintf(message,"IndividualWeightsModel::GetParameters(sc,s): mismatch between model and scan %u",s);
    throw EddyException(std::string(message));
  }
  return(arma::join_cols(_prev[s],_curr[s]));
} EddyCatch

void IndividualWeightsModel::UpdateParameters(ECScanManager& sm, const std::vector<arma::colvec>& update) EddyTry
{
  // First check agreement between model and update
  if (update.size() != _nscans || update[0].n_rows != NDerivs()) {
    throw EddyException("IndividualWeightsModel::UpdateParameters(sm,update): size mismatch between update and model");
  }
  // Next check agreement between model and scans
  if (sm.NScans() != _nscans) throw EddyException("IndividualWeightsModel::UpdateParameters(sm,update): size mismatch between sm.NScans() and _nscans");
  for (unsigned int s=0; s<sm.NScans(); s++) {
    if (!model_and_scan_agree(sm.Scan(s),s)) {
      char message[256]; sprintf(message,"IndividualWeightsModel::UpdateParameters(sm,update): mismatch between model and scan %u",s);
      throw EddyException(std::string(message));
    }
  }
  // Now update parameters
  for (unsigned int s=0; s<sm.NScans(); s++) {
    _prev[s] += update[s].head(_ngroups);
    _curr[s] += update[s].tail(_ngroups);
    sm.Scan(s).set_previous(_prev[s]);
    sm.Scan(s).set_current(_curr[s]);
  }
  return;
} EddyCatch

void IndividualWeightsModel::UpdateParameters(ECScan& sc, unsigned int s, const arma::colvec& update) EddyTry
{
  // First check agreement between model and update
  if (update.n_rows != NDerivs()) {
    throw EddyException("IndividualWeightsModel::UpdateParameters(sc,s,update): size mismatch between update and model");
  }
  if (s >= _nscans) throw EddyException("IndividualWeightsModel::UpdateParameters(sc,s,update): s out of bounds");
  // Next check agreement between model and scans
  if (!model_and_scan_agree(sc,s)) {
    char message[256]; sprintf(message,"IndividualWeightsModel::UpdateParameters(sc,s,update): mismatch between model and scan %u",s);
    throw EddyException(std::string(message));
  }
  // Now update parameters
  _prev[s] += update.head(_ngroups);
  _curr[s] += update.tail(_ngroups);
  sc.set_previous(_prev[s]);
  sc.set_current(_curr[s]);
  
  return;
} EddyCatch

nlohmann::json IndividualWeightsModel::WriteReport(const ECScanManager& sm, const std::string& fname, bool write_old_style_file) const EddyTry
{
  if (_nscans != sm.NScans()) throw EddyException("IndividualWeightsModel::WriteReport: Mismatch between _nscans and sm.NScans()");
  nlohmann::json long_ec_json;
  if (write_old_style_file) {
    try {
      std::ofstream fout;
      fout.open(fname.c_str(),std::ios::out|std::ios::trunc);
      fout << "Long time constant EC report for individual weights model. Two rows per volume." << std::endl; 
      fout << "The first row gives the weights for the EC-field from the previous diffusion gradient." << std::endl;
      fout << "The second row gives the weights for the EC-field from the current diffusion gradient." << std::endl;
      fout << "Each column represents the weight for one MB-group" << std::endl;
      for (unsigned int s=0; s<_nscans; s++) {
	arma::colvec par = this->GetParameters(sm.Scan(s),s);
	arma::colvec previous = par.head_rows(_ngroups);
	for (unsigned int c=0; c<_ngroups; c++) fout << previous(c) << " ";
	fout << std::endl;
	arma::colvec current = par.tail_rows(_ngroups);
	for (unsigned int c=0; c<_ngroups; c++) fout << current(c) << " ";
	fout << std::endl;
      }
      fout.close();
    }
    catch(...) { throw EddyException("IndividualWeightsModel::WriteReport: Error when attempting to write file " + fname); }
  }
  std::vector<nlohmann::json> volumes(_nscans);
  for (unsigned int s=0; s<_nscans; s++) {
    volumes[s]["Volume #"] = s;
    arma::colvec par = this->GetParameters(sm.Scan(s),s);
    volumes[s]["Previous"] = arma::conv_to<std::vector<double> >::from(par.head_rows(_ngroups));
    volumes[s]["Current"] = arma::conv_to<std::vector<double> >::from(par.tail_rows(_ngroups));
  }
  long_ec_json["Model"] = "Individual weights";
  long_ec_json["Format"] = "Long time-constant eddy currents was modelled as two sets of weights per volume,\nthe first is the weights of the EC field from the previous diffusion gradient\n and the second is the weights for the EC field for the current diffusion gradient.\nThe weights pertains to the MB-groups.";
  long_ec_json["Volumes"] = volumes;

  return(long_ec_json);
} EddyCatch

bool IndividualWeightsModel::model_and_scan_agree(const ECScan& sc, unsigned int s) const EddyTry
{
  return(!(arma::any(sc.GetWeightsForPrevious() != _prev[s]) || arma::any(sc.GetWeightsForCurrent() != _curr[s])));
} EddyCatch

//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//
// Class IndividualTimeConstantsModel
//
// This class models the time constants (half-life in seconds) 
// on a volume-by-volume basis.
//
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

IndividualTimeConstantsModel::IndividualTimeConstantsModel(ECScanManager& sm) EddyTry
: _nscans(sm.NScans()), _tai2w(sm.RepetitionTime(),sm.MultiBand()), _par(sm.NScans(),arma::colvec(4,arma::fill::none)),
_ll(sm.NScans(),0.1) // Start with a fair bit of regularisation 
{
  if (!sm.IsDiffusion()) throw EddyException("IndividualTimeConstantsModel::IndividualTimeConstantsModel: sm is not diffusion");

  for (unsigned int s=0; s<_nscans; s++) {
    _par[s](0) = TC_INITIAL_VALUE;
    _par[s](1) = INTCPT_INITIAL_VALUE;
    _par[s](2) = TC_INITIAL_VALUE;
    _par[s](3) = INTCPT_INITIAL_VALUE;
  }
  arma::colvec prev = _tai2w.GetWeightsForPrevious(_par[0](0),_par[0](1));
  arma::colvec curr = _tai2w.GetWeightsForCurrent(_par[0](2),_par[0](3));

  std::cout << "IndividualTimeConstantsModel::IndividualTimeConstantsModel" << std::endl;
  std::cout << "Previous:" << std::endl;
  for (unsigned int i=0; i<prev.n_rows; i++) std::cout << prev(i) << std::endl;
  std::cout << "Current:" << std::endl;
  for (unsigned int i=0; i<prev.n_rows; i++) std::cout << curr(i) << std::endl;

  for (unsigned int s=0; s<_nscans; s++) {
    sm.Scan(s).set_previous(prev);
    sm.Scan(s).set_current(curr);
  }
} EddyCatch

double IndividualTimeConstantsModel::GetDerivParam(const EDDY::ECScan& sc, unsigned int i, unsigned int s) const EddyTry
{
  if (i >= NDerivs()) throw EddyException("IndividualTimeConstantsModel::GetDerivParam: i out of bounds");
  if (s >= _nscans) throw EddyException("IndividualTimeConstantsModel::GetDerivParam: s out of bounds");
  return(_par[s](i));
} EddyCatch

double IndividualTimeConstantsModel::GetDerivScale(unsigned int i) const EddyTry 
{
  if (i >= NDerivs()) throw EddyException("IndividualTimeConstantsModel::GetDerivScale: i out of bounds");
  if (i==0 || i==2) return(1e-3); // If it is half life
  return(1e-4);                   // If it is intercept 
  // return(1e-3);
} EddyCatch

void IndividualTimeConstantsModel::SetDerivParam(ECScan& sc, unsigned int i, unsigned int s, double val) const
{
  if (i >= NDerivs()) throw EddyException("IndividualTimeConstantsModel::SetDerivParam: i out of bounds");
  if (s >= _nscans) throw EddyException("IndividualTimeConstantsModel::SetDerivParam: s out of bounds");
  if (i<2) {
    if (i==0) sc.set_previous(_tai2w.GetWeightsForPrevious(val,_par[s](1)));
    else sc.set_previous(_tai2w.GetWeightsForPrevious(_par[s](0),val));
  }
  else {
    if (i==2) sc.set_current(_tai2w.GetWeightsForCurrent(val,_par[s](3)));
    else sc.set_current(_tai2w.GetWeightsForCurrent(_par[s](2),val));
  }
}

double IndividualTimeConstantsModel::GetLevenbergLambda(unsigned int s) const EddyTry {
  if (s >= _nscans) throw EddyException("IndividualTimeConstantsModel::GetLevenbergLambda: s is out of range");
  return(_ll[s]);
} EddyCatch

void IndividualTimeConstantsModel::SetLevenbergLambda(unsigned int s, double lambda) EddyTry {
  if (s >= _nscans) throw EddyException("IndividualTimeConstantsModel::SetLevenbergLambda: s is out of range");
  _ll[s] = lambda;
  return;
} EddyCatch

std::vector<arma::colvec> IndividualTimeConstantsModel::GetParameters(const ECScanManager& sm) const EddyTry
{
  // First verify that the parameters are consistent
  for (unsigned int s=0; s<sm.NScans(); s++) {
    if (!model_and_scan_agree(sm.Scan(s),s)) {
      char message[256]; sprintf(message,"IndividualTimeConstantsModel::GetParameters(sm): mismatch between model and scan %u",s);
      throw EddyException(std::string(message));
    }
  }
  return(_par);
} EddyCatch

arma::colvec IndividualTimeConstantsModel::GetParameters(const ECScan& sc, unsigned int s) const EddyTry
{
  // First verify that the parameters are consistent
  if (s >= _nscans) throw EddyException("IndividalTimeConstantsModel::GetParameters(sc,s): s out of bounds");
  if (!model_and_scan_agree(sc,s)) {
    char message[256]; sprintf(message,"IndividualTimeConstantsModel::GetParameters(sc,s): mismatch between model and scan %u",s);
    throw EddyException(std::string(message));
  }
  return(_par[s]);
} EddyCatch

void IndividualTimeConstantsModel::UpdateParameters(ECScanManager& sm, const std::vector<arma::colvec>& update) EddyTry
{
  // First check agreement between model and update
  if (update.size() != _nscans || update[0].n_rows != NDerivs()) {
    throw EddyException("IndividualTimeConstantsModel::UpdateParameters(sm,update): size mismatch between update and model");
  }
  // Next check agreement between model and scans
  if (sm.NScans() != _nscans) throw EddyException("IndividualTimeConstantsModel::UpdateParameters(sm,update): size mismatch between sm.NScans() and _nscans");
  for (unsigned int s=0; s<sm.NScans(); s++) {
    if (!model_and_scan_agree(sm.Scan(s),s)) {
      char message[256]; sprintf(message,"IndividalTimeConstantsModel::UpdateParameters(sm,update): mismatch between model and scan %u",s);
      throw EddyException(std::string(message));
    }
  }
  // Now update parameters
  for (unsigned int s=0; s<sm.NScans(); s++) {
    for (unsigned int i=0; i<NDerivs(); i++) _par[s](i) += update[s](i);
    sm.Scan(s).set_previous(_tai2w.GetWeightsForPrevious(_par[s](0),_par[s](1)));
    sm.Scan(s).set_current(_tai2w.GetWeightsForCurrent(_par[s](2),_par[s](3)));    
  }
  return;
} EddyCatch

void IndividualTimeConstantsModel::UpdateParameters(ECScan& sc, unsigned int s, const arma::colvec& update) EddyTry
{
  // First check agreement between model and update
  if (update.n_rows != NDerivs()) {
    throw EddyException("IndividalTimeConstantsModel::UpdateParameters(sc,s,update): size mismatch between update and model");
  }
  if (s >= _nscans) throw EddyException("IndividalTimeConstantsModel::UpdateParameters(sc,s,update): s out of bounds");
  // Next check agreement between model and scans
  if (!model_and_scan_agree(sc,s)) {
    char message[256]; sprintf(message,"IndividalTimeConstantsModel::UpdateParameters(sc,s,update): mismatch between model and scan %u",s);
    throw EddyException(std::string(message));
  }
  // Now update parameters
  for (unsigned int i=0; i<NDerivs(); i++) _par[s](i) += update(i);
  sc.set_previous(_tai2w.GetWeightsForPrevious(_par[s](0),_par[s](1)));
  sc.set_current(_tai2w.GetWeightsForCurrent(_par[s](2),_par[s](3)));    
  
  return;
} EddyCatch

nlohmann::json IndividualTimeConstantsModel::WriteReport(const ECScanManager& sm, const std::string& fname, bool write_old_style_file) const EddyTry
{
  if (_nscans != sm.NScans()) throw EddyException("IndividualTimeConstantsModel::WriteReport: Mismatch between _nscans and sm.NScans()");
  if (write_old_style_file) {
    try {
      std::ofstream fout;
      fout.open(fname.c_str(),std::ios::out|std::ios::trunc);
      fout << "Long time constant EC report for individual time constants model. Three rows per volume." << std::endl; 
      fout << "The first row gives [TC Intercept] for previous, followed by [TC Intercept] for current." << std::endl;
      fout << "The second row gives the weights for the EC-field from the previous diffusion gradient." << std::endl;
      fout << "The third row gives the weights for the EC-field from the current diffusion gradient." << std::endl;
      fout << "Each column of rows two and three represents the weight for one MB-group" << std::endl;
      std::vector<arma::colvec> tc = this->GetParameters(sm);
      for (unsigned int s=0; s<_nscans; s++) {
	fout << tc[s](0) << " " << tc[s](1) << " " << tc[s](2) << " " << tc[s](3) << std::endl; 
	arma::colvec previous = sm.Scan(s).GetWeightsForPrevious();
	for (unsigned int c=0; c<_tai2w.NGroups(); c++) fout << previous(c) << " ";
	fout << std::endl;
	arma::colvec current = sm.Scan(s).GetWeightsForCurrent();
	for (unsigned int c=0; c<_tai2w.NGroups(); c++) fout << current(c) << " ";
	fout << std::endl;
      }
      fout.close();      
    }
    catch(...) { throw EddyException("IndividualTimeConstantsModel::WriteReport: Error when attempting to write file " + fname); }
  }
  nlohmann::json long_ec_json;
  std::vector<nlohmann::json> volumes(_nscans);
  for (unsigned int s=0; s<_nscans; s++) {
    volumes[s]["Volume #"] = s;
    volumes[s]["Half-life (s) Intercept for previous"] = arma::conv_to<std::vector<double> >::from(this->GetParameters(sm.Scan(s),s).rows(0,1));
    volumes[s]["Half-life (s) Intercept for current"] = arma::conv_to<std::vector<double> >::from(this->GetParameters(sm.Scan(s),s).rows(2,3));
    volumes[s]["Resulting weights for previous"] = arma::conv_to<std::vector<double> >::from(sm.Scan(s).GetWeightsForPrevious());
    volumes[s]["Resulting weights for current"] = arma::conv_to<std::vector<double> >::from(sm.Scan(s).GetWeightsForCurrent());	
  }
  long_ec_json["Model"] = "Individual time-constants";
  long_ec_json["Format"] = "Long time-constant eddy currents was modelled as one time-constant (half-life in seconds) \nand one intercept for previous and current, resulting in four parameters per volume.\nThe resulting weights for the MB-groups are also given.";
  long_ec_json["Volumes"] = volumes;
  
  return(long_ec_json);
} EddyCatch

bool IndividualTimeConstantsModel::model_and_scan_agree(const ECScan& sc, unsigned int s) const EddyTry
{
  return(!(arma::any(sc.GetWeightsForPrevious() != _tai2w.GetWeightsForPrevious(_par[s](0),_par[s](1))) || 
	   arma::any(sc.GetWeightsForCurrent() != _tai2w.GetWeightsForCurrent(_par[s](2),_par[s](3)))));
} EddyCatch

//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//
// Class JointWeightsModel
//
// This class models the weights jointly across all volumes.
//
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

JointWeightsModel::JointWeightsModel(ECScanManager& sm) EddyTry
: _nscans(sm.NScans()), _ngroups(sm.MultiBand().NGroups()), 
_prev(arma::colvec(sm.MultiBand().NGroups(),arma::fill::zeros)), _curr(arma::colvec(sm.MultiBand().NGroups(),arma::fill::ones)),
_ll(1e-6) // Start with very little regularisation
{
  if (!sm.IsDiffusion()) throw EddyException("JointWeightsModel::JointWeightsModel: sm is not diffusion");

  for (unsigned int s=0; s<sm.NScans(); s++) {
    sm.Scan(s).set_previous(_prev);
    sm.Scan(s).set_current(_curr);
  }
} EddyCatch

double JointWeightsModel::GetDerivParam(const EDDY::ECScan& sc, 
					unsigned int        i,
					unsigned int        s) const EddyTry
{
  if (s >= _nscans) throw EddyException("JointWeightsModel::GetDerivParam: s is out of range");
  if (i >= NDerivs()) throw EddyException("JointWeightsModel::GetDerivParam: i is out of range");
  if (i < _ngroups) return(sc.GetWeightsForPrevious()(i));
  else return(sc.GetWeightsForCurrent()(i-_ngroups));
} EddyCatch

double JointWeightsModel::GetDerivScale(unsigned int i) const EddyTry 
{
  if (i >= NDerivs()) throw EddyException("JointWeightsModel::GetDerivScale: i is out of range");
  return(1e-5); 
} EddyCatch

void JointWeightsModel::SetDerivParam(EDDY::ECScan&       sc, 
				      unsigned int        i,
				      unsigned int        s,  // Not needed, but checked anyway
				      double              val) const EddyTry
{
  if (i >= NDerivs()) throw EddyException("JointWeightsModel::GetDerivParam: i is out of range");
  if (s >= _nscans) throw EddyException("JointWeightsModel::GetDerivParam: s is out of range");
  if (i < _ngroups) {
    arma::colvec p = sc.GetWeightsForPrevious();
    p(i) = val;
    sc.set_previous(p);
  }
  else {
    arma::colvec p = sc.GetWeightsForCurrent();
    p(i-_ngroups) = val;
    sc.set_current(p);
  }
  return;
} EddyCatch

double JointWeightsModel::GetLevenbergLambda(unsigned int s) const EddyTry {
  if (s >= _nscans) throw EddyException("JointWeightsModel::GetLevenbergLambda: s is out of range"); // Not needed, but do anyway
  return(_ll);
} EddyCatch

void JointWeightsModel::SetLevenbergLambda(unsigned int s, double lambda) EddyTry {
  if (s >= _nscans) throw EddyException("JointWeightsModel::SetLevenbergLambda: s is out of range"); // Not needed, but do anyway
  _ll = lambda;
  return;
} EddyCatch

std::vector<arma::colvec> JointWeightsModel::GetParameters(const ECScanManager& sm) const EddyTry
{
  // First verify that the parameters are consistent
  for (unsigned int s=0; s<sm.NScans(); s++) {
    if (!model_and_scan_agree(sm.Scan(s),s)) {
      char message[256]; sprintf(message,"JointWeightsModel::GetParameters(sm): mismatch between model and scan %u",s);
      throw EddyException(std::string(message));
    }
  }
  std::vector<arma::colvec> rval(1);
  rval[0] = arma::join_cols(_prev,_curr);
  return(rval);
} EddyCatch

arma::colvec JointWeightsModel::GetParameters(const ECScan& sc, unsigned int s) const EddyTry
{
  // First verify that the parameters are consistent
  if (s >= _nscans) throw EddyException("JointWeightsModel::GetParameters(sc,s): s out of bounds");
  if (!model_and_scan_agree(sc,s)) {
    char message[256]; sprintf(message,"JointWeightsModel::GetParameters(sc,s): mismatch between model and scan %u",s);
    throw EddyException(std::string(message));
  }
  return(arma::join_cols(_prev,_curr));
} EddyCatch

void JointWeightsModel::UpdateParameters(ECScanManager& sm, const std::vector<arma::colvec>& update) EddyTry
{
  // First check agreement between model and update
  if (update.size() != 1 || update[0].n_rows != NDerivs()) {
    throw EddyException("JointWeightsModel::UpdateParameters(sm,update): size mismatch between update and model");
  }
  // Next check agreement between model and scans
  if (sm.NScans() != _nscans) throw EddyException("JointWeightsModel::UpdateParameters(sm,update): size mismatch between sm.NScans() and _nscans");
  for (unsigned int s=0; s<sm.NScans(); s++) {
    if (!model_and_scan_agree(sm.Scan(s),s)) {
      char message[256]; sprintf(message,"JointWeightsModel::UpdateParameters(sm,update): mismatch between model and scan %u",s);
      throw EddyException(std::string(message));
    }
  }
  // Now update parameters
  _prev += update[0].head(_ngroups);
  _curr += update[0].tail(_ngroups);
  for (unsigned int s=0; s<sm.NScans(); s++) {
    sm.Scan(s).set_previous(_prev);
    sm.Scan(s).set_current(_curr);
  }
  return;
} EddyCatch

void JointWeightsModel::UpdateParameters(ECScan& sc, unsigned int s, const arma::colvec& update) EddyTry
{
  throw EddyException("JointWeightsModel::UpdateParameters(sc,s,update): not allowed to update individual scan");
  return;
} EddyCatch

nlohmann::json JointWeightsModel::WriteReport(const ECScanManager& sm, const std::string& fname, bool write_old_style_file) const EddyTry
{
  if (_nscans != sm.NScans()) throw EddyException("JointWeightsModel::WriteReport: Mismatch between _nscans and sm.NScans()");
  if (write_old_style_file) {
    try {
      std::ofstream fout;
      fout.open(fname.c_str(),std::ios::out|std::ios::trunc);
      fout << "Long time constant EC report for joint weights model. Two rows." << std::endl; 
      fout << "The first row gives the weights for the EC-field from the previous diffusion gradient." << std::endl;
      fout << "The second row gives the weights for the EC-field from the current diffusion gradient." << std::endl;
      fout << "Each column represents the weight for one MB-group" << std::endl;
      std::vector<arma::colvec> par = this->GetParameters(sm);
      arma::colvec previous = par[0].head_rows(_ngroups);
      for (unsigned int c=0; c<_ngroups; c++) fout << previous(c) << " ";
      fout << std::endl;
      arma::colvec current = par[0].tail_rows(_ngroups);
      for (unsigned int c=0; c<_ngroups; c++) fout << current(c) << " ";
      fout << std::endl;
      fout.close();
    }
    catch(...) { throw EddyException("JointWeightsModel::WriteReport: Error when attempting to write file " + fname); }
  }
  nlohmann::json long_ec_json;
  long_ec_json["Model"] = "Joint weights";
  long_ec_json["Format"] = "Long time-constant eddy currents was modelled as two sets of weights,\nthe first is the weights of the EC field from the previous diffusion gradient\n and the second is the weights for the EC field for the current diffusion gradient.\nThe weights pertains to the MB-groups and are pooled across all volumes.";
  std::vector<arma::colvec> par = this->GetParameters(sm);
  long_ec_json["Previous"] = arma::conv_to<std::vector<double> >::from(par[0].head_rows(_ngroups));
  long_ec_json["Current"] = arma::conv_to<std::vector<double> >::from(par[0].tail_rows(_ngroups));

  return(long_ec_json);
} EddyCatch

bool JointWeightsModel::model_and_scan_agree(const ECScan& sc, unsigned int s) const EddyTry
{
  return(!(arma::any(sc.GetWeightsForPrevious() != _prev) || arma::any(sc.GetWeightsForCurrent() != _curr)));
} EddyCatch

//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//
// Class JointTimeConstantModel
//
// This class models the time-constant (half-life in seconds) 
// jointly across all volumes.
//
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

JointTimeConstantModel::JointTimeConstantModel(ECScanManager& sm) EddyTry
: _nscans(sm.NScans()), _tai2w(sm.RepetitionTime(),sm.MultiBand()), _par(arma::colvec(4,arma::fill::none)),
_ll(0.1) // Start with a fair bit of regularisation
 
{
  if (!sm.IsDiffusion()) throw EddyException("JointTimeConstantsModel::JointTimeConstantsModel: sm is not diffusion");

  _par(0) = TC_INITIAL_VALUE;
  _par(1) = INTCPT_INITIAL_VALUE;
  _par(2) = TC_INITIAL_VALUE;
  _par(3) = INTCPT_INITIAL_VALUE;
  arma::colvec prev = _tai2w.GetWeightsForPrevious(_par(0),_par(1));
  arma::colvec curr = _tai2w.GetWeightsForCurrent(_par(2),_par(3));

  for (unsigned int s=0; s<sm.NScans(); s++) {
    sm.Scan(s).set_previous(prev);
    sm.Scan(s).set_current(curr);
  }
} EddyCatch

double JointTimeConstantModel::GetDerivParam(const EDDY::ECScan& sc, unsigned int i, unsigned int s) const EddyTry
{
  if (i >= NDerivs()) throw EddyException("JointTimeConstantModel::GetDerivParam: i out of bounds");
  if (s >= _nscans) throw EddyException("JointTimeConstantModel::GetDerivParam: s out of bounds");
  return(_par(i));
} EddyCatch

double JointTimeConstantModel::GetDerivScale(unsigned int i) const EddyTry 
{
  if (i >= NDerivs()) throw EddyException("JointTimeConstantModel::GetDerivScale: i out of bounds");
  return(1e-5); 
} EddyCatch

void JointTimeConstantModel::SetDerivParam(ECScan& sc, unsigned int i, unsigned int s, double val) const
{
  if (i >= NDerivs()) throw EddyException("JointTimeConstantModel::SetDerivParam: i out of bounds");
  if (s >= _nscans) throw EddyException("JointTimeConstantModel::SetDerivParam: s out of bounds");
  if (i < 2) {
    if (i==0) sc.set_previous(_tai2w.GetWeightsForPrevious(val,_par(1)));
    else sc.set_previous(_tai2w.GetWeightsForPrevious(_par(0),val));
  }
  else {
    if (i==2) sc.set_current(_tai2w.GetWeightsForCurrent(val,_par(3)));
    else sc.set_current(_tai2w.GetWeightsForCurrent(_par(2),val));
  }
}

double JointTimeConstantModel::GetLevenbergLambda(unsigned int s) const EddyTry {
  if (s >= _nscans) throw EddyException("JointTimeConstantModel::GetLevenbergLambda: s is out of range"); // Not needed, but do anyway
  return(_ll);
} EddyCatch

void JointTimeConstantModel::SetLevenbergLambda(unsigned int s, double lambda) EddyTry {
  if (s >= _nscans) throw EddyException("JointTimeConstantModel::SetLevenbergLambda: s is out of range"); // Not needed, but do anyway
  _ll = lambda;
  return;
} EddyCatch

std::vector<arma::colvec> JointTimeConstantModel::GetParameters(const ECScanManager& sm) const EddyTry
{
  // First verify that the parameters are consistent
  for (unsigned int s=0; s<sm.NScans(); s++) {
    if (!model_and_scan_agree(sm.Scan(s),s)) {
      char message[256]; sprintf(message,"JointTimeConstantModel::GetParameters(sm): mismatch between model and scan %u",s);
      throw EddyException(std::string(message));
    }
  }
  return(std::vector<arma::colvec>(1,_par));
} EddyCatch

arma::colvec JointTimeConstantModel::GetParameters(const ECScan& sc, unsigned int s) const EddyTry
{
  // First verify that the parameters are consistent
  if (s >= _nscans) throw EddyException("JointTimeConstantModel::GetParameters(sc,s): s out of bounds");
  if (!model_and_scan_agree(sc,s)) {
    char message[256]; sprintf(message,"JointTimeConstantModel::GetParameters(sc,s): mismatch between model and scan %u",s);
    throw EddyException(std::string(message));
  }
  return(_par);
} EddyCatch

void JointTimeConstantModel::UpdateParameters(ECScanManager& sm, const std::vector<arma::colvec>& update) EddyTry
{
  // First check agreement between model and update
  if (update.size() != 1 || update[0].n_rows != NDerivs()) {
    throw EddyException("JointTimeConstantModel::UpdateParameters(sm,update): size mismatch between update and model");
  }
  // Next check agreement between model and scans
  if (sm.NScans() != _nscans) throw EddyException("JointTimeConstantModel::UpdateParameters(sm,update): size mismatch between sm.NScans() and _nscans");
  for (unsigned int s=0; s<sm.NScans(); s++) {
    if (!model_and_scan_agree(sm.Scan(s),s)) {
      char message[256]; sprintf(message,"JointTimeConstantModel::UpdateParameters(sm,update): mismatch between model and scan %u",s);
      throw EddyException(std::string(message));
    }
  }
  // Now update parameters
  for (unsigned int i=0; i<NDerivs(); i++) _par(i) += update[0](i);
  for (unsigned int s=0; s<sm.NScans(); s++) {
    sm.Scan(s).set_previous(_tai2w.GetWeightsForPrevious(_par(0),_par(1)));
    sm.Scan(s).set_current(_tai2w.GetWeightsForCurrent(_par(2),_par(3)));
  }
  return;
} EddyCatch

void JointTimeConstantModel::UpdateParameters(ECScan& sc, unsigned int s, const arma::colvec& update) EddyTry
{
  throw EddyException("JointTimeConstantModel::UpdateParameters(sc,s,update): not allowed to update individual scan");
  return;
} EddyCatch

nlohmann::json JointTimeConstantModel::WriteReport(const ECScanManager& sm, const std::string& fname, bool write_old_style_file) const EddyTry
{
  if (_nscans != sm.NScans()) throw EddyException("JointTimeConstantModel::WriteReport: Mismatch between _nscans and sm.NScans()");
  if (write_old_style_file) {
    try {
      std::ofstream fout;
      fout.open(fname.c_str(),std::ios::out|std::ios::trunc);
      fout << "Long time constant EC report for joint time constant model. Three rows." << std::endl; 
      fout << "The first row gives [TC Intercept] for previous, followed by [TC Intercept] for current." << std::endl;
      fout << "The second row gives the resulting weights for the EC-field from the previous diffusion gradient." << std::endl;
      fout << "The third row gives the resulting weights for the EC-field from the current diffusion gradient." << std::endl;
      fout << "Each column represents the weight for one MB-group" << std::endl;
      std::vector<arma::colvec> tc = this->GetParameters(sm);
      fout << tc[0](0) << " " << tc[0](1) << " " << tc[0](2) << " " << tc[0](3) << std::endl; 
      arma::colvec previous = sm.Scan(0).GetWeightsForPrevious();
      for (unsigned int c=0; c<_tai2w.NGroups(); c++) fout << previous(c) << " ";
      fout << std::endl;
      arma::colvec current = sm.Scan(0).GetWeightsForCurrent();
      for (unsigned int c=0; c<_tai2w.NGroups(); c++) fout << current(c) << " ";
      fout << std::endl;
      fout.close();
    }
    catch(...) { throw EddyException("JointTimeConstantModel::WriteReport: Error when attempting to write file " + fname); }
  }
  nlohmann::json long_ec_json;
  long_ec_json["Model"] = "Joint time-constant";
  long_ec_json["Format"] = "Long time-constant eddy currents was modelled as a single time-constant (half-life in seconds) across all volumes.\nThe resulting weights for the MB-groups are also given.";      
  long_ec_json["Half-life (s) Intercept for previous"] = arma::conv_to<std::vector<double> >::from(this->GetParameters(sm)[0].rows(0,1));
  long_ec_json["Half-life (s) Intercept for current"] = arma::conv_to<std::vector<double> >::from(this->GetParameters(sm)[0].rows(2,3));
  long_ec_json["Resulting weights for previous"] = arma::conv_to<std::vector<double> >::from(sm.Scan(0).GetWeightsForPrevious());
  long_ec_json["Resulting weights for current"] = arma::conv_to<std::vector<double> >::from(sm.Scan(0).GetWeightsForCurrent());	

  return(long_ec_json);
} EddyCatch

bool JointTimeConstantModel::model_and_scan_agree(const ECScan& sc, unsigned int s) const EddyTry
{
  return(!(arma::any(sc.GetWeightsForPrevious() != _tai2w.GetWeightsForPrevious(_par(0),_par(1))) || 
	   arma::any(sc.GetWeightsForCurrent() != _tai2w.GetWeightsForCurrent(_par(2),_par(3)))));
} EddyCatch

nlohmann::json NoLongECModel::WriteReport(const ECScanManager& sm, const std::string& fname, bool write_old_style_file) const EddyTry {
  nlohmann::json long_ec_json;
  long_ec_json["Model"] = "None";
  long_ec_json["Format"] = "No modelling of long time-constant eddy currents was performed.";
  return(long_ec_json);
} EddyCatch