Para.tsx 12.5 KB
Newer Older
Lijiaoa's avatar
Lijiaoa committed
1
import * as React from 'react';
2
import * as d3 from 'd3';
3
import { Dropdown, IDropdownOption, Stack, DefaultButton } from '@fluentui/react';
4
import ParCoords from 'parcoord-es';
Lijiaoa's avatar
Lijiaoa committed
5
6
7
8
9
10
import { SearchSpace } from '@model/searchspace';
import { filterByStatus } from '@static/function';
import { EXPERIMENT, TRIALS } from '@static/datamodel';
import { TableObj, SingleAxis, MultipleAxes } from '@static/interface';
import ChangeColumnComponent from '../ChangeColumnComponent';

11
import 'parcoord-es/dist/parcoords.css';
Lijiaoa's avatar
Lijiaoa committed
12
13
import '@style/button.scss';
import '@style/experiment/trialdetail/para.scss';
14

Deshui Yu's avatar
Deshui Yu committed
15
interface ParaState {
16
    dimName: string[];
17
18
19
    selectedPercent: string;
    primaryMetricKey: string;
    noChart: boolean;
20
21
22
    customizeColumnsDialogVisible: boolean;
    availableDimensions: string[];
    chosenDimensions: string[];
Deshui Yu's avatar
Deshui Yu committed
23
24
}

25
interface ParaProps {
26
27
    trials: Array<TableObj>;
    searchSpace: SearchSpace;
Lijiao's avatar
Lijiao committed
28
29
}

30
class Para extends React.Component<ParaProps, ParaState> {
31
32
33
    private paraRef = React.createRef<HTMLDivElement>();
    private pcs: any;

34
35
36
    private chartMulineStyle = {
        width: '100%',
        height: 392,
37
38
39
40
41
42
43
        margin: '0 auto'
    };
    private innerChartMargins = {
        top: 32,
        right: 20,
        bottom: 20,
        left: 28
44
45
46
    };

    constructor(props: ParaProps) {
Deshui Yu's avatar
Deshui Yu committed
47
48
49
        super(props);
        this.state = {
            dimName: [],
50
51
            primaryMetricKey: 'default',
            selectedPercent: '1',
52
53
54
            noChart: true,
            customizeColumnsDialogVisible: false,
            availableDimensions: [],
55
56
57
58
59
            chosenDimensions:
                localStorage.getItem('paraColumns') !== null
                    ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
                      JSON.parse(localStorage.getItem('paraColumns')!)
                    : []
Deshui Yu's avatar
Deshui Yu committed
60
61
        };
    }
62

Deshui Yu's avatar
Deshui Yu committed
63
    // get percent value number
64
65
    percentNum = (event: React.FormEvent<HTMLDivElement>, item?: IDropdownOption): void => {
        if (item !== undefined) {
66
67
            this.setState({ selectedPercent: item.key.toString() }, () => {
                this.renderParallelCoordinates();
68
69
            });
        }
70
    };
Deshui Yu's avatar
Deshui Yu committed
71

72
73
74
    // select all final keys
    updateEntries = (event: React.FormEvent<HTMLDivElement>, item: any): void => {
        if (item !== undefined) {
75
76
77
            this.setState({ primaryMetricKey: item.key }, () => {
                this.renderParallelCoordinates();
            });
78
        }
79
    };
80

Lijiao's avatar
Lijiao committed
81
    componentDidMount(): void {
82
        this.renderParallelCoordinates();
83
84
    }

85
    componentDidUpdate(prevProps: ParaProps): void {
86
87
        // FIXME: redundant update
        if (this.props.trials !== prevProps.trials || this.props.searchSpace !== prevProps.searchSpace) {
88
            this.renderParallelCoordinates();
89
90
        }
    }
Deshui Yu's avatar
Deshui Yu committed
91

Lijiao's avatar
Lijiao committed
92
    render(): React.ReactNode {
93
94
        const { selectedPercent, noChart, customizeColumnsDialogVisible, availableDimensions, chosenDimensions } =
            this.state;
95

Deshui Yu's avatar
Deshui Yu committed
96
        return (
97
98
            <div className='parameter'>
                <Stack horizontal className='para-filter' horizontalAlign='end'>
99
100
101
102
103
104
105
                    <DefaultButton
                        text='Add/Remove axes'
                        onClick={(): void => {
                            this.setState({ customizeColumnsDialogVisible: true });
                        }}
                        styles={{ root: { marginRight: 10 } }}
                    />
106
                    <Dropdown
107
                        selectedKey={selectedPercent}
108
109
                        onChange={this.percentNum}
                        options={[
110
111
112
                            { key: '0.01', text: 'Top 1%' },
                            { key: '0.05', text: 'Top 5%' },
                            { key: '0.2', text: 'Top 20%' },
113
                            { key: '1', text: 'Top 100%' }
114
                        ]}
115
                        styles={{ dropdown: { width: 120 } }}
116
                        className='para-filter-percent'
117
                    />
118
                    {this.finalKeysDropdown()}
119
                </Stack>
120
121
122
123
124
125
126
127
128
129
130
131
132
                {customizeColumnsDialogVisible && availableDimensions.length > 0 && (
                    <ChangeColumnComponent
                        selectedColumns={chosenDimensions}
                        allColumns={availableDimensions.map(dim => ({ key: dim, name: dim }))}
                        onSelectedChange={(selected: string[]): void => {
                            this.setState({ chosenDimensions: selected }, () => {
                                this.renderParallelCoordinates();
                            });
                        }}
                        onHideDialog={(): void => {
                            this.setState({ customizeColumnsDialogVisible: false });
                        }}
                        minSelected={2}
133
                        whichComponent='para'
134
135
                    />
                )}
136
137
                <div className='parcoords' style={this.chartMulineStyle} ref={this.paraRef} />
                {noChart && <div className='nodata'>No data</div>}
138
            </div>
Deshui Yu's avatar
Deshui Yu committed
139
140
        );
    }
141

142
143
    private finalKeysDropdown(): any {
        const { primaryMetricKey } = this.state;
144
145
146
147
148
149
        if (TRIALS.finalKeys().length === 1) {
            return null;
        } else {
            const finalKeysDropdown: any = [];
            TRIALS.finalKeys().forEach(item => {
                finalKeysDropdown.push({
150
151
                    key: item,
                    text: item
152
153
154
155
                });
            });
            return (
                <div>
156
                    <span className='para-filter-text para-filter-middle'>Metrics</span>
157
                    <Dropdown
158
                        selectedKey={primaryMetricKey}
159
160
161
                        options={finalKeysDropdown}
                        onChange={this.updateEntries}
                        styles={{ root: { width: 150, display: 'inline-block' } }}
162
                        className='para-filter-percent'
163
164
165
166
                    />
                </div>
            );
        }
167
    }
168

169
170
171
172
173
174
175
176
177
    /**
     * Render the parallel coordinates. Using trial data as base and leverage
     * information from search space at a best effort basis.
     * @param source Array of trial data
     * @param searchSpace Search space
     */
    private renderParallelCoordinates(): void {
        const { searchSpace } = this.props;
        const percent = parseFloat(this.state.selectedPercent);
178
        const { primaryMetricKey, chosenDimensions } = this.state;
179
180
181
182
183

        const inferredSearchSpace = TRIALS.inferredSearchSpace(searchSpace);
        const inferredMetricSpace = TRIALS.inferredMetricSpace();
        let convertedTrials = this.getTrialsAsObjectList(inferredSearchSpace, inferredMetricSpace);

184
        const dimensions: [string, any][] = [];
185
186
        let colorDim: string | undefined = undefined,
            colorScale: any = undefined;
187
188
        // treat every axis as numeric to fit for brush
        for (const [k, v] of inferredSearchSpace.axes) {
189
190
191
192
193
194
195
            dimensions.push([
                k,
                {
                    type: 'number',
                    yscale: this.convertToD3Scale(v)
                }
            ]);
196
197
198
199
200
        }
        for (const [k, v] of inferredMetricSpace.axes) {
            const scale = this.convertToD3Scale(v);
            if (k === primaryMetricKey && scale !== undefined && scale.interpolate) {
                // set color for primary metrics
201
202
                // `colorScale` is used to produce a color range, while `scale` is to produce a pixel range
                colorScale = this.convertToD3Scale(v, false);
203
                convertedTrials.sort((a, b) => (EXPERIMENT.optimizeMode === 'minimize' ? a[k] - b[k] : b[k] - a[k]));
204
205
206
207
208
209
                // filter top trials
                if (percent != 1) {
                    const keptTrialNum = Math.max(Math.ceil(convertedTrials.length * percent), 1);
                    convertedTrials = convertedTrials.slice(0, keptTrialNum);
                    const domain = d3.extent(convertedTrials, item => item[k]);
                    scale.domain([domain[0], domain[1]]);
210
                    colorScale.domain([domain[0], domain[1]]);
211
212
213
214
                    if (colorScale !== undefined) {
                        colorScale.domain(domain);
                    }
                }
215
216
217
                // reverse the converted trials to show the top ones upfront
                convertedTrials.reverse();
                const assignColors = (scale: any): void => {
218
                    scale.range([0, 1]); // fake a range to perform invert
219
220
                    const [scaleMin, scaleMax] = scale.domain();
                    const pivot = scale.invert(0.5);
221
222
                    scale
                        .domain([scaleMin, pivot, scaleMax])
223
224
225
226
227
                        .range(['#90EE90', '#FFC400', '#CA0000'])
                        .interpolate(d3.interpolateHsl);
                };
                assignColors(colorScale);
                colorDim = k;
228
            }
229
230
231
232
233
234
235
            dimensions.push([
                k,
                {
                    type: 'number',
                    yscale: scale
                }
            ]);
236
237
        }

Lijiaoa's avatar
Lijiaoa committed
238
        if (convertedTrials.length === 0 || dimensions.length <= 1) {
239
240
241
242
243
244
245
            return;
        }

        const firstRun = this.pcs === undefined;
        if (firstRun) {
            this.pcs = ParCoords()(this.paraRef.current);
        }
246
247
        this.pcs
            .data(convertedTrials)
248
249
250
251
252
            .dimensions(
                dimensions
                    .filter(([d, _]) => chosenDimensions.length === 0 || chosenDimensions.includes(d))
                    .reduce((obj, entry) => ({ ...obj, [entry[0]]: entry[1] }), {})
            );
253
        if (firstRun) {
254
255
            this.pcs
                .margin(this.innerChartMargins)
256
257
                .alphaOnBrushed(0.2)
                .smoothness(0.1)
258
                .brushMode('1D-axes')
259
260
261
262
263
264
265
266
267
268
                .reorderable()
                .interactive();
        }
        if (colorScale !== undefined) {
            this.pcs.color(d => (colorScale as any)(d[colorDim as any]));
        }
        this.pcs.render();
        if (firstRun) {
            this.setState({ noChart: false });
        }
269
270
271
272
273
274

        // set new available dims
        this.setState({
            availableDimensions: dimensions.map(e => e[0]),
            chosenDimensions: chosenDimensions.length === 0 ? dimensions.map(e => e[0]) : chosenDimensions
        });
275
276
277
278
279
280
281
282
    }

    private getTrialsAsObjectList(inferredSearchSpace: MultipleAxes, inferredMetricSpace: MultipleAxes): {}[] {
        const { trials } = this.props;
        const succeededTrials = trials.filter(filterByStatus);

        return succeededTrials.map(s => {
            const entries = Array.from(s.parameters(inferredSearchSpace).entries());
283
            entries.push(...Array.from(s.metrics(inferredMetricSpace).entries()));
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
            const ret = {};
            for (const [k, v] of entries) {
                ret[k.fullName] = v;
            }
            return ret;
        });
    }

    private getRange(): [number, number] {
        // Documentation is lacking.
        // Reference: https://github.com/syntagmatic/parallel-coordinates/issues/308
        // const range = this.pcs.height() - this.pcs.margin().top - this.pcs.margin().bottom;
        const range = this.chartMulineStyle.height - this.innerChartMargins.top - this.innerChartMargins.bottom;
        return [range, 1];
    }
299

300
301
    private convertToD3Scale(axis: SingleAxis, initRange: boolean = true): any {
        const padLinear = ([x0, x1], k = 0.1): [number, number] => {
302
            const dx = ((x1 - x0) * k) / 2;
303
304
305
306
307
            return [x0 - dx, x1 + dx];
        };
        const padLog = ([x0, x1], k = 0.1): [number, number] => {
            const [y0, y1] = padLinear([Math.log(x0), Math.log(x1)], k);
            return [Math.exp(y0), Math.exp(y1)];
308
        };
309
310
311
312
        let scaleInst: any = undefined;
        if (axis.scale === 'ordinal') {
            if (axis.nested) {
                // TODO: handle nested entries
313
                scaleInst = d3.scalePoint().domain(Array.from(axis.domain.keys())).padding(0.2);
314
            } else {
315
                scaleInst = d3.scalePoint().domain(axis.domain).padding(0.2);
316
317
318
319
320
321
322
323
324
325
326
            }
        } else if (axis.scale === 'log') {
            scaleInst = d3.scaleLog().domain(padLog(axis.domain));
        } else if (axis.scale === 'linear') {
            scaleInst = d3.scaleLinear().domain(padLinear(axis.domain));
        }
        if (initRange) {
            scaleInst = scaleInst.range(this.getRange());
        }
        return scaleInst;
    }
Deshui Yu's avatar
Deshui Yu committed
327
328
}

329
export default Para;