-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathenergy-chart-options.ts
More file actions
420 lines (397 loc) · 13 KB
/
energy-chart-options.ts
File metadata and controls
420 lines (397 loc) · 13 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
import type { HassConfig } from "home-assistant-js-websocket";
import {
subHours,
differenceInDays,
differenceInMonths,
differenceInCalendarMonths,
differenceInYears,
startOfYear,
addMilliseconds,
startOfMonth,
addYears,
addMonths,
addHours,
startOfDay,
addDays,
subDays,
} from "date-fns";
import type {
CallbackDataParams,
LineSeriesOption,
TopLevelFormatterParams,
} from "echarts/types/dist/shared";
import type { LineDataItemOption } from "echarts/types/src/chart/line/LineSeries";
import type { FrontendLocaleData } from "../../../../../data/translation";
import { formatNumber } from "../../../../../common/number/format_number";
import {
formatDateMonthYear,
formatDateShort,
formatDateVeryShort,
formatDateWeekdayShortDate,
formatDateWeekdayVeryShortDate,
} from "../../../../../common/datetime/format_date";
import { formatTime } from "../../../../../common/datetime/format_time";
import type { ECOption } from "../../../../../resources/echarts/echarts";
import { filterXSS } from "../../../../../common/util/xss";
import type { StatisticPeriod } from "../../../../../data/recorder";
import { getPeriodicAxisLabelConfig } from "../../../../../components/chart/axis-label";
import { getSuggestedPeriod } from "../../../../../data/energy";
export { fillDataGapsAndRoundCaps } from "../../../../../components/chart/round-caps";
/**
* Energy chart data point tuple:
* [0] displayX - bar position (midpoint for sub-daily periods, start otherwise)
* [1] value - the energy value
* [2] originalStart - original period start timestamp, used for tooltips
* [3] rawUnclamped - (optional) raw negative untracked value before clamping
*/
export type EnergyDataPoint = [
displayX: number,
value: number,
originalStart: number,
rawUnclamped?: number,
];
// Number of days of padding when showing time axis in months
const MONTH_TIME_AXIS_PADDING = 5;
export function getSuggestedMax(
period: StatisticPeriod,
end: Date,
noRounding: boolean
): Date {
// Maximum period depends on whether plotting a line chart or discrete bars.
// - For line charts we must be plotting all the way to end of a given period,
// otherwise we cut off the last period of data.
// - For bar charts we need to round down to the start of the final bars period
// to avoid unnecessary padding of the chart.
let suggestedMax = new Date(end);
if (noRounding || period === "5minute") {
return suggestedMax;
}
suggestedMax.setMinutes(0, 0, 0);
if (period === "hour") {
return suggestedMax;
}
// Sometimes around DST we get a time of 0:59 instead of 23:59 as expected.
// Correct for this when showing days/months so we don't get an extra day.
if (suggestedMax.getHours() === 0) {
suggestedMax = subHours(suggestedMax, 1);
}
suggestedMax.setHours(0);
if (period === "day" || period === "week") {
return suggestedMax;
}
// period === month
suggestedMax.setDate(1);
return suggestedMax;
}
function createYAxisLabelFormatter(locale: FrontendLocaleData) {
let previousValue: number | undefined;
return (value: number): string => {
const maximumFractionDigits = Math.max(
1,
-Math.floor(Math.log10(Math.abs(value - (previousValue ?? value) || 1)))
);
previousValue = value;
return formatNumber(value, locale, { maximumFractionDigits });
};
}
export function getCommonOptions(
start: Date,
end: Date,
locale: FrontendLocaleData,
config: HassConfig,
unit?: string,
compareStart?: Date,
compareEnd?: Date,
formatTotal?: (total: number) => string,
detailedDailyData = false
): ECOption {
const suggestedPeriod = getSuggestedPeriod(start, end, detailedDailyData);
const suggestedMax = getSuggestedMax(suggestedPeriod, end, detailedDailyData);
const compare = compareStart !== undefined && compareEnd !== undefined;
const showCompareYear =
compare && start.getFullYear() !== compareStart.getFullYear();
const monthTimeAxis: ECOption = {
xAxis: {
type: "time",
min: subDays(start, MONTH_TIME_AXIS_PADDING),
max: addDays(suggestedMax, MONTH_TIME_AXIS_PADDING),
axisLabel: getPeriodicAxisLabelConfig("month", locale, config),
// For shorter month ranges, force splitting to ensure time axis renders
// as whole month intervals. Limit the number of forced ticks to 6 months
// (so a max calendar difference of 5) to reduce clutter.
splitNumber: Math.min(differenceInCalendarMonths(end, start), 5),
},
};
const normalTimeAxis: ECOption = {
xAxis: {
type: "time",
min: start,
max: suggestedMax,
},
};
const options: ECOption = {
...(suggestedPeriod === "month" ? monthTimeAxis : normalTimeAxis),
yAxis: {
type: "value",
name: unit,
nameGap: 2,
nameTextStyle: {
align: "left",
},
axisLabel: {
formatter: createYAxisLabelFormatter(locale),
},
splitLine: {
show: true,
},
},
grid: {
top: 15,
bottom: 0,
left: 1,
right: 1,
containLabel: true,
},
tooltip: {
trigger: "axis",
formatter: (params: TopLevelFormatterParams): string => {
// trigger: "axis" gives an array of params, but "item" gives a single param
if (Array.isArray(params)) {
const mainItems: CallbackDataParams[] = [];
const compareItems: CallbackDataParams[] = [];
params.forEach((param: CallbackDataParams) => {
if (param.seriesId?.startsWith("compare-")) {
compareItems.push(param);
} else {
mainItems.push(param);
}
});
return [mainItems, compareItems]
.map((items) =>
formatTooltip(
items,
locale,
config,
suggestedPeriod,
compare,
showCompareYear,
unit,
formatTotal
)
)
.filter(Boolean)
.join("<br><br>");
}
return formatTooltip(
[params],
locale,
config,
suggestedPeriod,
compare,
showCompareYear,
unit,
formatTotal
);
},
},
};
return options;
}
function formatTooltip(
params: CallbackDataParams[],
locale: FrontendLocaleData,
config: HassConfig,
suggestedPeriod: string,
compare: boolean | null,
showCompareYear: boolean,
unit?: string,
formatTotal?: (total: number) => string
) {
if (!params[0]?.value) {
return "";
}
// displayX may be shifted from the period start (see EnergyDataPoint);
// originalStart has the real date for display. Gap-filled entries lack it.
const origDate = params.find((p) => p.value?.[2] != null)?.value?.[2];
const date = new Date(origDate ?? params[0].value?.[0]);
let period: string;
if (suggestedPeriod === "month") {
period = `${formatDateMonthYear(date, locale, config)}`;
} else if (suggestedPeriod === "day") {
period = showCompareYear
? formatDateWeekdayShortDate(date, locale, config)
: formatDateWeekdayVeryShortDate(date, locale, config);
} else {
period = `${
compare
? `${(showCompareYear ? formatDateShort : formatDateVeryShort)(date, locale, config)}: `
: ""
}${formatTime(date, locale, config)}`;
if (params[0].componentSubType === "bar") {
period += ` – ${formatTime(addHours(date, 1), locale, config)}`;
}
}
const title = `<h4 style="text-align: center; margin: 0;">${period}</h4>`;
let sumPositive = 0;
let countPositive = 0;
let sumNegative = 0;
let countNegative = 0;
const values = params
.map((param) => {
const y = param.value?.[1] as number;
// A negative 4th element indicates the untracked value was clamped to
// zero — show the original value so users understand the adjustment.
const rawUnclamped = param.value?.[3] as number | undefined;
if (rawUnclamped != null && rawUnclamped < 0) {
const excessFormatted = formatNumber(Math.abs(rawUnclamped), locale, {
maximumFractionDigits: 3,
});
return `${param.marker} Tracked devices exceeded grid consumption by ${excessFormatted} ${unit}`;
}
const value = formatNumber(
y,
locale,
y < 0.1 ? { maximumFractionDigits: 3 } : undefined
);
if (value === "0") {
return false;
}
if (param.componentSubType === "bar") {
if (y > 0) {
sumPositive += y;
countPositive++;
} else {
sumNegative += y;
countNegative++;
}
}
return `${param.marker} ${filterXSS(param.seriesName!)}: <div style="direction:ltr; display: inline;">${value} ${unit}</div>`;
})
.filter(Boolean);
let footer = "";
if (sumPositive !== 0 && countPositive > 1 && formatTotal) {
footer += `<br><b>${formatTotal(sumPositive)}</b>`;
}
if (sumNegative !== 0 && countNegative > 1 && formatTotal) {
footer += `<br><b>${formatTotal(sumNegative)}</b>`;
}
return values.length > 0 ? `${title}${values.join("<br>")}${footer}` : "";
}
function getDatapointX(datapoint: NonNullable<LineSeriesOption["data"]>[0]) {
const item =
datapoint && typeof datapoint === "object" && "value" in datapoint
? datapoint
: { value: datapoint };
return Number(item.value?.[0]);
}
export function fillLineGaps(datasets: LineSeriesOption[]) {
const buckets = Array.from(
new Set(
datasets
.map((dataset) =>
dataset.data!.map((datapoint) => getDatapointX(datapoint))
)
.flat()
)
).sort((a, b) => a - b);
datasets.forEach((dataset) => {
const dataMap = new Map<number, LineDataItemOption>();
dataset.data!.forEach((datapoint) => {
const item: LineDataItemOption =
datapoint && typeof datapoint === "object" && "value" in datapoint
? datapoint
: ({ value: datapoint } as LineDataItemOption);
const x = getDatapointX(datapoint);
if (!Number.isNaN(x)) {
dataMap.set(x, item);
}
});
dataset.data = buckets.map((bucket) => dataMap.get(bucket) ?? [bucket, 0]);
});
return datasets;
}
/**
* Compute the display x-position for an energy bar chart data point.
* For sub-daily periods (hour/5minute), returns the midpoint to center bars
* between ticks. For daily or longer periods, returns the start timestamp.
*/
export function computeStatMidpoint(
start: number,
end: number,
period: string,
compareTransform?: (ts: Date) => Date
): number {
const center = period === "hour" || period === "5minute";
if (!center) {
if (compareTransform) {
return compareTransform(new Date(start)).getTime();
}
return start;
}
if (compareTransform) {
return (
(compareTransform(new Date(start)).getTime() +
compareTransform(new Date(end)).getTime()) /
2
);
}
return (start + end) / 2;
}
export interface UntrackedConsumptionResult {
/** Untracked consumption per timestamp, clamped to >= 0. */
values: Record<number, number>;
/** Raw (unclamped) values for timestamps where the value was negative. */
rawNegatives: Record<number, number>;
}
/**
* Compute untracked energy consumption per timestamp.
*
* For each timestamp in `usedTotal`, subtracts the sum of tracked device
* consumption and clamps the result to zero. Negative untracked values are
* physically impossible — they arise from meter resolution mismatches
* (e.g., integer grid meter vs fractional device sensors).
*
* Returns the clamped values and the raw negative values for timestamps
* where clamping occurred, so callers can surface per-period indicators.
*/
export function computeUntrackedConsumption(
usedTotal: Record<number, number>,
totalDeviceConsumption: Record<number, number>
): UntrackedConsumptionResult {
const values: Record<number, number> = {};
const rawNegatives: Record<number, number> = {};
for (const time of Object.keys(usedTotal)) {
const ts = Number(time);
const raw = usedTotal[ts] - (totalDeviceConsumption[ts] || 0);
if (raw < 0) {
rawNegatives[ts] = raw;
}
values[ts] = Math.max(0, raw);
}
return { values, rawNegatives };
}
export function getCompareTransform(start: Date, compareStart?: Date) {
if (!compareStart) {
return (ts: Date) => ts;
}
const compareYearDiff = differenceInYears(start, compareStart);
if (
compareYearDiff !== 0 &&
start.getTime() === startOfYear(start).getTime()
) {
return (ts: Date) => addYears(ts, compareYearDiff);
}
const compareMonthDiff = differenceInMonths(start, compareStart);
if (
compareMonthDiff !== 0 &&
start.getTime() === startOfMonth(start).getTime()
) {
return (ts: Date) => addMonths(ts, compareMonthDiff);
}
const compareDayDiff = differenceInDays(start, compareStart);
if (compareDayDiff !== 0 && start.getTime() === startOfDay(start).getTime()) {
return (ts: Date) => addDays(ts, compareDayDiff);
}
const compareOffset = start.getTime() - compareStart.getTime();
return (ts: Date) => addMilliseconds(ts, compareOffset);
}