/+junk/pygooglechart-py3k

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/%2Bjunk/pygooglechart-py3k
22 by gak
- pygooglechart.py converted to unix line breaks
1
"""
35 by gak
- Initial "grammar" code
2
pygooglechart - A complete Python wrapper for the Google Chart API
22 by gak
- pygooglechart.py converted to unix line breaks
3
4
http://pygooglechart.slowchop.com/
5
34 by gak
- initial unit tests
6
Copyright 2007-2008 Gerald Kaszuba
22 by gak
- pygooglechart.py converted to unix line breaks
7
8
This program is free software: you can redistribute it and/or modify
9
it under the terms of the GNU General Public License as published by
10
the Free Software Foundation, either version 3 of the License, or
11
(at your option) any later version.
12
13
This program is distributed in the hope that it will be useful,
14
but WITHOUT ANY WARRANTY; without even the implied warranty of
15
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
GNU General Public License for more details.
17
18
You should have received a copy of the GNU General Public License
19
along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
21
"""
22
23
import os
24
import urllib
25
import urllib2
26
import math
27
import random
28
import re
36 by gak
- Really added initial unit tests
29
import warnings
30
import copy
22 by gak
- pygooglechart.py converted to unix line breaks
31
32
# Helper variables and functions
33
# -----------------------------------------------------------------------------
34
33 by gak
pep8 fixes, version bump
35
__version__ = '0.2.1'
35 by gak
- Initial "grammar" code
36
__author__ = 'Gerald Kaszuba'
22 by gak
- pygooglechart.py converted to unix line breaks
37
38
reo_colour = re.compile('^([A-Fa-f0-9]{2,2}){3,4}$')
39
40
def _check_colour(colour):
41
    if not reo_colour.match(colour):
42
        raise InvalidParametersException('Colours need to be in ' \
43
            'RRGGBB or RRGGBBAA format. One of your colours has %s' % \
44
            colour)
45
36 by gak
- Really added initial unit tests
46
47
def _reset_warnings():
48
    """Helper function to reset all warnings. Used by the unit tests."""
49
    globals()['__warningregistry__'] = None
50
51
22 by gak
- pygooglechart.py converted to unix line breaks
52
# Exception Classes
53
# -----------------------------------------------------------------------------
54
55
56
class PyGoogleChartException(Exception):
57
    pass
58
59
60
class DataOutOfRangeException(PyGoogleChartException):
61
    pass
62
63
64
class UnknownDataTypeException(PyGoogleChartException):
65
    pass
66
67
68
class NoDataGivenException(PyGoogleChartException):
69
    pass
70
71
72
class InvalidParametersException(PyGoogleChartException):
73
    pass
74
75
76
class BadContentTypeException(PyGoogleChartException):
77
    pass
78
79
35 by gak
- Initial "grammar" code
80
class AbstractClassException(PyGoogleChartException):
81
    pass
82
83
84
class UnknownChartType(PyGoogleChartException):
85
    pass
86
87
22 by gak
- pygooglechart.py converted to unix line breaks
88
# Data Classes
89
# -----------------------------------------------------------------------------
90
91
92
class Data(object):
93
94
    def __init__(self, data):
35 by gak
- Initial "grammar" code
95
        if type(self) == Data:
96
            raise AbstractClassException('This is an abstract class')
22 by gak
- pygooglechart.py converted to unix line breaks
97
        self.data = data
98
25 by gak
Autoscale fixes and refactoring by Grahm Ullrich
99
    @classmethod
100
    def float_scale_value(cls, value, range):
101
        lower, upper = range
34 by gak
- initial unit tests
102
        assert(upper > lower)
36 by gak
- Really added initial unit tests
103
        scaled = (value - lower) * (float(cls.max_value) / (upper - lower))
25 by gak
Autoscale fixes and refactoring by Grahm Ullrich
104
        return scaled
105
106
    @classmethod
107
    def clip_value(cls, value):
36 by gak
- Really added initial unit tests
108
        return max(0, min(value, cls.max_value))
25 by gak
Autoscale fixes and refactoring by Grahm Ullrich
109
110
    @classmethod
111
    def int_scale_value(cls, value, range):
34 by gak
- initial unit tests
112
        return int(round(cls.float_scale_value(value, range)))
25 by gak
Autoscale fixes and refactoring by Grahm Ullrich
113
114
    @classmethod
115
    def scale_value(cls, value, range):
116
        scaled = cls.int_scale_value(value, range)
117
        clipped = cls.clip_value(scaled)
37 by gak
- Added "colours within series" option to chart. (chco=xxx|xxx) (Steve Brandt)
118
        Data.check_clip(scaled, clipped)
119
        return clipped
120
121
    @staticmethod
122
    def check_clip(scaled, clipped):
36 by gak
- Really added initial unit tests
123
        if clipped != scaled:
124
            warnings.warn('One or more of of your data points has been '
125
                'clipped because it is out of range.')
22 by gak
- pygooglechart.py converted to unix line breaks
126
33 by gak
pep8 fixes, version bump
127
22 by gak
- pygooglechart.py converted to unix line breaks
128
class SimpleData(Data):
33 by gak
pep8 fixes, version bump
129
36 by gak
- Really added initial unit tests
130
    max_value = 61
22 by gak
- pygooglechart.py converted to unix line breaks
131
    enc_map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
132
133
    def __repr__(self):
134
        encoded_data = []
135
        for data in self.data:
136
            sub_data = []
137
            for value in data:
138
                if value is None:
139
                    sub_data.append('_')
36 by gak
- Really added initial unit tests
140
                elif value >= 0 and value <= self.max_value:
22 by gak
- pygooglechart.py converted to unix line breaks
141
                    sub_data.append(SimpleData.enc_map[value])
142
                else:
143
                    raise DataOutOfRangeException('cannot encode value: %d'
144
                                                  % value)
145
            encoded_data.append(''.join(sub_data))
146
        return 'chd=s:' + ','.join(encoded_data)
147
33 by gak
pep8 fixes, version bump
148
22 by gak
- pygooglechart.py converted to unix line breaks
149
class TextData(Data):
150
36 by gak
- Really added initial unit tests
151
    max_value = 100
152
22 by gak
- pygooglechart.py converted to unix line breaks
153
    def __repr__(self):
154
        encoded_data = []
155
        for data in self.data:
156
            sub_data = []
157
            for value in data:
158
                if value is None:
159
                    sub_data.append(-1)
36 by gak
- Really added initial unit tests
160
                elif value >= 0 and value <= self.max_value:
22 by gak
- pygooglechart.py converted to unix line breaks
161
                    sub_data.append("%.1f" % float(value))
162
                else:
163
                    raise DataOutOfRangeException()
164
            encoded_data.append(','.join(sub_data))
165
        return 'chd=t:' + '|'.join(encoded_data)
166
167
    @classmethod
168
    def scale_value(cls, value, range):
25 by gak
Autoscale fixes and refactoring by Grahm Ullrich
169
        # use float values instead of integers because we don't need an encode
170
        # map index
33 by gak
pep8 fixes, version bump
171
        scaled = cls.float_scale_value(value, range)
25 by gak
Autoscale fixes and refactoring by Grahm Ullrich
172
        clipped = cls.clip_value(scaled)
37 by gak
- Added "colours within series" option to chart. (chco=xxx|xxx) (Steve Brandt)
173
        Data.check_clip(scaled, clipped)
25 by gak
Autoscale fixes and refactoring by Grahm Ullrich
174
        return clipped
22 by gak
- pygooglechart.py converted to unix line breaks
175
33 by gak
pep8 fixes, version bump
176
22 by gak
- pygooglechart.py converted to unix line breaks
177
class ExtendedData(Data):
34 by gak
- initial unit tests
178
36 by gak
- Really added initial unit tests
179
    max_value = 4095
22 by gak
- pygooglechart.py converted to unix line breaks
180
    enc_map = \
181
        'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.'
182
183
    def __repr__(self):
184
        encoded_data = []
185
        enc_size = len(ExtendedData.enc_map)
186
        for data in self.data:
187
            sub_data = []
188
            for value in data:
189
                if value is None:
190
                    sub_data.append('__')
36 by gak
- Really added initial unit tests
191
                elif value >= 0 and value <= self.max_value:
22 by gak
- pygooglechart.py converted to unix line breaks
192
                    first, second = divmod(int(value), enc_size)
193
                    sub_data.append('%s%s' % (
194
                        ExtendedData.enc_map[first],
195
                        ExtendedData.enc_map[second]))
196
                else:
197
                    raise DataOutOfRangeException( \
198
                        'Item #%i "%s" is out of range' % (data.index(value), \
199
                        value))
200
            encoded_data.append(''.join(sub_data))
201
        return 'chd=e:' + ','.join(encoded_data)
202
203
204
# Axis Classes
205
# -----------------------------------------------------------------------------
206
207
208
class Axis(object):
34 by gak
- initial unit tests
209
22 by gak
- pygooglechart.py converted to unix line breaks
210
    BOTTOM = 'x'
211
    TOP = 't'
212
    LEFT = 'y'
213
    RIGHT = 'r'
214
    TYPES = (BOTTOM, TOP, LEFT, RIGHT)
215
216
    def __init__(self, axis_index, axis_type, **kw):
217
        assert(axis_type in Axis.TYPES)
218
        self.has_style = False
219
        self.axis_index = axis_index
220
        self.axis_type = axis_type
221
        self.positions = None
222
223
    def set_index(self, axis_index):
224
        self.axis_index = axis_index
225
226
    def set_positions(self, positions):
227
        self.positions = positions
228
229
    def set_style(self, colour, font_size=None, alignment=None):
230
        _check_colour(colour)
231
        self.colour = colour
232
        self.font_size = font_size
233
        self.alignment = alignment
234
        self.has_style = True
235
236
    def style_to_url(self):
237
        bits = []
238
        bits.append(str(self.axis_index))
239
        bits.append(self.colour)
240
        if self.font_size is not None:
241
            bits.append(str(self.font_size))
242
            if self.alignment is not None:
243
                bits.append(str(self.alignment))
244
        return ','.join(bits)
245
246
    def positions_to_url(self):
247
        bits = []
248
        bits.append(str(self.axis_index))
249
        bits += [str(a) for a in self.positions]
250
        return ','.join(bits)
251
252
253
class LabelAxis(Axis):
254
255
    def __init__(self, axis_index, axis_type, values, **kwargs):
256
        Axis.__init__(self, axis_index, axis_type, **kwargs)
257
        self.values = [str(a) for a in values]
258
259
    def __repr__(self):
260
        return '%i:|%s' % (self.axis_index, '|'.join(self.values))
261
262
263
class RangeAxis(Axis):
264
265
    def __init__(self, axis_index, axis_type, low, high, **kwargs):
266
        Axis.__init__(self, axis_index, axis_type, **kwargs)
267
        self.low = low
268
        self.high = high
269
270
    def __repr__(self):
271
        return '%i,%s,%s' % (self.axis_index, self.low, self.high)
272
273
# Chart Classes
274
# -----------------------------------------------------------------------------
275
276
277
class Chart(object):
278
    """Abstract class for all chart types.
279
280
    width are height specify the dimensions of the image. title sets the title
281
    of the chart. legend requires a list that corresponds to datasets.
282
    """
283
284
    BASE_URL = 'http://chart.apis.google.com/chart?'
285
    BACKGROUND = 'bg'
286
    CHART = 'c'
30 by gak
Added zero line to bar charts
287
    ALPHA = 'a'
288
    VALID_SOLID_FILL_TYPES = (BACKGROUND, CHART, ALPHA)
22 by gak
- pygooglechart.py converted to unix line breaks
289
    SOLID = 's'
290
    LINEAR_GRADIENT = 'lg'
291
    LINEAR_STRIPES = 'ls'
292
293
    def __init__(self, width, height, title=None, legend=None, colours=None,
37 by gak
- Added "colours within series" option to chart. (chco=xxx|xxx) (Steve Brandt)
294
            auto_scale=True, x_range=None, y_range=None,
295
            colours_within_series=None):
35 by gak
- Initial "grammar" code
296
        if type(self) == Chart:
297
            raise AbstractClassException('This is an abstract class')
22 by gak
- pygooglechart.py converted to unix line breaks
298
        assert(isinstance(width, int))
299
        assert(isinstance(height, int))
300
        self.width = width
301
        self.height = height
302
        self.data = []
303
        self.set_title(title)
304
        self.set_legend(legend)
37 by gak
- Added "colours within series" option to chart. (chco=xxx|xxx) (Steve Brandt)
305
        self.set_legend_position(None)
22 by gak
- pygooglechart.py converted to unix line breaks
306
        self.set_colours(colours)
37 by gak
- Added "colours within series" option to chart. (chco=xxx|xxx) (Steve Brandt)
307
        self.set_colours_within_series(colours_within_series)
22 by gak
- pygooglechart.py converted to unix line breaks
308
309
        # Data for scaling.
36 by gak
- Really added initial unit tests
310
        self.auto_scale = auto_scale  # Whether to automatically scale data
311
        self.x_range = x_range  # (min, max) x-axis range for scaling
312
        self.y_range = y_range  # (min, max) y-axis range for scaling
22 by gak
- pygooglechart.py converted to unix line breaks
313
        self.scaled_data_class = None
314
        self.scaled_x_range = None
315
        self.scaled_y_range = None
316
317
        self.fill_types = {
318
            Chart.BACKGROUND: None,
319
            Chart.CHART: None,
30 by gak
Added zero line to bar charts
320
            Chart.ALPHA: None,
22 by gak
- pygooglechart.py converted to unix line breaks
321
        }
322
        self.fill_area = {
323
            Chart.BACKGROUND: None,
324
            Chart.CHART: None,
30 by gak
Added zero line to bar charts
325
            Chart.ALPHA: None,
22 by gak
- pygooglechart.py converted to unix line breaks
326
        }
327
        self.axis = []
328
        self.markers = []
37 by gak
- Added "colours within series" option to chart. (chco=xxx|xxx) (Steve Brandt)
329
        self.trendline_data = []
330
        self.trendline_style = None
27 by gak
grids and line styles are not only restricted to line chart types
331
        self.line_styles = {}
332
        self.grid = None
22 by gak
- pygooglechart.py converted to unix line breaks
333
334
    # URL generation
335
    # -------------------------------------------------------------------------
336
25 by gak
Autoscale fixes and refactoring by Grahm Ullrich
337
    def get_url(self, data_class=None):
338
        url_bits = self.get_url_bits(data_class=data_class)
22 by gak
- pygooglechart.py converted to unix line breaks
339
        return self.BASE_URL + '&'.join(url_bits)
340
25 by gak
Autoscale fixes and refactoring by Grahm Ullrich
341
    def get_url_bits(self, data_class=None):
22 by gak
- pygooglechart.py converted to unix line breaks
342
        url_bits = []
343
        # required arguments
344
        url_bits.append(self.type_to_url())
345
        url_bits.append('chs=%ix%i' % (self.width, self.height))
25 by gak
Autoscale fixes and refactoring by Grahm Ullrich
346
        url_bits.append(self.data_to_url(data_class=data_class))
22 by gak
- pygooglechart.py converted to unix line breaks
347
        # optional arguments
348
        if self.title:
349
            url_bits.append('chtt=%s' % self.title)
350
        if self.legend:
351
            url_bits.append('chdl=%s' % '|'.join(self.legend))
37 by gak
- Added "colours within series" option to chart. (chco=xxx|xxx) (Steve Brandt)
352
        if self.legend_position:
353
            url_bits.append('chdlp=%s' % (self.legend_position))
22 by gak
- pygooglechart.py converted to unix line breaks
354
        if self.colours:
37 by gak
- Added "colours within series" option to chart. (chco=xxx|xxx) (Steve Brandt)
355
            url_bits.append('chco=%s' % ','.join(self.colours))            
356
        if self.colours_within_series:
357
            url_bits.append('chco=%s' % '|'.join(self.colours_within_series))
22 by gak
- pygooglechart.py converted to unix line breaks
358
        ret = self.fill_to_url()
359
        if ret:
360
            url_bits.append(ret)
361
        ret = self.axis_to_url()
362
        if ret:
37 by gak
- Added "colours within series" option to chart. (chco=xxx|xxx) (Steve Brandt)
363
            url_bits.append(ret)                    
364
        if self.trendline_data: 
365
            if not self.trendline_style: self.set_trendline_style()
366
            url_bits.append('ewtr=0,%s,%.1f' % (self.trendline_colour, self.trendline_thickness))
367
            url_bits.append(self.trendline_data_to_url(data_class=data_class))            
22 by gak
- pygooglechart.py converted to unix line breaks
368
        if self.markers:
37 by gak
- Added "colours within series" option to chart. (chco=xxx|xxx) (Steve Brandt)
369
            url_bits.append(self.markers_to_url())        
27 by gak
grids and line styles are not only restricted to line chart types
370
        if self.line_styles:
371
            style = []
372
            for index in xrange(max(self.line_styles) + 1):
373
                if index in self.line_styles:
374
                    values = self.line_styles[index]
375
                else:
376
                    values = ('1', )
377
                style.append(','.join(values))
378
            url_bits.append('chls=%s' % '|'.join(style))
379
        if self.grid:
380
            url_bits.append('chg=%s' % self.grid)
22 by gak
- pygooglechart.py converted to unix line breaks
381
        return url_bits
382
383
    # Downloading
384
    # -------------------------------------------------------------------------
385
386
    def download(self, file_name):
387
        opener = urllib2.urlopen(self.get_url())
388
389
        if opener.headers['content-type'] != 'image/png':
390
            raise BadContentTypeException('Server responded with a ' \
391
                'content-type of %s' % opener.headers['content-type'])
392
393
        open(file_name, 'wb').write(urllib.urlopen(self.get_url()).read())
394
395
    # Simple settings
396
    # -------------------------------------------------------------------------
397
398
    def set_title(self, title):
399
        if title:
400
            self.title = urllib.quote(title)
401
        else:
402
            self.title = None
403
404
    def set_legend(self, legend):
405
        """legend needs to be a list, tuple or None"""
406
        assert(isinstance(legend, list) or isinstance(legend, tuple) or
407
            legend is None)
408
        if legend:
409
            self.legend = [urllib.quote(a) for a in legend]
410
        else:
411
            self.legend = None
412
37 by gak
- Added "colours within series" option to chart. (chco=xxx|xxx) (Steve Brandt)
413
    def set_legend_position(self, legend_position):
414
        if legend_position:
415
            self.legend_position = urllib.quote(legend_position)
416
        else:    
417
            self.legend_position = None
418
22 by gak
- pygooglechart.py converted to unix line breaks
419
    # Chart colours
420
    # -------------------------------------------------------------------------
421
422
    def set_colours(self, colours):
423
        # colours needs to be a list, tuple or None
424
        assert(isinstance(colours, list) or isinstance(colours, tuple) or
425
            colours is None)
426
        # make sure the colours are in the right format
427
        if colours:
428
            for col in colours:
429
                _check_colour(col)
430
        self.colours = colours
431
37 by gak
- Added "colours within series" option to chart. (chco=xxx|xxx) (Steve Brandt)
432
    def set_colours_within_series(self, colours):
433
        # colours needs to be a list, tuple or None
434
        assert(isinstance(colours, list) or isinstance(colours, tuple) or
435
            colours is None)
436
        # make sure the colours are in the right format
437
        if colours:
438
            for col in colours:
439
                _check_colour(col)
440
        self.colours_within_series = colours        
441
22 by gak
- pygooglechart.py converted to unix line breaks
442
    # Background/Chart colours
443
    # -------------------------------------------------------------------------
444
445
    def fill_solid(self, area, colour):
30 by gak
Added zero line to bar charts
446
        assert(area in Chart.VALID_SOLID_FILL_TYPES)
22 by gak
- pygooglechart.py converted to unix line breaks
447
        _check_colour(colour)
448
        self.fill_area[area] = colour
449
        self.fill_types[area] = Chart.SOLID
450
451
    def _check_fill_linear(self, angle, *args):
452
        assert(isinstance(args, list) or isinstance(args, tuple))
453
        assert(angle >= 0 and angle <= 90)
454
        assert(len(args) % 2 == 0)
455
        args = list(args)  # args is probably a tuple and we need to mutate
456
        for a in xrange(len(args) / 2):
457
            col = args[a * 2]
458
            offset = args[a * 2 + 1]
459
            _check_colour(col)
460
            assert(offset >= 0 and offset <= 1)
461
            args[a * 2 + 1] = str(args[a * 2 + 1])
462
        return args
463
464
    def fill_linear_gradient(self, area, angle, *args):
30 by gak
Added zero line to bar charts
465
        assert(area in Chart.VALID_SOLID_FILL_TYPES)
22 by gak
- pygooglechart.py converted to unix line breaks
466
        args = self._check_fill_linear(angle, *args)
467
        self.fill_types[area] = Chart.LINEAR_GRADIENT
468
        self.fill_area[area] = ','.join([str(angle)] + args)
469
470
    def fill_linear_stripes(self, area, angle, *args):
30 by gak
Added zero line to bar charts
471
        assert(area in Chart.VALID_SOLID_FILL_TYPES)
22 by gak
- pygooglechart.py converted to unix line breaks
472
        args = self._check_fill_linear(angle, *args)
473
        self.fill_types[area] = Chart.LINEAR_STRIPES
474
        self.fill_area[area] = ','.join([str(angle)] + args)
475
476
    def fill_to_url(self):
477
        areas = []
30 by gak
Added zero line to bar charts
478
        for area in (Chart.BACKGROUND, Chart.CHART, Chart.ALPHA):
22 by gak
- pygooglechart.py converted to unix line breaks
479
            if self.fill_types[area]:
480
                areas.append('%s,%s,%s' % (area, self.fill_types[area], \
481
                    self.fill_area[area]))
482
        if areas:
483
            return 'chf=' + '|'.join(areas)
484
485
    # Data
486
    # -------------------------------------------------------------------------
487
488
    def data_class_detection(self, data):
489
        """Determines the appropriate data encoding type to give satisfactory
490
        resolution (http://code.google.com/apis/chart/#chart_data).
491
        """
492
        assert(isinstance(data, list) or isinstance(data, tuple))
493
        if not isinstance(self, (LineChart, BarChart, ScatterChart)):
494
            # From the link above:
495
            #   Simple encoding is suitable for all other types of chart
496
            #   regardless of size.
497
            return SimpleData
498
        elif self.height < 100:
499
            # The link above indicates that line and bar charts less
500
            # than 300px in size can be suitably represented with the
501
            # simple encoding. I've found that this isn't sufficient,
502
            # e.g. examples/line-xy-circle.png. Let's try 100px.
503
            return SimpleData
504
        else:
505
            return ExtendedData
506
507
    def data_x_range(self):
508
        """Return a 2-tuple giving the minimum and maximum x-axis
509
        data range.
510
        """
511
        try:
512
            lower = min([min(s) for type, s in self.annotated_data()
513
                         if type == 'x'])
514
            upper = max([max(s) for type, s in self.annotated_data()
515
                         if type == 'x'])
516
            return (lower, upper)
517
        except ValueError:
518
            return None     # no x-axis datasets
519
520
    def data_y_range(self):
521
        """Return a 2-tuple giving the minimum and maximum y-axis
522
        data range.
523
        """
524
        try:
525
            lower = min([min(s) for type, s in self.annotated_data()
526
                         if type == 'y'])
34 by gak
- initial unit tests
527
            upper = max([max(s) + 1 for type, s in self.annotated_data()
22 by gak
- pygooglechart.py converted to unix line breaks
528
                         if type == 'y'])
529
            return (lower, upper)
530
        except ValueError:
531
            return None     # no y-axis datasets
532
533
    def scaled_data(self, data_class, x_range=None, y_range=None):
534
        """Scale `self.data` as appropriate for the given data encoding
535
        (data_class) and return it.
536
537
        An optional `y_range` -- a 2-tuple (lower, upper) -- can be
538
        given to specify the y-axis bounds. If not given, the range is
539
        inferred from the data: (0, <max-value>) presuming no negative
540
        values, or (<min-value>, <max-value>) if there are negative
541
        values.  `self.scaled_y_range` is set to the actual lower and
542
        upper scaling range.
543
544
        Ditto for `x_range`. Note that some chart types don't have x-axis
545
        data.
546
        """
547
        self.scaled_data_class = data_class
548
549
        # Determine the x-axis range for scaling.
550
        if x_range is None:
551
            x_range = self.data_x_range()
552
            if x_range and x_range[0] > 0:
553
                x_range = (0, x_range[1])
554
        self.scaled_x_range = x_range
555
556
        # Determine the y-axis range for scaling.
557
        if y_range is None:
558
            y_range = self.data_y_range()
559
            if y_range and y_range[0] > 0:
560
                y_range = (0, y_range[1])
561
        self.scaled_y_range = y_range
562
563
        scaled_data = []
564
        for type, dataset in self.annotated_data():
565
            if type == 'x':
566
                scale_range = x_range
567
            elif type == 'y':
568
                scale_range = y_range
569
            elif type == 'marker-size':
570
                scale_range = (0, max(dataset))
571
            scaled_data.append([data_class.scale_value(v, scale_range)
572
                                for v in dataset])
573
        return scaled_data
574
575
    def add_data(self, data):
576
        self.data.append(data)
577
        return len(self.data) - 1  # return the "index" of the data set
578
579
    def data_to_url(self, data_class=None):
580
        if not data_class:
581
            data_class = self.data_class_detection(self.data)
582
        if not issubclass(data_class, Data):
583
            raise UnknownDataTypeException()
584
        if self.auto_scale:
585
            data = self.scaled_data(data_class, self.x_range, self.y_range)
586
        else:
587
            data = self.data
588
        return repr(data_class(data))
589
29 by gak
Added Google-o-meter chart
590
    def annotated_data(self):
591
        for dataset in self.data:
592
            yield ('x', dataset)
593
22 by gak
- pygooglechart.py converted to unix line breaks
594
    # Axis Labels
595
    # -------------------------------------------------------------------------
596
597
    def set_axis_labels(self, axis_type, values):
598
        assert(axis_type in Axis.TYPES)
33 by gak
pep8 fixes, version bump
599
        values = [urllib.quote(a) for a in values]
22 by gak
- pygooglechart.py converted to unix line breaks
600
        axis_index = len(self.axis)
601
        axis = LabelAxis(axis_index, axis_type, values)
602
        self.axis.append(axis)
603
        return axis_index
604
605
    def set_axis_range(self, axis_type, low, high):
606
        assert(axis_type in Axis.TYPES)
607
        axis_index = len(self.axis)
608
        axis = RangeAxis(axis_index, axis_type, low, high)
609
        self.axis.append(axis)
610
        return axis_index
611
612
    def set_axis_positions(self, axis_index, positions):
613
        try:
614
            self.axis[axis_index].set_positions(positions)
615
        except IndexError:
616
            raise InvalidParametersException('Axis index %i has not been ' \
617
                'created' % axis)
618
619
    def set_axis_style(self, axis_index, colour, font_size=None, \
620
            alignment=None):
621
        try:
622
            self.axis[axis_index].set_style(colour, font_size, alignment)
623
        except IndexError:
624
            raise InvalidParametersException('Axis index %i has not been ' \
625
                'created' % axis)
626
627
    def axis_to_url(self):
628
        available_axis = []
629
        label_axis = []
630
        range_axis = []
631
        positions = []
632
        styles = []
633
        index = -1
634
        for axis in self.axis:
635
            available_axis.append(axis.axis_type)
636
            if isinstance(axis, RangeAxis):
637
                range_axis.append(repr(axis))
638
            if isinstance(axis, LabelAxis):
639
                label_axis.append(repr(axis))
640
            if axis.positions:
641
                positions.append(axis.positions_to_url())
642
            if axis.has_style:
643
                styles.append(axis.style_to_url())
644
        if not available_axis:
645
            return
646
        url_bits = []
647
        url_bits.append('chxt=%s' % ','.join(available_axis))
648
        if label_axis:
649
            url_bits.append('chxl=%s' % '|'.join(label_axis))
650
        if range_axis:
651
            url_bits.append('chxr=%s' % '|'.join(range_axis))
652
        if positions:
653
            url_bits.append('chxp=%s' % '|'.join(positions))
654
        if styles:
655
            url_bits.append('chxs=%s' % '|'.join(styles))
656
        return '&'.join(url_bits)
657
658
    # Markers, Ranges and Fill area (chm)
659
    # -------------------------------------------------------------------------
660
37 by gak
- Added "colours within series" option to chart. (chco=xxx|xxx) (Steve Brandt)
661
    def markers_to_url(self):        
22 by gak
- pygooglechart.py converted to unix line breaks
662
        return 'chm=%s' % '|'.join([','.join(a) for a in self.markers])
663
31 by gak
Added priority to shape markers
664
    def add_marker(self, index, point, marker_type, colour, size, priority=0):
22 by gak
- pygooglechart.py converted to unix line breaks
665
        self.markers.append((marker_type, colour, str(index), str(point), \
31 by gak
Added priority to shape markers
666
            str(size), str(priority)))
22 by gak
- pygooglechart.py converted to unix line breaks
667
668
    def add_horizontal_range(self, colour, start, stop):
37 by gak
- Added "colours within series" option to chart. (chco=xxx|xxx) (Steve Brandt)
669
        self.markers.append(('r', colour, '0', str(start), str(stop)))
670
671
    def add_data_line(self, colour, data_set, size, priority=0):
672
        self.markers.append(('D', colour, str(data_set), '0', str(size), str(priority)))
673
674
    def add_marker_text(self, string, colour, data_set, data_point, size, priority=0):
675
        self.markers.append((str(string), colour, str(data_set), str(data_point), str(size), str(priority)))        
22 by gak
- pygooglechart.py converted to unix line breaks
676
677
    def add_vertical_range(self, colour, start, stop):
37 by gak
- Added "colours within series" option to chart. (chco=xxx|xxx) (Steve Brandt)
678
        self.markers.append(('R', colour, '0', str(start), str(stop)))
22 by gak
- pygooglechart.py converted to unix line breaks
679
680
    def add_fill_range(self, colour, index_start, index_end):
681
        self.markers.append(('b', colour, str(index_start), str(index_end), \
682
            '1'))
683
684
    def add_fill_simple(self, colour):
685
        self.markers.append(('B', colour, '1', '1', '1'))
686
27 by gak
grids and line styles are not only restricted to line chart types
687
    # Line styles
688
    # -------------------------------------------------------------------------
22 by gak
- pygooglechart.py converted to unix line breaks
689
690
    def set_line_style(self, index, thickness=1, line_segment=None, \
691
            blank_segment=None):
692
        value = []
693
        value.append(str(thickness))
694
        if line_segment:
695
            value.append(str(line_segment))
696
            value.append(str(blank_segment))
697
        self.line_styles[index] = value
698
27 by gak
grids and line styles are not only restricted to line chart types
699
    # Grid
700
    # -------------------------------------------------------------------------
701
22 by gak
- pygooglechart.py converted to unix line breaks
702
    def set_grid(self, x_step, y_step, line_segment=1, \
703
            blank_segment=0):
704
        self.grid = '%s,%s,%s,%s' % (x_step, y_step, line_segment, \
705
            blank_segment)
706
27 by gak
grids and line styles are not only restricted to line chart types
707
708
class ScatterChart(Chart):
709
710
    def type_to_url(self):
711
        return 'cht=s'
712
713
    def annotated_data(self):
714
        yield ('x', self.data[0])
715
        yield ('y', self.data[1])
716
        if len(self.data) > 2:
717
            # The optional third dataset is relative sizing for point
718
            # markers.
719
            yield ('marker-size', self.data[2])
720
33 by gak
pep8 fixes, version bump
721
27 by gak
grids and line styles are not only restricted to line chart types
722
class LineChart(Chart):
723
724
    def __init__(self, *args, **kwargs):
35 by gak
- Initial "grammar" code
725
        if type(self) == LineChart:
726
            raise AbstractClassException('This is an abstract class')
27 by gak
grids and line styles are not only restricted to line chart types
727
        Chart.__init__(self, *args, **kwargs)
728
22 by gak
- pygooglechart.py converted to unix line breaks
729
730
class SimpleLineChart(LineChart):
731
732
    def type_to_url(self):
733
        return 'cht=lc'
734
735
    def annotated_data(self):
736
        # All datasets are y-axis data.
737
        for dataset in self.data:
738
            yield ('y', dataset)
739
33 by gak
pep8 fixes, version bump
740
22 by gak
- pygooglechart.py converted to unix line breaks
741
class SparkLineChart(SimpleLineChart):
742
743
    def type_to_url(self):
744
        return 'cht=ls'
745
33 by gak
pep8 fixes, version bump
746
22 by gak
- pygooglechart.py converted to unix line breaks
747
class XYLineChart(LineChart):
748
749
    def type_to_url(self):
750
        return 'cht=lxy'
751
752
    def annotated_data(self):
753
        # Datasets alternate between x-axis, y-axis.
754
        for i, dataset in enumerate(self.data):
755
            if i % 2 == 0:
756
                yield ('x', dataset)
757
            else:
758
                yield ('y', dataset)
759
33 by gak
pep8 fixes, version bump
760
22 by gak
- pygooglechart.py converted to unix line breaks
761
class BarChart(Chart):
762
763
    def __init__(self, *args, **kwargs):
35 by gak
- Initial "grammar" code
764
        if type(self) == BarChart:
765
            raise AbstractClassException('This is an abstract class')
22 by gak
- pygooglechart.py converted to unix line breaks
766
        Chart.__init__(self, *args, **kwargs)
767
        self.bar_width = None
30 by gak
Added zero line to bar charts
768
        self.zero_lines = {}
22 by gak
- pygooglechart.py converted to unix line breaks
769
770
    def set_bar_width(self, bar_width):
771
        self.bar_width = bar_width
772
30 by gak
Added zero line to bar charts
773
    def set_zero_line(self, index, zero_line):
774
        self.zero_lines[index] = zero_line
775
776
    def get_url_bits(self, data_class=None, skip_chbh=False):
25 by gak
Autoscale fixes and refactoring by Grahm Ullrich
777
        url_bits = Chart.get_url_bits(self, data_class=data_class)
30 by gak
Added zero line to bar charts
778
        if not skip_chbh and self.bar_width is not None:
22 by gak
- pygooglechart.py converted to unix line breaks
779
            url_bits.append('chbh=%i' % self.bar_width)
30 by gak
Added zero line to bar charts
780
        zero_line = []
781
        if self.zero_lines:
782
            for index in xrange(max(self.zero_lines) + 1):
783
                if index in self.zero_lines:
784
                    zero_line.append(str(self.zero_lines[index]))
785
                else:
786
                    zero_line.append('0')
787
            url_bits.append('chp=%s' % ','.join(zero_line))
22 by gak
- pygooglechart.py converted to unix line breaks
788
        return url_bits
789
790
791
class StackedHorizontalBarChart(BarChart):
792
793
    def type_to_url(self):
794
        return 'cht=bhs'
795
796
797
class StackedVerticalBarChart(BarChart):
798
799
    def type_to_url(self):
800
        return 'cht=bvs'
801
802
    def annotated_data(self):
803
        for dataset in self.data:
804
            yield ('y', dataset)
805
806
807
class GroupedBarChart(BarChart):
808
809
    def __init__(self, *args, **kwargs):
35 by gak
- Initial "grammar" code
810
        if type(self) == GroupedBarChart:
811
            raise AbstractClassException('This is an abstract class')
22 by gak
- pygooglechart.py converted to unix line breaks
812
        BarChart.__init__(self, *args, **kwargs)
813
        self.bar_spacing = None
814
        self.group_spacing = None
815
816
    def set_bar_spacing(self, spacing):
817
        """Set spacing between bars in a group."""
818
        self.bar_spacing = spacing
819
820
    def set_group_spacing(self, spacing):
821
        """Set spacing between groups of bars."""
822
        self.group_spacing = spacing
823
25 by gak
Autoscale fixes and refactoring by Grahm Ullrich
824
    def get_url_bits(self, data_class=None):
22 by gak
- pygooglechart.py converted to unix line breaks
825
        # Skip 'BarChart.get_url_bits' and call Chart directly so the parent
826
        # doesn't add "chbh" before we do.
30 by gak
Added zero line to bar charts
827
        url_bits = BarChart.get_url_bits(self, data_class=data_class,
828
            skip_chbh=True)
22 by gak
- pygooglechart.py converted to unix line breaks
829
        if self.group_spacing is not None:
830
            if self.bar_spacing is None:
33 by gak
pep8 fixes, version bump
831
                raise InvalidParametersException('Bar spacing is required ' \
832
                    'to be set when setting group spacing')
22 by gak
- pygooglechart.py converted to unix line breaks
833
            if self.bar_width is None:
834
                raise InvalidParametersException('Bar width is required to ' \
835
                    'be set when setting bar spacing')
836
            url_bits.append('chbh=%i,%i,%i'
837
                % (self.bar_width, self.bar_spacing, self.group_spacing))
838
        elif self.bar_spacing is not None:
839
            if self.bar_width is None:
840
                raise InvalidParametersException('Bar width is required to ' \
841
                    'be set when setting bar spacing')
842
            url_bits.append('chbh=%i,%i' % (self.bar_width, self.bar_spacing))
27 by gak
grids and line styles are not only restricted to line chart types
843
        elif self.bar_width:
22 by gak
- pygooglechart.py converted to unix line breaks
844
            url_bits.append('chbh=%i' % self.bar_width)
845
        return url_bits
846
847
848
class GroupedHorizontalBarChart(GroupedBarChart):
849
850
    def type_to_url(self):
851
        return 'cht=bhg'
852
853
854
class GroupedVerticalBarChart(GroupedBarChart):
855
856
    def type_to_url(self):
857
        return 'cht=bvg'
858
859
    def annotated_data(self):
860
        for dataset in self.data:
861
            yield ('y', dataset)
862
863
864
class PieChart(Chart):
865
866
    def __init__(self, *args, **kwargs):
35 by gak
- Initial "grammar" code
867
        if type(self) == PieChart:
868
            raise AbstractClassException('This is an abstract class')
22 by gak
- pygooglechart.py converted to unix line breaks
869
        Chart.__init__(self, *args, **kwargs)
870
        self.pie_labels = []
36 by gak
- Really added initial unit tests
871
        if self.y_range:
872
            warnings.warn('y_range is not used with %s.' % \
873
                (self.__class__.__name__))
22 by gak
- pygooglechart.py converted to unix line breaks
874
875
    def set_pie_labels(self, labels):
876
        self.pie_labels = [urllib.quote(a) for a in labels]
877
25 by gak
Autoscale fixes and refactoring by Grahm Ullrich
878
    def get_url_bits(self, data_class=None):
879
        url_bits = Chart.get_url_bits(self, data_class=data_class)
22 by gak
- pygooglechart.py converted to unix line breaks
880
        if self.pie_labels:
881
            url_bits.append('chl=%s' % '|'.join(self.pie_labels))
882
        return url_bits
883
884
    def annotated_data(self):
885
        # Datasets are all y-axis data. However, there should only be
886
        # one dataset for pie charts.
887
        for dataset in self.data:
36 by gak
- Really added initial unit tests
888
            yield ('x', dataset)
22 by gak
- pygooglechart.py converted to unix line breaks
889
890
891
class PieChart2D(PieChart):
892
893
    def type_to_url(self):
894
        return 'cht=p'
895
896
897
class PieChart3D(PieChart):
898
899
    def type_to_url(self):
900
        return 'cht=p3'
901
902
903
class VennChart(Chart):
904
905
    def type_to_url(self):
906
        return 'cht=v'
907
908
    def annotated_data(self):
909
        for dataset in self.data:
910
            yield ('y', dataset)
911
912
26 by gak
Initial radar chart implementation
913
class RadarChart(Chart):
914
915
    def type_to_url(self):
916
        return 'cht=r'
917
33 by gak
pep8 fixes, version bump
918
28 by gak
Added map chart type
919
class SplineRadarChart(RadarChart):
920
921
    def type_to_url(self):
922
        return 'cht=rs'
923
924
925
class MapChart(Chart):
926
927
    def __init__(self, *args, **kwargs):
928
        Chart.__init__(self, *args, **kwargs)
929
        self.geo_area = 'world'
930
        self.codes = []
931
932
    def type_to_url(self):
933
        return 'cht=t'
934
935
    def set_codes(self, codes):
936
        self.codes = codes
937
938
    def get_url_bits(self, data_class=None):
939
        url_bits = Chart.get_url_bits(self, data_class=data_class)
940
        url_bits.append('chtm=%s' % self.geo_area)
941
        if self.codes:
942
            url_bits.append('chld=%s' % ''.join(self.codes))
943
        return url_bits
944
29 by gak
Added Google-o-meter chart
945
946
class GoogleOMeterChart(PieChart):
947
    """Inheriting from PieChart because of similar labeling"""
948
36 by gak
- Really added initial unit tests
949
    def __init__(self, *args, **kwargs):
950
        PieChart.__init__(self, *args, **kwargs)
951
        if self.auto_scale and not self.x_range:
952
            warnings.warn('Please specify an x_range with GoogleOMeterChart, '
953
                'otherwise one arrow will always be at the max.')
954
29 by gak
Added Google-o-meter chart
955
    def type_to_url(self):
956
        return 'cht=gom'
957
26 by gak
Initial radar chart implementation
958
35 by gak
- Initial "grammar" code
959
class ChartGrammar(object):
960
36 by gak
- Really added initial unit tests
961
    def __init__(self):
962
        self.grammar = None
963
        self.chart = None
964
965
    def parse(self, grammar):
35 by gak
- Initial "grammar" code
966
        self.grammar = grammar
967
        self.chart = self.create_chart_instance()
968
36 by gak
- Really added initial unit tests
969
        for attr in self.grammar:
970
            if attr in ('w', 'h', 'type', 'auto_scale', 'x_range', 'y_range'):
971
                continue  # These are already parsed in create_chart_instance
972
            attr_func = 'parse_' + attr
973
            if not hasattr(self, attr_func):
974
                warnings.warn('No parser for grammar attribute "%s"' % (attr))
975
                continue
976
            getattr(self, attr_func)(grammar[attr])
977
978
        return self.chart
979
980
    def parse_data(self, data):
981
        self.chart.data = data
982
35 by gak
- Initial "grammar" code
983
    @staticmethod
984
    def get_possible_chart_types():
985
        possible_charts = []
36 by gak
- Really added initial unit tests
986
        for cls_name in globals().keys():
35 by gak
- Initial "grammar" code
987
            if not cls_name.endswith('Chart'):
988
                continue
989
            cls = globals()[cls_name]
990
            # Check if it is an abstract class
991
            try:
36 by gak
- Really added initial unit tests
992
                a = cls(1, 1, auto_scale=False)
993
                del a
35 by gak
- Initial "grammar" code
994
            except AbstractClassException:
995
                continue
996
            # Strip off "Class"
997
            possible_charts.append(cls_name[:-5])
998
        return possible_charts
999
36 by gak
- Really added initial unit tests
1000
    def create_chart_instance(self, grammar=None):
1001
        if not grammar:
1002
            grammar = self.grammar
1003
        assert(isinstance(grammar, dict))  # grammar must be a dict
35 by gak
- Initial "grammar" code
1004
        assert('w' in grammar)  # width is required
1005
        assert('h' in grammar)  # height is required
1006
        assert('type' in grammar)  # type is required
36 by gak
- Really added initial unit tests
1007
        chart_type = grammar['type']
1008
        w = grammar['w']
1009
        h = grammar['h']
1010
        auto_scale = grammar.get('auto_scale', None)
1011
        x_range = grammar.get('x_range', None)
1012
        y_range = grammar.get('y_range', None)
35 by gak
- Initial "grammar" code
1013
        types = ChartGrammar.get_possible_chart_types()
36 by gak
- Really added initial unit tests
1014
        if chart_type not in types:
35 by gak
- Initial "grammar" code
1015
            raise UnknownChartType('%s is an unknown chart type. Possible '
36 by gak
- Really added initial unit tests
1016
                'chart types are %s' % (chart_type, ','.join(types)))
1017
        return globals()[chart_type + 'Chart'](w, h, auto_scale=auto_scale,
1018
            x_range=x_range, y_range=y_range)
35 by gak
- Initial "grammar" code
1019
1020
    def download(self):
1021
        pass
1022