source: qesdi/geoplot/trunk/lib/geoplot/utils.py @ 5683

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/qesdi/geoplot/trunk/lib/geoplot/utils.py@5683
Revision 5683, 4.2 KB checked in by pnorton, 11 years ago (diff)

Fixed a bug with the grid_builder_lat_lon that was causing the midpoints and bounds to be generated the wron way round.

Also added the make_test_data, that creates a dummy data variable with the mask from another extenral vairable. This allowed the code to be tested with a propper mask and other properties of the data changed.

Line 
1"""
2utils.py
3============
4
5Holds functions which dont fit within any of the other geoplot files.
6
7"""
8import time
9import Image
10import StringIO
11import logging
12import numpy
13
14import matplotlib.colors as colors
15#from matplotlib import colors
16import matplotlib.backends.backend_agg
17
18
19# was having problems with alpha belnding so swapped the backend
20#from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
21from matplotlib.backends.backend_cairo import FigureCanvasCairo as FigureCanvas
22
23log = logging.getLogger(__name__) 
24
25def generateDiscreteCmap(rgbList, name):
26    """
27    Generates a discrete colour map form a given list of rgb colours.
28
29    @param rgbList: A list of rgb tuples given in values 0-255, i.e
30        [(1,4,5), (243,0,34), ... (r, g, b)]
31    @type  rgbList: A list of tuples
32    @param    name:The name for the new colour map
33    @type     name:string
34    @return       :returns a a colour map
35    @rtype        :a matplotlib.colors.ListedColormap instance
36    """
37
38    #first need to scale the values so they are between 0 and 1
39    scaledRGBList = _scaleRGBList(rgbList)
40
41    return colors.ListedColormap(scaledRGBList, name, len(scaledRGBList))
42
43def _scaleRGBList(rgbList):
44    """
45    Reduces a list of rgb tuples to values between 0 and 1 from 0 and 255
46
47    @param list: A list of rgb tuples with values between 0 and 255
48    @type  list: A list of tuples
49    @return    : A list of rgb tuples with values between 0 and 1
50    @rtype     : A list of tuplese
51    """
52
53    newList = []
54    for (r,g,b) in rgbList:
55        (r,g,b) = (float(r), float(g), float(b))
56
57        #check the values are less than 255
58        if r > 255.0 or g > 255.0 or b > 255.0:
59            raise Exception("Value in RGB tuple is grater than 255 (%f,%f,%f)" % (r,g,b))
60
61        newList.append(((float(r)/255.0), (float(g)/255.0), (float(b)/255.0)))
62
63    return newList
64
65
66def figureToImage(fig):
67    st = time.time()
68   
69    log.debug("started converting figure to image")
70    canvas = FigureCanvas(fig)
71   
72#    canvas.print_figure('/tmp/tmp.png')
73   
74   
75    # a shortcut with the agg backend
76#    canvas.draw()
77#    size = canvas.get_width_height()
78#    buffer = canvas.buffer_rgba(0,0)
79#    im = Image.fromstring('RGBA', size, buffer, 'raw', 'RGBA', 0, 1)
80   
81#    log.debug("im.palette.mode = %s" % (im.palette.mode,))
82    #im.-convert("RGBA")
83   
84    buffer = StringIO.StringIO()
85    canvas.print_figure(buffer, dpi=fig.get_dpi(), facecolor=fig.get_facecolor(), edgecolor=fig.get_edgecolor())
86    buffer.seek(0)   
87    im = Image.open(buffer)
88   
89#    canvas.print_figure('/tmp/tmp.png', dpi=fig.get_dpi(), facecolor=fig.get_facecolor(), edgecolor=fig.get_edgecolor())
90#    fin = open(file,'rb')
91#    im = Image.open(fin)
92   
93    log.debug("converted figure to image in %s" % (time.time() - st,))
94   
95    return im
96
97def round_to_n(arr, n):
98   
99   
100    c = numpy.log10(arr)
101    log.debug("c = %s" % (c,))
102   
103    if c.__class__ == numpy.ndarray:
104        c[numpy.isinf(c)] = 0.0
105    else:
106        if numpy.isinf(c) :
107            c = 0.0
108    log.debug("c = %s" % (c,))       
109    c = numpy.power(10,numpy.floor(c))
110    log.debug("c = %s" % (c,))
111    res = (arr/c).round(n-1) * c
112    log.debug("res = %s" % (res,))
113   
114    return res
115
116def getAllIndices(shape):
117    totalSize = 1
118    for dim in shape:
119        totalSize *= dim
120
121    #build a list to hold the results
122    res = [0] * len(shape)
123
124    for i in range(totalSize):
125       
126        for dimInd, dim in enumerate(shape):
127           
128            step = i % dim # step along this dimension
129            i = i / dim    # reduce the remaining steps
130            res[dimInd] = step
131       
132        yield tuple(res)
133   
134       
135
136def ispointInLimits(point, xLimits, yLimits):
137    x,y = point
138   
139    if isValueInLimits(x, xLimits) and isValueInLimits(y, yLimits):
140        return True
141    else:
142        return False
143
144def isRangeInLimits(range, limits):
145       
146    if isValueInLimits(range[0], limits):
147        return True
148   
149    if isValueInLimits(range[1], limits):
150        return True
151   
152    if range[0] <= limits[0] and range[1] >= limits[1]:
153        return True
154   
155    return False
156       
157def isValueInLimits(val, limits):   
158    return  val >= limits[0] and val <= limits[1]
Note: See TracBrowser for help on using the repository browser.