high-dimensional.tsx 17.9 KB
Newer Older
P
Peter Pan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/**
 * Copyright 2020 Baidu Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

P
Peter Pan 已提交
17
import Aside, {AsideSection} from '~/components/Aside';
P
Peter Pan 已提交
18 19 20 21 22 23
import type {
    Dimension,
    PCAResult,
    ParseParams,
    ParseResult,
    Reduction,
P
Peter Pan 已提交
24
    Shape,
P
Peter Pan 已提交
25 26 27 28 29 30
    TSNEResult,
    UMAPResult
} from '~/resource/high-dimensional';
import HighDimensionalChart, {HighDimensionalChartRef} from '~/components/HighDimensionalPage/HighDimensionalChart';
import LabelSearchInput, {LabelSearchInputProps} from '~/components/HighDimensionalPage/LabelSearchInput';
import React, {FunctionComponent, useCallback, useEffect, useMemo, useRef, useState} from 'react';
31
import Select, {SelectProps} from '~/components/Select';
32

P
Peter Pan 已提交
33 34 35
import type {BlobResponse} from '~/utils/fetch';
import BodyLoading from '~/components/BodyLoading';
import Button from '~/components/Button';
36
import Content from '~/components/Content';
P
Peter Pan 已提交
37
import DimensionSwitch from '~/components/HighDimensionalPage/DimensionSwitch';
38
import Error from '~/components/Error';
39
import Field from '~/components/Field';
P
Peter Pan 已提交
40 41 42 43
import LabelSearchResult from '~/components/HighDimensionalPage/LabelSearchResult';
import PCADetail from '~/components/HighDimensionalPage/PCADetail';
import ReductionTab from '~/components/HighDimensionalPage/ReductionTab';
import TSNEDetail from '~/components/HighDimensionalPage/TSNEDetail';
44
import Title from '~/components/Title';
P
Peter Pan 已提交
45 46 47 48
import UMAPDetail from '~/components/HighDimensionalPage/UMAPDetail';
import UploadDialog from '~/components/HighDimensionalPage/UploadDialog';
import queryString from 'query-string';
import {rem} from '~/utils/style';
49
import styled from 'styled-components';
P
Peter Pan 已提交
50 51
import {toast} from 'react-toastify';
import useRequest from '~/hooks/useRequest';
52
import {useTranslation} from 'react-i18next';
P
Peter Pan 已提交
53
import useWorker from '~/hooks/useWorker';
54

P
Peter Pan 已提交
55
const MODE = import.meta.env.MODE;
56

P
Peter Pan 已提交
57 58 59 60 61 62 63 64 65 66 67 68
const MAX_COUNT: Record<Reduction, number | undefined> = {
    pca: 50000,
    tsne: 10000,
    umap: 5000
} as const;

const MAX_DIMENSION: Record<Reduction, number | undefined> = {
    pca: 200,
    tsne: undefined,
    umap: undefined
};

69 70 71 72
const AsideTitle = styled.div`
    font-size: ${rem(16)};
    line-height: ${rem(16)};
    font-weight: 700;
P
Peter Pan 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
    margin-bottom: ${rem(20)};
`;

const FullWidthSelect = styled<React.FunctionComponent<SelectProps<string>>>(Select)`
    width: 100%;
`;

const FullWidthButton = styled(Button)`
    width: 100%;
`;

const HDAside = styled(Aside)`
    .secondary {
        color: var(--text-light-color);
    }
88 89
`;

P
Peter Pan 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
const RightAside = styled(HDAside)`
    border-left: 1px solid var(--border-color);
`;

const LeftAside = styled(HDAside)`
    border-right: 1px solid var(--border-color);

    ${AsideSection} {
        border-bottom: none;
    }

    > .aside-top > .search-result {
        margin-top: 0;
        margin-left: 0;
        margin-right: 0;
        flex: auto;
        overflow: hidden auto;
    }
`;

const HDContent = styled(Content)`
    background-color: var(--background-color);
`;

type EmbeddingInfo = {
    name: string;
    shape: [number, number];
    path?: string;
118 119
};

120
const HighDimensional: FunctionComponent = () => {
121 122
    const {t} = useTranslation(['high-dimensional', 'common']);

P
Peter Pan 已提交
123
    const chart = useRef<HighDimensionalChartRef>(null);
P
Peter Pan 已提交
124

P
Peter Pan 已提交
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 157 158 159 160 161 162 163 164 165 166 167 168
    const {data: list, loading: loadingList} = useRequest<EmbeddingInfo[]>('/embedding/list');
    const embeddingList = useMemo(() => list?.map(item => ({value: item.name, label: item.name, ...item})) ?? [], [
        list
    ]);
    const [selectedEmbeddingName, setSelectedEmbeddingName] = useState<string>();
    const selectedEmbedding = useMemo(
        () => embeddingList.find(embedding => embedding.value === selectedEmbeddingName),
        [embeddingList, selectedEmbeddingName]
    );
    useEffect(() => {
        setSelectedEmbeddingName(embeddingList[0]?.value ?? undefined);
    }, [embeddingList]);
    const {data: tensorData, loading: loadingTensor} = useRequest<BlobResponse>(
        selectedEmbeddingName ? `/embedding/tensor?${queryString.stringify({name: selectedEmbeddingName})}` : null
    );
    const {data: metadataData, loading: loadingMetadata} = useRequest<string>(
        selectedEmbeddingName ? `/embedding/metadata?${queryString.stringify({name: selectedEmbeddingName})}` : null
    );

    const [uploadModal, setUploadModal] = useState(false);
    const [loading, setLoading] = useState(false);
    const [loadingPhase, setLoadingPhase] = useState('');
    useEffect(() => {
        if (!loading) {
            setLoadingPhase('');
        }
    }, [loading]);
    useEffect(() => {
        if (loadingPhase) {
            setLoading(true);
        }
    }, [loadingPhase]);
    useEffect(() => {
        if (loadingTensor) {
            setLoading(true);
            setLoadingPhase('fetching-tensor');
        }
    }, [loadingTensor]);
    useEffect(() => {
        if (loadingMetadata) {
            setLoading(true);
            setLoadingPhase('fetching-metadata');
        }
    }, [loadingMetadata]);
169

P
Peter Pan 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183
    const [vectorFile, setVectorFile] = useState<File | null>(null);
    const [metadataFile, setMetadataFile] = useState<File | null>(null);
    const changeVectorFile = useCallback((file: File) => {
        setVectorFile(file);
        setMetadataFile(null);
    }, []);
    const [vectorContent, setVectorContent] = useState('');
    const [metadataContent, setMetadataContent] = useState('');
    const [vectors, setVectors] = useState<Float32Array>(new Float32Array());
    const [labels, setLabels] = useState<string[]>([]);
    const [labelBy, setLabelBy] = useState<string>();
    const [metadata, setMetadata] = useState<string[][]>([]);
    // dimension of data
    const [dim, setDim] = useState<number>(0);
P
Peter Pan 已提交
184
    const [rawShape, setRawShape] = useState<Shape>([0, 0]);
P
Peter Pan 已提交
185 186 187 188 189 190 191 192
    const getLabelByLabels = useCallback(
        (value: string | undefined) => {
            if (value != null) {
                const labelIndex = labels.indexOf(value);
                if (labelIndex !== -1) {
                    return metadata.map(row => row[labelIndex]);
                }
            }
193
            return [];
P
Peter Pan 已提交
194 195 196 197 198
        },
        [labels, metadata]
    );
    const labelByLabels = useMemo(() => getLabelByLabels(labelBy), [getLabelByLabels, labelBy]);

P
Peter Pan 已提交
199 200 201 202 203 204
    // dimension of display
    const [dimension, setDimension] = useState<Dimension>('3d');
    const [reduction, setReduction] = useState<Reduction>('pca');

    const is3D = useMemo(() => dimension === '3d', [dimension]);

P
Peter Pan 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
    const readFile = useCallback(
        (phase: string, file: File | null, setter: React.Dispatch<React.SetStateAction<string>>) => {
            if (file) {
                setLoading(true);
                setLoadingPhase(phase);
                const reader = new FileReader();
                reader.readAsText(file, 'utf-8');
                reader.onload = () => {
                    setter(content => {
                        const result = reader.result as string;
                        if (content === result) {
                            setLoading(false);
                        }
                        return result;
                    });
                };
            } else {
                setter('');
            }
        },
        []
    );
    useEffect(() => readFile('reading-vector', vectorFile, setVectorContent), [vectorFile, readFile]);
    useEffect(() => readFile('reading-metadata', metadataFile, setMetadataContent), [metadataFile, readFile]);
    useEffect(() => setVectorFile(null), [selectedEmbeddingName]);

    const showError = useCallback((e: Error) => {
        toast(e.message, {
            position: toast.POSITION.TOP_CENTER,
            type: toast.TYPE.ERROR
        });
        if (MODE !== 'production') {
            // eslint-disable-next-line no-console
            console.error(e);
        }
        setLoading(false);
    }, []);

    const params = useMemo<ParseParams>(() => {
P
Peter Pan 已提交
244 245 246 247
        const maxValues = {
            maxCount: MAX_COUNT[reduction],
            maxDimension: MAX_DIMENSION[reduction]
        };
P
Peter Pan 已提交
248 249 250 251 252
        if (vectorContent) {
            return {
                from: 'string',
                params: {
                    vectors: vectorContent,
P
Peter Pan 已提交
253 254
                    metadata: metadataContent,
                    ...maxValues
P
Peter Pan 已提交
255 256 257 258 259 260 261 262 263
                }
            };
        }
        if (selectedEmbedding && tensorData) {
            return {
                from: 'blob',
                params: {
                    shape: selectedEmbedding.shape,
                    vectors: tensorData.data,
P
Peter Pan 已提交
264 265
                    metadata: metadataData ?? '',
                    ...maxValues
P
Peter Pan 已提交
266 267
                }
            };
268
        }
P
Peter Pan 已提交
269
        return null;
P
Peter Pan 已提交
270
    }, [reduction, vectorContent, selectedEmbedding, tensorData, metadataContent, metadataData]);
P
Peter Pan 已提交
271 272 273 274 275 276
    const result = useWorker<ParseResult, ParseParams>('high-dimensional/parse-data', params);
    useEffect(() => {
        const {error, data} = result;
        if (error) {
            showError(error);
        } else if (data) {
P
Peter Pan 已提交
277
            setRawShape(data.rawShape);
P
Peter Pan 已提交
278 279 280 281 282 283 284 285 286 287 288 289 290 291
            setDim(data.dimension);
            setVectors(data.vectors);
            setLabels(data.labels);
            setLabelBy(data.labels[0]);
            setMetadata(data.metadata);
        } else if (data !== null) {
            setLoadingPhase('parsing');
        }
    }, [result, showError]);
    const hasVector = useMemo(() => dim !== 0, [dim]);

    const dataPath = useMemo(() => (vectorFile ? vectorFile.name : selectedEmbedding?.path ?? ''), [
        vectorFile,
        selectedEmbedding
292
    ]);
293

P
Peter Pan 已提交
294 295 296 297 298 299 300 301 302 303
    const [perplexity, setPerplexity] = useState(5);
    const [learningRate, setLearningRate] = useState(10);

    const [neighbors, setNeighbors] = useState(15);
    const runUMAP = useCallback((n: number) => {
        setNeighbors(n);
        chart.current?.rerunUMAP();
    }, []);

    const [data, setData] = useState<PCAResult | TSNEResult | UMAPResult>();
304

P
Peter Pan 已提交
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
    const calculate = useCallback(() => {
        setData(undefined);
        setLoadingPhase('calculating');
    }, []);
    const calculated = useCallback((data: PCAResult | TSNEResult | UMAPResult) => {
        setData(data);
        setLoading(false);
    }, []);

    const [searchResult, setSearchResult] = useState<Parameters<NonNullable<LabelSearchInputProps['onChange']>>['0']>({
        labelBy: undefined,
        value: ''
    });

    const searchedResult = useMemo(() => {
        if (searchResult.labelBy == null || searchResult.value === '') {
            return {
                indices: [],
                metadata: []
            };
        }
        const labelByLabels = getLabelByLabels(searchResult.labelBy);
        const metadataResult: string[] = [];
        const vectorsIndices: number[] = [];
        for (let i = 0; i < labelByLabels.length; i++) {
            if (labelByLabels[i].includes(searchResult.value)) {
                metadataResult.push(labelByLabels[i]);
                vectorsIndices.push(i);
            }
        }
        // const vectorsResult = new Float32Array(vectorsIndices.length * dim);
        // for (let i = 0; i < vectorsIndices.length; i++) {
        //     vectorsResult.set(vectors.subarray(vectorsIndices[i] * dim, vectorsIndices[i] * dim + dim), i * dim);
        // }
        return {
            indices: vectorsIndices,
            metadata: metadataResult
        };
    }, [getLabelByLabels, searchResult.labelBy, searchResult.value]);

P
Peter Pan 已提交
345 346 347 348 349 350
    const [hoveredIndices, setHoveredIndices] = useState<number[]>([]);
    const hoverSearchResult = useCallback(
        (index?: number) => setHoveredIndices(index == null ? [] : [searchedResult.indices[index]]),
        [searchedResult.indices]
    );

P
Peter Pan 已提交
351 352 353
    const detail = useMemo(() => {
        switch (reduction) {
            case 'pca':
P
Peter Pan 已提交
354 355 356 357 358 359 360
                return (
                    <PCADetail
                        dimension={dimension}
                        variance={(data as PCAResult)?.variance ?? []}
                        totalVariance={(data as PCAResult)?.totalVariance ?? 0}
                    />
                );
P
Peter Pan 已提交
361 362 363 364 365 366
            case 'tsne':
                return (
                    <TSNEDetail
                        iteration={(data as TSNEResult)?.step ?? 0}
                        perplexity={perplexity}
                        learningRate={learningRate}
367
                        is3D={is3D}
P
Peter Pan 已提交
368 369 370 371 372 373 374 375 376 377 378 379 380
                        onChangePerplexity={setPerplexity}
                        onChangeLearningRate={setLearningRate}
                        onPause={chart.current?.pauseTSNE}
                        onResume={chart.current?.resumeTSNE}
                        onStop={chart.current?.pauseTSNE}
                        onRerun={chart.current?.rerunTSNE}
                    />
                );
            case 'umap':
                return <UMAPDetail neighbors={neighbors} onRun={runUMAP} />;
            default:
                return null as never;
        }
381
    }, [reduction, dimension, data, perplexity, learningRate, is3D, neighbors, runUMAP]);
P
Peter Pan 已提交
382 383

    const aside = useMemo(
P
Peter Pan 已提交
384 385 386 387 388 389 390 391 392 393 394 395 396 397
        () => (
            <RightAside>
                <AsideSection>
                    <AsideTitle>{t('high-dimensional:data')}</AsideTitle>
                    <Field label={t('high-dimensional:select-data')}>
                        <FullWidthSelect
                            list={embeddingList}
                            value={selectedEmbeddingName}
                            onChange={setSelectedEmbeddingName}
                        />
                    </Field>
                    <Field label={t('high-dimensional:select-label')}>
                        <FullWidthSelect list={labels} value={labelBy} onChange={setLabelBy} />
                    </Field>
P
Peter Pan 已提交
398 399 400
                    {/* <Field label={t('high-dimensional:select-color')}>
                        <FullWidthSelect />
                    </Field> */}
P
Peter Pan 已提交
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
                    <Field>
                        <FullWidthButton rounded outline type="primary" onClick={() => setUploadModal(true)}>
                            {t('high-dimensional:upload-data')}
                        </FullWidthButton>
                    </Field>
                    <Field>
                        {dataPath && (
                            <div className="secondary">
                                {t('high-dimensional:data-path')}
                                {t('common:colon')}
                                {dataPath}
                            </div>
                        )}
                    </Field>
                </AsideSection>
                <AsideSection>
                    <Field>
                        <ReductionTab value={reduction} onChange={setReduction} />
                    </Field>
                    <Field label={t('high-dimensional:dimension')}>
                        <DimensionSwitch value={dimension} onChange={setDimension} />
                    </Field>
                    {detail}
                </AsideSection>
            </RightAside>
        ),
P
Peter Pan 已提交
427
        [t, dataPath, reduction, dimension, labels, labelBy, embeddingList, selectedEmbeddingName, detail]
P
Peter Pan 已提交
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
    );

    const leftAside = useMemo(
        () => (
            <LeftAside>
                <AsideSection>
                    <Field>
                        <LabelSearchInput labels={labels} onChange={setSearchResult} />
                    </Field>
                    {searchResult.value !== '' && (
                        <Field className="secondary">
                            <span>
                                {t('high-dimensional:matched-result-count', {
                                    count: searchedResult.metadata.length
                                })}
                            </span>
444
                        </Field>
P
Peter Pan 已提交
445 446 447 448
                    )}
                </AsideSection>
                <AsideSection className="search-result">
                    <Field>
P
Peter Pan 已提交
449
                        <LabelSearchResult list={searchedResult.metadata} onHovered={hoverSearchResult} />
P
Peter Pan 已提交
450 451 452 453
                    </Field>
                </AsideSection>
            </LeftAside>
        ),
P
Peter Pan 已提交
454
        [hoverSearchResult, labels, searchResult.value, searchedResult.metadata, t]
455 456 457 458 459
    );

    return (
        <>
            <Title>{t('common:high-dimensional')}</Title>
P
Peter Pan 已提交
460 461 462
            {loading || loadingList ? <BodyLoading>{t(`high-dimensional:loading.${loadingPhase}`)}</BodyLoading> : null}
            <HDContent aside={aside} leftAside={leftAside}>
                {hasVector ? (
463
                    <HighDimensionalChart
P
Peter Pan 已提交
464 465 466
                        ref={chart}
                        vectors={vectors}
                        labels={labelByLabels}
P
Peter Pan 已提交
467
                        shape={rawShape}
P
Peter Pan 已提交
468 469
                        dim={dim}
                        is3D={is3D}
470
                        reduction={reduction}
P
Peter Pan 已提交
471 472 473
                        perplexity={perplexity}
                        learningRate={learningRate}
                        neighbors={neighbors}
P
Peter Pan 已提交
474
                        focusedIndices={hoveredIndices}
P
Peter Pan 已提交
475 476 477 478
                        highlightIndices={searchedResult.indices}
                        onCalculate={calculate}
                        onCalculated={calculated}
                        onError={showError}
479
                    />
P
Peter Pan 已提交
480 481
                ) : (
                    <Error />
482
                )}
P
Peter Pan 已提交
483 484 485 486 487 488 489 490
                <UploadDialog
                    open={uploadModal}
                    hasVector={hasVector}
                    onClose={() => setUploadModal(false)}
                    onChangeVectorFile={changeVectorFile}
                    onChangeMetadataFile={setMetadataFile}
                />
            </HDContent>
491 492 493 494 495
        </>
    );
};

export default HighDimensional;