-
Notifications
You must be signed in to change notification settings - Fork 0
/
datamodeler.py
executable file
·1240 lines (1045 loc) · 49.8 KB
/
datamodeler.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
# Data Modeler for Power Calculations Python Edition
# Dedicated to the Appel Lab at Stanford University Department of Bioengineering
# Developed by Peyton Chen, Summer 2020
# Copyright (C) 2020 Peyton Chen
import sys
import pandas as pd
import numpy as np
import webbrowser
import json
import matplotlib
import matplotlib.pyplot as plt
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from modules.Mainwindow import Ui_MainWindow
from modules.verify import s1verify, s2verify, s3and4verify, s5verify, verifygriddict
from modules.textmanager import preparemultitxt, preparemultisas, preparelabeltxt
from modules.generateglm import makeglmresults, printpwr, exportresultframe, makeftest, fpwr
from modules.autofillLD import runLDalgo
from modules.autofillCP import runCPalgo, verifyCPalgo, combotofitgrid
from modules.exportxlsx import writetoxlsx
from modules.inputs import Inputs
from modules.results import Results
from modules.displaypd import pdModel
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setupUi(self) #From Mainwindow.py
self.inputs = Inputs() #Initialize classes
self.results = Results()
self.runcounter = 0 #Initialize run counter at step 5
self.bFbox = QFormLayout()
self.bFscrollWidget.setLayout(self.bFbox) #Blocking factor inputs FormLayout
self.cBox = QHBoxLayout()
self.cScrollWidget.setLayout(self.cBox) #Current Inputs View
self.tBox = QFormLayout()
self.tScrollWidget.setLayout(self.tBox) #Treatment inputs FormLayout
self.eBox = QFormLayout()
self.eRscrollWidget.setLayout(self.eBox) #Error inputs FormLayout
self.dGrid = QGridLayout()
self.dScrollWidget.setLayout(self.dGrid) #Distributing assignments Step 5 GridLayout
self.dfBox = QVBoxLayout()
self.GLMScrollWidget.setLayout(self.dfBox) #Dataframes from pairwise t-test GLM VBoxLayout
self.pwrBox = QVBoxLayout()
self.PCScrollWidget.setLayout(self.pwrBox) #Power estimate results VBoxLayout
self.pwrBox.setSpacing(5)
self.fBox = QVBoxLayout()
self.FScrollWidget.setLayout(self.fBox) #Fixed effect F-test results VBoxLayout
self.fBox.setSpacing(5)
self.dGroupBox.hide()
self.cGroupBox.hide()
self.GLMGroupBox.hide()
self.PCGroupBox.hide() #Hiding boxes that won't be shown unless expanded
self.s2but.setEnabled(False) #Buttons will be enabled when input pane is advanced
self.s4but.setEnabled(False)
self.updates4.hide()
self.editInputs.hide()
self.hides6fields()
self.setMinimumSize(QSize(450, 750)) #Setting minimum sizes and resize for pane 1
self.resize(450, 750)
self.updatebool = False #Initializing variables
self.finalexpand = False
self.firstexpand = False
self.dViewlabelchanged = False
self.badexpmt = False
self.dViewlabels = [] #Will store QLabel objects of labels in the grid so these can be updated w/o reinitialization
#Connecting events
self.nameMeas.textChanged.connect(self.changedViewlabelsbool)
self.namedVar.textChanged.connect(self.changedViewlabelsbool)
self.s1but.clicked.connect(self.s1process)
self.s2but.clicked.connect(self.s2process)
self.s4but.clicked.connect(self.s3and4process)
self.updates4.clicked.connect(self.s3and4update)
self.s5but.clicked.connect(self.s5process)
self.addRun.clicked.connect(self.s5add)
self.editGrid.clicked.connect(self.unlockgrid)
self.loadgridCSV.clicked.connect(self.loadincsv)
self.editInputs.clicked.connect(self.unlockinputs)
self.autogenGrid.clicked.connect(self.genGrid)
self.exportTextBut.clicked.connect(self.exporttxt)
self.exportSAS.clicked.connect(self.exportsas)
self.glmCalc.clicked.connect(self.runglm)
self.parsepower.clicked.connect(self.pwr)
self.exportpwrcsv.clicked.connect(self.exportframes)
#Status bar events
self.actionSave.triggered.connect(self.exportxlsx)
self.actionSave.setShortcut("Ctrl+S")
self.actionReset.triggered.connect(self.reset)
self.actionReset.setShortcut("Ctrl+R")
self.actionDocumentation.triggered.connect(self.opendocs)
self.actionDocumentation.setShortcut("Ctrl+D")
self.actionSave_2.triggered.connect(self.savejson)
self.actionSave_2.setShortcut("Ctrl+J")
self.actionLoad.triggered.connect(self.loadjson)
self.actionLoad.setShortcut("Ctrl+L")
#Timer used in a few places for statusBar background
self.timer = QTimer(self)
self.timer.timeout.connect(self.resetSBbkgrd)
#Setting up QCompleters for labelling/naming
completerNmMeaslst = ['Rat', 'Mouse', 'Pig', 'Sheep',
'Rabbit', 'Guinea Pig', 'Subject', 'Measurement', 'Sample']
self.completer1 = QCompleter(completerNmMeaslst, self)
self.completer1.setCaseSensitivity(0) #Case insensitive
self.nameMeas.setCompleter(self.completer1)
completerNmDvarlst = ['Days Survived', 'Time to peak', 'Dependent Variable',
'Tumor Size', 'Concentration']
self.completer2 = QCompleter(completerNmDvarlst, self)
self.completer2.setCaseSensitivity(0)
self.namedVar.setCompleter(self.completer2)
completerNmBF = ['Cage', 'Gender', 'Color', 'Species', 'Age', 'Strain', 'Day', 'Week']
completerNmBF += completerNmMeaslst[0:11]
self.completer3 = QCompleter(completerNmBF, self)
self.completer3.setCaseSensitivity(0)
def s1process(self):
#Continue/Update for initial parameters
#Store values from step 1 into an instance of Inputs class created at Mainwindow init
self.store_s1()
#Status bar handling in case of unrecognized Step 1 input
self.statusBar.clearMessage()
self.statusBar.setStyleSheet("background-color: none;")
verify = s1verify(self.inputs.s1Inputs) #Returns bool and string description of error
if not verify[0]:
self.statusBar.showMessage(verify[1])
self.statusBar.setStyleSheet("background-color: pink;")
return #if unrecognized inputs program will not continue and halt here
else:
self.minimize() #Minimizes 3rd pane if it exists
#Sets button text to 'Update' after initial press
self.s1but.setText('Update')
self.s1but.repaint()
self.s4but.setEnabled(True)
if self.numMeasure.isModified():
self.minimize2()
self.s4but.setText('Continue')
self.s4but.repaint()
self.updates4.hide()
self.updates4.repaint()
self.numMeasure.setModified(False)
if self.numTreat.isModified(): #Only if number of treatments is updated/edited
self.initTView()
self.numTreat.setModified(False)
self.clearLayout(self.cBox) #Clears current input box until everything is updated after S4 (Step 4)
if self.numBf.isModified(): #Only if the number of blocking factor is updated/edited
self.minimize2()
self.s4but.setText('Continue')
self.s4but.repaint()
self.updates4.hide()
self.updates4.repaint()
self.initBfView()
self.clearLayout(self.eBox) #Clears error box in preparation for update
if int(self.inputs.s1Inputs[2]) == 0: #handles case where there are 0 blocking factors to initialize error view
self.initEView(True)
self.s2but.setEnabled(False) #in case this is updating from non-zero initial # of blocking factors
self.s2but.setText('Skip this!')
self.s2but.repaint()
self.inputs.s2Inputs.append([]) #To ensure input variables have the same shape even in case of 0 BF
self.inputs.s2Inputs.append([])
else:
#Reveals S2 button in case where there are more than 0 blocking factors
self.s2but.setEnabled(True)
self.s2but.repaint()
if self.dViewlabelchanged:
self.updateDviewlabels()
self.dViewlabelchanged = False
if self.firstexpand:
self.unlockgrid()
def s2process(self):
#Continue/Update for assigning blocking factor names and number
#Store values from step 2 into an instance of Inputs class created at Mainwindow init
self.inputs.store_s2(self.inputs.s2Obj[0], self.inputs.s2Obj[1])
self.statusBar.clearMessage()
self.statusBar.setStyleSheet("background-color: none;")
verify = s2verify(self.inputs.s2Inputs)
if not verify[0]:
self.statusBar.showMessage(verify[1])
self.statusBar.setStyleSheet("background-color: pink;")
return
else:
if self.numBf.isModified(): #Only reinitializes Error Step 3 View if Step 1 number of blocking factors is changed/updated
self.initEView(False)
self.numBf.setModified(False)
if self.dViewlabelchanged:
self.updateDviewlabels()
if self.firstexpand: #Updates labels in the Current Input View
self.initcurrInpView()
self.dViewlabelchanged = False
self.s2but.setText('Update')
self.s2but.repaint()
if self.firstexpand:
self.unlockgrid()
self.results.genEVals(self.inputs.s2Inputs, self.inputs.s3Inputs)
self.initcurrInpView() #Reinitializes current input box: if blank, updated needed S3 or S4
def s3and4process(self):
#Continue/reset grid button
#Store values from step 3 and 4 into an instance of Inputs class created at Mainwindow init
self.inputs.store_s3and4(self.inputs.s3Obj, self.inputs.s4Obj, self.inputs.s4labelobj)
self.statusBar.clearMessage()
self.statusBar.setStyleSheet("background-color: none;")
verify = s3and4verify(self.inputs.s3Inputs, self.inputs.s4Inputs)
if not verify[0]:
self.statusBar.showMessage(verify[1])
self.statusBar.setStyleSheet("background-color: pink;")
return
else:
self.s4but.setText('Reinitialize grid')
self.s4but.repaint()
if not self.firstexpand and not self.finalexpand: #To ensure window resizing isn't awkward
self.expand()
self.firstexpand = True
self.updatebool = False
self.initDView()
self.results.genEVals(self.inputs.s2Inputs, self.inputs.s3Inputs)
self.initcurrInpView()
self.unlockgrid()
def s3and4update(self):
#Update errors and treatment means button
#Store values from step 3 and 4 into an instance of Inputs class created at Mainwindow init
self.inputs.store_s3and4(self.inputs.s3Obj, self.inputs.s4Obj, self.inputs.s4labelobj)
self.statusBar.clearMessage()
self.statusBar.setStyleSheet("background-color: none;")
verify = s3and4verify(self.inputs.s3Inputs, self.inputs.s4Inputs)
if not verify[0]:
self.statusBar.showMessage(verify[1])
self.statusBar.setStyleSheet("background-color: pink;")
return
else:
#Generates new error values and clears any current/outdated dependent variables
self.results.genEVals(self.inputs.s2Inputs, self.inputs.s3Inputs)
self.initcurrInpView()
self.updatebool = True #To update not reinitialize and overwrite current dVVal view
self.unlockgrid()
def s5process(self):
#Generate values/reset runs button
#Store values from step 5 (distribution grid) into an instance of Inputs class created at Mainwindow init
self.inputs.stores_s5(self.inputs.s5Obj)
self.statusBar.clearMessage()
self.statusBar.setStyleSheet("background-color: none;")
verify = s5verify(self.inputs.s5Inputs, self.inputs.s1Inputs, self.inputs.s2Inputs)
if not verify[0]:
self.statusBar.showMessage(verify[1])
self.statusBar.setStyleSheet("background-color: pink;")
return
else:
self.lockgrid()
self.lockinputs()
self.editInputs.show()
self.editInputs.repaint()
self.results.gendvVals(self.inputs.s5Inputs, self.inputs.s4Inputs, self.inputs.s3Inputs[0])
self.results.multiRun.clear() #Doubles as reset runs button
self.results.addRun()
self.runcounter = 1 #Reset run counter
self.runCount.setText('Current run count: ' + str(self.runcounter))
self.runCount.repaint()
self.minimize()
if not self.updatebool:
self.initdVValView()
self.s5but.setText('Reset runs')
self.s5but.repaint()
self.updates4.show()
self.updates4.repaint()
self.shows6fields()
else:
self.shows6fields()
self.updatedVVal()
self.runCount.repaint()
self.updatebool = True
def s5add(self):
#Add runs button
self.inputs.stores_s5(self.inputs.s5Obj)
self.statusBar.clearMessage()
self.statusBar.setStyleSheet("background-color: none;")
verify = s5verify(self.inputs.s5Inputs, self.inputs.s1Inputs, self.inputs.s2Inputs)
if not verify[0]:
self.statusBar.showMessage(verify[1])
self.statusBar.setStyleSheet("background-color: pink;")
return
else:
self.statusBar.clearMessage()
self.statusBar.setStyleSheet("background-color: none;")
self.minimize()
if self.runcounter > 2000:
self.statusBar.showMessage('Are you trying to crash the program??? Error - Too many runs',5000)
self.statusBar.setStyleSheet("background-color: pink;")
self.timer.start(5000)
return
if str(self.numRuns.text()):
try:
numR = int(str(self.numRuns.text()))
except ValueError:
self.statusBar.showMessage('Invalid input - Number of runs must be integer')
self.statusBar.setStyleSheet("background-color: pink;")
return
if numR < 0:
self.statusBar.showMessage('Invalid input - Number of runs must be positive')
self.statusBar.setStyleSheet("background-color: pink;")
return
self.statusBar.showMessage('Calculating...')
for i in range(numR):
self.results.gendvVals(self.inputs.s5Inputs, self.inputs.s4Inputs, self.inputs.s3Inputs[0])
self.runcounter += 1
self.results.addRun()
self.runCount.setText('Current run count: ' + str(self.runcounter))
self.runCount.repaint()
self.runCount.adjustSize()
self.updatedVVal()
self.numRuns.clear()
self.numRuns.repaint()
self.statusBar.clearMessage()
else:
self.results.gendvVals(self.inputs.s5Inputs, self.inputs.s4Inputs, self.inputs.s3Inputs[0])
self.runcounter += 1
self.runCount.setText('Current run count: ' + str(self.runcounter))
self.runCount.repaint()
self.updatedVVal()
self.results.addRun()
def loadincsv(self):
self.unlockgrid()
dlg = QFileDialog()
dlg.setFileMode(QFileDialog.ExistingFile)
filename, _filter = dlg.getOpenFileName(None, "Load in csv", ".", "(*.csv)")
if filename:
grid = pd.read_csv(str(filename))
griddict = grid.to_dict('list') #list format extraction of dataframe to dict
verify = verifygriddict(griddict, self.inputs.s1Inputs, self.inputs.s2Inputs)
self.statusBar.clearMessage()
self.statusBar.setStyleSheet("background-color: none;")
if not verify[0]:
self.statusBar.showMessage(verify[1])
self.statusBar.setStyleSheet("background-color: pink;")
return
else:
self.inputs.loadin_s5(self.inputs.s5Obj, griddict)
def genGrid(self):
choices = ('Cartesian product assignment (Default)', 'Quasi-random low discrepancy sequence assignment')
choice, ok = QInputDialog.getItem(self, 'Select auto-gen method', 'Note: Use cartesian product for all but very large sample sizes.', choices, 0 , False)
if ok and choice:
self.unlockgrid()
if choice == 'Cartesian product assignment (Default)':
combos = runCPalgo(self.inputs.s1Inputs, self.inputs.s2Inputs)
verify = verifyCPalgo(self.inputs.s1Inputs, combos)
self.statusBar.clearMessage()
self.statusBar.setStyleSheet("background-color: none;")
if not verify[0]:
self.statusBar.showMessage(verify[1])
self.statusBar.setStyleSheet("background-color: pink;")
return #will not fit to grid unless #of measurements is multiple of combos
else:
dic = combotofitgrid(combos, self.inputs.s2Inputs, self.inputs.s1Inputs)
self.inputs.loadin_s5(self.inputs.s5Obj, dic)
if choice == 'Quasi-random low discrepancy sequence assignment':
dic = runLDalgo(self.inputs.s1Inputs, self.inputs.s2Inputs)
verify = verifygriddict(dic, self.inputs.s1Inputs, self.inputs.s2Inputs)
self.statusBar.clearMessage()
self.statusBar.setStyleSheet("background-color: none;")
if not verify[0]:
self.statusBar.showMessage('Auto-generation is an experimental feature... it did something wrong, going to have to grid in yourself or try Cartesian product!')
self.statusBar.setStyleSheet("background-color: pink;")
return
else:
self.statusBar.setStyleSheet("background-color: #FFFF99") #Light yellow warning
self.timer.start(5000)
self.statusBar.showMessage('Experimental feature - there may be a better distribution if done by hand or cartesian product', 5000)
self.inputs.loadin_s5(self.inputs.s5Obj, dic)
def runglm(self):
#Expands and initializes GLM fit and pairwise t-test multiple comparison for display in QTableViews
self.expand2()
self.clearLayout(self.dfBox)
self.clearLayout(self.pwrBox) #Since GLM is reinitialized
self.clearLayout(self.fBox)
self.badexpmt = False
results = makeglmresults(self.inputs.s5Inputs, self.results.multiRun, self.inputs.s1Inputs, self.inputs.s2Inputs)
resultframes = results[0]
bigmodels = results[1]
self.results.resultframes.clear()
self.results.resultframes = resultframes
fresults = makeftest(self.inputs.s5Inputs, self.results.multiRun, self.inputs.s1Inputs, self.inputs.s2Inputs, bigmodels)
self.results.fresults.clear()
self.results.fresults = fresults
#Initializing text for display in F-test box
self.fBox.addWidget(QLabel('Fixed effects F-test results:'))
fstring = ''
for i, tup in enumerate(self.results.fresults):
fstring += 'Run ' + str(i+1) + ' | ' + 'F-stat: ' + str(round(tup[0], 4)) + ', ' + 'p-value: ' + str(round(tup[1], 4))
fstring += '\n'
if tup[0] == -np.inf or tup[0] == np.inf:
self.badexpmt = True
flabel = QLabel(fstring)
self.results.fstring = fstring
flabel.setTextInteractionFlags(Qt.TextSelectableByMouse)
flabel.setCursor(Qt.IBeamCursor)
self.fBox.addWidget(flabel)
if self.badexpmt:
self.statusBar.setStyleSheet("background-color: #FFFF99") #Light yellow warning
self.statusBar.showMessage('Warning - this experiment is designed without enough separation in treatment and blocking factor assignments, unable to complete F-test', 10000)
self.timer.start(10000)
#Initializing tableviews for pairwise t-test
self.dfBox.addWidget(QLabel('Pairwise t-test results:'))
for frame in self.results.resultframes:
model = pdModel(frame)
view = QTableView()
view.setModel(model)
#setting height of TableViews, capping expandability @ 4 treatments / 6 rows
height = view.rowHeight(0)
numRows = model.rowCount()
if numRows > 6:
numRows = 6
height = (height * numRows)
view.resizeColumnsToContents()
view.resizeRowsToContents()
view.setFixedHeight(height) #locks in height
self.dfBox.addWidget(view)
self.dfBox.addStretch() #Fill in empty space if there aren't enough tables generated
def pwr(self):
#Initializes display after parsing power with power estimation results
self.clearLayout(self.pwrBox)
labels = printpwr(self.results.resultframes)
headpwrlabel = QLabel('Based on ' + str(len(self.results.multiRun)) + ' runs and alpha = 0.05:')
headpwrlabel.setStyleSheet("font-weight: bold;")
self.pwrBox.addWidget(headpwrlabel)
fixedlabel = QLabel('Power for fixed effect F-test is estimated as:')
fixedlabel.setStyleSheet("font-weight: bold;")
self.pwrBox.addWidget(fixedlabel)
fixedeffect = fpwr(self.results.fresults)
self.results.fpwrstring = fixedeffect
fixedeffectresult = QLabel(fixedeffect)
fixedeffectresult.setTextInteractionFlags(Qt.TextSelectableByMouse)
fixedeffectresult.setCursor(Qt.IBeamCursor)
self.pwrBox.addWidget(fixedeffectresult)
pairwiselabel = QLabel('Power for pairwise t-tests between treatments are estimated as:')
pairwiselabel.setStyleSheet("font-weight: bold;")
self.pwrBox.addWidget(pairwiselabel)
pairwiseresultstr = ''
for label in labels:
pairwiseresultstr += label
pairwiseresultstr += '\n'
pairwiseresult = QLabel(pairwiseresultstr)
self.results.pstring = pairwiseresultstr
pairwiseresult.setTextInteractionFlags(Qt.TextSelectableByMouse)
pairwiseresult.setCursor(Qt.IBeamCursor)
self.pwrBox.addWidget(pairwiseresult)
def exportframes(self):
#Creates file dialog for csv export of resultant dataframes from pairwise t-test after GLM fit
dlg = QFileDialog()
dlg.setFileMode(QFileDialog.Directory)
dataframe = exportresultframe(self.results.resultframes)
if dlg.exec_():
directory, _filter = dlg.getSaveFileName()
dataframe.to_csv(str(directory) + '.csv', index=True)
def exporttxt(self):
#Exports a read-out of all runs and only runs into text file
dlg = QFileDialog()
dlg.setFileMode(QFileDialog.Directory)
outstring = preparemultitxt(self.inputs.s5Inputs, self.results.multiRun, self.inputs.s1Inputs, self.inputs.s2Inputs)
if dlg.exec_():
directory, _filter = dlg.getSaveFileName()
f = open(str(directory) + '.txt', 'w+')
f.write(outstring)
f.close()
def exportsas(self):
#Exports SAS script in a text file for multiple comparison tests with Tukey correction. This can be done in house!
dlg = QFileDialog()
dlg.setFileMode(QFileDialog.Directory)
if self.experimentName.text() == '': #Sets experiment name as 'UnnamedExpmt' if nothing is inputted befores gen script
self.experimentName.setText('UnnamedExpmt')
self.experimentName.repaint()
outstring = preparemultisas(self.inputs.s5Inputs, self.results.multiRun, self.inputs.s1Inputs,
self.inputs.s2Inputs, self.experimentName.text())
if dlg.exec_():
directory, _filter = dlg.getSaveFileName()
f = open(str(directory) + '.txt', 'w+')
f.write(outstring)
f.close()
self.experimentName.clear() #Clears experiment name
def exportxlsx(self):
#Exports a read-out of current session into excel file
#Includes all inputs, generated error, treatment means, all runs and dVVal generation, power estimation results
#if they exist. CSV dataframes must be separately exported
if self.updatebool:
dlg = QFileDialog()
dlg.setFileMode(QFileDialog.Directory)
if dlg.exec_():
directory, _filter = dlg.getSaveFileName()
labels = preparelabeltxt(self.inputs.s1Inputs, self.inputs.s2Inputs)
labels.insert(0, 'Run')
writetoxlsx(self.inputs.s1Inputs, self.inputs.s2Inputs, self.inputs.s3Inputs, self.inputs.s4Inputs,
self.inputs.s4labels, self.inputs.s5Inputs, self.results.multiRun, self.results.fstring, self.results.fpwrstring,
self.results.pstring, labels, self.results.errorResults, directory)
else:
self.statusBar.setStyleSheet("background-color: #FFFF99")
self.statusBar.showMessage('Generate some values before you export to xlsx!', 7000)
self.timer.start(7000)
def savejson(self):
#Saves to json so that user can load in data from a session later
if self.results.multiRun: #Can't be empty to save
dlg = QFileDialog()
dlg.setFileMode(QFileDialog.Directory)
if dlg.exec_():
directory, _filter = dlg.getSaveFileName()
outdic = {}
outdic['s1Inputs'] = self.inputs.s1Inputs
outdic['s2Inputs'] = self.inputs.s2Inputs
outdic['s3Inputs'] = self.inputs.s3Inputs
outdic['s4Inputs'] = self.inputs.s4Inputs
outdic['s4labels'] = self.inputs.s4labels
outdic['s5Inputs'] = self.inputs.s5Inputs
outdic['errorResults'] = self.results.errorResults
outdic['multiRun'] = self.results.multiRun
outdic['finalexpand'] = self.finalexpand
with open(str(directory) + '.json', 'w') as write_file:
json.dump(outdic,write_file)
else:
self.statusBar.setStyleSheet("background-color: #FFFF99")
self.statusBar.showMessage('Generate some values before you export to json!', 7000)
self.timer.start(7000)
def loadjson(self):
self.reset() #Resets to prepare for loading in
dlg = QFileDialog()
dlg.setFileMode(QFileDialog.ExistingFile)
filename, _filter = dlg.getOpenFileName(None, "Load in json", ".", "(*.json)")
if filename:
self.reset()
with open(filename, 'r') as read_file:
try:
indic = json.load(read_file)
for key in indic:
if key not in ['s1Inputs', 's2Inputs', 's3Inputs', 's4Inputs', 's4labels', 's5Inputs', 'errorResults', 'multiRun', 'finalexpand']:
self.statusBar.setStyleSheet("background-color: pink;")
self.statusBar.showMessage('Unrecognized JSON format, select another file', 7000)
self.timer.start(7000)
return
if len(indic['s1Inputs']) != 5:
self.statusBar.setStyleSheet("background-color: pink;")
self.statusBar.showMessage('Unrecognized JSON format, select another file', 7000)
self.timer.start(7000)
return
if not indic['errorResults']:
self.statusBar.setStyleSheet("background-color: pink;")
self.statusBar.showMessage('Unrecognized JSON format, select another file', 7000)
self.timer.start(7000)
return
if not indic['multiRun']:
self.statusBar.setStyleSheet("background-color: pink;")
self.statusBar.showMessage('Unrecognized JSON format, select another file', 7000)
self.timer.start(7000)
return
#Set text for S1
self.numMeasure.setText(indic['s1Inputs'][0])
self.numMeasure.setModified(True)
self.numMeasure.repaint()
self.numTreat.setText(indic['s1Inputs'][1])
self.numTreat.setModified(True)
self.numTreat.repaint()
self.numBf.setText(indic['s1Inputs'][2])
self.numBf.setModified(True)
self.numBf.repaint()
self.nameMeas.setText(indic['s1Inputs'][3])
self.nameMeas.setModified(True)
self.nameMeas.repaint()
self.namedVar.setText(indic['s1Inputs'][4])
self.namedVar.setModified(True)
self.namedVar.repaint()
self.s1process()
#Set text for S2
for i, obj in enumerate(self.inputs.s2Obj[0]): #labels
obj.setText(indic['s2Inputs'][0][i])
obj.repaint()
for i, obj in enumerate(self.inputs.s2Obj[1]): #values
obj.setText(indic['s2Inputs'][1][i])
obj.repaint()
self.s2process()
#Set text for S3
for i, obj in enumerate(self.inputs.s3Obj):
obj.setText(indic['s3Inputs'][i])
obj.repaint()
#Set text for S4
for i, obj in enumerate(self.inputs.s4Obj):
obj.setText(indic['s4Inputs'][i])
obj.repaint()
for i, obj in enumerate(self.inputs.s4labelobj):
obj.setText(indic['s4labels'][i])
obj.repaint()
self.s3and4process()
#Set text for S5 and storage
self.results.multiRun = indic['multiRun']
self.results.dVResults = self.results.multiRun[-1]
self.initdVValView()
self.results.errorResults = indic['errorResults']
self.initcurrInpView()
self.inputs.s5Inputs = indic['s5Inputs']
verify = s5verify(self.inputs.s5Inputs, self.inputs.s1Inputs, self.inputs.s2Inputs)
if not verify[0]:
self.statusBar.showMessage(verify[1])
self.statusBar.setStyleSheet("background-color: pink;")
return
else:
for i, obj in enumerate(self.inputs.s5Obj[0]): #Treatment col
obj.setText(indic['s5Inputs'][0][i])
obj.repaint()
for i,lst in enumerate(self.inputs.s5Obj[1]): #Blocking fac cols
for j,obj in enumerate(lst):
obj.setText(indic['s5Inputs'][1][i][j])
obj.repaint()
self.lockgrid()
self.lockinputs()
self.editInputs.show()
self.editInputs.repaint()
self.runcounter = len(self.results.multiRun)
self.runCount.setText('Current run count: ' + str(self.runcounter))
self.runCount.repaint()
self.s5but.setText('Reset runs')
self.s5but.repaint()
self.updates4.show()
self.updates4.repaint()
self.shows6fields()
if indic['finalexpand']:
self.runglm()
self.pwr()
except json.decoder.JSONDecodeError:
self.statusBar.showMessage('Invalid JSON format, select another file')
self.statusBar.setStyleSheet("background-color: pink;")
return
def initcurrInpView(self):
#Current inputs box display initialization
self.clearLayout(self.cBox)
self.errors = QLabel()
self.tmeans = QLabel()
#To make the text copyable
self.errors.setTextInteractionFlags(Qt.TextSelectableByMouse)
self.errors.setCursor(Qt.IBeamCursor)
self.tmeans.setTextInteractionFlags(Qt.TextSelectableByMouse)
self.tmeans.setCursor(Qt.IBeamCursor)
self.errors.setAlignment(Qt.AlignTop)
self.tmeans.setAlignment(Qt.AlignTop)
self.cBox.addWidget(self.errors) #in a hbox
self.cBox.addWidget(self.tmeans)
generrors = ''
tmeans = 'Treatment Means:\n'
#For generated error
for i in range(len(self.inputs.s2Inputs[0])):
generrors += self.inputs.s2Inputs[0][i] + ' SD generated error:\n'
for j in range(len(self.results.errorResults[i])):
generrors += str(j + 1)
generrors += ': '
generrors += str(self.results.errorResults[i][j])
generrors += '\n'
generrors += '\n'
#For treatment means
for i in range(len(self.inputs.s4Inputs)):
tmeans += str(i + 1)
tmeans += ': '
tmeans += self.inputs.s4Inputs[i]
tmeans += '\n'
if generrors == '':
generrors = 'No SD generated errors'
self.errors.setText(generrors)
self.tmeans.setText(tmeans)
self.errors.repaint()
self.tmeans.repaint()
def updatedVVal(self):
#Updates dependent var generation text with setText rather than overwriting
if self.results.dVObjects:
for i in range(len(self.results.dVResults)):
self.results.dVObjects[i].setText(str(self.results.dVResults[i]))
self.results.dVObjects[i].repaint()
def initdVValView(self):
#Initializes dvVal View in newly generated grid when the view doesn't exist yet
labellst = []
colCount = int(self.inputs.s1Inputs[2]) + 2
for i in range(len(self.results.dVResults)):
label = QLabel(str(self.results.dVResults[i]))
label.setAlignment(Qt.AlignHCenter)
label.setFixedHeight(21)
label.setTextInteractionFlags(Qt.TextSelectableByMouse)
label.setCursor(Qt.IBeamCursor)
labellst.append(label)
self.dGrid.addWidget(label,i+1,colCount)
self.results.dVObjects = labellst
self.updatebool = True
def updateDviewlabels(self):
#Updates the distribute view labels if any of the names are changed in step 1 or step 2
if self.firstexpand and self.dViewlabels:
self.dViewlabels[0].setText(self.inputs.s1Inputs[3])
self.dViewlabels[0].repaint()
for i in range(len(self.inputs.s2Inputs[0])):
newtext = self.inputs.s2Inputs[0][i]
self.dViewlabels[i+1].setText(newtext)
self.dViewlabels[i+1].repaint()
self.dViewlabels[len(self.dViewlabels) - 1].setText(self.inputs.s1Inputs[4])
self.dViewlabels[len(self.dViewlabels) - 1].repaint()
def initDView(self):
#Initializes distribution view in grid format in ScrollArea
self.clearLayout(self.dGrid)
tAssignObj = []
bAssignObj = []
self.dViewlabels.clear()
self.results.dVObjects.clear()
#Init the row labels
l1 = QLabel(self.inputs.s1Inputs[3])
l2 = QLabel("Treatment")
l1.setAlignment(Qt.AlignHCenter)
l2.setAlignment(Qt.AlignHCenter)
l1.setFixedHeight(21)
l2.setFixedHeight(21)
self.dGrid.addWidget(l1,0,0)
self.dGrid.addWidget(l2,0,1)
self.dViewlabels.append(l1)
#self.dViewlabels.append(l2) Skipped because this will always be treatment
for i in range(len(self.inputs.s2Inputs[0])):
blabel = QLabel(self.inputs.s2Inputs[0][i])
blabel.setFixedHeight(21)
blabel.setAlignment(Qt.AlignHCenter)
self.dGrid.addWidget(blabel,0,i+2)
self.dViewlabels.append(blabel)
colCount = int(self.inputs.s1Inputs[2]) + 2
name = QLabel(self.inputs.s1Inputs[4])
name.setAlignment(Qt.AlignHCenter)
name.setFixedHeight(21)
self.dGrid.addWidget(name,0,colCount)
self.dViewlabels.append(name)
#Init the rest of distribute groups view
for i in range(int(self.inputs.s1Inputs[0])):
numl = QLabel(str(i+1))
numl.setMaximumWidth(125)
numl.setAlignment(Qt.AlignHCenter)
self.dGrid.addWidget(numl,i+1,0)
tAssign = QLineEdit()
tAssign.setFixedHeight(21)
tAssign.setMaximumWidth(125)
tAssign.setAlignment(Qt.AlignHCenter)
tAssignObj.append(tAssign)
self.dGrid.addWidget(tAssign,i+1,1)
tAssign.repaint()
iBAssign = []
for j in range(len(self.inputs.s2Inputs[0])):
bAssign = QLineEdit()
bAssign.setFixedHeight(21)
bAssign.setMaximumWidth(125)
bAssign.setAlignment(Qt.AlignHCenter)
iBAssign.append(bAssign)
self.dGrid.addWidget(bAssign,i+1,j+2)
bAssign.repaint()
bAssignObj.append(iBAssign)
#Store these inputs to extract values at a later time
self.inputs.s5Obj.clear()
self.inputs.s5Obj.append(tAssignObj)
self.inputs.s5Obj.append(bAssignObj)
def initEView(self,emptybool):
#Initializes inputting error SD's for total and all the blocking factors
self.clearLayout(self.eBox)
lsterrors = []
totalerror = QLabel("Total error SD:")
totalerrorval = QLineEdit()
totalerrorval.setPlaceholderText('Enter SD value')
self.eBox.addRow(totalerror, totalerrorval)
lsterrors.append(totalerrorval)
if not emptybool: #if there aren't 0 blocking factors
for i in range(len(self.inputs.s2Inputs[0])):
label = QLabel(self.inputs.s2Inputs[0][i] + ' SD:')
sdval = QLineEdit()
sdval.setPlaceholderText('Enter SD value')
lsterrors.append(sdval)
self.eBox.addRow(label, sdval)
label.repaint()
sdval.repaint()
#Stores objects to extract values later
self.inputs.s3Obj.clear()
self.inputs.s3Obj = lsterrors
def initTView(self):
#Initializes treatment view box based on number of treatments
self.clearLayout(self.tBox)
lstmeans = []
lsttlabels = []
for i in range(int(self.inputs.s1Inputs[1])):
num = QLabel(str(i + 1))
label = QLineEdit()
label.setPlaceholderText('Enter label (opt)')
lsttlabels.append(label)
mean = QLineEdit()
mean.setPlaceholderText('Enter mean')
hbox = QHBoxLayout()
hbox.addWidget(label)
hbox.addWidget(mean)
lstmeans.append(mean)
self.tBox.addRow(num, hbox)
num.repaint()
mean.repaint()
#Stores objects to extract values later
self.inputs.s4Obj.clear()
self.inputs.s4Obj = lstmeans
self.inputs.s4labelobj.clear()
self.inputs.s4labelobj = lsttlabels
def initBfView(self):
#Initializes blocking factor view box based on number of blocking factors
self.clearLayout(self.bFbox)
lstlabel = []
lstval = []
for i in range(int(self.inputs.s1Inputs[2])):
bName = QLineEdit()
bName.textChanged.connect(self.changedViewlabelsbool)
bName.setCompleter(self.completer3)
bName.setPlaceholderText('Enter label')
bVal = QLineEdit()
bVal.setPlaceholderText('Enter value')
lstlabel.append(bName)
lstval.append(bVal)
self.bFbox.addRow(bName, bVal)
bName.repaint()
bVal.repaint()
#Stores objects to extract values later
self.inputs.s2Obj.clear()
self.inputs.s2Obj.append(lstlabel)
self.inputs.s2Obj.append(lstval)
def lockinputs(self):
#Locks input QLineEdits and QPushButtons for pane 1
self.editInputs.setEnabled(True)
self.editInputs.repaint()
#Locking out S1
self.numMeasure.setReadOnly(True)
self.numTreat.setReadOnly(True)
self.numBf.setReadOnly(True)
self.nameMeas.setReadOnly(True)
self.namedVar.setReadOnly(True)
self.s1but.setEnabled(False)
self.s1but.repaint()
#Locking out S2
for obj in self.inputs.s2Obj[0]:
obj.setReadOnly(True)
for obj in self.inputs.s2Obj[1]:
obj.setReadOnly(True)
self.s2but.setEnabled(False)
self.s2but.repaint()
#Locking out S3
for obj in self.inputs.s3Obj:
obj.setReadOnly(True)
#Locking out S4
for obj in self.inputs.s4Obj:
obj.setReadOnly(True)
for obj in self.inputs.s4labelobj:
obj.setReadOnly(True)
self.s4but.setEnabled(False)
self.s4but.repaint()
self.updates4.setEnabled(False)
self.updates4.repaint()
def unlockinputs(self):
#Unlocks QLineEdits and QPushButtons to update inputs for pane 1
self.editInputs.setEnabled(False)