/
glyph.py
1687 lines (1427 loc) · 61.9 KB
/
glyph.py
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Copyright 2008 Orbitz WorldWide
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License."""
import os, cairo, math, itertools, re
import StringIO
from datetime import datetime, timedelta
from urllib import unquote_plus
from ConfigParser import SafeConfigParser
from django.conf import settings
from graphite.render.datalib import TimeSeries
from graphite.util import json
import pytz
INFINITY = float('inf')
colorAliases = {
'black' : (0,0,0),
'white' : (255,255,255),
'blue' : (100,100,255),
'green' : (0,200,0),
'red' : (200,00,50),
'yellow' : (255,255,0),
'orange' : (255, 165, 0),
'purple' : (200,100,255),
'brown' : (150,100,50),
'cyan' : (0,255,255),
'aqua' : (0,150,150),
'gray' : (175,175,175),
'grey' : (175,175,175),
'magenta' : (255,0,255),
'pink' : (255,100,100),
'gold' : (200,200,0),
'rose' : (200,150,200),
'darkblue' : (0,0,255),
'darkgreen' : (0,255,0),
'darkred' : (255,0,0),
'darkgray' : (111,111,111),
'darkgrey' : (111,111,111),
}
# This gets overriden by graphTemplates.conf
defaultGraphOptions = dict(
background='black',
foreground='white',
majorline='white',
minorline='grey',
linecolors='blue,green,red,purple,brown,yellow,aqua,grey,magenta,pink,gold,rose',
fontname='Sans',
fontsize=10,
fontbold='false',
fontitalic='false',
)
#X-axis configurations (copied from rrdtool, this technique is evil & ugly but effective)
SEC = 1
MIN = 60
HOUR = MIN * 60
DAY = HOUR * 24
WEEK = DAY * 7
MONTH = DAY * 31
YEAR = DAY * 365
# Set a flag to indicate whether the '%l' option can be used safely.
# On Windows, in particular the %l option in strftime is not supported.
#(It is not one of the documented Python formatters).
try:
datetime.now().strftime("%a %l%p")
percent_l_supported = True
except ValueError, e:
percent_l_supported = False
xAxisConfigs = (
dict(seconds=0.00, minorGridUnit=SEC, minorGridStep=5, majorGridUnit=MIN, majorGridStep=1, labelUnit=SEC, labelStep=5, format="%H:%M:%S", maxInterval=10*MIN),
dict(seconds=0.07, minorGridUnit=SEC, minorGridStep=10, majorGridUnit=MIN, majorGridStep=1, labelUnit=SEC, labelStep=10, format="%H:%M:%S", maxInterval=20*MIN),
dict(seconds=0.14, minorGridUnit=SEC, minorGridStep=15, majorGridUnit=MIN, majorGridStep=1, labelUnit=SEC, labelStep=15, format="%H:%M:%S", maxInterval=30*MIN),
dict(seconds=0.27, minorGridUnit=SEC, minorGridStep=30, majorGridUnit=MIN, majorGridStep=2, labelUnit=MIN, labelStep=1, format="%H:%M", maxInterval=2*HOUR),
dict(seconds=0.5, minorGridUnit=MIN, minorGridStep=1, majorGridUnit=MIN, majorGridStep=2, labelUnit=MIN, labelStep=1, format="%H:%M", maxInterval=2*HOUR),
dict(seconds=1.2, minorGridUnit=MIN, minorGridStep=1, majorGridUnit=MIN, majorGridStep=4, labelUnit=MIN, labelStep=2, format="%H:%M", maxInterval=3*HOUR),
dict(seconds=2, minorGridUnit=MIN, minorGridStep=1, majorGridUnit=MIN, majorGridStep=10, labelUnit=MIN, labelStep=5, format="%H:%M", maxInterval=6*HOUR),
dict(seconds=5, minorGridUnit=MIN, minorGridStep=2, majorGridUnit=MIN, majorGridStep=10, labelUnit=MIN, labelStep=10, format="%H:%M", maxInterval=12*HOUR),
dict(seconds=10, minorGridUnit=MIN, minorGridStep=5, majorGridUnit=MIN, majorGridStep=20, labelUnit=MIN, labelStep=20, format="%H:%M", maxInterval=1*DAY),
dict(seconds=30, minorGridUnit=MIN, minorGridStep=10, majorGridUnit=HOUR, majorGridStep=1, labelUnit=HOUR, labelStep=1, format="%H:%M", maxInterval=2*DAY),
dict(seconds=60, minorGridUnit=MIN, minorGridStep=30, majorGridUnit=HOUR, majorGridStep=2, labelUnit=HOUR, labelStep=2, format="%H:%M", maxInterval=2*DAY),
dict(seconds=100, minorGridUnit=HOUR, minorGridStep=2, majorGridUnit=HOUR, majorGridStep=4, labelUnit=HOUR, labelStep=4, format=percent_l_supported and "%a %l%p" or "%a %I%p", maxInterval=6*DAY),
dict(seconds=255, minorGridUnit=HOUR, minorGridStep=6, majorGridUnit=HOUR, majorGridStep=12, labelUnit=HOUR, labelStep=12, format=percent_l_supported and "%m/%d %l%p" or "%m/%d %I%p"),
dict(seconds=600, minorGridUnit=HOUR, minorGridStep=6, majorGridUnit=DAY, majorGridStep=1, labelUnit=DAY, labelStep=1, format="%m/%d", maxInterval=14*DAY),
dict(seconds=600, minorGridUnit=HOUR, minorGridStep=12, majorGridUnit=DAY, majorGridStep=1, labelUnit=DAY, labelStep=1, format="%m/%d", maxInterval=365*DAY),
dict(seconds=2000, minorGridUnit=DAY, minorGridStep=1, majorGridUnit=DAY, majorGridStep=2, labelUnit=DAY, labelStep=2, format="%m/%d", maxInterval=365*DAY),
dict(seconds=4000, minorGridUnit=DAY, minorGridStep=2, majorGridUnit=DAY, majorGridStep=4, labelUnit=DAY, labelStep=4, format="%m/%d", maxInterval=365*DAY),
dict(seconds=8000, minorGridUnit=DAY, minorGridStep=3.5,majorGridUnit=DAY, majorGridStep=7, labelUnit=DAY, labelStep=7, format="%m/%d", maxInterval=365*DAY),
dict(seconds=16000, minorGridUnit=DAY, minorGridStep=7, majorGridUnit=DAY, majorGridStep=14, labelUnit=DAY, labelStep=14, format="%m/%d", maxInterval=365*DAY),
dict(seconds=32000, minorGridUnit=DAY, minorGridStep=15, majorGridUnit=DAY, majorGridStep=30, labelUnit=DAY, labelStep=30, format="%m/%d", maxInterval=365*DAY),
dict(seconds=64000, minorGridUnit=DAY, minorGridStep=30, majorGridUnit=DAY, majorGridStep=60, labelUnit=DAY, labelStep=60, format="%m/%d %Y"),
dict(seconds=100000,minorGridUnit=DAY, minorGridStep=60, majorGridUnit=DAY, majorGridStep=120,labelUnit=DAY, labelStep=120, format="%m/%d %Y"),
dict(seconds=120000,minorGridUnit=DAY, minorGridStep=120,majorGridUnit=DAY, majorGridStep=240,labelUnit=DAY, labelStep=240, format="%m/%d %Y"),
)
UnitSystems = {
'binary': (
('Pi', 1024.0**5),
('Ti', 1024.0**4),
('Gi', 1024.0**3),
('Mi', 1024.0**2),
('Ki', 1024.0 )),
'si': (
('P', 1000.0**5),
('T', 1000.0**4),
('G', 1000.0**3),
('M', 1000.0**2),
('K', 1000.0 )),
'none' : [],
}
class GraphError(Exception):
pass
class Graph:
customizable = ('width','height','margin','bgcolor','fgcolor', \
'fontName','fontSize','fontBold','fontItalic', \
'colorList','template','yAxisSide','outputFormat')
def __init__(self,**params):
self.params = params
self.data = params['data']
self.dataLeft = []
self.dataRight = []
self.secondYAxis = False
self.width = int( params.get('width',200) )
self.height = int( params.get('height',200) )
self.margin = int( params.get('margin',10) )
self.userTimeZone = params.get('tz')
self.logBase = params.get('logBase', None)
self.minorY = int(params.get('minorY', 1))
if self.logBase:
if self.logBase == 'e':
self.logBase = math.e
elif self.logBase <= 0:
self.logBase = None
params['logBase'] = None
else:
self.logBase = float(self.logBase)
if self.margin < 0:
self.margin = 10
self.area = {
'xmin' : self.margin + 10, # Need extra room when the time is near the left edge
'xmax' : self.width - self.margin,
'ymin' : self.margin,
'ymax' : self.height - self.margin,
}
self.loadTemplate( params.get('template','default') )
self.setupCairo( params.get('outputFormat','png').lower() )
opts = self.ctx.get_font_options()
opts.set_antialias( cairo.ANTIALIAS_NONE )
self.ctx.set_font_options( opts )
self.foregroundColor = params.get('fgcolor',self.defaultForeground)
self.backgroundColor = params.get('bgcolor',self.defaultBackground)
self.setColor( self.backgroundColor )
self.drawRectangle( 0, 0, self.width, self.height )
if 'colorList' in params:
colorList = unquote_plus( str(params['colorList']) ).split(',')
else:
colorList = self.defaultColorList
self.colors = itertools.cycle( colorList )
self.drawGraph(**params)
def setupCairo(self,outputFormat='png'):
self.outputFormat = outputFormat
if outputFormat == 'png':
self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.width, self.height)
else:
self.surfaceData = StringIO.StringIO()
self.surface = cairo.SVGSurface(self.surfaceData, self.width, self.height)
self.ctx = cairo.Context(self.surface)
def setColor(self, value, alpha=1.0, forceAlpha=False):
if type(value) is tuple and len(value) == 3:
r,g,b = value
elif value in colorAliases:
r,g,b = colorAliases[value]
elif type(value) in (str,unicode) and len(value) >= 6:
s = value
if s[0] == '#': s = s[1:]
if s[0:3] == '%23': s = s[3:]
r,g,b = ( int(s[0:2],base=16), int(s[2:4],base=16), int(s[4:6],base=16) )
if len(s) == 8 and not forceAlpha:
alpha = float( int(s[6:8],base=16) ) / 255.0
else:
raise ValueError, "Must specify an RGB 3-tuple, an html color string, or a known color alias!"
r,g,b = [float(c) / 255.0 for c in (r,g,b)]
self.ctx.set_source_rgba(r,g,b,alpha)
def setFont(self, **params):
p = self.defaultFontParams.copy()
p.update(params)
self.ctx.select_font_face(p['name'], p['italic'], p['bold'])
self.ctx.set_font_size( float(p['size']) )
def getExtents(self,text=None,fontOptions={}):
if fontOptions:
self.setFont(**fontOptions)
F = self.ctx.font_extents()
extents = { 'maxHeight' : F[2], 'maxAscent' : F[0], 'maxDescent' : F[1] }
if text:
T = self.ctx.text_extents(text)
extents['width'] = T[4]
extents['height'] = T[3]
return extents
def drawRectangle(self, x, y, w, h, fill=True, dash=False):
if not fill:
o = self.ctx.get_line_width() / 2.0 #offset for borders so they are drawn as lines would be
x += o
y += o
w -= o
h -= o
self.ctx.rectangle(x,y,w,h)
if fill:
self.ctx.fill()
else:
if dash:
self.ctx.set_dash(dash,1)
else:
self.ctx.set_dash([],0)
self.ctx.stroke()
def drawText(self,text,x,y,font={},color={},align='left',valign='top',border=False,rotate=0):
if font: self.setFont(**font)
if color: self.setColor(**color)
extents = self.getExtents(text)
angle = math.radians(rotate)
origMatrix = self.ctx.get_matrix()
horizontal = {
'left' : 0,
'center' : extents['width'] / 2,
'right' : extents['width'],
}[align.lower()]
vertical = {
'top' : extents['maxAscent'],
'middle' : extents['maxHeight'] / 2 - extents['maxDescent'],
'bottom' : -extents['maxDescent'],
'baseline' : 0,
}[valign.lower()]
self.ctx.move_to(x,y)
self.ctx.rel_move_to( math.sin(angle) * -vertical, math.cos(angle) * vertical)
self.ctx.rotate(angle)
self.ctx.rel_move_to( -horizontal, 0 )
bx, by = self.ctx.get_current_point()
by -= extents['maxAscent']
self.ctx.text_path(text)
self.ctx.fill()
if border:
self.drawRectangle(bx, by, extents['width'], extents['maxHeight'], fill=False)
else:
self.ctx.set_matrix(origMatrix)
def drawTitle(self,text):
self.encodeHeader('title')
y = self.area['ymin']
x = self.width / 2
lineHeight = self.getExtents()['maxHeight']
for line in text.split('\n'):
self.drawText(line, x, y, align='center')
y += lineHeight
if self.params.get('yAxisSide') == 'right':
self.area['ymin'] = y
else:
self.area['ymin'] = y + self.margin
def drawLegend(self, elements, unique=False): #elements is [ (name,color,rightSide), (name,color,rightSide), ... ]
self.encodeHeader('legend')
if unique:
# remove duplicate names
namesSeen = []
newElements = []
for e in elements:
if e[0] not in namesSeen:
namesSeen.append(e[0])
newElements.append(e)
elements = newElements
# Check if there's enough room to use two columns.
rightSideLabels = False
padding = 5
longestName = sorted([e[0] for e in elements],key=len)[-1]
testSizeName = longestName + " " + longestName # Double it to check if there's enough room for 2 columns
testExt = self.getExtents(testSizeName)
testBoxSize = testExt['maxHeight'] - 1
testWidth = testExt['width'] + 2 * (testBoxSize + padding)
if testWidth + 50 < self.width:
rightSideLabels = True
if(self.secondYAxis and rightSideLabels):
extents = self.getExtents(longestName)
padding = 5
boxSize = extents['maxHeight'] - 1
lineHeight = extents['maxHeight'] + 1
labelWidth = extents['width'] + 2 * (boxSize + padding)
columns = max(1, math.floor( (self.width - self.area['xmin']) / labelWidth ))
numRight = len([name for (name,color,rightSide) in elements if rightSide])
numberOfLines = max(len(elements) - numRight, numRight)
columns = math.floor(columns / 2.0)
if columns < 1: columns = 1
legendHeight = numberOfLines * (lineHeight + padding)
self.area['ymax'] -= legendHeight #scoot the drawing area up to fit the legend
self.ctx.set_line_width(1.0)
x = self.area['xmin']
y = self.area['ymax'] + (2 * padding)
n = 0
xRight = self.area['xmax'] - self.area['xmin']
yRight = y
nRight = 0
for (name,color,rightSide) in elements:
self.setColor( color )
if rightSide:
nRight += 1
self.drawRectangle(xRight - padding,yRight,boxSize,boxSize)
self.setColor( 'darkgrey' )
self.drawRectangle(xRight - padding,yRight,boxSize,boxSize,fill=False)
self.setColor( self.foregroundColor )
self.drawText(name, xRight - boxSize, yRight, align='right')
xRight -= labelWidth
if nRight % columns == 0:
xRight = self.area['xmax'] - self.area['xmin']
yRight += lineHeight
else:
n += 1
self.drawRectangle(x,y,boxSize,boxSize)
self.setColor( 'darkgrey' )
self.drawRectangle(x,y,boxSize,boxSize,fill=False)
self.setColor( self.foregroundColor )
self.drawText(name, x + boxSize + padding, y, align='left')
x += labelWidth
if n % columns == 0:
x = self.area['xmin']
y += lineHeight
else:
extents = self.getExtents(longestName)
boxSize = extents['maxHeight'] - 1
lineHeight = extents['maxHeight'] + 1
labelWidth = extents['width'] + 2 * (boxSize + padding)
columns = math.floor( self.width / labelWidth )
if columns < 1: columns = 1
numberOfLines = math.ceil( float(len(elements)) / columns )
legendHeight = numberOfLines * (lineHeight + padding)
self.area['ymax'] -= legendHeight #scoot the drawing area up to fit the legend
self.ctx.set_line_width(1.0)
x = self.area['xmin']
y = self.area['ymax'] + (2 * padding)
for i,(name,color,rightSide) in enumerate(elements):
if rightSide:
self.setColor( color )
self.drawRectangle(x + labelWidth + padding,y,boxSize,boxSize)
self.setColor( 'darkgrey' )
self.drawRectangle(x + labelWidth + padding,y,boxSize,boxSize,fill=False)
self.setColor( self.foregroundColor )
self.drawText(name, x + labelWidth, y, align='right')
x += labelWidth
else:
self.setColor( color )
self.drawRectangle(x,y,boxSize,boxSize)
self.setColor( 'darkgrey' )
self.drawRectangle(x,y,boxSize,boxSize,fill=False)
self.setColor( self.foregroundColor )
self.drawText(name, x + boxSize + padding, y, align='left')
x += labelWidth
if (i + 1) % columns == 0:
x = self.area['xmin']
y += lineHeight
def encodeHeader(self,text):
self.ctx.save()
self.setColor( self.backgroundColor )
self.ctx.move_to(-88,-88) # identifier
for i, char in enumerate(text):
self.ctx.line_to(-ord(char), -i-1)
self.ctx.stroke()
self.ctx.restore()
def loadTemplate(self,template):
conf = SafeConfigParser()
if conf.read(settings.GRAPHTEMPLATES_CONF):
defaults = dict( conf.items('default') )
if template in conf.sections():
opts = dict( conf.items(template) )
else:
opts = defaults
else:
opts = defaults = defaultGraphOptions
self.defaultBackground = opts.get('background', defaults['background'])
self.defaultForeground = opts.get('foreground', defaults['foreground'])
self.defaultMajorGridLineColor = opts.get('majorline', defaults['majorline'])
self.defaultMinorGridLineColor = opts.get('minorline', defaults['minorline'])
self.defaultColorList = [c.strip() for c in opts.get('linecolors', defaults['linecolors']).split(',')]
fontName = opts.get('fontname', defaults['fontname'])
fontSize = float( opts.get('fontsize', defaults['fontsize']) )
fontBold = opts.get('fontbold', defaults['fontbold']).lower() == 'true'
fontItalic = opts.get('fontitalic', defaults['fontitalic']).lower() == 'true'
self.defaultFontParams = {
'name' : self.params.get('fontName',fontName),
'size' : int( self.params.get('fontSize',fontSize) ),
'bold' : self.params.get('fontBold',fontBold),
'italic' : self.params.get('fontItalic',fontItalic),
}
def output(self, fileObj):
if self.outputFormat == 'png':
self.surface.write_to_png(fileObj)
else:
metaData = {
'x': {
'start': self.startTime,
'end': self.endTime
},
'options': {
'lineWidth': self.lineWidth
},
'font': self.defaultFontParams,
'area': self.area,
'series': []
}
if not self.secondYAxis:
metaData['y'] = {
'top': self.yTop,
'bottom': self.yBottom,
'step': self.yStep,
'labels': self.yLabels,
'labelValues': self.yLabelValues
}
for series in self.data:
if 'stacked' not in series.options:
metaData['series'].append({
'name': series.name,
'start': series.start,
'end': series.end,
'step': series.step,
'valuesPerPoint': series.valuesPerPoint,
'color': series.color,
'data': series,
'options': series.options
})
self.surface.finish()
svgData = self.surfaceData.getvalue()
self.surfaceData.close()
svgData = svgData.replace('pt"', 'px"', 2) # we expect height/width in pixels, not points
svgData = svgData.replace('</svg>\n', '', 1)
svgData = svgData.replace('</defs>\n<g', '</defs>\n<g class="graphite"', 1)
# We encode headers using special paths with d^="M -88 -88"
# Find these, and turn them into <g> wrappers instead
def onHeaderPath(match):
name = ''
for char in re.findall(r'L -(\d+) -\d+', match.group(1)):
name += chr(int(char))
return '</g><g data-header="true" class="%s">' % name
svgData = re.sub(r'<path.+?d="M -88 -88 (.+?)"/>', onHeaderPath, svgData)
# Replace the first </g><g> with <g>, and close out the last </g> at the end
svgData = svgData.replace('</g><g data-header','<g data-header',1) + "</g>"
svgData = svgData.replace(' data-header="true"','')
fileObj.write(svgData)
fileObj.write("""<script>
<![CDATA[
metadata = %s
]]>
</script>
</svg>""" % json.dumps(metaData))
class LineGraph(Graph):
customizable = Graph.customizable + \
('title','vtitle','lineMode','lineWidth','hideLegend', \
'hideAxes','minXStep','hideGrid','majorGridLineColor', \
'minorGridLineColor','thickness','min','max', \
'graphOnly','yMin','yMax','yLimit','yStep','areaMode', \
'areaAlpha','drawNullAsZero','tz', 'yAxisSide','pieMode', \
'yUnitSystem', 'logBase','yMinLeft','yMinRight','yMaxLeft', \
'yMaxRight', 'yLimitLeft', 'yLimitRight', 'yStepLeft', \
'yStepRight', 'rightWidth', 'rightColor', 'rightDashed', \
'leftWidth', 'leftColor', 'leftDashed', 'xFormat', 'minorY', \
'hideYAxis', 'uniqueLegend', 'vtitleRight', 'yDivisors', \
'connectedLimit')
validLineModes = ('staircase','slope','connected')
validAreaModes = ('none','first','all','stacked')
validPieModes = ('maximum', 'minimum', 'average')
def drawGraph(self,**params):
# Make sure we've got datapoints to draw
if self.data:
startTime = min([series.start for series in self.data])
endTime = max([series.end for series in self.data])
timeRange = endTime - startTime
else:
timeRange = None
if not timeRange:
x = self.width / 2
y = self.height / 2
self.setColor('red')
self.setFont(size=math.log(self.width * self.height) )
self.drawText("No Data", x, y, align='center')
return
# Determine if we're doing a 2 y-axis graph.
for series in self.data:
if 'secondYAxis' in series.options:
self.dataRight.append(series)
else:
self.dataLeft.append(series)
if len(self.dataRight) > 0:
self.secondYAxis = True
#API compatibilty hacks
if params.get('graphOnly',False):
params['hideLegend'] = True
params['hideGrid'] = True
params['hideAxes'] = True
params['hideYAxis'] = False
params['yAxisSide'] = 'left'
params['title'] = ''
params['vtitle'] = ''
params['margin'] = 0
params['tz'] = ''
self.margin = 0
self.area['xmin'] = 0
self.area['xmax'] = self.width
self.area['ymin'] = 0
self.area['ymax'] = self.height
if 'yMin' not in params and 'min' in params:
params['yMin'] = params['min']
if 'yMax' not in params and 'max' in params:
params['yMax'] = params['max']
if 'lineWidth' not in params and 'thickness' in params:
params['lineWidth'] = params['thickness']
if 'yAxisSide' not in params:
params['yAxisSide'] = 'left'
if 'yUnitSystem' not in params:
params['yUnitSystem'] = 'si'
else:
params['yUnitSystem'] = str(params['yUnitSystem']).lower()
if params['yUnitSystem'] not in UnitSystems.keys():
params['yUnitSystem'] = 'si'
self.params = params
# Don't do any of the special right y-axis stuff if we're drawing 2 y-axes.
if self.secondYAxis:
params['yAxisSide'] = 'left'
# When Y Axis is labeled on the right, we subtract x-axis positions from the max,
# instead of adding to the minimum
if self.params.get('yAxisSide') == 'right':
self.margin = self.width
#Now to setup our LineGraph specific options
self.lineWidth = float( params.get('lineWidth', 1.2) )
self.lineMode = params.get('lineMode','slope').lower()
self.connectedLimit = params.get("connectedLimit", INFINITY)
assert self.lineMode in self.validLineModes, "Invalid line mode!"
self.areaMode = params.get('areaMode','none').lower()
assert self.areaMode in self.validAreaModes, "Invalid area mode!"
self.pieMode = params.get('pieMode', 'maximum').lower()
assert self.pieMode in self.validPieModes, "Invalid pie mode!"
# Line mode slope does not work (or even make sense) for series that have
# only one datapoint. So if any series have one datapoint we force staircase mode.
if self.lineMode == 'slope':
for series in self.data:
if len(series) == 1:
self.lineMode = 'staircase'
break
if self.secondYAxis:
for series in self.data:
if 'secondYAxis' in series.options:
if 'rightWidth' in params:
series.options['lineWidth'] = params['rightWidth']
if 'rightDashed' in params:
series.options['dashed'] = params['rightDashed']
if 'rightColor' in params:
series.color = params['rightColor']
else:
if 'leftWidth' in params:
series.options['lineWidth'] = params['leftWidth']
if 'leftDashed' in params:
series.options['dashed'] = params['leftDashed']
if 'leftColor' in params:
series.color = params['leftColor']
for series in self.data:
if not hasattr(series, 'color'):
series.color = self.colors.next()
titleSize = self.defaultFontParams['size'] + math.floor( math.log(self.defaultFontParams['size']) )
self.setFont( size=titleSize )
self.setColor( self.foregroundColor )
if params.get('title'):
self.drawTitle( str(params['title']) )
if params.get('vtitle'):
self.drawVTitle( str(params['vtitle']) )
if self.secondYAxis and params.get('vtitleRight'):
self.drawVTitle( str(params['vtitleRight']), rightAlign=True )
self.setFont()
if not params.get('hideLegend', len(self.data) > settings.LEGEND_MAX_ITEMS):
elements = [ (series.name,series.color,series.options.get('secondYAxis')) for series in self.data if series.name ]
self.drawLegend(elements, params.get('uniqueLegend', False))
#Setup axes, labels, and grid
#First we adjust the drawing area size to fit X-axis labels
if not self.params.get('hideAxes',False):
self.area['ymax'] -= self.getExtents()['maxAscent'] * 2
self.startTime = min([series.start for series in self.data])
if self.lineMode == 'staircase':
self.endTime = max([series.end for series in self.data])
else:
self.endTime = max([(series.end - series.step) for series in self.data])
self.timeRange = self.endTime - self.startTime
#Now we consolidate our data points to fit in the currently estimated drawing area
self.consolidateDataPoints()
self.encodeHeader('axes')
#Now its time to fully configure the Y-axis and determine the space required for Y-axis labels
#Since we'll probably have to squeeze the drawing area to fit the Y labels, we may need to
#reconsolidate our data points, which in turn means re-scaling the Y axis, this process will
#repeat until we have accurate Y labels and enough space to fit our data points
currentXMin = self.area['xmin']
currentXMax = self.area['xmax']
if self.secondYAxis:
self.setupTwoYAxes()
else:
self.setupYAxis()
while currentXMin != self.area['xmin'] or currentXMax != self.area['xmax']: #see if the Y-labels require more space
self.consolidateDataPoints() #this can cause the Y values to change
currentXMin = self.area['xmin'] #so let's keep track of the previous Y-label space requirements
currentXMax = self.area['xmax']
if self.secondYAxis: #and recalculate their new requirements
self.setupTwoYAxes()
else:
self.setupYAxis()
#Now that our Y-axis is finalized, let's determine our X labels (this won't affect the drawing area)
self.setupXAxis()
if not self.params.get('hideAxes',False):
self.drawLabels()
if not self.params.get('hideGrid',False): #hideAxes implies hideGrid
self.encodeHeader('grid')
self.drawGridLines()
#Finally, draw the graph lines
self.encodeHeader('lines')
self.drawLines()
def drawVTitle(self, text, rightAlign=False):
lineHeight = self.getExtents()['maxHeight']
if rightAlign:
self.encodeHeader('vtitleRight')
x = self.area['xmax'] - lineHeight
y = self.height / 2
for line in text.split('\n'):
self.drawText(line, x, y, align='center', valign='baseline', rotate=90)
x -= lineHeight
self.area['xmax'] = x - self.margin - lineHeight
else:
self.encodeHeader('vtitle')
x = self.area['xmin'] + lineHeight
y = self.height / 2
for line in text.split('\n'):
self.drawText(line, x, y, align='center', valign='baseline', rotate=270)
x += lineHeight
self.area['xmin'] = x + self.margin + lineHeight
def getYCoord(self, value, side=None):
if "left" == side:
yLabelValues = self.yLabelValuesL
yTop = self.yTopL
yBottom = self.yBottomL
elif "right" == side:
yLabelValues = self.yLabelValuesR
yTop = self.yTopR
yBottom = self.yBottomR
else:
yLabelValues = self.yLabelValues
yTop = self.yTop
yBottom = self.yBottom
try:
highestValue = max(yLabelValues)
lowestValue = min(yLabelValues)
except ValueError:
highestValue = yTop
lowestValue = yBottom
pixelRange = self.area['ymax'] - self.area['ymin']
relativeValue = value - lowestValue
valueRange = highestValue - lowestValue
if self.logBase:
if value <= 0:
return None
relativeValue = math.log(value, self.logBase) - math.log(lowestValue, self.logBase)
valueRange = math.log(highestValue, self.logBase) - math.log(lowestValue, self.logBase)
pixelToValueRatio = pixelRange / valueRange
valueInPixels = pixelToValueRatio * relativeValue
return self.area['ymax'] - valueInPixels
def drawLines(self, width=None, dash=None, linecap='butt', linejoin='miter'):
if not width: width = self.lineWidth
self.ctx.set_line_width(width)
originalWidth = width
width = float(int(width) % 2) / 2
if dash:
self.ctx.set_dash(dash,1)
else:
self.ctx.set_dash([],0)
self.ctx.set_line_cap({
'butt' : cairo.LINE_CAP_BUTT,
'round' : cairo.LINE_CAP_ROUND,
'square' : cairo.LINE_CAP_SQUARE,
}[linecap])
self.ctx.set_line_join({
'miter' : cairo.LINE_JOIN_MITER,
'round' : cairo.LINE_JOIN_ROUND,
'bevel' : cairo.LINE_JOIN_BEVEL,
}[linejoin])
# stack the values
if self.areaMode == 'stacked' and not self.secondYAxis: #TODO Allow stacked area mode with secondYAxis
total = []
for series in self.data:
for i in range(len(series)):
if len(total) <= i: total.append(0)
if series[i] is not None:
original = series[i]
series[i] += total[i]
total[i] += original
# check whether there is an stacked metric
singleStacked = False
for series in self.data:
if 'stacked' in series.options:
singleStacked = True
if singleStacked:
self.data = sort_stacked(self.data)
# apply stacked setting on series based on areaMode
if self.areaMode == 'first':
self.data[0].options['stacked'] = True
elif self.areaMode != 'none':
for series in self.data:
series.options['stacked'] = True
# apply alpha channel and create separate stroke series
if self.params.get('areaAlpha'):
try:
alpha = float(self.params['areaAlpha'])
except ValueError:
alpha = 0.5
pass
strokeSeries = []
for series in self.data:
if 'stacked' in series.options:
series.options['alpha'] = alpha
newSeries = TimeSeries(series.name, series.start, series.end, series.step*series.valuesPerPoint, [x for x in series])
newSeries.xStep = series.xStep
newSeries.color = series.color
if 'secondYAxis' in series.options:
newSeries.options['secondYAxis'] = True
strokeSeries.append(newSeries)
self.data += strokeSeries
# setup the clip region
self.ctx.set_line_width(1.0)
self.ctx.rectangle(self.area['xmin'], self.area['ymin'], self.area['xmax'] - self.area['xmin'], self.area['ymax'] - self.area['ymin'])
self.ctx.clip()
self.ctx.set_line_width(originalWidth)
# save clip to restore once stacked areas are drawn
self.ctx.save()
clipRestored = False
for series in self.data:
if 'stacked' not in series.options:
# stacked areas are always drawn first. if this series is not stacked, we finished stacking.
# reset the clip region so lines can show up on top of the stacked areas.
if not clipRestored:
clipRestored = True
self.ctx.restore()
if 'lineWidth' in series.options:
self.ctx.set_line_width(series.options['lineWidth'])
if 'dashed' in series.options:
self.ctx.set_dash([ series.options['dashed'] ], 1)
else:
self.ctx.set_dash([], 0)
# Shift the beginning of drawing area to the start of the series if the
# graph itself has a larger range
missingPoints = (series.start - self.startTime) / series.step
startShift = series.xStep * (missingPoints / series.valuesPerPoint)
x = float(self.area['xmin']) + startShift + (self.lineWidth / 2.0)
y = float(self.area['ymin'])
startX = x
if series.options.get('invisible'):
self.setColor( series.color, 0, True )
else:
self.setColor( series.color, series.options.get('alpha') or 1.0 )
# The number of preceeding datapoints that had a None value.
consecutiveNones = 0
for index, value in enumerate(series):
if value != value: # convert NaN to None
value = None
if value is None and self.params.get('drawNullAsZero'):
value = 0.0
if value is None:
if consecutiveNones == 0:
self.ctx.line_to(x, y)
if 'stacked' in series.options: #Close off and fill area before unknown interval
self.fillAreaAndClip(x, y, startX)
x += series.xStep
consecutiveNones += 1
else:
if self.secondYAxis:
if 'secondYAxis' in series.options:
y = self.getYCoord(value, "right")
else:
y = self.getYCoord(value, "left")
else:
y = self.getYCoord(value)
if y is None:
value = None
elif y < 0:
y = 0
if 'drawAsInfinite' in series.options and value > 0:
self.ctx.move_to(x, self.area['ymax'])
self.ctx.line_to(x, self.area['ymin'])
self.ctx.stroke()
x += series.xStep
continue
if consecutiveNones > 0:
startX = x
if self.lineMode == 'staircase':
if consecutiveNones > 0:
self.ctx.move_to(x, y)
else:
self.ctx.line_to(x, y)
x += series.xStep
self.ctx.line_to(x, y)
elif self.lineMode == 'slope':
if consecutiveNones > 0:
self.ctx.move_to(x, y)
self.ctx.line_to(x, y)
x += series.xStep
elif self.lineMode == 'connected':
# If if the gap is larger than the connectedLimit or if this is the
# first non-None datapoint in the series, start drawing from that datapoint.
if consecutiveNones > self.connectedLimit or consecutiveNones == index:
self.ctx.move_to(x, y)
self.ctx.line_to(x, y)
x += series.xStep
consecutiveNones = 0
if 'stacked' in series.options:
self.fillAreaAndClip(x-series.xStep, y, startX)
else:
self.ctx.stroke()
self.ctx.set_line_width(originalWidth) # return to the original line width
if 'dash' in series.options: # if we changed the dash setting before, change it back now
if dash:
self.ctx.set_dash(dash,1)
else:
self.ctx.set_dash([],0)
def fillAreaAndClip(self, x, y, startX=None):
startX = (startX or self.area['xmin'])
pattern = self.ctx.copy_path()
self.ctx.line_to(x, self.area['ymax']) # bottom endX
self.ctx.line_to(startX, self.area['ymax']) # bottom startX
self.ctx.close_path()
self.ctx.fill()
self.ctx.append_path(pattern)
self.ctx.line_to(x, self.area['ymax']) # bottom endX
self.ctx.line_to(self.area['xmax'], self.area['ymax']) # bottom right
self.ctx.line_to(self.area['xmax'], self.area['ymin']) # top right
self.ctx.line_to(self.area['xmin'], self.area['ymin']) # top left
self.ctx.line_to(self.area['xmin'], self.area['ymax']) # bottom left
self.ctx.line_to(startX, self.area['ymax']) # bottom startX
self.ctx.close_path()
self.ctx.clip()
def consolidateDataPoints(self):
numberOfPixels = self.graphWidth = self.area['xmax'] - self.area['xmin'] - (self.lineWidth + 1)
for series in self.data:
numberOfDataPoints = self.timeRange/series.step
minXStep = float( self.params.get('minXStep',1.0) )
divisor = self.timeRange / series.step
bestXStep = numberOfPixels / divisor
if bestXStep < minXStep:
drawableDataPoints = int( numberOfPixels / minXStep )
pointsPerPixel = math.ceil( float(numberOfDataPoints) / float(drawableDataPoints) )
series.consolidate(pointsPerPixel)
series.xStep = (numberOfPixels * pointsPerPixel) / numberOfDataPoints
else:
series.xStep = bestXStep
def setupYAxis(self):
seriesWithMissingValues = [ series for series in self.data if None in series ]
if self.params.get('drawNullAsZero') and seriesWithMissingValues:
yMinValue = 0.0
else:
yMinValue = safeMin( [safeMin(series) for series in self.data if not series.options.get('drawAsInfinite')] )
if self.areaMode == 'stacked':
length = safeMin( [len(series) for series in self.data if not series.options.get('drawAsInfinite')] )
sumSeries = []
for i in xrange(0, length):
sumSeries.append( safeSum( [series[i] for series in self.data if not series.options.get('drawAsInfinite')] ) )
yMaxValue = safeMax( sumSeries )
else:
yMaxValue = safeMax( [safeMax(series) for series in self.data if not series.options.get('drawAsInfinite')] )
if yMinValue is None:
yMinValue = 0.0
if yMaxValue is None:
yMaxValue = 1.0
if 'yMax' in self.params:
if self.params['yMax'] != 'max':