-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWaveSystem.cpp
More file actions
1829 lines (1546 loc) · 86.8 KB
/
Copy pathWaveSystem.cpp
File metadata and controls
1829 lines (1546 loc) · 86.8 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
/****
* @date Created on 2025-07-31 at 14:30:06 CEST
* @author David Gaspard (ORCID 0000-0002-4449-8782) <david.gaspard@espci.fr>
* @copyright This program is distributed under the MIT License.
* @file C++ code providing the implementation of the WaveSystem methods.
***/
#include "WaveSystem.hpp"
#include "BaseTools.hpp"
#include <random>
#include <algorithm>
#include <iomanip>
/**
* Constructor of the WaveSystem object.
*
* Arguments:
*
* sysname = String containing the name of the system (typically describing the system geometry) which is used to generate file output.
* mesh = Square mesh object.
* kh = Wavenumber times the lattice step, 2*pi*h/lambda. Also the phase accumulated across a lattice step (in radian).
* density = Scatterer density per unit pixel. Between 0 and 1.
* holscat = Lattice step divided by the scattering mean free path, h/lscat. Total length is not a well defined unit.
* holabso = Lattice step divided by the absorption length, h/labso. Total length is not a well defined unit.
*/
WaveSystem::WaveSystem(const std::string& sysname, const SquareMesh& mesh, const double kh, const double density, const double holscat, const double holabso) :
sysname(sysname), // Use initializer list to allocate matrix sizes.
mesh(mesh),
kh(checkWavenumber(kh)),
density(checkDensity(density)),
holscat(checkScattering(holscat)),
holabso(checkAbsorption(holabso)),
khc(complexWavenumber(kh, holabso)),
npoint(mesh.getNPoint()),
ninput(mesh.getNBoundary(BND_INPUT)),
noutput(mesh.getNBoundary(BND_OUTPUT)),
ninputprop(computeNInputProp()),
noutputprop(computeNOutputProp()),
computed(false),
hamiltonian(npoint, npoint),
inputState(npoint, ninputprop),
outputState(npoint, noutputprop),
inputKlh(ninputprop, 1),
outputKlh(noutputprop, 1),
green(npoint, ninputprop)
{
//std::cout << TAG_INFO << "Creating WaveSystem...\n";
computeHamiltonian();
computeIOStates();
}
/***********************************************************
* PRIVATE SETTERS
***********************************************************/
/**
* Check the validity of the given wavenumber, k*h, and returns it.
*/
double WaveSystem::checkWavenumber(const double kh) const {
if (kh < 0.) {
throw std::invalid_argument("In checkWavenumber(): Wavenumber cannot be negative.");
}
else if (kh > 2.) {
throw std::invalid_argument("In checkWavenumber(): Wavenumber cannot exceed Nyquist-Shannon bound (kh<2).");
}
return kh;
}
/**
* Check the validity of the given density, and returns it.
*/
double WaveSystem::checkDensity(const double density) const {
if (density < 0. || density > 1.) {
throw std::invalid_argument("In checkDensity(): Density must be between 0 and 1.");
}
return density;
}
/**
* Assigns the scattering strength, h/lscat.
*/
double WaveSystem::checkScattering(const double holscat) const {
if (holscat < 0.) {
throw std::invalid_argument("In checkScattering(): Scattering strength cannot be negative.");
}
else if (kh < holscat && VERBOSE >= 1) {
std::cout << TAG_WARN << "Scattering strength is large (k*lscat=" << kh/holscat << " <1). Localization may occur.\n";
}
return holscat;
}
/**
* Assigns the absorption strength, h/labso.
*/
double WaveSystem::checkAbsorption(const double holabso) const {
return holabso;
}
/**
* Returns the complex wavenumber khc = kh + I*(h/labso)/2.
*/
dcomplex WaveSystem::complexWavenumber(const double kh, const double holabso) const {
return (holabso == 0.) ? dcomplex(kh, MEPS) : dcomplex(kh, holabso/2.);
}
/***********************************************************
* PUBLIC GETTERS
***********************************************************/
/**
* Returns the total number of points in the mesh.
*/
int WaveSystem::getNPoint() const {
return npoint;
}
/**
* Returns the i-th point of the mesh.
*/
MeshPoint WaveSystem::getPoint(const int ipoint) const {
return mesh.getPoint(ipoint);
}
/**
* Return the openings of the mesh.
*/
std::vector<Opening> WaveSystem::getOpening() const {
return mesh.getOpening();
}
/**
* Returns the total number of openings (input or output leads).
*/
int WaveSystem::getNOpening() const {
return mesh.getNOpening();
}
/**
* Returns the number of input points, also the number of input channels.
*/
int WaveSystem::getNInput() const {
return ninput;
}
/**
* Returns the number of output points, also the number of output channels.
*/
int WaveSystem::getNOutput() const {
return noutput;
}
/**
* Returns the number of propagating modes in the input lead(s).
*/
int WaveSystem::getNInputProp() const {
return ninputprop;
}
/**
* Returns the number of propagating modes in the output lead(s).
*/
int WaveSystem::getNOutputProp() const {
return noutputprop;
}
/**
* Returns the wavenumber times the lattice step, k*h = 2*pi*h/lambda.
*/
double WaveSystem::getWavenumber() const {
return kh;
}
/**
* Returns the density of scatterers per unit pixel.
*/
double WaveSystem::getDensity() const {
return density;
}
/**
* Returns the value of "holscat" which is defined by h/lscat, where "h" is the lattice step
* (the unit length) and "lscat" is the scattering mean free path.
*/
double WaveSystem::getScattering() const {
return holscat;
}
/**
* Returns the value of "holabso" which is defined by h/labso, where "h" is the lattice step
* (the unit length) and "labso" is the ballistic absorption length.
*/
double WaveSystem::getAbsorption() const {
return holabso;
}
/**
* Returns a deep copy of the name of the UsadelSystem.
*/
std::string WaveSystem::getName() const {
return sysname;
}
/***********************************************************
* PRINTING METHODS
***********************************************************/
/**
* Returns a unique output filename for the given "dataname" with given file "extension" (with dot).
*/
std::string WaveSystem::uniqueFile(const std::string& dataname, const std::string& extension) const {
std::string filename;
uniqueFilename("out/" + sysname + "/" + dataname + "/" + dataname + "_", extension, filename);
return filename;
}
/**
* Returns the summary of essential information about the current wave system.
*/
std::vector<std::string> WaveSystem::summary() const {
std::vector<std::string> smr;
smr.push_back("WaveSystem with sysname='" + sysname + "', Npoint=" + std::to_string(npoint) + ", kh=" + std::to_string(kh)
+ ", lambda/h=[" + std::to_string(PI/std::asin(kh/2)) + ", " + std::to_string(PI/(std::sqrt(2.)*std::asin(kh/std::sqrt(8.)))) + "]");
smr.push_back("density=" + std::to_string(density) + ", h/lscat=" + std::to_string(holscat) + ", h/labso=" + std::to_string(holabso)
+ ", Ninputprop/Ninput=" + std::to_string(ninputprop) + "/" + std::to_string(ninput)
+ ", Noutputprop/Noutput=" + std::to_string(noutputprop) + "/" + std::to_string(noutput));
smr.push_back("DOSinput=" + std::to_string(dosinput) + ", DOSoutput=" + std::to_string(dosoutput) + ", DOSlattice=" + std::to_string(doslattice)
+ ", DOSfree=" + std::to_string(DOSFREE) + ", Hamiltonian_sparse_density=" + std::to_string(100.*hamiltonian.density()) + "%");
return smr;
}
/**
* Print essential information about the current wave system to standard output.
*/
void WaveSystem::printSummary() const {
for (const std::string& line : summary()) {// Loop over the lines of the summary.
std::cout << TAG_INFO << line << "\n";
}
}
/**
* Prints essential information about the sparse Hamiltonian matrix.
*/
void WaveSystem::infoHamiltonian() const {
hamiltonian.printSummary("Hamiltonian");
}
/**
* Prints the sparsity pattern of the Hamiltonian to a portable pixmap file, a PPM file (see: https://en.wikipedia.org/wiki/Netpbm).
*/
void WaveSystem::plotMatrixHamiltonian() const {
const std::string filename = uniqueFile("hamiltonian", ".png");
const auto start = std::chrono::steady_clock::now();
hamiltonian.savePNG(filename);
if (VERBOSE >= 1) {
double ctime = std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::steady_clock::now() - start).count();
std::cout << TAG_INFO << "Hamiltonian saved to file '" << filename << "' in " << ctime << " s.\n";
}
}
/**
* Prints the sparsity pattern of the input state matrix to a portable pixmap file, a PPM file (see: https://en.wikipedia.org/wiki/Netpbm).
*/
void WaveSystem::plotMatrixInputState() const {
const std::string filename = uniqueFile("input_state", ".png");
const auto start = std::chrono::steady_clock::now();
inputState.savePNG(filename);
if (VERBOSE >= 1) {
double ctime = std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::steady_clock::now() - start).count();
std::cout << TAG_INFO << "Input state saved to file '" << filename << "' in " << ctime << " s.\n";
}
}
/**
* Prints the sparsity pattern of the output state matrix to a portable pixmap file, a PPM file (see: https://en.wikipedia.org/wiki/Netpbm).
*/
void WaveSystem::plotMatrixOutputState() const {
const std::string filename = uniqueFile("output_state", ".png");
const auto start = std::chrono::steady_clock::now();
outputState.savePNG(filename);
if (VERBOSE >= 1) {
double ctime = std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::steady_clock::now() - start).count();
std::cout << TAG_INFO << "Input state saved to file '" << filename << "' in " << ctime << " s.\n";
}
}
/**
* Plot the mesh contained in the present wave system.
*/
void WaveSystem::plotMesh() const {
mesh.plotMesh(uniqueFile("mesh", ".csv"));
}
/**
* Save the given intensity profile to a CSV file and plot it using an external script.
*/
void WaveSystem::plotIntensity(const RealMatrix& intensity, const std::string& description, const std::string& dataname) const {
if (intensity.getNrow() != npoint) {// First check for possible errors:
std::string msg = "In plotIntensity(): Invalid intensity matrix, received nrow=" + std::to_string(intensity.getNrow())
+ ", expected nrow=" + std::to_string(npoint) + ".";
throw std::invalid_argument(msg);
}
else if (description.empty()) {
throw std::invalid_argument("In plotIntensity(): Empty 'description'. Please provide a description of the intensity profile.");
}
else if (dataname.empty()) {
throw std::invalid_argument("In plotIntensity(): Empty 'dataname'. Please provide a short folder name for the intensity profile.");
}
const int nstate = intensity.getNcol(); // Number of states in the wavefunction.
const char* sep = ", "; // Separator used between entries of the CSV file.
const int prec = 16; // Precision used in printing double precision values.
const std::string filename = uniqueFile(dataname, ".csv");
if (VERBOSE >= 1) {
const double fsize = ( (prec+4.)*nstate + 3.*DIMENSION*(std::log10(npoint)+2.) ) * static_cast<double>(npoint); // Roughly estimated file size in bytes (octets).
std::cout << TAG_INFO << "Save intensity to file '" << filename << "', size ~" << (fsize/1e6) << " Mo...\n";
}
std::ofstream ofs(filename); // Open the output file.
ofs << std::setprecision(prec); // Set the printing precision.
writeTimestamp(ofs, "%% "); // Apply a timestamp at the beginning.
for (const std::string& line : summary()) {// Write the summary to the file header.
ofs << "%% " << line << "\n";
}
ofs << "%% dataname='" + dataname + "'\n%% Info: " << description << "\n"
<< "x" << sep << "y" << sep << "north" << sep << "south" << sep << "east" << sep << "west";
for (int istate = 0; istate < nstate; istate++) {// Loop over the input modes to finish the column names.
ofs << sep << "I" << istate;
}
ofs << "\n";
MeshPoint p;
for (int ipoint = 0; ipoint < npoint; ipoint++) {// Loop over the points of the mesh.
p = mesh.getPoint(ipoint); // Extract the point to get its coordinates.
ofs << p.x << sep << p.y << sep
<< boundaryTypeString(p.north) << sep << boundaryTypeString(p.south) << sep
<< boundaryTypeString(p.east) << sep << boundaryTypeString(p.west);
for (int istate = 0; istate < nstate; istate++) {// Loop over the input modes.
ofs << sep << intensity(ipoint, istate); // Save the square modulus to the file.
}
ofs << "\n";
}
ofs.close(); // Close the stream before calling an external script (this may cause I/O trouble).
// Plot the I0 state:
std::string cmd;
if (holscat == 0.) {
cmd = "plot/plot_map.py I0 " + filename;
}
else {
cmd = "plot/plot_map.py -u " + std::to_string(holscat) + " I0 " + filename;
}
if (VERBOSE >= 1) {
std::cout << TAG_EXEC << cmd << "\n";
}
if (std::system(cmd.c_str())) {
std::cout << TAG_WARN << "The plot script returned an error.\n";
}
// Plot the average of all states:
//cmd = "plot/plot_map_avg.py -u " + std::to_string(holscat) + " " + std::to_string(nstate) + " " + filename;
//if (VERBOSE >= 1) {
// std::cout << TAG_EXEC << cmd << "\n";
//}
//if (std::system(cmd.c_str())) {
// std::cout << TAG_WARN << "The plot script returned an error.\n";
//}
}
/**
* Save the given fields to a CSV file and plot it using an external script.
*/
void WaveSystem::plotFields(const RealMatrix& fields, const std::vector<std::string>& labels, const std::string& description, const std::string& plotname) const {
// 1. First check for possible errors:
const int nfields = fields.getNcol();
if (fields.getNrow() != npoint) {// First check for possible errors:
std::string msg = "In plotFields(): Invalid field matrix, received nrow=" + std::to_string(fields.getNrow())
+ ", expected nrow=" + std::to_string(npoint) + ".";
throw std::invalid_argument(msg);
}
else if (static_cast<long int>(labels.size()) != nfields) {
std::string msg = "In plotFields(): Invalid number of labels, received " + std::to_string(labels.size())
+ "labels, expected " + std::to_string(nfields) + ".";
throw std::invalid_argument(msg);
}
else if (description.empty()) {
throw std::invalid_argument("In plotFields(): Empty 'description'. Please provide a description of the plot.");
}
else if (plotname.empty()) {
throw std::invalid_argument("In plotFields(): Empty 'plotname'. Please provide a short folder name.");
}
// 2. Define the output settings:
const char* sep = ", "; // Separator used between entries of the CSV file.
const int prec = 16; // Precision used in printing double precision values.
const std::string filename = uniqueFile(plotname, ".csv");
if (VERBOSE >= 1) {
const double fsize = ( (prec+4.)*nfields + 3.*DIMENSION*(std::log10(npoint)+2.) ) * static_cast<double>(npoint); // Roughly estimated file size in bytes (octets).
std::cout << TAG_INFO << "Save intensity to file '" << filename << "', size ~" << (fsize/1e6) << " Mo...\n";
}
// 3. Write the header:
std::ofstream ofs(filename); // Open the output file.
ofs << std::setprecision(prec); // Set the printing precision.
writeTimestamp(ofs, "%% "); // Apply a timestamp at the beginning.
for (const std::string& line : summary()) {// Write the summary to the file header.
ofs << "%% " << line << "\n";
}
ofs << "%% plotname='" + plotname + "'\n%% Info: " << description << "\n"
<< "x" << sep << "y" << sep << "north" << sep << "south" << sep << "east" << sep << "west";
for (int ifield = 0; ifield < nfields; ifield++) {// Loop over the input modes to finish the column names.
ofs << sep << labels.at(ifield);
}
ofs << "\n";
// 4. Write the data:
MeshPoint p;
for (int ipoint = 0; ipoint < npoint; ipoint++) {// Loop over the points of the mesh.
p = mesh.getPoint(ipoint); // Extract the point to get its coordinates.
ofs << p.x << sep << p.y << sep
<< boundaryTypeString(p.north) << sep << boundaryTypeString(p.south) << sep
<< boundaryTypeString(p.east) << sep << boundaryTypeString(p.west);
for (int ifield = 0; ifield < nfields; ifield++) {// Loop over the input modes.
ofs << sep << fields(ipoint, ifield); // Save the square modulus to the file.
}
ofs << "\n";
}
ofs.close(); // Close the stream before calling an external script (this may cause I/O trouble).
// 5. Plot the data by calling an external script:
std::string cmd = "plot/plot_map.py -u " + std::to_string(holscat) + " " + labels.at(0) + " " + filename;
if (VERBOSE >= 1) {
std::cout << TAG_EXEC << cmd << "\n";
}
if (std::system(cmd.c_str())) {
std::cout << TAG_WARN << "The plot script returned an error.\n";
}
}
/**
* Save the square modulus of the Green functions associated to each input mode to a CSV file and
* call an external script to plot the lowest mode.
*/
void WaveSystem::plotGreenFunction() {
computeGreenFunction(); // Ensure that the Green function has already been computed.
// Compute the square modulus of the Green function:
RealMatrix intensity(npoint, ninputprop);
dcomplex psi;
for (int imode = 0; imode < ninputprop; imode++) {// Loop over the modes.
for (int ipoint = 0; ipoint < npoint; ipoint++) {// Loop over the points.
psi = green(ipoint, imode);
intensity(ipoint, imode) = psi.real()*psi.real() + psi.imag()*psi.imag();
}
}
plotIntensity(intensity, "Modal Green functions", "green");
}
/**
* Save the first "nmode" eigenmodes of the input lead and call an extrernal script to plot the lowest mode.
* The modes are normalized so that the input intensity is 1 on average over the cross section of the input lead.
* This normalization does not take into account multiple input leads.
*/
void WaveSystem::plotInputModes(const int nmode) {
// 1. First check for possible invalid values of "nmode":
if (nmode <= 0 || nmode > ninputprop) {
std::string msg = "In plotInputModes(): Invalid number of modes, received nmode=" + std::to_string(nmode)
+ ", expected in 1.." + std::to_string(ninputprop) + ".";
throw std::invalid_argument(msg);
}
// 2. Compute the Green function and save the square modulus with appropriate normalization:
computeGreenFunction(); // Ensure that the Green function has already been computed.
RealMatrix intensity(npoint, nmode);
dcomplex psi;
for (int imode = 0; imode < nmode; imode++) {// Loop over the first modes.
for (int ipoint = 0; ipoint < npoint; ipoint++) {// Loop over the points.
psi = green(ipoint, imode) * 2.*I*std::sqrt(ninput) * inputKlh(imode, 0).real();
intensity(ipoint, imode) = psi.real()*psi.real() + psi.imag()*psi.imag();
}
}
std::string description = "First " + std::to_string(nmode) + " input modes.";
plotIntensity(intensity, description, "imode");
}
/**
* Save the square modulus of the first transmission eigenstates to a CSV file and call an external script to plot them.
* "nstate" is the number of desired transmission eigenstates, starting from the largest transmission value.
*/
void WaveSystem::plotTransmissionStates(const int nstate) {
// 1. First check for possible invalid values of "nstate":
const int ntval = std::min(noutputprop, ninputprop);
if (nstate <= 0 || nstate > ntval) {
std::string msg = "In plotTransmissionStates(): Invalid number of transmission eigenstates, received nstate=" + std::to_string(nstate)
+ ", expected in 1.." + std::to_string(ntval) + ".";
throw std::invalid_argument(msg);
}
// 2. Compute the transmission eigenstates:
ComplexMatrix tstate(npoint, nstate);
RealMatrix tval(ntval, 1);
computeTransmissionStates(tstate, tval);
// 2. Then compute the square modulus of the transmission eigenstates:
RealMatrix intensity(npoint, nstate);
dcomplex psi;
for (int istate = 0; istate < nstate; istate++) {// Loop over the first "nstate" transmission eigenstates.
for (int ipoint = 0; ipoint < npoint; ipoint++) {// Loop over the points.
psi = tstate(ipoint, istate);
intensity(ipoint, istate) = psi.real()*psi.real() + psi.imag()*psi.imag();
}
}
std::string description = "First " + std::to_string(nstate) + " transmission eigenstates with Tval=[";
for (int istate = 0; istate < nstate; istate++) {// Loop over the transmission eigenvalues.
description += " " + std::to_string(tval(istate, 0)) + " ";
}
description += "] (same order), Tavg=" + std::to_string(tval.mean()) + ".";
plotIntensity(intensity, description, "tstate");
}
/***********************************************************
* COMPUTATIONAL METHODS
***********************************************************/
/**
* Creates the free part of the "Hamiltonian", (d_x^2 + d_y^2 + k^2) * h^2, and store the result within the present WaveSystem object.
*/
void WaveSystem::computeHamiltonian() {
if (VERBOSE >= 1) {
std::cout << TAG_INFO << "Building the Hamiltonian... ";
}
const auto start_build = std::chrono::steady_clock::now(); // Gets the current time.
const dcomplex kh2 = khc*khc;
const std::vector<Opening> opening = mesh.getOpening(); // Extract the list of openings.
Opening op;
MeshPoint p;
int np, j, ip;
// 1. Preallocate the sparse Hamiltonian and precompute the opening matrices:
int nnzub = 5*npoint; // Computes an upper bound on the number of nonzero elements.
std::vector<ComplexMatrix> opmatrix; // Precompute the opneing matrices.
for (const Opening& op : opening) {// Loop over the openings.
np = op.index.size();
nnzub += (np - 1)*np;
opmatrix.push_back(openingMatrix(kh2, np));
}
hamiltonian.allocate(nnzub);
if (VERBOSE >= 2) {
std::cout << TAG_INFO << "Preallocated Hamiltonian with nnzub = " << nnzub << "\n";
}
// 2. Build the Hamiltonian row per row:
for (int i = 0; i < npoint; i++) {//Loop over the points of the mesh.
p = mesh.getPoint(i);
if (not p.isOpening()) {// If the point is not in an opening.
hamiltonian(i, i) = -4. + kh2; // Add the diagonal element of the Hamiltonian H(i, i) = -4 + (k*h)^2.
for (const Direction dir : allDirections) {// Loop over all directions.
j = p.neighbor(dir); // Extract the index of the neighboring point.
if (j >= 0) {// If the neigbhoring point is in the mesh, then add H(i, j) = 1.
hamiltonian(i, j) = 1.;
}
}
}
else {// If the point is actually in an opening.
// Find to which opening the point p(i) belongs:
for (uint iop = 0; iop < opening.size(); iop++) {// Loop over the openings.
op = opening.at(iop);
auto ptr = lower_bound(op.index.begin(), op.index.end(), i); // Find the point p(i) in the opening "op".
if (ptr != op.index.end() && *ptr == i) {// If the present opening contains the point p(i).
ip = std::distance(op.index.begin(), ptr); // Get the index of p(i) inside the opening.
np = op.index.size(); // Number of points in this opening.
for (int jp = 0; jp < np; jp++) {// Loop over the points in the present opening.
hamiltonian(i, op.index.at(jp)) = opmatrix.at(iop)(ip, jp);
}
}
}
for (const Direction dir : allDirections) {// Loop over the directions.
j = p.neighbor(dir);
if (j >= 0 && not mesh.getPoint(j).isOpening()) {// If point of index "j" belongs to the mesh, and is not an opening, then add H(i, j) = 1.
hamiltonian(i, j) = 1.;
}
}
}
}
// 3. Finalize the sparse Hamiltonian (sort the matrix elements in column-major ordering):
hamiltonian.finalize();
if (VERBOSE >= 1) {
// Print some warnings:
if (hamiltonian.getNnz() > nnzub) {
std::cout << TAG_WARN << "Insufficient matrix preallocation. Added nnz=" << hamiltonian.getNnz()
<< " elements, but allocated only nnzub=" << nnzub << ".\n";
}
// Measure the build time for information:
double ctime_build = std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::steady_clock::now() - start_build).count();
std::cout << "Done in " << ctime_build << " s.\n";
}
}
/**
* Assigns a realization of the disorder to the Hamiltonian.
*/
void WaveSystem::setDisorder(const uint64_t seed) {
//std::cout << TAG_INFO << "Setting disorder with seed=" << seed << "..." << std::endl;
computed = false; // Each time the Hamiltonian is modified, the Green function is no more valid and must be computed again.
double uh2;
dcomplex kh2 = khc*khc;
// Standard deviation of the random potential uh2 = U(x, y) * h^2 approximately producing the scattering strength h/lscat :
const double sigma = std::sqrt(kh*holscat/(PI*doslattice*density));
//const double sigma = std::sqrt(kh*holscat/(PI*doslattice));
std::mt19937_64 rng; // Instantiate the standard Mersenne Twister random number generator (64-bit-return version).
rng.seed(seed); // Initialize the random generator with the given seed.
std::normal_distribution<double> random_normal(0., sigma);
std::uniform_real_distribution<double> random_uniform(0., 1.);
for (int i = 0; i < npoint; i++) {//Loop over the points of the mesh.
if (not mesh.getPoint(i).isOpening()) {// If the point is not in an opening, then modifies the potential.
if (random_uniform(rng) < density) {// If the pixel is a scattering pixel (probability given by 'density').
uh2 = random_normal(rng); // Generate a Gaussian random number with standard deviation "sigma".
}
else {// Otherwise, then reset the value of the potential to zero.
uh2 = 0.;
}
hamiltonian(i, i) = -4. + kh2 - uh2; // In any case, replace the diagonal element of the Hamiltonian H(i, i) = -4 + (k*h)^2 - U*h^2.
}
}
}
/**
* Add the potential U(x,y)*h^2 to the current Hamiltonian at the given position (x,y) on the mesh.
*/
void WaveSystem::addPotential(const int x, const int y, const dcomplex uh2) {
computed = false; // Each time the Hamiltonian is modified, the Green function is no more valid and must be computed again.
const int i = mesh.indexOf(x, y); // Compute the index of the given point.
if (i >= 0) {// If the point is in the mesh.
hamiltonian(i, i) -= uh2; // Add the diagonal element of the Hamiltonian H(i, i) = -4 + (k*h)^2 - U*h^2.
}
}
/**
* Computes and return the number of input propagating modes.
*/
int WaveSystem::computeNInputProp() const {
const double fac = (2./PI) * std::asin(kh/2. - KLHMIN*KLHMIN/(4.*kh));
int np, ninputprop = 0; // Initialize the number of input propagating modes (it will be incremented).
for (const Opening& op : mesh.getOpening()) {// Loop over the openings.
if (op.bndtype == BND_INPUT) {// If the opening is an input, then construct the modes.
np = op.index.size(); // Number of point in the current input.
/**
* kh2 + d2ev > KLHMIN^2 (> 0)
*
* d2ev = -4.*sin((i+1)*PI/(2*(n+1)))^2
*
* kh2 - 4*sin((i+1)*PI/(2*(n+1)))^2 > KLHMIN^2, i=[0, n-1]
*
* ninputprop < (2*(n+1)/PI) * asin(sqrt((kh2 - KLHMIN^2)/4))
*
* Using the approx: sqrt((kh2 - KLHMIN^2)/4) <= kh/2 - KLHMIN^2/(4*kh)
*
* ninputprop = std::floor( (2*(n+1)/PI) * std::asin(kh/2 - KLHMIN^2/(4*kh)) );
*/
ninputprop += std::floor(fac*(np + 1));
}
}
if (ninputprop == 0) {// Check for possible errors.
throw std::invalid_argument("In computeNInputProp(): The number of input propagating modes is zero. Please increase the number of points in the opening.");
}
return ninputprop;
}
/**
* Computes and return the number of output propagating modes.
*/
int WaveSystem::computeNOutputProp() const {
const double fac = (2./PI) * std::asin(kh/2. - KLHMIN*KLHMIN/(4.*kh));
int np, noutputprop = 0; // Initialize the number of input propagating modes (it will be incremented).
for (const Opening& op : mesh.getOpening()) {// Loop over the openings.
if (op.bndtype == BND_OUTPUT) {// If the opening is an input, then construct the modes.
np = op.index.size(); // Number of point in the current input.
noutputprop += std::floor(fac*(np + 1));
}
}
if (noutputprop == 0) {// Check for possible errors.
throw std::invalid_argument("In computeNOutputProp(): The number of output propagating modes is zero. Please increase the number of points in the opening.");
}
return noutputprop;
}
/**
* Compute the input and output matrices containing the input and output modes.
*/
void WaveSystem::computeIOStates() {
if (VERBOSE >= 1) {
std::cout << TAG_INFO << "Building the input/output states... ";
}
const auto start_build = std::chrono::steady_clock::now(); // Gets the current time.
// Construct the input/output modes :
const dcomplex kh2 = khc*khc;
dcomplex d2pkh2, klh;
const double klhmin2 = KLHMIN*KLHMIN; // Minimum value of klh^2 for a mode to be considered as a propagating.
int np; // Number of points in the current opening.
int jinput = 0; // Current number of input modes.
int joutput = 0; // Current number of output modes.
dosinput = 0.; // Initialize the density of states in the input lead(s).
dosoutput = 0.; // Initialize the density of states in the output lead(s).
for (const Opening& op : mesh.getOpening()) {// Loop over the openings.
if (op.bndtype == BND_INPUT) {// If the opening is an input, then construct the modes.
np = op.index.size(); // Number of point in the current input.
ComplexMatrix u = modalMatrix(np); // Construct the matrix of modes (each mode is normalized to 1).
for (int j = 0; j < np; j++) {// Loop over the modes of U (columns of U).
d2pkh2 = laplacianEigenvalue(j, np) + kh2; // j^th eigenvalue of D_y^2 + (kh)^2 for an operator of size "np". Close to klh^2.
if (d2pkh2.real() > klhmin2) {// If the mode is propagating.
klh = std::sqrt( d2pkh2 * ( 1. - d2pkh2/4. ) ); // Compute the effective longitudinal wavenumber.
for (int i = 0; i < np; i++) {// Loop over the points in the opening (rows of U).
inputState(op.index.at(i), jinput) = u(i, j);
}
inputKlh(jinput, 0) = klh;
dosinput += 1./klh.real(); // Increments the DOS in the input lead(s).
jinput++;
}
}
}
else if (op.bndtype == BND_OUTPUT) {// If the opening is an output, then construct the modes.
np = op.index.size(); // Number of point in the current output.
ComplexMatrix u = modalMatrix(np); // Construct the matrix of modes (each mode is normalized to 1).
for (int j = 0; j < np; j++) {// Loop over the modes of U (columns of U).
d2pkh2 = laplacianEigenvalue(j, np) + kh2; // j^th eigenvalue of D_y^2 + (kh)^2 for an operator of size "np". Close to klh^2.
if (d2pkh2.real() > klhmin2) {// If the mode is propagating.
klh = std::sqrt( d2pkh2 * ( 1. - d2pkh2/4. ) ); // Compute the effective longitudinal wavenumber.
for (int i = 0; i < np; i++) {// Loop over the points in the opening (rows of U).
outputState(op.index.at(i), joutput) = u(i, j);
}
outputKlh(joutput, 0) = klh;
dosoutput += 1./klh.real(); // Increments the DOS in the output lead(s).
joutput++;
}
}
}
}
// Finalize the sparse matrices (sort the elements):
inputState.finalize();
outputState.finalize();
// Normalize the density of states:
dosinput /= 2*PI*ninput; // Note that it is the total number of input/output modes (including evanescent modes).
dosoutput /= 2*PI*noutput;
// Compute the exact free density of states on a square lattice:
const double mkh = 1. - kh*kh/4.;
doslattice = ellipticK(1. - 1./(mkh*mkh))/(2.*PI*PI*mkh);
if (VERBOSE >= 1) {
// Print some warnings:
if (jinput != ninputprop) {
std::cout << TAG_WARN << "Computed jinput=" << jinput << " input states, but planned ninputprop=" << ninputprop << ".\n";
}
if (joutput != noutputprop) {
std::cout << TAG_WARN << "Computed joutput=" << joutput << " output states, but planned noutputprop=" << noutputprop << ".\n";
}
if (std::abs(dosinput - doslattice) > 0.05*doslattice) {// Tolerance of 5% on the DOS.
std::cout << TAG_WARN << "DOSinput=" << dosinput << " is different from DOSlattice=" << doslattice << ", meaning that an input lead resonates (inputKlh.real.min=" << inputKlh.real().min() << "). You may consider changing the wavenumber...\n";
}
if (std::abs(dosoutput - doslattice) > 0.05*doslattice) {// Tolerance of 5% on the DOS.
std::cout << TAG_WARN << "DOSoutput=" << dosoutput << " is different from DOSlattice=" << doslattice << ", meaning that an output lead resonates (outputKlh.real.min=" << outputKlh.real().min() << "). You may consider changing the wavenumber...\n";
}
// Measure the build time for information:
double ctime_build = std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::steady_clock::now() - start_build).count();
std::cout << "Done in " << ctime_build << " s.\n";
}
}
/**
* Compute the retarded Green function between a point in the input lead(s) to a point in the output lead(s).
* If the Green function has already been computed and the Hamiltonian has not changed, this method does nothing.
* This method contains the most time-consuming operation in the program.
*/
void WaveSystem::computeGreenFunction() {
if (not computed) {// This function only does the computation if the flag "computed" is "false".
if (VERBOSE >= 2) {
std::cout << TAG_INFO << "Solving the sparse system now... ";
}
const auto start_solve = std::chrono::steady_clock::now(); // Gets the current time.
/**
* Solve the system using UMFPACK (no parallelization, no iterative refinement).
*/
solveUmfpack(hamiltonian, inputState, green);
/**
* Solve the system using MUMPS sequentially (MPI disabled, no iterative refinement).
* Note that MUMPS is faster than UMFPACK but uses more memory.
*/
//solveMumps(hamiltonian, inputState, green);
if (VERBOSE >= 2) {
double ctime_solve = std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::steady_clock::now() - start_solve).count();
std::cout << "Done in " << ctime_solve << " s.\n";
}
computed = true; // Declare the Green function as computed (avoids further recomputing).
}
}
/**
* Compute the transmission matrix "tmat" from the Green function using the Fisher & Lee relation.
* t_ij = 2*I*sqrt(k_i k_j) G(Output mode i | Input mode j). Size: (noutput, ninput).
*/
void WaveSystem::transmissionMatrix(ComplexMatrix& tmat) {
if (tmat.getNrow() != noutputprop || tmat.getNcol() != ninputprop) {// First check for possible errors.
std::string msg = "In transmissionMatrix(): Invalid transmission matrix size, received ("
+ std::to_string(tmat.getNrow()) + ", " + std::to_string(tmat.getNcol()) + "), expected ("
+ std::to_string(noutputprop) + ", " + std::to_string(ninputprop) + ").";
throw std::invalid_argument(msg);
}
computeGreenFunction(); // Ensure that the Green function has been computed (this does nothing if it is so).
tmat = outputState.conj() * green; // Project the Green function over the output states.
// Apply the Fisher & Lee relation :
for (int i = 0; i < noutputprop; i++) {// Loop over the output channels (rows).
for (int j = 0; j < ninputprop; j++) {// Loop over the input channels (columns).
tmat(i, j) = 2. * I * std::sqrt(inputKlh(j, 0).real() * outputKlh(i, 0).real()) * tmat(i, j);
// Note that the real parts strip the evanescent modes.
}
}
}
/**
* Compute the reflection matrix "rmat" from the Green function using hte Fisher & Lee relation.
* r_ij = -delta_ij + 2*I*sqrt(k_i k_j) G(Input mode i | Input mode j). Size: (ninput, ninput).
*/
void WaveSystem::reflectionMatrix(ComplexMatrix& rmat) {
if (rmat.getNrow() != ninputprop || rmat.getNcol() != ninputprop) {// First check for possible errors.
std::string msg = "In reflectionMatrix(): Invalid reflection matrix size, received ("
+ std::to_string(rmat.getNrow()) + ", " + std::to_string(rmat.getNcol()) + "), expected ("
+ std::to_string(ninputprop) + ", " + std::to_string(ninputprop) + ").";
throw std::invalid_argument(msg);
}
computeGreenFunction(); // Ensure that the Green function has been computed (this does nothing if it is so).
rmat = inputState.conj() * green; // Project the Green function over the input states.
// Apply the Fisher & Lee relation :
for (int i = 0; i < ninputprop; i++) {// Loop over the input channels (rows).
for (int j = 0; j < ninputprop; j++) {// Loop over the input channels (columns).
rmat(i, j) = 2. * I * std::sqrt(inputKlh(j, 0).real() * inputKlh(i, 0).real()) * rmat(i, j);
// Note that the real parts strip the evanescent modes.
}
rmat(i, i) -= 1.; // Note Fisher & Lee: r_ij = -delta_ij + 2*I*sqrt(k_i*k_j)*G(Input mode i | Input mode j).
}
}
/**
* Check that the residual of the solution of the linear system is reasonably close to zero.
*/
void WaveSystem::checkResidual() {
computeGreenFunction(); // Ensure that the Green function has been computed (this does nothing if it is so).
if (VERBOSE >= 1) {
std::cout << TAG_INFO << "Computing the residual...\n";
}
const ComplexMatrix inputState_product = hamiltonian * green; // Recompute the input state from the solution of the linear system.
// Compare the matrices elementwise:
const double tol = 1e-11; // Tolerance over the relative error (elementwise).
double res, res_total = 0.;
dcomplex elem, elem_expc;
for (int i = 0; i < npoint; i++) {// Loop over the mesh points.
for (int j = 0; j < ninputprop; j++) {// Loop over the input modes.
elem = inputState_product(i, j);
elem_expc = inputState.get(i, j);
res = std::abs(elem - elem_expc);
res_total += res;
if (res > tol*(std::abs(elem_expc) + 1.)) {// If the residual is two large.
std::cout << TAG_WARN << "Matrix element (" << i << ", " << j << ") is "
<< elem << ", expected " << elem_expc << " (diff=" << res << ").\n";
}
}
}
std::cout << TAG_INFO << "Average residual = " << (res_total/npoint)/ninputprop << " (total=" << res_total << ").\n";
}
/**
* Check the unitary of the propagation, i.e., check that in the absence of absorption, the relation associated to probability conservation,
* t*t.conj() + r*r.conj() = identityMatrix(), is verified. This method does the checking for several realizations of the disorder (number "nseed").
* This method is mainly used for testing purposes.
* If "showtval" is "true", then compute the transmission eigenvalues and print them to standard output.
*/
void WaveSystem::checkUnitarity(const bool showtval) {
ComplexMatrix tmat(noutputprop, ninputprop), rmat(ninputprop, ninputprop), unitarity(ninputprop, ninputprop);
transmissionMatrix(tmat);
reflectionMatrix(rmat);
unitarity = tmat.conj() * tmat + rmat.conj() * rmat - identityMatrix(ninputprop); // The unitarity matrix should ideally be zero on output.
std::cout << TAG_INFO << "Unitarity: t^H * t + r^H * r - 1 = " << unitarity.norm() << "\n";
if (showtval) {// Compute and print the transmission eigenvalues.
const int ntval = std::min(noutputprop, ninputprop); // Number of transmission eigenvalues.
ComplexMatrix u(noutputprop, noutputprop), vh(ninputprop, ninputprop);
RealMatrix tval(ntval, 1);
svd(tmat, tval, u, vh); // Compute the singular value decomposition (SVD).
for (int i = 0; i < ntval; i++) {
tval(i, 0) = tval(i, 0)*tval(i, 0); // Convert singular values of "t" to transmission eigenvalues.
}
tval.transpose().print("Tval");
std::cout << TAG_INFO << "Tavg = " << tval.mean() << "\n";
}
}
/**
* Add the transmission eigenvalues corresponding to the current settings of the WaveSystem to the given vector.
*/
void WaveSystem::addTSpectrum(RealMatrix& tval) {
// 1. First check for possible errors:
const int ntval = std::min(ninputprop, noutputprop); // Expected maximum number of transmission eigenstates.
if (tval.getNrow() != ntval || tval.getNcol() != 1) {
std::string msg = "In addTSpectrum(): Invalid size of 'tval'. Received ("
+ std::to_string(tval.getNrow()) + ", " + std::to_string(tval.getNcol()) + "), expected ("
+ std::to_string(ntval) + ", 1) as Ninputprop=" + std::to_string(ninputprop) + " and Noutputprop=" + std::to_string(noutputprop) + ".";
throw std::invalid_argument(msg);
}
// 2. Compute the transmission matrix and transmission eigenvalues: