Para.tsx 12.5 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
27
    trials: Array<TableObj>;
    searchSpace: SearchSpace;
    whichChart: string;
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
55
            noChart: true,
            customizeColumnsDialogVisible: false,
            availableDimensions: [],
            chosenDimensions: []
Deshui Yu's avatar
Deshui Yu committed
56
57
        };
    }
58

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

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

Lijiao's avatar
Lijiao committed
77
    componentDidMount(): void {
78
        this.renderParallelCoordinates();
79
80
    }

81
    componentDidUpdate(prevProps: ParaProps): void {
82
83
84
85
86
        // FIXME: redundant update
        if (this.props.trials !== prevProps.trials || this.props.searchSpace !== prevProps.searchSpace) {
            const { whichChart } = this.props;
            if (whichChart === 'Hyper-parameter') {
                this.renderParallelCoordinates();
87
            }
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
137
138
                {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}
                    />
                )}
139
140
                <div className='parcoords' style={this.chartMulineStyle} ref={this.paraRef} />
                {noChart && <div className='nodata'>No data</div>}
141
            </div>
Deshui Yu's avatar
Deshui Yu committed
142
143
        );
    }
144

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

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

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

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

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

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

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

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

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

338
export default Para;