File size: 8,227 Bytes
0fff343
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Shared parser: program_repr (typed tree, opaque IDs) -> render model.
//
// Grammar (engine_v2 full DSL):
//   Vector := Reduce(Matrix, agg)
//           | Combine(Vector, Vector, op)
//           | Split(Vector, predicate)
//           | FitApply(Vector, target)
//   Matrix := M
//           | Select(Matrix, FeatureSet)
//           | Search(Matrix, k)
//   Scalar := Associate(Vector, target, kind)
//           | Effect(Vector, target, kind)
//   FeatureSet := [id1,id2,...]
//
// We also accept the legacy engine_v1 string shape
//   "Fit(Reduce(Select(M, [N ids]), mean), ... -> target)"
// by surfacing a "Fit" wrapper node — useful when the page is showing
// an older persisted run.

export type ReprNode =
  | { kind: "M" }
  | { kind: "Select"; matrix: ReprNode; features: string[] }
  | { kind: "Search"; matrix: ReprNode; k: number }
  | { kind: "Reduce"; matrix: ReprNode; agg: string }
  | { kind: "Combine"; left: ReprNode; right: ReprNode; op: string }
  | { kind: "Split"; inner: ReprNode; predicate: string }
  | { kind: "FitApply"; inner: ReprNode; target: string }
  | { kind: "Associate"; inner: ReprNode; target: string; assocKind: string }
  | { kind: "Effect"; inner: ReprNode; target: string; assocKind: string }
  | { kind: "Fit"; children: ReprNode[]; output: string }
  | { kind: "Unknown"; text: string };

class _Parser {
  s: string;
  i: number;
  constructor(s: string) {
    this.s = s;
    this.i = 0;
  }
  peek(): string {
    return this.s[this.i] ?? "";
  }
  eof(): boolean {
    return this.i >= this.s.length;
  }
  skip() {
    while (!this.eof() && /\s/.test(this.peek())) this.i++;
  }
  expect(ch: string) {
    this.skip();
    if (this.peek() !== ch) {
      throw new Error(
        `expected '${ch}' at offset ${this.i}, got '${this.peek()}' in ${this.s}`,
      );
    }
    this.i++;
  }
  ident(): string {
    this.skip();
    const start = this.i;
    while (!this.eof() && /[A-Za-z0-9_]/.test(this.peek())) this.i++;
    return this.s.slice(start, this.i);
  }
  parseFeatureSet(): string[] {
    this.expect("[");
    const out: string[] = [];
    this.skip();
    if (this.peek() === "]") {
      this.i++;
      return out;
    }
    while (true) {
      this.skip();
      const start = this.i;
      while (!this.eof() && /[^,\]\s]/.test(this.peek())) this.i++;
      out.push(this.s.slice(start, this.i).trim());
      this.skip();
      if (this.peek() === ",") {
        this.i++;
        continue;
      }
      if (this.peek() === "]") {
        this.i++;
        return out;
      }
      throw new Error(`bad FeatureSet at offset ${this.i}`);
    }
  }
  parseExpr(): ReprNode {
    this.skip();
    const head = this.ident();
    if (head === "M") return { kind: "M" };
    if (head === "Select") {
      this.expect("(");
      const matrix = this.parseExpr();
      this.expect(",");
      const features = this.parseFeatureSet();
      this.expect(")");
      return { kind: "Select", matrix, features };
    }
    if (head === "Reduce") {
      this.expect("(");
      const matrix = this.parseExpr();
      this.expect(",");
      const agg = this.ident();
      this.expect(")");
      return { kind: "Reduce", matrix, agg };
    }
    if (head === "Combine") {
      this.expect("(");
      const left = this.parseExpr();
      this.expect(",");
      const right = this.parseExpr();
      this.expect(",");
      const op = this.ident();
      this.expect(")");
      return { kind: "Combine", left, right, op };
    }
    if (head === "Search") {
      this.expect("(");
      const matrix = this.parseExpr();
      this.expect(",");
      this.skip();
      const kStart = this.i;
      while (!this.eof() && /[0-9]/.test(this.peek())) this.i++;
      const k = Number.parseInt(this.s.slice(kStart, this.i), 10) || 1;
      this.expect(")");
      return { kind: "Search", matrix, k };
    }
    if (head === "Split") {
      this.expect("(");
      const inner = this.parseExpr();
      this.expect(",");
      const predicate = this.ident();
      this.expect(")");
      return { kind: "Split", inner, predicate };
    }
    if (head === "FitApply") {
      this.expect("(");
      const inner = this.parseExpr();
      this.expect(",");
      const target = this.ident();
      this.expect(")");
      return { kind: "FitApply", inner, target };
    }
    if (head === "Associate") {
      this.expect("(");
      const inner = this.parseExpr();
      this.expect(",");
      const target = this.ident();
      this.expect(",");
      const assocKind = this.ident();
      this.expect(")");
      return { kind: "Associate", inner, target, assocKind };
    }
    if (head === "Effect") {
      this.expect("(");
      const inner = this.parseExpr();
      this.expect(",");
      const target = this.ident();
      this.expect(",");
      const assocKind = this.ident();
      this.expect(")");
      return { kind: "Effect", inner, target, assocKind };
    }
    if (head === "Fit") {
      return this.parseFitTail();
    }
    throw new Error(`unknown head '${head}' at offset ${this.i}`);
  }

  /** Tolerant parser for the legacy v1 shape:
   *    Fit(Reduce(Select(M, [3 ids]), mean), ... -> target)
   * It doesn't always serialise gene IDs (sometimes it's "[N ids]"). We
   * pull out the comma-separated children and an "-> output" tail; we
   * keep raw text for unknown bits. */
  parseFitTail(): ReprNode {
    this.expect("(");
    const children: ReprNode[] = [];
    let output = "target";
    while (true) {
      this.skip();
      // Detect "-> output" marker.
      if (this.s.startsWith("->", this.i)) {
        this.i += 2;
        this.skip();
        const start = this.i;
        let depth = 0;
        while (!this.eof()) {
          const ch = this.peek();
          if (ch === "(") depth++;
          else if (ch === ")") {
            if (depth === 0) break;
            depth--;
          }
          this.i++;
        }
        output = this.s.slice(start, this.i).trim();
        break;
      }
      // Try to parse a known child. If it fails, skip until comma/paren.
      const safeStart = this.i;
      try {
        const child = this.parseExpr();
        children.push(child);
      } catch {
        this.i = safeStart;
        let depth = 0;
        const start = this.i;
        while (!this.eof()) {
          const ch = this.peek();
          if (ch === "(") depth++;
          else if (ch === ")") {
            if (depth === 0) break;
            depth--;
          } else if (ch === "," && depth === 0) break;
          this.i++;
        }
        children.push({ kind: "Unknown", text: this.s.slice(start, this.i).trim() });
      }
      this.skip();
      if (this.peek() === ",") {
        this.i++;
        continue;
      }
      break;
    }
    this.expect(")");
    return { kind: "Fit", children, output };
  }
}

export function parseProgramRepr(repr: string): ReprNode {
  const p = new _Parser(repr.trim());
  p.skip();
  return p.parseExpr();
}

export function safeParseProgramRepr(repr: string): {
  ok: boolean;
  tree: ReprNode | null;
  error?: string;
} {
  try {
    return { ok: true, tree: parseProgramRepr(repr) };
  } catch (e) {
    return {
      ok: false,
      tree: null,
      error: e instanceof Error ? e.message : String(e),
    };
  }
}

// Walk a tree and collect every FeatureSet leaf's IDs (union, ordered).
export function geneIds(tree: ReprNode): string[] {
  const out: string[] = [];
  const seen = new Set<string>();
  function visit(n: ReprNode) {
    switch (n.kind) {
      case "Select":
        for (const id of n.features) {
          if (!seen.has(id)) {
            seen.add(id);
            out.push(id);
          }
        }
        visit(n.matrix);
        return;
      case "Search":
      case "Reduce":
        visit(n.matrix);
        return;
      case "Combine":
        visit(n.left);
        visit(n.right);
        return;
      case "Split":
      case "FitApply":
      case "Associate":
      case "Effect":
        visit(n.inner);
        return;
      case "Fit":
        for (const c of n.children) visit(c);
        return;
      case "M":
      case "Unknown":
        return;
    }
  }
  visit(tree);
  return out;
}