-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathasp2vl.ts
65 lines (55 loc) · 2.15 KB
/
asp2vl.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { TopLevelUnitSpec } from 'vega-lite/build/src/spec/unit';
import { Field } from 'vega-lite/build/src/channeldef';
const REGEX = /(\w+)\(([\w\.\/]+)(,([\w\.]+))?\)/;
const DEFAULT_DATASET = 'data/cars.json';
/**
* Convert from ASP to Vega-Lite.
*/
export default function asp2vl(facts: string[], url: string = DEFAULT_DATASET): TopLevelUnitSpec<Field> {
let mark = '';
const encodings: { [enc: string]: any } = {};
for (const value of facts) {
// TODO: Better handle quoted fields. We currently simply remove all ".
const cleanedValue = value.replace(/\"/g, '');
const negSymbol = value.trim().startsWith(':-'); // TODO: remove this
const [_, predicate, first, __, second] = REGEX.exec(cleanedValue) as any;
if (predicate === 'mark') {
mark = first;
} else if (predicate === 'data') {
url = first;
} else if (predicate !== 'soft') {
if (!encodings[first]) {
encodings[first] = {};
}
// if it contains the neg symbol, and the field is a boolean field, its value would be false
// e.g., for the case ":- zero(e3)"
encodings[first][predicate] = second || !negSymbol;
}
}
const encoding: { [channel: string]: any } = {};
for (const e of Object.keys(encodings)) {
const enc = encodings[e];
// if quantitative encoding and zero is not set, set zero to false
if (enc.type === 'quantitative' && enc.zero === undefined && enc.bin === undefined) {
enc.zero = false;
}
const scale = {
...(enc.log ? { type: 'log' } : {}),
...(enc.zero === undefined ? {} : enc.zero ? { zero: true } : { zero: false }),
};
encoding[enc.channel] = {
type: enc.type,
...(enc.aggregate ? { aggregate: enc.aggregate } : {}),
...(enc.field ? { field: enc.field } : {}),
...(enc.stack ? { stack: enc.stack } : {}),
...(enc.bin !== undefined ? (+enc.bin === 10 ? { bin: true } : { bin: { maxbins: +enc.bin } }) : {}),
...(Object.keys(scale).length ? { scale } : {}),
};
}
return {
$schema: 'https://vega.github.io/schema/vega-lite/v5.json',
data: { url: `${url}` },
mark,
encoding,
} as TopLevelUnitSpec<Field>;
}