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

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

Added a module to fix the import Image / from PIL import Image problem.

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