-
Notifications
You must be signed in to change notification settings - Fork 8
/
constellation.js
296 lines (265 loc) · 10.3 KB
/
constellation.js
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
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/*global graph:true designEnumeration:true imparse:true*/
constants = require('./constants');
EdgeGraph = require('./edgeGraph');
design = require('./designEnumeration');
symbolicEnumeration = require('./symbolicEnumeration');
imparse = require('imparse');
graphGOLDBAR = require('./graphGOLDBAR');
uuidv4 = require('uuidv4');
edgeSBOL = require('./edgeSBOL');
nodeSBOL = require('./nodeSBOL');
graphFromSBOL = require('./graphSBOL');
SBOLDocument = require('sboljs');
simplify = require('./simplifyOperators');
const GRAMMAR_DEF = [{'Seq':[{'Then':[['Exp'],'.',['Seq']]},{'Then':[['Exp'],'then',['Seq']]},{'':[['Exp']]}]},{'Exp':[{'Or':[['Term'],'or',['Exp']]},{'And0':[['Term'],'and0',['Exp']]}, {'And1':[['Term'],'and1',['Exp']]}, {'And2':[['Term'],'and2',['Exp']]},{'Merge':[['Term'],'merge',['Exp']]},{'':[['Term']]}]},{'Term':[{'OneOrMore':['one-or-more',['Term']]},{'ZeroOrMore':['zero-or-more',['Term']]},{'ZeroOrOne':['zero-or-one',['Term']]}, {'ReverseComp':['reverse-comp',['Term']]},{'ZeroOrOneSBOL':['zero-or-one-sbol',['Term']]},{'ZeroOrMoreSBOL':['zero-or-more-sbol',['Term']]},{'':['{',['Seq'],'}']},{'':['(',['Seq'],')']},{'Atom':[{'RegExp':'([A-Za-z0-9]|-|_)+'}]}]}];
/* * * * * * */
/* MAIN */
/* * * * * * */
/**
* Builds a graph representation of the equivalent GOLDBAR syntax and restraints
* and returns the graph, valid paths, and valid designs up to numDesigns
* @param designName Name of combinatorial design
* @param langText Text with GOLDBAR specification input
* @param categories Text or object with categories
* @param numDesigns Maximum number of designs to output
* @param maxCycles Maximum depth of cycles
* @param representation Config variable representing which form of graph was requested (NODE vs. EDGE)
* @returns {{stateGraph, designs: *, paths}}
*/
async function goldbar(langText, categories,
{
designName = 'constellation-design',
numDesigns = 20,
maxCycles = 0,
representation = constants.EDGE
} = {}) {
if (!langText) {
throw new Error('No input received');
}
if (numDesigns < 1) {
throw new Error('Invalid number of designs');
}
if (maxCycles < 0 || maxCycles > 10) {
throw new Error('Invalid cycle depth');
}
if (representation !== constants.NODE && representation !== constants.EDGE) {
throw new Error('Invalid graph representation');
}
let parsed, gra, designs, sbolDoc, sparsed;
try {
parsed = parseGoldbar(langText);
} catch (error) {
throw new Error('Error parsing design specification')
}
// Propagate `reverse-comp` operations to the atoms.
parsed = propagateReverseComplements(parsed);
try {
categories = parseCategories(categories);
} catch (error) {
throw new Error('Error parsing categories specification')
}
if (Object.entries(categories).length === 0 && categories.constructor === Object) {
throw new Error('No categories specified');
}
let messages = {};
// simplify the parsed object based on the formalized simplification rules
sparsed = simplify(parsed);
// graph the data on whatever representation is in the config file
gra = graphGOLDBAR.createGraphFromGOLDBAR(sparsed, maxCycles, representation, categories);
// if we get an empty graph back (invalid design) display a single epsilon node
let epsGraph = new EdgeGraph();
if (gra.stateGraph.equals(epsGraph)) {
epsGraph.createEpsilonNode();
return {stateGraph: epsGraph.graph, designs: [], sbol: null, messages: messages};
}
designs = design.enumerateDesigns(gra.paths, categories, numDesigns);
if (designs.totalNum > numDesigns) {
messages.exceedsDesigns = `Displaying ${numDesigns} of approximately ${designs.totalNum} possible designs.
If there are specific parts you would like to see, please limit your category definitions to those parts.`;
}
try {
designName = String(designName).replace(/ /g, '_');
if (representation === constants.NODE) {
sbolDoc = nodeSBOL(gra.stateGraph, categories, designName, numDesigns, maxCycles);
} else {
if (gra.mergeFlag[0]) {
messages.hasMerge = `SBOL generation does not support the MERGE operator.`;
sbolDoc = null;
} else if (gra.andFlag[0]) {
messages.hasAnd = `SBOL generation does not support the AND operator.`;
sbolDoc = null;
} else {
sbolDoc = edgeSBOL(gra.stateGraph, categories, designName, numDesigns, maxCycles);
}
}
} catch (error) {
console.log(error);
}
if (representation === constants.NODE) {
return {stateGraph: gra.stateGraph.graph, designs: designs.designs, sbol: sbolDoc, messages: messages};
} else {
return {stateGraph: gra.collapsed.graph, designs: designs.designs, sbol: sbolDoc, messages: messages};
}
}
/**
* Runs symbolic enumeration component
* @param designName Name of combinatorial design
* @param langText Text with GOLDBAR specification input
* @param categories Text or object with categories
* @param numDesigns Maximum number of designs to output
* @param maxCycles Maximum number of cycles in total
* @returns {{designs: *}}
*/
async function symbolic(langText, categories,
{
designName = 'constellation-design',
numDesigns = 'all', // Must be 'all' or an integer.
maxCycles = 4
} = {}) {
if (!langText) {
throw new Error('No input received');
}
if (!isNaN(numDesigns) && numDesigns <= 0) {
throw new Error('Number of designs must be a positive integer.');
}
if (isNaN(numDesigns) && numDesigns != 'all') {
throw new Error('Number of designs must be an integer or "all".');
}
if (isNaN(maxCycles) || maxCycles < 0) {
throw new Error('Number of allowed cycles must be at least 0.');
}
let parsed, designs;
try {
parsed = parseGoldbar(langText);
} catch (error) {
throw new Error('Error parsing design specification')
}
try {
categories = parseCategories(categories);
} catch (error) {
throw new Error('Error parsing categories specification')
}
if (Object.entries(categories).length === 0 && categories.constructor === Object) {
throw new Error('No categories specified');
}
designs = symbolicEnumeration.enumerateDesigns(parsed, categories, numDesigns, maxCycles);
return {designs: designs};
}
/**
* Builds a graph representation of the equivalent SBOL and restraints
* and returns the graph, valid paths, and valid designs up to numDesigns
* @param sbolDocs List of SBOL files
* @param combineMethod AND or MERGE operators
* @param tolerance Tolerance value of AND or MERGE operators
* @param representation Config variable representing which form of graph was requested (NODE vs. EDGE)
* @returns {{stateGraph, designs: *, paths}}
*/
async function sbol(sbolDocs, combineMethod, tolerance, representation=constants.EDGE){
// process each of the sbol files
let processedSBOL = [];
for (let sbolDoc of sbolDocs) {
processedSBOL.push(await loadSBOL(sbolDoc));
}
// generate graph from array of SBOL documents
let gra;
try {
gra = graphFromSBOL(processedSBOL,representation, combineMethod, tolerance);
} catch (error) {
console.log(error);
throw new Error('SBOL Parsing error! ' + error)
}
if (!gra){
throw new Error('No collections were found in the SBOL');
}
let designs = design.enumerateDesigns(gra.paths, gra.categories, gra.numDesigns);
return {stateGraph: gra.stateGraph, designs: designs.designs, paths: gra.paths}
}
/**
* Sanitises specification input and parses GOLDBAR
* @param langText Text with GOLDBAR specification text
* @returns {object} Parsed object
*/
function parseGoldbar(langText) {
langText = String(langText).replace('\t', ' ');
langText = langText.trim();
return imparse.parse(GRAMMAR_DEF, langText);
}
/**
* Propagates `reverse-comp` operations down to the atoms,
* reversing `then` nodes along the way.
* @param {Object} ast_node
* @param {boolean} reverse
* @returns {Object} Transformed GOLDBAR AST root node
*/
function propagateReverseComplements(ast_node, reverse) {
var reverse = (reverse == null) ? false : reverse;
var a = ast_node;
var rec = propagateReverseComplements;
if ("ReverseComp" in a) {
//a["ReverseComp"][0] = rec(a["ReverseComp"][0], reverse);
//return a;
return rec(a["ReverseComp"][0], !reverse);
} else if ("Then" in a) {
a["Then"][0] = rec(a["Then"][0], reverse);
a["Then"][1] = rec(a["Then"][1], reverse);
a["Then"] = reverse ? a["Then"].reverse() : a["Then"];
return a;
} else if ("Or" in a) {
a["Or"][0] = rec(a["Or"][0], reverse);
a["Or"][1] = rec(a["Or"][1], reverse);
return a;
} else if ("And0" in a) {
a["And0"][0] = rec(a["And0"][0], reverse);
a["And0"][1] = rec(a["And0"][1], reverse);
return a;
} else if ("And1" in a) {
a["And1"][0] = rec(a["And1"][0], reverse);
a["And1"][1] = rec(a["And1"][1], reverse);
return a;
} else if ("And2" in a) {
a["And2"][0] = rec(a["And2"][0], reverse);
a["And2"][1] = rec(a["And2"][1], reverse);
return a;
} else if ("Merge" in a) {
a["Merge"][0] = rec(a["Merge"][0], reverse);
a["Merge"][1] = rec(a["Merge"][1], reverse);
return a;
} else if ("OneOrMore" in a) {
a["OneOrMore"][0] = rec(a["OneOrMore"][0], reverse);
return a;
} else if ("ZeroOrOne" in a) {
a["ZeroOrOne"][0] = rec(a["ZeroOrOne"][0], reverse);
return a;
} else if ("ZeroOrMore" in a) {
a["ZeroOrMore"][0] = rec(a["ZeroOrMore"][0], reverse);
return a;
} else if ("ZeroOrOneSBOL" in a) {
a["ZeroOrOneSBOL"][0] = rec(a["ZeroOrOneSBOL"][0], reverse);
return a;
} else if ("ZeroOrMoreSBOL" in a) {
a["ZeroOrMoreSBOL"][0] = rec(a["ZeroOrMoreSBOL"][0], reverse);
return a;
} else if ("Atom" in a) {
return reverse ? {"ReverseComp": [a]} : a;
}
}
function parseCategories(categories) {
if (typeof categories === 'string' || categories instanceof String) {
categories = String(categories).replace('\t', ' ');
return JSON.parse(categories);
} else { // Maybe validate categories here?
return categories;
}
}
function loadSBOL(sbolData) {
return new Promise((resolve) => {
SBOLDocument.loadRDF(sbolData, (err, sbol) => {
resolve(sbol);
});
});
}
module.exports = {
goldbar,
symbolic,
sbol
};