ml-time-graph 1.7.2 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/USAGE.md CHANGED
@@ -113,6 +113,25 @@ underneath, add `markers` for points, set `style.line: false` for points only.
113
113
  },
114
114
  }
115
115
 
116
+ // Markers carry their own pen and their own colours — they do NOT inherit the
117
+ // line's stroke width. The line can be thick and the marker outlined thinly,
118
+ // or the other way round.
119
+ {
120
+ name: 'CPU',
121
+ data,
122
+ style: {
123
+ line: { color: '#4285f4', width: 6 },
124
+ markers: {
125
+ type: 'circle', // 13 shapes, see PointStyleType
126
+ size: 5, // radius (or half-width) in px
127
+ stroke: '#1e3a8a', // outline colour; defaults to the line/zone colour
128
+ fill: '#ffffff', // fill colour; defaults to the line/zone colour
129
+ strokeWidth: 1.5, // the marker's own pen, independent of line.width
130
+ threshold: 500, // only draw markers while the series has ≤ n points
131
+ },
132
+ },
133
+ }
134
+
116
135
  // Step + smoothed overlay (multi-line array — same data, both rendered)
117
136
  // Each entry keeps its own shape: the first is the staircase, the second a
118
137
  // smoothed line through the readings. An entry without a `shape` of its own is
@@ -144,6 +163,73 @@ underneath, add `markers` for points, set `style.line: false` for points only.
144
163
  A point with `value: null` (or a slot with `min/max/avg: null`) marks a **gap** — the
145
164
  line breaks there. Multiple y-axes are supported via `yAxisIndex: 0 | 1 | 2 | ...` on the series.
146
165
 
166
+ ### Aggregated series: `showAs`
167
+
168
+ A series whose points are `{ time, min, max, avg, count }` instead of `{ time, value }` is
169
+ *aggregated* — one slot per time bucket, as `aggregateBySlot()` produces. `showAs` decides
170
+ how a slot is drawn, and the two forms are genuinely different pictures:
171
+
172
+ | `showAs` | What is drawn | Per slot |
173
+ | :--- | :--- | :--- |
174
+ | `'minmaxavg'` | Three lines through the min, max and avg of each slot, optionally with a fill between avg and each edge | 3 points on 3 paths |
175
+ | `'band'` | One filled rectangle spanning min→max | 1 `<rect>`, 10 px wide |
176
+
177
+ ```ts
178
+ {
179
+ name: 'Temp',
180
+ showAs: 'minmaxavg',
181
+ data: aggregateBySlot(raw, 'hourly'),
182
+ minColor: '#3b82f6', maxColor: '#ef4444', avgColor: '#64748b',
183
+ avgDashed: true, // default true
184
+ fillToMax: '#ef444433', fillToMin: '#3b82f633',
185
+ fillToMaxHatch: 'classic-diagonal', // optional, per fill
186
+ }
187
+ ```
188
+
189
+ `'band'` has two options of its own — both currently **TypeScript only**: `avgLine: true`
190
+ draws a short average tick inside each slot, and `countOpacity: true` makes a slot's opacity
191
+ proportional to its `count`, so a slot backed by two readings looks fainter than one backed
192
+ by thirty.
193
+
194
+ **`'minmaxavg'` is exactly three ordinary series.** Measured: the three paths have the same
195
+ geometry, character for character, as three plain series carrying the min, max and avg
196
+ values — `tests/series/minmaxavg_drei_serien.test.ts` proves it. What the aggregated form
197
+ adds is bookkeeping, not drawing: one legend entry instead of three, one series key for all
198
+ three paths (`…-min-line-0`, `-max-line-0`, `-avg-line-0`), `avgDashed` on by default, and
199
+ the two envelope fills in one line each.
200
+
201
+ So reach for three plain series when you want them to behave as three — separate legend
202
+ entries, separate toggling, separate axes. Reach for `showAs: 'minmaxavg'` when they are one
203
+ measurement seen three ways.
204
+
205
+ The envelope fills can be rebuilt too, since 1.8.0: a `FillBound` also takes
206
+ `{ series: '<id or name>' }`, so a region can span the gap between two curves.
207
+
208
+ ```ts
209
+ series: [
210
+ { name: 'Max', data: max },
211
+ { name: 'Avg', data: avg, style: { fill: { regions: [
212
+ { from: 'series', to: { series: 'Max' }, fill: '#ef444433' },
213
+ ] } } },
214
+ ]
215
+ ```
216
+
217
+ The referenced curve is interpolated onto *this* series' timestamps, so the two need not
218
+ share a sampling rate. Where it has no value — a gap, or a time outside its own range — the
219
+ area **stops**, exactly as a line stops at a gap: continuing would assert a distance to a
220
+ reading nobody took. An unknown series name is an error naming the series, not a silently
221
+ missing fill.
222
+
223
+ This is useful well beyond rebuilding a band: a tolerance corridor, target against actual,
224
+ two sensors compared.
225
+
226
+ `'band'` has no such equivalent either: a rectangle per slot is not a line through the slots.
227
+
228
+ All three sit one under the other in the demo gallery under *Main Demos* — the aggregated
229
+ series, the same data as three plain series, and the same data again as a band. They all
230
+ carry an `outside-left` legend, which is where the difference shows: one entry against
231
+ three. (It also shifts the plot — an outside legend reserves width by its widest label.)
232
+
147
233
  ## Thresholds (incident analysis)
148
234
 
149
235
  Define named thresholds once and reference them from a series:
@@ -355,6 +441,24 @@ both get one; leave it out and there is none. (Before 1.5.1 the Go port drew a g
355
441
  nothing was configured while the TypeScript side drew none — the same JSON gave two
356
442
  different charts.)
357
443
 
444
+ ### Room at the edge — `padding`
445
+
446
+ The computed domain ends exactly at the smallest and largest reading, and the plot
447
+ is clipped to its rectangle. A line of `width: 10` at the maximum loses half its
448
+ stroke; a marker loses half its disc. `padding` keeps the automatic domain and adds
449
+ room around it:
450
+
451
+ ```ts
452
+ axes: { left: { padding: 8 } } // both sides
453
+ axes: { left: { padding: { top: 24, bottom: 4 } } } // room for a label on top
454
+ ```
455
+
456
+ In **pixels**, not a share of the range — the cause is in pixels (`line.width`,
457
+ `markers.size`), so the same number works for a series in °C and one in kW. Half the
458
+ widest stroke plus a little is a good rule of thumb. An explicit `domain` is left
459
+ alone, and padding that does not fit the chart height is ignored rather than
460
+ producing an inverted scale.
461
+
358
462
  ### Multi-Axis Layout (N Stacked Y-Axes)
359
463
 
360
464
  To support 3 or more vertical axes (or arbitrary left/right positioning), define `axes.y: YAxisConfig[]` and assign series using `yAxisIndex`:
@@ -417,6 +521,42 @@ If `locale` is omitted it defaults to `navigator.language` in the browser and
417
521
  `'en-US'` server-side, with an internal fallback to `en-US` when the requested
418
522
  locale is unavailable in the runtime's ICU data.
419
523
 
524
+ ### Time zone
525
+
526
+ The locale decides *how* a time is written. `timeZone` decides **which** time is
527
+ written — an IANA name:
528
+
529
+ ```ts
530
+ new MLTimeGraph({
531
+ locale: 'de-DE',
532
+ timeZone: 'Europe/Berlin', // or 'UTC', 'Asia/Kolkata', …
533
+ series: [/* … */],
534
+ });
535
+ ```
536
+
537
+ Omit it and the machine's zone applies, which is the behaviour up to 1.8.1 and stays the
538
+ default so nothing changes for callers who never thought about it. **Think about it once,
539
+ though**, because a browser sits in the reader's zone and a server almost always in UTC: the
540
+ *same* JSON then labels the same reading with different times depending on where it was
541
+ drawn. For a renderer whose point is that one call serves both, that is the one place the
542
+ promise leaks. The nightly PDF and the dashboard beside it should not disagree about when an
543
+ excursion happened.
544
+
545
+ Only the labels depend on it. Tick **positions** are epoch arithmetic and never move.
546
+
547
+ The zone is handled by `Intl` (TypeScript) and `time.Location` (Go), so daylight saving,
548
+ historical shifts and half-hour zones come out right — `Asia/Kolkata` is `UTC+05:30`, not a
549
+ rounded hour. The Go port embeds the zone database (`time/tzdata`, ~0.4 MB), so it also works
550
+ in a `scratch` or distroless image that ships no `/usr/share/zoneinfo`.
551
+
552
+ An unknown name is reported rather than silently ignored: `Intl` throws in TypeScript, and in
553
+ Go `models.ValidateOptions` — which both the CLI and the HTTP server call before drawing —
554
+ returns an error naming the zone.
555
+
556
+ ```go
557
+ opts.TimeZone = "Europe/Berlin" // pkg/models, JSON key: "timeZone"
558
+ ```
559
+
420
560
  A custom `axes.x.format` takes precedence over locale formatting — you receive
421
561
  the raw `Date` and own the output entirely:
422
562
 
@@ -431,6 +571,52 @@ Value (Y) axes are numeric; for locale-aware number formatting use their
431
571
  `format` with `Intl.NumberFormat`, e.g.
432
572
  `format: (v) => new Intl.NumberFormat('de-DE').format(v)`.
433
573
 
574
+ ## Fonts
575
+
576
+ Every text in the chart carries an explicit `font-family`:
577
+
578
+ ```xml
579
+ <text x="52" y="364" text-anchor="end" font-size="11"
580
+ font-family="Liberation Sans, Arial, Helvetica, sans-serif" fill="#777">
581
+ ```
582
+
583
+ Until 1.8.3 the SVG said nothing about fonts, so the viewer picked its own —
584
+ and the same chart had different label widths in a browser, in an email client
585
+ and in a rasteriser. That is the opposite of what a DOM-free renderer is for.
586
+
587
+ The default stack is chosen for **metric compatibility**, not for looks:
588
+ Liberation Sans was designed with the same advance widths as Arial. Linux lands
589
+ on Liberation, Windows and macOS on Arial or Helvetica, and the labels occupy
590
+ the same space. A stack built on DejaVu Sans would not do that — it is
591
+ noticeably wider, and labels would collide differently.
592
+
593
+ A CSS stack *is* "use it if installed, otherwise ours"; no extra mechanism is
594
+ needed. Override it per chart:
595
+
596
+ ```ts
597
+ new MLTimeGraph({
598
+ fontFamily: 'Corporate Sans, Liberation Sans, Arial, sans-serif',
599
+ series: [/* … */],
600
+ });
601
+ ```
602
+
603
+ **It does not change the layout.** The library never *measures* text — it
604
+ renders DOM-free, and label positions come from anchors and `text-anchor`, not
605
+ from glyph widths. Naming a font changes what the viewer draws, not where the
606
+ anchors sit. A much wider house font will therefore collide differently; that
607
+ is your call to make. (The legend reserves its width from a rough estimate of
608
+ `0.6 em` per character, identical in both libraries — see the backlog for the
609
+ measurement work.)
610
+
611
+ When rasterising to PNG you can drop the font flag, because the SVG names it
612
+ itself:
613
+
614
+ ```bash
615
+ resvg --skip-system-fonts \
616
+ --use-font-file /usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf \
617
+ --width 1200 chart.svg chart.png
618
+ ```
619
+
434
620
  ## Gaps
435
621
 
436
622
  Per-series gaps (the line just breaks at `value: null`) plus chart-level
@@ -469,6 +655,34 @@ new MLTimeGraph({
469
655
  `gaps:` accepts either the structured `GapsConfig` (preferred) or a plain
470
656
  `Gap[]` array for shorthand chart-level regions.
471
657
 
658
+ ### Where a gap starts and ends
659
+
660
+ There are two ways to say "no reading here", and they mean the same thing:
661
+
662
+ - the point carries `value: null`, or
663
+ - the row is simply absent from `data`.
664
+
665
+ `autoDetect` finds both. It measures from the **last point that carries a
666
+ value to the next one that does**, and marks a gap when that span exceeds
667
+ `minGapMs`. The same threshold breaks the line, so the band and the break
668
+ always cover the same stretch — if they did not, the marking would say "data
669
+ missing here" while the curve drew straight through it.
670
+
671
+ Mark a region by hand and you should use the same boundaries: the last real
672
+ measurement and the next one, **not** the first and last null. The period
673
+ nobody knows anything about begins with the last reading taken:
674
+
675
+ ```ts
676
+ // data[10] has a value, data[11..14] are null, data[15] has a value again
677
+ gaps: [{ startTime: data[10].time, endTime: data[15].time, label: 'Sensor offline' }]
678
+ ```
679
+
680
+ Two notes. A `value: null` always breaks the line, whatever `minGapMs` says —
681
+ you stated there is no reading, and the threshold only governs what gets a
682
+ band. And a gap band's default fill is white at 15% opacity, which is
683
+ invisible on a white chart; `style: 'dashed_border'` draws the edges you can
684
+ actually see, or give the region its own `fill`.
685
+
472
686
  ## Statistic overlays
473
687
 
474
688
  Computed at render time from the series' raw data; each overlay has its own
@@ -493,8 +707,67 @@ style and appears as a sub-element on top of the parent series.
493
707
  Supported overlay kinds: `'movingAverage'`, `'movingMkt'` (USP <1079.2>),
494
708
  `'stdDevBand'` (mean ± multiplier·σ band), `'limits'`.
495
709
 
710
+ `type: 'exponential'` on a `movingAverage` switches to an exponentially weighted mean over
711
+ the same **time** window: `alpha = 1 - exp(-Δt / window)`. Not the textbook `2/(N+1)` form,
712
+ which assumes an even sampling rate — sensor data rarely has one, and after a gap the
713
+ reading before it would otherwise still weigh as much as the one right before. Here the
714
+ weight decays with elapsed *time*; at an even rate the two coincide.
715
+
716
+ ### Computing an overlay yourself
717
+
718
+ An overlay is a convenience, not a second implementation. The same numbers come out of the
719
+ public helpers, so you can compute the series before rendering and pass it as an ordinary
720
+ one:
721
+
722
+ ```ts
723
+ import { rollingMean, rollingMkt, rollingStdDev } from 'ml-time-graph/analyze';
724
+
725
+ const glaettung = rollingMean(data, 4 * 60 * 60_000);
726
+
727
+ new MLTimeGraph({
728
+ series: [
729
+ { name: 'Fridge sensor', data },
730
+ { name: 'Moving average', data: glaettung, style: { line: { color: '#7c3aed' } } },
731
+ ],
732
+ });
733
+ ```
734
+
735
+ This is *proven*, not asserted: `tests/series/overlay_extern.test.ts` renders both ways and
736
+ compares the path geometry character for character.
737
+
738
+ The Go port renders `overlays` too, since 1.8.0, from the same maths in its own public
739
+ package:
740
+
741
+ ```go
742
+ import "gitlab.com/mlc0911/mlctimegraph/go-time-graph/pkg/analyze"
743
+
744
+ geglaettet := analyze.RollingMean(punkte, 4*60*60*1000)
745
+ mkt := analyze.RollingMkt(punkte, 24*60*60*1000, analyze.DefaultActivationEnergy)
746
+ ```
747
+
748
+ `RollingMean`, `RollingEma`, `RollingStdDev`, `RollingMkt`, `StdDev`, `SampleStdDev` and
749
+ `Mkt` are exported from `pkg/analyze` — deliberately, so a caller that only wants the
750
+ numbers (a PDF renderer, a report service) gets them without drawing a chart. They are
751
+ bit-identical to their TypeScript namesakes, down to the order of the summands.
752
+
753
+ > **Windows are in milliseconds** throughout that family. `MovingAvg`
754
+ > (`ml-time-graph/internals`) is the odd one out: it counts *points*, and it renders itself
755
+ > rather than returning data. It predates the rolling family and is kept for callers that
756
+ > want a moving average as a ready `DrawCommand`; for everything else, prefer `rollingMean`
757
+ > / `rollingEma`, which handle uneven sampling and gaps correctly.
758
+
496
759
  ## Aggregation & helpers
497
760
 
761
+ **Why a chart library carries this at all.** None of it is hard maths — a rolling mean is a
762
+ dozen lines. But it is the handful of figures a time series is almost always looked at
763
+ through, and a caller who has to write them again gets a slightly different answer each
764
+ time: a window counted in points here and in milliseconds there, a gap skipped in one place
765
+ and interpolated in another, MKT with someone's own activation energy. Then the smoothed
766
+ line in the nightly PDF and the one on the dashboard disagree, and nobody can say which is
767
+ right. They live here so that both come from the same twelve lines — and they are public so
768
+ that computing them *outside* the chart gives the identical result, which
769
+ `tests/series/overlay_extern.test.ts` checks rather than asserts.
770
+
498
771
  The full analyse companion is at `ml-time-graph/analyze`:
499
772
 
500
773
  ```ts
@@ -503,7 +776,8 @@ import {
503
776
  mkt, rollingMkt, DEFAULT_ACTIVATION_ENERGY,
504
777
  stdDev, sampleStdDev, rollingStdDev,
505
778
  computeLimitExcursions,
506
- MovingAvg, StatsAggregator,
779
+ rollingMean,
780
+ StatsAggregator,
507
781
  } from 'ml-time-graph/analyze';
508
782
 
509
783
  aggregateBySlot(raw, 'hourly'); // min/max/avg per slot
@@ -531,7 +805,7 @@ new MLTimeGraph({
531
805
  annotations: [
532
806
  { type: 'arrow', from: { time: t1, value: 22 }, to: { time: t2, value: 30 }, color: '#7c3aed' },
533
807
  { type: 'label', at: { time: t2, value: 30 }, text: 'Spike', dy: -8 },
534
- { type: 'rect', from: { time: a, value: 20 }, to: { time: b, value: 26 }, fill: '#7c3aed18' },
808
+ { type: 'rect', from: { time: a, value: 20 }, to: { time: b, value: 26 }, fill: '#7c3aed18', hatch: 'classic-diagonal' },
535
809
  { type: 'point', at: { time: t, value: v }, shape: 'circle' },
536
810
  { type: 'line', from: { time: a, value: v }, to: { time: b, value: v }, dash: 'dotted' },
537
811
  ],
@@ -539,6 +813,9 @@ new MLTimeGraph({
539
813
  ```
540
814
 
541
815
  A coordinate is a `DataPointRef` = `{ time, value, axis? }` (`axis` selects the y-scale).
816
+ `dash` takes a variant (`'dashed'` or `'dotted'`), not a raw SVG pattern — a `'5,5'` is
817
+ not rejected, it simply draws a solid line. Give an annotation an `id` and it is wrapped in
818
+ its own group you can style or toggle (see [CSS classes](#css-classes-in-the-svg)).
542
819
 
543
820
  Annotations can also be managed **dynamically** (e.g. on a click). Like `setData`,
544
821
  these update state — re-render afterwards (`renderCommands()` → renderer):
@@ -619,6 +896,126 @@ attachments. For a Node-free backend, the Go port
619
896
  [`go-time-graph`](https://gitlab.com/mlc0911/mlctimegraph/-/tree/main/go-time-graph)
620
897
  renders the same JSON config to identical SVG.
621
898
 
899
+ ## CSS classes in the SVG
900
+
901
+ Every group the renderer emits carries a class, and so do the line and fill paths inside
902
+ a series. The same classes come out of the Go port — a chart styled in the browser looks
903
+ the same when the backend renders it. The
904
+ one exception is marked in the table and explained below.
905
+
906
+ | Class | Element | Contains |
907
+ | :--- | :--- | :--- |
908
+ | `value-axis left` / `value-axis right` | `<g>` | One per value axis: its line, ticks and tick labels. The second word is the axis position. |
909
+ | `time-axis` | `<g>` | The x-axis line, ticks and time labels. |
910
+ | `axis-labels` | `<g>` | The axis *titles* (`axes.<axis>.label`), not the tick labels. |
911
+ | `chart-grid` | `<g>` | Horizontal and vertical grid lines. |
912
+ | `chart-legend` | `<g>` | The SVG legend. The optional HTML legend is your own markup and not affected. |
913
+ | `series series--<slug>` | `<g>` | One per series — line, area, markers and its gaps. See [Slugs](#slugs) below. |
914
+ | `thresholds` | `<g>` | Wraps all threshold lines and zones. |
915
+ | `threshold threshold--<slug>` | `<g>` | One per threshold, inside `.thresholds`. |
916
+ | `threshold-labels` | `<g>` | Wraps all threshold labels. |
917
+ | `threshold-label threshold-label--<slug>` | `<g>` | One per threshold label, inside `.threshold-labels`. |
918
+ | `markers` | `<g>` | Time-based markers (`markers`), with their projection lines. |
919
+ | `gaps` | `<g>` | Chart-wide gap regions (`gaps.regions`). Per-series gaps sit inside their series group. |
920
+ | `highlights` | `<g>` | Time-range highlights (`highlights`). |
921
+ | `annotations` | `<g>` | Wraps all free annotations. |
922
+ | `annotation annotation--<slug>` | `<g>` | One per annotation **that has an `id`** — without one it is drawn bare, with no group. |
923
+ | `annotation-band` | `<g>` | A status/phase band below the plot. |
924
+ | `annotation-band-axis` | `<g>` | That band's own axis line. |
925
+ | `series-line` | `<path>` | A line segment. Not a group — the class sits on the path itself. |
926
+ | `series-fill` | `<path>` | A filled area: a `fill.region`, a min/max/avg band, a zone fill. |
927
+
928
+ The classes are **not namespaced**. If you inline the SVG into a page whose stylesheet
929
+ has a rule like `.series { display: none }`, that rule applies to the chart too. Scope
930
+ your own rules, and check the host page's when a chart comes out wrong.
931
+
932
+ ### Slugs
933
+
934
+ Series and thresholds follow the same rule, and the Go port follows it too:
935
+
936
+ ```
937
+ class suffix = config.id ?? slugify(config.name)
938
+ ```
939
+
940
+ An explicit `id` is taken **verbatim** — you chose it, so you get it back unchanged, and
941
+ it is your job to keep it selector-safe. Without one, the display name is slugified:
942
+ lowercased, accents stripped, every run of non-alphanumerics collapsed to `-`, capped at
943
+ 50 characters, empty → `unnamed`.
944
+
945
+ Annotations differ on both counts: they are grouped only when they carry an `id`, and
946
+ that `id` *is* slugified (`slugify(a.id)`).
947
+
948
+ ```ts
949
+ import { slugify } from 'ml-time-graph';
950
+
951
+ slugify('Temperatur (°C)') // 'temperatur-c' → .series--temperatur-c
952
+ slugify('Warning Low') // 'warning-low' → .threshold--warning-low
953
+ ```
954
+
955
+ `slugify` is exported so you can compute the selector for a name you hold at runtime —
956
+ building a legend with toggles, for instance:
957
+
958
+ ```ts
959
+ const cls = `.series--${slugify(series.name)}`;
960
+ svgRoot.querySelector(cls)?.classList.toggle('is-hidden');
961
+ ```
962
+
963
+ The same slug is also the group's `id` (`#series-temperatur-c`, `#threshold-warning-low`),
964
+ so either handle works.
965
+
966
+ **Inside** a series group the elements carry a different, stable key: `s-<crc32 of the
967
+ name>`, from `seriesKey()` (`ml-time-graph/internals`). It stays the same across renders
968
+ and is identical in both libraries:
969
+
970
+ | Element | `id` |
971
+ | :--- | :--- |
972
+ | A line segment | `s-<key>-line-<n>` — `<n>` counts across the whole series, so a series broken by two data gaps gives `-line-0`, `-line-1`, `-line-2` |
973
+ | A line segment of a layered `line: [...]` | `s-<key>-line-<n>-<layer>` |
974
+ | A fill region | `s-<key>-fill-r<region>-<piece>` — a region that crosses the curve several times draws as several pieces, and the piece number is always present, even when there is only one |
975
+
976
+ ### ids are document-global — classes are not
977
+
978
+ An `id` is unique per *document*, not per chart. Put two charts on one page and their ids
979
+ collide: the same series name yields the same key, so `getElementById('series-temperature')`
980
+ and `#s-38d2a5bb-line-0` find the **first** chart's element, whichever you meant.
981
+
982
+ ```
983
+ one page, two charts, same series → series-temperature ×2
984
+ s-38d2a5bb-line-0 ×2
985
+ ```
986
+
987
+ Classes do not have that problem, which is why the group carries both and the paths inside
988
+ carry `series-line` / `series-fill`. Scope through the container and use the classes:
989
+
990
+ ```css
991
+ #chart-2 .series--temperature { opacity: .3 } /* one series, one chart */
992
+ #chart-2 .series--temperature .series-line { stroke-width: 3 }
993
+ #chart-2 .series-fill { display: none }
994
+ ```
995
+
996
+ There is a second reason to prefer them: a class is something you can *write down*. The
997
+ `id` contains a crc32 of the series name, which you cannot compute without `seriesKey()`
998
+ from `ml-time-graph/internals` — whereas `slugify(name)` is exported precisely so you can
999
+ build `.series--${slugify(name)}` from a name you hold.
1000
+
1001
+ Reach for the `id` when there is one chart in the document, or when you have scoped the
1002
+ lookup yourself (`container.querySelector('#…')` rather than `document.getElementById`).
1003
+
1004
+ ### Provenance
1005
+
1006
+ Every SVG names the library and version that drew it, as the first child of the root:
1007
+
1008
+ ```xml
1009
+ <svg xmlns="http://www.w3.org/2000/svg" width="800" height="400" viewBox="0 0 800 400">
1010
+ <!-- MLTimeGraph 1.8.0 -->
1011
+ ```
1012
+
1013
+ The line is deliberately the same in both libraries — it does not say whether the browser
1014
+ or the server drew the file, because that would break the byte-identical output the two
1015
+ are held to. The version is `VERSION`, exported from the package root and always equal to
1016
+ `version.Version` in the Go port. SVG minifiers strip comments by default; if you need the
1017
+ provenance to survive, keep comments.
1018
+
622
1019
  ## Package exports
623
1020
 
624
1021
  | Import | Contents |
@@ -626,7 +1023,7 @@ renders the same JSON config to identical SVG.
626
1023
  | `ml-time-graph` | The rendering API — `mount`, `MLTimeGraph`, `SVGRenderer`, `attachTooltip`, the legend helpers `getLineStyle` / `drawMarker` / `getHatch`, and all option/data types. |
627
1024
  | `ml-time-graph/analyze` | Statistics companion — `aggregateBySlot`, `downsample`, `detectGaps`, `mkt` / `rollingMkt`, `stdDev`, `StatsAggregator`, … (see [Aggregation](#aggregation--helpers)). |
628
1025
  | `ml-time-graph/interaction` | Optional interaction primitives — `Zoom`, `Minimap`, `Tooltip` (lower-level than `attachTooltip`). |
629
- | `ml-time-graph/internals` | Building blocks for **custom renderers** — the abstract `Renderer`, free render-functions, scales, axis classes, the `DrawCommand` model. |
1026
+ | `ml-time-graph/internals` | Building blocks for **custom renderers** — the abstract `Renderer`, free render-functions, scales, axis classes, the `DrawCommand` model, and `MovingAvg`. |
630
1027
 
631
1028
  ## Renderer
632
1029
 
@@ -289,6 +289,59 @@ declare function sampleStdDev(samples: (number | null)[]): number | null;
289
289
  */
290
290
  declare function rollingStdDev(data: DataPoint[], windowMs: number, sample?: boolean): DataPoint[];
291
291
 
292
+ /*!
293
+ * MLTimeGraph — Copyright (c) 2026 Michael Lechner
294
+ * MIT with Attribution: free use incl. commercial requires visible credit to
295
+ * "Michael Lechner". Commercial license (no attribution) on request. See LICENSE.
296
+ */
297
+
298
+ /**
299
+ * Rolling arithmetic mean over a sliding time window. For each input point at
300
+ * time `t`, emits an output point whose value is the mean of all valid samples
301
+ * in `[t - windowMs, t]`. The output has the same length / timestamps as the
302
+ * input, and the same shape as {@link rollingStdDev} and `rollingMkt`.
303
+ *
304
+ * `data` must be sorted by `time` ascending. `value: null` is skipped; a window
305
+ * without a single valid sample yields `value: null`.
306
+ *
307
+ * Diese Funktion lag bis 1.8.0 als privater Helfer im Overlay-Renderer der
308
+ * Chart-Bibliothek — und damit war die Frage "koennte man das Overlay auch
309
+ * ausserhalb rechnen und als normale Serie uebergeben?" nicht mit Ja zu
310
+ * beantworten: `rollingMkt` und `rollingStdDev` waren oeffentlich, der
311
+ * gleitende Mittelwert nicht. Wer es von aussen versuchte, musste ihn
312
+ * nachbauen und konnte nur hoffen, dieselben Zahlen zu treffen.
313
+ *
314
+ * @param data Sorted input DataPoints.
315
+ * @param windowMs Window length in ms.
316
+ */
317
+ declare function rollingMean(data: DataPoint[], windowMs: number): DataPoint[];
318
+ /**
319
+ * Exponentiell gewichteter gleitender Mittelwert ueber ein ZEITfenster.
320
+ *
321
+ * Das klassische EMA rechnet mit `alpha = 2/(N+1)` und einer Anzahl N von
322
+ * Punkten -- das setzt einen gleichmaessigen Takt voraus. Messreihen aus
323
+ * Sensoren haben den oft nicht: Abstaende schwanken, und nach einer Luecke
324
+ * liegen Stunden zwischen zwei Werten. Mit einer festen Punktzahl zaehlt der
325
+ * Wert vor der Luecke dann genauso schwer wie der davor.
326
+ *
327
+ * Deshalb hier die zeitbasierte Form: `alpha = 1 - exp(-dt / tau)` mit
328
+ * `tau = windowMs`. Das Gewicht eines alten Wertes faellt mit der
329
+ * VERSTRICHENEN ZEIT, nicht mit der Anzahl der Messungen dazwischen, und nach
330
+ * einer langen Luecke faengt die Kurve praktisch beim neuen Wert an. Bei
331
+ * gleichmaessigem Takt `dt` geht sie in das klassische EMA ueber.
332
+ *
333
+ * Gleiche Form wie {@link rollingMean}: gleiche Laenge, gleiche Zeitstempel,
334
+ * `value: null` wird uebersprungen. `data` muss nach `time` aufsteigend
335
+ * sortiert sein.
336
+ *
337
+ * Nicht zu verwechseln mit `MovingAvg.exponential()` in `ml-time-graph`: die
338
+ * nimmt eine Punktzahl und bleibt, was sie ist.
339
+ *
340
+ * @param data Sorted input DataPoints.
341
+ * @param windowMs Zeitkonstante tau in ms.
342
+ */
343
+ declare function rollingEma(data: DataPoint[], windowMs: number): DataPoint[];
344
+
292
345
  /*!
293
346
  * MLTimeGraph — Copyright (c) 2026 Michael Lechner
294
347
  * MIT with Attribution: free use incl. commercial requires visible credit to
@@ -534,4 +587,4 @@ interface F0Opts {
534
587
  */
535
588
  declare function f0Sterilization(data: DataPoint[], opts?: F0Opts): number;
536
589
 
537
- export { type AggregatedPoint, type AggregationConfig, type AggregationMode, type AggregationThresholds, type ComputeLimitsOpts, DEFAULT_ACTIVATION_ENERGY, type DataPoint, type F0Opts, type HotColdSpotsResult, type LimitExcursion, type LimitStats, type LimitStatsPoint, type LongTermInsight, type MktPoint, type NamedSeries, PRODUCT_PROFILES, type PredictOpts, type PredictResult, type ProductConfig, type ProductType, type SensorStat, SeriesProcessor, type SpatialPoint, type StatsAggregatedPoint, StatsAggregator, type StatsResult, type StdDevPoint, type TrendFit, type TrendPoint, aggregateBySlot, aggregateWithStats, analyzeLongTermTrends, computeLimitExcursions, createAggr, currentTrend, detectGaps, downsample, f0Sterilization, hotColdSpots, linearFit, mkt, predictTimeToThreshold, rollingMkt, rollingStdDev, rollingTrend, sampleStdDev, spatialDelta, stdDev, varianceCoefficient };
590
+ export { type AggregatedPoint, type AggregationConfig, type AggregationMode, type AggregationThresholds, type ComputeLimitsOpts, DEFAULT_ACTIVATION_ENERGY, type DataPoint, type F0Opts, type HotColdSpotsResult, type LimitExcursion, type LimitStats, type LimitStatsPoint, type LongTermInsight, type MktPoint, type NamedSeries, PRODUCT_PROFILES, type PredictOpts, type PredictResult, type ProductConfig, type ProductType, type SensorStat, SeriesProcessor, type SpatialPoint, type StatsAggregatedPoint, StatsAggregator, type StatsResult, type StdDevPoint, type TrendFit, type TrendPoint, aggregateBySlot, aggregateWithStats, analyzeLongTermTrends, computeLimitExcursions, createAggr, currentTrend, detectGaps, downsample, f0Sterilization, hotColdSpots, linearFit, mkt, predictTimeToThreshold, rollingEma, rollingMean, rollingMkt, rollingStdDev, rollingTrend, sampleStdDev, spatialDelta, stdDev, varianceCoefficient };
@@ -1,4 +1,4 @@
1
- var E=class{static interpolateDataPoint(n,i,t){return {time:n.time+Math.round(t*(i.time-n.time)),value:(n.value??0)+t*((i.value??0)-(n.value??0))}}static interpolateAggregatedPoint(n,i,t){let a=(e,l)=>e!==null&&l!==null?e+t*(l-e):null;return {time:n.time+t*(i.time-n.time),min:a(n.min,i.min),max:a(n.max,i.max),avg:a(n.avg,i.avg),count:Math.round(n.count+t*(i.count-n.count))}}static getRuns(n,i,t=0){let a=[...n].sort((r,m)=>r.time-m.time),e=[],l=[],u=null;for(let r of a){let m=i(r),o=t>0&&u&&r.time-u.time>t;(m||o)&&l.length&&(e.push(l),l=[]),m||l.push(r),u=r;}return l.length&&e.push(l),e}static splitByBoundaries(n,i,t,a){if(n.length===0)return [];if(i.length===0)return [{data:n,zoneIndex:0,zoneLow:Number.NEGATIVE_INFINITY}];let e=[...i].sort((o,s)=>o-s),l=[],u=o=>o<=0?Number.NEGATIVE_INFINITY:e[o-1],r=o=>{let s=0;for(let f=0;f<e.length&&o>=e[f];f++)s=f+1;return s},m=[n[0]];for(let o=1;o<n.length;o++){let s=n[o-1],f=n[o],g=t(s),d=t(f),p;d>g?p=e.filter(v=>v>g&&v<=d):d<g?p=e.filter(v=>v>=d&&v<g).reverse():p=[];let b=g;for(let v of p){let x=(v-g)/(d-g),h=a(s,f,x);m.push(h);let c=r((b+v)/2);l.push({data:m,zoneIndex:c,zoneLow:u(c)}),m=[h],b=v;}(p.length===0||p[p.length-1]!==d)&&m.push(f);}if(m.length>1){let o=t(m[0]),s=t(m[m.length-1]),f=r((o+s)/2);l.push({data:m,zoneIndex:f,zoneLow:u(f)});}return l}static splitByThreshold(n,i,t,a){let e=this.splitByBoundaries(n,[i],t,a),l={above:[],below:[]};for(let u of e)u.zoneIndex===0?l.below.push(u.data):l.above.push(u.data);return l}},H={pharma_cold:{limitLow:2,limitHigh:8,activationEnergy:83144},pharma_ambient:{limitLow:15,limitHigh:25,activationEnergy:83144},blood:{limitLow:2,limitHigh:6,activationEnergy:83144},food_chilled:{limitLow:0,limitHigh:4},frozen:{limitLow:-40,limitHigh:-18}},D=8.314462618,N=273.15;function y(n,i,t,a=1){let e=i.filter(h=>h.value!==null&&h.value!==void 0&&!Number.isNaN(h.value)).map(h=>h.value);if(!e.length)return {time:n,min:null,max:null,avg:null,mkt:null,deltaMkt:null,stdDev:null,minutesAboveHigh:t?0:null,minutesBelowLow:t?0:null,count:0};let l=1/0,u=-1/0,r=0;for(let h of e)h<l&&(l=h),h>u&&(u=h),r+=h;let m=r/e.length,o=t?0:null,s=t?0:null;if(t)for(let h=0;h<i.length;h++){let c=i[h];if(c.value!==null&&c.value!==void 0){let M=i[h+1],w=(M?M.time-c.time:0)/(1e3*60);c.value>t.limitHigh&&(o+=w),c.value<t.limitLow&&(s+=w);}}let f=0,g=0,d=(t?.activationEnergy??83144)/D;for(let h of e){f+=Math.pow(h-m,2);let c=h+N;g+=Math.exp(-d/c);}let p=f/e.length,b=Math.sqrt(p),v=null,x=null;if(e.length>=a){let h=g/e.length,c=d/-Math.log(h);v=Number((c-N).toFixed(2)),x=Number((v-m).toFixed(2));}return {time:n,min:Number(l.toFixed(2)),max:Number(u.toFixed(2)),avg:Number(m.toFixed(2)),mkt:v,deltaMkt:x,stdDev:Number(b.toFixed(2)),minutesAboveHigh:o!==null?Number(o.toFixed(1)):null,minutesBelowLow:s!==null?Number(s.toFixed(1)):null,count:e.length}}function L(n,i="hourly",t,a,e=1){if(!n.length)return [];let l=i==="hourly"?36e5:i==="daily"?864e5:t??3600*1e3,u=[...n].sort((s,f)=>s.time-f.time),r=[],m=u[0].time,o=[];for(let s of u){for(;s.time-m>=l;)r.push(y(m,o,a,e)),m+=l,o=[];o.push(s);}return r.push(y(m,o,a,e)),r}function S(n,i){let t=1/0,a=-1/0,e=0;for(let u of i)u<t&&(t=u),u>a&&(a=u),e+=u;let l=e/i.length;return {time:n,min:t,max:a,avg:l,count:i.length}}function z(n,i=6e4){if(n.length<2)return [];let t=[...n].sort((e,l)=>e.time-l.time),a=[];for(let e=1;e<t.length;e++)t[e].time-t[e-1].time>i&&a.push({startTime:t[e-1].time,endTime:t[e].time});return a}function B(n){let i=[],t=0,a=0,e=0,l=0;for(let u of n)u.count>0&&(e++,u.minutesAboveHigh&&(t+=u.minutesAboveHigh),u.stdDev&&u.stdDev>a&&(a=u.stdDev),u.deltaMkt&&u.deltaMkt>2&&l++);return e===0?[]:(t>120&&i.push({type:"critical",message:`Kritische Gesamtbelastung: Das Produkt war im gesamten Zeitraum insgesamt ${Math.round(t)} Minuten zu warm.`,metric:"Total Excursion Time"}),l>e*.15&&i.push({type:"warning",message:"Frequent thermal shocks detected. The kinetic temperature deviates strongly from the average (possible regular door openings).",metric:"Delta MKT Instability"}),a>4&&i.push({type:"warning",message:`High instability measured. Maximum standard deviation was ${a}\xB0C. The cooling system controls imprecisely.`,metric:"Standard Deviation Peak"}),i)}function P(n,i){if(n.length<=i)return n;let t=[],a=Math.ceil(n.length/i);t.push(n[0]);for(let e=1;e<n.length;e+=a)t.push(n[Math.min(e,n.length-1)]);return t}function _(n,i="hourly",t){let a={limitLow:t.low,limitHigh:t.high,activationEnergy:t.activationEnergy};return L(n,i,t.interval,a,t.minCountForMkt??1)}var C=class{static compute(n){let i=n.map(r=>r.value).filter(r=>r!==null).sort((r,m)=>r-m);if(i.length===0)return {min:NaN,max:NaN,avg:NaN,mean:NaN,median:NaN,stdDev:NaN,count:0};let t=i.length,a=i.reduce((r,m)=>r+m,0)/t,e=t%2===1?i[Math.floor(t/2)]:(i[t/2-1]+i[t/2])/2,l=i.reduce((r,m)=>r+Math.pow(m-a,2),0)/t,u=Math.sqrt(l);return {min:i[0],max:i[t-1],avg:a,mean:a,median:e,stdDev:u,count:t}}static computeInRange(n,i,t){let a=n.filter(e=>e.time>=i&&e.time<=t);return this.compute(a)}};function q(n,i){let t=typeof n=="number"?n:n.mean,a=typeof n=="number"?i??NaN:n.stdDev;return !Number.isFinite(t)||!Number.isFinite(a)||t===0?null:Math.abs(a/t)*100}var G=83144;function F(n,i=83144){let t=i/8.314,a=0,e=0;for(let u of n)u!==null&&(a+=Math.exp(-t/(u+273.15)),e++);if(e===0)return null;let l=a/e;return t/-Math.log(l)-273.15}function R(n,i,t=83144){let a=new Array(n.length),e=0;for(let l=0;l<n.length;l++){let u=n[l].time,r=u-i;for(;e<l&&n[e].time<r;)e++;let m=n.slice(e,l+1).map(s=>s.value),o=F(m,t);a[l]={time:u,value:o,synthetic:true};}return a}function I(n){let i=0,t=0;for(let l of n)l!==null&&(i+=l,t++);if(t===0)return null;let a=i/t,e=0;for(let l of n){if(l===null)continue;let u=l-a;e+=u*u;}return Math.sqrt(e/t)}function k(n){let i=0,t=0;for(let l of n)l!==null&&(i+=l,t++);if(t<2)return null;let a=i/t,e=0;for(let l of n){if(l===null)continue;let u=l-a;e+=u*u;}return Math.sqrt(e/(t-1))}function V(n,i,t=false){let a=new Array(n.length),e=0,l=t?k:I;for(let u=0;u<n.length;u++){let r=n[u].time,m=r-i;for(;e<u&&n[e].time<m;)e++;let o=n.slice(e,u+1).map(f=>f.value),s=l(o);a[u]={time:r,value:s,synthetic:true};}return a}function K(n,i){let{high:t,low:a}=i,e={msAboveHigh:0,msBelowLow:0,globalMax:null,globalMin:null,excursions:[]},l=null;for(let u=0;u<n.length;u++){let r=n[u];if(r.value===null){l&&(e.excursions.push(l),l=null);continue}(e.globalMax===null||r.value>e.globalMax)&&(e.globalMax=r.value),(e.globalMin===null||r.value<e.globalMin)&&(e.globalMin=r.value);let m=t!==void 0&&r.value>t,o=a!==void 0&&r.value<a,s=m?"above":o?"below":null,f=n[u-1];if(f&&f.value!==null&&s!==null){let g=r.time-f.time;s==="above"?e.msAboveHigh+=g:e.msBelowLow+=g;}if(s===null){l&&(e.excursions.push(l),l=null);continue}l&&l.side===s?(l.endTime=r.time,l.durationMs=l.endTime-l.startTime,(s==="above"&&r.value>l.extremum||s==="below"&&r.value<l.extremum)&&(l.extremum=r.value)):(l&&e.excursions.push(l),l={startTime:r.time,endTime:r.time,side:s,extremum:r.value,durationMs:0});}return l&&e.excursions.push(l),e}function O(n){if(n.length===0)return [];let i=new Map;for(let a of n)for(let e of a.data){if(e.value===null)continue;let l=i.get(e.time);l||(l=[],i.set(e.time,l)),l.push({name:a.name,value:e.value});}let t=[];for(let a of [...i.keys()].sort((e,l)=>e-l)){let e=i.get(a);if(e.length===0){t.push({time:a,min:null,max:null,delta:null,minSensor:null,maxSensor:null});continue}let l=e[0],u=e[0];for(let r=1;r<e.length;r++)e[r].value<l.value&&(l=e[r]),e[r].value>u.value&&(u=e[r]);t.push({time:a,min:l.value,max:u.value,delta:e.length<2?null:u.value-l.value,minSensor:l.name,maxSensor:u.name});}return t}function U(n){let i=[];for(let e of n){let l=0,u=0,r=1/0,m=-1/0;for(let o of e.data)o.value!==null&&(l+=o.value,u++,o.value<r&&(r=o.value),o.value>m&&(m=o.value));u!==0&&i.push({name:e.name,mean:l/u,min:r,max:m,count:u});}if(i.length===0)return {sensors:[],hottest:null,coldest:null,meanDelta:null};let t=i[0],a=i[0];for(let e=1;e<i.length;e++)i[e].mean>t.mean&&(t=i[e]),i[e].mean<a.mean&&(a=i[e]);return {sensors:i,hottest:t,coldest:a,meanDelta:t.mean-a.mean}}function T(n){let i=0,t=0,a=0,e=0,l=0;for(let o of n)o.value!==null&&(i++,t+=o.time,a+=o.value,e+=o.time*o.value,l+=o.time*o.time);if(i<2)return null;let u=i*l-t*t;if(u===0)return null;let r=(i*e-t*a)/u,m=(a-r*t)/i;return {slope:r,intercept:m,n:i}}function A(n,i){if(n.length===0)return null;let t=n[n.length-1].time,a=t-i,e=n.filter(l=>l.time>=a&&l.time<=t);return T(e)}function Y(n,i){let t=[],a=0;for(let e=0;e<n.length;e++){let l=n[e].time,u=l-i;for(;a<n.length&&n[a].time<u;)a++;let r=T(n.slice(a,e+1));t.push({time:l,fit:r});}return t}function W(n,i,t={}){let a=t.lookbackMs??9e5,e=t.side??"either";if(n.length===0)return null;let l=n[n.length-1];if(l.value===null)return null;let u=A(n,a);if(!u||u.slope===0)return null;let r=u.slope>0&&l.value<i,m=u.slope<0&&l.value>i;if(e==="above"&&!r||e==="below"&&!m||e==="either"&&!r&&!m)return null;let o=(i-u.intercept)/u.slope,s=o-l.time;return s<=0?null:{msUntil:s,eta:o,fit:u,currentValue:l.value}}function Z(n,i={}){let t=i.refTempCelsius??121.11,a=i.zValueKelvin??10,e=0;for(let l=0;l<n.length-1;l++){let u=n[l],r=n[l+1];if(u.value===null||r.value===null)continue;let m=(r.time-u.time)/6e4;if(m<=0)continue;let o=Math.pow(10,(u.value-t)/a),s=Math.pow(10,(r.value-t)/a);e+=(o+s)/2*m;}return e}/*!
1
+ var k=class{static interpolateDataPoint(n,u,l){return {time:n.time+Math.round(l*(u.time-n.time)),value:(n.value??0)+l*((u.value??0)-(n.value??0))}}static interpolateAggregatedPoint(n,u,l){let i=(e,t)=>e!==null&&t!==null?e+l*(t-e):null;return {time:n.time+l*(u.time-n.time),min:i(n.min,u.min),max:i(n.max,u.max),avg:i(n.avg,u.avg),count:Math.round(n.count+l*(u.count-n.count))}}static getRuns(n,u,l=0){let i=[...n].sort((r,o)=>r.time-o.time),e=[],t=[],a=null;for(let r of i){let o=u(r),m=l>0&&a&&r.time-a.time>l;(o||m)&&t.length&&(e.push(t),t=[]),o||t.push(r),a=r;}return t.length&&e.push(t),e}static splitByBoundaries(n,u,l,i){if(n.length===0)return [];if(u.length===0)return [{data:n,zoneIndex:0,zoneLow:Number.NEGATIVE_INFINITY}];let e=[...u].sort((m,s)=>m-s),t=[],a=m=>m<=0?Number.NEGATIVE_INFINITY:e[m-1],r=m=>{let s=0;for(let f=0;f<e.length&&m>=e[f];f++)s=f+1;return s},o=[n[0]];for(let m=1;m<n.length;m++){let s=n[m-1],f=n[m],g=l(s),d=l(f),p;d>g?p=e.filter(v=>v>g&&v<=d):d<g?p=e.filter(v=>v>=d&&v<g).reverse():p=[];let b=g;for(let v of p){let x=(v-g)/(d-g),h=i(s,f,x);o.push(h);let c=r((b+v)/2);t.push({data:o,zoneIndex:c,zoneLow:a(c)}),o=[h],b=v;}(p.length===0||p[p.length-1]!==d)&&o.push(f);}if(o.length>1){let m=l(o[0]),s=l(o[o.length-1]),f=r((m+s)/2);t.push({data:o,zoneIndex:f,zoneLow:a(f)});}return t}static splitByThreshold(n,u,l,i){let e=this.splitByBoundaries(n,[u],l,i),t={above:[],below:[]};for(let a of e)a.zoneIndex===0?t.below.push(a.data):t.above.push(a.data);return t}},H={pharma_cold:{limitLow:2,limitHigh:8,activationEnergy:83144},pharma_ambient:{limitLow:15,limitHigh:25,activationEnergy:83144},blood:{limitLow:2,limitHigh:6,activationEnergy:83144},food_chilled:{limitLow:0,limitHigh:4},frozen:{limitLow:-40,limitHigh:-18}},D=8.314462618,N=273.15;function y(n,u,l,i=1){let e=u.filter(h=>h.value!==null&&h.value!==void 0&&!Number.isNaN(h.value)).map(h=>h.value);if(!e.length)return {time:n,min:null,max:null,avg:null,mkt:null,deltaMkt:null,stdDev:null,minutesAboveHigh:l?0:null,minutesBelowLow:l?0:null,count:0};let t=1/0,a=-1/0,r=0;for(let h of e)h<t&&(t=h),h>a&&(a=h),r+=h;let o=r/e.length,m=l?0:null,s=l?0:null;if(l)for(let h=0;h<u.length;h++){let c=u[h];if(c.value!==null&&c.value!==void 0){let M=u[h+1],w=(M?M.time-c.time:0)/(1e3*60);c.value>l.limitHigh&&(m+=w),c.value<l.limitLow&&(s+=w);}}let f=0,g=0,d=(l?.activationEnergy??83144)/D;for(let h of e){f+=Math.pow(h-o,2);let c=h+N;g+=Math.exp(-d/c);}let p=f/e.length,b=Math.sqrt(p),v=null,x=null;if(e.length>=i){let h=g/e.length,c=d/-Math.log(h);v=Number((c-N).toFixed(2)),x=Number((v-o).toFixed(2));}return {time:n,min:Number(t.toFixed(2)),max:Number(a.toFixed(2)),avg:Number(o.toFixed(2)),mkt:v,deltaMkt:x,stdDev:Number(b.toFixed(2)),minutesAboveHigh:m!==null?Number(m.toFixed(1)):null,minutesBelowLow:s!==null?Number(s.toFixed(1)):null,count:e.length}}function A(n,u="hourly",l,i,e=1){if(!n.length)return [];let t=u==="hourly"?36e5:u==="daily"?864e5:l??3600*1e3,a=[...n].sort((s,f)=>s.time-f.time),r=[],o=a[0].time,m=[];for(let s of a){for(;s.time-o>=t;)r.push(y(o,m,i,e)),o+=t,m=[];m.push(s);}return r.push(y(o,m,i,e)),r}function S(n,u){let l=1/0,i=-1/0,e=0;for(let a of u)a<l&&(l=a),a>i&&(i=a),e+=a;let t=e/u.length;return {time:n,min:l,max:i,avg:t,count:u.length}}function z(n,u=6e4){if(n.length<2)return [];let l=[...n].sort((e,t)=>e.time-t.time),i=[];for(let e=1;e<l.length;e++)l[e].time-l[e-1].time>u&&i.push({startTime:l[e-1].time,endTime:l[e].time});return i}function B(n){let u=[],l=0,i=0,e=0,t=0;for(let a of n)a.count>0&&(e++,a.minutesAboveHigh&&(l+=a.minutesAboveHigh),a.stdDev&&a.stdDev>i&&(i=a.stdDev),a.deltaMkt&&a.deltaMkt>2&&t++);return e===0?[]:(l>120&&u.push({type:"critical",message:`Kritische Gesamtbelastung: Das Produkt war im gesamten Zeitraum insgesamt ${Math.round(l)} Minuten zu warm.`,metric:"Total Excursion Time"}),t>e*.15&&u.push({type:"warning",message:"Frequent thermal shocks detected. The kinetic temperature deviates strongly from the average (possible regular door openings).",metric:"Delta MKT Instability"}),i>4&&u.push({type:"warning",message:`High instability measured. Maximum standard deviation was ${i}\xB0C. The cooling system controls imprecisely.`,metric:"Standard Deviation Peak"}),u)}function P(n,u){if(n.length<=u)return n;let l=[],i=Math.ceil(n.length/u);l.push(n[0]);for(let e=1;e<n.length;e+=i)l.push(n[Math.min(e,n.length-1)]);return l}function _(n,u="hourly",l){let i={limitLow:l.low,limitHigh:l.high,activationEnergy:l.activationEnergy};return A(n,u,l.interval,i,l.minCountForMkt??1)}var C=class{static compute(n){let u=n.map(r=>r.value).filter(r=>r!==null).sort((r,o)=>r-o);if(u.length===0)return {min:NaN,max:NaN,avg:NaN,mean:NaN,median:NaN,stdDev:NaN,count:0};let l=u.length,i=u.reduce((r,o)=>r+o,0)/l,e=l%2===1?u[Math.floor(l/2)]:(u[l/2-1]+u[l/2])/2,t=u.reduce((r,o)=>r+Math.pow(o-i,2),0)/l,a=Math.sqrt(t);return {min:u[0],max:u[l-1],avg:i,mean:i,median:e,stdDev:a,count:l}}static computeInRange(n,u,l){let i=n.filter(e=>e.time>=u&&e.time<=l);return this.compute(i)}};function q(n,u){let l=typeof n=="number"?n:n.mean,i=typeof n=="number"?u??NaN:n.stdDev;return !Number.isFinite(l)||!Number.isFinite(i)||l===0?null:Math.abs(i/l)*100}var G=83144;function L(n,u=83144){let l=u/8.314,i=0,e=0;for(let a of n)a!==null&&(i+=Math.exp(-l/(a+273.15)),e++);if(e===0)return null;let t=i/e;return l/-Math.log(t)-273.15}function R(n,u,l=83144){let i=new Array(n.length),e=0;for(let t=0;t<n.length;t++){let a=n[t].time,r=a-u;for(;e<t&&n[e].time<r;)e++;let o=n.slice(e,t+1).map(s=>s.value),m=L(o,l);i[t]={time:a,value:m,synthetic:true};}return i}function E(n){let u=0,l=0;for(let t of n)t!==null&&(u+=t,l++);if(l===0)return null;let i=u/l,e=0;for(let t of n){if(t===null)continue;let a=t-i;e+=a*a;}return Math.sqrt(e/l)}function F(n){let u=0,l=0;for(let t of n)t!==null&&(u+=t,l++);if(l<2)return null;let i=u/l,e=0;for(let t of n){if(t===null)continue;let a=t-i;e+=a*a;}return Math.sqrt(e/(l-1))}function V(n,u,l=false){let i=new Array(n.length),e=0,t=l?F:E;for(let a=0;a<n.length;a++){let r=n[a].time,o=r-u;for(;e<a&&n[e].time<o;)e++;let m=n.slice(e,a+1).map(f=>f.value),s=t(m);i[a]={time:r,value:s,synthetic:true};}return i}function K(n,u){let l=new Array(n.length),i=0;for(let e=0;e<n.length;e++){let t=n[e].time,a=t-u;for(;i<e&&n[i].time<a;)i++;let r=0,o=0;for(let m=i;m<=e;m++){let s=n[m].value;s!==null&&(r+=s,o++);}l[e]={time:t,value:o===0?null:r/o,synthetic:true};}return l}function O(n,u){let l=new Array(n.length),i=null,e=0;for(let t=0;t<n.length;t++){let a=n[t].time,r=n[t].value;if(r===null){l[t]={time:a,value:i,synthetic:true};continue}if(i===null||u<=0)i=r;else {let o=1-Math.exp(-(a-e)/u);i=r*o+i*(1-o);}e=a,l[t]={time:a,value:i,synthetic:true};}return l}function U(n,u){let{high:l,low:i}=u,e={msAboveHigh:0,msBelowLow:0,globalMax:null,globalMin:null,excursions:[]},t=null;for(let a=0;a<n.length;a++){let r=n[a];if(r.value===null){t&&(e.excursions.push(t),t=null);continue}(e.globalMax===null||r.value>e.globalMax)&&(e.globalMax=r.value),(e.globalMin===null||r.value<e.globalMin)&&(e.globalMin=r.value);let o=l!==void 0&&r.value>l,m=i!==void 0&&r.value<i,s=o?"above":m?"below":null,f=n[a-1];if(f&&f.value!==null&&s!==null){let g=r.time-f.time;s==="above"?e.msAboveHigh+=g:e.msBelowLow+=g;}if(s===null){t&&(e.excursions.push(t),t=null);continue}t&&t.side===s?(t.endTime=r.time,t.durationMs=t.endTime-t.startTime,(s==="above"&&r.value>t.extremum||s==="below"&&r.value<t.extremum)&&(t.extremum=r.value)):(t&&e.excursions.push(t),t={startTime:r.time,endTime:r.time,side:s,extremum:r.value,durationMs:0});}return t&&e.excursions.push(t),e}function Y(n){if(n.length===0)return [];let u=new Map;for(let i of n)for(let e of i.data){if(e.value===null)continue;let t=u.get(e.time);t||(t=[],u.set(e.time,t)),t.push({name:i.name,value:e.value});}let l=[];for(let i of [...u.keys()].sort((e,t)=>e-t)){let e=u.get(i);if(e.length===0){l.push({time:i,min:null,max:null,delta:null,minSensor:null,maxSensor:null});continue}let t=e[0],a=e[0];for(let r=1;r<e.length;r++)e[r].value<t.value&&(t=e[r]),e[r].value>a.value&&(a=e[r]);l.push({time:i,min:t.value,max:a.value,delta:e.length<2?null:a.value-t.value,minSensor:t.name,maxSensor:a.name});}return l}function $(n){let u=[];for(let e of n){let t=0,a=0,r=1/0,o=-1/0;for(let m of e.data)m.value!==null&&(t+=m.value,a++,m.value<r&&(r=m.value),m.value>o&&(o=m.value));a!==0&&u.push({name:e.name,mean:t/a,min:r,max:o,count:a});}if(u.length===0)return {sensors:[],hottest:null,coldest:null,meanDelta:null};let l=u[0],i=u[0];for(let e=1;e<u.length;e++)u[e].mean>l.mean&&(l=u[e]),u[e].mean<i.mean&&(i=u[e]);return {sensors:u,hottest:l,coldest:i,meanDelta:l.mean-i.mean}}function T(n){let u=0,l=0,i=0,e=0,t=0;for(let m of n)m.value!==null&&(u++,l+=m.time,i+=m.value,e+=m.time*m.value,t+=m.time*m.time);if(u<2)return null;let a=u*t-l*l;if(a===0)return null;let r=(u*e-l*i)/a,o=(i-r*l)/u;return {slope:r,intercept:o,n:u}}function I(n,u){if(n.length===0)return null;let l=n[n.length-1].time,i=l-u,e=n.filter(t=>t.time>=i&&t.time<=l);return T(e)}function W(n,u){let l=[],i=0;for(let e=0;e<n.length;e++){let t=n[e].time,a=t-u;for(;i<n.length&&n[i].time<a;)i++;let r=T(n.slice(i,e+1));l.push({time:t,fit:r});}return l}function Z(n,u,l={}){let i=l.lookbackMs??9e5,e=l.side??"either";if(n.length===0)return null;let t=n[n.length-1];if(t.value===null)return null;let a=I(n,i);if(!a||a.slope===0)return null;let r=a.slope>0&&t.value<u,o=a.slope<0&&t.value>u;if(e==="above"&&!r||e==="below"&&!o||e==="either"&&!r&&!o)return null;let m=(u-a.intercept)/a.slope,s=m-t.time;return s<=0?null:{msUntil:s,eta:m,fit:a,currentValue:t.value}}function j(n,u={}){let l=u.refTempCelsius??121.11,i=u.zValueKelvin??10,e=0;for(let t=0;t<n.length-1;t++){let a=n[t],r=n[t+1];if(a.value===null||r.value===null)continue;let o=(r.time-a.time)/6e4;if(o<=0)continue;let m=Math.pow(10,(a.value-l)/i),s=Math.pow(10,(r.value-l)/i);e+=(m+s)/2*o;}return e}/*!
2
2
  * MLTimeGraph — Copyright (c) 2026 Michael Lechner
3
3
  * MIT with Attribution: free use incl. commercial requires visible credit to
4
4
  * "Michael Lechner". Commercial license (no attribution) on request. See LICENSE.
@@ -12,4 +12,4 @@ var E=class{static interpolateDataPoint(n,i,t){return {time:n.time+Math.round(t*
12
12
  * MLTimeGraph — Copyright (c) 2026 Michael Lechner
13
13
  * MIT with Attribution: free use incl. commercial requires visible credit to
14
14
  * "Michael Lechner". Commercial license (no attribution) on request. See LICENSE.
15
- */export{G as DEFAULT_ACTIVATION_ENERGY,H as PRODUCT_PROFILES,E as SeriesProcessor,C as StatsAggregator,L as aggregateBySlot,_ as aggregateWithStats,B as analyzeLongTermTrends,K as computeLimitExcursions,S as createAggr,A as currentTrend,z as detectGaps,P as downsample,Z as f0Sterilization,U as hotColdSpots,T as linearFit,F as mkt,W as predictTimeToThreshold,R as rollingMkt,V as rollingStdDev,Y as rollingTrend,k as sampleStdDev,O as spatialDelta,I as stdDev,q as varianceCoefficient};
15
+ */export{G as DEFAULT_ACTIVATION_ENERGY,H as PRODUCT_PROFILES,k as SeriesProcessor,C as StatsAggregator,A as aggregateBySlot,_ as aggregateWithStats,B as analyzeLongTermTrends,U as computeLimitExcursions,S as createAggr,I as currentTrend,z as detectGaps,P as downsample,j as f0Sterilization,$ as hotColdSpots,T as linearFit,L as mkt,Z as predictTimeToThreshold,O as rollingEma,K as rollingMean,R as rollingMkt,V as rollingStdDev,W as rollingTrend,F as sampleStdDev,Y as spatialDelta,E as stdDev,q as varianceCoefficient};