-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnew_salstat.py
3361 lines (3111 loc) · 139 KB
/
new_salstat.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
"""SalStat Statistics Package. Copyright 2002 Alan James Salmoni. Licensed
under the GNU General Public License (GPL). See the file COPYING for full
details of this license. """
# import wx stuff
from __future__ import unicode_literals
import wx
from wx.stc import *
import wx.grid as gridlib
import wx.html as htmllib
import wx.html2 as html2lib
import xlrd, xlwt # import xls format
import string, os, os.path, pickle
# import SalStat specific modules
import salstat_stats, images, xlrd, tabler, charter, ChartWindow
import MetaGrid
import numpy, math
# and for plots!
#from wx.Python.lib.wx.PlotCanvas import *
#from wx.Python.lib import wx.PlotCanvas
# set ip the xml modules
from xml.dom import minidom
#---------------------------------------------------------------------------
# set up id's for menu events - all on menu, some also available elsewhere
ID_FILE_NEW = wx.NewId()
ID_FILE_NEWOUTPUT = wx.NewId()
ID_FILE_OPEN = wx.NewId()
ID_FILE_SAVE = wx.NewId()
ID_FILE_SAVEAS = wx.NewId()
ID_FILE_PRINT = wx.NewId()
ID_FILE_EXIT = wx.NewId()
ID_EDIT_CUT = wx.NewId()
ID_EDIT_COPY = wx.NewId()
ID_EDIT_PASTE = wx.NewId()
ID_EDIT_SELECTALL = wx.NewId()
ID_EDIT_FIND = wx.NewId()
ID_EDIT_DELETECOL = wx.NewId()
ID_EDIT_DELETEROW = wx.NewId()
ID_PREF_VARIABLES = wx.NewId()
ID_PREF_GRID = wx.NewId()
ID_PREF_CELLS = wx.NewId()
ID_PREF_FONTS = wx.NewId()
ID_PREPARATION_DESCRIPTIVES = wx.NewId()
ID_PREPARATION_TRANSFORM = wx.NewId()
ID_PREPARATION_OUTLIERS = wx.NewId()
ID_PREPARATION_NORMALITY = wx.NewId()
ID_TRANSFORM_SQUAREROOT = wx.NewId()
ID_TRANSFORM_SQUARE = wx.NewId()
ID_TRANSFORM_INVERSE = wx.NewId()
ID_TRANSFORM_OTHER = wx.NewId()
ID_ANALYSE_1COND = wx.NewId()
ID_ANALYSE_2COND = wx.NewId()
ID_ANALYSE_3COND = wx.NewId()
ID_ANALYSE_CORRELATION = wx.NewId()
ID_ANALYSE_2FACT = wx.NewId()
ID_ANALYSE_SCRIPT = wx.NewId()
ID_ANALYSE2_1COND = wx.NewId()
ID_ANALYSE2_2COND = wx.NewId()
ID_ANALYSE2_3COND = wx.NewId()
ID_ANALYSE2_1_TTEST = wx.NewId()
ID_ANALYSE2_1_SIGN = wx.NewId()
ID_CHART = wx.NewId()
ID_CHART_DRAW = wx.NewId()
ID_BARCHART_DRAW = wx.NewId()
ID_HELP_WIZARD = wx.NewId()
ID_HELP_TOPICS = wx.NewId()
ID_HELP_SCRIPTING = wx.NewId()
ID_HELP_LICENCE = wx.NewId()
ID_HELP_ABOUT = wx.NewId()
ID_OFILE_NEW = wx.NewId()
ID_OFILE_OPEN = wx.NewId()
ID_OFILE_SAVE = wx.NewId()
ID_OFILE_SAVEAS = wx.NewId()
ID_OFILE_PRINT = wx.NewId()
ID_OFILE_CLOSE = wx.NewId()
ID_OEDIT_CUT = wx.NewId()
ID_OEDIT_COPY = wx.NewId()
ID_OEDIT_PASTE = wx.NewId()
ID_OEDIT_SELECTALL = wx.NewId()
ID_OPREF_FONT = wx.NewId()
ID_FILE_GSAVEAS = wx.NewId()
ID_FILE_GPRINTSETUP = wx.NewId()
ID_FILE_GPRINTPREVIEW = wx.NewId()
ID_FILE_GPRINT = wx.NewId()
ID_FILE_GCLOSE = wx.NewId()
ID_TITLE_GYAXIS = wx.NewId()
ID_TITLE_GXAXIS = wx.NewId()
ID_TITLE_GTITLE = wx.NewId()
ID_TITLE_LEGEND = wx.NewId()
ID_TITLE_GRID = wx.NewId()
DescList=['N','Sum','Mean','Variance','Standard Deviation','Standard Error',\
'Sum of Squares','Sum of Squared Devs', \
'Coefficient of Variation','Minimum', \
'Maximum','Range','Number Missing', \
'Geometric Mean','Harmonic Mean', \
'Skewness','Kurtosis', 'Median', \
'Median Absolute Deviation','Mode', \
'Interquartile Range', \
'Number of Unique Levels']
HypList = ['One tailed','Two tailed']
inits={} # dictionary to hold the config values
ColsUsed = []
RowsUsed = []
missingvalue = -99.999
global filename # ugh
filename = 'UNTITLED'
global BWidth, BHeight # ugh again!
BWidth = 80
BHeight = 25
HOME = os.getcwd()
if wx.Platform == '__WXMSW__':
face1 = 'Courier New'
face2 = 'Times New Roman'
face3 = 'Courier New'
fontsizes = [7,8,10,12,16,22,30]
pb = 12
wind = 50
DOCDIR = 'c:\My Documents'
INITDIR = os.getcwd()
else:
face1 = 'Helvetica'
face2 = 'Times'
face3 = 'Courier'
fontsizes = [10,12,14,16,19,24,32]
pb = 12
wind = 50
DOCDIR = os.environ['HOME']
INITDIR = DOCDIR
class History:
def __init__(self):
self.history = '' # change this for the proper DTD please!
def AppendEvent(self, xmltags):
self.history = self.history + xmltags
def ClearHistory(self):
self.history = ''
class SaveDialog2(wx.Dialog):
def __init__(self, parent, id):
wx.Dialog.__init__(self, parent, id, "Save Data?", \
size=(404+wind,100+wind))#, style = wx.DIALOG_MODAL)
icon = images.getIconIcon()
#icon = wx.Icon("icons/PurpleIcon05_32.png",wx.BITMAP_TYPE_PNG)
iconPNG = wx.Image("icons/PurpleIcon05_64.png",wx.BITMAP_TYPE_PNG).ConvertToBitmap()
iconBMP = wx.StaticBitmap(self, -1, iconPNG, pos=(20,16))
l1 = wx.StaticText(self, -1, 'Do you want to save the changes you made to', pos=(105,16))
l2 = wx.StaticText(self, -1, 'this document?', pos=(105, 36))
discardButton = wx.Button(self, 332, "Don't save", size=(90, 21),pos=(105,80))
saveButton = wx.Button(self, 331, "Save...", size=(69, 21),pos=(274,80))
CancelButton = wx.Button(self, 333, "Cancel", size=(69, 21),pos=(355,80))
self.SetIcon(ico)
self.Layout()
wx.EVT_BUTTON(self, 331, self.SaveData)
wx.EVT_BUTTON(self, 332, self.DiscardData)
wx.EVT_BUTTON(self, 333, self.CancelDialog)
def SaveData(self, event):
self.EndModal(2)
def DiscardData(self, event):
self.EndModal(3)
def CancelDialog(self, event):
self.EndModal(4)
class SaveDialog(wx.Dialog):
def __init__(self, parent, id):
wx.Dialog.__init__(self, parent, id, "Save Data?", \
size=(270+wind,100+wind))#, style = wx.DIALOG_MODAL)
icon = images.getIconIcon()
self.SetIcon(ico)
self.Choice = 'none'
vbox = wx.BoxSizer(wx.VERTICAL)
l1 = wx.StaticText(self, -1, 'You have unsaved Data')
l2 = wx.StaticText(self, -1, 'Do you wish to save it?')
vbox.Add(l1,1, wx.ALIGN_CENTER)
vbox.Add(l2,1, wx.ALIGN_CENTER)
hbox = wx.BoxSizer(wx.HORIZONTAL)
saveButton = wx.Button(self, 331, "Save...", size=(BWidth, BHeight))
discardButton = wx.Button(self, 332, "Don't save", size=(BWidth, BHeight))
CancelButton = wx.Button(self, 333, "Cancel", size=(BWidth, BHeight))
hbox.Add(saveButton, 0, wx.ALL, 5)
hbox.Add(discardButton, 0, wx.ALL, 5)
hbox.Add(CancelButton, 0, wx.ALL, 5)
vbox.Add(hbox,1)
self.SetAutoLayout(True)
self.SetSizer(vbox)
self.Layout()
self.res = ""
wx.EVT_BUTTON(self, 331, self.SaveData)
wx.EVT_BUTTON(self, 332, self.DiscardData)
wx.EVT_BUTTON(self, 333, self.CancelDialog)
def SaveData(self, event):
frame.grid.Saved = True
frame.grid.SaveAsDataASCII(self) # will it be ASCII or XML?
output.Close(True)
frame.Close(True)
self.res = "Saved"
self.Close(True)
def DiscardData(self, event):
output.Close(True)
frame.Close(True)
self.res = "Discard"
self.Close(True)
def CancelDialog(self, event):
self.res = "Cancel"
self.Close(True)
#---------------------------------------------------------------------------
# creates an init file in the home directory of the user
class GetInits:
"""This class deals with a users init file. The coords and sizes of the
various widgets are kept here, and are stored throughout the program
as a dictionary for easy access. When the program starts, the home
directory is checked for the init files existence. If absent, it is
created with a series of default values. If it is present, the values are
read into the dictionary in a slightly roundabout way! I am sure that
there is a more "Python" way of doing this, but this way works for now"""
def __init__(self):
self.initfile = os.path.join(INITDIR, '.salstatrc')
if os.path.isfile(self.initfile):
self.ReadInitFile(self.initfile)
else:
self.CreateInitFile(self.initfile)
def ReadInitFile(self, initfilename):
inits.clear()
fin = file(initfilename, 'r')
for i in range(28):
a = fin.readline()
a = string.split(a)
tmpdict = {a[0]:a[1]}
inits.update(tmpdict)
def CreateInitFile(self, initfilename):
inits = {
'gridsizex': '600',
'gridsizey': '420',
'gridposx': '50',
'gridposy': '20',
'gridcellsx': '20',
'gridcellsy': '80',
'outputsizex': '500',
'outputsizey': '400',
'outputposx': '20',
'outputposy': '50',
'scriptsizex': '600',
'scriptsizey': '400',
'scriptposx': '35',
'scriptposy': '35',
'chartsizex': '600',
'chartsizey': '400',
'chartposx': '50',
'chartposy': '50',
'helpsizex': '600',
'helpsizey': '400',
'helpposx': '40',
'helpposy': '40',
'lastfile1': "...",
'lastfile2': "...",
'lastfile3': "...",
'lastfile4': "...",
'opendir': DOCDIR,
'savedir': DOCDIR
}
initskeys = inits.keys()
initsvalues = inits.values()
fout = file(initfilename,'w')
for i in range(len(initskeys)):
fout.write(str(initskeys[i])+' '+str(initsvalues[i])+'\n')
fout.close()
self.ReadInitFile(initfilename) # damn hack!
#---------------------------------------------------------------------------
# class to output the results of several "descriptives" in one table
class ManyDescriptives:
def __init__(self, source, ds):
#__x__ = len(ds)
str2 = '<table class="table table-striped">'
outlist = ['Statistic']
for i in ds:
outlist.append(i.Name)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(0):
outlist = ['N']
for i in ds:
outlist.append(i.N)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(1):
outlist = ['Sum']
for i in ds:
outlist.append(i.sum)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(2):
outlist = ['Mean']
for i in ds:
outlist.append(i.mean)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(3):
outlist = ['Sample variance']
for i in ds:
outlist.append(i.samplevar)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(4):
outlist = ['Sample Standard Deviation']
for i in ds:
outlist.append(i.stddev)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(5):
outlist = ['Standard error']
for i in ds:
outlist.append(i.stderr)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(6):
outlist = ['Sum of squares']
for i in ds:
outlist.append(i.sumsquares)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(7):
outlist = ['Sum of squared deviations']
for i in ds:
outlist.append(i.ssdevs)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(8):
outlist = ['Coefficient of variation']
for i in ds:
outlist.append(i.coeffvar)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(9):
outlist = ['Minimum']
for i in ds:
outlist.append(i.minimum)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(10):
outlist = ['Maximum']
for i in ds:
outlist.append(i.maximum)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(11):
outlist = ['Range']
for i in ds:
outlist.append(i.range)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(12):
outlist = ['Number missing']
for i in ds:
outlist.append(i.missing)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(13):
outlist = ['Geometric mean']
for i in ds:
outlist.append(i.geomean)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(14):
outlist = ['Harmonic mean']
for i in ds:
outlist.append(i.harmmean)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(15):
outlist = ['Skewness']
for i in ds:
outlist.append(i.skewness)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(16):
outlist = ['Kurtosis']
for i in ds:
outlist.append(i.kurtosis)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(17):
outlist = ['Median']
for i in ds:
outlist.append(i.median)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(18):
outlist = ['Median absolute deviation']
for i in ds:
outlist.append(i.mad)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(19):
outlist = ['Mode']
for i in ds:
outlist.append(i.mode)
ln = tabler.vtable(outlist)
str2 = str2 + ln
if source.DescChoice.IsChecked(20):
outlist = ['Number of unique values']
for i in ds:
outlist.append(i.numberuniques)
ln = tabler.vtable(outlist)
str2 = str2 + ln
output.Addhtml(str2+'</table>\n')
#---------------------------------------------------------------------------
# class for grid - used as datagrid.
class SimpleGrid(gridlib.Grid):
def __init__(self, parent, log):
gridlib.Grid.__init__(self, parent)
self.parent = parent
self.named = False
self.Saved = True
self.filename = "Untitled"
self.moveTo = None
self.SetGridLineColour(wx.LIGHT_GREY)
self.CreateGrid(int(inits.get("gridcellsy")), \
int(inits.get("gridcellsx")))
self.SetColLabelAlignment(wx.ALIGN_LEFT, wx.ALIGN_BOTTOM)
#for i in range(20):
#self.SetColFormatFloat(i, 8, 4)
gridlib.EVT_GRID_CELL_CHANGE(self, self.AlterSaveStatus)
gridlib.EVT_GRID_RANGE_SELECT(self, self.RangeSelected)
self.wildcard = "Any File (*.*)|*.*|" \
"ASCII data format (*.dat)|*.dat|" \
"SalStat Format (*.xml)|*.xml"
self.BeginMeta()
def BeginMeta(self):
self.meta = {}
ncols = self.GetNumberCols()
for colidx in range(ncols):
labelObj = {}
varObj = {'label':labelObj}
varObj['name'] = self.GetColLabelValue(colidx)
varObj['ivdv'] = 'None set'
varObj['align'] = 'left'
varObj['missingvalues'] = ''
varObj['measure'] = 'None set'
self.meta[colidx] = varObj
def RangeSelected(self, event):
if event.Selecting():
self.tl = event.GetTopLeftCoords()
self.br = event.GetBottomRightCoords()
def AlterSaveStatus(self, event):
# this is activated when the user enters some data
self.Saved = False
# also record in the history file
col = self.GetGridCursorCol()
row = self.GetGridCursorRow()
value = self.GetCellValue(row, col)
xmlevt = '<data row="'+str(row)+'" col="'+str(col)+'">'+str(value)+'</data>\n'
hist.AppendEvent(xmlevt)
#print hist.history
# check if missing data and mark background if it is
def CutData(self, event):
buffer = wx.TextDataObject()
currentcol = self.GetGridCursorCol()
currentrow = self.GetGridCursorRow()
if self.IsSelection():
self.tl = self.GetSelectionBlockTopLeft()[0]
self.br = self.GetSelectionBlockBottomRight()[0]
top = self.tl[0]
left = self.tl[1]
bot = self.br[0] + 1
right = self.br[1] + 1
data = ''
for row in range(top, bot):
line = []
for col in range(left, right):
val = str(self.GetCellValue(row, col))
self.SetCellValue(row, col, '')
line.append(val)
data = data + '\t'.join(line) + '\r'
else:
data = self.GetCellValue(currentrow, currentcol)
if (wx.TheClipboard.Open()):
buffer.SetText(data)
wx.TheClipboard.SetData(buffer)
wx.TheClipboard.Close()
self.SetCellValue(currentrow, currentcol, '')
self.Saved = False
def CopyData(self, event):
buffer = wx.TextDataObject()
currentcol = self.GetGridCursorCol()
currentrow = self.GetGridCursorRow()
if self.IsSelection(): # extend this only if SalStat can paste lists
self.tl = self.GetSelectionBlockTopLeft()[0]
self.br = self.GetSelectionBlockBottomRight()[0]
top = self.tl[0]
left = self.tl[1]
bot = self.br[0] + 1
right = self.br[1] + 1
data = ''
for row in range(top, bot):
line = []
for col in range(left, right):
val = str(self.GetCellValue(row, col))
line.append(val)
data = data + '\t'.join(line) + '\r'
else:
data = self.GetCellValue(currentrow, currentcol)
if (wx.TheClipboard.Open()):
buffer.SetText(data)
wx.TheClipboard.SetData(buffer)
wx.TheClipboard.Close()
def PasteData(self, event):
buffer = wx.TextDataObject()
currentcol = self.GetGridCursorCol()
currentrow = self.GetGridCursorRow()
res = wx.TheClipboard.Open()
if res:
data = wx.TheClipboard.GetData(buffer)
pastetext = buffer.GetText()
wx.TheClipboard.Close()
if pastetext:
self.Saved = False
rows = pastetext.split('\r')
for row in range(len(rows)):
cells = rows[row].split('\t')
for col in range(len(cells)):
val = cells[col]
self.SetCellValue(currentrow+row, currentcol+col, val)
def EditGrid(self, event, numrows):
insert = self.AppendRows(numrows)
def DeleteCurrentCol(self, event):
currentcol = self.GetGridCursorCol()
self.DeleteCols(currentcol, 1)
self.AdjustScrollbars()
xmlevt = '<deleteColumn>'+str(currentcol)+'</deleteColumn>\n'
hist.AppendEvent(xmlevt)
def DeleteCurrentRow(self, event):
currentrow = self.GetGridCursorRow()
self.DeleteRows(currentrow, 1)
self.AdjustScrollbars()
xmlevt = '<deleteRow>'+str(currentrow)+'</deleteRow>\n'
hist.AppendEvent(xmlevt)
def SelectAllCells(self, event):
self.SelectAll()
def ResizeGrid(self, ncols, nrows):
spare = 10 # extra spaces
# check that data is saved before clearing!
self.ClearGrid()
self.AppendCols(ncols + spare)
self.AppendRows(nrows + spare)
# adds columns and rows to the grid
def AddNCells(self, numcols, numrows):
insert = self.AppendCols(numcols)
insert = self.AppendRows(numrows)
for i in range(self.GetNumberCols() - numcols):
self.SetColLabelAlignment(wx.ALIGN_LEFT, wx.ALIGN_BOTTOM)
self.SetColFormatFloat(i, 8, 4)
self.AdjustScrollbars()
xmlevt = '<appendColumn>'+str(numcols)+'</appendColumn>\n'
hist.AppendEvent(xmlevt)
xmlevt = '<appendRow>'+str(numrows)+'</appendRow>\n'
hist.AppendEvent(xmlevt)
# function finds out how many cols contain data - all in a list
#(ColsUsed) which has col #'s
def GetUsedCols(self):
ColsUsed = []
colnums = []
cols = self.GetNumberCols()
for i in range(cols):
dat = self.GetCellValue(0, i)
if (dat!=''):
ColsUsed.append(self.GetColLabelValue(i))
colnums.append(i)
return ColsUsed, colnums
def GetColsUsedList(self):
colsusedlist = []
for i in range(self.GetNumberCols()):
try:
tmp = float(self.GetCellValue(0,i))
colsusedlist.append(i)
except ValueError:
colsusedlist.append(0)
return colsusedlist
def GetUsedColsType(self):
ColsUsedIV = []
ColsUsedDV = []
colnumsIV = []
colnumsDV = []
ColsUsed, Colnums = self.GetUsedCols()
for idx, col in enumerate(Colnums):
if self.meta[col].ivdv == 'IV':
ColsUsedIV.append(ColsUsed[idx])
colnumsIV.append(col)
elif self.meta[col].ivdv == 'DV':
ColsUsedDV.append(ColsUsed[idx])
colnumsDV.append(col)
return ColsUsedIV, ColsUsedDV, colnumsIV, colnumsDV
def GetUsedRows(self):
RowsUsed = []
for i in range(self.GetNumberCols()):
if (self.GetCellValue(0, i) != ''):
for j in range(self.GetNumberRows()):
if (self.GetCellValue(j,i) == ''):
RowsUsed.append(j)
break
return RowsUsed
def SaveAsDataASCII(self, event):
default = inits.get('savedir')
dlg = wx.FileDialog(self, "Save Data File", default,"",\
"CSV text (*.csv)|*.csv|Plain text (*.txt)|*.txt", wx.SAVE)
dlg.SetIcon(ico)
if dlg.ShowModal() == wx.ID_OK:
inits.update({'savedir': dlg.GetDirectory()})
filename = dlg.GetPath()
fout = open(filename, "w")
cols,waste = self.GetUsedCols()
if (dlg.GetFilterIndex() == 0):
#save as plain text
rows = self.GetUsedRows()
maxrows = max(rows)
for i in range(len(cols)):
for j in range(maxrows):
if (self.GetCellValue(j,i) == ''):
self.SetCellValue(j,i,'.')
for i in range(maxrows):
datapoint=[]
for j in range(len(cols)):
try:
datapoint.append(self.GetCellValue(i, j))
except:
datapoint.append("0")
line = string.join(datapoint)
fout.write(line)
fout.write('\n')
elif (dlg.GetFilterIndex() == 1):
# save as native format
print "cannot do this just yet!"
fout.close
self.Saved = True
self.named = True
path, self.filename = os.path.split(filename)
self.parent.SetTitle(self.filename)
def SaveDataASCII(self, event):
if self.named:
defaultDir = inits.get('savedir')
fout = open(defaultDir + os.sep + self.filename, "w")
cols, waste = self.GetUsedCols()
rows = self.GetUsedRows()
maxrows = max(rows) + 1
for i in range(maxrows):
datapoint=[]
for j in range(len(cols)):
try:
datapoint.append(self.GetCellValue(i, j))
except:
datapoint.append("0")
line = string.join(datapoint)
fout.write(line)
fout.write('\n')
fout.close
self.Saved = True
else:
self.SaveAsDataASCII(None)
# Loads an ASCII data file - only with all datapoints filled though!
# also does csv values as well
def LoadDataASCII(self, event):
default = inits.get('opendir')
dlg = wx.FileDialog(self, "Open Data File", "","",\
#self.wildcard, wx.OPEN)
"All files (*.*)|*.*|", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
dlg.SetIcon(ico)
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetPath()
if filename[-3:] == 'xml':
self.LoadNativeXML(filename)
if filename[-3:] == "xls" or filename[-4:] == "xlsx":
self.LoadExcel(filename)
else:
inits.update({'opendir': dlg.GetDirectory()})
self.ClearGrid()
# exception handler here!
try:
fin = open(filename, "r")
except IOError:
pass # what to do if they filename isn't visible? Messagebox?
gridline = 0
self.Freeze()
for i in fin.readlines():
words = string.split(i)
if len(words) > self.GetNumberCols():
NumberCols = len(words) - self.GetNumberCols() + 10
self.AddNCells(NumberCols, 0)
for j in range(len(words)):
self.SetCellValue(gridline, j, words[j])
gridline = gridline + 1
if (gridline == self.GetNumberRows()):
self.AddNCells(0,10)
fin.close()
self.Thaw()
self.ForceRefresh()
self.Saved = False
self.named = True
path, self.filename = os.path.split(filename)
self.parent.SetTitle(self.filename)
def LoadExcel(self, filename):
try:
workbook = xlrd.open_workbook(filename)
except: # get proper exception
pass # could not open file
try:
# numsheets = workbook.nsheets
# user should decide here which sheet.
# temp code: Default to first
worksheet = workbook.sheet_by_index(0)
nrows = worksheet.nrows
ncols = worksheet.ncols
self.ResizeGrid(ncols, nrows)
for idx_row in range(nrows):
for idx_col in range(ncols):
val = unicode(worksheet.cell(idx_row, idx_col).value)
self.SetCellValue(idx_row, idx_col, val)
except:
pass
def getData(self, x):
for i in range(len(x)):
try:
row = int(x[i].attributes["row"].value)
col = int(x[i].attributes["column"].value)
datavalue = float(self.getText(x[i].childNodes))
self.SetCellValue(row, col, str(datavalue))
except ValueError:
print "problem importing the xml"
def getText(self, nodelist):
rc = ""
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc = rc + node.data
return rc
def LoadNativeXML(self, filename):
# also get rid of the old history
if os.path.isfile(filename) == 0:
pass
else:
# now start the XML processing
self.ClearGrid()
self.Freeze()
xmldoc = minidom.parse(filename)
datatags = xmldoc.getElementsByTagName('data')
self.getData(datatags)
deleteRowTags = xmldoc.getElementsByTagName('deleteRow')
for i in range(len(deleteRowTags)):
rownum = int(self.getText(deleteRowTags[i].childNodes))
self.DeleteRows(rownum, 1)
deleteColTags = xmldoc.getElementsByTagName('deleteColumn')
for i in range(len(deleteColTags)):
colnum = int(self.getText(deleteColTags[i].childNodes))
self.DeleteCols(colnum, 1)
appendRowTags = xmldoc.getElementsByTagName('appendRow')
for i in range(len(appendRowTags)):
rownum = int(self.getText(appendRowTags[i].childNodes))
self.AppendRows()
appendColTags = xmldoc.getElementsByTagName('appendColumn')
for i in range(len(appendColTags)):
colnum = int(self.getText(appendRowTags[i].childNodes))
self.AppendCols()
deleteColTags = xmldoc.getElementsByTagName('deleteColumn')
for i in range(len(deleteColTags)):
colnum = int(self.getText(deleteColTags[i].childNodes))
self.DeleteCurrentCol(colnum)
deleteRowTags = xmldoc.getElementsByTagName('deleteRow')
for i in range(len(deleteRowTags)):
rownum = int(self.getText(deleteRowTags[i].childNodes))
self.DeleteCurrentRow(rownum)
# there is a problem here - the html tags embedded between the <results> tags
# are parsed as XML, but I want the whole lot available as a string.
output.Addhtml('<P><B>SalStat Statistics</B></P>')
output.htmlpage.WholeOutString = ''
resultsTags = xmldoc.getElementsByTagName('results')
for i in range(len(resultsTags)):
outputText = self.getText(resultsTags[i].childNodes)
#print "out" + outputText # debugging!
output.Addhtml(outputText)
#describeTags = xmldoc.getElementsByTagName('describe')
#for i in range(len(describeTags)):
self.Thaw()
def LoadNumericData(self, event):
default = inits.get('opendir')
dlg = wx.FileDialog(self, "Load Data File", default,"","*.\
dat|*.*", wx.OPEN)
dlg.SetIcon(ico)
if dlg.ShowModal() == wx.ID_OK:
inits.update({'opendir': dlg.GetDirectory()})
filename = dlg.GetPath()
self.ClearGrid()
# exception handler here!
fin = open(filename, "r")
p = pickle.Unpickler(fin)
dataset = p.load()
fin.close()
# put dataset into grid
def CleanRowData(self, row):
indata = []
for i in range(self.GetNumberCols()):
datapoint = self.GetCellValue(row, i)
if (datapoint != ''):
value = float(datapoint)
if (value != missingvalue):
indata.append(value)
return indata
# Routine to return a "clean" list of data from one column
def CleanData(self, col):
indata = []
self.missing = 0
for i in range(self.GetNumberRows()):
datapoint = self.GetCellValue(i, col)
if (datapoint != '') and (datapoint != '.'):
try:
value = float(datapoint)
if (value != missingvalue):
indata.append(value)
else:
self.missing = self.missing + 1
except ValueError:
pass
return indata
def GetColumnData(self, col):
indata = []
self.missing = 0
for i in range(self.GetNumberRows()):
val = self.GetCellValue(i, col)
if val != "":
if val != missingvalue:
try:
indata.append(float(val))
except ValueError:
indata.append(val)
else:
self.missing += 1
try:
return numpy.array(indata)
except TypeError:
return indata
def GetEntireDataSet(self, numcols):
"""Returns the data specified by a list 'numcols' in a Numpy
array"""
biglist = []
for i in range(len(numcols)):
smalllist = frame.grid.CleanData(numcols[i])
biglist.append(smalllist)
return numpy.array((biglist), numpy.Float)
#---------------------------------------------------------------------------
# DescChoice-wx.CheckListBox with list of descriptive stats in it
class DescChoiceBox(wx.CheckListBox):
def __init__(self, parent, id):
wx.CheckListBox.__init__(self, parent, -1, pos=(250,30), \
size=(240,310), choices=DescList)
def SelectAllDescriptives(self, event):
for i in range(len(DescList)):
self.Check(i, True)
def SelectNoDescriptives(self, event):
for i in range(len(DescList)):
self.Check(i, False)
#---------------------------------------------------------------------------
# base class for getting number of columns/rows to add
class EditGridFrame(wx.Dialog):
def __init__(self, parent, id):
wx.Dialog.__init__(self, parent, id, "Change Grid Size", \
size=(205, 100+wind))
self.SetIcon(ico)
l1 = wx.StaticText(self, -1, 'Add Columns',pos=(10,15))
l2 = wx.StaticText(self, -1, 'Add Rows',pos=(10,55))
self.numnewcols = wx.SpinCtrl(self, -1, "", wx.Point(110,10), wx.Size(80,25))
self.numnewcols.SetRange(0, 100)
self.numnewcols.SetValue(0)
self.numnewRows = wx.SpinCtrl(self, -1, "", wx.Point(110, 50), wx.Size(80,25))
self.numnewRows.SetRange(0, 100)
self.numnewRows.SetValue(0)
okaybutton = wx.Button(self, 421, "Okay", wx.Point(10, 90),\
wx.Size(BWidth, BHeight))
cancelbutton = wx.Button(self, 422, "Cancel", wx.Point(110,90), \
wx.Size(BWidth, BHeight))
wx.EVT_BUTTON(self, 421, self.OkayButtonPressed)
wx.EVT_BUTTON(self, 422, self.CancelButtonPressed)
def OkayButtonPressed(self, event):
colswanted = self.numnewcols.GetValue()
rowswanted = self.numnewRows.GetValue()
frame.grid.AddNCells(colswanted, rowswanted)
self.Close(True)
def CancelButtonPressed(self, event):
self.Close(True)
#---------------------------------------------------------------------------
# grid preferences - set row & col sizes
class GridPrefs(wx.Dialog):
def __init__(self, parent, id):
wx.Dialog.__init__(self, parent, id, "Cell Size", \
size=(205,100+wind))
self.SetIcon(ico)
self.colwidth = wx.SpinCtrl(self, -1, "", wx.Point(110,10), wx.Size(80,25))
self.colwidth.SetRange(1,200)
self.colwidth.SetValue(frame.grid.GetDefaultColSize())
self.rowheight= wx.SpinCtrl(self, -1, "", wx.Point(110,50), wx.Size(80,25))
self.rowheight.SetRange(1,100)
self.rowheight.SetValue(frame.grid.GetDefaultRowSize())
l1 = wx.StaticText(self, -1, 'Column Width:',pos=(10,15))
l2 = wx.StaticText(self, -1, 'Row Height:',pos=(10,55))
okaybutton = wx.Button(self, 321, "Okay", wx.Point(10, 90), \
wx.Size(BWidth, BHeight))
cancelbutton = wx.Button(self, 322, "Cancel", wx.Point(110,90),\
wx.Size(BWidth, BHeight))
wx.EVT_BUTTON(self, 321, self.OkayButtonPressed)
wx.EVT_BUTTON(self, 322, self.OnCloseGridPrefs)
def OkayButtonPressed(self, event):
frame.grid.SetDefaultColSize(self.colwidth.GetValue(), True)
frame.grid.SetDefaultRowSize(self.rowheight.GetValue(), True)
frame.grid.ForceRefresh()
self.Close(True)
def OnCloseGridPrefs(self, event):
self.Close(True)
#---------------------------------------------------------------------------
# shows the scripting window for entering Python syntax commands
class ScriptFrame(wx.Frame):
def __init__(self, parent, id):
dimx = int(inits.get('scriptsizex'))
dimy = int(inits.get('scriptsizey'))
posx = int(inits.get('scriptposx'))
posy = int(inits.get('scriptposy'))
wx.Frame.__init__(self, parent, id, "Scripting Window", \