@matheos/core 0.2.3 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/display.d.ts +9 -0
- package/dist/display.js +74 -0
- package/dist/display.js.map +1 -0
- package/dist/evaluate.d.ts +34 -0
- package/dist/evaluate.js +151 -179
- package/dist/evaluate.js.map +1 -1
- package/dist/fit.d.ts +24 -0
- package/dist/fit.js +151 -0
- package/dist/fit.js.map +1 -0
- package/dist/graph.js +4 -8
- package/dist/graph.js.map +1 -1
- package/dist/html.d.ts +25 -0
- package/dist/html.js +54 -56
- package/dist/html.js.map +1 -1
- package/dist/index.d.ts +9 -5
- package/dist/index.js +7 -5
- package/dist/index.js.map +1 -1
- package/dist/model.d.ts +10 -7
- package/dist/parse.d.ts +50 -1
- package/dist/parse.js +124 -65
- package/dist/parse.js.map +1 -1
- package/dist/plot.d.ts +11 -17
- package/dist/plot.js +67 -3
- package/dist/plot.js.map +1 -1
- package/dist/printer.d.ts +32 -13
- package/dist/printer.js +105 -100
- package/dist/printer.js.map +1 -1
- package/dist/units.d.ts +4 -2
- package/dist/units.js +8 -2
- package/dist/units.js.map +1 -1
- package/dist/verdict.d.ts +21 -0
- package/dist/verdict.js +22 -0
- package/dist/verdict.js.map +1 -0
- package/package.json +1 -1
package/dist/evaluate.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { math, isUnit, isNA, NA, wording, unitLatex, isForeignUnit, displayUnit, isMatrixLike } from './units.js';
|
|
2
|
-
import { print, identifier,
|
|
3
|
-
import {
|
|
1
|
+
import { math, isUnit, isNA, NA, wording, unitLatex, isForeignUnit, isDimensionless, displayUnit, isMatrixLike } from './units.js';
|
|
2
|
+
import { print, printFunction, identifier, stamp, negate, plainText, comparison, implies, not as notTex, text as textTex, literalEcho, range as rangeTex } from './printer.js';
|
|
3
|
+
import { shown as shownValue } from './display.js';
|
|
4
|
+
import { plot } from './plot.js';
|
|
4
5
|
import { parse } from './parse.js';
|
|
5
6
|
const CMP_FN = { '<=': 'smallerEq', '>=': 'largerEq', '<': 'smaller', '>': 'larger', '==': 'equal', '!=': 'unequal' };
|
|
6
|
-
const CMP_TEX = { '<=': '\\le', '>=': '\\ge', '<': '<', '>': '>', '==': '=', '!=': '\\ne' };
|
|
7
7
|
class DependsError extends Error {
|
|
8
8
|
constructor(dep) { super(`depends on ${dep}`); }
|
|
9
9
|
}
|
|
@@ -63,44 +63,18 @@ function freeSymbols(node) {
|
|
|
63
63
|
export function evaluate(doc, options = {}) {
|
|
64
64
|
const depth = options.depth ?? 0;
|
|
65
65
|
const scope = new Map();
|
|
66
|
-
const display = new Map(); //
|
|
66
|
+
const display = new Map(); // each bound name as it reads on its result line
|
|
67
67
|
const failed = new Set();
|
|
68
68
|
const errors = [];
|
|
69
69
|
const digits = typeof doc.frontMatter.digits === 'number' ? doc.frontMatter.digits : 4;
|
|
70
70
|
scope.set('na', NA); // `na`: a value that does not apply (min/max skip it, checks report n/a)
|
|
71
71
|
// catalogues: each JSON table becomes an object of rows keyed by name, numeric columns carrying the units given
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
for (const [
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
const data = options.resolve?.(cat.file);
|
|
79
|
-
if (data === undefined)
|
|
80
|
-
throw new Error(`catalog ${name}: cannot load ${cat.file}`);
|
|
81
|
-
const rows = Array.isArray(data) ? data : typeof data === 'object' && data !== null && Array.isArray(data.rows) ? data.rows : undefined;
|
|
82
|
-
if (!rows)
|
|
83
|
-
throw new Error(`catalog ${name}: ${cat.file} is not a table`);
|
|
84
|
-
const units = { ...(data.units ?? {}), ...(cat.units ?? {}) };
|
|
85
|
-
for (const u of Object.values(units))
|
|
86
|
-
for (const sym of math.parse(u).filter((x) => x.type === 'SymbolNode'))
|
|
87
|
-
if (isForeignUnit(sym.name))
|
|
88
|
-
throw new Error(`catalog ${name}: unknown unit "${u}"`);
|
|
89
|
-
const key = cat.key ?? 'Name';
|
|
90
|
-
const table = {};
|
|
91
|
-
for (const row of rows) {
|
|
92
|
-
const id = String(row[key] ?? row['name'] ?? row['id'] ?? Object.keys(table).length + 1);
|
|
93
|
-
const o = {};
|
|
94
|
-
for (const [k, v] of Object.entries(row))
|
|
95
|
-
o[k] = typeof v === 'number' && units[k] ? math.unit(v, units[k]) : v;
|
|
96
|
-
table[id] = o;
|
|
97
|
-
}
|
|
98
|
-
scope.set(name, table);
|
|
99
|
-
}
|
|
100
|
-
catch (e) {
|
|
101
|
-
errors.push({ message: wording(e), pos: { start: { line: 1, column: 1, offset: 0 }, end: { line: 1, column: 1, offset: 0 } } });
|
|
102
|
-
}
|
|
103
|
-
}
|
|
72
|
+
if (doc.frontMatter.catalogs && typeof doc.frontMatter.catalogs === 'object') {
|
|
73
|
+
const c = catalogueTables(doc.frontMatter.catalogs, options.resolve);
|
|
74
|
+
for (const [k, v] of c.bindings)
|
|
75
|
+
scope.set(k, v);
|
|
76
|
+
for (const message of c.errors)
|
|
77
|
+
errors.push({ message, pos: { start: { line: 1, column: 1, offset: 0 }, end: { line: 1, column: 1, offset: 0 } } });
|
|
104
78
|
}
|
|
105
79
|
// includes: front matter `include: helpers.mth` (or a list). Each file is evaluated on its own and its bindings
|
|
106
80
|
// (variables, functions, catalogues) land in this scope; nothing of it is printed.
|
|
@@ -151,33 +125,11 @@ export function evaluate(doc, options = {}) {
|
|
|
151
125
|
if (!scope.has(sym.name) && isForeignUnit(sym.name))
|
|
152
126
|
throw new Error(`unknown unit "${sym.name}"`);
|
|
153
127
|
}
|
|
154
|
-
return node;
|
|
128
|
+
return stamp(node, expr); // the printer echoes the literals as typed
|
|
155
129
|
};
|
|
156
130
|
const run = (node) => node.compile().evaluate(scope);
|
|
157
|
-
const
|
|
158
|
-
|
|
159
|
-
return v;
|
|
160
|
-
if (to === '%') {
|
|
161
|
-
if (typeof v === 'number' || (isUnit(v) && v.dimensions.every((d) => d === 0)))
|
|
162
|
-
return v;
|
|
163
|
-
throw new Error(`only a dimensionless value can be shown in %`);
|
|
164
|
-
}
|
|
165
|
-
for (const sym of math.parse(to).filter((x) => x.type === 'SymbolNode'))
|
|
166
|
-
if (isForeignUnit(sym.name))
|
|
167
|
-
throw new Error(`unknown unit "${sym.name}"`);
|
|
168
|
-
if (Array.isArray(v) || (typeof v === 'object' && v !== null && 'toArray' in v)) { // vectors and matrices convert element by element
|
|
169
|
-
return math.map(v, (e) => convert(e, to));
|
|
170
|
-
}
|
|
171
|
-
if (!isUnit(v))
|
|
172
|
-
throw new Error(`cannot convert a number to ${to}`);
|
|
173
|
-
try {
|
|
174
|
-
return v.to(to);
|
|
175
|
-
}
|
|
176
|
-
catch (e) {
|
|
177
|
-
throw new Error(`cannot convert ${v.formatUnits()} to ${to}`);
|
|
178
|
-
}
|
|
179
|
-
};
|
|
180
|
-
const fmt = (v, to) => formatValue(v, to, digits);
|
|
131
|
+
const fmtShown = (v, to) => shownValue(v, to, digits); // throws when `to` cannot apply
|
|
132
|
+
const fmt = (v, to) => fmtShown(v, to).tex;
|
|
181
133
|
const isLiteral = (n) => {
|
|
182
134
|
const u = n.type === 'ParenthesisNode' ? n.content : n;
|
|
183
135
|
return u.type === 'ConstantNode' || (u.type === 'OperatorNode' && u.op === '*' && !!u.implicit
|
|
@@ -185,7 +137,7 @@ export function evaluate(doc, options = {}) {
|
|
|
185
137
|
};
|
|
186
138
|
const collapse = (pieces) => pieces.filter((p, i) => i === 0 || p !== pieces[i - 1]);
|
|
187
139
|
/** Result text of an expression: a bound name keeps its own display unit, anything else uses the default rule. */
|
|
188
|
-
const shown = (node, value) => (node.type === 'SymbolNode' && display.get(node.name)) || fmt(value);
|
|
140
|
+
const shown = (node, value) => (node.type === 'SymbolNode' && display.get(node.name)?.tex) || fmt(value);
|
|
189
141
|
/** One side of a check or condition: its formula (absent for a literal), its value text, and `formula = value`. */
|
|
190
142
|
const side = (expr) => {
|
|
191
143
|
const node = parseExpr(expr);
|
|
@@ -193,7 +145,7 @@ export function evaluate(doc, options = {}) {
|
|
|
193
145
|
const v = shown(node, value);
|
|
194
146
|
if (isLiteral(node))
|
|
195
147
|
return { v, latex: v, value };
|
|
196
|
-
const formula = print(node, 'formula',
|
|
148
|
+
const formula = print(node, 'formula', ctx);
|
|
197
149
|
return { formula, v, latex: collapse([formula, v]).join(' = '), value };
|
|
198
150
|
};
|
|
199
151
|
/** Condition line: `condition → evaluated` (docs/spec/conditionals.md). */
|
|
@@ -206,17 +158,17 @@ export function evaluate(doc, options = {}) {
|
|
|
206
158
|
const L = side(a.toString()), R = side(b.toString());
|
|
207
159
|
if (op === '==' && (isLiteral(b) && R.v === fmt(L.value) || isLiteral(a) && L.v === fmt(R.value)))
|
|
208
160
|
return { latex: isLiteral(b) ? L.latex : R.latex, value };
|
|
209
|
-
const evaluated =
|
|
161
|
+
const evaluated = comparison(L.v, op, R.v);
|
|
210
162
|
if (!L.formula && !R.formula)
|
|
211
163
|
return { latex: evaluated, value };
|
|
212
|
-
return { latex:
|
|
164
|
+
return { latex: implies(comparison(L.formula ?? L.v, op, R.formula ?? R.v), evaluated), value };
|
|
213
165
|
}
|
|
214
|
-
const latex = print(node, 'formula',
|
|
215
|
-
return { latex: negated ?
|
|
166
|
+
const latex = print(node, 'formula', ctx);
|
|
167
|
+
return { latex: negated ? notTex(latex) : latex, value };
|
|
216
168
|
};
|
|
217
169
|
/** `1 : n` or `1 : 2 : n` → the values of a loop variable (inclusive, at most 10 000). */
|
|
218
170
|
const rangeValues = (range) => {
|
|
219
|
-
const parts = range.split(':').map((p) => { const v = run(parseExpr(p.trim())); return typeof v === 'number' ? v :
|
|
171
|
+
const parts = range.split(':').map((p) => { const v = run(parseExpr(p.trim())); return typeof v === 'number' ? v : isDimensionless(v) ? Number(v.value) : NaN; });
|
|
220
172
|
if (parts.length < 2 || parts.length > 3 || parts.some((p) => !Number.isFinite(p)))
|
|
221
173
|
throw new Error(`loop range must be "from : to" or "from : step : to", got "${range}"`);
|
|
222
174
|
const [from, step, to] = parts.length === 3 ? parts : [parts[0], 1, parts[1]];
|
|
@@ -245,7 +197,7 @@ export function evaluate(doc, options = {}) {
|
|
|
245
197
|
if (st.kind !== 'comment' && st.kind !== 'if' && st.kind !== 'for')
|
|
246
198
|
items.push({ kind: st.kind, latex: '', error: message, pos: st.pos, ...(st.caption !== undefined && { caption: st.caption }), ...(indent && { indent }) });
|
|
247
199
|
else if (st.kind === 'for')
|
|
248
|
-
items.push({ kind: '
|
|
200
|
+
items.push({ kind: 'loop', latex: '', error: message, pos: st.pos, ...(indent && { indent }) });
|
|
249
201
|
};
|
|
250
202
|
const renderStatements = (statements, opts, items, indent = false) => {
|
|
251
203
|
for (const st of statements) {
|
|
@@ -261,37 +213,35 @@ export function evaluate(doc, options = {}) {
|
|
|
261
213
|
const value = run(node);
|
|
262
214
|
if (silent)
|
|
263
215
|
return;
|
|
264
|
-
const
|
|
265
|
-
const head = print(node.object, 'formula', ctx) + print(node.index, 'formula', { ...ctx, literals: literalsOf(s.name) });
|
|
216
|
+
const head = print(node.object, 'formula', ctx) + print(node.index, 'formula', ctx);
|
|
266
217
|
const vectorOperand = node.value.filter((x) => x.type === 'SymbolNode').some((x) => isMatrixLike(scope.get(x.name)));
|
|
267
|
-
const stages = vectorOperand ? [print(node.value, 'formula',
|
|
268
|
-
: [print(node.value, 'formula',
|
|
218
|
+
const stages = vectorOperand ? [print(node.value, 'formula', ctx), fmt(value)]
|
|
219
|
+
: [print(node.value, 'formula', ctx), print(node.value, 'subst', ctx), fmt(value)];
|
|
269
220
|
const pieces = resultOnly ? [fmt(value)] : collapse(stages);
|
|
270
221
|
items.push({ kind: 'derived', latex: [head, ...pieces].join(' = '), pieces: [head, ...pieces], pos: s.pos, ...cap, ...ind });
|
|
271
222
|
return;
|
|
272
223
|
}
|
|
273
224
|
const node = parseExpr(s.expr);
|
|
274
225
|
const value = run(node);
|
|
275
|
-
|
|
276
|
-
const result =
|
|
226
|
+
const asShown = fmtShown(value, s.to); // throws before the name is bound when `to` cannot apply
|
|
227
|
+
const result = asShown.tex;
|
|
277
228
|
// bound after printing, so `x = x + 1` substitutes the old x
|
|
278
229
|
const bind = () => { if (s.kind === 'derived') {
|
|
279
230
|
scope.set(s.name, value);
|
|
280
231
|
failed.delete(s.name);
|
|
281
|
-
display.set(s.name,
|
|
232
|
+
display.set(s.name, asShown);
|
|
282
233
|
} };
|
|
283
234
|
if (silent) {
|
|
284
235
|
bind();
|
|
285
236
|
return;
|
|
286
237
|
}
|
|
287
238
|
const warning = lint(node);
|
|
288
|
-
const lits = literalsOf(s.expr);
|
|
289
239
|
// a vector operand would make the substituted line unreadable: formula = result then
|
|
290
240
|
// a vector operand or a `solve` (whose variable is now bound to the root) would make the substituted line unreadable
|
|
291
241
|
const vectorOperand = node.filter((x) => x.type === 'SymbolNode').some((x) => isMatrixLike(scope.get(x.name)))
|
|
292
242
|
|| node.filter((x) => x.type === 'FunctionNode' && x.fn.name === 'solve').length > 0;
|
|
293
|
-
const stages = vectorOperand ? [print(node, 'formula',
|
|
294
|
-
: [print(node, 'formula',
|
|
243
|
+
const stages = vectorOperand ? [print(node, 'formula', ctx), result]
|
|
244
|
+
: [print(node, 'formula', ctx), print(node, 'subst', ctx), result];
|
|
295
245
|
const pieces = resultOnly ? [result] : collapse(stages);
|
|
296
246
|
const head = s.kind === 'derived' ? [identifier(s.name)] : [];
|
|
297
247
|
bind();
|
|
@@ -301,22 +251,28 @@ export function evaluate(doc, options = {}) {
|
|
|
301
251
|
case 'comment': break;
|
|
302
252
|
case 'input': {
|
|
303
253
|
// echo the literal as typed: number (or a row vector of numbers), then the unit text upright
|
|
304
|
-
const
|
|
305
|
-
if (
|
|
254
|
+
const unit = st.unit;
|
|
255
|
+
if (unit && scope.has(unit)) {
|
|
306
256
|
derived({ ...st, kind: 'derived' });
|
|
307
257
|
break;
|
|
308
258
|
} // `25 t` with t bound: a product, not a unit
|
|
309
259
|
const node = parseExpr(st.expr);
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
260
|
+
let value;
|
|
261
|
+
try {
|
|
262
|
+
value = run(node);
|
|
263
|
+
}
|
|
264
|
+
catch (e) { // `1 kpa`: the word after the literal was meant as a unit
|
|
265
|
+
const sym = /^Undefined symbol (\S+)/.exec(e instanceof Error ? e.message : '')?.[1];
|
|
266
|
+
if (sym && unit && unit.split(/[\s/^*()]+/).includes(sym))
|
|
267
|
+
throw new Error(`unknown unit "${sym}"`);
|
|
268
|
+
throw e;
|
|
269
|
+
}
|
|
270
|
+
const latex = literalEcho(st.literal, unit);
|
|
315
271
|
scope.set(st.name, value);
|
|
316
272
|
failed.delete(st.name);
|
|
317
|
-
display.set(st.name, latex);
|
|
273
|
+
display.set(st.name, { tex: latex, negative: st.literal.startsWith('-'), unit: !!unit });
|
|
318
274
|
if (!silent)
|
|
319
|
-
items.push({ kind: 'input', latex: `${identifier(st.name)} = ${latex}`, pos: st.pos, ...cap, ...ind });
|
|
275
|
+
items.push({ kind: 'input', latex: `${identifier(st.name)} = ${latex}`, pieces: [identifier(st.name), latex], pos: st.pos, ...cap, ...ind });
|
|
320
276
|
break;
|
|
321
277
|
}
|
|
322
278
|
case 'derived':
|
|
@@ -327,7 +283,7 @@ export function evaluate(doc, options = {}) {
|
|
|
327
283
|
const values = rangeValues(st.range);
|
|
328
284
|
const at = items.length;
|
|
329
285
|
if (!silent && !resultOnly)
|
|
330
|
-
items.push({ kind: '
|
|
286
|
+
items.push({ kind: 'loop', latex: `${identifier(st.variable)} = ${rangeTex(values[0], values[values.length - 1])}`, pos: st.pos, ...ind });
|
|
331
287
|
for (const v of values) {
|
|
332
288
|
scope.set(st.variable, v);
|
|
333
289
|
failed.delete(st.variable);
|
|
@@ -341,26 +297,27 @@ export function evaluate(doc, options = {}) {
|
|
|
341
297
|
const node = parseExpr(`${st.name}(${st.params.join(', ')}) = ${st.expr}`, new Set(st.params));
|
|
342
298
|
run(node); // binds the function in scope; the body is evaluated per call
|
|
343
299
|
failed.delete(st.name);
|
|
300
|
+
const pieces = printFunction(node, ctx);
|
|
344
301
|
if (!silent)
|
|
345
|
-
items.push({ kind: 'function', latex:
|
|
302
|
+
items.push({ kind: 'function', latex: pieces.join(' = '), pieces, pos: st.pos, ...cap, ...ind });
|
|
346
303
|
break;
|
|
347
304
|
}
|
|
348
305
|
case 'check': {
|
|
349
306
|
if (st.only !== undefined && !run(parseExpr(st.only))) { // `check … if cond` with cond false: shown as n/a
|
|
350
307
|
const tex = (e) => { try {
|
|
351
|
-
return print(parseExpr(e), 'formula',
|
|
308
|
+
return print(parseExpr(e), 'formula', ctx);
|
|
352
309
|
}
|
|
353
310
|
catch {
|
|
354
|
-
return
|
|
311
|
+
return textTex(e);
|
|
355
312
|
} };
|
|
356
313
|
if (!silent)
|
|
357
|
-
items.push({ kind: 'check', latex:
|
|
314
|
+
items.push({ kind: 'check', latex: comparison(tex(st.left), st.op, tex(st.right)), verdict: true, na: true, pos: st.pos, ...cap, ...ind });
|
|
358
315
|
break;
|
|
359
316
|
}
|
|
360
317
|
const L = side(st.left), R = side(st.right);
|
|
361
318
|
if (isNA(L.value) || isNA(R.value)) { // a side that does not apply
|
|
362
319
|
if (!silent)
|
|
363
|
-
items.push({ kind: 'check', latex:
|
|
320
|
+
items.push({ kind: 'check', latex: comparison(L.latex, st.op, R.latex), verdict: true, na: true, pos: st.pos, ...cap, ...ind });
|
|
364
321
|
break;
|
|
365
322
|
}
|
|
366
323
|
const warning = lint(parseExpr(st.left)) ?? lint(parseExpr(st.right));
|
|
@@ -368,11 +325,11 @@ export function evaluate(doc, options = {}) {
|
|
|
368
325
|
const numeric = typeof L.value !== 'string' && typeof L.value !== 'boolean' && typeof R.value !== 'string' && typeof R.value !== 'boolean'; // `check curve == "b"` has no η
|
|
369
326
|
const ratio = !numeric ? NaN : st.op === '>=' || st.op === '>' ? math.divide(R.value, L.value) : math.divide(L.value, R.value);
|
|
370
327
|
const r = typeof ratio === 'number' ? ratio : isUnit(ratio) ? ratio.toNumber('') : NaN;
|
|
371
|
-
const eta = numeric ?
|
|
328
|
+
const eta = numeric ? Math.round(r * 100) / 100 : undefined;
|
|
372
329
|
const warn = verdict && st.warn !== undefined && r > st.warn; // passed, but closer to the limit than the author wants
|
|
373
330
|
const same = st.op === '==' && !R.formula && L.v === R.v; // `check curve == "b"` holding: `curve = b`, not `curve = b = b`
|
|
374
331
|
if (!silent)
|
|
375
|
-
items.push({ kind: 'check', latex: same ? L.latex :
|
|
332
|
+
items.push({ kind: 'check', latex: same ? L.latex : comparison(L.latex, st.op, R.latex), verdict, ...(eta !== undefined && { eta }), ...(warn && { warn }), ...(warning && { warning }), pos: st.pos, ...cap, ...ind });
|
|
376
333
|
break;
|
|
377
334
|
}
|
|
378
335
|
case 'if': {
|
|
@@ -450,67 +407,15 @@ export function evaluate(doc, options = {}) {
|
|
|
450
407
|
continue;
|
|
451
408
|
}
|
|
452
409
|
if (block.kind === 'plot') {
|
|
453
|
-
|
|
410
|
+
// plot.ts owns the range, the sampling and the axis units; it gets the two things only the evaluation has: an
|
|
411
|
+
// expression in `x` compiled against the scope, and its label as the printer writes it
|
|
454
412
|
const X = new Set(['x']);
|
|
455
|
-
|
|
456
|
-
const
|
|
457
|
-
|
|
458
|
-
return v;
|
|
459
|
-
if (typeof v === 'boolean')
|
|
460
|
-
return v ? 1 : 0;
|
|
461
|
-
if (isUnit(v)) {
|
|
462
|
-
if (v.dimensions.every((d) => d === 0))
|
|
463
|
-
return Number(v.value);
|
|
464
|
-
unit && (unit.u ??= displayUnit(v));
|
|
465
|
-
return v.toNumber(unit?.u ?? displayUnit(v));
|
|
466
|
-
}
|
|
467
|
-
return NaN;
|
|
468
|
-
};
|
|
469
|
-
const value = (expr) => run(parseExpr(expr, X));
|
|
470
|
-
let x0 = 0, x1 = 1;
|
|
471
|
-
const ux = {};
|
|
472
|
-
try {
|
|
473
|
-
const r = /^(.+?)\s*(?:\.\.|:)\s*(.+)$/.exec(block.options.x ?? '0 .. 1');
|
|
474
|
-
if (r) {
|
|
475
|
-
x0 = value(r[1]);
|
|
476
|
-
x1 = value(r[2]);
|
|
477
|
-
}
|
|
478
|
-
}
|
|
479
|
-
catch (e) {
|
|
480
|
-
errs.push(wording(e));
|
|
481
|
-
}
|
|
482
|
-
const span = math.subtract(x1, x0);
|
|
483
|
-
const xAt = (t) => math.add(x0, math.multiply(span, t)); // keeps the unit of x
|
|
484
|
-
const series = block.series.map((s) => {
|
|
485
|
-
const pts = [];
|
|
486
|
-
const uy = {};
|
|
487
|
-
try {
|
|
488
|
-
const compiled = parseExpr(s.expr, X).compile();
|
|
489
|
-
for (let i = 0; i <= 120; i++) {
|
|
490
|
-
const x = xAt(i / 120);
|
|
491
|
-
const y = asNum(compiled.evaluate(new Map([...scope, ['x', x]])), uy);
|
|
492
|
-
if (Number.isFinite(y))
|
|
493
|
-
pts.push([asNum(x, ux), y]);
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
catch (e) {
|
|
497
|
-
errs.push(`${s.expr}: ${wording(e)}`);
|
|
498
|
-
}
|
|
499
|
-
return { label: s.caption ?? plainText(print(math.parse(s.expr), 'formula', ctx)), pts };
|
|
500
|
-
});
|
|
501
|
-
const num = (expr) => asNum(value(expr), ux);
|
|
502
|
-
const points = block.points.map((p) => {
|
|
503
|
-
try {
|
|
504
|
-
return { label: p.caption, x: num(p.x), y: num(p.y) };
|
|
505
|
-
}
|
|
506
|
-
catch (e) {
|
|
507
|
-
errs.push(`(${p.x}, ${p.y}): ${wording(e)}`);
|
|
508
|
-
return undefined;
|
|
509
|
-
}
|
|
510
|
-
}).filter((p) => !!p);
|
|
413
|
+
const at = (expr) => { const c = parseExpr(expr, X).compile(); return (x) => c.evaluate(x === undefined ? scope : new Map([...scope, ['x', x]])); };
|
|
414
|
+
const label = (expr) => plainText(print(parseExpr(expr, X), 'formula', ctx));
|
|
415
|
+
const { svg, errors: errs } = plot(block, at, label);
|
|
511
416
|
for (const m of errs)
|
|
512
417
|
errors.push({ message: m, pos: block.pos });
|
|
513
|
-
blocks.push({ kind: 'plot', svg
|
|
418
|
+
blocks.push({ kind: 'plot', svg, errors: errs, pos: block.pos });
|
|
514
419
|
continue;
|
|
515
420
|
}
|
|
516
421
|
if (block.kind === 'calc') {
|
|
@@ -521,10 +426,9 @@ export function evaluate(doc, options = {}) {
|
|
|
521
426
|
else {
|
|
522
427
|
const inlines = block.inlines.map((inl) => {
|
|
523
428
|
try {
|
|
524
|
-
const
|
|
525
|
-
const node = parseExpr(tm ? inl.expr.slice(0, tm.index) : inl.expr);
|
|
429
|
+
const node = parseExpr(inl.expr);
|
|
526
430
|
const value = run(node);
|
|
527
|
-
const v =
|
|
431
|
+
const v = inl.to ? fmt(value, inl.to) : shown(node, value);
|
|
528
432
|
return { raw: inl.raw, latex: inl.showName ? `${identifier(inl.expr)} = ${v}` : v, pos: inl.pos, ...(inl.plain && { plain: true }) };
|
|
529
433
|
}
|
|
530
434
|
catch (e) {
|
|
@@ -544,26 +448,8 @@ export function evaluate(doc, options = {}) {
|
|
|
544
448
|
// join the table or drawing around it; positions map back to the source lines for the preview and the CLI
|
|
545
449
|
const loops = doc.blocks.map((b, i) => (b.kind === 'loop' ? { b, r: blocks[i] } : undefined)).filter((x) => !!x);
|
|
546
450
|
if (loops.length && depth < 4) {
|
|
547
|
-
const
|
|
548
|
-
const
|
|
549
|
-
let cursor = 1;
|
|
550
|
-
for (const { b, r } of loops) {
|
|
551
|
-
for (let n = cursor; n < b.pos.start.line; n++) {
|
|
552
|
-
out.push(src[n - 1] ?? '');
|
|
553
|
-
map.push(n);
|
|
554
|
-
}
|
|
555
|
-
for (const l of r.text.split('\n')) {
|
|
556
|
-
out.push(l);
|
|
557
|
-
map.push(b.pos.start.line);
|
|
558
|
-
}
|
|
559
|
-
cursor = b.pos.end.line + 1;
|
|
560
|
-
}
|
|
561
|
-
for (let n = cursor; n <= src.length; n++) {
|
|
562
|
-
out.push(src[n - 1] ?? '');
|
|
563
|
-
map.push(n);
|
|
564
|
-
}
|
|
565
|
-
const r2 = evaluate(parse(out.join('\n')), { ...options, depth: depth + 1 });
|
|
566
|
-
const line = (n) => map[n - 1] ?? n;
|
|
451
|
+
const { text, line } = spliceLoops(doc.text, loops.map(({ b, r }) => ({ start: b.pos.start.line, end: b.pos.end.line, text: r.text })));
|
|
452
|
+
const r2 = evaluate(parse(text), { ...options, depth: depth + 1 });
|
|
567
453
|
const mapPos = (p) => ({ start: { ...p.start, line: line(p.start.line) }, end: { ...p.end, line: line(p.end.line) } });
|
|
568
454
|
const fix = (bs) => { for (const b of bs) {
|
|
569
455
|
b.pos = mapPos(b.pos);
|
|
@@ -584,8 +470,86 @@ export function evaluate(doc, options = {}) {
|
|
|
584
470
|
}
|
|
585
471
|
return rendered;
|
|
586
472
|
}
|
|
473
|
+
/** Front-matter catalogues → bindings: each JSON table (an array, or `{ rows, units }`) becomes an object of rows keyed by
|
|
474
|
+
* the key column (`Name`, else name / id / position), numeric columns carrying the units given (the table's own, then the
|
|
475
|
+
* front matter's). Errors are messages; the caller places them. */
|
|
476
|
+
export function catalogueTables(catalogs, resolve) {
|
|
477
|
+
const bindings = new Map(), errors = [];
|
|
478
|
+
for (const [name, cat] of Object.entries(catalogs)) {
|
|
479
|
+
try {
|
|
480
|
+
if (!cat || typeof cat !== 'object' || typeof cat.file !== 'string')
|
|
481
|
+
throw new Error(`catalog ${name}: needs a file`);
|
|
482
|
+
const data = resolve?.(cat.file);
|
|
483
|
+
if (data === undefined)
|
|
484
|
+
throw new Error(`catalog ${name}: cannot load ${cat.file}`);
|
|
485
|
+
const rows = Array.isArray(data) ? data : typeof data === 'object' && data !== null && Array.isArray(data.rows) ? data.rows : undefined;
|
|
486
|
+
if (!rows)
|
|
487
|
+
throw new Error(`catalog ${name}: ${cat.file} is not a table`);
|
|
488
|
+
const units = { ...(data.units ?? {}), ...(cat.units ?? {}) };
|
|
489
|
+
for (const u of Object.values(units))
|
|
490
|
+
for (const sym of math.parse(u).filter((x) => x.type === 'SymbolNode'))
|
|
491
|
+
if (isForeignUnit(sym.name) || !math.Unit.isValuelessUnit(sym.name))
|
|
492
|
+
throw new Error(`catalog ${name}: unknown unit "${u}"`); // outside the table, or no unit at all
|
|
493
|
+
const key = cat.key ?? 'Name';
|
|
494
|
+
const table = {};
|
|
495
|
+
for (const row of rows) {
|
|
496
|
+
const id = String(row[key] ?? row['name'] ?? row['id'] ?? Object.keys(table).length + 1);
|
|
497
|
+
const o = {};
|
|
498
|
+
for (const [k, v] of Object.entries(row))
|
|
499
|
+
o[k] = typeof v === 'number' && units[k] ? math.unit(v, units[k]) : v;
|
|
500
|
+
table[id] = o;
|
|
501
|
+
}
|
|
502
|
+
bindings.set(name, table);
|
|
503
|
+
}
|
|
504
|
+
catch (e) {
|
|
505
|
+
errors.push(wording(e));
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
return { bindings, errors };
|
|
509
|
+
}
|
|
510
|
+
/** The second pass's source: every prose loop's expansion in place of its lines, and the map from a line of the spliced
|
|
511
|
+
* text back to the source line (every expanded line points at the loop's first line) for the preview and the CLI. */
|
|
512
|
+
export function spliceLoops(source, loops) {
|
|
513
|
+
const src = source.split('\n');
|
|
514
|
+
const out = [], map = [];
|
|
515
|
+
let cursor = 1;
|
|
516
|
+
for (const l of loops) {
|
|
517
|
+
for (let n = cursor; n < l.start; n++) {
|
|
518
|
+
out.push(src[n - 1] ?? '');
|
|
519
|
+
map.push(n);
|
|
520
|
+
}
|
|
521
|
+
for (const x of l.text.split('\n')) {
|
|
522
|
+
out.push(x);
|
|
523
|
+
map.push(l.start);
|
|
524
|
+
}
|
|
525
|
+
cursor = l.end + 1;
|
|
526
|
+
}
|
|
527
|
+
for (let n = cursor; n <= src.length; n++) {
|
|
528
|
+
out.push(src[n - 1] ?? '');
|
|
529
|
+
map.push(n);
|
|
530
|
+
}
|
|
531
|
+
return { text: out.join('\n'), line: (n) => map[n - 1] ?? n };
|
|
532
|
+
}
|
|
533
|
+
/** The `?`-marked inputs of a document, in order, inside branches and loops too: what the parameters view edits in place. */
|
|
534
|
+
export function parameters(doc) {
|
|
535
|
+
const out = [];
|
|
536
|
+
const walk = (sts) => {
|
|
537
|
+
for (const st of sts) {
|
|
538
|
+
if ((st.kind === 'input' || st.kind === 'derived') && st.param)
|
|
539
|
+
out.push({ name: st.name, expr: st.expr, caption: st.caption, line: st.pos.start.line, options: st.options });
|
|
540
|
+
if (st.kind === 'if')
|
|
541
|
+
st.branches.forEach((b) => walk(b.statements));
|
|
542
|
+
if (st.kind === 'for')
|
|
543
|
+
walk(st.statements);
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
for (const b of doc.blocks)
|
|
547
|
+
if (b.kind === 'calc')
|
|
548
|
+
walk(b.statements);
|
|
549
|
+
return out;
|
|
550
|
+
}
|
|
587
551
|
/** The loop variable as text, inside `{…}` placeholders and inside fenced math/plot lines; prose text is left alone. */
|
|
588
|
-
function substituteVar(body, variable, value) {
|
|
552
|
+
export function substituteVar(body, variable, value) {
|
|
589
553
|
const re = new RegExp(`(?<![\\w\\u0370-\\u03FF])${variable}(?![\\w\\u0370-\\u03FF'])`, 'g');
|
|
590
554
|
const sub = (s) => s.replace(re, `(${value})`); // parenthesised, so `3 j` stays a product after substitution
|
|
591
555
|
let inFence = false;
|
|
@@ -609,4 +573,12 @@ export function statements(r) {
|
|
|
609
573
|
walk(r.blocks);
|
|
610
574
|
return out;
|
|
611
575
|
}
|
|
576
|
+
/** The statement shown for each source line. A `for` loop renders a line once per iteration: the last one stands for the
|
|
577
|
+
* line, in the editor and in the dependency graph alike. */
|
|
578
|
+
export function byLine(items) {
|
|
579
|
+
const out = new Map();
|
|
580
|
+
for (const it of items)
|
|
581
|
+
out.set(it.pos.start.line, it);
|
|
582
|
+
return out;
|
|
583
|
+
}
|
|
612
584
|
//# sourceMappingURL=evaluate.js.map
|