@milabench/bujang 0.1.16 → 0.1.18

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.
@@ -1,6 +1,6 @@
1
1
  /** Charts of the JSONL data of a job: the chart builder, its Vega-Lite spec, and the chart itself. */
2
2
  import React, { useEffect, useRef, useState } from 'react';
3
- import { Alert, Box } from '@chakra-ui/react';
3
+ import { Alert, Box, HStack, Input, Text } from '@chakra-ui/react';
4
4
  import type { JobData, JobDataField, JobDataRole, OverviewBlock } from '../types';
5
5
  import { useColorMode } from '../hooks/useColorMode';
6
6
 
@@ -140,21 +140,117 @@ export const isDarkPage = () =>
140
140
  typeof document !== 'undefined' &&
141
141
  (document.documentElement.classList.contains('dark') || document.documentElement.dataset.theme === 'dark');
142
142
 
143
+ type Param = { name?: string; value?: unknown; select?: unknown; bind?: { input?: string; options?: unknown; labels?: string[] } };
144
+
145
+ /** The params of a spec with an input. The options of a select can be those of a field of the rows
146
+ * (`options: {field: "epoch"}`), after "all" (null) */
147
+ export const boundParams = (spec: Record<string, unknown>, rows: Record<string, unknown>[], values: Map<string, unknown>): Param[] | undefined => {
148
+ if (!Array.isArray(spec.params)) return undefined;
149
+ return (spec.params as Param[]).map((param) => {
150
+ if (!param.name || !param.bind || typeof param.bind !== 'object' || !param.bind.input) return param;
151
+ let { bind } = param;
152
+ const field = (bind.options as { field?: string } | undefined)?.field;
153
+ let value = values.has(param.name) ? values.get(param.name) : param.value;
154
+ if (typeof field === 'string') {
155
+ const found = [...new Set(rows.map((r) => r[field]).filter((v) => v !== undefined && v !== null))] as (number | string)[];
156
+ found.sort((a, b) => (typeof a === 'number' && typeof b === 'number' ? a - b : String(a).localeCompare(String(b))));
157
+ bind = { ...bind, options: [null, ...found], labels: ['all', ...found.map(String)] };
158
+ if (!found.includes(value as number | string)) value = null;
159
+ }
160
+ return { ...param, bind, value };
161
+ });
162
+ };
163
+
164
+ /** The fields of the x encodings of a spec, those of its layers included */
165
+ const xFields = (spec: unknown, out = new Set<string>()): Set<string> => {
166
+ if (Array.isArray(spec)) spec.forEach((item) => xFields(item, out));
167
+ else if (spec && typeof spec === 'object') {
168
+ const x = (spec as { encoding?: { x?: { field?: unknown } } }).encoding?.x?.field;
169
+ if (typeof x === 'string') out.add(x);
170
+ for (const key of ['layer', 'hconcat', 'vconcat', 'concat', 'spec']) xFields((spec as Record<string, unknown>)[key], out);
171
+ }
172
+ return out;
173
+ };
174
+
175
+ /** The rows without the first `skip` x values of each event of each file. An x the spec computes: their `start`, else their `time` */
176
+ export const skipFirst = <T extends Record<string, unknown>, >(rows: T[], spec: unknown, skip: number): T[] => {
177
+ if (!(skip > 0)) return rows;
178
+ const fields = [...xFields(spec), 'start', 'time'];
179
+ const groups = new Map<string, T[]>();
180
+ rows.forEach((r) => {
181
+ const key = `${r._file ?? ''}|${r.type ?? ''}`;
182
+ const group = groups.get(key);
183
+ if (group) group.push(r); else groups.set(key, [r]);
184
+ });
185
+ const dropped = new Set<T>();
186
+ groups.forEach((group) => {
187
+ const field = fields.find((f) => group.some((r) => typeof r[f] === 'number'));
188
+ if (!field) return;
189
+ const values = [...new Set(group.map((r) => r[field]).filter((v): v is number => typeof v === 'number'))].sort((a, b) => a - b);
190
+ const last = values[Math.min(skip, values.length) - 1];
191
+ group.forEach((r) => { if (typeof r[field] === 'number' && (r[field] as number) <= last) dropped.add(r); });
192
+ });
193
+ return rows.filter((r) => !dropped.has(r));
194
+ };
195
+
196
+ /** The number of first x values a chart leaves out */
197
+ export const SkipInput: React.FC<{ value: number; onChange: (skip: number) => void; onDone?: () => void }> = ({ value, onChange, onDone }) => (
198
+ <HStack gap={1} as="label" title="Leave out the first x values (of each event of each file)">
199
+ <Text fontSize="xs" color="var(--color-text-muted)">skip</Text>
200
+ <Input
201
+ size="2xs"
202
+ w="56px"
203
+ type="number"
204
+ min={0}
205
+ step={1}
206
+ aria-label="First x values left out"
207
+ value={value || ''}
208
+ placeholder="0"
209
+ onChange={(e) => onChange(Math.max(0, Math.floor(Number(e.target.value) || 0)))}
210
+ onBlur={onDone}
211
+ onKeyDown={(e) => { if (e.key === 'Enter') onDone?.(); }}
212
+ />
213
+ </HStack>
214
+ );
215
+
216
+ /** The signals holding the zoom of a spec: those of its interval params bound to the scales (`<param>_<field>`), null: no zoom */
217
+ export const zoomSignals = (spec: Record<string, unknown>): string[] => {
218
+ const encoding = (spec.encoding ?? {}) as Record<string, { field?: string } | undefined>;
219
+ return (Array.isArray(spec.params) ? (spec.params as { name?: string; bind?: unknown; select?: { encodings?: string[] } }[]) : [])
220
+ .filter((p) => p.name && p.bind === 'scales')
221
+ .flatMap((p) => (p.select?.encodings ?? ['x', 'y']).flatMap((channel) => {
222
+ const field = encoding[channel]?.field;
223
+ return field ? [`${p.name}_${field.replace(/\W/g, '_')}`] : [];
224
+ }));
225
+ };
226
+
143
227
  /** A Vega-Lite spec rendered with vega-embed (loaded on first use), `rows` as the dataset "rows" */
144
- export const VegaChart: React.FC<{ spec: Record<string, unknown>; rows: Record<string, unknown>[] }> = ({ spec, rows }) => {
228
+ export const VegaChart: React.FC<{
229
+ spec: Record<string, unknown>;
230
+ rows: Record<string, unknown>[];
231
+ /** where the inputs of the params go, under the chart when absent */
232
+ controls?: HTMLElement | null;
233
+ }> = ({ spec, rows, controls }) => {
145
234
  const ref = useRef<HTMLDivElement>(null);
146
235
  const [error, setError] = useState<string | null>(null);
147
236
  const { colorMode } = useColorMode();
237
+ // what is picked in the inputs of the chart, kept when its rows change
238
+ const picked = useRef(new Map<string, unknown>());
148
239
 
149
240
  useEffect(() => {
150
241
  let cancelled = false;
151
242
  let finalize: (() => void) | undefined;
152
243
  setError(null);
244
+ // one per chart made: an embed that ends too late fills one that is gone
245
+ const inputs = controls ? document.createElement('div') : undefined;
246
+ if (inputs) controls?.replaceChildren(inputs);
153
247
  import('vega-embed')
154
248
  .then(async ({ default: embed }) => {
155
249
  if (cancelled || !ref.current) return;
250
+ const params = boundParams(spec, rows, picked.current);
156
251
  const full = {
157
252
  ...spec,
253
+ ...(params ? { params } : {}),
158
254
  datasets: { ...((spec.datasets as object) || {}), rows },
159
255
  background: 'transparent',
160
256
  };
@@ -163,16 +259,37 @@ export const VegaChart: React.FC<{ spec: Record<string, unknown>; rows: Record<s
163
259
  theme: colorMode === 'dark' || isDarkPage() ? 'dark' : undefined,
164
260
  // canvas: the CSS reset of the page (font: inherit) would restyle the SVG texts Vega measured
165
261
  renderer: 'canvas',
262
+ ...(inputs ? { bind: inputs } : {}),
263
+ });
264
+ if (cancelled) {
265
+ result.finalize();
266
+ return;
267
+ }
268
+ finalize = result.finalize;
269
+ params?.forEach(({ name, bind }) => {
270
+ if (name && bind && typeof bind === 'object' && bind.input) {
271
+ result.view.addSignalListener(name, (_, value) => {
272
+ picked.current.set(name, value);
273
+ // other rows: the zoom on the previous ones would hide them (once the update is over)
274
+ const zoomed = zoomSignals(spec);
275
+ if (!zoomed.length) return;
276
+ window.setTimeout(() => {
277
+ if (cancelled) return;
278
+ zoomed.forEach((signal) => {
279
+ try { result.view.signal(signal, null); } catch { /* not a signal of this chart */ }
280
+ });
281
+ void result.view.runAsync();
282
+ });
283
+ });
284
+ }
166
285
  });
167
- if (cancelled) result.finalize();
168
- else finalize = result.finalize;
169
286
  })
170
287
  .catch((err: unknown) => !cancelled && setError(err instanceof Error ? err.message : String(err)));
171
288
  return () => {
172
289
  cancelled = true;
173
290
  finalize?.();
174
291
  };
175
- }, [spec, rows, colorMode]);
292
+ }, [spec, rows, colorMode, controls]);
176
293
 
177
294
  return (
178
295
  // room for the chart while it loads
@@ -203,6 +320,28 @@ export const filesWithEvent = (files: JobData['files'], event: string): JobData[
203
320
  return files.filter((f) => f.events?.some((e) => events.includes(e.event)));
204
321
  };
205
322
 
323
+ /** The rank of the process that wrote a file: its `rank` field, when all its rows have the same one */
324
+ const rankField = (file: JobData['files'][number]): number | null => {
325
+ for (const e of file.events || []) {
326
+ const field = e.fields.find((f) => f.name === 'rank' && f.type === 'number');
327
+ if (field && field.min !== undefined) return field.min === field.max ? field.min : null;
328
+ }
329
+ return null;
330
+ };
331
+
332
+ /** The rank of each file (null: of none). In a job whose files have a `rank`, the others are told by their name, <name>.<rank>.jsonl */
333
+ export const fileRanks = (files: JobData['files']): Map<string, number | null> => {
334
+ const ranks = new Map(files.map((f) => [f.path, rankField(f)]));
335
+ const known = new Set([...ranks.values()].filter((r) => r !== null));
336
+ files.forEach((f) => {
337
+ const named = /\.(\d+)\.jsonl$/.exec(f.path);
338
+ if (ranks.get(f.path) === null && named && known.has(Number(named[1])) && !f.events?.some((e) => e.fields.some((x) => x.name === 'rank'))) {
339
+ ranks.set(f.path, Number(named[1]));
340
+ }
341
+ });
342
+ return ranks;
343
+ };
344
+
206
345
  /** The fields of `event` (comma separated events) in `files`, merged (counts added, ranges widened, values joined) */
207
346
  export const mergeFields = (files: JobData['files'], event: string): JobDataField[] => {
208
347
  const merged = new Map<string, JobDataField>();