-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNMR_acq.cc
2851 lines (2552 loc) · 90.5 KB
/
NMR_acq.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
/* routines particular to complex simulations */
// first load config for USEMPI
// Set up MPI stuff here to avoid conflicts after using libcmatrix
#include "config.h"
#if defined(HAVE_LIBMKL) && defined(LCM_USE_EXTERNAL)
#include "mkl.h"
#define USEMKL 1
#else
#undef USEMKL
#endif
#include "NMRsim.h"
#ifndef DISABLE_EXEC
#ifdef USEMPI
#include "cmatrix_MPI.h"
#define PARTYPE libcmatrix::MPI_controller
#else
#ifdef HAVE_FORK_CONTROLLER
#include "Fork_controller.h"
#define USE_FORK_CONTROLLER
#define PARTYPE libcmatrix::Fork_controller
#endif
#endif
#endif
#ifdef HAVE_PARSYS
#include "smartptr.h"
libcmatrix::smartptr<PARTYPE,false> parconp;
bool assumeparallel=true; //!< assume parallel computation unless impossible
size_t get_thread_num() {
return !parconp ? 0 : parconp->get_thread_num();
}
#else
size_t get_thread_num() {
return 0;
}
#endif
#include "NMRsim_Process.h"
#include "NMRsim_spinsys.h"
#include "NMRsim_logfile.h"
#include "Action.h"
#include "powder.h"
#include <sstream>
FILE* transitions_fp=NMRSIM_NULL;
const char* lastlogfilename=NMRSIM_NULL;
size_t global_workers=0; // number of *workers* (0 if unset)
Matrix<accumulating_timer<> >* timers_arrayp;
LIST<BaseWarning*> resetwarning_list;
size_t global_np=0; //!< finalise data set size not fixed
LIST<size_t> global_nps;
static bool powder_print=false; //!< if set to true, force print number of powder orientations each time (re-)created
//! cutoff warning trigger (%)
#define CUTOFF_TRIGGER 1.0
std::pair<double,double> actual_swref()
{
return (hist_min==hist_max)
? std::pair<double,double>(sw,0.0)
: std::pair<double,double>(hist_max-hist_min,0.5*(hist_min+hist_max));
}
static DataStore ResultSpec; //!< temporary object used by distributed sums
static DataStore OrientSpec; //!< temporary object used for individual orientation
namespace {
void init_row(DataStore& a)
{
const bool istd=!isfrequency();
if (!isirregular()) {
if (a.empty())
a.create(array_n0,np,complex(0.0));
}
else {
if (a.empty())
a.create(array_n0);
if (a.rows()<=row_index) {
const std::pair<double,double> swref(actual_swref());
a.createrow(np,complex(0.0),processing_state(swref.first,istd,detect_freq,swref.second));
}
else {
if (a.state(row_index).sw!=sw) {
char buf[256];
snprintf(buf,sizeof(buf),": row %lu",(unsigned long)(row_index+1));
changedsw_warning.raise(buf);
}
}
processing_state& cstate(a.state(row_index));
cstate.istimedomain=istd;
}
}
void create_empty(DataStore& a)
{
if (!isirregular()) {
if (np==0)
a.clear();
else
a.create(array_n0,np,complex(0.0));
}
else {
a.clear();
array_iter variter;
while (variter.next())
init_row(a);
}
}
void make_zero(DataStore& Spec)
{
if (Spec.empty())
create_empty(Spec);
else
Spec=complex(0.0);
}
}
enum powder_t { POW_NONE, POW_ZCW, POW_BETA, POW_FILE, POW_ZCW3, POW_ALPHABETA, POW_SPHERICALZCW };
powder_t powder_type=POW_NONE;
char* crystal_filep=NMRSIM_NULL;
void parse_powderquality();
void parse_histogram(int);
void parse_crystal_file();
const BlockedOperator empty_op;
const BlockedOperator* use_detectp=NMRSIM_NULL;
bool detectED=false;
option optgamma("gammacompute");
option optparallel("parallel");
option optED("EDmatching","matching initial density matrix and detect operator");
option optforceeigenbasis("forceeigenbasis","",option::AUTO,option::NOTUSED);
option optforcepointbypoint("forcepointbypoint","",option::AUTO,option::NOTUSED);
//optional_t optlongdtsync;
static const double rad_to_deg=180.0/M_PI;
static const double deg_to_rad=M_PI/180.0;
static const double dotlimit=2.5; //show progress counter if > this time (s)
static const double siglimit=10.0; //show ETA if > this limit (s)
static size_t use_gamma_angles=0; //!< gamma integration steps (0 if not gamma-COMPUTE)
static bool update_gamma=false;
static double detect_period=0.0;
static double restrict_gamma=2*M_PI;
static double globalscale=0.0;
dirty_t update_propagators=DIRTY_ALL; //flag that cached propagators shouldn't be used
size_t orientations=1; //!< if not set, implicitly a single orientation
int orientation=-1;
int nzcw=0;
bool zcwisindex=true; //!< by default always treat as index
range_t rangequal=sphere;
void ensure_basepowder();
bool powder_array=false;
bool powder_reverse=false;
static rmatrix powder_weights;
static int curnzcw=-1;
static int nalpha=1;
//smartptr<PowderMethod> pregammapowdm; //!< powder averaging method before any gamma_angles
smartptr<PowderMethod> powdm; //!< powder averaging method
bool have_orientation=false;
bool process2D=true;
static double gammaX=0.0;
rmatrix vararray;
rmatrix valerrs;
LIST<const char*> varnames;
ThreadWarning<> shortCW("Continuous wave sequence with short duration may lead to inefficiences - consider using effectively infinite duration e.g. 1e6 for sequence: ",&NMRsim_once_warning);
double get_rf_period(const CompSequenceBase* seqp)
{
double rf_period=0.0;
if (seqp) {
rf_period=seqp->duration();
if (seqp->isCW) {
if (detect_period<rf_period+tolerance)
rf_period=detect_period;
else
shortCW.raise(seqp->name(),true);
}
}
return rf_period;
}
void flush_transitionlog()
{
if (transitions_fp && (transitions_fp!=stdout))
fclose(transitions_fp);
}
void ensure_vararray()
{
if (!!vararray)
return;
ensure_array(); //!< can be called twice
if (array_n0>1) {
size_t usevars=varpars.size();
if (powder_array)
usevars+=3;
if (usevars) {//NB array parameters within sum are not included
vararray.create(array_n0,usevars,0.0);
varnames.create(usevars);
size_t i=0;
for (;i<varpars.size();i++)
varnames(i)=varpars(i).name();
if (powder_array) {
varnames(i++)="alpha";
varnames(i++)="beta";
varnames(i)="gamma";
}
}
}
}
void save_parameters()
{
ensure_vararray();
if (!(vararray.empty())) {
if (row_index>=vararray.rows())
throw BadIndex("save_parameters",row_index,vararray.rows());
get_variables(vararray.row(row_index));
}
}
void parse_n(int);
struct SysVar_histogram : public SystemVariable<double*> {
SysVar_histogram(const std::string& name_, double* value_)
: SystemVariable<double*>(name_,value_) {}
void update() { update_lineshapegen(); }
};
static double curscale=0.0; //!< current powder weighting
SystemVariable<double*> v_alpha("alpha",&(global_powder.alpha),rad_to_deg,V_UPDATEINTS | V_POWDERSUMDEP);
SystemVariable<double*> v_beta("beta",&(global_powder.beta),rad_to_deg,V_UPDATEINTS | V_POWDERSUMDEP);
SystemVariable<double*> v_gamma("gamma",&(global_powder.gamma),rad_to_deg,V_UPDATEINTS | V_POWDERSUMDEP);
SystemVariable<double*> v_weight("weight_orientation",&curscale,1.0,V_ISFIXED | V_POWDERSUMDEP);
SysVar_histogram v_histlw("histogram_linewidth",&hist_lw);
SysVar_histogram v_histgfrac("histogram_gaussianfraction",&hist_gfrac);
SystemVariable<int*> v_powderquality("powderquality",&nzcw,V_ISFIXED | V_ISCONST);
SystemVariable<int*> v_orientation("i_orientation",&orientation,V_ISFIXED | V_POWDERSUMDEP);
//SystemVariable<int*> v_var_index("i_array",&var_index,true,false);
//SystemVariable<int*> v_row_index("i_row",&row_index,true,false);
complex single_point(const BlockedOperator& sigma)
{
return (!detect || detectED) ? NMR_trace(sigma) : NMR_trace(detect,sigma);
}
static PowderMethod::include_t offsetqual=PowderMethod::middle;
bool havepowderquality() { return (nzcw>=2); }
enum { CRYS_SPHERE =1, //!< complete sphere
CRYS_HEMISPHERE =2, //!< hemisphere
CRYS_OCTANT =4, //!< octant
CRYS_PRINT =128, //!< verbose
CRYS_START =256, //!< include pole
CRYS_END =512, //!< include max beta angle
CRYS_MIDDLE =1024, //!< between limits
CRYS_BOTH =2048, //!< include both limits
CRYS_REVERSE =8192 //!< reverse order
};
bool ammaster=true;
ThreadWarning<> parfailed_warning("Not using parallelisation as fewer summation steps than processors",&NMRsim_once_warning);
ThreadWarning<> parnone_warning("Ignoring -enable:parallel as no parallelisation mechanism enabled at compile time",&NMRsim_once_warning);
ThreadWarning<> npfailed_warning("Cannot determine number of processor cores - use NMRSIM_NUM_CORES environment to set explicitly",&NMRsim_once_warning);
ThreadWarning<> numcoreslarge_warning("Number of threads set using NMRSIM_NUM_CORES exceeds number of (online) processor cores",&NMRsim_once_warning);
bool cleanup_parallel()
{
#ifdef USE_FORK_CONTROLLER
if (!!parconp) {
try {
parconp->join_kill();
} catch (...) { //!< don't allow exceptions to leak
return false;
}
}
#endif
return true;
}
void init_parallel(int& argc, char**& argv)
{
if (!optparallel)
return;
#if (defined(USEMPI) || defined(HAVE_FORK_CONTROLLER)) && defined(USEMKL)
mkl_set_num_threads(1); //!< disable MKL threading to prevent oversubscription
#endif
const int lverbose=(verbose & (VER_POWDER | VER_PARALLEL)) ? verbose_level : 0;
#ifdef USEMPI
parconp.reset(new MPI_controller(argc,argv,lverbose));
global_workers=parconp->get_workers();
optparallel.setusage(true);
#else
#ifdef USE_FORK_CONTROLLER
size_t nproc=0;
const char* envval=register_and_getenv("NMRSIM_NUM_CORES");
if (envval) {
nproc=parse_counting(envval);
if (nproc==0)
error_abort("NMRSIM_NUM_CORES does not evaluate to a valid number of processors");
}
else {
if (optparallel.isauto())
assumeparallel=false; //!< don't assume parallel mode
else {
if (optparallel.isenabled() && lverbose)
std::cout << "NMRSIM_NUM_CORES unset and so defaulting to using all available processor cores\n";
}
}
#ifdef _SC_NPROCESSORS_ONLN
const size_t nonln=sysconf(_SC_NPROCESSORS_ONLN);
if (nproc) {
if (!nochecks && (nproc>nonln))
numcoreslarge_warning.raise();
}
else {
if (assumeparallel)
nproc=nonln;
}
if (nproc)
parconp.reset(new Fork_controller(nproc,lverbose));
#endif
global_workers=nproc;
optparallel.setusage(global_workers!=0);
if (global_workers==0) {
if (optparallel.isenabled())
npfailed_warning.raise();
return;
}
#else
optparallel.setusage(false);
if (optparallel.isenabled())
parnone_warning.raise();
return;
#endif
#endif
}
void ensure_parallel()
{
static bool done_parallel_init=false;
if (done_parallel_init)
return;
done_parallel_init=true;
#ifdef HAVE_PARSYS
if (!parconp)
throw InternalError("ensure_parallel");
ammaster=parconp->ammaster();
// disablelogging=!ammaster;
if (!silent && ammaster)
std::cout << "Starting parallel system with " << global_workers << " workers." << (optparallel.isauto() ? " Disable parallel execution with -disable:parallel\n" : "\n");
// else {
// parfailed_warning.raise();
// parconp.clear();
// }
#else
throw InternalError("ensure_parallel");
#endif
}
std::ostream& parser_printthread(std::ostream& ostr)
{
#ifdef HAVE_PARSYS
#ifdef USE_FORK_CONTROLLER
static const int offset=1;
#else
static const int offset=0; //!< don't shift as master process is 0 and workers are numbered from 1
#endif
if (!!parconp)
ostr << 'T' << (offset+parconp->get_thread_num()) << ": ";
#endif
return ostr;
}
static void make_nD_par_variables()
{
add_systemvarmap(v_ni);
add_systemvarmap(v_sw1);
command_Factory_t& par_Factory(get_par_Factory());
char vname[6];
for (size_t i=1;i<=MAX_DIMENSIONS;i++) {
snprintf(vname,sizeof(vname),"n%" LCM_PRI_SIZE_T_MODIFIER "u",i);
par_Factory[vname]=par_t(&parse_n,i,true);
snprintf(vname,sizeof(vname),"sw%" LCM_PRI_SIZE_T_MODIFIER "u",i);
par_Factory[vname]=par_t(&parse_swn,i,true);
}
par_Factory["ni"]=par_t(&parse_n,1,true);
}
void add_reset_warning(BaseWarning& warning)
{
warning.type(BaseWarning::FirstOnly);
resetwarning_list.push_back(&warning);
}
void reset_warnings()
{
for (size_t i=resetwarning_list.size();i--;)
resetwarning_list(i)->reset();
}
static void prepar_callback()
{
add_systemvarmap(v_powderquality);
add_systemvarmap(v_alpha);
add_systemvarmap(v_beta);
add_systemvarmap(v_gamma);
add_systemvarmap(v_weight);
add_systemvarmap(v_orientation);
make_nD_par_variables();
command_Factory_t& par_Factory(get_par_Factory());
par_Factory["powderquality"]=&parse_powderquality;
par_Factory["histogram"]=par_t(&parse_histogram,ACC_FREQ,true);
par_Factory["pseudohistogram"]=par_t(&parse_histogram,ACC_PSEUDO,true);
par_Factory["method"]=par_t(&parse_ignored,true);
par_Factory["crystal_file"]=&parse_crystal_file;
add_flushcallback(flush_transitionlog); //!< flush transition log when calculation terminates
add_reset_warning(chebyshev_convergence_warning);
add_reset_warning(chebyshev_nonunitary_warning);
add_reset_warning(cmatrix_eigensystem_controller.nonorthogonal_warning);
}
namespace {
struct Proxy_ {
Proxy_() {
// optional_map_t& optional_map(get_optional_map());
add_option(optgamma);
add_option(optED);
// optional_map["parallel"]=&optparallel;
add_option(optforceeigenbasis);
// optional_map["longdtsync"]=&optlongdtsync;
add_option(optforcepointbypoint);
addprepar_callback(prepar_callback);
}
};
static Proxy_ proxy;
}
#define NMRSIM_ENABLE_ROMAN
class DotMaker {
public:
DotMaker(double dottimev =dotlimit)
: makedots(dottimev>=0.0), donedots(false), dottime(dottimev), unhandled(0) {}
void flush();
void print();
private:
bool makedots,donedots;
timer<> stopwatch;
double dottime;
size_t unhandled;
size_t basestep;
char basechar;
};
void DotMaker::flush()
{
if (!donedots)
return;
#ifdef NMRSIM_ENABLE_ROMAN
if (unhandled>=500) {
std::cout << 'D';
unhandled-=500;
}
while (unhandled>=100) {
std::cout << 'C';
unhandled-=100;
}
if (unhandled>=50) {
std::cout << 'L';
unhandled-=50;
}
while (unhandled>=10) {
std::cout << 'X';
unhandled-=10;
}
if (unhandled>5) {
std::cout << 'V';
unhandled-=5;
}
for (size_t i=unhandled;i--;)
std::cout << 'I';
#endif
std::cout << '\n';
}
void DotMaker::print()
{
if (!makedots)
return;
if (!donedots) {
const double t=stopwatch();
if (t>dottime) {
donedots=true;
#ifdef NMRSIM_ENABLE_ROMAN
const double rate=unhandled/t;
if (rate>=1000.0) {
basestep=1000;
basechar='M';
}
else {
if (rate>=100.0) {
basestep=100;
basechar='C';
}
else {
if (rate>=10.0) {
basestep=10;
basechar='X';
}
else {
basestep=1;
basechar='I';
}
}
}
#else
basechar='.';
basestep=1;
#endif
while (unhandled>=basestep) {
std::cout << basechar;
unhandled-=basestep;
}
std::cout.flush();
}
else
unhandled++;
}
else {
unhandled++;
if (unhandled==basestep) {
std::cout << basechar;
std::cout.flush();
unhandled-=basestep;
}
}
}
static void set_orientation(Euler& powder, double& scale, size_t orient, int locverbose)
{
powder.gamma=gamma_zero;
if (!!powdm) {
if (powder_reverse)
orient = powdm->orientations()-orient-1;
powdm->orientation(powder,scale,orient);
if (scale<0.0) {
parser_printthread(std::cerr) << "Powder orientation " << orient << " returned -ve scale factor: " << powder << ' ' << scale << '\n';
error_abort();
}
if (powdm->angles()==3)
powder.gamma+=gamma_zero; //for 3 angle sets, use gamma_zero as offset
}
orientation=orient; //set global orientation index
if (locverbose & VER_POWDER) {
std::cout << "Orientation: " << powder;
if (verbose_level>1)
std::cout << " (" << scale << ')';
std::cout << std::endl;
}
global_powder=powder;
}
size_t nobs=0;
double hist_include_threshold=0.0;
double hist_log_threshold=0.0;
void parse_histogram_range()
{
// if (hist_flags & HIST_RANGE) {
hist_min=parse_double();
hist_max=parse_double();
if (hist_min==hist_max)
error_abort("Bad histogram range: histogram -range <min> <max>");
if (hist_min>hist_max)
::std::swap(hist_min,hist_max);
}
ContextWarning<> doubleascii_warning("-double has no effect on ASCII output",&NMRsim_once_warning);
ContextWarning<> streamopenfailed_warning("failed to open transitions stream",&NMRsim_repeat_warning);
ContextWarning<> logfileMPI_warning("histogram log_file is not compatible with MPI operation - any file will almost certainly be garbled",&NMRsim_repeat_warning);
void parse_histogram_log_file()
{
#ifdef USEMPI
if (global_workers)
logfileMPI_warning.raise();
#endif
const char* fname=parse_string();
if (parser_isnormal())
hist_log_threshold=parse_double();
static flagsmap_type histflags;
if (histflags.empty()) {
histflags["binary"]=HIST_BINARY;
histflags["double"]=HIST_DOUBLE;
histflags["real"]=HIST_REAL;
histflags["append"]=HIST_APPEND;
}
static const int mask=HIST_BINARY | HIST_DOUBLE | HIST_REAL | HIST_APPEND;
hist_flags=(hist_flags & ~mask) | parse_flags(histflags);
// if ((hist_flags & HIST_BINARY) && !fname)
// parser_printcontext() << "Warning: -binary specified without file\n";
if ((hist_flags & HIST_DOUBLE) && !(hist_flags & HIST_BINARY))
doubleascii_warning.raise();
if (strcmp(fname,"-")==0) {
transitions_fp=stdout;
hist_flags &= ~HIST_BINARY; //ensure ASCII;
}
else {
if (!nochecks)
checklogfile(fname,logfile_active(),hist_flags & HIST_APPEND);
static char openflags[3]={'\0'};
openflags[0]=(hist_flags & HIST_APPEND) ? 'a' : 'w';
openflags[1]=(hist_flags & HIST_BINARY) ? 'b' : '\0';
transitions_fp=fopen(fname,openflags);
if (!transitions_fp)
streamopenfailed_warning.raise();
}
//else {
// if (hist_flags & HIST_REAL)
// parser_printcontext() << "Warning: real flag has no effect without output file\n";
//}
}
bool transitions_log_active() { return (transitions_fp!=NMRSIM_NULL); }
ContextWarning<> excessivecutoff_warning("histogram lineshape cutoff is more than " NMRSIM_STRINGISE(CUTOFF_TRIGGER) "%",&NMRsim_once_warning);
int makeshapeflags(bool dofold)
{
int flags=LineshapeSpec::variable;
if (!dofold)
flags|=LineshapeSpec::nofold;
if ((verbose & VER_GEN) && (verbose_level>1))
flags|=LineshapeSpec::verbose;
return flags;
}
void parse_histogram_lineshape()
{
if (acc_mode!=ACC_FREQ)
error_abort("can only specify lineshape in histogram mode (use addlb for time-domain data)");
const char histogram_lineshape_syntax[]="histogram lineshape <linewidth / Hz>#<Guassian fn>#[<lineshape steps>#<cutoff>]";
lineshape_spec.cutoff=NMRSIM_DEFAULT_LINESHAPE_CUTOFF;
lineshape_spec.resolution_steps=NMRSIM_DEFAULT_LINESHAPE_STEPS;
lineshape_spec.cache_maximum= !optcache ? 0 : NMRSIM_DEFAULT_LINESHAPES_CACHE;
parse_system_variable_syntax(histogram_lineshape_syntax,1,v_histlw);
if (are_left()) {
parse_system_variable_syntax(histogram_lineshape_syntax,2,v_histgfrac);
if (are_left()) {
lineshape_spec.resolution_steps=parse_unsigned_syntax(histogram_lineshape_syntax,3);
if (lineshape_spec.resolution_steps==0)
error_abort("histogram steps must be >0");
lineshape_spec.cutoff=parse_double_syntax(histogram_lineshape_syntax,4);
if ((lineshape_spec.cutoff>=1.0) || (lineshape_spec.cutoff<0.0))
error_abort("histogram lineshape cutoff must be >=0 and <1");
if (lineshape_spec.cutoff>=0.01*CUTOFF_TRIGGER)
excessivecutoff_warning.raise();
}
}
lineshape_spec.flags=makeshapeflags(hist_flags & HIST_FOLD);
update_lineshapegen();
}
void parse_histogram_flags()
{
if (parser_isnormal())
hist_include_threshold=parse_double();
static flagsmap_type histflags;
if (histflags.empty()) {
// histflags["binary"]=HIST_BINARY;
//histflags["interpolate"]=HIST_INTERP;
//histflags["double"]=HIST_DOUBLE;
histflags["fold"]=HIST_FOLD;
//histflags["real"]=HIST_REAL;
//histflags["range"]=HIST_RANGE;
}
static const int mask=HIST_FOLD;
if (are_left()) {
if (lineshape_genp)
error_abort("can't change flags after histogram lineshape"); //!< fold flag is needed when generator created
hist_flags=(hist_flags & ~mask) | parse_flags(histflags);
}
// if ((hist_flags & HIST_BINARY) && !fname)
// parser_printcontext() << "Warning: -binary specified without file\n";
// if ((hist_flags & HIST_DOUBLE) && !(hist_flags & HIST_BINARY))
// parser_printcontext() << "Warning: -double has no effect on ASCII output\n";
// if (fname) {
// if (strcmp(fname,"-")==0) {
// transitions_fp=stdout;
// hist_flags &= ~HIST_BINARY; //ensure ASCII;
// }
// else {
// transitions_fp=fopen(fname,(hist_flags & HIST_BINARY) ? "wb" : "w");
// if (!transitions_fp)
// parser_printcontext() << "Warning: failed to open transitions stream\n";
// }
// }
// else {
// if (hist_flags & HIST_REAL)
// parser_printcontext() << "Warning: real flag has no effect without output file\n";
// }
// }
// }
}
//command_Factory_t& get_histogram_Factory()
//{
// return histogram_Factory;
//}
void parse_histogram(int newm)
{
const acc_t newaccm=static_cast<acc_t>(newm);
if (acc_mode==ACC_TIME)
acc_mode=newaccm;
else {
if (acc_mode!=newaccm)
error_abort("can't switch between acquisition modes");
}
//command_Factory_t& histogram_Factory(get_histogram_Factory());
//static bool doneadd=false;
static command_Factory_t histogram_Factory;
if (histogram_Factory.empty()) {
histogram_Factory["range"]=&parse_histogram_range;
histogram_Factory["log_file"]=&parse_histogram_log_file;
histogram_Factory["lineshape"]=&parse_histogram_lineshape;
}
if (are_left()) {
const char* keyname=parse_string(F_IGNORESYNTAX);
// const command_Factory_t::iterator iter(histogram_Factory.find(keyname));
// if (iter!=histogram_Factory.end()) {
// (iter->second)();
// return;
// }
(factory_parse(keyname,histogram_Factory))();
return;
}
parse_histogram_flags();
}
template<class T> void write_binary(const complex& amp, double freq)
{
T binvals[3];
if (hist_flags & HIST_REAL) {
binvals[0]=real(amp);
binvals[1]=freq;
fwrite(binvals,sizeof(T),2,transitions_fp);
}
else {
binvals[0]=real(amp);
binvals[1]=imag(amp);
binvals[2]=freq;
fwrite(binvals,sizeof(T),3,transitions_fp);
}
}
void raw_write_transitions(const complex& amp, double freq)
{
if (hist_flags & HIST_BINARY) {
if (hist_flags & HIST_DOUBLE)
write_binary<double>(amp,freq);
else
write_binary<float>(amp,freq);
}
else {
if (hist_flags & HIST_REAL)
fprintf(transitions_fp,"%g %g\n",real(amp),freq);
else
fprintf(transitions_fp,"%g %g %g\n",real(amp),imag(amp),freq);
}
}
void add_transition(BaseHistogram<complex>& hist,const complex& amp, double freq)
{
// if (verbose_level>1)
// std::cout << "Adding " << amp << " of " << freq << '\n';
static const double threshold2=hist_include_threshold*hist_include_threshold;
if (norm(amp)<threshold2)
return;
if (acc_mode==ACC_PSEUDO) {
if (sw==0.0)
throw InternalError("add_transition");
const BaseList<complex> data(hist.row());
add_FID(data,amp,-freq/sw); //!< flip sign for consistency between pseudohist & TD
}
else
hist.add(amp,freq);
static const double logthreshold2=hist_log_threshold*hist_log_threshold;
if (transitions_fp && (norm(amp)>=logthreshold2)) {
if (hist_flags & HIST_FOLD) {
const double minf=hist.minimum();
freq=minf+mod(freq-minf,hist.range());
}
if ((hist_max==hist_min) || ((freq<=hist_max) && (freq>=hist_min))) {
#ifdef USE_FORK_CONTROLLER
if (global_workers) {
static Mutex<> lock;
MutexLock<> guard(lock);
raw_write_transitions(amp,freq);
}
else
#endif
raw_write_transitions(amp,freq);
}
}
}
template<typename T> void add_spectrum_(BaseHistogram<complex>& hist, const complex& scale, SpectrumIterator<T>& Obj, double fold_sw =0.0)
{
const double fold_sw2=fold_sw/2.0;
const bool check_fold(fold_sw>=0.0);
T amp;
double freq;
while (Obj(amp,freq)) {
if (check_fold) {
if (freq>=fold_sw2) //fold frequencies into +/- fold_sw/2
freq-=fold_sw;
else {
if (freq<-fold_sw2)
freq+=fold_sw;
}
}
//if (isreal)
// add_transition(hist,amp*rscale,freq);
//else
add_transition(hist,amp*scale,freq);
}
}
template<typename F> void add_spectrum(BaseHistogram<complex>& hist, const complex& scale, F& Obj, double fold_sw =0.0)
{
if (eigenvalue!=NMRSIM_INVALID)
Obj.eigenvalue(eigenvalue);
add_spectrum_(hist,scale,Obj,fold_sw);
}
template<class Obj,class Ugen> void add_metaspectrum(BaseHistogram<complex>& hist, const complex& scale, double fold_sw,Obj& obj, const Ugen& propgen, size_t npts, double t1, double t2, const BlockedOperator& ldensity, const BlockedOperator& ldetect, int lverbose)
{
if (sideband!=NMRSIM_INVALID)
obj.sideband(sideband);
RawMetaSpectrum<Ugen,Obj,BlockedOperator> mobj(obj,propgen,npts,t1,t2,ldensity,ldetect,lverbose);
add_spectrum(hist,scale,mobj,fold_sw);
}
ThreadWarning<> ignoringsideband_warning("sideband ignored in static/time-domain simulation",&NMRsim_once_warning);
template<class Obj,class Ugen> void add_metaspectrum(BaseHistogram<complex>& hist, const complex& scale, Obj& obj, const Ugen& propgen, double deltat, const BlockedOperator& ldensity, const BlockedOperator& ldetect, int lverbose)
{
if (sideband!=NMRSIM_INVALID)
ignoringsideband_warning.raise();
RawMetaSpectrum<Ugen,Obj,BlockedOperator> mobj(obj,propgen,1,master_time,master_time+deltat,ldensity,ldetect,lverbose);
add_spectrum(hist,scale,mobj);
}
namespace {
template<class Holder,class T> void ensureobj_(Holder& holder,size_t,Type2Type<T>,Bool2Type<false>)
{
holder.set(Type2Type< smartptr<T,false> >()).reset(new T((verbose & VER_GEN) ? verbose_level : 0));
}
template<class Holder,class T> void ensureobj_(Holder& holder,size_t lnobs,Type2Type<T>,Bool2Type<true>)
{
holder.set(Type2Type< smartptr<T,false> >()).reset(new T(lnobs,(verbose & VER_GEN) ? verbose_level : 0));
}
template<class T> bool matchobs(const T& obj,Bool2Type<true>) { return (obj.observations()==nobs); }
template<class T> bool matchobs(const T&, Bool2Type<false>) { return true; }
}
void checkED()
{
const bool ison=optED();
if (ison) {
density.makeidentitycache();
if (use_detectp)
use_detectp->makeidentitycache();
}
if ((verbose & VER_GEN) && (verbose_level>1))
std::cout << "Checking for sigma0/detect matching identity operator: " << (ison ? "Yes\n" : "No\n");
}
template<class T> T& MasterObj::ensuretobj()
{
typedef Type2Type< smartptr<T,false> > switch_type;
if (!(objholder.istype(switch_type())) || !matchobs(*(objholder.get(switch_type())),Bool2Type<SignalGenerator_traits<T>::gamma>()) )
ensureobj_(objholder,nobs,Type2Type<T>(),Bool2Type<SignalGenerator_traits<T>::gamma>());
use_detectp = (detectED & SignalGenerator_traits<T>::allowED) ? &empty_op : &detect;
checkED();
return *(objholder.get(switch_type()));
}
template<class PropGen> void MasterObj::add_freq(BaseHistogram<complex>& hist, complex scale, PropGen& propgen)
{
const int lverbose = (verbose & VER_GEN) ? verbose_level : 0;
const double fold_sw=nobs/detect_period;
if (use_gamma_angles) {
if (detectED)
add_metaspectrum(hist,scale,fold_sw,ensurefobj<GammaPeriodicSpectrumED>(),propgen,use_gamma_angles,master_time,master_time+detect_period,density,empty_op,lverbose);
else
add_metaspectrum(hist,scale,fold_sw,ensurefobj<GammaPeriodicSpectrum>(),propgen,use_gamma_angles,master_time,master_time+detect_period,density,detect,lverbose);
}
else
add_metaspectrum(hist,scale,fold_sw,ensurefobj<PeriodicSpectrum>(),propgen,nobs,master_time,master_time+detect_period,density,detect,lverbose);
}
template<class StaticObj,class SpinObj> void MasterObj::add_freq(BaseHistogram<complex>& hist, complex scale, const StaticObj& Hstaticp, const SpinObj& Hspinp, const ActionDirectAcq& acq)
{
// assert(acqp!=NMRSIM_NULL);
const CompSequenceBase* acqseqp = acq.sequence();
if (Hempty() && !acqseqp) {
const complex val=scale*single_point(density);
add_transition(hist,val,0.0);
return;
}
const bool point_by_point=acq.ispoint_by_point();
if (point_by_point || !detect_period || !nobs)
throw InternalError("add_freq");
const double dt=dwelltime();
const int lverbose = (verbose & VER_GEN) ? verbose_level : 0;
const double fold_sw=nobs/detect_period;
// const double act_acq_period=acqseqp ? acqseqp->duration() : 0.0;
const int prop_flags= acqseqp ? acqseqp->prop_flags() : global_prop_flags;
const double rf_period=get_rf_period(acqseqp);
const double maxdt=get_maxdt();
switch (hamobjtype) {
case M_SPIND: {
MetaPropagator propgen(*Hspindp,0.0,lverbose,prop_flags);
set_partitioning(propgen);
if (use_gamma_angles) {
if (detectED)
add_metaspectrum(hist,scale,fold_sw,ensurefobj<GammaInhomogeneousSpectrumED>(),propgen,use_gamma_angles,master_time,master_time+detect_period,density,empty_op,lverbose);
else
add_metaspectrum(hist,scale,fold_sw,ensurefobj<GammaInhomogeneousSpectrum>(),propgen,use_gamma_angles,master_time,master_time+detect_period,density,detect,lverbose);
}
else
add_metaspectrum(hist,scale,fold_sw,ensurefobj<InhomogeneousSpectrum>(),propgen,nobs,master_time,master_time+detect_period,density,detect,lverbose);
break;
}
case M_SPIN:
if (acqseqp) {
if (acqseqp->modulation().get()) {
PhaseModulatedPropagator& propgen(const_cast<CompSequenceBase*>(acqseqp)->updatepm(*this));
add_freq(hist,scale,propgen);
// add_metaspectrum(hist,scale,fold_sw,ensurefobj<PeriodicSpectrum>(),propgen,nobs,master_time,master_time+detect_period,density,detect,lverbose);
}
else {
SequencePropagator propgen(*Hspinp,maxdt,acqseqp->seqlist,master_time,rf_period,tolerance,lverbose,prop_flags);
set_partitioning(propgen,*acqseqp);
propgen.synchronisation_hint(acqseqp->synchronisation_time());
add_freq(hist,scale,propgen);
}
}
else {