forked from green-coding-solutions/green-metrics-tool
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcharts.js
More file actions
606 lines (532 loc) · 20 KB
/
Copy pathcharts.js
File metadata and controls
606 lines (532 loc) · 20 KB
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
let select_diff_buffer = [];
const addToDiffSelection = (node) => {
select_diff_buffer.push(node.getAttribute('data-run-id'));
return false;
}
const getCompareChartOptions = (legend, series, chart_type='line', x_axis='time', y_axis_name, mark_area=null, graphic=null, comparison_details=null, comparison_identifiers=null) => {
let tooltip_trigger = (chart_type=='line') ? 'axis' : 'item';
let series_count = series.length;
let max = 0
series.forEach(item => {
if(item == undefined) return;
max = Math.max(max, ...item)
})
max = (Math.abs(max) < 1) ? parseFloat((max*1.2).toFixed(5)) : Math.ceil(max*1.2) // max 5 significant digits if < 1
let options = {
tooltip: {
triggerOn: 'click',
formatter: function (params, ticket, callback) {
if(params.componentType != 'series') return; // no overlay for markLine and markArea etc.
if (select_diff_buffer.length > 0) {
window.open(`/compare.html?ids=${select_diff_buffer[0]},${comparison_details[params.seriesIndex][params.dataIndex].run_id}`, '_blank');
select_diff_buffer = [] // reset
return false;
}
const commit_link = getRepoRefUrl(comparison_details[params.seriesIndex][params.dataIndex].repo, 'commit');
const commit_hash = comparison_details[params.seriesIndex][params.dataIndex].commit_hash;
const commit_hash_link = commit_link
? `<a href="${escapeString(commit_link + commit_hash)}" target="_blank">${commit_hash}</a>`
: commit_hash;
return `<strong>${comparison_details[params.seriesIndex][params.dataIndex].name}</strong><br>
run_id: <a href="/stats.html?id=${comparison_details[params.seriesIndex][params.dataIndex].run_id}" target="_blank">${comparison_details[params.seriesIndex][params.dataIndex].run_id}</a><br>
date: ${comparison_details[params.seriesIndex][params.dataIndex].created_at}<br>
value: ${numberFormatter.format(params.value)}<br>
commit_timestamp: ${comparison_details[params.seriesIndex][params.dataIndex].commit_timestamp}<br>
commit_hash: ${commit_hash_link}<br>
gmt_hash: <a href="https://github.com/green-coding-solutions/green-metrics-tool/commit/${comparison_details[params.seriesIndex][params.dataIndex].gmt_hash}" target="_blank">${comparison_details[params.seriesIndex][params.dataIndex].gmt_hash}</a><br>
<br>
👉 <a href="" class="select-diff-run" onClick="return addToDiffSelection(this);" data-run-id="${comparison_details[params.seriesIndex][params.dataIndex].run_id}" target="_blank">Diff with ... (?)</a>
`;
},
},
xAxis: [],
yAxis: [],
areaStyle: {},
grid: [],
series: [],
animation: false,
graphic: graphic,
legend: [],
}
series.forEach((item, index) => {
options.xAxis.push(
{
gridIndex: index,
type: x_axis,
splitLine: {show: false},
name: [legend[index]],
nameLocation: 'center',
axisLabel: {show: false},
}
);
options.yAxis.push(
{
gridIndex: index,
splitLine: {show: true},
max: max,
axisLabel: {show: false},
}
);
options.grid.push(
{
left: `${10 + (90 / series_count) * index}%`,
right: `${100 - (10 + (90 / series_count) * (index+1))}%`,
type: 'value',
bottom: 30,
containLabel: false
}
);
options.legend.push(
{
data: legend[index],
bottom: 0,
show: false,
type: 'scroll',
}
);
let mark_point = {
data: []
};
let data = [null] // default. Used as indicator for missing data
if (series[index] == null) { // whole series to compare is missing. Happens if different metrics where captured
mark_point.data.push({ name: 'Missing', coord: [0, 0], value: 'Missing Data', label: { show: true } })
} else { // single runs have missing metrics. Happens if run ended prematurely in earlier phase or did not run at all
data = series[index]
for (let i = 0; i < series[index].length; i++) {
if (series[index][i] == null) {
mark_point.data.push({ name: 'Missing', coord: [i, 0], value: 'Missing Data', label: { show: true } })
}
}
}
options.series.push(
{
type: chart_type,
data: data,
xAxisIndex: index,
yAxisIndex:index,
markLine: {
precision: 4, // generally annoying that precision is by default 2. Wrong AVG if values are smaller than 0.001 and no autoscaling!
data: [ {type: "average",label: {formatter: "Mean:\n{c}"}}]
},
markPoint: mark_point,
},
);
if (mark_area != null) {
options['series'][index]['markArea'] = {
data: [
[
{ name: mark_area[index].name, yAxis: mark_area[index].top }, // a name in one item is apprently enough ...
{ yAxis: mark_area[index].bottom }
]
]
};
}
})
options.yAxis[0].axisLabel = {show: true};
options.yAxis[0].name = `Unit: [${y_axis_name}]`;
return options;
}
const calculateMA = (series, factor) => {
var result = [];
factor = Math.round(factor)
for (let i = 0, len = series.length; i < len; i++) {
if (i < factor) {
result.push('-');
continue;
}
var sum = 0;
for (let j = 0; j < factor; j++) {
sum += series[i - j].value;
}
result.push(sum / factor);
}
return result;
}
const getLineBarChartOptions = (legend, labels, series, x_axis_name=null, y_axis_name='', x_axis='time', mark_area=null, no_toolbox=false, graphic=null, moving_average=false, show_x_axis_label=true, stddev=false) => {
if(Object.keys(series).length == 0) {
return {graphic: getChartGraphic("No energy reporter active")};
}
let tooltip_trigger = (series[0].type=='line') ? 'axis' : 'item';
if(moving_average) {
legend.push('Moving Average (5)')
series.push({
name: 'Moving Average (5)',
type: 'line',
data: calculateMA(series[0].data, 5),
smooth: true,
lineStyle: {
opacity: 1,
color: 'red'
}
})
}
if(stddev) {
const [ mean, stddev ] = calculateStatistics(series[0].data);
legend.push('Stddev')
series.push({
name: 'Stddev',
type: 'line',
markArea: {
label: {
show: true,
name: "MarkArea",
position: 'top'
},
data: [
[
{ yAxis: mean + stddev, name: `StdDev: ${stddev.toFixed(2)} (${mean !== 0 ? `(${(stddev/mean * 100).toFixed(2)} %)` : 'N/A'}} %)`},
{ yAxis: mean - stddev},
]
],
}
});
}
let options = {
tooltip: { trigger: tooltip_trigger },
grid: {
left: '0%',
right: 70,
bottom: 5,
containLabel: true
},
xAxis: {
name: x_axis_name,
type: x_axis,
splitLine: {show: false},
data: labels,
axisLabel: {
show: show_x_axis_label,
interval: 0,
rotate: -15,
},
},
yAxis: {
name: `Unit: [${y_axis_name}]`,
type: 'value',
splitLine: {show: true}
},
series: series,
animation: false,
graphic: graphic,
legend: {
data: legend,
top: 0,
type: 'scroll'
}
};
if (mark_area != null) {
options['series']['markArea'] = {
data: [
[
{ name: mark_area[0].name, yAxis: mark_area[0].top }, // a name in one item is apprently enough ...
{ yAxis: mark_area[0].bottom }
]
]
}
}
if (no_toolbox == false) {
options['toolbox'] = {
itemSize: 25,
top: 15,
feature: {
dataZoom: {
yAxisIndex: 'none'
},
restore: {}
}
}
}
return options;
}
const getPieChartOptions = (title, data) => {
return {
tooltip: {
trigger: 'item'
},
toolbox: {
show: false,
},
title: {
left: 'center',
text: title
},
series: [
{
name: title,
type: 'pie',
radius: [30, 100],
center: ['50%', '50%'],
roseType: 'radius',
itemStyle: {
borderRadius: 2
},
data: data
}
]
};
}
const getChartGraphic = (text, top = 'center', left= 'center') => {
return graphic = {
type: 'group',
top: top,
left: left,
draggable: true,
children: [
{
type: 'rect',
top: 'center',
left: 'center',
z: 100,
shape: {
height: 20,
width: 250,
},
style: {
fill: 'white',
stroke: '#999',
lineWidth: 2,
shadowBlur: 8,
shadowOffsetX: 3,
shadowOffsetY: 3,
shadowColor: 'rgba(0,0,0,0.3)',
},
},
{
type: 'text',
top: 'center',
left: 'center',
z: 101,
style: {
text: text,
fontSize: 14,
fontWeight: 'bold',
lineDash: [0, 200],
lineDashOffset: 0,
fill: 'black',
stroke: '#000',
lineWidth: 1
}
}
]
}
}
function moveRight(e) {
let el = e.currentTarget.closest(".statistics-chart-card")
const next = el.nextSibling;
if (!next) return;
next.after(el)
window.dispatchEvent(new Event('resize'));
}
function moveToLast(e) {
let el = e.currentTarget.closest(".statistics-chart-card")
const last = el.parentNode.lastChild;
last.after(el)
window.dispatchEvent(new Event('resize'));
}
function moveLeft(e) {
let el = e.currentTarget.closest(".statistics-chart-card")
const previous = el.previousElementSibling;
if (!previous) return;
previous.before(el)
window.dispatchEvent(new Event('resize'));
}
function moveToFirst(e) {
let el = e.currentTarget.closest(".statistics-chart-card")
const first = el.parentNode.childNodes[0];
first.before(el)
window.dispatchEvent(new Event('resize'));
}
function toggleWidth(e) {
let chart = e.currentTarget.closest(".statistics-chart-card")
let icon = e.currentTarget.firstChild
chart.classList.toggle("full-width")
if (chart.classList.contains("full-width"))
{
icon.classList.remove("expand")
icon.classList.add("compress")
}
else
{
icon.classList.remove("compress")
icon.classList.add("expand")
}
window.dispatchEvent(new Event('resize'));
}
function movers(e) {
let icons = e.currentTarget.closest(".content").querySelector('.chart-navigation-icon')
icons.classList.toggle("hide")
}
const createChartContainer = (container, title) => {
const chart_node = document.createElement("div")
chart_node.classList.add("card");
chart_node.classList.add('statistics-chart-card')
chart_node.classList.add('print-page-break')
chart_node.classList.add('ui')
chart_node.innerHTML = `
<div class="content">
<div class="ui left floated chart-title">
${title}
</div>
<div class="ui right floated icon buttons">
<button class="ui button toggle-width"><i class="expand icon toggle-icon"></i></button>
</div>
<div class="ui right floated icon buttons">
<button class="ui button movers"><i class="arrows alternate icon"></i></button>
</div>
<div class="ui right floated icon buttons chart-navigation-icon hide">
<button class="ui button move-first"><i class="angle double left icon"></i></button>
<button class="ui button move-left"><i class="angle left icon"></i></button>
<button class="ui button move-right"><i class="angle right icon"></i></button>
<button class="ui button move-last"><i class="angle double right icon"></i></button>
</div>
<div class="description">
<div class="statistics-chart"></div>
</div>
</div>`;
document.querySelector(container).appendChild(chart_node)
chart_node.querySelector('.toggle-width').addEventListener("click", toggleWidth, false);
chart_node.querySelector('.movers').addEventListener("click", movers, false);
chart_node.querySelector('.move-first').addEventListener("click", moveToFirst, false);
chart_node.querySelector('.move-left').addEventListener("click", moveLeft, false);
chart_node.querySelector('.move-right').addEventListener("click", moveRight, false);
chart_node.querySelector('.move-last').addEventListener("click", moveToLast, false);
return chart_node.querySelector('.statistics-chart');
}
const displayKeyMetricsRadarChart = (legend, labels, data, phase) => {
let chartDom = document.querySelector(`.ui.tab[data-tab='${phase}'] .radar-chart .statistics-chart`);
document.querySelector(`.ui.tab[data-tab='${phase}'] .radar-chart .chart-title`).innerText = RADAR_CHART_TITLE;
let myChart = echarts.init(chartDom);
labels = labels.map((el) => { return {name: el}})
let series = data.map((el, idx) => { return {name: legend[idx], value: el}})
let options = {
legend: {
data: legend,
top: 0,
type: 'scroll',
},
radar: {
shape: 'circle',
indicator: labels,
radius: '70%',
center: ['50%', '55%'], // Adjust the vertical position (y-axis) as needed
},
series: [
{
name: 'TODO',
type: 'radar',
areaStyle: {},
data: series
}
]
};
options && myChart.setOption(options);
// set callback when ever the user changes the viewport
// we need to use jQuery here and not Vanilla JS to not overwrite but add multiple resize callbacks
$(window).on('resize', () => {
myChart.resize();
});
}
const removeKeyMetricsRadarChart = (phase) => {
document.querySelector(`.ui.tab[data-tab='${phase}'] .bar-chart`).classList.add('single')
document.querySelector(`.ui.tab[data-tab='${phase}'] .radar-chart`).remove()
}
const displayKeyMetricsBarChart = (legend, labels, data, phase, unit) => {
let series = data.map((el, idx) => { return {type: "bar", name: legend[idx], data: el}})
let chartDom = document.querySelector(`.ui.tab[data-tab='${phase}'] .bar-chart .statistics-chart`);
document.querySelector(`.ui.tab[data-tab='${phase}'] .bar-chart .chart-title`).innerText = TOP_BAR_CHART_TITLE;
let myChart = echarts.init(chartDom);
let options = getLineBarChartOptions(null, labels, series, null, unit, 'category', null, true);
myChart.setOption(options);
// set callback when ever the user changes the viewport
// we need to use jQuery here and not Vanilla JS to not overwrite but add multiple resize callbacks
$(window).on('resize', () => {
myChart.resize();
});
}
/*
Currently broken and unused, cause pie chart is misleading in suggesting a hidden "total"
*/
const displayKeyMetricsPieChart = () => {
let chartDom = document.querySelector(`.ui.tab[data-tab='${phase}'] .pie-chart`);
let myChart = echarts.init(chartDom);
let options = getPieChartOptions('Energy distribution of measured metrics', data);
myChart.setOption(options);
// set callback when ever the user changes the viewport
// we need to use jQuery here and not Vanilla JS to not overwrite but add multiple resize callbacks
$(window).on('resize', () => {
myChart.resize();
});
}
// TODO
const displayKeyMetricsEmbodiedCarbonChart = (phase) => {
let chartDom = document.querySelector(`.ui.tab[data-tab='${phase}'] .embodied-chart .statistics-chart`);
document.querySelector(`.ui.tab[data-tab='${phase}'] .embodied-chart .chart-title`).innerText = 'Embodied carbon vs. Usage Phase';
let myChart = echarts.init(chartDom);
let series = [
{
name: 'Embodied carbon',
type: 'bar',
emphasis: {
focus: 'series'
},
data: ['N/A']
},
{
name: 'Usage Phase',
type: 'bar',
stack: 'total',
emphasis: {
focus: 'series'
},
data: ['N/A']
}
];
let options = getLineBarChartOptions(null, ['Phases'], series);
myChart.setOption(options);
// set callback when ever the user changes the viewport
// we need to use jQuery here and not Vanilla JS to not overwrite but add multiple resize callbacks
$(window).on('resize', () => {
myChart.resize();
});
}
const displayTotalChart = (legend, labels, data, unit) => {
const chartDom = document.querySelector(`#total-phases-data .bar-chart .statistics-chart`);
document.querySelector(`#total-phases-data .bar-chart .chart-title`).innerText = TOTAL_CHART_BOTTOM_TITLE;
const myChart = echarts.init(chartDom);
const series = [];
for (let key in data) {
const mark_point_data = []
for (let i = 0; i < data[key].length; i++) {
if (data[key][i] == null) {
mark_point_data.push({ name: 'Missing', coord: [i, 0], value: 'Missing Data', label: { show: true } })
}
}
series.push({
name: key,
type: 'bar',
emphasis: {
focus: 'series'
},
data: data[key],
markPoint: {data: mark_point_data}
})
}
const options = getLineBarChartOptions(null, labels, series, null, unit, 'category', null, true)
myChart.setOption(options);
// set callback when ever the user changes the viewport
// we need to use jQuery here and not Vanilla JS to not overwrite but add multiple resize callbacks
$(window).on('resize', () => {
myChart.resize();
});
}
const displayCompareChart = (phase, title, y_axis_name, legend, data, mark_area=null, graphic=null, comparison_details=null, comparison_identifiers=null) => {
const element = createChartContainer(`.ui.tab[data-tab='${phase}'] .compare-chart-container`, title);
const myChart = echarts.init(element);
let options = getCompareChartOptions(legend, data, 'bar', 'category', y_axis_name, mark_area, graphic, comparison_details, comparison_identifiers);
myChart.setOption(options);
// set callback when ever the user changes the viewport
// we need to use jQuery here and not Vanilla JS to not overwrite but add multiple resize callbacks
$(window).on('resize', () => {
myChart.resize();
});
}