-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNMR_RF.cc
2572 lines (2309 loc) · 73 KB
/
NMR_RF.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
// arbitrary separation of "sequence" related stuff to lighten NMR.cc
#include "NMRsim_RF.h"
#include "Parser.h"
#include <sstream>
//! parse pulse directive
/** qualifier distinguishes hard, soft, auto */
void parse_pulse(int);
void parse_reset();
void parse_store();
void parse_channel();
void parse_delay();
#ifdef NMRSIM_INTUITIVE_OFFSET
inline double convertoffset(double x) { return -x; }
#else
inline double convertoffset(double x) { return x; }
#endif
inline bool quickphasemod(const CompSequenceBase& seq) { return seq.modulation().get() && optcache(); }
//inline bool quickphasemod(const Sequence& seq) { return false; }
//! don't use (phase modulation) steps below this fraction of maxdt
#define NMRSIM_MINSTEP 0.6
dirtylist_t dirty_list;
bool havestore=false;
double phasetolerance=5e-4; // match that must be achieved on rotor phase (degrees) NB. doesn't account for "jitter". Can't be too tight as phase at long times will not be calculated accurately
double tolerance=5e-9; //5 ns
option optcombinepropagators("combinepropagators","combine propagators",option::AUTO,option::NOTUSED);
option optsmartprop("smartprop","",option::AUTO,option::NOTUSED);
LIST<smartptr<PulseGeneratorBase> > pgenstack;
LIST<matrix_partition_set> partitions;
LIST<int> prop_flags;
//LIST<double> transient_amps;
//! RF transient model
enum trans_t { TRANS_NONE, //!< no transients
TRANS_AUTO, //!< simple "Vega" model global per channel
TRANS_MANUAL //!< specified per pulse
};
trans_t transient_model=TRANS_NONE; //!< RF transient model (default \c TRANS_NONE)
//! "manual" mode does not involve trailing transients
//bool inline hastransients() { return (transient_model==TRANS_SIMPLE); }
size_t usedchannels=0;
size_t curchannel=0; //!< current channel (::AsyncSequence build)
struct SysVar_trans : public SystemVariable<double*> {
SysVar_trans(const char* name, size_t which)
: SystemVariable<double*>(name,&value_), which_(which), value_(0.0) {}
void update();
size_t which_;
double value_;
};
LIST<SysVar_trans*> transient_amps;
option optphasemod("phasemodulation","phase modulated RF");
namespace {
const double rad_to_deg=180.0/M_PI;
const double deg_to_rad=M_PI/180.0;
struct Proxy_ {
Proxy_() {
// optional_map_t& optional_map(get_optional_map());
//optional_map["phasemodulation"]=&optphasemod;
//optional_map["combinepropagators"]=&optcombinepropagators;
//optional_map["smartprop"]=&optsmartprop;
add_option(optphasemod);
add_option(optcombinepropagators);
add_option(optsmartprop);
command_Factory_t& par_Factory(get_par_Factory());
par_Factory["channel"]=par_t(&parse_channel,true);
par_Factory["delay"]=par_t(&parse_delay,true);
par_Factory["pulse"]=par_t(&parse_pulse,EventID::soft,true);
par_Factory["pulseid"]=par_t(&parse_pulse,EventID::ideal,true);
par_Factory["pulseauto"]=par_t(&parse_pulse,EventID::automatic,true);
par_Factory["store"]=par_t(&parse_store,true);
}
};
Proxy_ proxy;
}
void sequencestate_t::reset(bool resetdur)
{
curptr=0; //!< reset current fragment pointer
lastoffset_=0.0; //!< no trailing fragment
if (resetdur)
duration_=-1.0;
}
void CycledSequence::reset(bool resetduration)
{
if (states_.empty()) {
states_.create(size());
return;
}
for (size_t i=states_.size();i--;)
states_(i).reset(resetduration);
}
CycledSequence::CycledSequence()
: dirty_(false)
{ reset(true); }
CycledSequence::CycledSequence(CompSequenceBase& seq)
: ListList<PhasedSequence*>(ExplicitList<1,size_t>(1U),new PhasedSequence(seq,0.0)),
name_(seq.name())
{ reset(true); }
CycledSequence::CycledSequence(PhasedSequence* pseq)
: ListList<PhasedSequence*>(ExplicitList<1,size_t>(1U),pseq)
{ reset(true); }
subsid_t CycledSequence::index_to_subsid(size_t ind)
{
return subsid_t(ind+100);
}
size_t CycledSequence::subsid_to_index(subsid_t subsid)
{
int ind=int(subsid)-100;
if (ind<0) {
std::cerr << "Bad subsid_to_index parameter: " << subsid << '\n';
error_abort();
}
return ind;
}
void SysVar_trans::update()
{
// if (!hastransients()) {
// PulseGenerator_SimpleTransients* pgenp(dynamic_cast<PulseGenerator_SimpleTransients*>(pgenstack(which_).get()));
// if (pgenp)
pgenstack(which_)->transient_amplitude(transient_amps(which_)->get());
// else
// throw InternalError("transient_amplitude");
//flagdirty(DIRTY_HAMILTONIAN);
// }
//! invalidate propagators
/** A touch inefficient since only sequences involving the relevant channels are affected */
update_propagators=DIRTY_ALL;
}
template<class T> void set_partitioning(T& propgen, const CompSequenceBase& seq)
{
const matrix_partition_set& part(seq.partitioning());
if (!part.empty())
propgen.partitioning(part);
}
void parse_transients()
{
const char* com=parse_string(F_REPLACEDOLLAR);
// if (strcmp(com,"none")==0) {
// transient_model=TRANS_NONE;
// return true;
// }
if (strcmp(com,"manual")==0)
transient_model=TRANS_MANUAL;
else {
if (strcmp(com,"automatic")==0)
transient_model=TRANS_AUTO;
else
error_abort("Unknown transient model");
}
char name[32];
bool nonzero=false;
transient_amps.create(nchannels);
for (size_t j=0;j<nchannels;j++) {
snprintf(name,sizeof(name),"transient_amplitude%" LCM_PRI_SIZE_T_MODIFIER "u",j+1);
transient_amps(j)=new SysVar_trans(name,j);
parse_system_variable(*(transient_amps(j)));
if (transient_amps(j)->get())
nonzero=true;
// Variable cvar(S_ARG1,varp);
//transient_amps(j)=parse_double(&cvar);
}
if (nonzero && optphasemod.isauto())
optphasemod.set(option::OFF);
// parse_system_variable(v_trans);
}
size_t CompSequenceBase::verbose_check_sync(double x,const char* nx, double y, const char* ny) const
{
const size_t sync=check_sync(x/y);
if (!donesyncwarn && syncfailed_warning.enabled() && (sync==0)) {//!< check enabled as build is expensive
std::ostringstream str(std::ostringstream::out);
str << ny << " (";
prettyprint_time(y,str) << ") does not divide into " << nx << " (";
prettyprint_time(x,str) << ") for sequence " << name_ << " (future warnings for this sequence suppressed)";
syncfailed_warning.raise(str.str().c_str());
donesyncwarn=true;
}
return sync;
}
smartptr<ZshiftCache,false> zshift_cachep;
simple_counter global_cache(NMRSIM_CACHE_LIMIT*1024*1024);
Spectrometer spectrometer;
double tres=0.0;
struct SysVar_tres : public SystemVariable<double*> {
SysVar_tres(const std::string& name_, double* value_)
: SystemVariable<double*>(name_,value_,1e6) {}
void update() {
spectrometer.time_resolution(tres);
update_propagators=DIRTY_ALL;
// flagdirty(DIRTY_ALL); //all sequences need rebuilding
}
};
SysVar_tres v_tres("time_resolution",&tres);
void parse_time_resolution()
{
if (are_left())
parse_system_variable(v_tres);
else
std::cout << "time_resolution=" << (tres*1e6) << " us\n";
}
template<class HType> void MasterObj::propagator_(BlockedMatrix<complex>& Udest, const HType& H, const CompSequenceBase& seq, double t1,double t2,double origin)
{
SequencePropagator propgen(H,get_maxdt(),seq.seqlist,origin,seq.duration(),tolerance,(verbose & VER_GEN) ? verbose_level : 0,seq.prop_flags());
set_partitioning(propgen,seq);
propgen.synchronisation_hint(seq.synchronisation_time());
propgen(Udest,t1,t2);
}
template<class HType> void MasterObj::propagator_(BlockedMatrix<complex>& Udest, const HType& H, const Sequence& seq, double t1,double t2,double origin)
{
SequencePropagator propgen(H,get_maxdt(),seq,origin,seq.duration(),tolerance,(verbose & VER_GEN) ? verbose_level : 0);
// propgen.synchronisation_hint(seq.synchronisation_time());
propgen(Udest,t1,t2);
}
ThreadWarning<> phasemodulation_cache_warning("phase modulation: failed to cache all propagators. Increase cache_limit or use verbose -general for more information",&NMRsim_once_warning);
template<class HType> void CompSequenceBase::updatepm_(const HType& H)
{
const int lverbose = (verbose & VER_GEN) ? verbose_level : 0;
const double maxdt=get_maxdt();
if (propgenp.get()) {
const double timeoff=gammatimeoffset();
if (lverbose>1)
std::cout << "PhaseModulation: updating PhaseModulatedPropagator gamma / time offset to " << (timeoff*1e6) << " us\n";
propgenp->Hsys_offset(timeoff);
}
else {
const matrix_partition_set* partp=partitioning().empty() ? NMRSIM_NULL : &(partitioning());
propgenp.clear(); // clear old to clear cache
size_t jumpsteps=0;
double tcommon=0.0;
static double lastjumpprint=-1.0;
if (maxjumpdt) {
jumpsteps=int(0.98+H.period()/(2.0*maxjumpdt));
tcommon=(phasemodp->tick()<maxdt) ? phasemodp->tick() : maxdt;
if (lverbose) {
const double jumpprint=0.5e6*H.period();
if (jumpprint!=lastjumpprint) {
std::cout << "PhaseModulation maximum jump time: " << (0.5e6*H.period()/jumpsteps) << " us (" << jumpsteps << " step(s) over rotor period) Cached time: ";
prettyprint_time(tcommon) << '\n';
lastjumpprint=jumpprint;
}
}
}
else {
if (lverbose && (lastjumpprint!=0.0)) {
std::cout << "PhaseModulation maximum jump time: disabled\n";
lastjumpprint=0.0;
}
}
if (lverbose>1)
std::cout << "PhaseModulation: creating new PhaseModulatedPropagator\n";
PhaseModulatedPropagator* newpropgenp = new PhaseModulatedPropagator(H,partp,maxdt,master_time,*phasemodp,gammatimeoffset(),&global_cache,tolerance,lverbose,prop_flags(),jumpsteps,tcommon);
if (!(newpropgenp->cacheok()))
phasemodulation_cache_warning.raise();
propgenp.reset(newpropgenp);
}
}
template<class HType> void MasterObj::spin_propagator_(BlockedMatrix<complex>& Udest, const HType& H, const CompSequenceBase& seq, double t1,double t2,double origin)
{
if (quickphasemod(seq)) {
PhaseModulatedPropagator& propgen(const_cast<CompSequenceBase&>(seq).updatepm(*this));
// set_partitioning(propgen,seq);
propgen(Udest,t1,t2);
}
else
propagator_(Udest,H,seq,t1,t2,origin);
}
template<class HType> void MasterObj::spin_propagator_(BlockedMatrix<complex>& Udest, const HType& H, const Sequence& seq, double t1,double t2,double origin)
{
propagator_(Udest,H,seq,t1,t2,origin);
}
PhaseModulatedPropagator& CompSequenceBase::updatepm(const MasterObj& obj)
{
if (!(obj.isspinningH()))
throw InternalError("updatepm: not spinning Hamiltonian!");
if (obj.Hspinp.iscomplex())
updatepm_(*(obj.Hspinp.get_complex()));
else
updatepm_(*(obj.Hspinp.get_real()));
return *propgenp;
}
template<class SequenceHolder> void MasterObj::propagator(BlockedMatrix<complex>& U,const SequenceHolder& seq, double t1,double t2,double origin)
{
// if ((nchannels==0) && ((hamobjtype!=M_SPIN) || !quickphasemod(seq))) {
if (nchannels==0) {
propagator(U,t1,t2);
return;
}
switch (hamobjtype) {
case M_SPIN:
if (Hspinp.iscomplex())
spin_propagator_(U,*(Hspinp.get_complex()),seq,t1,t2,origin);
else
spin_propagator_(U,*(Hspinp.get_real()),seq,t1,t2,origin);
break;
case M_STATIC:
if (Hstaticp.iscomplex())
propagator_(U,*(Hstaticp.get_complex()),seq,t1,t2,origin);
else
propagator_(U,*(Hstaticp.get_real()),seq,t1,t2,origin);
break;
case M_STATICD:
propagator_(U,*Hstaticdp,seq,t1,t2,origin);
break;
default:
throw Failed("Unsupported combination of Hamiltonian and RF");
}
}
template void MasterObj::propagator(BlockedMatrix<complex>&, const CompSequenceBase&, double t1,double t2,double origin);
template void MasterObj::propagator(BlockedMatrix<complex>&, const Sequence&, double t1,double t2,double origin);
namespace {
std::ostream& printhstate(const hamiltonian_state_t& state, std::ostream& ostr =std::cout)
{
return ostr << "Rotor angle=" << (state*rad_to_deg) << " degrees";
}
}
ThreadWarning<> Ucache_obj::reset_warning("Unable to use previously calculated propagators because requests don't coincide with previous rotor phases / durations. If these are 'near misses' due to rounding errors, try relaxing the rotor phase tolerance (tolerance <value> -phase). Otherwise you may be able to improve efficiency by not re-using the same sequence at different points in the sequence or by changing the gamma angle sampling. Sequence: ",&NMRsim_once_warning);
// NB. don't bother checking whether matrices are used or not
usage_t Ucache_obj::usage() const {
return Ulist.empty() ? usage_t() : usage_t(Ulist.size()*Ulist.front().size(),Type2Type<complex>());
}
// NB. don't bother checking whether matrices are used or not
usage_t Usequentialcache::usage() const {
return Ulist.empty() ? usage_t() : usage_t(Ulist.size()*Ulist.front().size(),Type2Type<complex>());
}
usage_t Udurcache::usage() const {
return U.empty() ? usage_t() : usage_t(U.size(),Type2Type<complex>());
}
// void Ucache_obj::update_time(const MasterObj& obj, double t, double dur)
// {
// const bool isverb=(verbose & VER_GEN) && (verbose_level>1);
// const double rphase(get_rotor_phase(t));
// const hamiltonian_state_t newstate(obj.hamiltonian_state());
// if (!(Umap.empty())) {
// if ((fabs(rphase-phase)<1e-8) && (newstate==state) && (fabs(duration-dur)<1e-9)) {
// if (isverb)
// std::cout << "Re-using cached propagator\n";
// return;
// }
// if (isverb) {
// std::cout << "Clearing MAS propagator cache for rotor phase=" << rphase << " degrees, ";
// printhstate(obj.hamiltonian_state()) << " Duration: ";
// prettyprint_time(dur) << '\n';
// }
// clear();
// }
// duration=dur;
// state=newstate;
// phase=rphase;
// }
int Ucache_obj::nearest(double rphase) const
{
const size_t n=Ulist.size();
if (n==0)
throw InternalError("Ucache_obj::nearest");
double delta=rphase-phase;
if (delta<0)
delta+=360.0;
size_t ind=0;
if (fabs(delta)>phasetolerance) {
if (n>1) {
const double step=360.0/n;
ind=size_t(delta/step+0.5);
delta-=ind*step;
}
else {
if (delta>180.0)
delta-=360.0;
}
}
return (fabs(delta)>phasetolerance) ? -1 : ind;
}
void Usequentialcache::initialise(const MasterObj& obj, double t, const BlockedMatrix<complex>& U, double durv)
{
phase=get_rotor_phase(t);
state=obj.hamiltonian_state();
Ulist.create(3U);
Ulist.front()=U;
lastn=incr=0;
duration_=durv;
}
bool Usequentialcache::isvalid(const MasterObj& obj, double t, double durv) const
{
if (empty())
return false;
const bool beverb=(verbose & VER_GEN) && (verbose_level>1);
const double rphase(get_rotor_phase(t));
if (fabs(rphase-phase)>phasetolerance) {
if (beverb)
std::cout << "Usequential cache: rejecting cache match because current rotor phase (" << rphase << " doesn't match stored (" << phase << ") within tolerance of " << phasetolerance << "\n";
return false;
}
if (obj.hamiltonian_state()!=state) {
if (beverb)
std::cout << "Usequential cache: rejecting cache match because Hamiltonian states differ\n";
return false;
}
if (fabs(durv-duration_)>tolerance) {
if (beverb)
std::cout << "Usequential cache: rejecting cache match because periods don't match\n";
return false;
}
return true;
}
const BlockedMatrix<complex>* Usequentialcache::rawfind(size_t n) const
{
if (empty())
throw Failed("Usequentialcache used before initialisation");
if (n==0)
throw InvalidParameter("Usequentialcache::find");
if (n==1)
return &(Ulist.front());
if (n==lastn)
return &(Ulist(1U));
if (n==incr)
return &(Ulist(2U));
return NMRSIM_NULL;
}
const BlockedMatrix<complex>* Udurcache::operator()(const MasterObj& obj, double t, double dur) const
{
if (empty())
return NMRSIM_NULL;
const bool beverb=(verbose & VER_GEN) && (verbose_level>1);
if (fabs(dur-duration)>tolerance) {
if (beverb)
std::cout << "Uduration cache: rejecting cache match because durations differ\n";
return NMRSIM_NULL;
}
const double rphase(get_rotor_phase(t));
if (fabs(rphase-phase)>phasetolerance) {
if (beverb)
std::cout << "Uduration cache: rejecting cache match because rotor phase doesn't match\n";
return NMRSIM_NULL;
}
if (obj.hamiltonian_state()!=state) {
if (beverb)
std::cout << "Uduration cache: rejecting cache match because Hamiltonian states differ\n";
return NMRSIM_NULL;
}
return &U;
}
void Udurcache::store(const BlockedMatrix<complex>& Ulast, const MasterObj& obj, double t, double dur)
{
state=obj.hamiltonian_state();
phase=get_rotor_phase(t);
duration=dur;
U=Ulast;
}
// const BlockedMatrix<complex>* Usequentialcache::find(const MasterObj& obj, double t, size_t n, double dur) const
// {
// if (!isvalid(obj,t,dur))
// return NMRSIM_NULL;
// return rawfind(n);
// }
ThreadWarning<> Usequentialcache::ordering_warning("could not optimise re-use of propagators (smartprop) as not used in increasing order",&NMRsim_once_warning);
ThreadWarning<> Usequentialcache::irregular_warning("could not optimise re-use of propagators (smartprop) as not regularly incremented",&NMRsim_once_warning);
const BlockedMatrix<complex>& Usequentialcache::operator()(const MasterObj& obj, double t, size_t n, double durv)
{
if (!nochecks && !isvalid(obj,t,durv))
throw Failed("Usequentialcache used improperly");
const BlockedMatrix<complex>* Up(rawfind(n));
if (Up)
return *Up;
if ((lastn==0) || (n<lastn)) {
if (n<lastn)
ordering_warning.raise();
pow(Ulist(1U),Ulist.front(),n);
}
else {
BlockedMatrix<complex> U;
const size_t delt=n-lastn;
if (delt==1)
multiply(U,Ulist.front(),Ulist(1U));
else {
if (delt==lastn) {
Ulist(2U)=Ulist(1U);
incr=delt;
}
else {
if (delt!=incr) {
if (incr)
irregular_warning.raise();
pow(Ulist(2U),Ulist.front(),delt);
incr=delt;
}
}
multiply(U,Ulist(2U),Ulist(1U));
}
Ulist(1U).swap(U);
}
lastn=n;
return Ulist(1U);
}
BlockedMatrix<complex>& Ucache_obj::operator()(const CompSequenceBase& seq, const MasterObj& obj, double t, double dur)
{
const int lverb=(verbose & VER_GEN) ? verbose_level : 0;
if ((spin_rate==0) || (dur==0.0)) {
Ulist.create(1U);
if ((phase>=0.0) || duration)
Ulist.front().clear(); //!< empty any object
phase=-1.0; //!< flag not spinning
duration=0.0;
return Ulist.front();
}
const double rphase(get_rotor_phase(t));
const hamiltonian_state_t newstate(obj.hamiltonian_state());
if (!(Ulist.empty())) {
if ((newstate==state) && (fabs(duration-dur)<1e-9)) {
const int ind=nearest(rphase);
if (ind>=0) {
if (lverb>1)
std::cout << "Found cache match at index " << (ind+1) << '\n';
return Ulist(size_t(ind));
}
}
if (lverb) {
std::cout << "Clearing MAS propagator cache for rotor phase=" << rphase << " degrees, ";
printhstate(obj.hamiltonian_state()) << " Duration: ";
prettyprint_time(dur) << '\n';
}
clear();
reset_warning.raise(seq.name());
}
size_t nsteps=1;
if (seq.synchint)
nsteps=seq.synchint;
else {
const double rotor_period=1.0/spin_rate;
if (dur>rotor_period)
seq.verbose_check_sync(dur,"propagator duration",rotor_period,"rotor period");
else {
const size_t nsync=seq.verbose_check_sync(1.0/spin_rate,"rotor period",dur,"propagator duration");
if (nsync)
nsteps=nsync;
else {
if (!(seq.donesyncwarn) && syncfailed_warning.enabled()) {
seq.donesyncwarn=true;
std::cerr << "If appropriate, supply synchronisation hint in store for sequence: " << seq.name() << '\n';
}
}
}
}
Ulist.create(nsteps);
size_t offset=0U;
phase=rphase;
if (nsteps>1) {
const double step=360.0/nsteps;
offset=size_t(rphase/step);
if (offset)
phase-=offset*step;
}
if (lverb)
std::cout << "Built MAS propagator cache with " << nsteps << " step(s) and initial rotor phase " << phase << " degrees\n";
duration=dur;
state=newstate;
return Ulist(offset);
}
BlockedMatrix<complex> Utmp;
ThreadWarning<> transients_problem_warning("trailing transients and non-zero sequence phase shift detected!",&NMRsim_repeat_warning);
ThreadWarning<> null_sequence_warning("sequence doesn't seem to do anything: ",&NMRsim_once_warning);
CompSequenceBase::CompSequenceBase()
: synctime(0.0),
partition_index(-1),
synchint(0),
donesyncwarn(false),
status_(DIRTY_ALL),
lastusedmult(0)
{}
BlockedMatrix<complex>& CompSequenceBase::evaluate(MasterObj* objp, double t, double dur, bool disablecache, double phase, double offset) const
{
if (status_!=DIRTY_CLEAN)
throw InternalError("CompSequenceBase::evaluate called before sequence rebuilt");
//if static, use global store, otherwise use object store
BlockedMatrix<complex>* Up=NMRSIM_NULL;
bool transproblem=transients_active();
if (!optcache || transproblem || disablecache || offset)
Up=&Utmp;
else {
Up=&(Ucache(*this,*objp,t,dur));
if (!!(*Up))
optcache.setusage(true);
}
const int lverbose = (verbose & VER_GEN) ? verbose_level : 0;
if ((Up==&Utmp) || !(*Up)) {
if (lverbose) {
std::cout << "Evaluating propagator for " << name_;
if (dur) {
std::cout << " from t=";
prettyprint_interval(t,t+dur);
if (offset)
std::cout << " (offset into sequence " << (offset*1e6) << " us)";
}
else {
std::cout << " at t=";
prettyprint_time(t);
}
std::cout << '\n';
}
objp->propagator(*Up,*this,t,t+dur,t-offset);
if (lverbose>1)
std::cout << (*Up);
if (!transproblem && transients_active())
transproblem=true;
if (transproblem && phase)
transients_problem_warning.raise();
if (!(*Up) && !doneerror) {
null_sequence_warning.raise(name(),true);
doneerror=true; //!< implemented per sequence
}
if (transproblem && (Up!=&Utmp)) { //prevent cacheing
Utmp=*Up;
Up->clear();
Up=&Utmp;
}
if (lverbose)
std::cout << "Caching resulting propagator: " << ((Up==&Utmp) ? "No\n" : "Yes\n");
}
else {
if (lverbose) {
std::cout << "Using cached propagator for " << name_ << " at t=";
prettyprint_time(t) << '\n';
}
}
if (phase) {
Utmp=*Up;
Up=&Utmp;
(*zshift_cachep)(Utmp,deg_to_rad*phase); //don't modify cached value
}
return *Up;
}
const BlockedMatrix<complex>& PhasedSequence::evaluate(MasterObj* objp, double t, double dur, bool disablecache, double offset) const
{
const BlockedMatrix<complex>& U(seq.evaluate(objp,t,dur,disablecache,phase,offset));
const int lverbose = (verbose & VER_GEN) ? verbose_level : 0;
if (lverbose) {
std::cout << "Phase shift: " << phase << "\n";
if (phase && (lverbose>1))
std::cout << U;
}
return U;
}
LIST<CycledSequence*> cycledseqlist; //!< list of all cycled sequences
seqmap_type seqmap;
CompSequenceBase* acqseqp=NMRSIM_NULL;
cycledseqmap_type cycledseqmap;
static CompSequenceBase* CurSeqp=NMRSIM_NULL; //!< sequence under construction
//! reset current sequence to empty state
void reset_sequence()
{
CurSeqp=NMRSIM_NULL;
curchannel=0; // revert to synchronous
usedchannels=0U;
}
//! ensure we have a current sequence
void ensure_sequence()
{
if (!CurSeqp)
CurSeqp=new SyncSequence();
}
void
CompSequenceBase::set(double v, subsid_t subsid)
{
switch (subsid) {
case S_ARG1:
if (v<0.0)
error_abort("synchronisation time can't be <0");
synctime=v*1e-6;
break;
case S_ARG2:
if (v<0.0)
error_abort("synchronisation hint can't be <0");
synchint=round_int(v);
break;
default:
throw InternalError("CompSequenceBase::set");
}
}
/** \c Failed exception if object is dirty */
double CompSequenceBase::duration() const
{
if (status_>=DIRTY_ALL)
throw Failed("CompSequence: info requested while sequence is in undefined state");
return duration_;
}
double CompSequenceBase::safe_duration()
{
if (status_>=DIRTY_ALL)
refresh();
return duration_;
}
std::ostream& operator<< (std::ostream& ostr, dirty_t status)
{
switch (status) {
case DIRTY_CLEAN:
return ostr << "update not required";
case DIRTY_GAMMA:
return ostr << "gamma angle changed";
case DIRTY_HAMILTONIANRF:
return ostr << "Hamiltonian/RF changed";
case DIRTY_ALL:
return ostr << "needs full rebuild";
}
throw InternalError("dirty_t");
}
void
CompSequenceBase::print(std::ostream& ostr) const
{
ostr << name_ << " (" << status_ << ")\n";
if (status_!=DIRTY_ALL) {
for (size_t chan=0;chan<seqlist.size();chan++) {
if (!(seqlist(chan).empty())) {
if (nchannels>1)
ostr << "Channel " << (chan+1) << '\n';
ostr << seqlist(chan);
}
}
ostr << "Total duration: ";
prettyprint_time(duration_) << '\n';
ostr << "CW: " << (isCW ? "Yes\n" : "No\n");
}
ostr << "Synchronise over: ";
if (synctime)
ostr << (synctime*1e6) << " us\n";
else
ostr << "<unspecified>\n";
if ((verbose & VER_GEN) && (verbose_level>1))
ostr << "Partitioning type: " << partition_index << '\n';
}
void
CompSequenceBase::printvariablename(std::ostream& ostr, subsid_t subsid) const
{
ostr << name_ << "_synctime";
}
void
CompSequenceBase::parse_pulse(EventID::id_t type)
{
if (nchannels==0)
error_abort("can't define pulse sequences without active RF channels (add channels directive to spinsys block)\n");
char *syncp=get_curline();
const bool issync=isspace(syncp[1]) && strchr("|+-",*syncp);
char sync='\0';
if (issync) {
sync=*syncp;
(void)get_token(); //swallow argument
}
switch (type) {
case EventID::automatic:
if (!issync)
error_abort("pulseauto: synchronisation must be one of | + -\n");
break;
case EventID::soft:
if (issync)
error_abort("pulse: synchronisation cannot be specified");
break;
default:
break;
}
push_back(EventID::create(this,type,sync));
}
void EventID::print(std::ostream& ostr) const
{
std::cout << "Duration: ";
if (durs_)
durs_->print(ostr);
else
prettyprint_time(nomdur_);
ostr << ": ";
for (size_t chan=0;chan<events.size();chan++) {
const eventlist_t& evl(events(chan));
if (!evl.empty()) {
if (nchannels>1)
ostr << "Channel " << (chan+1) << ": ";
for (size_t i=0;i<evl.size();i++)
ostr << (*evl(i));
}
}
}
std::ostream& operator<< (std::ostream& ostr, const EventID& a)
{
a.print(ostr);
return ostr;
}
std::ostream& operator<< (std::ostream& ostr, const CompSequenceBase& a)
{
a.print(ostr);
return ostr;
}
int rf_to_subsid(size_t chan, subsid_t subsid)
{
return (subsid<<3)+chan;
}
void subsid_to_rf(size_t& chan, subsid_t& actsubsid, int subsid)
{
chan = subsid & 7;
actsubsid=subsid >> 3;
}
bool RawPulseDef::isconst() const
{
if (rf && !(rf->isconst()))
return false;
if (phase && !(phase->isconst()))
return false;
if (offset && !(offset->isconst()))
return false;
return true;
}
void EventID::ensureevents()
{
if (events.empty()) {
events.create(channels());
buildevents();
}
}
void EventID::init(size_t nchans, size_t chanoff_)
{
chanoff=chanoff_;
if ((nchans>1) && chanoff_)
throw InternalError("EventID::init");
pulses.create(nchans);
}
void EventID::set(double fval_int, size_t chan, subsid_t subsid)
{
if (isconst())
error_abort("attempt to change const EventID");
if (events.empty())
return;
eventlist_t& curlist(events(chan));
const bool doset=(!(curlist.empty()) || (subsid==pulses(chan).master_subsid));
if ((verbose & VER_GEN) && (verbose_level>1))
std::cout << "Waiting for complete event: " << (doset ? "No\n" : "Yes\n");
if (!doset)
return;
if (curlist.empty()) {
buildevents();
if (!checknull(chan))
seqp_->flagdirty(DIRTY_ALL); //!< if changing list size, flag that timing will have changed
return;
}
for (size_t item=curlist.size();item--;) {
RFEvent* eventp(curlist(item).get());
switch (subsid) {
case S_RF:
dynamic_cast<RFPulseEvent*>(eventp)->rf(fval_int);
break;
case S_PHASE:
dynamic_cast<RFPulseEvent*>(eventp)->phase(fval_int);
break;
case S_OFFSET:
eventp->offset(convertoffset(fval_int));
break;
default:
throw InternalError("EventID::set");
}
}
seqp_->flagdirty(DIRTY_HAMILTONIANRF);
}
ThreadWarning<> emptypulseevent_warning("setting RF parameter for empty pulse event in sequence: ",&NMRsim_once_warning);
bool EventID::checknull(size_t chan)
{
const eventlist_t& curlist(events(chan));
if (curlist.empty()) {
emptypulseevent_warning.raise(seqp_->name());
return true;
}
return false;
}
ThreadWarning<> EventID::resizelist_warning("Changing number of elements in a multi-step pulse. This may be inefficient compared to keeping a fixed number of steps, particularly for simple phase-modulated sequences.", &NMRsim_once_warning);
void EventID::set(const BaseList<double>& fval_int, size_t chan, subsid_t subsid)
{
if (isconst())
error_abort("attempt to change const EventID");
if (events.empty())
return;
eventlist_t& curlist(events(chan));
if ((curlist.size()!=fval_int.size()) && !(curlist.empty())) {
resizelist_warning.raise();
curlist.clear();
}
const bool doset=(!(curlist.empty()) || (subsid==pulses(chan).master_subsid));
if ((verbose & VER_GEN) && (verbose_level>1))
std::cout << "Waiting for complete event: " << (doset ? "No\n" : "Yes\n");
if (!doset)
return;
if (curlist.empty()) {
buildevents(); //!< note we are assuming that the list argument has come from the VariableBase objects used to build the events
seqp_->flagdirty(DIRTY_ALL); //!< if changing list size, flag that timing will have changed
return;
}
if (checknull(chan))
return;
const bool issoft(type!=ideal);
for (size_t item=curlist.size();item--;) {
RFEvent* eventp(curlist(item).get());
double val=fval_int(item);
switch (subsid) {
// case S_DUR: