forked from CY-Zhang/MultisliceCPP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslicelib.cpp
More file actions
3066 lines (2705 loc) · 106 KB
/
slicelib.cpp
File metadata and controls
3066 lines (2705 loc) · 106 KB
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
/* *** slicelib.c ***
------------------------------------------------------------------------
Copyright 1998-2015 Earl J. Kirkland
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
---------------------- NO WARRANTY ------------------
THIS PROGRAM IS PROVIDED AS-IS WITH ABSOLUTELY NO WARRANTY
OR GUARANTEE OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
IN NO EVENT SHALL THE AUTHOR BE LIABLE
FOR DAMAGES RESULTING FROM THE USE OR INABILITY TO USE THIS
PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA
BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR
THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH
ANY OTHER PROGRAM).
------------------------------------------------------------------------
function library for use with multislice programs
should put each subroutine in a separate file and make
a real obj library but its easier to manage this way
askYN() : ask a yes/no question and return true/false
bessi0() : modified Bessel function I0(x)
bessk0() : modified Bessel function K0(x)
chi() : return aberration function (needs 2pi/wave factor)
cputim() : return current CPU time in sec
featom() : return scattering factor for a given atom
free2D() : free 2D array allocated with malloc2D()
free3D() : free 3D array allocated with malloc3D()
freqn() : calculate spatial frequencies
malloc1D() : allocate memory for 1D arrays
malloc2D() : allocate memory for 2D arrays
malloc3D() : allocate memory for 3D arrays
messageSL() : message handler
parlay() : parse the layer structure
propagate() : propagate a 2D wavefunction
propagateW() : propagate a 2D wavefunction
ranflat() : return a random number with uniform distribution
rangauss() : return a random number with Gaussian distribution
ranPoisson() : return a random number with Poisson distribution
readCnm() : decypher aberr. of the form C34a etc.
ReadfeTable() : read fe scattering factor table
ReadXYZcoord(): read a set of (x,y,z) coordinates from a file
scaleW() : scale a 2D FFTW
seval() : Interpolate from cubic spline coefficients
sigma() : return the interaction parameter
sortByZ() : sort atomic x,y,z coord. by z
splinh() : fit a quasi-Hermite cubic spline
transmit() : transmit a 2D wavefunction
transmitW() : transmit a 2D wavefunction with openMP
vatom() : return real space atomic potential (NOT projected)
vzatom() : return real space projected atomic potential
vzatomLUT() : same as vzatom() but with a look-up-table (faster)
wavelength() : return electron wavelength in A for given keV
this file is formatted for a tab size of 4 characters
started may 1996 E. Kirkland
added askYN() 23-jun-1996 ejk
add scattering factor routines featom, ReadfeTable, ReadLine
seval, spinh 26-july-1996 ejk
move random number generator here 3-aug-1996 ejk
move freqn(), transmitt() and propagate() to here 4-aug-1996 ejk
converted to new 12 parameter fe(k) from mcdf 16-jan-1997 ejk
add bessk0(), bessi0(), vzatom() and wavelength() 18-feb-1997 ejk
update random number generators 20-may-1997 ejk
added more directories to look for "fparams.dat" 5-july-1997 ejk
added vatom() and changed constants in vxatom() in about
5th sig. fig. 24-nov-1997 ejk
added sigma() 30-nov-1997 ejk
change min Z to 1 for hydrogen 15-dec-1997 ejk
fixed possible log(0) problem in rangaus() 10-jan-1998 ejk
moved seval(), splinh() and ReadXYZcoord()
into this library 11-jan-1998 ejk
switched scattering factors to hardcoded table
so you don't have to worry about an external data
file (and also so it can't be changed accidentily)
21-jan-199 ejk
add nowarranty() 27-jan-1999 ejk
put in new scattering factor parameters 9-oct-1999 ejk
move malloc1D() and malloc2D() to here 6-nov-1999 ejk
rearrange nowarranty 22-jan-2000 ejk
add malloc3D(), free2D() and free3D() 20-jul-2005 ejk
move sortbyz() to here, and add short nowaranty 23-aug-2006 ejk
remove nowarranty() subroutine from this file 11-jul-2007 ejk
fix a few small issues (scanf field width etc.) 16-mar-2008 ejk
convert format to 4 char TAB size and add vzatomLUT() 11-jun-2008 ejk
convert freqn() for use with n not a power of 2 on 21-feb-2010
add subroutines for use with FFTW 18-mar-2010 ejk
put conditional compilation around FFTW portion and add parameter
offsets for multipole aberrations 12-apr-2011 ejk
add readCnm() and chi() and ns to askYN() 8-may-2011 ejk
fix error in C12a,b= astigmatism calculation 4-jul-2012 ejk
add messageSL() and convert all printf output to go thru it
for redirections under a GUI 14-apr-2013
convert char[] and sprintf() to std::string and
add 3 versions of toString() 24-nov-2013 ejk
change printfOK to USE_TERMINAL and
start conversion to streams 10-mar-2014 ejk
remove ReadLine() and use C++ getline() 4-apr-2014 ejk
add ranPoisson() 27-sep-2015 ejk
*/
#include <stdio.h> /* ANSI C libraries */
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <ctype.h>
#include <cmath>
#include <time.h>
#include <string>
#include <iostream>
#include <sstream> // string streams
#include <fstream> // STD file IO streams
#include <vector> // STD vector class
using namespace std;
/*#include <omp.h> for openMP testing */
// define the following symbol to enable bound checking
// define for debugging, and undefine for final run
//#define CFPIX_BOUNDS_CHECK
#include "cfpix.hpp" /* complex image handler with FFT */
#include "slicelib.hpp" /* verify consistency and use some routines */
//#define wxGUI // set for wxWidgets graphical user interface
#ifdef wxGUI
#include "wx/wx.h" // regular headers
//#include "wx/wxprec.h" // for precompiled headers
#endif
// for the atomic scattering factor tables
const int NPMAX= 12; // number of parameters for each Z
const int NZMIN= 1; // min Z in featom.tab
const int NZMAX= 103; // max Z in featom.tab
int feTableRead=0; // flag to remember if the param file has been read
double **fparams; // to get fe(k) parameters
const int nl=3, ng=3; // number of Lorenzians and Gaussians
/*--------------------- askYN() -----------------------------------*/
/*
ask a yes/no question and return 1 or 0 for TRUE/FALSE
message[] = question to ask
*/
#ifdef USE_TERMINAL
int askYN( const char message[] )
{
string cline;
cout << message << " (y/n) :" << endl;
cin >> cline;
if( (cline.compare("Y")==0) || (cline.compare("y")==0) ||
(cline.compare("1")==0) ) return( 1 ); else return( 0 );
} /* end askYN() */
#endif
/*-------------------- bessi0() ---------------*/
/*
modified Bessel function I0(x)
see Abramowitz and Stegun page 379
x = (double) real arguments
12-feb-1997 E. Kirkland
*/
double bessi0( double x )
{
int i;
double ax, sum, t;
double i0a[] = { 1.0, 3.5156229, 3.0899424, 1.2067492,
0.2659732, 0.0360768, 0.0045813 };
double i0b[] = { 0.39894228, 0.01328592, 0.00225319,
-0.00157565, 0.00916281, -0.02057706, 0.02635537,
-0.01647633, 0.00392377};
ax = fabs( x );
if( ax <= 3.75 ) {
t = x / 3.75;
t = t * t;
sum = i0a[6];
for( i=5; i>=0; i--) sum = sum*t + i0a[i];
} else {
t = 3.75 / ax;
sum = i0b[8];
for( i=7; i>=0; i--) sum = sum*t + i0b[i];
sum = exp( ax ) * sum / sqrt( ax );
}
return( sum );
} /* end bessi0() */
/*-------------------- bessk0() ---------------*/
/*
modified Bessel function K0(x)
see Abramowitz and Stegun page 380
Note: K0(0) is not define and this function
returns 1E20
x = (double) real arguments
this routine calls bessi0() = Bessel function I0(x)
12-feb-1997 E. Kirkland
*/
double bessk0( double x )
{
double bessi0(double);
int i;
double ax, x2, sum;
double k0a[] = { -0.57721566, 0.42278420, 0.23069756,
0.03488590, 0.00262698, 0.00010750, 0.00000740};
double k0b[] = { 1.25331414, -0.07832358, 0.02189568,
-0.01062446, 0.00587872, -0.00251540, 0.00053208};
ax = fabs( x );
if( (ax > 0.0) && ( ax <= 2.0 ) ){
x2 = ax/2.0;
x2 = x2 * x2;
sum = k0a[6];
for( i=5; i>=0; i--) sum = sum*x2 + k0a[i];
sum = -log(ax/2.0) * bessi0(x) + sum;
} else if( ax > 2.0 ) {
x2 = 2.0/ax;
sum = k0b[6];
for( i=5; i>=0; i--) sum = sum*x2 + k0b[i];
sum = exp( -ax ) * sum / sqrt( ax );
} else sum = 1.0e20;
return ( sum );
} /* end bessk0() */
double oldchi( float p[], double alx, double aly, int multiMode )
{
double theta, al, al2, aln;
double w, ct, st, c2t, s2t, c3t, s3t, c4t, s4t, c5t, s5t,
c6t, s6t;
aln = al2 = alx*alx + aly*aly; /* alpha squared, angle in k space */
/* just rotationally symm. aberrations (faster) */
w = ( ( al2*p[pCS5]/6.0 + 0.25*p[pCS] )*al2 - 0.5*p[pDEFOCUS] )*al2;
if( multiMode != 0 ) {
/* ---- first order ----- */
theta = atan2( aly, alx );
ct = cos( theta );
st = sin( theta );
c2t = ct*ct - st*st; /* cos/sin of 2*theta */
s2t = 2.0*ct*st;
w += al2*( p[pC12a]*c2t + p[pC12b]*s2t )/2.0;
al = sqrt( al2 );
/* ---- second order ----- */
/* generate the other theta's recursively to reduce CPU time */
aln = al2*al; /* alpha^3 */
c3t = ct*c2t - st*s2t; /* cos/sin of 3*theta */
s3t = ct*s2t + st*c2t;
w += aln*( p[pC21a]*ct + p[pC21b]*st + p[pC23a]*c3t + p[pC23b]*s3t )/3.0;
/* ---- third order ----- */
aln = al2*al2; /* alpha^4 */
c4t = ct*c3t - st*s3t; /* cos/sin of 4*theta */
s4t = ct*s3t + st*c3t;
w += aln*( p[pC32a]*c2t + p[pC32b]*s2t + p[pC34a]*c4t
+ p[pC34b]*s4t )/4.0;
/* ---- fourth order ----- */
aln = aln*al; /* alpha^5 */
c5t = ct*c4t - st*s4t; /* cos/sin of 5*theta */
s5t = ct*s4t + st*c4t;
w += aln*( p[pC41a]*ct + p[pC41b]*st + p[pC43a]*c3t + p[pC43b]*s3t
+ p[pC45a]*c5t + p[pC45b]*s5t )/5.0;
/* ---- fifth order ----- */
aln = aln*al; /* alpha^6 */
c6t = ct*c5t - st*s5t; /* cos/sin of 5*theta */
s6t = ct*s5t + st*c5t;
w += aln*( p[pC52a]*c2t + p[pC52b]*s2t + p[pC54a]*c4t + p[pC54b]*s4t
+ p[pC56a]*c6t + p[pC56b]*s6t )/6.0;
#ifdef TEST_COS
string stemp;
ct = cos( 6*theta ); /* quick test of recursion algebra */
st = sin( 6*theta );
if( fabs(ct-c6t)+fabs(st-s6t) > 1.0e-10 ) {
stemp = "cos/sin= " +toString(ct)+", "+ toString(st),", c6t/s6t= "+
toString(c6t) +", "+ toString(s6t );
messageSL( stemp.c_str() );
}
#endif
}
return( w );
}
/*------------------------ chi() ---------------------*/
/*
calculate the aberration function chi
with 3rd and 5th order Cs plus astigmatism plus offset
put in a subroutine so I only have to get it right once
input values:
Aberration parameters are:
C1, defocus, in nm
A1, 2-fold astigmatism, in nm
A2, 3-fold astigmatism, in nm
B2, axial coma, in nm
C3, primary spherical aberration, in um
A3, 4-fold astigmasitm, in um
S3, star aberration, in um
A4, 5-fold astigmatism, in um
D4, 3-lobe aberration, in um
B4, axial coma, in um
C5, 5th order spherical aberration, in mm
A5, 5th order spherical aberration, in mm
In the aberrations array, the first column contains the aberration coefficient, the
second column contains the rotation angle for that aberration, the third column
contains the sine of the angle, and the fourth column contains the cosine.
wl = wavelength (in Ang.)
kx, ky = spatial freq (in 1/Ang)
dx,dy = offset (in Ang)
*/
double chi( double **aber, double wl, float kx, float ky, double dx, double dy)
{
double c, phi;
double kxr, kyr;
kxr = kx;
kyr = ky;
c = 0.0;
/* Evaluate the phase shifts from the various aberrations */
c += -1.0*(dx*kx + dy*ky); /* probe center shift */
c += 0.5*wl*aber[0][0]*(kx*kx + ky*ky); /* C1, defocus */
kxr = kx*aber[1][3] + ky*aber[1][2]; kyr = ky*aber[1][3] - kx*aber[1][2];
c += 0.5*wl*aber[1][0]*(kxr*kxr - kyr*kyr); /* A1, 2-fold astigmatism */
kxr = kx*aber[2][3] + ky*aber[2][2]; kyr = ky*aber[2][3] - kx*aber[2][2];
c += (1.0/3.0)*wl*wl*aber[2][0]*(pow(kxr,3) - 3*kxr*kyr*kyr); /* A2, 3-fold astigmatism */
kxr = kx*aber[3][3] + ky*aber[3][2]; kyr = ky*aber[3][3] - kx*aber[3][2];
c += wl*wl*aber[3][0]*(pow(kxr, 3) + kxr*kyr*kyr); /* B2, axial coma */
c += 0.25*pow(wl,3)*aber[4][0]*(pow(kx, 4) + 2*pow(kx,2)*pow(ky,2) + pow(ky, 4)); /* C3, primary spherical aberration */
kxr = kx*aber[5][3] + ky*aber[5][2]; kyr = ky*aber[5][3] - kx*aber[5][2];
c += 0.25*pow(wl,3)*aber[5][0]*(pow(kxr, 4) - 6*pow(kxr,2)*pow(kyr, 2) + pow(kyr,4)); /* A3, 4-fold astigmasitm */
kxr = kx*aber[6][3] + ky*aber[6][2]; kyr = ky*aber[6][3] - kx*aber[6][2];
c += pow(wl,3)*aber[6][0]*(pow(kxr,4) - pow(kyr,4)); /* S3, star aberration */
kxr = kx*aber[7][3] + ky*aber[7][2]; kyr = ky*aber[7][3] - kx*aber[7][2];
c += 0.2*pow(wl,4)*aber[7][0]*(pow(kxr, 5) - 10*pow(kxr,3)*pow(kyr,2) + 5*kxr*pow(kyr,4)); /* A4, 5-fold astigmatism */
kxr = kx*aber[8][3] + ky*aber[8][2]; kyr = ky*aber[8][3] - kx*aber[8][2];
c += pow(wl,4)*aber[8][0]*(pow(kxr, 5) - 2*pow(kxr,3)*pow(kyr,2) - 3*kxr*pow(kyr, 4)); /* D4, 3-lobe aberration */
kxr = kx*aber[9][3] + ky*aber[9][2]; kyr = ky*aber[9][3] - kx*aber[9][2];
c += pow(wl,4)*aber[9][0]*(pow(kxr,5) + 2*pow(kxr,3)*pow(kyr,2) + kxr*pow(kyr,4)); /* B4, axial coma */
c += (1.0/6.0)*pow(wl,5)*aber[10][0]*(pow(kx,6) + 3*pow(kx,4)*pow(ky,2)
+ 3*pow(kx,2)*pow(ky,4) + pow(ky,6)); /* C5, 5th order spherical aberration */
kxr = kx*aber[11][3] + ky*aber[11][2]; kyr = ky*aber[11][3] - kx*aber[11][2];
c += (1.0/6.0)*pow(wl,5)*aber[11][0]*(pow(kxr,6) - 15*pow(kxr,4)*pow(kyr,2)
+ 15*pow(kxr,2)*pow(kyr,4) - pow(kyr,6)); /* A5, 5th order spherical aberration */
c *= 2.0*3.1415927;
/*phi = atan2( ky, kx );
// c = chi1*k2* ( (chi2 + chi3*k2)*k2 - df
// + dfa2*sin( 2.0*(phi-dfa2phi) )
// + 2.0*dfa3*wavlen*sqrt(k2)* sin( 3.0*(phi-dfa3phi) )/3.0 )
// - ( (dx2p*kx) + (dy2p*ky) ); */
return( c );
}
/*--------------------- cputim() -----------------------------------*/
/*
retrieve current CPU time in seconds
*/
double cputim()
{
return ( ( (double)clock() ) / ( (double)CLOCKS_PER_SEC) );
} /* end cputim() */
/*--------------------- featom() -----------------------------------*/
/*
return the electron scattering factor for atomic
number Z at scattering angle k
Z = atomic number 1 <= Z <= 103
k2 = k*k where k =1/d = scattering angle (in 1/A)
assumed global vars:
#define NZMIN 1 min Z in featom.tab
#define NZMAX 103 max Z in featom.tab
int feTableRead=0; = flag to remember if the param file has been read
int nl=3, ng=3; = number of Lorenzians and Gaussians
double fparams[][] = fe parameters
*/
double featom( int Z, double k2 )
{
int i, nfe;
double sum;
int ReadfeTable( );
if( (Z<NZMIN) || (Z>NZMAX) ) return( 0.0 );
/* read in the table from a file if this is the
first time this is called */
if( feTableRead == 0 ) nfe = ReadfeTable();
sum = 0.0;
/* Lorenztians */
for( i=0; i<2*nl; i+=2 )
sum += fparams[Z][i]/( k2 + fparams[Z][i+1] );
/* Gaussians */
for( i=2*nl; i<2*(nl+ng); i+=2 )
sum += fparams[Z][i]*exp( - k2 * fparams[Z][i+1] );
return( sum );
} /* end featom() */
/*--------------- free2D() ----------------------------*/
/*
free a 2D array f[][] dimensioned as f[ix][iy]
0 < ix < (nx-1)
0 < iy < (ny-1) <not used>
*/
void free2D( void ** f, int nx )
{
int ix;
for( ix=0; ix<nx; ix++) free( f[ix] );
free( f );
return;
} /* end free2D() */
/*--------------- free3D() ----------------------------*/
/*
free a 2D array f[][] dimensioned as f[ix][iy]
0 < ix < (nx-1)
0 < iy < (ny-1)
0 < iz < (nz-1) <not used>
*/
void free3D( void *** f, int nx, int ny )
{
int ix, iy;
for( ix=0; ix<nx; ix++) {
for( iy=0; iy<ny; iy++) free( f[ix][iy] );
free( f[ix] );
}
free( f );
return;
} /* end free3D() */
/*------------------------ freqn() ------------------------*/
/*
Calculate spatial frequencies for use with fft's
NOTE: zero freg is in the bottom left corner and
expands into all other corners - not in the center
this is required for fft - don't waste time rearranging
This routine must be called once for each direction
ko[n] = real array to get spatial frequencies
ko2[n] = real array to get k[i]*k[i]
xo[n] = real array to get positions
nk = integer number of pixels
ak = real full scale size of image in pixels
*/
void freqn( float *ko, float *ko2, float *xo, int nk, double ak )
{
int i, imid;
/* imid = nk/2; only for nk=2^m - very small error otherwise */
imid = (int) ( nk/2.0 + 0.5); /* when nk may not be 2^m */
for( i=0; i<nk; i++) {
xo[i] = ((float) (i * ak) ) / ((float)(nk-1));
if ( i > imid ) {
ko[i] = ((float)(i-nk)) / ((float)ak);
} else {
ko[i] = ((float)i) / ((float)ak);
}
ko2[i] = ko[i] * ko[i];
}
} /* end freqn() */
/*---------------------------- malloc1D() -------------------------------*/
/*
1D array allocator for arbitrary type
make space for m[0...(n-1)]
printf error message and exit if not successful
this save checking for a NULL return etc. every time
n = number of elements
size = size of each element as returned by
sizeof(double), sizeof(int), etc.
*/
void* malloc1D( int n, size_t size, const char *message )
{
void *m;
std::string stemp;
m = (void*) malloc( n * size );
if( NULL == m ) {
stemp= "out of memory in malloc1D(), size= "+toString(n)+": "+ message;
messageSL( stemp.c_str(), 2 );
exit( 0 );
}
return( m );
} /* end malloc1D() */
/*---------------------------- malloc2D() -------------------------------*/
/*
2D array allocator for type float
make space for m[0...(nx-1)][0..(ny-1)]
nx,ny = number of elements
size = size of each element as returned by
sizeof(double), sizeof(int), etc.
*/
void **malloc2D( int nx, int ny, size_t size, const char *message )
{ void **m;
int i;
std::string stemp;
m = (void**) malloc( nx * sizeof( void* ) );
if( m == NULL ) {
stemp= "out of memory in malloc2D(), size=" + toString(nx) +
", "+toString(ny)+": "+message;
messageSL( stemp.c_str(), 2 );
exit(0);
}
for (i=0; i<nx; i++){
m[i] = (void*) malloc( ny * size );
if( m[i] == NULL ){
stemp= "out of memory in malloc2D(), size=" + toString(nx) +
", "+toString(ny)+": "+message;
messageSL( stemp.c_str(), 2 );
exit(0);
}
}
return m;
} /* end malloc2D() */
/*---------------------------- malloc3D() -------------------------------*/
/*
3D array allocator for type float
make space for m[0...(nx-1)][0..(ny-1)][0..(nz-1)]
nx,ny,nz = number of elements
size = size of each element as returned by
sizeof(double), sizeof(int), etc.
*/
void ***malloc3D( int nx, int ny, int nz, size_t size, const char *message )
{ void ***m;
int i, j;
std::string stemp;
m = (void***) malloc( nx * sizeof( void** ) );
if( m == NULL ) {
stemp= "out of memory in malloc3D(), size=" + toString(nx) + ", " +
toString(ny) + ", " + toString(nz) + ": " + message;
messageSL( stemp.c_str(), 2 );
exit(0);
}
for (i=0; i<nx; i++){
m[i] = (void**) malloc( ny * sizeof( void* ) );
if( m[i] == NULL ){
stemp= "out of memory in malloc3D(), size=" + toString(nx) + ", " +
toString(ny) + ", " + toString(nz) + ": " + message;
messageSL( stemp.c_str(), 2 );
exit(0);
}
for (j=0; j<ny; j++){
m[i][j] = (void*) malloc( nz * size );
if( m[i][j] == NULL ){
stemp= "out of memory in malloc3D(), size=" + toString(nx) + ", " +
toString(ny) + ", " + toString(nz) + ": " + message;
messageSL( stemp.c_str(), 2 );
exit(0);
}
}
}
return m;
} /* end malloc3D() */
/*--------------------- messageSL() -----------------------------------*/
/*
slicelib message output
direct all output message here to redirect to the command line
or a GUI status line or message box when appropriate
msg[] = character string with message to disply
level = level of seriousness
0 = simple status message
1 = significant warning
2 = possibly fatal error
*/
void messageSL( const char msg[], int level )
{
#ifdef USE_TERMINAL
cout << msg << endl; //simplest possible version
#endif
#ifdef wxGUI
if( 0 == level ){
//wxLogStatus( wxT(msg) );
wxLogStatus( msg );
} else if( 1 == level ) {
wxMessageBox( msg, wxT("slicelib"), wxOK | wxICON_INFORMATION );
}
#endif
}
/*--------------------- parlay() -----------------------------------*/
/*
subroutine to parse the atomic layer stacking sequence
for use with multislice programs.
This converts layer structure definition of the form:
2(abc)d
into a sequence of numerical indices where a=1, b=2, c=3, ...
The main attraction is the repeat operator n(...) where
the structure inside the parenthesis (...) is repeated n times.
for instance the above structure is translated into:
1 2 3 1 2 3 4
The parenthesis may be nested up to 100 levels (determined by
nlmax). For instance 5( 2(abc) 3(cba) ) is also a valid structure
definition. This is a compact way of specifying the layer structure
for a multislice calculation. tab's may be present in the structure
anywhere (they are ignored).
This is done by pushing the position of each '(' and its repeat
count onto a stack. Each ')' pops the last entry from the stack
and invokes a duplication process.
Layers refer to the distinquishable subset of different
types of layers, whereas slices refer to the way these
layers are sequentially stacked.
fortran version started 22-dec-1989 earl j. kirkland
added nested parenthesis by stacking entry points
31-jan-1990 ejk
added tab handling (in ascii and ebcdic) 1-feb-1990 ejk
minor changes to error messages to make rs6000's happy
7-july-1992 ejk
converted to ANSI-C 26-jun-1995 ejk
added include of stdlib.h 6-july-1995 ejk
c = input character string
islice[nsmax] = integer array to get stacking sequence indicies
nsmax = (integer) size of layer
lmax = (integer) maximum allowed layer index
nslice = (integer) number of layers
returned value= (integer) success/error code
0 : success
-1 : layer out of range
-2 : missing left parenthesis
-3 : parenthesis nested too deep
-4 : bad repeat code
-5 : unmatched right parenthesis
-6 : invalid character
-7 : too many layers
-8 : incomplete stacking sequence
fperr = (int) if this is not a NULL then write
error messages
NOTE: islice and nslice may be modified by this routine
cname determines the mapping of characters into numbers.
*/
#ifdef USE_TERMINAL
#define NCMAX 132 // characters per line to read
#define NSTKMAX 100 /* maximum stack depth (i.e. maximum level
of nesting the parenthesis) */
#define NCHARS 52 /* maximum number of character symbols */
int parlay( const char c[], int islice[], int nsmax, int lmax,
int *nslice, int fperr )
{
/* define our own symbol sequence */
const char cname[] =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int ic, lenc, name, i, j, istack, n,
ipoint[NSTKMAX], repeat[NSTKMAX];
/* initialize misc constants */
*nslice = 0;
istack = 0;
lenc = (int) strlen( c ); /* length of c */
for( ic=0; ic<lenc; ic++ ) { /* loop over all characters in c */
/* skip over embedded spaces, tabs and weird characters */
while( isspace( c[ic] ) ) ic++;
/* if its a character do this */
if( isalpha( c[ic] ) ) {
for(name=0; name<NCHARS; name++)
if( c[ic] == cname[name] ) break;
if( name > lmax ) {
if( fperr != 0 )
printf("Layer /%c/ out of range in the stacking sequence"
" in subroutine parlay.\n", c[ic] );
return( -1 );
} else {
if( *nslice >= nsmax ) {
if( fperr != 0 )
printf("Too many layers generated in the stacking"
" sequence in parlay.\n");
return( -7 );
}
islice[ (*nslice)++ ] = name;
}
/* if its a number then extract repeat count up to the '('
and save it until a ')' appears (i.e. push on the stack)
*/
} else if ( isdigit( c[ic] ) ) {
if( istack >= NSTKMAX ) {
if( fperr != 0 )
printf("Parenthesis nested too deep in "
"the stacking sequence in subroutine parlay.\n");
return( -3 );
}
repeat[istack] = atoi( &c[ic] ) - 1;
while( isdigit(c[ic]) || isspace(c[ic]) ) ic++;
if( c[ic] != '(' ) {
if( fperr != 0 )
printf("Missing left parenthesis in "
"the stacking sequence in subroutine parlay.'\n");
for(i=0; i<=ic; i++) printf("%c", c[i]);
printf("?\n");
return( -2 );
}
ipoint[istack++] = *nslice;
/* if its a ')' then repeat back to the last '('
(i.e. pop the stack) */
} else if( c[ic] == ')' ) {
if( istack <= 0 ) {
if( fperr != 0 )
printf("Unmatched right parenthesis in "
"the stacking sequence in subroutine parlay.\n");
return( -5 );
}
n = *nslice;
istack--;
for( j=0; j<repeat[istack]; j++)
for(i=ipoint[istack]; i<n; i++){
if( *nslice >= nsmax ) {
if( fperr != 0 )
printf("Too many layers generated in the stacking"
" sequence in parlay.\n");
return( -7 );
}
islice[ (*nslice)++ ] = islice[ i ];
}
} else {
if( fperr != 0 )
printf("Invalid character /%c/ encountered in "
"the stacking sequence in subroutine parlay.\n",
c[ic]);
return( -6 );
}
} /* end for( ic... */
if( istack != 0 ) {
if( fperr != 0 )
printf("incomplete stacking sequence in parlay.\n");
return( -8 );
} else return( 0 );
#undef NCMAX
#undef NSTKMAX
#undef NCHARS
} /* end parlay() */
#endif
/*------------------------ propagate() ------------------------*/
/*
propagate the wavefunction thru one layer
wave = complex wavefunction
propxr,i[ix] = real and imag. parts of x comp of propagator
propyr,i[iy] = real and imag. parts of y comp of propagator
kx2[], ky2[] = spatial frequency components
k2max = square of maximum k value
nx, ny = size of array
on entrance waver,i and
propxr,i/propyr,i are in reciprocal space
only wave will be changed by this routine
*/
void propagate( cfpix &wave,
float* propxr, float* propxi, float* propyr, float* propyi,
float* kx2, float* ky2, float k2max, int nx, int ny )
{
int ix, iy;
float pxr, pxi, pyr, pyi, wr, wi, tr, ti;
/* multiplied by the propagator function */
/* parallizing this loop usually runs slower (!)
#pragma omp parallel for private(j,iy,pxr,pxi,pyr,pyi,wr,wi,tr,ti) */
for( ix=0; ix<nx; ix++) {
if( kx2[ix] < k2max ) {
pxr = propxr[ix];
pxi = propxi[ix];
for( iy=0; iy<ny; iy++) {
if( (kx2[ix] + ky2[iy]) < k2max ) {
pyr = propyr[iy];
pyi = propyi[iy];
wr = wave.re(ix,iy); // real
wi = wave.im(ix,iy); // imag
tr = wr*pyr - wi*pyi;
ti = wr*pyi + wi*pyr;
wave.re(ix,iy) = tr*pxr - ti*pxi;
wave.im(ix,iy) = tr*pxi + ti*pxr;
} else {
wave.re(ix,iy) = 0.0F;
wave.im(ix,iy) = 0.0F;
}
} /* end for(iy..) */
} else for( iy=0; iy<ny; iy++) {
wave.re(ix,iy) = 0.0F;
wave.im(ix,iy) = 0.0F;
} /* end if( kx2[ix]... */
} /* end for(ix..) */
} /* end propagate() */
/*---------------------------- ranflat -------------------------------*/
/*
return a random number in the range 0.0->1.0
with uniform distribution
the 'Magic Numbers' are from
Numerical Recipes 2nd edit pg. 285
*/
double ranflat( unsigned long *iseed )
{
static unsigned long a=1366, c=150889L, m=714025L;
*iseed = ( a * (*iseed) + c ) % m;
return( ((double) *iseed)/m);
} /* end ranflat() */
/*-------------------- rangauss() -------------------------- */
/*
Return a normally distributed random number with
zero mean and unit variance using Box-Muller method
ranflat() is the source of uniform deviates
ref. Numerical Recipes, 2nd edit. page 289
added log(0) test 10-jan-1998 E. Kirkland
*/
double rangauss( unsigned long *iseed )
{
double ranflat( unsigned long* );
double x1, x2, y;
static double tpi=2.0*3.141592654;
/* be careful to avoid taking log(0) */
do{
x1 = ranflat( iseed );
x2 = ranflat( iseed );
} while ( (x1 < 1.0e-30) || (x2 < 1.0e-30) );
y = sqrt( - 2.0 * log(x1) ) * cos( tpi * x2 );
return( y );
} /* end rangauss() */
/*---------------------------- ranPoisson -------------------------------*/
/*
return a random number with Poisson distribution
and mean value mean
There is a nice poisson RNG in c++11 but some compilers still do not
have it, so make one here. The function lgamma()= log of gamma function
is in the C99 standard and seems to have more widespread support
(in mac osx 10.8 but NOT MSVS2010!). Leave lgamma() code for future
and approximate large means with Stirling's formula.
A. C, Atkinson, "The Computer Generation of Poisson Random Variable"
J. Royal Statistical Society, Series C (Applied Statistics),
p. 29-35.
D. E. Knuth, "The Art of Computer Programming, vol.2, Seminumerical
Algorithms" Addison-Wesley 1981, 1969, p. 132.
calls ranflat()
input:
mean = desired mean (can be fractional)
iseed = random number seed
started 23-sep-2015 ejk
add large mean portion 26-sep-2015 ejk
*/
int ranPoisson( double mean, unsigned long *iseed )
{
int n;
static int lut=-1;
static double oldMean=-100, oldEmean=0;
static double alpha, beta, c, k, PI, lnf[256];
// negative mean is not allowed
if( mean <= 0 ) return 0;
if( lut < 0 ) { // init log( n! ) look up table