File: base.py

package info (click to toggle)
grass 6.4.4-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 104,028 kB
  • ctags: 40,409
  • sloc: ansic: 419,980; python: 63,559; tcl: 46,692; cpp: 29,791; sh: 18,564; makefile: 7,000; xml: 3,505; yacc: 561; perl: 559; lex: 480; sed: 70; objc: 7
file content (522 lines) | stat: -rw-r--r-- 20,422 bytes parent folder | download
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
"""!
@package wxplot.base

@brief Base classes for iinteractive plotting using PyPlot

Classes:
 - base::PlotIcons
 - base::BasePlotFrame

(C) 2011 by the GRASS Development Team

This program is free software under the GNU General Public License
(>=v2). Read the file COPYING that comes with GRASS for details.

@author Michael Barton, Arizona State University
"""

import os
import sys

import wx
import wx.lib.plot as plot

from core.globalvar    import ETCICONDIR
from core.settings     import UserSettings
from wxplot.dialogs    import TextDialog, OptDialog
from core.render       import Map
from icons.icon        import MetaIcon
from gui_core.toolbars import BaseIcons

import grass.script as grass

PlotIcons = {
    'draw'         : MetaIcon(img = 'show',
                              label = _('Draw/re-draw plot')),
    'transect'     : MetaIcon(img = 'layer-raster-profile',
                              label = _('Draw transect in map display window to profile')),
    'options'      : MetaIcon(img = 'settings',
                              label = _('Plot options')),
    'statistics'   : MetaIcon(img = 'check',
                              label = _('Plot statistics')),
    'save'         : MetaIcon(img = 'save',
                              label = _('Save profile data to CSV file')),
    'quit'         : BaseIcons['quit'].SetLabel(_('Quit plot tool')),
    }

class BasePlotFrame(wx.Frame):
    """!Abstract PyPlot display frame class"""
    def __init__(self, parent = None, id = wx.ID_ANY, size = wx.Size(700, 400),
                 style = wx.DEFAULT_FRAME_STYLE, rasterList = [],  **kwargs):

        wx.Frame.__init__(self, parent, id, size = size, style = style, **kwargs)
        
        self.parent = parent            # MapFrame for a plot type
        self.mapwin = self.parent.MapWindow
        self.Map    = Map()             # instance of render.Map to be associated with display
        self.rasterList = rasterList    #list of rasters to plot
        self.raster = {}    # dictionary of raster maps and their plotting parameters
        self.plottype = ''
        
        self.linestyledict = { 'solid' : wx.SOLID,
                            'dot' : wx.DOT,
                            'long-dash' : wx.LONG_DASH,
                            'short-dash' : wx.SHORT_DASH,
                            'dot-dash' : wx.DOT_DASH }

        self.ptfilldict = { 'transparent' : wx.TRANSPARENT,
                            'solid' : wx.SOLID }

        #
        # Icon
        #
        self.SetIcon(wx.Icon(os.path.join(ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
                
        #
        # Add statusbar
        #
        self.statusbar = self.CreateStatusBar(number = 2, style = 0)
        self.statusbar.SetStatusWidths([-2, -1])

        #
        # Define canvas and settings
        #
        # 
        self.client = plot.PlotCanvas(self)

        #define the function for drawing pointLabels
        self.client.SetPointLabelFunc(self.DrawPointLabel)

        # Create mouse event for showing cursor coords in status bar
        self.client.canvas.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)

        # Show closest point when enabled
        self.client.canvas.Bind(wx.EVT_MOTION, self.OnMotion)

        self.plotlist = []      # list of things to plot
        self.plot = None        # plot draw object
        self.ptitle = ""        # title of window
        self.xlabel = ""        # default X-axis label
        self.ylabel = ""        # default Y-axis label

        #
        # Bind various events
        #
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
        
        self.CentreOnScreen()
        
        self._createColorDict()


    def _createColorDict(self):
        """!Create color dictionary to return wx.Colour tuples
        for assigning colors to images in imagery groups"""
                
        self.colorDict = {}
        for clr in grass.named_colors.iterkeys():
            if clr == 'white' or clr == 'black': continue
            r = grass.named_colors[clr][0] * 255
            g = grass.named_colors[clr][1] * 255
            b = grass.named_colors[clr][2] * 255
            self.colorDict[clr] = (r,g,b,255)

    def InitPlotOpts(self, plottype):
        """!Initialize options for entire plot
        """        
        self.plottype = plottype                # profile

        self.properties = {}                    # plot properties
        self.properties['font'] = {}
        self.properties['font']['prop'] = UserSettings.Get(group = self.plottype, key = 'font')
        self.properties['font']['wxfont'] = wx.Font(11, wx.FONTFAMILY_SWISS,
                                                    wx.FONTSTYLE_NORMAL,
                                                    wx.FONTWEIGHT_NORMAL)
        
        self.properties['raster'] = {}
        self.properties['raster'] = UserSettings.Get(group = self.plottype, key = 'raster')
        colstr = str(self.properties['raster']['pcolor'])
        self.properties['raster']['pcolor'] = tuple(int(colval) for colval in colstr.strip('()').split(','))

        if self.plottype == 'profile':
            self.properties['marker'] = UserSettings.Get(group = self.plottype, key = 'marker')
            # changing color string to tuple for markers/points
            colstr = str(self.properties['marker']['color'])
            self.properties['marker']['color'] = tuple(int(colval) for colval in colstr.strip('()').split(','))
 

        self.properties['grid'] = UserSettings.Get(group = self.plottype, key = 'grid')        
        colstr = str(self.properties['grid']['color']) # changing color string to tuple        
        self.properties['grid']['color'] = tuple(int(colval) for colval in colstr.strip('()').split(','))
                
        self.properties['x-axis'] = {}
        self.properties['x-axis']['prop'] = UserSettings.Get(group = self.plottype, key = 'x-axis')
        self.properties['x-axis']['axis'] = None

        self.properties['y-axis'] = {}
        self.properties['y-axis']['prop'] = UserSettings.Get(group = self.plottype, key = 'y-axis')
        self.properties['y-axis']['axis'] = None
        
        self.properties['legend'] = UserSettings.Get(group = self.plottype, key = 'legend')

        self.zoom = False  # zooming disabled
        self.drag = False  # draging disabled
        self.client.SetShowScrollbars(True) # vertical and horizontal scrollbars

        # x and y axis set to normal (non-log)
        self.client.setLogScale((False, False))
        if self.properties['x-axis']['prop']['type']:
            self.client.SetXSpec(self.properties['x-axis']['prop']['type'])
        else:
            self.client.SetXSpec('auto')
        
        if self.properties['y-axis']['prop']['type']:
            self.client.SetYSpec(self.properties['y-axis']['prop']['type'])
        else:
            self.client.SetYSpec('auto')
        
    def InitRasterOpts(self, rasterList, plottype):
        """!Initialize or update raster dictionary for plotting
        """

        rdict = {} # initialize a dictionary

        self.properties['raster'] = UserSettings.Get(group = self.plottype, key = 'raster')

        for r in rasterList:
            idx = rasterList.index(r)
            
            try:
                ret = grass.raster_info(r)
            except:
                continue
                # if r.info cannot parse map, skip it
               
            self.raster[r] = self.properties['raster'] # some default settings
            rdict[r] = {} # initialize sub-dictionaries for each raster in the list
            
            rdict[r]['units'] = ''
            if ret['units'] not in ('(none)', '"none"', '', None):
                rdict[r]['units'] = ret['units']
            
            rdict[r]['plegend'] = r.split('@')[0]
            rdict[r]['datalist'] = [] # list of cell value,frequency pairs for plotting
            rdict[r]['pline'] = None
            rdict[r]['datatype'] = ret['datatype']

            #    
            #initialize with saved values
            #
            if self.properties['raster']['pwidth'] != None:
                rdict[r]['pwidth'] = self.properties['raster']['pwidth']
            else:
                rdict[r]['pwidth'] = 1
                
            if self.properties['raster']['pstyle'] != None and \
                self.properties['raster']['pstyle'] != '':
                rdict[r]['pstyle'] = self.properties['raster']['pstyle']
            else:
                rdict[r]['pstyle'] = 'solid'
                        
            if idx <= len(self.colorList):
                if idx == 0:
                    # use saved color for first plot
                    if self.properties['raster']['pcolor'] != None:
                        rdict[r]['pcolor'] = self.properties['raster']['pcolor'] 
                    else:
                        rdict[r]['pcolor'] = self.colorDict[self.colorList[idx]]
                else:
                    rdict[r]['pcolor'] = self.colorDict[self.colorList[idx]]
            else:
                r = randint(0, 255)
                b = randint(0, 255)
                g = randint(0, 255)
                rdict[r]['pcolor'] = ((r,g,b,255))
        
        return rdict

    def SetGraphStyle(self):
        """!Set plot and text options
        """
        self.client.SetFont(self.properties['font']['wxfont'])
        self.client.SetFontSizeTitle(self.properties['font']['prop']['titleSize'])
        self.client.SetFontSizeAxis(self.properties['font']['prop']['axisSize'])

        self.client.SetEnableZoom(self.zoom)
        self.client.SetEnableDrag(self.drag)
        
        #
        # axis settings
        #
        if self.properties['x-axis']['prop']['type'] == 'custom':
            self.client.SetXSpec('min')
        else:
            self.client.SetXSpec(self.properties['x-axis']['prop']['type'])

        if self.properties['y-axis']['prop']['type'] == 'custom':
            self.client.SetYSpec('min')
        else:
            self.client.SetYSpec(self.properties['y-axis']['prop'])

        if self.properties['x-axis']['prop']['type'] == 'custom' and \
               self.properties['x-axis']['prop']['min'] < self.properties['x-axis']['prop']['max']:
            self.properties['x-axis']['axis'] = (self.properties['x-axis']['prop']['min'],
                                                 self.properties['x-axis']['prop']['max'])
        else:
            self.properties['x-axis']['axis'] = None

        if self.properties['y-axis']['prop']['type'] == 'custom' and \
                self.properties['y-axis']['prop']['min'] < self.properties['y-axis']['prop']['max']:
            self.properties['y-axis']['axis'] = (self.properties['y-axis']['prop']['min'],
                                                 self.properties['y-axis']['prop']['max'])
        else:
            self.properties['y-axis']['axis'] = None
            
        if self.properties['x-axis']['prop']['log'] == True:
            self.properties['x-axis']['axis'] = None
            self.client.SetXSpec('min')
        if self.properties['y-axis']['prop']['log'] == True:
            self.properties['y-axis']['axis'] = None
            self.client.SetYSpec('min')
                        
        self.client.setLogScale((self.properties['x-axis']['prop']['log'],
                                 self.properties['y-axis']['prop']['log']))
        
        #
        # grid settings
        #
        self.client.SetEnableGrid(self.properties['grid']['enabled'])
                
        self.client.SetGridColour(wx.Colour(self.properties['grid']['color'][0],
                                           self.properties['grid']['color'][1],
                                           self.properties['grid']['color'][2],
                                           255))
        
        #
        # legend settings
        #
        self.client.SetFontSizeLegend(self.properties['font']['prop']['legendSize'])
        self.client.SetEnableLegend(self.properties['legend']['enabled'])

    def DrawPlot(self, plotlist):
        """!Draw line and point plot from list plot elements.
        """
        self.plot = plot.PlotGraphics(plotlist,
                                         self.ptitle,
                                         self.xlabel,
                                         self.ylabel)

        if self.properties['x-axis']['prop']['type'] == 'custom':
            self.client.SetXSpec('min')
        else:
            self.client.SetXSpec(self.properties['x-axis']['prop']['type'])

        if self.properties['y-axis']['prop']['type'] == 'custom':
            self.client.SetYSpec('min')
        else:
            self.client.SetYSpec(self.properties['y-axis']['prop']['type'])

        self.client.Draw(self.plot, self.properties['x-axis']['axis'],
                         self.properties['y-axis']['axis'])
                
    def DrawPointLabel(self, dc, mDataDict):
        """!This is the fuction that defines how the pointLabels are
            plotted dc - DC that will be passed mDataDict - Dictionary
            of data that you want to use for the pointLabel

            As an example I have decided I want a box at the curve
            point with some text information about the curve plotted
            below.  Any wxDC method can be used.
        """
        dc.SetPen(wx.Pen(wx.BLACK))
        dc.SetBrush(wx.Brush( wx.BLACK, wx.SOLID ) )

        sx, sy = mDataDict["scaledXY"] #scaled x,y of closest point
        dc.DrawRectangle( sx-5,sy-5, 10, 10)  #10by10 square centered on point
        px,py = mDataDict["pointXY"]
        cNum = mDataDict["curveNum"]
        pntIn = mDataDict["pIndex"]
        legend = mDataDict["legend"]
        #make a string to display
        s = "Crv# %i, '%s', Pt. (%.2f,%.2f), PtInd %i" %(cNum, legend, px, py, pntIn)
        dc.DrawText(s, sx , sy+1)

    def OnZoom(self, event):
        """!Enable zooming and disable dragging
        """
        self.zoom = True
        self.drag = False
        self.client.SetEnableZoom(self.zoom)
        self.client.SetEnableDrag(self.drag)

    def OnDrag(self, event):
        """!Enable dragging and disable zooming
        """
        self.zoom = False
        self.drag = True
        self.client.SetEnableDrag(self.drag)
        self.client.SetEnableZoom(self.zoom)

    def OnRedraw(self, event):
        """!Redraw the plot window. Unzoom to original size
        """
        self.client.Reset()
        self.client.Redraw()
       
    def OnErase(self, event):
        """!Erase the plot window
        """
        self.client.Clear()
        self.mapwin.ClearLines(self.mapwin.pdc)
        self.mapwin.ClearLines(self.mapwin.pdcTmp)
        self.mapwin.polycoords = []
        self.mapwin.Refresh()

    def SaveToFile(self, event):
        """!Save plot to graphics file
        """
        self.client.SaveFile()

    def OnMouseLeftDown(self,event):
        self.SetStatusText(_("Left Mouse Down at Point:") + \
                               " (%.4f, %.4f)" % self.client._getXY(event))
        event.Skip() # allows plotCanvas OnMouseLeftDown to be called

    def OnMotion(self, event):
        """!Indicate when mouse is outside the plot area
        """
        if self.client.OnLeave(event): print 'out of area'
        #show closest point (when enbled)
        if self.client.GetEnablePointLabel() == True:
            #make up dict with info for the pointLabel
            #I've decided to mark the closest point on the closest curve
            dlst =  self.client.GetClosetPoint( self.client._getXY(event), pointScaled =  True)
            if dlst != []:      #returns [] if none
                curveNum, legend, pIndex, pointXY, scaledXY, distance = dlst
                #make up dictionary to pass to my user function (see DrawPointLabel)
                mDataDict =  {"curveNum":curveNum, "legend":legend, "pIndex":pIndex,\
                    "pointXY":pointXY, "scaledXY":scaledXY}
                #pass dict to update the pointLabel
                self.client.UpdatePointLabel(mDataDict)
        event.Skip()           #go to next handler        
 
 
    def PlotOptionsMenu(self, event):
        """!Popup menu for plot and text options
        """
        point = wx.GetMousePosition()
        popt = wx.Menu()

        # Add items to the menu
        settext = wx.MenuItem(popt, wx.ID_ANY, _('Text settings'))
        popt.AppendItem(settext)
        self.Bind(wx.EVT_MENU, self.PlotText, settext)

        setgrid = wx.MenuItem(popt, wx.ID_ANY, _('Plot settings'))
        popt.AppendItem(setgrid)
        self.Bind(wx.EVT_MENU, self.PlotOptions, setgrid)

        # Popup the menu.  If an item is selected then its handler
        # will be called before PopupMenu returns.
        self.PopupMenu(popt)
        popt.Destroy()

    def NotFunctional(self):
        """!Creates a 'not functional' message dialog
        """
        dlg = wx.MessageDialog(parent = self,
                               message = _('This feature is not yet functional'),
                               caption = _('Under Construction'),
                               style = wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()

    def OnPlotText(self, dlg):
        """!Custom text settings.
        """
        self.ptitle = dlg.ptitle
        self.xlabel = dlg.xlabel
        self.ylabel = dlg.ylabel

        self.client.SetFont(self.properties['font']['wxfont'])
        self.client.SetFontSizeTitle(self.properties['font']['prop']['titleSize'])
        self.client.SetFontSizeAxis(self.properties['font']['prop']['axisSize'])

        if self.plot:
            self.plot.setTitle(dlg.ptitle)
            self.plot.setXLabel(dlg.xlabel)
            self.plot.setYLabel(dlg.ylabel)

        self.OnRedraw(event = None)
    
    def PlotText(self, event):
        """!Set custom text values for profile title and axis labels.
        """
        dlg = TextDialog(parent = self, id = wx.ID_ANY, 
                         plottype = self.plottype, 
                         title = _('Text settings'))
        
        btnval = dlg.ShowModal()
        if btnval == wx.ID_SAVE or btnval == wx.ID_OK or btnval == wx.ID_CANCEL:
            dlg.Destroy()            
        
    def PlotOptions(self, event):
        """!Set various profile options, including: line width, color,
        style; marker size, color, fill, and style; grid and legend
        options.  Calls OptDialog class.
        """
       
        dlg = OptDialog(parent = self, id = wx.ID_ANY, 
                        plottype = self.plottype, 
                        title = _('Plot settings'))

        btnval = dlg.ShowModal()

        if btnval == wx.ID_SAVE or btnval == wx.ID_OK or btnval == wx.ID_CANCEL:
            dlg.Destroy()            

    def PrintMenu(self, event):
        """!Print options and output menu
        """
        point = wx.GetMousePosition()
        printmenu = wx.Menu()
        for title, handler in ((_("Page setup"), self.OnPageSetup),
                               (_("Print preview"), self.OnPrintPreview),
                               (_("Print display"), self.OnDoPrint)):
            item = wx.MenuItem(printmenu, wx.ID_ANY, title)
            printmenu.AppendItem(item)
            self.Bind(wx.EVT_MENU, handler, item)
        
        # Popup the menu.  If an item is selected then its handler
        # will be called before PopupMenu returns.
        self.PopupMenu(printmenu)
        printmenu.Destroy()

    def OnPageSetup(self, event):
        self.client.PageSetup()

    def OnPrintPreview(self, event):
        self.client.PrintPreview()

    def OnDoPrint(self, event):
        self.client.Printout()

    def OnQuit(self, event):
        self.Close(True)

    def OnCloseWindow(self, event):
        """!Close plot window and clean up
        """
        try:
            self.mapwin.ClearLines()
            self.mapwin.mouse['begin'] = self.mapwin.mouse['end'] = (0.0, 0.0)
            self.mapwin.mouse['use'] = 'pointer'
            self.mapwin.mouse['box'] = 'point'
            self.mapwin.polycoords = []
            self.mapwin.UpdateMap(render = False, renderVector = False)
        except:
            pass
        
        self.mapwin.SetCursor(self.Parent.cursors["default"])
        self.Destroy()