-
Notifications
You must be signed in to change notification settings - Fork 0
/
FitResultTableGrid.py
1462 lines (1161 loc) · 52.8 KB
/
FitResultTableGrid.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/python
#-*- coding: latin-1 -*-
"""Store and display fit results in table."""
from __future__ import with_statement
import wx
import wx.grid
import wx.aui
import numpy
from observer import Subject, changes_state
import gridtypes
import dynamic_expressions
import functools
import re
import types
from custom_events import ReloadImageEvent
class DynamicExpressionDialog(wx.Dialog):
"""
Create dialog for entering dynamic expressions.
"""
def __init__(self, parent, title, expression = ''):
wx.Dialog.__init__(self, parent, -1, title, )
if 0:
reload(dynamic_expressions) #use most recent entries in
#moduly dynamic_expressions NOTE: this
#fails if cwd has changed (e.g., due
#to saving results)
sizer = wx.BoxSizer(wx.VERTICAL)
#top label
label = wx.StaticText(self, -1, 'Enter dynamic expression')
sizer.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
#entry with label
box = wx.BoxSizer(wx.HORIZONTAL)
label = wx.StaticText(self, -1, 'expression:')
box.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
self.text = wx.ComboBox(self, -1, value = expression,
choices = dynamic_expressions.dynamic_expressions)
box.Add(self.text, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
sizer.Add(box, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
#bottom line
line = wx.StaticLine(self, -1, size = (20,-1), style = wx.LI_HORIZONTAL)
sizer.Add(line, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.RIGHT|wx.TOP, 5)
#buttons
btnsizer = wx.StdDialogButtonSizer()
btn = wx.Button(self, wx.ID_OK)
btn.SetDefault()
btnsizer.AddButton(btn)
btn = wx.Button(self, wx.ID_CANCEL)
btnsizer.AddButton(btn)
btnsizer.Realize()
sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
self.SetSizer(sizer)
sizer.Fit(self)
def changes_data(f):
"""decorator for methods which changes data. Needed to see wheter
file has been modified after last save. Changes attribute
'modified'."""
@functools.wraps(f)
def wrapper(self, *args, **kwargs):
self.modified = True
return f(self, *args, **kwargs)
return wrapper
class FitResultDataTable(wx.grid.PyGridTableBase, Subject):
"""
Stores and handles all data for fit results.
"""
def __init__(self):
wx.grid.PyGridTableBase.__init__(self)
self.begin_batch() #avoid updates
#initialize fields
#NOTE: if columns added, perhaps it's necessary to change fitpar
#below
_columns = numpy.array([
#name type dynamic show
'FileID', 'long', 0, 1, '', #0
'Filename', 'string', 0, 0, '',
'N H', 'double_empty:4,1', 0, 1, 'H',
'Nerr H', 'double_empty:4,2', 0, 0, 'H',
'Nth H', 'double_empty:4,1', 0, 0, 'H',
'Nbec H', 'double_empty:4,1', 0, 0, 'H', #5
'N0 H', 'double_empty:4,1', 0, 0, 'H',
'N1 H', 'double_empty:4,1', 0, 0, 'H',
'N2 H', 'double_empty:4,1', 0, 0, 'H',
'N3 H', 'double_empty:4,1', 0, 0, 'H',
'N4 H', 'double_empty:4,1', 0, 0, 'H', #10
'N5 H', 'double_empty:4,1', 0, 0, 'H',
'OD H', 'double_empty:4,1', 0, 1, 'H',
'sx H', 'double_empty:4,1', 0, 1, 'H',
'sxerr H', 'double_empty:4,2', 0, 0, 'H',
'sy H', 'double_empty:4,1', 0, 1, 'H', #15
'syerr H', 'double_empty:4,2', 0, 0, 'H',
's1x H', 'double_empty:4,1', 0, 0, 'H',
's1xerr H', 'double_empty:4,2', 0, 0, 'H',
's1y H', 'double_empty:4,1', 0, 0, 'H',
's1yerr H', 'double_empty:4,2', 0, 0, 'H', #20
's2x H', 'double_empty:4,1', 0, 0, 'H',
's2xerr H', 'double_empty:4,2', 0, 0, 'H',
's2y H', 'double_empty:4,1', 0, 0, 'H',
's2yerr H', 'double_empty:4,2', 0, 0, 'H',
'rx H', 'double_empty:4,1', 0, 1, 'H', #25
'rxerr H', 'double_empty:4,2', 0, 0, 'H',
'ry H', 'double_empty:4,1', 0, 1, 'H',
'ryerr H', 'double_empty:4,2', 0, 0, 'H',
'mx H', 'double_empty:4,1', 0, 1, 'H',
'mxerr H', 'double_empty:4,2', 0, 0, 'H', #30
'my H', 'double_empty:4,1', 0, 1, 'H',
'myerr H', 'double_empty:4,2', 0, 0, 'H',
'm1x H', 'double_empty:4,1', 0, 0, 'H',
'm1xerr H', 'double_empty:4,2', 0, 0, 'H',
'm1y H', 'double_empty:4,1', 0, 0, 'H',
'm1yerr H', 'double_empty:4,2', 0, 0, 'H',
'm2x H', 'double_empty:4,1', 0, 0, 'H',
'm2xerr H', 'double_empty:4,2', 0, 0, 'H',
'm2y H', 'double_empty:4,1', 0, 0, 'H',
'm2yerr H', 'double_empty:4,2', 0, 0, 'H', #40
'm3x H', 'double_empty:4,1', 0, 0, 'H',
'm3xerr H', 'double_empty:4,2', 0, 0, 'H',
'm3y H', 'double_empty:4,1', 0, 0, 'H',
'm3yerr H', 'double_empty:4,2', 0, 0, 'H',
'm4x H', 'double_empty:4,1', 0, 0, 'H',
'm4xerr H', 'double_empty:4,2', 0, 0, 'H',
'm4y H', 'double_empty:4,1', 0, 0, 'H',
'm4yerr H', 'double_empty:4,2', 0, 0, 'H',
'm5x H', 'double_empty:4,1', 0, 0, 'H',
'm5xerr H', 'double_empty:4,2', 0, 0, 'H', #50
'm5y H', 'double_empty:4,1', 0, 0, 'H',
'm5yerr H', 'double_empty:4,2', 0, 0, 'H',
'T H', 'double_empty:4,3', 0, 1, 'H',
'Terr H', 'double_empty:4,3', 0, 0, 'H',
'T1 H', 'double_empty:4,3', 0, 0, 'H',
'T1err H', 'double_empty:4,3', 0, 0, 'H',
'sigma H', 'double_empty:4,3', 0, 0, 'H',
'params H', 'string', 0, 0, 'H',
'resid H','double_empty:6,4', 0, 0, 'H',
'N V', 'double_empty:4,1', 0, 1, 'V',
'Nerr V', 'double_empty:4,2', 0, 0, 'V', #60
'Nth V', 'double_empty:4,1', 0, 0, 'V',
'Nbec V', 'double_empty:4,1', 0, 0, 'V',
'N0 V', 'double_empty:4,1', 0, 0, 'V',
'N1 V', 'double_empty:4,1', 0, 0, 'V',
'N2 V', 'double_empty:4,1', 0, 0, 'V',
'N3 V', 'double_empty:4,1', 0, 0, 'V',
'N4 V', 'double_empty:4,1', 0, 0, 'V',
'N5 V', 'double_empty:4,1', 0, 0, 'V',
'OD V', 'double_empty:4,1', 0, 1, 'V',
'ODerr V', 'double_empty:4,1', 0, 0, 'V', #70
'sx V', 'double_empty:4,1', 0, 1, 'V',
'sxerr V', 'double_empty:4,2', 0, 0, 'V',
'sy V', 'double_empty:4,1', 0, 1, 'V',
'syerr V', 'double_empty:4,2', 0, 0, 'V',
's1x V', 'double_empty:4,1', 0, 0, 'V',
's1xerr V', 'double_empty:4,2', 0, 0, 'V',
's1y V', 'double_empty:4,1', 0, 0, 'V',
's1yerr V', 'double_empty:4,2', 0, 0, 'V',
's2x V', 'double_empty:4,1', 0, 0, 'V',
's2xerr V', 'double_empty:4,2', 0, 0, 'V', #80
's2y V', 'double_empty:4,1', 0, 0, 'V',
's2yerr V', 'double_empty:4,2', 0, 0, 'V',
'rx V', 'double_empty:4,1', 0, 1, 'V',
'rxerr V', 'double_empty:4,2', 0, 0, 'V',
'ry V', 'double_empty:4,1', 0, 1, 'V',
'ryerr V', 'double_empty:4,2', 0, 0, 'V',
'mx V', 'double_empty:4,1', 0, 0, 'V',
'mxerr V', 'double_empty:4,2', 0, 0, 'V',
'my V', 'double_empty:4,1', 0, 0, 'V',
'myerr V', 'double_empty:4,2', 0, 0, 'V', #90
'm1x V', 'double_empty:4,1', 0, 0, 'V',
'm1xerr V', 'double_empty:4,2', 0, 0, 'V',
'm1y V', 'double_empty:4,1', 0, 0, 'V',
'm1yerr V', 'double_empty:4,2', 0, 0, 'V',
'm2x V', 'double_empty:4,1', 0, 0, 'V',
'm2xerr V', 'double_empty:4,2', 0, 0, 'V',
'm2y V', 'double_empty:4,1', 0, 0, 'V',
'm2yerr V', 'double_empty:4,2', 0, 0, 'V',
'm3x V', 'double_empty:4,1', 0, 0, 'V',
'm3xerr V', 'double_empty:4,2', 0, 0, 'V', #100
'm3y V', 'double_empty:4,1', 0, 0, 'V',
'm3yerr V', 'double_empty:4,2', 0, 0, 'V',
'm4x V', 'double_empty:4,1', 0, 0, 'V',
'm4xerr V', 'double_empty:4,2', 0, 0, 'V',
'm4y V', 'double_empty:4,1', 0, 0, 'V',
'm4yerr V', 'double_empty:4,2', 0, 0, 'V',
'm5x V', 'double_empty:4,1', 0, 0, 'V',
'm5xerr V', 'double_empty:4,2', 0, 0, 'V',
'm5y V', 'double_empty:4,1', 0, 0, 'V',
'm5yerr V', 'double_empty:4,2', 0, 0, 'V', #110
'T V', 'double_empty:4,3', 0, 1, 'V',
'Terr V', 'double_empty:4,3', 0, 0, 'V',
'T1 V', 'double_empty:4,3', 0, 0, 'V',
'T1err V', 'double_empty:4,3', 0, 0, 'V', #110
'sigma V', 'double_empty:4,3', 0, 0, 'V',
'params V','string', 0, 0, 'V',
'resid V','double_empty:6,4', 0, 0, 'V',
'dynamic', 'double_empty:5,3', 1, 1, '',
'dynamic 2','double_empty:5,3', 1, 1, '',
'dynamic 3','double_empty:5,3', 1, 0, '',
'dynamic 4','double_empty:5,3', 1, 0, '', #120
'Mark', 'bool', 0, 0, '', #those were 'bool_custom' once
'Mark2', 'bool', 0, 0, '',
'Mark3', 'bool', 0, 0, '',
'user', 'double_empty:5,3', 0, 1, '',
'user2', 'double_empty:5,3', 0, 1, '',
'user3', 'double_empty:5,3', 0, 1, '',
'user4', 'double_empty:5,3', 0, 0, '',
'user5', 'double_empty:5,3', 0, 0, '',
'Omit', 'bool', 0, 1, '',
'Remark', 'string', 0, 1, '',
], dtype = numpy.object)
_columns.shape = (-1, 5)
self.colLabels = _columns[:,0] #:column labels
self.dataTypes = _columns[:,1] #:data types
#:indices of columns whith dynamic content
self.dynamic_cols = list(_columns[:,2].nonzero()[0])
#:expressions for dynamic columns"
self.dynamic_expressions = ['']*len(self.dynamic_cols)
#:date stored in table, as numpy array of objects
self.data = numpy.array(
['']*len(self.colLabels),
dtype = numpy.object,
ndmin = 2
)
#dict (keys: species) for list of columns of fit params
self.fitparcols = {'H': [], 'V': []}
for col, species in enumerate(_columns[:,4]):
if species:
self.fitparcols[species].append(col)
#:which rows are masked
self.rowmask = numpy.array([False])
#:dictionary for custom column labels
self.column_labels_custom = {}
#:indices of columns that are displayed
self.colsel = list(_columns[:,3].nonzero()[0])
#:initialize column sizes
self.colsize = [50]*len(self.colLabels) #array to store width of columns
self.colsize[-2] = 30
self.colsize[-1] = 200
#dict of sets to store column numbers which shall be displayed as X or Y values
self.marks = {'X': set(),
'Y1': set(),
'Y2': set(),
'G': set(),
}
self.CanHaveAttributes() #TODO: n\F6tig???
#:measurement name
self.name = ""
#:associated filename
self.filename = None
#:is the active table
self.active = True
#:do record values
self.record = True
#:Table is not (yet) modified
self.modified = False
#observers
self.observers = set()
self.end_batch()
#{ required methods for the wxPyGridTableBase interface
def GetNumberRows(self):
return len(self.data)
def GetNumberCols(self):
return len(self.colsel)
def IsEmptyCell(self, row, col):
try:
val = self.data[row, self.colsel[col]]
if val is None or val is '':
return True
else:
return False
except IndexError:
return True
def GetValue(self, row, col):
try:
return self.data[row, self.colsel[col]]
except IndexError:
return ''
@changes_state
@changes_data
def SetValue(self, row, col, value):
"""Set value if user set value. If necessary, append
rows. Updates dynamic columns. Signal this to observers.
@param col: column numbered as visible
"""
try:
self.data[row, self.colsel[col]] = value
except IndexError:
while self.GetNumberRows()-1<=row:
self.AppendRows()
self.data[row, self.colsel[col]] = value
self.update_dynamic_cols(row)
def GetColLabelValue(self, col):
"""Get column labels as displayed on top of table. Add markers
to name of column"""
label = self.column_label(self.colsel[col])
labels = []
for mark in sorted(self.marks.keys()):
if self.colsel[col] in self.marks[mark]:
labels.append(mark)
if labels:
return label + "\n(" + ','.join(labels) + ')'
else:
return label
def GetRowLabelValue(self, row):
if self.active:
if row == self.GetNumberRows() - 2:
return "next"
elif row == self.GetNumberRows() - 1:
return "..."
else:
if row >= self.GetNumberRows() - 2:
return ""
return "%d"%(row + 0)
def GetTypeName(self, row, col):
return self.dataTypes[self.colsel[col]]
def CanGetValueAs(self, row, col, typeName):
colType = self.dataTypes[self.colsel[col]].split(':')[0]
#check for substring! e.g., 'double' matches custom type
#'double_empty'
return typeName in colType
def CanSetValueAs(self, row, col, typeName):
return self.CanGetValueAs(row, col, typeName)
#{ Additional methods
def SetValueRaw(self, row, rawcol, value):
"""Set value of entry. For internal use.
@param rawcol: column numbered like in Table (not on screen)
"""
try:
self.data[row, rawcol] = value
except IndexError:
while self.GetNumberRows()-1<=row:
self.AppendRows()
self.data[row, rawcol] = value
def GetValueRaw(self, row, rawcol):
return self.data[row, rawcol]
def colname_to_raw(self, field):
rawcol = numpy.flatnonzero(self.colLabels == field)
return rawcol[0] if len(rawcol) == 1 else None
def raw_to_colname(self, rawcol):
try:
return self.colLabels[rawcol]
except IndexError:
return None
def SetValueNamed(self, row, field, value):
rawcol = self.colname_to_raw(field)
if rawcol is not None:
self.SetValueRaw(row, rawcol, value)
else:
raise ValueError('no column named "%s"'%field)
def GetValueNamed(self, row, field):
rawcol = self.colname_to_raw(field)
if rawcol is not None:
return self.GetValueRaw(row, rawcol)
else:
raise ValueError('no column named "%s"'%field)
def column_label(self, rawcol):
"""helper function to get column label
@param rawcol: column numbered like in full table
"""
label = self.colLabels[rawcol]
try:
idx = self.dynamic_cols.index(rawcol)
except ValueError:
pass
else:
if self.dynamic_expressions[idx]:
label = self.dynamic_expressions[idx]
#custom labels overrides automic column labels
custom_label = self.column_labels_custom.get(rawcol)
if custom_label:
label = custom_label
return label
@changes_data
def AppendRows(self, numRows = 1):
"""Append empty rows to table"""
for i in range(numRows):
self.data = numpy.vstack((self.data,
numpy.array([''] * self.data.shape[1], dtype = numpy.object),
))
self.rowmask = numpy.append(self.rowmask, numpy.zeros((numRows,), dtype = numpy.bool))
msg = wx.grid.GridTableMessage(self,
wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED,
numRows)
#if not self._batchcount:
# self.GetView().ProcessTableMessage(msg)
self.GetView().ProcessTableMessage(msg)
return True
@changes_state
@changes_data
def UpdateResults(self, data, row = None):
"""Update values of actual row (only if active) from fit results.
@param data: dict, possibly with keys 'H', 'V', ...
"""
if not self.active:
return
if row is None:
row = self.active_row
self.SetValueRaw(row, 0, row) #set FileID
#take only values from fit with match column labels
for species, fitpars in data.iteritems():
#clear fit parameter entries for species TODO: always
#cleared, even if fitpars not valid (Note: NoFit says
#invalid
for rawcol in self.fitparcols[species]:
self.SetValueRaw(row, rawcol, None)
if fitpars.valid:
for key, val in fitpars.valuedict().iteritems():
try:
rawcol = self.colLabels.tolist().index(key+' '+species)
self.SetValueRaw(row, rawcol, val)
except ValueError:
pass
self.update_dynamic_cols()
self.GetView().MakeCellVisible(row, 0)
self.GetView().Refresh()
def UpdateFilename(self, filename):
"""Update filename entry"""
if not self.active:
return
row = self.active_row
col = self.colname_to_raw('Filename')
self.SetValueRaw(row, col, filename)
self.GetView().Refresh()
def DeleteCols(self, pos=0, numcols=1):
pass
def AppendCols(self, numcols=1, updateLabels = True):
pass
#not used
#def DeleteRows(self, pos = 0, numRows = 1):
# print "Delete Rows", numRows, pos
def SetColSize(self, col, size):
self.colsize[self.colsel[col]] = size
def GetColSize(self, col):
return self.colsize[self.colsel[col]]
@changes_state
@changes_data
def SetColMark(self, col, mark, remove = False):
"""Set (or remove) column mark.
@param col: column number, for which mark s be set
@param mark: mark. One of 'X', 'Y1', 'Y2', 'G', ...
@type mark: string
@param remove: if True, remove mark for column
"""
if not remove:
if mark == "X" or mark == 'G':
#only one column can be labeled as 'X', remove existing 'X' mark
self.marks[mark].clear()
self.marks[mark].add(self.colsel[col])
else:
self.marks[mark].remove(self.colsel[col])
def GetAttr(self, row, col, kind):
"""Give attribute (colour, font, ...) for entry."""
#print "Get Attr",row,col,kind
provider = self.GetAttrProvider()
if provider and provider.GetAttr(row, col, kind):
attr = provider.GetAttr(row, col, kind).Clone()
else:
attr = wx.grid.GridCellAttr()
#color marks
if self.colsel[col] in self.marks['X']:
attr.SetBackgroundColour(wx.Colour(255, 230, 230))
elif self.colsel[col] in self.marks['Y1']:
attr.SetBackgroundColour(wx.Colour(255, 255, 205))
elif self.colsel[col] in self.marks['Y2']:
attr.SetBackgroundColour(wx.Colour(255, 255, 155))
elif self.colsel[col] in self.marks['G']:
attr.SetBackgroundColour(wx.Colour(155, 255, 155))
#color dynamic columns
if self.colsel[col] in self.dynamic_cols:
attr.SetBackgroundColour(wx.Colour(200, 200, 200))
#color last rows
maxRows = self.GetNumberRows()
if self.active:
if maxRows - row == 1: #last row
attr.SetBackgroundColour(wx.Colour(255, 230, 230))
elif maxRows - row == 2: #second to last row
attr.SetBackgroundColour(wx.Colour(255, 255, 205))
elif maxRows - row == 3:
if self.record:
attr.SetBackgroundColour(wx.Colour(200, 255, 200))
else:
attr.SetBackgroundColour(wx.Colour(255, 100, 100))
else:
if maxRows - row <= 2:
attr.SetBackgroundColour(wx.Colour(127, 127, 127))
###print row, len(self.rowmask)
if len(self.rowmask)>0:
if self.rowmask[row]:
attr.SetTextColour(wx.Colour(0,0,255))
return attr
@changes_state
@changes_data
def maskrows(self, rows, setmask = True):
self.rowmask[rows] = setmask
@changes_state
@changes_data
def omitrows(self, rows):
col = self.colname_to_raw('Omit')
for row in rows:
self.data[row][col] = True
def colhasmark(self, col, mark):
"return True if column col is marked mit mark"
return self.colsel[col] in self.marks.get(mark, [])
#{ service methods for plot
@property
def plotdata(self):
#collect x values
if len(self.marks['X']) == 1:
xcol = tuple(self.marks['X'])
xdata = numpy.ma.zeros((self.GetNumberRows()-2,))
xdata.mask = numpy.ma.getmaskarray(xdata)
for k, row in enumerate(self.data[:-2]):
try:
xdata[k] = row[xcol]
except ValueError:
xdata.mask[k] = True
xcollabel = self.column_label(xcol[0]) #xcol is tuple with single entry
else:
xcol = None
xdata = numpy.ma.array([])
xcollabel = ''
#collect group values
if len(self.marks['G']) == 1:
gcol = tuple(self.marks['G'])
gdata = numpy.ma.zeros((self.GetNumberRows()-2,))
gdata.mask = numpy.ma.getmaskarray(gdata)
for k, row in enumerate(self.data[:-2]):
try:
gdata[k] = row[gcol]
except ValueError:
gdata.mask[k] = True
gcollabel = self.column_label(gcol[0]) #xcol is tuple with single entry
else:
gcol = None
gdata = numpy.ma.array([])
gcollabel = ''
#collect ydata (list of arrays)
ycols = []
ydatas = []
ycollabels = []
for ymark in ['Y1', 'Y2']:
ycol = sorted(self.marks[ymark])
if len(ycol):
ydata = numpy.ma.zeros((self.GetNumberRows()-2, len(ycol)))
ydata.mask = numpy.ma.getmaskarray(ydata)
#collect ycols data
for k, row in enumerate(self.data[:-2]):
for yi, yc in enumerate(ycol):
try:
ydata[k, yi] = row[yc]
except ValueError:
ydata.mask[k, yi] = True
ycols.append(ycol)
ydatas.append(ydata)
ycollabels.append(map(self.column_label, ycol))
#masked entries
masked = self.rowmask[:-2]
#collect yid and omitted
#init arrays
yid = numpy.zeros(shape = (self.GetNumberRows()-2,), dtype = numpy.integer)
omitted = numpy.zeros(shape = (self.GetNumberRows()-2,), dtype = numpy.bool_)
omitcol = self.colname_to_raw('Omit')
for k, row in enumerate(self.data[:-2]):
yid[k] = k
if row[omitcol]:
omitted[k] = True
def sel(data, take):
if len(data):
return data[take]
else:
return data
#remove omitted values
take = ~omitted
#ydatas = [data[take] for data in ydatas]
for k, data in enumerate(ydatas):
#print k, repr(take), repr(data)
ydatas[k] = data[take]
xdata, yid, masked, gdata = \
(sel(data, take) for data in
(xdata, yid, masked, gdata))
##TODO: won't work
#for data in [xdata,yid,omitted,gdata, masked]+ydatas:
# if len(data):
# data = data[take]
#calculate group indices (i.e. integer to which group each data point belongs
#use group index -1 for empty group value
gvals = []
if gcol:
gidx = -1*numpy.ones(xdata.shape, dtype = numpy.int_)
for idx, val in enumerate(numpy.unique(gdata).compressed()):
gidx[gdata==val] = idx
gvals.append(val)
else:
gidx = numpy.zeros(xdata.shape, dtype = numpy.int_)
gvals = numpy.asarray(gvals)
#sort data
if xcol:
sortind = xdata.argsort()
ydatas = [data[sortind] for data in ydatas]
xdata, yid, gidx, masked, gdata =\
(sel(data, sortind) for data in
(xdata, yid, gidx, masked, gdata))
d = dict()
d['yid'] = yid
d['xcol'] = xcol
d['xcollabel'] = xcollabel
d['ycols'] = ycols
d['ycollabels'] = ycollabels
d['gcol'] = gcol
d['gdata'] = gdata
d['gcollabel'] = gcollabel
d['gidx'] = gidx
d['gvals'] = gvals
d['masked'] = masked
d['name'] = self.name
ydatas = [data for data in ydatas if data.size] #TODO this doesn't remove empty arrays!
#print len(ydatas), [data.shape for data in ydatas]
return (xdata, ydatas, d)
@property
def active_row(self):
row = max(0, self.GetNumberRows() - 3)
return row
#@changes_state
def activate(self, status = True):
self.active = status
def set_record(self, status = True):
self.record_data = status
def get_record(self):
return self.record_data
record = property(get_record, set_record)
def update_dynamic_cols(self, row = None, column = None):
"""
recalculate values of 'dynamic columns'.
@param row: row. If no argument given, recalculate value of active (last) row
@param column: column. If not given, recalculate all dynamic columns
"""
if row is None:
row = self.active_row
valuedict = {}
for label, value in zip(self.colLabels, self.data[row].tolist()):
valuedict[label.replace(' ', '_')] = value
for col, expression in zip(self.dynamic_cols, self.dynamic_expressions):
if column is None or col == column:
try:
# fm 2010-01-05: modified to include numpy functions
# result = eval(expression, valuedict)
tmpdict={'res':0.}
exec('import numpy as np; res =' + expression, valuedict, tmpdict)
result = tmpdict['res']
except StandardError:
# print "Error evaluation expression", expression
self.SetValueRaw(row, col, None)
else:
self.SetValueRaw(row, col, result)
#@changes_data #(reset = True) #TODO: decorator with parameter?
def save_data_csv(self, filename):
"""save data in comma seperated format."""
#add masked entry as last column
fields = numpy.r_[self.colLabels, ['masked']]
#add dynamic expression to column headers
for k, col in enumerate(self.dynamic_cols):
fields[col] += " [%s]"%self.dynamic_expressions[k] if self.dynamic_expressions[k] else ''
#add custom labels to field names
for col, fieldname in enumerate(fields):
custom_label = self.column_labels_custom.get(col)
fields[col] += " (%s)"%custom_label if custom_label else ''
fields[col] += " {*}" if (col in self.colsel and (fieldname.find('user')==0 or col in self.dynamic_cols)) else ''
#add options
#don't save last two lines
data = numpy.c_[self.data[:-2], self.rowmask[:-2]]
with open(filename, 'wb') as f:
import csv
writer = csv.writer(f)
writer.writerow(fields)
#writer.writerows(data)
for row in data:
r = [entry.encode('latin_1') if type(entry) is types.UnicodeType else entry for entry in row]
writer.writerow(r)
self.modified = False
def load_data_csv(self, filename):
"""load date from csv file into table"""
import csv
self.begin_batch() #avoid unecessary updates
#delete old data
#TODO: check of deleting data is really what user wants
#TODO: create method for clearing data
msg = wx.grid.GridTableMessage(self,
wx.grid.GRIDTABLE_NOTIFY_ROWS_DELETED,
0,
self.GetNumberRows())
self.rowmask = numpy.array([], dtype = numpy.bool)
self.data = numpy.empty(shape = (0, len(self.colLabels)), dtype = numpy.object)
self.GetView().ProcessTableMessage(msg)
#process file
with open(filename, 'rb') as f:
#read first row to extract fieldnames
header = csv.reader(f).next()
#parse field header "name [dynamic] (custom label)"
pattern = re.compile(r"(?P<name>\w+(\s\w+)?)\s*(\[(?P<dynamic>.*)\])?\s*(\((?P<label>.*)\))?\s*(\{(?P<options>.*)\})?",
re.VERBOSE)
fields = []
dyn_expr = {}
cust_label = {}
vis_cols = {}
for entry in header:
r = pattern.match(entry)
d = r.groupdict()
name = d['name']
if name:
fields.append(name)
if d['dynamic']: dyn_expr[name] = d['dynamic']
if d['label']: cust_label[name] = d['label']
if d['options']:
if '*' in d['options']: vis_cols[name] = True
#set dynamic expressions
for k, col in enumerate(self.dynamic_cols):
dexpr = dyn_expr.get(self.colLabels[col])
if dexpr:
self.dynamic_expressions[k] = dexpr
#set custom column labels
for k, label in enumerate(self.colLabels):
clabel = cust_label.get(label)
if clabel:
self.column_labels_custom[k] = clabel
#also show columns which are marked as visible in csv file
colsel = set(self.colsel)
for k, label in enumerate(self.colLabels):
if vis_cols.get(label):
colsel.add(k)
colsel = list(colsel)
colsel.sort()
self.View.SetColumnSelection(colsel)
#read data
reader = csv.DictReader(f, fieldnames = fields)
row = -1
for rowdict in reader:
row += 1
self.AppendRows()
if rowdict.get('masked') == 'True':
self.maskrows(row)
#loop over columns in _actual_ table,
for col, typelabel in enumerate(zip(self.dataTypes, self.colLabels)):
datatype, label = typelabel
#ask csv reader whether corresponding entry exists
value = rowdict.get(label)
if value is None or value == '':
continue
try:
#convert string value to proper type
#TODO: optimize it by creating a table of conversion functions
#or a table method that takes a string
if wx.grid.GRID_VALUE_FLOAT in datatype:
val = float(value)
elif wx.grid.GRID_VALUE_NUMBER in datatype:
val = int(value)
elif wx.grid.GRID_VALUE_BOOL in datatype:
if value == '1' or value == 'True':
val = True
else:
val = False
elif wx.grid.GRID_VALUE_STRING in datatype:
val = value
else:
print "loading of type %s is not supported"%datatype
continue
self.SetValueRaw(row, col, val)
except ValueError:
print "warning reading csv: cannot convert value '%s' to type %s"%(value, datatype)
self.AppendRows(2)
self.end_batch()
self.modified = False
def give_metadata(self):
"""return metadata, not stored in table data, e.g. which
columns are displayed, dynamic expressions, marks, ..."""
m = dict()
m['dynamic_expressions'] = self.dynamic_expressions
cust_labels = {}
for key, value in self.column_labels_custom.iteritems():
cust_labels[self.raw_to_colname(key)] = value
m['column_labels_custom'] = cust_labels
m['colsel'] = [self.raw_to_colname(col) for col in self.colsel]
colsizedict = {}
for col, size in enumerate(self.colsize):
colsizedict[self.raw_to_colname(col)] = size
m['colsize'] = colsizedict
marksdict = {}
for mark, colset in self.marks.iteritems():
marksdict[mark] = [self.raw_to_colname(col) for col in colset]
m['marks'] = marksdict
m['name'] = self.name
return m
def set_metadata(self, m):
"""opposite of give_metadata..."""
m_dyn_ex = m['dynamic_expressions']
self.dynamic_expressions[0:len(m_dyn_ex)] = m_dyn_ex
m_cust_lab = m['column_labels_custom']
cust_labels = {}
for name, value in m_cust_lab.iteritems():
cust_labels[self.colname_to_raw(name)] = value
self.column_labels_custom = cust_labels
self.colsel = [self.colname_to_raw(name) for name in m['colsel']]
colsize = {}
for name, size in m['colsize'].iteritems():
colsize[self.colname_to_raw(name)] = size
dcolsize = m['colsize']
for col in range(len(colsize)):
size = dcolsize.get(self.raw_to_colname)
if size is not None:
self.colsize[col] = size
for mark, colnames in m['marks'].iteritems():
self.marks[mark] = set([self.colname_to_raw(name) for name in colnames])
class FitResultDataTableGrid(wx.grid.Grid):
ID_popup_MaskRow = wx.NewId()
ID_popup_MaskSelection = wx.NewId()
ID_popup_UnmaskSelection = wx.NewId()
ID_popup_OmitSelection = wx.NewId()
ID_popup_ReloadRow = wx.NewId()
ID_popup_Column_SetX = wx.NewId()
ID_popup_Column_SetY1 = wx.NewId()
ID_popup_Column_SetY2 = wx.NewId()
ID_popup_Column_SetG = wx.NewId()
ID_popup_Select_Columns = wx.NewId()
ID_popup_Set_Column_Label= wx.NewId()
ID_popup_Column_SetExpression = wx.NewId()
ID_popup_Column_Recalculate = wx.NewId()