This repository has been archived by the owner on Nov 5, 2020. It is now read-only.
/
controls.py
1366 lines (1131 loc) · 47.2 KB
/
controls.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: utf-8 -*-
""" ShapeOut - control panels
"""
from __future__ import division, print_function
import numpy as np
import wx
import wx.grid as gridlib
import wx.lib.agw.hypertreelist as HT
from wx.lib.scrolledpanel import ScrolledPanel
import dclab
from dclab import config as dc_config
from ..configuration import ConfigurationFile
from .. import tlabwrap
from .. import util
from .polygonselect import LineDrawerWindow
from . import plot_scatter
from . import plot_contour
from .controls_subpanel import SubPanel
from .controls_analysis import SubPanelAnalysis
class FlatNotebook(wx.Notebook):
"""
Flatnotebook class
"""
def __init__(self, parent):
"""Constructor"""
self.fnb = wx.Notebook.__init__(self, parent, wx.ID_ANY)
class ControlPanel(ScrolledPanel):
""""""
def __init__(self, parent, frame):
"""Constructor"""
ScrolledPanel.__init__(self, parent)
self.SetupScrolling(scroll_y=True)
self.SetupScrolling(scroll_x=True)
self.frame = frame
self.config = frame.config
self.notebook = FlatNotebook(self)
self.subpanels = []
self.AddSubpanels()
self.notebook.SetSelection(4)
# Shortucut SHIFT+ENTER replots everything
randomId = wx.NewId()
self.Bind(wx.EVT_MENU, self.OnChangePlot, id=randomId)
accel_tbl = wx.AcceleratorTable([(wx.ACCEL_SHIFT, wx.WXK_RETURN, randomId )])
self.SetAcceleratorTable(accel_tbl)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.notebook, 1, wx.ALL | wx.EXPAND, 5)
self.SetSizer(sizer)
def AddSubpanels(self):
notebook=self.notebook
page_info = SubPanelInfo(notebook)
notebook.AddPage(page_info, _("Information"))
self.subpanels.append(page_info)
self.page_info = page_info
self.page_filter = SubPanelFilter(notebook, funcparent=self)
notebook.AddPage(self.page_filter, _("Filtering"))
self.subpanels.append(self.page_filter)
self.page_stat = SubPanelStatistics(notebook)
notebook.AddPage(self.page_stat, _("Statistics"))
self.subpanels.append(self.page_stat)
self.page_cont = SubPanelAnalysis(notebook, funcparent=self)
notebook.AddPage(self.page_cont, _("Analysis"))
self.subpanels.append(self.page_cont)
self.page_plot = SubPanelPlotting(notebook, funcparent=self)
notebook.AddPage(self.page_plot, _("Plotting"))
self.subpanels.append(self.page_plot)
self.page_scat = SubPanelPlotScatter(notebook, funcparent=self)
notebook.AddPage(self.page_scat, _("Scatter Plot"))
self.subpanels.append(self.page_scat)
self.page_cont = SubPanelPlotContour(notebook, funcparent=self)
notebook.AddPage(self.page_cont, _("Contour Plot"))
self.subpanels.append(self.page_cont)
def NewAnalysis(self, anal=None):
# destroy everything on Info panel and replot.
if anal is not None:
self.analysis = anal
self.UpdatePages()
def OnChangeFilter(self, e=None):
# get all values
wx.BeginBusyCursor()
ctrls = self.page_filter.GetChildren()
samdict = self.analysis.measurements[0].\
Configuration["Filtering"].copy()
newfilt = dict()
# identify controls via their name correspondence in the cfg
for c in ctrls:
name = c.GetName()
if samdict.has_key(name):
# box filters
if isinstance(c, wx._controls.CheckBox):
newfilt[name] = bool(c.GetValue())
else:
newfilt[name] = float(c.GetValue())
chlist = self.page_filter.GetPolygonHtreeChecked()
checked = []
for ch in chlist:
checked.append(ch.GetData())
# Polygon filters are handled separately for each measurement.
# This is done by the autobinding methods of the SubPanelFilter
# - OnPolygonCombobox (display filter for each mm)
# - OnPolygonHtreeChecked (change filter for each mm)
#newfilt["Polygon Filters"] = checked
cfg = { "Filtering" : newfilt }
# Apply base data limits
if cfg["Filtering"]["Limit Events Auto"]:
minsize = self.analysis.ForceSameDataSize()
cfg["Filtering"]["Limit Events"] = minsize
for c in ctrls:
name = c.GetName()
if name == "Limit Events":
c.SetValue(str(minsize))
self.analysis.SetParameters(cfg)
# Only update the plotting data.
# (Until version 0.6.1 the plots were recreated after
# each update, which caused a memory leak)
plot_window = self.frame.PlotArea.mainplot.plot_window
plots = plot_window.component.components
for plot in plots:
for mm in self.analysis.measurements:
if plot.id == mm.identifier:
plot_scatter.set_scatter_data(plot, mm)
plot_scatter.reset_inspector(plot)
if plot.id == "ShapeOut_contour_plot":
plot_contour.set_contour_data(plot, self.analysis.measurements)
self.UpdatePages()
wx.EndBusyCursor()
def OnChangePlot(self, e=None):
# Set plot order
if hasattr(self.analysis, "measurements"):
print(self.page_plot.plot_order)
self.analysis.measurements = [ self.analysis.measurements[ii] for ii in self.page_plot.plot_order ]
wait = wx.BusyCursor()
ctrls = list(self.page_plot.GetChildren())
ctrls += list(self.page_cont.GetChildren())
ctrls += list(self.page_scat.GetChildren())
samdict = self.analysis.measurements[0].\
Configuration["Plotting"].copy()
newfilt = dict()
# identify controls via their name correspondence in the cfg
for c in ctrls:
name = c.GetName()
if samdict.has_key(name):
var = name
if isinstance(c, wx.ComboBox) and hasattr(c, "data"):
# handle combobox selections such that the string in the
# combobox does not matter, only the selection id.
cid = c.GetSelection()
if cid != -1:
val = c.data[cid]
else:
val = c.GetValue()
else:
val = c.GetValue()
var, val = dc_config.map_config_value_str2type(var, val)
newfilt[var] = val
elif "Title " in name:
# Change title of measurement
for mm in self.analysis.measurements:
if mm.identifier in name:
mm.title = c.GetValue()
elif "Color " in name:
# Change plotting color of measurement
for mm in self.analysis.measurements:
if mm.identifier in name:
col = c.GetColour()
col = np.array([col.Red(), col.Green(),
col.Blue(), col.Alpha()])/255
mm.Configuration["Plotting"]["Contour Color"] = col.tolist()
cfg = { "Plotting" : newfilt }
self.analysis.SetParameters(cfg)
# Update Plots
self.frame.PlotArea.Plot(self.analysis)
self.UpdatePages()
del wait
def OnPolygonFilter(self, result):
""" Called by polygon Window """
dclab.PolygonFilter(points=result["points"],
axes=result["axes"])
# update list of polygon filters
self.UpdatePages()
# The first polygon will be applied to all plots
if len(self.page_filter.GetPolygonHtreeChecked()) == 0:
ctrls = self.page_filter.GetChildren()
# identify controls via their name correspondence in the cfg
for c in ctrls:
if c.GetName() == "Polygon Filter Selection":
# get the selected items
r = c.GetRootItem()
cs = r.GetChildren()
unique_id = cs[-1].GetData()
newcfg = {"Filtering":
{"Polygon Filters": [unique_id]} }
self.analysis.SetParameters(newcfg)
# and apply
self.OnChangeFilter()
def Reset(self, key, subkeys=[]):
newcfg = tlabwrap.GetDefaultConfiguration(key)
if len(subkeys) != 0:
for k in list(newcfg.keys()):
if not k in subkeys:
newcfg.pop(k)
self.analysis.SetParameters({key : newcfg})
if key == "Plotting" and "Contour Plot" in subkeys:
self.analysis.SetContourAccuracies()
self.UpdatePages()
self.frame.PlotArea.Plot(self.analysis)
def UpdatePages(self):
""" fills pages """
sel = self.notebook.GetSelection()
# Recreate all pages instead of just calling `UpdatePanel`.
# This resolves issues on at least Linux
for _i in range(len(self.subpanels)):
self.notebook.RemovePage(0)
self.subpanels = []
self.AddSubpanels()
# Update page content
for page in self.subpanels:
page.UpdatePanel(self.analysis)
# workaround to force redrawing of Page:
page.Layout()
page.Refresh()
page.Update()
# select previously selected page
self.notebook.SetSelection(sel)
self.notebook.Refresh()
self.notebook.Update()
class DragListStriped(wx.ListCtrl):
def __init__(self, *arg, **kw):
wx.ListCtrl.__init__(self, *arg, **kw)
self.Bind(wx.EVT_LIST_BEGIN_DRAG, self._onDrag)
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self._onSelect)
self.Bind(wx.EVT_LEFT_UP,self._onMouseUp)
self.Bind(wx.EVT_LEFT_DOWN, self._onMouseDown)
self.Bind(wx.EVT_LEAVE_WINDOW, self._onLeaveWindow)
self.Bind(wx.EVT_ENTER_WINDOW, self._onEnterWindow)
self.Bind(wx.EVT_LIST_INSERT_ITEM, self._onInsert)
self.Bind(wx.EVT_LIST_DELETE_ITEM, self._onDelete)
#---------------
# Variables
#---------------
self.IsInControl=True
self.startIndex=-1
self.dropIndex=-1
self.IsDrag=False
self.dragIndex=-1
def _onLeaveWindow(self, event):
self.IsInControl=False
self.IsDrag=False
event.Skip()
def _onEnterWindow(self, event):
self.IsInControl=True
event.Skip()
def _onDrag(self, event):
self.IsDrag=True
self.dragIndex=event.m_itemIndex
event.Skip()
pass
def _onSelect(self, event):
self.startIndex=event.m_itemIndex
event.Skip()
def _onMouseUp(self, event):
# Purpose: to generate a dropIndex.
# Process: check self.IsInControl, check self.IsDrag, HitTest, compare HitTest value
# The mouse can end up in 5 different places:
# Outside the Control
# On itself
# Above its starting point and on another item
# Below its starting point and on another item
# Below its starting point and not on another item
if self.IsInControl==False: #1. Outside the control : Do Nothing
self.IsDrag=False
else: # In control but not a drag event : Do Nothing
if self.IsDrag==False:
pass
else: # In control and is a drag event : Determine Location
self.hitIndex=self.HitTest(event.GetPosition())
self.dropIndex=self.hitIndex[0]
# -- Drop index indicates where the drop location is; what index number
#---------
# Determine dropIndex and its validity
#--------
if self.dropIndex==self.startIndex or self.dropIndex==-1: #2. On itself or below control : Do Nothing
pass
else:
#----------
# Now that dropIndex has been established do 3 things
# 1. gather item data
# 2. delete item in list
# 3. insert item & it's data into the list at the new index
#----------
dropList=[] # Drop List is the list of field values from the list control
thisItem=self.GetItem(self.startIndex)
for x in range(self.GetColumnCount()):
dropList.append(self.GetItem(self.startIndex,x).GetText())
thisItem.SetId(self.dropIndex)
self.DeleteItem(self.startIndex)
self.InsertItem(thisItem)
for x in range(self.GetColumnCount()):
self.SetStringItem(self.dropIndex,x,dropList[x])
#------------
# I don't know exactly why, but the mouse event MUST
# call the stripe procedure if the control is to be successfully
# striped. Every time it was only in the _onInsert, it failed on
# dragging index 3 to the index 1 spot.
#-------------
# Furthermore, in the load button on the wxFrame that this lives in,
# I had to call the _onStripe directly because it would occasionally fail
# to stripe without it. You'll notice that this is present in the example stub.
# Someone with more knowledge than I probably knows why...and how to fix it properly.
#-------------
self._onStripe()
self.IsDrag=False
event.Skip()
def _onMouseDown(self, event):
self.IsInControl=True
event.Skip()
def _onInsert(self, event):
# Sequencing on a drop event is:
# wx.EVT_LIST_ITEM_SELECTED
# wx.EVT_LIST_BEGIN_DRAG
# wx.EVT_LEFT_UP
# wx.EVT_LIST_ITEM_SELECTED (at the new index)
# wx.EVT_LIST_INSERT_ITEM
#--------------------------------
# this call to onStripe catches any addition to the list; drag or not
self._onStripe()
self.dragIndex=-1
event.Skip()
def _onDelete(self, event):
self._onStripe()
event.Skip()
def _onStripe(self):
if self.GetItemCount()>0:
for x in range(self.GetItemCount()):
if x % 2==0:
self.SetItemBackgroundColour(x,wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DLIGHT))
else:
self.SetItemBackgroundColour(x,wx.WHITE)
class SubPanelFilter(SubPanel):
def __init__(self, parent, *args, **kwargs):
SubPanel.__init__(self, parent, *args, **kwargs)
self.config = ConfigurationFile()
self.key = "Filtering"
def _box_rest_filter(self, analysis, key):
"""
Display rest like data event limit
"""
gen = wx.StaticBox(self, label=_("Other filters"))
hbox = wx.StaticBoxSizer(gen, wx.VERTICAL)
items = analysis.GetParameters(key).items()
sortfunc = lambda x: (x[0].replace("Max", "2")
.replace("Min", "1"))
items.sort(key=sortfunc)
sgen = wx.FlexGridSizer(len(items), 1)
excludeend = ["Min", "Max"]
excludeis = ["Enable Filters"]
excludestart = ["Polygon"]
#sgen = wx.BoxSizer(wx.VERTICAL)
for item in items:
ins = True
for it in excludeend:
if item[0].endswith(it):
ins = False
for it in excludeis:
if item[0] == it:
ins = False
for it in excludestart:
if item[0].startswith(it):
ins = False
if not ins:
continue
stemp = self._create_type_wx_controls(analysis,
key, item)
sgen.Add(stemp)
sgen.Layout()
hbox.Add(sgen)
return hbox
def _box_minmax_filter(self, analysis, key):
"""
Display everything with Min/Max
"""
gen = wx.StaticBox(self, label=_("Box Filters"))
hbox = wx.StaticBoxSizer(gen, wx.VERTICAL)
items = analysis.GetParameters(key).items()
sortfunc = lambda x: (x[0].replace("Max", "2")
.replace("Min", "1"))
items.sort(key=sortfunc)
sgen = wx.FlexGridSizer(len(items), 2)
#sgen = wx.BoxSizer(wx.VERTICAL)
# distinguish between deformation and circularity
display_circ = False
if "Circ" in analysis.GetPlotAxes():
display_circ = True
if "Defo" in analysis.GetPlotAxes():
display_circ = False
for item in items:
if item[0].startswith("Circ") and display_circ is False:
pass
elif item[0].startswith("Defo") and display_circ is True:
pass
elif item[0].endswith("Min"):
if item[0][:-4] in analysis.GetUnusableAxes():
# ignore this item
continue
# find item with max
idmax = [ii[0] for ii in items].index(item[0][:-3]+"Max")
itemmax = items[idmax]
a = wx.StaticText(self, label=_("Range "+item[0][:-4]))
b = wx.TextCtrl(self, value=str(item[1]), name=item[0])
c = wx.TextCtrl(self, value=str(itemmax[1]), name=itemmax[0])
stemp = wx.BoxSizer(wx.HORIZONTAL)
sgen.Add(a, 0, wx.ALIGN_CENTER_VERTICAL)
stemp.Add(b)
stemp.Add(c)
sgen.Add(stemp)
elif item[0].endswith("Max"):
# did that before
pass
else:
pass
sgen.Layout()
hbox.Add(sgen)
return hbox
def _box_polygon_filter(self, analysis):
## Polygon box
# layout:
# new selection box
# duplicate (multiple selections)
# edit
# delete
# import
# export preview plot
# export all (own axis w/ label)
polybox = wx.StaticBox(self, name="",
label=_("Polygon Filters"))
# sizers
polysizer = wx.StaticBoxSizer(polybox, wx.HORIZONTAL)
horsizer = wx.BoxSizer(wx.HORIZONTAL)
optsizer = wx.BoxSizer(wx.VERTICAL)
plotsizer = wx.BoxSizer(wx.VERTICAL)
horsizer.Add(optsizer)
horsizer.Add(plotsizer)
polysizer.Add(horsizer)
## left column
# new
new = wx.Button(self, label=_("New"))
new.Bind(wx.EVT_BUTTON, self.OnPolygonWindow)
optsizer.Add(new)
# duplicate
duplicate = wx.Button(self, label=_("Duplicate"))
duplicate.Bind(wx.EVT_BUTTON, self.OnPolygonDuplicate)
optsizer.Add(duplicate)
# edit
edit = wx.Button(self, label=_("Edit"))
#edit.Bind(wx.EVT_BUTTON, self.OnPolygonEdit)
edit.Disable()
optsizer.Add(edit)
# remove
remove = wx.Button(self, label=_("Remove"))
remove.Bind(wx.EVT_BUTTON, self.OnPolygonRemove)
optsizer.Add(remove)
# import
imp = wx.Button(self, label=_("Import"))
imp.Bind(wx.EVT_BUTTON, self.OnPolygonImport)
optsizer.Add(imp)
## right column
# dropdown (plot selection)
choice_be = analysis.GetTitles()
cbg = wx.ComboBox(self, -1, choices=choice_be,
value=_("None"), name="None",
style=wx.CB_DROPDOWN|wx.CB_READONLY)
cbg.SetSelection(min(0, len(choice_be)-1))
cbg.SetValue(choice_be[-1])
cbg.Bind(wx.EVT_COMBOBOX, self.OnPolygonCombobox)
plotsizer.Add(cbg)
# htree control for polygon filter selection
pol_filters = dclab.PolygonFilter.instances
htreectrl = HT.HyperTreeList(self, name="Polygon Filter Selection",
agwStyle=wx.TR_DEFAULT_STYLE|wx.TR_HIDE_ROOT|\
HT.TR_NO_HEADER|HT.TR_EDIT_LABELS)
htreectrl.DeleteAllItems()
htreectrl.AddColumn("")
htreectrl.SetColumnWidth(0, 500)
rroot = htreectrl.AddRoot("", ct_type=0)
for p in pol_filters:
# filtit =
htreectrl.AppendItem(rroot, p.name, ct_type=1,
data=p.unique_id)
htreectrl.Bind(HT.EVT_TREE_ITEM_CHECKED, self.OnPolygonHtreeChecked)
# This is covered by self.OnPolygonCombobox()
# FIL = analysis.GetParameters("Filtering")
# if (FIL.has_key("Polygon Filters") and
# p.unique_id in FIL["Polygon Filters"]):
# filtit.Check(True)
htreectrl.SetMinSize((200,120))
plotsizer.Add(htreectrl, 1, wx.EXPAND, 3)
# export
horsizer2 = wx.BoxSizer(wx.HORIZONTAL)
export = wx.Button(self, label=_("Export"))
export.Bind(wx.EVT_BUTTON, self.OnPolygonExport)
horsizer2.Add(export)
# export_all
export_all = wx.Button(self, label=_("Export All"))
export_all.Bind(wx.EVT_BUTTON, self.OnPolygonExportAll)
horsizer2.Add(export_all)
plotsizer.Add(horsizer2)
self._polygon_filter_combo_box = cbg
self._polygon_filter_selection_htree = htreectrl
self.OnPolygonCombobox()
return polysizer
def GetPolygonHtreeChecked(self):
""" Returns
"""
checked = list()
# get selection from htree
ctrls = self.GetChildren()
# identify controls via their name correspondence in the cfg
for c in ctrls:
if c.GetName() == "Polygon Filter Selection":
# get the selected items
r = c.GetRootItem()
for ch in r.GetChildren():
if ch.IsChecked():
checked.append(ch)
# else
return checked
def GetPolygonHtreeSelected(self):
""" Returns
"""
# get selection from htree
ctrls = self.GetChildren()
# identify controls via their name correspondence in the cfg
for c in ctrls:
if c.GetName() == "Polygon Filter Selection":
# get the selected items
r = c.GetRootItem()
for ch in r.GetChildren():
if ch.IsSelected():
return c, ch
# else
return c, None
def OnPolygonCombobox(self, e=None):
"""
Called when the user selects a different item in the plot selection
combobox. We will mark the activated filters for that plot. in the
selection box below.
ComboBox:: self._polygon_filter_combo_box
HTreeCtrl: self._polygon_filter_selection_htree
"""
htreectrl = self._polygon_filter_selection_htree
cmb = self._polygon_filter_combo_box
# get selection
sel = cmb.GetSelection()
# get measurement
mm = self.analysis.measurements[sel]
# get filters
r = htreectrl.GetRootItem()
if "Polygon Filters" in mm.Configuration["Filtering"]:
filterlist = mm.Configuration["Filtering"]["Polygon Filters"]
#print(filterlist)
# set visible filters
for item in r.GetChildren():
#print("looking at", item.GetData())
if item.GetData() in filterlist:
#print("will check")
htreectrl.CheckItem(item, True)
else:
#print("wont check")
htreectrl.CheckItem(item, False)
else:
# Uncheck everything, because mm does not know Filtering
for item in r.GetChildren():
htreectrl.CheckItem(item, False)
def OnPolygonDuplicate(self, e=None):
_c, ch = self.GetPolygonHtreeSelected()
if ch is None:
return
unique_id = ch.GetData()
p = dclab.PolygonFilter.get_instance_from_id(unique_id)
dclab.PolygonFilter(points=p.points, axes=p.axes)
self.UpdatePanel()
def OnPolygonExport(self, e=None, export_all=False):
if not export_all:
_c, ch = self.GetPolygonHtreeSelected()
if ch is None:
return
dlg = wx.FileDialog(self, "Open polygon file",
self.config.GetWorkingDirectory(name="Polygon"), "",
"ShapeOut polygon file (*.poly)|*.poly", wx.FD_SAVE)
if dlg.ShowModal() == wx.ID_OK:
fname = dlg.GetPath()
self.config.SetWorkingDirectory(dlg.GetDirectory(),
name="Polygon")
dlg.Destroy()
else:
self.config.SetWorkingDirectory(dlg.GetDirectory(),
name="Polygon")
dlg.Destroy()
return # nothing more to do here
if not fname.endswith(".poly"):
fname += ".poly"
if not export_all:
unique_id = ch.GetData()
p = dclab.PolygonFilter.get_instance_from_id(unique_id)
p.save(fname)
else:
# export all
dclab.PolygonFilter.save_all(fname)
def OnPolygonExportAll(self, e=None):
if len(dclab.PolygonFilter.instances) != 0:
self.OnPolygonExport(export_all=True)
def OnPolygonHtreeChecked(self, e=None):
"""
This function is called when an item in the htreectrl is checked
or unchecked. We apply the corresponding filters to the underlying
RTDC data set live.
ComboBox:: self._polygon_filter_combo_box
HTreeCtrl: self._polygon_filter_selection_htree
"""
htreectrl = self._polygon_filter_selection_htree
cmb = self._polygon_filter_combo_box
# get selection
sel = cmb.GetSelection()
# get measurement
mm = self.analysis.measurements[sel]
# get filters
newfilterlist = list()
# set visible filters
r = htreectrl.GetRootItem()
for item in r.GetChildren():
if item.IsChecked():
#print(item.GetData(), "checked")
newfilterlist.append(item.GetData())
else:
#print(item.GetData(), "unhecked")
pass
# apply filters to data set
mm.Configuration["Filtering"]["Polygon Filters"] = newfilterlist
def OnPolygonImport(self, e=None):
dlg = wx.FileDialog(self, "Open polygon file",
self.config.GetWorkingDirectory(name="Polygon"), "",
"ShapeOut polygon file (*.poly)|*.poly", wx.FD_OPEN)
if dlg.ShowModal() == wx.ID_OK:
fname = dlg.GetPath()
self.config.SetWorkingDirectory(dlg.GetDirectory(),
name="Polygon")
dlg.Destroy()
else:
self.config.SetWorkingDirectory(dlg.GetDirectory(),
name="Polygon")
dlg.Destroy()
return # nothing more to do here
if not fname.endswith(".poly"):
fname += ".poly"
dclab.PolygonFilter.import_all(fname)
self.UpdatePanel()
def OnPolygonRemove(self, e=None):
c, ch = self.GetPolygonHtreeSelected()
if ch is None:
return
unique_id = ch.GetData()
dclab.PolygonFilter.remove(unique_id)
self.analysis.PolygonFilterRemove(unique_id)
c.Delete(ch)
self.funcparent.frame.PlotArea.Plot(self.analysis)
def OnPolygonWindow(self, e=None):
""" Called when user wants to add a new polygon filter """
ldw = LineDrawerWindow(self.funcparent,
self.funcparent.OnPolygonFilter)
# get plot that we want to use
name = self._polygon_filter_combo_box.GetValue()
names = self.analysis.GetTitles()
if name in names:
idn = names.index(name)
else:
idn = 0
xax, yax = self.analysis.GetPlotAxes()
mm = self.analysis.measurements[idn]
ldw.show_scatter(mm, xax=xax, yax=yax)
ldw.Show()
def UpdatePanel(self, analysis=None):
if analysis is None:
# previous analysis is used
analysis = self.analysis
if hasattr(self, "_polygon_filter_combo_box") :
old_meas_selection = self._polygon_filter_combo_box.GetSelection()
else:
old_meas_selection = 0
self.analysis = analysis
for item in self.GetChildren():
item.Hide()
self.RemoveChild(item)
item.Destroy()
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizerv = wx.BoxSizer(wx.VERTICAL)
sizer.Add(sizerv)
# Box filters
fbox = self._box_minmax_filter(analysis, "Filtering")
sizerv.Add(fbox)
# Rest filters:
rbox = self._box_rest_filter(analysis, "Filtering")
sizerv.Add(rbox)
# Polygon filters
polysizer = self._box_polygon_filter(analysis)
sizer.Add(polysizer)
## Polygon box
# layout:
# new selection box
# duplicate (multiple selections)
# edit
# delete
# import
# export preview plot
# export all (own axis w/ label)
#
## Polygon selection
# line_drawing example
# - selection: choose which data to be displayed
# - on press enter, draw polygon and allow new selection.
# - buttons: add, clear, clear all
# (- show other polygons with selection box)
vertsizer = wx.BoxSizer(wx.VERTICAL)
filten = analysis.GetParameters("Filtering")["Enable Filters"]
cb = self._create_type_wx_controls(analysis,
"Filtering",
["Enable Filters", filten],)
vertsizer.Add(cb)
btn_apply = wx.Button(self, label=_("Apply"))
## TODO:
# write function in this class that gives ControlPanel a new
# analysis, such that OnChangeFilter becomes shorter.
self.Bind(wx.EVT_BUTTON, self.funcparent.OnChangeFilter, btn_apply)
vertsizer.Add(btn_apply)
btn_reset = wx.Button(self, label=_("Reset"))
self.Bind(wx.EVT_BUTTON, self.OnReset, btn_reset)
vertsizer.Add(btn_reset)
# Set the previously selected measurement
self._polygon_filter_combo_box.SetSelection(old_meas_selection)
# Make the htree control below the combobox aware of this selection
self.OnPolygonCombobox()
sizer.Add(vertsizer)
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()
class SubPanelInfo(SubPanel):
def __init__(self, *args, **kwargs):
SubPanel.__init__(self, *args, **kwargs)
def UpdatePanel(self, analysis):
""" """
for item in self.GetChildren():
item.Hide()
self.RemoveChild(item)
item.Destroy()
# Create three boxes containing information
sizer = wx.BoxSizer(wx.HORIZONTAL)
genbox = self._box_from_cfg_read(analysis, "General")
imbox = self._box_from_cfg_read(analysis, "Image")
frbox = self._box_from_cfg_read(analysis, "Framerate")
roibox = self._box_from_cfg_read(analysis, "ROI")
# same size
h = genbox.GetMinSize()[1]
h = max(h, imbox.GetMinSize()[1])
h = max(h, frbox.GetMinSize()[1])
h = max(h, roibox.GetMinSize()[1])
h = max(h, 50)
genbox.SetMinSize((-1, h))
imbox.SetMinSize((-1, h))
frbox.SetMinSize((-1, h))
roibox.SetMinSize((-1, h))
sizer.Add(genbox)
sizer.Add(imbox)
sizer.Add(frbox)
sizer.Add(roibox)
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()
class SubPanelPlotting(SubPanel):
def __init__(self, parent, *args, **kwargs):
SubPanel.__init__(self, parent, *args, **kwargs)
self.key = "Plotting"
def _box_from_cfg_plotting(self, analysis):
""" Top panel draw plotting elements
"""
key = self.key
mastersizer = wx.BoxSizer(wx.HORIZONTAL)
axes = wx.StaticBox(self, label=_("Axes"))
axesbox = wx.StaticBoxSizer(axes, wx.VERTICAL)
axessizer = wx.BoxSizer(wx.VERTICAL)
axesbox.Add(axessizer)
mastersizer.Add(axesbox)
misc = wx.StaticBox(self, label=_("Miscellaneous"))
miscbox = wx.StaticBoxSizer(misc, wx.VERTICAL)
miscsizer = wx.BoxSizer(wx.VERTICAL)
miscbox.Add(miscsizer)
mastersizer.Add(miscbox)
items = analysis.GetParameters(key).items()
# Determine the order in which things are displayed
# in the control panel
sortfunc = lambda x: (x[0].replace("Max", "2")
.replace("Min", "1")
.replace("Plot", "1")
.replace("Accuracy", "2")
.replace("Columns", "a1")
.replace("Rows", "a2")
.replace("Axis", "Aa"))
items.sort(key=sortfunc)
# distinguish between deformation and circularity
display_circ = False
if "Circ" in analysis.GetPlotAxes():
display_circ = True
if "Defo" in analysis.GetPlotAxes():
display_circ = False
xax, yax = analysis.GetPlotAxes()
# Remove all items that have nothing to do with this page
dellist = list()
exclude = Plotting_Elements_Scatter+Plotting_Elements_Contour
for item in items:
for stid in exclude:
if item[0].startswith(stid):
dellist.append(item)
for it in dellist:
items.remove(it)
# Remove unneccessary controls
for topic in ["Min", "Max"]:
dellist = list()
for item in items:
if (item[0].endswith(topic) and
not (item[0] == "{} {}".format(xax, topic) or
item[0] == "{} {}".format(yax, topic))):
dellist.append(item)
elif display_circ and item[0] == "Defo {}".format(topic):
dellist.append(item)
elif not display_circ and item[0] == "Circ {}".format(topic):
dellist.append(item)
for it in dellist:
items.remove(it)
useditems = []
## Populate axes
for item in items:
if (item[0].startswith("Axis") or
item[0].startswith("Scale ")):
stemp = self._create_type_wx_controls(analysis, key, item)
useditems.append(item)
axessizer.Add(stemp)
elif item[0].endswith("Min"):
# find item with max
idmax = [ii[0] for ii in items].index(item[0][:-3]+"Max")