-
Notifications
You must be signed in to change notification settings - Fork 2
/
GUI.py
3184 lines (2638 loc) · 126 KB
/
GUI.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 python
# -*- coding: utf-8 -*-
#
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
import numpy as np
import temCalcs as tc
sp = QSizePolicy()
sp.setRetainSizeWhenHidden(True)
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = "ALPHABETA v0.01 BETA"
#self.left = 50
#self.top = 50
#self.width = 640
#self.height = 400
self.setWindowTitle(self.title)
#self.setGeometry(self.left, self.top, self.width, self.height)
self.setWindowIcon(QIcon('./Images/logo.png'))
layout = QVBoxLayout()
layout.setSpacing(0)
marg = 0
layout.setContentsMargins(marg, marg, marg, marg)
###########The loading and saving menu#########
self.loadsavemenu = loadMenu(self)
layout.addWidget(self.loadsavemenu)
###########The microscopes menu#################
self.microscopemenu = microscopeMenu(self)
layout.addWidget(self.microscopemenu)
###########The strucutres menu##################
self.structuremenu = structuresMenu(self)
layout.addWidget(self.structuremenu)
###The crystals menu#########
self.crystalmenu = crystalMenu(self)
layout.addWidget(self.crystalmenu)
####The calculation menu#########
self.calcmenu = calculationMenu(self)
layout.addWidget(self.calcmenu)
####The plotting menu#########
self.plotmenu = plottingMenu(self)
layout.addWidget(self.plotmenu)
layout.setSizeConstraint(layout.SetFixedSize)
wd = QWidget()
wd.setLayout(layout)
self.setCentralWidget(wd)
#autoload
self.loadsavemenu.autoload()
#show the window
self.show()
def updateGUI(self):
self.microscopemenu.updateAll()
self.structuremenu.updateAll()
self.crystalmenu.updateAll()
def updateCrystals(self):
self.crystalmenu.updateAll()
def getCurrentTEM(self):
return self.microscopemenu.currentTEM()
def getCurrentDetector(self):
return self.microscopemenu.currentDetector()
def getCurrentStage(self):
return self.microscopemenu.currentStage()
def getAlpha(self):
return self.microscopemenu.getAlpha()
def getBeta(self):
return self.microscopemenu.getBeta()
def getMode(self):
return self.microscopemenu.getMode()
def getSetting(self):
return self.microscopemenu.getSetting()
def getTheta(self):
return self.microscopemenu.getTheta()
def getCurrentStructure(self):
return self.structuremenu.currentStruc()
def getCurrentCrystal(self):
return self.crystalmenu.currentCrystal()
class loadMenu(QWidget):
def __init__(self, caller):
super().__init__()
self.caller = caller
self.mainbox = QGroupBox("Load/Save")
mainlayout = QGridLayout()
mainlayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
size = [24, 24]
self.loadbutton = QPushButton("")
self.loadbutton.setToolTip("Load configuration")
self.loadbutton.setIcon(QIcon(".\Images\load.png"))
self.loadbutton.clicked.connect(self.load)
self.loadbutton.resize(size[0]+6, size[1]+6)
self.loadbutton.setIconSize(QSize(size[0],size[1]))
self.loadbutton.setSizePolicy(sp)
mainlayout.addWidget(self.loadbutton, 1, 0)
self.savebutton = QPushButton("")
self.savebutton.setToolTip("Save configuration")
self.savebutton.setIcon(QIcon(".\Images\save.png"))
self.savebutton.clicked.connect(self.save)
self.savebutton.resize(size[0]+6, size[1]+6)
self.savebutton.setIconSize(QSize(size[0],size[1]))
self.savebutton.setSizePolicy(sp)
mainlayout.addWidget(self.savebutton, 1, 1)
self.trashbutton = QPushButton("")
self.trashbutton.setToolTip("Clear the session")
self.trashbutton.setIcon(QIcon(".\Images\poubelle.png"))
self.trashbutton.clicked.connect(self.trash)
self.trashbutton.resize(size[0]+6, size[1]+6)
self.trashbutton.setIconSize(QSize(size[0],size[1]))
self.trashbutton.setSizePolicy(sp)
mainlayout.addWidget(self.trashbutton, 1, 2)
self.mainbox.setLayout(mainlayout)
Layout = QVBoxLayout()
Layout.addWidget(self.mainbox)
#mainLayout.addWidget(self.buttonBox)
self.setLayout(Layout)
#show the window
self.show()
def trash(self):
if self.checkEvent("Are you sure you want to clear everything in the session?"):
tc.clearSession()
self.caller.updateGUI()
def checkEvent(self, msg = "Are you sure?"):
reply = QMessageBox.question(self, ' ', msg, QMessageBox.Yes, QMessageBox.No)
if reply == QMessageBox.Yes:
return True
else:
return False
def load(self):
filename, okpres = QFileDialog.getOpenFileName(caption = "Load previous session", filter = "Text files (*txt)")
if okpres:
tc.clearSession()
tc.loadSession(filename)
self.caller.updateGUI()
def autoload(self):
#autoload the autoload.txt file if it exists
try:
tc.loadSession("autoload.txt")
self.caller.updateGUI()
except:
pass
def testload(self):
tc.clearSession()
tc.addStructure(name="Steel", a=3.66, b=3.66, c=3.66, alpha=90, beta=90, gamma=90)
mic = tc.addMicroscope(name = "Jeol3000", kv=300)
stag = mic.addStage(name = "Doubletilt", alpha = 20, beta = 10, alphamin = -29, alphamax = 31, betamin = -21, betamax = 22, alpharev = True, betarev = False)
ccd = mic.addDetector(name="MSC")
ccd.setCalibration("rotationCalibrationMSC-IMG.txt", mode = "imaging", type = "r")
ccd.setCalibration("rotationCalibrationMSC-DIFF.txt", mode = "diffraction", type = "r")
crl = stag.addCrystal("Steel", name = "grain1")
crl.calcOrient(tc.miller(1, 1, 0), tc.miller(1, -1, 1), -30, "MSC", "d", 30)
self.caller.updateGUI()
def save(self):
filname, okpress = QFileDialog.getSaveFileName(caption = "Save session", filter = "Text files (*txt)")
#check that filname ends in txt
if okpress:
tc.saveSession(filname)
class microscopeMenu(QWidget):
def __init__(self, caller):
###########The microscopes menu#################
super().__init__()
##make a grouping box
self.formInstrumentGroupBox = QGroupBox("Instrument settings")
#caller is the app that calls it
self.caller = caller
#inside the grouping box have a grid layout
temlayout = QGridLayout()
temlayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
temlayout.setSpacing(10)
#labels - never hide labels
self.mcrlbl = QLabel("Microscope")
self.mcrlbl.setToolTip("Transmission electron microscopes.")
temlayout.addWidget(self.mcrlbl, 1, 0)
self.stlbl = QLabel("Stage")
self.stlbl.setToolTip("Double tilt stages on the current microscope.\nA microscope is prerequisite to adding and editing stages.")
temlayout.addWidget(self.stlbl, 2, 0)
self.dtlbl = QLabel("Detector")
self.dtlbl.setToolTip("Detectors on the current microscope.\nA microscope is prerequisite to adding and editing detectors.")
temlayout.addWidget(self.dtlbl, 3, 0)
self.vtlbl = QLabel("Voltage")
self.vtlbl.setToolTip("High tension of the current microscope.\nA microscope is prerequisite to changing these settings.")
temlayout.addWidget(self.vtlbl, 1, 5)
self.allbl = QLabel(u"\u03b1")
self.allbl.setToolTip("\u03b1 tilt angle setting of the current stage.\nA stage is prerequisite to changing these settings.")
temlayout.addWidget(self.allbl, 2, 5) #alpha
self.btlbl = QLabel(u"\u03b2")
self.btlbl.setToolTip("\u03b2 tilt angle setting of the current stage.\nA stage is prerequisite to changing these settings.")
temlayout.addWidget(self.btlbl, 2, 7) #beta
self.mdlbl = QLabel("Mode")
self.mdlbl.setToolTip("Current imaging mode of the microscope.\nA detector is a prerequisite to changing these settings.")
temlayout.addWidget(self.mdlbl, 3, 5)
self.mglbl = QLabel("Mag/CL") #this one must be updated when mode is changed
self.mglbl.setToolTip("Current magnification or camera length setting.\nA detector calibration is a prerequisite to changing these settings.")
temlayout.addWidget(self.mglbl, 4, 5)
self.ttlbl = QLabel(u"\u03b8")
self.ttlbl.setToolTip("The angle the \u03b1-axis makes with the detector x-axis.\nA detector calibration is a prerequisite to changing these settings.")
temlayout.addWidget(self.ttlbl, 4, 7)
#add the microscopes dropdown list
xbut = 50
ybut = 50
self.temlist = self.combobox(list(tc.microscopes.keys()), pos = [xbut, ybut], action = self.updateAll)
temlayout.addWidget(self.temlist, 1, 1)
#add microscope add, edit and delete buttons
self.adtembut = self.button(logo=".\Images\plus.png", hint = "Add new microscope", position = [xbut+100, ybut], action = self.createMicroscope)
self.edittembut = self.button(logo = ".\Images\edit.png", hint = "Edit microscope", position = [xbut+130, ybut], action = self.editMicroscope)
self.deltembut = self.button(logo=".\Images\delete-icon.png", hint = "Delete microscope", position = [xbut+160, ybut], action = self.deleteMicroscope)
temlayout.addWidget(self.adtembut, 1, 2)
temlayout.addWidget(self.edittembut, 1, 3)
temlayout.addWidget(self.deltembut, 1, 4)
#add the kv box. Update done automatically.
self.kvbox = QSpinBox(self)
self.kvbox.setRange(1, 10000)
self.kvbox.setSingleStep(10)
#self.kvbox.move(xbut + 260, ybut)
self.kvbox.setSuffix(" kV")
self.kvbox.valueChanged[int].connect(self.updateVoltage)
self.kvbox.setSizePolicy(sp)
temlayout.addWidget(self.kvbox, 1, 6)
#the ewald sphere radius. The angle must be added later when you update the field
self.eslbl = QLabel(u"K0")
self.eslbl.setToolTip("The radius of the Ewald sphere\n1/electron wavelength")
temlayout.addWidget(self.eslbl, 1, 7)
self.k0view = QLineEdit(self)
self.k0view.setReadOnly(True)
self.k0view.setSizePolicy(sp)
temlayout.addWidget(self.k0view, 1, 8)
######The stage menu#################
#add the stage dropdown list
yoffset = 50
self.stagelist = self.combobox([], pos = [xbut, ybut+yoffset], action = self.updateStages)
temlayout.addWidget(self.stagelist, 2, 1)
dec = 2
#add boxes for alpha and beta
self.alphabox = QDoubleSpinBox(self)
self.alphabox.setDecimals(dec)
self.alphabox.setSingleStep(10**(-dec))
#maxima should only be updated once a stage actually exists
self.alphabox.setMaximum(90)
self.alphabox.setMinimum(-90)
#self.alphabox.setValue(alpha)
self.alphabox.setSuffix(u" \u00b0")
self.alphabox.valueChanged.connect(self.updateAlpha)
self.alphabox.setSizePolicy(sp)
temlayout.addWidget(self.alphabox, 2, 6)
self.betabox = QDoubleSpinBox(self)
self.betabox.setDecimals(dec)
self.betabox.setSingleStep(10**(-dec))
self.betabox.setMaximum(90)
self.betabox.setMinimum(-90)
self.betabox.setSuffix(u" \u00b0")
self.betabox.valueChanged.connect(self.updateBeta)
self.betabox.setSizePolicy(sp)
temlayout.addWidget(self.betabox, 2, 8)
#add the stage add and delete buttongs
self.adstagbut = self.button(logo=".\Images\plus.png", hint = "Add new stage", position = [xbut+100, ybut+yoffset], action = self.createStage)
self.editstagbut = self.button(logo = ".\Images\edit.png", hint = "Edit stage", position = [xbut+130, ybut+yoffset], action = self.editStage)
self.delstagbut = self.button(logo=".\Images\delete-icon.png", hint = "Delete stage", position = [xbut+160, ybut+yoffset], action = self.deleteStage)
temlayout.addWidget(self.adstagbut, 2, 2)
temlayout.addWidget(self.editstagbut, 2, 3)
temlayout.addWidget(self.delstagbut, 2, 4)
######The detector menu#########
self.detectorlist = self.combobox([], action = self.updateDetectors)
temlayout.addWidget(self.detectorlist, 3, 1)
self.addetbut = self.button(logo=".\Images\plus.png", hint = "Add new detector", action = self.createDetector)
self.editdetbut = self.button(logo = ".\Images\edit.png", hint = "Edit detector", action = self.editDetector)
self.deldetbut = self.button(logo=".\Images\delete-icon.png", hint = "Delete detector", action = self.deleteDetector)
temlayout.addWidget(self.addetbut, 3, 2)
temlayout.addWidget(self.editdetbut, 3, 3)
temlayout.addWidget(self.deldetbut, 3, 4)
#the mode dropdown button
self.imgmode = self.combobox(["Diffraction", "Imaging", "STEM"], action = self.updateMagoptions)
temlayout.addWidget(self.imgmode, 3, 6)
#the load calibration button
self.loadcalib = self.button(logo = ".\Images\impo.png", hint = "Load calibration file", action = self.addCalibration)
temlayout.addWidget(self.loadcalib, 3, 8)
#the mag/cl dropdown
self.magcl = self.combobox([], action = self.updateTheta)
temlayout.addWidget(self.magcl, 4, 6)
#the theta view box. The angle must be added later when you update the field
self.thetaview = QLineEdit(self)
self.thetaview.setReadOnly(True)
self.thetaview.setSizePolicy(sp)
temlayout.addWidget(self.thetaview, 4, 8)
####set the layout of the microscope control box
self.formInstrumentGroupBox.setLayout(temlayout)
self.updatebuttons()
mainLayout = QVBoxLayout()
mainLayout.addWidget(self.formInstrumentGroupBox)
#mainLayout.addWidget(self.buttonBox)
self.setLayout(mainLayout)
#show the window
self.show()
def getAlpha(self):
return self.alphabox.value()
def getBeta(self):
return self.betabox.value()
def getMode(self):
return self.imgmode.currentText()
def getSetting(self):
return self.magcl.currentText()
def getTheta(self):
return self.thetaview.currentText()
def button(self, text ="" , logo = "", hint = "", position = [0,0], size = [24, 24], action = None):
if action is None:
action = self.nothingHappens
button = QPushButton(text, self)
button.setToolTip(hint)
#button.move(position[0], position[1])
button.setIcon(QIcon(logo))
button.clicked.connect(action)
button.resize(size[0]+6, size[1]+6)
button.setIconSize(QSize(size[0],size[1]))
button.setSizePolicy(sp)
return button
def combobox(self, lst, pos = [0,0], action = None):
"""combobox creates a drop down list from a list of strings lst at position [x, y]. When one option is active an action is performed."""
if action is None:
action = self.nothingHappens
combobx = QComboBox(self)
combobx.addItems(lst)
#combobx.move(pos[0], pos[1])
combobx.activated[str].connect(action)
combobx.setSizePolicy(sp)
return combobx
def nothingHappens(self):
pass
def createMicroscope(self):
res, okPressed = microscopeDialog.getInfo()
#print(res)
#print(ok)
#text, okPressed = QInputDialog.getText(self, "New microscope","Microscope name:", QLineEdit.Normal, "")
#d, okPressed = QInputDialog.getDouble(self, "New microscope","Operating voltage (kV):", 300)
if okPressed:
#need to check if that name doesn't already exist or the TEM will overwrite items
if res[0] not in tc.microscopes:
newtem = tc.addMicroscope(name = res[0], kv = res[1])
self.updateAll(focus = newtem.name)
else:
QMessageBox.warning(self, " ", "A microscope by this name already exists. Please choose another name.")
def editMicroscope(self):
res, okPressed = microscopeDialog.getInfo(windowtitle = "Edit microscope", name = self.currentTEM().name, voltage = self.currentTEM().getKv())
if okPressed:
#if the name is nothing or it already exists, keep old name
if res[0]=="" or res[0] in tc.microscopes:
res[0] = self.currentTEM().name
self.currentTEM().setKv(res[1])
self.currentTEM().setName(res[0]) #must update name last if you don't want to store current TEM in a temp variable
self.updateAll(focus = res[0])
def deleteMicroscope(self):
nt = self.currentTEM().name
check = self.checkEvent(msg = "Are you sure you want to delete %s?" %(nt))
if check:
tc.removeMicroscope(nt)
self.updateAll()
def createStage(self):
res, okPressed = stageDialog.getInfo()
if okPressed:
#need to check if that name doesn't already exist or it will be overwritten
if res[0] not in self.currentTEM().stages:
newstage = self.currentTEM().addStage(name = res[0], alpha = res[3], beta = res[6], alphamin = res[1], alphamax = res[2], betamin = res[4], betamax = res[5], alpharev = res[7], betarev = res[8])
self.updateStages(focus = newstage.name)
else:
QMessageBox.warning(self, " ", "A stage by this name already exists. Please choose another name.")
def editStage(self):
res, okPressed = stageDialog.getInfo(windowtitle = "Edit stage", name = self.currentStage().name, alpha = self.currentStage().getAlpha(), beta = self.currentStage().getBeta(), alphamin = self.currentStage().getAlphaMin(), alphamax = self.currentStage().getAlphaMax(), betamin = self.currentStage().getBetaMin(), betamax = self.currentStage().getBetaMax(), alpharev = self.currentStage().alpharev, betarev = self.currentStage().betarev )
if okPressed:
#if the name is nothing or already exists in the list keep the name
if res[0]=="" or res[0] in self.currentTEM().stages:
res[0] = self.currentStage().name
self.currentStage().setAlphaRange(res[1], res[2])
self.currentStage().setBetaRange(res[4], res[5])
self.currentStage().setAlpha(res[3])
self.currentStage().setBeta(res[6])
self.currentStage().setRev(res[7], res[8])
self.currentStage().setName(res[0]) #must change name last
self.updateStages(focus = res[0])
def deleteStage(self):
nt = self.currentStage().name
check = self.checkEvent(msg = "Are you sure you want to delete %s?" %(nt))
if check:
self.currentTEM().removeStage(nt)
self.updateStages()
def createDetector(self):
#res, okPressed = detectorDialog.getInfo()
res, okPressed = detectorDialog.getInfo()
if okPressed:
#need to check if that name doesn't already exist or it will be overwritten
if res[0] not in self.currentTEM().detectors:
newdet = self.currentTEM().addDetector(name = res[0])
self.updateDetectors(focus = newdet.name)
else:
QMessageBox.warning(self, " ", "A detector by this name already exists. Please choose another name.")
def editDetector(self):
res, okPressed = detectorDialog.getInfo(windowtitle = "Edit stage", name = self.currentDetector().name)
if okPressed:
#if the name is nothing or already exists in the list keep the name
if res[0]=="" or res[0] in self.currentTEM().detectors:
res[0] = self.currentDetector().name
self.currentDetector().setName(res[0]) #must change name last
self.updateDetectors(focus = res[0])
def deleteDetector(self):
nt = self.currentDetector().name
check = self.checkEvent(msg = "Are you sure you want to delete %s?" %(nt))
if check:
self.currentTEM().removeDetector(nt)
self.updateDetectors()
def updateVoltage(self, value):
try:
self.currentTEM().setKv(value)
self.updateK0()
except:
pass
def updateAlpha(self):
#if the alpha and beta box are visible it means a stage must be present
currentstage = self.currentStage()
currentstage.setAlpha(self.alphabox.value())
def updateBeta(self):
currentstage = self.currentStage()
currentstage.setBeta(self.betabox.value())
def addCalibration(self):
filename, okpress = QFileDialog.getOpenFileName(caption = "Open calibration file", filter = "Text files (*txt)")
if filename != "" and okpress:
currentdetector = self.currentDetector()
mod = self.imgmode.currentText()
if mod == "Diffraction":
mod = "diffraction"
if mod == "STEM":
mod = "stem"
if mod == "Imaging":
mod = "imaging"
try:
currentdetector.setCalibration(filename, mode = mod)
self.updateMagoptions()
self.updatebuttons()
except:
QMessageBox.warning(self, " ", "That does not appear to be a valid calibration file.")
def updateMagoptions(self):
mod = self.imgmode.currentText()
self.magcl.clear()
try:
opts = self.currentDetector().getMags(mod)
opts = list(map(int, opts))
opts = list(map(str, opts))
#update the Mag dropdown list
#print(opts)
self.magcl.addItems(opts)
except:
pass
self.updateTheta()
#we should also update the crystals
self.caller.updateCrystals()
def updateTheta(self):
try:
mod = self.imgmode.currentText()
if mod == "Diffraction":
mod = "diffraction"
if mod == "STEM":
mod = "stem"
if mod == "Imaging":
mod = "imaging"
set = self.magcl.currentText()
val = self.currentDetector().getRot(mod, float(set))
self.thetaview.setText(str(val) + u" \u00b0")
except: #if no mag data can be found
self.thetaview.setText("")
def updateK0(self):
try:
self.k0view.setText(u"%s 1/\u212B" %(round(self.currentTEM().getEwaldR(units = "angstrom"), 2)))
except:
#when the current TEM is none
self.k0view.setText("")
def currentTEM(self):
if tc.microscopes:
return tc.getMicroscope(self.temlist.currentText())
else:
return None
def currentStage(self):
if tc.microscopes:
#check that stages aren't empty
if self.currentTEM().stages:
return self.currentTEM().getStage(self.stagelist.currentText())
else:
return None
else:
return None
def currentDetector(self):
if tc.microscopes:
#check that detectors aren't empty
if self.currentTEM().detectors:
return self.currentTEM().getDetector(self.detectorlist.currentText())
else:
return None
else:
return None
def checkEvent(self, msg = "Are you sure?"):
reply = QMessageBox.question(self, ' ', msg, QMessageBox.Yes, QMessageBox.No)
if reply == QMessageBox.Yes:
return True
else:
return False
def updateAll(self, **kwargs):
self.updateTEMlist(**kwargs)
self.updateStagelist()
self.updateDetectorlist()
self.updateMagoptions()
self.updatebuttons()
#the crystals are somewhat dependent on this so we call it here
self.caller.updateCrystals()
def updateStages(self, **kwargs):
self.updateStagelist(**kwargs)
self.updatebuttons()
#the crystals are somewhat dependent on this so we call it here
self.caller.updateCrystals()
def updateDetectors(self, **kwargs):
self.updateDetectorlist(**kwargs)
self.updateMagoptions()
self.updatebuttons()
#the crystals are somewhat dependent on this so we call it here
self.caller.updateCrystals()
def updateTEMlist(self, focus = None):
#save whichever name was active
currentstrucname = ""
if focus is None:
try:
currentstrucname = self.currentTEM().name
except:
pass
else:
currentstrucname = focus
#update the TEM dropdown list
self.temlist.clear()
self.temlist.addItems(list(tc.microscopes.keys()))
#set the TEM again that was active before if possible
#first find the index of the current TEM
try:
index = self.temlist.findText(currentstrucname, Qt.MatchFixedString)
if index>=0:
self.temlist.setCurrentIndex(index)
except:
pass
def updateStagelist(self, focus = None):
#save whichever was active
currentdetectorname = ""
if focus is None:
try:
currentdetectorname = self.currentStage().name
except:
pass
else:
currentdetectorname = focus
#update the stage dropdown list
self.stagelist.clear()
#the stages are only those stages that belong to the current TEM, if there is a current TEM
try:
self.stagelist.addItems(list(self.currentTEM().stages.keys()))
except:
#no TEM exists
pass
#set the stage again that was active before if possible
#first find the index of the current stage
try:
index = self.stagelist.findText(currentdetectorname, Qt.MatchFixedString)
if index>=0:
self.stagelist.setCurrentIndex(index)
except:
pass
def updateDetectorlist(self, focus = None):
#save whichever was active
currentdetectorname = ""
if focus is None:
try:
currentdetectorname = self.currentDetector().name
except:
pass
else:
currentdetectorname = focus
#update the stage dropdown list
self.detectorlist.clear()
#the stages are only those stages that belong to the current TEM, if there is a current TEM
try:
self.detectorlist.addItems(list(self.currentTEM().detectors.keys()))
except:
#no TEM exists
pass
#set the stage again that was active before if possible
#first find the index of the current stage
try:
index = self.detectorlist.findText(currentdetectorname, Qt.MatchFixedString)
if index>=0:
self.detectorlist.setCurrentIndex(index)
except:
pass
def updatebuttons(self):
#Hide certain features if the list of microscopes is empty
if not tc.microscopes:
#microscope buttons
self.edittembut.hide()
self.deltembut.hide()
self.kvbox.hide()
self.k0view.hide()
#stage buttons
self.stagelist.hide()
self.adstagbut.hide()
self.editstagbut.hide()
self.delstagbut.hide()
#the alpha and beta boxes are hidden
self.alphabox.hide()
self.betabox.hide()
#the detector buttons
self.detectorlist.hide()
self.addetbut.hide()
self.editdetbut.hide()
self.deldetbut.hide()
#detector calibration buttons
self.loadcalib.hide()
self.imgmode.hide()
self.thetaview.hide()
self.magcl.hide()
else: #there is a microscope
self.edittembut.show()
self.deltembut.show()
self.kvbox.show()
self.k0view.show()
#update the kV box
self.kvbox.setValue(self.currentTEM().getKv())
self.updateK0()
#stage buttons
self.stagelist.show()
self.adstagbut.show()
#detector buttons
self.detectorlist.show()
self.addetbut.show()
#check if there are stages
if self.currentTEM().stages:
self.editstagbut.show()
self.delstagbut.show()
#update alpha and beta boxes and their max and mins. First set maxes otherwise below zero doesn't work.
self.alphabox.setMaximum(self.currentStage().getAlphaMax())
self.alphabox.setMinimum(self.currentStage().getAlphaMin())
self.alphabox.setValue(self.currentStage().getAlpha())
self.betabox.setMaximum(self.currentStage().getBetaMax())
self.betabox.setMinimum(self.currentStage().getBetaMin())
self.betabox.setValue(self.currentStage().getBeta())
self.alphabox.show()
self.betabox.show()
else:
self.editstagbut.hide()
self.delstagbut.hide()
self.alphabox.hide()
self.betabox.hide()
#check if there are detectors
if self.currentTEM().detectors:
self.editdetbut.show()
self.deldetbut.show()
self.loadcalib.show()
self.imgmode.show()
#check if there is a relevant calibration file
if self.currentDetector().getCalibration(self.imgmode.currentText()):
self.thetaview.show()
self.magcl.show()
else:
self.thetaview.hide()
self.magcl.hide()
else:
self.editdetbut.hide()
self.deldetbut.hide()
self.loadcalib.hide()
self.imgmode.hide()
self.thetaview.hide()
self.magcl.hide()
class structuresMenu(QWidget):
def __init__(self, caller):
###########The structures menu#################
super().__init__()
##make a grouping box
self.formGroupBox = QGroupBox("Crystallography")
#caller is the thing that calls this menu#########
self.caller = caller
#inside the grouping box have a grid layout
layout = QGridLayout()
layout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
layout.setSpacing(10)
#scrollable list of structures
self.strclbl = QLabel("Structure")
self.strclbl.setToolTip("Crystal structures serving as templates to Crystals/Grains objects.")
layout.addWidget(self.strclbl, 1, 0)
#structures
self.struclist = self.combobox(list(tc.structures.keys()), action = self.doNothing)
layout.addWidget(self.struclist, 1, 1)
#buttons
self.adstrucbut = self.button(logo=".\Images\plus.png", hint = "Add new structure", action = self.createStructure)
self.editstrucbut = self.button(logo = ".\Images\edit.png", hint = "Edit structure", action = self.editStructure)
self.delstrucbut = self.button(logo=".\Images\delete-icon.png", hint = "Delete structure", action = self.deleteStructure)
self.calcbut = self.button(logo=".\Images\wizard.png", hint = "Indexing wizard", action = self.showWizard)
layout.addWidget(self.adstrucbut, 1, 2)
layout.addWidget(self.editstrucbut, 1, 3)
layout.addWidget(self.delstrucbut, 1, 4)
layout.addWidget(self.calcbut, 1, 5)
####set the layout of the microscope control box
self.formGroupBox.setLayout(layout)
self.updateButtons()
mainLayout = QVBoxLayout()
mainLayout.addWidget(self.formGroupBox)
#mainLayout.addWidget(self.buttonBox)
self.setLayout(mainLayout)
#show the window
self.show()
def checkEvent(self, msg = "Are you sure?"):
reply = QMessageBox.question(self, ' ', msg, QMessageBox.Yes, QMessageBox.No)
if reply == QMessageBox.Yes:
return True
else:
return False
def button(self, text ="" , logo = "", hint = "", position = [0,0], size = [24, 24], action = None):
if action is None:
action = self.nothingHappens
button = QPushButton(text, self)
button.setToolTip(hint)
#button.move(position[0], position[1])
button.setIcon(QIcon(logo))
button.clicked.connect(action)
button.resize(size[0]+6, size[1]+6)
button.setIconSize(QSize(size[0],size[1]))
button.setSizePolicy(sp)
return button
def combobox(self, lst, pos = [0,0], action = None):
"""combobox creates a drop down list from a list of strings lst at position [x, y]. When one option is active an action is performed."""
if action is None:
action = self.nothingHappens
combobx = QComboBox(self)
combobx.addItems(lst)
#combobx.move(pos[0], pos[1])
combobx.activated[str].connect(action)
combobx.setSizePolicy(sp)
return combobx
def doNothing(self):
pass
def anglesArePossible(self, ang):
"""This function returns whether a list of 3 angles is possible or not. The sum of the angles needs to be smaller than 360 degrees. Also the sum of the two smallest angles needs to be larger than the largest angle. Angles are supplied in degrees."""
ang = sorted(ang)
cond1 = sum(ang)<360
cond2 = ang[0] + ang[1]>ang[2]
return (cond1 and cond2)
def createStructure(self):
res, okPressed = structureDialog.getInfo()
if okPressed:
#need to check if that name doesn't already exist or the structure will overwrite items
if res[0] not in tc.structures:
if self.anglesArePossible(res[4:7]):
newstruc = tc.addStructure(name = res[0], a=res[1], b=res[2], c=res[3], alpha=res[4], beta=res[5], gamma=res[6])
self.updateAll(focus = newstruc.name)
else:
QMessageBox.warning(self, " ", "The crystal angles are invalid.")
else:
QMessageBox.warning(self, " ", "A structure by this name already exists. Please choose another name.")
def editStructure(self):
cur = self.currentStruc()
res, okPressed = structureDialog.getInfo(windowtitle = "Edit structure", name = cur.name, a = cur.a, b = cur.b, c = cur.c, alpha = cur.alpha, beta = cur.beta, gamma = cur.gamma)
if okPressed:
if self.anglesArePossible(res[4:7]): #res[4, 5, 6]
#if the name is nothing or it already exists, keep old name
if res[0]=="" or res[0] in tc.structures:
res[0] = self.currentStruc().name
self.currentStruc().changeCrystallography(*res)
self.updateAll(focus = res[0])
else:
QMessageBox.warning(self, " ", "The crystal angles are invalid.")
def deleteStructure(self):
nt = self.currentStruc().name
check = self.checkEvent(msg = "Are you sure you want to delete %s? All Crystals with this structure will also be deleted!" %(nt))
if check:
tc.removeStructure(nt)
self.updateAll()
def showWizard(self):
indexingDialog.getInfo(caller = self.caller)
def currentStruc(self):
try:
return tc.getStructure(self.struclist.currentText())
except:
return None
def updateAll(self, **kwargs):
self.updateStructurelist(**kwargs)
self.updateButtons()
self.caller.updateCrystals() #also update the crystals
def updateStructurelist(self, focus = None):
#save whichever name was active
currentstrucname = ""
if focus is None:
try:
currentstrucname = self.currentStruc().name
except:
pass
else:
currentstrucname = focus
#update the structure dropdown list
self.struclist.clear()
self.struclist.addItems(list(tc.structures.keys()))
#set the structure again that was active before or the one that was newly added
try:
index = self.struclist.findText(currentstrucname, Qt.MatchFixedString)
if index>=0:
self.struclist.setCurrentIndex(index)
except:
pass
def updateButtons(self):
#if there are no structures
if not tc.structures:
self.editstrucbut.hide()
self.delstrucbut.hide()
self.calcbut.hide()
else:
self.editstrucbut.show()
self.delstrucbut.show()
self.calcbut.show()
class crystalMenu(QWidget):
def __init__(self, caller):
###########The crystals menu#################
super().__init__()
self.caller = caller
self.formGroupBox = QGroupBox("Crystals/Grain")
#inside the grouping box have a grid layout
layout = QGridLayout()
layout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
layout.setSpacing(10)
#scrollable list of structures
self.cryslabel = QLabel("Crystal")
layout.addWidget(self.cryslabel, 1, 0)
self.cryslabel.setToolTip("A microscope, stage, calibrated detector and structure are prerequisites to Crystal creation and editing.")
#crystals - empty in the beginning
self.crystallist = self.combobox(list([]), action = self.changeToolTip)
layout.addWidget(self.crystallist, 1, 1)