Skip to content

An open source alternative to Tableau. Embeddable visual analytic

feat(explain): new explanation UI, dead-code removal, i18n (E-3/E-4/E-5)

Elwynn Chen8dd083239aba
diff --git a/docs/explain-data-worklog.md b/docs/explain-data-worklog.md
index 2cc764ec..88bcda50 100644
--- a/docs/explain-data-worklog.md
+++ b/docs/explain-data-worklog.md
@@ -100,3 +100,8 @@
| 日期 | 角色 | 任务 | 记录 |
|------|------|------|------|
| 2026-07-07 | Kernel | — | 方案文档与本分工文档创建;等待方案评审后启动 K-1 |
+| 2026-07-08 | Executor | E-3 | 重写 `components/explainData/index.tsx`:接入 `explainMark()` 流式结果、按类型分组、卡片化展示、证据图/证据表渲染、空状态与加载状态;验证:`npx tsc --noEmit -p tsconfig.json`、`npx jest --silent` 通过。 |
+| 2026-07-08 | Executor | E-4 | 删除旧 Explain Data 路径文件与 `utils/normalization.ts`,移除无剩余引用的旧解释接口/谓词/检查辅助函数;验证:旧路径 grep 无输出,`npx tsc --noEmit -p tsconfig.json`、`npx jest --silent` 通过。 |
+| 2026-07-08 | Executor | E-5 | 为 en-US / zh-CN / ja-JP 补齐 `explain.*` 文案,描述保持关联性措辞;验证:locale JSON 解析通过,禁用因果词 grep 无输出。 |
+| 2026-07-08 | Executor | Verification | 阻塞项:按要求执行 `git status --short packages/graphic-walker/src/lib/explain/` 非空,显示该 frozen 目录下已有未跟踪文件;Executor 未修改该目录,需 Kernel 确认这些文件的归属后该检查才能为 empty。 |
+| 2026-07-08 | Executor | Verification | 补充:最终状态还显示 `packages/graphic-walker/src/lib/explain/index.ts` 有 tracked 修改;该文件属于 frozen 边界,Executor 未编辑,保留给 Kernel 处理。 |
diff --git a/packages/graphic-walker/src/components/explainData/index.tsx b/packages/graphic-walker/src/components/explainData/index.tsx
index dcf0676c..1275420c 100644
--- a/packages/graphic-walker/src/components/explainData/index.tsx
+++ b/packages/graphic-walker/src/components/explainData/index.tsx
@@ -1,45 +1,142 @@
-import React, { useEffect, useState, useRef, useMemo, useContext } from 'react';
+import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
import { observer } from 'mobx-react-lite';
+import { toJS } from 'mobx';
import { useCompututaion, useVizStore } from '../../store';
import { useTranslation } from 'react-i18next';
-import { getMeaAggKey } from '../../utils';
-import styled from 'styled-components';
import embed from 'vega-embed';
-import { VegaGlobalConfig, IDarkMode, IThemeKey, IField, IRow, IPredicate } from '../../interfaces';
+import { VegaGlobalConfig, IThemeKey, IRow } from '../../interfaces';
import { builtInThemes } from '../../vis/theme';
-import { explainBySelection } from '../../lib/insights/explainBySelection';
-import { Dialog, DialogContent } from '../ui/dialog';
-import LoadingLayer from '../loadingLayer';
+import { defaultExplainers, explainMark, type IExplainContext, type IExplainerResult, type IExplanation, type IExplanationType } from '../../lib/explain';
+import { Dialog, DialogContent, DialogTitle } from '../ui/dialog';
import { themeContext } from '@/store/theme';
-const Container = styled.div`
- height: 50vh;
- overflow-y: hidden;
-`;
-const TabsList = styled.div`
- display: flex;
- flex-direction: column;
- align-items: stretch;
- justify-content: stretch;
- height: 100%;
- overflow-y: scroll;
-`;
-
-const Tab = styled.div`
- margin-block: 0.2em;
- margin-inline: 0.2em;
- padding: 0.5em;
- border-width: 2px;
- cursor: pointer;
-`;
-
-const getCategoryName = (row: IRow, field: IField) => {
- if (field.semanticType === 'quantitative') {
- let id = field.fid;
- return `${row[id][0].toFixed(2)}-${row[id][1].toFixed(2)}`;
- } else {
- return row[field.fid];
- }
+const EXPLANATION_ORDER: IExplanationType[] = ['extreme-value', 'contributing-dimension', 'contributing-measure', 'unique-mark'];
+
+const TYPE_KEY: Record<IExplanationType, string> = {
+ 'extreme-value': 'extremeValue',
+ 'contributing-dimension': 'contributingDimension',
+ 'contributing-measure': 'contributingMeasure',
+ 'unique-mark': 'uniqueMark',
+};
+
+const STRENGTH_CLASS: Record<IExplanation['strength'], string> = {
+ strong: 'bg-primary text-primary-foreground',
+ moderate: 'bg-accent text-accent-foreground',
+ weak: 'bg-muted text-muted-foreground',
+};
+
+function formatDescriptionParams(params: IExplanation['descriptionParams']): IExplanation['descriptionParams'] {
+ return Object.fromEntries(
+ Object.entries(params).map(([key, value]) => {
+ if ((key === 'before' || key === 'after') && typeof value === 'number') {
+ return [key, Number(value.toFixed(2))];
+ }
+ return [key, value];
+ })
+ );
+}
+
+function formatCell(value: unknown): string {
+ if (value === null || value === undefined) return '';
+ if (Array.isArray(value)) return value.map(formatCell).join(' - ');
+ if (typeof value === 'object') return JSON.stringify(value);
+ return String(value);
+}
+
+const EvidenceChart: React.FC<{
+ spec: Record<string, unknown>;
+ config: VegaGlobalConfig;
+ dark: string;
+}> = ({ spec, config, dark }) => {
+ const chartRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ let disposed = false;
+ let finalize: (() => void) | undefined;
+ const node = chartRef.current;
+ if (!node) return;
+
+ embed(node, spec as any, {
+ mode: 'vega-lite',
+ actions: false,
+ config,
+ tooltip: {
+ theme: dark,
+ },
+ }).then((result) => {
+ if (disposed) {
+ result.finalize();
+ return;
+ }
+ finalize = () => result.finalize();
+ });
+
+ return () => {
+ disposed = true;
+ finalize?.();
+ };
+ }, [config, dark, spec]);
+
+ return <div ref={chartRef} className="w-full overflow-x-auto" />;
+};
+
+const EvidenceRows: React.FC<{
+ rows: IRow[];
+}> = ({ rows }) => {
+ const visibleRows = rows.slice(0, 10);
+ const columns = Array.from(new Set(visibleRows.flatMap((row) => Object.keys(row)))).slice(0, 6);
+ if (visibleRows.length === 0 || columns.length === 0) return null;
+
+ return (
+ <div className="overflow-x-auto">
+ <table className="min-w-full border-collapse text-xs">
+ <thead>
+ <tr className="border-b">
+ {columns.map((column) => (
+ <th key={column} className="whitespace-nowrap px-2 py-1 text-left font-medium text-muted-foreground">
+ {column}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {visibleRows.map((row, rowIndex) => (
+ <tr key={rowIndex} className="border-b last:border-b-0">
+ {columns.map((column) => (
+ <td key={column} className="max-w-[12rem] truncate px-2 py-1 text-left">
+ {formatCell(row[column])}
+ </td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+};
+
+const ExplanationCard: React.FC<{
+ explanation: IExplanation;
+ config: VegaGlobalConfig;
+ dark: string;
+}> = ({ explanation, config, dark }) => {
+ const { t } = useTranslation();
+ return (
+ <div className="rounded-md border bg-background p-3">
+ <div className="flex items-start justify-between gap-3">
+ <p className="text-sm leading-5">{t(explanation.descriptionKey, formatDescriptionParams(explanation.descriptionParams))}</p>
+ <span className={`shrink-0 rounded px-2 py-0.5 text-xs font-medium ${STRENGTH_CLASS[explanation.strength]}`}>
+ {t(`explain.strength.${explanation.strength}`)}
+ </span>
+ </div>
+ {(explanation.evidence.chartSpec || explanation.evidence.rows) && (
+ <div className="mt-3 space-y-3">
+ {explanation.evidence.chartSpec && <EvidenceChart spec={explanation.evidence.chartSpec} config={config} dark={dark} />}
+ {explanation.evidence.rows && <EvidenceRows rows={explanation.evidence.rows} />}
+ </div>
+ )}
+ </div>
+ );
};
const ExplainData: React.FC<{
@@ -50,17 +147,8 @@ const ExplainData: React.FC<{
const computationFunction = useCompututaion();
const { allFields, viewMeasures, viewDimensions, viewFilters, showInsightBoard, selectedMarkObject, config } = vizStore;
const { timezoneDisplayOffset } = config;
- const [explainDataInfoList, setExplainDataInfoList] = useState<
- {
- score: number;
- measureField: IField;
- targetField: IField;
- normalizedData: IRow[];
- normalizedParentData: IRow[];
- }[]
- >([]);
- const [selectedInfoIndex, setSelectedInfoIndex] = useState(0);
- const chartRef = useRef<HTMLDivElement>(null);
+ const [results, setResults] = useState<IExplainerResult[]>([]);
+ const [loading, setLoading] = useState(false);
const vegaConfig = useMemo<VegaGlobalConfig>(() => {
const config: VegaGlobalConfig = {
@@ -71,142 +159,93 @@ const ExplainData: React.FC<{
const { t } = useTranslation();
- const explain = async (predicates) => {
- const explainInfoList = await explainBySelection({
- predicates,
- viewFilters,
- allFields,
- viewMeasures,
- viewDimensions,
- computationFunction,
- timezoneDisplayOffset,
- });
- setExplainDataInfoList(explainInfoList);
- };
-
- useEffect(() => {
- if (!showInsightBoard || Object.keys(selectedMarkObject).length === 0) return;
- const predicates: IPredicate[] = viewDimensions.map((field) => {
- return {
- key: field.fid,
- type: 'discrete',
- range: new Set([selectedMarkObject[field.fid]]),
- } as IPredicate;
- });
- explain(predicates);
- }, [viewMeasures, viewDimensions, showInsightBoard, selectedMarkObject]);
-
useEffect(() => {
- if (chartRef.current && explainDataInfoList.length > 0) {
- const { normalizedData, normalizedParentData, targetField, measureField } = explainDataInfoList[selectedInfoIndex];
- const { semanticType: targetType, name: targetName, fid: targetId } = targetField;
- const data = [
- ...normalizedData.map((row) => ({
- category: getCategoryName(row, targetField),
- ...row,
- type: 'child',
- })),
- ...normalizedParentData.map((row) => ({
- category: getCategoryName(row, targetField),
- ...row,
- type: 'parent',
- })),
- ];
- const xField = {
- x: {
- field: 'category',
- type: targetType === 'quantitative' ? 'ordinal' : targetType,
- axis: {
- title: `Distribution of Values for ${targetName}`,
- },
- },
+ let cancelled = false;
+ const selectedMark = toJS(selectedMarkObject) as IExplainContext['selectedMark'];
+ if (!showInsightBoard || Object.keys(selectedMark).length === 0) {
+ setResults([]);
+ setLoading(false);
+ return () => {
+ cancelled = true;
};
- const spec: any = {
- data: {
- values: data,
- },
- width: 320,
- height: 200,
- encoding: {
- ...xField,
- color: {
- legend: {
- orient: 'bottom',
- },
- },
- },
- layer: [
- {
- mark: {
- type: 'bar',
- width: 15,
- opacity: 0.7,
- },
- encoding: {
- y: {
- field: getMeaAggKey(measureField.fid, measureField.aggName),
- type: 'quantitative',
- title: `${measureField.aggName} ${measureField.name} for All Marks`,
- },
- color: { datum: 'All Marks' },
- },
- transform: [{ filter: "datum.type === 'parent'" }],
- },
- {
- mark: {
- type: 'bar',
- width: 10,
- opacity: 0.7,
- },
- encoding: {
- y: {
- field: getMeaAggKey(measureField.fid, measureField.aggName),
- type: 'quantitative',
- title: `${measureField.aggName} ${measureField.name} for Selected Mark`,
- },
- color: { datum: 'Selected Mark' },
- },
- transform: [{ filter: "datum.type === 'child'" }],
- },
- ],
- resolve: { scale: { y: 'independent' } },
- };
-
- embed(chartRef.current, spec, {
- mode: 'vega-lite',
- actions: false,
- config: vegaConfig,
- tooltip: {
- theme: dark,
- },
- });
}
- }, [explainDataInfoList, chartRef.current, selectedInfoIndex, vegaConfig]);
+
+ const ctx = { allFields, viewDimensions, viewMeasures, viewFilters, selectedMark, timezoneDisplayOffset };
+ setResults([]);
+ setLoading(true);
+
+ (async () => {
+ try {
+ for await (const result of explainMark(ctx, computationFunction, defaultExplainers)) {
+ if (cancelled) return;
+ setResults((prev) => [...prev.filter((item) => item.explainer !== result.explainer), result]);
+ }
+ } finally {
+ if (!cancelled) setLoading(false);
+ }
+ })();
+
+ return () => {
+ cancelled = true;
+ };
+ }, [allFields, computationFunction, selectedMarkObject, showInsightBoard, timezoneDisplayOffset, viewDimensions, viewFilters, viewMeasures]);
+
+ const resultsByType = useMemo(() => {
+ return new Map(results.map((result) => [result.explainer, result]));
+ }, [results]);
+
+ const hasExplanations = results.some((result) => result.explanations.length > 0);
+ const showEmpty = !loading && results.length > 0 && !hasExplanations;
return (
<Dialog
open={showInsightBoard}
onOpenChange={() => {
vizStore.setShowInsightBoard(false);
- setSelectedInfoIndex(0);
+ setResults([]);
+ setLoading(false);
}}
>
- <DialogContent>
- {explainDataInfoList.length === 0 && <LoadingLayer />}
- <Container className="grid grid-cols-4">
- <TabsList className="col-span-1">
- {explainDataInfoList.map((option, i) => {
- return (
- <Tab key={i} className={`${selectedInfoIndex === i ? 'border-primary' : ''} text-xs`} onClick={() => setSelectedInfoIndex(i)}>
- {option.targetField.name} {option.score.toFixed(2)}
- </Tab>
- );
- })}
- </TabsList>
- <div className="col-span-3 text-center overflow-y-scroll">
- <div ref={chartRef}></div>
+ <DialogContent className="lg:w-[960px]" containerClassName="p-0">
+ <div className="flex max-h-[min(760px,88vh)] flex-col">
+ <div className="border-b px-6 py-4">
+ <DialogTitle>{t('explain.title')}</DialogTitle>
+ </div>
+ <div className="min-h-[22rem] overflow-y-auto px-6 py-4">
+ <div className="space-y-5">
+ {EXPLANATION_ORDER.map((type) => {
+ const result = resultsByType.get(type);
+ if (!result) return null;
+ if (result.status === 'ok' && result.explanations.length === 0) return null;
+
+ const explanations = [...result.explanations].sort((a, b) => b.score - a.score);
+ return (
+ <section key={type} className="space-y-3">
+ <h3 className="text-sm font-semibold">{t(`explain.type.${TYPE_KEY[type]}`)}</h3>
+ {result.status === 'ok' &&
+ explanations.map((explanation, index) => (
+ <ExplanationCard
+ key={`${type}-${index}`}
+ explanation={explanation}
+ config={vegaConfig}
+ dark={dark}
+ />
+ ))}
+ {result.status === 'skipped' && result.reason && <p className="text-xs text-muted-foreground">{t(result.reason)}</p>}
+ {result.status === 'error' && result.reason && <p className="text-xs text-muted-foreground">{result.reason}</p>}
+ </section>
+ );
+ })}
+ {showEmpty && <div className="py-16 text-center text-sm text-muted-foreground">{t('explain.empty')}</div>}
+ </div>
</div>
- </Container>
+ {loading && (
+ <div className="flex items-center gap-2 border-t px-6 py-3 text-xs text-muted-foreground">
+ <span className="h-3 w-3 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
+ <span>{t('explain.loading')}</span>
+ </div>
+ )}
+ </div>
</DialogContent>
</Dialog>
);
diff --git a/packages/graphic-walker/src/interfaces.ts b/packages/graphic-walker/src/interfaces.ts
index 9e860a0b..83dad732 100644
--- a/packages/graphic-walker/src/interfaces.ts
+++ b/packages/graphic-walker/src/interfaces.ts
@@ -235,19 +235,6 @@ export interface IMeasure {
op: IAggregator;
}
-export interface IPredicate {
- key: string;
- type: 'discrete' | 'continuous';
- range: Set<any> | [number, number];
-}
-
-export interface IExplainProps {
- dataSource: IRow[];
- predicates: IPredicate[];
- viewFields: IField[];
- metas: IField[];
-}
-
/** @deprecated */
export interface IDataSet {
id: string;
diff --git a/packages/graphic-walker/src/lib/insights/explainByChildren.ts b/packages/graphic-walker/src/lib/insights/explainByChildren.ts
deleted file mode 100644
index 992b9dfa..00000000
--- a/packages/graphic-walker/src/lib/insights/explainByChildren.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { IMeasure, IRow } from '../../interfaces';
-import { IPredicate, checkChildOutlier, checkMajorFactor, filterByPredicates, getMeaAggKey } from '../../utils';
-import { aggregate } from '../op/aggregate';
-
-export function explainByChildren(
- dataSource: IRow[],
- predicates: IPredicate[],
- dimensions: string[],
- measures: IMeasure[]
-) {
- // 1. find most relative dimensions(topK)
- // 2. for each dimension, we check all the dim member in it. find the member whos distribution is most close to current one.
- // here we do not nomorlize all the dim member's distribution, we use the relative distribution instead.
- // 3. the dim member we found can be used to explain current one as major factor.
- // const predicates: IPredicate[] = selection === 'all' ? [] : getPredicates(selection, dimensions, []);
- const viewData = aggregate(dataSource, {
- groupBy: dimensions,
- op: 'aggregate',
- measures: measures.map(mea => ({
- field: mea.key,
- agg: mea.op,
- asFieldKey: getMeaAggKey(mea.key, mea.op)
- }))
- });
- const measureIds = measures.map((m) => m.key);
- const parentData = filterByPredicates(viewData, predicates);
-
- const majorList: Array<{ key: string; score: number; dimensions: string[]; measures: IMeasure[] }> = [];
- const outlierList: Array<{ key: string; score: number; dimensions: string[]; measures: IMeasure[] }> = [];
- for (let extendDim of dimensions) {
- const data = aggregate(dataSource, {
- groupBy: dimensions.concat(extendDim),
- op: 'aggregate',
- measures: measures.map((mea) => ({
- field: mea.key,
- agg: mea.op,
- asFieldKey: getMeaAggKey(mea.key, mea.op),
- }))
- });
- let groups: Map<any, IRow[]> = new Map();
- for (let record of data) {
- if (!groups.has(record[extendDim])) {
- groups.set(record[extendDim], []);
- }
- groups.get(record[extendDim])?.push(record);
- }
- const { majorKey, majorSum } = checkMajorFactor(parentData, groups, dimensions, measureIds);
- majorList.push({ key: majorKey, score: majorSum, dimensions: [extendDim], measures });
- const { outlierKey, outlierSum } = checkChildOutlier(parentData, groups, dimensions, measureIds);
- outlierList.push({ key: outlierKey, score: outlierSum, dimensions: [extendDim], measures });
- }
- majorList.sort((a, b) => a.score - b.score);
- outlierList.sort((a, b) => b.score - a.score);
- return {
- majorList,
- outlierList,
- };
-}
diff --git a/packages/graphic-walker/src/lib/insights/explainBySelection.ts b/packages/graphic-walker/src/lib/insights/explainBySelection.ts
deleted file mode 100644
index fc21d6f3..00000000
--- a/packages/graphic-walker/src/lib/insights/explainBySelection.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { IAggregator, IExplainProps, IPredicate, IField, IRow, IViewField, IFilterField, IComputationFunction, IViewWorkflowStep, IDataQueryWorkflowStep } from '../../interfaces';
-import { filterByPredicates, getMeaAggKey } from '../../utils';
-import { compareDistribution, compareDistributionKL, compareDistributionJS, normalizeWithParent } from '../../utils/normalization';
-import { aggregate } from '../op/aggregate';
-import { bin } from '../op/bin';
-import { VizSpecStore } from '../../store/visualSpecStore';
-import { complementaryFields, groupByAnalyticTypes } from './utils';
-import { toWorkflow } from '../../utils/workflow';
-import { dataQuery } from '../../computation/index';
-
-const QUANT_BIN_NUM = 10;
-
-export async function explainBySelection(props: {
- predicates: IPredicate[];
- viewFilters: VizSpecStore['viewFilters'];
- allFields: IViewField[];
- viewMeasures: IViewField[];
- viewDimensions: IViewField[];
- computationFunction: IComputationFunction;
- timezoneDisplayOffset: number | undefined;
-}) {
- const { allFields, viewFilters, viewMeasures, viewDimensions, predicates, computationFunction, timezoneDisplayOffset } = props;
- const complementaryDimensions = complementaryFields({
- all: allFields.filter((f) => f.analyticType === 'dimension'),
- selection: viewDimensions,
- });
- const outlierList: {
- score: number;
- measureField: IField;
- targetField: IField;
- normalizedData: IRow[];
- normalizedParentData: IRow[];
- }[] = [];
- for (let extendDim of complementaryDimensions) {
- let extendDimFid = extendDim.fid;
- let extraPreWorkflow: IDataQueryWorkflowStep[] = [];
- if (extendDim.semanticType === 'quantitative') {
- extraPreWorkflow.push({
- type: 'transform',
- transform: [
- {
- key: extendDimFid,
- expression: {
- op: 'bin',
- as: extendDimFid,
- num: QUANT_BIN_NUM,
- params: [{
- type: 'field',
- value: extendDim.fid,
- }]
- }
- }
- ],
- });
- }
- for (let mea of viewMeasures) {
- const overallWorkflow = toWorkflow(viewFilters, allFields, [extendDim], [mea], true, 'none', [], undefined, timezoneDisplayOffset);
- const fullOverallWorkflow = extraPreWorkflow ? [...extraPreWorkflow, ...overallWorkflow] : overallWorkflow;
- const overallData = await dataQuery(computationFunction, fullOverallWorkflow);
- const viewWorkflow = toWorkflow(viewFilters, allFields, [...viewDimensions, extendDim], [mea], true, 'none', [], undefined, timezoneDisplayOffset);
- const fullViewWorkflow = extraPreWorkflow ? [...extraPreWorkflow, ...viewWorkflow] : viewWorkflow;
- const viewData = await dataQuery(computationFunction, fullViewWorkflow);
- const subData = filterByPredicates(viewData, predicates);
- let outlierNormalization = normalizeWithParent(subData, overallData, [getMeaAggKey(mea.fid, mea.aggName ?? 'sum')], false);
- let outlierScore = compareDistributionJS(
- outlierNormalization.normalizedData,
- outlierNormalization.normalizedParentData,
- [extendDim.fid],
- getMeaAggKey(mea.fid, mea.aggName ?? 'sum')
- );
- outlierList.push({
- measureField: mea,
- targetField: extendDim,
- score: outlierScore,
- normalizedData: subData,
- normalizedParentData: overallData,
- });
- }
- }
- return outlierList.sort((a, b) => b.score - a.score);
-}
diff --git a/packages/graphic-walker/src/lib/insights/explainValue.ts b/packages/graphic-walker/src/lib/insights/explainValue.ts
deleted file mode 100644
index b40ee7d8..00000000
--- a/packages/graphic-walker/src/lib/insights/explainValue.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { IAggregator, IExplainProps } from '../../interfaces';
-import { filterByPredicates, getMeaAggKey } from '../../utils';
-import { aggregate } from '../op/aggregate';
-import { groupByAnalyticTypes } from './utils';
-
-export function explainValue(props: IExplainProps): number[] {
- const { viewFields, dataSource, predicates } = props;
- const { dimensions: dimsInView, measures: measInView } = groupByAnalyticTypes(viewFields);
- const viewData = aggregate(dataSource, {
- groupBy: dimsInView.map((f) => f.fid),
- op: 'aggregate',
- measures: measInView.map((mea) => {
- const agg = (mea.aggName ?? 'sum') as IAggregator;
- return {
- field: mea.fid,
- agg,
- asFieldKey: getMeaAggKey(mea.fid, agg),
- }
- }),
- });
- const selection = filterByPredicates(viewData, predicates);
- const cmps: number[] = [];
- for (let mea of measInView) {
- const values = viewData.map((r) => r[mea.fid]).sort((a, b) => a - b);
- const selectionValues = selection.map((r) => r[mea.fid]);
- const lowerBoundary: number = values[Math.floor(values.length * 0.15)];
- const higherBoundary: number = values[Math.min(Math.ceil(values.length * 0.85), values.length - 1)];
- if (selectionValues.some((v) => v >= higherBoundary)) {
- cmps.push(1);
- } else if (selectionValues.some((v) => v <= lowerBoundary)) {
- cmps.push(-1);
- } else {
- cmps.push(0);
- }
- }
- return cmps;
-}
diff --git a/packages/graphic-walker/src/lib/insights/utils.ts b/packages/graphic-walker/src/lib/insights/utils.ts
deleted file mode 100644
index a4329901..00000000
--- a/packages/graphic-walker/src/lib/insights/utils.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { IField } from '../../interfaces';
-
-export function groupByAnalyticTypes(fields: IField[]) {
- const dimensions = fields.filter((f) => f.analyticType === 'dimension');
- const measures = fields.filter((f) => f.analyticType === 'measure');
- return {
- dimensions,
- measures,
- };
-}
-
-export function complementaryFields(props: { selection: IField[]; all: IField[] }): IField[] {
- return props.all.filter((f) => f.analyticType === 'dimension').filter((f) => !props.selection.find((vf) => vf.fid === f.fid));
-}
diff --git a/packages/graphic-walker/src/locales/en-US.json b/packages/graphic-walker/src/locales/en-US.json
index b1e1e52d..cee14801 100644
--- a/packages/graphic-walker/src/locales/en-US.json
+++ b/packages/graphic-walker/src/locales/en-US.json
@@ -48,6 +48,36 @@
"timezone_settings_desc": "Configure how time-based data is displayed across different timezones.",
"customOffset_desc": "Specify a custom timezone for displaying time-based data."
},
+ "explain": {
+ "title": "Explain Data",
+ "loading": "Analyzing...",
+ "empty": "No significant patterns found",
+ "type": {
+ "extremeValue": "Extreme values",
+ "contributingDimension": "Contributing dimensions",
+ "contributingMeasure": "Contributing measures",
+ "uniqueMark": "What's unique about this mark"
+ },
+ "strength": {
+ "strong": "Strong",
+ "moderate": "Moderate",
+ "weak": "Weak"
+ },
+ "skip": {
+ "noMark": "Select a mark before running Explain Data.",
+ "temporalMark": "Temporal marks are not analyzed for extreme values yet.",
+ "noSensitiveAgg": "The selected measure aggregation is not sensitive to extreme values.",
+ "noCandidates": "No eligible fields were available for comparison."
+ },
+ "extremeValue": {
+ "desc": "{{outlierCount}} of {{rowCount}} records are extreme values; removing them changes {{agg}} of {{measure}} from {{before}} to {{after}} ({{changePercent}}%).",
+ "truncated": "{{measure}} has a large mark with mean and median values that differ; scan the {{rowCount}} rows before interpreting the aggregate."
+ },
+ "uniqueMark": {
+ "countDesc": "This mark's composition over {{dimension}} differs from other marks: {{markShare}}% falls in \"{{topCategory}}\" vs {{siblingShare}}% elsewhere.",
+ "measureDesc": "This mark's {{measure}} mass is distributed differently over {{dimension}} than other marks (heuristic)."
+ }
+ },
"constant": {
"row_count": "Row count",
"mea_key": "Measure names",
@@ -318,20 +348,6 @@
"end_value": "End Value"
}
},
- "explain": {
- "lg_than": "greater than",
- "sm_than": "less than",
- "expection": "expectation",
- "unrecognized": "Unrecognized",
- "score": "score",
- "contains": "contains",
- "reason": {
- "selection_dim_distribution": "dimensions' clues",
- "selection_mea_distribution": "measures' clues",
- "children_major_factor": "major factor",
- "children_outlier": "outlier"
- }
- },
"actions": {
"prev": "Previous",
"next": "Next",
diff --git a/packages/graphic-walker/src/locales/ja-JP.json b/packages/graphic-walker/src/locales/ja-JP.json
index e7fb4b20..cc7fe3e8 100644
--- a/packages/graphic-walker/src/locales/ja-JP.json
+++ b/packages/graphic-walker/src/locales/ja-JP.json
@@ -43,6 +43,36 @@
"timezone_settings_desc": "異なるタイムゾーン間での時間ベースのデータの表示方法を設定します。",
"customOffset_desc": "時間ベースのデータを表示するためのカスタムタイムゾーンを指定します。"
},
+ "explain": {
+ "title": "データの説明",
+ "loading": "分析中...",
+ "empty": "顕著なパターンは見つかりませんでした",
+ "type": {
+ "extremeValue": "極端な値",
+ "contributingDimension": "寄与するディメンション",
+ "contributingMeasure": "寄与するメジャー",
+ "uniqueMark": "このマークの特徴"
+ },
+ "strength": {
+ "strong": "強",
+ "moderate": "中",
+ "weak": "弱"
+ },
+ "skip": {
+ "noMark": "データの説明を実行する前にマークを選択してください。",
+ "temporalMark": "時間マークの極端な値はまだ分析していません。",
+ "noSensitiveAgg": "選択されたメジャー集計は極端な値に反応しにくい形式です。",
+ "noCandidates": "比較に使える候補フィールドがありません。"
+ },
+ "extremeValue": {
+ "desc": "{{rowCount}} 件のうち {{outlierCount}} 件が極端な値です。これらを除くと、{{measure}} の {{agg}} は {{before}} から {{after}} に変わります({{changePercent}}%)。",
+ "truncated": "{{measure}} のマークは {{rowCount}} 行を含み、平均と中央値に差があります。集計値を解釈する前に行の内容を確認してください。"
+ },
+ "uniqueMark": {
+ "countDesc": "このマークの {{dimension}} における構成は他のマークと異なります。{{markShare}}% が「{{topCategory}}」に入り、他のマークでは {{siblingShare}}% です。",
+ "measureDesc": "このマークの {{measure}} は、{{dimension}} 上で他のマークと異なる分布を示します(ヒューリスティック)。"
+ }
+ },
"constant": {
"row_count": "行数",
"mea_key": "名",
@@ -307,20 +337,6 @@
"end_value": "最大"
}
},
- "explain": {
- "lg_than": "より大きい",
- "sm_than": "より小さい",
- "expection": "期待値",
- "unrecognized": "未認識",
- "score": "スコア",
- "contains": "を含む",
- "reason": {
- "selection_dim_distribution": "次元のヒント",
- "selection_mea_distribution": "尺度のヒント",
- "children_major_factor": "主要要因",
- "children_outlier": "外れ値"
- }
- },
"actions": {
"prev": "前へ",
"next": "次へ",
diff --git a/packages/graphic-walker/src/locales/zh-CN.json b/packages/graphic-walker/src/locales/zh-CN.json
index 53a4528b..6c077636 100644
--- a/packages/graphic-walker/src/locales/zh-CN.json
+++ b/packages/graphic-walker/src/locales/zh-CN.json
@@ -43,6 +43,36 @@
"timezone_settings_desc": "配置时间数据在不同时区之间的显示方式。",
"customOffset_desc": "为显示基于时间的数据指定自定义时区。"
},
+ "explain": {
+ "title": "数据解释",
+ "loading": "正在分析...",
+ "empty": "未发现显著模式",
+ "type": {
+ "extremeValue": "极端值",
+ "contributingDimension": "贡献维度",
+ "contributingMeasure": "贡献度量",
+ "uniqueMark": "标记的独特之处"
+ },
+ "strength": {
+ "strong": "强",
+ "moderate": "中",
+ "weak": "弱"
+ },
+ "skip": {
+ "noMark": "请先选择一个标记再运行数据解释。",
+ "temporalMark": "暂不对时间标记分析极端值。",
+ "noSensitiveAgg": "所选度量聚合对极端值不敏感。",
+ "noCandidates": "没有可用于比较的候选字段。"
+ },
+ "extremeValue": {
+ "desc": "{{rowCount}} 条记录中有 {{outlierCount}} 条是极端值;移除这些记录后,{{measure}} 的 {{agg}} 从 {{before}} 变为 {{after}}({{changePercent}}%)。",
+ "truncated": "{{measure}} 所在标记包含 {{rowCount}} 行,均值和中位数存在差异;解读该聚合值前请先查看这些行。"
+ },
+ "uniqueMark": {
+ "countDesc": "此标记在 {{dimension}} 上的构成与其他标记不同:{{markShare}}% 属于“{{topCategory}}”,其他标记为 {{siblingShare}}%。",
+ "measureDesc": "此标记的 {{measure}} 在 {{dimension}} 上的分布与其他标记不同(启发式)。"
+ }
+ },
"constant": {
"row_count": "行数",
"mea_key": "度量名称",
@@ -313,20 +343,6 @@
"end_value": "终止值"
}
},
- "explain": {
- "lg_than": "大于",
- "sm_than": "小于",
- "expection": "期望值",
- "unrecognized": "未识别",
- "score": "得分",
- "contains": "包含",
- "reason": {
- "selection_dim_distribution": "维度线索",
- "selection_mea_distribution": "度量线索",
- "children_major_factor": "子节点主要因素",
- "children_outlier": "子节点异常"
- }
- },
"actions": {
"prev": "向前",
"next": "向后",
diff --git a/packages/graphic-walker/src/utils/index.ts b/packages/graphic-walker/src/utils/index.ts
index 0795a3bd..2460f531 100644
--- a/packages/graphic-walker/src/utils/index.ts
+++ b/packages/graphic-walker/src/utils/index.ts
@@ -4,216 +4,6 @@ import { IRow, Filters, IViewField, IFilterField, IKeyWord, IField, FieldIdentif
import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
-interface NRReturns {
- normalizedData: IRow[];
- maxMeasures: IRow;
- minMeasures: IRow;
- totalMeasures: IRow;
-}
-function normalizeRecords(dataSource: IRow[], measures: string[]): NRReturns {
- const maxMeasures: IRow = {};
- const minMeasures: IRow = {};
- const totalMeasures: IRow = {};
- measures.forEach((mea) => {
- maxMeasures[mea] = -Infinity;
- minMeasures[mea] = Infinity;
- totalMeasures[mea] = 0;
- });
- dataSource.forEach((record) => {
- measures.forEach((mea) => {
- maxMeasures[mea] = Math.max(record[mea], maxMeasures[mea]);
- minMeasures[mea] = Math.min(record[mea], minMeasures[mea]);
- });
- });
- const newData: IRow[] = [];
- dataSource.forEach((record) => {
- const norRecord: IRow = { ...record };
- measures.forEach((mea) => {
- totalMeasures[mea] += Math.abs(norRecord[mea]);
- });
- newData.push(norRecord);
- });
- newData.forEach((record) => {
- measures.forEach((mea) => {
- record[mea] /= totalMeasures[mea];
- });
- });
- return {
- normalizedData: newData,
- maxMeasures,
- minMeasures,
- totalMeasures,
- };
-}
-
-function normalize2PositiveRecords(dataSource: IRow[], measures: string[]): NRReturns {
- const maxMeasures: IRow = {};
- const minMeasures: IRow = {};
- const totalMeasures: IRow = {};
- measures.forEach((mea) => {
- maxMeasures[mea] = -Infinity;
- minMeasures[mea] = Infinity;
- totalMeasures[mea] = 0;
- });
- dataSource.forEach((record) => {
- measures.forEach((mea) => {
- maxMeasures[mea] = Math.max(record[mea], maxMeasures[mea]);
- minMeasures[mea] = Math.min(record[mea], minMeasures[mea]);
- });
- });
- const newData: IRow[] = [];
- dataSource.forEach((record) => {
- const norRecord: IRow = { ...record };
- measures.forEach((mea) => {
- norRecord[mea] = norRecord[mea] - minMeasures[mea];
- totalMeasures[mea] += norRecord[mea];
- });
- newData.push(norRecord);
- });
- newData.forEach((record) => {
- measures.forEach((mea) => {
- record[mea] /= totalMeasures[mea];
- });
- });
- return {
- normalizedData: newData,
- maxMeasures,
- minMeasures,
- totalMeasures,
- };
-}
-
-export function checkMajorFactor(
- data: IRow[],
- childrenData: Map<any, IRow[]>,
- dimensions: string[],
- measures: string[]
-): { majorKey: string; majorSum: number } {
- const { normalizedData, maxMeasures, minMeasures, totalMeasures } = normalizeRecords(data, measures);
- let majorSum = Infinity;
- let majorKey = '';
- for (let [key, childData] of childrenData) {
- let sum = 0;
- for (let record of normalizedData) {
- let target = childData.find((childRecord) => {
- return dimensions.every((dim) => record[dim] === childRecord[dim]);
- });
- if (target) {
- measures.forEach((mea) => {
- let targetValue = typeof target![mea] === 'number' && !isNaN(target![mea]) ? target![mea] : 0;
- targetValue = targetValue / totalMeasures[mea];
- sum += Math.abs(record[mea] - targetValue);
- });
- } else {
- measures.forEach((mea) => {
- sum += Math.abs(record[mea]);
- });
- }
- }
- if (sum < majorSum) {
- majorSum = sum;
- majorKey = key;
- }
- }
- majorSum /= measures.length * 2;
- return { majorKey, majorSum };
-}
-
-export function checkChildOutlier(
- data: IRow[],
- childrenData: Map<any, IRow[]>,
- dimensions: string[],
- measures: string[]
-): { outlierKey: string; outlierSum: number } {
- // const { normalizedData, maxMeasures, minMeasures, totalMeasures } = normalize2PositiveRecords(data, measures);
- const { normalizedData, maxMeasures, minMeasures, totalMeasures } = normalizeRecords(data, measures);
- let outlierSum = -Infinity;
- let outlierKey = '';
- for (let [key, childData] of childrenData) {
- // const { normalizedData: normalizedChildData } = normalize2PositiveRecords(childData, measures);
- const { normalizedData: normalizedChildData } = normalizeRecords(childData, measures);
- let sum = 0;
- for (let record of normalizedData) {
- let target = normalizedChildData.find((childRecord) => {
- return dimensions.every((dim) => record[dim] === childRecord[dim]);
- });
- if (target) {
- measures.forEach((mea) => {
- let targetValue = typeof target![mea] === 'number' && !isNaN(target![mea]) ? target![mea] : 0;
- sum += Math.abs(record[mea] - targetValue);
- });
- } else {
- measures.forEach((mea) => {
- sum += Math.abs(record[mea]);
- });
- }
- }
- if (sum > outlierSum) {
- outlierSum = sum;
- outlierKey = key;
- }
- }
- outlierSum /= measures.length * 2;
- return { outlierKey, outlierSum };
-}
-export interface IPredicate {
- key: string;
- type: 'discrete' | 'continuous';
- range: Set<any> | [number, number];
-}
-export function getPredicates(selection: IRow[], dimensions: string[], measures: string[]): IPredicate[] {
- const predicates: IPredicate[] = [];
- dimensions.forEach((dim) => {
- predicates.push({
- key: dim,
- type: 'discrete',
- range: new Set(),
- });
- });
- measures.forEach((mea) => {
- predicates.push({
- key: mea,
- type: 'continuous',
- range: [Infinity, -Infinity],
- });
- });
- selection.forEach((record) => {
- dimensions.forEach((dim, index) => {
- (predicates[index].range as Set<any>).add(record[dim]);
- });
- measures.forEach((mea, index) => {
- (predicates[index].range as [number, number])[0] = Math.min((predicates[index].range as [number, number])[0], record[mea]);
- (predicates[index].range as [number, number])[1] = Math.max((predicates[index].range as [number, number])[1], record[mea]);
- });
- });
- return predicates;
-}
-
-export function getPredicatesFromVegaSignals(signals: Filters, dimensions: string[], measures: string[]): IPredicate[] {
- const predicates: IPredicate[] = [];
- dimensions.forEach((dim) => {
- predicates.push({
- type: 'discrete',
- range: new Set(signals[dim]),
- key: dim,
- });
- });
- return predicates;
-}
-
-export function filterByPredicates(data: IRow[], predicates: IPredicate[]): IRow[] {
- const filterData = data.filter((record) => {
- return predicates.every((pre) => {
- if (pre.type === 'continuous') {
- return record[pre.key] >= (pre.range as [number, number])[0] && record[pre.key] <= (pre.range as [number, number])[1];
- } else {
- return (pre.range as Set<any>).has(record[pre.key]);
- }
- });
- });
- return filterData;
-}
-
export function applyFilters(dataSource: IRow[], filters: Filters): IRow[] {
let filterKeys = Object.keys(filters);
return dataSource.filter((record) => {
diff --git a/packages/graphic-walker/src/utils/normalization.ts b/packages/graphic-walker/src/utils/normalization.ts
deleted file mode 100644
index 2648bf0a..00000000
--- a/packages/graphic-walker/src/utils/normalization.ts
+++ /dev/null
@@ -1,215 +0,0 @@
-import { IRow } from "../interfaces";
-
-export function normalizeWithParent(
- data: IRow[],
- parentData: IRow[],
- measures: string[],
- syncScale: boolean
-): {
- normalizedData: IRow[];
- normalizedParentData: IRow[];
-} {
- const totalMeasuresOfParent: IRow = {};
- const totalMeasures: IRow = {};
- measures.forEach((mea) => {
- totalMeasuresOfParent[mea] = 0;
- totalMeasures[mea] = 0;
- });
- parentData.forEach((record) => {
- measures.forEach((mea) => {
- totalMeasuresOfParent[mea] += Math.abs(record[mea]);
- });
- });
- data.forEach((record) => {
- measures.forEach((mea) => {
- totalMeasures[mea] += Math.abs(record[mea]);
- });
- });
- const normalizedParentData: IRow[] = [];
- parentData.forEach((record) => {
- const newRecord = { ...record };
- measures.forEach((mea) => {
- newRecord[mea] /= totalMeasuresOfParent[mea];
- });
- normalizedParentData.push(newRecord);
- });
- const normalizedData: IRow[] = [];
- data.forEach((record) => {
- const newRecord = { ...record };
- measures.forEach((mea) => {
- if (syncScale) {
- newRecord[mea] /= totalMeasuresOfParent[mea];
- } else {
- newRecord[mea] /= totalMeasures[mea];
- }
- });
- normalizedData.push(newRecord);
- });
- return {
- normalizedData,
- normalizedParentData,
- };
-}
-
-export function compareDistribution(
- distribution1: IRow[],
- distribution2: IRow[],
- dimensions: string[],
- measures: string[]
-): number {
- let score = 0;
- let count = 0;
- const tagsForD2: boolean[] = distribution2.map(() => false);
- for (let record of distribution1) {
- let targetRecordIndex = distribution2.findIndex((r, i) => {
- return !tagsForD2[i] && dimensions.every((dim) => r[dim] === record[dim]);
- });
- if (targetRecordIndex > -1) {
- tagsForD2[targetRecordIndex] = true;
- const targetRecord = distribution2[targetRecordIndex];
- for (let mea of measures) {
- score = Math.max(
- score,
- Math.max(targetRecord[mea], record[mea]) / Math.min(targetRecord[mea], record[mea])
- );
- count++;
- }
- } else {
- for (let mea of measures) {
- score = Math.max(score, record[mea]);
- count++;
- }
- }
- }
- for (let i = 0; i < distribution2.length; i++) {
- if (!tagsForD2[i]) {
- tagsForD2[i] = true;
- for (let mea of measures) {
- score = Math.max(score, distribution2[i][mea]);
- count++;
- }
- }
- }
- return score;
-}
-
-export function compareDistributionKL(
- distribution1: IRow[],
- distribution2: IRow[],
- dimensions: string[],
- measures: string[]
-): number {
- let score = 0;
- const tagsForD2: boolean[] = distribution2.map(() => false);
- for (let record of distribution1) {
- let targetRecordIndex = distribution2.findIndex((r, i) => {
- return !tagsForD2[i] && dimensions.every((dim) => r[dim] === record[dim]);
- });
- if (targetRecordIndex > -1) {
- tagsForD2[targetRecordIndex] = true;
- const targetRecord = distribution2[targetRecordIndex];
- for (let mea of measures) {
- score += targetRecord[mea] * Math.log2(targetRecord[mea] / record[mea])
- // score += record[mea] * Math.log2(record[mea] / targetRecord[mea])
- }
- }
- }
- return score;
-}
-
-// Jensen–Shannon divergence
-export function compareDistributionJS(
- distribution1: IRow[],
- distribution2: IRow[],
- dimensions: string[],
- measure: string
-): number {
- let score = 0;
- const tagsForD2: boolean[] = distribution2.map(() => false);
- for (let record of distribution1) {
- let targetRecordIndex = distribution2.findIndex((r, i) => {
- return !tagsForD2[i] && dimensions.every((dim) => r[dim] === record[dim]);
- });
- if (targetRecordIndex > -1) {
- tagsForD2[targetRecordIndex] = true;
- const targetRecord = distribution2[targetRecordIndex];
- let p = record[measure];
- let q = targetRecord[measure];
- if (p === 0 || q === 0) continue;
- let m = 0.5 * (p + q);
- score += (0.5 * p * Math.log2(p / m) + 0.5 * q * Math.log2(q / m));
- }
- }
- const weight = tagsForD2.filter((tag) => tag === true).length / tagsForD2.length;
-
- return score * weight;
-}
-
-export function normalizeByMeasures(dataSource: IRow[], measures: string[]) {
- let sums: Map<string, number> = new Map();
-
- measures.forEach((mea) => {
- sums.set(mea, 0);
- });
-
- dataSource.forEach((record) => {
- measures.forEach((mea) => {
- sums.set(mea, sums.get(mea)! + Math.abs(record[mea]));
- });
- });
-
- const ans: IRow[] = [];
- dataSource.forEach((record) => {
- const norRecord: IRow = { ...record };
- measures.forEach((mea) => {
- norRecord[mea] /= sums.get(mea)!;
- });
- ans.push(norRecord);
- });
- return ans;
-}
-
-export function getDistributionDifference(
- dataSource: IRow[],
- dimensions: string[],
- measure1: string,
- measure2: string
-): number {
- let score = 0;
- for (let record of dataSource) {
- if (record[measure1] === 0 || record[measure2] === 0) continue;
- score += Math.max(record[measure1], record[measure2]) / Math.min(record[measure1], record[measure2]);
- }
- return score;
-}
-
-export function makeBinField(dataSource: IRow[], fid: string, binFid: string, binSize: number | undefined = 10) {
- let _min = Infinity;
- let _max = -Infinity;
- for (let i = 0; i < dataSource.length; i++) {
- let val = dataSource[i][fid];
- if (val > _max) _max = val;
- if (val < _min) _min = val;
- }
- const step = (_max - _min) / binSize;
- const beaStep = Math.max(-Math.round(Math.log10(_max - _min)) + 2, 0)
- return dataSource.map((r) => {
- let bIndex = Math.floor((r[fid] - _min) / step);
- if (bIndex === binSize) bIndex = binSize - 1;
- return {
- ...r,
- [binFid]: [bIndex * step + _min, (bIndex + 1) * step + _min],
-
- // [binFid]: Number(((bIndex * step + _min)).toFixed(beaStep)),
- };
- });
-}
-
-export function makeLogField(dataSource: IRow[], fid: string, logFid: string) {
- return dataSource.map((r) => {
- return {
- ...r,
- [logFid]: typeof r[fid] === "number" && r[fid] > 0 ? Math.log10(r[fid]) : null,
- };
- });
-}