-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
392 lines (390 loc) · 16.3 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Electricity Usage and Tariffs</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/plotly.js/2.0.0/plotly.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
</head>
<body>
<style>
/* Custom CSS for changing file input button color */
.custom-file-input {
color: #fff !important; /* Change the text color */
background-color: #007bff !important; /* Change the background color */
border-color: #007bff !important; /* Change the border color */
}
</style>
<div class="container-fluid">
<div class="alert alert-success" role="alert" id="tariffLoadStatus">
</div>
<h1>Electricity Usage and Tariffs</h1>
<div class="row">
<div class="col-md-6">
<h3>Electricity Usage Data File</h3>
<input type="file" class="form-control custom-file-input" id="usageFile" accept=".csv">
</div>
<hr class="my-4">
</div>
<div class="row">
<div class="col-md-12">
<div id="tariffCostsTable"></div>
</div>
<div class="col-md-12">
<div id="summaryTable"></div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div id="chart"></div>
</div>
</div>
<div class="row">
<div id="accordion">
<div class="card">
<div class="card-header" id="headingSummaryHourTable">
<h5 class="mb-0">
<button class="btn btn-link" type="button" data-bs-toggle="collapse" data-bs-target="#summaryHourTable" aria-expanded="true" aria-controls="summaryHourTable">Usage by hour</button>
</h5>
</div>
<div id="summaryHourTable" class="collapse" aria-labelledby="headingSummaryHourTable" data-bs-parent="#accordion">
<div class="card-body">
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingUsageTable">
<h5 class="mb-0">
<button class="btn btn-link" type="button" data-bs-toggle="collapse" data-bs-target="#usageTable" aria-expanded="true" aria-controls="usageTable">Sample of Electricity Usage Data</button>
</h5>
</div>
<div id="usageTable" class="collapse" aria-labelledby="headingUsageTable" data-bs-parent="#accordion">
<div class="card-body">
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingTariffTable">
<h5 class="mb-0">
<button class="btn btn-link" type="button" data-bs-toggle="collapse" data-bs-target="#tariffTable" aria-expanded="true" aria-controls="tariffTable">Sample of Electricity Tariff Data</button>
</h5>
</div>
<div id="tariffTable" class="collapse" aria-labelledby="headingTariffTable" data-bs-parent="#accordion">
<div class="card-body">
</div>
</div>
</div>
</div>
</div>
</div>
<script>
// Variables to hold parsed CSV data
headingSummaryHourTable.style.display = "none";
headingUsageTable.style.display = "none";
headingTariffTable.style.display = "none";
const usageCSVData = [];
const tariffCSVData = [];
let globalDetailedUsage = [];
let structuredTariffData = [];
// Function to read CSV file
function readCSV(file, callback) {
const reader = new FileReader();
reader.onload = function(e) {
try {
const rows = e.target.result.split('\n');
const data = [];
for(let i = 0; i < rows.length; i++) {
data.push(rows[i].split(','));
}
callback(data);
} catch (error) {
console.error('Error reading CSV file:', error);
}
};
reader.readAsText(file);
}
// Function to display CSV data in a table
function displayCSV(data, targetElement, title) {
let tableHTML = title + '<table class="table table-sm table-bordered table-striped">';
for(let i = 0; i < Math.min(4, data.length); i++) {
const cells = data[i];
if(i === 0) {
tableHTML += '<thead class="thead-lite"><tr>';
for(let j = 0; j < cells.length; j++) {
tableHTML += '<th>' + cells[j] + '</th>';
}
tableHTML += '</tr></thead><tbody>';
} else {
tableHTML += '<tr>';
for(let j = 0; j < cells.length; j++) {
tableHTML += '<td>' + cells[j] + '</td>';
}
tableHTML += '</tr>';
}
}
if(data.length > 5) {
tableHTML += '<tr><td colspan="' + data[0].length + '">...</td></tr>';
}
for(let i = Math.max(3, data.length - 3); i < data.length; i++) {
const cells = data[i];
tableHTML += '<tr>';
for(let j = 0; j < cells.length; j++) {
tableHTML += '<td>' + cells[j] + '</td>';
}
tableHTML += '</tr>';
}
tableHTML += '</tbody></table>';
document.getElementById(targetElement).innerHTML = tableHTML;
}
// Function to create chart using Plotly
function createPlotlyCharts(seriesData) {
const trace = {
x: seriesData.map(data => data.x),
y: seriesData.map(data => data.y),
type: 'bar',
marker: {
color: seriesData.map(data => (data.y < 0 ? '#800080' : '#488fc2'))
}
};
const layout = {
title: 'Electricity Usage Timeline',
xaxis: {
title: 'Timestamp',
type: 'date'
},
yaxis: {
title: 'Usage'
}
};
Plotly.newPlot('chart', [trace], layout);
}
// function to calculate the total cost of electricity usage
function calculateCostsUsingTariff(detailedUsage, tariffData) {
const costByCompanyAndPlan = {};
Object.entries(detailedUsage).forEach(([monthYear, days]) => {
Object.entries(days).forEach(([dayOfWeek, hours]) => {
Object.entries(hours).forEach(([hour, usage]) => {
tariffData.forEach(tariff => {
// Ensure to parse it as an integer since keys from objects are strings
const dayIndex = parseInt(dayOfWeek, 10);
// Skip if the tariff doesn't apply to this day of the week
if(!tariff.days[dayIndex]) return;
const startHour = parseInt(tariff.timeStart.split(':')[0], 10);
const endHour = tariff.timeEnd === "00:00" ? 24 : parseInt(tariff.timeEnd.split(':')[0], 10);
const hourInt = parseInt(hour, 10);
// Adjusted check for time applicability to handle spans that cross midnight
const isTimeApplicable = endHour > startHour ? (hourInt >= startHour && hourInt < endHour) : // For times that don't span midnight
(hourInt >= startHour || hourInt < endHour); // For times that do span midnight
if(isTimeApplicable) {
// Initialize cost structure if not present
if(!costByCompanyAndPlan[tariff.company]) {
costByCompanyAndPlan[tariff.company] = {};
}
if(!costByCompanyAndPlan[tariff.company][tariff.plan]) {
costByCompanyAndPlan[tariff.company][tariff.plan] = {
totalCostImport: 0,
totalCostExport: 0
};
}
// Calculate and add to the total cost for import and export separately
const costImport = usage.import * tariff.consumePrice;
const costExport = usage.export * tariff.exportPrice;
costByCompanyAndPlan[tariff.company][tariff.plan].totalCostImport += costImport;
costByCompanyAndPlan[tariff.company][tariff.plan].totalCostExport += costExport;
}
});
});
});
});
return costByCompanyAndPlan;
}
// Function to display the summarized data on the page
function displaySummary(summaryData) {
let summaryHTML = "<h3>Monthly Summary</h3><table class='table table-sm table-bordered table-striped'>";
summaryHTML += "<thead class='thead-light'><tr><th>Month-Year</th><th>Total Import (kW)</th><th>Total Export (kW)</th></tr></thead><tbody>";
Object.keys(summaryData).forEach(monthYear => {
const {
import: totalImport,
export: totalExport
} = summaryData[monthYear];
summaryHTML += `<tr><td>${monthYear}</td><td>${totalImport.toFixed(2)}</td><td>${totalExport.toFixed(2)}</td></tr>`;
});
summaryHTML += "</tbody></table>";
document.getElementById("summaryTable").innerHTML = summaryHTML; // Ensure you have a div with id="summaryTable"
}
// Function to display tariff costs per plan grouped by company
function displayTariffCosts(groupedData) {
let tableHTML = '<h3>Tariff Costs per Plan Grouped by Company</h3><table class="table table-sm table-bordered table-striped">';
tableHTML += '<thead class="thead-lite"><tr><th>Company</th><th>Plan</th><th>Total Import Cost (€)</th><th>Total Export Revenue (€)</th></tr></thead><tbody>';
Object.entries(groupedData).forEach(([company, plans]) => {
Object.entries(plans).forEach(([plan, costDetails]) => {
const totalCostExport = (costDetails.totalCostExport / 100).toLocaleString('en-US', {
style: 'currency',
currency: 'EUR'
});
const totalCostImport = (costDetails.totalCostImport / 100).toLocaleString('en-US', {
style: 'currency',
currency: 'EUR'
});
tableHTML += `<tr><td>${company}</td><td>${plan}</td><td>${totalCostImport}</td><td>${totalCostExport}</td></tr>`;
});
});
tableHTML += '</tbody></table>';
document.getElementById('tariffCostsTable').innerHTML = tableHTML;
}
function parseUsageData(data) {
const detailedUsage = {};
const summaryByMonth = {};
let seriesData = [];
// Initialize an array to hold kWh totals for each hour, for both import and export
let kWhPerHour = {
import: Array(24).fill(0),
export: Array(24).fill(0)
};
for(let i = 1; i < data.length; i++) {
const row = data[i];
// Skip empty rows or rows that don't have the expected number of columns
if (!row || row.length < 5 || !row[4].trim()) {
continue;
}
const dateTime = moment(row[4], "DD-MM-YYYY HH:mm");
const readValueKWh = parseFloat(row[2]) * 0.5; // Convert kW to kWh for a 30-minute interval
const readType = row[3].includes("Import") ? "import" : "export";
const monthYear = dateTime.format("MM-YYYY");
const dayOfWeek = dateTime.day(); // 0 (Sunday) to 6 (Saturday)
const hourOfDay = dateTime.hour();
// Accumulate detailed usage for cost calculation
if(!detailedUsage[monthYear]) {
detailedUsage[monthYear] = {};
}
if(!detailedUsage[monthYear][dayOfWeek]) {
detailedUsage[monthYear][dayOfWeek] = {};
}
if(!detailedUsage[monthYear][dayOfWeek][hourOfDay]) {
detailedUsage[monthYear][dayOfWeek][hourOfDay] = {
import: 0,
export: 0
};
}
detailedUsage[monthYear][dayOfWeek][hourOfDay][readType] += readValueKWh;
// Accumulate kWh per hour for import/export
kWhPerHour[readType][hourOfDay] += readValueKWh;
// Monthly summary
if(!summaryByMonth[monthYear]) {
summaryByMonth[monthYear] = {
import: 0,
export: 0
};
}
summaryByMonth[monthYear][readType] += readValueKWh;
// Series data for Plotly chart
const plotValue = readType === "export" ? -readValueKWh : readValueKWh;
seriesData.push({
x: dateTime.toDate().getTime(),
y: plotValue
});
}
// Return the accumulated data, including the new kWhPerHour summary
return {
detailedUsage,
summaryByMonth,
seriesData,
kWhPerHour // Include the hourly kWh summary in the returned object
};
}
// Function to display kwh per hour of day
function displayKWhPerHourTable(kWhPerHour) {
let tableHTML = "<h3>Total kWh per Hour of Day</h3>";
tableHTML += "<table class='table table-sm table-bordered table-striped'>";
tableHTML += "<thead class='thead-light'><tr><th>Hour of Day</th><th>Total Import kWh</th><th>Total Export kWh</th></tr></thead>";
tableHTML += "<tbody>";
for(let hour = 0; hour < 24; hour++) {
tableHTML += `<tr><td>${hour}:00 - ${hour + 1}:00</td><td>${kWhPerHour.import[hour].toFixed(2)}</td><td>${kWhPerHour.export[hour].toFixed(2)}</td></tr>`;
}
tableHTML += "</tbody></table>";
document.getElementById("summaryHourTable").innerHTML = tableHTML; // Assume you have a div with id="summaryTable" for this table
}
// Function to fetch tariff data from URL
function fetchTariffFromURL(url, callback) {
fetch(url).then(response => response.text()).then(text => {
// Parse the fetched CSV text
const rows = text.split('\n');
const data = rows.map(row => row.split(','));
callback(data);
// Display success message
document.getElementById('tariffLoadStatus').innerText = 'Tariff data loaded successfully.';
}).catch(error => {
console.error('Error fetching tariff data:', error);
// Display error message
document.getElementById('tariffLoadStatus').innerText = 'Error loading tariff data. Please try again.';
tariffLoadStatus.className = 'alert alert-danger' // Change the alert color to red
});
}
// Function to load tariff data on page load
window.onload = function() {
// Fetch tariff data from the specified URL
//fetchTariffFromURL('https://raw.githubusercontent.com/frankenbubble/HDF_thing/main/tariffs.csv', function(tariffData) {
fetchTariffFromURL('/tariffs.csv', function(tariffData) {
// Process the fetched tariff data
structuredTariffData = tariffData.slice(1).map(row => ({
company: row[0],
plan: row[1],
date: row[2],
timeStart: row[3],
timeEnd: row[4],
band: row[5],
consumePrice: parseFloat(row[6]),
exportPrice: parseFloat(row[7]),
days: row.slice(8, 15).map(day => parseInt(day, 10))
}));
// Display the tariff data
displayCSV(tariffData, 'tariffTable', '<h3>Sample of Electricity Tariff Data</h3>');
headingTariffTable.style.display = "block";
// Check if both globalDetailedUsage and structuredTariffData have data
if(Object.keys(globalDetailedUsage).length > 0 && structuredTariffData.length > 0) {
// Calculate the costs using the detailed usage and structured tariff data
const costsByCompanyAndPlan = calculateCostsUsingTariff(globalDetailedUsage, structuredTariffData);
// Display tariff costs
displayTariffCosts(costsByCompanyAndPlan);
}
});
};
// Event listener for tariff file input
document.getElementById('usageFile').addEventListener('change', function(e) {
const file = e.target.files[0];
if(file) {
readCSV(file, function(data) {
// Clear previous data and add new data
usageCSVData.length = 0;
usageCSVData.push(...data);
// Parse and process the usage data without directly updating the UI
const {
detailedUsage,
summaryByMonth,
seriesData,
kWhPerHour
} = parseUsageData(usageCSVData);
globalDetailedUsage = detailedUsage;
// Now update the UI based on processed data
displayCSV(usageCSVData, 'usageTable', '<h3>Sample of Electricity Usage Data </h3>'); // Display raw usage data in a table
displaySummary(summaryByMonth); // Display the summarized usage data
createPlotlyCharts(seriesData); // Create and display the chart using Plotly
displayKWhPerHourTable(kWhPerHour);
headingSummaryHourTable.style.display = "block";
headingUsageTable.style.display = "block";
// Check if both globalDetailedUsage and structuredTariffData have data
if(Object.keys(globalDetailedUsage).length > 0 && structuredTariffData.length > 0) {
// Calculate the costs using the detailed usage and structured tariff data
const costsByCompanyAndPlan = calculateCostsUsingTariff(globalDetailedUsage, structuredTariffData);
// Assuming you have a function to display these costs
displayTariffCosts(costsByCompanyAndPlan);
}
});
}
});
</script>
</body>
</html>