ScalarChart.tsx 5.6 KB
Newer Older
1 2 3
import {
    Dataset,
    Range,
4
    RangeParams,
5
    TransformParams,
6 7
    chartData,
    range,
8
    singlePointRange,
9 10 11 12
    sortingMethodMap,
    tooltip,
    transform,
    xAxisMap
13
} from '~/resource/scalars';
14 15 16 17
import React, {FunctionComponent, useCallback, useMemo} from 'react';
import {em, size} from '~/utils/style';

import {EChartOption} from 'echarts';
18
import LineChart from '~/components/LineChart';
19 20 21 22 23 24
import {cycleFetcher} from '~/utils/fetch';
import queryString from 'query-string';
import styled from 'styled-components';
import useHeavyWork from '~/hooks/useHeavyWork';
import {useRunningRequest} from '~/hooks/useRequest';
import {useTranslation} from '~/utils/i18n';
25 26 27 28

const width = em(430);
const height = em(320);

29
const smoothWasm = () =>
30
    import('@visualdl/wasm').then(({transform}) => (params: TransformParams) =>
31 32 33
        (transform(params.datasets, params.smoothing) as unknown) as Dataset[]
    );
const rangeWasm = () =>
34
    import('@visualdl/wasm').then(({range}) => (params: RangeParams) =>
35 36 37 38 39 40
        (range(params.datasets, params.outlier) as unknown) as Range
    );

const smoothWorker = () => new Worker('~/worker/scalars/smooth.worker.ts', {type: 'module'});
const rangeWorker = () => new Worker('~/worker/scalars/range.worker.ts', {type: 'module'});

41 42 43 44
const StyledLineChart = styled(LineChart)`
    ${size(height, width)}
`;

45 46 47 48 49 50 51
const Error = styled.div`
    ${size(height, width)}
    display: flex;
    justify-content: center;
    align-items: center;
`;

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
type ScalarChartProps = {
    runs: string[];
    tag: string;
    smoothing: number;
    xAxis: keyof typeof xAxisMap;
    sortingMethod: keyof typeof sortingMethodMap;
    outlier?: boolean;
    running?: boolean;
};

const ScalarChart: FunctionComponent<ScalarChartProps> = ({
    runs,
    tag,
    smoothing,
    xAxis,
    sortingMethod,
    outlier,
    running
}) => {
P
Peter Pan 已提交
71
    const {t, i18n} = useTranslation(['scalars', 'common']);
72

73
    const {data: datasets, error, loading} = useRunningRequest<(Dataset | null)[]>(
P
Peter Pan 已提交
74
        runs.map(run => `/scalars/list?${queryString.stringify({run, tag})}`),
75 76
        !!running,
        (...urls) => cycleFetcher(urls)
77 78
    );

79 80 81
    const smooth = false;
    const type = useMemo(() => (xAxis === 'wall' ? 'time' : 'value'), [xAxis]);
    const xAxisLabel = useMemo(() => (xAxis === 'step' ? '' : t(`x-axis-value.${xAxis}`)), [xAxis, t]);
82

83 84
    const transformParams = useMemo(
        () => ({
85
            datasets: datasets?.map(data => data ?? []) ?? [],
86 87 88 89 90 91 92 93 94 95 96 97 98 99
            smoothing
        }),
        [datasets, smoothing]
    );
    const smoothedDatasets = useHeavyWork(smoothWasm, smoothWorker, transform, transformParams) ?? [];

    const rangeParams = useMemo(
        () => ({
            datasets: smoothedDatasets,
            outlier: !!outlier
        }),
        [smoothedDatasets, outlier]
    );
    const yRange = useHeavyWork(rangeWasm, rangeWorker, range, rangeParams);
100

101 102 103 104 105 106 107 108 109 110 111 112 113 114
    const ranges: Record<'x' | 'y', Range | undefined> = useMemo(() => {
        let x: Range | undefined = undefined;
        let y: Range | undefined = yRange;

        // if there is only one point, place it in the middle
        if (smoothedDatasets.length === 1 && smoothedDatasets[0].length === 1) {
            if (['value', 'log'].includes(type)) {
                x = singlePointRange(smoothedDatasets[0][0][xAxisMap[xAxis]]);
            }
            y = singlePointRange(smoothedDatasets[0][0][2]);
        }
        return {x, y};
    }, [smoothedDatasets, yRange, type, xAxis]);

115 116
    const data = useMemo(
        () =>
117 118 119 120 121 122 123
            chartData({
                data: smoothedDatasets,
                runs,
                smooth,
                xAxis
            }),
        [smoothedDatasets, runs, smooth, xAxis]
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
    );

    const formatter = useCallback(
        (params: EChartOption.Tooltip.Format | EChartOption.Tooltip.Format[]) => {
            const data = Array.isArray(params) ? params[0].data : params.data;
            const step = data[1];
            const points =
                smoothedDatasets?.map((series, index) => {
                    let nearestItem;
                    if (step === 0) {
                        nearestItem = series[0];
                    } else {
                        for (let i = 0; i < series.length; i++) {
                            const item = series[i];
                            if (item[1] === step) {
                                nearestItem = item;
                                break;
                            }
                            if (item[1] > step) {
                                nearestItem = series[i - 1 >= 0 ? i - 1 : 0];
                                break;
                            }
                            if (!nearestItem) {
                                nearestItem = series[series.length - 1];
                            }
                        }
                    }
                    return {
                        run: runs[index],
                        item: nearestItem || []
                    };
                }) ?? [];
            const sort = sortingMethodMap[sortingMethod];
P
Peter Pan 已提交
157
            return tooltip(sort ? sort(points, data) : points, i18n);
158
        },
P
Peter Pan 已提交
159
        [smoothedDatasets, runs, sortingMethod, i18n]
160 161
    );

162 163 164
    // display error only on first fetch
    if (!data && error) {
        return <Error>{t('common:error')}</Error>;
165 166
    }

167 168 169
    return (
        <StyledLineChart
            title={tag}
170
            xAxis={xAxisLabel}
171 172
            xRange={ranges.x}
            yRange={ranges.y}
173 174 175
            type={type}
            tooltip={formatter}
            data={data}
176
            loading={loading}
177 178 179 180 181
        />
    );
};

export default ScalarChart;