Para.tsx 12.4 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
54
            noChart: true,
            customizeColumnsDialogVisible: false,
            availableDimensions: [],
            chosenDimensions: []
Deshui Yu's avatar
Deshui Yu committed
55
56
        };
    }
57

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

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

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

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

Lijiao's avatar
Lijiao committed
87
    render(): React.ReactNode {
88
89
90
91
92
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
133
134
                {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}
                    />
                )}
135
136
                <div className='parcoords' style={this.chartMulineStyle} ref={this.paraRef} />
                {noChart && <div className='nodata'>No data</div>}
137
            </div>
Deshui Yu's avatar
Deshui Yu committed
138
139
        );
    }
140

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

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

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

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

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

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

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

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

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

334
export default Para;