-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwindow.py
More file actions
3230 lines (2682 loc) · 150 KB
/
window.py
File metadata and controls
3230 lines (2682 loc) · 150 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
import ast
import csv
import itertools
import math
import os
import re
import sys
from collections import Counter
from collections import defaultdict
from typing import Dict
import pickle
import matplotlib.pyplot as plt
import common
from UI import Ui_APTMainWindow, Ui_InputElementTable, Ui_PeriodicTable, Ui_MonoLayer, Ui_DecomposeList, \
Ui_AbstractLayer, Ui_SRO, Ui_CompositionMap
import docx
import numpy as np
import pandas as pd
from IPython.external.qt_for_kernel import QtCore
from PyQt5 import QtGui
from PyQt5.QtCore import QEvent, Qt
from PyQt5.QtGui import QCursor, QStandardItemModel, QStandardItem
from PyQt5.QtWidgets import QMainWindow, QFileDialog, QDialog, QVBoxLayout, QTableWidgetItem, \
QHeaderView, QLineEdit, QLabel, QDialogButtonBox
from ase.io import read
from ase.neighborlist import NeighborList, NewPrimitiveNeighborList
from matplotlib.backends.backend_qt5 import NavigationToolbar2QT
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from natsort import index_natsorted, order_by_index
from scipy import special
from scipy.signal import savgol_filter
from scipy.spatial import ConvexHull, Delaunay
from silx.gui.widgets.PeriodicTable import PeriodicTable
# Remember that the above non-project library file was hard edited to add D to the periodic table
# This is a really bad practice, and needs to be changed. The git repository wont reflect this addition for example
from sklearn.cluster import DBSCAN
from sklearn.neighbors import KDTree
pd.options.mode.chained_assignment = None
pd.set_option('display.width', 320)
np.set_printoptions(linewidth=320)
pd.set_option('display.max_columns', 10)
pickle.HIGHEST_PROTOCOL = 4
# Functions defined in the common class
show_message = common.show_message
# maximum number of ions can be specified here
max_ions = 50
# The dictionary of ions for global use and update. Each ion will be one element_dict.
element_dict = {'ion': [], 'num': [], 'mass': [], 'charge': []}
cutoff_dict = {'peak_MNRatio': float, 'peak_width': float, 'cutoff_bin': float, 'cutoff_height': int,
'cutoff_width': int}
# list of element_dict corresponding to row number
element_dict_array: Dict[int, dict] = {}
# list of cutoff values corresponding to row number
cutoff_dict_array: Dict[int, dict] = {}
# The following class is used to visualize the dataframe inside the main window. The column size could be readjusted.
# reference: https://stackoverflow.com/questions/44603119/how-to-display-a-pandas-data-frame-with-pyqt5-pyside2
# Does not inherit any UI files
class DataFrameModel(QtCore.QAbstractTableModel):
DtypeRole = QtCore.Qt.UserRole + 1000
ValueRole = QtCore.Qt.UserRole + 1001
def __init__(self, df=pd.DataFrame(), parent=None):
super(DataFrameModel, self).__init__(parent)
self._dataframe = df
def setDataFrame(self, dataframe):
self.beginResetModel()
self._dataframe = dataframe.copy()
self.endResetModel()
def dataFrame(self):
return self._dataframe
dataFrame = QtCore.pyqtProperty(pd.DataFrame, fget=dataFrame, fset=setDataFrame)
@QtCore.pyqtSlot(int, QtCore.Qt.Orientation, result=str)
def headerData(self, section: int, orientation: QtCore.Qt.Orientation, role: int = QtCore.Qt.DisplayRole):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
return self._dataframe.columns[section]
else:
return str(self._dataframe.index[section])
return QtCore.QVariant()
def rowCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return len(self._dataframe.index)
def columnCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return self._dataframe.columns.size
def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid() or not (0 <= index.row() < self.rowCount() and 0 <= index.column() < self.columnCount()):
return QtCore.QVariant()
row = self._dataframe.index[index.row()]
col = self._dataframe.columns[index.column()]
dt = self._dataframe[col].dtype
val = self._dataframe.iloc[row][col]
if role == QtCore.Qt.DisplayRole:
return str(val)
elif role == DataFrameModel.ValueRole:
return val
if role == DataFrameModel.DtypeRole:
return dt
return QtCore.QVariant()
def roleNames(self):
roles = {
QtCore.Qt.DisplayRole: b'display',
DataFrameModel.DtypeRole: b'dtype',
DataFrameModel.ValueRole: b'value'
}
return roles
def sort(self, column, order):
self.layoutAboutToBeChanged.emit()
if order == 0:
self._dataframe = self._dataframe.reindex(index=order_by_index(self._dataframe.index, index_natsorted(
eval('self._dataframe.%s' % (list(self._dataframe.columns)[column])))))
else:
self._dataframe = self._dataframe.reindex(index=order_by_index(self._dataframe.index, reversed(
index_natsorted(eval('self._dataframe.%s' % (list(self._dataframe.columns)[column]))))))
self._dataframe.reset_index(inplace=True, drop=True)
self.setDataFrame(self._dataframe)
self.layoutChanged.emit()
# Class used to plot and display histogram
# Does not inherit any UI files
class HistogramWindow(QDialog):
def __init__(self, subset_df_apt_hist, parent=None):
super(HistogramWindow, self).__init__(parent)
# a figure instance to plot on
self.figure = Figure()
self.subset_df_apt_hist = subset_df_apt_hist
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init__
self.canvas = FigureCanvasQTAgg(self.figure)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar2QT(self.canvas, self)
# set the layout
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
self.setLayout(layout)
self.plot()
def plot(self):
# create an axis
ax = self.figure.add_subplot(111)
# discards the old graph
ax.clear()
# plot data
ax.title.set_text('APT Spectrum')
ax.set_xlabel('MN_Ratio')
ax.set_ylabel('Counts')
ax.bar(self.subset_df_apt_hist.bin_lower, self.subset_df_apt_hist.freq,
width=self.subset_df_apt_hist.bin_upper - self.subset_df_apt_hist.bin_lower, ec="k", align="edge")
# refresh canvas
self.canvas.draw()
# The class shows an on-the-top dialog that can input num of elements and mass (different from default for isotope).
# Does not inherit any UI files
class NumberAndMass(QDialog):
def __init__(self, parent=None):
super(NumberAndMass, self).__init__(parent)
mainLayout = QVBoxLayout()
self.lineedit, self.lineedit2 = QLineEdit(), QLineEdit()
self.label, self.label2 = QLabel(), QLabel()
self.btns = QDialogButtonBox()
self.btns.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)
self.label.setText("Enter No: of atoms (default 1)")
self.label2.setText("Enter Atomic Mass (default as filled)")
mainLayout.addWidget(self.label)
mainLayout.addWidget(self.lineedit)
mainLayout.addWidget(self.label2)
mainLayout.addWidget(self.lineedit2)
mainLayout.addWidget(self.btns)
self.btns.accepted.connect(self.accept)
self.btns.rejected.connect(self.reject)
self.setLayout(mainLayout)
# The class inherits a custom UI layout and has facility to view periodic table, add elements into the table
# Inherits from Ui_PeriodicTable
class PeriodicTableCustom(Ui_PeriodicTable.Ui_Form, QDialog):
def __init__(self, parent=None):
super(PeriodicTableCustom, self).__init__(parent)
self.setupUi(self)
# inputDialog is used to get no: of atoms
self.inputDialog = NumberAndMass()
self.inputDialog.setWindowTitle('Input')
self.lineEdit.setText("0")
self.curr_row = None
self.ptable = PeriodicTable(self.widget, selectable=False)
self.ptable.sigElementClicked.connect(self.click_table)
self.inputDialog.setWindowModality(QtCore.Qt.ApplicationModal)
self.pushButton_2.clicked.connect(self.delete)
self.pushButton_5.clicked.connect(self.emit_charge)
self.pushButton_5.clicked.connect(self.accept)
self.pushButton_4.clicked.connect(self.reject)
def delete(self):
text = ""
if len(element_dict['ion']) > 0:
del element_dict['ion'][-1]
del element_dict['num'][-1]
for i in range(len(element_dict['ion'])):
text = text + str(element_dict['ion'][i]) + common.subscript(str(element_dict['num'][i]))
self.lineEdit_3.setText(text)
def emit_charge(self):
text = self.lineEdit.text()
if '-' in text:
sign = '-'
else:
sign = '+'
text_num = re.sub('\D', '', text)
text = text_num + sign
return text
def click_table(self, item):
self.showdialogTOP()
self.inputDialog.lineedit2.setText(str(item.mass))
self.inputDialog.lineedit.setText(str(1))
ok = self.inputDialog.exec_()
elem_num = self.inputDialog.lineedit.text()
elem_mass = self.inputDialog.lineedit2.text()
if ok:
if len(element_dict['ion']) == 0:
self.lineEdit_3.setText("")
element_dict['ion'].append(str(item.symbol))
element_dict['num'].append(elem_num)
element_dict['mass'].append(elem_mass)
element_dict['charge'] = [self.emit_charge()]
text = ""
for i in range(len(element_dict['ion'])):
text = text + str(element_dict['ion'][i]) + common.subscript(str(element_dict['num'][i]))
self.lineEdit_3.setText(text)
element_dict_array[str(self.curr_row)] = dict()
element_dict_array[str(self.curr_row)]['ion'] = element_dict['ion']
element_dict_array[str(self.curr_row)]['num'] = element_dict['num']
element_dict_array[str(self.curr_row)]['mass'] = element_dict['mass']
element_dict_array[str(self.curr_row)]['charge'] = element_dict['charge']
# The following makes sure the input dialogue to enter no: of atoms stays on top and on cursor location
def showdialogTOP(self):
self.inputDialog.move(QCursor.pos())
self.inputDialog.show()
self.inputDialog.raise_()
def showEvent(self, event):
if len(element_dict['ion']) == 0:
self.lineEdit_3.setText("")
text = ""
for i in range(len(element_dict['ion'])):
text = text + str(element_dict['ion'][i]) + common.subscript(str(element_dict['num'][i]))
self.lineEdit_3.setText(text)
event.accept()
# The class inherits a custom UI layout and has facility to complete the input elements table as well as cutoff values
# Inherits from Ui_InputElementTable
class InputElementTable(Ui_InputElementTable.Ui_Form, QDialog):
def __init__(self, parent=None):
super(InputElementTable, self).__init__(parent)
self.setupUi(self)
self.tableWidget.setRowCount(max_ions)
self.tableWidget.setColumnCount(6)
self.tableWidget.setHorizontalHeaderItem(0, QTableWidgetItem("ION"))
self.tableWidget.setHorizontalHeaderItem(1, QTableWidgetItem("peak_MNRatio(Da)"))
self.tableWidget.setHorizontalHeaderItem(2, QTableWidgetItem("MNRatio_width(Da)"))
self.tableWidget.setHorizontalHeaderItem(3, QTableWidgetItem("cutoff_bin"))
self.tableWidget.setHorizontalHeaderItem(4, QTableWidgetItem("cutoff_height"))
self.tableWidget.setHorizontalHeaderItem(5, QTableWidgetItem("cutoff_width"))
self.PeriodicTableCustom = None
self.row = 0
self.col = 0
self.item = None
self.cell_clicked = False
self.buttonBox.accepted.connect(self.submit_close)
self.buttonBox.rejected.connect(self.reject)
self.setMinimumSize(500, 500)
self.setGeometry(QtCore.QRect(417, 220, 666, 653))
header = self.tableWidget.horizontalHeader()
header.setSectionResizeMode(0, QHeaderView.Stretch)
header.setSectionResizeMode(1, QHeaderView.ResizeToContents)
header.setSectionResizeMode(2, QHeaderView.ResizeToContents)
header.setSectionResizeMode(3, QHeaderView.ResizeToContents)
header.setSectionResizeMode(4, QHeaderView.ResizeToContents)
self.tableWidget.cellClicked.connect(self.cell_was_clicked)
self.tableWidget.cellDoubleClicked.connect(self.cell_was_clicked)
self.pushButton_2.clicked.connect(self.export_table)
self.pushButton.clicked.connect(self.import_table)
viewport = self.tableWidget.viewport()
viewport.installEventFilter(self)
def saveFileDialog(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getSaveFileName(self, "QFileDialog.getSaveFileName()", "",
"All Files (*);;csv Files (*.csv)", options=options)
if fileName:
return fileName + '.csv'
def submit(self):
key = None
for r in range(max_ions):
for c in range(1, 4):
if c == 1:
key = 'ion'
if c == 2:
key = 'num'
if c == 3:
key = 'mass'
if c == 4:
key = 'charge'
for c in range(1, 6):
if c == 1:
key = 'peak_MNRatio'
if c == 2:
key = 'peak_width'
if c == 3:
key = 'cutoff_bin'
if c == 4:
key = 'cutoff_height'
if c == 5:
key = 'cutoff_width'
if self.tableWidget.item(r, c):
cutoff_dict[key] = self.tableWidget.item(r, c).text()
else:
cutoff_dict[key] = None
cutoff_dict_array[str(r)] = dict()
cutoff_dict_array[str(r)]['peak_MNRatio'] = cutoff_dict['peak_MNRatio']
cutoff_dict_array[str(r)]['peak_width'] = cutoff_dict['peak_width']
cutoff_dict_array[str(r)]['cutoff_bin'] = cutoff_dict['cutoff_bin']
cutoff_dict_array[str(r)]['cutoff_height'] = cutoff_dict['cutoff_height']
cutoff_dict_array[str(r)]['cutoff_width'] = cutoff_dict['cutoff_width']
def export_table(self):
csv_file, extension = QFileDialog.getSaveFileName(
self, 'Save File', '.', filter=self.tr("csv file (*.csv)"))
csv_columns = ['ion', 'num', 'mass', 'charge', 'peak_MNRatio', 'peak_width',
'cutoff_bin', 'cutoff_height', 'cutoff_width']
self.submit()
list_of_dict = []
list1 = list(element_dict_array.keys())
list1 = [int(i) for i in list1]
list2 = list(cutoff_dict_array.keys())
list2 = [int(i) for i in list2]
if min(list1) <= min(list2):
for key1 in element_dict_array:
x = element_dict_array[key1]
if int(key1) in list2:
y = cutoff_dict_array[key1]
else:
y = {}
z = {**x, **y}
list_of_dict.append(z)
for key2 in cutoff_dict_array:
if int(key2) not in list1:
x = {}
y = cutoff_dict_array[key2]
z = {**x, **y}
list_of_dict.append(z)
else:
for key2 in cutoff_dict_array:
y = cutoff_dict_array[key2]
if int(key2) in list1:
x = element_dict_array[key2]
else:
x = {}
z = {**x, **y}
list_of_dict.append(z)
for key1 in element_dict_array:
if int(key1) not in list2:
x = element_dict_array[key1]
y = {}
z = {**x, **y}
list_of_dict.append(z)
try:
with open(csv_file, 'w', newline="") as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
writer.writeheader()
for row in list_of_dict:
writer.writerow(row)
except IOError:
common.show_message("I/O error")
def import_table(self):
csv_file, extension = QFileDialog.getOpenFileName(
self, 'Save File', '.', filter=self.tr("csv file (*.csv)"))
for value in element_dict.values():
del value[:]
for value in cutoff_dict.values():
del value
element_dict_array.clear()
cutoff_dict_array.clear()
if csv_file:
try:
with open(csv_file, "r") as fileInput:
for row_num, row in enumerate(csv.reader(fileInput)):
if row_num > 0:
r = row_num - 1
if row[0] != '':
element_dict_array[str(r)] = dict()
element_dict_array[str(r)]['ion'] = ast.literal_eval(row[0])
element_dict_array[str(r)]['num'] = ast.literal_eval(row[1])
element_dict_array[str(r)]['mass'] = ast.literal_eval(row[2])
element_dict_array[str(r)]['charge'] = ast.literal_eval(row[3])
cutoff_dict_array[str(r)] = dict()
cutoff_dict_array[str(r)]['peak_MNRatio'] = (row[4])
cutoff_dict_array[str(r)]['peak_width'] = (row[5])
cutoff_dict_array[str(r)]['cutoff_bin'] = (row[6])
cutoff_dict_array[str(r)]['cutoff_height'] = (row[7])
cutoff_dict_array[str(r)]['cutoff_width'] = (row[8])
except IOError:
common.show_message("I/O error")
self.refresh_table()
def refresh_table(self):
if len(element_dict_array) != 0:
for key in element_dict_array:
if eval(key) is not None:
row = int(key)
value = ''
for ii in range(len(element_dict_array[key]['ion'])):
value = value + element_dict_array[key]['ion'][ii] + common.subscript(
element_dict_array[key]['num'][ii])
if ii == len(element_dict_array[key]['ion']) - 1:
value = value + '(' + element_dict_array[key]['charge'][0] + ')'
item_ion = QTableWidgetItem()
item_ion.setText(value)
self.tableWidget.setItem(row, 0, item_ion)
if len(cutoff_dict_array) != 0:
for key in cutoff_dict_array:
row = int(key)
peak_MNRatio = cutoff_dict_array[key]['peak_MNRatio']
peak_width = cutoff_dict_array[key]['peak_width']
cutoff_bin = cutoff_dict_array[key]['cutoff_bin']
cutoff_height = cutoff_dict_array[key]['cutoff_height']
cutoff_width = cutoff_dict_array[key]['cutoff_width']
if peak_MNRatio:
item_peak = QTableWidgetItem()
item_peak.setText(str(peak_MNRatio))
self.tableWidget.setItem(row, 1, item_peak)
if peak_width:
item_peak = QTableWidgetItem()
item_peak.setText(str(peak_width))
self.tableWidget.setItem(row, 2, item_peak)
if cutoff_bin:
item_cutoff_bin = QTableWidgetItem()
item_cutoff_bin.setText(str(cutoff_bin))
self.tableWidget.setItem(row, 3, item_cutoff_bin)
if cutoff_height:
item_cutoff_height = QTableWidgetItem()
item_cutoff_height.setText(str(cutoff_height))
self.tableWidget.setItem(row, 4, item_cutoff_height)
if cutoff_width:
item_cutoff_width = QTableWidgetItem()
item_cutoff_width.setText(str(cutoff_width))
self.tableWidget.setItem(row, 5, item_cutoff_width)
def showEvent(self, event):
super(InputElementTable, self).showEvent(event)
self.refresh_table()
def submit_close(self):
self.submit()
self.accept()
self.close()
def cell_was_clicked(self, row, column):
self.cell_clicked = True
self.row = row
self.col = column
self.item = self.tableWidget.itemAt(row, column)
def eventFilter(self, source: QtCore.QObject, event: QtCore.QEvent) -> bool:
if event.type() == QEvent.MouseButtonDblClick:
for key in element_dict:
element_dict[key] = []
headertext = self.tableWidget.horizontalHeaderItem(self.col).text()
if headertext == 'ION' and self.cell_clicked:
self.PeriodicTableCustom = PeriodicTableCustom()
if self.tableWidget.item(self.row, 0):
already_ion = self.tableWidget.item(self.row, 0).text()
if already_ion:
self.PeriodicTableCustom.lineEdit_3.setText(already_ion)
self.PeriodicTableCustom.curr_row = self.row
if self.PeriodicTableCustom.exec() == 1:
element_dict['charge'] = [self.PeriodicTableCustom.emit_charge()]
element_dict_array[str(self.row)] = dict()
element_dict_array[str(self.row)]['ion'] = element_dict['ion']
element_dict_array[str(self.row)]['num'] = element_dict['num']
element_dict_array[str(self.row)]['mass'] = element_dict['mass']
element_dict_array[str(self.row)]['charge'] = element_dict['charge']
text = ''
for i in range(len(element_dict['ion'])):
text = text + str(element_dict['ion'][i]) + common.subscript(str(element_dict['num'][i]))
if text:
charge = str(element_dict['charge'][0])
charge = '(' + charge + ')'
text = text + charge
item = QTableWidgetItem()
item.setText(text)
self.tableWidget.setItem(self.row, self.col, item)
return super(InputElementTable, self).eventFilter(source, event)
# The window containing 2 lists with provision to add and subtract ions to decompose
# Inherits from Ui_DecomposeList
class InputDecomposeList(Ui_DecomposeList.Ui_Dialog, QDialog):
def __init__(self, df_el=[], parent=None):
super(InputDecomposeList, self).__init__(parent)
self.setupUi(self)
self.df_el = df_el
self.df_decompose_el = None
self.init_list()
self.pushButton.clicked.connect(self.add_ion)
self.pushButton_2.clicked.connect(self.subtract_ion)
self.buttonBox.accepted.connect(self.submit_close)
def submit_close(self):
self.df_decompose_el = [str(self.listWidget_2.item(i).text()) for i in range(self.listWidget_2.count())]
def init_list(self):
for text in self.df_el:
self.listWidget.addItem(text)
def add_ion(self):
if self.listWidget.currentItem():
selected_text = self.listWidget.currentItem().text()
self.listWidget_2.addItem(selected_text)
self.listWidget.takeItem(self.listWidget.currentRow())
def subtract_ion(self):
if self.listWidget_2.currentItem():
selected_text = self.listWidget_2.currentItem().text()
self.listWidget.addItem(selected_text)
self.listWidget_2.takeItem(self.listWidget_2.currentRow())
# The class inherits a custom UI layout and has facility to analyse mono-layers from H5 file
# Inherits from Ui_MonoLayer
class MonoLayerDialog(Ui_MonoLayer.Ui_Dialog, QDialog):
def __init__(self, parent=None):
super(MonoLayerDialog, self).__init__(parent)
self.setupUi(self)
self.hdf_file = None
self.df_apt = None
self.df_apt_layer = None
self.widget_window = None
self.ION = None
self.my_old_plane = None
self.alpha = None
self.scatter3d = None
self.scatter3d_noise_free = None
self.scatter3d_noise = None
self.count_layer = None
self.dist_layer = None
self.layer_thick_dict = None
self.my_final_layers = None
self.df_el = None
self.df_decompose_el = None
self.no_layers = False
self.decomposition_list = None
self.PeriodicTableCustom = PeriodicTableCustom()
self.xs = 0
self.ys = 0
self.zs = 0
self.d = 0
self.x_plane_start = 0
self.x_plane_end = 1
self.y_plane_start = 0
self.y_plane_end = 1
self.z_plane_start = 0
self.z_plane_end = 1
self.plane = [0, 0, 0]
# Progress bar
self.completed = 0
self.progressBar.setValue(self.completed)
# Buttons
self.pushButton_2.clicked.connect(self.plot_3d, False) # Plot the APT data in 3D
self.pushButton_3.clicked.connect(self.input_file) # Input H5 file
self.pushButton_4.clicked.connect(self.plot_plane) # Plot the plane based on given miller indices (and d)
self.pushButton_11.clicked.connect(self.plot_DBScan) # Scatter plot the ions after doing DBScan
self.pushButton_5.clicked.connect(self.find_layers) # Start finding layers by travelling along plane direction
self.pushButton.clicked.connect(self.show_peaks) # Show the graph with ion counts across layer bins
self.pushButton_13.clicked.connect(self.plot_layers) # calculate the layer ions and plot layers
self.pushButton_14.clicked.connect(self.decompose_list) # give ions to decompose
self.pushButton_16.clicked.connect(self.export_report) # calculate and export final report as word docx
self.pushButton_15.clicked.connect(self.export_hdf) # export final dataframe as HDF file
self.textEdit.setReadOnly(True)
self.textEdit.mouseDoubleClickEvent = self.textEdit_click
self.widget.fig = Figure()
self.widget.canvas = FigureCanvas(self.widget.fig)
self.widget.axes = self.widget.fig.add_subplot(111, projection='3d')
# The below function is used to read the H5 file containing binned (mapped) apt data for mono-layer analysis
def input_file(self):
file = QFileDialog.getOpenFileName(self, 'Select HDF File"',
os.getcwd(), "HDF files (*.h5)")
try:
self.hdf_file = file[0]
self.df_apt = pd.read_hdf(self.hdf_file)
self.pushButton_2.setEnabled(True)
self.pushButton.setEnabled(True)
except:
self.pushButton_2.setEnabled(False)
self.pushButton.setEnabled(False)
# The below function is invoked upon doubleclick on the edit next to layer_element. It takes event as an input
# The function is used to find the layer ion from periodic table to plot in 3D
def textEdit_click(self, event):
self.PeriodicTableCustom.show()
if self.PeriodicTableCustom.exec() == 1:
element_dict['charge'] = []
element_dict['charge'].append(self.PeriodicTableCustom.emit_charge())
text = ''
for i in range(len(element_dict['ion'])):
text = text + str(element_dict['ion'][i]) + common.subscript(str(element_dict['num'][i]))
if text:
charge = str(element_dict['charge'][0])
charge = '(' + charge + ')'
text = text + charge
self.textEdit.setText(text)
# Function to remove all plots after checking if they exist
def remove_plots(self):
if self.scatter3d:
self.scatter3d.remove()
del self.scatter3d
self.scatter3d = None
if self.scatter3d_noise_free:
self.scatter3d_noise_free.remove()
del self.scatter3d_noise_free
self.scatter3d_noise_free = None
if self.scatter3d_noise:
self.scatter3d_noise.remove()
del self.scatter3d_noise
self.scatter3d_noise = None
# The below function is used to plot the layer element in 3D plot. It can also plots after DBScan (keyword: outlier)
# Initialises df_apt_layer which is required for further layer analysis, so must be always plotted
def plot_3d(self, outliers):
if self.df_apt is not None:
layout = QVBoxLayout(self.widget)
layout.addWidget(self.widget.canvas)
# element_dict = {'ion': ['O', 'D'], 'num': ['1', '1'], 'mass': ['16.0', '2.014'], 'charge': ['1-']}
if outliers:
self.remove_plots()
df_apt_layer_noise_free = self.df_apt_layer[self.df_apt_layer['DBSCAN_Label'] != -1]
df_apt_layer_noise = self.df_apt_layer[self.df_apt_layer['DBSCAN_Label'] == -1]
xs_nf = df_apt_layer_noise_free['X'].astype(float)
ys_nf = df_apt_layer_noise_free['Y'].astype(float)
zs_nf = df_apt_layer_noise_free['Z'].astype(float)
xs_n = df_apt_layer_noise['X'].astype(float)
ys_n = df_apt_layer_noise['Y'].astype(float)
zs_n = df_apt_layer_noise['Z'].astype(float)
self.scatter3d_noise_free = self.widget.axes.scatter(xs_nf, ys_nf, zs_nf, c='blue', s=30,
label=self.ION, marker='.')
self.scatter3d_noise = self.widget.axes.scatter(xs_n, ys_n, zs_n, c='red', s=30,
label=self.ION + "_noise", marker='.')
self.widget.axes.set_xlim3d(self.x_plane_start, self.x_plane_end)
self.widget.axes.set_ylim3d(self.y_plane_start, self.y_plane_end)
self.widget.axes.set_zlim3d(self.z_plane_start, self.z_plane_end)
else:
self.remove_plots()
if len(element_dict['ion']) > 0:
ion_array = element_dict['ion']
self.ION = ''
for ii in range(len(ion_array)):
self.ION = self.ION + ion_array[ii] + common.subscript(element_dict['num'][ii])
if ii == len(ion_array) - 1:
self.ION = self.ION + '(' + element_dict['charge'][0] + ')'
self.df_apt_layer = self.df_apt[self.df_apt['ION'] == self.ION]
# approximate input data as enclosed in 1st quadrant
# bringing negative coordinates into positive coordinates
if self.df_apt_layer.shape[0] > 2:
self.df_apt_layer = common.bring_df_to_positive_coord(self.df_apt_layer)
self.x_plane_start = self.df_apt_layer["X"].min()
self.x_plane_end = self.df_apt_layer["X"].max()
self.y_plane_start = self.df_apt_layer["Y"].min()
self.y_plane_end = self.df_apt_layer["Y"].max()
self.z_plane_start = self.df_apt_layer["Z"].min()
self.z_plane_end = self.df_apt_layer["Z"].max()
self.xs = self.df_apt_layer['X'].astype(float)
self.ys = self.df_apt_layer['Y'].astype(float)
self.zs = self.df_apt_layer['Z'].astype(float)
else:
self.xs = 0
self.ys = 0
self.zs = 0
else:
self.xs = 0
self.ys = 0
self.zs = 0
self.ION = None
self.scatter3d = self.widget.axes.scatter(self.xs, self.ys, self.zs, c='blue',
s=30, label=self.ION, marker='.')
self.widget.axes.set_xlim3d(self.x_plane_start, self.x_plane_end)
self.widget.axes.set_ylim3d(self.y_plane_start, self.y_plane_end)
self.widget.axes.set_zlim3d(self.z_plane_start, self.z_plane_end)
self.widget.axes.legend()
self.widget.fig.canvas.draw()
self.widget.axes.set_xlabel('X Axis')
self.widget.axes.set_ylabel('Y Axis')
self.widget.axes.set_zlabel('Z Axis')
self.widget.fig.tight_layout()
# The below function is used to get the plane coordinates in miller indices as well as plot it on the 3D layer plot
# The default value for plane direction is set as [001] (parallel to Z axis)
def plot_plane(self):
self.plane = self.lineEdit.text()
self.d = self.lineEdit_2.text()
pattern_MI = "^['['](\s*[0-9]*?),(\s*[0-9]*?),(\s*[0-9]*)\]$"
rex_pattern_MI = re.compile(pattern_MI)
pattern_D = "^\s*\d+\.?\d*\s*$"
rex_pattern_D = re.compile(pattern_D)
if self.my_old_plane:
self.my_old_plane.remove()
self.my_old_plane = None
if not self.d:
self.d = 1
self.lineEdit_2.setText("1")
else:
text = self.lineEdit_2.text()
if rex_pattern_D.match(text):
self.d = float(text)
else:
common.show_message("A (positive) float value is required as input for d intercept of the Layer Plane")
self.d = None
if not self.plane:
self.plane = [0, 0, 1]
self.lineEdit.setText("[0,0,1]")
else:
text = self.lineEdit.text()
if rex_pattern_MI.match(text):
text_groups = re.search(pattern_MI, text)
a = float(text_groups.group(1))
b = float(text_groups.group(2))
c = float(text_groups.group(3))
self.plane = [a, b, c]
else:
self.plane = None
common.show_message("Incorrect format of Miller Indices input expected for Layer Plane (\"[a,b,c]\")")
self.alpha = dict() # alpha plane which curr to the plane specified by miller indices (inside unit cube)
intercepts = ['a', 'b', 'c']
if self.plane and self.d:
for i in range(3):
if self.plane[i] == 0:
self.alpha[intercepts[i]] = 0 # to avoid infinity
else:
self.alpha[intercepts[i]] = 1 / self.plane[i] # intercepts are reciprocals of miller indices
self.alpha['d'] = self.d # for ideal miller indices, d = 1
X, Y, Z = None, None, None
if self.alpha['c'] != 0:
x = np.linspace(self.x_plane_start, self.x_plane_end, 10)
y = np.linspace(self.y_plane_start, self.y_plane_end, 10)
X, Y = np.meshgrid(x, y)
Z = (self.alpha['d'] - self.alpha['a'] * X - self.alpha['b'] * Y) / self.alpha['c']
else:
if self.alpha['b'] != 0:
x = np.linspace(self.x_plane_start, self.x_plane_end, 10)
z = np.linspace(self.z_plane_start, self.z_plane_end, 10)
X, Z = np.meshgrid(x, z)
Y = (self.alpha['d'] - self.alpha['c'] * Z - self.alpha['a'] * X) / self.alpha['b']
elif self.alpha['a'] != 0:
y = np.linspace(self.y_plane_start, self.y_plane_end, 10)
z = np.linspace(self.z_plane_start, self.z_plane_end, 10)
Y, Z = np.meshgrid(y, z)
X = (self.alpha['d'] - self.alpha['c'] * Z - self.alpha['b'] * Y) / self.alpha['a']
if self.widget.axes:
if self.my_final_layers:
for layer in self.my_final_layers:
layer.remove()
del self.my_final_layers
self.my_final_layers = []
if X is not None:
my_plane = self.widget.axes.plot_surface(X, Y, Z, color='gray', shade=False)
self.my_old_plane = my_plane
self.widget.fig.canvas.draw()
# The below function optionally reduces the noise in the layer element using DBScan. Takes in Min_Points and Epsilon
# It then plots the 3D plot with noises (ignored ions) as red dots. This helps in brute force optimisation of DBScan
def plot_DBScan(self):
if self.df_apt_layer is not None:
pattern_Dbscan_minpoints = "^[0-9]*[1-9][0-9]*$"
pattern_Dbscan_eps = "^\s*\d+\.?\d*\s*$"
rex_pattern_Dbscan_minpoints = re.compile(pattern_Dbscan_minpoints)
rex_pattern_Dbscan_eps = re.compile(pattern_Dbscan_eps)
MIN_POINTS = None
EPSILON = None
min_pints_text = self.lineEdit_7.text()
epsilon_text = self.lineEdit_8.text()
if rex_pattern_Dbscan_minpoints.match(min_pints_text):
MIN_POINTS = int(min_pints_text)
else:
common.show_message("a positive integer value is expected for MIN_POINTS")
if rex_pattern_Dbscan_eps.match(epsilon_text):
EPSILON = float(epsilon_text)
else:
common.show_message("a positive float value is expected for EPSILON")
if type(MIN_POINTS) == int and MIN_POINTS > 0 and type(EPSILON) == float and EPSILON > 0:
self.remove_plots()
X = self.df_apt_layer[['X', 'Y', 'Z']].to_numpy()
db = DBSCAN(eps=EPSILON, min_samples=MIN_POINTS).fit(X)
labels = db.labels_
self.df_apt_layer['DBSCAN_Label'] = labels.reshape(-1, 1)
self.plot_3d(True)
if self.scatter3d_noise is not None:
self.widget.fig.canvas.draw()
if type(MIN_POINTS) == int and MIN_POINTS == 0 and type(EPSILON) == float and EPSILON == 0:
self.remove_plots()
if 'DBSCAN_Label' in self.df_apt_layer.columns:
self.df_apt_layer = self.df_apt_layer.drop('DBSCAN_Label', 1)
self.plot_3d(False)
if self.scatter3d_noise is not None:
self.widget.fig.canvas.draw()
else:
common.show_message("Plot the layer elements once before attempting to remove outliers")
# The below function calculates the layers using input bin size and plane direction.
# The output of the function are inputs for histogram 'peak' plot: self.dist_layer and self.count_layer
def find_layers(self):
self.completed = 0
self.progressBar.setValue(self.completed)
pattern_no_layers = "^[0-9]*[1-9][0-9]*$"
rex_pattern_bin = re.compile(pattern_no_layers)
text = self.lineEdit_3.text()
self.no_layers = False
if text == '':
self.no_layers = 1
self.lineEdit_3.setText('1')
else:
if rex_pattern_bin.match(text):
self.no_layers = int(text)
else:
common.show_message("A (positive) integer is required as input for No: of Layer Plane(s)")
if self.no_layers:
self.lineEdit_3.setText(str(self.no_layers))
text = self.lineEdit_9.text()
pattern_bin = "^\s*\d+\.?\d*\s*$"
rex_pattern_bin = re.compile(pattern_bin)
layer_bin = False
if text == '':
layer_bin = 0.1
self.lineEdit_9.setText("0.1")
else:
if rex_pattern_bin.match(text):
layer_bin = float(text)
else:
common.show_message("A (positive) float value is required as input for bin of the Layer Plane")
if layer_bin and self.alpha is not None and self.df_apt_layer is not None:
if 'DBSCAN_Label' in self.df_apt_layer.columns:
df_apt_layer_noise_free = self.df_apt_layer[self.df_apt_layer['DBSCAN_Label'] != -1]
else:
df_apt_layer_noise_free = self.df_apt_layer
max_xyz = int(
max(self.df_apt_layer['X'].max(), self.df_apt_layer['Y'].max(), self.df_apt_layer['Z'].max()) + 1)
bin_num = int(max_xyz / layer_bin + 1)
beta = [dict() for x in range(bin_num)] # beta planes are number of binning planes
self.count_layer = np.empty(bin_num)
for i in range(bin_num):
beta[i] = {k: self.alpha[k] for k in set(list(self.alpha.keys())) - {'d'}}
beta[i]['d'] = (i + 1) * layer_bin
# find number of points bw origin and beta[0]
for bin_i in range(len(self.count_layer)):
self.progressBar.setValue(self.completed)
self.completed = (bin_i / len(self.count_layer)) * 100.0
if bin_i == 0:
counts = 0
for i in range(df_apt_layer_noise_free.shape[0]):
p_xyz = [df_apt_layer_noise_free.iloc[i]['X'], df_apt_layer_noise_free.iloc[i]['Y'],
df_apt_layer_noise_free.iloc[i]['Z']]
side = beta[0]['a'] * p_xyz[0] + beta[0]['b'] * p_xyz[1] + beta[0]['c'] * p_xyz[2] - beta[0][
'd']
side_sign = np.sign(side)
if side_sign == -1:
counts = counts + 1
self.count_layer[bin_i] = counts
else:
counts = 0
for i in range(df_apt_layer_noise_free.shape[0]):
p_xyz = [df_apt_layer_noise_free.iloc[i]['X'], df_apt_layer_noise_free.iloc[i]['Y'],
df_apt_layer_noise_free.iloc[i]['Z']]
side_beta_1 = beta[bin_i - 1]['a'] * p_xyz[0] + beta[bin_i - 1]['b'] * p_xyz[1] + \
beta[bin_i - 1]['c'] * p_xyz[2] - beta[bin_i - 1]['d']
side_beta_2 = beta[bin_i]['a'] * p_xyz[0] + beta[bin_i]['b'] * p_xyz[1] + \