-
Notifications
You must be signed in to change notification settings - Fork 50
/
mainwindow.py
2179 lines (1868 loc) · 87 KB
/
mainwindow.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
from __future__ import print_function
import os
import copy
import logging
import matplotlib
import numpy as np
import scipy
import sys
import signal
import warnings
from io import BytesIO
import six
from collections import OrderedDict
from getdist.gui.qt_import import pyside_version
import getdist
from getdist import plots, IniFile
from getdist.chain_grid import ChainDirGrid, file_root_to_root, get_chain_root_files, load_supported_grid
from getdist.mcsamples import SettingError, ParamError
from getdist.gui.SyntaxHighlight import PythonHighlighter
import matplotlib.pyplot as plt
if pyside_version == 2:
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as QNavigationToolbar
import PySide2 as PySide
from PySide2.QtGui import QIcon, QKeySequence, QFont, QTextOption, QPixmap, QImage
from PySide2.QtCore import Qt, SIGNAL, QSize, QSettings, QCoreApplication
from PySide2.QtWidgets import QListWidget, QMainWindow, QDialog, QApplication, QAbstractItemView, QAction, \
QTabWidget, QWidget, QComboBox, QPushButton, QShortcut, QCheckBox, QRadioButton, QGridLayout, QVBoxLayout, \
QSplitter, QHBoxLayout, QToolBar, QPlainTextEdit, QScrollArea, QFileDialog, QMessageBox, QTableWidgetItem, \
QLabel, QTableWidget, QListWidgetItem, QTextEdit
os.environ['QT_API'] = 'pyside2'
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling) # DPI support
QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)
class NavigationToolbar(QNavigationToolbar):
def sizeHint(self):
return QToolBar.sizeHint(self)
else:
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
import PySide
from PySide.QtCore import Qt, SIGNAL, QSize, QSettings, QCoreApplication
from PySide.QtGui import QListWidget, QMainWindow, QDialog, QApplication, QAbstractItemView, QAction, \
QTabWidget, QWidget, QComboBox, QPushButton, QShortcut, QCheckBox, QRadioButton, QGridLayout, QVBoxLayout, \
QSplitter, QHBoxLayout, QToolBar, QPlainTextEdit, QScrollArea, QFileDialog, QMessageBox, QTableWidgetItem, \
QLabel, QTableWidget, QListWidgetItem, QTextEdit, QIcon, QKeySequence, QFont, QTextOption, QImage, QPixmap
os.environ['QT_API'] = 'pyside'
class GuiSelectionError(Exception):
pass
class QStatusLogger(logging.Handler):
def __init__(self, parent):
super(QStatusLogger, self).__init__(level=logging.WARNING)
self.widget = parent
def emit(self, record):
msg = self.format(record)
self.widget.showMessage(msg, color='red')
def write(self, m):
pass
class RootListWidget(QListWidget):
def __init__(self, widget, owner):
QListWidget.__init__(self, widget)
self.setDragDropMode(self.InternalMove)
self.setMaximumSize(QSize(16777215, 120))
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.setSelectionMode(QAbstractItemView.SingleSelection)
self.setDragEnabled(True)
self.viewport().setAcceptDrops(True)
self.setDropIndicatorShown(True)
self.setDragDropMode(QAbstractItemView.InternalMove)
self.owner = owner
def dropEvent(self, event):
super(RootListWidget, self).dropEvent(event)
self.owner._updateParameters()
class MainWindow(QMainWindow):
def __init__(self, app, ini=None, base_dir=None):
"""
Initialize of GUI components.
"""
super(MainWindow, self).__init__()
self.setWindowTitle("GetDist GUI")
self.setWindowIcon(self._icon('Icon', False))
if base_dir is None:
try:
# If cosmomc is configured
from paramgrid import batchjob
base_dir = batchjob.getCodeRootPath()
except ImportError:
pass
if base_dir:
os.chdir(base_dir)
self.updating = False
self.app = app
self.base_dir = base_dir
self.orig_rc = matplotlib.rcParams.copy()
self.plot_module = 'getdist.plots'
self.script_plot_module = self.plot_module
# GUI setup
self.createActions()
self.createMenus()
self._createWidgets()
self.createStatusBar()
self.settingDlg = None
self.ConfigDlg = None
self.plotSettingDlg = None
self.custom_plot_settings = {}
self.setAttribute(Qt.WA_DeleteOnClose)
if os.name == 'nt':
# This is needed to display the app icon on the taskbar on Windows 7+
import ctypes
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID('GetDist.Gui.1.0.0')
# Allow to shutdown the GUI with Ctrl+C
signal.signal(signal.SIGINT, signal.SIG_DFL)
# Path for .ini file
self.default_settings = IniFile(getdist.default_getdist_settings)
self.iniFile = ini
if ini:
self.base_settings = IniFile(ini)
else:
self.base_settings = self.default_settings
self.current_settings = copy.deepcopy(self.base_settings)
# Path of root directory
self.rootdirname = None
self.plotter = None
self.root_infos = {}
self._resetGridData()
self._resetPlotData()
self.log_handler = QStatusLogger(self)
logging.getLogger().addHandler(self.log_handler)
self._last_color = None
dirs = self.getSettings().value('directoryList')
last_dir = self.getSettings().value('lastSearchDirectory')
if dirs is None and last_dir:
dirs = [last_dir]
elif isinstance(dirs, six.string_types):
dirs = [dirs] # QSettings doesn't save single item lists reliably
if dirs is not None:
dirs = [x for x in dirs if os.path.exists(x)]
if last_dir is not None and last_dir not in dirs and os.path.exists(last_dir):
dirs.insert(0, last_dir)
self.listDirectories.addItems(dirs)
if last_dir is not None and os.path.exists(last_dir):
self.listDirectories.setCurrentIndex(dirs.index(last_dir))
self.openDirectory(last_dir)
else:
self.listDirectories.setCurrentIndex(-1)
def createActions(self):
"""
Create Qt actions used in GUI.
"""
self.openChainsAct = QAction("&Open folder...", self,
shortcut="Ctrl+O",
statusTip="Open a directory containing chain (sample files) to use",
triggered=self.selectRootDirName)
self.exportAct = QAction("&Export as PDF/Image...", self,
statusTip="Export image as PDF, PNG, JPG",
triggered=self.export)
self.exportAct.setEnabled(False)
self.scriptAct = QAction("Save script...", self,
shortcut="Ctrl+S",
statusTip="Export commands to script",
triggered=self.saveScript)
self.reLoadAct = QAction("Re-load files", self,
statusTip="Re-scan directory",
triggered=self.reLoad)
self.exitAct = QAction("Exit", self,
shortcut="Ctrl+Q",
statusTip="Exit application",
triggered=self.close)
self.statsAct = QAction("Marge Stats", self,
shortcut="",
statusTip="Show Marge Stats",
triggered=self.showMargeStats)
self.likeStatsAct = QAction("Like Stats", self,
shortcut="",
statusTip="Show Likelihood (N-D) Stats",
triggered=self.showLikeStats)
self.convergeAct = QAction("Converge Stats", self,
statusTip="Show Convergence Stats",
triggered=self.showConvergeStats)
self.PCAAct = QAction("Parameter PCA", self,
statusTip="Do PCA of selected parameters",
triggered=self.showPCA)
self.paramTableAct = QAction("Parameter table (latex)", self,
statusTip="View parameter table",
triggered=self.showParamTable)
self.optionsAct = QAction("Analysis settings", self,
statusTip="Show settings for getdist and plot densities",
triggered=self.showSettings)
self.plotOptionsAct = QAction("Plot settings", self,
statusTip="Show settings for plot display",
triggered=self.showPlotSettings)
self.resetPlotOptionsAct = QAction("Reset plot settings", self,
statusTip="Reset settings for plot display",
triggered=self.resetPlotSettings)
self.resetAnalysisSettingsAct = QAction("Reset analysis settings", self,
statusTip="Reset settings for sample analysis",
triggered=self.resetAnalysisSettings)
self.configOptionsAct = QAction("Plot style module", self,
statusTip="Configure plot module that sets default settings",
triggered=self.showConfigSettings)
self.helpAct = QAction("GetDist documentation", self,
statusTip="Show getdist readthedocs",
triggered=self.openHelpDocs)
self.githubAct = QAction("GetDist on GitHub", self,
statusTip="Show getdist source",
triggered=self.openGitHub)
self.planckAct = QAction("Download Planck chains", self,
statusTip="Download sample chain files",
triggered=self.openPlanck)
self.aboutAct = QAction("About", self,
statusTip="Show About box",
triggered=self.about)
def createMenus(self):
"""
Create Qt menus.
"""
menu = self.menuBar()
self.menu = menu
self.fileMenu = menu.addMenu("&File")
self.fileMenu.addAction(self.openChainsAct)
self.fileMenu.addAction(self.exportAct)
self.fileMenu.addAction(self.scriptAct)
self.separatorAct = self.fileMenu.addSeparator()
self.fileMenu.addAction(self.reLoadAct)
self.fileMenu.addAction(self.exitAct)
menu.addSeparator()
self.dataMenu = menu.addMenu("&Data")
self.dataMenu.addAction(self.statsAct)
self.dataMenu.addAction(self.likeStatsAct)
self.dataMenu.addAction(self.convergeAct)
self.dataMenu.addSeparator()
self.dataMenu.addAction(self.PCAAct)
self.dataMenu.addAction(self.paramTableAct)
menu.addSeparator()
self.optionMenu = menu.addMenu("&Options")
self.optionMenu.addAction(self.optionsAct)
self.optionMenu.addAction(self.plotOptionsAct)
self.optionMenu.addAction(self.configOptionsAct)
self.optionMenu.addSeparator()
self.optionMenu.addAction(self.resetAnalysisSettingsAct)
self.optionMenu.addAction(self.resetPlotOptionsAct)
menu.addSeparator()
self.helpMenu = menu.addMenu("&Help")
self.helpMenu.addAction(self.helpAct)
self.helpMenu.addAction(self.githubAct)
self.helpMenu.addSeparator()
self.helpMenu.addAction(self.planckAct)
self.helpMenu.addSeparator()
self.helpMenu.addAction(self.aboutAct)
def createStatusBar(self):
"""
Create Qt status bar.
"""
self.statusBar().setStyleSheet("height:1em")
self.statusBar().showMessage("Ready", 2000)
def showMessage(self, msg='', color=None):
if not msg and not color and self._last_color:
return
self._last_color = color
bar = self.statusBar()
bar.showMessage(msg)
bar.setStyleSheet("color: %s" % (color or "black"))
if msg:
self.statusBar().repaint()
QCoreApplication.processEvents()
def _image_file(self, name):
return os.path.join(os.path.dirname(__file__), 'images', name)
def _icon(self, name, large=True):
if pyside_version > 1 and large:
name = name + '_large'
pm = QPixmap(self._image_file('%s.png' % name))
if hasattr(pm, 'setDevicePixelRatio'):
pm.setDevicePixelRatio(self.devicePixelRatio())
return QIcon(pm)
def _createWidgets(self):
"""
Create widgets.
"""
if sys.platform in ["darwin", "Windows"]:
self.setStyleSheet("* {font-size:9pt} QComboBox,QPushButton {height:1.3em}")
else:
self.setStyleSheet("* {font-size:12px} QComboBox,QPushButton {height:1.3em}")
self.tabWidget = QTabWidget(self)
self.tabWidget.setTabPosition(QTabWidget.East)
self.tabWidget.setTabPosition(QTabWidget.South)
self.connect(self.tabWidget, SIGNAL("currentChanged(int)"), self.tabChanged)
self.setCentralWidget(self.tabWidget)
# First tab: Gui Selection
self.firstWidget = QWidget(self)
self.tabWidget.addTab(self.firstWidget, "Gui Selection")
self.selectWidget = QWidget(self.firstWidget)
self.listDirectories = QComboBox(self.selectWidget)
self.connect(self.listDirectories, SIGNAL("activated(const QString&)"), self.openDirectory)
self.pushButtonSelect = QPushButton(self._icon("open"), "", self.selectWidget)
self.pushButtonSelect.setMaximumWidth(30)
self.pushButtonSelect.setToolTip("Open chain file root directory")
self.connect(self.pushButtonSelect, SIGNAL("clicked()"), self.selectRootDirName)
self.listRoots = RootListWidget(self.selectWidget, self)
self.connect(self.listRoots, SIGNAL("itemChanged(QListWidgetItem *)"), self.updateListRoots)
self.connect(self.listRoots, SIGNAL("itemSelectionChanged()"), self.selListRoots)
self.pushButtonRemove = QPushButton(self._icon('remove'), "", self.selectWidget)
self.pushButtonRemove.setToolTip("Remove a chain root")
self.pushButtonRemove.setEnabled(False)
self.pushButtonRemove.setMaximumWidth(30)
self.connect(self.pushButtonRemove, SIGNAL("clicked()"), self.removeRoot)
self.comboBoxParamTag = QComboBox(self.selectWidget)
self.comboBoxParamTag.clear()
self.connect(self.comboBoxParamTag, SIGNAL("activated(const QString&)"), self.setParamTag)
self.comboBoxDataTag = QComboBox(self.selectWidget)
self.comboBoxDataTag.clear()
self.connect(self.comboBoxDataTag, SIGNAL("activated(const QString&)"), self.setDataTag)
self.comboBoxRootname = QComboBox(self.selectWidget)
self.comboBoxRootname.clear()
self.connect(self.comboBoxRootname, SIGNAL("activated(const QString&)"), self.setRootname)
self.listParametersX = QListWidget(self.selectWidget)
self.listParametersX.clear()
self.connect(self.listParametersX, SIGNAL("itemChanged(QListWidgetItem *)"), self.itemCheckChange)
self.listParametersY = QListWidget(self.selectWidget)
self.listParametersY.clear()
self.connect(self.listParametersY, SIGNAL("itemChanged(QListWidgetItem *)"), self.itemCheckChange)
self.selectAllX = QCheckBox("Select All", self.selectWidget)
self.selectAllX.setCheckState(Qt.Unchecked)
self.connect(self.selectAllX, SIGNAL("clicked()"), self.statusSelectAllX)
self.selectAllY = QCheckBox("Select All", self.selectWidget)
self.selectAllY.setCheckState(Qt.Unchecked)
self.connect(self.selectAllY, SIGNAL("clicked()"), self.statusSelectAllY)
self.toggleFilled = QRadioButton("Filled")
self.toggleLine = QRadioButton("Line")
self.connect(self.toggleLine, SIGNAL("toggled(bool)"), self.statusPlotType)
self.checkShade = QCheckBox("Shaded", self.selectWidget)
self.checkShade.setEnabled(False)
self.checkInsideLegend = QCheckBox("Axis legend", self.selectWidget)
self.checkInsideLegend.setCheckState(Qt.Unchecked)
self.checkInsideLegend.setVisible(False)
self.toggleColor = QRadioButton("Color by:")
self.connect(self.toggleColor, SIGNAL("toggled(bool)"), self.statusPlotType)
self.comboBoxColor = QComboBox(self)
self.comboBoxColor.clear()
self.comboBoxColor.setEnabled(False)
self.toggleFilled.setChecked(True)
self.trianglePlot = QCheckBox("Triangle Plot", self.selectWidget)
self.trianglePlot.setCheckState(Qt.Unchecked)
self.connect(self.trianglePlot, SIGNAL("toggled(bool)"), self.statusTriangle)
self.pushButtonPlot = QPushButton("Make plot", self.selectWidget)
self.connect(self.pushButtonPlot, SIGNAL("clicked()"), self.plotData)
def h_stack(*items):
widget = QWidget(self.selectWidget)
lay = QHBoxLayout(widget)
lay.setContentsMargins(0, 0, 0, 0)
for item in items:
lay.addWidget(item)
widget.setLayout(lay)
lay.setAlignment(items[1], Qt.AlignTop)
return widget
# Graphic Layout
leftLayout = QGridLayout()
leftLayout.setSpacing(5)
leftLayout.addWidget(h_stack(self.listDirectories, self.pushButtonSelect), 0, 0, 1, 4)
leftLayout.addWidget(self.comboBoxRootname, 1, 0, 1, 3)
leftLayout.addWidget(self.comboBoxParamTag, 1, 0, 1, 4)
leftLayout.addWidget(self.comboBoxDataTag, 2, 0, 1, 4)
leftLayout.addWidget(h_stack(self.listRoots, self.pushButtonRemove), 3, 0, 2, 4)
leftLayout.addWidget(self.selectAllX, 5, 0, 1, 2)
leftLayout.addWidget(self.selectAllY, 5, 2, 1, 2)
leftLayout.addWidget(self.listParametersX, 6, 0, 5, 2)
leftLayout.addWidget(self.listParametersY, 6, 2, 1, 2)
leftLayout.addWidget(self.toggleFilled, 7, 2, 1, 1)
leftLayout.addWidget(self.checkInsideLegend, 7, 3, 1, 1)
leftLayout.addWidget(self.toggleLine, 8, 2, 1, 1)
leftLayout.addWidget(self.checkShade, 8, 3, 1, 1)
leftLayout.addWidget(self.toggleColor, 9, 2, 1, 1)
leftLayout.addWidget(self.comboBoxColor, 9, 3, 1, 1)
leftLayout.addWidget(self.trianglePlot, 10, 2, 1, 2)
leftLayout.addWidget(self.pushButtonPlot, 12, 0, 1, 4)
self.selectWidget.setLayout(leftLayout)
self.listRoots.hide()
self.pushButtonRemove.hide()
self.comboBoxRootname.hide()
self.comboBoxParamTag.hide()
self.comboBoxDataTag.hide()
self.plotWidget = QWidget(self.firstWidget)
layout = QVBoxLayout(self.plotWidget)
self.plotWidget.setLayout(layout)
splitter = QSplitter(self.firstWidget)
splitter.addWidget(self.selectWidget)
splitter.addWidget(self.plotWidget)
w = self.width()
splitter.setSizes([w / 4., 3 * w / 4.])
self.splitter = splitter
hbox = QHBoxLayout()
hbox.addWidget(splitter)
hbox.setContentsMargins(0, 0, 0, 0)
self.firstWidget.setLayout(hbox)
# Second tab: Script
self.secondWidget = QWidget(self)
self.tabWidget.addTab(self.secondWidget, "Script Preview")
self.editWidget = QWidget(self.secondWidget)
self.script_edit = ""
self.plotter_script = None
self.toolBar = QToolBar()
self.toolBar.setIconSize(QSize(22, 22))
openAct = QAction(self._icon("open"),
"open script", self.toolBar,
statusTip="Open script",
triggered=self.openScript)
saveAct = QAction(self._icon("save"),
"Save script", self.toolBar,
statusTip="Save script",
triggered=self.saveScript)
clearAct = QAction(self._icon("delete"),
"Clear", self.toolBar,
statusTip="Clear",
triggered=self.clearScript)
self.toolBar.addAction(openAct)
self.toolBar.addAction(saveAct)
self.toolBar.addAction(clearAct)
self.textWidget = QPlainTextEdit(self.editWidget)
textfont = QFont("Monospace")
textfont.setStyleHint(QFont.TypeWriter)
self.textWidget.setWordWrapMode(QTextOption.NoWrap)
self.textWidget.setFont(textfont)
PythonHighlighter(self.textWidget.document())
self.pushButtonPlot2 = QPushButton("Make plot", self.editWidget)
self.pushButtonPlot2.setToolTip("Ctrl+Return")
self.connect(self.pushButtonPlot2, SIGNAL("clicked()"), self.plotData2)
shortcut = QShortcut(QKeySequence(self.tr("Ctrl+Return")), self)
self.connect(shortcut, SIGNAL("activated()"), self.plotData2)
layoutEdit = QVBoxLayout()
layoutEdit.addWidget(self.toolBar)
layoutEdit.addWidget(self.textWidget)
layoutEdit.addWidget(self.pushButtonPlot2)
layoutEdit.setContentsMargins(0, 0, 0, 0)
layoutEdit.setSpacing(0)
self.editWidget.setLayout(layoutEdit)
self.plotWidget2 = QWidget(self.secondWidget)
layout2 = QVBoxLayout(self.plotWidget2)
layout2.setContentsMargins(0, 0, 0, 0)
self.plotWidget2.setLayout(layout2)
self.scrollArea = QScrollArea(self.plotWidget2)
layout2.addWidget(self.scrollArea)
splitter2 = QSplitter(self.secondWidget)
splitter2.addWidget(self.editWidget)
splitter2.addWidget(self.plotWidget2)
w = self.width()
splitter2.setSizes([w / 2., w / 2.])
hbox2 = QHBoxLayout()
hbox2.addWidget(splitter2)
hbox2.setContentsMargins(0, 0, 0, 0)
self.secondWidget.setLayout(hbox2)
self.canvas = None
self.readSettings()
def closeEvent(self, event):
self.writeSettings()
event.accept()
def getSettings(self):
return QSettings('getdist', 'gui')
def readSettings(self):
settings = self.getSettings()
screen = QApplication.desktop().screenGeometry()
h = min(screen.height() * 4 / 5., 700)
size = QSize(min(screen.width() * 4 / 5., 900), h)
pos = settings.value("pos", None)
savesize = settings.value("size", size)
if savesize.width() > screen.width():
savesize.setWidth(size.width())
if savesize.height() > screen.height():
savesize.setHeight(size.height())
self.resize(savesize)
if pos is None or pos.x() + savesize.width() > screen.width() or pos.y() + savesize.height() > screen.height():
self.move(screen.center() - self.rect().center())
else:
self.move(pos)
self.plot_module = settings.value("plot_module", self.plot_module)
self.script_plot_module = settings.value("script_plot_module", self.script_plot_module)
splitter_settings = settings.value("splitter_settings")
if splitter_settings:
self.splitter.restoreState(splitter_settings)
def writeSettings(self):
settings = self.getSettings()
settings.setValue("pos", self.pos())
settings.setValue("size", self.size())
settings.setValue('plot_module', self.plot_module)
settings.setValue('script_plot_module', self.script_plot_module)
splitter_settings = self.splitter.saveState()
if splitter_settings:
settings.setValue("splitter_settings", splitter_settings)
def export(self):
"""
Callback for action 'Export as PDF/Image'.
"""
index = self.tabWidget.currentIndex()
if index == 0:
plotter = self.plotter
else:
plotter = self.plotter_script
if plotter:
filename, _ = QFileDialog.getSaveFileName(
self, "Choose a file name", '.', "PDF (*.pdf);; Image (*.png *.jpg)")
if not filename: return
filename = str(filename)
plotter.export(filename)
else:
QMessageBox.warning(self, "Export", "No plotter data to export")
def saveScript(self):
"""
Callback for action 'Save script'.
"""
index = self.tabWidget.currentIndex()
if index == 0:
script = self.script
else:
self.script_edit = self.textWidget.toPlainText()
script = self.script_edit
if script == '':
QMessageBox.warning(self, "Script", "No script to save")
return
filename, _ = QFileDialog.getSaveFileName(self, "Choose a file name", '.', "Python (*.py)")
if not filename:
return
filename = str(filename)
logging.debug("Export script to %s" % filename)
with open(filename, 'w') as f:
f.write(script)
def reLoad(self):
adir = self.getSettings().value('lastSearchDirectory')
if adir is not None:
batchjob.resetGrid(adir)
self.openDirectory(adir)
if self.plotter:
self.plotter.sample_analyser.reset(self.current_settings)
def getRootname(self):
rootname = None
item = self.listRoots.currentItem()
if not item and self.listRoots.count(): item = self.listRoots.item(0)
if item is not None:
rootname = str(item.text())
if rootname is None:
QMessageBox.warning(self, "Chain Stats", "Select a root name first. ")
return rootname
def showConvergeStats(self):
"""
Callback for action 'Show Converge Stats'.
"""
rootname = self.getRootname()
if rootname is None: return
try:
self.showMessage("Calculating convergence stats....")
samples = self.getSamples(rootname)
stats = samples.getConvergeTests(samples.converge_test_limit)
summary = samples.getNumSampleSummaryText()
if getattr(samples, 'GelmanRubin', None):
summary += "var(mean)/mean(var), remaining chains, worst e-value: R-1 = %13.5F" % samples.GelmanRubin
dlg = DialogConvergeStats(self, stats, summary, rootname)
dlg.show()
dlg.activateWindow()
except Exception as e:
self.errorReport(e, caption="Convergence stats")
finally:
self.showMessage()
def showPCA(self):
"""
Callback for action 'Show PCA'.
"""
rootname = self.getRootname()
if rootname is None: return
try:
samples = self.getSamples(rootname)
pars = self.getXParams()
if len(pars) == 1: pars += self.getYParams()
if len(pars) < 2: raise GuiSelectionError('Select two or more parameters first')
self.showMessage("Calculating PCA....")
PCA = samples.PCA(pars)
dlg = DialogPCA(self, PCA, rootname)
dlg.show()
except Exception as e:
self.errorReport(e, caption="Parameter PCA")
finally:
self.showMessage()
def showMargeStats(self):
"""
Callback for action 'Show Marge Stats'.
"""
rootname = self.getRootname()
if rootname is None: return
try:
self.showMessage("Calculating margestats....")
QCoreApplication.processEvents()
samples = self.getSamples(rootname)
stats = samples.getMargeStats()
dlg = DialogMargeStats(self, stats, rootname)
dlg.show()
except Exception as e:
self.errorReport(e, caption="Marge stats")
finally:
self.showMessage()
def showParamTable(self):
"""
Callback for action 'Show Parameter Table'.
"""
rootname = self.getRootname()
if rootname is None: return
try:
samples = self.getSamples(rootname)
pars = self.getXParams()
ignore_unknown = False
if len(pars) < 1:
pars = self.getXParams(fulllist=True)
# If no parameters selected, it shouldn't fail if some sample is missing
# parameters present in the first one
ignore_unknown = True
if len(pars) < 1:
raise GuiSelectionError('Select one or more parameters first')
# Add renames to match parameter across samples
renames = self.paramNames.getRenames(keep_empty=True)
pars = [getattr(samples.paramNames.parWithName(
p, error=not ignore_unknown, renames=renames), "name", None)
for p in pars]
while None in pars:
pars.remove(None)
self.showMessage("Generating table....")
cols = len(pars) // 20 + 1
tables = [samples.getTable(columns=cols, limit=lim + 1, paramList=pars) for lim in
range(len(samples.contours))]
dlg = DialogParamTables(self, tables, rootname)
dlg.show()
except Exception as e:
self.errorReport(e, caption="Parameter tables")
finally:
self.showMessage()
def showLikeStats(self):
rootname = self.getRootname()
if rootname is None: return
samples = self.getSamples(rootname)
stats = samples.getLikeStats()
if stats is None:
QMessageBox.warning(self, "Like stats", "Samples do not likelihoods")
return
dlg = DialogLikeStats(self, stats, rootname)
dlg.show()
def changed_settings(self):
changed = {}
for key, value in self.current_settings.params.items():
if self.default_settings.params[key] != value:
changed[key] = value
return changed
def showSettings(self):
"""
Callback for action 'Show settings'
"""
if not self.plotter:
QMessageBox.warning(self, "Settings", "Open chains first ")
return
self.settingDlg = self.settingDlg or DialogSettings(self, self.current_settings)
self.settingDlg.show()
self.settingDlg.activateWindow()
def settingsChanged(self):
if self.plotter:
self.plotter.sample_analyser.reset(self.current_settings, chain_settings_have_priority=False)
if self.tabWidget.currentIndex() == 0:
if self.plotter and self.plotter.fig:
self.plotData()
else:
script = self.textWidget.toPlainText().split("\n")
tag = 'analysis_settings ='
changed_settings = self.changed_settings()
newline = tag + (' %s' % changed_settings).replace(', ', ",\n" + " " * 21)
last = 0
for i, line in enumerate(script):
if line.startswith(tag):
for j in range(i, len(script)):
if '}' in script[j]:
del script[i:j + 1]
break
script.insert(i, newline)
last = None
break
elif not last and line.startswith('g='):
last = i
if last is not None:
script.insert(last, newline)
for i, line in enumerate(script):
if line.startswith('g=plots.') and 'analysis_settings' not in line:
script[i] = line.strip()[:-1] + ', analysis_settings=analysis_settings)'
break
self.textWidget.setPlainText("\n".join(script))
self.plotData2()
def showPlotSettings(self):
"""
Callback for action 'Show plot settings'
"""
self.getPlotter()
settings = self.default_plot_settings
pars = []
skips = ['param_names_for_labels', 'progress']
comments = {}
for line in settings.__doc__.split("\n"):
if 'ivar' in line:
items = line.split(':', 2)
par = items[1].split('ivar ')[1]
if par not in skips:
pars.append(par)
comments[par] = items[2].strip()
pars.sort()
ini = IniFile()
for par in pars:
ini.getAttr(settings, par, comment=[comments.get(par, None)])
if isinstance(ini.params[par], matplotlib.colors.Colormap):
ini.params[par] = ini.params[par].name
ini.params.update(self.custom_plot_settings)
self.plotSettingIni = ini
self.plotSettingDlg = self.plotSettingDlg or DialogPlotSettings(self, ini, pars, title='Plot Settings',
width=420)
self.plotSettingDlg.show()
self.plotSettingDlg.activateWindow()
def resetPlotSettings(self):
self.custom_plot_settings = {}
if self.plotSettingDlg:
self.plotSettingDlg.close()
self.plotSettingDlg = None
def resetAnalysisSettings(self):
self.current_settings = copy.deepcopy(self.base_settings)
if self.settingDlg:
self.settingDlg.close()
self.settingDlg = None
def plotSettingsChanged(self, vals):
try:
settings = self.default_plot_settings
self.custom_plot_settings = {}
deleted = []
for key, value in six.iteritems(vals):
current = getattr(settings, key)
if str(current) != value and len(value):
if isinstance(current, six.string_types):
self.custom_plot_settings[key] = value
else:
try:
self.custom_plot_settings[key] = eval(value)
except:
import re
if current is None or re.match(r'^[\w]+$', value):
self.custom_plot_settings[key] = value
else:
raise
else:
deleted.append(key)
self.custom_plot_settings.pop(key, None)
except Exception as e:
self.errorReport(e, caption="Plot settings")
if self.tabWidget.currentIndex() == 0:
self.plotData()
else:
# Try to update current plot script text
script = self.textWidget.toPlainText().split("\n")
if self.custom_plot_settings:
for key, value in six.iteritems(self.custom_plot_settings):
if isinstance(value, six.string_types):
value = '"' + value + '"'
script_set = 'g.settings.%s =' % key
script_line = '%s %s' % (script_set, value)
last = None
for i, line in enumerate(script):
if line.startswith(script_set):
script[i] = script_line
script_line = None
break
elif line.startswith('g.settings.') or last is None and line.startswith('g='):
last = i
if script_line and last:
script.insert(last + 1, script_line)
for key in deleted:
script_set = 'g.settings.%s =' % key
for i, line in enumerate(script):
if line.startswith(script_set):
del script[i]
break
self.textWidget.setPlainText("\n".join(script))
self.plotData2()
def showConfigSettings(self):
"""
Callback for action 'Show config settings'
"""
ini = IniFile()
ini.params['plot_module'] = self.plot_module
ini.params['script_plot_module'] = self.script_plot_module
ini.comments['plot_module'] = [
"stylw module used by the GUI (e.g. change to getdist.styles.planck, getdist.styles.tab10)"]
ini.comments['script_plot_module'] = ["module used by saved plot scripts (e.g. getdist.styles.planck)"]
self.ConfigDlg = self.ConfigDlg or DialogConfigSettings(self, ini, list(ini.params.keys()), title='Plot Config')
self.ConfigDlg.show()
self.ConfigDlg.activateWindow()
def configSettingsChanged(self, vals):
scriptmod = vals.get('script_plot_module', self.script_plot_module)
self.script = ''
mod = vals.get('plot_module', self.plot_module)
if mod != self.plot_module or scriptmod != self.script_plot_module:
try:
self._set_rc(self.orig_rc)
__import__(mod) # test for error
logging.debug('Loaded module %s', mod)
self.plot_module = mod
self.script_plot_module = scriptmod
if self.plotSettingDlg:
self.plotSettingDlg.close()
self.plotSettingDlg = None
if self.plotter:
has_plot = self.plotter.fig
self.closePlots()
self.getPlotter(loadNew=True)
self.custom_plot_settings = {}
if has_plot:
self.plotData()
except Exception as e:
self.errorReport(e, "plot_module")
def openHelpDocs(self):
import webbrowser
webbrowser.open("https://getdist.readthedocs.org/")
def openGitHub(self):
import webbrowser
webbrowser.open("https://github.com/cmbant/getdist/")
def openPlanck(self):
import webbrowser
webbrowser.open("http://pla.esac.esa.int/pla/#cosmology")
def about(self):
"""
Callback for action 'About'.
"""
QMessageBox.about(self, "About GetDist GUI",
"GetDist GUI v " + getdist.__version__ +
"\nAntony Lewis (University of Sussex) and contributors" +
"\nhttps://github.com/cmbant/getdist/\n" +
"\nPython: " + sys.version +
"\nMatplotlib: " + matplotlib.__version__ +
"\nSciPy: " + scipy.__version__ +
"\nNumpy: " + np.__version__ +
"\nPySide: " + PySide.__version__ +
"\nQt (PySide): " + PySide.QtCore.__version__ +
("" if pyside_version == 1 else
"\n\nPix ratio: %s; Logical dpi: %s, %s" % (
self.devicePixelRatio(), self.logicalDpiX(), self.logicalDpiY())) +
'\nUsing getdist at: %s' % os.path.dirname(getdist.__file__))
def getDirectories(self):
return [self.listDirectories.itemText(i) for i in range(self.listDirectories.count())]
def saveDirectories(self):
dirs = self.getDirectories()
if self.rootdirname:
dirs = [self.rootdirname] + [x for x in dirs if not x == self.rootdirname]
if len(dirs) > 10: dirs = dirs[:10]
settings = self.getSettings()
settings.setValue('directoryList', dirs)
if self.rootdirname:
settings.setValue('lastSearchDirectory', self.rootdirname)
def selectRootDirName(self):
"""
Slot function called when pushButtonSelect is pressed.
"""
settings = self.getSettings()
last_dir = settings.value('lastSearchDirectory')
if not last_dir: last_dir = os.getcwd()
title = self.tr("Choose an existing chains grid or chains folder")