/
pairinteraction.py
executable file
·2236 lines (1727 loc) · 111 KB
/
pairinteraction.py
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
#!/usr/bin/env python3
import sys
from pint import UnitRegistry
from pint.unit import UndefinedUnitError
from PyQt4 import QtCore, QtGui
from plotter import Ui_plotwindow # pyuic4 plotter.ui > plotter.py or py3uic4 plotter.ui > plotter.py
import pyqtgraph as pg
import numpy as np
import collections
from abc import ABCMeta, abstractmethod
from time import sleep, time
from datetime import timedelta
import locale
import json
import os
import multiprocessing
import subprocess
from scipy import sparse
import signal
from queue import Queue
import ctypes
import sip
from scipy import constants
import psutil
from scipy.ndimage.filters import gaussian_filter
from palettable import cubehelix
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
QtCore.QLocale.setDefault(QtCore.QLocale(locale.getlocale()[0]))
signal.signal(signal.SIGINT, signal.SIG_DFL)
ureg = UnitRegistry()
Q = ureg.Quantity
C = lambda s : Q(constants.value(s),constants.unit(s))
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
# http://stackoverflow.com/questions/4695337/expanding-adding-a-row-or-column-a-scipy-sparse-matrix
def csr_vappend(a,b):
""" Takes in 2 csr_matrices and appends the second one to the bottom of the first one.
Much faster than scipy.sparse.vstack but assumes the type to be csr and overwrites
the first matrix instead of copying it. The data, indices, and indptr still get copied."""
a.data = np.hstack((a.data,b.data))
a.indices = np.hstack((a.indices,b.indices))
a.indptr = np.hstack((a.indptr,(b.indptr + a.nnz)[1:]))
a._shape = (a.shape[0]+b.shape[0],b.shape[1])
#a = sparse.csr_matrix( (a.data,a.indices,a.indptr), shape=a.shape )
# ----- Returns a normalized image -----
def normscale(data, cmin=None, cmax=None):
if cmin is None:
cmin = np.nanmin(data)
if cmax is None:
cmax = np.nanmax(data)
return (data-cmin)/(cmax-cmin or 1)
# ----- Returns a byte-scaled image -----
def bytescale(data, cmin=None, cmax=None, high=255, low=0):
return np.array(normscale(data,cmin,cmax)*(high - low + 0.9999) + low).astype(int) # TODO
class Converter:
converter = dict()
dimensionless = Q('1')
converter[str(dimensionless.dimensionality)] = dimensionless
au_energy = C('atomic unit of energy')/C('Planck constant')
converter[str(au_energy.dimensionality)] = au_energy
au_bfield = C('atomic unit of mag. flux density')
converter[str(au_bfield.dimensionality)] = au_bfield
au_efield = C('atomic unit of electric field')
converter[str(au_efield.dimensionality)] = au_efield
au_length = C('atomic unit of length')
converter[str(au_length.dimensionality)] = au_length
@classmethod
def toAU(self,v):
dimensionality = v.dimensionality
return (v/self.converter[str(dimensionality)]).to('dimensionless')
@classmethod
def fromAU(self, v, units):
dimensionality = Q(1,units).dimensionality
return (v*self.converter[str(dimensionality)]).to(units)
class Units:
length = Q('micrometer').units
energy = Q('gigahertz').units
efield = Q('volt/centimeter').units
bfield = Q('gauss').units
angle = Q('degree').units
dimensionless = Q('1').units
class GUIDict(collections.MutableMapping, metaclass=ABCMeta):
def __init__(self, ui):
self.store = dict()
self._setup(self.store, ui)
@abstractmethod
def _setup(self, store, ui):
pass
def __getattr__(self, key):
return self.__getitem__(key)
def __getitem__(self, key):
widget = self.store[key]['widget']
unit = self.store[key]['unit'] if 'unit' in self.store[key] else None
value = None
if isinstance(widget, QtGui.QComboBox):
value = str(widget.currentText())
elif isinstance(widget, QtGui.QSpinBox):
value = int(widget.value())
elif isinstance(widget, QtGui.QDoubleSpinBox):
value = float(widget.value())
elif isinstance(widget, QtGui.QLineEdit):
try: value = locale.atof(str(widget.text()))
except ValueError: value = None
elif isinstance(widget, QtGui.QCheckBox):
value = widget.checkState() == QtCore.Qt.Checked
elif isinstance(widget, QtGui.QRadioButton):
value = widget.isChecked()
elif isinstance(widget, QtGui.QGroupBox):
value = widget.isChecked()
if unit is not None and value is not None:
return Q(value, unit)
else:
return value
def __setitem__(self, key, value):
widget = self.store[key]['widget']
unit = self.store[key]['unit'] if 'unit' in self.store[key] else None
if isinstance(value,Q):
value = value.to(unit).magnitude
if isinstance(widget, QtGui.QComboBox):
index = widget.findText(value)
if index >= 0: widget.setCurrentIndex(index)
elif isinstance(widget, QtGui.QSpinBox):
widget.setValue(value)
elif isinstance(widget, QtGui.QDoubleSpinBox):
widget.setValue(value)
elif isinstance(widget, QtGui.QLineEdit):
if value is None: widget.setText("None")
else: widget.setText(locale.str(value))
elif isinstance(widget, QtGui.QCheckBox):
if value: widget.setCheckState(QtCore.Qt.Checked)
else: widget.setCheckState(QtCore.Qt.Unchecked)
elif isinstance(widget, QtGui.QRadioButton):
widget.setChecked(value)
elif isinstance(widget, QtGui.QGroupBox):
widget.setChecked(value)
def __delitem__(self, key):
del self.store[key]
def __iter__(self):
return iter(self.store)
def __len__(self):
return len(self.store)
def load(self, params):
for k, v in params.items():
try:
if not isinstance(v, str): raise TypeError
v = v.replace("dimensionless","1")
self[k] = Q(v)
except (UndefinedUnitError, TypeError):
self[k] = v
def paramsInAU(self, f, exclude = []):
params = dict()
for k, v in self.items():
if k in exclude: continue
if isinstance(v, Q): params[k] = Converter.toAU(v).magnitude
else: params[k] = v
return params
def paramsInOriginalunits(self, exclude = []):
params = dict()
for k, v in self.items():
if k in exclude: continue
if isinstance(v, Q): params[k] = str(v)
else: params[k] = v
return params
class SystemDict(GUIDict):
def _setup(self, store, ui):
store["species1"] = {'widget': ui.combobox_system_species1}
store["species2"] = {'widget': ui.combobox_system_species2}
store["n1"] = {'widget': ui.spinbox_system_n1, 'unit': Units.dimensionless}
store["n2"] = {'widget': ui.spinbox_system_n2, 'unit': Units.dimensionless}
store["l1"] = {'widget': ui.spinbox_system_l1, 'unit': Units.dimensionless}
store["l2"] = {'widget': ui.spinbox_system_l2, 'unit': Units.dimensionless}
store["j1"] = {'widget': ui.spinbox_system_j1, 'unit': Units.dimensionless}
store["j2"] = {'widget': ui.spinbox_system_j2, 'unit': Units.dimensionless}
store["m1"] = {'widget': ui.spinbox_system_m1, 'unit': Units.dimensionless}
store["m2"] = {'widget': ui.spinbox_system_m2, 'unit': Units.dimensionless}
store["deltaNSingle"] = {'widget': ui.spinbox_system_deltaNSingle, 'unit': Units.dimensionless}
store["deltaLSingle"] = {'widget': ui.spinbox_system_deltaLSingle, 'unit': Units.dimensionless}
store["deltaJSingle"] = {'widget': ui.spinbox_system_deltaJSingle, 'unit': Units.dimensionless}
store["deltaMSingle"] = {'widget': ui.spinbox_system_deltaMSingle, 'unit': Units.dimensionless}
store["deltaNPair"] = {'widget': ui.spinbox_system_deltaNPair, 'unit': Units.dimensionless}
store["deltaLPair"] = {'widget': ui.spinbox_system_deltaLPair, 'unit': Units.dimensionless}
store["deltaJPair"] = {'widget': ui.spinbox_system_deltaJPair, 'unit': Units.dimensionless}
store["deltaMPair"] = {'widget': ui.spinbox_system_deltaMPair, 'unit': Units.dimensionless}
store["deltaESingle"] = {'widget': ui.lineedit_system_deltaESingle, 'unit': Units.energy}
store["deltaEPair"] = {'widget': ui.lineedit_system_deltaEPair, 'unit': Units.energy}
store["pairbasisSame"] = {'widget': ui.radiobutton_system_pairbasisSame}
store["pairbasisDefined"] = {'widget': ui.radiobutton_system_pairbasisDefined}
store["samebasis"] = {'widget': ui.checkbox_system_samebasis}
store["minEx"] = {'widget': ui.lineedit_system_minEx, 'unit': Units.efield}
store["minEy"] = {'widget': ui.lineedit_system_minEy, 'unit': Units.efield}
store["minEz"] = {'widget': ui.lineedit_system_minEz, 'unit': Units.efield}
store["minBx"] = {'widget': ui.lineedit_system_minBx, 'unit': Units.bfield}
store["minBy"] = {'widget': ui.lineedit_system_minBy, 'unit': Units.bfield}
store["minBz"] = {'widget': ui.lineedit_system_minBz, 'unit': Units.bfield}
store["maxEx"] = {'widget': ui.lineedit_system_maxEx, 'unit': Units.efield}
store["maxEy"] = {'widget': ui.lineedit_system_maxEy, 'unit': Units.efield}
store["maxEz"] = {'widget': ui.lineedit_system_maxEz, 'unit': Units.efield}
store["maxBx"] = {'widget': ui.lineedit_system_maxBx, 'unit': Units.bfield}
store["maxBy"] = {'widget': ui.lineedit_system_maxBy, 'unit': Units.bfield}
store["maxBz"] = {'widget': ui.lineedit_system_maxBz, 'unit': Units.bfield}
store["minR"] = {'widget': ui.lineedit_system_minR, 'unit': Units.length}
store["maxR"] = {'widget': ui.lineedit_system_maxR, 'unit': Units.length}
store["theta"] = {'widget': ui.lineedit_system_theta, 'unit': Units.angle}
store["dd"] = {'widget': ui.checkbox_system_dd}
store["dq"] = {'widget': ui.checkbox_system_dq}
store["qq"] = {'widget': ui.checkbox_system_qq}
store["steps"] = {'widget': ui.spinbox_system_steps, 'unit': Units.dimensionless}
store["precision"] = {'widget': ui.lineedit_system_precision, 'unit': Units.dimensionless}
def saveInAU_field1(self, f):
params = self.paramsInAU(f,['pairbasisSame','pairbasisDefined','species2','n2','l2','m2','j2','minR','maxR','theta','dd','dq','qq','deltaNPair','deltaLPair','deltaMPair','deltaJPair','deltaEPair'])
json.dump(params, f, indent=4, sort_keys=True)
def saveInAU_field2(self, f):
params = self.paramsInAU(f,['pairbasisSame','pairbasisDefined','species1','n1','l1','m1','j1','minR','maxR','theta','dd','dq','qq','deltaNPair','deltaLPair','deltaMPair','deltaJPair','deltaEPair'])
json.dump(params, f, indent=4, sort_keys=True)
def saveInAU_field12(self, f):
params = self.paramsInAU(f,['pairbasisSame','pairbasisDefined','minR','maxR','theta','dd','dq','qq','deltaNPair','deltaLPair','deltaMPair','deltaJPair','deltaEPair'])
json.dump(params, f, indent=4, sort_keys=True)
def saveInAU_potential(self, f):
params = self.paramsInAU(f,['pairbasisSame','pairbasisDefined'])
if self["pairbasisSame"]:
params["deltaNPair"] = -1
params["deltaLPair"] = -1
params["deltaJPair"] = -1
params["deltaMPair"] = -1
json.dump(params, f, indent=4, sort_keys=True)
class PlotDict(GUIDict):
def _setup(self, store, ui):
store["minE_field1"] = {'widget': ui.lineedit_field1_minE, 'unit': Units.energy}
store["maxE_field1"] = {'widget': ui.lineedit_field1_maxE, 'unit': Units.energy}
store["minE_field2"] = {'widget': ui.lineedit_field2_minE, 'unit': Units.energy}
store["maxE_field2"] = {'widget': ui.lineedit_field2_maxE, 'unit': Units.energy}
store["minE_potential"] = {'widget': ui.lineedit_potential_minE, 'unit': Units.energy}
store["maxE_potential"] = {'widget': ui.lineedit_potential_maxE, 'unit': Units.energy}
store["lines"] = {'widget': ui.groupbox_plot_lines}
store["points"] = {'widget': ui.groupbox_plot_points}
store["labels"] = {'widget': ui.groupbox_plot_labels}
store["overlap"] = {'widget': ui.groupbox_plot_overlap}
store["szLine"] = {'widget': ui.spinbox_plot_szLine, 'unit': Units.dimensionless}
store["szPoint"] = {'widget': ui.spinbox_plot_szPoint, 'unit': Units.dimensionless}
store["szLabel"] = {'widget': ui.spinbox_plot_szLabel, 'unit': Units.dimensionless}
store["szOverlap"] = {'widget': ui.spinbox_plot_szOverlap, 'unit': Units.dimensionless}
store["transpLine"] = {'widget': ui.spinbox_plot_transpLine, 'unit': Units.dimensionless}
store["transpPoint"] = {'widget': ui.spinbox_plot_transpPoint, 'unit': Units.dimensionless}
store["transpLabel"] = {'widget': ui.spinbox_plot_transpLabel, 'unit': Units.dimensionless}
store["transpOverlap"] = {'widget': ui.spinbox_plot_transpOverlap, 'unit': Units.dimensionless}
store["overlapUnperturbed"] = {'widget': ui.radiobutton_plot_overlapUnperturbed}
store["lin"] = {'widget': ui.radiobutton_plot_lin}
store["log"] = {'widget': ui.radiobutton_plot_log}
store["resolution"] = {'widget': ui.spinbox_plot_resolution}
store["n1"] = {'widget': ui.spinbox_plot_n1, 'unit': Units.dimensionless}
store["n2"] = {'widget': ui.spinbox_plot_n2, 'unit': Units.dimensionless}
store["l1"] = {'widget': ui.spinbox_plot_l1, 'unit': Units.dimensionless}
store["l2"] = {'widget': ui.spinbox_plot_l2, 'unit': Units.dimensionless}
store["j1"] = {'widget': ui.spinbox_plot_j1, 'unit': Units.dimensionless}
store["j2"] = {'widget': ui.spinbox_plot_j2, 'unit': Units.dimensionless}
store["m1"] = {'widget': ui.spinbox_plot_m1, 'unit': Units.dimensionless}
store["m2"] = {'widget': ui.spinbox_plot_m2, 'unit': Units.dimensionless}
store["antialiasing"] = {'widget': ui.checkbox_plot_antialiasing}
class Worker(QtCore.QThread):
def __init__(self, parent = None):
super().__init__(parent)
self.exiting = False
self.samebasis = False
self.message = ""
self.basisfile_field1 = ""
self.basisfile_field2 = ""
self.basisfile_potential = ""
self.numBlocks_field1 = 0
self.numBlocks_field2 = 0
self.numBlocks_potential = 0
self.dataqueue_field1 = Queue()
self.dataqueue_field2 = Queue()
self.dataqueue_potential = Queue()
def __del__(self):
self.exiting = True
self.wait()
def execute(self, stdout):
self.stdout = stdout
self.start()
def clear(self):
with self.dataqueue_field1.mutex: self.dataqueue_field1.queue.clear()
with self.dataqueue_field2.mutex: self.dataqueue_field2.queue.clear()
with self.dataqueue_potential.mutex: self.dataqueue_potential.queue.clear()
def run(self):
finishedgracefully = False
self.message = ""
# Clear filenames
self.basisfile_field1 = ""
self.basisfile_field2 = ""
self.basisfile_potential = ""
# Clear data queue
with self.dataqueue_field1.mutex: self.dataqueue_field1.queue.clear()
with self.dataqueue_field2.mutex: self.dataqueue_field2.queue.clear()
with self.dataqueue_potential.mutex: self.dataqueue_potential.queue.clear()
# Parse stdout
dim = 0
type = 0
current = 0
total = 0
status_type = ""
status_progress = ""
status_dimension = ""
for line in iter(self.stdout.readline, b""):
if self.exiting or not line:
break
elif line[:5] == b">>TYP":
type = int(line[5:12].decode('utf-8'))
status_type = ["Field map of first atom: ", "Field map of second atom: ", "Pair potential: ", "Field maps: "][type]
status_progress = "construct matrices"
if type == 3: self.samebasis = True
elif type == 0 or type == 1: self.samebasis = False
elif line[:5] == b">>BAS":
basissize = int(line[5:12].decode('utf-8'))
status_progress = "construct matrices using {} basis vectors".format(basissize)
elif line[:5] == b">>STA":
filename = line[6:-1].decode('utf-8')
if type == 0 or type == 3:
self.basisfile_field1 = filename
elif type == 1:
self.basisfile_field2 = filename
elif type == 2:
self.basisfile_potential = filename
elif line[:5] == b">>TOT":
total = int(line[5:12].decode('utf-8'))
numBlocks = int(line[12:19].decode('utf-8'))
current = 0
if type == 0 or type == 3:
self.numBlocks_field1 = numBlocks
elif type == 1:
self.numBlocks_field2 = numBlocks
elif type == 2:
self.numBlocks_potential = numBlocks
elif line[:5] == b">>DIM":
dim = int(line[5:12])
status_progress = "diagonalize {} x {} matrix, {} of {} matrices processed".format(dim, dim, current,total)
elif line[:5] == b">>OUT":
current += 1
status_progress = "diagonalize {} x {} matrix, {} of {} matrices processed".format(dim, dim, current,total)
filenumber = int(line[5:12].decode('utf-8'))
filestep = int(line[12:19].decode('utf-8'))
blocknumber = int(line[19:26].decode('utf-8'))
filename = line[27:-1].decode('utf-8')
if type == 0 or type == 3:
self.dataqueue_field1.put([filestep,blocknumber,filename])
elif type == 1:
self.dataqueue_field2.put([filestep,blocknumber,filename])
elif type == 2:
self.dataqueue_potential.put([filestep,blocknumber,filename])
elif line[:5] == b">>END":
finishedgracefully = True
break
else:
print (line.decode('utf-8'), end="")
self.message = status_type + status_progress
# Clear data queue if thread has aborted
if not finishedgracefully:
self.clear()
class BinaryLoader:
def __init__(self):
# types
self.typeIds = {1008: 'int8', 1016 : 'int16', 1032 : 'int32', 1064 : 'int64', 1108 : 'uint8', 1116 : 'uint16', 1132 : 'uint32', \
1164 : 'int64', 2032 : 'float32', 2064 : 'float64'}
self.type_t = 'uint16'
# bit masks
self.csr_not_csc = 0x01; # xxx0: csc, xxx1: csr
self.complex_not_real = 0x02; # xx0x: real, xx1x: complex
def readNumber(self, f, sz = None):
datatype = self.typeIds[np.fromfile(f, dtype=np.dtype(self.type_t), count=1)[0]]
if sz is None: return np.fromfile(f, dtype=np.dtype(datatype), count=1)[0]
else: return np.fromfile(f, dtype=np.dtype(datatype), count=sz)
def readVector(self, f):
size = self.readNumber(f)
return self.readNumber(f, size)
def readMatrix(self, f):
flags = self.readNumber(f)
rows = self.readNumber(f)
cols = self.readNumber(f)
if flags & self.complex_not_real: data = self.readVector(f) + self.readVector(f)*1j
else: data = self.readVector(f)
indices = self.readVector(f)
indptr = np.append(self.readVector(f),len(data))
if flags & self.csr_not_csc: return sparse.csr_matrix((data, indices, indptr), shape=(rows, cols))
else: return sparse.csc_matrix((data, indices, indptr), shape=(rows, cols))
class Eigensystem(BinaryLoader):
def __init__(self, filename):
super().__init__()
self._filename = filename
self._shift = 0
self._params = None
self._energies = None
self._basis = None
@property
def params(self):
if self._params is None:
with open(self._filename+'.json','r') as f:
self._params = json.load(f)
return self._params
@property
def energies(self):
if self._energies is None:
with open(self._filename+'.mat','rb') as f:
self._energies = np.real(self.readMatrix(f).diagonal())
self._shift = f.tell()
return self._energies
@property
def basis(self):
if self._basis is None:
with open(self._filename+'.mat','rb') as f:
if self._shift > 0: f.seek(self._shift,0)
else: self._energies = np.real(self.readMatrix(f).diagonal())
self._basis = self.readMatrix(f)
return self._basis
from ctypes.util import find_library
# see https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!msg/pyqtgraph/O-d2L6qfPoo/i1zedC2Oda4J
if sys.platform == 'win32':
qtlib = ctypes.windll.qtgui4
drawPoints = getattr(qtlib, '?drawPoints@QPainter@@QEAAXPEBVQPointF@@H@Z')
else:
"""
pwd: /usr/lib/i386-linux-gnu
list: nm -D ./libQtGui.so.4 > ~./list.txt
"""
qtlib = ctypes.cdll.LoadLibrary(find_library("QtGui"))
drawPoints = getattr(qtlib, '_ZN8QPainter10drawPointsEPK7QPointFi')
class PointsItem(QtGui.QGraphicsItem):
def __init__(self, x=None, y=None, size=1, alpha=80, color=(0,0,0)):
QtGui.QGraphicsItem.__init__(self)
self.size = size
self.alpha = alpha
#self.pen = pg.mkPen((0,0,0,self.alpha),width=self.size,style=QtCore.Qt.CustomDashLine)
#self.pen.setDashPattern([1, 20, 5, 4])
self.pen = pg.mkPen(color+(self.alpha,),width=self.size,cosmetic=True)
self.setData(x, y)
#self.ItemIgnoresTransformations = True
#self.setFlag(QtGui.QGraphicsItem.ItemIgnoresTransformations, True)
def setData(self, x, y):
if x is None:
x = np.array([])
y = np.array([])
self.data = np.empty((len(x), 2), dtype=np.float)
self.data[:,0] = x
self.data[:,1] = y
xmin = x.min()
xmax = x.max()
ymin = y.min()
ymax = y.max()
self.bounds = QtCore.QRectF(xmin, ymin, xmax-xmin, ymax-ymin)
self.prepareGeometryChange()
#self.qdata = [None]*len(x)
#for n,[a,b] in enumerate(zip(x,y)):
# self.qdata[n] = QtCore.QPointF(a,b)
#self.qdata = QtGui.QPolygonF(self.qdata)
def boundingRect(self):
return self.bounds
def paint(self, p, *args):
p.setPen(self.pen)
#p.drawPoints(self.qdata)
ptr = ctypes.c_void_p(sip.unwrapinstance(p))
drawPoints(ptr, self.data.ctypes, self.data.shape[0])
# https://stackoverflow.com/questions/17103698/plotting-large-arrays-in-pyqtgraph
class MultiLine(pg.QtGui.QGraphicsPathItem):
def __init__(self, x, y, size=1, alpha=80, color=(0,0,0)):
"""x and y are 2D arrays of shape (Nplots, Nsamples)"""
connections = np.ones(x.shape, dtype=bool)
connections[:,-1] = 0 # don't draw the segment between each trace
self.path = pg.arrayToQPath(x.flatten(), y.flatten(), connections.flatten())
pg.QtGui.QGraphicsPathItem.__init__(self, self.path)
pen = pg.mkPen(color+(alpha,),width=size,cosmetic=True)
self.setPen(pen)
def shape(self): # override because QGraphicsPathItem.shape is too expensive.
return pg.QtGui.QGraphicsItem.shape(self)
def boundingRect(self):
return self.path.boundingRect()
class DoublenoneValidator(QtGui.QDoubleValidator):
def __init__(self, parent=None):
super().__init__(parent)
def validate(self, s, pos):
if s == 'None':
return (QtGui.QValidator.Acceptable, s, pos)
lastpos = -1
for c in s.lower():
try:
lastpos = 'none'[lastpos+1:].index(c)
except ValueError:
return super().validate(s, pos)
return (QtGui.QValidator.Intermediate, s, pos)
def fixup(self, s):
return 'None'
class DoublepositiveValidator(QtGui.QDoubleValidator):
def __init__(self, parent=None):
super().__init__(parent)
def validate(self, s, pos):
status = super().validate(s, pos)
if status[0] == QtGui.QValidator.Intermediate and len(s) > 0 and s[0] == '-':
return (QtGui.QValidator.Invalid, s, pos)
if status[0] == QtGui.QValidator.Acceptable and locale.atof(s) < 0: # TODO atof soll auch mit englischem Zahlenformat umgehen koennen
return (QtGui.QValidator.Invalid, s, pos)
return status
def fixup(self, s):
return "0"
class DoubledeltaValidator(QtGui.QDoubleValidator):
def __init__(self, parent=None):
super().__init__(parent)
def validate(self, s, pos):
status = super().validate(s, pos)
if status[0] == QtGui.QValidator.Acceptable and locale.atof(s) < 0 and locale.atof(s) != -1:
return (QtGui.QValidator.Intermediate, s, pos)
return status
def fixup(self, s):
if locale.atof(s) < 0: return "-1"
return "0"
class DoubleValidator(QtGui.QDoubleValidator):
def __init__(self, parent=None):
super().__init__(parent)
def validate(self, s, pos):
return super().validate(s, pos)
def fixup(self, s):
return "0"
def unique_rows(a):
a = np.ascontiguousarray(a)
unique_a = np.unique(a.view([('', a.dtype)]*a.shape[1]))
return unique_a.view(a.dtype).reshape((unique_a.shape[0], a.shape[1]))
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
del pg.graphicsItems.GradientEditorItem.Gradients['greyclip']
del pg.graphicsItems.GradientEditorItem.Gradients['grey']
del pg.graphicsItems.GradientEditorItem.Gradients['cyclic']
del pg.graphicsItems.GradientEditorItem.Gradients['spectrum']
del pg.graphicsItems.GradientEditorItem.Gradients['bipolar']
color = cubehelix.Cubehelix.make(sat=1.8,n=7,rotation=1.21,start=1.2,reverse=True).colors[::-1]
color = np.append(color, [[255]]*len(color), axis=1).astype(np.ubyte)
pos = np.linspace(0,1,len(color))
pg.graphicsItems.GradientEditorItem.Gradients['cubehelix1'] = {'mode':'rgb', 'ticks':[(p, tuple(c)) for c, p in zip(color,pos)]}
color = cubehelix.Cubehelix.make(sat=1.5,n=7,rotation=-1.0,start=0.9,reverse=True).colors[::-1]
color = np.append(color, [[255]]*len(color), axis=1).astype(np.ubyte)
pos = np.linspace(0,1,len(color))
pg.graphicsItems.GradientEditorItem.Gradients['cubehelix2'] = {'mode':'rgb', 'ticks':[(p, tuple(c)) for c, p in zip(color,pos)]}
for k, v in pg.graphicsItems.GradientEditorItem.Gradients.items():
pg.graphicsItems.GradientEditorItem.Gradients[k]['ticks'] = [(1-p, c) for p, c in v['ticks']]
self.ui = Ui_plotwindow()
self.ui.setupUi(self)
self.invalidQuantumnumbers = [False, False, False, False]
self.samebasis_state = None
self.samebasis = False
self.systemdict = SystemDict(self.ui)
self.plotdict = PlotDict(self.ui)
self.systempath = os.getcwd()
self.plotpath = os.getcwd()
self.systemfile = None
self.plotfile = None
self.numprocessors = max(2,multiprocessing.cpu_count())
self.path_base = os.path.dirname(os.path.realpath(__file__))
self.path_workingdir = os.path.join(self.path_base,"../calc/")
self.path_cpp_real = os.path.join(self.path_base,"../calc/pairinteraction-real")
self.path_cpp_complex = os.path.join(self.path_base,"../calc/pairinteraction-complex")
if os.name == 'nt': self.path_out = os.path.join(os.path.expanduser('~user'), "pairinteraction/")
else: self.path_out = os.path.join(os.path.expanduser('~'), ".pairinteraction/")
self.path_system_last = os.path.join(self.path_out,"lastsystem.json")
self.path_plot_last = os.path.join(self.path_out,"lastplotter.json")
self.path_tabs_last = os.path.join(self.path_out,"lasttabs.json")
self.path_config = os.path.join(self.path_out,"conf.json")
self.proc = None
self.thread = Worker()
self.timer = QtCore.QTimer()
self.momentumcolors = [(55,126,184),(77,175,74),(228,26,28),(152,78,163),(0,0,0),(255//5,255//5,255//5)] # s, p, d, f, other, undetermined
self.symmetrycolors = [(0,0,0),(140,81,10),(1,102,94)] # all, sym, asym
self.momentummat = [None]*2
self.labelmat = [None]*2
self.labelstates = [None]*2
self.momentumstrings = [None]*2
self.buffer_basis = [{}]*2
self.buffer_energies = [{}]*2
self.buffer_positions = [{}]*2
self.buffer_boolarr = [{}]*2
self.buffer_basis_potential = {}
self.buffer_energies_potential = {}
self.buffer_positions_potential = {}
self.buffer_energiesMap = [{}]*2
self.buffer_positionsMap = [{}]*2
self.buffer_energiesMap_potential = {}
self.buffer_positionsMap_potential = {}
self.buffer_overlapMap_potential = {}
self.labelprob_potential = None
self.labelprob_num_potential = 0
self.lines_buffer_minIdx = {}
self.colormap_buffer_minIdx = 0
self.lines_buffer_minIdx_field = 0
#clrmp = pg.ColorMap(pos,color)
#self.lut = clrmp.getLookupTable()
self.ui.gradientwidget_plot_gradient.setOrientation("top")
self.ui.gradientwidget_plot_gradient.loadPreset('cubehelix1')
# TODOs
self.ui.lineedit_system_theta.setEnabled(False)
self.ui.lineedit_system_precision.setEnabled(False)
self.ui.pushbutton_field1_save.setEnabled(False)
self.ui.pushbutton_field2_save.setEnabled(False)
self.ui.pushbutton_potential_save.setEnabled(False)
self.ui.checkbox_system_dq.setEnabled(False)
self.ui.checkbox_system_qq.setEnabled(False)
# Create directories
if not os.path.exists(self.path_out):
os.makedirs(self.path_out)
if os.name == 'nt':
ret = ctypes.windll.kernel32.SetFileAttributesW(self.path_out,FILE_ATTRIBUTE_HIDDEN)
if not ret: raise ctypes.WinError()
# Set validators
validator_double = DoubleValidator()
validator_doublenone = DoublenoneValidator()
validator_doublepositive = DoublepositiveValidator()
validator_doubledelta = DoubledeltaValidator()
self.ui.lineedit_system_deltaESingle.setValidator(validator_doubledelta)
self.ui.lineedit_system_deltaEPair.setValidator(validator_doubledelta)
self.ui.lineedit_system_minEx.setValidator(validator_double)
self.ui.lineedit_system_minEy.setValidator(validator_double)
self.ui.lineedit_system_minEz.setValidator(validator_double)
self.ui.lineedit_system_maxEx.setValidator(validator_double)
self.ui.lineedit_system_maxEy.setValidator(validator_double)
self.ui.lineedit_system_maxEz.setValidator(validator_double)
self.ui.lineedit_system_minBx.setValidator(validator_double)
self.ui.lineedit_system_minBy.setValidator(validator_double)
self.ui.lineedit_system_minBz.setValidator(validator_double)
self.ui.lineedit_system_maxBx.setValidator(validator_double)
self.ui.lineedit_system_maxBy.setValidator(validator_double)
self.ui.lineedit_system_maxBz.setValidator(validator_double)
self.ui.lineedit_system_minR.setValidator(validator_doublepositive)
self.ui.lineedit_system_maxR.setValidator(validator_doublepositive)
self.ui.lineedit_system_theta.setValidator(validator_double)
self.ui.lineedit_system_precision.setValidator(validator_doublepositive)
self.ui.lineedit_field1_minE.setValidator(validator_doublenone)
self.ui.lineedit_field1_maxE.setValidator(validator_doublenone)
self.ui.lineedit_field2_minE.setValidator(validator_doublenone)
self.ui.lineedit_field2_maxE.setValidator(validator_doublenone)
self.ui.lineedit_potential_minE.setValidator(validator_doublenone)
self.ui.lineedit_potential_maxE.setValidator(validator_doublenone)
# Connect signals and slots
self.ui.spinbox_system_n1.valueChanged.connect(self.validateQuantumnumbers)
self.ui.spinbox_system_n2.valueChanged.connect(self.validateQuantumnumbers)
self.ui.spinbox_system_l1.valueChanged.connect(self.validateQuantumnumbers)
self.ui.spinbox_system_l2.valueChanged.connect(self.validateQuantumnumbers)
self.ui.spinbox_system_j1.valueChanged.connect(self.validateQuantumnumbers)
self.ui.spinbox_system_j2.valueChanged.connect(self.validateQuantumnumbers)
self.ui.spinbox_system_m1.valueChanged.connect(self.validateQuantumnumbers)
self.ui.spinbox_system_m2.valueChanged.connect(self.validateQuantumnumbers)
self.ui.spinbox_plot_n1.valueChanged.connect(self.validateQuantumnumbers)
self.ui.spinbox_plot_n2.valueChanged.connect(self.validateQuantumnumbers)
self.ui.spinbox_plot_l1.valueChanged.connect(self.validateQuantumnumbers)
self.ui.spinbox_plot_l2.valueChanged.connect(self.validateQuantumnumbers)
self.ui.spinbox_plot_j1.valueChanged.connect(self.validateQuantumnumbers)
self.ui.spinbox_plot_j2.valueChanged.connect(self.validateQuantumnumbers)
self.ui.spinbox_plot_m1.valueChanged.connect(self.validateQuantumnumbers)
self.ui.spinbox_plot_m2.valueChanged.connect(self.validateQuantumnumbers)
self.ui.spinbox_system_j1.editingFinished.connect(self.validateHalfinteger)
self.ui.spinbox_system_j2.editingFinished.connect(self.validateHalfinteger)
self.ui.spinbox_system_m1.editingFinished.connect(self.validateHalfinteger)
self.ui.spinbox_system_m2.editingFinished.connect(self.validateHalfinteger)
self.ui.spinbox_plot_j1.editingFinished.connect(self.validateHalfinteger)
self.ui.spinbox_plot_j2.editingFinished.connect(self.validateHalfinteger)
self.ui.spinbox_plot_m1.editingFinished.connect(self.validateHalfinteger)
self.ui.spinbox_plot_m2.editingFinished.connect(self.validateHalfinteger)
self.ui.combobox_system_species1.currentIndexChanged.connect(self.forbidSamebasis)
self.ui.combobox_system_species2.currentIndexChanged.connect(self.forbidSamebasis)
self.ui.radiobutton_system_pairbasisDefined.toggled.connect(self.togglePairbasis)
self.ui.radiobutton_plot_overlapDefined.toggled.connect(self.toggleOverlapstate)
self.ui.radiobutton_plot_log.toggled.connect(self.toggleYScale)
self.ui.checkbox_plot_antialiasing.toggled.connect(self.toggleAntialiasing)
self.ui.spinbox_system_deltaNSingle.valueChanged.connect(self.adjustPairlimits)
self.ui.spinbox_system_deltaLSingle.valueChanged.connect(self.adjustPairlimits)
self.ui.spinbox_system_deltaJSingle.valueChanged.connect(self.adjustPairlimits)
self.ui.spinbox_system_deltaMSingle.valueChanged.connect(self.adjustPairlimits)
self.ui.action_system_open.triggered.connect(self.openSystemConf)
self.ui.action_system_save.triggered.connect(self.saveSystemConf)
self.ui.action_plot_open.triggered.connect(self.openPlotConf)
self.ui.action_plot_save.triggered.connect(self.savePlotConf)
self.ui.action_quit.triggered.connect(self.close)
self.ui.action_whatsthis.triggered.connect(QtGui.QWhatsThis.enterWhatsThisMode)
self.ui.pushbutton_field1_calc.clicked.connect(self.startCalc)
self.ui.pushbutton_field2_calc.clicked.connect(self.startCalc)
self.ui.pushbutton_potential_calc.clicked.connect(self.startCalc)
self.timer.timeout.connect(self.checkForData)
# Load last settings
try: # TODO
if os.path.isfile(self.path_system_last):
with open(self.path_system_last, 'r') as f:
params = json.load(f)
self.systemdict.load(params)
except:
pass
try:
if os.path.isfile(self.path_plot_last):
with open(self.path_plot_last, 'r') as f:
params = json.load(f)
self.ui.gradientwidget_plot_gradient.restoreState(params["gradientwidget"])
del params["gradientwidget"]
self.plotdict.load(params)
except:
pass
try:
if os.path.isfile(self.path_tabs_last):
with open(self.path_tabs_last, 'r') as f:
params = json.load(f)
self.ui.tabwidget_config.setCurrentIndex(params["config"])
self.ui.tabwidget_plotter.setCurrentIndex(params["plotter"])
self.ui.toolbox_system.setCurrentIndex(params["system"])
except:
pass
# Emit change-signals in order to let the validation run
self.ui.spinbox_system_n1.valueChanged.emit(self.ui.spinbox_system_n1.value())
self.ui.spinbox_system_n2.valueChanged.emit(self.ui.spinbox_system_n2.value())
self.ui.spinbox_plot_n1.valueChanged.emit(self.ui.spinbox_plot_n1.value())
self.ui.spinbox_plot_n2.valueChanged.emit(self.ui.spinbox_plot_n2.value())
self.ui.spinbox_system_j1.editingFinished.emit()
self.ui.spinbox_system_j2.editingFinished.emit()
self.ui.spinbox_system_m1.editingFinished.emit()
self.ui.spinbox_system_m2.editingFinished.emit()
self.ui.spinbox_plot_j1.editingFinished.emit()
self.ui.spinbox_plot_j2.editingFinished.emit()
self.ui.spinbox_plot_m1.editingFinished.emit()
self.ui.spinbox_plot_m2.editingFinished.emit()
self.ui.combobox_system_species1.currentIndexChanged.emit(self.ui.combobox_system_species1.currentIndex())
self.ui.radiobutton_system_pairbasisDefined.toggled.emit(self.ui.radiobutton_system_pairbasisDefined.isChecked())
self.ui.radiobutton_plot_overlapDefined.toggled.emit(self.ui.radiobutton_plot_overlapDefined.isChecked())
self.ui.radiobutton_plot_log.toggled.emit(self.ui.radiobutton_plot_log.isChecked())
self.ui.checkbox_plot_antialiasing.toggled.emit(self.ui.checkbox_plot_antialiasing.isChecked())
self.ui.spinbox_system_deltaNSingle.valueChanged.emit(self.ui.spinbox_system_deltaNSingle.value())
self.ui.spinbox_system_deltaLSingle.valueChanged.emit(self.ui.spinbox_system_deltaLSingle.value())
self.ui.spinbox_system_deltaJSingle.valueChanged.emit(self.ui.spinbox_system_deltaJSingle.value())
self.ui.spinbox_system_deltaMSingle.valueChanged.emit(self.ui.spinbox_system_deltaMSingle.value())
# Setup plot
self.minE_field1 = None
self.minE_field2 = None
self.minE_potential = None
self.maxE_field1 = None
self.maxE_field2 = None
self.maxE_potential = None
self.constDistance = self.getConstDistance()
self.constEField = self.getConstEField()
self.constBField = self.getConstBField()
#self.sameSpecies = self.getSameSpecies()
for plotarea in [self.ui.graphicsview_field1_plot, self.ui.graphicsview_field2_plot, self.ui.graphicsview_potential_plot]:
plotarea.setDownsampling(ds=True, auto=True, mode='peak')
plotarea.setClipToView(True)
plotarea.setLabel('left', 'Energy ('+str(Units.energy)+')')
if self.constEField and not self.constBField:
for plotarea in [self.ui.graphicsview_field1_plot, self.ui.graphicsview_field2_plot]: plotarea.setLabel('bottom', 'Magnetic field ('+str(Units.bfield)+')')
else:
for plotarea in [self.ui.graphicsview_field1_plot, self.ui.graphicsview_field2_plot]: plotarea.setLabel('bottom', 'Electric field ('+str(Units.efield)+')')
if self.constDistance and not self.constEField:
self.ui.graphicsview_potential_plot.setLabel('bottom', 'Electric field ('+str(Units.efield)+')')
elif self.constDistance and not self.constBField:
self.ui.graphicsview_potential_plot.setLabel('bottom', 'Magnetic field ('+str(Units.bfield)+')')
else:
self.ui.graphicsview_potential_plot.setLabel('bottom', 'Interatomic distance ('+str(Units.length)+')')
def resizeEvent(self, event):
super().resizeEvent(event)
if sys.platform == "darwin": QtGui.QApplication.processEvents() # hack to circumvent the no-redraw-after-resizing-bug
def get1DPosition(self, x, y, z):
vec = np.array([x,y,z])
return np.sign(np.vdot(vec,[1,1,1]))*np.linalg.norm(vec)
def getConstEField(self):
minVec = np.array([self.systemdict['minEx'].magnitude,self.systemdict['minEy'].magnitude,self.systemdict['minEz'].magnitude])
maxVec = np.array([self.systemdict['maxEx'].magnitude,self.systemdict['maxEy'].magnitude,self.systemdict['maxEz'].magnitude])
return np.all(minVec==maxVec)
def getConstBField(self):
minVec = np.array([self.systemdict['minBx'].magnitude,self.systemdict['minBy'].magnitude,self.systemdict['minBz'].magnitude])
maxVec = np.array([self.systemdict['maxBx'].magnitude,self.systemdict['maxBy'].magnitude,self.systemdict['maxBz'].magnitude])
return np.all(minVec==maxVec)
def getConstDistance(self):
minR = self.systemdict['minR'].magnitude # TODO
maxR = self.systemdict['maxR'].magnitude # TODO
return minR == maxR
#def getSameSpecies(self):
# return self.systemdict['species1'] == self.systemdict['species2']
def abortCalculation(self):
# kill c++ process - this terminates the self.thread, too
if self.proc is not None: self.proc.kill()
# wait until self.thread has finished
self.thread.wait()
# clear queues
self.thread.clear()
def checkForData(self):
dataamount = 0
# === print status ===
elapsedtime = "{}".format(timedelta(seconds=int(time()-self.starttime)))
if self.thread.message != "":
self.ui.statusbar.showMessage(self.thread.message+", elapsed time "+elapsedtime)
else:
self.ui.statusbar.showMessage("Elapsed time "+elapsedtime)
# === check if memory consumption is to high ===
if psutil.virtual_memory().percent > 99: # TODO: is the virtual or swap memory the problem on rqo-donkey?
self.abortCalculation()
QtGui.QMessageBox.critical(self, "Message", "The program has run out of memory.")
# === process potential map ===
# --- load basis states ---
if self.thread.basisfile_potential != "":
# load basis
basis = np.loadtxt(self.thread.basisfile_potential)
if self.ui.groupbox_plot_overlap.isChecked():
self.stateidx_potential = np.where(np.all(basis[:,[1,2,3,4,5,6,7,8]] == self.overlapstate[None,:],axis=-1))[0]
if len(self.stateidx_potential) == 0: self.stateidx_potential = -1
else: self.stateidx_potential = self.stateidx_potential[0]
self.displayunits2pixelunits_x = np.nan
self.displayunits2pixelunits_y = np.nan
# extract labels
nlj = basis[:,[1,2,3,5,6,7]]
# sort pair state names
if self.thread.samebasis:
firstsmaller = np.argmax(np.append(nlj[:,0:3] < nlj[:,3:6],np.ones((len(nlj),1),dtype=bool),axis=-1),axis=-1) # TODO in Funktion auslagern
firstsmaller_reverted = np.argmax(np.append(nlj[:,3:6] < nlj[:,0:3],np.ones((len(nlj),1),dtype=bool),axis=-1),axis=-1) # TODO in Funktion auslagern
namesToSwap = firstsmaller > firstsmaller_reverted
nlj[namesToSwap] = nlj[namesToSwap][:,[3,4,5,0,1,2]]
sorter = np.lexsort(nlj.T[::-1])
nlj = nlj[sorter]