formlab-mcp 0.6.61 → 0.6.63
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/README.md +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
- package/theoretical.js +3 -3
- package/tools/analytics.js +232 -8
- package/tools/formulations.js +4 -0
- package/vendor/reactive.js +613 -0
- package/vendor/theoretical-params.js +179 -12
package/README.md
CHANGED
|
@@ -52,7 +52,7 @@ Ask Claude (or another MCP client) things like:
|
|
|
52
52
|
| `compare_batches` | Reproducibility of 2+ runs (ideally of one formula): each run's **yield %**, actual produced mass, cost/kg; per-ingredient **drift** across the runs vs the formula's proposed wt-%; and the biggest **outlier** run. `basis`: `wt_percent` (default) or `amount` |
|
|
53
53
|
| `get_batch_pivot` | Production analytics — aggregate batches by `group_by` (formula / status / month / prepared_by / project) × `metric` (count, avg_yield_pct, total_produced_kg, avg_cost_per_batch, total_samples, total_tests), with share + total for additive metrics. Optional `batch_uids` scope + `status` filter |
|
|
54
54
|
| `get_project_pivot` | Portfolio analytics — aggregate projects by `group_by` (status / phase / priority / business_unit / site / customer / lead, or `cf:<custom field>`) × `metric` (count, total_formulas / batches / samples, total_cost, avg_formulas / batches / cost_per_batch), rolling child activity + cost up by any project attribute. Optional `project_uids` scope |
|
|
55
|
-
| `get_stability` | Grounded stability / shelf-life analysis for a formulation, sample or batch × parameter (auto-detected): time-series, drift (per-month slope + R²), an I-chart (mean ±3σ + out-of-control points), spec status, and an ICH-Q1E-flavored projected shelf life (point + 95%-CI crossing), all on **one point per test date per run condition** (replicates averaged, never separate time points), split by storage condition. A ranked-scale (ordinal) or text parameter returns its step / pass-fail series instead: per-condition points, firstFail, latest, scaleShift |
|
|
55
|
+
| `get_stability` | Grounded stability / shelf-life analysis for a formulation, sample or batch × parameter (auto-detected): time-series, drift (per-month slope + R²), an I-chart (mean ±3σ + out-of-control points), spec status, and an ICH-Q1E-flavored projected shelf life (point + 95%-CI crossing), all on **one point per test date per run condition** (replicates averaged, never separate time points), split by storage condition. A ranked-scale (ordinal) or text parameter returns its step / pass-fail series instead: per-condition points, firstFail, latest, scaleShift. Also the app's **Time points** (per condition: tested time points, skipped pulls, the next pull with its due date and whether it's overdue, on the formula's own pull schedule, in months or weeks, or the standard one; `as_of`) and **Arrhenius** (rates at the storage temperatures → the rate, Ea, Q10 and shelf life at `predict_at_c`, zero or first `order`, with 95% CIs and a verdict against the target) |
|
|
56
56
|
| `get_design_space` | COMPOSITION design space for one project, several (`projects`) or any formula list (`formulas`, across projects — like the app's Scope → DOE Matrix): which ingredients vary and over what observed wt-% ranges (ranked), an occupied-region summary ("where you've been"), the biggest untested **interior gap** as ready-to-seed DOE ranges (a combination you could have made but skipped), and an optional standardised **2-component PCA** of all varying ingredients — loadings, variance-explained, scree, and a full-dimensional gap. Optional `axes` (choose the 2–3 axes), `by_role` (map ingredients summed by primary Function, e.g. Pigment / Solvent / Film Former — no gap, roles aren't DOE factors) and `property` (highest / lowest formula plus the ingredients whose level tracks it, Spearman ρ). Reports formulas that aren't on the map and the spread on it. Matches the in-app Design Space Viewer exactly. Answers *"where haven't I explored?"* / *"what should I formulate next?"* |
|
|
57
57
|
| `list_doe_designs` | Saved DOE designs — the *recipe* behind each batch of runs: design type, factors + ranges, constraints, run count, D-efficiency. Filters: `project`, `design_type`, `constrained_only`, `name_contains` |
|
|
58
58
|
| `get_doe_design` | One design in full: constraints in plain language, the model it was optimised for, generation settings (run budget, replicates, centre points, seed) and the complete run matrix with the formulation each run became |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "formlab-mcp",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.63",
|
|
4
4
|
"mcpName": "io.github.juliu1980/formlab-mcp",
|
|
5
5
|
"description": "Read-only Model Context Protocol server for FormLab. Lets Claude and other MCP clients read and analyze your FormLab data, from a local export file or your live cloud workspace.",
|
|
6
6
|
"homepage": "https://formvix.com/mcp",
|
package/server.json
CHANGED
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
|
|
3
3
|
"name": "io.github.juliu1980/formlab-mcp",
|
|
4
4
|
"description": "Read-only MCP server for FormLab formulation data: a local export file or your live cloud workspace.",
|
|
5
|
-
"version": "0.6.
|
|
5
|
+
"version": "0.6.63",
|
|
6
6
|
"websiteUrl": "https://formvix.com/mcp",
|
|
7
7
|
"packages": [
|
|
8
8
|
{
|
|
9
9
|
"registryType": "npm",
|
|
10
10
|
"identifier": "formlab-mcp",
|
|
11
|
-
"version": "0.6.
|
|
11
|
+
"version": "0.6.63",
|
|
12
12
|
"runtimeHint": "npx",
|
|
13
13
|
"transport": {
|
|
14
14
|
"type": "stdio"
|
package/theoretical.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// =====================================================================
|
|
2
2
|
// Theoretical parameters for the MCP server — the app's own engine, not a
|
|
3
|
-
// port. mcp/vendor/ holds exact copies of js/cost.js, js/nesting.js
|
|
4
|
-
// js/views/theoretical-params.js (test/mcp-theoretical.test.js keeps them
|
|
3
|
+
// port. mcp/vendor/ holds exact copies of js/cost.js, js/nesting.js,
|
|
4
|
+
// js/views/theoretical-params.js and js/reactive.js (test/mcp-theoretical.test.js keeps them
|
|
5
5
|
// identical), so get_formulation reports the same Energy / NV / Cost per kg
|
|
6
6
|
// the Params tab shows, with the same ⚠ notes.
|
|
7
7
|
//
|
|
@@ -16,7 +16,7 @@ import { readFileSync } from 'node:fs';
|
|
|
16
16
|
import vm from 'node:vm';
|
|
17
17
|
|
|
18
18
|
const VENDOR = new URL('./vendor/', import.meta.url);
|
|
19
|
-
const FILES = ['cost.js', 'nesting.js', 'theoretical-params.js'];
|
|
19
|
+
const FILES = ['cost.js', 'nesting.js', 'theoretical-params.js', 'reactive.js']; // reactive.js: ing.epoxy … ing.vinyl for the Reactive presets
|
|
20
20
|
let _source = null;
|
|
21
21
|
function source() {
|
|
22
22
|
if (!_source) _source = FILES.map(f => readFileSync(new URL(f, VENDOR), 'utf8')).join('\n;\n');
|
package/tools/analytics.js
CHANGED
|
@@ -1350,16 +1350,229 @@ function _shelfLifeAssess(sl, targetMonths, now) {
|
|
|
1350
1350
|
return { verdict: null, level: (overdue || sl.remainingMonths < 3) ? 'medium' : 'info', pointTotal, ciTotal, overdue, crossDate };
|
|
1351
1351
|
}
|
|
1352
1352
|
|
|
1353
|
+
// ---- Time points and Arrhenius: the app's Stability plots as numbers (FormLab 46a–46i) ----
|
|
1354
|
+
// Copies of js/views/stability.js (_stabTpBucket, _stabTpLadder, _stabTpRows, _stabCondTempC, _stabArrRows);
|
|
1355
|
+
// test/mcp-stability-arrhenius-timepoints.test.js holds them to the app's.
|
|
1356
|
+
const _MS_PER_DAY = 86400000;
|
|
1357
|
+
const _PULLS_ACCEL = [1, 2, 3, 6];
|
|
1358
|
+
const _PULLS_LONG = [1, 2, 3, 6, 9, 12, 18, 24, 36];
|
|
1359
|
+
// A time point from days since T₀: T₀ (≤ 3 days), weeks under 3 weeks (or past the last week a schedule names), else
|
|
1360
|
+
// whole months. key = days, for sorting.
|
|
1361
|
+
function _tpBucket(days, weekDays = 21) {
|
|
1362
|
+
if (days <= 3) return { key: 0, label: 'T₀' };
|
|
1363
|
+
if (days < weekDays) { const w = Math.max(1, Math.round(days / 7)); return { key: w * 7, label: `${w} wk` }; }
|
|
1364
|
+
const m = Math.max(1, Math.round(days / 30.4375));
|
|
1365
|
+
return { key: Math.round(m * 30.4375), label: `${m} mo` };
|
|
1366
|
+
}
|
|
1367
|
+
// A pull on a schedule: a number of months, or "<n>w" for weeks (Jun, 1 Nov: short accelerated and freeze-thaw
|
|
1368
|
+
// studies pull at 1, 2, 4 weeks).
|
|
1369
|
+
function _pullWeeks(e) { const w = typeof e === 'string' && /^(\d*\.?\d+)w$/.exec(e); return w ? +w[1] : null; }
|
|
1370
|
+
function _pullDays(e) { const w = _pullWeeks(e); return w != null ? w * 7 : +e * 30.4375; }
|
|
1371
|
+
function _pullLabel(e) { const w = _pullWeeks(e); return w != null ? `${w} wk` : `${+e} mo`; }
|
|
1372
|
+
// Valid pulls, one per day count, in time order.
|
|
1373
|
+
function _pullsClean(a) {
|
|
1374
|
+
if (!Array.isArray(a)) return [];
|
|
1375
|
+
const seen = new Set();
|
|
1376
|
+
return a.map(e => _pullWeeks(e) != null ? e : Number(e)).filter(e => _pullDays(e) > 0)
|
|
1377
|
+
.sort((x, y) => _pullDays(x) - _pullDays(y)).filter(e => { const d = _pullDays(e); return !seen.has(d) && seen.add(d); });
|
|
1378
|
+
}
|
|
1379
|
+
// A formula's own pull schedule (Stability → Time points → Pull schedule, or its Edit): { long, accel }, accel = 35 °C
|
|
1380
|
+
// and up.
|
|
1381
|
+
function _tpPlanOf(formula) {
|
|
1382
|
+
const p = formula && formula.stabilityPulls;
|
|
1383
|
+
return { long: p ? _pullsClean(p.long) : [], accel: p ? _pullsClean(p.accel) : [] };
|
|
1384
|
+
}
|
|
1385
|
+
function _tpOwnPulls(plan, tC) {
|
|
1386
|
+
const own = plan && plan[tC != null && tC >= 35 ? 'accel' : 'long'];
|
|
1387
|
+
return own && own.length ? own : null;
|
|
1388
|
+
}
|
|
1389
|
+
// The months a condition is pulled at: the formula's own, else accelerated (35 °C and up) to 6 months and the rest
|
|
1390
|
+
// to the target shelf life.
|
|
1391
|
+
function _tpLadder(tC, targetMonths, plan) {
|
|
1392
|
+
const own = _tpOwnPulls(plan, tC);
|
|
1393
|
+
if (own) return own;
|
|
1394
|
+
if (tC != null && tC >= 35) return _PULLS_ACCEL;
|
|
1395
|
+
const end = targetMonths || 36;
|
|
1396
|
+
const l = _PULLS_LONG.filter(m => m <= end);
|
|
1397
|
+
if (targetMonths && !l.includes(targetMonths)) l.push(targetMonths);
|
|
1398
|
+
return l;
|
|
1399
|
+
}
|
|
1400
|
+
// A storage temperature in °C from a condition's name: "40 °C / 75% RH" → 40, "2–8 °C" → 5, "104F" → 40, else null.
|
|
1401
|
+
// A bare number with no C or F (a humidity, a cycle count) is never a temperature.
|
|
1402
|
+
function _condTempC(label) {
|
|
1403
|
+
const s = String(label || '');
|
|
1404
|
+
const toC = (v, u) => /f/i.test(u) ? (v - 32) * 5 / 9 : v;
|
|
1405
|
+
const range = s.match(/(\d+(?:\.\d+)?)\s*(?:–|-|to)\s*(\d+(?:\.\d+)?)\s*(?:°|º|deg(?:rees)?\.?)?\s*([CF])\b/i);
|
|
1406
|
+
if (range) return toC((parseFloat(range[1]) + parseFloat(range[2])) / 2, range[3]);
|
|
1407
|
+
const one = s.match(/(^|[^\d.\-–])(-?\d+(?:\.\d+)?)\s*(?:°|º|deg(?:rees)?\.?)?\s*([CF])\b/i);
|
|
1408
|
+
return one ? toC(parseFloat(one[2]), one[3]) : null;
|
|
1409
|
+
}
|
|
1410
|
+
// The study at a glance, one row per storage condition (the app's Time points plot): what was tested at each time
|
|
1411
|
+
// point from the entity's T₀ (its first test under any condition), the time points skipped, and the next pull with
|
|
1412
|
+
// its due date. points: [{ date, cond, pf }].
|
|
1413
|
+
function _mcpTimePoints(points, formula, targetMonths, now) {
|
|
1414
|
+
if (!points.length) return null;
|
|
1415
|
+
const day = d => new Date(d).toISOString().slice(0, 10);
|
|
1416
|
+
const t0 = Math.min(...points.map(p => p.date.getTime()));
|
|
1417
|
+
const plan = _tpPlanOf(formula);
|
|
1418
|
+
const byCond = new Map();
|
|
1419
|
+
points.forEach(p => { const c = (p.cond || '').trim(); if (!byCond.has(c)) byCond.set(c, []); byCond.get(c).push(p); });
|
|
1420
|
+
const rows = [...byCond.entries()].map(([cond, ps]) => ({ cond, ps, tC: cond ? _condTempC(cond) : null }))
|
|
1421
|
+
.sort((a, b) => (a.tC == null ? -Infinity : a.tC) - (b.tC == null ? -Infinity : b.tC) || a.cond.localeCompare(b.cond))
|
|
1422
|
+
.map(({ cond, ps, tC }) => {
|
|
1423
|
+
const ladder = _tpLadder(tC, targetMonths, plan);
|
|
1424
|
+
// A schedule in weeks keeps its time points in weeks up to its last week pull.
|
|
1425
|
+
const weekDays = Math.max(21, ...ladder.filter(e => _pullWeeks(e) != null).map(e => _pullDays(e) + 4));
|
|
1426
|
+
const keyOf = e => _tpBucket(_pullDays(e), weekDays).key;
|
|
1427
|
+
const cells = new Map();
|
|
1428
|
+
ps.forEach(p => {
|
|
1429
|
+
const b = _tpBucket((p.date.getTime() - t0) / _MS_PER_DAY, weekDays);
|
|
1430
|
+
if (!cells.has(b.key)) cells.set(b.key, { ...b, dates: new Set(), pfs: [] });
|
|
1431
|
+
const c = cells.get(b.key); c.dates.add(day(p.date)); c.pfs.push(p.pf);
|
|
1432
|
+
});
|
|
1433
|
+
const lastKey = Math.max(...cells.keys());
|
|
1434
|
+
const nextE = ladder.find(e => keyOf(e) > lastKey);
|
|
1435
|
+
const due = nextE == null ? null : t0 + _pullDays(nextE) * _MS_PER_DAY;
|
|
1436
|
+
return { cond, tC, cells, lastKey, weekDays, ladder, ladderKeys: ladder.map(keyOf), own: !!_tpOwnPulls(plan, tC),
|
|
1437
|
+
next: nextE == null ? null : { timePoint: _pullLabel(nextE), due: day(due), daysUntil: Math.floor((due - now) / _MS_PER_DAY) } };
|
|
1438
|
+
});
|
|
1439
|
+
// Skipped: a time point before this row's last test that its schedule, or (on the standard one) another row at its
|
|
1440
|
+
// temperature on the standard one, has.
|
|
1441
|
+
rows.forEach(r => {
|
|
1442
|
+
const peers = r.own ? [] : rows.filter(o => o !== r && !o.own && (o.tC != null ? o.tC === r.tC : o.cond === r.cond));
|
|
1443
|
+
const keys = new Set([...r.ladderKeys, ...peers.flatMap(o => [...o.cells.keys()])]);
|
|
1444
|
+
r.skipped = [...keys].filter(k => k > 0 && k < r.lastKey && !r.cells.has(k)).sort((a, b) => a - b);
|
|
1445
|
+
});
|
|
1446
|
+
return {
|
|
1447
|
+
t0: day(t0),
|
|
1448
|
+
rows: rows.map(r => ({
|
|
1449
|
+
condition: r.cond || null,
|
|
1450
|
+
temperatureC: r.tC != null ? _round(r.tC, 1) : null,
|
|
1451
|
+
schedule: r.own ? 'formula' : 'standard',
|
|
1452
|
+
pulls: r.ladder.map(_pullLabel),
|
|
1453
|
+
tested: [...r.cells.values()].sort((a, b) => a.key - b.key).map(c => ({ timePoint: c.label, testDates: c.dates.size,
|
|
1454
|
+
pf: c.pfs.includes('fail') ? 'fail' : c.pfs.includes('pass') ? 'pass' : null })),
|
|
1455
|
+
skipped: r.skipped.map(k => _tpBucket(k, r.weekDays).label),
|
|
1456
|
+
next: r.next ? { ...r.next, overdue: r.next.daysUntil < 0 } : null,
|
|
1457
|
+
})),
|
|
1458
|
+
};
|
|
1459
|
+
}
|
|
1460
|
+
// Two-sided 95% Student t (t 0.975), for a confidence interval: the Arrhenius CI. A copy of the app's _stabT975.
|
|
1461
|
+
const _T975_TABLE = [null, 12.706, 4.303, 3.182, 2.776, 2.571, 2.447, 2.365, 2.306, 2.262, 2.228, 2.201, 2.179, 2.160, 2.145, 2.131, 2.120, 2.110, 2.101, 2.093, 2.086, 2.080, 2.074, 2.069, 2.064, 2.060, 2.056, 2.052, 2.048, 2.045, 2.042];
|
|
1462
|
+
function _t975(df) {
|
|
1463
|
+
df = Math.floor(df);
|
|
1464
|
+
if (!(df >= 1)) return Infinity;
|
|
1465
|
+
if (df < _T975_TABLE.length) return _T975_TABLE[df];
|
|
1466
|
+
const z = 1.959964;
|
|
1467
|
+
return z + (z ** 3 + z) / (4 * df) + (5 * z ** 5 + 16 * z ** 3 + 3 * z) / (96 * df * df);
|
|
1468
|
+
}
|
|
1469
|
+
// Standard error of an OLS slope; null with fewer than 3 points.
|
|
1470
|
+
function _slopeSE(xs, ys, fit) {
|
|
1471
|
+
const n = xs.length;
|
|
1472
|
+
if (!fit || n < 3) return null;
|
|
1473
|
+
const mx = xs.reduce((a, b) => a + b, 0) / n;
|
|
1474
|
+
const ssX = xs.reduce((a, x) => a + (x - mx) ** 2, 0);
|
|
1475
|
+
if (!(ssX > 0)) return null;
|
|
1476
|
+
let ssR = 0; xs.forEach((x, i) => { ssR += (ys[i] - (fit.intercept + fit.slope * x)) ** 2; });
|
|
1477
|
+
return Math.sqrt(ssR / (n - 2) / ssX);
|
|
1478
|
+
}
|
|
1479
|
+
// Arrhenius (the app's plot of that name): each storage condition with a temperature in its name and 3+ test dates
|
|
1480
|
+
// gives a rate (zero order: the slope per month; first order: of ln value, a steady % change). ln(rate) against 1/T
|
|
1481
|
+
// is fitted and read at atC for the rate, Ea, Q10 and the shelf life from the T₀ value to the spec limit, with 95%
|
|
1482
|
+
// CIs. null when no condition names a temperature. points: [{ date, value, cond }].
|
|
1483
|
+
function _mcpArrhenius(points, spec, atC, order, targetMonths) {
|
|
1484
|
+
const firstOrder = order === 'first';
|
|
1485
|
+
const skipped = [];
|
|
1486
|
+
const byT = new Map();
|
|
1487
|
+
points.forEach(p => {
|
|
1488
|
+
const cond = (p.cond || '').trim();
|
|
1489
|
+
const t = cond ? _condTempC(cond) : null;
|
|
1490
|
+
if (t == null) { const k = cond || '(no condition)'; if (!skipped.some(x => x.condition === k)) skipped.push({ condition: k, why: cond ? 'no temperature in the name' : 'no storage condition' }); return; }
|
|
1491
|
+
const key = Number(t.toFixed(1));
|
|
1492
|
+
if (!byT.has(key)) byT.set(key, { tC: key, conds: new Set(), points: [] });
|
|
1493
|
+
byT.get(key).conds.add(cond); byT.get(key).points.push(p);
|
|
1494
|
+
});
|
|
1495
|
+
if (!byT.size) return null;
|
|
1496
|
+
const temps = [...byT.values()].sort((a, b) => a.tC - b.tC).map(g => {
|
|
1497
|
+
const pts = g.points.slice().sort((a, b) => a.date - b.date);
|
|
1498
|
+
const t0 = pts[0].date.getTime();
|
|
1499
|
+
const days = new Set(pts.map(p => p.date.toISOString().slice(0, 10))).size;
|
|
1500
|
+
const mx = pts.map(p => (p.date.getTime() - t0) / _MS_PER_MONTH), my = pts.map(p => p.value);
|
|
1501
|
+
const fitOf = (ys) => { const f = days >= 3 ? _ols(mx, ys) : null; if (f) { f.se = _slopeSE(mx, ys, f) || 0; f.df = pts.length - 2; } return f; };
|
|
1502
|
+
const pos = my.every(v => v > 0);
|
|
1503
|
+
const fitZ = fitOf(my), fitF = pos ? fitOf(my.map(Math.log)) : null;
|
|
1504
|
+
const firstDay = pts[0].date.toISOString().slice(0, 10);
|
|
1505
|
+
const t0Vals = pts.filter(p => p.date.toISOString().slice(0, 10) === firstDay).map(p => p.value);
|
|
1506
|
+
return { tC: g.tC, label: [...g.conds].join(' / '), points: pts, days, fit: firstOrder ? fitF : fitZ, fitZ, fitF, pos,
|
|
1507
|
+
y0: t0Vals.reduce((a, b) => a + b, 0) / t0Vals.length };
|
|
1508
|
+
});
|
|
1509
|
+
// The direction is the hottest fitted temperature's; a temperature moving the other way, or not at all, has no rate.
|
|
1510
|
+
const fitted = temps.filter(t => t.fit && Math.abs(t.fit.slope) > 1e-12);
|
|
1511
|
+
temps.filter(t => !t.fit).forEach(t => skipped.push({ condition: t.label, why: t.days < 3 ? `${t.days} test date${t.days === 1 ? '' : 's'}` : firstOrder && !t.pos ? 'a value ≤ 0' : 'no change' }));
|
|
1512
|
+
const dir = fitted.length ? Math.sign(fitted[fitted.length - 1].fit.slope) : 0;
|
|
1513
|
+
const used = fitted.filter(t => Math.sign(t.fit.slope) === dir);
|
|
1514
|
+
fitted.filter(t => Math.sign(t.fit.slope) !== dir).forEach(t => skipped.push({ condition: t.label, why: 'changes the other way' }));
|
|
1515
|
+
const rate = (k) => firstOrder ? _round(k * 100, 4) : _round(k, 6); // first order: % per month
|
|
1516
|
+
const mo = (m) => m == null ? null : (!Number.isFinite(m) || m > 120) ? '> 120' : _round(m, 1);
|
|
1517
|
+
const out = {
|
|
1518
|
+
predictAtC: atC, order, rateUnit: firstOrder ? '% per month' : 'per month',
|
|
1519
|
+
temperatures: used.map(t => ({ temperatureC: t.tC, conditions: t.label, testDates: t.days, rate: rate(Math.abs(t.fit.slope)), r2: _round(t.fit.r2, 3) })),
|
|
1520
|
+
skipped,
|
|
1521
|
+
};
|
|
1522
|
+
const both = used.filter(t => t.fitZ && t.fitF);
|
|
1523
|
+
if (both.length) out.meanR2ByOrder = { zero: _round(both.reduce((a, t) => a + t.fitZ.r2, 0) / both.length, 3), first: _round(both.reduce((a, t) => a + t.fitF.r2, 0) / both.length, 3) };
|
|
1524
|
+
if (used.length < 2) { out.why = !points.length ? 'no readings' : used.length ? 'one temperature with a rate' : 'no temperature with a rate'; return out; }
|
|
1525
|
+
const xs = used.map(t => 1 / (t.tC + 273.15)), ys = used.map(t => Math.log(Math.abs(t.fit.slope)));
|
|
1526
|
+
const arr = _ols(xs, ys);
|
|
1527
|
+
if (!arr || !(arr.slope < 0)) { out.why = 'the rate doesn’t rise with temperature'; return out; }
|
|
1528
|
+
const kAt = (c) => Math.exp(arr.intercept + arr.slope / (c + 273.15));
|
|
1529
|
+
// 95% CI on ln k: each rate's own scatter carried through the fit (SE(ln k) = SE(k) / k), or, with 3+
|
|
1530
|
+
// temperatures, the rates' scatter about the line when that is wider.
|
|
1531
|
+
const m = used.length, mx = xs.reduce((a, b) => a + b, 0) / m, sxx = xs.reduce((a, x) => a + (x - mx) ** 2, 0);
|
|
1532
|
+
const v = used.map(t => Math.max(1e-18, (t.fit.se / Math.abs(t.fit.slope)) ** 2));
|
|
1533
|
+
const tW = _t975(used.reduce((a, t) => a + t.fit.df, 0));
|
|
1534
|
+
const ssB = xs.reduce((a, x, i) => a + (ys[i] - (arr.intercept + arr.slope * x)) ** 2, 0);
|
|
1535
|
+
const tsB = m > 2 ? _t975(m - 2) * Math.sqrt(ssB / (m - 2)) : 0;
|
|
1536
|
+
const d = 1 / (atC + 273.15) - mx;
|
|
1537
|
+
const lam = xs.map(x => 1 / m + d * (x - mx) / sxx);
|
|
1538
|
+
const h = Math.max(tW * Math.sqrt(lam.reduce((a, l, i) => a + l * l * v[i], 0)), tsB * Math.sqrt(1 / m + d * d / sxx));
|
|
1539
|
+
const k = kAt(atC), kLo = k * Math.exp(-h), kHi = k * Math.exp(h);
|
|
1540
|
+
out.fit = { activationEnergyKJmol: _round(-arr.slope * 8.314 / 1000, 1), q10: _round(kAt(atC + 10) / k, 2), r2: _round(arr.r2, 3), exactLine: m === 2 };
|
|
1541
|
+
out.rateAt = { rate: rate(k), ci95: [rate(kLo), rate(kHi)] };
|
|
1542
|
+
// Shelf life at atC: from the T₀ value (the first test date's mean, averaged over the temperatures used) to the
|
|
1543
|
+
// spec limit the change heads for, at the predicted rate; the CI from the rate's (a faster rate, a shorter life).
|
|
1544
|
+
const y0 = used.reduce((a, t) => a + t.y0, 0) / used.length;
|
|
1545
|
+
const limit = dir < 0 ? (spec && spec.min) : (spec && spec.max);
|
|
1546
|
+
let shelf = null, lo = null, hi = null, why = null;
|
|
1547
|
+
if (limit == null) why = spec && (spec.min != null || spec.max != null) ? `no ${dir < 0 ? 'lower' : 'upper'} limit` : 'no spec';
|
|
1548
|
+
else if ((limit - y0) * dir <= 0) why = 'starts outside spec';
|
|
1549
|
+
else if (firstOrder && !(limit > 0)) shelf = lo = hi = Infinity;
|
|
1550
|
+
else {
|
|
1551
|
+
const gap = firstOrder ? Math.abs(Math.log(limit / y0)) : Math.abs(limit - y0);
|
|
1552
|
+
shelf = gap / k; lo = gap / kHi; hi = gap / kLo;
|
|
1553
|
+
}
|
|
1554
|
+
const verdict = shelf != null && targetMonths ? (shelf < targetMonths ? 'short' : lo < targetMonths ? 'marginal' : 'meets') : null;
|
|
1555
|
+
out.shelfLife = shelf == null ? { months: null, why }
|
|
1556
|
+
: { months: mo(shelf), ci95Months: [mo(lo), mo(hi)], fromValue: _round(y0, 6), toLimit: limit, verdict };
|
|
1557
|
+
// Real time, when atC was itself tested: its own projection, for comparison.
|
|
1558
|
+
const rt = temps.find(t => Math.abs(t.tC - atC) <= 1);
|
|
1559
|
+
if (rt) { const a = _shelfLifeAssess(_shelfLife(rt.points, spec || {}), null); out.realTimeShelfLifeMonths = a ? _round(a.pointTotal, 1) : null; }
|
|
1560
|
+
return out;
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1353
1563
|
const get_stability = {
|
|
1354
1564
|
definition: {
|
|
1355
1565
|
name: 'get_stability',
|
|
1356
|
-
description: 'Grounded stability / shelf-life analysis for one entity × parameter — the deterministic numbers behind the Stability & Trends view. Pass a formulation (pools all its samples), a sample (that sample over time), or a batch (pools its samples) by id or UID, plus a parameter name. Returns the time series, drift (per-month slope + R²), an individuals control chart (mean ± 3σ + out-of-control points), spec status, and an ICH-flavored projected shelf life (linear extrapolation to the spec crossing: point estimate + the conservative 95%-confidence-bound crossing). When measurements carry run conditions (e.g. Storage 25 °C vs 40 °C) it splits into one series per condition — a true accelerated-vs-ambient comparison. A point is one TEST DATE: every reading taken that day under that condition is averaged (points = test dates, readings = the raw count), so replicates never count as separate time points in the drift, control chart or shelf-life fit — the same points as the app. A ranked-scale (ordinal, e.g. pencil hardness) or text (e.g. appearance) parameter returns kind "ordinal" / "categorical" instead: per-condition points with the label (median rank for an ordinal), pass/fail, firstFail, latest and scaleShift — the app\'s step / pass-fail-strip trend, with no regression. Use these figures directly; do not re-derive the regression.',
|
|
1566
|
+
description: 'Grounded stability / shelf-life analysis for one entity × parameter — the deterministic numbers behind the Stability & Trends view. Pass a formulation (pools all its samples), a sample (that sample over time), or a batch (pools its samples) by id or UID, plus a parameter name. Returns the time series, drift (per-month slope + R²), an individuals control chart (mean ± 3σ + out-of-control points), spec status, and an ICH-flavored projected shelf life (linear extrapolation to the spec crossing: point estimate + the conservative 95%-confidence-bound crossing). When measurements carry run conditions (e.g. Storage 25 °C vs 40 °C) it splits into one series per condition — a true accelerated-vs-ambient comparison. A point is one TEST DATE: every reading taken that day under that condition is averaged (points = test dates, readings = the raw count), so replicates never count as separate time points in the drift, control chart or shelf-life fit — the same points as the app. A ranked-scale (ordinal, e.g. pencil hardness) or text (e.g. appearance) parameter returns kind "ordinal" / "categorical" instead: per-condition points with the label (median rank for an ordinal), pass/fail, firstFail, latest and scaleShift — the app\'s step / pass-fail-strip trend, with no regression. Also returns timePoints (the app\'s Time points plot: per condition, what was tested at each time point, skipped pulls, the next pull with its due date and whether it is overdue, on the formula\'s own pull schedule or the standard one) and arrhenius (the app\'s Arrhenius plot: rates at the storage temperatures fitted to predict the rate and shelf life at predict_at_c, with 95% CIs and a verdict against the target shelf life). Use these figures directly; do not re-derive the regression.',
|
|
1357
1567
|
inputSchema: {
|
|
1358
1568
|
type: 'object',
|
|
1359
1569
|
properties: {
|
|
1360
1570
|
entity_id: { type: 'string', description: 'A formulation, sample, or batch — id or UID (e.g. FRM-002, SMP-007, BTC-001). The type is auto-detected and sets the pooling level.' },
|
|
1361
1571
|
parameter: { type: 'string', description: 'The measured parameter to analyze (case-insensitive, e.g. "Niacinamide assay").' },
|
|
1362
1572
|
by_condition: { type: 'boolean', description: 'Split the series by captured storage condition (default true). Set false to pool all conditions into one trend.' },
|
|
1573
|
+
predict_at_c: { type: 'number', description: 'Arrhenius: the storage temperature (°C) to predict the rate and shelf life at (default 25; the app offers 5, 25 and 30).' },
|
|
1574
|
+
order: { type: 'string', enum: ['zero', 'first'], description: 'Arrhenius kinetics: "zero" (a steady change per month, default) or "first" (a steady % change per month, e.g. an assay or viscosity falling by a share of what is left). meanR2ByOrder compares the two.' },
|
|
1575
|
+
as_of: { type: 'string', description: 'Date (YYYY-MM-DD) that time points\' next pulls are counted from (due in / overdue). Default today.' },
|
|
1363
1576
|
},
|
|
1364
1577
|
required: ['entity_id', 'parameter'],
|
|
1365
1578
|
},
|
|
@@ -1423,7 +1636,8 @@ const get_stability = {
|
|
|
1423
1636
|
}
|
|
1424
1637
|
const cond = (m.conditions && Object.keys(m.conditions).length)
|
|
1425
1638
|
? Object.entries(m.conditions).map(([k, v]) => `${k} ${v}`).join(' · ') : '';
|
|
1426
|
-
|
|
1639
|
+
const pf0 = sp ? _evalPassFail(m, t.templateId) : null;
|
|
1640
|
+
points.push({ date, day: dStr, value, cond, spec: sp, pf: pf0 === 'pass' || pf0 === 'fail' ? pf0 : null });
|
|
1427
1641
|
});
|
|
1428
1642
|
});
|
|
1429
1643
|
const specList = [...specByKey.values()].map(e => ({ min: e.min, max: e.max, readings: e.readings, sources: [...e.sources] }));
|
|
@@ -1446,21 +1660,27 @@ const get_stability = {
|
|
|
1446
1660
|
points.length = 0;
|
|
1447
1661
|
byDay.forEach(g => {
|
|
1448
1662
|
const value = g.reduce((a, r) => a + r.value, 0) / g.length;
|
|
1449
|
-
points.push({ date: new Date(g[0].day), value, cond: g[0].cond, spec: (g.find(r => r.spec) || {}).spec || null, readings: g.length
|
|
1663
|
+
points.push({ date: new Date(g[0].day), value, cond: g[0].cond, spec: (g.find(r => r.spec) || {}).spec || null, readings: g.length,
|
|
1664
|
+
pf: g.some(r => r.pf === 'fail') ? 'fail' : g.some(r => r.pf === 'pass') ? 'pass' : null });
|
|
1450
1665
|
});
|
|
1451
1666
|
points.sort((a, b) => (a.date - b.date) || a.cond.localeCompare(b.cond));
|
|
1452
|
-
if (!points.length && graded.length) return _mcpGradedStability(entity, entityType, args, graded);
|
|
1453
|
-
if (!points.length) return { error: `No dated "${args.parameter}" measurements on ${entity.uid || entity.id}.` };
|
|
1454
|
-
|
|
1455
|
-
const spec = { min: specMin, max: specMax };
|
|
1456
1667
|
// Target shelf life: the formula's own Shelf life, else the workspace
|
|
1457
1668
|
// default when this store carries it (the app's Settings → Stability).
|
|
1669
|
+
// A batch or sample reaches its formula through formulationId (a sample of a batch through the batch).
|
|
1458
1670
|
const formula = entityType === 'formulation' ? entity
|
|
1459
|
-
: (db.formulations || []).find(f => f.id === entity.formulationId) || null;
|
|
1671
|
+
: (db.formulations || []).find(f => f.id === (entity.formulationId || ((db.batches || []).find(b => b.id === entity.batchId) || {}).formulationId)) || null;
|
|
1460
1672
|
const ownT = formula ? parseFloat(formula.shelfLifeMonths) : NaN;
|
|
1461
1673
|
const defT = parseFloat(db.defaultShelfLifeMonths);
|
|
1462
1674
|
const target = (Number.isFinite(ownT) && ownT > 0) ? { months: ownT, source: 'formula' }
|
|
1463
1675
|
: (Number.isFinite(defT) && defT > 0) ? { months: defT, source: 'workspace default' } : null;
|
|
1676
|
+
const asOf = args.as_of && /^\d{4}-\d{2}-\d{2}$/.test(args.as_of) ? Date.parse(args.as_of) : Date.now();
|
|
1677
|
+
if (!points.length && graded.length) {
|
|
1678
|
+
const tp = _mcpTimePoints(graded.map(r => ({ date: new Date(r.day), cond: r.cond, pf: r.pf === 'pass' || r.pf === 'fail' ? r.pf : null })), formula, target && target.months, asOf);
|
|
1679
|
+
return { ..._mcpGradedStability(entity, entityType, args, graded), ...(tp ? { timePoints: tp } : {}) };
|
|
1680
|
+
}
|
|
1681
|
+
if (!points.length) return { error: `No dated "${args.parameter}" measurements on ${entity.uid || entity.id}.` };
|
|
1682
|
+
|
|
1683
|
+
const spec = { min: specMin, max: specMax };
|
|
1464
1684
|
const analyze = (pts) => {
|
|
1465
1685
|
const ys = pts.map(p => p.value);
|
|
1466
1686
|
const n = ys.length;
|
|
@@ -1519,6 +1739,10 @@ const get_stability = {
|
|
|
1519
1739
|
entity: { type: entityType, uid: entity.uid, name: entity.name || entity.uid },
|
|
1520
1740
|
parameter: args.parameter, unit, spec, ...((skipped.ordinal || skipped.categorical) ? { skipped, skippedNote: 'Ordinal (ranked scale) and text readings have no number to trend and are left out, as in the app.' } : {}), ...(specVaries ? { specVaries, specNote: 'Readings were judged against different specs (different panels): no single band, no shelf-life projection; each reading keeps its own pass/fail.' } : {}), pointCount: points.length, byCondition: split, series,
|
|
1521
1741
|
targetShelfLife: target ? { months: target.months, source: target.source } : null,
|
|
1742
|
+
timePoints: _mcpTimePoints(points, formula, target && target.months, asOf),
|
|
1743
|
+
arrhenius: specVaries ? null : _mcpArrhenius(points, spec, Number.isFinite(+args.predict_at_c) && args.predict_at_c !== null && args.predict_at_c !== '' ? +args.predict_at_c : 25, args.order === 'first' ? 'first' : 'zero', target && target.months),
|
|
1744
|
+
timePointsNote: 'timePoints: one row per storage condition, time points counted from t0 (the first test under any condition): tested (pf "fail" when any reading that time point failed), skipped (a time point before the last test that the schedule or another condition at that temperature has, but this one does not), next (the next pull not yet tested, its due date, daysUntil; overdue = past as_of; null = schedule complete). schedule "formula" = the formula\'s own pulls (months, or weeks such as "2 wk"), else "standard": 1, 2, 3, 6 months at 35 °C and up; 1, 2, 3, 6, 9, 12, 18, 24, 36 months up to the target shelf life; pulls lists the row\'s schedule.',
|
|
1745
|
+
arrheniusNote: 'arrhenius (null when no condition names a temperature): rates per storage temperature (3+ test dates each), ln(rate) against 1/T fitted and read at predictAtC: activation energy, Q10 (how many times faster 10 °C warmer, from predictAtC to predictAtC + 10; it varies with temperature), the rate there with its 95% CI, and the shelf life there from the T0 value to the spec limit (ci95Months: a faster rate gives the low end). "> 120" = beyond 10 years. verdict as shelfLife.verdict, against targetShelfLife. realTimeShelfLifeMonths = the trend projection at predictAtC itself when that temperature was tested. why = no prediction, and the reason.',
|
|
1522
1746
|
note: 'shelfLife.fromT0Months / ci95FromT0Months are the projected shelf life counted from the first test (T0): point estimate and the conservative (ICH Q1E) 95%-bound crossing. remainingMonths / ci95Months are the same, counted from the last test. verdict compares against targetShelfLife: "short" = the trend crosses spec before the target, "marginal" = the trend clears it but the 95% bound does not, "meets" = both clear it; null = no target set (then concern is by time left: medium <3 mo or overdue, else info). A projection never reaches \"high\": high is reserved for a MEASURED out-of-spec value (spec.latestInSpec=false). short/overdue → medium, marginal/meets → info. overdue=true means projectedCrossDate is already past today (time left runs from the last test), so the sample is probably out of spec now — recommend a re-test. reportable=false means the app shows no projection (R² < 0.3, crossing already past, or beyond 5 years). Numbers are computed here — narrate them, do not recompute.',
|
|
1523
1747
|
};
|
|
1524
1748
|
},
|
package/tools/formulations.js
CHANGED
|
@@ -30,6 +30,10 @@ function _trimFormulation(f) {
|
|
|
30
30
|
// Target shelf life (months): sets finished-goods expiry AND is what
|
|
31
31
|
// get_stability judges the projected shelf life against.
|
|
32
32
|
shelfLifeMonths: f.shelfLifeMonths ?? null,
|
|
33
|
+
// Its own stability pull schedule (Stability → Time points → Pull schedule, or its Edit): long = below 35 °C,
|
|
34
|
+
// accel = 35 °C and up; a number is months, "2w" two weeks; null = the standard schedule. get_stability's timePoints
|
|
35
|
+
// follow it.
|
|
36
|
+
stabilityPulls: f.stabilityPulls && (Array.isArray(f.stabilityPulls.long) || Array.isArray(f.stabilityPulls.accel)) ? { long: f.stabilityPulls.long || [], accel: f.stabilityPulls.accel || [] } : null,
|
|
33
37
|
// Density of the MIXED product (g/mL), when declared — volume-targeted
|
|
34
38
|
// batches scale by it instead of the ideal-mix estimate. null = not set.
|
|
35
39
|
finishedDensity: (f.finishedDensity && isFinite(parseFloat(f.finishedDensity.value)))
|