-
Notifications
You must be signed in to change notification settings - Fork 2
/
CarbonXS_GUI.py
2195 lines (1580 loc) · 83.9 KB
/
CarbonXS_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
from PySide import QtGui, QtCore
import ujson
import sys
import os
import numpy as np
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import (
FigureCanvasQTAgg as FigureCanvas,
NavigationToolbar2QT as NavigationToolbar)
from matplotlib.backends import qt_compat
import shutil
import webbrowser
import data_io
import appdirs
from scalable_mw import Ui_MainWindow
from text_file_viewer import Ui_Dialog
use_pyside = qt_compat.QT_API == qt_compat.QT_API_PYSIDE
if hasattr(sys, 'frozen') and sys.platform == 'darwin':
print "Detected a frozen application and extracting the appropriate file directory format"
base_directory = os.path.join(os.path.dirname(sys.executable))
else:
base_directory = '.'
user_data_directory = appdirs.user_data_dir("CarbonXS_GUI")
if use_pyside:
from PySide.QtCore import *
from PySide.QtGui import *
class FittingParams(object):
# Fitting Parameters object to store current FPs in buffer
def __init__(self, parameter_list, param_enable, fit_settings, diff_settings):
self.param_values = [param.value() for param in parameter_list]
self.param_flags = [pe.isChecked() for pe in param_enable]
self.fit_settings = {}
for key in fit_settings.keys():
if key == 'number_layers':
self.fit_settings[key] = fit_settings[key].currentIndex()
else:
self.fit_settings[key] = fit_settings[key].value()
self.diff_values = [ds.value() for ds in diff_settings]
class TextFileViewer(QtGui.QDialog, Ui_Dialog):
def __init__(self, parent=None):
"""
Text File Viewer
Displays the contents of a text file so that the user may specify
:param parent:
"""
super(TextFileViewer, self).__init__(parent)
self.setupUi(self)
self.ok_button.clicked.connect(self.accept)
self.cancel_button.clicked.connect(self.reject)
self.setWindowTitle('Load a Text File')
def load_contents(self, filename):
text = open(filename).read()
self.text_display.setPlainText(text)
class ConsoleStream(QtCore.QObject):
message = QtCore.Signal(str)
def __init__(self, parent=None):
super(ConsoleStream, self).__init__(parent)
def write(self, message):
self.message.emit(str(message))
class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, version):
"""
Initializes the main window of the program
:param version: String to use in the window header indicating the program version
"""
super(MainWindow, self).__init__()
self.version = version
self.setupUi(self)
self.parameter_list = [
self.param_00,
self.param_01,
self.param_02,
self.param_03,
self.param_04,
self.param_05,
self.param_06,
self.param_07,
self.param_08,
self.param_09,
self.param_10,
self.param_11,
self.param_12,
self.param_13,
self.param_14,
self.param_15,
self.param_16,
self.param_17,
]
for item in self.parameter_list:
item.setMaximum(1e21)
item.setMinimum(-1e21)
item.setDecimals(5)
self.parameter_labels = [
self.param_label_00,
self.param_label_01,
self.param_label_02,
self.param_label_03,
self.param_label_04,
self.param_label_05,
self.param_label_06,
self.param_label_07,
self.param_label_08,
self.param_label_09,
self.param_label_10,
self.param_label_11,
self.param_label_12,
self.param_label_13,
self.param_label_14,
self.param_label_15,
self.param_label_16,
self.param_label_17,
]
self.parameter_enable_list = [
self.param_enable_00,
self.param_enable_01,
self.param_enable_02,
self.param_enable_03,
self.param_enable_04,
self.param_enable_05,
self.param_enable_06,
self.param_enable_07,
self.param_enable_08,
self.param_enable_09,
self.param_enable_10,
self.param_enable_11,
self.param_enable_12,
self.param_enable_13,
self.param_enable_14,
self.param_enable_15,
self.param_enable_16,
self.param_enable_17,
]
self.fit_settings = {'theta_min':self.theta_min_value,
'theta_max':self.theta_max_value,
'iterations':self.iterations,
'epsilon':self.epsilon,
'nskip':self.nskip,
'number_layers':self.number_layers,
'tci_pts':self.n_phi,
'integration_width':self.n_sg
}
self.diff_settings = [self.wavelength, self.sample_depth, self.sample_width,
self.goniometer_radius, self.beam_width, self.sample_density]
self.num_params = len(self.parameter_list)
self.init_ui_elements()
self.fig = Figure()
self.ax = self.fig.add_subplot(111)
self.x_data = []
self.y_data = []
self.x_fit_data = []
self.y_fit_data = []
self.prev_x_fit = []
self.prev_y_fit = []
self.ax.tick_params(axis='both', which='major', labelsize=14)
self.ax.set_xlabel('2 $\\theta$ / Degrees', fontsize=14)
self.ax.set_ylabel(r'Intensity / a.u.', fontsize=14)
self.ax.grid(True)
self.addmpl(self.fig)
self.y_axis_lim = None
self.x_axis_lim = None
self.current_filename = None
# Remember the last header lines / separator used
self.last_header_lines_used = 0
self.last_separator_used = 0
# Default data directories
self.default_diff_data_dir = None
self.default_export_dir = None
self.default_carboninp_import_dir = None
self.default_carboninp_export_dir = None
self.default_fitparams_import_dir = None
self.default_fitparams_export_dir = None
self.default_fitsettings_import_dir = None
self.default_fitsettings_export_dir = None
self.default_diffsettings_import_dir = None
self.default_diffsettings_export_dir = None
# Fitting Process
self.fitting_process = QtCore.QProcess(self)
self.fitting_process.readyRead.connect(self.on_process_message)
self.fitting_process.finished.connect(self.fitting_finished)
self.pattern_calc_flag = False
self.abort_flag = False
self.init_menubar_osx()
self.assignWidgets()
self.setWindowTitle("CarbonXS GUI v"+version)
self.showMaximized()
# Undo Buffer
self.append_to_buffer = True
self.undo_buffer = []
self.undo_index = 0
QtGui.QFontDatabase.addApplicationFont(os.path.join(base_directory, 'fonts', 'SourceCodePro-Regular.ttf'))
console_font = QtGui.QFont()
console_font.setFamily('Source Code Pro')
self.console.setFont(console_font)
def write_config(self):
"""
Exports the current program configuration to JSON
:return:
"""
configuration = {'program_config':
{'last_header_lines':self.last_header_lines_used,
'last_separator':self.last_separator_used,
'lock_x':bool(self.lock_x_axis.checkState()),
'lock_y':bool(self.lock_y_axis.checkState()),
'show_previous_fit':bool(self.show_previous.checkState()),
},
'file_defaults':
{'diff_data_dir':self.default_diff_data_dir,
'export_dir':self.default_export_dir,
'export_carboninp':self.default_carboninp_export_dir,
'import_carboninp':self.default_carboninp_import_dir,
'export_fitparams':self.default_fitparams_export_dir,
'import_fitparams':self.default_fitparams_import_dir,
'export_fitsettings':self.default_fitsettings_export_dir,
'import_fitsettings':self.default_fitsettings_import_dir,
'export_diffsettings':self.default_diffsettings_export_dir,
'import_diffsettings':self.default_diffsettings_import_dir,
}
}
config_file = open(os.path.join(user_data_directory, 'config','config.json'), 'w')
ujson.dump(configuration, config_file, indent=4)
def first_time_app_setup(self):
"""
Sets up the directory structure into the user data directories
Returns
-------
"""
print "Running first time app data setup."
print "Creating data directory in %s"%user_data_directory
if not os.path.exists(user_data_directory):
os.makedirs(user_data_directory)
if not os.path.exists(os.path.join(user_data_directory, "config")):
os.mkdir(os.path.join(user_data_directory, "config"))
if not os.path.exists(os.path.join(user_data_directory, "config", 'diffractometer settings')):
os.mkdir(os.path.join(user_data_directory, "config", 'diffractometer settings'))
shutil.copy2(os.path.join(base_directory, 'config','diffractometer settings',
'dal_diffractometer.json'),
os.path.join(user_data_directory, 'config', 'diffractometer settings'))
shutil.copy2(os.path.join(base_directory, 'config','diffractometer settings',
'unm_diffractometer.json'),
os.path.join(user_data_directory, 'config', 'diffractometer settings'))
if not os.path.exists(os.path.join(user_data_directory, "config", 'fitting parameters')):
os.mkdir(os.path.join(user_data_directory, "config", 'fitting parameters'))
shutil.copy2(os.path.join(base_directory, 'config','fitting parameters',
'example_params.json'),
os.path.join(user_data_directory, 'config', 'fitting parameters'))
if not os.path.exists(os.path.join(user_data_directory, "config", 'fitting settings')):
os.mkdir(os.path.join(user_data_directory, "config", 'fitting settings'))
shutil.copy2(os.path.join(base_directory, 'config','fitting settings',
'example_settings.json'),
os.path.join(user_data_directory, 'config', 'fitting settings'))
if not os.path.exists(os.path.join(user_data_directory, "examples")):
os.mkdir(os.path.join(user_data_directory, "examples"))
shutil.copy2(os.path.join(base_directory, 'examples','CARBON.INP'),
os.path.join(user_data_directory, 'examples'))
shutil.copy2(os.path.join(base_directory, 'examples','crystalline_carbon.dat'),
os.path.join(user_data_directory, 'examples'))
def data_init(self):
""""
On startup, read the last used Carbon.INP file
"""
if not os.path.exists(user_data_directory):
self.first_time_app_setup()
# Attempts to load a Carbon.INP file if it exists
try:
self.read_carboninp(os.path.join(base_directory, 'carbonxs', 'carbon.inp'))
print "Loaded most recently used parameters successfully from 'carbonxs' directory."
except IOError:
print "No previous parameters found in 'carbonxs' directory."
# Clears any SCAN.DAT file already in carbonxs directory
if 'SCAN.DAT' in os.listdir(os.path.join(base_directory, 'carbonxs')):
os.remove(os.path.join(base_directory, 'carbonxs', 'SCAN.DAT'))
# Read in the previously written configuration file
if 'config.json' in os.listdir(os.path.join(user_data_directory, 'config')):
config_file = open(os.path.join(user_data_directory, 'config', 'config.json'),'r')
config = ujson.load(config_file)
try:
self.lock_y_axis.setChecked(config['program_config']['lock_y'])
except KeyError:
print "No configuration found for Y Axis Lock in config.json. Setting to default of False."
self.lock_y_axis.setChecked(False)
try:
self.lock_x_axis.setChecked(config['program_config']['lock_x'])
except KeyError:
print "No configuration found for X Axis Lock in config.json. Setting to default of False."
self.lock_x_axis.setChecked(False)
try:
self.show_previous.setChecked(config['program_config']['show_previous_fit'])
except KeyError:
print "No configuration found for Show Previous in config.json. Setting to default of False."
self.show_previous.setChecked(False)
try:
self.last_separator_used = config['program_config']['last_separator']
except KeyError:
print "No configuration found for Last Separator Type used. Defaulting to Whitespace"
self.last_separator_used = 0
try:
self.last_header_lines_used = config['program_config']['last_header_lines']
except KeyError:
print "No configuration found for Last Number of Header Lines used. Defaulting to 0 Header Lines"
self.last_header_lines_used = 0
# Loads file directory defaults from configuration file
try:
self.default_diff_data_dir = config['file_defaults']['diff_data_dir']
except KeyError:
print "No configuration found for default diffraction data directory. Using default directory."
self.default_diff_data_dir = None
try:
self.default_export_dir = config['file_defaults']['export_dir']
except KeyError:
print "No configuration found for default export data directory. Using default directory."
self.default_export_dir = None
try:
self.default_carboninp_export_dir = config['file_defaults']['export_carboninp']
except KeyError:
print "No configuration found for default carbon.inp export directory. Using default directory."
self.default_carboninp_export_dir = None
try:
self.default_carboninp_import_dir = config['file_defaults']['import_carboninp']
except KeyError:
print "No configuration found for default carbon.inp import directory. Using default directory."
self.default_carboninp_import_dir = None
try:
self.default_fitparams_export_dir = config['file_defaults']['export_fitparams']
except KeyError:
print "No configuration found for default fit parameters export directory. Using default directory."
self.default_fitparams_export_dir = None
try:
self.default_fitparams_import_dir = config['file_defaults']['import_fitparams']
except KeyError:
print "No configuration found for default fit parameters import directory. Using default directory."
self.default_fitparams_import_dir = None
try:
self.default_fitsettings_export_dir = config['file_defaults']['export_fitsettings']
except KeyError:
print "No configuration found for default fit settings export directory. Using default directory."
self.default_fitsettings_export_dir = None
try:
self.default_fitsettings_import_dir = config['file_defaults']['import_fitsettings']
except KeyError:
print "No configuration found for default fit settings import directory. Using default directory."
self.default_fitsettings_import_dir = None
try:
self.default_diffsettings_export_dir = config['file_defaults']['export_diffsettings']
except KeyError:
print "No configuration found for default diffractometer settings export directory. Using default directory."
self.default_diffsettings_export_dir = None
try:
self.default_diffsettings_import_dir = config['file_defaults']['import_diffsettings']
except KeyError:
print "No configuration found for default diffractometer settings import directory. Using default directory."
self.default_diffsettings_import_dir = None
self.check_pt_parameter()
self.check_undo_index()
def check_pt_parameter(self):
"""
Depending on the model used, parameter 15 is overloaded to be 2 variables:
1 layer model - g / Fraction of Low Strain Carbon
2 layer model - Pt / Probability of 3R stacking
:return:
"""
if self.number_layers.currentIndex() == 0:
self.param_label_15.setText('g, Fraction of Low Strain Carbon')
print "Currently using 1 layer model - Parameter 15 is g, Fraction of Low Strain Carbon."
else:
self.param_label_15.setText('Pt, Probability of 3R Stacking')
print "Currently using 2 layer model - Parameter 15 is Pt, Probability of 3R Stacking."
def init_menubar_osx(self):
"""
Re-initializes the menubar for OSX to make it appear at the top of the screen.
:return:
"""
if sys.platform == 'darwin':
self.menubar = QtGui.QMenuBar()
self.menubar.setGeometry(QtCore.QRect(0, 0, 1366, 21))
self.menubar.setNativeMenuBar(True)
self.menubar.setObjectName("menubar")
self.menu_file = QtGui.QMenu(self.menubar)
self.menu_file.setObjectName("menu_file")
self.menu_category_import = QtGui.QMenu(self.menu_file)
self.menu_category_import.setObjectName("menu_category_import")
self.menuExport = QtGui.QMenu(self.menu_file)
self.menuExport.setObjectName("menuExport")
self.menuFitting = QtGui.QMenu(self.menubar)
self.menuFitting.setObjectName("menuFitting")
self.menuHelp = QtGui.QMenu(self.menubar)
self.menuHelp.setObjectName("menuHelp")
self.setMenuBar(self.menubar)
self.menu_open_xrd_pattern = QtGui.QAction(self)
self.menu_open_xrd_pattern.setObjectName("menu_open_xrd_pattern")
self.menu_import_carboninp = QtGui.QAction(self)
self.menu_import_carboninp.setObjectName("menu_import_carboninp")
self.menu_import_diffsettings = QtGui.QAction(self)
self.menu_import_diffsettings.setObjectName("menu_import_diffsettings")
self.menu_import_fittingparams = QtGui.QAction(self)
self.menu_import_fittingparams.setObjectName("menu_import_fittingparams")
self.menu_import_fittingsettings = QtGui.QAction(self)
self.menu_import_fittingsettings.setObjectName("menu_import_fittingsettings")
self.menu_export_carboninp = QtGui.QAction(self)
self.menu_export_carboninp.setObjectName("menu_export_carboninp")
self.menu_export_diffsettings = QtGui.QAction(self)
self.menu_export_diffsettings.setObjectName("menu_export_diffsettings")
self.menu_export_fittingparams = QtGui.QAction(self)
self.menu_export_fittingparams.setObjectName("menu_export_fittingparams")
self.menu_export_fittingsettings = QtGui.QAction(self)
self.menu_export_fittingsettings.setObjectName("menu_export_fittingsettings")
self.menu_calculate_pattern = QtGui.QAction(self)
self.menu_calculate_pattern.setObjectName("menu_calculate_pattern")
self.menu_start_fit = QtGui.QAction(self)
self.menu_start_fit.setObjectName("menu_start_fit")
self.menu_abort_fit = QtGui.QAction(self)
self.menu_abort_fit.setObjectName("menu_abort_fit")
self.menu_tutorial = QtGui.QAction(self)
self.menu_tutorial.setObjectName("menu_tutorial")
self.menu_bugreport = QtGui.QAction(self)
self.menu_bugreport.setObjectName("menu_bugreport")
self.menu_about = QtGui.QAction(self)
self.menu_about.setObjectName("menu_about")
self.menu_exit = QtGui.QAction(self)
self.menu_exit.setObjectName("menu_exit")
self.menu_category_import.addAction(self.menu_import_carboninp)
self.menu_category_import.addAction(self.menu_import_fittingparams)
self.menu_category_import.addAction(self.menu_import_fittingsettings)
self.menu_category_import.addAction(self.menu_import_diffsettings)
self.menuExport.addAction(self.menu_export_carboninp)
self.menuExport.addAction(self.menu_export_fittingparams)
self.menuExport.addAction(self.menu_export_fittingsettings)
self.menuExport.addAction(self.menu_export_diffsettings)
self.menu_file.addAction(self.menu_open_xrd_pattern)
self.menu_file.addAction(self.menu_category_import.menuAction())
self.menu_file.addAction(self.menuExport.menuAction())
self.menu_file.addAction(self.menu_exit)
self.menuFitting.addAction(self.menu_calculate_pattern)
self.menuFitting.addAction(self.menu_start_fit)
self.menuFitting.addAction(self.menu_abort_fit)
self.menuHelp.addAction(self.menu_tutorial)
self.menuHelp.addAction(self.menu_bugreport)
self.menuHelp.addAction(self.menu_about)
self.menubar.addAction(self.menu_file.menuAction())
self.menubar.addAction(self.menuFitting.menuAction())
self.menubar.addAction(self.menuHelp.menuAction())
self.retranslateUi(self)
def init_ui_elements(self):
"""
Initiates the toolbar buttons
:return:
"""
self.open_pattern_button = QtGui.QAction(QtGui.QIcon(os.path.join(base_directory,'icons','open.png')), 'Open Pattern', self)
self.open_pattern_button.setStatusTip('Open Pattern')
self.open_pattern_button.setToolTip("Opens a new XRD pattern.")
self.calculate_pattern_button= QtGui.QAction(QtGui.QIcon(os.path.join(base_directory,'icons','calculator.png')), 'Calculate', self)
self.calculate_pattern_button.setStatusTip('Calculate Pattern')
self.calculate_pattern_button.setToolTip("Calculates pattern using current parameters without performing a fit.")
self.fit_pattern_button= QtGui.QAction(QtGui.QIcon(os.path.join(base_directory,'icons','fit.png')), 'Fit', self)
self.fit_pattern_button.setStatusTip('Fit Pattern')
self.fit_pattern_button.setToolTip("Uses current parameters to perform a fit.")
self.abort_fit_button= QtGui.QAction(QtGui.QIcon(os.path.join(base_directory,'icons','stop.png')), 'Abort', self)
self.abort_fit_button.setStatusTip('Abort Fit')
self.abort_fit_button.setEnabled(False)
self.abort_fit_button.setToolTip("Aborts current fit by killing CarbonXS process.")
self.export_fit_button= QtGui.QAction(QtGui.QIcon(os.path.join(base_directory,'icons','export.png')), 'Export Last Fit', self)
self.export_fit_button.setStatusTip('Export Last Fit')
self.export_fit_button.setToolTip("Export the carbon.out, carbon.dat, and new CARBON.INP files of the most recent fit run by CarbonXS.")
self.back_button = QtGui.QAction(QtGui.QIcon(os.path.join(base_directory,'icons','back_button.png')), 'Previous Fit/Calc', self)
self.back_button.setStatusTip('Go to Previous Fit or Calculation')
self.back_button.setToolTip("Go to Previous Fit or Calculation")
self.forward_button = QtGui.QAction(QtGui.QIcon(os.path.join(base_directory,'icons','forward_button.png')), 'Next Fit/Calc', self)
self.forward_button.setStatusTip('Go to Next Fit or Calculation')
self.forward_button.setToolTip("Go to Next Fit or Calculation")
self.toolbar = self.addToolBar('Tools')
self.toolbar.addAction(self.open_pattern_button)
self.toolbar.addAction(self.calculate_pattern_button)
self.toolbar.addAction(self.fit_pattern_button)
self.toolbar.addAction(self.abort_fit_button)
self.toolbar.addAction(self.export_fit_button)
self.toolbar.addAction(self.back_button)
self.toolbar.addAction(self.forward_button)
# Any time the layer model changes, update the Pt parameter
self.number_layers.currentIndexChanged.connect(self.check_pt_parameter)
@QtCore.Slot(str)
def on_stream_message(self, message):
"""
Method for reading print messages and error messages that are sent to the console
:param message:
:return:
"""
self.console.moveCursor(QtGui.QTextCursor.End)
self.console.insertPlainText(message)
self.console.moveCursor(QtGui.QTextCursor.End)
def on_process_message(self):
"""
Method for reading messages from the carbonxs.exe process
:return:
"""
self.console.moveCursor(QtGui.QTextCursor.End)
message = str(self.fitting_process.readAll())
self.console.insertPlainText(message)
self.console.moveCursor(QtGui.QTextCursor.End)
# if a singular matrix is detected raise the option to abort the fit.
if "Singular matrix." in message:
reply = QtGui.QMessageBox.critical(self, 'Singular matrix detected.',
"Singular matrix detected. Abort?", QtGui.QMessageBox.Yes |
QtGui.QMessageBox.No, QtGui.QMessageBox.Yes)
if reply == QtGui.QMessageBox.Yes:
self.abort_fit_process()
def addmpl(self, fig):
"""
Add a Matplotlib object to the plot
:param fig:
:return:
"""
self.canvas = FigureCanvas(fig)
self.canvas.setMinimumHeight(100)
self.mplvl.addWidget(self.canvas, 2, 0)
self.canvas.draw()
self.mpl_toolbar = NavigationToolbar(self.canvas, self)
self.mplvl.addWidget(self.mpl_toolbar)
self.plot_buttons_layout = QtGui.QHBoxLayout()
self.plot_pattern_button = QtGui.QPushButton(self)
self.plot_pattern_button.setText("Pattern + Last Fit")
self.plot_pattern_button.setToolTip("Plots the currently loaded pattern and the last fit result.")
self.plot_difference_button = QtGui.QPushButton(self)
self.plot_difference_button.setText("Last Fit Difference")
self.plot_difference_button.setToolTip("Plots the difference between source and fit data for the last fit result.")
self.lock_y_axis = QtGui.QCheckBox(self)
self.lock_y_axis.setText("Lock Pattern/Fit Y-Axis")
self.lock_y_axis.setToolTip("Locks the Y-Axis during pattern/fit plotting.")
self.lock_x_axis = QtGui.QCheckBox(self)
self.lock_x_axis.setText("Lock Pattern/Fit X-Axis")
self.lock_x_axis.setToolTip("Locks the X-Axis during pattern/fit plotting.")
self.show_previous = QtGui.QCheckBox(self)
self.show_previous.setText("Show Previous Fit")
self.show_previous.setToolTip("Shows the Previous Iteration's Fit Result")
self.plot_buttons_layout.addWidget(self.plot_pattern_button)
self.plot_buttons_layout.addWidget(self.plot_difference_button)
self.plot_buttons_layout.addWidget(self.lock_y_axis)
self.plot_buttons_layout.addWidget(self.lock_x_axis)
self.plot_buttons_layout.addWidget(self.show_previous)
self.mplvl.addLayout(self.plot_buttons_layout)
def assignWidgets(self):
"""
Assigns buttons and menu items to functions
:return:
"""
# Toolbar buttons
self.open_pattern_button.triggered.connect(self.open_pattern)
self.calculate_pattern_button.triggered.connect(lambda: self.calculate_pattern(append_to_buffer=True))
self.fit_pattern_button.triggered.connect(self.start_fitting_process)
self.abort_fit_button.triggered.connect(self.abort_fit_process)
self.export_fit_button.triggered.connect(self.export_fit_results)
self.back_button.triggered.connect(self.go_back)
self.forward_button.triggered.connect(self.go_forward)
# Enable/Disable/Invert All Parameter Buttons
self.enable_all_button.clicked.connect(self.enable_all_params)
self.enable_none_button.clicked.connect(self.disable_all_params)
self.enable_invert_button.clicked.connect(self.invert_all_params)
self.enable_bg_button.clicked.connect(self.enable_background_params)
# self.import_data.clicked.connect(self.load_parameters)
self.menu_open_xrd_pattern.triggered.connect(self.open_pattern)
self.menu_import_carboninp.triggered.connect(self.import_from_carboninp)
self.menu_import_diffsettings.triggered.connect(self.import_diffractometer_params)
self.menu_import_fittingparams.triggered.connect(self.import_fitting_params)
self.menu_import_fittingsettings.triggered.connect(self.import_fitting_settings)
self.menu_exit.triggered.connect(self.close)
# Export Data
self.menu_export_carboninp.triggered.connect(self.export_to_carboninp)
self.menu_export_diffsettings.triggered.connect(self.export_diffractometer_params)
self.menu_export_fittingparams.triggered.connect(self.export_fitting_params)
self.menu_export_fittingsettings.triggered.connect(self.export_fitting_settings)
# Fitting Process Options
self.menu_calculate_pattern.triggered.connect(lambda: self.calculate_pattern(append_to_buffer=True))
self.menu_start_fit.triggered.connect(self.start_fitting_process)
self.menu_abort_fit.triggered.connect(self.abort_fit_process)
# Graph buttons
self.plot_pattern_button.clicked.connect(self.plot_loaded_data)
self.plot_difference_button.clicked.connect(self.plot_difference)
# Help Menu
self.menu_tutorial.triggered.connect(self.open_documentation)
self.menu_bugreport.triggered.connect(self.open_bug_report_page)
self.menu_about.triggered.connect(self.open_about_dialog)
self.set_shortcut_keys()
def set_shortcut_keys(self):
"""
Sets the shortcut keys for widgets
:return:
"""
self.menu_open_xrd_pattern.setShortcut(QtGui.QKeySequence.Open)
self.menu_tutorial.setShortcut(QtGui.QKeySequence.HelpContents)
self.menu_calculate_pattern.setShortcut(Qt.CTRL+Qt.Key_R)
self.menu_start_fit.setShortcut(Qt.CTRL+Qt.SHIFT+Qt.Key_R)
self.menu_abort_fit.setShortcut(Qt.CTRL+Qt.Key_D)
self.back_button.setShortcut(QtGui.QKeySequence.Back)
self.forward_button.setShortcut(QtGui.QKeySequence.Forward)
if 'win32' in sys.platform:
self.menu_exit.setShortcut(Qt.ALT+Qt.Key_F4)
else:
self.menu_exit.setShortcut(QtGui.QKeySequence.Quit)
self.open_pattern_button.setToolTip(self.open_pattern_button.toolTip()+" (%s)"%QtGui.QKeySequence.toString(QtGui.QKeySequence(QtGui.QKeySequence.Open),
format=QKeySequence.NativeText))
self.calculate_pattern_button.setToolTip(self.calculate_pattern_button.toolTip()+" (%s)"%QtGui.QKeySequence.toString(QtGui.QKeySequence(Qt.CTRL+Qt.Key_R),
format=QKeySequence.NativeText))
self.fit_pattern_button.setToolTip(self.fit_pattern_button.toolTip()+" (%s)"%QtGui.QKeySequence.toString(QtGui.QKeySequence(Qt.CTRL+Qt.SHIFT+Qt.Key_R),
format=QKeySequence.NativeText))
self.abort_fit_button.setToolTip(self.abort_fit_button.toolTip()+" (%s)"%QtGui.QKeySequence.toString(QtGui.QKeySequence(Qt.CTRL+Qt.Key_D),
format=QKeySequence.NativeText))
self.back_button.setToolTip(self.back_button.toolTip()+" (%s)"%QtGui.QKeySequence.toString(QtGui.QKeySequence(QtGui.QKeySequence.Back),
format=QKeySequence.NativeText))
self.forward_button.setToolTip(self.forward_button.toolTip()+" (%s)"%QtGui.QKeySequence.toString(QtGui.QKeySequence(QtGui.QKeySequence.Forward),
format=QKeySequence.NativeText))
def plot_difference(self):
"""
Loads the current carbon.dat and plots the difference between source and fit data.
:return:
"""
if len(self.x_data) == 0:
reply = QtGui.QMessageBox.information(self, 'Warning',
"No pattern data loaded. Cannot calculate a difference.",
QtGui.QMessageBox.Close)
return
pattern_filename = os.path.join(base_directory, 'carbonxs', 'carbon.dat')
self.x_fit_data = []
self.y_fit_data = []
fit_color = "#fc8d62"
pattern_file = open(pattern_filename, 'r')
for line in pattern_file.readlines():
data_elements = line.split()
self.x_fit_data.append(float(data_elements[0]))
self.y_fit_data.append(float(data_elements[2]))
interpolated_y_data = np.interp(np.array(self.x_data), np.array(self.x_fit_data), np.array(self.y_fit_data))
self.fig.clf()
self.ax_diff = self.fig.add_subplot(111)
self.ax_diff.plot(self.x_data, np.array(self.y_data) - interpolated_y_data, label="Source - Fit", linewidth = 2, color=fit_color)
self.ax_diff.ticklabel_format(style='sci', scilimits=(-3,4), axis='y')
self.ax_diff.tick_params(axis='both', which='major', labelsize=14)
self.ax_diff.set_xlabel('2 $\\theta$ / Degrees', fontsize=14)
self.ax_diff.set_ylabel(r'Intensity / a.u.', fontsize=14)
if self.current_filename:
self.ax_diff.set_title("Difference - %s"%self.current_filename)
else:
self.ax_diff.set_title("Difference")
self.ax_diff.legend(fontsize=14, frameon=True)
self.ax_diff.grid(True)
self.canvas.draw()
def disable_all_params(self):
"""
Turns off all fitting parameters
:return:
"""
for setting in self.parameter_enable_list:
setting.setChecked(False)
def enable_all_params(self):
"""
Turns on all fitting parameters
:return:
"""
for setting in self.parameter_enable_list:
setting.setChecked(True)
def invert_all_params(self):
"""
Inverts all fitting parameters. Enabled becomes disabled and disabled becomes enabled.
:return:
"""
for setting in self.parameter_enable_list:
setting.setChecked(not setting.isChecked())
def enable_background_params(self):
"""
Enables only the fitting parameters for the background.
:return:
"""
for index, setting in enumerate(self.parameter_enable_list):
if index > 0 and index < 7:
setting.setChecked(True)
else:
setting.setChecked(False)
def open_pattern(self):
"""
Method to call up a file dialog and ask the user to load an XRD pattern
:return:
"""
if self.default_diff_data_dir:
full_path, _= QtGui.QFileDialog.getOpenFileName(self, 'Open file', self.default_diff_data_dir)
else:
full_path, _= QtGui.QFileDialog.getOpenFileName(self, 'Open file', user_data_directory)
previous_filename = self.current_filename
if full_path:
input_file = open(full_path, 'r')
directory, filename = os.path.split(full_path)
if full_path.endswith('.mdi'):
try:
print "Attempting to load MDI file: %s"%full_path
self.x_data, self.y_data = data_io.read_mdi_file(full_path)
self.current_filename = filename
self.default_diff_data_dir = directory
except ValueError:
print "Error: Improperly formatted pattern file in file %s."%full_path
print "The pattern file should conform to the JADE MDI format."
self.current_filename = previous_filename
return
elif full_path.endswith('.ras'):
try:
print "Attempting to load RAS file: %s"%full_path
self.x_data, self.y_data = data_io.read_ras_file(full_path)
self.current_filename = filename
self.default_diff_data_dir = directory
except ValueError:
print "Error: Improperly formatted pattern file in file %s."%full_path
print "The pattern file should conform to the RAS format."
self.current_filename = previous_filename
return
else:
# Pops up dialog with
loadtxt_dialog = TextFileViewer(self)
loadtxt_dialog.load_contents(full_path)
loadtxt_dialog.header_lines.setValue(self.last_header_lines_used)
loadtxt_dialog.separator_selector.setCurrentIndex(self.last_separator_used)
header_dialog_accepted = loadtxt_dialog.exec_()
header_lines = 0
if header_dialog_accepted:
header_lines = loadtxt_dialog.header_lines.value()
separator_selection = loadtxt_dialog.separator_selector.currentIndex()
if separator_selection == 1:
separator = ','
elif separator_selection == 0:
separator = None
else:
print "Some other separator not currently implemented is selected"
else:
# User cancelled
self.current_filename = previous_filename
return
if header_lines:
print "Skipping first %d lines as header."%header_lines
print "Attempting to load data from text file: %s"%full_path
try:
if separator:
plot_data = np.loadtxt(input_file, skiprows=header_lines, delimiter=separator)
else:
plot_data = np.loadtxt(input_file, skiprows=header_lines)
self.x_data = plot_data[:, 0]
self.y_data = plot_data[:, 1]
self.theta_min_value.setValue(np.min(self.x_data))
self.theta_max_value.setValue(np.max(self.x_data))
self.current_filename = filename
self.last_header_lines_used = header_lines
self.last_separator_used = separator_selection
self.default_diff_data_dir = directory
except ValueError:
print "Error: loading data from %s"%full_path
print "Please check that the number of header lines and the separator is correct."