Para.tsx 12.7 KB
Newer Older
1
import * as d3 from 'd3';
2
import { Dropdown, IDropdownOption, Stack, DefaultButton } from '@fluentui/react';
3
4
import ParCoords from 'parcoord-es';
import 'parcoord-es/dist/parcoords.css';
Deshui Yu's avatar
Deshui Yu committed
5
import * as React from 'react';
6
import { EXPERIMENT, TRIALS } from '../../static/datamodel';
7
8
9
import { SearchSpace } from '../../static/model/searchspace';
import { filterByStatus } from '../../static/function';
import { TableObj, SingleAxis, MultipleAxes } from '../../static/interface';
10
import '../../static/style/button.scss';
11
import '../../static/style/para.scss';
12
import ChangeColumnComponent from '../modals/ChangeColumnComponent';
13

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

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

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

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

    constructor(props: ParaProps) {
Deshui Yu's avatar
Deshui Yu committed
46
47
48
        super(props);
        this.state = {
            dimName: [],
49
50
            primaryMetricKey: 'default',
            selectedPercent: '1',
51
52
53
            noChart: true,
            customizeColumnsDialogVisible: false,
            availableDimensions: [],
54
55
56
57
58
            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
59
60
        };
    }
61

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

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

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

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

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

Deshui Yu's avatar
Deshui Yu committed
100
        return (
101
102
            <div className='parameter'>
                <Stack horizontal className='para-filter' horizontalAlign='end'>
103
104
105
106
107
108
109
                    <DefaultButton
                        text='Add/Remove axes'
                        onClick={(): void => {
                            this.setState({ customizeColumnsDialogVisible: true });
                        }}
                        styles={{ root: { marginRight: 10 } }}
                    />
110
                    <Dropdown
111
                        selectedKey={selectedPercent}
112
113
                        onChange={this.percentNum}
                        options={[
114
115
116
                            { key: '0.01', text: 'Top 1%' },
                            { key: '0.05', text: 'Top 5%' },
                            { key: '0.2', text: 'Top 20%' },
117
                            { key: '1', text: 'Top 100%' }
118
                        ]}
119
                        styles={{ dropdown: { width: 120 } }}
120
                        className='para-filter-percent'
121
                    />
122
                    {this.finalKeysDropdown()}
123
                </Stack>
124
125
126
127
128
129
130
131
132
133
134
135
136
                {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}
137
                        whichComponent='para'
138
139
                    />
                )}
140
141
                <div className='parcoords' style={this.chartMulineStyle} ref={this.paraRef} />
                {noChart && <div className='nodata'>No data</div>}
142
            </div>
Deshui Yu's avatar
Deshui Yu committed
143
144
        );
    }
145

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

173
174
175
176
177
178
179
180
181
    /**
     * 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);
182
        const { primaryMetricKey, chosenDimensions } = this.state;
183
184
185
186
187

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

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

Lijiaoa's avatar
Lijiaoa committed
242
        if (convertedTrials.length === 0 || dimensions.length <= 1) {
243
244
245
246
247
248
249
            return;
        }

        const firstRun = this.pcs === undefined;
        if (firstRun) {
            this.pcs = ParCoords()(this.paraRef.current);
        }
250
251
        this.pcs
            .data(convertedTrials)
252
253
254
255
256
            .dimensions(
                dimensions
                    .filter(([d, _]) => chosenDimensions.length === 0 || chosenDimensions.includes(d))
                    .reduce((obj, entry) => ({ ...obj, [entry[0]]: entry[1] }), {})
            );
257
        if (firstRun) {
258
259
            this.pcs
                .margin(this.innerChartMargins)
260
261
                .alphaOnBrushed(0.2)
                .smoothness(0.1)
262
                .brushMode('1D-axes')
263
264
265
266
267
268
269
270
271
272
                .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 });
        }
273
274
275
276
277
278

        // set new available dims
        this.setState({
            availableDimensions: dimensions.map(e => e[0]),
            chosenDimensions: chosenDimensions.length === 0 ? dimensions.map(e => e[0]) : chosenDimensions
        });
279
280
281
282
283
284
285
286
    }

    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());
287
            entries.push(...Array.from(s.metrics(inferredMetricSpace).entries()));
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
            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];
    }
303

304
305
    private convertToD3Scale(axis: SingleAxis, initRange: boolean = true): any {
        const padLinear = ([x0, x1], k = 0.1): [number, number] => {
306
            const dx = ((x1 - x0) * k) / 2;
307
308
309
310
311
            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)];
312
        };
313
314
315
316
        let scaleInst: any = undefined;
        if (axis.scale === 'ordinal') {
            if (axis.nested) {
                // TODO: handle nested entries
317
318
319
320
                scaleInst = d3
                    .scalePoint()
                    .domain(Array.from(axis.domain.keys()))
                    .padding(0.2);
321
            } else {
322
323
324
325
                scaleInst = d3
                    .scalePoint()
                    .domain(axis.domain)
                    .padding(0.2);
326
327
328
329
330
331
332
333
334
335
336
            }
        } 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
337
338
}

339
export default Para;