-
Notifications
You must be signed in to change notification settings - Fork 3
/
calcTrend2.py
executable file
·1150 lines (959 loc) · 58.8 KB
/
calcTrend2.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
#!/usr/bin/env python
#
# Execute on perfstat-<cluster>-<date>.csv file generated by QueryStat2.py
#
import glob
import copy
import os
from optparse import OptionParser
import datetime as dt
import numpy
from shutil import copyfile
import sys
import inspect
import traceback
import linecache
import re
try:
import ConfigParser
except ImportError:
# Python3
import configparser as ConfigParser
try:
import matplotlib as mpl
mpl.use('Agg') # use a non-interactive backend
import matplotlib.pyplot as plt
except ImportError as e:
print("Error in import matplotlib: %s" % (repr(e)) )
plt = None
finally:
pass
try:
from ReportedTestCasesHistory import ReportedTestCasesHistory
except ImportError:
ReportedTestCasesHistory = None
debug = False
smallDataSet = False
# To enable diagram generation for "only good" cases as well
enableGood = True
def PrintException(msg = ''):
exc_type, exc_obj, tb = sys.exc_info()
f = tb.tb_frame
lineno = tb.tb_lineno
filename = f.f_code.co_filename
linecache.checkcache(filename)
line = linecache.getline(filename, lineno, f.f_globals)
print ('EXCEPTION IN (%s, LINE %s CODE:"%s"): %s' % ( filename, lineno, line.strip(), msg))
class TrendReport(object):
# To decide time consumption is increased (>threshold), unaltered (-threshold< <threshold)
# or decreased (<-threshold)
threshold = 5.0 # %
results2 = {}
maxDatapoints = 180
maxDataPointsOverhead = 5
def myPrint(self, Msg, *Args):
if self.verbose:
format=''.join(['%s']*(len(Args)+1))
print( format % tuple([Msg]+map(str,Args)) )
def __init__(self, options):
if options.dataPath.startswith('~/'):
self.dataPath = options.dataPath.replace('~', os.environ['HOME'])
else:
self.dataPath = os.path.abspath(options.dataPath)
if not self.dataPath.endswith('/'):
self.dataPath += '/'
if not os.path.exists(self.dataPath):
print("Fatal error: %s report path doesn't exist." % (self.dataPath))
exit()
if options.reportPath.startswith('~/'):
self.reportPath = options.reportPath.replace('~', os.environ['HOME'])
else:
self.reportPath = os.path.abspath(options.reportPath)
if not self.reportPath.endswith('/'):
self.reportPath += '/'
if not os.path.exists(self.reportPath):
print("Fatal error: %s report path doesn't exist." % (self.reportPath))
exit()
self.enablePdfReport = True
self.enablePdfReport = options.pdfReport
self.badThreshold = options.threshold
self.goodThreshold = -1 * options.threshold
self.movingAverageWindow1 = options.movingAverageWindow1
self.disableMovingAverage1 = options.disableMovingAverage1
self.movingAverageWindow2 = options.movingAverageWindow2
self.disableMovingAverage2 = options.disableMovingAverage2
self.enableSigma = options.enableSigma
self.enableMin = options.enableMin
self.enableMax = options.enableMax
self.enableTrend = True
self.enableMean = True
self.verbose = options.verbose
self.diagramWidth = 16 # Original width
self.diagramHeight = 10 # Original height
self.enableReportGood = True
self.enablePlotGeneration = True
if smallDataSet:
self.maxDatapoints = 4
self.numberOfTestDays = 0
if self.verbose:
print("self.dataPath :%s" % (self.dataPath))
print("self.reportPath :%s" % (self.reportPath))
print("self.enablePdfReport:%s" % (str(self.enablePdfReport)))
print("self.badThreshold :%3.0f %%" % (self.badThreshold))
print("self.goodThreshold :%3.0f %%" % (self.goodThreshold))
print("self.maxDatapoints :%3d " % (self.maxDatapoints))
self.defaultHeaderData = [
['Test case','Last two run', '', '', 'Last five run', '', '', 'All runs', '' , '' ],
['','Trend\nsec/run','Trend','%','Trend\nsec/run','Trend','%','Trend\nsec/run','Trend','%'],
]
self.badTag = "Bad"
self.uglyTag = "Ugly"
self.uglyAndBadTag = "Ugly and Bad"
self.goodTag = "Good"
self.neutralTag = "Neutral"
self.badTags = [ self.badTag, self.uglyTag, self.uglyAndBadTag ]
self.markTags = self.badTags + [self.goodTag]
self.neutralTags = [self.neutralTag]
# To create dictionary from list
# d={ badTags[i]:x for i,x in enumerate(badTags)}
# result is:
# {'Ugly': 'Ugly', 'Bad': 'Bad', 'Bad and Ugly': 'Bad and Ugly'}
self.numOfRuns = {}
# Pro cluster pro day (commulated result of all run on a day)
self.clusterTrends = {}
self.testDays = set()
today = dt.datetime.today()
self.dateStr = today.strftime("%y%m%d")
self.hpccVersion = ''
self.currentIssues = {}
self.newIssues = {}
# Read PerformanceIssues.csv into self.currentIssues
self.issueFileName = 'PerformanceIssues.csv'
if os.path.exists(self.issueFileName):
file = open(self.issueFileName, "r")
for line in file:
items = line.replace('\n', '').split(',')
self.myPrint("Items:", items)
if items[0] not in self.currentIssues:
self.currentIssues[items[0]] ={} # test name
if items[1] not in self.currentIssues[items[0]]:
self.currentIssues[items[0]][items[1]] = {'tag': items[2], 'known' : False}
if items[3] == 'True':
self.currentIssues[items[0]][items[1]]['known'] = True
file.close()
pass
def filterOutOldDatafiles(self, files):
today = dt.date.today()
borderDate = today - dt.timedelta(self.maxDatapoints + self.maxDataPointsOverhead)
numOfRuns = {}
numOfCheckedFiles = {}
retFiles = []
try:
for fileName in files:
nameItems = fileName.replace('./', '').replace('OBT-', 'OBT_').replace('.csv', '').split('-')
if len(nameItems) < 3:
print("Wrong file name!")
continue
cluster = nameItems[1]
resultDate = dt.date(2000 + int(nameItems[2][0:2]), int(nameItems[2][2:4]),int(nameItems[2][4:6]))
if os.stat(fileName).st_size == 0:
continue
if cluster not in numOfRuns:
numOfRuns[cluster] = 0
numOfCheckedFiles[cluster] = 0
numOfCheckedFiles[cluster] += 1
# Read and process self.maxDatapoints files pro cluster only
if (numOfRuns[cluster] < self.maxDatapoints) and (numOfCheckedFiles[cluster] <= self.maxDatapoints + self.maxDataPointsOverhead) and (borderDate <= resultDate):
retFiles.append(fileName)
numOfRuns[cluster] += 1
except:
pass
pass
retFiles.sort()
return retFiles
def readData(self):
def processLine(line):
retCode = 0
testName = ''
loop = 0
testDay = ''
value = 0.0
items = line.split(',')
testNameItems = items[0].split('-')
testNameLen = len(testNameItems)
if testNameLen < 3:
retCode = -1
else:
if testNameLen == 3:
testName = testNameItems[0]
else:
testName = testNameItems[0]
p = re.compile('.*rteloop([0-9]+).*$')
for testNameItem in testNameItems[1:testNameLen-2]:
if testNameItem.startswith('#'):
# Suffix, can contain loop count
m = p.match(testNameItem)
if m:
loop = int(m.group(1))
else:
# other suffix, don't add it to test name
pass
else:
# Version tag, add it to test name
testName += '-' + testNameItem
testDay = '20' + testNameItems[testNameLen-2][0:2] + '.' + testNameItems[testNameLen-2][2:4] + '.' + testNameItems[testNameLen-2][4:6]
value = float(items[1])
return (retCode, testName, loop, testDay, value)
allFiles = glob.glob(self.dataPath+'perfstat-*.csv')
allFiles.sort(reverse = True)
files = self.filterOutOldDatafiles(allFiles)
for fileName in files:
print("File name: " + fileName)
nameItems = fileName.replace('./', '').replace('OBT-', 'OBT_').replace('.csv', '').split('-')
if len(nameItems) < 3:
print("Wrong file name!")
continue
cluster = nameItems[1]
date = '20' + nameItems[2][0:2] + '.' + nameItems[2][2:4] + '.' + nameItems[2][4:6]
if len(nameItems) > 3:
self.hpccVersion = nameItems[3]
if cluster not in self.results2:
self.results2[cluster] = {}
self.numOfRuns[cluster] = 0
self.clusterTrends[cluster] = {'Dates' : [], 'Totals' :[], 'ConfigName':''}
if date not in self.clusterTrends[cluster]['Dates']:
self.clusterTrends[cluster]['Dates'].append(date)
self.clusterTrends[cluster]['ConfigName'] = fileName.replace('.csv', '.cfg')
file = open(fileName, "r")
for line in file:
line = line.strip().replace('\n', '')
(retCode, testname, loop, testDay, value) = processLine(line)
if retCode == -1:
print("Mailformed test name!")
continue
if testname not in self.results2[cluster] :
self.results2[cluster][testname] = { 'Days' : {}, 'Dates': [], 'Values2' : numpy.array([])}
if testDay not in self.results2[cluster][testname]['Days']:
self.results2[cluster][testname]['Days'][testDay] = { 'values' : [], 'totalValue' : 0, 'runsPerDay' : 0, 'max' : value, 'min' : value, 'loops' : 0 }
self.results2[cluster][testname]['Days'][testDay]['values'].append(value)
self.results2[cluster][testname]['Days'][testDay]['totalValue'] += value
self.results2[cluster][testname]['Days'][testDay]['runsPerDay'] += 1
if self.results2[cluster][testname]['Days'][testDay]['max'] < value :
self.results2[cluster][testname]['Days'][testDay]['max'] = value
if self.results2[cluster][testname]['Days'][testDay]['min'] > value :
self.results2[cluster][testname]['Days'][testDay]['min'] = value
self.results2[cluster][testname]['Days'][testDay]['loops'] += 1
# Get the largest number of test day
if self.numOfRuns[cluster] < len(self.results2[cluster][testname]['Days']):
self.numOfRuns[cluster] = len(self.results2[cluster][testname]['Days'])
pass
# More than one result pro day adjust the dates in clusterTrends
# (not the best way to use dates of each cluster first test case)
print ("Read done")
print("Read the last test config")
for cluster in sorted(self.clusterTrends):
try:
self.clusterTrends[cluster]['testConfig'] = ConfigParser.ConfigParser()
self.clusterTrends[cluster]['testConfig'].read(self.clusterTrends[cluster]['ConfigName'])
print("%s FlushDiskCache :'%s'" % (cluster, self.clusterTrends[cluster]['testConfig'].get("Performance", "FlushDiskCache") ))
pass
except:
print("Unexpected error:" + str(sys.exc_info()[0]) + " (line: " + str(inspect.stack()[0][2]) + ")" )
traceback.print_stack()
pass
# Collect run counts to determine how many performance test has been executed
loopCounts = {}
for cluster in sorted(self.clusterTrends):
loopCounts[cluster] = { 'Days':{} , 'Loops': {}}
for testname in sorted(self.results2[cluster]):
for day in sorted(self.results2[cluster][testname]['Days']):
if day not in loopCounts[cluster]['Days']:
loopCounts[cluster]['Days'][day] = {}
runCount = self.results2[cluster][testname]['Days'][day]['loops']
if runCount not in loopCounts[cluster]['Days'][day]:
loopCounts[cluster]['Days'][day][runCount] = 1
else:
loopCounts[cluster]['Days'][day][runCount] += 1
for day in loopCounts[cluster]['Days']:
loopCounts[cluster]['Loops'][day] = max(loopCounts[cluster]['Days'][day], key=loopCounts[cluster]['Days'][day].get)
for cluster in sorted(self.clusterTrends):
#clusterTotalTimes = self.numOfRuns[cluster] * [0]
clusterTotalTimes = len(self.clusterTrends[cluster]['Dates']) * [0]
clusterTotalTimesPerDay = {}
for testname in sorted(self.results2[cluster]):
# if not testname.startswith('80ab_scalesort-scale(16)'):
# continue
days = sorted(self.clusterTrends[cluster]['Dates'])
for day in days:
dayIndex = days.index(day)
date = day #self.results[cluster][testname]['Dates'][dayIndex]
# Calculate average daily value if there were more than one run on that day
# Cases:
# testLoopCount == 1 and dailyLoopCount == 1
# Fine (time) value is the exacte execution time of test case
#
# testLoopCount == 1 and dailyLoopCount > 1
# Some execution missing, the approximated (time) value is the value
#
# testLoopCount > 1 and dailyLoopCount == 1
# Fine (time) value is the summarised execution time of test case in multiple times
#
# testLoopCount > 1 and dailyLoopCount > 1
# Subcases:
# testLoopCount < dailyLoopCount
# Some execution missing, use some approximation: test is invalid, keep original value
#
# testLoopCount == testCaseInLoop * dailyLoopCount
# Fine (time) value is the approximated (time) value is value / dailyLoopCount
#
# testLoopCount != testCaseInLoop * dailyLoopCount
# Some execution missing, use some approximation: test is invalid , keep original value
#
try:
value = self.results2[cluster][testname]['Days'][day]['totalValue']
testLoopCount = self.results2[cluster][testname]['Days'][day]['loops']
if testLoopCount > 1:
value = value / testLoopCount
value2 = value
except KeyError as e:
PrintException(repr(e) + " Missing test result on '%s' with test '%s' in engine '%s'." % (day, testname, cluster))
value = 0
value2 = numpy.nan
if day not in self.results2[cluster][testname]['Days']:
self.results2[cluster][testname]['Days'][day] = { 'values' : [], 'totalValue' : 0, 'runsPerDay' : 0, 'max' : value, 'min' : value, 'loops' : 0 }
self.results2[cluster][testname]['Days'][day]['average'] = value
self.results2[cluster][testname]['Dates'].append(day)
self.results2[cluster][testname]['Values2'] = numpy.append(self.results2[cluster][testname]['Values2'], value2)
if day not in clusterTotalTimesPerDay:
clusterTotalTimesPerDay[day] = 0
clusterTotalTimesPerDay[day] += value
clusterTotalTimes[dayIndex] += value
self.clusterTrends[cluster]['Totals'] = clusterTotalTimes
self.clusterTrends[cluster]['DailyTotals'] = clusterTotalTimesPerDay
pass
# Dump Results pro cluster
for cluster in sorted(self.results2):
resultFileName= self.reportPath+ "results-" + cluster + "-" + self.hpccVersion +".csv"
print("resultFileName:" + resultFileName)
resultFile = open(resultFileName, "w")
resultFile.write("Testcase,avg,sigma,alpha,beta,numOfTests\n")
for test in sorted(self.results2[cluster]):
try:
self.results2[cluster][test]['avg'] = numpy.nanmean(self.results2[cluster][test]['Values2'])
self.results2[cluster][test]['sigma'] = numpy.nanstd(self.results2[cluster][test]['Values2'])
except AttributeError as e:
if self.verbose:
PrintException(repr(e) + " Problem with an older numpy.")
# A hack for an older numpy ehre nonmean() and nanstd() doesn't exists
v2 = self.results2[cluster][test]['Values2'][~numpy.isnan(self.results2[cluster][test]['Values2'])]
self.results2[cluster][test]['avg'] = numpy.mean(v2)
self.results2[cluster][test]['sigma'] = numpy.std(v2)
self.results2[cluster][test]['all'] = self.CalcTrend(self.results2[cluster][test]['Values2'])
dataPoints = len(self.results2[cluster][test]['Days'])
resultFile.write(test+','+ str(self.results2[cluster][test]['avg']) + ',' + str(self.results2[cluster][test]['sigma']) + ',' + str(self.results2[cluster][test]['all']['alpha']) + ',' + str(self.results2[cluster][test]['all']['beta']) + ',' + str(dataPoints))
for day in sorted(days):
if day in self.results2[cluster][test]['Days']:
resultFile.write(',' + day + ',' + str(self.results2[cluster][test]['Days'][day]['average']))
else:
resultFile.write(',' + day + ',0')
resultFile.write('\n')
resultFile.close()
pass
# Calculate trendline for an iput data array and give back the trend
def CalcTrend(self, _data):
self.myPrint("\t\t", _data)
# Remove 'nan' values
#data = numpy.unique(_data[~numpy.isnan(_data)])
try:
data = _data[~numpy.isnan(_data)]
except TypeError as e:
# It is possible the _data is not a numpy array, so it can't convert with numpy functions
PrintException(repr(e) + " The _data is %s not a numpy array" % (repr(type(_data))) )
data = _data
n = len(data)
if n <= 1:
print("Not enough data!")
return {'alpha':0.0, 'beta': 0.0, 'direction':'unaltered', 'percentage': 0.0}
sumxy = 0
sumx = 0
sumy = 0
sumx2 = 0
for i in range(0, n): # x = 1.. n
sumxy += (i+1) * data[i] # = sum(x*y)
sumx += (i+1) # = sum(x)
sumy += data[i] # = sum(y)
sumx2 += (i+1) * (i+1) # = sum(x^2)
sum5 = sumx * sumy
sum6 = sumx * sumx # = sum(x)^2
#print ("sumxy: "+str(sumxy))
#print ("sum5: "+str(sum5))
#print ("sumx*sumy: "+str(sumx*sumy))
##print ("sumy: "+str(sumy))
#print ("sumx2: "+str(sumx2))
#print ("sum6: "+str(sum6))
alpha = (n * sumxy - sum5) / (n * sumx2 - sum6) # =(n * sumxy-L3)/(J3*M3-N3)
beta = (sumy - alpha * sumx) / n
percentage = 0.0
if data[0] != 0.0:
#percentage = (data[1] - data[0]) / data[0] * 100
percentage = alpha * 100
if percentage >= self.badThreshold:
direction = "increased"
elif percentage >= self.goodThreshold:
direction = "unaltered"
else:
direction = "decreased"
if self.verbose:
print("\t\ty = %.4f * x %+.4f --> %s (%.4f %%)") % (alpha, beta, direction, percentage)
return {'alpha':alpha, 'beta': beta, 'direction':direction, 'percentage': percentage}
def calcTrendTest(self):
data1 = [32.53, 31.74, 32.45, 32.38, 31.75, 32.18, 31.71, 31.9]
self.CalcTrend(data1)
def calcMovingAverage(self, numberOfDays, data):
self.myPrint("\t\t number of days:%d" % (numberOfDays))
self.myPrint("\t\t", data)
n = len(data)
if n == 0:
print("Not enough data!")
return []
retArray = []
for i in range(0, n):
endIndex = i + 1
startIndex = max (endIndex - numberOfDays, 0)
dataSlice = numpy.array([])
dataSlice = numpy.append(dataSlice, data[startIndex:endIndex])
movingMean = dataSlice.mean()
retArray.append(movingMean)
pass
return retArray
def calcMovingAverageTest(self):
#data1 = [32.53, 31.74, 32.45, 32.38, 31.75, 32.18, 31.71, 31.9]
data1 = [1.0, 2.0, 20.0, 3.0, 1.0, 4.0, 5.0]
movingAverages = self.calcMovingAverage(4, data1)
self.myPrint("\t\t", movingAverages)
def separateAndWrapTestName(self, testName):
testName.replace('-', ' '),
testNameItems = testName.split('-')
testName = testNameItems[0] + '\n '
params = ''
part = ''
for item in testNameItems[1:]:
if len(part + item) > 60:
params += part + '\n '
part = ''
part += item + ', '
testName += params + part
return testName
# add test dates to the X axis
def createDateSeries(self, dateStrings, dataPoints):
# TO-DO Avoid to generate large gap(s) in the date series like
# 2018.09.11, 2018.11.27, 2018.11.28, 2018.11.29 etc.
today = dt.date.today()
# Determine the starting border date and allow a couple of missing date
borderDate = today - dt.timedelta(dataPoints + self.maxDataPointsOverhead)
isBorderDateUpdated = False
dateSeries = []
for dateString in dateStrings:
# Convert datetime object
dateItems = dateString.split('.')
if len(dateItems) > 3:
date1 = dt.datetime(int(dateItems[0]), int(dateItems[1]),int(dateItems[2]), int(dateItems[3]), int(dateItems[4]), int(dateItems[5]))
else:
date1 = dt.datetime(int(dateItems[0]), int(dateItems[1]),int(dateItems[2]))
if not isBorderDateUpdated:
# If there is larger gap between two datap oint than self.maxDataPointsOverhead (a couple of weeks data missing)
if borderDate > date1.date():
borderDate = date1.date()
isBorderDateUpdated = True
if borderDate <= date1.date():
# Convert floating point number
dateSeries.append(mpl.dates.date2num(date1))
return dateSeries
def getTestInfo(self, cluster):
retVal = ''
paramString = self.clusterTrends[cluster]['testConfig'].get("Performance", "FlushDiskCache") + self.clusterTrends[cluster]['testConfig'].get("Performance", "RunCount")
params = paramString.strip().strip('"').split('--')
for param in params:
param = param.strip()
paramItems = param.split()
if len(paramItems) > 1:
if 'flushDiskCachePolicy' in param:
if paramItems[1] == '1':
retVal = retVal.strip().strip(',')
retVal += " before each test, "
if 'runcount' in param:
retVal += "execute each test in " + paramItems[1] + " times, "
else:
if 'flushDiskCache' in param:
retVal += "clear disk cache, "
retVal = retVal.strip().strip(',')
if len(retVal) > 0:
retVal = '\n(Parameters: ' + retVal + ')'
return retVal
def manageTestCase(self, cluster, test, tag):
if tag in self.markTags:
print("\tIt is %s so marked marked now." % (tag))
if test not in self.newIssues:
self.newIssues[test] = {}
self.newIssues[test][cluster] = {'tag': tag, 'known': False}
else:
print("\tIt is %s." % (tag))
if self.enablePlotGeneration:
self.createPlot(cluster, test, tag)
def createPlot(self, cluster, test, tag):
self.myPrint("cluster:%s, test:%s, tag:%s" % (cluster, test, tag))
try:
# print("cluster:%s, test: %s" % (cluster, test))
fig = plt.figure(figsize=(self.diagramWidth, self.diagramHeight), dpi=100)
fig.subplots_adjust(bottom=0.2)
ax = fig.add_subplot(111)
diagramColors = { 'value': 'blue', 'mean': 'red', 'trend': 'black', 'movingAverage1' : 'green', 'movingAverage2' : 'purple', 'sigma':'yellow', 'min': 'lime', 'max' : 'red'}
self.myPrint("\t\t", self.results2[cluster][test])
dataPoints = min(len(self.results2[cluster][test]['Days']), self.maxDatapoints)
dates = self.results2[cluster][test]['Dates'][-dataPoints:]
for index in range(len(dates)):
dateLen = len(dates[index])
if dateLen== 6:
dates[index] = '20' + dates[index][0:2] + '.' + dates[index][2:4] + '.' + dates[index][4:6]
elif dateLen == 8:
dates[index] = '20' + dates[index][0:2] + '.' + dates[index][2:4] + '.' + dates[index][4:6] + '.' + dates[index][7:9] + '.' + dates[index][9:11] + '.' + dates[index][11:13]
else:
pass
dates2 = self.createDateSeries(dates, dataPoints)
dataPoints = len(dates2)
days = dates2[-1] - dates2[0] + 1
try:
self.results2[cluster][test]['avg'] = numpy.nanmean(self.results2[cluster][test]['Values2'][-dataPoints:])
self.results2[cluster][test]['sigma'] = numpy.nanstd(self.results2[cluster][test]['Values2'][-dataPoints:])
except AttributeError as e:
if self.verbose:
PrintException(repr(e) + " Problem with an older numpy.")
# A hack for an older numpy ehre nonmean() and nanstd() doesn't exists
v2 = self.results2[cluster][test]['Values2'][~numpy.isnan(self.results2[cluster][test]['Values2'])][-dataPoints:]
self.results2[cluster][test]['avg'] = numpy.mean(v2)
self.results2[cluster][test]['sigma'] = numpy.std(v2)
self.results2[cluster][test]['maxDataPoints'] = self.CalcTrend(self.results2[cluster][test]['Values2'][-dataPoints:])
# Plot the data
ax.plot_date(dates2, self.results2[cluster][test]['Values2'][-dataPoints:], label=cluster, linestyle = '--', color=diagramColors['value'])
#ax.plot_date(dates2, self.results[cluster][test]['Values'][-dataPoints:], linestyle = '--', color=diagramColors['value'])
# plot the mean
if self.enableMean:
clusterTrendLabel = '%s (mean:%0.2f, sigma:%02f)' % ( cluster, self.results2[cluster][test]['avg'], self.results2[cluster][test]['sigma'])
mx = [dates2[0], dates2[-1]]
my = [self.results2[cluster][test]['avg'] , self.results2[cluster][test]['avg'] ]
ax.plot(mx, my, label=clusterTrendLabel, marker ='.', linestyle = '-', color=diagramColors['mean'] )
# plot the sigma
if self.enableSigma:
mx = [dates2[0], dates2[-1]]
my = [self.results2[cluster][test]['avg']+self.results2[cluster][test]['sigma'], self.results2[cluster][test]['avg']+self.results2[cluster][test]['sigma']]
ax.plot(mx, my, marker ='.', linestyle = '-', color=diagramColors['sigma'] )
mx = [dates2[0], dates2[-1]]
my = [self.results2[cluster][test]['avg']-self.results2[cluster][test]['sigma'], self.results2[cluster][test]['avg']-self.results2[cluster][test]['sigma']]
ax.plot(mx, my, marker ='.', linestyle = '-', color=diagramColors['sigma'] )
# plot the trend
if self.enableTrend:
clusterTrendLabel = '%s-trend (%0.2f sec/day, alpha:%0.3f, beta:%0.3f)' % ( cluster, self.results2[cluster][test]['maxDataPoints']['alpha'], self.results2[cluster][test]['maxDataPoints']['alpha'], self.results2[cluster][test]['maxDataPoints']['beta'])
x1 = [dates2[0], dates2[-1]]
y1 = [self.results2[cluster][test]['maxDataPoints']['beta'], self.results2[cluster][test]['maxDataPoints']['alpha'] * (len(dates2) - 1) + self.results2[cluster][test]['maxDataPoints']['beta'] ]
ax.plot(x1, y1, label=clusterTrendLabel, marker ='.', linestyle = '-', color=diagramColors['trend'] )
# plot the moving average 1 (default: on 7 days)
if not self.disableMovingAverage1:
movingAverage1Label = 'Moving average with %d days window' % (self.movingAverageWindow1)
movingAverages = self.calcMovingAverage(self.movingAverageWindow1, self.results2[cluster][test]['Values2'][-dataPoints:])
ax.plot_date(dates2, movingAverages, label=movingAverage1Label, marker ='.', linestyle = '-', color=diagramColors['movingAverage1'])
# plot the moving average 2 (default: on 30 days)
if not self.disableMovingAverage2:
movingAverage2Label = 'Moving average with %d days window' % (self.movingAverageWindow2)
movingAverages = self.calcMovingAverage(self.movingAverageWindow2, self.results2[cluster][test]['Values2'][-dataPoints:])
ax.plot_date(dates2, movingAverages, label=movingAverage2Label, marker ='.', linestyle = '-', color=diagramColors['movingAverage2'])
# Plot the min values
if self.enableMin:
ax.plot_date(dates2, self.results2[cluster][test]['min'][-dataPoints:], label='Min', marker ='2', linestyle = '--', color=diagramColors['min'])
# Plot the max values
if self.enableMax:
ax.plot_date(dates2, self.results2[cluster][test]['max'][-dataPoints:], label='Max', marker ='1', linestyle = '--', color=diagramColors['max'])
# Plot the loop values
# Experimental
self.enableLoopValues = False
if self.enableLoopValues:
markers = { 0:'s', 1:'X', 2:'P'}
colours = { 0:diagramColors['value'], 1: diagramColors['min'], 2:diagramColors['max']}
for loop in (1, 2):
values = [ d[loop] if loop in d else 0 for d in self.results2[cluster][test]['loops'][-dataPoints:] ]
loopLabel = "Loop-%d" % (loop)
ax.plot_date(dates2, values, label=loopLabel, linestyle = (markers[loop], (2, (loop +1), (loop +1), (loop +1) )), color=colours[loop])
# Format X labels ans ticks
dateFmt = mpl.dates.DateFormatter('%Y-%m-%d')
ax.xaxis.set_major_formatter(dateFmt)
daysLoc = mpl.dates.DayLocator(interval=max( 1, int(dataPoints/30)))
hoursLoc = mpl.dates.HourLocator(interval=6)
ax.xaxis.set_major_locator(daysLoc)
ax.xaxis.set_minor_locator(hoursLoc)
fig.autofmt_xdate(bottom=0.18) # adjust for date labels display
fig.subplots_adjust(left=0.18)
# Y axis ticks
ml = mpl.ticker.AutoMinorLocator()
ax.yaxis.set_minor_locator(ml)
#ax.grid(True, which='both')
ax.grid(True)
wrapTestName = test
if len(test) > 100:
testNameItems = test.split('-')
wrapTestName = ''
partSize = 0
for index in range (len(testNameItems)):
partSize += len(testNameItems[index])
wrapTestName += testNameItems[index] + '-'
if partSize > 100:
partSize = 0
wrapTestName += '\n'
myTitle = tag + ' ' + wrapTestName + ' on ' + cluster + ' in last ' + "%d" % (days) +' days'
myTitle += self.getTestInfo(cluster)
ax.set_title(myTitle)
ax.set_xlabel('Date')
testShortName = test.split('-')[0]
ax.set_ylabel(testShortName + ' execution time (Seconds)')
try:
ax.legend(loc = 'best', framealpha=0.5)
except Exception as e:
if self.verbose:
PrintException(repr(e) + " There is an old matplotlib.")
ax.legend(loc = 'best')
#plt.show()
diagramFileName = self.reportPath + test +"-" + cluster + '-' + self.dateStr + ".png"
plt.savefig(diagramFileName)
fig.clear()
plt.close(fig)
print("\t %s created." % (diagramFileName))
pass
except Exception as e:
PrintException(repr(e) + " No diagram generated")
pass
def processResults(self):
if self.enablePdfReport:
from pdfPerfReportGen import PdfPerfReportGen
pdfReport = PdfPerfReportGen()
pdfShortReport = PdfPerfReportGen()
twoDays = 2
fiveDays = 5
thirtyDays = 30
today = dt.datetime.today()
dateStr = today.strftime("%y%m%d")
pageBreak = False
for cluster in sorted(self.results2):
print ("Cluster:" + cluster + ' (' +str(self.numOfRuns[cluster]) + ' datasets )')
if self.enablePdfReport:
pdfReport.startNewSection("Performance test result on cluster " + cluster + " on " + today.strftime("%d/%m/%y"), pageBreak)
pdfShortReport.startNewSection("Performance test short result on cluster " + cluster + " on " + today.strftime("%d/%m/%y"), pageBreak)
if not pageBreak:
pageBreak = True
pdfReport.newTable()
headerData = copy.deepcopy(self.defaultHeaderData)
#headerData.extend(self.defaultHeaderData)
headerData[0][0] = headerData[0][0] + ' ( executed on ' + cluster + ' )'
headerData[0][7] = headerData[0][7] + ' (%d datasets )' % (self.numOfRuns[cluster])
pdfReport.setTableHeader(headerData)
pdfShortReport.newTable()
pdfShortReport.setTableHeader(headerData)
numOfFluctTests = 0
averageTimeOfFlucTests = 0.0
numOfBadTests = 0
averageTimeOfBadTests = 0.0
numOfUglyBadTests = 0
averageTimeOfUglyBadTests = 0.0
numberOfTests = len(self.results2[cluster])
testIndex = 0
reportFileName = self.reportPath+ "perfreport-" + cluster + "-" + dateStr + ".csv"
print("reportFileName:" + reportFileName)
reportFile = open(reportFileName, "w")
reportFile.write("Testcase,twoDaysTredValue,twoDaysTred,twoDaysTredPercentage,fiveDaysTredValue,fiveDaysTred,fiveDaysTredPercentage,TredValue,Tred,TredPercentage,avg,sigma,fluctuation\n")
for test in sorted(self.results2[cluster]):
testIndex += 1
if debug:
# Only for generate an example diagram
if (not test.startswith('04ad_')) and (not test.startswith('07dc_')) and (not test.startswith('80ab_scalesort-scale(16)')):
continue
isShortlisted = False
dataPoints = len(self.results2[cluster][test]['Values2'])
lastDataDateStr = self.results2[cluster][test]['Dates'][-1]
lastDataDate = dt.date(2000+int(lastDataDateStr[2:4]), int(lastDataDateStr[5:7]), int(lastDataDateStr[8:10]))
lastDataAgeDays = (dt.date.today() - lastDataDate).days
self.myPrint("\ttest:"+ test + "(data points:"+ str(dataPoints) + ")")
if lastDataAgeDays > thirtyDays:
# Last result is too old, skip it.
self.myPrint("\t\t last result date is: %s and it is %s days old. Skip this test." % (lastDataDate.strftime("%y.%m.%d"), str(lastDataAgeDays)))
continue
if dataPoints > 1:
self.results2[cluster][test]['twoDays'] = {'alpha':0.0, 'beta': 0.0, 'direction':'unaltered', 'percentage': 0.0}
self.results2[cluster][test]['fiveDays'] = {'alpha':0.0, 'beta': 0.0, 'direction':'unaltered', 'percentage': 0.0}
self.results2[cluster][test]['thirtyDays'] = {'alpha':0.0, 'beta': 0.0, 'direction':'unaltered', 'percentage': 0.0}
if dataPoints >= twoDays:
self.results2[cluster][test]['twoDays'] = self.CalcTrend(self.results2[cluster][test]['Values2'][dataPoints-twoDays:])
if 'unaltered' != self.results2[cluster][test]['twoDays']['direction']:
isShortlisted = True
if dataPoints >= fiveDays:
self.results2[cluster][test]['fiveDays'] = self.CalcTrend(self.results2[cluster][test]['Values2'][dataPoints-fiveDays:])
if 'unaltered' != self.results2[cluster][test]['fiveDays']['direction']:
isShortlisted = True
if dataPoints >= thirtyDays:
self.results2[cluster][test]['thirtyDays'] = self.CalcTrend(self.results2[cluster][test]['Values2'][dataPoints-thirtyDays:])
pass
if 'unaltered' != self.results2[cluster][test]['thirtyDays']['direction']:
isShortlisted = True
reportFile.write("%s" % (test ))
reportFile.write(",%f,%s,%f" % (self.results2[cluster][test]['twoDays']['alpha'], self.results2[cluster][test]['twoDays']['direction'], self.results2[cluster][test]['twoDays']['percentage'] ))
reportFile.write(",%f,%s,%f" % (self.results2[cluster][test]['fiveDays']['alpha'], self.results2[cluster][test]['fiveDays']['direction'], self.results2[cluster][test]['fiveDays']['percentage'] ))
reportFile.write(",%f,%s,%f" % (self.results2[cluster][test]['thirtyDays']['alpha'], self.results2[cluster][test]['thirtyDays']['direction'], self.results2[cluster][test]['thirtyDays']['percentage'] ))
fluctuation = 0.0
if self.results2[cluster][test]['avg'] != 0.0:
fluctuation = self.results2[cluster][test]['sigma'] / self.results2[cluster][test]['avg']
#print("%3d/%3d: cluster:%s, test:%s, mean:%f sec, sigma:%f sec, fluctuation:%f, alpha:%f" % (testIndex, numberOfTests, cluster, test, self.results2[cluster][test]['avg'], self.results2[cluster][test]['sigma'], fluctuation, self.results2[cluster][test]['all']['alpha']))
print("%3d/%3d: cluster:%s " % (testIndex, numberOfTests, cluster)),
# # Only for generate example diagram
# if test.startswith('01da'):
# self.enableTrend = False
# self.enableMean = False
# self.enableSigma = False
# self.disableMovingAverage1 = True
# self.disableMovingAverage2 = True
# if plt:
# self.manageTestCase(cluster, test, 'Result of ')
# break
if (self.results2[cluster][test]['all']['alpha'] > self.badThreshold / 100.0) and (fluctuation >= 1.0):
print("test:%s\n\t\tmean:%f sec, sigma:%f sec, fluctuation:%f, alpha:%f" % (test, self.results2[cluster][test]['avg'], self.results2[cluster][test]['sigma'], fluctuation, self.results2[cluster][test]['all']['alpha']))
numOfUglyBadTests += 1
averageTimeOfUglyBadTests += self.results2[cluster][test]['avg']
if plt:
self.manageTestCase(cluster, test, self.uglyAndBadTag)
elif self.results2[cluster][test]['all']['alpha'] > self.badThreshold / 100.0:
print("test:%s\n\t\tmean:%f sec, sigma:%f sec, fluctuation:%f, alpha:%f" % (test, self.results2[cluster][test]['avg'], self.results2[cluster][test]['sigma'], fluctuation, self.results2[cluster][test]['all']['alpha']))
numOfBadTests += 1
averageTimeOfBadTests += self.results2[cluster][test]['avg']
if plt:
self.manageTestCase(cluster, test, self.badTag)
elif fluctuation >= 1.0:
print("test:%s\n\t\tmean:%f sec, sigma:%f sec, fluctuation:%f, alpha:%f" % (test, self.results2[cluster][test]['avg'], self.results2[cluster][test]['sigma'], fluctuation, self.results2[cluster][test]['all']['alpha']))
numOfFluctTests += 1
averageTimeOfFlucTests += self.results2[cluster][test]['avg']
if plt:
self.manageTestCase(cluster, test, self.uglyTag)
# elif test.startswith('02cd') or test.startswith('02ea') or test.startswith('02eb') or \
# test.startswith('04ae') or test.startswith('04cd') or test.startswith('04cf') or \
# elif test.startswith('05bc') or test.startswith('06bc'):
# pass
elif self.results2[cluster][test]['all']['alpha'] < self.goodThreshold / 100.0:
print("test:%s\n\t\tmean:%f sec, sigma:%f sec, fluctuation:%f, alpha:%f" % (test, self.results2[cluster][test]['avg'], self.results2[cluster][test]['sigma'], fluctuation, self.results2[cluster][test]['all']['alpha']))
if plt and self.enableReportGood:
self.manageTestCase(cluster, test, self.goodTag)
elif enableGood:
print("test:%s\n\t\tmean:%f sec, sigma:%f sec, fluctuation:%f, alpha:%f" % (test, self.results2[cluster][test]['avg'], self.results2[cluster][test]['sigma'], fluctuation, self.results2[cluster][test]['all']['alpha']))
if plt and self.enableReportGood:
self.manageTestCase(cluster, test, self.neutralTag)
reportFile.write(",%f,%f,%f\n" % (self.results2[cluster][test]['avg'], self.results2[cluster][test]['sigma'], fluctuation))
if self.enablePdfReport:
rowData = [ self.separateAndWrapTestName(test),
"%0.2f" % self.results2[cluster][test]['twoDays']['alpha'], self.results2[cluster][test]['twoDays']['direction'], "%0.2f" % self.results2[cluster][test]['twoDays']['percentage'],
"%0.2f" % self.results2[cluster][test]['fiveDays']['alpha'], self.results2[cluster][test]['fiveDays']['direction'], "%0.2f" % self.results2[cluster][test]['fiveDays']['percentage'],
"%0.2f" % self.results2[cluster][test]['all']['alpha'], self.results2[cluster][test]['all']['direction'], "%0.2f" % self.results2[cluster][test]['all']['percentage']
]
pdfReport.addTableRow(rowData)
if isShortlisted:
pdfShortReport.addTableRow(rowData)
if self.enablePdfReport:
pdfReport.addTableToStory()
pdfShortReport.addTableToStory()
reportFile.close()
# Calc cluster total trends
dataPoints = self.numOfRuns[cluster]
if dataPoints >= twoDays:
self.clusterTrends[cluster]['twoDays'] = self.CalcTrend(self.clusterTrends[cluster]['Totals'][dataPoints-twoDays:])
if dataPoints >= fiveDays:
self.clusterTrends[cluster]['fiveDays'] = self.CalcTrend(self.clusterTrends[cluster]['Totals'][dataPoints-fiveDays:])
if dataPoints > 30:
self.clusterTrends[cluster]['thirtyDays'] = self.CalcTrend(self.clusterTrends[cluster]['Totals'][dataPoints-thirtyDays:])
else:
self.clusterTrends[cluster]['thirtyDays'] = self.CalcTrend(self.clusterTrends[cluster]['Totals'])
pass
if numOfUglyBadTests > 0:
print("num of ugly (fluctuating) and bad (increasing) tests:%d, average time of them:%f\n" % (numOfUglyBadTests, averageTimeOfFlucTests))
if numOfFluctTests > 0:
print("num of ugly (fluctuating) tests:%d, average time of them:%f\n" % (numOfFluctTests, averageTimeOfFlucTests))
if numOfBadTests > 0:
print("num of bad (increasing) tests:%d, average time of them:%f\n" % (numOfBadTests, averageTimeOfBadTests))
if self.enablePdfReport:
pdfReport.create_pdfdoc(self.reportPath + 'PerformanceTestReport-'+ today.strftime("%y-%m-%d") +'.pdf')
pdfShortReport.create_pdfdoc(self.reportPath+'PerformanceTestShortReport-'+ today.strftime("%y-%m-%d") +'.pdf')
# Write out Performance Test summary file
summaryFileName = self.reportPath + "perftest-" + dateStr + ".summary"
print("summaryFileName:" + summaryFileName)
summaryFile = open(summaryFileName, "w")
summaryFile.write("# cluster, time, twoDaysTredValue, twoDaysTred, twoDaysTredPercentage, fiveDaysTredValue, fiveDaysTred, fiveDaysTredPercentage, TredValue, Tred, TredPercentage\n")
for cluster in sorted(self.clusterTrends):
summaryFile.write("%s" % (cluster ))
summaryFile.write(",%0.2f" % (self.clusterTrends[cluster]['Totals'][-1] ))
if 'twoDays' in self.clusterTrends[cluster]:
summaryFile.write(",%0.2f,%s,%0.2f" % (self.clusterTrends[cluster]['twoDays']['alpha'], self.clusterTrends[cluster]['twoDays']['direction'], self.clusterTrends[cluster]['twoDays']['percentage'] ))
if 'fiveDays' in self.clusterTrends[cluster]:
summaryFile.write(",%0.2f,%s,%0.2f" % (self.clusterTrends[cluster]['fiveDays']['alpha'], self.clusterTrends[cluster]['fiveDays']['direction'], self.clusterTrends[cluster]['fiveDays']['percentage'] ))
summaryFile.write(",%0.2f,%s,%0.2f\n" % (self.clusterTrends[cluster]['thirtyDays']['alpha'], self.clusterTrends[cluster]['thirtyDays']['direction'], self.clusterTrends[cluster]['thirtyDays']['percentage'] ))
summaryFile.close()
# Write out Performance Test totals
try:
totalsFileName = self.reportPath + "perftest-totals" + dateStr + ".csv"
print("totalsFileName:" + totalsFileName)
totalsFile = open(totalsFileName, "w")
totalsFile.write("# cluster, date, time\n")
for cluster in sorted(self.clusterTrends):
for index in range(self.numOfRuns[cluster]):
totalsFile.write("%s" % (cluster ))
totalsFile.write(",%s" % (self.clusterTrends[cluster]['Dates'][index]))
totalsFile.write(",%0.2f" % (self.clusterTrends[cluster]['Totals'][index] ))
totalsFile.write("\n")
totalsFile.close()
except Exception as e:
PrintException(repr(e) + " Unexpected error")
#print("Unexpected error:" + str(sys.exc_info()[0]) + " (line: " + str(inspect.stack()[0][2]) + ")" )
traceback.print_stack()
pass
if plt:
fig = plt.figure(figsize=(self.diagramWidth, self.diagramHeight), dpi=100)
fig.subplots_adjust(bottom=0.2)
ax = fig.add_subplot(111)
clusterColors = { 'hthor': 'blue', 'thor': 'red', 'roxie': 'magenta'}
dataPoints = 0
for cluster in sorted(self.clusterTrends):
# Plot the data
dataPoints = min(self.numOfRuns[cluster], thirtyDays)
dates2 = self.createDateSeries(self.clusterTrends[cluster]['Dates'][-dataPoints:], dataPoints)
dataPoints = len(dates2)
dataSet = self.clusterTrends[cluster]['Totals'][-dataPoints:]
ax.plot_date(dates2, dataSet, label=cluster, linestyle = '--', color=clusterColors[cluster])
# plot the trend
clusterTrendLabel = '%s-trend (%0.3f sec/day, alpha:%0.3f, beta:%0.3f)' % ( cluster, self.clusterTrends[cluster]['thirtyDays']['alpha'], self.clusterTrends[cluster]['thirtyDays']['alpha'], self.clusterTrends[cluster]['thirtyDays']['beta'])
x1 = [dates2[0], dates2[-1]]
y1 = [self.clusterTrends[cluster]['thirtyDays']['beta'], self.clusterTrends[cluster]['thirtyDays']['alpha'] * (len(dates2) - 1) + self.clusterTrends[cluster]['thirtyDays']['beta'] ]
ax.plot(x1, y1, label=clusterTrendLabel, marker ='.', linestyle = '-', color=clusterColors[cluster])
# X axis tick and format
dateFmt = mpl.dates.DateFormatter('%Y-%m-%d')
ax.xaxis.set_major_formatter(dateFmt)
daysLoc = mpl.dates.DayLocator()
hoursLoc = mpl.dates.HourLocator(interval=6)
ax.xaxis.set_major_locator(daysLoc)