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

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

Moved the getMatplotlibColour function from the base layer drawer to the utils module.

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