File: PlotTimeSeriesGrid.py

package info (click to toggle)
cain 1.10%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 29,848 kB
  • sloc: cpp: 49,612; python: 14,988; xml: 11,654; ansic: 3,644; makefile: 129; sh: 2
file content (364 lines) | stat: -rw-r--r-- 13,719 bytes parent folder | download | duplicates (4)
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
"""Grid of the items (species or reactions) to plot."""

import os, os.path
# If we are running the test code.
if os.path.split(os.getcwd())[1] == 'gui':
    import sys
    sys.path.insert(1, '..')

import wx
import wx.grid
import colorsys

styleNames = ['solid', 'dashed', 'dash dot', 'dot']
styleStrings = ('-', '--', '-.', ':')
# Extracted from matplotlib/lines.py.
markers =  (
    ('', 'No marker'),
    ('.', 'Point'),
    (',', 'Pixel'),
    ('o', 'Circle'),
    ('v', 'Triangle down'),
    ('^', 'Triangle up'),
    ('<', 'Triangle left'),
    ('>', 'Triangle right'),
    ('1', 'Tripod down'),
    ('2', 'Tripod up'),
    ('3', 'Tripod left'),
    ('4', 'Tripod right'),
    ('s', 'Square'),
    ('p', 'Pentagon'),
    ('h', 'Hexagon1'),
    ('H', 'Hexagon2'),
    ('+', 'Plus'),
    ('x', 'x'),
    ('D', 'Diamond'),
    ('d', 'Thin diamond'),
    ('|', 'Vertical line'),
    ('_', 'Horizontal line')
    )
markerNames = [x[1] for x in list(markers)]
markerStrings = [x[0] for x in list(markers)]

def wxToMatplotlibColor(color):
    return (color.Red() / 255.0, color.Green() / 255.0, color.Blue() / 255.0)

class PlotTimeSeriesGrid(wx.grid.Grid):
    def __init__(self, parent):
        wx.grid.Grid.__init__(self, parent)
        columnLabels = ['Show', 'Std\nDev', 'Line\nColor', 'Style', 'Width',
                        'Marker\nStyle', 'Size', 'Face\nColor', 'Edge\nColor',
                        'Edge\nWidth', 'Legend\nLabel']
        self.CreateGrid(0, len(columnLabels))
        v = [int(_x) for _x in wx.__version__.split('.')]
        assert(len(v) >= 3)
        wxVersion = 100 * v[0] + 10 * v[1] + v[2]
        if wxVersion >= 288:
            # CONTINUE: This does not work.
            #self.SetColLabelSize(wx.grid.GRID_AUTOSIZE)
            self.SetColLabelSize(36)
        else:
            self.SetColLabelSize(36)
        for n in range(len(columnLabels)):
            self.SetColLabelValue(n, columnLabels[n])
        # CONTINUE: Determine this from the identifiers.
        self.SetRowLabelSize(160)
        self.SetRowLabelAlignment(wx.ALIGN_LEFT, wx.ALIGN_CENTRE)
        # Set the minimal column widths.
        self.SetColMinimalAcceptableWidth(0)
        # The Std. Dev. column may be hidden.
        self.SetColMinimalWidth(1, 0)

        # Lower and upper bounds for sizes and widths.
        self.lowerBound = 1
        self.upperBound = 10

        # Renderers and editors.
        boolRenderer = wx.grid.GridCellBoolRenderer()
        boolEditor = wx.grid.GridCellBoolEditor()
        lineStyleEditor = wx.grid.GridCellChoiceEditor(styleNames)
        markerStyleEditor = wx.grid.GridCellChoiceEditor(markerNames)
        numberEditor = wx.grid.GridCellNumberEditor(self.lowerBound,
                                                    self.upperBound)
        
        #
        # Grid column attributes.
        #
        # Show and Std Dev.
        attr = wx.grid.GridCellAttr()
        attr.SetRenderer(boolRenderer)
        attr.SetEditor(boolEditor)
        for col in range(2):
            self.SetColAttr(col, attr)
        # Line Color.
        attr = wx.grid.GridCellAttr()
        attr.SetReadOnly()
        self.SetColAttr(2, attr)
        # Line Style.
        attr = wx.grid.GridCellAttr()
        attr.SetEditor(lineStyleEditor)
        self.SetColAttr(3, attr)
        # Line Width.
        attr = wx.grid.GridCellAttr()
        attr.SetEditor(numberEditor)
        self.SetColAttr(4, attr)
        # Marker Style.
        attr = wx.grid.GridCellAttr()
        attr.SetEditor(markerStyleEditor)
        self.SetColAttr(5, attr)
        # Marker Size. The default size is 5.
        attr = wx.grid.GridCellAttr()
        attr.SetEditor(numberEditor)
        self.SetColAttr(6, attr)
        # Marker Face Color.
        attr = wx.grid.GridCellAttr()
        attr.SetReadOnly()
        self.SetColAttr(7, attr)
        # Marker Edge Color.
        attr = wx.grid.GridCellAttr()
        attr.SetReadOnly()
        self.SetColAttr(8, attr)
        # Marker Edge Width.
        attr = wx.grid.GridCellAttr()
        attr.SetEditor(numberEditor)
        self.SetColAttr(9, attr)
        # Use the default for the legend labels.

        # Events.
        self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.onCellLeftClick)
        self.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.onLabelLeftClick)
        self.Bind(wx.grid.EVT_GRID_LABEL_RIGHT_CLICK, self.onLabelRightClick)
        self.columnLabelFunctions = [self.select, self.select, self.lineColor,
                                     self.lineStyle, self.increment,
                                     self.markerStyle, self.increment,
                                     self.matchColor, self.matchColor,
                                     self.increment, self.legendLabels]

    def onCellLeftClick(self, event):
        row, col = event.GetRow(), event.GetCol()
        if col in (2, 7, 8):
            color = wx.GetColourFromUser(None)
            if color.IsOk():
                self.SetCellBackgroundColour(row, col, color)
        # Let the cell be selected.
        event.Skip()

    def onLabelLeftClick(self, event):
        self.labelClick(event, True)

    def onLabelRightClick(self, event):
        self.labelClick(event, False)

    def labelClick(self, event, isLeft):
        row, col = event.GetRow(), event.GetCol()
        # Do nothing if they did not click a column label.
        if col == -1:
            return
        self.saveEditControlValue()
        self.columnLabelFunctions[col](col, isLeft)
        # Don't skip the event. This prevents the row or column from being 
        # selected.
        # Force a refresh to render the modified cells.
        self.ForceRefresh()

    def select(self, col, isLeft):
        if isLeft:
            value = '1'
        else:
            value = ''
        for row in range(self.GetNumberRows()):
            self.SetCellValue(row, col, value)

    def lineColor(self, col, isLeft):
        black = wx.Colour(0, 0, 0)
        if isLeft:
            # Count the selected items.
            count = 0
            for row in range(self.GetNumberRows()):
                if self.GetCellValue(row, 0):
                    count += 1
            # Color the lines for the selected items.
            n = 0.0
            for row in range(self.GetNumberRows()):
                if self.GetCellValue(row, 0):
                    rgb = colorsys.hsv_to_rgb(n / count, 1, 1)
                    color = wx.Colour(rgb[0] * 255, rgb[1] * 255, rgb[2] * 255)
                    self.SetCellBackgroundColour(row, col, color)
                    n += 1
                else:
                    self.SetCellBackgroundColour(row, col, black)
        else:
            for row in range(self.GetNumberRows()):
                self.SetCellBackgroundColour(row, col, black)

    def lineStyle(self, col, isLeft):
        if isLeft:
            # Cycle between the available line styles.
            n = 0
            for row in range(self.GetNumberRows()):
                if self.GetCellValue(row, 0):
                    self.SetCellValue(row, col, styleNames[n])
                    n = (n + 1) % len(styleNames)
        else:
            # Set all line styles to solid.
            for row in range(self.GetNumberRows()):
                self.SetCellValue(row, col, styleNames[0])

    def increment(self, col, isLeft):
        if isLeft:
            for row in range(self.GetNumberRows()):
                try:
                    value = int(self.GetCellValue(row, col)) + 1
                    if value > self.upperBound:
                        value = self.upperBound
                    self.SetCellValue(row, col, str(value))
                except:
                    print('Could not convert "' + self.GetCellValue(row, col) +
                          '" to an integer.')
        else:
            for row in range(self.GetNumberRows()):
                try:
                    value = int(self.GetCellValue(row, col)) - 1
                    if value < self.lowerBound:
                        value = self.lowerBound
                    self.SetCellValue(row, col, str(value))
                except:
                    print('Could not convert "' + self.GetCellValue(row, col) +
                          '" to an integer.')

    def markerStyle(self, col, isLeft):
        if isLeft:
            # Cycle between the available marker styles.
            n = 0
            for row in range(self.GetNumberRows()):
                if self.GetCellValue(row, 0):
                    # Note that the first marker style is "No marker" and the
                    # second and third (point and pixel) don't scale with the
                    # marker size.
                    # We skip these choices.
                    self.SetCellValue(row, col, markerNames[n + 3])
                    n = (n + 1) % (len(markerNames) - 3)
        else:
            # No markers.
            for row in range(self.GetNumberRows()):
                self.SetCellValue(row, col, markerNames[0])

    def matchColor(self, col, isLeft):
        if isLeft:
            # Match the line colors.
            for row in range(self.GetNumberRows()):
                self.SetCellBackgroundColour\
                    (row, col, self.GetCellBackgroundColour(row, 2))
        else:
            # Set the color to black.
            color = wx.Colour(0, 0, 0)
            for row in range(self.GetNumberRows()):
                self.SetCellBackgroundColour(row, col, color)

    def legendLabels(self, col, isLeft):
        if isLeft:
            for row in range(self.GetNumberRows()):
                self.SetCellValue(row, col, self.GetRowLabelValue(row))
        else:
            for row in range(self.GetNumberRows()):
                self.SetCellValue(row, col, '')
        
    def setIdentifiers(self, identifiers):
        if self.GetNumberRows() < len(identifiers):
            self.InsertRows(0, len(identifiers) - self.GetNumberRows())
        elif self.GetNumberRows() > len(identifiers):
            self.DeleteRows(0, self.GetNumberRows() - len(identifiers))
        for row in range(self.GetNumberRows()):
            self.SetRowLabelValue(row, identifiers[row])
            # Show and Std Dev.
            for col in range(2):
                # '' is False, '1' is True.
                self.SetCellValue(row, col, '1')
            # Line Style.
            self.SetCellValue(row, 3, styleNames[0])
            # Line Width.
            self.SetCellValue(row, 4, str(self.lowerBound))
            # Marker Style.
            self.SetCellValue(row, 5, markerNames[0])
            # Marker Size. The default size is 5.
            self.SetCellValue(row, 6, '5')
            # Marker Edge Width.
            self.SetCellValue(row, 9, str(self.lowerBound))
            # Legend labels.
            self.SetCellValue(row, 10, identifiers[row])
        self.AutoSizeColumns(False)
        self.Layout()
        # Color the lines by hue.
        self.lineColor(2, True)
        # The marker face and marker edge are black.
        self.matchColor(7, False)
        self.matchColor(8, False)

    def saveEditControlValue(self):
        """Save the values being edited.."""
        if self.IsCellEditControlShown(): 
            self.SaveEditControlValue() 
            self.HideCellEditControl() 

    def showStdDev(self):
        self.AutoSizeColumn(1, False)
        self.ForceRefresh()

    def hideStdDev(self):
        self.SetColSize(1, 0)
        self.ForceRefresh()

    def getCheckedItems(self):
        """Return the list of checked item indices."""
        return filter(lambda row: self.GetCellValue(row, 0),
                      range(self.GetNumberRows()))

    def useMarkers(self, row):
        """Return True if the specified item should be plotted with markers."""
        return self.GetCellValue(row, 5) != markerNames[0]

    def getLegendLabel(self, row):
        """If no legend label is specified, use a single space."""
        return self.GetCellValue(row, 10) or ' '
    
    def getLineStyles(self, row):
        """Get the line styles."""
        return {'color':wxToMatplotlibColor
                (self.GetCellBackgroundColour(row, 2)),
                'linestyle':
                    styleStrings[styleNames.index(self.GetCellValue(row, 3))],
                'linewidth':int(self.GetCellValue(row, 4))}

    def getLineAndMarkerStyles(self, row):
        """Get the line and marker styles."""
        styles = self.getLineStyles(row)
        styles.update(
            {'marker':
                 markerStrings[markerNames.index(self.GetCellValue(row, 5))],
             'markersize':int(self.GetCellValue(row, 6)),
             'markerfacecolor':
                 wxToMatplotlibColor(self.GetCellBackgroundColour(row, 7)),
             'markeredgecolor':
                 wxToMatplotlibColor(self.GetCellBackgroundColour(row, 8)),
             'markeredgewidth':int(self.GetCellValue(row, 9))})
        return styles

    def areAnyItemsSelected(self):
        return self.GetNumberRows() != 0 and\
               reduce(lambda x, y: x or y, [self.GetCellValue(row, 0) for row
                                            in range(self.GetNumberRows())])

if __name__ == '__main__':
    class Frame(wx.Frame):
        def __init__(self, parent=None):
            wx.Frame.__init__(self, parent, title='Plot', size=(600,300))
            sizer = wx.BoxSizer(wx.VERTICAL)
            grid = PlotTimeSeriesGrid(self)
            grid.setIdentifiers(['a', 'b'])
            sizer.Add(grid, 1, wx.EXPAND)
            self.SetSizer(sizer)
            self.Fit()

    app = wx.PySimpleApp()
    Frame().Show()
    app.MainLoop()