TableList.tsx 23.3 KB
Newer Older
Lijiao's avatar
Lijiao committed
1
2
3
import * as React from 'react';
import axios from 'axios';
import ReactEcharts from 'echarts-for-react';
4
import { Row, Table, Button, Popconfirm, Modal, Checkbox, Select, Icon } from 'antd';
5
import { ColumnProps } from 'antd/lib/table';
6
const Option = Select.Option;
7
const CheckboxGroup = Checkbox.Group;
8
import { MANAGER_IP, trialJobStatus, COLUMN_INDEX, COLUMNPro } from '../../static/const';
9
import { convertDuration, formatTimestamp, intermediateGraphOption, killJob } from '../../static/function';
10
import { EXPERIMENT, TRIALS } from '../../static/datamodel';
11
import { TableRecord } from '../../static/interface';
Lijiao's avatar
Lijiao committed
12
import OpenRow from '../public-child/OpenRow';
Lijiao's avatar
Lijiao committed
13
import Compare from '../Modal/Compare';
14
import Customize from '../Modal/CustomizedTrial';
15
import '../../static/style/search.scss';
Lijiao's avatar
Lijiao committed
16
17
require('../../static/style/tableStatus.css');
require('../../static/style/logPath.scss');
18
require('../../static/style/search.scss');
Lijiao's avatar
Lijiao committed
19
20
require('../../static/style/table.scss');
require('../../static/style/button.scss');
Lijiao's avatar
Lijiao committed
21
require('../../static/style/openRow.scss');
Lijiao's avatar
Lijiao committed
22
23
24
25
26
27
28
29
30
const echarts = require('echarts/lib/echarts');
require('echarts/lib/chart/line');
require('echarts/lib/component/tooltip');
require('echarts/lib/component/title');
echarts.registerTheme('my_theme', {
    color: '#3c8dbc'
});

interface TableListProps {
31
32
    pageSize: number;
    tableSource: Array<TableRecord>;
33
34
    columnList: Array<string>; // user select columnKeys
    changeColumn: (val: Array<string>) => void;
35
    trialsUpdateBroadcast: number;
Lijiao's avatar
Lijiao committed
36
37
38
39
40
}

interface TableListState {
    intermediateOption: object;
    modalVisible: boolean;
41
42
    isObjFinal: boolean;
    isShowColumn: boolean;
43
    selectRows: Array<TableRecord>;
Lijiao's avatar
Lijiao committed
44
45
    isShowCompareModal: boolean;
    selectedRowKeys: string[] | number[];
46
47
48
    intermediateData: Array<object>; // a trial's intermediate results (include dict)
    intermediateId: string;
    intermediateOtherKeys: Array<string>;
49
50
    isShowCustomizedModal: boolean;
    copyTrialId: string; // user copy trial to submit a new customized trial
51
52
53
54
55
}

interface ColumnIndex {
    name: string;
    index: number;
Lijiao's avatar
Lijiao committed
56
57
}

Lijiao's avatar
Lijiao committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
const AccuracyColumnConfig: ColumnProps<TableRecord> = {
    title: 'Default metric',
    className: 'leftTitle',
    dataIndex: 'accuracy',
    sorter: (a, b, sortOrder) => {
        if (a.latestAccuracy === undefined) {
            return sortOrder === 'ascend' ? 1 : -1;
        } else if (b.latestAccuracy === undefined) {
            return sortOrder === 'ascend' ? -1 : 1;
        } else {
            return a.latestAccuracy - b.latestAccuracy;
        }
    },
    render: (text, record): React.ReactNode => <div>{record.formattedLatestAccuracy}</div>
};

const SequenceIdColumnConfig: ColumnProps<TableRecord> = {
    title: 'Trial No.',
    dataIndex: 'sequenceId',
    className: 'tableHead',
    sorter: (a, b) => a.sequenceId - b.sequenceId
};

const IdColumnConfig: ColumnProps<TableRecord> = {
    title: 'ID',
    dataIndex: 'id',
    className: 'tableHead leftTitle',
    sorter: (a, b) => a.id.localeCompare(b.id),
    render: (text, record): React.ReactNode => (
        <div>{record.id}</div>
    )
};

const StartTimeColumnConfig: ColumnProps<TableRecord> = {
    title: 'Start Time',
    dataIndex: 'startTime',
    sorter: (a, b) => a.startTime - b.startTime,
    render: (text, record): React.ReactNode => (
        <span>{formatTimestamp(record.startTime)}</span>
    )
};

const EndTimeColumnConfig: ColumnProps<TableRecord> = {
    title: 'End Time',
    dataIndex: 'endTime',
    sorter: (a, b, sortOrder) => {
        if (a.endTime === undefined) {
            return sortOrder === 'ascend' ? 1 : -1;
        } else if (b.endTime === undefined) {
            return sortOrder === 'ascend' ? -1 : 1;
        } else {
            return a.endTime - b.endTime;
        }
    },
    render: (text, record): React.ReactNode => (
        <span>{formatTimestamp(record.endTime, '--')}</span>
    )
};

const DurationColumnConfig: ColumnProps<TableRecord> = {
    title: 'Duration',
    dataIndex: 'duration',
    sorter: (a, b) => a.duration - b.duration,
    render: (text, record): React.ReactNode => (
        <span className="durationsty">{convertDuration(record.duration)}</span>
    )
};

const StatusColumnConfig: ColumnProps<TableRecord> = {
    title: 'Status',
    dataIndex: 'status',
    className: 'tableStatus',
    render: (text, record): React.ReactNode => (
        <span className={`${record.status} commonStyle`}>{record.status}</span>
    ),
    sorter: (a, b) => a.status.localeCompare(b.status),
    filters: trialJobStatus.map(status => ({ text: status, value: status })),
    onFilter: (value, record) => (record.status === value)
};

const IntermediateCountColumnConfig: ColumnProps<TableRecord> = {
    title: 'Intermediate result',
    dataIndex: 'intermediateCount',
    sorter: (a, b) => a.intermediateCount - b.intermediateCount,
    render: (text, record): React.ReactNode => (
        <span>{`#${record.intermediateCount}`}</span>
    )
};

Lijiao's avatar
Lijiao committed
147
148
class TableList extends React.Component<TableListProps, TableListState> {

149
150
    public intervalTrialLog = 10;
    public _trialId: string;
151
    public tables: Table<TableRecord> | null;
152

Lijiao's avatar
Lijiao committed
153
154
155
156
157
    constructor(props: TableListProps) {
        super(props);

        this.state = {
            intermediateOption: {},
158
159
160
            modalVisible: false,
            isObjFinal: false,
            isShowColumn: false,
Lijiao's avatar
Lijiao committed
161
162
            isShowCompareModal: false,
            selectRows: [],
163
164
165
            selectedRowKeys: [], // close selected trial message after modal closed
            intermediateData: [],
            intermediateId: '',
166
167
168
            intermediateOtherKeys: [],
            isShowCustomizedModal: false,
            copyTrialId: ''
Lijiao's avatar
Lijiao committed
169
170
171
        };
    }

Lijiao's avatar
Lijiao committed
172
    showIntermediateModal = async (id: string): Promise<void> => {
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
        const res = await axios.get(`${MANAGER_IP}/metric-data/${id}`);
        if (res.status === 200) {
            const intermediateArr: number[] = [];
            // support intermediate result is dict because the last intermediate result is
            // final result in a succeed trial, it may be a dict.
            // get intermediate result dict keys array
            let otherkeys: Array<string> = ['default'];
            if (res.data.length !== 0) {
                otherkeys = Object.keys(JSON.parse(res.data[0].data));
            }
            // intermediateArr just store default val
            Object.keys(res.data).map(item => {
                const temp = JSON.parse(res.data[item].data);
                if (typeof temp === 'object') {
                    intermediateArr.push(temp.default);
                } else {
                    intermediateArr.push(temp);
Lijiao's avatar
Lijiao committed
190
191
                }
            });
192
            const intermediate = intermediateGraphOption(intermediateArr, id);
Lijiao's avatar
Lijiao committed
193
            this.setState({
194
195
196
197
                intermediateData: res.data, // store origin intermediate data for a trial
                intermediateOption: intermediate,
                intermediateOtherKeys: otherkeys,
                intermediateId: id
Lijiao's avatar
Lijiao committed
198
199
            });
        }
200
        this.setState({ modalVisible: true });
Lijiao's avatar
Lijiao committed
201
202
    }

203
204
    // intermediate button click -> intermediate graph for each trial
    // support intermediate is dict
Lijiao's avatar
Lijiao committed
205
    selectOtherKeys = (value: string): void => {
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229

        const isShowDefault: boolean = value === 'default' ? true : false;
        const { intermediateData, intermediateId } = this.state;
        const intermediateArr: number[] = [];
        // just watch default key-val
        if (isShowDefault === true) {
            Object.keys(intermediateData).map(item => {
                const temp = JSON.parse(intermediateData[item].data);
                if (typeof temp === 'object') {
                    intermediateArr.push(temp[value]);
                } else {
                    intermediateArr.push(temp);
                }
            });
        } else {
            Object.keys(intermediateData).map(item => {
                const temp = JSON.parse(intermediateData[item].data);
                if (typeof temp === 'object') {
                    intermediateArr.push(temp[value]);
                }
            });
        }
        const intermediate = intermediateGraphOption(intermediateArr, intermediateId);
        // re-render
230
231
232
        this.setState({
            intermediateOption: intermediate
        });
233
234
    }

Lijiao's avatar
Lijiao committed
235
    hideIntermediateModal = (): void => {
236
237
238
        this.setState({
            modalVisible: false
        });
Lijiao's avatar
Lijiao committed
239
240
    }

Lijiao's avatar
Lijiao committed
241
    hideShowColumnModal = (): void => {
242
243
244
        this.setState({
            isShowColumn: false
        });
245
246
247
    }

    // click add column btn, just show the modal of addcolumn
Lijiao's avatar
Lijiao committed
248
    addColumn = (): void => {
249
        // show user select check button
250
251
252
        this.setState({
            isShowColumn: true
        });
253
254
255
    }

    // checkbox for coloumn
Lijiao's avatar
Lijiao committed
256
    selectedColumn = (checkedValues: Array<string>): void => {
257
258
259
        // 9: because have nine common column, 
        // [Intermediate count, Start Time, End Time] is hidden by default
        let count = 9;
260
261
262
263
264
        const want: Array<object> = [];
        const finalKeys: Array<string> = [];
        const wantResult: Array<string> = [];
        Object.keys(checkedValues).map(m => {
            switch (checkedValues[m]) {
Lijiao's avatar
Lijiao committed
265
                case 'Trial No.':
Lijiao's avatar
Lijiao committed
266
                case 'ID':
267
268
                case 'Start Time':
                case 'End Time':
Lijiao's avatar
Lijiao committed
269
270
                case 'Duration':
                case 'Status':
271
272
                case 'Operation':
                case 'Default':
273
                case 'Intermediate result':
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
                    break;
                default:
                    finalKeys.push(checkedValues[m]);
            }
        });

        Object.keys(finalKeys).map(n => {
            want.push({
                name: finalKeys[n],
                index: count++
            });
        });

        Object.keys(checkedValues).map(item => {
            const temp = checkedValues[item];
            Object.keys(COLUMN_INDEX).map(key => {
                const index = COLUMN_INDEX[key];
                if (index.name === temp) {
                    want.push(index);
                }
            });
        });

        want.sort((a: ColumnIndex, b: ColumnIndex) => {
            return a.index - b.index;
        });

        Object.keys(want).map(i => {
            wantResult.push(want[i].name);
        });

305
        this.props.changeColumn(wantResult);
306
307
    }

Lijiao's avatar
Lijiao committed
308
    openRow = (record: TableRecord): any => {
Lijiao's avatar
Lijiao committed
309
        return (
310
            <OpenRow trialId={record.id} />
Lijiao's avatar
Lijiao committed
311
312
313
        );
    }

Lijiao's avatar
Lijiao committed
314
    fillSelectedRowsTostate = (selected: number[] | string[], selectedRows: Array<TableRecord>): void => {
315
        this.setState({ selectRows: selectedRows, selectedRowKeys: selected });
Lijiao's avatar
Lijiao committed
316
317
    }
    // open Compare-modal
Lijiao's avatar
Lijiao committed
318
    compareBtn = (): void => {
Lijiao's avatar
Lijiao committed
319
320
321
322
323

        const { selectRows } = this.state;
        if (selectRows.length === 0) {
            alert('Please select datas you want to compare!');
        } else {
324
            this.setState({ isShowCompareModal: true });
Lijiao's avatar
Lijiao committed
325
326
327
        }
    }
    // close Compare-modal
Lijiao's avatar
Lijiao committed
328
    hideCompareModal = (): void => {
Lijiao's avatar
Lijiao committed
329
        // close modal. clear select rows data, clear selected track
330
        this.setState({ isShowCompareModal: false, selectedRowKeys: [], selectRows: [] });
Lijiao's avatar
Lijiao committed
331
332
    }

333
    // open customized trial modal
Lijiao's avatar
Lijiao committed
334
    setCustomizedTrial = (trialId: string): void => {
335
336
337
338
339
340
        this.setState({
            isShowCustomizedModal: true,
            copyTrialId: trialId
        });
    }

Lijiao's avatar
Lijiao committed
341
    closeCustomizedTrial = (): void => {
342
343
344
345
346
        this.setState({
            isShowCustomizedModal: false,
            copyTrialId: ''
        });
    }
Lijiao's avatar
Lijiao committed
347
    render(): React.ReactNode {
348
349
        const { pageSize, columnList } = this.props;
        const tableSource: Array<TableRecord> = JSON.parse(JSON.stringify(this.props.tableSource));
350
        const { intermediateOption, modalVisible, isShowColumn,
351
352
353
            selectRows, isShowCompareModal, selectedRowKeys, intermediateOtherKeys,
            isShowCustomizedModal, copyTrialId
        } = this.state;
Lijiao's avatar
Lijiao committed
354
355
        const rowSelection = {
            selectedRowKeys: selectedRowKeys,
Lijiao's avatar
Lijiao committed
356
            onChange: (selected: string[] | number[], selectedRows: Array<TableRecord>): void => {
Lijiao's avatar
Lijiao committed
357
358
359
                this.fillSelectedRowsTostate(selected, selectedRows);
            }
        };
360
361
362
        // [supportCustomizedTrial: true]
        const supportCustomizedTrial = (EXPERIMENT.multiPhase === true) ? false : true;
        const disabledAddCustomizedTrial = ['DONE', 'ERROR', 'STOPPED'].includes(EXPERIMENT.status);
363
        let showTitle = COLUMNPro;
364
        const showColumn: Array<object> = [];
365
366
367

        // parameter as table column
        const parameterStr: Array<string> = [];
368
369
370
371
372
373
374
375
        if (tableSource.length > 0) {
            const trialMess = TRIALS.getTrial(tableSource[0].id);
            const trial = trialMess.description.parameters;
            const parameterColumn: Array<string> = Object.keys(trial);
            parameterColumn.forEach(value => {
                parameterStr.push(`${value} (search space)`);
            });
        }
376
377
        showTitle = COLUMNPro.concat(parameterStr);

378
        // only succeed trials have final keys
379
380
        if (tableSource.filter(record => record.status === 'SUCCEEDED').length >= 1) {
            const temp = tableSource.filter(record => record.status === 'SUCCEEDED')[0].accuracy;
381
            if (temp !== undefined && typeof temp === 'object') {
382
383
384
385
386
387
388
389
390
391
392
393
                // concat default column and finalkeys
                const item = Object.keys(temp);
                // item: ['default', 'other-keys', 'maybe loss']
                if (item.length > 1) {
                    const want: Array<string> = [];
                    item.forEach(value => {
                        if (value !== 'default') {
                            want.push(value);
                        }
                    });
                    showTitle = COLUMNPro.concat(want);
                }
394
395
            }
        }
396
        for (const item of columnList) {
397
398
399
400
401
            const paraColumn = item.match(/ \(search space\)$/);
            let cc;
            if (paraColumn !== null) {
                cc = paraColumn.input;
            }
402
            switch (item) {
Lijiao's avatar
Lijiao committed
403
                case 'Trial No.':
404
                    showColumn.push(SequenceIdColumnConfig);
405
                    break;
Lijiao's avatar
Lijiao committed
406
                case 'ID':
407
                    showColumn.push(IdColumnConfig);
408
                    break;
409
410
                case 'Start Time':
                    showColumn.push(StartTimeColumnConfig);
411
                    break;
412
413
                case 'End Time':
                    showColumn.push(EndTimeColumnConfig);
414
                    break;
Lijiao's avatar
Lijiao committed
415
                case 'Duration':
416
                    showColumn.push(DurationColumnConfig);
417
                    break;
Lijiao's avatar
Lijiao committed
418
                case 'Status':
419
                    showColumn.push(StatusColumnConfig);
420
                    break;
421
                case 'Intermediate result':
422
                    showColumn.push(IntermediateCountColumnConfig);
423
                    break;
424
                case 'Default':
425
                    showColumn.push(AccuracyColumnConfig);
426
427
428
429
430
431
                    break;
                case 'Operation':
                    showColumn.push({
                        title: 'Operation',
                        dataIndex: 'operation',
                        key: 'operation',
432
                        render: (text: string, record: TableRecord) => {
Lijiao's avatar
Lijiao committed
433
                            const trialStatus = record.status;
Lijiao's avatar
Lijiao committed
434
435
                            // could kill a job when its status is RUNNING or UNKNOWN
                            const flag: boolean = (trialStatus === 'RUNNING' || trialStatus === 'UNKNOWN') ? false : true;
436
                            return (
437
438
439
440
441
442
443
444
445
446
447
                                <Row id="detail-button">
                                    {/* see intermediate result graph */}
                                    <Button
                                        type="primary"
                                        className="common-style"
                                        onClick={this.showIntermediateModal.bind(this, record.id)}
                                        title="Intermediate"
                                    >
                                        <Icon type="line-chart" />
                                    </Button>
                                    {/* kill job */}
Lijiao's avatar
Lijiao committed
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
                                    {
                                        flag
                                            ?
                                            <Button
                                                type="default"
                                                disabled={true}
                                                className="margin-mediate special"
                                                title="kill"
                                            >
                                                <Icon type="stop" />
                                            </Button>
                                            :
                                            <Popconfirm
                                                title="Are you sure to cancel this trial?"
                                                okText="Yes"
                                                cancelText="No"
                                                onConfirm={killJob.
                                                    bind(this, record.key, record.id, record.status)}
                                            >
                                                <Button
                                                    type="default"
                                                    disabled={false}
                                                    className="margin-mediate special"
                                                    title="kill"
                                                >
                                                    <Icon type="stop" />
                                                </Button>
                                            </Popconfirm>
                                    }
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
                                    {/* Add a new trial-customized trial */}
                                    {
                                        supportCustomizedTrial
                                            ?
                                            <Button
                                                type="primary"
                                                className="common-style"
                                                disabled={disabledAddCustomizedTrial}
                                                onClick={this.setCustomizedTrial.bind(this, record.id)}
                                                title="Customized trial"
                                            >
                                                <Icon type="copy" />
                                            </Button>
                                            :
                                            null
                                    }
493
                                </Row>
494
495
496
497
                            );
                        },
                    });
                    break;
498
499
                case (cc):
                    // remove SEARCH_SPACE title
Lijiao's avatar
Lijiao committed
500
                    // const realItem = item.replace(' (search space)', '');
501
                    showColumn.push({
Lijiao's avatar
Lijiao committed
502
                        title: item.replace(' (search space)', ''),
503
504
                        dataIndex: item,
                        key: item,
505
                        render: (text: string, record: TableRecord) => {
506
                            const eachTrial = TRIALS.getTrial(record.id);
507
                            return (
Lijiao's avatar
Lijiao committed
508
                                <span>{eachTrial.description.parameters[item.replace(' (search space)', '')]}</span>
509
510
511
512
513
                            );
                        },
                    });
                    break;
                default:
514
515
                    // FIXME
                    alert('Unexpected column type');
Lijiao's avatar
Lijiao committed
516
            }
517
        }
Lijiao's avatar
Lijiao committed
518
519
520
521
522

        return (
            <Row className="tableList">
                <div id="tableList">
                    <Table
Lijiao's avatar
Lijiao committed
523
                        ref={(table: Table<TableRecord> | null): any => this.tables = table}
524
                        columns={showColumn}
Lijiao's avatar
Lijiao committed
525
                        rowSelection={rowSelection}
Lijiao's avatar
Lijiao committed
526
                        expandedRowRender={this.openRow}
527
                        dataSource={tableSource}
Lijiao's avatar
Lijiao committed
528
                        className="commonTableStyle"
529
                        scroll={{ x: 'max-content' }}
530
                        pagination={pageSize > 0 ? { pageSize } : false}
Lijiao's avatar
Lijiao committed
531
                    />
532
                    {/* Intermediate Result Modal */}
Lijiao's avatar
Lijiao committed
533
                    <Modal
Lijiao's avatar
Lijiao committed
534
                        title="Intermediate result"
Lijiao's avatar
Lijiao committed
535
536
537
538
539
540
                        visible={modalVisible}
                        onCancel={this.hideIntermediateModal}
                        footer={null}
                        destroyOnClose={true}
                        width="80%"
                    >
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
                        {
                            intermediateOtherKeys.length > 1
                                ?
                                <Row className="selectKeys">
                                    <Select
                                        className="select"
                                        defaultValue="default"
                                        onSelect={this.selectOtherKeys}
                                    >
                                        {
                                            Object.keys(intermediateOtherKeys).map(item => {
                                                const keys = intermediateOtherKeys[item];
                                                return <Option value={keys} key={item}>{keys}</Option>;
                                            })
                                        }
                                    </Select>

                                </Row>
                                :
                                <div />
                        }
Lijiao's avatar
Lijiao committed
562
563
564
565
566
567
568
569
570
571
                        <ReactEcharts
                            option={intermediateOption}
                            style={{
                                width: '100%',
                                height: 0.7 * window.innerHeight
                            }}
                            theme="my_theme"
                        />
                    </Modal>
                </div>
572
573
574
575
576
577
578
579
580
581
582
                {/* Add Column Modal */}
                <Modal
                    title="Table Title"
                    visible={isShowColumn}
                    onCancel={this.hideShowColumnModal}
                    footer={null}
                    destroyOnClose={true}
                    width="40%"
                >
                    <CheckboxGroup
                        options={showTitle}
583
584
                        defaultValue={columnList}
                        // defaultValue={columnSelected}
585
586
587
588
                        onChange={this.selectedColumn}
                        className="titleColumn"
                    />
                </Modal>
589
                {/* compare trials based message */}
Lijiao's avatar
Lijiao committed
590
                <Compare compareRows={selectRows} visible={isShowCompareModal} cancelFunc={this.hideCompareModal} />
591
592
593
594
595
596
                {/* clone trial parameters and could submit a customized trial */}
                <Customize
                    visible={isShowCustomizedModal}
                    copyTrialId={copyTrialId}
                    closeCustomizeModal={this.closeCustomizedTrial}
                />
Lijiao's avatar
Lijiao committed
597
598
599
600
601
            </Row>
        );
    }
}

602
export default TableList;