-
Notifications
You must be signed in to change notification settings - Fork 7
/
main_form.py
2113 lines (1754 loc) · 81.2 KB
/
main_form.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
################
# #
# George Dietz #
# CEBM@Brown #
# #
################
import sys
from functools import partial
import pickle
import cProfile
from PyQt4 import QtCore, QtGui
from PyQt4.Qt import *
import pdb
from PyQt4.QtCore import pyqtRemoveInputHook
import ui_main_window
import about
import calculate_effect_sizes_wizard
import transform_effect_size_wizard
import ee_model
import useful_dialogs
import python_to_R
from python_to_R import exR
import csv_import_dlg
import csv_export_dlg
import preferences_dlg
import contingency_table_dlg
import imputation.imputation_wizard
import binary_calculator
import variable_group_graphic
import analyses
import r_log_dlg
from ome_globals import *
import ome_globals
# TODO: Handle setting the dirty bit more correctly in undo/redo
# right now just set it all the time/(or not) (very haphazard) during redo but don't bother unsetting it
# debug:
#pyqtRemoveInputHook()
#pdb.set_trace()
####################################################################################
import ui_conf_level_toolbar_widget
class ConfLevelToolbarWidget(QWidget, ui_conf_level_toolbar_widget.Ui_Form):
def __init__(self, parent=None):
super(ConfLevelToolbarWidget, self).__init__(parent)
self.setupUi(self)
def set_spinbox_value_no_signals(self, new_val):
self.conf_level_spinbox.blockSignals(True)
self.conf_level_spinbox.setValue(new_val)
self.conf_level_spinbox.blockSignals(False)
####################################################################################
class MainForm(QtGui.QMainWindow, ui_main_window.Ui_MainWindow):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
self.setupUi(self)
# Setup analyses.analyzer (which performs analyses)
self.analyst = analyses.Analyzer(main_form=self)
# R log dialog
self.r_log_dlg = None
layout = self.verticalLayout #
self.vargroup_graphic = variable_group_graphic.VariableGroupGraphic()
layout.addWidget(self.vargroup_graphic)
# Confidence level spinbox
self.conf_level_toolbar_widget = ConfLevelToolbarWidget(parent=self)
self.toolBar.insertWidget(self.actionResetAnalysisChoices,
self.conf_level_toolbar_widget)
self.undo_stack = QUndoStack(self)
#### Handle user prefs / settings issue # 111
load_settings()
self.populate_recent_datasets()
self.model = ee_model.EETableModel(undo_stack=self.undo_stack)
self.tableView.setModel(self.model)
self.tableView.resizeColumnsToContents()
self.conf_level_toolbar_widget.conf_level_spinbox.setValue(
self.model.get_conf_level(),
)
python_to_R.set_conf_level_in_R(self.model.get_conf_level())
#### Display undo stack (if we want to...)
self.undo_view_form = useful_dialogs.UndoViewForm(
undo_stack=self.undo_stack,
model=self.model,
parent=self,
)
if ome_globals.SHOW_UNDO_VIEW:
self.undo_view_form.show()
self.undo_view_form.raise_()
self.statusBar().showMessage("Welcome to OpenMEE")
self.setup_menus()
self.setup_connections()
self.outpath = None
horizontal_header = self.tableView.horizontalHeader()
horizontal_header.setContextMenuPolicy(Qt.CustomContextMenu)
horizontal_header.customContextMenuRequested.connect(
self.make_horizontal_header_context_menu,
)
vertical_header = self.tableView.verticalHeader()
vertical_header.setContextMenuPolicy(Qt.CustomContextMenu)
vertical_header.customContextMenuRequested.connect(
self.make_vertical_header_context_menu,
)
self.set_window_title()
# issue #8: disable copy-pasta if nothing
# is selected (which is true at the outset)
self.toggle_copy_pasta(False)
def set_window_title(self):
if self.outpath is None:
filename = ome_globals.DEFAULT_FILENAME
else:
filename = os.path.basename(self.outpath)
self.setWindowTitle(' - '.join([ome_globals.PROGRAM_NAME, filename]))
# don't know why this isn't set automatically (since I set it in Qt Designer for the main.ui)
self.setWindowIcon(QIcon(":/general/images/logo.png"))
def toggle_copy_pasta(self, b):
'''
set all menu options pertaining to
copy/paste to (boolean) b.
'''
print("Toggling copy pasta %d" % b)
self.actionCopy.setEnabled(b)
self.actionPaste.setEnabled(b)
self.actionCut.setEnabled(b)
self.actionClear_Selected_Cells.setEnabled(b)
def showEvent(self, show_event):
''' do custom stuff upon showing the window '''
self.initialize_display()
QMainWindow.showEvent(self, show_event)
def initialize_display(self):
''' collection of function calls to perform when the main window is
first displayed or a new model is loaded '''
self._set_show_toolbar_txt() # change status of show toolbar action
# undo/redo actions
self.update_undo_enable_status()
self.update_redo_enable_status()
self.toggle_analyses_enable_status()
def toggle_analyses_enable_status(self):
''' Toggle the enable status of the analysis actions according whether
1) There are studies
2) a label column has been set '''
enable = True
not_enabled_msg = ""
try:
old_enable_status = self.enable_analyses
except AttributeError:
old_enable_status = False
studies = self.model.get_studies_in_current_order()
if len(studies) == 0:
enable = False
not_enabled_msg = "No studies entered yet."
if self.model.label_column is None:
enable = False
not_enabled_msg = "Can't enable analyses yet, did you set a study ID column?"
if (old_enable_status != True) and (not enable) and (not_enabled_msg != ""):
self.statusbar.showMessage("%s" % not_enabled_msg)
else:
self.statusbar.showMessage("")
self.enable_analyses = enable
print("Enable status for analyses: %s" % enable)
self.actionCalculate_Effect_Size.setEnabled(enable)
self.actionStandard_Meta_Analysis.setEnabled(enable)
self.actionLeave_one_out.setEnabled(enable)
self.actionCumulative.setEnabled(enable)
self.actionMeta_Regression.setEnabled(enable)
self.actionBootstrapped_Meta_Analysis.setEnabled(enable)
if enable:
if self.model.get_variables(var_type=CATEGORICAL) == []:
self.actionSubgroup.setEnabled(False)
else:
self.actionSubgroup.setEnabled(True)
else:
self.actionSubgroup.setEnabled(False)
def set_model(self, state):
'''
Used when loading a picked model. Take note we clear the undo
stack here
'''
self.disconnect_model_connections()
self.undo_stack.clear()
self.model = ee_model.EETableModel(
undo_stack=self.undo_stack,
model_state=state,
)
self.model.dirty = False
self.model.change_row_count_if_needed()
self.model.change_column_count_if_needed(debug=True)
self.tableView.setModel(self.model)
self.tableView.resizeColumnsToContents()
self.conf_level_toolbar_widget.conf_level_spinbox.setValue(
self.model.get_conf_level(),
)
self.make_model_connections()
def setup_menus(self):
# File Menu
QObject.connect(self.actionNew, SIGNAL("triggered()"), self.new_dataset)
self.actionNew.setShortcut(QKeySequence.New)
QObject.connect(self.actionOpen, SIGNAL("triggered()"), self.open)
self.actionOpen.setShortcut(QKeySequence.Open)
QObject.connect(self.actionSave, SIGNAL("triggered()"), self.save)
self.actionSave.setShortcut(QKeySequence.Save)
QObject.connect(self.actionSave_As, SIGNAL("triggered()"),
lambda: self.save(save_as=True))
self.actionSave_As.setShortcut(QKeySequence.SaveAs)
QObject.connect(self.actionQuit, SIGNAL("triggered()"), self.quit)
self.actionQuit.setShortcut(QKeySequence.Quit)
QObject.connect(self.actionImportCSV, SIGNAL("triggered()"), self.import_csv)
QObject.connect(self.actionExportCSV, SIGNAL("triggered()"), self.export_csv)
### Edit Menu ###
QObject.connect(self.actionUndo, SIGNAL("triggered()"), self.undo)
self.actionUndo.setShortcut(QKeySequence(QKeySequence.Undo))
QObject.connect(self.actionRedo, SIGNAL("triggered()"), self.redo)
self.actionRedo.setShortcut(QKeySequence.Redo)
# Cut, Copy, Paste #
QObject.connect(self.actionCut, SIGNAL("triggered()"), self.cut)
self.actionCut.setShortcut(QKeySequence.Cut)
QObject.connect(self.actionCopy, SIGNAL("triggered()"), self.copy)
self.actionCopy.setShortcut(QKeySequence.Copy)
QObject.connect(self.actionPaste, SIGNAL("triggered()"), self.paste)
self.actionPaste.setShortcut(QKeySequence.Paste)
QObject.connect(self.actionClear_Selected_Cells, SIGNAL("triggered()"), self.clear_selected_cells)
# Show/hide toolbar
QObject.connect(self.actionShow_toolbar, SIGNAL("triggered()"), self.toggle_toolbar_visibility)
### Table Menu ###
self.actionTable_Preferences.triggered.connect(self.adjust_preferences)
### Analysis Menu ###
QObject.connect(self.actionCalculate_Effect_Size, SIGNAL("triggered()"), self.calculate_effect_size)
QObject.connect(self.actionStandard_Meta_Analysis, SIGNAL("triggered()"), self.analyst.meta_analysis)
QObject.connect(self.actionCumulative, SIGNAL("triggered()"), self.analyst.cum_ma)
QObject.connect(self.actionLeave_one_out, SIGNAL("triggered()"), self.analyst.loo_ma)
QObject.connect(self.actionSubgroup, SIGNAL("triggered()"), self.analyst.subgroup_ma)
self.actionTransform_Effect_Size.triggered.connect(self.transform_effect_size_bulk)
self.actionModel_Building.triggered.connect(self.analyst.model_building)
self.actionMultiple_Imputation_Meta_Analysis.triggered.connect(self.analyst.mi_meta_analysis)
self.actionPermuted_MA.triggered.connect(lambda: self.analyst.PermutationAnalysis(meta_reg_mode=False))
self.actionPermuted_metareg.triggered.connect(lambda: self.analyst.PermutationAnalysis(meta_reg_mode=True))
#self.actionMeta_Regression.triggered.connect(self.analyst.meta_regression)
self.actionMeta_Regression.triggered.connect(self.analyst.gmeta_regression)
self.actionBootstrapped_Meta_Analysis.triggered.connect(self.analyst.bootstrap_ma)
QObject.connect(self.actionPhyloMA, SIGNAL("triggered()"), self.analyst.phylo_ma)
#### Publication Bias Menu ###
self.actionFail_Safe_N.triggered.connect(self.analyst.failsafe_analysis)
self.actionFunnel_Plot.triggered.connect(self.analyst.funnel_plot_analysis)
#### Data Exploration Menu ####
self.actionHistogram.triggered.connect(self.analyst.histogram)
self.actionScatterplot.triggered.connect(self.analyst.scatterplot)
self.actionContingency_Table.triggered.connect(self.contingency_table)
self.actionImpute_Missing_Data.triggered.connect(self.impute_missing_data)
#### Add supplementary data exploration ananlyes from openmeer
self.setup_dynamic_data_exploration_options(self.actionContingency_Table)
#### End Data Exploration Menu ####
# Help Menu
self.action_about.triggered.connect(self.show_about_dlg)
self.actionGet_help_online.triggered.connect(self.open_help_online)
# Through the looking glass .... Menu
self.actionR_log.triggered.connect(self.show_R_log_dlg)
# Toolbar
self.actionResetAnalysisChoices.triggered.connect(self.reset_analysis_selection)
# Binary Data Calculator
self.actionCalculator.triggered.connect(self.binary_calculator)
def setup_dynamic_data_exploration_options(self, last_not_dynamic_action=None):
''' Add data exploration options from R to data exploration menu
and connect them to analysis actions.
Arguments:
last_not_dynamic_action - last action that is not dynamically
generated from openmeer
'''
# Should probably sort these in some manner ....
options_descriptions = python_to_R.get_data_exploration_analyses()
for key, info in options_descriptions.items():
if key != 'ORDER':
action = self.menuData_Exploration.addAction(info['ACTIONTEXT'])
action.triggered.connect(partial(self.analyst.dynamic_data_exploration_analysis, info))
def binary_calculator(self):
form = binary_calculator.BinaryCalculator(parent=self)
form.exec_()
def open_help_online(self):
QDesktopServices.openUrl(QUrl(ome_globals.HELP_URL))
def contingency_table(self):
dlg = contingency_table_dlg.ContingencyTableDlg(
model=self.model,
parent=self,
)
dlg.exec_()
def show_about_dlg(self):
dlg = about.About()
dlg.exec_()
def toggle_toolbar_visibility(self):
status = self.toolBar.isVisible()
self.toolBar.setVisible(not status)
self._set_show_toolbar_txt()
def _set_show_toolbar_txt(self):
visible = self.toolBar.isVisible()
if visible:
print("hide toolbar")
self.actionShow_toolbar.setText("Hide toolbar")
else:
self.actionShow_toolbar.setText("Show toolbar")
def setup_connections(self):
self.make_model_connections()
# connect undo/redo signals to enable/disable menu items
self.undo_stack.canUndoChanged.connect(self.update_undo_enable_status)
self.undo_stack.canRedoChanged.connect(self.update_redo_enable_status)
self.tableView.horizontalScrollBar().actionTriggered.connect(
lambda: QTimer.singleShot(0, self.update_vargroup_graphic),
)
def stupid(self):
print("column formats changed")
def reset_analysis_selection(self):
self.model.reset_last_analysis_selection()
def table_selection_changed(self):
if self.model.big_paste_mode:
return
print("Table selection changed")
anything_selected = False
selected_indexes = self.tableView.selectionModel().selectedIndexes()
upper_left_index = self._upper_left(selected_indexes)
if upper_left_index is not None:
anything_selected = True
# issue #8
self.toggle_copy_pasta(anything_selected)
def update_undo_enable_status(self):
if self.undo_stack.canUndo():
self.actionUndo.setEnabled(True)
else:
self.actionUndo.setEnabled(False)
def update_redo_enable_status(self):
if self.undo_stack.canRedo():
self.actionRedo.setEnabled(True)
else:
self.actionRedo.setEnabled(False)
def populate_recent_datasets(self):
self.menuRecent_Data.clear()
for fpath in get_setting('recent_files'):
action = self.menuRecent_Data.addAction("Load %s" % fpath)
QObject.connect(
action,
SIGNAL("triggered()"),
partial(self.open, file_path=fpath),
)
def disconnect_model_connections(self):
QObject.disconnect(self.model, SIGNAL("DataError"), self.warning_msg)
QObject.disconnect(
self.model,
SIGNAL("dataChanged(QModelIndex, QModelIndex)"),
self.change_index_after_data_edited,
)
QObject.disconnect(
self.tableView_selection_model,
SIGNAL("selectionChanged(QItemSelection, QItemSelection)"),
self.table_selection_changed,
)
self.model.column_formats_changed.disconnect(
self.toggle_analyses_enable_status,
)
self.model.studies_changed.disconnect(
self.toggle_analyses_enable_status,
)
self.model.label_column_changed.disconnect(
self.toggle_analyses_enable_status,
)
self.model.duplicate_label.disconnect(self.duplicate_label_attempt)
self.model.error_msg_signal.disconnect(self.error_msg_signal_handler)
self.model.should_resize_column.disconnect(self.resize_column)
self.conf_level_toolbar_widget.conf_level_spinbox.valueChanged[float].disconnect(
self.model.set_conf_level,
)
self.model.conf_level_changed_during_undo.disconnect(
self.conf_level_toolbar_widget.set_spinbox_value_no_signals,
)
def make_model_connections(self):
QObject.connect(
self.model,
SIGNAL("DataError"),
self.warning_msg,
)
QObject.connect(
self.model,
SIGNAL("dataChanged(QModelIndex, QModelIndex)"),
self.change_index_after_data_edited,
)
self.tableView_selection_model = self.tableView.selectionModel()
QObject.connect(
self.tableView_selection_model,
SIGNAL("selectionChanged(QItemSelection, QItemSelection)"),
self.table_selection_changed,
)
self.model.column_formats_changed.connect(self.toggle_analyses_enable_status)
self.model.studies_changed.connect(self.toggle_analyses_enable_status)
self.model.label_column_changed.connect(self.toggle_analyses_enable_status)
self.model.duplicate_label.connect(self.duplicate_label_attempt)
self.model.error_msg_signal.connect(self.error_msg_signal_handler)
self.model.should_resize_column.connect(self.resize_column)
self.model.column_formats_changed.connect(lambda: QTimer.singleShot(1, self.update_vargroup_graphic))
self.conf_level_toolbar_widget.conf_level_spinbox.valueChanged[float].connect(self.model.set_conf_level)
self.model.conf_level_changed_during_undo.connect(self.conf_level_toolbar_widget.set_spinbox_value_no_signals)
def duplicate_label_attempt(self):
QMessageBox.critical(self, "Attempted duplicate label", "Labels must be unique")
def error_msg_signal_handler(self, title, err_msg):
QMessageBox.critical(self, title, err_msg)
def adjust_preferences(self):
form = preferences_dlg.PreferencesDialog()
if form.exec_():
update_setting('digits', form.get_precision())
update_setting('model_header_font_str', form.get_model_header_font().toString())
update_setting('model_data_font_str', form.get_model_data_font().toString())
update_setting('show_additional_values', form.get_show_additional_values())
update_setting('show_analysis_selections', form.get_show_analysis_selections())
update_setting("reg_coeff_forest_plot", form.get_make_reg_coeff_fp())
update_setting("exclude_intercept_coeff_fp", form.get_exclude_intercept())
# Copy color scheme into settings
color_scheme = form.get_color_scheme()
for key, color in color_scheme.items():
settings_key = "colors/" + key # add colors prefix
update_setting(settings_key, color)
self.model.beginResetModel()
self.model.endResetModel()
self.tableView.resizeColumnsToContents()
def calculate_effect_size(self):
'''
Opens the calculate effect size wizard form and then calculates the new
effect size. Places the new calculated effect + variance in the 2
columns beyond the most recently occupied one as new continuous
variables
'''
wizard = calculate_effect_sizes_wizard.CalculateEffectSizeWizard(
model=self.model,
parent=self,
)
if wizard.exec_():
data_type, metric = wizard.get_data_type_and_metric()
data_location = wizard.get_data_location()
cols_to_overwrite = wizard.get_columns_to_overwrite()
make_link = wizard.make_link()
# save data locations choices for this data type in the model
self.model.update_data_location_choices(data_type, data_location)
data = python_to_R.gather_data(self.model, data_location)
try:
effect_sizes = python_to_R.effect_size(metric, data_type, data)
except CrazyRError as e:
QMessageBox.critical(self, QString("R error"), QString(str(e)))
return False
print("Computed these effect sizes: %s" % str(effect_sizes))
self.undo_stack.beginMacro("Calculate Effect Size")
###################################################################
if cols_to_overwrite:
effect_cols_dict = self.model.add_effect_sizes_to_model(
metric,
effect_sizes,
cols_to_overwrite=cols_to_overwrite,
)
else: # vanilla
# effect sizes is just yi and vi
effect_cols_dict = self.model.add_effect_sizes_to_model(
metric,
effect_sizes,
)
#### Add raw data source variables to group ###
tmp_var = self.model.get_variable_assigned_to_column(
effect_cols_dict[TRANS_EFFECT],
)
var_grp = self.model.get_variable_group_of_var(tmp_var)
old_var_group_data = var_grp.get_group_data_copy()
undo_fn = lambda: var_grp.set_group_data(old_var_group_data)
if make_link:
redo_fn = lambda: self.add_data_vars_to_var_group(
data_location,
var_grp,
)
else:
redo_fn = lambda: self.clear_data_vars_from_var_group(
data_location.keys(),
var_grp,
)
self.undo_stack.push(
GenericUndoCommand(
redo_fn=redo_fn,
undo_fn=undo_fn,
),
)
###################################################################
self.undo_stack.endMacro()
self.tableView.resizeColumnsToContents()
QTimer.singleShot(0, self.update_vargroup_graphic)
def add_data_vars_to_var_group(self, data_location, var_group):
data_location = self.column_data_location_to_var_data_location(data_location)
for key, var in data_location.items():
if key in ['effect_size','variance']:
continue
var_group.set_var_with_key(key, var)
def clear_data_vars_from_var_group(self, keys, var_group):
''' clears out assignments from keys in the var_group '''
for key in keys:
var_group.unset_key(key)
def column_data_location_to_var_data_location(self, col_data_location):
''' Convert data location given by columns to given by variables '''
var_data_location = {}
for key, col in col_data_location.items():
var_data_location[key] = self.model.get_variable_assigned_to_column(col)
return var_data_location
def transform_effect_size_bulk(self):
'''
Transforms the effect size given in metric from either
1) normal scale to transformed scale (usually log scale) or
2) transformed scale to normal scale
This is given in direction via the global enumerations
TRANS_TO_NORM and NORM_TO_TRANS
data_location is a dictionary mapping to columns
Output:
Will make new columns at the end of existing columns and put
the new info there.
'''
conf_level=self.model.conf_level
wizard = transform_effect_size_wizard.TransformEffectSizeWizard(
model=self.model,
)
if not wizard.exec_():
return False
effect_var_to_transform = self.model.get_variable_assigned_to_column(
wizard.get_chosen_column(),
)
transform_direction = wizard.get_transformation_direction()
verify_transform_direction(transform_direction)
self.undo_stack.beginMacro("Transforming/backtransforming effect size")
# Need to make a new column group if the effect column we chose doesn't belong to one yet
if wizard.make_new_column_group():
print("Making new column group")
new_grp_cols = wizard.get_new_column_group_column_selections()
metric = wizard.get_new_column_group_metric()
if transform_direction == TRANS_TO_RAW:
trans_yi = self.model.get_variable_assigned_to_column(
new_grp_cols[TRANS_EFFECT],
)
trans_vi = self.model.get_variable_assigned_to_column(
new_grp_cols[TRANS_VAR],
)
keys_to_vars = {
TRANS_EFFECT: trans_yi,
TRANS_VAR: trans_vi,
}
elif transform_direction == RAW_TO_TRANS:
raw_yi = self.model.get_variable_assigned_to_column(
new_grp_cols[RAW_EFFECT],
)
raw_lb = self.model.get_variable_assigned_to_column(
new_grp_cols[RAW_LOWER],
)
raw_ub = self.model.get_variable_assigned_to_column(
new_grp_cols[RAW_UPPER],
)
keys_to_vars = {
RAW_EFFECT: raw_yi,
RAW_LOWER: raw_lb,
RAW_UPPER: raw_ub,
}
# make new column group and add variables to it
col_group = self.model.make_new_variable_group(
metric=metric,
name=METRIC_TEXT_SIMPLE[metric] + " column group",
)
self.undo_stack.push(
GenericUndoCommand(
redo_fn=partial(
self.model.add_vars_to_col_group,
col_group,
keys_to_vars,
),
undo_fn=partial(
self.model.remove_vars_from_col_group,
col_group,
keys=keys_to_vars.keys(),
),
description="Add variables to column group",
),
)
else: # column group already exists
col_group = self.model.get_variable_group_of_var(
effect_var_to_transform,
)
metric = col_group.get_metric()
data_location = {}
if transform_direction == TRANS_TO_RAW:
trans_yi = col_group.get_var_with_key(TRANS_EFFECT)
trans_vi = col_group.get_var_with_key(TRANS_VAR)
data_location = {
TRANS_EFFECT: trans_yi,
TRANS_VAR: trans_vi,
}
elif transform_direction == RAW_TO_TRANS:
raw_yi = col_group.get_var_with_key(RAW_EFFECT)
raw_lb = col_group.get_var_with_key(RAW_LOWER)
raw_ub = col_group.get_var_with_key(RAW_UPPER)
data_location = {
RAW_EFFECT: raw_yi,
RAW_LOWER: raw_lb,
RAW_UPPER: raw_ub,
}
data = python_to_R.gather_data(
self.model,
data_location,
vars_given_directly=True,
)
try:
effect_sizes = python_to_R.transform_effect_size(
metric,
data,
transform_direction,
conf_level,
)
except CrazyRError as e:
QMessageBox.critical(self, QString("R error"), QString(str(e)))
return False
# effect sizes is just yi and vi
self.model.add_transformed_effect_sizes_to_model(
metric,
effect_sizes,
transform_direction,
col_group,
)
self.tableView.resizeColumnsToContents()
self.undo_stack.endMacro()
#@profile_this
def change_index_after_data_edited(
self,
index_top_left,
index_bottom_right,
):
row, col = index_top_left.row(), index_top_left.column()
row += 1
if row < self.model.rowCount():
self.tableView.setFocus()
new_index = self.model.createIndex(row,col)
self.tableView.setCurrentIndex(new_index)
if not self.model.big_paste_mode:
end_col = index_bottom_right.column()
ncols = end_col - col + 1
if ncols >= 10:
self.tableView.resizeColumnsToContents()
#else: this is handled by resize_column when the appropriate signal comes out of the model
def resize_column(self, col):
print("resizing column %d" % col)
self.tableView.resizeColumnToContents(col)
def warning_msg(self, title="mystery warning", msg="a mysterious warning"):
warning_box = QMessageBox(self)
warning_box.setIcon(QMessageBox.Warning)
warning_box.setText(msg)
warning_box.setWindowTitle(title)
warning_box.exec_()
##### Undo / redo
def undo(self):
#print("Undo action triggered")
self.undo_stack.undo()
def redo(self):
#print("Redo action triggered")
self.undo_stack.redo()
def make_vertical_header_context_menu(self, pos):
'''
Makes the context menu for the row headers when user right-clicks
Actions:
Insert row
delete study (row)
'''
row_clicked = self.tableView.rowAt(pos.y())
is_study_row = self.model.row_assigned_to_study(row_clicked)
if not is_study_row:
return False
context_menu = QMenu(self.tableView)
# Delete a row(study)
delete_row_action = context_menu.addAction("Remove row")
QAction.connect(
delete_row_action,
SIGNAL("triggered()"),
lambda: self.model.removeRow(row_clicked),
)
# Insert a row
insert_row_action = context_menu.addAction("Insert row")
QAction.connect(
insert_row_action,
SIGNAL("triggered()"),
lambda: self.model.insertRow(row_clicked),
)
context_menu.popup(QCursor.pos())
def make_horizontal_header_context_menu(self, pos):
'''
Makes the context menu for column headers when user right-clicks:
Possible actions:
change format of column (only for variable columns)
rename column
mark column as label (only for categorical cols)
unmark column as label (only for label column)
delete column
insert column
'''
# # profiling fun
# pr=cProfile.Profile()
# pr.enable()
# ###############
column_clicked = self.tableView.columnAt(pos.x())
if DEBUG_MODE:
print("Right clicked column %d" % column_clicked)
label_column = self.model.get_label_column()
is_variable_column = self.model.column_assigned_to_variable(column_clicked)
context_menu = QMenu(self.tableView)
if (column_clicked == label_column or is_variable_column):
if column_clicked != label_column:
if is_variable_column:
variable = self.model.get_variable_assigned_to_column(column_clicked)
# Change format of column
change_format_menu = QMenu("Change format", parent=context_menu)
self.add_choices_to_change_format_menu(change_format_menu, column_clicked)
if len(change_format_menu.actions()) > 0:
context_menu.addMenu(change_format_menu)
# Mark column as label
if label_column is None and variable.get_type() == CATEGORICAL:
mark_as_label_action = context_menu.addAction("Mark as Study ID column")
QAction.connect(mark_as_label_action, SIGNAL("triggered()"),
partial(self.mark_column_as_label, column_clicked))
else: # column is label column
# Unmark column as label
unmark_as_label_action = context_menu.addAction("Unmark as Study ID column")
QAction.connect(unmark_as_label_action, SIGNAL("triggered()"),
partial(self.unmark_column_as_label, column_clicked))
# rename label column
rename_column_action = context_menu.addAction("Rename %s" % ('variable' if is_variable_column else 'Study ID column'))
QAction.connect(rename_column_action, SIGNAL("triggered()"), lambda: self.rename_column(column_clicked))
# delete column
delete_column_action = context_menu.addAction("Remove %s" % ('variable' if is_variable_column else 'Study ID column'))
QAction.connect(delete_column_action, SIGNAL("triggered()"), partial(self.remove_column, column_clicked))
# insert column
insert_column_action = context_menu.addAction("Insert column")
QAction.connect(insert_column_action, SIGNAL("triggered()"), lambda: self.model.insertColumn(column_clicked))
# Sort by column data
sort_action = context_menu.addAction("Sort by column data")
QAction.connect(sort_action, SIGNAL("triggered()"), lambda: self.model.sort_by_column(column_clicked))
else: # column is not a label column or variable column
# Make new variable
make_new_categorical_variable_action = context_menu.addAction("Make new categorical variable")
QObject.connect(make_new_categorical_variable_action, SIGNAL("triggered()"), partial(self.make_new_variable_at_col, col=column_clicked,var_type=CATEGORICAL))
context_menu.popup(QCursor.pos())
def remove_column(self, column):
is_variable_column = self.model.column_assigned_to_variable(column)
# Remove other columns @ same scale in var_group
if is_variable_column:
var = self.model.get_variable_assigned_to_column(column)
var_group = self.model.get_variable_group_of_var(var)
if var_group is not None:
var_is_trans = var_group.get_var_key(var) in [TRANS_EFFECT, TRANS_VAR]
if var_is_trans:
keylist = [TRANS_EFFECT, TRANS_VAR]
else:
keylist = [RAW_EFFECT, RAW_LOWER, RAW_UPPER]
self.undo_stack.beginMacro("Deleting all columns at same scale as selected column to delete")
for var_key in keylist:
othervar = var_group.get_var_with_key(var_key)
if othervar is not None:
other_var_col = self.model.get_column_assigned_to_variable(othervar)
self.model.removeColumn(other_var_col)
# Delete var group if it is empty now
if var_group.effects_empty():
self.model.remove_variable_group(var_group) # undoable
self.undo_stack.endMacro()
return
self.model.removeColumn(column)
def mark_column_as_label(self, col):
''' Should only occur for columns of CATEGORICAL type and only for a
column which is not already the label column
(the check happens elsewhere) '''
variable = self.model.get_variable_assigned_to_column(col)
variable_name = variable.get_label()
# Ensure that study labels are unique
distinct_study_labels = {} # map labels to # of times used
overridden_study_labels = {}
original_study_labels = {}
studies = self.model.get_studies_in_current_order()
for study in studies:
proposed_label = study.get_var(variable)
if proposed_label is None:
proposed_label = ''
if proposed_label not in distinct_study_labels:
distinct_study_labels[proposed_label] = 1
else:
distinct_study_labels[proposed_label] += 1
original_study_labels[study] = proposed_label
num_times_used = distinct_study_labels[proposed_label]
if num_times_used > 1:
proposed_label = proposed_label + '-' + str(num_times_used)
distinct_study_labels[proposed_label] = 1
overridden_study_labels[study] = proposed_label
if overridden_study_labels != {}:
choice = QMessageBox.warning(self, "Warning",
"Variable names need to be unique. If you continue, labels will be slightly altered to ensure uniqueness (by appending #s to the end). Do you want to continue?",
QMessageBox.Ok | QMessageBox.Cancel)
if choice == QMessageBox.Cancel:
return # do nothing
# build up undo command
redo = lambda: self.model.mark_column_as_label(col, overridden_study_labels)
undo = lambda: self.model.unmark_column_as_label(col, original_study_labels)
on_exit = lambda: self.model.emit_change_signals_for_col(col)
mark_column_as_label_cmd = GenericUndoCommand(
redo_fn=redo,
undo_fn=undo,
on_redo_exit=on_exit,
on_undo_exit=on_exit,
description="Mark column '%s' as label" % variable_name,
)
self.undo_stack.push(mark_column_as_label_cmd)
self.model.set_dirty_bit()
def unmark_column_as_label(self, col):
''' Unmarks column as label and makes it a CATEGORICAL variable '''
label_column_name = self.model.label_column_name_label
# build up undo command
redo = lambda: self.model.unmark_column_as_label(col)