change interpolation datacache, add string values to graphs [WIP]

This commit is contained in:
Sina Blattmann 2023-05-11 10:49:01 +02:00
parent 06bc9b6b2e
commit 8cecf2885e
6 changed files with 160 additions and 178 deletions

View File

@ -21,7 +21,6 @@ const LogContextProvider = ({ children }: { children: ReactNode }) => {
const [checkedToggles, setCheckedToggles] = useState<ToggleElement | null>( const [checkedToggles, setCheckedToggles] = useState<ToggleElement | null>(
null null
); );
console.log("provider", toggles);
return ( return (
<LogContext.Provider <LogContext.Provider
value={{ value={{

View File

@ -56,7 +56,6 @@ const CheckboxTree = () => {
) => { ) => {
event.stopPropagation(); event.stopPropagation();
}; };
const renderTree = (data: TreeElement[]): ReactNode => { const renderTree = (data: TreeElement[]): ReactNode => {
return data.map((element) => { return data.map((element) => {
const checked = checkedToggles?.[element.id]; const checked = checkedToggles?.[element.id];

View File

@ -15,6 +15,7 @@ import DataCache, { FetchResult } from "../../../dataCache/dataCache";
import { LogContext } from "../../Context/LogContextProvider"; import { LogContext } from "../../Context/LogContextProvider";
import { TreeElement, ToggleElement } from "./CheckboxTree"; import { TreeElement, ToggleElement } from "./CheckboxTree";
import { isDefined } from "../../../dataCache/utils/maybe"; import { isDefined } from "../../../dataCache/utils/maybe";
import { timeStamp } from "console";
export const createTimes = ( export const createTimes = (
range: TimeRange, range: TimeRange,
@ -102,7 +103,6 @@ const ScalarGraph = () => {
setTimeSeries(timeSeries); setTimeSeries(timeSeries);
const toggleValues = timeSeries.find((timeStamp) => timeStamp.value); const toggleValues = timeSeries.find((timeStamp) => timeStamp.value);
if (toggles === null && toggleValues && toggleValues.value) { if (toggles === null && toggleValues && toggleValues.value) {
console.log("toggles inside", toggles);
const treeElements = Object.keys(toggleValues.value) const treeElements = Object.keys(toggleValues.value)
.map((path) => { .map((path) => {
return path return path
@ -121,7 +121,6 @@ const ScalarGraph = () => {
(children, path) => insert(children, path), (children, path) => insert(children, path),
[] as TreeElement[] [] as TreeElement[]
); );
console.log("elements", treeElements);
setToggles(treeElements); setToggles(treeElements);
setCheckedToggles(flattenToggles(treeElements)); setCheckedToggles(flattenToggles(treeElements));
} }
@ -200,6 +199,7 @@ const ScalarGraph = () => {
const renderGraphs = () => { const renderGraphs = () => {
const coordinateTimeSeries = transformToGraphData(timeSeries); const coordinateTimeSeries = transformToGraphData(timeSeries);
console.log("coordinates", coordinateTimeSeries);
const graphCoordinates: GraphCoordinates[] = Object.keys( const graphCoordinates: GraphCoordinates[] = Object.keys(
coordinateTimeSeries coordinateTimeSeries
) )
@ -229,7 +229,7 @@ const ScalarGraph = () => {
autorange: false, autorange: false,
range: range, range: range,
type: "date", type: "date",
mirror: "allticks", showticklabels: true,
}, },
grid: { grid: {
subplots: subplots as any, subplots: subplots as any,
@ -237,24 +237,6 @@ const ScalarGraph = () => {
ygap: 0.1, ygap: 0.1,
}, },
height: graphCoordinates.length * 300, height: graphCoordinates.length * 300,
annotations: [
{
text: "X1/Y1 title",
showarrow: false,
x: 0,
y: 1,
yref: "paper",
yanchor: "bottom",
},
{
text: "X2/Y2 title",
showarrow: false,
x: 0,
y: 1,
yref: "paper",
yanchor: "bottom",
},
],
}} }}
config={{ config={{
modeBarButtonsToRemove: [ modeBarButtonsToRemove: [

View File

@ -2,12 +2,12 @@ import { Maybe } from "yup";
import {Timestamped} from "./types"; import {Timestamped} from "./types";
import { isDefined } from "./utils/maybe"; import { isDefined } from "./utils/maybe";
export type DataRecord = Record<string, number> export type DataRecord = Record<string, number | string>
export type DataPoint = Timestamped<Maybe<DataRecord>> export type DataPoint = Timestamped<Maybe<DataRecord>>
export type RecordSeries = Array<DataPoint> export type RecordSeries = Array<DataPoint>
export type PointSeries = Array<Timestamped<Maybe<number>>> export type PointSeries = Array<Timestamped<Maybe<number| string>>>
export type DataSeries = Array<Maybe<number>> export type DataSeries = Array<Maybe<number| string>>
export function getPoints(recordSeries: RecordSeries, series: keyof DataRecord): PointSeries export function getPoints(recordSeries: RecordSeries, series: keyof DataRecord): PointSeries
{ {

View File

@ -6,164 +6,153 @@ import {createDispatchQueue} from "./promiseQueue";
import { SkipListNode } from "./skipList/skipListNode"; import { SkipListNode } from "./skipList/skipListNode";
import { RecordSeries } from "./data"; import { RecordSeries } from "./data";
import { Maybe, isUndefined } from "./utils/maybe"; import { Maybe, isUndefined } from "./utils/maybe";
import { isNumber, isString } from "./utils/runtimeTypeChecking";
export const FetchResult = {
export const FetchResult =
{
notAvailable: "N/A", notAvailable: "N/A",
tryLater : "Try Later" tryLater: "Try Later",
} as const } as const;
export type FetchResult<T> = export type FetchResult<T> =
| T | T
| typeof FetchResult.notAvailable | typeof FetchResult.notAvailable
| typeof FetchResult.tryLater | typeof FetchResult.tryLater;
function reverseBits(x : number): number function reverseBits(x: number): number {
{
// https://stackoverflow.com/a/60227327/141397 // https://stackoverflow.com/a/60227327/141397
x = (x & 0x55555555) << 1 | (x & 0xAAAAAAAA) >> 1; x = ((x & 0x55555555) << 1) | ((x & 0xaaaaaaaa) >> 1);
x = (x & 0x33333333) << 2 | (x & 0xCCCCCCCC) >> 2; x = ((x & 0x33333333) << 2) | ((x & 0xcccccccc) >> 2);
x = (x & 0x0F0F0F0F) << 4 | (x & 0xF0F0F0F0) >> 4; x = ((x & 0x0f0f0f0f) << 4) | ((x & 0xf0f0f0f0) >> 4);
x = (x & 0x00FF00FF) << 8 | (x & 0xFF00FF00) >> 8; x = ((x & 0x00ff00ff) << 8) | ((x & 0xff00ff00) >> 8);
x = (x & 0x0000FFFF) << 16 | (x & 0xFFFF0000) >> 16; x = ((x & 0x0000ffff) << 16) | ((x & 0xffff0000) >> 16);
return x >>> 0; return x >>> 0;
} }
export default class DataCache<T extends Record<string, number>> {
export default class DataCache<T extends Record<string, number>> private readonly cache: SkipList<Maybe<T>> = new SkipList<Maybe<T>>();
{
private readonly cache: SkipList<Maybe<T>> = new SkipList<Maybe<T>>()
private readonly resolution: TimeSpan; private readonly resolution: TimeSpan;
readonly _fetch: (t: UnixTime) => Promise<FetchResult<T>>; readonly _fetch: (t: UnixTime) => Promise<FetchResult<T>>;
private readonly fetchQueue = createDispatchQueue(6) private readonly fetchQueue = createDispatchQueue(6);
private readonly fetching: Set<number> = new Set<number>() private readonly fetching: Set<number> = new Set<number>();
public readonly gotData: Observable<UnixTime>; public readonly gotData: Observable<UnixTime>;
constructor(fetch: (t: UnixTime) => Promise<FetchResult<T>>, resolution: TimeSpan) constructor(
{ fetch: (t: UnixTime) => Promise<FetchResult<T>>,
resolution: TimeSpan
) {
this._fetch = fetch; this._fetch = fetch;
this.resolution = resolution; this.resolution = resolution;
this.gotData = new Subject<UnixTime>() this.gotData = new Subject<UnixTime>();
} }
public prefetch(times: Array<UnixTime>, clear = true) public prefetch(times: Array<UnixTime>, clear = true) {
{ if (clear) {
if (clear) this.fetching.clear();
{ this.fetchQueue.clear();
this.fetching.clear()
this.fetchQueue.clear()
} }
const timesWithPriority = times.map((time, index) => ({time, priority: reverseBits(index)})) const timesWithPriority = times.map((time, index) => ({
timesWithPriority.sort((x, y) => x.priority - y.priority) time,
priority: reverseBits(index),
}));
timesWithPriority.sort((x, y) => x.priority - y.priority);
for (let i = 0; i < timesWithPriority.length; i++) for (let i = 0; i < timesWithPriority.length; i++) {
{ const time = timesWithPriority[i].time.round(this.resolution);
const time = timesWithPriority[i].time.round(this.resolution)
const t = time.ticks; const t = time.ticks;
const node = this.cache.find(t); const node = this.cache.find(t);
if (node.index !== t) if (node.index !== t) this.fetchData(time);
this.fetchData(time);
} }
} }
public get(timeStamp: UnixTime, fetch = true): Maybe<T> public get(timeStamp: UnixTime, fetch = true): Maybe<T> {
{ const time = timeStamp.round(this.resolution);
const time = timeStamp.round(this.resolution)
const t = time.ticks; const t = time.ticks;
const node = this.cache.find(t); const node = this.cache.find(t);
if (node.index === t) if (node.index === t) return node.value;
return node.value
if (fetch) if (fetch) this.fetchData(time);
this.fetchData(time);
return this.interpolate(node, t) return this.interpolate(node, t);
} }
public getSeries(sampleTimes: UnixTime[]): RecordSeries public getSeries(sampleTimes: UnixTime[]): RecordSeries {
{ this.prefetch(sampleTimes);
this.prefetch(sampleTimes) return sampleTimes.map((time) => ({ time, value: this.get(time, false) }));
return sampleTimes.map(time => ({time, value: this.get(time, false)}))
} }
private interpolate(before: SkipListNode<Maybe<T>>, t: number): Maybe<T> private interpolate(before: SkipListNode<Maybe<T>>, t: number): Maybe<T> {
{ const dataBefore = before.value;
const dataBefore = before.value
const after = before.next[0]; const after = before.next[0];
const dataAfter = after.value const dataAfter = after.value;
if (isUndefined(dataBefore) && isUndefined(dataAfter)) if (isUndefined(dataBefore) && isUndefined(dataAfter)) return undefined;
return undefined
if (isUndefined(dataBefore)) if (isUndefined(dataBefore)) return dataAfter;
return dataAfter
if (isUndefined(dataAfter)) if (isUndefined(dataAfter)) return dataBefore;
return dataBefore
const p = t - before.index const p = t - before.index;
const n = after.index - t const n = after.index - t;
const pn = p + n const pn = p + n;
let interpolated: Partial<Record<string, number>> = {} let interpolated: Partial<Record<string, number>> = {};
//What about string nodes? like Alarms //What about string nodes? like Alarms
for (const k of Object.keys(dataBefore)) for (const k of Object.keys(dataBefore)) {
{ interpolated[k] = isNumber(dataBefore[k])
interpolated[k] = (dataBefore[k] * n + dataAfter[k] * p) / pn ? (dataBefore[k] * n + dataAfter[k] * p) / pn
: n < p
? dataAfter[k]
: dataBefore[k];
} }
return interpolated as T return interpolated as T;
} }
private fetchData(time: UnixTime) private fetchData(time: UnixTime) {
{
const t = time.ticks; const t = time.ticks;
if (this.fetching.has(t)) // we are already fetching t if (this.fetching.has(t))
return // we are already fetching t
return;
const fetchTask = () => const fetchTask = () => {
{ const onSuccess = (data: FetchResult<T>) => {
const onSuccess = (data: FetchResult<T>) => if (data === FetchResult.tryLater) {
{ console.warn(FetchResult.tryLater);
if (data === FetchResult.tryLater) return;
{
console.warn(FetchResult.tryLater)
return
} }
const value = data === FetchResult.notAvailable ? undefined : data; const value = data === FetchResult.notAvailable ? undefined : data;
this.cache.insert(value, t) this.cache.insert(value, t);
}
const onFailure = (_: unknown) =>
{
console.error(time.ticks + " FAILED!") // should not happen
}
const dispatch = () =>
{
this.fetching.delete(time.ticks);
(this.gotData as Subject<UnixTime>).next(time);
}
return this._fetch(time)
.then(d => onSuccess(d), f => onFailure(f))
.finally(() => dispatch())
}; };
this.fetching.add(t) const onFailure = (_: unknown) => {
console.error(time.ticks + " FAILED!"); // should not happen
};
const dispatch = () => {
this.fetching.delete(time.ticks);
(this.gotData as Subject<UnixTime>).next(time);
};
return this._fetch(time)
.then(
(d) => onSuccess(d),
(f) => onFailure(f)
)
.finally(() => dispatch());
};
this.fetching.add(t);
this.fetchQueue.dispatch(() => fetchTask()); this.fetchQueue.dispatch(() => fetchTask());
} }
} }

View File

@ -1,6 +1,4 @@
import { Datum, TypedArray } from "plotly.js"; import { Datum, TypedArray } from "plotly.js";
import { RecordSeries } from "../dataCache/data";
import { isDefined } from "../dataCache/utils/maybe";
export const mergeDeep = (...objects: any[]) => { export const mergeDeep = (...objects: any[]) => {
const isObject = (obj: GraphCoordinates) => obj && typeof obj === "object"; const isObject = (obj: GraphCoordinates) => obj && typeof obj === "object";
@ -36,11 +34,26 @@ export interface GraphData {
export const parseCsv = (text: string) => { export const parseCsv = (text: string) => {
const y = text const y = text
.split(/\r?\n/) .split(/\r?\n/)
.map((l) => l.split(";")) .filter((split) => split.length > 0)
.filter((fields) => !isNaN(parseFloat(fields[1]))); .map((l) => {
if (l.length === 0) {
console.log("splitting", l, l.split(";"));
}
return l.split(";");
});
console.log("text", y);
/* .filter((fields) => !isNaN(parseFloat(fields[1])));
*/
const x = y const x = y
.map((fields) => ({ [fields[0]]: parseFloat(fields[1]) })) .map((fields) => {
.reduce((acc, current) => ({ ...acc, ...current }), {}); if (typeof fields[1] === "string") {
console.log("if inside", fields, { [fields[0]]: fields[1] });
return { [fields[0]]: fields[1] };
}
console.log("if outside", fields, { [fields[0]]: parseFloat(fields[1]) });
return { [fields[0]]: parseFloat(fields[1]) };
})
.reduce((acc, current) => ({ ...acc, ...current }), {} as any);
return x; return x;
}; };