The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Rebuild Lab Bench around real experiments and reproducible evidence (#155)
Dee119c5b69ac1d
diff --git a/.github/workflows/experience-checks.yml b/.github/workflows/experience-checks.ymlindex 2b13e4d84..8cda6be3d 100644--- a/.github/workflows/experience-checks.yml+++ b/.github/workflows/experience-checks.yml@@ -24,6 +24,8 @@ jobs:sh store/agents/voxel-worlds/toolchain/setup.shsh store/agents/drone-pilot/toolchain/setup.shsh store/agents/game-master/toolchain/setup.sh+ sh store/agents/lab-bench/toolchain/setup.sh+ node store/agents/lab-bench/toolchain/build-math.mjs --checknode store/tools/build-experiences.mjs --check- name: Verify packaged branding matches desktop assetsrun: node store/tools/build-experience-branding.mjs --check@@ -57,7 +59,7 @@ jobs:authoring-browser:runs-on: ubuntu-latest- timeout-minutes: 15+ timeout-minutes: 20steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7@@ -103,6 +105,21 @@ jobs:node store/agents/game-master/test/browser.mjsnode store/agents/game-master/test/acceptance.mjspython3 store/agents/game-master/test/verify-delivery.py work/experience-evidence/relay-acceptance+ - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6+ with:+ python-version: '3.12'+ - name: Plan experiments, import measurements and independently verify the delivered statistics+ env:+ LAB_QA_ROOT: work/experience-evidence/signal-browser+ LAB_ACCEPTANCE_ROOT: work/experience-evidence/signal-acceptance+ run: |+ npm ci --prefix store/agents/lab-bench/toolchain --ignore-scripts --no-audit --no-fund+ node store/agents/lab-bench/test/browser.mjs+ node store/agents/lab-bench/test/acceptance.mjs+ node store/agents/lab-bench/test/reopen-deliveries.mjs work/experience-evidence/signal-acceptance+ python3 -m venv /tmp/signal-statistics-reader+ /tmp/signal-statistics-reader/bin/pip install -r store/agents/lab-bench/template/studio/requirements.txt+ /tmp/signal-statistics-reader/bin/python store/agents/lab-bench/test/verify-delivery.py work/experience-evidence/signal-acceptance- name: Verify MIDI and aligned audio with independent readersrun: |python3 -m venv /tmp/music-delivery-readerdiff --git a/HANDOFF.md b/HANDOFF.mdindex 2205109c6..213468c52 100644--- a/HANDOFF.md+++ b/HANDOFF.md@@ -9,8 +9,7 @@ studio, source save bridge and complete launch exports; [FORME-REBUILD.md](work/records the actual tests and limits. It is published for Store testing (#141). Voxel Worlds now has a source-backed 3D studio,standard exports and six independently reopened deliveries; published in #146 at `88250305`,with public catalog/artifact/screenshots verified and a normal Store install on this Mac. Read-[its acceptance evidence](store/agents/voxel-worlds/test/ACCEPTANCE.md). Drone Pilot is in progress;-Game Master and Lab Bench also remain unlisted. The older “focus only on Art/Music”+[its acceptance evidence](store/agents/voxel-worlds/test/ACCEPTANCE.md). Drone Pilot is published (#151), and Game Master is published (#153); both were installed and verified on this Mac. Game Master's public catalog, studio and screenshots match its tested release. Lab Bench is the last rebuild, now in progress and still unlisted. The older “focus only on Art/Music”instruction below is historical and has been superseded by this user request.**Score installation regression fixed and published (#145):** setup now installs officialdiff --git a/desktop/lib/widgets/engine_identity.dart b/desktop/lib/widgets/engine_identity.dartindex 66d990411..5669fac2f 100644--- a/desktop/lib/widgets/engine_identity.dart+++ b/desktop/lib/widgets/engine_identity.dart@@ -351,7 +351,7 @@ const _harnesses = <String, EngineIdentity>{id: 'autonomous/lab-bench',label: 'Lab Bench',category: 'Science',- tagline: 'Explore an experiment with reproducible synthetic data',+ tagline: 'Turn a question into evidence you can act on',creator: 'Autonomous',color: Color(0xfff2ca7d),asset: 'assets/engine-icons/lab-bench.png',diff --git a/store/agents/lab-bench/.gitignore b/store/agents/lab-bench/.gitignorenew file mode 100644index 000000000..b1df3fe62--- /dev/null+++ b/store/agents/lab-bench/.gitignore@@ -0,0 +1,3 @@+template/.harness/+template/delivery/+toolchain/browsers/diff --git a/store/agents/lab-bench/AGENTS.md b/store/agents/lab-bench/AGENTS.mdindex 2c1f3a8b7..df34c8543 100644--- a/store/agents/lab-bench/AGENTS.md+++ b/store/agents/lab-bench/AGENTS.md@@ -1,68 +1,65 @@-# Lab Bench / Experiment Log harness+# Lab Bench / Signal-You turn a plain-English description into a **deterministic, seedable bench page**-rendered in one self-contained `bench/index.html`. The pane renders the experiment-live — seeded synthetic data with interactive charts — so the person probes the-dataset, and a re-seed, as you work.+Help a person turn a practical question into an experiment they can carry out, then turn their+actual observations into a decision they can explain. Author the factors, independent units,+procedure, allocation and analysis for their question. The coffee plan is an editable example;+there is no fixed list of experiment genres and no synthetic-response generator in the product.-## What a good bench is+## Complete the experiment workflow-- **One file, offline.** All data generation and charting inline on canvas. No CDN- at runtime. A `?seed=` query param selects the version: the same seed always- renders the same dataset on this machine.-- **Determinism is the product.** Seed a PRNG and name sub-streams (per variable,- per group, per noise source) so tuning one doesn't reshuffle the rest. Same seed- → same dataset, same trend, same spread.-- **Probeable, not just pretty.** Make the dataset interrogable: a live-rendering- run, a trendline, and filters the person can click. The bench should invite- questions about the data, not just display it.-- **Be honest about verification.** Same-machine render is checkable. Anything that- depends on browser timing (animated runs) is not bit-identical across machines —- say so in the verdict rather than overclaiming.+1. Establish the decision, continuous response and unit, controllable factors/ranges, independent+ experimental unit, available repetitions, blocking conditions and practical constraints.+ Ask only for missing information that materially changes the design. Record assumptions.+2. Author `bench/project.json` using the [source contract](skills/bench/references/project.md).+ Full factorial designs cover every combination within each block. Randomize independent runs;+ repeated readings of the same sample do not become independent replicates. Scheduled controls+ use numeric midpoints and categorical reference levels at the start, end and between treatments.+3. Build `node tools/build.mjs`. Deliver an actual collection sheet early. Explain the procedure+ in the person's language, including what to measure and what to record if a run goes wrong.+ The person can approve the protocol in the studio; collecting measurements also protects it.+4. Import actual CSVs or record supplied observations. Keep original bytes, hashes, run ids, units+ and row references. Never fill missing responses with predictions or fabricated measurements.+ Use the correction/exclusion helpers with reasons. Preserve existing run settings and sources.+5. Fit only an identifiable, appropriate model. Inspect the raw/run-order, measured–fitted and+ residual views. Distinguish uncertainty in the mean from uncertainty in a new observation.+ A high R² or an influence flag is not a decision. Do not delete rows to improve a result.+6. Compare practical settings and append a follow-up. Confirmation snapshots freeze the training+ matrix, model and forecasts; new responses stay held out. Extensions explicitly add future+ measurements to the model. Keep approved factors, response definition and procedure unchanged;+ a different method or blocking condition needs a separate experiment with its earlier source kept.+7. Deliver `node tools/export.mjs delivery`: offline editable studio, complete project, original+ CSVs, collection sheets, model matrix, figures, report, PDFs and Python reproduction script.+ Open the actual delivery. Record what is measured, inferred, unresolved and ready for the next run.-## How to work so the pane moves+`LAB_DSH_DIR` points to the installed package. Setup supplies managed Node and pinned build/browser+utilities. If Node is absent from PATH, use `bash "$LAB_DSH_DIR/toolchain/node.sh" tools/build.mjs`+from the workspace. Do not send a nonprogrammer away to install a runtime manually.-1. **Save within a minute.** Materialize `bench/index.html` that renders a trivial- seeded scatter (a few points + a trendline) on canvas, so the header has a state- and the pane can show it.-2. **Build the data, then the charts.** Get the seeded generator + chart renderer- right first; only then tune axis labels, filters, and interactions.-3. **Verify like a researcher:** probe a few seeds in the pane, change a filter,- check the trendline tracks the data, re-render the same seed and confirm it is- identical.-4. **Update `.harness/verdict.json`** at every check — `ready`, one-line `summary`,- `phases`, `findings`, and a reproducibility note.+## Verification and honest status-## Rules+Run `node tools/check.mjs`: it checks source hashes, matrix identifiability and repeatable analysis.+Then exercise the actual browser controls and exported files. The kit's `reproduce.py` uses an+independent statsmodels/SciPy implementation of the delivered matrix and frozen forecasts.+Inspect PDF pages and every figure for readable labels, units, intervals and source retention.+For a new experiment with no measurements, verify and deliver the plan; do not claim results.-- A bench is only "ready" when every seed in the range you promise renders clean:- no empty chart, no overlapping garbage, no broken axis. Sample a grid of seeds.-- Tag every crafted decision USER vs AI in `bench/DESIGN.md`- (`YYYY-MM-DD | USER|AI | topic | decision | still in build?`).-- The `summary` says plainly what is reproducible now and what is not.+Builders and presence helpers keep `.harness/verdict.json` at `ready:false`. Only actual checks+justify changing it; state whether the plan, measured analysis or final delivery is ready. Record+commands, inputs, observations and limitations in `bench/DESIGN.md`, separating USER decisions,+AI assumptions and supplied evidence. Never claim a physical experiment, customer validation,+installed-agent trial or empirical finding from synthetic acceptance fixtures.-## Shipped experience and operating standard+## Method scope-The workspace starts with **Signal**, a working experience, not an empty placeholder.-Seeded synthetic experiment, adjustable effect/noise/sample size, group filters, regression, difference-of-means interval, point probe, collection replay, CSV.+Small continuous-response experiments: numeric/categorical factors, main effects, two-factor+interactions, numeric quadratics and fixed blocks. SVD checks rank and conditioning. Conventional+OLS intervals assume independent units, constant residual variance, a suitable mean model and+approximately normal errors. The intervals are pointwise, without adjustment for searching many+settings. Planned-range checks are not proof that a prediction is empirically supported there.-- Read the existing artifact before replacing it. The useful model boundaries are experiment, stats, regression, treatmentEffect, csvRows.-- Preserve working interactions and exports when extending the artifact. Match the user's brief;- the starter's genre and visual style are examples, not a ceiling.-- Expose meaningful domain controls and outputs. Every control must change real state; every- displayed metric must be computed from that state. Never invent model activity or test results.-- Use named random streams and a fixed simulation/score clock. Sample seeds, repeat the same- seed, inspect exported data, and verify keyboard/touch controls in the actual viewer.-- This HTML runs with same-origin APIs in the shared viewer. Sibling fetches, localStorage,- downloads and pointer lock are available. Keep files portable and support direct opening.-- Do not equate an existing HTML file, a successful reload, or a source-string test with a usable- result. `seed-verdict.sh` deliberately keeps `ready:false`; write `ready:true` only after your- checks establish it. Record exact commands, sampled seeds, observations and limitations.-- Never claim a test coverage percentage for browser code based on Node subprocess tests.--## Check your actual edited model--Run `node tools/check.mjs --seeds 100` in the workspace. It reads the pure model from-`<script id="harness-model">` in the artifact, checks domain invariants, repeats each seed, and-writes `.harness/model-check.json`. Preserve that script boundary when editing. Model checks are-followed by browser interaction, exported-output inspection, and visual or listening review.+The package does not implement clinical trials, repeated-measure/mixed/GLM models, arbitrary+observational causal inference, adaptive optimization, hardware acquisition or instrument control.+If the requested method exceeds this model, explain the mismatch and author an appropriate, verified+method or separate tool; do not relabel this calculation to imply unsupported capabilities.+Keep the original Signal identity and old `store/tools/experiences/lab-bench.*` implementation.+Never overwrite a person's legacy workspace to migrate it into this format.diff --git a/store/agents/lab-bench/README.md b/store/agents/lab-bench/README.mdindex a1ece0e6e..a360f1ab7 100644--- a/store/agents/lab-bench/README.md+++ b/store/agents/lab-bench/README.md@@ -1,60 +1,69 @@# Lab Bench — Signal-> Withdrawn from Store discovery on 2026-09-20: the current starter does not meet our-> standard for an open-ended tool that completes real user work. Existing projects and-> source remain available. See [the product review](../../../work/SUPERPOWERS.md).--Explore an experiment with reproducible synthetic data. Change effect, noise and sample size, probe observations, filter groups, inspect computed uncertainty, and export CSV.--## Try it+Turn a question into evidence you can act on. Describe what you want to learn; the agent builds+an experiment with an editable protocol, randomized run sheet, measurement workflow and a+reproducible analysis. Keep the original observations and the reasoning behind each decision.-> Build a synthetic catalyst experiment. Let me vary the true effect and noise, compare groups, inspect uncertainty, and export the observations.+> I want to make my cold brew more consistent. Help me compare steeping time and coffee dose,+> plan independent jars, import my measured extraction values, and choose two settings to test+> again. Keep the original data and give me a report I can share.-The starter already works before the first prompt. Change it with the agent, interact with the-result in the pane, and keep the output. Everything needed at runtime is in `bench/index.html`.-It works offline and can be opened outside Harness.+The initial coffee project is a collection plan with **no invented measurements**. It is fully+editable. Your project can use different factors, categories, blocks, units, procedures and model+terms; the agent authors these from the question and the practical constraints.## What you can do-Seeded synthetic experiment, adjustable effect/noise/sample size, group filters, regression, difference-of-means interval, point probe, collection replay, CSV.--## Build on the starter--The model functions `experiment`, `stats`, `regression`, `treatmentEffect` and `csvRows` are the starting points for substantive changes. Preserve seed-reproducibility and user controls while changing the domain behavior. A different brief can replace-this starter's entire visual language. Keep the artifact self-contained and test the actual result.--The source checkout builds these starters with `node store/tools/build-experiences.mjs`. Installed-workspaces are editable HTML; no build tool, network dependency or paid service is required.--## Verification--Model census: `node --test store/tools/experience-tests/models.test.mjs` from the source checkout.-Browser interactions, exports, same-origin APIs and manifest routing: see-[`store/tools/experience-tests`](../../tools/experience-tests/README.md).--`seed-verdict.sh` establishes only artifact presence and keeps `ready:false`. The agent must run-and record real domain and browser checks before writing a ready verdict. No cross-device pixel or-audio equality is promised. The research is inspiration; this is original code, not a wrapper of-any cited third-party engine.--## Check your actual edited model--Run `node tools/check.mjs --seeds 100` in the workspace. It reads the pure model from-`<script id="harness-model">` in the artifact, checks domain invariants, repeats each seed, and-writes `.harness/model-check.json`. Preserve that script boundary when editing. Model checks are-followed by browser interaction, exported-output inspection, and visual or listening review.+- Plan a complete factorial experiment with independent repetitions, complete blocks and scheduled+ midpoint/reference controls. Approve the protocol; collected runs then retain their settings.+- Download or print a collection sheet. Import actual CSV measurements with explicit column and+ unit mapping, or record results directly. Preserve original bytes, hashes and row references.+- Correct a transcription or exclude a known problem with a reason. Keep its original value and+ history, and compare the primary analysis with a fit using all recorded training measurements.+- Inspect raw/run-order plots, model coefficients and intervals, residuals and influential rows.+ Rank and residual-df checks stop analyses the data cannot support.+- Compare practical settings and their shared uncertainty. Append fresh confirmation runs with+ the forecast frozen beforehand, or extend the model with explicitly identified new observations.+- Keep a portable editable studio, complete source, original data, run sheets, figures, report,+ PDFs and a Python script that independently reproduces the delivered calculations.++The studio and exported HTML work offline. No account, remote model API or Python is needed to+interact with them. Setup supplies managed Node and pinned local build/browser tools. Existing+legacy projects and the original synthetic viewer remain available; they are not overwritten.++## Workspace commands++```sh+node tools/build.mjs+node tools/check.mjs+node tools/export.mjs delivery+```++In an installed workspace, `LAB_DSH_DIR` resolves package-local tools. If Node is not on PATH,+use `bash "$LAB_DSH_DIR/toolchain/node.sh"` in place of `node`. Setup and doctor handle readiness.+The browser also exports the complete kit with printable HTML; the command adds actual PDFs.++## Scope and evidence++Small continuous-response experiments, up to six factors and 512 runs: main effects, interactions,+quadratics and fixed blocks. Conventional OLS intervals rely on the declared model and independent+units. They are pointwise; searching settings does not prove an optimum. Confirmation data remain+outside the original training fit. The tool does not perform the physical experiment for you.++See [acceptance evidence](test/ACCEPTANCE.md) and the [method/source contract](skills/bench/references/project.md).+Acceptance response files are explicitly synthetic. No physical experiment, customer result or+installed-agent prompt completion is implied by a browser or numerical test.## Logo and icon-The original identity ships in `brand/`: [vector icon](brand/icon.svg),-[256px PNG](brand/icon.png), [light logo](brand/logo.svg) and-[dark logo](brand/logo-dark.svg). The same mark appears in the starter header,-its offline favicon and the desktop Store/picker/tabs. MIT, by OpenHarness contributors.+The original Signal identity remains in `brand/`: [vector icon](brand/icon.svg),+[256px PNG](brand/icon.png), [light logo](brand/logo.svg) and [dark logo](brand/logo-dark.svg).+The same mark appears in the studio, offline favicon and desktop Store/picker/tabs.## Credit and stewardship-Original implementation and visual identity by OpenHarness contributors, maintained by-Autonomous under the [MIT license](LICENSE). Report issues in the OpenHarness repository.+Original implementation and visual identity by OpenHarness contributors, maintained by Autonomous+under the [MIT license](LICENSE). Numerical libraries are bundled with their complete+[third-party notices](template/studio/THIRD_PARTY_LICENSES.txt). Report issues in the OpenHarness repository.diff --git a/store/agents/lab-bench/harness.json b/store/agents/lab-bench/harness.jsonindex fca38514a..776640c45 100644--- a/store/agents/lab-bench/harness.json+++ b/store/agents/lab-bench/harness.json@@ -4,7 +4,7 @@"name": "Lab Bench","category": "Science","author": "Autonomous",- "description": "Explore an experiment with reproducible synthetic data. Change effect, noise and sample size, probe observations, filter groups, inspect computed uncertainty, and export CSV.",+ "description": "Turn a practical question into a real experiment. Plan randomized runs, collect your measurements, inspect uncertainty and diagnostics, and design a follow-up with a reproducible report.","engine": "claude","workspace": {"template": "template",@@ -15,18 +15,21 @@"instructions": "AGENTS.md","skills": ["skills"- ]+ ],+ "env": {+ "LAB_DSH_DIR": "${dsh}"+ }},"toolchain": {"setup": "toolchain/setup.sh","doctor": "toolchain/doctor.sh"},"viewer": {- "use": "autonomous/web-viewer",+ "command": "toolchain/viewer.sh","artifactExtensions": [".html"],- "url": "http://127.0.0.1:${port}/?file=${artifact}"+ "url": "http://127.0.0.1:${port}/"},"verdict": ".harness/verdict.json"}diff --git a/store/agents/lab-bench/skills/bench/SKILL.md b/store/agents/lab-bench/skills/bench/SKILL.mdindex 328db0ba2..0065da38f 100644--- a/store/agents/lab-bench/skills/bench/SKILL.md+++ b/store/agents/lab-bench/skills/bench/SKILL.md@@ -1,77 +1,45 @@---name: bench-description: Build a deterministic, seedable data bench page in one HTML file from a plain-English description. Use whenever the user asks for an experiment log, a dataset explorer, seeded synthetic data, a trend chart, or prompt-to-bench.+description: Plan real experiments and analyze supplied continuous measurements in Lab Bench. Use for defining factors and independent runs, randomized collection sheets, measurement CSV imports, experimental uncertainty and diagnostics, comparisons and follow-up confirmation runs with a reproducible report.---# bench-Take the user's description and produce a **single self-contained `bench/index.html`**-that renders a **deterministic, seedable** experiment — seeded synthetic data with-interactive charts — loading the seed from a `?seed=` query param so the web-viewer-can preview the current seed and re-seed live.--## The floor (in order)--1. **Seeded PRNG.** A small seeded PRNG derived from the hash of the seed string.- Nothing may call a non-seeded random — the dataset must be reproducible.-2. **Data generator + chart renderer.** A seeded generator (variables, groups, a- trend with noise) driving a canvas scatter/trend renderer with real axes.-3. **`?seed=` plumbing.** Reading the param, plus a tiny UI (input + "re-seed"- button, and filter toggles) so the person can probe datasets in the pane.-4. **Named sub-streams.** One PRNG sub-stream per concern (variable, noise group,- group assignment) so tuning one doesn't reshuffle the other.--## The gold checklist--- **Trait tables that survive an edition**: seed → dataset (dimensions, group- sizes, trend strength), and a census that shows no empty/degenerate render in the- range you claim.-- **Axis discipline**: legible scales, labelled axes, a trendline that tracks the- points; filters that actually change the view.-- **Style range**: a scatter with a trendline, a grouped bar/probe, a run chart,- a distribution — matched to the brief, not all at once.-- **Export route**: expose a "live run" mode that animates points being added and a- hover/readout that shows point values.--## Verify like a researcher, not a compiler--Probe a grid of seeds — actually render them — and read the charts.-Two hard checks before "ready":-- **Re-render same-seed** — it must be identical on this machine.-- **Census the seed range you promise** (e.g. 0–99); reject any empty chart,- overlapping garbage, or broken axis.--Be explicit in the verdict about the reproducibility guarantee: same-machine yes;-animated-run frame timing you cannot prove bit-identical — say so.--## Verdict feed--Write `.harness/verdict.json` at every change:--```json-{ "spec": 1, "ready": false, "summary": "seeded scatter · trend + filters · census 0–99 clean",- "findings": [{ "severity": "info", "kind": "reproducibility", "message": "same-machine verification pending; animated-run timing not provable bit-identical" }],- "artifact": "bench/index.html",- "phases": [{ "id": "seed", "name": "Seeded core", "state": "done" },- { "id": "bench", "name": "The bench", "state": "active" },- { "id": "edition", "name": "Edition", "state": "pending" }],- "updatedAt": "2026-09-18T00:00:00Z" }-```--## Starting from Signal--The template is functional: Seeded synthetic experiment, adjustable effect/noise/sample size, group filters, regression, difference-of-means interval, point probe, collection replay, CSV.--Keep its useful controls and exports when making a user's creation. Test the behavioral core-(experiment, stats, regression, treatmentEffect, csvRows) as well as the visible result. A self-contained HTML file can still have well-separated-model, rendering, input and export functions. Do not turn a finished starter into a waiting screen.--Presence-only helpers do not prove correctness or reproducibility. Record actual evidence before-marking the result ready. Export and reopen the result as part of the handoff to the user.--## Check your actual edited model--Run `node tools/check.mjs --seeds 100` in the workspace. It reads the pure model from-`<script id="harness-model">` in the artifact, checks domain invariants, repeats each seed, and-writes `.harness/model-check.json`. Preserve that script boundary when editing. Model checks are-followed by browser interaction, exported-output inspection, and visual or listening review.+Build a usable experiment from the person's question. Read [the project contract](references/project.md)+when authoring or revising the source. Keep the procedure, independent unit, factors, levels,+response unit and intended decision explicit. Use the studio to make the work inspectable.++1. Inspect `bench/project.json` and `bench/DESIGN.md`. Preserve existing collected runs, approved+ protocol, original files and change history. A new brief is open ended; the coffee plan is only+ an example. Record necessary assumptions and choose an achievable initial run budget.+2. Generate a balanced factorial with independent repetitions and complete blocks. If adding+ controls, bracket and intersperse them. A two-level design plus shared centers cannot separately+ identify multiple quadratic effects; inspect matrix rank before collection.+3. Build with `node tools/build.mjs` and give the person a real collection sheet. Do not invent+ observations. Use blank responses for unfinished runs. Labels, units and ids must survive CSV+ round trips. A source edit must leave the browser's source-save bridge operational.+4. Import original bytes with `prepareImport` / `commitImport`, or use `recordMeasurement` with a+ reason for a direct observation or correction. Do not quietly change units, sample identity,+ settings or response values. Exclude only with a defensible recorded reason; keep the value and+ compare the sensitivity fit using every recorded training measurement.+5. Use model terms consistent with the question and design. Inspect residual structure and+ independent units, not only the fit statistic. Post-data term changes are exploratory. Explain+ numeric coding, category references, block effects and pointwise interval assumptions.+6. Compare settings within the planned ranges. A model mean interval differs from a new-observation+ prediction interval. Preserve their covariance when comparing two predictions. Do not call the+ best observed or modeled candidate a proven optimum.+7. Freeze predictions before collecting a confirmation phase. Keep its new data out of the model+ it evaluates. Append an extension explicitly when new data should instead improve the model.+ A protocol change requires a separate experiment while retaining the previous source and data.+8. Run `node tools/check.mjs`, exercise real browser inputs and export with+ `node tools/export.mjs delivery`. Reopen HTML/source/ZIP, verify raw data, independently reproduce+ calculations and visually inspect PDFs. Helpers never establish empirical validity or set ready.++Update `bench/DESIGN.md` and `.harness/verdict.json` with actual evidence and the remaining work.+A verified collection plan may be ready for collection even when no measured result exists.+Never turn an acceptance fixture or a successful build into a claim of real experimental evidence.++The browser needs no account, cloud computation or Python. Managed Node and package-local build+utilities are installed by setup; `LAB_DSH_DIR` resolves them in materialized workspaces. The+optional independent Python reader has pinned requirements in the exported kit. Retain complete+numerical-library licenses and the original Signal logo/icon in portable deliveries.diff --git a/store/agents/lab-bench/skills/bench/references/project.md b/store/agents/lab-bench/skills/bench/references/project.mdnew file mode 100644index 000000000..59e0258d0--- /dev/null+++ b/store/agents/lab-bench/skills/bench/references/project.md@@ -0,0 +1,110 @@+# Signal source and method contract++`bench/project.json` is the complete version-1 experiment. `studio/` contains portable, ordinary+ES modules; `tools/build.mjs` emits `bench/index.html`. The source JSON contains the original CSV+bytes, so a `.signal.json` file reopens independently. No executable user code is embedded in data.++## Source fields++- `id`, `title`, `question`; `response: {id,name,unit,goal,target?}`. Goal is maximize, minimize or+ target. Response values are finite continuous numbers, absolute value at most 1e12.+- `factors: [{id,name,type,unit,levels}]`: 1–6 numeric or categorical factors, 2–5 levels each.+ Numeric levels increase strictly; the low/high levels define the fixed −1/+1 model coding.+ Categories use the first level as the reference. Factor ids remain stable CSV columns.+- `protocol: {unit,randomization,analysisPlan,steps,notes}` describes independent experimental+ units and a reproducible measurement procedure. `approved` protects it before collection;+ the first actual measurement also freezes the factors, response, design and original runs.+- `design: {seed,replicates,blocks,controls}`: 1–20 independent repetitions of every factorial+ combination per block; 1–8 named complete blocks. Controls are 0 or 2–5 per block, placed at+ start/end and between treatments. Their settings are numeric midpoints / first categories.+- `model: {terms,blocks,confidence}`. Terms are factor ids, `a:b` interactions or numeric `a^2`.+ Include the main effects belonging to interactions/quadratics. An intercept is always included;+ optional fixed-block columns compare with the first block. At most 48 expanded columns.+ Confidence is .8/.9/.95/.99. No automatic variable selection or multiplicity adjustment.+- `runs: [{id,order,phase,block,kind,settings}]`: at most 512; ids and order are unique. Existing+ collected/approved rows stay unchanged. `phases` name initial, extension or confirmation work.+- `measurements: [{runId,value,origin,note,excluded}]`. `origin` retains original value and manual+ or CSV provenance; CSV references its source id and physical row. `excluded` is null or a reason.+- `sources` retain original filenames, UTF-8 bytes in base64, SHA-256, column mapping, unit and time.+ Each file is at most 1 MB; the complete project is at most 5 MB. Import is all-or-nothing.+- `audit` records before/after measurement changes, model changes, imports and design decisions.+ Never truncate it to hide an inconvenient observation. `conclusion` is the person's decision+ note. Optional `comparison:{a,b}` retains settings/block for each inspected candidate.+- Confirmation phases retain a snapshot of the original training matrix, coefficients, covariance,+ model, source hash and predictions. These are ordinary inspectable data, not a signed security log.++## Authoring and source edits++Use helpers instead of changing historical measurements in place:++```js+import {readFile, writeFile} from 'node:fs/promises';+import {generatePlan, appendPhase} from './studio/design.mjs';+import {validateProject, validateTransition, event} from './studio/project.mjs';+import {prepareImport, commitImport, recordMeasurement} from './studio/measurements.mjs';+import {fitProject, predictionSnapshot} from './studio/analysis.mjs';+const before = JSON.parse(await readFile('bench/project.json', 'utf8'));+const bytes = new Uint8Array(await readFile('observations.csv'));+const staged = await prepareImport(before, bytes, {+ name: 'observations.csv', mapping: {runId: 'run_id', response: 'response'},+ unit: before.response.unit,+});+const next = commitImport(before, staged);+validateTransition(before, next);+await writeFile('bench/project.json', JSON.stringify(next, null, 2) + '\n');+```++When redefining an uncollected, unapproved plan, record the previous plan in an audit event,+clear its `runs`/`phases`, then call `generatePlan(next)`. Do not regenerate after collection.+Manual corrections use `recordMeasurement(project, runId, {value,note,excluded,reason})`.+Model changes after collection use `event(next,'model',reason,{before:oldModel,after:newModel,+afterCollection:true})` before writing `next.model`. Preserve the entire previous audit prefix.+Always call `validateTransition` and `verifySources` before saving an edited existing project.++A follow-up uses `appendPhase(project,{points:[{settings,block}],repeats,label,reason,seed,kind,+snapshot})`. The kind is extension or confirmation. For confirmation first compute+`await predictionSnapshot(project,fitProject(project),points)`. It requires an estimable primary+model with residual uncertainty. Extensions can add informative interior points to a rank-deficient+model. New blocks or a changed response/procedure require a separate experiment.++The loopback viewer provides GET/PUT `/api/project`, optimistic `If-Match` revisions and prior+source snapshots in `.harness/history/`. A conflicting save keeps both versions. It accepts local,+same-origin writes. Direct agent edits should preserve the same history and protocol contracts.++## Numerical details and limits++Numeric factors use `(value-midpoint)/halfRange`; categories and fixed blocks use reference+indicators. Interaction columns are products of the corresponding basis columns. Quadratic+columns square the coded numeric term. SVD identifies rank with relative singular cutoff 1e-12;+fits with insufficient residual df or condition number above 1e9 are stopped. Values above 1e6+produce a conditioning warning. Conventional covariance is MSE × X-pseudoinverse × its transpose.++Intervals use Student-t quantiles with n−p df. Mean SE is `sqrt(x cov x')`; one-observation SE+adds residual MSE. A comparison uses the contrast vector `xB−xA`, retaining covariance. Near-zero+residual variation withholds intervals. Residuals, internal studentization, leverage, Cook's+influence and leave-one-out RMSE are exported; review thresholds never remove data automatically.++These assume independent experimental units, a suitable linear mean model, constant residual+variance and approximately normal errors. The model does not establish causal validity by itself.+The package does not implement fractional designs, random/mixed effects, repeated-measure models,+GLMs, sequential testing, clinical protocols, arbitrary optimization or hardware control.++Raw missing responses stay pending. CSV uses UTF-8 (BOM accepted), commas and RFC-style quoting.+Headers must be unique; map distinct id/response columns and confirm the response unit. Known+factor/block/unit columns are checked against the run sheet. Unknown or duplicate run ids, existing+measurements, nonfinite values and mismatched settings are rejected together. No implicit conversion.++## Reproduction and delivery++`node tools/check.mjs` writes `.harness/lab-check.json`; it leaves readiness unchanged.+`node tools/export.mjs delivery` produces source/HTML/CSV/SVG/report and collection PDFs/ZIP.+Browser export includes HTML versions that can be printed, without requiring a local PDF service.+`reproduce.py` with `requirements.txt` independently repeats the actual delivered matrix and frozen+forecasts. It writes `reproduction.json`. Python is only needed for this independent check.++Methods: [NIST factorial designs](https://www.itl.nist.gov/div898/handbook/pri/section3/pri3331.htm),+[control scheduling](https://www.itl.nist.gov/div898/handbook/pri/section3/pri337.htm),+[model assessment](https://www.itl.nist.gov/div898/handbook/pri/section4/pri43.htm),+[confirmation](https://www.itl.nist.gov/div898/handbook/pri/section4/pri46.htm).+Use pinned ml-matrix 6.15.0 and jstat 1.9.6 with complete bundled notices. Acceptance uses independently+constructed matrices and statsmodels 0.14.6 / SciPy 1.13.1. Numerical agreement is not a physical experiment.diff --git a/store/agents/lab-bench/store.json b/store/agents/lab-bench/store.jsonindex a121e1702..58079bb12 100644--- a/store/agents/lab-bench/store.json+++ b/store/agents/lab-bench/store.json@@ -1,16 +1,28 @@{- "listed": false,+ "listed": true,"homepage": "https://github.com/autonomous-ai/openharness/tree/main/store/agents/lab-bench","license": "MIT",- "tagline": "Explore an experiment with reproducible synthetic data",+ "tagline": "Turn a question into evidence you can act on","screenshots": [- "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/lab-bench/starter.jpg"+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/lab-bench/starter.jpg",+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/lab-bench/canopy.jpg",+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/lab-bench/fold.jpg"],"examples": [{- "prompt": "Build a synthetic catalyst experiment. Let me vary the true effect and noise, compare groups, inspect uncertainty, and export the observations.",- "caption": "Signal · interactive offline starter",+ "prompt": "Help me make my cold brew more consistent. Plan independent jars at different steeping times and coffee doses, import my measured extraction values, and compare two settings with fresh confirmation runs. Keep the original data and give me a reproducible report.",+ "caption": "Clearwater Coffee \u00b7 confirmation workflow shown with explicitly synthetic acceptance data","image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/lab-bench/starter.jpg"+ },+ {+ "prompt": "I have seedlings on two shelves. Design a fair comparison of three growing media and two water allocations, keeping each pot independent. Let me import the height gains, account for shelf differences and investigate a recorded instrument problem without losing its data.",+ "caption": "Canopy Seedlings \u00b7 categories, fixed blocks and sensitivity analysis; synthetic acceptance data",+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/lab-bench/canopy.jpg"+ },+ {+ "prompt": "Help our paper workshop test crease width and flap overlap. Give us a randomized collection sheet, analyze our measured peak loads, and add new interior settings to investigate curvature while preserving the original tests. Export the source, figures and report.",+ "caption": "Fold Paperworks \u00b7 curved response model and new measurements; synthetic acceptance data",+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/lab-bench/fold.jpg"}]}diff --git a/store/agents/lab-bench/template/bench/index.html b/store/agents/lab-bench/template/bench/index.htmlindex 4fa393d60..b09d89ce1 100644--- a/store/agents/lab-bench/template/bench/index.html+++ b/store/agents/lab-bench/template/bench/index.html@@ -1,1041 +1,82 @@<!doctype html>-<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">-<meta name="color-scheme" content="dark light"><title>SIGNAL — Lab Bench</title>-<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22256%22%20height%3D%22256%22%20viewBox%3D%220%200%2096%2096%22%3E%0A%20%20%3Ctitle%3ELab%20Bench%20%E2%80%94%20signal%20in%20a%20flask%3C%2Ftitle%3E%0A%20%20%3Crect%20x%3D%224%22%20y%3D%224%22%20width%3D%2288%22%20height%3D%2288%22%20rx%3D%2223%22%20fill%3D%22%23143740%22%2F%3E%0A%20%20%3Cpath%20d%3D%22M36%2020h24M40%2021v22L24%2069q-4%207%205%207h38q9%200%205-7L56%2043V21%22%20fill%3D%22none%22%20stroke%3D%22%23f2ca7d%22%20stroke-width%3D%225%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m32%2063%208-7%208%208%209-15%208%2014%22%20fill%3D%22none%22%20stroke%3D%22%2389c7bd%22%20stroke-width%3D%225%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%2F%3E%0A%20%20%3Ccircle%20cx%3D%2270%22%20cy%3D%2230%22%20r%3D%225%22%20fill%3D%22%2389c7bd%22%2F%3E%0A%3C%2Fsvg%3E">-<!-- Built by store/tools/build-experiences.mjs. Edit this file freely in your workspace. -->-<style>:root {- color-scheme: dark;- --bg: #111414;- --panel: #191e1c;- --line: #ffffff1c;- --ink: #f4f2e9;- --muted: #a1aaa4;- --accent: #d0f28a;- font:- 14px/1.5 -apple-system,- BlinkMacSystemFont,- "Segoe UI",- sans-serif;-}-* {- box-sizing: border-box;-}-body {- margin: 0;- background: var(--bg);- color: var(--ink);-}-button,-input,-select {- font: inherit;-}-button,-a,-input,-select {- -webkit-tap-highlight-color: transparent;-}-button,-a {- touch-action: manipulation;-}-button {- cursor: pointer;-}-button:disabled {- opacity: 0.45;- cursor: wait;-}-button:focus-visible,-input:focus-visible,-select:focus-visible,-a:focus-visible {- outline: 2px solid var(--accent);- outline-offset: 4px;-}-button,-input,-select {- color: inherit;- background: transparent;- border: 1px solid var(--line);- border-radius: 5px;- padding: 9px 13px;-}-button:hover {- background: #ffffff0c;- border-color: var(--muted);-}-button.primary {- background: var(--accent);- color: #142015;- border-color: transparent;- font-weight: 650;-}-button[aria-pressed="true"] {- border-color: var(--accent);- color: var(--accent);-}-input[type="range"] {- accent-color: var(--accent);- padding: 0;- min-width: 0;-}-input[type="number"] {- width: 80px;-}-select {- background: var(--panel);-}-label {- cursor: pointer;-}-a {- color: inherit;-}-h1,-h2,-h3,-p {- margin: 0;-}-h1 {- font-size: clamp(32px, 5vw, 64px);- line-height: 1.02;- letter-spacing: -0.055em;- font-weight: 550;-}-h2 {- font-weight: 550;- letter-spacing: -0.03em;-}-h3 {- font-size: 14px;- font-weight: 550;-}-.mono,-.eyebrow {- font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;-}-.eyebrow {- font-size: 10px;- letter-spacing: 0.16em;- text-transform: uppercase;- color: var(--muted);-}-.muted {- color: var(--muted);-}-.small {- font-size: 12px;-}-.masthead {- display: flex;- align-items: center;- justify-content: space-between;- gap: 20px;- padding: 19px 28px;- border-bottom: 1px solid var(--line);-}-.identity {- display: flex;- gap: 12px;- align-items: center;- white-space: nowrap;- font-size: 12px;- font-weight: 600;- letter-spacing: 0.04em;-}-.mark {- width: 28px;- height: 28px;- flex: 0 0 28px;- display: grid;- place-items: center;-}-.mark svg {- display: block;- width: 100%;- height: 100%;-}-.seed-form {- display: flex;- align-items: center;- gap: 6px;-}-.seed-form label {- font:- 10px ui-monospace,- monospace;- text-transform: uppercase;- letter-spacing: 0.12em;- color: var(--muted);- margin-right: 4px;-}-.seed-form input {- width: 74px;- padding: 6px 8px;- font:- 12px ui-monospace,- monospace;-}-.seed-form button {- padding: 6px 10px;- font-size: 12px;-}-.intro {- padding: 32px 28px;- display: flex;- align-items: flex-end;- justify-content: space-between;- gap: 20px;-}-.intro p {- max-width: 440px;- color: var(--muted);- margin-top: 14px;-}-.intro .eyebrow {- margin-bottom: 12px;-}-.actions {- display: flex;- align-items: center;- gap: 8px;- flex-wrap: wrap;-}-.workspace {- display: grid;- grid-template-columns: minmax(0, 1fr) 270px;- gap: 22px;- padding: 0 28px 28px;-}-.panel {- background: var(--panel);- border: 1px solid var(--line);- border-radius: 8px;- overflow: hidden;-}-.panel-head {- display: flex;- align-items: center;- justify-content: space-between;- padding: 16px 20px;- border-bottom: 1px solid var(--line);- gap: 10px;-}-.side {- display: flex;- flex-direction: column;- gap: 20px;-}-.section {- border-top: 1px solid var(--line);- padding-top: 18px;-}-.section h3 {- margin-bottom: 15px;-}-.field {- display: grid;- gap: 7px;- margin: 14px 0;-}-.field > span {- display: flex;- justify-content: space-between;- font-size: 12px;- color: var(--muted);-}-.metrics {- display: grid;- grid-template-columns: repeat(3, 1fr);- gap: 1px;- background: var(--line);- border: 1px solid var(--line);- border-radius: 6px;- overflow: hidden;-}-.metric {- background: var(--bg);- padding: 13px 15px;-}-.metric strong {- display: block;- font:- 24px ui-monospace,- monospace;- letter-spacing: -0.06em;-}-.metric span {- font-size: 10px;- color: var(--muted);- text-transform: uppercase;- letter-spacing: 0.09em;-}-canvas {- display: block;- max-width: 100%;-}-.status-line {- display: flex;- justify-content: space-between;- gap: 20px;- padding: 14px 28px;- border-top: 1px solid var(--line);- font:- 10px ui-monospace,- monospace;- color: var(--muted);-}-.dot {- width: 6px;- height: 6px;- display: inline-block;- background: var(--accent);- border-radius: 50%;- margin-right: 6px;-}-.toast {- position: fixed;- z-index: 99;- left: 50%;- bottom: 22px;- transform: translateX(-50%);- max-width: 90vw;- background: var(--ink);- color: var(--bg);- padding: 11px 18px;- border-radius: 6px;- box-shadow: 0 3px 30px #0004;- font-size: 12px;-}-.toast:empty {- display: none;-}-[hidden] {- display: none !important;-}-.sr-only {- position: absolute;- width: 1px;- height: 1px;- padding: 0;- margin: -1px;- overflow: hidden;- clip-path: inset(50%);- white-space: nowrap;- border: 0;-}-@media (max-width: 800px) {- .workspace {- grid-template-columns: 1fr;- }- .side {- display: grid;- grid-template-columns: repeat(2, minmax(0, 1fr));- }- .intro {- align-items: flex-start;- flex-direction: column;- }- .intro h1 {- font-size: 44px;- }-}-@media (max-width: 480px) {- .masthead {- padding: 13px 16px;- gap: 8px;- flex-wrap: wrap;- }- .intro {- padding: 26px 16px;- }- .intro h1 {- font-size: 38px;- }- .workspace {- padding: 0 16px 20px;- gap: 18px;- }- .side {- grid-template-columns: 1fr;- }- .seed-form label {- display: none;- }- .status-line {- padding: 12px 16px;- }- .status-line span:last-child {- display: none;- }- .metrics .metric {- padding: 12px 10px;- }- .panel-head {- padding: 12px;- }- .actions {- gap: 6px;- }-}-@media (prefers-reduced-motion: reduce) {- *,- *::before,- *::after {- scroll-behavior: auto !important;- animation: none !important;- transition: none !important;- }-}+<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><title>Signal — Lab Bench</title><link rel="icon" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22256%22%20height%3D%22256%22%20viewBox%3D%220%200%2096%2096%22%3E%0A%20%20%3Ctitle%3ELab%20Bench%20%E2%80%94%20signal%20in%20a%20flask%3C%2Ftitle%3E%0A%20%20%3Crect%20x%3D%224%22%20y%3D%224%22%20width%3D%2288%22%20height%3D%2288%22%20rx%3D%2223%22%20fill%3D%22%23143740%22%2F%3E%0A%20%20%3Cpath%20d%3D%22M36%2020h24M40%2021v22L24%2069q-4%207%205%207h38q9%200%205-7L56%2043V21%22%20fill%3D%22none%22%20stroke%3D%22%23f2ca7d%22%20stroke-width%3D%225%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m32%2063%208-7%208%208%209-15%208%2014%22%20fill%3D%22none%22%20stroke%3D%22%2389c7bd%22%20stroke-width%3D%225%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%2F%3E%0A%20%20%3Ccircle%20cx%3D%2270%22%20cy%3D%2230%22%20r%3D%225%22%20fill%3D%22%2389c7bd%22%2F%3E%0A%3C%2Fsvg%3E%0A"><style>[hidden]{display:none!important}*{box-sizing:border-box}body{margin:0;background:#eef1e9;color:#183f3b;font-family:Inter,ui-sans-serif,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;font-size:14px;line-height:1.5}button,input,select,textarea{font:inherit;color:inherit}button{cursor:pointer;border:1px solid #ccd8ce;background:#fffefa;padding:10px 15px;border-radius:7px;font-weight:600;line-height:1.35}button:hover{background:#e5eee3}button:disabled{opacity:.48;cursor:default}button.primary{background:#0b736d;border-color:#0b736d;color:white}button.primary:hover{background:#075d59}.quiet{background:none}.danger{color:#a64431}button:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible{outline:3px solid #dc9b38;outline-offset:3px}input,textarea,select{display:block;width:100%;background:#fffefa;border:1px solid #c8d4c9;border-radius:6px;padding:9px 11px;min-height:40px}textarea{resize:vertical;line-height:1.5}input[type=checkbox]{display:inline-block;min-height:0;width:17px;height:17px;vertical-align:middle;accent-color:#0b736d}input[type=range]{padding:0;accent-color:#0b736d}label{display:block;font-size:12px;font-weight:650;letter-spacing:.1px}label input,label select,label textarea{margin-top:5px;font-size:14px;font-weight:400}label:has(input[type=checkbox]){display:flex;align-items:center;gap:9px;font-size:14px;letter-spacing:0}.topbar{display:flex;align-items:center;gap:24px;min-height:88px;padding:18px 30px;background:#fbfcf6;border-bottom:1px solid #cedbd0;position:relative;z-index:2}.brand{display:flex;align-items:center;gap:12px;font-size:21px;font-weight:800;letter-spacing:3px}.brand small{display:block;font-size:8px;letter-spacing:3.4px;font-weight:600}.mark{width:40px;height:40px;display:flex}.mark svg{width:100%;height:100%}.connection{font-size:11px;color:#557569;margin-left:auto;max-width:225px}.header-actions{display:flex;gap:8px}.header-actions button{font-size:12px;padding:10px 12px}.workspace{display:grid;grid-template-columns:236px minmax(0,1fr);max-width:1720px;margin:auto;min-height:calc(100vh - 88px)}.sidebar{padding:31px 24px;border-right:1px solid #cfdbcf;display:flex;flex-direction:column;align-items:stretch;gap:20px;background:#e5eadf}.sidebar h2{font-size:19px;font-weight:650;line-height:1.3;margin:-8px 0 12px;overflow-wrap:anywhere}.eyebrow{text-transform:uppercase;font-size:10px;letter-spacing:1.6px;font-weight:700;color:#578073}.sidebar nav{display:flex;flex-direction:column;gap:5px;margin:0 -10px}.sidebar nav button{display:flex;gap:13px;text-align:left;border-color:transparent;background:none;font-size:13px;padding:14px 12px}.sidebar nav button b{font-size:10px;font-weight:500;line-height:20px;opacity:.65}.sidebar nav button.active{background:#143f39;color:#fafbf4}.side-foot{margin-top:auto;font-family:Georgia,serif;font-size:17px;line-height:1.5;padding-top:35px;color:#6b8171}.sidebar>button{font-size:11px;background:none}.side-count{display:flex;align-items:baseline;gap:6px;margin:20px 0 8px}.side-count strong{font-size:34px;font-weight:550}.progress{height:5px;border-radius:4px;background:#cbd8c9;overflow:hidden}.progress span{display:block;height:100%;background:#0b736d}.small,.muted{color:#678174;font-size:12px}.side-note{font-size:11px;margin-top:12px;line-height:1.7}main{min-width:0;padding:34px 38px 70px}.hero{display:flex;align-items:flex-start;gap:30px;justify-content:space-between;margin-bottom:25px}.hero h1{font-family:Georgia,"Times New Roman",serif;font-size:42px;line-height:1.09;font-weight:400;letter-spacing:-1.4px;margin:9px 0 13px;max-width:850px}.hero p{color:#607e70;margin:0;max-width:720px;font-size:14px}.stage-number{font-size:72px;line-height:1;font-family:Georgia,serif;color:#bdccba;margin-top:13px}.metrics{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin-bottom:24px}.metric{border:1px solid #d3dece;border-radius:8px;padding:16px 18px;background:#f6f8f0}.metric strong{display:block;font-size:31px;line-height:1.2;font-weight:550;letter-spacing:-1px}.metric span{display:block;color:#627c6b;font-size:11px;margin-top:6px}.metric.accent{background:#d5e0bd;border-color:#c9d6b0}.card{background:#fbfcf6;border:1px solid #d2ddcd;border-radius:10px;padding:23px;margin-bottom:18px;min-width:0}.card h2{font-size:18px;letter-spacing:-.4px;margin:0 0 15px;font-weight:650}.card h3{font-size:14px;margin:0 0 12px}.section-head{display:flex;align-items:center;justify-content:space-between;gap:15px;margin-bottom:12px}.section-head h2{margin:0}.actions{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.two-col{display:grid;grid-template-columns:minmax(0,1.35fr) minmax(270px,1fr);gap:20px}.form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:15px}.span-all{grid-column:1/-1}.factor-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}.factor{padding:17px;background:#eff3e9;border:1px solid #d5dfce;border-radius:8px}.factor .form-grid{gap:10px}.factor-head{display:flex;justify-content:space-between;align-items:center;margin-bottom:10px}.factor-head strong{font-size:11px;letter-spacing:1px;color:#72916d}.factor-head button{padding:3px 7px;font-size:11px;border:0;background:none}.helper{color:#667e70;font-size:12px;margin:8px 0 0}.strip{border:1px solid #d4dfcd;background:#eaf0df;border-radius:8px;padding:15px 18px;margin:15px 0;line-height:1.55;font-size:13px}.strip.warn{background:#f7ebd6;border-color:#e7d2a9;color:#745927}.strip strong{display:block;margin-bottom:3px}.pill{display:inline-block;font-size:10px;padding:3px 8px;border-radius:20px;background:#e4edda;color:#56704c;white-space:nowrap}.pill.warn{background:#f2dfb9;color:#795923}.pill.dark{background:#1b534a;color:white}.table-scroll{max-width:100%;overflow:auto}.table-scroll table{min-width:650px}table{width:100%;border-collapse:collapse;font-size:12px}th{text-align:left;font-size:10px;text-transform:uppercase;letter-spacing:.6px;color:#6a826f;padding:11px 12px;background:#edf2e6;border-bottom:1px solid #c8d6c4;white-space:nowrap}td{padding:12px;border-bottom:1px solid #e0e7d9;vertical-align:top}td strong{font-weight:600}tr[data-run]{cursor:pointer}tr[data-run]:hover{background:#edf3e5}td button{font-size:11px;padding:5px 9px;white-space:nowrap}.state-measured{color:#0b736d}.state-pending{color:#8b9780}.state-excluded{color:#a66639}.chart svg{width:100%;height:auto;max-height:440px;display:block}.legend{display:flex;gap:13px;flex-wrap:wrap;margin-top:9px;font-size:10px;color:#557565}.dot{display:inline-block;height:8px;width:8px;border-radius:50%;margin-right:5px}.empty{padding:55px 25px;text-align:center;background:linear-gradient(125deg,#edf2e6,#f8f8ed);border:1px dashed #bccfb4;border-radius:10px}.empty h2{font-family:Georgia,serif;font-size:28px;font-weight:400;margin:0 0 12px}.empty p{max-width:540px;margin:0 auto 22px;color:#658170}.terms{display:grid;gap:9px;margin-bottom:20px}.tabs{display:flex;gap:5px;padding:4px;background:#e8eee0;border-radius:7px}.tabs button{background:none;border:0;font-size:11px;padding:7px 11px}.tabs button.selected{background:#fffefa;box-shadow:0 1px 4px #173b3520}.prediction{background:#173f3a;border-radius:10px;color:#f5f9e9;padding:23px}.prediction .eyebrow{color:#adc5a4}.prediction .value{font-size:45px;letter-spacing:-1.5px;margin:6px 0}.prediction small{color:#abc5ae}.comparison{background:#dce7c3;padding:21px;border-radius:9px;margin-top:16px}.comparison strong{font-size:28px;font-weight:500}.candidate-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:15px}.candidate-title{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px}.candidate-title h3{margin:0}.setting{margin-bottom:15px}.setting .setting-fields{display:flex;gap:12px;align-items:center}.setting input[type=number]{max-width:100px}.ranked td:nth-child(2){font-variant-numeric:tabular-nums;white-space:nowrap}details>summary{cursor:pointer;font-weight:600;font-size:13px;color:#497264;padding:7px 0}details[open]>summary{margin-bottom:12px}dialog{width:min(720px,calc(100vw - 30px));max-height:90vh;overflow:auto;border:1px solid #bfd1bc;padding:28px;border-radius:12px;background:#fcfcf6;color:#183f3b;box-shadow:0 25px 90px #12392e40}dialog::backdrop{background:#14383177;backdrop-filter:blur(3px)}dialog h2{font-family:Georgia,serif;font-weight:400;font-size:29px;margin:0 0 13px}dialog .actions{justify-content:flex-end;margin-top:24px}#toast{position:fixed;right:25px;bottom:24px;max-width:min(650px,calc(100vw - 30px));background:#173f3a;color:#fffefa;padding:15px 20px;border-radius:9px;box-shadow:0 7px 30px #12392e30;font-size:13px;z-index:10}#toast.error{background:#854733}#conflict{padding:16px 30px;background:#f4dfb5;border-bottom:1px solid #d8bb7f;font-size:13px}#conflict .actions{display:inline-flex;margin-left:20px}#conflict button{font-size:11px}.check-row{padding:11px 0;border-bottom:1px solid #dfe6d8;display:flex;justify-content:space-between;gap:18px;font-size:12px}.check-row>span:last-child{text-align:right}.audit-row{padding:12px 0;border-bottom:1px solid #dfe6d8}.audit-row small{color:#789078;display:block;margin-top:4px}.wrap{overflow-wrap:anywhere}.measure-value{font-size:35px;font-variant-numeric:tabular-nums}.plot-tip{font-size:12px;min-height:21px;color:#496f61;margin-top:8px}.report-actions{margin-top:22px}.visually-hidden{position:absolute;width:1px;height:1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}+@media(min-width:1450px){main{padding:40px 52px}.hero h1{font-size:48px}.sidebar{padding:37px 25px}}@media(max-width:1100px){.topbar{padding:15px 20px;gap:15px}.connection{display:none}.header-actions{margin-left:auto}.workspace{grid-template-columns:190px minmax(0,1fr)}.sidebar{padding:25px 16px}main{padding:27px 24px}.two-col{grid-template-columns:1fr}.hero h1{font-size:36px}.stage-number{font-size:60px}}@media(max-width:760px){.topbar{flex-wrap:wrap;padding:15px;gap:12px}.brand{font-size:17px}.brand .mark{width:30px;height:30px}.header-actions{width:100%;display:grid;grid-template-columns:1fr 1fr 1.1fr}.header-actions button{font-size:10px;padding:9px 5px}.workspace{display:block}.sidebar{border-right:0;border-bottom:1px solid #cfdbcf;padding:12px 15px;display:block}.sidebar>.eyebrow,.sidebar>h2,#side-status,.side-foot,.sidebar>button{display:none}.sidebar nav{margin:0;flex-direction:row;gap:4px;justify-content:space-between}.sidebar nav button{font-size:10px;padding:9px 6px;gap:5px;flex:1}.sidebar nav button b{display:none}main{padding:25px 16px 65px}.hero{gap:10px}.hero h1{font-size:32px}.hero p{font-size:12px}.stage-number{font-size:42px}.metrics{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.metric{padding:13px}.metric strong{font-size:26px}.card{padding:17px}.form-grid,.factor-grid,.candidate-grid{grid-template-columns:1fr}.span-all{grid-column:auto}.chart svg{min-height:180px}.section-head{align-items:flex-start;flex-direction:column}.two-col{gap:0}.tabs{flex-wrap:wrap}.candidate-title{margin-top:7px}#conflict{padding:14px}#conflict .actions{margin:10px 0 0}.prediction .value{font-size:37px}}-:root {- --bg: #111b20;- --panel: #17242b;- --ink: #e9efe9;- --muted: #98abb1;- --line: #8ea4aa30;- --accent: #efc273;-}-.intro h1 {- font-weight: 450;-}-.workspace {- grid-template-columns: minmax(0, 1fr) 240px;- gap: 28px;-}-.chart-panel {- margin-top: 18px;-}-.chart-panel canvas {- width: 100%;- height: 390px;-}-.filter {- font-size: 11px;- padding: 4px 8px;-}-.key {- width: 7px;- height: 7px;- border-radius: 50%;- display: inline-block;- margin-right: 5px;-}-.control-key {- background: #73b3b5;-}-.treatment-key {- background: #efc273;-}-.probe {- padding: 10px 18px;- font-size: 10px;- min-height: 38px;- color: var(--muted);- border-top: 1px solid var(--line);-}-.inference {- display: grid;- grid-template-columns: 1.3fr 1fr;- gap: 20px;- padding: 24px 0;-}-.inference h2 {- font-size: 22px;- margin: 7px 0;-}-.inference canvas {- width: 100%;- height: 115px;-}-.formula {- padding: 15px 12px;- background: #0b151b;- font:- 11px/1.9 ui-monospace,- monospace;- border-left: 2px solid var(--accent);- color: var(--accent);-}-details {- border-top: 1px solid var(--line);- padding: 16px 0;-}-summary {- font-size: 12px;- cursor: pointer;-}-.table-scroll {- overflow: auto;-}-table {- width: 100%;- border-collapse: collapse;- font:- 11px ui-monospace,- monospace;- margin-top: 14px;- text-align: left;-}-td,-th {- padding: 9px 10px;- border-bottom: 1px solid var(--line);-}-th {- color: var(--muted);- font-weight: 400;-}-@media (max-width: 800px) {- .workspace {- grid-template-columns: 1fr;- }-}-@media (max-width: 480px) {- .chart-panel canvas {- height: 300px;- }- .panel-head {- flex-wrap: wrap;- }- .inference {- grid-template-columns: 1fr;- gap: 3px;- }- .metric strong {- font-size: 21px;- }-}-</style></head><body>-<header class="masthead"><div class="identity"><span class="mark" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96">+#plan-form label:has([name="question"]),#plan-form label:has([name="steps"]),#plan-form label:has([name="controls"]){grid-column:1/-1}.factor .form-grid{grid-template-columns:1fr}#plan-form label:has([name="blocks"]){grid-column:1/-1}+.two-col>*,.candidate-grid>*,.form-grid>*{min-width:0}input,textarea,select{max-width:100%;min-width:0}@media(max-width:1100px){.two-col{grid-template-columns:minmax(0,1fr)}}+</style></head>+<body><header class="topbar"><div class="brand"><span class="mark" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96"><title>Lab Bench — signal in a flask</title><rect x="4" y="4" width="88" height="88" rx="23" fill="#143740"/><path d="M36 20h24M40 21v22L24 69q-4 7 5 7h38q9 0 5-7L56 43V21" fill="none" stroke="#f2ca7d" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/><path d="m32 63 8-7 8 8 9-15 8 14" fill="none" stroke="#89c7bd" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/><circle cx="70" cy="30" r="5" fill="#89c7bd"/>-</svg></span>SIGNAL / LAB</div>-<form class="seed-form" id="seed-form"><label for="seed">Seed</label><input id="seed" aria-label="Seed" maxlength="128" autocomplete="off" spellcheck="false"><button type="submit">Apply</button><button id="next-seed" type="button" title="Next seed">↗ Next</button></form></header>-<section class="intro">- <div>- <p class="eyebrow">Experiment 024 / Synthetic materials lab</p>- <h1>Find the signal.</h1>- <p>- Does a catalyst improve yield? Change the experiment, inspect each- observation, and see what the data supports.- </p>- </div>- <button id="export-csv" class="primary">Export observations ↗</button>-</section>-<main class="workspace">- <div>- <div class="metrics">- <div class="metric">- <strong id="sample-count"></strong><span>Visible samples</span>- </div>- <div class="metric">- <strong id="effect-estimate"></strong><span>Observed uplift · pp</span>- </div>- <div class="metric">- <strong id="r-squared"></strong><span>Visible fit · R²</span>- </div>- </div>- <section class="panel chart-panel">- <div class="panel-head">- <span class="small">Temperature × reaction yield</span>- <div class="actions">- <button class="filter" id="control" aria-pressed="true">- <i class="key control-key"></i>Control</button- ><button class="filter" id="treatment" aria-pressed="true">- <i class="key treatment-key"></i>Catalyst- </button>- </div>- </div>- <canvas- id="chart"- tabindex="0"- role="img"- aria-label="Scatter plot of temperature against yield. Exact observations are available in the table below."- ></canvas>- <p id="probe" class="probe mono" role="status">- Hover a point to inspect an observation.- </p>- </section>- <section class="inference">- <div>- <p class="eyebrow">What the experiment says</p>- <h2 id="conclusion"></h2>- <p class="small muted" id="interval"></p>- </div>- <canvas- id="interval-chart"- aria-label="Confidence interval for the observed treatment difference"- ></canvas>- </section>- <details>- <summary>- Inspect observations <span class="muted">/ first 12 visible rows</span>- </summary>- <div class="table-scroll">- <table>- <thead>- <tr>- <th>Sample</th>- <th>Group</th>- <th>Temp · °C</th>- <th>Yield · %</th>- </tr>- </thead>- <tbody id="observations"></tbody>- </table>- </div>- </details>- </div>- <aside class="side">- <div>- <p class="eyebrow">Design the experiment</p>- <label class="field"- ><span>True catalyst effect <output id="effect-value"></output></span- ><input id="effect" type="range" min="-20" max="30" value="12" /></label- ><label class="field"- ><span>Measurement noise <output id="noise-value"></output></span- ><input id="noise" type="range" min="1" max="20" value="9" /></label- ><label class="field"- ><span>Sample size <output id="count-value"></output></span- ><input- id="count"- type="range"- min="48"- max="240"- step="12"- value="120" /></label- ><button id="run" style="width: 100%">Replay collection</button>- </div>- <div class="section">- <h3>A model you can inspect</h3>- <p class="formula">- yield = 28 + 0.48 × temperature<br />+ catalyst effect + noise- </p>- <p class="small muted" style="margin-top: 12px">- Balanced groups, seeded temperatures, independent Gaussian measurement- noise. The observed difference can depart from the true effect.- </p>- </div>- <div class="section small muted">- <strong>Synthetic data, by design.</strong>- <p style="margin-top: 8px">- The 95% interval uses a normal approximation for the unadjusted- difference of means. It illustrates uncertainty; it is not a real- experimental finding.- </p>- </div>- </aside>-</main>-<footer class="status-line">- <span><i class="dot"></i>REPRODUCIBLE OBSERVATIONS</span- ><span>SEED / PROBE / QUESTION / REPEAT</span>-</footer>-<div class="toast" id="toast" role="status"></div>-<script id="harness-model">-'use strict';-// Shared deterministic primitives. Domain models use named streams so unrelated edits stay stable.-function hash(value) {- let h = 2166136261;- for (const c of String(value)) h = Math.imul(h ^ c.charCodeAt(0), 16777619);- return h >>> 0;-}-function random(seed, stream = "main") {- let a = hash(`${seed}:${stream}`);- return () => {- a = (a + 0x6d2b79f5) | 0;- let t = Math.imul(a ^ (a >>> 15), 1 | a);- t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;- };-}-const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));-const lerp = (a, b, t) => a + (b - a) * t;-const pick = (items, rng) => items[Math.floor(rng() * items.length)];-function normal(rng) {- return (- Math.sqrt(-2 * Math.log(Math.max(1e-9, rng()))) *- Math.cos(2 * Math.PI * rng())- );-}+</svg>+</span><span>SIGNAL<small>LAB BENCH</small></span></div><div id="connection" class="connection">Opening experiment…</div><div class="header-actions"><button data-action="open">Open project</button><button data-action="save" id="save-source">Save to workspace</button><button class="primary" data-action="export">Export experiment ↗</button></div></header>+<div id="conflict" hidden></div><div class="workspace"><aside class="sidebar"><div class="eyebrow">Your experiment</div><h2 id="side-title"></h2><nav aria-label="Experiment workflow"><button data-tab="plan"><b>01</b> Plan the test</button><button data-tab="collect"><b>02</b> Collect evidence</button><button data-tab="analyze"><b>03</b> Understand</button><button data-tab="followup"><b>04</b> Next experiment</button></nav><div id="side-status"></div><div class="side-foot">A question. A fair test.<br>A decision you can explain.</div><button data-action="download-project">Download editable project</button></aside><main id="main"></main></div>+<div id="toast" role="status" aria-live="polite" hidden></div><dialog id="dialog"><div id="dialog-content"></div></dialog><input id="project-file" type="file" accept=".json,.signal.json,application/json" hidden><input id="csv-file" type="file" accept=".csv,text/csv" hidden>+<script id="signal-data" type="application/json">{"project":{"spec":1,"id":"clearwater","title":"Clearwater Coffee","question":"Which steeping time and coffee dose bring extraction closest to our target, with a repeatable process?","response":{"id":"extraction","name":"Extraction yield","unit":"%","goal":"target","target":19},"factors":[{"id":"steep","name":"Steeping time","type":"number","unit":"h","levels":[8,16]},{"id":"dose","name":"Coffee dose","type":"number","unit":"g/L","levels":[60,90]}],"protocol":{"unit":"One separately prepared brewing jar. Repeated readings from the same jar are not independent runs.","randomization":"Prepare separate jars in the randomized order within the water batch. Keep the scheduled midpoint controls at the beginning, middle and end.","analysisPlan":"Use the planned time, dose and interaction terms. Examine residuals and repeatability. Compare two chosen settings, then collect fresh independent confirmation jars.","steps":["Label every jar with its run id before preparation. Keep the coffee lot, water batch, grind and filtering procedure consistent.","Set the planned coffee dose and steeping duration for that jar. Record any preparation departure in its note.","Use the same calibrated measurement procedure for each jar. Record extraction yield in percent; keep raw instrument observations separately.","Enter one final response per independently prepared jar. Review the residual and run-order plots before selecting the next comparison."],"notes":"Example protocol. Adapt the procedure to your actual equipment before approving it. Supply measured responses from your own independent runs."},"approved":false,"design":{"seed":"clearwater-01","replicates":3,"blocks":["Water batch A"],"controls":3},"model":{"terms":["steep","dose","steep:dose"],"blocks":false,"confidence":0.95},"phases":[{"id":"initial","label":"Initial experiment","kind":"plan","reason":"Full factorial, independent repetitions and complete blocks.","seed":"clearwater-01"}],"runs":[{"id":"r0001","order":1,"phase":"initial","block":"Water batch A","kind":"control","settings":{"steep":12,"dose":75}},{"id":"r0002","order":2,"phase":"initial","block":"Water batch A","kind":"factorial","settings":{"steep":8,"dose":60}},{"id":"r0003","order":3,"phase":"initial","block":"Water batch A","kind":"factorial","settings":{"steep":8,"dose":90}},{"id":"r0004","order":4,"phase":"initial","block":"Water batch A","kind":"factorial","settings":{"steep":16,"dose":60}},{"id":"r0005","order":5,"phase":"initial","block":"Water batch A","kind":"factorial","settings":{"steep":8,"dose":90}},{"id":"r0006","order":6,"phase":"initial","block":"Water batch A","kind":"factorial","settings":{"steep":16,"dose":90}},{"id":"r0007","order":7,"phase":"initial","block":"Water batch A","kind":"factorial","settings":{"steep":16,"dose":60}},{"id":"r0008","order":8,"phase":"initial","block":"Water batch A","kind":"control","settings":{"steep":12,"dose":75}},{"id":"r0009","order":9,"phase":"initial","block":"Water batch A","kind":"factorial","settings":{"steep":16,"dose":90}},{"id":"r0010","order":10,"phase":"initial","block":"Water batch A","kind":"factorial","settings":{"steep":8,"dose":90}},{"id":"r0011","order":11,"phase":"initial","block":"Water batch A","kind":"factorial","settings":{"steep":8,"dose":60}},{"id":"r0012","order":12,"phase":"initial","block":"Water batch A","kind":"factorial","settings":{"steep":16,"dose":60}},{"id":"r0013","order":13,"phase":"initial","block":"Water batch A","kind":"factorial","settings":{"steep":16,"dose":90}},{"id":"r0014","order":14,"phase":"initial","block":"Water batch A","kind":"factorial","settings":{"steep":8,"dose":60}},{"id":"r0015","order":15,"phase":"initial","block":"Water batch A","kind":"control","settings":{"steep":12,"dose":75}}],"measurements":[],"sources":[],"audit":[{"id":"starter-design","at":"2026-09-20T00:00:00.000Z","action":"design","reason":"Generated a randomized run sheet; control positions are scheduled.","previous":{"runs":[],"phases":[]},"runs":15}],"conclusion":"","revision":"4309e41bb937fd8b393b8f26ba8a8f3667e9b865ada79caac48cc166544545f4"},"assets":{"reproduce":"\"\"\"Recompute the delivered primary OLS analysis using independent Python libraries.\n\nRun in the delivery directory. This does not infer experimental validity from a model fit.\n\"\"\"\nimport json\nfrom pathlib import Path\nimport numpy as np\nimport scipy.stats as stats\nimport statsmodels.api as sm\n\nroot = Path(__file__).resolve().parent\nanalysis = json.loads((root / \"analysis.json\").read_text())\nif not analysis[\"ok\"]:\n raise SystemExit(\"No estimable primary model: \" + analysis[\"issue\"])\nx = np.asarray(analysis[\"matrix\"][\"X\"], dtype=float)\ny = np.asarray(analysis[\"matrix\"][\"y\"], dtype=float)\nresult = sm.OLS(y, x, missing=\"raise\", hasconst=True).fit()\nalpha = 1 - analysis[\"model\"][\"confidence\"]\ninfluence = result.get_influence()\nreport = {\n \"method\": \"statsmodels OLS, exact delivered design matrix; conventional covariance\",\n \"run_ids\": analysis[\"matrix\"][\"runIds\"],\n \"n\": int(result.nobs), \"df\": int(result.df_resid),\n \"coefficients\": result.params.tolist(), \"se\": result.bse.tolist(),\n \"intervals\": result.conf_int(alpha=alpha).tolist(),\n \"covariance\": result.cov_params().tolist(),\n \"rmse\": float(np.sqrt(result.mse_resid)),\n \"fitted\": result.fittedvalues.tolist(), \"residuals\": result.resid.tolist(),\n \"leverage\": influence.hat_matrix_diag.tolist(),\n \"studentized\": influence.resid_studentized_internal.tolist(),\n \"cook\": influence.cooks_distance[0].tolist(),\n \"critical\": float(stats.t.ppf(1 - alpha / 2, result.df_resid)),\n}\nnp.testing.assert_allclose(result.params, analysis[\"beta\"], rtol=1e-8, atol=1e-8)\nnp.testing.assert_allclose(result.cov_params(), analysis[\"covariance\"], rtol=1e-8, atol=1e-8)\nnp.testing.assert_allclose(result.fittedvalues, [r[\"fitted\"] for r in analysis[\"residuals\"]], rtol=1e-8, atol=1e-8)\nnp.testing.assert_allclose(influence.hat_matrix_diag, [r[\"leverage\"] for r in analysis[\"residuals\"]], rtol=1e-8, atol=1e-8)\nif analysis[\"inferential\"]:\n np.testing.assert_allclose(result.conf_int(alpha=alpha), [c[\"ci\"] for c in analysis[\"coefficients\"]], rtol=1e-7, atol=1e-7)\n np.testing.assert_allclose(influence.cooks_distance[0], [r[\"cook\"] for r in analysis[\"residuals\"]], rtol=1e-7, atol=1e-7)\n\nproject = json.loads((root / \"project.signal.json\").read_text())\nconfirmation_checks = []\nfor phase in project[\"phases\"]:\n if phase[\"kind\"] != \"confirmation\":\n continue\n snapshot = phase[\"snapshot\"]\n old_x = np.asarray(snapshot[\"matrix\"][\"X\"], dtype=float)\n old_y = np.asarray(snapshot[\"matrix\"][\"y\"], dtype=float)\n frozen = sm.OLS(old_y, old_x, missing=\"raise\", hasconst=True).fit()\n np.testing.assert_allclose(frozen.params, [c[\"value\"] for c in snapshot[\"coefficients\"]], rtol=1e-8, atol=1e-8)\n for point in snapshot[\"predictions\"]:\n prediction = frozen.get_prediction(np.asarray([point[\"x\"]])).summary_frame(alpha=1-snapshot[\"model\"][\"confidence\"])\n np.testing.assert_allclose(float(prediction[\"mean\"].iloc[0]), point[\"mean\"], rtol=1e-8, atol=1e-8)\n np.testing.assert_allclose(prediction[[\"mean_ci_lower\", \"mean_ci_upper\"]].iloc[0], point[\"meanCI\"], rtol=1e-7, atol=1e-7)\n np.testing.assert_allclose(prediction[[\"obs_ci_lower\", \"obs_ci_upper\"]].iloc[0], point[\"predictionCI\"], rtol=1e-7, atol=1e-7)\n confirmation_checks.append({\"phase\": phase[\"id\"], \"predictions\": len(snapshot[\"predictions\"]), \"training_revision\": snapshot[\"trainingRevision\"]})\nreport[\"frozen_confirmation_checks\"] = confirmation_checks\n\ndef clean(value):\n if isinstance(value, float) and not np.isfinite(value):\n return None\n if isinstance(value, list):\n return [clean(v) for v in value]\n if isinstance(value, dict):\n return {k: clean(v) for k, v in value.items()}\n return value\n\n(root / \"reproduction.json\").write_text(json.dumps(clean(report), indent=2, allow_nan=False) + \"\\n\")\nprint(f\"Verified {report['n']} measured runs, {len(result.params)} coefficients and uncertainty. Wrote reproduction.json.\")\n","requirements":"numpy==1.26.4\nscipy==1.13.1\npandas==2.2.3\nstatsmodels==0.14.6\n","licenses":"Numerical libraries bundled in Signal\n\nml-matrix 6.15.0\nThe MIT License (MIT)\n\nCopyright (c) 2014 Michaël Zasso\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n\n\njstat 1.9.6\nCopyright (c) 2013 jStat\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n\nis-any-array 3.0.0\nThe MIT License (MIT)\n\nCopyright (c) 2018 cheminfo\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n\nml-array-rescale 2.0.0\nMIT License\n\nCopyright (c) 2017 mljs\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n\nml-array-min 2.0.0\nMIT License\n\nCopyright (c) 2017 mljs\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n\nml-array-max 2.0.0\nMIT License\n\nCopyright (c) 2017 ml.js\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","license":"MIT License\n\nCopyright (c) 2026 Autonomous, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"}}</script><script id="signal-app">(()=>{var ht=h=>JSON.parse(JSON.stringify(h));function D(h,d){if(!h)throw new Error(d)}var lt=(h,d=160,p=!1)=>typeof h=="string"&&(p||h.trim().length>0)&&h.length<=d,Re=h=>typeof h=="string"&&/^[a-z][a-z0-9_-]{0,47}$/.test(h)&&!["constructor","prototype"].includes(h),Gt=h=>typeof h=="number"&&Number.isFinite(h)&&Math.abs(h)<=1e12,yt=(h,d,p=0)=>Array.isArray(h)&&h.length>=p&&h.length<=d;function rt(h){return h===null||typeof h!="object"?JSON.stringify(h):Array.isArray(h)?"["+h.map(rt).join(",")+"]":"{"+Object.keys(h).sort().map(d=>JSON.stringify(d)+":"+rt(h[d])).join(",")+"}"}async function ye(h){let d=h instanceof Uint8Array?h:new TextEncoder().encode(typeof h=="string"?h:rt(h));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(p=>p.toString(16).padStart(2,"0")).join("")}function ae(h,d){D(d&&Object.keys(d).length===h.factors.length,"Every run needs exactly one setting for each factor.");for(let p of h.factors){let s=d[p.id];D(p.type==="number"?Gt(s)&&s>=p.levels[0]&&s<=p.levels.at(-1):p.levels.includes(s),`Keep ${p.name} inside its planned range.`)}return d}function xt(h){D(h&&new TextEncoder().encode(JSON.stringify(h)).length<=5e6,"Keep the complete project below 5 MB.");let d=ht(h);delete d.revision,D(d.spec===1&&Re(d.id)&<(d.title)&<(d.question,1200),"Use a version 1 Signal project with an id, title and question."),D(d.response&&Re(d.response.id)&<(d.response.name,80)&<(d.response.unit,40),"Name the continuous response and its measurement unit."),D(["maximize","minimize","target"].includes(d.response.goal),"Choose a response goal."),D(d.conclusion===void 0||lt(d.conclusion,8e3,!0),"Keep the decision note within 8000 characters."),D(d.evidenceNote===void 0||lt(d.evidenceNote,600),"Keep the evidence note short and explicit."),d.response.goal==="target"&&D(Gt(d.response.target),"Enter a finite target response."),D(yt(d.factors,6,1),"Use 1\u20136 experimental factors.");let p=new Set;for(let e of d.factors)D(Re(e.id)&&!p.has(e.id)&&!["run_id","response","block","order","phase","kind","unit","note"].includes(e.id),"Factors need distinct ids, separate from collection columns."),p.add(e.id),D(lt(e.name,80)&&["number","category"].includes(e.type)&<(e.unit,40,!0),"Each factor needs a name, type and unit (which can be blank)."),D(yt(e.levels,5,2)&&new Set(e.levels).size===e.levels.length,"Use 2\u20135 distinct levels per factor."),e.type==="number"?D(e.levels.every(Gt)&&e.levels.every((r,i)=>i===0||r>e.levels[i-1]),"Numeric levels must be finite and increasing."):D(e.levels.every(r=>lt(r,60)),"Category levels must be short, nonempty names.");let s=d.protocol;D(s&<(s.unit,300)&<(s.randomization,600)&<(s.analysisPlan,1200)&&yt(s.steps,20,1)&&s.steps.every(e=>lt(e,1200)),"Describe the independent experimental unit, randomization, planned analysis and procedure."),D(lt(s.notes,4e3,!0)&&typeof d.approved=="boolean","Include protocol notes and approval state."),D(d.design&<(d.design.seed,100)&&Number.isInteger(d.design.replicates)&&d.design.replicates>=1&&d.design.replicates<=20,"Use a seed and 1\u201320 independent repetitions per combination and block."),D(yt(d.design.blocks,8,1)&&d.design.blocks.every(e=>lt(e,60))&&new Set(d.design.blocks).size===d.design.blocks.length,"Name 1\u20138 distinct complete blocks."),D(Number.isInteger(d.design.controls)&&d.design.controls>=0&&d.design.controls<=5&&d.design.controls!==1,"Choose zero or 2\u20135 control runs per block (at the beginning, end and between)."),D(d.model&&yt(d.model.terms,24)&&new Set(d.model.terms).size===d.model.terms.length&&typeof d.model.blocks=="boolean","Use a distinct list of model terms and a block setting."),D([.8,.9,.95,.99].includes(d.model.confidence),"Use 80%, 90%, 95% or 99% confidence.");for(let e of d.model.terms)if(D(typeof e=="string","Model terms must be names."),e.endsWith("^2")){let r=d.factors.find(i=>i.id===e.slice(0,-2));D(r?.type==="number"&&d.model.terms.includes(r.id),"A quadratic term needs its numeric main effect.")}else{let r=e.split(":");D(r.length<=2&&new Set(r).size===r.length&&r.every(i=>p.has(i)),"Use main effects, two-factor interactions or numeric quadratic terms."),r.length===2&&D(r.every(i=>d.model.terms.includes(i)),"An interaction needs both main effects.")}D(yt(d.phases,30)&&yt(d.runs,512)&&yt(d.measurements,512)&&yt(d.sources,30)&&yt(d.audit,5e3),"This workshop supports up to 512 runs, 30 phases/imports and 5000 recorded changes.");let u=new Set;for(let e of d.phases)if(D(Re(e.id)&&!u.has(e.id)&<(e.label)&&["plan","extension","confirmation"].includes(e.kind)&<(e.reason,1e3)&<(e.seed,100),"Each phase needs a unique id, purpose, reason and seed."),u.add(e.id),e.kind==="confirmation"){D(e.snapshot&&/^[a-f0-9]{64}$/.test(e.snapshot.trainingRevision)&&yt(e.snapshot.predictions,12,1),"Confirmation runs retain their original model and predictions.");let r=e.snapshot,i=r.matrix,c=r.columns?.length;D(Number.isInteger(r.n)&&r.n>1&&r.n<=512&&yt(r.columns,48,1)&&r.columns.every(f=>lt(f.id)&<(f.label,300))&&r.df===r.n-c&&r.df>0,"A confirmation snapshot needs its original measured count, columns and residual degrees of freedom."),D(r.model&&[.8,.9,.95,.99].includes(r.model.confidence)&&yt(r.coefficients,c,c)&&yt(r.covariance,c,c),"Retain the original model, coefficients and covariance for confirmation."),D(i&&yt(i.X,r.n,r.n)&&yt(i.y,r.n,r.n)&&yt(i.runIds,r.n,r.n)&&new Set(i.runIds).size===r.n,"Retain the complete training matrix and run ids with the forecast."),D(i.X.every(f=>yt(f,c,c)&&f.every(Gt))&&i.y.every(Gt)&&r.coefficients.every(f=>Number.isFinite(f.value))&&r.covariance.every(f=>yt(f,c,c)&&f.every(Number.isFinite))&&Number.isFinite(r.mse)&&r.mse>0,"The frozen analysis must contain finite numerical results.");for(let f of e.snapshot.predictions)ae(d,f.settings),D(d.design.blocks.includes(f.block)&&Number.isFinite(f.mean)&&yt(f.x,c,c)&&f.x.every(Gt)&&yt(f.meanCI,2,2)&&yt(f.predictionCI,2,2)&&[...f.meanCI,...f.predictionCI].every(Number.isFinite)&&f.meanCI[0]<=f.mean&&f.meanCI[1]>=f.mean&&f.predictionCI[0]<=f.meanCI[0]&&f.predictionCI[1]>=f.meanCI[1],"Confirmation predictions must retain their design row, ordered intervals and named block.")}let M=new Map;for(let[e,r]of d.runs.entries())D(Re(r.id)&&!M.has(r.id)&&r.order===e+1&&u.has(r.phase)&&d.design.blocks.includes(r.block)&&["factorial","control","followup"].includes(r.kind),"Run ids and order must be unique, with a declared phase and block."),ae(d,r.settings),M.set(r.id,r);for(let e of d.phases.filter(r=>r.kind==="confirmation")){let r=e.snapshot.predictions.map(i=>rt({settings:i.settings,block:i.block}));D(new Set(r).size===r.length,"Use distinct confirmation points."),D(d.runs.filter(i=>i.phase===e.id).every(i=>r.includes(rt({settings:i.settings,block:i.block}))),"Each confirmation run must match one of its frozen predicted settings."),D(e.snapshot.matrix.runIds.every(i=>M.has(i)&&d.phases.find(c=>c.id===M.get(i).phase)?.kind!=="confirmation"),"The frozen training matrix must reference existing non-confirmation runs.")}let x=new Map;for(let e of d.sources)D(Re(e.id)&&!x.has(e.id)&<(e.name,160)&&/^[a-f0-9]{64}$/.test(e.sha256),"Imported measurements need unique ids, original filenames and SHA-256 hashes."),D(lt(e.base64,14e5)&&/^[A-Za-z0-9+/]*={0,2}$/.test(e.base64)&<(e.unit,40)&&e.unit===d.response.unit,"Keep each original CSV below 1 MB and confirm its response unit."),D(e.mapping&<(e.mapping.runId)&<(e.mapping.response)&&e.mapping.runId!==e.mapping.response&<(e.importedAt,50),"Map distinct run id and response columns."),x.set(e.id,e);let R=new Set;for(let e of d.measurements)D(M.has(e.runId)&&!R.has(e.runId)&&Gt(e.value)&<(e.note,1e3,!0),"Each known run may have one finite measurement."),R.add(e.runId),D(e.excluded===null||lt(e.excluded,600),"An excluded measurement needs a recorded reason."),D(e.origin&&Gt(e.origin.value)&&["manual","csv"].includes(e.origin.kind),"Keep the original measurement and its provenance."),e.origin.kind==="csv"&&D(x.has(e.origin.source)&&Number.isInteger(e.origin.row)&&e.origin.row>=2,"CSV measurements must reference their original file and row.");let v=new Set;for(let e of d.audit)D(lt(e.id,80)&&!v.has(e.id)&<(e.at,50)&<(e.action,80)&<(e.reason,1200),"Every change in the log needs an id, time, action and reason."),v.add(e.id);for(let e of d.measurements)(e.value!==e.origin.value||e.excluded)&&D(d.audit.some(r=>r.action==="measurement"&&r.runId===e.runId&&rt(r.after)===rt(e)),"A corrected or excluded result needs its complete logged change and reason.");if(d.comparison)for(let e of[d.comparison.a,d.comparison.b])D(e&&d.design.blocks.includes(e.block),"Comparison points need a known block."),ae(d,e.settings);return d}function Bt(h,d,p,s={}){D(lt(p,1200),"Record a reason for this change."),h.audit.push({id:crypto.randomUUID(),at:new Date().toISOString(),action:d,reason:p,...ht(s)})}var fe=h=>h.approved||h.measurements.length>0;function An(h,d){D(h.id===d.id,"Open a different project in its own workspace; source saves keep this experiment id."),D(rt(d.audit.slice(0,h.audit.length))===rt(h.audit),"Keep the existing change log.");for(let s of h.sources)D(rt(d.sources.find(u=>u.id===s.id))===rt(s),"Keep every original imported file.");if(fe(h)){for(let s of["factors","protocol","response","design"])D(rt(h[s])===rt(d[s]),"The collected or approved protocol is locked. Start a separate experiment to change its factors or measurement method.");D(!h.approved||d.approved,"Preserve protocol approval.");for(let s of h.runs)D(rt(d.runs.find(u=>u.id===s.id))===rt(s),"Keep existing run settings and order; append a follow-up phase.");for(let s of h.phases)D(rt(d.phases.find(u=>u.id===s.id))===rt(s),"Keep each phase and its original prediction snapshot.")}let p=d.audit.slice(h.audit.length);for(let s of d.measurements.filter(u=>!h.measurements.some(M=>M.runId===u.runId)))D(p.some(u=>u.action==="measurement"&&u.runId===s.runId&&u.before===null&&rt(u.after)===rt(s))||p.some(u=>u.action==="import"&&u.source===s.origin.source&&u.runs?.includes(s.runId)),"Keep the entry or import event for every new measurement.");for(let s of h.measurements){let u=d.measurements.find(M=>M.runId===s.runId);if(D(u&&rt(u.origin)===rt(s.origin),"Keep each measured result and its original provenance."),rt(s)!==rt(u)){let M=s;for(let x of p.filter(R=>R.runId===s.runId&&R.action==="measurement"))D(rt(x.before)===rt(M),"Measurement corrections must keep their previous value."),M=x.after;D(rt(M)===rt(u),"Use a logged correction or exclusion with a reason to change a measured result.")}}return h.measurements.length&&rt(h.model)!==rt(d.model)&&D(p.some(s=>s.action==="model"&&rt(s.before)===rt(h.model)&&rt(s.after)===rt(d.model)),"Record the reason for changing a model after seeing data."),d}function xe(h,d=24){let p=[ht(h)],s=0;return{get value(){return ht(p[s])},get canUndo(){return s>0},get canRedo(){return s<p.length-1},push(u){return p=p.slice(0,s+1),p.push(ht(u)),p.length>d&&p.shift(),s=p.length-1,this.value},undo(){return s=Math.max(0,s-1),this.value},redo(){return s=Math.min(p.length-1,s+1),this.value}}}function Tr(h){let d=2166136261;for(let p of String(h))d=Math.imul(d^p.charCodeAt(0),16777619);return()=>{let p=d+=1831565813;return p=Math.imul(p^p>>>15,p|1),p^=p+Math.imul(p^p>>>7,p|61),((p^p>>>14)>>>0)/4294967296}}function Cn(h,d){let p=ht(h),s=Tr(d);for(let u=p.length-1;u>0;u--){let M=Math.floor(s()*(u+1));[p[u],p[M]]=[p[M],p[u]]}return p}function un(h){let d=[{}];for(let p of h.factors)D(d.length*p.levels.length<=512,"The full factorial exceeds 512 combinations. Narrow the factors or levels."),d=d.flatMap(s=>p.levels.map(u=>({...s,[p.id]:u})));return d}function zr(h){return Object.fromEntries(h.factors.map(d=>[d.id,d.type==="number"?(d.levels[0]+d.levels.at(-1))/2:d.levels[0]]))}function cn(h){let d=xt(h);D(!fe(d),"Collected or approved runs cannot be reshuffled. Append a follow-up.");let p=un(d),s=d.design,u=(p.length*s.replicates+s.controls)*s.blocks.length;D(u<=512,`This design needs ${u} runs. Keep it within 512.`);let M={runs:d.runs,phases:d.phases};d.runs=[],d.phases=[{id:"initial",label:"Initial experiment",kind:"plan",reason:"Full factorial, independent repetitions and complete blocks.",seed:s.seed}];for(let x of s.blocks){let R=Cn(Array.from({length:s.replicates},()=>p).flat().map(e=>({kind:"factorial",settings:e})),s.seed+":block:"+x),v=[];for(let e=0;e<=R.length;e++){for(let r=0;r<s.controls;r++)Math.round(r*R.length/(s.controls-1))===e&&v.push({kind:"control",settings:zr(d)});e<R.length&&v.push(R[e])}for(let e of v){let r=d.runs.length+1;d.runs.push({id:"r"+String(r).padStart(4,"0"),order:r,phase:"initial",block:x,...e})}}return Bt(d,"design","Generated a randomized run sheet; control positions are scheduled.",{previous:M,runs:d.runs.length}),xt(d)}function jn(h){let d=xt(h);return D(d.runs.length,"Generate the run sheet first."),d.approved=!0,Bt(d,"approve","Approved the protocol and original run order."),d}function Tn(h,{points:d,repeats:p=3,label:s="Confirmation",reason:u,seed:M,kind:x="confirmation",snapshot:R}){let v=xt(h);D(["confirmation","extension"].includes(x),"Choose a confirmation or an extension."),D(Array.isArray(d)&&d.length>=1&&d.length<=12&&Number.isInteger(p)&&p>=1&&p<=20,"Choose 1\u201312 points and 1\u201320 independent repetitions."),D(v.runs.length+d.length*p<=512,"The follow-up exceeds 512 total runs.");for(let i of d)ae(v,i.settings),D(v.design.blocks.includes(i.block),"Choose an existing comparable block. New blocking conditions need a separate design.");let e="phase"+(v.phases.length+1),r={id:e,label:s,kind:x,reason:u,seed:M};x==="confirmation"&&(D(R&&R.predictions.length===d.length,"Freeze the predictions before collecting confirmation measurements."),r.snapshot=ht(R)),v.phases.push(r);for(let i of v.design.blocks){let c=Array.from({length:p},()=>d.filter(f=>f.block===i)).flat();for(let f of Cn(c,M+":"+i)){let g=v.runs.length+1;v.runs.push({id:"r"+String(g).padStart(4,"0"),order:g,phase:e,block:i,kind:"followup",settings:ht(f.settings)})}}return Bt(v,"followup",u,{phase:e,kind:x,runs:d.length*p}),xt(v)}function ze(h){D(typeof h=="string"&&h.length<=1e6,"Use a UTF-8 CSV below 1 MB.");let d=h.replace(/^\uFEFF/,""),p=[],s=[],u="",M=!1,x=!1,R=1,v=1,e=()=>{s.push(u),u="",x=!1},r=()=>{e(),s.some(c=>c!=="")&&p.push({row:v,cells:s}),s=[],v=R+1};for(let c=0;c<d.length;c++){let f=d[c];M?f==='"'?d[c+1]==='"'?(u+='"',c++):(M=!1,x=!0):(u+=f,(f===`+`||f==="\r"&&d[c+1]!==`+`)&&R++):f==='"'?(D(u===""&&!x,`Unexpected quote at line ${R}.`),M=!0):f===","?e():f===`+`||f==="\r"?(f==="\r"&&d[c+1]===`+`&&c++,r(),R++):(D(!x,`Unexpected text after a quoted field at line ${R}.`),u+=f)}D(!M,"The CSV ends inside a quoted field."),(u||s.length||x)&&r(),D(p.length>=1&&p.length<=1025,"Include a header and at most 1024 measurement rows.");let i=p.shift().cells.map(c=>c.trim());D(i.length>=2&&i.length<=40&&i.every(c=>lt(c,160))&&new Set(i).size===i.length,"Use 2\u201340 distinct, nonempty column names.");for(let c of p)D(c.cells.length===i.length,`Line ${c.row} has ${c.cells.length} cells; the header has ${i.length}.`);return{headers:i,rows:p.map(c=>({row:c.row,values:Object.fromEntries(i.map((f,g)=>[f,c.cells[g]]))}))}}function dn(h){let d=String(h).trim();return D(/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(d)&&Gt(Number(d)),"Use a finite decimal measurement, with no unit text or thousands separators."),Number(d)}function Pe(h){try{return new TextDecoder("utf-8",{fatal:!0}).decode(h)}catch{throw new Error("The CSV must use UTF-8 text.")}}function Pr(h){let d="";for(let p=0;p<h.length;p+=8192)d+=String.fromCharCode(...h.subarray(p,p+8192));return btoa(d)}var Ge=h=>Uint8Array.from(atob(h),d=>d.charCodeAt(0));function fn(h,d,p,s,{checkExisting:u=!0}={}){D(d.headers.includes(p.runId)&&d.headers.includes(p.response)&&p.runId!==p.response,"Map two different columns: run id and measured response."),D(s===h.response.unit,`Confirm measurements are in ${h.response.unit}. No unit conversion is applied.`);let M=new Map(h.runs.map(r=>[r.id,r])),x=new Set,R=new Set(h.measurements.map(r=>r.runId)),v=0,e=[];for(let r of d.rows){let i=r.values[p.runId].trim(),c=M.get(i);D(c,`Line ${r.row}: unknown run id \u201C${i}\u201D. Use the run sheet ids.`),D(!x.has(i),`Line ${r.row}: duplicate run id ${i}.`),x.add(i);for(let g of h.factors)if(Object.hasOwn(r.values,g.id)){let y=g.type==="number"?dn(r.values[g.id]):r.values[g.id];D(y===c.settings[g.id],`Line ${r.row}: ${g.name} does not match the planned run.`)}if(Object.hasOwn(r.values,"block")&&D(r.values.block===c.block,`Line ${r.row}: the block does not match the plan.`),Object.hasOwn(r.values,"unit")&&D(r.values.unit===s,`Line ${r.row}: the response unit does not match.`),r.values[p.response].trim()===""){v++;continue}D(!u||!R.has(i),`${i} is already measured. Use a logged correction to change it.`);let f;try{f=dn(r.values[p.response])}catch(g){throw new Error(`Line ${r.row}: ${g.message}`)}e.push({runId:i,value:f,row:r.row,note:r.values.note??""})}return{records:e,pending:v,rows:d.rows.length}}async function zn(h,d,{name:p,mapping:s,unit:u}){let M=xt(h);D(d.length>0&&d.length<=1e6,"Use a nonempty CSV below 1 MB.");let x=ze(Pe(d)),R=fn(M,x,s,u);D(R.records.length,"This file has no new measured responses. Blank response cells remain pending.");let v=await ye(d);return D(!M.sources.some(e=>e.sha256===v),"This original file has already been imported."),{source:{id:"csv"+(M.sources.length+1)+"_"+v.slice(0,10),name:p,base64:Pr(d),sha256:v,mapping:s,unit:u,importedAt:new Date().toISOString()},...R}}function Pn(h,d){let p=xt(h),s=d.source,u=fn(p,ze(Pe(Ge(s.base64))),s.mapping,s.unit);D(!p.sources.some(M=>M.id===s.id||M.sha256===s.sha256),"This source is already part of the experiment."),p.sources.push(ht(s));for(let M of u.records)p.measurements.push({runId:M.runId,value:M.value,origin:{kind:"csv",source:s.id,row:M.row,value:M.value},note:M.note,excluded:null});return Bt(p,"import",`Imported ${u.records.length} measured responses from ${s.name}; ${u.pending} blank responses remain pending.`,{source:s.id,sha256:s.sha256,runs:u.records.map(M=>M.runId)}),xt(p)}function On(h,d,{value:p,note:s="",excluded:u=null,reason:M}){let x=xt(h);D(x.runs.some(i=>i.id===d),"Choose a known run.");let R=typeof p=="number"?p:dn(p);D(Gt(R),"Enter a finite measured value.");let v=x.measurements.findIndex(i=>i.runId===d),e=v<0?null:ht(x.measurements[v]),r={runId:d,value:R,origin:e?.origin??{kind:"manual",value:R},note:s,excluded:u};return v<0?x.measurements.push(r):x.measurements[v]=r,Bt(x,"measurement",M,{runId:d,before:e,after:r}),xt(x)}async function me(h){let d=xt(h);for(let p of d.sources){let s=Ge(p.base64);D(await ye(s)===p.sha256,`Original file hash mismatch: ${p.name}.`);let{records:u}=fn(d,ze(Pe(s)),p.mapping,p.unit,{checkExisting:!1});for(let M of u)D(d.measurements.some(x=>x.runId===M.runId&&x.origin.source===p.id&&x.origin.row===M.row),`Keep every imported measurement; use an exclusion reason instead of deleting ${M.runId}.`);for(let M of d.measurements.filter(x=>x.origin.kind==="csv"&&x.origin.source===p.id)){let x=u.find(R=>R.runId===M.runId&&R.row===M.origin.row);D(x?.value===M.origin.value,`Original measurement provenance does not match ${p.name}: ${M.runId}.`)}}return d}var Or=h=>'"'+String(h??"").replace(/"/g,'""')+'"',mn=h=>h.map(d=>d.map(Or).join(",")).join(`\r+`)+`\r+`;function Me(h,{blank:d=!0,phase:p=null}={}){let s=new Map(h.measurements.map(u=>[u.runId,u]));return mn([["run_id","order","phase","block","kind",...h.factors.map(u=>u.id),"response","unit","note"],...h.runs.filter(u=>!p||u.phase===p).map(u=>{let M=s.get(u.id);return[u.id,u.order,u.phase,u.block,u.kind,...h.factors.map(x=>u.settings[x.id]),d?"":M?.value,h.response.unit,d?"":M?.note]})])}var Vr=Object.create,Vn=Object.defineProperty,Fr=Object.getOwnPropertyDescriptor,Dr=Object.getOwnPropertyNames,Ur=Object.getPrototypeOf,_r=Object.prototype.hasOwnProperty,Fn=(h,d)=>()=>(d||h((d={exports:{}}).exports,d),d.exports),Lr=(h,d,p,s)=>{if(d&&typeof d=="object"||typeof d=="function")for(let u of Dr(d))!_r.call(h,u)&&u!==p&&Vn(h,u,{get:()=>d[u],enumerable:!(s=Fr(d,u))||s.enumerable});return h},Dn=(h,d,p)=>(p=h!=null?Vr(Ur(h)):{},Lr(d||!h||!h.__esModule?Vn(p,"default",{value:h,enumerable:!0}):p,h)),Hr=Fn(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});var d=Object.prototype.toString;function p(l){let o=d.call(l);return o.endsWith("Array]")&&!o.includes("Big")}function s(l,o={}){if(!p(l))throw new TypeError("input must be an array");if(l.length===0)throw new TypeError("input must not be empty");let{fromIndex:t=0,toIndex:n=l.length}=o;if(t<0||t>=l.length||!Number.isInteger(t))throw new Error("fromIndex must be a positive integer smaller than length");if(n<=t||n>l.length||!Number.isInteger(n))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");let a=l[t];for(let m=t+1;m<n;m++)l[m]>a&&(a=l[m]);return a}function u(l,o={}){if(!p(l))throw new TypeError("input must be an array");if(l.length===0)throw new TypeError("input must not be empty");let{fromIndex:t=0,toIndex:n=l.length}=o;if(t<0||t>=l.length||!Number.isInteger(t))throw new Error("fromIndex must be a positive integer smaller than length");if(n<=t||n>l.length||!Number.isInteger(n))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");let a=l[t];for(let m=t+1;m<n;m++)l[m]<a&&(a=l[m]);return a}function M(l,o={}){if(p(l)){if(l.length===0)throw new TypeError("input must not be empty")}else throw new TypeError("input must be an array");let t;if(o.output!==void 0){if(!p(o.output))throw new TypeError("output option must be an array if specified");t=o.output}else t=new Array(l.length);let n=u(l),a=s(l);if(n===a)throw new RangeError("minimum and maximum input values are equal. Cannot rescale a constant array");let{min:m=o.autoMinMax?n:0,max:w=o.autoMinMax?a:1}=o;if(m>=w)throw new RangeError("min option must be smaller than max option");let b=(w-m)/(a-n);for(let I=0;I<l.length;I++)t[I]=(l[I]-n)*b+m;return t}var x=" ".repeat(2),R=" ".repeat(4);function v(){return e(this)}function e(l,o={}){let{maxRows:t=15,maxColumns:n=10,maxNumSize:a=8,padMinus:m="auto"}=o;return`${l.constructor.name} {+${x}[+${R}${r(l,t,n,a,m)}+${x}]+${x}rows: ${l.rows}+${x}columns: ${l.columns}+}`}function r(l,o,t,n,a){let{rows:m,columns:w}=l,b=Math.min(m,o),I=Math.min(w,t),E=[];if(a==="auto"){a=!1;t:for(let z=0;z<b;z++)for(let A=0;A<I;A++)if(l.get(z,A)<0){a=!0;break t}}for(let z=0;z<b;z++){let A=[];for(let V=0;V<I;V++)A.push(i(l.get(z,V),n,a));E.push(`${A.join(" ")}`)}return I!==w&&(E[E.length-1]+=` ... ${w-t} more columns`),b!==m&&E.push(`... ${m-o} more rows`),E.join(`+${R}`)}function i(l,o,t){return(l>=0&&t?` ${c(l,o-1)}`:c(l,o)).padEnd(o)}function c(l,o){let t=l.toString();if(t.length<=o)return t;let n=l.toFixed(o);if(n.length>o&&(n=l.toFixed(Math.max(0,o-(n.length-o)))),n.length<=o&&!n.startsWith("0.000")&&!n.startsWith("-0.000"))return n;let a=l.toExponential(o);return a.length>o&&(a=l.toExponential(Math.max(0,o-(a.length-o)))),a.slice(0)}function f(l,o){l.prototype.add=function(t){return typeof t=="number"?this.addS(t):this.addM(t)},l.prototype.addS=function(t){for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)+t);return this},l.prototype.addM=function(t){if(t=o.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)+t.get(n,a));return this},l.add=function(t,n){return new o(t).add(n)},l.prototype.sub=function(t){return typeof t=="number"?this.subS(t):this.subM(t)},l.prototype.subS=function(t){for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)-t);return this},l.prototype.subM=function(t){if(t=o.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)-t.get(n,a));return this},l.sub=function(t,n){return new o(t).sub(n)},l.prototype.subtract=l.prototype.sub,l.prototype.subtractS=l.prototype.subS,l.prototype.subtractM=l.prototype.subM,l.subtract=l.sub,l.prototype.mul=function(t){return typeof t=="number"?this.mulS(t):this.mulM(t)},l.prototype.mulS=function(t){for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)*t);return this},l.prototype.mulM=function(t){if(t=o.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)*t.get(n,a));return this},l.mul=function(t,n){return new o(t).mul(n)},l.prototype.multiply=l.prototype.mul,l.prototype.multiplyS=l.prototype.mulS,l.prototype.multiplyM=l.prototype.mulM,l.multiply=l.mul,l.prototype.div=function(t){return typeof t=="number"?this.divS(t):this.divM(t)},l.prototype.divS=function(t){for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)/t);return this},l.prototype.divM=function(t){if(t=o.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)/t.get(n,a));return this},l.div=function(t,n){return new o(t).div(n)},l.prototype.divide=l.prototype.div,l.prototype.divideS=l.prototype.divS,l.prototype.divideM=l.prototype.divM,l.divide=l.div,l.prototype.mod=function(t){return typeof t=="number"?this.modS(t):this.modM(t)},l.prototype.modS=function(t){for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)%t);return this},l.prototype.modM=function(t){if(t=o.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)%t.get(n,a));return this},l.mod=function(t,n){return new o(t).mod(n)},l.prototype.modulus=l.prototype.mod,l.prototype.modulusS=l.prototype.modS,l.prototype.modulusM=l.prototype.modM,l.modulus=l.mod,l.prototype.and=function(t){return typeof t=="number"?this.andS(t):this.andM(t)},l.prototype.andS=function(t){for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)&t);return this},l.prototype.andM=function(t){if(t=o.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)&t.get(n,a));return this},l.and=function(t,n){return new o(t).and(n)},l.prototype.or=function(t){return typeof t=="number"?this.orS(t):this.orM(t)},l.prototype.orS=function(t){for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)|t);return this},l.prototype.orM=function(t){if(t=o.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)|t.get(n,a));return this},l.or=function(t,n){return new o(t).or(n)},l.prototype.xor=function(t){return typeof t=="number"?this.xorS(t):this.xorM(t)},l.prototype.xorS=function(t){for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)^t);return this},l.prototype.xorM=function(t){if(t=o.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)^t.get(n,a));return this},l.xor=function(t,n){return new o(t).xor(n)},l.prototype.leftShift=function(t){return typeof t=="number"?this.leftShiftS(t):this.leftShiftM(t)},l.prototype.leftShiftS=function(t){for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)<<t);return this},l.prototype.leftShiftM=function(t){if(t=o.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)<<t.get(n,a));return this},l.leftShift=function(t,n){return new o(t).leftShift(n)},l.prototype.signPropagatingRightShift=function(t){return typeof t=="number"?this.signPropagatingRightShiftS(t):this.signPropagatingRightShiftM(t)},l.prototype.signPropagatingRightShiftS=function(t){for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)>>t);return this},l.prototype.signPropagatingRightShiftM=function(t){if(t=o.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)>>t.get(n,a));return this},l.signPropagatingRightShift=function(t,n){return new o(t).signPropagatingRightShift(n)},l.prototype.rightShift=function(t){return typeof t=="number"?this.rightShiftS(t):this.rightShiftM(t)},l.prototype.rightShiftS=function(t){for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)>>>t);return this},l.prototype.rightShiftM=function(t){if(t=o.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)>>>t.get(n,a));return this},l.rightShift=function(t,n){return new o(t).rightShift(n)},l.prototype.zeroFillRightShift=l.prototype.rightShift,l.prototype.zeroFillRightShiftS=l.prototype.rightShiftS,l.prototype.zeroFillRightShiftM=l.prototype.rightShiftM,l.zeroFillRightShift=l.rightShift,l.prototype.not=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,~this.get(t,n));return this},l.not=function(t){return new o(t).not()},l.prototype.abs=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.abs(this.get(t,n)));return this},l.abs=function(t){return new o(t).abs()},l.prototype.acos=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.acos(this.get(t,n)));return this},l.acos=function(t){return new o(t).acos()},l.prototype.acosh=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.acosh(this.get(t,n)));return this},l.acosh=function(t){return new o(t).acosh()},l.prototype.asin=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.asin(this.get(t,n)));return this},l.asin=function(t){return new o(t).asin()},l.prototype.asinh=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.asinh(this.get(t,n)));return this},l.asinh=function(t){return new o(t).asinh()},l.prototype.atan=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.atan(this.get(t,n)));return this},l.atan=function(t){return new o(t).atan()},l.prototype.atanh=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.atanh(this.get(t,n)));return this},l.atanh=function(t){return new o(t).atanh()},l.prototype.cbrt=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.cbrt(this.get(t,n)));return this},l.cbrt=function(t){return new o(t).cbrt()},l.prototype.ceil=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.ceil(this.get(t,n)));return this},l.ceil=function(t){return new o(t).ceil()},l.prototype.clz32=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.clz32(this.get(t,n)));return this},l.clz32=function(t){return new o(t).clz32()},l.prototype.cos=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.cos(this.get(t,n)));return this},l.cos=function(t){return new o(t).cos()},l.prototype.cosh=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.cosh(this.get(t,n)));return this},l.cosh=function(t){return new o(t).cosh()},l.prototype.exp=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.exp(this.get(t,n)));return this},l.exp=function(t){return new o(t).exp()},l.prototype.expm1=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.expm1(this.get(t,n)));return this},l.expm1=function(t){return new o(t).expm1()},l.prototype.floor=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.floor(this.get(t,n)));return this},l.floor=function(t){return new o(t).floor()},l.prototype.fround=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.fround(this.get(t,n)));return this},l.fround=function(t){return new o(t).fround()},l.prototype.log=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.log(this.get(t,n)));return this},l.log=function(t){return new o(t).log()},l.prototype.log1p=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.log1p(this.get(t,n)));return this},l.log1p=function(t){return new o(t).log1p()},l.prototype.log10=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.log10(this.get(t,n)));return this},l.log10=function(t){return new o(t).log10()},l.prototype.log2=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.log2(this.get(t,n)));return this},l.log2=function(t){return new o(t).log2()},l.prototype.round=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.round(this.get(t,n)));return this},l.round=function(t){return new o(t).round()},l.prototype.sign=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.sign(this.get(t,n)));return this},l.sign=function(t){return new o(t).sign()},l.prototype.sin=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.sin(this.get(t,n)));return this},l.sin=function(t){return new o(t).sin()},l.prototype.sinh=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.sinh(this.get(t,n)));return this},l.sinh=function(t){return new o(t).sinh()},l.prototype.sqrt=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.sqrt(this.get(t,n)));return this},l.sqrt=function(t){return new o(t).sqrt()},l.prototype.tan=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.tan(this.get(t,n)));return this},l.tan=function(t){return new o(t).tan()},l.prototype.tanh=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.tanh(this.get(t,n)));return this},l.tanh=function(t){return new o(t).tanh()},l.prototype.trunc=function(){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,Math.trunc(this.get(t,n)));return this},l.trunc=function(t){return new o(t).trunc()},l.pow=function(t,n){return new o(t).pow(n)},l.prototype.pow=function(t){return typeof t=="number"?this.powS(t):this.powM(t)},l.prototype.powS=function(t){for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)**t);return this},l.prototype.powM=function(t){if(t=o.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.set(n,a,this.get(n,a)**t.get(n,a));return this}}function g(l,o,t){let n=t?l.rows:l.rows-1;if(o<0||o>n)throw new RangeError("Row index out of range")}function y(l,o,t){let n=t?l.columns:l.columns-1;if(o<0||o>n)throw new RangeError("Column index out of range")}function k(l,o){if(o.to1DArray&&(o=o.to1DArray()),o.length!==l.columns)throw new RangeError("vector size must be the same as the number of columns");return o}function N(l,o){if(o.to1DArray&&(o=o.to1DArray()),o.length!==l.rows)throw new RangeError("vector size must be the same as the number of rows");return o}function $(l,o){if(!p(o))throw new TypeError("row indices must be an array");for(let t=0;t<o.length;t++)if(o[t]<0||o[t]>=l.rows)throw new RangeError("row indices are out of range")}function S(l,o){if(!p(o))throw new TypeError("column indices must be an array");for(let t=0;t<o.length;t++)if(o[t]<0||o[t]>=l.columns)throw new RangeError("column indices are out of range")}function q(l,o,t,n,a){if(arguments.length!==5)throw new RangeError("expected 4 arguments");if(L("startRow",o),L("endRow",t),L("startColumn",n),L("endColumn",a),o>t||n>a||o<0||o>=l.rows||t<0||t>=l.rows||n<0||n>=l.columns||a<0||a>=l.columns)throw new RangeError("Submatrix indices are out of range")}function T(l,o=0){let t=[];for(let n=0;n<l;n++)t.push(o);return t}function L(l,o){if(typeof o!="number")throw new TypeError(`${l} must be a number`)}function W(l){if(l.isEmpty())throw new Error("Empty matrix has no elements to index")}function Z(l){let o=T(l.rows);for(let t=0;t<l.rows;++t)for(let n=0;n<l.columns;++n)o[t]+=l.get(t,n);return o}function nt(l){let o=T(l.columns);for(let t=0;t<l.rows;++t)for(let n=0;n<l.columns;++n)o[n]+=l.get(t,n);return o}function st(l){let o=0;for(let t=0;t<l.rows;t++)for(let n=0;n<l.columns;n++)o+=l.get(t,n);return o}function Et(l){let o=T(l.rows,1);for(let t=0;t<l.rows;++t)for(let n=0;n<l.columns;++n)o[t]*=l.get(t,n);return o}function Rt(l){let o=T(l.columns,1);for(let t=0;t<l.rows;++t)for(let n=0;n<l.columns;++n)o[n]*=l.get(t,n);return o}function X(l){let o=1;for(let t=0;t<l.rows;t++)for(let n=0;n<l.columns;n++)o*=l.get(t,n);return o}function dt(l,o,t){let n=l.rows,a=l.columns,m=[];for(let w=0;w<n;w++){let b=0,I=0,E=0;for(let z=0;z<a;z++)E=l.get(w,z)-t[w],b+=E,I+=E*E;o?m.push((I-b*b/a)/(a-1)):m.push((I-b*b/a)/a)}return m}function Mt(l,o,t){let n=l.rows,a=l.columns,m=[];for(let w=0;w<a;w++){let b=0,I=0,E=0;for(let z=0;z<n;z++)E=l.get(z,w)-t[w],b+=E,I+=E*E;o?m.push((I-b*b/n)/(n-1)):m.push((I-b*b/n)/n)}return m}function vt(l,o,t){let n=l.rows,a=l.columns,m=n*a,w=0,b=0,I=0;for(let E=0;E<n;E++)for(let z=0;z<a;z++)I=l.get(E,z)-t,w+=I,b+=I*I;return o?(b-w*w/m)/(m-1):(b-w*w/m)/m}function Dt(l,o){for(let t=0;t<l.rows;t++)for(let n=0;n<l.columns;n++)l.set(t,n,l.get(t,n)-o[t])}function Wt(l,o){for(let t=0;t<l.rows;t++)for(let n=0;n<l.columns;n++)l.set(t,n,l.get(t,n)-o[n])}function Ut(l,o){for(let t=0;t<l.rows;t++)for(let n=0;n<l.columns;n++)l.set(t,n,l.get(t,n)-o)}function At(l){let o=[];for(let t=0;t<l.rows;t++){let n=0;for(let a=0;a<l.columns;a++)n+=l.get(t,a)**2/(l.columns-1);o.push(Math.sqrt(n))}return o}function _t(l,o){for(let t=0;t<l.rows;t++)for(let n=0;n<l.columns;n++)l.set(t,n,l.get(t,n)/o[t])}function zt(l){let o=[];for(let t=0;t<l.columns;t++){let n=0;for(let a=0;a<l.rows;a++)n+=l.get(a,t)**2/(l.rows-1);o.push(Math.sqrt(n))}return o}function Yt(l,o){for(let t=0;t<l.rows;t++)for(let n=0;n<l.columns;n++)l.set(t,n,l.get(t,n)/o[n])}function de(l){let o=l.size-1,t=0;for(let n=0;n<l.columns;n++)for(let a=0;a<l.rows;a++)t+=l.get(a,n)**2/o;return Math.sqrt(t)}function je(l,o){for(let t=0;t<l.rows;t++)for(let n=0;n<l.columns;n++)l.set(t,n,l.get(t,n)/o)}var gt=class St{static from1DArray(o,t,n){if(o*t!==n.length)throw new RangeError("data length does not match given dimensions");let a=new Y(o,t);for(let m=0;m<o;m++)for(let w=0;w<t;w++)a.set(m,w,n[m*t+w]);return a}static rowVector(o){let t=new Y(1,o.length);for(let n=0;n<o.length;n++)t.set(0,n,o[n]);return t}static columnVector(o){let t=new Y(o.length,1);for(let n=0;n<o.length;n++)t.set(n,0,o[n]);return t}static zeros(o,t){return new Y(o,t)}static ones(o,t){return new Y(o,t).fill(1)}static rand(o,t,n={}){if(typeof n!="object")throw new TypeError("options must be an object");let{random:a=Math.random}=n,m=new Y(o,t);for(let w=0;w<o;w++)for(let b=0;b<t;b++)m.set(w,b,a());return m}static randInt(o,t,n={}){if(typeof n!="object")throw new TypeError("options must be an object");let{min:a=0,max:m=1e3,random:w=Math.random}=n;if(!Number.isInteger(a))throw new TypeError("min must be an integer");if(!Number.isInteger(m))throw new TypeError("max must be an integer");if(a>=m)throw new RangeError("min must be smaller than max");let b=m-a,I=new Y(o,t);for(let E=0;E<o;E++)for(let z=0;z<t;z++){let A=a+Math.round(w()*b);I.set(E,z,A)}return I}static eye(o,t,n){t===void 0&&(t=o),n===void 0&&(n=1);let a=Math.min(o,t),m=this.zeros(o,t);for(let w=0;w<a;w++)m.set(w,w,n);return m}static diag(o,t,n){let a=o.length;t===void 0&&(t=a),n===void 0&&(n=t);let m=Math.min(a,t,n),w=this.zeros(t,n);for(let b=0;b<m;b++)w.set(b,b,o[b]);return w}static min(o,t){o=this.checkMatrix(o),t=this.checkMatrix(t);let n=o.rows,a=o.columns,m=new Y(n,a);for(let w=0;w<n;w++)for(let b=0;b<a;b++)m.set(w,b,Math.min(o.get(w,b),t.get(w,b)));return m}static max(o,t){o=this.checkMatrix(o),t=this.checkMatrix(t);let n=o.rows,a=o.columns,m=new this(n,a);for(let w=0;w<n;w++)for(let b=0;b<a;b++)m.set(w,b,Math.max(o.get(w,b),t.get(w,b)));return m}static checkMatrix(o){return St.isMatrix(o)?o:new Y(o)}static isMatrix(o){return o!=null&&o.klass==="Matrix"}get size(){return this.rows*this.columns}apply(o){if(typeof o!="function")throw new TypeError("callback must be a function");for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)o.call(this,t,n);return this}applyAlongAxis(o,t){if(typeof o!="function")throw new TypeError("callback must be a function");let n=[];switch(t){case"row":{for(let a=0;a<this.rows;a++)n.push(o.call(this,this.getRow(a),a));break}case"column":{for(let a=0;a<this.columns;a++)n.push(o.call(this,this.getColumn(a),a));break}default:throw new Error(`invalid option: ${t}`)}return n}to1DArray(){let o=[];for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)o.push(this.get(t,n));return o}to2DArray(){let o=[];for(let t=0;t<this.rows;t++){o.push([]);for(let n=0;n<this.columns;n++)o[t].push(this.get(t,n))}return o}toJSON(){return this.to2DArray()}isRowVector(){return this.rows===1}isColumnVector(){return this.columns===1}isVector(){return this.rows===1||this.columns===1}isSquare(){return this.rows===this.columns}isEmpty(){return this.rows===0||this.columns===0}isSymmetric(){if(this.isSquare()){for(let o=0;o<this.rows;o++)for(let t=0;t<=o;t++)if(this.get(o,t)!==this.get(t,o))return!1;return!0}return!1}isDistance(){if(!this.isSymmetric())return!1;for(let o=0;o<this.rows;o++)if(this.get(o,o)!==0)return!1;return!0}isEchelonForm(){let o=0,t=0,n=-1,a=!0,m=!1;for(;o<this.rows&&a;){for(t=0,m=!1;t<this.columns&&m===!1;)this.get(o,t)===0?t++:this.get(o,t)===1&&t>n?(m=!0,n=t):(a=!1,m=!0);o++}return a}isReducedEchelonForm(){let o=0,t=0,n=-1,a=!0,m=!1;for(;o<this.rows&&a;){for(t=0,m=!1;t<this.columns&&m===!1;)this.get(o,t)===0?t++:this.get(o,t)===1&&t>n?(m=!0,n=t):(a=!1,m=!0);for(let w=t+1;w<this.rows;w++)this.get(o,w)!==0&&(a=!1);o++}return a}echelonForm(){let o=this.clone(),t=0,n=0;for(;t<o.rows&&n<o.columns;){let a=t;for(let m=t;m<o.rows;m++)o.get(m,n)>o.get(a,n)&&(a=m);if(o.get(a,n)===0)n++;else{o.swapRows(t,a);let m=o.get(t,n);for(let w=n;w<o.columns;w++)o.set(t,w,o.get(t,w)/m);for(let w=t+1;w<o.rows;w++){let b=o.get(w,n)/o.get(t,n);o.set(w,n,0);for(let I=n+1;I<o.columns;I++)o.set(w,I,o.get(w,I)-o.get(t,I)*b)}t++,n++}}return o}reducedEchelonForm(){let o=this.echelonForm(),t=o.columns,n=o.rows,a=n-1;for(;a>=0;)if(o.maxRow(a)===0)a--;else{let m=0,w=!1;for(;m<n&&w===!1;)o.get(a,m)===1?w=!0:m++;for(let b=0;b<a;b++){let I=o.get(b,m);for(let E=m;E<t;E++){let z=o.get(b,E)-I*o.get(a,E);o.set(b,E,z)}}a--}return o}set(){throw new Error("set method is unimplemented")}get(){throw new Error("get method is unimplemented")}repeat(o={}){if(typeof o!="object")throw new TypeError("options must be an object");let{rows:t=1,columns:n=1}=o;if(!Number.isInteger(t)||t<=0)throw new TypeError("rows must be a positive integer");if(!Number.isInteger(n)||n<=0)throw new TypeError("columns must be a positive integer");let a=new Y(this.rows*t,this.columns*n);for(let m=0;m<t;m++)for(let w=0;w<n;w++)a.setSubMatrix(this,this.rows*m,this.columns*w);return a}fill(o){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,o);return this}neg(){return this.mulS(-1)}getRow(o){g(this,o);let t=[];for(let n=0;n<this.columns;n++)t.push(this.get(o,n));return t}getRowVector(o){return Y.rowVector(this.getRow(o))}setRow(o,t){g(this,o),t=k(this,t);for(let n=0;n<this.columns;n++)this.set(o,n,t[n]);return this}swapRows(o,t){g(this,o),g(this,t);for(let n=0;n<this.columns;n++){let a=this.get(o,n);this.set(o,n,this.get(t,n)),this.set(t,n,a)}return this}getColumn(o){y(this,o);let t=[];for(let n=0;n<this.rows;n++)t.push(this.get(n,o));return t}getColumnVector(o){return Y.columnVector(this.getColumn(o))}setColumn(o,t){y(this,o),t=N(this,t);for(let n=0;n<this.rows;n++)this.set(n,o,t[n]);return this}swapColumns(o,t){y(this,o),y(this,t);for(let n=0;n<this.rows;n++){let a=this.get(n,o);this.set(n,o,this.get(n,t)),this.set(n,t,a)}return this}addRowVector(o){o=k(this,o);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)+o[n]);return this}subRowVector(o){o=k(this,o);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)-o[n]);return this}mulRowVector(o){o=k(this,o);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)*o[n]);return this}divRowVector(o){o=k(this,o);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)/o[n]);return this}addColumnVector(o){o=N(this,o);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)+o[t]);return this}subColumnVector(o){o=N(this,o);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)-o[t]);return this}mulColumnVector(o){o=N(this,o);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)*o[t]);return this}divColumnVector(o){o=N(this,o);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)/o[t]);return this}mulRow(o,t){g(this,o);for(let n=0;n<this.columns;n++)this.set(o,n,this.get(o,n)*t);return this}mulColumn(o,t){y(this,o);for(let n=0;n<this.rows;n++)this.set(n,o,this.get(n,o)*t);return this}max(o){if(this.isEmpty())return NaN;switch(o){case"row":{let t=new Array(this.rows).fill(Number.NEGATIVE_INFINITY);for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.get(n,a)>t[n]&&(t[n]=this.get(n,a));return t}case"column":{let t=new Array(this.columns).fill(Number.NEGATIVE_INFINITY);for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.get(n,a)>t[a]&&(t[a]=this.get(n,a));return t}case void 0:{let t=this.get(0,0);for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.get(n,a)>t&&(t=this.get(n,a));return t}default:throw new Error(`invalid option: ${o}`)}}maxIndex(){W(this);let o=this.get(0,0),t=[0,0];for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.get(n,a)>o&&(o=this.get(n,a),t[0]=n,t[1]=a);return t}min(o){if(this.isEmpty())return NaN;switch(o){case"row":{let t=new Array(this.rows).fill(Number.POSITIVE_INFINITY);for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.get(n,a)<t[n]&&(t[n]=this.get(n,a));return t}case"column":{let t=new Array(this.columns).fill(Number.POSITIVE_INFINITY);for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.get(n,a)<t[a]&&(t[a]=this.get(n,a));return t}case void 0:{let t=this.get(0,0);for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.get(n,a)<t&&(t=this.get(n,a));return t}default:throw new Error(`invalid option: ${o}`)}}minIndex(){W(this);let o=this.get(0,0),t=[0,0];for(let n=0;n<this.rows;n++)for(let a=0;a<this.columns;a++)this.get(n,a)<o&&(o=this.get(n,a),t[0]=n,t[1]=a);return t}maxRow(o){if(g(this,o),this.isEmpty())return NaN;let t=this.get(o,0);for(let n=1;n<this.columns;n++)this.get(o,n)>t&&(t=this.get(o,n));return t}maxRowIndex(o){g(this,o),W(this);let t=this.get(o,0),n=[o,0];for(let a=1;a<this.columns;a++)this.get(o,a)>t&&(t=this.get(o,a),n[1]=a);return n}minRow(o){if(g(this,o),this.isEmpty())return NaN;let t=this.get(o,0);for(let n=1;n<this.columns;n++)this.get(o,n)<t&&(t=this.get(o,n));return t}minRowIndex(o){g(this,o),W(this);let t=this.get(o,0),n=[o,0];for(let a=1;a<this.columns;a++)this.get(o,a)<t&&(t=this.get(o,a),n[1]=a);return n}maxColumn(o){if(y(this,o),this.isEmpty())return NaN;let t=this.get(0,o);for(let n=1;n<this.rows;n++)this.get(n,o)>t&&(t=this.get(n,o));return t}maxColumnIndex(o){y(this,o),W(this);let t=this.get(0,o),n=[0,o];for(let a=1;a<this.rows;a++)this.get(a,o)>t&&(t=this.get(a,o),n[0]=a);return n}minColumn(o){if(y(this,o),this.isEmpty())return NaN;let t=this.get(0,o);for(let n=1;n<this.rows;n++)this.get(n,o)<t&&(t=this.get(n,o));return t}minColumnIndex(o){y(this,o),W(this);let t=this.get(0,o),n=[0,o];for(let a=1;a<this.rows;a++)this.get(a,o)<t&&(t=this.get(a,o),n[0]=a);return n}diag(){let o=Math.min(this.rows,this.columns),t=[];for(let n=0;n<o;n++)t.push(this.get(n,n));return t}norm(o="frobenius"){switch(o){case"max":return this.max();case"frobenius":return Math.sqrt(this.dot(this));default:throw new RangeError(`unknown norm type: ${o}`)}}cumulativeSum(){let o=0;for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)o+=this.get(t,n),this.set(t,n,o);return this}dot(o){St.isMatrix(o)&&(o=o.to1DArray());let t=this.to1DArray();if(t.length!==o.length)throw new RangeError("vectors do not have the same size");let n=0;for(let a=0;a<t.length;a++)n+=t[a]*o[a];return n}mmul(o){o=Y.checkMatrix(o);let t=this.rows,n=this.columns,a=o.columns,m=new Y(t,a),w=new Float64Array(n);for(let b=0;b<a;b++){for(let I=0;I<n;I++)w[I]=o.get(I,b);for(let I=0;I<t;I++){let E=0;for(let z=0;z<n;z++)E+=this.get(I,z)*w[z];m.set(I,b,E)}}return m}gram(){let o=this.rows,t=this.columns,n=new Float64Array(t*t);for(let m=0;m<o;m++)for(let w=0;w<t;w++){let b=this.get(m,w);if(b===0)continue;let I=w*t;for(let E=w;E<t;E++)n[I+E]+=b*this.get(m,E)}let a=new Y(t,t);for(let m=0;m<t;m++){let w=m*t;for(let b=m;b<t;b++){let I=n[w+b];a.set(m,b,I),a.set(b,m,I)}}return a}transposeMultiply(o){if(o=Y.checkMatrix(o),this.rows!==o.rows)throw new RangeError("the number of rows of the two matrices must be equal");let t=this.columns,n=o.columns,a=new Y(t,n),m=new Float64Array(n);for(let w=0;w<this.rows;w++){for(let b=0;b<n;b++)m[b]=o.get(w,b);for(let b=0;b<t;b++){let I=this.get(w,b);if(I===0)continue;let E=a.data[b];for(let z=0;z<n;z++)E[z]+=I*m[z]}}return a}mmulByTranspose(o){let t=this.rows,n=this.columns;if(o!==void 0&&o.length!==n)throw new RangeError("scale must have one value per column");let a=new Y(t,t),m=new Float64Array(n);for(let w=0;w<t;w++){if(o===void 0)for(let b=0;b<n;b++)m[b]=this.get(w,b);else for(let b=0;b<n;b++)m[b]=o[b]*this.get(w,b);for(let b=w;b<t;b++){let I=0;for(let E=0;E<n;E++)I+=this.get(b,E)*m[E];a.set(b,w,I),a.set(w,b,I)}}return a}mpow(o){if(!this.isSquare())throw new RangeError("Matrix must be square");if(!Number.isInteger(o)||o<0)throw new RangeError("Exponent must be a non-negative integer");let t=Y.eye(this.rows),n=this;for(let a=o;a>=1;a/=2)(a&1)!==0&&(t=t.mmul(n)),n=n.mmul(n);return t}strassen2x2(o){o=Y.checkMatrix(o);let t=new Y(2,2),n=this.get(0,0),a=o.get(0,0),m=this.get(0,1),w=o.get(0,1),b=this.get(1,0),I=o.get(1,0),E=this.get(1,1),z=o.get(1,1),A=(n+E)*(a+z),V=(b+E)*a,F=n*(w-z),O=E*(I-a),H=(n+m)*z,J=(b-n)*(a+w),P=(m-E)*(I+z),K=A+O-H+P,G=F+H,ot=V+O,it=A-V+F+J;return t.set(0,0,K),t.set(0,1,G),t.set(1,0,ot),t.set(1,1,it),t}strassen3x3(o){o=Y.checkMatrix(o);let t=new Y(3,3),n=this.get(0,0),a=this.get(0,1),m=this.get(0,2),w=this.get(1,0),b=this.get(1,1),I=this.get(1,2),E=this.get(2,0),z=this.get(2,1),A=this.get(2,2),V=o.get(0,0),F=o.get(0,1),O=o.get(0,2),H=o.get(1,0),J=o.get(1,1),P=o.get(1,2),K=o.get(2,0),G=o.get(2,1),ot=o.get(2,2),it=(n+a+m-w-b-z-A)*J,et=(n-w)*(-F+J),mt=b*(-V+F+H-J-P-K+ot),tt=(-n+w+b)*(V-F+J),C=(w+b)*(-V+F),_=n*V,Q=(-n+E+z)*(V-O+P),B=(-n+E)*(O-P),wt=(E+z)*(-V+O),bt=(n+a+m-b-I-E-z)*P,pt=z*(-V+O+H-J-P-K+G),ft=(-m+z+A)*(J+K-G),Lt=(m-A)*(J-G),Ct=m*K,Ht=(z+A)*(-K+G),$t=(-m+b+I)*(P+K-ot),ie=(m-I)*(P-ot),at=(b+I)*(-K+ot),Nt=a*H,Ot=I*G,Vt=w*O,kt=E*F,kr=A*ot,Sr=_+Ct+Nt,Ir=it+tt+C+_+ft+Ct+Ht,Er=_+Q+wt+bt+Ct+$t+at,Rr=et+mt+tt+_+Ct+$t+ie,Nr=et+tt+C+_+Ot,qr=Ct+$t+ie+at+Vt,Ar=_+Q+B+pt+ft+Lt+Ct,Cr=ft+Lt+Ct+Ht+kt,jr=_+Q+B+wt+kr;return t.set(0,0,Sr),t.set(0,1,Ir),t.set(0,2,Er),t.set(1,0,Rr),t.set(1,1,Nr),t.set(1,2,qr),t.set(2,0,Ar),t.set(2,1,Cr),t.set(2,2,jr),t}mmulStrassen(o){o=Y.checkMatrix(o);let t=this.clone(),n=t.rows,a=t.columns,m=o.rows,w=o.columns;a!==m&&console.warn(`Multiplying ${n} x ${a} and ${m} x ${w} matrix: dimensions do not match.`);function b(A,V,F){let O=A.rows,H=A.columns;if(O===V&&H===F)return A;{let J=St.zeros(V,F);return J=J.setSubMatrix(A,0,0),J}}let I=Math.max(n,m),E=Math.max(a,w);t=b(t,I,E),o=b(o,I,E);function z(A,V,F,O){if(F<=512||O<=512)return A.mmul(V);F%2===1&&O%2===1?(A=b(A,F+1,O+1),V=b(V,F+1,O+1)):F%2===1?(A=b(A,F+1,O),V=b(V,F+1,O)):O%2===1&&(A=b(A,F,O+1),V=b(V,F,O+1));let H=parseInt(A.rows/2,10),J=parseInt(A.columns/2,10),P=A.subMatrix(0,H-1,0,J-1),K=V.subMatrix(0,H-1,0,J-1),G=A.subMatrix(0,H-1,J,A.columns-1),ot=V.subMatrix(0,H-1,J,V.columns-1),it=A.subMatrix(H,A.rows-1,0,J-1),et=V.subMatrix(H,V.rows-1,0,J-1),mt=A.subMatrix(H,A.rows-1,J,A.columns-1),tt=V.subMatrix(H,V.rows-1,J,V.columns-1),C=z(St.add(P,mt),St.add(K,tt),H,J),_=z(St.add(it,mt),K,H,J),Q=z(P,St.sub(ot,tt),H,J),B=z(mt,St.sub(et,K),H,J),wt=z(St.add(P,G),tt,H,J),bt=z(St.sub(it,P),St.add(K,ot),H,J),pt=z(St.sub(G,mt),St.add(et,tt),H,J),ft=St.add(C,B);ft.sub(wt),ft.add(pt);let Lt=St.add(Q,wt),Ct=St.add(_,B),Ht=St.sub(C,_);Ht.add(Q),Ht.add(bt);let $t=St.zeros(2*ft.rows,2*ft.columns);return $t=$t.setSubMatrix(ft,0,0),$t=$t.setSubMatrix(Lt,ft.rows,0),$t=$t.setSubMatrix(Ct,0,ft.columns),$t=$t.setSubMatrix(Ht,ft.rows,ft.columns),$t.subMatrix(0,F-1,0,O-1)}return z(t,o,I,E)}scaleRows(o={}){if(typeof o!="object")throw new TypeError("options must be an object");let{min:t=0,max:n=1}=o;if(!Number.isFinite(t))throw new TypeError("min must be a number");if(!Number.isFinite(n))throw new TypeError("max must be a number");if(t>=n)throw new RangeError("min must be smaller than max");let a=new Y(this.rows,this.columns);for(let m=0;m<this.rows;m++){let w=this.getRow(m);w.length>0&&M(w,{min:t,max:n,output:w}),a.setRow(m,w)}return a}scaleColumns(o={}){if(typeof o!="object")throw new TypeError("options must be an object");let{min:t=0,max:n=1}=o;if(!Number.isFinite(t))throw new TypeError("min must be a number");if(!Number.isFinite(n))throw new TypeError("max must be a number");if(t>=n)throw new RangeError("min must be smaller than max");let a=new Y(this.rows,this.columns);for(let m=0;m<this.columns;m++){let w=this.getColumn(m);w.length&&M(w,{min:t,max:n,output:w}),a.setColumn(m,w)}return a}flipRows(){let o=Math.ceil(this.columns/2);for(let t=0;t<this.rows;t++)for(let n=0;n<o;n++){let a=this.get(t,n),m=this.get(t,this.columns-1-n);this.set(t,n,m),this.set(t,this.columns-1-n,a)}return this}flipColumns(){let o=Math.ceil(this.rows/2);for(let t=0;t<this.columns;t++)for(let n=0;n<o;n++){let a=this.get(n,t),m=this.get(this.rows-1-n,t);this.set(n,t,m),this.set(this.rows-1-n,t,a)}return this}kroneckerProduct(o){o=Y.checkMatrix(o);let t=this.rows,n=this.columns,a=o.rows,m=o.columns,w=new Y(t*a,n*m);for(let b=0;b<t;b++)for(let I=0;I<n;I++)for(let E=0;E<a;E++)for(let z=0;z<m;z++)w.set(a*b+E,m*I+z,this.get(b,I)*o.get(E,z));return w}kroneckerSum(o){if(o=Y.checkMatrix(o),!this.isSquare()||!o.isSquare())throw new Error("Kronecker Sum needs two Square Matrices");let t=this.rows,n=o.rows,a=this.kroneckerProduct(Y.eye(n,n)),m=Y.eye(t,t).kroneckerProduct(o);return a.add(m)}transpose(){let o=new Y(this.columns,this.rows);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)o.set(n,t,this.get(t,n));return o}sortRows(o=be){for(let t=0;t<this.rows;t++)this.setRow(t,this.getRow(t).sort(o));return this}sortColumns(o=be){for(let t=0;t<this.columns;t++)this.setColumn(t,this.getColumn(t).sort(o));return this}subMatrix(o,t,n,a){q(this,o,t,n,a);let m=new Y(t-o+1,a-n+1);for(let w=o;w<=t;w++)for(let b=n;b<=a;b++)m.set(w-o,b-n,this.get(w,b));return m}subMatrixRow(o,t,n){if(t===void 0&&(t=0),n===void 0&&(n=this.columns-1),t>n||t<0||t>=this.columns||n<0||n>=this.columns)throw new RangeError("Argument out of range");let a=new Y(o.length,n-t+1);for(let m=0;m<o.length;m++)for(let w=t;w<=n;w++){if(o[m]<0||o[m]>=this.rows)throw new RangeError(`Row index out of range: ${o[m]}`);a.set(m,w-t,this.get(o[m],w))}return a}subMatrixColumn(o,t,n){if(t===void 0&&(t=0),n===void 0&&(n=this.rows-1),t>n||t<0||t>=this.rows||n<0||n>=this.rows)throw new RangeError("Argument out of range");let a=new Y(n-t+1,o.length);for(let m=0;m<o.length;m++)for(let w=t;w<=n;w++){if(o[m]<0||o[m]>=this.columns)throw new RangeError(`Column index out of range: ${o[m]}`);a.set(w-t,m,this.get(w,o[m]))}return a}setSubMatrix(o,t,n){if(o=Y.checkMatrix(o),o.isEmpty())return this;let a=t+o.rows-1,m=n+o.columns-1;q(this,t,a,n,m);for(let w=0;w<o.rows;w++)for(let b=0;b<o.columns;b++)this.set(t+w,n+b,o.get(w,b));return this}concat(o,t="row"){switch(o=Y.checkMatrix(o),t){case"row":{if(this.columns!==o.columns)throw new RangeError("both matrices must have the same number of columns");let n=new Y(this.rows+o.rows,this.columns);return n.setSubMatrix(this,0,0),n.setSubMatrix(o,this.rows,0),n}case"column":{if(this.rows!==o.rows)throw new RangeError("both matrices must have the same number of rows");let n=new Y(this.rows,this.columns+o.columns);return n.setSubMatrix(this,0,0),n.setSubMatrix(o,0,this.columns),n}default:throw new Error(`invalid option: ${t}`)}}selection(o,t){$(this,o),S(this,t);let n=new Y(o.length,t.length);for(let a=0;a<o.length;a++){let m=o[a];for(let w=0;w<t.length;w++){let b=t[w];n.set(a,w,this.get(m,b))}}return n}trace(){let o=Math.min(this.rows,this.columns),t=0;for(let n=0;n<o;n++)t+=this.get(n,n);return t}clone(){return this.constructor.copy(this,new Y(this.rows,this.columns))}static copy(o,t){for(let[n,a,m]of o.entries())t.set(n,a,m);return t}sum(o){switch(o){case"row":return Z(this);case"column":return nt(this);case void 0:return st(this);default:throw new Error(`invalid option: ${o}`)}}product(o){switch(o){case"row":return Et(this);case"column":return Rt(this);case void 0:return X(this);default:throw new Error(`invalid option: ${o}`)}}mean(o){let t=this.sum(o);switch(o){case"row":{for(let n=0;n<this.rows;n++)t[n]/=this.columns;return t}case"column":{for(let n=0;n<this.columns;n++)t[n]/=this.rows;return t}case void 0:return t/this.size;default:throw new Error(`invalid option: ${o}`)}}variance(o,t={}){if(typeof o=="object"&&(t=o,o=void 0),typeof t!="object")throw new TypeError("options must be an object");let{unbiased:n=!0,mean:a=this.mean(o)}=t;if(typeof n!="boolean")throw new TypeError("unbiased must be a boolean");switch(o){case"row":{if(!p(a))throw new TypeError("mean must be an array");return dt(this,n,a)}case"column":{if(!p(a))throw new TypeError("mean must be an array");return Mt(this,n,a)}case void 0:{if(typeof a!="number")throw new TypeError("mean must be a number");return vt(this,n,a)}default:throw new Error(`invalid option: ${o}`)}}standardDeviation(o,t){typeof o=="object"&&(t=o,o=void 0);let n=this.variance(o,t);if(o===void 0)return Math.sqrt(n);for(let a=0;a<n.length;a++)n[a]=Math.sqrt(n[a]);return n}center(o,t={}){if(typeof o=="object"&&(t=o,o=void 0),typeof t!="object")throw new TypeError("options must be an object");let{center:n=this.mean(o)}=t;switch(o){case"row":{if(!p(n))throw new TypeError("center must be an array");return Dt(this,n),this}case"column":{if(!p(n))throw new TypeError("center must be an array");return Wt(this,n),this}case void 0:{if(typeof n!="number")throw new TypeError("center must be a number");return Ut(this,n),this}default:throw new Error(`invalid option: ${o}`)}}scale(o,t={}){if(typeof o=="object"&&(t=o,o=void 0),typeof t!="object")throw new TypeError("options must be an object");let n=t.scale;switch(o){case"row":{if(n===void 0)n=At(this);else if(!p(n))throw new TypeError("scale must be an array");return _t(this,n),this}case"column":{if(n===void 0)n=zt(this);else if(!p(n))throw new TypeError("scale must be an array");return Yt(this,n),this}case void 0:{if(n===void 0)n=de(this);else if(typeof n!="number")throw new TypeError("scale must be a number");return je(this,n),this}default:throw new Error(`invalid option: ${o}`)}}toString(o){return e(this,o)}[Symbol.iterator](){return this.entries()}*entries(){for(let o=0;o<this.rows;o++)for(let t=0;t<this.columns;t++)yield[o,t,this.get(o,t)]}*values(){for(let o=0;o<this.rows;o++)for(let t=0;t<this.columns;t++)yield this.get(o,t)}};gt.prototype.klass="Matrix",typeof Symbol<"u"&&(gt.prototype[Symbol.for("nodejs.util.inspect.custom")]=v);function be(l,o){return l-o}function rr(l){return l.every(o=>typeof o=="number")}gt.random=gt.rand,gt.randomInt=gt.randInt,gt.diagonal=gt.diag,gt.prototype.diagonal=gt.prototype.diag,gt.identity=gt.eye,gt.prototype.negate=gt.prototype.neg,gt.prototype.tensorProduct=gt.prototype.kroneckerProduct;var Y=class hn extends gt{data;#t(o,t){if(this.data=[],Number.isInteger(t)&&t>=0)for(let n=0;n<o;n++)this.data.push(new Float64Array(t));else throw new TypeError("nColumns must be a positive integer");this.rows=o,this.columns=t}constructor(o,t){if(super(),hn.isMatrix(o))this.#t(o.rows,o.columns),hn.copy(o,this);else if(Number.isInteger(o)&&o>=0)this.#t(o,t);else if(p(o)){let n=o;if(o=n.length,t=o?n[0].length:0,typeof t!="number")throw new TypeError("Data must be a 2D array with at least one element");this.data=[];for(let a=0;a<o;a++){if(n[a].length!==t)throw new RangeError("Inconsistent array dimensions");if(!rr(n[a]))throw new TypeError("Input data contains non-numeric values");this.data.push(Float64Array.from(n[a]))}this.rows=o,this.columns=t}else throw new TypeError("First argument must be a positive number or an array")}set(o,t,n){return this.data[o][t]=n,this}get(o,t){return this.data[o][t]}removeRow(o){return g(this,o),this.data.splice(o,1),this.rows-=1,this}addRow(o,t){return t===void 0&&(t=o,o=this.rows),g(this,o,!0),t=Float64Array.from(k(this,t)),this.data.splice(o,0,t),this.rows+=1,this}removeColumn(o){y(this,o);for(let t=0;t<this.rows;t++){let n=new Float64Array(this.columns-1);for(let a=0;a<o;a++)n[a]=this.data[t][a];for(let a=o+1;a<this.columns;a++)n[a-1]=this.data[t][a];this.data[t]=n}return this.columns-=1,this}addColumn(o,t){typeof t>"u"&&(t=o,o=this.columns),y(this,o,!0),t=N(this,t);for(let n=0;n<this.rows;n++){let a=new Float64Array(this.columns+1),m=0;for(;m<o;m++)a[m]=this.data[n][m];for(a[m++]=t[n];m<this.columns+1;m++)a[m]=this.data[n][m-1];this.data[n]=a}return this.columns+=1,this}};f(gt,Y);var Te=class pn extends gt{#t;get size(){return this.#t.size}get rows(){return this.#t.rows}get columns(){return this.#t.columns}get diagonalSize(){return this.rows}static isSymmetricMatrix(o){return Y.isMatrix(o)&&o.klassType==="SymmetricMatrix"}static zeros(o){return new this(o)}static ones(o){return new this(o).fill(1)}constructor(o){if(super(),Y.isMatrix(o)){if(!o.isSymmetric())throw new TypeError("not symmetric data");this.#t=Y.copy(o,new Y(o.rows,o.rows))}else if(Number.isInteger(o)&&o>=0)this.#t=new Y(o,o);else if(this.#t=new Y(o),!this.isSymmetric())throw new TypeError("not symmetric data")}clone(){let o=new pn(this.diagonalSize);for(let[t,n,a]of this.upperRightEntries())o.set(t,n,a);return o}toMatrix(){return new Y(this)}get(o,t){return this.#t.get(o,t)}set(o,t,n){return this.#t.set(o,t,n),this.#t.set(t,o,n),this}removeCross(o){return this.#t.removeRow(o),this.#t.removeColumn(o),this}addCross(o,t){t===void 0&&(t=o,o=this.diagonalSize);let n=t.slice();return n.splice(o,1),this.#t.addRow(o,n),this.#t.addColumn(o,t),this}applyMask(o){if(o.length!==this.diagonalSize)throw new RangeError("Mask size do not match with matrix size");let t=[];for(let[n,a]of o.entries())a||t.push(n);t.reverse();for(let n of t)this.removeCross(n);return this}toCompact(){let{diagonalSize:o}=this,t=new Array(o*(o+1)/2);for(let n=0,a=0,m=0;m<t.length;m++)t[m]=this.get(a,n),++n>=o&&(n=++a);return t}static fromCompact(o){let t=o.length,n=(Math.sqrt(8*t+1)-1)/2;if(!Number.isInteger(n))throw new TypeError(`This array is not a compact representation of a Symmetric Matrix, ${JSON.stringify(o)}`);let a=new pn(n);for(let m=0,w=0,b=0;b<t;b++)a.set(m,w,o[b]),++m>=n&&(m=++w);return a}*upperRightEntries(){for(let o=0,t=0;o<this.diagonalSize;void 0){let n=this.get(o,t);yield[o,t,n],++t>=this.diagonalSize&&(t=++o)}}*upperRightValues(){for(let o=0,t=0;o<this.diagonalSize;void 0)yield this.get(o,t),++t>=this.diagonalSize&&(t=++o)}};Te.prototype.klassType="SymmetricMatrix";var Sn=class Un extends Te{static isDistanceMatrix(o){return Te.isSymmetricMatrix(o)&&o.klassSubType==="DistanceMatrix"}constructor(o){if(super(o),!this.isDistance())throw new TypeError("Provided arguments do no produce a distance matrix")}set(o,t,n){return o===t&&(n=0),super.set(o,t,n)}addCross(o,t){return t===void 0&&(t=o,o=this.diagonalSize),t=t.slice(),t[o]=0,super.addCross(o,t)}toSymmetricMatrix(){return new Te(this)}clone(){let o=new Un(this.diagonalSize);for(let[t,n,a]of this.upperRightEntries())t!==n&&o.set(t,n,a);return o}toCompact(){let{diagonalSize:o}=this,t=(o-1)*o/2,n=new Array(t);for(let a=1,m=0,w=0;w<n.length;w++)n[w]=this.get(m,a),++a>=o&&(a=++m+1);return n}static fromCompact(o){let t=o.length;if(t===0)return new this(0);let n=(Math.sqrt(8*t+1)+1)/2;if(!Number.isInteger(n))throw new TypeError(`This array is not a compact representation of a DistanceMatrix, ${JSON.stringify(o)}`);let a=new this(n);for(let m=1,w=0,b=0;b<t;b++)a.set(m,w,o[b]),++m>=n&&(m=++w+1);return a}};Sn.prototype.klassSubType="DistanceMatrix";var oe=class extends gt{constructor(l,o,t){super(),this.matrix=l,this.rows=o,this.columns=t}},or=class extends oe{constructor(l,o){y(l,o),super(l,l.rows,1),this.column=o}set(l,o,t){return this.matrix.set(l,this.column,t),this}get(l){return this.matrix.get(l,this.column)}},sr=class extends oe{constructor(l,o){S(l,o),super(l,l.rows,o.length),this.columnIndices=o}set(l,o,t){return this.matrix.set(l,this.columnIndices[o],t),this}get(l,o){return this.matrix.get(l,this.columnIndices[o])}},ir=class extends oe{constructor(l){super(l,l.rows,l.columns)}set(l,o,t){return this.matrix.set(l,this.columns-o-1,t),this}get(l,o){return this.matrix.get(l,this.columns-o-1)}},ar=class extends oe{constructor(l){super(l,l.rows,l.columns)}set(l,o,t){return this.matrix.set(this.rows-l-1,o,t),this}get(l,o){return this.matrix.get(this.rows-l-1,o)}},lr=class extends oe{constructor(l,o){g(l,o),super(l,1,l.columns),this.row=o}set(l,o,t){return this.matrix.set(this.row,o,t),this}get(l,o){return this.matrix.get(this.row,o)}},ur=class extends oe{constructor(l,o){$(l,o),super(l,o.length,l.columns),this.rowIndices=o}set(l,o,t){return this.matrix.set(this.rowIndices[l],o,t),this}get(l,o){return this.matrix.get(this.rowIndices[l],o)}},Je=class extends oe{constructor(l,o,t){$(l,o),S(l,t),super(l,o.length,t.length),this.rowIndices=o,this.columnIndices=t}set(l,o,t){return this.matrix.set(this.rowIndices[l],this.columnIndices[o],t),this}get(l,o){return this.matrix.get(this.rowIndices[l],this.columnIndices[o])}},cr=class extends oe{constructor(l,o,t,n,a){q(l,o,t,n,a),super(l,t-o+1,a-n+1),this.startRow=o,this.startColumn=n}set(l,o,t){return this.matrix.set(this.startRow+l,this.startColumn+o,t),this}get(l,o){return this.matrix.get(this.startRow+l,this.startColumn+o)}},dr=class extends oe{constructor(l){super(l,l.columns,l.rows)}set(l,o,t){return this.matrix.set(o,l,t),this}get(l,o){return this.matrix.get(o,l)}},In=class extends gt{constructor(l,o={}){let{rows:t=1}=o;if(l.length%t!==0)throw new Error("the data length is not divisible by the number of rows");super(),this.rows=t,this.columns=l.length/t,this.data=l}set(l,o,t){let n=this._calculateIndex(l,o);return this.data[n]=t,this}get(l,o){let t=this._calculateIndex(l,o);return this.data[t]}_calculateIndex(l,o){return l*this.columns+o}},Pt=class extends gt{constructor(l){super(),this.data=l,this.rows=l.length,this.columns=l[0].length}set(l,o,t){return this.data[l][o]=t,this}get(l,o){return this.data[l][o]}};function fr(l,o){if(p(l))return l[0]&&p(l[0])?new Pt(l):new In(l,o);throw new Error("the argument is not an array")}var Ke=class{constructor(l){l=Pt.checkMatrix(l);let o=l.clone(),t=o.rows,n=o.columns,a=new Float64Array(t),m=1,w,b,I,E,z,A,V,F,O;for(w=0;w<t;w++)a[w]=w;for(F=new Float64Array(t),b=0;b<n;b++){for(w=0;w<t;w++)F[w]=o.get(w,b);for(w=0;w<t;w++){for(O=Math.min(w,b),z=0,I=0;I<O;I++)z+=o.get(w,I)*F[I];F[w]-=z,o.set(w,b,F[w])}for(E=b,w=b+1;w<t;w++)Math.abs(F[w])>Math.abs(F[E])&&(E=w);if(E!==b){for(I=0;I<n;I++)A=o.get(E,I),o.set(E,I,o.get(b,I)),o.set(b,I,A);V=a[E],a[E]=a[b],a[b]=V,m=-m}if(b<t&&o.get(b,b)!==0)for(w=b+1;w<t;w++)o.set(w,b,o.get(w,b)/o.get(b,b))}this.LU=o,this.pivotVector=a,this.pivotSign=m}isSingular(){let l=this.LU,o=l.columns;for(let t=0;t<o;t++)if(l.get(t,t)===0)return!0;return!1}solve(l){l=Y.checkMatrix(l);let o=this.LU;if(o.rows!==l.rows)throw new Error("Invalid matrix dimensions");if(this.isSingular())throw new Error("LU matrix is singular");let t=l.columns,n=l.subMatrixRow(this.pivotVector,0,t-1),a=o.columns,m,w,b;for(b=0;b<a;b++)for(m=b+1;m<a;m++)for(w=0;w<t;w++)n.set(m,w,n.get(m,w)-n.get(b,w)*o.get(m,b));for(b=a-1;b>=0;b--){for(w=0;w<t;w++)n.set(b,w,n.get(b,w)/o.get(b,b));for(m=0;m<b;m++)for(w=0;w<t;w++)n.set(m,w,n.get(m,w)-n.get(b,w)*o.get(m,b))}return n}get determinant(){let l=this.LU;if(!l.isSquare())throw new Error("Matrix must be square");let o=this.pivotSign,t=l.columns;for(let n=0;n<t;n++)o*=l.get(n,n);return o}get lowerTriangularMatrix(){let l=this.LU,o=l.rows,t=l.columns,n=new Y(o,t);for(let a=0;a<o;a++)for(let m=0;m<t;m++)a>m?n.set(a,m,l.get(a,m)):a===m?n.set(a,m,1):n.set(a,m,0);return n}get upperTriangularMatrix(){let l=this.LU,o=l.rows,t=l.columns,n=new Y(o,t);for(let a=0;a<o;a++)for(let m=0;m<t;m++)a<=m?n.set(a,m,l.get(a,m)):n.set(a,m,0);return n}get pivotPermutationVector(){return Array.from(this.pivotVector)}};function an(l){let o=l.data,t=l.rows;for(let n=0;n<t;n++){let a=o[n];for(let m=n+1;m<t;m++){let w=a[m];a[m]=o[m][n],o[m][n]=w}}return l}function se(l,o){let t=0;return Math.abs(l)>Math.abs(o)?(t=o/l,Math.abs(l)*Math.sqrt(1+t*t)):o!==0?(t=l/o,Math.abs(o)*Math.sqrt(1+t*t)):0}var ln=class{constructor(l){l=Pt.checkMatrix(l);let o=l.clone(),t=l.rows,n=l.columns,a=new Float64Array(n),m,w,b,I;for(b=0;b<n;b++){let E=0;for(m=b;m<t;m++)E=se(E,o.get(m,b));if(E!==0){for(o.get(b,b)<0&&(E=-E),m=b;m<t;m++)o.set(m,b,o.get(m,b)/E);for(o.set(b,b,o.get(b,b)+1),w=b+1;w<n;w++){for(I=0,m=b;m<t;m++)I+=o.get(m,b)*o.get(m,w);for(I=-I/o.get(b,b),m=b;m<t;m++)o.set(m,w,o.get(m,w)+I*o.get(m,b))}}a[b]=-E}this.QR=o,this.Rdiag=a}solve(l){l=Y.checkMatrix(l);let o=this.QR,t=o.rows;if(l.rows!==t)throw new Error("Matrix row dimensions must agree");if(!this.isFullRank())throw new Error("Matrix is rank deficient");let n=l.columns,a=l.clone(),m=o.columns,w,b,I,E;for(I=0;I<m;I++)for(b=0;b<n;b++){for(E=0,w=I;w<t;w++)E+=o.get(w,I)*a.get(w,b);for(E=-E/o.get(I,I),w=I;w<t;w++)a.set(w,b,a.get(w,b)+E*o.get(w,I))}for(I=m-1;I>=0;I--){for(b=0;b<n;b++)a.set(I,b,a.get(I,b)/this.Rdiag[I]);for(w=0;w<I;w++)for(b=0;b<n;b++)a.set(w,b,a.get(w,b)-a.get(I,b)*o.get(w,I))}return a.subMatrix(0,m-1,0,n-1)}isFullRank(){let l=this.QR.columns;for(let o=0;o<l;o++)if(this.Rdiag[o]===0)return!1;return!0}get upperTriangularMatrix(){let l=this.QR,o=l.columns,t=new Y(o,o),n,a;for(n=0;n<o;n++)for(a=0;a<o;a++)n<a?t.set(n,a,l.get(n,a)):n===a?t.set(n,a,this.Rdiag[n]):t.set(n,a,0);return t}get orthogonalMatrix(){let l=this.QR,o=l.rows,t=l.columns,n=new Y(o,t),a,m,w,b;for(w=t-1;w>=0;w--){for(a=0;a<o;a++)n.set(a,w,0);for(n.set(w,w,1),m=w;m<t;m++)if(l.get(w,w)!==0){for(b=0,a=w;a<o;a++)b+=l.get(a,w)*n.get(a,m);for(b=-b/l.get(w,w),a=w;a<o;a++)n.set(a,m,n.get(a,m)+b*l.get(a,w))}}return n}},Ee=class{constructor(l,o={}){if(l=Pt.checkMatrix(l),l.isEmpty())throw new Error("Matrix must be non-empty");let t=l.rows,n=l.columns,{computeLeftSingularVectors:a=!0,computeRightSingularVectors:m=!0,autoTranspose:w=!1}=o,b=!!a,I=!!m,E=!1,z;if(t<n)if(!w)console.warn("Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose"),z=l.transpose();else{z=l.clone(),t=l.columns,n=l.rows,E=!0;let C=b;b=I,I=C}else z=l.transpose();let A=Math.min(t,n),V=Math.min(t+1,n),F=new Float64Array(V),O=new Y(A,t),H=new Y(n,n),J=new Float64Array(n),P=new Float64Array(t),K=new Float64Array(V);for(let C=0;C<V;C++)K[C]=C;let G=Math.min(t-1,n),ot=Math.max(0,Math.min(n-2,t)),it=Math.max(G,ot);for(let C=0;C<it;C++){if(C<G){F[C]=0;for(let _=C;_<t;_++)F[C]=se(F[C],z.get(C,_));if(F[C]!==0){z.get(C,C)<0&&(F[C]=-F[C]);for(let _=C;_<t;_++)z.set(C,_,z.get(C,_)/F[C]);z.set(C,C,z.get(C,C)+1)}F[C]=-F[C]}for(let _=C+1;_<n;_++){if(C<G&&F[C]!==0){let Q=0;for(let B=C;B<t;B++)Q+=z.get(C,B)*z.get(_,B);Q=-Q/z.get(C,C);for(let B=C;B<t;B++)z.set(_,B,z.get(_,B)+Q*z.get(C,B))}J[_]=z.get(_,C)}if(b&&C<G)for(let _=C;_<t;_++)O.set(C,_,z.get(C,_));if(C<ot){J[C]=0;for(let _=C+1;_<n;_++)J[C]=se(J[C],J[_]);if(J[C]!==0){J[C+1]<0&&(J[C]=0-J[C]);for(let _=C+1;_<n;_++)J[_]/=J[C];J[C+1]+=1}if(J[C]=-J[C],C+1<t&&J[C]!==0){for(let _=C+1;_<t;_++)P[_]=0;for(let _=C+1;_<t;_++)for(let Q=C+1;Q<n;Q++)P[_]+=J[Q]*z.get(Q,_);for(let _=C+1;_<n;_++){let Q=-J[_]/J[C+1];for(let B=C+1;B<t;B++)z.set(_,B,z.get(_,B)+Q*P[B])}}if(I)for(let _=C+1;_<n;_++)H.set(C,_,J[_])}}let et=Math.min(n,t+1);if(G<n&&(F[G]=z.get(G,G)),t<et&&(F[et-1]=0),ot+1<et&&(J[ot]=z.get(et-1,ot)),J[et-1]=0,b){for(let C=G;C<A;C++){for(let _=0;_<t;_++)O.set(C,_,0);O.set(C,C,1)}for(let C=G-1;C>=0;C--)if(F[C]!==0){for(let _=C+1;_<A;_++){let Q=0;for(let B=C;B<t;B++)Q+=O.get(C,B)*O.get(_,B);Q=-Q/O.get(C,C);for(let B=C;B<t;B++)O.set(_,B,O.get(_,B)+Q*O.get(C,B))}for(let _=C;_<t;_++)O.set(C,_,-O.get(C,_));O.set(C,C,1+O.get(C,C));for(let _=0;_<C-1;_++)O.set(C,_,0)}else{for(let _=0;_<t;_++)O.set(C,_,0);O.set(C,C,1)}}if(I)for(let C=n-1;C>=0;C--){if(C<ot&&J[C]!==0)for(let _=C+1;_<n;_++){let Q=0;for(let B=C+1;B<n;B++)Q+=H.get(C,B)*H.get(_,B);Q=-Q/H.get(C,C+1);for(let B=C+1;B<n;B++)H.set(_,B,H.get(_,B)+Q*H.get(C,B))}for(let _=0;_<n;_++)H.set(C,_,0);H.set(C,C,1)}let mt=et-1,tt=Number.EPSILON;for(;et>0;){let C,_;for(C=et-2;C>=-1&&C!==-1;C--){let Q=Number.MIN_VALUE+tt*Math.abs(F[C]+Math.abs(F[C+1]));if(Math.abs(J[C])<=Q||Number.isNaN(J[C])){J[C]=0;break}}if(C===et-2)_=4;else{let Q;for(Q=et-1;Q>=C&&Q!==C;Q--){let B=(Q!==et?Math.abs(J[Q]):0)+(Q!==C+1?Math.abs(J[Q-1]):0);if(Math.abs(F[Q])<=tt*B){F[Q]=0;break}}Q===C?_=3:Q===et-1?_=1:(_=2,C=Q)}switch(C++,_){case 1:{let Q=J[et-2];J[et-2]=0;for(let B=et-2;B>=C;B--){let wt=se(F[B],Q),bt=F[B]/wt,pt=Q/wt;if(F[B]=wt,B!==C&&(Q=-pt*J[B-1],J[B-1]=bt*J[B-1]),I)for(let ft=0;ft<n;ft++)wt=bt*H.get(B,ft)+pt*H.get(et-1,ft),H.set(et-1,ft,-pt*H.get(B,ft)+bt*H.get(et-1,ft)),H.set(B,ft,wt)}break}case 2:{let Q=J[C-1];J[C-1]=0;for(let B=C;B<et;B++){let wt=se(F[B],Q),bt=F[B]/wt,pt=Q/wt;if(F[B]=wt,Q=-pt*J[B],J[B]=bt*J[B],b)for(let ft=0;ft<t;ft++)wt=bt*O.get(B,ft)+pt*O.get(C-1,ft),O.set(C-1,ft,-pt*O.get(B,ft)+bt*O.get(C-1,ft)),O.set(B,ft,wt)}break}case 3:{let Q=Math.max(Math.abs(F[et-1]),Math.abs(F[et-2]),Math.abs(J[et-2]),Math.abs(F[C]),Math.abs(J[C])),B=F[et-1]/Q,wt=F[et-2]/Q,bt=J[et-2]/Q,pt=F[C]/Q,ft=J[C]/Q,Lt=((wt+B)*(wt-B)+bt*bt)/2,Ct=B*bt*(B*bt),Ht=0;(Lt!==0||Ct!==0)&&(Lt<0?Ht=0-Math.sqrt(Lt*Lt+Ct):Ht=Math.sqrt(Lt*Lt+Ct),Ht=Ct/(Lt+Ht));let $t=(pt+B)*(pt-B)+Ht,ie=pt*ft;for(let at=C;at<et-1;at++){let Nt=se($t,ie);Nt===0&&(Nt=Number.MIN_VALUE);let Ot=$t/Nt,Vt=ie/Nt;if(at!==C&&(J[at-1]=Nt),$t=Ot*F[at]+Vt*J[at],J[at]=Ot*J[at]-Vt*F[at],ie=Vt*F[at+1],F[at+1]=Ot*F[at+1],I)for(let kt=0;kt<n;kt++)Nt=Ot*H.get(at,kt)+Vt*H.get(at+1,kt),H.set(at+1,kt,-Vt*H.get(at,kt)+Ot*H.get(at+1,kt)),H.set(at,kt,Nt);if(Nt=se($t,ie),Nt===0&&(Nt=Number.MIN_VALUE),Ot=$t/Nt,Vt=ie/Nt,F[at]=Nt,$t=Ot*J[at]+Vt*F[at+1],F[at+1]=-Vt*J[at]+Ot*F[at+1],ie=Vt*J[at+1],J[at+1]=Ot*J[at+1],b&&at<t-1)for(let kt=0;kt<t;kt++)Nt=Ot*O.get(at,kt)+Vt*O.get(at+1,kt),O.set(at+1,kt,-Vt*O.get(at,kt)+Ot*O.get(at+1,kt)),O.set(at,kt,Nt)}J[et-2]=$t;break}case 4:{if(F[C]<=0&&(F[C]=F[C]<0?-F[C]:0,I))for(let Q=0;Q<=mt;Q++)H.set(C,Q,-H.get(C,Q));for(;C<mt&&!(F[C]>=F[C+1]);){let Q=F[C];if(F[C]=F[C+1],F[C+1]=Q,I&&C<n-1)for(let B=0;B<n;B++)Q=H.get(C+1,B),H.set(C+1,B,H.get(C,B)),H.set(C,B,Q);if(b&&C<t-1)for(let B=0;B<t;B++)Q=O.get(C+1,B),O.set(C+1,B,O.get(C,B)),O.set(C,B,Q);C++}et--;break}}}if(O=O.isSquare()?an(O):O.transpose(),H=an(H),E){let C=H;H=O,O=C}this.m=t,this.n=n,this.s=F,this.U=O,this.V=H}solve(l){let o=l,t=this.threshold,n=this.s.length,a=Y.zeros(n,n);for(let A=0;A<n;A++)Math.abs(this.s[A])<=t?a.set(A,A,0):a.set(A,A,1/this.s[A]);let m=this.U,w=this.rightSingularVectors,b=w.mmul(a),I=w.rows,E=m.rows,z=Y.zeros(I,E);for(let A=0;A<I;A++)for(let V=0;V<E;V++){let F=0;for(let O=0;O<n;O++)F+=b.get(A,O)*m.get(V,O);z.set(A,V,F)}return z.mmul(o)}solveForDiagonal(l){return this.solve(Y.diag(l))}inverse(){let l=this.V,o=this.threshold,t=l.rows,n=l.columns,a=new Y(t,this.s.length);for(let E=0;E<t;E++)for(let z=0;z<n;z++)Math.abs(this.s[z])>o&&a.set(E,z,l.get(E,z)/this.s[z]);let m=this.U,w=m.rows,b=m.columns,I=new Y(t,w);for(let E=0;E<t;E++)for(let z=0;z<w;z++){let A=0;for(let V=0;V<b;V++)A+=a.get(E,V)*m.get(z,V);I.set(E,z,A)}return I}get condition(){return this.s[0]/this.s[Math.min(this.m,this.n)-1]}get norm2(){return this.s[0]}get rank(){let l=Math.max(this.m,this.n)*this.s[0]*Number.EPSILON,o=0,t=this.s;for(let n=0,a=t.length;n<a;n++)t[n]>l&&o++;return o}get diagonal(){return Array.from(this.s)}get threshold(){return Number.EPSILON/2*Math.max(this.m,this.n)*this.s[0]}get leftSingularVectors(){return this.U}get rightSingularVectors(){return this.V}get diagonalMatrix(){return Y.diag(this.s)}};function mr(l,o=!1){return l=Pt.checkMatrix(l),o?new Ee(l).inverse():En(l,Y.eye(l.rows))}function En(l,o,t=!1){return l=Pt.checkMatrix(l),o=Pt.checkMatrix(o),t?new Ee(l).solve(o):l.isSquare()?new Ke(l).solve(o):new ln(l).solve(o)}function We(l){if(l=Y.checkMatrix(l),l.isSquare()){if(l.columns===0)return 1;let o,t,n,a;if(l.columns===2)return o=l.get(0,0),t=l.get(0,1),n=l.get(1,0),a=l.get(1,1),o*a-t*n;if(l.columns===3){let m,w,b;return m=new Je(l,[1,2],[1,2]),w=new Je(l,[1,2],[0,2]),b=new Je(l,[1,2],[0,1]),o=l.get(0,0),t=l.get(0,1),n=l.get(0,2),o*We(m)-t*We(w)+n*We(b)}else return new Ke(l).determinant}else throw Error("determinant can only be calculated for a square matrix")}function hr(l,o){let t=[];for(let n=0;n<l;n++)n!==o&&t.push(n);return t}function pr(l,o,t,n=1e-9,a=1e-9){if(l>a)return new Array(o.rows+1).fill(0);{let m=o.addRow(t,[0]);for(let w=0;w<m.rows;w++)Math.abs(m.get(w,0))<n&&m.set(w,0,0);return m.to1DArray()}}function gr(l,o={}){let{thresholdValue:t=1e-9,thresholdError:n=1e-9}=o;l=Y.checkMatrix(l);let a=l.rows,m=new Y(a,a);for(let w=0;w<a;w++){let b=Y.columnVector(l.getRow(w)),I=l.subMatrixRow(hr(a,w)).transpose(),E=new Ee(I).solve(b),z=Y.abs(b).max()||1,A=Y.sub(b,I.mmul(E)).abs().max()/z;m.setRow(w,pr(A,E,w,t,n))}return m}function wr(l,o=Number.EPSILON){if(l=Y.checkMatrix(l),l.isEmpty())return l.transpose();let t=new Ee(l,{autoTranspose:!0}),n=t.leftSingularVectors,a=t.rightSingularVectors,m=t.diagonal,w=o*Math.max(l.rows,l.columns)*m[0];for(let b=0;b<m.length;b++)Math.abs(m[b])>w?m[b]=1/m[b]:m[b]=0;return a.mmul(Y.diag(m).mmul(n.transpose()))}function vr(l,o=l,t={}){l=new Y(l);let n=!1;if(typeof o=="object"&&!Y.isMatrix(o)&&!p(o)?(t=o,o=l,n=!0):o=new Y(o),l.rows!==o.rows)throw new TypeError("Both matrices must have the same number of rows");let{center:a=!0}=t;a&&(l=l.center("column"),n||(o=o.center("column")));let m=l.transposeMultiply(o);for(let w=0;w<m.rows;w++)for(let b=0;b<m.columns;b++)m.set(w,b,m.get(w,b)*(1/(l.rows-1)));return m}function br(l,o=l,t={}){l=new Y(l);let n=!1;if(typeof o=="object"&&!Y.isMatrix(o)&&!p(o)?(t=o,o=l,n=!0):o=new Y(o),l.rows!==o.rows)throw new TypeError("Both matrices must have the same number of rows");let{center:a=!0,scale:m=!0}=t;a&&(l.center("column"),n||o.center("column")),m&&(l.scale("column"),n||o.scale("column"));let w=l.standardDeviation("column",{unbiased:!0}),b=n?w:o.standardDeviation("column",{unbiased:!0}),I=l.transposeMultiply(o);for(let E=0;E<I.rows;E++)for(let z=0;z<I.columns;z++)I.set(E,z,I.get(E,z)*(1/(w[E]*b[z]))*(1/(l.rows-1)));return I}var Rn=class{constructor(l,o={}){let{assumeSymmetric:t=!1}=o;if(l=Pt.checkMatrix(l),!l.isSquare())throw new Error("Matrix is not a square matrix");if(l.isEmpty())throw new Error("Matrix must be non-empty");let n=l.columns,a=new Y(n,n),m=new Float64Array(n),w=new Float64Array(n),b=l,I,E,z=!1;if(t?z=!0:z=l.isSymmetric(),z){for(I=0;I<n;I++)for(E=0;E<n;E++)a.set(E,I,b.get(I,E));yr(n,w,m,a),xr(n,w,m,a),an(a)}else{let A=new Y(n,n),V=new Float64Array(n);for(E=0;E<n;E++)for(I=0;I<n;I++)A.set(I,E,b.get(I,E));Mr(n,A,V,a),$r(n,w,m,a,A)}this.n=n,this.e=w,this.d=m,this.V=a}get realEigenvalues(){return Array.from(this.d)}get imaginaryEigenvalues(){return Array.from(this.e)}get eigenvectorMatrix(){return this.V}get diagonalMatrix(){let l=this.n,o=this.e,t=this.d,n=new Y(l,l),a,m;for(a=0;a<l;a++){for(m=0;m<l;m++)n.set(a,m,0);n.set(a,a,t[a]),o[a]>0?n.set(a,a+1,o[a]):o[a]<0&&n.set(a,a-1,o[a])}return n}};function yr(l,o,t,n){let a,m,w,b,I,E,z,A;for(I=0;I<l;I++)t[I]=n.get(I,l-1);for(b=l-1;b>0;b--){for(A=0,w=0,E=0;E<b;E++)A=A+Math.abs(t[E]);if(A===0)for(o[b]=t[b-1],I=0;I<b;I++)t[I]=n.get(I,b-1),n.set(I,b,0),n.set(b,I,0);else{for(E=0;E<b;E++)t[E]/=A,w+=t[E]*t[E];for(a=t[b-1],m=Math.sqrt(w),a>0&&(m=-m),o[b]=A*m,w=w-a*m,t[b-1]=a-m,I=0;I<b;I++)o[I]=0;for(I=0;I<b;I++){for(a=t[I],n.set(b,I,a),m=o[I]+n.get(I,I)*a,E=I+1;E<=b-1;E++)m+=n.get(I,E)*t[E],o[E]+=n.get(I,E)*a;o[I]=m}for(a=0,I=0;I<b;I++)o[I]/=w,a+=o[I]*t[I];for(z=a/(w+w),I=0;I<b;I++)o[I]-=z*t[I];for(I=0;I<b;I++){for(a=t[I],m=o[I],E=I;E<=b-1;E++)n.set(I,E,n.get(I,E)-(a*o[E]+m*t[E]));t[I]=n.get(I,b-1),n.set(I,b,0)}}t[b]=w}for(b=0;b<l-1;b++){if(n.set(b,l-1,n.get(b,b)),n.set(b,b,1),w=t[b+1],w!==0){for(E=0;E<=b;E++)t[E]=n.get(b+1,E)/w;for(I=0;I<=b;I++){for(m=0,E=0;E<=b;E++)m+=n.get(b+1,E)*n.get(I,E);for(E=0;E<=b;E++)n.set(I,E,n.get(I,E)-m*t[E])}}for(E=0;E<=b;E++)n.set(b+1,E,0)}for(I=0;I<l;I++)t[I]=n.get(I,l-1),n.set(I,l-1,0);n.set(l-1,l-1,1),o[0]=0}function xr(l,o,t,n){let a,m,w,b,I,E,z,A,V,F,O,H,J,P,K,G;for(w=1;w<l;w++)o[w-1]=o[w];o[l-1]=0;let ot=0,it=0,et=Number.EPSILON;for(E=0;E<l;E++){for(it=Math.max(it,Math.abs(t[E])+Math.abs(o[E])),z=E;z<l&&!(Math.abs(o[z])<=et*it);)z++;if(z>E)do{for(a=t[E],A=(t[E+1]-a)/(2*o[E]),V=se(A,1),A<0&&(V=-V),t[E]=o[E]/(A+V),t[E+1]=o[E]*(A+V),F=t[E+1],m=a-t[E],w=E+2;w<l;w++)t[w]-=m;for(ot=ot+m,A=t[z],O=1,H=O,J=O,P=o[E+1],K=0,G=0,w=z-1;w>=E;w--)for(J=H,H=O,G=K,a=O*o[w],m=O*A,V=se(A,o[w]),o[w+1]=K*V,K=o[w]/V,O=A/V,A=O*t[w]-K*a,t[w+1]=m+K*(O*a+K*t[w]),I=0;I<l;I++)m=n.get(w+1,I),n.set(w+1,I,K*n.get(w,I)+O*m),n.set(w,I,O*n.get(w,I)-K*m);A=-K*G*J*P*o[E]/F,o[E]=K*A,t[E]=O*A}while(Math.abs(o[E])>et*it);t[E]=t[E]+ot,o[E]=0}for(w=0;w<l-1;w++){for(I=w,A=t[w],b=w+1;b<l;b++)t[b]<A&&(I=b,A=t[b]);if(I!==w)for(t[I]=t[w],t[w]=A,b=0;b<l;b++)A=n.get(w,b),n.set(w,b,n.get(I,b)),n.set(I,b,A)}}function Mr(l,o,t,n){let a=0,m=l-1,w,b,I,E,z,A,V;for(A=a+1;A<=m-1;A++){for(V=0,E=A;E<=m;E++)V=V+Math.abs(o.get(E,A-1));if(V!==0){for(I=0,E=m;E>=A;E--)t[E]=o.get(E,A-1)/V,I+=t[E]*t[E];for(b=Math.sqrt(I),t[A]>0&&(b=-b),I=I-t[A]*b,t[A]=t[A]-b,z=A;z<l;z++){for(w=0,E=m;E>=A;E--)w+=t[E]*o.get(E,z);for(w=w/I,E=A;E<=m;E++)o.set(E,z,o.get(E,z)-w*t[E])}for(E=0;E<=m;E++){for(w=0,z=m;z>=A;z--)w+=t[z]*o.get(E,z);for(w=w/I,z=A;z<=m;z++)o.set(E,z,o.get(E,z)-w*t[z])}t[A]=V*t[A],o.set(A,A-1,V*b)}}for(E=0;E<l;E++)for(z=0;z<l;z++)n.set(E,z,E===z?1:0);for(A=m-1;A>=a+1;A--)if(o.get(A,A-1)!==0){for(E=A+1;E<=m;E++)t[E]=o.get(E,A-1);for(z=A;z<=m;z++){for(b=0,E=A;E<=m;E++)b+=t[E]*n.get(E,z);for(b=b/t[A]/o.get(A,A-1),E=A;E<=m;E++)n.set(E,z,n.get(E,z)+b*t[E])}}}function $r(l,o,t,n,a){let m=l-1,w=0,b=l-1,I=Number.EPSILON,E=0,z=0,A=0,V=0,F=0,O=0,H=0,J=0,P,K,G,ot,it,et,mt,tt,C,_,Q,B,wt,bt,pt;for(P=0;P<l;P++)for((P<w||P>b)&&(t[P]=a.get(P,P),o[P]=0),K=Math.max(P-1,0);K<l;K++)z=z+Math.abs(a.get(P,K));for(;m>=w;){for(ot=m;ot>w&&(O=Math.abs(a.get(ot-1,ot-1))+Math.abs(a.get(ot,ot)),O===0&&(O=z),!(Math.abs(a.get(ot,ot-1))<I*O));)ot--;if(ot===m)a.set(m,m,a.get(m,m)+E),t[m]=a.get(m,m),o[m]=0,m--,J=0;else if(ot===m-1){if(mt=a.get(m,m-1)*a.get(m-1,m),A=(a.get(m-1,m-1)-a.get(m,m))/2,V=A*A+mt,H=Math.sqrt(Math.abs(V)),a.set(m,m,a.get(m,m)+E),a.set(m-1,m-1,a.get(m-1,m-1)+E),tt=a.get(m,m),V>=0){for(H=A>=0?A+H:A-H,t[m-1]=tt+H,t[m]=t[m-1],H!==0&&(t[m]=tt-mt/H),o[m-1]=0,o[m]=0,tt=a.get(m,m-1),O=Math.abs(tt)+Math.abs(H),A=tt/O,V=H/O,F=Math.sqrt(A*A+V*V),A=A/F,V=V/F,K=m-1;K<l;K++)H=a.get(m-1,K),a.set(m-1,K,V*H+A*a.get(m,K)),a.set(m,K,V*a.get(m,K)-A*H);for(P=0;P<=m;P++)H=a.get(P,m-1),a.set(P,m-1,V*H+A*a.get(P,m)),a.set(P,m,V*a.get(P,m)-A*H);for(P=w;P<=b;P++)H=n.get(P,m-1),n.set(P,m-1,V*H+A*n.get(P,m)),n.set(P,m,V*n.get(P,m)-A*H)}else t[m-1]=tt+A,t[m]=tt+A,o[m-1]=H,o[m]=-H;m=m-2,J=0}else{if(tt=a.get(m,m),C=0,mt=0,ot<m&&(C=a.get(m-1,m-1),mt=a.get(m,m-1)*a.get(m-1,m)),J===10){for(E+=tt,P=w;P<=m;P++)a.set(P,P,a.get(P,P)-tt);O=Math.abs(a.get(m,m-1))+Math.abs(a.get(m-1,m-2)),tt=C=.75*O,mt=-.4375*O*O}if(J===30&&(O=(C-tt)/2,O=O*O+mt,O>0)){for(O=Math.sqrt(O),C<tt&&(O=-O),O=tt-mt/((C-tt)/2+O),P=w;P<=m;P++)a.set(P,P,a.get(P,P)-O);E+=O,tt=C=mt=.964}for(J=J+1,it=m-2;it>=ot&&(H=a.get(it,it),F=tt-H,O=C-H,A=(F*O-mt)/a.get(it+1,it)+a.get(it,it+1),V=a.get(it+1,it+1)-H-F-O,F=a.get(it+2,it+1),O=Math.abs(A)+Math.abs(V)+Math.abs(F),A=A/O,V=V/O,F=F/O,!(it===ot||Math.abs(a.get(it,it-1))*(Math.abs(V)+Math.abs(F))<I*(Math.abs(A)*(Math.abs(a.get(it-1,it-1))+Math.abs(H)+Math.abs(a.get(it+1,it+1))))));)it--;for(P=it+2;P<=m;P++)a.set(P,P-2,0),P>it+2&&a.set(P,P-3,0);for(G=it;G<=m-1&&(bt=G!==m-1,G!==it&&(A=a.get(G,G-1),V=a.get(G+1,G-1),F=bt?a.get(G+2,G-1):0,tt=Math.abs(A)+Math.abs(V)+Math.abs(F),tt!==0&&(A=A/tt,V=V/tt,F=F/tt)),tt!==0);G++)if(O=Math.sqrt(A*A+V*V+F*F),A<0&&(O=-O),O!==0){for(G!==it?a.set(G,G-1,-O*tt):ot!==it&&a.set(G,G-1,-a.get(G,G-1)),A=A+O,tt=A/O,C=V/O,H=F/O,V=V/A,F=F/A,K=G;K<l;K++)A=a.get(G,K)+V*a.get(G+1,K),bt&&(A=A+F*a.get(G+2,K),a.set(G+2,K,a.get(G+2,K)-A*H)),a.set(G,K,a.get(G,K)-A*tt),a.set(G+1,K,a.get(G+1,K)-A*C);for(P=0;P<=Math.min(m,G+3);P++)A=tt*a.get(P,G)+C*a.get(P,G+1),bt&&(A=A+H*a.get(P,G+2),a.set(P,G+2,a.get(P,G+2)-A*F)),a.set(P,G,a.get(P,G)-A),a.set(P,G+1,a.get(P,G+1)-A*V);for(P=w;P<=b;P++)A=tt*n.get(P,G)+C*n.get(P,G+1),bt&&(A=A+H*n.get(P,G+2),n.set(P,G+2,n.get(P,G+2)-A*F)),n.set(P,G,n.get(P,G)-A),n.set(P,G+1,n.get(P,G+1)-A*V)}}}if(z!==0){for(m=l-1;m>=0;m--)if(A=t[m],V=o[m],V===0)for(ot=m,a.set(m,m,1),P=m-1;P>=0;P--){for(mt=a.get(P,P)-A,F=0,K=ot;K<=m;K++)F=F+a.get(P,K)*a.get(K,m);if(o[P]<0)H=mt,O=F;else if(ot=P,o[P]===0?a.set(P,m,mt!==0?-F/mt:-F/(I*z)):(tt=a.get(P,P+1),C=a.get(P+1,P),V=(t[P]-A)*(t[P]-A)+o[P]*o[P],et=(tt*O-H*F)/V,a.set(P,m,et),a.set(P+1,m,Math.abs(tt)>Math.abs(H)?(-F-mt*et)/tt:(-O-C*et)/H)),et=Math.abs(a.get(P,m)),I*et*et>1)for(K=P;K<=m;K++)a.set(K,m,a.get(K,m)/et)}else if(V<0)for(ot=m-1,Math.abs(a.get(m,m-1))>Math.abs(a.get(m-1,m))?(a.set(m-1,m-1,V/a.get(m,m-1)),a.set(m-1,m,-(a.get(m,m)-A)/a.get(m,m-1))):(pt=Ye(0,-a.get(m-1,m),a.get(m-1,m-1)-A,V),a.set(m-1,m-1,pt[0]),a.set(m-1,m,pt[1])),a.set(m,m-1,0),a.set(m,m,1),P=m-2;P>=0;P--){for(_=0,Q=0,K=ot;K<=m;K++)_=_+a.get(P,K)*a.get(K,m-1),Q=Q+a.get(P,K)*a.get(K,m);if(mt=a.get(P,P)-A,o[P]<0)H=mt,F=_,O=Q;else if(ot=P,o[P]===0?(pt=Ye(-_,-Q,mt,V),a.set(P,m-1,pt[0]),a.set(P,m,pt[1])):(tt=a.get(P,P+1),C=a.get(P+1,P),B=(t[P]-A)*(t[P]-A)+o[P]*o[P]-V*V,wt=(t[P]-A)*2*V,B===0&&wt===0&&(B=I*z*(Math.abs(mt)+Math.abs(V)+Math.abs(tt)+Math.abs(C)+Math.abs(H))),pt=Ye(tt*F-H*_+V*Q,tt*O-H*Q-V*_,B,wt),a.set(P,m-1,pt[0]),a.set(P,m,pt[1]),Math.abs(tt)>Math.abs(H)+Math.abs(V)?(a.set(P+1,m-1,(-_-mt*a.get(P,m-1)+V*a.get(P,m))/tt),a.set(P+1,m,(-Q-mt*a.get(P,m)-V*a.get(P,m-1))/tt)):(pt=Ye(-F-C*a.get(P,m-1),-O-C*a.get(P,m),H,V),a.set(P+1,m-1,pt[0]),a.set(P+1,m,pt[1]))),et=Math.max(Math.abs(a.get(P,m-1)),Math.abs(a.get(P,m))),I*et*et>1)for(K=P;K<=m;K++)a.set(K,m-1,a.get(K,m-1)/et),a.set(K,m,a.get(K,m)/et)}for(P=0;P<l;P++)if(P<w||P>b)for(K=P;K<l;K++)n.set(P,K,a.get(P,K));for(K=l-1;K>=w;K--)for(P=w;P<=b;P++){for(H=0,G=w;G<=Math.min(K,b);G++)H=H+n.get(P,G)*a.get(G,K);n.set(P,K,H)}}}function Ye(l,o,t,n){let a,m;return Math.abs(t)>Math.abs(n)?(a=n/t,m=t+a*n,[(l+a*o)/m,(o-a*l)/m]):(a=t/n,m=n+a*t,[(a*l+o)/m,(a*o-l)/m])}var Nn=class{constructor(l){if(l=Pt.checkMatrix(l),!l.isSymmetric())throw new Error("Matrix is not symmetric");let o=l,t=o.rows,n=new Y(t,t),a=!0,m,w,b;for(w=0;w<t;w++){let I=0;for(b=0;b<w;b++){let E=0;for(m=0;m<b;m++)E+=n.get(b,m)*n.get(w,m);E=(o.get(w,b)-E)/n.get(b,b),n.set(w,b,E),I=I+E*E}for(I=o.get(w,w)-I,a&&=I>0,n.set(w,w,Math.sqrt(Math.max(I,0))),b=w+1;b<t;b++)n.set(w,b,0)}this.L=n,this.positiveDefinite=a}isPositiveDefinite(){return this.positiveDefinite}solve(l){l=Pt.checkMatrix(l);let o=this.L,t=o.rows;if(l.rows!==t)throw new Error("Matrix dimensions do not match");if(this.isPositiveDefinite()===!1)throw new Error("Matrix is not positive definite");let n=l.columns,a=l.clone(),m,w,b;for(b=0;b<t;b++)for(w=0;w<n;w++){for(m=0;m<b;m++)a.set(b,w,a.get(b,w)-a.get(m,w)*o.get(b,m));a.set(b,w,a.get(b,w)/o.get(b,b))}for(b=t-1;b>=0;b--)for(w=0;w<n;w++){for(m=b+1;m<t;m++)a.set(b,w,a.get(b,w)-a.get(m,w)*o.get(m,b));a.set(b,w,a.get(b,w)/o.get(b,b))}return a}get lowerTriangularMatrix(){return this.L}},qn=class{constructor(l,o={}){l=Pt.checkMatrix(l);let{Y:t}=o,{scaleScores:n=!1,maxIterations:a=1e3,terminationCriteria:m=1e-10}=o,w;if(t){if(p(t)&&typeof t[0]=="number"?t=Y.columnVector(t):t=Pt.checkMatrix(t),t.rows!==l.rows)throw new Error("Y should have the same number of rows as X");w=t.getColumnVector(0)}else w=l.getColumnVector(0);let b=1,I,E,z,A;for(let V=0;V<a&&b>m;V++)z=l.transpose().mmul(w).div(w.transpose().mmul(w).get(0,0)),z=z.div(z.norm()),I=l.mmul(z).div(z.transpose().mmul(z).get(0,0)),V>0&&(b=I.clone().sub(A).pow(2).sum()),A=I.clone(),t?(E=t.transpose().mmul(I).div(I.transpose().mmul(I).get(0,0)),E=E.div(E.norm()),w=t.mmul(E).div(E.transpose().mmul(E).get(0,0))):w=I;if(t){let V=l.transpose().mmul(I).div(I.transpose().mmul(I).get(0,0));V=V.div(V.norm());let F=l.clone().sub(I.clone().mmul(V.transpose())),O=w.transpose().mmul(I).div(I.transpose().mmul(I).get(0,0)),H=t.clone().sub(I.clone().mulS(O.get(0,0)).mmul(E.transpose()));this.t=I,this.p=V.transpose(),this.w=z.transpose(),this.q=E,this.u=w,this.s=I.transpose().mmul(I),this.xResidual=F,this.yResidual=H,this.betas=O}else this.w=z.transpose(),this.s=I.transpose().mmul(I).sqrt(),n?this.t=I.clone().div(this.s.get(0,0)):this.t=I,this.xResidual=l.sub(I.mmul(z.transpose()))}};h.AbstractMatrix=gt,h.CHO=Nn,h.CholeskyDecomposition=Nn,h.DistanceMatrix=Sn,h.EVD=Rn,h.EigenvalueDecomposition=Rn,h.LU=Ke,h.LuDecomposition=Ke,h.Matrix=Y,h.MatrixColumnSelectionView=sr,h.MatrixColumnView=or,h.MatrixFlipColumnView=ir,h.MatrixFlipRowView=ar,h.MatrixRowSelectionView=ur,h.MatrixRowView=lr,h.MatrixSelectionView=Je,h.MatrixSubView=cr,h.MatrixTransposeView=dr,h.NIPALS=qn,h.Nipals=qn,h.QR=ln,h.QrDecomposition=ln,h.SVD=Ee,h.SingularValueDecomposition=Ee,h.SymmetricMatrix=Te,h.WrapperMatrix1D=In,h.WrapperMatrix2D=Pt,h.correlation=br,h.covariance=vr,h.default=Y,h.determinant=We,h.inverse=mr,h.linearDependencies=gr,h.pseudoInverse=wr,h.solve=En,h.wrap=fr}),Br=Fn((h,d)=>{(function(p,s){typeof h=="object"?d.exports=s():typeof define=="function"&&define.amd?define(s):p.jStat=s()})(h,function(){var p=(function(s,u){var M=Array.prototype.concat,x=Array.prototype.slice,R=Object.prototype.toString;function v($,S){var q=$>S?$:S;return s.pow(10,17-~~(s.log(q>0?q:-q)*s.LOG10E))}var e=Array.isArray||function($){return R.call($)==="[object Array]"};function r($){return R.call($)==="[object Function]"}function i($){return typeof $=="number"?$-$===0:!1}function c($){return M.apply([],$)}function f(){return new f._init(arguments)}f.fn=f.prototype,f._init=function($){if(e($[0]))if(e($[0][0])){r($[1])&&($[0]=f.map($[0],$[1]));for(var S=0;S<$[0].length;S++)this[S]=$[0][S];this.length=$[0].length}else this[0]=r($[1])?f.map($[0],$[1]):$[0],this.length=1;else if(i($[0]))this[0]=f.seq.apply(null,$),this.length=1;else{if($[0]instanceof f)return f($[0].toArray());this[0]=[],this.length=1}return this},f._init.prototype=f.prototype,f._init.constructor=f,f.utils={calcRdx:v,isArray:e,isFunction:r,isNumber:i,toVector:c},f._random_fn=s.random,f.setRandom=function($){if(typeof $!="function")throw new TypeError("fn is not a function");f._random_fn=$},f.extend=function($){var S,q;if(arguments.length===1){for(q in $)f[q]=$[q];return this}for(S=1;S<arguments.length;S++)for(q in arguments[S])$[q]=arguments[S][q];return $},f.rows=function($){return $.length||1},f.cols=function($){return $[0].length||1},f.dimensions=function($){return{rows:f.rows($),cols:f.cols($)}},f.row=function($,S){return e(S)?S.map(function(q){return f.row($,q)}):$[S]},f.rowa=function($,S){return f.row($,S)},f.col=function($,S){if(e(S)){var q=f.arange($.length).map(function(){return new Array(S.length)});return S.forEach(function(W,Z){f.arange($.length).forEach(function(nt){q[nt][Z]=$[nt][W]})}),q}for(var T=new Array($.length),L=0;L<$.length;L++)T[L]=[$[L][S]];return T},f.cola=function($,S){return f.col($,S).map(function(q){return q[0]})},f.diag=function($){for(var S=f.rows($),q=new Array(S),T=0;T<S;T++)q[T]=[$[T][T]];return q},f.antidiag=function($){for(var S=f.rows($)-1,q=new Array(S),T=0;S>=0;S--,T++)q[T]=[$[T][S]];return q},f.transpose=function($){var S=[],q,T,L,W,Z;for(e($[0])||($=[$]),T=$.length,L=$[0].length,Z=0;Z<L;Z++){for(q=new Array(T),W=0;W<T;W++)q[W]=$[W][Z];S.push(q)}return S.length===1?S[0]:S},f.map=function($,S,q){var T,L,W,Z,nt;for(e($[0])||($=[$]),L=$.length,W=$[0].length,Z=q?$:new Array(L),T=0;T<L;T++)for(Z[T]||(Z[T]=new Array(W)),nt=0;nt<W;nt++)Z[T][nt]=S($[T][nt],T,nt);return Z.length===1?Z[0]:Z},f.cumreduce=function($,S,q){var T,L,W,Z,nt;for(e($[0])||($=[$]),L=$.length,W=$[0].length,Z=q?$:new Array(L),T=0;T<L;T++)for(Z[T]||(Z[T]=new Array(W)),W>0&&(Z[T][0]=$[T][0]),nt=1;nt<W;nt++)Z[T][nt]=S(Z[T][nt-1],$[T][nt]);return Z.length===1?Z[0]:Z},f.alter=function($,S){return f.map($,S,!0)},f.create=function($,S,q){var T=new Array($),L,W;for(r(S)&&(q=S,S=$),L=0;L<$;L++)for(T[L]=new Array(S),W=0;W<S;W++)T[L][W]=q(L,W);return T};function g(){return 0}f.zeros=function($,S){return i(S)||(S=$),f.create($,S,g)};function y(){return 1}f.ones=function($,S){return i(S)||(S=$),f.create($,S,y)},f.rand=function($,S){return i(S)||(S=$),f.create($,S,f._random_fn)};function k($,S){return $===S?1:0}f.identity=function($,S){return i(S)||(S=$),f.create($,S,k)},f.symmetric=function($){var S=$.length,q,T;if($.length!==$[0].length)return!1;for(q=0;q<S;q++)for(T=0;T<S;T++)if($[T][q]!==$[q][T])return!1;return!0},f.clear=function($){return f.alter($,g)},f.seq=function($,S,q,T){r(T)||(T=!1);var L=[],W=v($,S),Z=(S*W-$*W)/((q-1)*W),nt=$,st;for(st=0;nt<=S&&st<q;st++,nt=($*W+Z*W*st)/W)L.push(T?T(nt,st):nt);return L},f.arange=function($,S,q){var T=[],L;if(q=q||1,S===u&&(S=$,$=0),$===S||q===0)return[];if($<S&&q<0)return[];if($>S&&q>0)return[];if(q>0)for(L=$;L<S;L+=q)T.push(L);else for(L=$;L>S;L+=q)T.push(L);return T},f.slice=(function(){function $(q,T,L,W){var Z,nt=[],st=q.length;if(T===u&&L===u&&W===u)return f.copy(q);if(T=T||0,L=L||q.length,T=T>=0?T:st+T,L=L>=0?L:st+L,W=W||1,T===L||W===0)return[];if(T<L&&W<0)return[];if(T>L&&W>0)return[];if(W>0)for(Z=T;Z<L;Z+=W)nt.push(q[Z]);else for(Z=T;Z>L;Z+=W)nt.push(q[Z]);return nt}function S(q,T){var L,W;if(T=T||{},i(T.row)){if(i(T.col))return q[T.row][T.col];var Z=f.rowa(q,T.row);return L=T.col||{},$(Z,L.start,L.end,L.step)}if(i(T.col)){var nt=f.cola(q,T.col);return W=T.row||{},$(nt,W.start,W.end,W.step)}W=T.row||{},L=T.col||{};var st=$(q,W.start,W.end,W.step);return st.map(function(Et){return $(Et,L.start,L.end,L.step)})}return S})(),f.sliceAssign=function($,S,q){var T,L;if(i(S.row)){if(i(S.col))return $[S.row][S.col]=q;S.col=S.col||{},S.col.start=S.col.start||0,S.col.end=S.col.end||$[0].length,S.col.step=S.col.step||1,T=f.arange(S.col.start,s.min($.length,S.col.end),S.col.step);var W=S.row;return T.forEach(function(nt,st){$[W][nt]=q[st]}),$}if(i(S.col)){S.row=S.row||{},S.row.start=S.row.start||0,S.row.end=S.row.end||$.length,S.row.step=S.row.step||1,L=f.arange(S.row.start,s.min($[0].length,S.row.end),S.row.step);var Z=S.col;return L.forEach(function(nt,st){$[nt][Z]=q[st]}),$}return q[0].length===u&&(q=[q]),S.row.start=S.row.start||0,S.row.end=S.row.end||$.length,S.row.step=S.row.step||1,S.col.start=S.col.start||0,S.col.end=S.col.end||$[0].length,S.col.step=S.col.step||1,L=f.arange(S.row.start,s.min($.length,S.row.end),S.row.step),T=f.arange(S.col.start,s.min($[0].length,S.col.end),S.col.step),L.forEach(function(nt,st){T.forEach(function(Et,Rt){$[nt][Et]=q[st][Rt]})}),$},f.diagonal=function($){var S=f.zeros($.length,$.length);return $.forEach(function(q,T){S[T][T]=q}),S},f.copy=function($){return $.map(function(S){return i(S)?S:S.map(function(q){return q})})};var N=f.prototype;return N.length=0,N.push=Array.prototype.push,N.sort=Array.prototype.sort,N.splice=Array.prototype.splice,N.slice=Array.prototype.slice,N.toArray=function(){return this.length>1?x.call(this):x.call(this)[0]},N.map=function($,S){return f(f.map(this,$,S))},N.cumreduce=function($,S){return f(f.cumreduce(this,$,S))},N.alter=function($){return f.alter(this,$),this},(function($){for(var S=0;S<$.length;S++)(function(q){N[q]=function(T){var L=this,W;return T?(setTimeout(function(){T.call(L,N[q].call(L))}),this):(W=f[q](this),e(W)?f(W):W)}})($[S])})("transpose clear symmetric rows cols dimensions diag antidiag".split(" ")),(function($){for(var S=0;S<$.length;S++)(function(q){N[q]=function(T,L){var W=this;return L?(setTimeout(function(){L.call(W,N[q].call(W,T))}),this):f(f[q](this,T))}})($[S])})("row col".split(" ")),(function($){for(var S=0;S<$.length;S++)(function(q){N[q]=function(){return f(f[q].apply(null,arguments))}})($[S])})("create zeros ones rand identity".split(" ")),f})(Math);return(function(s,u){var M=s.utils.isFunction;function x(e,r){return e-r}function R(e,r,i){return u.max(r,u.min(e,i))}s.sum=function(e){for(var r=0,i=e.length;--i>=0;)r+=e[i];return r},s.sumsqrd=function(e){for(var r=0,i=e.length;--i>=0;)r+=e[i]*e[i];return r},s.sumsqerr=function(e){for(var r=s.mean(e),i=0,c=e.length,f;--c>=0;)f=e[c]-r,i+=f*f;return i},s.sumrow=function(e){for(var r=0,i=e.length;--i>=0;)r+=e[i];return r},s.product=function(e){for(var r=1,i=e.length;--i>=0;)r*=e[i];return r},s.min=function(e){for(var r=e[0],i=0;++i<e.length;)e[i]<r&&(r=e[i]);return r},s.max=function(e){for(var r=e[0],i=0;++i<e.length;)e[i]>r&&(r=e[i]);return r},s.unique=function(e){for(var r={},i=[],c=0;c<e.length;c++)r[e[c]]||(r[e[c]]=!0,i.push(e[c]));return i},s.mean=function(e){return s.sum(e)/e.length},s.meansqerr=function(e){return s.sumsqerr(e)/e.length},s.geomean=function(e){var r=e.map(u.log),i=s.mean(r);return u.exp(i)},s.median=function(e){var r=e.length,i=e.slice().sort(x);return r&1?i[r/2|0]:(i[r/2-1]+i[r/2])/2},s.cumsum=function(e){return s.cumreduce(e,function(r,i){return r+i})},s.cumprod=function(e){return s.cumreduce(e,function(r,i){return r*i})},s.diff=function(e){var r=[],i=e.length,c;for(c=1;c<i;c++)r.push(e[c]-e[c-1]);return r},s.rank=function(e){var r,i=[],c={};for(r=0;r<e.length;r++){var f=e[r];c[f]?c[f]++:(c[f]=1,i.push(f))}var g=i.sort(x),y={},k=1;for(r=0;r<g.length;r++){var f=g[r],N=c[f],$=k,S=k+N-1,q=($+S)/2;y[f]=q,k+=N}return e.map(function(T){return y[T]})},s.mode=function(e){var r=e.length,i=e.slice().sort(x),c=1,f=0,g=0,y=[],k;for(k=0;k<r;k++)i[k]===i[k+1]?c++:(c>f?(y=[i[k]],f=c,g=0):c===f&&(y.push(i[k]),g++),c=1);return g===0?y[0]:y},s.range=function(e){return s.max(e)-s.min(e)},s.variance=function(e,r){return s.sumsqerr(e)/(e.length-(r?1:0))},s.pooledvariance=function(e){var r=e.reduce(function(c,f){return c+s.sumsqerr(f)},0),i=e.reduce(function(c,f){return c+f.length},0);return r/(i-e.length)},s.deviation=function(e){for(var r=s.mean(e),i=e.length,c=new Array(i),f=0;f<i;f++)c[f]=e[f]-r;return c},s.stdev=function(e,r){return u.sqrt(s.variance(e,r))},s.pooledstdev=function(e){return u.sqrt(s.pooledvariance(e))},s.meandev=function(e){for(var r=s.mean(e),i=[],c=e.length-1;c>=0;c--)i.push(u.abs(e[c]-r));return s.mean(i)},s.meddev=function(e){for(var r=s.median(e),i=[],c=e.length-1;c>=0;c--)i.push(u.abs(e[c]-r));return s.median(i)},s.coeffvar=function(e){return s.stdev(e)/s.mean(e)},s.quartiles=function(e){var r=e.length,i=e.slice().sort(x);return[i[u.round(r/4)-1],i[u.round(r/2)-1],i[u.round(r*3/4)-1]]},s.quantiles=function(e,r,i,c){var f=e.slice().sort(x),g=[r.length],y=e.length,k,N,$,S,q,T;for(typeof i>"u"&&(i=3/8),typeof c>"u"&&(c=3/8),k=0;k<r.length;k++)N=r[k],$=i+N*(1-i-c),S=y*N+$,q=u.floor(R(S,1,y-1)),T=R(S-q,0,1),g[k]=(1-T)*f[q-1]+T*f[q];return g},s.percentile=function(e,r,i){var c=e.slice().sort(x),f=r*(c.length+(i?1:-1))+(i?0:1),g=parseInt(f),y=f-g;return g+1<c.length?c[g-1]+y*(c[g]-c[g-1]):c[g-1]},s.percentileOfScore=function(e,r,i){var c=0,f=e.length,g=!1,y,k;for(i==="strict"&&(g=!0),k=0;k<f;k++)y=e[k],(g&&y<r||!g&&y<=r)&&c++;return c/f},s.histogram=function(e,r){r=r||4;var i=s.min(e),c=(s.max(e)-i)/r,f=e.length,g=[],y;for(y=0;y<r;y++)g[y]=0;for(y=0;y<f;y++)g[u.min(u.floor((e[y]-i)/c),r-1)]+=1;return g},s.covariance=function(e,r){var i=s.mean(e),c=s.mean(r),f=e.length,g=new Array(f),y;for(y=0;y<f;y++)g[y]=(e[y]-i)*(r[y]-c);return s.sum(g)/(f-1)},s.corrcoeff=function(e,r){return s.covariance(e,r)/s.stdev(e,1)/s.stdev(r,1)},s.spearmancoeff=function(e,r){return e=s.rank(e),r=s.rank(r),s.corrcoeff(e,r)},s.stanMoment=function(e,r){for(var i=s.mean(e),c=s.stdev(e),f=e.length,g=0,y=0;y<f;y++)g+=u.pow((e[y]-i)/c,r);return g/e.length},s.skewness=function(e){return s.stanMoment(e,3)},s.kurtosis=function(e){return s.stanMoment(e,4)-3};var v=s.prototype;(function(e){for(var r=0;r<e.length;r++)(function(i){v[i]=function(c,f){var g=[],y=0,k=this;if(M(c)&&(f=c,c=!1),f)return setTimeout(function(){f.call(k,v[i].call(k,c))}),this;if(this.length>1){for(k=c===!0?this:this.transpose();y<k.length;y++)g[y]=s[i](k[y]);return g}return s[i](this[0],c)}})(e[r])})("cumsum cumprod".split(" ")),(function(e){for(var r=0;r<e.length;r++)(function(i){v[i]=function(c,f){var g=[],y=0,k=this;if(M(c)&&(f=c,c=!1),f)return setTimeout(function(){f.call(k,v[i].call(k,c))}),this;if(this.length>1){for(i!=="sumrow"&&(k=c===!0?this:this.transpose());y<k.length;y++)g[y]=s[i](k[y]);return c===!0?s[i](s.utils.toVector(g)):g}return s[i](this[0],c)}})(e[r])})("sum sumsqrd sumsqerr sumrow product min max unique mean meansqerr geomean median diff rank mode range variance deviation stdev meandev meddev coeffvar quartiles histogram skewness kurtosis".split(" ")),(function(e){for(var r=0;r<e.length;r++)(function(i){v[i]=function(){var c=[],f=0,g=this,y=Array.prototype.slice.call(arguments),k;if(M(y[y.length-1])){k=y[y.length-1];var N=y.slice(0,y.length-1);return setTimeout(function(){k.call(g,v[i].apply(g,N))}),this}else{k=void 0;var $=function(S){return s[i].apply(g,[S].concat(y))}}if(this.length>1){for(g=g.transpose();f<g.length;f++)c[f]=$(g[f]);return c}return $(this[0])}})(e[r])})("quantiles percentileOfScore".split(" "))})(p,Math),(function(s,u){s.gammaln=function(M){var x=0,R=[76.18009172947146,-86.50532032941678,24.01409824083091,-1.231739572450155,.001208650973866179,-5395239384953e-18],v=1.000000000190015,e,r,i;for(i=(r=e=M)+5.5,i-=(e+.5)*u.log(i);x<6;x++)v+=R[x]/++r;return u.log(2.5066282746310007*v/e)-i},s.loggam=function(M){var x,R,v,e,r,i,c,f=[.08333333333333333,-.002777777777777778,.0007936507936507937,-.0005952380952380952,.0008417508417508418,-.001917526917526918,.00641025641025641,-.02955065359477124,.1796443723688307,-1.3924322169059];if(x=M,c=0,M==1||M==2)return 0;for(M<=7&&(c=u.floor(7-M),x=M+c),R=1/(x*x),v=2*u.PI,r=f[9],i=8;i>=0;i--)r*=R,r+=f[i];if(e=r/x+.5*u.log(v)+(x-.5)*u.log(x)-x,M<=7)for(i=1;i<=c;i++)e-=u.log(x-1),x-=1;return e},s.gammafn=function(M){var x=[-1.716185138865495,24.76565080557592,-379.80425647094563,629.3311553128184,866.9662027904133,-31451.272968848367,-36144.413418691176,66456.14382024054],R=[-30.8402300119739,315.35062697960416,-1015.1563674902192,-3107.771671572311,22538.11842098015,4755.846277527881,-134659.9598649693,-115132.2596755535],v=!1,e=0,r=0,i=0,c=M,f,g,y,k;if(M>171.6243769536076)return 1/0;if(c<=0)if(k=c%1+36e-17,k)v=(c&1?-1:1)*u.PI/u.sin(u.PI*k),c=1-c;else return 1/0;for(y=c,c<1?g=c++:g=(c-=e=(c|0)-1)-1,f=0;f<8;++f)i=(i+x[f])*g,r=r*g+R[f];if(k=i/r+1,y<c)k/=y;else if(y>c)for(f=0;f<e;++f)k*=c,c++;return v&&(k=v/k),k},s.gammap=function(M,x){return s.lowRegGamma(M,x)*s.gammafn(M)},s.lowRegGamma=function(M,x){var R=s.gammaln(M),v=M,e=1/M,r=e,i=x+1-M,c=1/1e-30,f=1/i,g=f,y=1,k=-~(u.log(M>=1?M:1/M)*8.5+M*.4+17),N;if(x<0||M<=0)return NaN;if(x<M+1){for(;y<=k;y++)e+=r*=x/++v;return e*u.exp(-x+M*u.log(x)-R)}for(;y<=k;y++)N=-y*(y-M),i+=2,f=N*f+i,c=i+N/c,f=1/f,g*=f*c;return 1-g*u.exp(-x+M*u.log(x)-R)},s.factorialln=function(M){return M<0?NaN:s.gammaln(M+1)},s.factorial=function(M){return M<0?NaN:s.gammafn(M+1)},s.combination=function(M,x){return M>170||x>170?u.exp(s.combinationln(M,x)):s.factorial(M)/s.factorial(x)/s.factorial(M-x)},s.combinationln=function(M,x){return s.factorialln(M)-s.factorialln(x)-s.factorialln(M-x)},s.permutation=function(M,x){return s.factorial(M)/s.factorial(M-x)},s.betafn=function(M,x){if(!(M<=0||x<=0))return M+x>170?u.exp(s.betaln(M,x)):s.gammafn(M)*s.gammafn(x)/s.gammafn(M+x)},s.betaln=function(M,x){return s.gammaln(M)+s.gammaln(x)-s.gammaln(M+x)},s.betacf=function(M,x,R){var v=1e-30,e=1,r=x+R,i=x+1,c=x-1,f=1,g=1-r*M/i,y,k,N,$;for(u.abs(g)<v&&(g=v),g=1/g,$=g;e<=100&&(y=2*e,k=e*(R-e)*M/((c+y)*(x+y)),g=1+k*g,u.abs(g)<v&&(g=v),f=1+k/f,u.abs(f)<v&&(f=v),g=1/g,$*=g*f,k=-(x+e)*(r+e)*M/((x+y)*(i+y)),g=1+k*g,u.abs(g)<v&&(g=v),f=1+k/f,u.abs(f)<v&&(f=v),g=1/g,N=g*f,$*=N,!(u.abs(N-1)<3e-7));e++);return $},s.gammapinv=function(M,x){var R=0,v=x-1,e=1e-8,r=s.gammaln(x),i,c,f,g,y,k,N;if(M>=1)return u.max(100,x+100*u.sqrt(x));if(M<=0)return 0;for(x>1?(k=u.log(v),N=u.exp(v*(k-1)-r),y=M<.5?M:1-M,f=u.sqrt(-2*u.log(y)),i=(2.30753+f*.27061)/(1+f*(.99229+f*.04481))-f,M<.5&&(i=-i),i=u.max(.001,x*u.pow(1-1/(9*x)-i/(3*u.sqrt(x)),3))):(f=1-x*(.253+x*.12),M<f?i=u.pow(M/f,1/x):i=1-u.log(1-(M-f)/(1-f)));R<12;R++){if(i<=0)return 0;if(c=s.lowRegGamma(x,i)-M,x>1?f=N*u.exp(-(i-v)+v*(u.log(i)-k)):f=u.exp(-i+v*u.log(i)-r),g=c/f,i-=f=g/(1-.5*u.min(1,g*((x-1)/i-1))),i<=0&&(i=.5*(i+f)),u.abs(f)<e*i)break}return i},s.erf=function(M){var x=[-1.3026537197817094,.6419697923564902,.019476473204185836,-.00956151478680863,-.000946595344482036,.000366839497852761,42523324806907e-18,-20278578112534e-18,-1624290004647e-18,130365583558e-17,15626441722e-18,-85238095915e-18,6529054439e-18,5059343495e-18,-991364156e-18,-227365122e-18,96467911e-18,2394038e-18,-6886027e-18,894487e-18,313092e-18,-112708e-18,381e-18,7106e-18,-1523e-18,-94e-18,121e-18,-28e-18],R=x.length-1,v=!1,e=0,r=0,i,c,f,g;for(M<0&&(M=-M,v=!0),i=2/(2+M),c=4*i-2;R>0;R--)f=e,e=c*e-r+x[R],r=f;return g=i*u.exp(-M*M+.5*(x[0]+c*e)-r),v?g-1:1-g},s.erfc=function(M){return 1-s.erf(M)},s.erfcinv=function(M){var x=0,R,v,e,r;if(M>=2)return-100;if(M<=0)return 100;for(r=M<1?M:2-M,e=u.sqrt(-2*u.log(r/2)),R=-.70711*((2.30753+e*.27061)/(1+e*(.99229+e*.04481))-e);x<2;x++)v=s.erfc(R)-r,R+=v/(1.1283791670955126*u.exp(-R*R)-R*v);return M<1?R:-R},s.ibetainv=function(M,x,R){var v=1e-8,e=x-1,r=R-1,i=0,c,f,g,y,k,N,$,S,q,T,L;if(M<=0)return 0;if(M>=1)return 1;for(x>=1&&R>=1?(g=M<.5?M:1-M,y=u.sqrt(-2*u.log(g)),$=(2.30753+y*.27061)/(1+y*(.99229+y*.04481))-y,M<.5&&($=-$),S=($*$-3)/6,q=2/(1/(2*x-1)+1/(2*R-1)),T=$*u.sqrt(S+q)/q-(1/(2*R-1)-1/(2*x-1))*(S+5/6-2/(3*q)),$=x/(x+R*u.exp(2*T))):(c=u.log(x/(x+R)),f=u.log(R/(x+R)),y=u.exp(x*c)/x,k=u.exp(R*f)/R,T=y+k,M<y/T?$=u.pow(x*T*M,1/x):$=1-u.pow(R*T*(1-M),1/R)),L=-s.gammaln(x)-s.gammaln(R)+s.gammaln(x+R);i<10;i++){if($===0||$===1)return $;if(N=s.ibeta($,x,R)-M,y=u.exp(e*u.log($)+r*u.log(1-$)+L),k=N/y,$-=y=k/(1-.5*u.min(1,k*(e/$-r/(1-$)))),$<=0&&($=.5*($+y)),$>=1&&($=.5*($+y+1)),u.abs(y)<v*$&&i>0)break}return $},s.ibeta=function(M,x,R){var v=M===0||M===1?0:u.exp(s.gammaln(x+R)-s.gammaln(x)-s.gammaln(R)+x*u.log(M)+R*u.log(1-M));return M<0||M>1?!1:M<(x+1)/(x+R+2)?v*s.betacf(M,x,R)/x:1-v*s.betacf(1-M,R,x)/R},s.randn=function(M,x){var R,v,e,r,i;if(x||(x=M),M)return s.create(M,x,function(){return s.randn()});do R=s._random_fn(),v=1.7156*(s._random_fn()-.5),e=R-.449871,r=u.abs(v)+.386595,i=e*e+r*(.196*r-.25472*e);while(i>.27597&&(i>.27846||v*v>-4*u.log(R)*R*R));return v/R},s.randg=function(M,x,R){var v=M,e,r,i,c,f,g;if(R||(R=x),M||(M=1),x)return g=s.zeros(x,R),g.alter(function(){return s.randg(M)}),g;M<1&&(M+=1),e=M-1/3,r=1/u.sqrt(9*e);do{do f=s.randn(),c=1+r*f;while(c<=0);c=c*c*c,i=s._random_fn()}while(i>1-.331*u.pow(f,4)&&u.log(i)>.5*f*f+e*(1-c+u.log(c)));if(M==v)return e*c;do i=s._random_fn();while(i===0);return u.pow(i,1/v)*e*c},(function(M){for(var x=0;x<M.length;x++)(function(R){s.fn[R]=function(){return s(s.map(this,function(v){return s[R](v)}))}})(M[x])})("gammaln gammafn factorial factorialln".split(" ")),(function(M){for(var x=0;x<M.length;x++)(function(R){s.fn[R]=function(){return s(s[R].apply(null,arguments))}})(M[x])})("randn".split(" "))})(p,Math),(function(s,u){(function(e){for(var r=0;r<e.length;r++)(function(i){s[i]=function c(f,g,y){return this instanceof c?(this._a=f,this._b=g,this._c=y,this):new c(f,g,y)},s.fn[i]=function(c,f,g){var y=s[i](c,f,g);return y.data=this,y},s[i].prototype.sample=function(c){var f=this._a,g=this._b,y=this._c;return c?s.alter(c,function(){return s[i].sample(f,g,y)}):s[i].sample(f,g,y)},(function(c){for(var f=0;f<c.length;f++)(function(g){s[i].prototype[g]=function(y){var k=this._a,N=this._b,$=this._c;return!y&&y!==0&&(y=this.data),typeof y!="number"?s.fn.map.call(y,function(S){return s[i][g](S,k,N,$)}):s[i][g](y,k,N,$)}})(c[f])})("pdf cdf inv".split(" ")),(function(c){for(var f=0;f<c.length;f++)(function(g){s[i].prototype[g]=function(){return s[i][g](this._a,this._b,this._c)}})(c[f])})("mean median mode variance".split(" "))})(e[r])})("beta centralF cauchy chisquare exponential gamma invgamma kumaraswamy laplace lognormal noncentralt normal pareto studentt weibull uniform binomial negbin hypgeom poisson triangular tukey arcsine".split(" ")),s.extend(s.beta,{pdf:function(e,r,i){return e>1||e<0?0:r==1&&i==1?1:r<512&&i<512?u.pow(e,r-1)*u.pow(1-e,i-1)/s.betafn(r,i):u.exp((r-1)*u.log(e)+(i-1)*u.log(1-e)-s.betaln(r,i))},cdf:function(e,r,i){return e>1||e<0?(e>1)*1:s.ibeta(e,r,i)},inv:function(e,r,i){return s.ibetainv(e,r,i)},mean:function(e,r){return e/(e+r)},median:function(e,r){return s.ibetainv(.5,e,r)},mode:function(e,r){return(e-1)/(e+r-2)},sample:function(e,r){var i=s.randg(e);return i/(i+s.randg(r))},variance:function(e,r){return e*r/(u.pow(e+r,2)*(e+r+1))}}),s.extend(s.centralF,{pdf:function(e,r,i){var c,f,g;return e<0?0:r<=2?e===0&&r<2?1/0:e===0&&r===2?1:1/s.betafn(r/2,i/2)*u.pow(r/i,r/2)*u.pow(e,r/2-1)*u.pow(1+r/i*e,-(r+i)/2):(c=r*e/(i+e*r),f=i/(i+e*r),g=r*f/2,g*s.binomial.pdf((r-2)/2,(r+i-2)/2,c))},cdf:function(e,r,i){return e<0?0:s.ibeta(r*e/(r*e+i),r/2,i/2)},inv:function(e,r,i){return i/(r*(1/s.ibetainv(e,r/2,i/2)-1))},mean:function(e,r){return r>2?r/(r-2):void 0},mode:function(e,r){return e>2?r*(e-2)/(e*(r+2)):void 0},sample:function(e,r){var i=s.randg(e/2)*2,c=s.randg(r/2)*2;return i/e/(c/r)},variance:function(e,r){if(!(r<=4))return 2*r*r*(e+r-2)/(e*(r-2)*(r-2)*(r-4))}}),s.extend(s.cauchy,{pdf:function(e,r,i){return i<0?0:i/(u.pow(e-r,2)+u.pow(i,2))/u.PI},cdf:function(e,r,i){return u.atan((e-r)/i)/u.PI+.5},inv:function(e,r,i){return r+i*u.tan(u.PI*(e-.5))},median:function(e){return e},mode:function(e){return e},sample:function(e,r){return s.randn()*u.sqrt(1/(2*s.randg(.5)))*r+e}}),s.extend(s.chisquare,{pdf:function(e,r){return e<0?0:e===0&&r===2?.5:u.exp((r/2-1)*u.log(e)-e/2-r/2*u.log(2)-s.gammaln(r/2))},cdf:function(e,r){return e<0?0:s.lowRegGamma(r/2,e/2)},inv:function(e,r){return 2*s.gammapinv(e,.5*r)},mean:function(e){return e},median:function(e){return e*u.pow(1-2/(9*e),3)},mode:function(e){return e-2>0?e-2:0},sample:function(e){return s.randg(e/2)*2},variance:function(e){return 2*e}}),s.extend(s.exponential,{pdf:function(e,r){return e<0?0:r*u.exp(-r*e)},cdf:function(e,r){return e<0?0:1-u.exp(-r*e)},inv:function(e,r){return-u.log(1-e)/r},mean:function(e){return 1/e},median:function(e){return 1/e*u.log(2)},mode:function(){return 0},sample:function(e){return-1/e*u.log(s._random_fn())},variance:function(e){return u.pow(e,-2)}}),s.extend(s.gamma,{pdf:function(e,r,i){return e<0?0:e===0&&r===1?1/i:u.exp((r-1)*u.log(e)-e/i-s.gammaln(r)-r*u.log(i))},cdf:function(e,r,i){return e<0?0:s.lowRegGamma(r,e/i)},inv:function(e,r,i){return s.gammapinv(e,r)*i},mean:function(e,r){return e*r},mode:function(e,r){if(e>1)return(e-1)*r},sample:function(e,r){return s.randg(e)*r},variance:function(e,r){return e*r*r}}),s.extend(s.invgamma,{pdf:function(e,r,i){return e<=0?0:u.exp(-(r+1)*u.log(e)-i/e-s.gammaln(r)+r*u.log(i))},cdf:function(e,r,i){return e<=0?0:1-s.lowRegGamma(r,i/e)},inv:function(e,r,i){return i/s.gammapinv(1-e,r)},mean:function(e,r){return e>1?r/(e-1):void 0},mode:function(e,r){return r/(e+1)},sample:function(e,r){return r/s.randg(e)},variance:function(e,r){if(!(e<=2))return r*r/((e-1)*(e-1)*(e-2))}}),s.extend(s.kumaraswamy,{pdf:function(e,r,i){return e===0&&r===1?i:e===1&&i===1?r:u.exp(u.log(r)+u.log(i)+(r-1)*u.log(e)+(i-1)*u.log(1-u.pow(e,r)))},cdf:function(e,r,i){return e<0?0:e>1?1:1-u.pow(1-u.pow(e,r),i)},inv:function(e,r,i){return u.pow(1-u.pow(1-e,1/i),1/r)},mean:function(e,r){return r*s.gammafn(1+1/e)*s.gammafn(r)/s.gammafn(1+1/e+r)},median:function(e,r){return u.pow(1-u.pow(2,-1/r),1/e)},mode:function(e,r){if(e>=1&&r>=1&&e!==1&&r!==1)return u.pow((e-1)/(e*r-1),1/e)},variance:function(){throw new Error("variance not yet implemented")}}),s.extend(s.lognormal,{pdf:function(e,r,i){return e<=0?0:u.exp(-u.log(e)-.5*u.log(2*u.PI)-u.log(i)-u.pow(u.log(e)-r,2)/(2*i*i))},cdf:function(e,r,i){return e<0?0:.5+.5*s.erf((u.log(e)-r)/u.sqrt(2*i*i))},inv:function(e,r,i){return u.exp(-1.4142135623730951*i*s.erfcinv(2*e)+r)},mean:function(e,r){return u.exp(e+r*r/2)},median:function(e){return u.exp(e)},mode:function(e,r){return u.exp(e-r*r)},sample:function(e,r){return u.exp(s.randn()*r+e)},variance:function(e,r){return(u.exp(r*r)-1)*u.exp(2*e+r*r)}}),s.extend(s.noncentralt,{pdf:function(e,r,i){var c=1e-14;return u.abs(i)<c?s.studentt.pdf(e,r):u.abs(e)<c?u.exp(s.gammaln((r+1)/2)-i*i/2-.5*u.log(u.PI*r)-s.gammaln(r/2)):r/e*(s.noncentralt.cdf(e*u.sqrt(1+2/r),r+2,i)-s.noncentralt.cdf(e,r,i))},cdf:function(e,r,i){var c=1e-14,f=200;if(u.abs(i)<c)return s.studentt.cdf(e,r);var g=!1;e<0&&(g=!0,i=-i);for(var y=s.normal.cdf(-i,0,1),k=c+1,N=k,$=e*e/(e*e+r),S=0,q=u.exp(-i*i/2),T=u.exp(-i*i/2-.5*u.log(2)-s.gammaln(3/2))*i;S<f||N>c||k>c;)N=k,S>0&&(q*=i*i/(2*S),T*=i*i/(2*(S+1/2))),k=q*s.beta.cdf($,S+.5,r/2)+T*s.beta.cdf($,S+1,r/2),y+=.5*k,S++;return g?1-y:y}}),s.extend(s.normal,{pdf:function(e,r,i){return u.exp(-.5*u.log(2*u.PI)-u.log(i)-u.pow(e-r,2)/(2*i*i))},cdf:function(e,r,i){return .5*(1+s.erf((e-r)/u.sqrt(2*i*i)))},inv:function(e,r,i){return-1.4142135623730951*i*s.erfcinv(2*e)+r},mean:function(e){return e},median:function(e){return e},mode:function(e){return e},sample:function(e,r){return s.randn()*r+e},variance:function(e,r){return r*r}}),s.extend(s.pareto,{pdf:function(e,r,i){return e<r?0:i*u.pow(r,i)/u.pow(e,i+1)},cdf:function(e,r,i){return e<r?0:1-u.pow(r/e,i)},inv:function(e,r,i){return r/u.pow(1-e,1/i)},mean:function(e,r){if(!(r<=1))return r*u.pow(e,r)/(r-1)},median:function(e,r){return e*(r*u.SQRT2)},mode:function(e){return e},variance:function(e,r){if(!(r<=2))return e*e*r/(u.pow(r-1,2)*(r-2))}}),s.extend(s.studentt,{pdf:function(e,r){return r=r>1e100?1e100:r,1/(u.sqrt(r)*s.betafn(.5,r/2))*u.pow(1+e*e/r,-((r+1)/2))},cdf:function(e,r){var i=r/2;return s.ibeta((e+u.sqrt(e*e+r))/(2*u.sqrt(e*e+r)),i,i)},inv:function(e,r){var i=s.ibetainv(2*u.min(e,1-e),.5*r,.5);return i=u.sqrt(r*(1-i)/i),e>.5?i:-i},mean:function(e){return e>1?0:void 0},median:function(){return 0},mode:function(){return 0},sample:function(e){return s.randn()*u.sqrt(e/(2*s.randg(e/2)))},variance:function(e){return e>2?e/(e-2):e>1?1/0:void 0}}),s.extend(s.weibull,{pdf:function(e,r,i){return e<0||r<0||i<0?0:i/r*u.pow(e/r,i-1)*u.exp(-u.pow(e/r,i))},cdf:function(e,r,i){return e<0?0:1-u.exp(-u.pow(e/r,i))},inv:function(e,r,i){return r*u.pow(-u.log(1-e),1/i)},mean:function(e,r){return e*s.gammafn(1+1/r)},median:function(e,r){return e*u.pow(u.log(2),1/r)},mode:function(e,r){return r<=1?0:e*u.pow((r-1)/r,1/r)},sample:function(e,r){return e*u.pow(-u.log(s._random_fn()),1/r)},variance:function(e,r){return e*e*s.gammafn(1+2/r)-u.pow(s.weibull.mean(e,r),2)}}),s.extend(s.uniform,{pdf:function(e,r,i){return e<r||e>i?0:1/(i-r)},cdf:function(e,r,i){return e<r?0:e<i?(e-r)/(i-r):1},inv:function(e,r,i){return r+e*(i-r)},mean:function(e,r){return .5*(e+r)},median:function(e,r){return s.mean(e,r)},mode:function(){throw new Error("mode is not yet implemented")},sample:function(e,r){return e/2+r/2+(r/2-e/2)*(2*s._random_fn()-1)},variance:function(e,r){return u.pow(r-e,2)/12}});function M(e,r,i,c){for(var f=0,g=1,y=1,k=1,N=0,$=0,S;u.abs((y-$)/y)>c;)$=y,S=-(r+N)*(r+i+N)*e/(r+2*N)/(r+2*N+1),f=y+S*f,g=k+S*g,N=N+1,S=N*(i-N)*e/(r+2*N-1)/(r+2*N),y=f+S*y,k=g+S*k,f=f/k,g=g/k,y=y/k,k=1;return y/r}s.extend(s.binomial,{pdf:function(e,r,i){return i===0||i===1?r*i===e?1:0:s.combination(r,e)*u.pow(i,e)*u.pow(1-i,r-e)},cdf:function(e,r,i){var c,f=1e-10;if(e<0)return 0;if(e>=r)return 1;if(i<0||i>1||r<=0)return NaN;e=u.floor(e);var g=i,y=e+1,k=r-e,N=y+k,$=u.exp(s.gammaln(N)-s.gammaln(k)-s.gammaln(y)+y*u.log(g)+k*u.log(1-g));return g<(y+1)/(N+2)?c=$*M(g,y,k,f):c=1-$*M(1-g,k,y,f),u.round((1-c)*(1/f))/(1/f)}}),s.extend(s.negbin,{pdf:function(e,r,i){return e!==e>>>0?!1:e<0?0:s.combination(e+r-1,r-1)*u.pow(1-i,e)*u.pow(i,r)},cdf:function(e,r,i){var c=0,f=0;if(e<0)return 0;for(;f<=e;f++)c+=s.negbin.pdf(f,r,i);return c}}),s.extend(s.hypgeom,{pdf:function(e,r,i,c){if(e!==e|0)return!1;if(e<0||e<i-(r-c)||e>c||e>i)return 0;if(i*2>r)return c*2>r?s.hypgeom.pdf(r-i-c+e,r,r-i,r-c):s.hypgeom.pdf(c-e,r,r-i,c);if(c*2>r)return s.hypgeom.pdf(i-e,r,i,r-c);if(i<c)return s.hypgeom.pdf(e,r,c,i);for(var f=1,g=0,y=0;y<e;y++){for(;f>1&&g<c;)f*=1-i/(r-g),g++;f*=(c-y)*(i-y)/((y+1)*(r-i-c+y+1))}for(;g<c;g++)f*=1-i/(r-g);return u.min(1,u.max(0,f))},cdf:function(e,r,i,c){if(e<0||e<i-(r-c))return 0;if(e>=c||e>=i)return 1;if(i*2>r)return c*2>r?s.hypgeom.cdf(r-i-c+e,r,r-i,r-c):1-s.hypgeom.cdf(c-e-1,r,r-i,c);if(c*2>r)return 1-s.hypgeom.cdf(i-e-1,r,i,r-c);if(i<c)return s.hypgeom.cdf(e,r,c,i);for(var f=1,g=1,y=0,k=0;k<e;k++){for(;f>1&&y<c;){var N=1-i/(r-y);g*=N,f*=N,y++}g*=(c-k)*(i-k)/((k+1)*(r-i-c+k+1)),f+=g}for(;y<c;y++)f*=1-i/(r-y);return u.min(1,u.max(0,f))}}),s.extend(s.poisson,{pdf:function(e,r){return r<0||e%1!==0||e<0?0:u.pow(r,e)*u.exp(-r)/s.factorial(e)},cdf:function(e,r){var i=[],c=0;if(e<0)return 0;for(;c<=e;c++)i.push(s.poisson.pdf(c,r));return s.sum(i)},mean:function(e){return e},variance:function(e){return e},sampleSmall:function(e){var r=1,i=0,c=u.exp(-e);do i++,r*=s._random_fn();while(r>c);return i-1},sampleLarge:function(e){var r=e,i,c,f,g,y,k,N,$,S,q;for(g=u.sqrt(r),y=u.log(r),N=.931+2.53*g,k=-.059+.02483*N,$=1.1239+1.1328/(N-3.4),S=.9277-3.6224/(N-2);;)if(c=u.random()-.5,f=u.random(),q=.5-u.abs(c),i=u.floor((2*k/q+N)*c+r+.43),q>=.07&&f<=S||!(i<0||q<.013&&f>q)&&u.log(f)+u.log($)-u.log(k/(q*q)+N)<=-r+i*y-s.loggam(i+1))return i},sample:function(e){return e<10?this.sampleSmall(e):this.sampleLarge(e)}}),s.extend(s.triangular,{pdf:function(e,r,i,c){return i<=r||c<r||c>i?NaN:e<r||e>i?0:e<c?2*(e-r)/((i-r)*(c-r)):e===c?2/(i-r):2*(i-e)/((i-r)*(i-c))},cdf:function(e,r,i,c){return i<=r||c<r||c>i?NaN:e<=r?0:e>=i?1:e<=c?u.pow(e-r,2)/((i-r)*(c-r)):1-u.pow(i-e,2)/((i-r)*(i-c))},inv:function(e,r,i,c){return i<=r||c<r||c>i?NaN:e<=(c-r)/(i-r)?r+(i-r)*u.sqrt(e*((c-r)/(i-r))):r+(i-r)*(1-u.sqrt((1-e)*(1-(c-r)/(i-r))))},mean:function(e,r,i){return(e+r+i)/3},median:function(e,r,i){if(i<=(e+r)/2)return r-u.sqrt((r-e)*(r-i))/u.sqrt(2);if(i>(e+r)/2)return e+u.sqrt((r-e)*(i-e))/u.sqrt(2)},mode:function(e,r,i){return i},sample:function(e,r,i){var c=s._random_fn();return c<(i-e)/(r-e)?e+u.sqrt(c*(r-e)*(i-e)):r-u.sqrt((1-c)*(r-e)*(r-i))},variance:function(e,r,i){return(e*e+r*r+i*i-e*r-e*i-r*i)/18}}),s.extend(s.arcsine,{pdf:function(e,r,i){return i<=r?NaN:e<=r||e>=i?0:2/u.PI*u.pow(u.pow(i-r,2)-u.pow(2*e-r-i,2),-.5)},cdf:function(e,r,i){return e<r?0:e<i?2/u.PI*u.asin(u.sqrt((e-r)/(i-r))):1},inv:function(e,r,i){return r+(.5-.5*u.cos(u.PI*e))*(i-r)},mean:function(e,r){return r<=e?NaN:(e+r)/2},median:function(e,r){return r<=e?NaN:(e+r)/2},mode:function(){throw new Error("mode is not yet implemented")},sample:function(e,r){return(e+r)/2+(r-e)/2*u.sin(2*u.PI*s.uniform.sample(0,1))},variance:function(e,r){return r<=e?NaN:u.pow(r-e,2)/8}});function x(e){return e/u.abs(e)}s.extend(s.laplace,{pdf:function(e,r,i){return i<=0?0:u.exp(-u.abs(e-r)/i)/(2*i)},cdf:function(e,r,i){return i<=0?0:e<r?.5*u.exp((e-r)/i):1-.5*u.exp(-(e-r)/i)},mean:function(e){return e},median:function(e){return e},mode:function(e){return e},variance:function(e,r){return 2*r*r},sample:function(e,r){var i=s._random_fn()-.5;return e-r*x(i)*u.log(1-2*u.abs(i))}});function R(e,r,i){var c=12,f=6,g=-30,y=-50,k=60,N=8,$=3,S=2,q=3,T=[.9815606342467192,.9041172563704749,.7699026741943047,.5873179542866175,.3678314989981802,.1252334085114689],L=[.04717533638651183,.10693932599531843,.16007832854334622,.20316742672306592,.2334925365383548,.24914704581340277],W=e*.5;if(W>=N)return 1;var Z=2*s.normal.cdf(W,0,1,1,0)-1;Z>=u.exp(y/i)?Z=u.pow(Z,i):Z=0;var nt;e>$?nt=S:nt=q;for(var st=W,Et=(N-W)/nt,Rt=st+Et,X=0,dt=i-1,Mt=1;Mt<=nt;Mt++){for(var vt=0,Dt=.5*(Rt+st),Wt=.5*(Rt-st),Ut=1;Ut<=c;Ut++){var At,_t;f<Ut?(At=c-Ut+1,_t=T[At-1]):(At=Ut,_t=-T[At-1]);var zt=Wt*_t,Yt=Dt+zt,de=Yt*Yt;if(de>k)break;var je=2*s.normal.cdf(Yt,0,1,1,0),gt=2*s.normal.cdf(Yt,e,1,1,0),be=je*.5-gt*.5;be>=u.exp(g/dt)&&(be=L[At-1]*u.exp(-(.5*de))*u.pow(be,dt),vt+=be)}vt*=2*Wt*i/u.sqrt(2*u.PI),X+=vt,st=Rt,Rt+=Et}return Z+=X,Z<=u.exp(g/r)?0:(Z=u.pow(Z,r),Z>=1?1:Z)}function v(e,r,i){var c=.322232421088,f=.099348462606,g=-1,y=.588581570495,k=-.342242088547,N=.531103462366,$=-.204231210125,S=.10353775285,q=-453642210148e-16,T=.0038560700634,L=.8832,W=.2368,Z=1.214,nt=1.208,st=1.4142,Et=120,Rt=.5-.5*e,X=u.sqrt(u.log(1/(Rt*Rt))),dt=X+((((X*q+$)*X+k)*X+g)*X+c)/((((X*T+S)*X+N)*X+y)*X+f);i<Et&&(dt+=(dt*dt*dt+dt)/i/4);var Mt=L-W*dt;return i<Et&&(Mt+=-Z/i+nt*dt/i),dt*(Mt*u.log(r-1)+st)}s.extend(s.tukey,{cdf:function(e,r,i){var c=1,f=r,g=16,y=8,k=-30,N=1e-14,$=100,S=800,q=5e3,T=25e3,L=1,W=.5,Z=.25,nt=.125,st=[.9894009349916499,.9445750230732326,.8656312023878318,.755404408355003,.6178762444026438,.45801677765722737,.2816035507792589,.09501250983763744],Et=[.027152459411754096,.062253523938647894,.09515851168249279,.12462897125553388,.14959598881657674,.16915651939500254,.18260341504492358,.1894506104550685];if(e<=0)return 0;if(i<2||c<1||f<2)return NaN;if(!Number.isFinite(e))return 1;if(i>T)return R(e,c,f);var Rt=i*.5,X=Rt*u.log(i)-i*u.log(2)-s.gammaln(Rt),dt=Rt-1,Mt=i*.25,vt;i<=$?vt=L:i<=S?vt=W:i<=q?vt=Z:vt=nt,X+=u.log(vt);for(var Dt=0,Wt=1;Wt<=50;Wt++){for(var Ut=0,At=(2*Wt-1)*vt,_t=1;_t<=g;_t++){var zt,Yt;y<_t?(zt=_t-y-1,Yt=X+dt*u.log(At+st[zt]*vt)-(st[zt]*vt+At)*Mt):(zt=_t-1,Yt=X+dt*u.log(At-st[zt]*vt)+(st[zt]*vt-At)*Mt);var de;if(Yt>=k){y<_t?de=e*u.sqrt((st[zt]*vt+At)*.5):de=e*u.sqrt((-(st[zt]*vt)+At)*.5);var je=R(de,c,f),gt=je*Et[zt]*u.exp(Yt);Ut+=gt}}if(Wt*vt>=1&&Ut<=N)break;Dt+=Ut}if(Ut>N)throw new Error("tukey.cdf failed to converge");return Dt>1&&(Dt=1),Dt},inv:function(e,r,i){var c=1,f=r,g=1e-4,y=50;if(i<2||c<1||f<2)return NaN;if(e<0||e>1)return NaN;if(e===0)return 0;if(e===1)return 1/0;var k=v(e,f,i),N=s.tukey.cdf(k,r,i)-e,$;N>0?$=u.max(0,k-1):$=k+1;for(var S=s.tukey.cdf($,r,i)-e,q,T=1;T<y;T++){q=$-S*($-k)/(S-N),N=S,k=$,q<0&&(q=0,S=-e),S=s.tukey.cdf(q,r,i)-e,$=q;var L=u.abs($-k);if(L<g)return q}throw new Error("tukey.inv failed to converge")}})})(p,Math),(function(s,u){var M=Array.prototype.push,x=s.utils.isArray;function R(v){return x(v)||v instanceof s}s.extend({add:function(v,e){return R(e)?(R(e[0])||(e=[e]),s.map(v,function(r,i,c){return r+e[i][c]})):s.map(v,function(r){return r+e})},subtract:function(v,e){return R(e)?(R(e[0])||(e=[e]),s.map(v,function(r,i,c){return r-e[i][c]||0})):s.map(v,function(r){return r-e})},divide:function(v,e){return R(e)?(R(e[0])||(e=[e]),s.multiply(v,s.inv(e))):s.map(v,function(r){return r/e})},multiply:function(v,e){var r,i,c,f,g,y,k,N;if(v.length===void 0&&e.length===void 0)return v*e;if(g=v.length,y=v[0].length,k=s.zeros(g,c=R(e)?e[0].length:y),N=0,R(e)){for(;N<c;N++)for(r=0;r<g;r++){for(f=0,i=0;i<y;i++)f+=v[r][i]*e[i][N];k[r][N]=f}return g===1&&N===1?k[0][0]:k}return s.map(v,function($){return $*e})},outer:function(v,e){return s.multiply(v.map(function(r){return[r]}),[e])},dot:function(v,e){R(v[0])||(v=[v]),R(e[0])||(e=[e]);for(var r=v[0].length===1&&v.length!==1?s.transpose(v):v,i=e[0].length===1&&e.length!==1?s.transpose(e):e,c=[],f=0,g=r.length,y=r[0].length,k,N;f<g;f++){for(c[f]=[],k=0,N=0;N<y;N++)k+=r[f][N]*i[f][N];c[f]=k}return c.length===1?c[0]:c},pow:function(v,e){return s.map(v,function(r){return u.pow(r,e)})},exp:function(v){return s.map(v,function(e){return u.exp(e)})},log:function(v){return s.map(v,function(e){return u.log(e)})},abs:function(v){return s.map(v,function(e){return u.abs(e)})},norm:function(v,e){var r=0,i=0;for(isNaN(e)&&(e=2),R(v[0])&&(v=v[0]);i<v.length;i++)r+=u.pow(u.abs(v[i]),e);return u.pow(r,1/e)},angle:function(v,e){return u.acos(s.dot(v,e)/(s.norm(v)*s.norm(e)))},aug:function(v,e){var r=[],i;for(i=0;i<v.length;i++)r.push(v[i].slice());for(i=0;i<r.length;i++)M.apply(r[i],e[i]);return r},inv:function(v){for(var e=v.length,r=v[0].length,i=s.identity(e,r),c=s.gauss_jordan(v,i),f=[],g=0,y;g<e;g++)for(f[g]=[],y=r;y<c[0].length;y++)f[g][y-r]=c[g][y];return f},det:function v(e){if(e.length===2)return e[0][0]*e[1][1]-e[0][1]*e[1][0];for(var r=0,i=0;i<e.length;i++){for(var c=[],f=1;f<e.length;f++){c[f-1]=[];for(var g=0;g<e.length;g++)g<i?c[f-1][g]=e[f][g]:g>i&&(c[f-1][g-1]=e[f][g])}var y=i%2?-1:1;r+=v(c)*e[0][i]*y}return r},gauss_elimination:function(v,e){var r=0,i=0,c=v.length,f=v[0].length,g=1,y=0,k=[],N,$,S,q;for(v=s.aug(v,e),N=v[0].length,r=0;r<c;r++){for($=v[r][r],i=r,q=r+1;q<f;q++)$<u.abs(v[q][r])&&($=v[q][r],i=q);if(i!=r)for(q=0;q<N;q++)S=v[r][q],v[r][q]=v[i][q],v[i][q]=S;for(i=r+1;i<c;i++)for(g=v[i][r]/v[r][r],q=r;q<N;q++)v[i][q]=v[i][q]-g*v[r][q]}for(r=c-1;r>=0;r--){for(y=0,i=r+1;i<=c-1;i++)y=y+k[i]*v[r][i];k[r]=(v[r][N-1]-y)/v[r][r]}return k},gauss_jordan:function(v,e){var r=s.aug(v,e),i=r.length,c=r[0].length,f=0,g,y,k;for(y=0;y<i;y++){var N=y;for(k=y+1;k<i;k++)u.abs(r[k][y])>u.abs(r[N][y])&&(N=k);var $=r[y];for(r[y]=r[N],r[N]=$,k=y+1;k<i;k++)for(f=r[k][y]/r[y][y],g=y;g<c;g++)r[k][g]-=r[y][g]*f}for(y=i-1;y>=0;y--){for(f=r[y][y],k=0;k<y;k++)for(g=c-1;g>y-1;g--)r[k][g]-=r[y][g]*r[k][y]/f;for(r[y][y]/=f,g=i;g<c;g++)r[y][g]/=f}return r},triaUpSolve:function(v,e){var r=v[0].length,i=s.zeros(1,r)[0],c,f=!1;return e[0].length!=null&&(e=e.map(function(g){return g[0]}),f=!0),s.arange(r-1,-1,-1).forEach(function(g){c=s.arange(g+1,r).map(function(y){return i[y]*v[g][y]}),i[g]=(e[g]-s.sum(c))/v[g][g]}),f?i.map(function(g){return[g]}):i},triaLowSolve:function(v,e){var r=v[0].length,i=s.zeros(1,r)[0],c,f=!1;return e[0].length!=null&&(e=e.map(function(g){return g[0]}),f=!0),s.arange(r).forEach(function(g){c=s.arange(g).map(function(y){return v[g][y]*i[y]}),i[g]=(e[g]-s.sum(c))/v[g][g]}),f?i.map(function(g){return[g]}):i},lu:function(v){var e=v.length,r=s.identity(e),i=s.zeros(v.length,v[0].length),c;return s.arange(e).forEach(function(f){i[0][f]=v[0][f]}),s.arange(1,e).forEach(function(f){s.arange(f).forEach(function(g){c=s.arange(g).map(function(y){return r[f][y]*i[y][g]}),r[f][g]=(v[f][g]-s.sum(c))/i[g][g]}),s.arange(f,e).forEach(function(g){c=s.arange(f).map(function(y){return r[f][y]*i[y][g]}),i[f][g]=v[c.length][g]-s.sum(c)})}),[r,i]},cholesky:function(v){var e=v.length,r=s.zeros(v.length,v[0].length),i;return s.arange(e).forEach(function(c){i=s.arange(c).map(function(f){return u.pow(r[c][f],2)}),r[c][c]=u.sqrt(v[c][c]-s.sum(i)),s.arange(c+1,e).forEach(function(f){i=s.arange(c).map(function(g){return r[c][g]*r[f][g]}),r[f][c]=(v[c][f]-s.sum(i))/r[c][c]})}),r},gauss_jacobi:function(v,e,r,i){for(var c=0,f=0,g=v.length,y=[],k=[],N=[],$,S,q,T;c<g;c++)for(y[c]=[],k[c]=[],N[c]=[],f=0;f<g;f++)c>f?(y[c][f]=v[c][f],k[c][f]=N[c][f]=0):c<f?(k[c][f]=v[c][f],y[c][f]=N[c][f]=0):(N[c][f]=v[c][f],y[c][f]=k[c][f]=0);for(q=s.multiply(s.multiply(s.inv(N),s.add(y,k)),-1),S=s.multiply(s.inv(N),e),$=r,T=s.add(s.multiply(q,r),S),c=2;u.abs(s.norm(s.subtract(T,$)))>i;)$=T,T=s.add(s.multiply(q,$),S),c++;return T},gauss_seidel:function(v,e,r,i){for(var c=0,f=v.length,g=[],y=[],k=[],N,$,S,q,T;c<f;c++)for(g[c]=[],y[c]=[],k[c]=[],N=0;N<f;N++)c>N?(g[c][N]=v[c][N],y[c][N]=k[c][N]=0):c<N?(y[c][N]=v[c][N],g[c][N]=k[c][N]=0):(k[c][N]=v[c][N],g[c][N]=y[c][N]=0);for(q=s.multiply(s.multiply(s.inv(s.add(k,g)),y),-1),S=s.multiply(s.inv(s.add(k,g)),e),$=r,T=s.add(s.multiply(q,r),S),c=2;u.abs(s.norm(s.subtract(T,$)))>i;)$=T,T=s.add(s.multiply(q,$),S),c=c+1;return T},SOR:function(v,e,r,i,c){for(var f=0,g=v.length,y=[],k=[],N=[],$,S,q,T,L;f<g;f++)for(y[f]=[],k[f]=[],N[f]=[],$=0;$<g;$++)f>$?(y[f][$]=v[f][$],k[f][$]=N[f][$]=0):f<$?(k[f][$]=v[f][$],y[f][$]=N[f][$]=0):(N[f][$]=v[f][$],y[f][$]=k[f][$]=0);for(T=s.multiply(s.inv(s.add(N,s.multiply(y,c))),s.subtract(s.multiply(N,1-c),s.multiply(k,c))),q=s.multiply(s.multiply(s.inv(s.add(N,s.multiply(y,c))),e),c),S=r,L=s.add(s.multiply(T,r),q),f=2;u.abs(s.norm(s.subtract(L,S)))>i;)S=L,L=s.add(s.multiply(T,S),q),f++;return L},householder:function(v){for(var e=v.length,r=v[0].length,i=0,c=[],f=[],g,y,k,N,$;i<e-1;i++){for(g=0,N=i+1;N<r;N++)g+=v[N][i]*v[N][i];for($=v[i+1][i]>0?-1:1,g=$*u.sqrt(g),y=u.sqrt((g*g-v[i+1][i]*g)/2),c=s.zeros(e,1),c[i+1][0]=(v[i+1][i]-g)/(2*y),k=i+2;k<e;k++)c[k][0]=v[k][i]/(2*y);f=s.subtract(s.identity(e,r),s.multiply(s.multiply(c,s.transpose(c)),2)),v=s.multiply(f,s.multiply(v,f))}return v},QR:(function(){var v=s.sum,e=s.arange;function r(i){var c=i.length,f=i[0].length,g=s.zeros(f,f);i=s.copy(i);var y,k,N;for(k=0;k<f;k++){for(g[k][k]=u.sqrt(v(e(c).map(function($){return i[$][k]*i[$][k]}))),y=0;y<c;y++)i[y][k]=i[y][k]/g[k][k];for(N=k+1;N<f;N++)for(g[k][N]=v(e(c).map(function($){return i[$][k]*i[$][N]})),y=0;y<c;y++)i[y][N]=i[y][N]-i[y][k]*g[k][N]}return[i,g]}return r})(),lstsq:(function(){function v(r){r=s.copy(r);var i=r.length,c=s.identity(i);return s.arange(i-1,-1,-1).forEach(function(f){s.sliceAssign(c,{row:f},s.divide(s.slice(c,{row:f}),r[f][f])),s.sliceAssign(r,{row:f},s.divide(s.slice(r,{row:f}),r[f][f])),s.arange(f).forEach(function(g){var y=s.multiply(r[g][f],-1),k=s.slice(r,{row:g}),N=s.multiply(s.slice(r,{row:f}),y);s.sliceAssign(r,{row:g},s.add(k,N));var $=s.slice(c,{row:g}),S=s.multiply(s.slice(c,{row:f}),y);s.sliceAssign(c,{row:g},s.add($,S))})}),c}function e(r,i){var c=!1;i[0].length===void 0&&(i=i.map(function(L){return[L]}),c=!0);var f=s.QR(r),g=f[0],y=f[1],k=r[0].length,N=s.slice(g,{col:{end:k}}),$=s.slice(y,{row:{end:k}}),S=v($),q=s.transpose(N);q[0].length===void 0&&(q=[q]);var T=s.multiply(s.multiply(S,q),i);return T.length===void 0&&(T=[[T]]),c?T.map(function(L){return L[0]}):T}return e})(),jacobi:function(v){for(var e=1,r=v.length,i=s.identity(r,r),c=[],f,g,y,k,N,$,S,q;e===1;){for($=v[0][1],k=0,N=1,g=0;g<r;g++)for(y=0;y<r;y++)g!=y&&$<u.abs(v[g][y])&&($=u.abs(v[g][y]),k=g,N=y);for(v[k][k]===v[N][N]?S=v[k][N]>0?u.PI/4:-u.PI/4:S=u.atan(2*v[k][N]/(v[k][k]-v[N][N]))/2,q=s.identity(r,r),q[k][k]=u.cos(S),q[k][N]=-u.sin(S),q[N][k]=u.sin(S),q[N][N]=u.cos(S),i=s.multiply(i,q),f=s.multiply(s.multiply(s.inv(q),v),q),v=f,e=0,g=1;g<r;g++)for(y=1;y<r;y++)g!=y&&u.abs(v[g][y])>.001&&(e=1)}for(g=0;g<r;g++)c.push(v[g][g]);return[i,c]},rungekutta:function(v,e,r,i,c,f){var g,y,k,N,$;if(f===2)for(;i<=r;)g=e*v(i,c),y=e*v(i+e,c+g),k=c+(g+y)/2,c=k,i=i+e;if(f===4)for(;i<=r;)g=e*v(i,c),y=e*v(i+e/2,c+g/2),N=e*v(i+e/2,c+y/2),$=e*v(i+e,c+N),k=c+(g+2*y+2*N+$)/6,c=k,i=i+e;return c},romberg:function(v,e,r,i){for(var c=0,f=(r-e)/2,g=[],y=[],k=[],N,$,S,q,T;c<i/2;){for(T=v(e),S=e,q=0;S<=r;S=S+f,q++)g[q]=S;for(N=g.length,S=1;S<N-1;S++)T+=(S%2!==0?4:2)*v(g[S]);T=f/3*(T+v(r)),k[c]=T,f/=2,c++}for($=k.length,N=1;$!==1;){for(S=0;S<$-1;S++)y[S]=(u.pow(4,N)*k[S+1]-k[S])/(u.pow(4,N)-1);$=y.length,k=y,y=[],N++}return k},richardson:function(v,e,r,i){function c(L,W){for(var Z=0,nt=L.length,st;Z<nt;Z++)L[Z]===W&&(st=Z);return st}for(var f=u.abs(r-v[c(v,r)+1]),g=0,y=[],k=[],N,$,S,q,T;i>=f;)N=c(v,r+i),$=c(v,r),y[g]=(e[N]-2*e[$]+e[2*$-N])/(i*i),i/=2,g++;for(q=y.length,S=1;q!=1;){for(T=0;T<q-1;T++)k[T]=(u.pow(4,S)*y[T+1]-y[T])/(u.pow(4,S)-1);q=k.length,y=k,k=[],S++}return y},simpson:function(v,e,r,i){for(var c=(r-e)/i,f=v(e),g=[],y=e,k=0,N=1,$;y<=r;y=y+c,k++)g[k]=y;for($=g.length;N<$-1;N++)f+=(N%2!==0?4:2)*v(g[N]);return c/3*(f+v(r))},hermite:function(v,e,r,i){for(var c=v.length,f=0,g=0,y=[],k=[],N=[],$=[],S;g<c;g++){for(y[g]=1,S=0;S<c;S++)g!=S&&(y[g]*=(i-v[S])/(v[g]-v[S]));for(k[g]=0,S=0;S<c;S++)g!=S&&(k[g]+=1/(v[g]-v[S]));N[g]=(1-2*(i-v[g])*k[g])*(y[g]*y[g]),$[g]=(i-v[g])*(y[g]*y[g]),f+=N[g]*e[g]+$[g]*r[g]}return f},lagrange:function(v,e,r){for(var i=0,c=0,f,g,y=v.length;c<y;c++){for(g=e[c],f=0;f<y;f++)c!=f&&(g*=(r-v[f])/(v[c]-v[f]));i+=g}return i},cubic_spline:function(v,e,r){for(var i=v.length,c=0,f,g=[],y=[],k=[],N=[],$=[],S=[],q=[];c<i-1;c++)$[c]=v[c+1]-v[c];for(k[0]=0,c=1;c<i-1;c++)k[c]=3/$[c]*(e[c+1]-e[c])-3/$[c-1]*(e[c]-e[c-1]);for(c=1;c<i-1;c++)g[c]=[],y[c]=[],g[c][c-1]=$[c-1],g[c][c]=2*($[c-1]+$[c]),g[c][c+1]=$[c],y[c][0]=k[c];for(N=s.multiply(s.inv(g),y),f=0;f<i-1;f++)S[f]=(e[f+1]-e[f])/$[f]-$[f]*(N[f+1][0]+2*N[f][0])/3,q[f]=(N[f+1][0]-N[f][0])/(3*$[f]);for(f=0;f<i&&!(v[f]>r);f++);return f-=1,e[f]+(r-v[f])*S[f]+s.sq(r-v[f])*N[f]+(r-v[f])*s.sq(r-v[f])*q[f]},gauss_quadrature:function(){throw new Error("gauss_quadrature not yet implemented")},PCA:function(v){var e=v.length,r=v[0].length,i=0,c,f,g=[],y=[],k=[],N=[],$=[],S=[],q=[],T=[],L=[],W=[];for(i=0;i<e;i++)g[i]=s.sum(v[i])/r;for(i=0;i<r;i++)for(q[i]=[],c=0;c<e;c++)q[i][c]=v[c][i]-g[c];for(q=s.transpose(q),i=0;i<e;i++)for(T[i]=[],c=0;c<e;c++)T[i][c]=s.dot([q[i]],[q[c]])/(r-1);for(k=s.jacobi(T),L=k[0],y=k[1],W=s.transpose(L),i=0;i<y.length;i++)for(c=i;c<y.length;c++)y[i]<y[c]&&(f=y[i],y[i]=y[c],y[c]=f,N=W[i],W[i]=W[c],W[c]=N);for(S=s.transpose(q),i=0;i<e;i++)for($[i]=[],c=0;c<S.length;c++)$[i][c]=s.dot([W[i]],[S[c]]);return[v,y,W,$]}}),(function(v){for(var e=0;e<v.length;e++)(function(r){s.fn[r]=function(i,c){var f=this;return c?(setTimeout(function(){c.call(f,s.fn[r].call(f,i))},15),this):typeof s[r](this,i)=="number"?s[r](this,i):s(s[r](this,i))}})(v[e])})("add divide multiply subtract dot pow exp log abs norm angle".split(" "))})(p,Math),(function(s,u){var M=[].slice,x=s.utils.isNumber,R=s.utils.isArray;s.extend({zscore:function(){var e=M.call(arguments);return x(e[1])?(e[0]-e[1])/e[2]:(e[0]-s.mean(e[1]))/s.stdev(e[1],e[2])},ztest:function(){var e=M.call(arguments),r;return R(e[1])?(r=s.zscore(e[0],e[1],e[3]),e[2]===1?s.normal.cdf(-u.abs(r),0,1):s.normal.cdf(-u.abs(r),0,1)*2):e.length>2?(r=s.zscore(e[0],e[1],e[2]),e[3]===1?s.normal.cdf(-u.abs(r),0,1):s.normal.cdf(-u.abs(r),0,1)*2):(r=e[0],e[1]===1?s.normal.cdf(-u.abs(r),0,1):s.normal.cdf(-u.abs(r),0,1)*2)}}),s.extend(s.fn,{zscore:function(e,r){return(e-this.mean())/this.stdev(r)},ztest:function(e,r,i){var c=u.abs(this.zscore(e,i));return r===1?s.normal.cdf(-c,0,1):s.normal.cdf(-c,0,1)*2}}),s.extend({tscore:function(){var e=M.call(arguments);return e.length===4?(e[0]-e[1])/(e[2]/u.sqrt(e[3])):(e[0]-s.mean(e[1]))/(s.stdev(e[1],!0)/u.sqrt(e[1].length))},ttest:function(){var e=M.call(arguments),r;return e.length===5?(r=u.abs(s.tscore(e[0],e[1],e[2],e[3])),e[4]===1?s.studentt.cdf(-r,e[3]-1):s.studentt.cdf(-r,e[3]-1)*2):x(e[1])?(r=u.abs(e[0]),e[2]==1?s.studentt.cdf(-r,e[1]-1):s.studentt.cdf(-r,e[1]-1)*2):(r=u.abs(s.tscore(e[0],e[1])),e[2]==1?s.studentt.cdf(-r,e[1].length-1):s.studentt.cdf(-r,e[1].length-1)*2)}}),s.extend(s.fn,{tscore:function(e){return(e-this.mean())/(this.stdev(!0)/u.sqrt(this.cols()))},ttest:function(e,r){return r===1?1-s.studentt.cdf(u.abs(this.tscore(e)),this.cols()-1):s.studentt.cdf(-u.abs(this.tscore(e)),this.cols()-1)*2}}),s.extend({anovafscore:function(){var e=M.call(arguments),r,i,c,f,g,y,k,N;if(e.length===1){for(g=new Array(e[0].length),k=0;k<e[0].length;k++)g[k]=e[0][k];e=g}for(i=new Array,k=0;k<e.length;k++)i=i.concat(e[k]);for(c=s.mean(i),r=0,k=0;k<e.length;k++)r=r+e[k].length*u.pow(s.mean(e[k])-c,2);for(r/=e.length-1,y=0,k=0;k<e.length;k++)for(f=s.mean(e[k]),N=0;N<e[k].length;N++)y+=u.pow(e[k][N]-f,2);return y/=i.length-e.length,r/y},anovaftest:function(){var e=M.call(arguments),r,i,c,f;if(x(e[0]))return 1-s.centralF.cdf(e[0],e[1],e[2]);var g=s.anovafscore(e);for(r=e.length-1,c=0,f=0;f<e.length;f++)c=c+e[f].length;return i=c-r-1,1-s.centralF.cdf(g,r,i)},ftest:function(e,r,i){return 1-s.centralF.cdf(e,r,i)}}),s.extend(s.fn,{anovafscore:function(){return s.anovafscore(this.toArray())},anovaftes:function(){var e=0,r;for(r=0;r<this.length;r++)e=e+this[r].length;return s.ftest(this.anovafscore(),this.length-1,e-this.length)}}),s.extend({qscore:function(){var e=M.call(arguments),r,i,c,f,g;return x(e[0])?(r=e[0],i=e[1],c=e[2],f=e[3],g=e[4]):(r=s.mean(e[0]),i=s.mean(e[1]),c=e[0].length,f=e[1].length,g=e[2]),u.abs(r-i)/(g*u.sqrt((1/c+1/f)/2))},qtest:function(){var e=M.call(arguments),r;e.length===3?(r=e[0],e=e.slice(1)):e.length===7?(r=s.qscore(e[0],e[1],e[2],e[3],e[4]),e=e.slice(5)):(r=s.qscore(e[0],e[1],e[2]),e=e.slice(3));var i=e[0],c=e[1];return 1-s.tukey.cdf(r,c,i-c)},tukeyhsd:function(e){for(var r=s.pooledstdev(e),i=e.map(function(N){return s.mean(N)}),c=e.reduce(function(N,$){return N+$.length},0),f=[],g=0;g<e.length;++g)for(var y=g+1;y<e.length;++y){var k=s.qtest(i[g],i[y],e[g].length,e[y].length,r,c,e.length);f.push([[g,y],k])}return f}}),s.extend({normalci:function(){var e=M.call(arguments),r=new Array(2),i;return e.length===4?i=u.abs(s.normal.inv(e[1]/2,0,1)*e[2]/u.sqrt(e[3])):i=u.abs(s.normal.inv(e[1]/2,0,1)*s.stdev(e[2])/u.sqrt(e[2].length)),r[0]=e[0]-i,r[1]=e[0]+i,r},tci:function(){var e=M.call(arguments),r=new Array(2),i;return e.length===4?i=u.abs(s.studentt.inv(e[1]/2,e[3]-1)*e[2]/u.sqrt(e[3])):i=u.abs(s.studentt.inv(e[1]/2,e[2].length-1)*s.stdev(e[2],!0)/u.sqrt(e[2].length)),r[0]=e[0]-i,r[1]=e[0]+i,r},significant:function(e,r){return e<r}}),s.extend(s.fn,{normalci:function(e,r){return s.normalci(e,r,this.toArray())},tci:function(e,r){return s.tci(e,r,this.toArray())}});function v(e,r,i,c){if(e>1||i>1||e<=0||i<=0)throw new Error("Proportions should be greater than 0 and less than 1");var f=(e*r+i*c)/(r+c),g=u.sqrt(f*(1-f)*(1/r+1/c));return(e-i)/g}s.extend(s.fn,{oneSidedDifferenceOfProportions:function(e,r,i,c){var f=v(e,r,i,c);return s.ztest(f,1)},twoSidedDifferenceOfProportions:function(e,r,i,c){var f=v(e,r,i,c);return s.ztest(f,2)}})})(p,Math),p.models=(function(){function s(v){var e=v[0].length,r=p.arange(e).map(function(i){var c=p.arange(e).filter(function(f){return f!==i});return u(p.col(v,i).map(function(f){return f[0]}),p.col(v,c))});return r}function u(v,e){var r=v.length,i=e[0].length-1,c=r-i-1,f=p.lstsq(e,v),g=p.multiply(e,f.map(function(T){return[T]})).map(function(T){return T[0]}),y=p.subtract(v,g),k=p.mean(v),N=p.sum(g.map(function(T){return Math.pow(T-k,2)})),$=p.sum(v.map(function(T,L){return Math.pow(T-g[L],2)})),S=N+$,q=N/S;return{exog:e,endog:v,nobs:r,df_model:i,df_resid:c,coef:f,predict:g,resid:y,ybar:k,SST:S,SSE:N,SSR:$,R2:q}}function M(v){var e=s(v.exog),r=Math.sqrt(v.SSR/v.df_resid),i=e.map(function(k){var N=k.SST,$=k.R2;return r/Math.sqrt(N*(1-$))}),c=v.coef.map(function(k,N){return(k-0)/i[N]}),f=c.map(function(k){var N=p.studentt.cdf(k,v.df_resid);return(N>.5?1-N:N)*2}),g=p.studentt.inv(.975,v.df_resid),y=v.coef.map(function(k,N){var $=g*i[N];return[k-$,k+$]});return{se:i,t:c,p:f,sigmaHat:r,interval95:y}}function x(v){var e=v.R2/v.df_model/((1-v.R2)/v.df_resid),r=function(c,f,g){return p.beta.cdf(c/(g/f+c),f/2,g/2)},i=1-r(e,v.df_model,v.df_resid);return{F_statistic:e,pvalue:i}}function R(v,e){var r=u(v,e),i=M(r),c=x(r),f=1-(1-r.R2)*((r.nobs-1)/r.df_resid);return r.t=i,r.f=c,r.adjust_R2=f,r}return{ols:R}})(),p.extend({buildxmatrix:function(){for(var s=new Array(arguments.length),u=0;u<arguments.length;u++){var M=[1];s[u]=M.concat(arguments[u])}return p(s)},builddxmatrix:function(){for(var s=new Array(arguments[0].length),u=0;u<arguments[0].length;u++){var M=[1];s[u]=M.concat(arguments[0][u])}return p(s)},buildjxmatrix:function(s){for(var u=new Array(s.length),M=0;M<s.length;M++)u[M]=s[M];return p.builddxmatrix(u)},buildymatrix:function(s){return p(s).transpose()},buildjymatrix:function(s){return s.transpose()},matrixmult:function(s,u){var M,x,R,v,e;if(s.cols()==u.rows()){if(u.rows()>1){for(v=[],M=0;M<s.rows();M++)for(v[M]=[],x=0;x<u.cols();x++){for(e=0,R=0;R<s.cols();R++)e+=s.toArray()[M][R]*u.toArray()[R][x];v[M][x]=e}return p(v)}for(v=[],M=0;M<s.rows();M++)for(v[M]=[],x=0;x<u.cols();x++){for(e=0,R=0;R<s.cols();R++)e+=s.toArray()[M][R]*u.toArray()[x];v[M][x]=e}return p(v)}},regress:function(s,u){var M=p.xtranspxinv(s),x=s.transpose(),R=p.matrixmult(p(M),x);return p.matrixmult(R,u)},regresst:function(s,u,M){var x=p.regress(s,u),R={};R.anova={};var v=p.jMatYBar(s,x);R.yBar=v;var e=u.mean();R.anova.residuals=p.residuals(u,v),R.anova.ssr=p.ssr(v,e),R.anova.msr=R.anova.ssr/(s[0].length-1),R.anova.sse=p.sse(u,v),R.anova.mse=R.anova.sse/(u.length-(s[0].length-1)-1),R.anova.sst=p.sst(u,e),R.anova.mst=R.anova.sst/(u.length-1),R.anova.r2=1-R.anova.sse/R.anova.sst,R.anova.r2<0&&(R.anova.r2=0),R.anova.fratio=R.anova.msr/R.anova.mse,R.anova.pvalue=p.anovaftest(R.anova.fratio,s[0].length-1,u.length-(s[0].length-1)-1),R.anova.rmse=Math.sqrt(R.anova.mse),R.anova.r2adj=1-R.anova.mse/R.anova.mst,R.anova.r2adj<0&&(R.anova.r2adj=0),R.stats=new Array(s[0].length);for(var r=p.xtranspxinv(s),i,c,f,g=0;g<x.length;g++)i=Math.sqrt(R.anova.mse*Math.abs(r[g][g])),c=Math.abs(x[g]/i),f=p.ttest(c,u.length-s[0].length-1,M),R.stats[g]=[x[g],i,c,f];return R.regress=x,R},xtranspx:function(s){return p.matrixmult(s.transpose(),s)},xtranspxinv:function(s){var u=p.matrixmult(s.transpose(),s),M=p.inv(u);return M},jMatYBar:function(s,u){var M=p.matrixmult(s,u);return new p(M)},residuals:function(s,u){return p.matrixsubtract(s,u)},ssr:function(s,u){for(var M=0,x=0;x<s.length;x++)M+=Math.pow(s[x]-u,2);return M},sse:function(s,u){for(var M=0,x=0;x<s.length;x++)M+=Math.pow(s[x]-u[x],2);return M},sst:function(s,u){for(var M=0,x=0;x<s.length;x++)M+=Math.pow(s[x]-u,2);return M},matrixsubtract:function(s,u){for(var M=new Array(s.length),x=0;x<s.length;x++){M[x]=new Array(s[x].length);for(var R=0;R<s[x].length;R++)M[x][R]=s[x][R]-u[x][R]}return p(M)}}),p.jStat=p,p})}),Oe=Dn(Hr(),1),gn=Oe.Matrix,_n=Oe.SingularValueDecomposition,fo=Oe.default.Matrix?Oe.default.Matrix:Oe.Matrix,Jr=Dn(Br(),1),wn=(h,d)=>Jr.default.studentt.inv(h,d);function bn(h){let d=[{id:"intercept",label:"Intercept",factors:[]}],p=s=>{let u=h.factors.find(M=>M.id===s);return u.type==="number"?[{factor:s,power:1,label:u.name}]:u.levels.slice(1).map(M=>({factor:s,level:M,label:`${u.name}: ${M} vs ${u.levels[0]}`}))};for(let s of h.model.terms)if(s.endsWith("^2")){let u=s.slice(0,-2),M=h.factors.find(x=>x.id===u);d.push({id:s,label:`${M.name} squared`,factors:[{factor:u,power:2}]})}else{let u=s.split(":"),M=u.map(p),x=M.length===1?M[0].map(R=>[R]):M[0].flatMap(R=>M[1].map(v=>[R,v]));for(let R of x)d.push({id:R.map(v=>v.factor+(v.level===void 0?"":"["+v.level+"]")).join(":"),label:R.map(v=>v.label).join(" \xD7 "),factors:R})}if(h.model.blocks)for(let s of h.design.blocks.slice(1))d.push({id:"block["+s+"]",label:`Block: ${s} vs ${h.design.blocks[0]}`,block:s,factors:[]});return D(d.length<=48,"The expanded model exceeds 48 columns. Reduce factors, levels or interactions."),d}function yn(h,d,p,s=bn(h)){return ae(h,d),D(h.design.blocks.includes(p),"Choose a declared block."),s.map(u=>u.block!==void 0?+(p===u.block):u.factors.reduce((M,x)=>{let R=h.factors.find(v=>v.id===x.factor);return M*(R.type==="category"?+(d[R.id]===x.level):((d[R.id]-(R.levels[0]+R.levels.at(-1))/2)/((R.levels.at(-1)-R.levels[0])/2))**x.power)},1))}var Ve=h=>h.reduce((d,p)=>d+p,0),he=(h,d)=>Ve(h.map((p,s)=>p*d[s])),vn=h=>Ve(h)/h.length;function Ln(h,d){if(!h.length)return{rank:0,condition:null,df:-d,svd:null};let p=new _n(new gn(h),{autoTranspose:!0}),s=p.diagonal,u=s[0]*1e-12,M=s.filter(x=>x>u).length;return{rank:M,condition:M<d?null:s[0]/s.at(-1),df:h.length-d,singular:s,svd:p}}function Qe(h){let d=bn(h),p=new Map(h.phases.map(x=>[x.id,x])),s=h.runs.filter(x=>p.get(x.phase).kind!=="confirmation").map(x=>yn(h,x.settings,x.block,d)),{svd:u,...M}=Ln(s,d.length);return{...M,rows:s.length,columns:d.map(x=>x.label),parameters:d.length}}function ke(h,{includeExcluded:d=!1}={}){let p=xt(h),s=bn(p),u=new Map(p.phases.map(X=>[X.id,X])),M=new Map(p.measurements.map(X=>[X.runId,X])),x=p.runs.filter(X=>u.get(X.phase).kind!=="confirmation"&&M.has(X.id)&&(d||!M.get(X.id).excluded)),R=x.map(X=>yn(p,X.settings,X.block,s)),v=x.map(X=>M.get(X.id).value),e=Ln(R,s.length),r=v.length,i=s.length,c={n:r,parameters:i,rank:e.rank,df:r-i,condition:e.condition,includeExcluded:d,columns:s,pending:p.runs.length-p.measurements.length,excluded:p.measurements.filter(X=>X.excluded).length,confirmation:p.measurements.filter(X=>u.get(p.runs.find(dt=>dt.id===X.runId).phase).kind==="confirmation").length,model:ht(p.model),matrix:{X:R,y:v,runIds:x.map(X=>X.id)},warnings:[]};if(!r)return{...c,ok:!1,issue:"Collect measurements first. The plan does not contain invented responses."};if(e.rank<i)return{...c,ok:!1,issue:`These measurements identify ${e.rank} of ${i} model columns. Collect the missing combinations or simplify the model. Center points alone cannot separate multiple squared effects.`};if(r<=i)return{...c,ok:!1,issue:`There are ${r} measured runs and ${i} parameters. Independent repetitions are needed to estimate residual uncertainty.`};if(e.condition>1e9)return{...c,ok:!1,issue:"The model is numerically unstable. Redesign the experiment or remove confounded terms."};let f=e.svd.inverse(),g=f.mmul(gn.columnVector(v)).to1DArray(),y=f.mmul(f.transpose()).to2DArray(),k=R.map(X=>he(X,g)),N=v.map((X,dt)=>X-k[dt]),$=Ve(N.map(X=>X*X)),S=r-i,q=$/S,T=Math.max(1,...v.map(Math.abs)),L=q>(Number.EPSILON*T*64)**2,W=y.map(X=>X.map(dt=>dt*q)),Z=wn((1+p.model.confidence)/2,S);D(Number.isFinite(Z),"The uncertainty calculation could not be resolved.");let nt=s.map((X,dt)=>{let Mt=Math.sqrt(Math.max(0,W[dt][dt]));return{id:X.id,label:X.label,value:g[dt],se:L?Mt:null,ci:L?[g[dt]-Z*Mt,g[dt]+Z*Mt]:null}}),st=x.map((X,dt)=>{let Mt=Math.max(0,Math.min(1,he(R[dt],y.map(Wt=>he(Wt,R[dt]))))),vt=L&&1-Mt>1e-10?N[dt]/Math.sqrt(q*(1-Mt)):null,Dt=vt===null?null:vt**2*Mt/(i*(1-Mt));return{runId:X.id,order:X.order,block:X.block,settings:ht(X.settings),measured:v[dt],fitted:k[dt],residual:N[dt],leverage:Mt,studentized:vt,cook:Dt,review:Mt>2*i/r||Dt!==null&&Dt>4/r}}),Et=Ve(v.map(X=>(X-vn(v))**2)),Rt=st.every(X=>1-X.leverage>1e-10)?Math.sqrt(vn(st.map(X=>(X.residual/(1-X.leverage))**2))):null;return L||c.warnings.push("Residual variation is zero at numerical precision. Uncertainty intervals are withheld; collect independently varying repeated measurements."),e.condition>1e6&&c.warnings.push("The design is poorly conditioned; coefficients are sensitive to small measurement changes."),st.some(X=>X.review)&&c.warnings.push("Some measurements have high leverage or influence. Review their procedure and provenance; they have not been deleted."),p.audit.some(X=>X.action==="model"&&X.afterCollection)&&c.warnings.push("Model terms changed after data were collected. Treat the revised analysis as exploratory."),c.excluded&&c.warnings.push(`${c.excluded} recorded measurements are excluded with reasons. Compare the sensitivity fit that includes them.`),{...c,ok:!0,inferential:L,coefficients:nt,beta:g,covariance:W,normalizedCovariance:y,critical:Z,mse:q,sse:$,rmse:Math.sqrt(q),r2:Et>(Number.EPSILON*T*64)**2?1-$/Et:null,adjustedR2:Et>(Number.EPSILON*T*64)**2?1-$/S/(Et/(r-1)):null,residuals:st,looRMSE:Rt,assumptions:"Intervals assume independent experimental units, a correctly specified linear mean model, constant residual variance and approximately normal errors. Intervals are pointwise, without adjustment for searching many settings. Confirmation measurements are held out of this fit."}}function $e(h,d,p,s){D(d.ok,d.issue||"Fit the measured data first.");let u=yn(h,p,s,d.columns),M=he(u,d.beta),x=Math.max(0,he(u,d.covariance.map(e=>he(e,u)))),R=Math.sqrt(x),v=Math.sqrt(x+d.mse);return{settings:ht(p),block:s,x:u,mean:M,se:d.inferential?R:null,meanCI:d.inferential?[M-d.critical*R,M+d.critical*R]:null,predictionCI:d.inferential?[M-d.critical*v,M+d.critical*v]:null}}function Xe(h,d,p,s){let u=$e(h,d,p.settings,p.block),M=$e(h,d,s.settings,s.block),x=M.x.map((e,r)=>e-u.x[r]),R=Math.max(0,he(x,d.covariance.map(e=>he(e,x)))),v=M.mean-u.mean;return{A:u,B:M,difference:v,se:d.inferential?Math.sqrt(R):null,ci:d.inferential?[v-d.critical*Math.sqrt(R),v+d.critical*Math.sqrt(R)]:null}}async function Hn(h,d,p){return D(d.ok&&d.inferential&&!d.includeExcluded,"Use a measured primary model with residual uncertainty before planning confirmation."),{trainingRevision:await ye(h),n:d.n,df:d.df,model:ht(h.model),columns:ht(d.columns),matrix:ht(d.matrix),coefficients:ht(d.coefficients),covariance:ht(d.covariance),mse:d.mse,assumptions:d.assumptions,predictions:p.map(s=>$e(h,d,s.settings,s.block))}}function Fe(h){let d=new Map(h.measurements.filter(p=>!p.excluded).map(p=>[p.runId,p]));return h.phases.filter(p=>p.kind==="confirmation").flatMap(p=>p.snapshot.predictions.map(s=>{let u=h.runs.filter(r=>r.phase===p.id&&r.block===s.block&&rt(r.settings)===rt(s.settings)),M=u.filter(r=>d.has(r.id)).map(r=>d.get(r.id).value),x=M.length,R=x?vn(M):null,v=x>1?Math.sqrt(Ve(M.map(r=>(r-R)**2))/((x-1)*x)):null,e=x>1?wn((1+p.snapshot.model.confidence)/2,x-1):null;return{phase:p.label,phaseId:p.id,prediction:s,planned:u.length,n:x,runIds:u.map(r=>r.id),mean:R,ci:v===null?null:[R-e*v,R+e*v],difference:x?R-s.mean:null}}))}var U=h=>String(h??"").replace(/[&<>"']/g,d=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[d]),ut=(h,d=3)=>h==null||!Number.isFinite(h)?"\u2014":Math.abs(h)!==0&&(Math.abs(h)<.001||Math.abs(h)>=1e6)?h.toExponential(2):h.toLocaleString("en-US",{maximumFractionDigits:d}),Bn=(h,d)=>h.length>d?h.slice(0,d-1)+"\u2026":h,Qt=h=>h?`${ut(h[0])} to ${ut(h[1])}`:"Not available",Se=(h,d)=>h.factors.map(p=>`${p.name}: ${d[p.id]}${p.unit?" "+p.unit:""}`).join(" \xB7 "),Ze=["#087f79","#c36443","#7365a7","#397baf","#bd8720","#b85680","#567c32","#525d69"],tn=h=>{let d=Math.min(...h),p=Math.max(...h),s=(p-d||Math.max(1,Math.abs(p)*.1))*.12;return[d-s,p+s]};function pe(h,d,p="run"){let s=new Map(h.measurements.map(r=>[r.runId,r])),u=p==="run"?h.runs.filter(r=>s.has(r.id)).map(r=>({id:r.id,x:r.order,y:s.get(r.id).value,block:r.block,excluded:s.get(r.id).excluded,label:Se(h,r.settings)})):d.ok?d.residuals.map(r=>({id:r.runId,x:r.fitted,y:p==="residual"?r.residual:r.measured,block:r.block,review:r.review,label:Se(h,r.settings)})):[],M=p==="run"?"Measurements in collection order":p==="residual"?"Residuals against fitted response":"Measured and fitted responses",x=p==="run"?"Run order":`Fitted ${h.response.name} (${h.response.unit})`,R=p==="residual"?`Residual (${h.response.unit})`:`${h.response.name} (${h.response.unit})`,v=355+Math.ceil(h.design.blocks.length/3)*22,e=`<rect width="760" height="${v}" fill="#fcfcf8"/><text x="24" y="29" font-size="16" font-weight="650">${U(M)}</text>`;if(!u.length)e+='<text x="380" y="177" text-anchor="middle" fill="#677b78" font-size="15">Your measurements will appear here.</text>';else{let r=tn(u.map(g=>g.x)),i=tn([...u.map(g=>g.y),...p==="residual"?[0]:[]]);if(p==="run"&&r.splice(0,2,0,Math.max(...u.map(g=>g.x))+1),p==="fit"){let g=tn(u.flatMap(y=>[y.x,y.y]));r.splice(0,2,...g),i.splice(0,2,...g)}let c=g=>88+(g-r[0])/(r[1]-r[0])*638,f=g=>270-(g-i[0])/(i[1]-i[0])*205;for(let g=0;g<=4;g++){let y=p==="run"?1+Math.round(g*(r[1]-2)/4):r[0]+g*(r[1]-r[0])/4,k=i[0]+g*(i[1]-i[0])/4;e+=`<path d="M88 ${f(k)}H726" stroke="#e1e8e3"/><text x="77" y="${f(k)+4}" text-anchor="end" font-size="13">${U(ut(k,2))}</text><text x="${c(y)}" y="291" text-anchor="middle" font-size="13">${U(ut(y,2))}</text>`}p==="residual"&&(e+=`<path d="M88 ${f(0)}H726" stroke="#8d9f96" stroke-dasharray="5 4"/>`),p==="fit"&&(e+=`<path d="M${c(r[0])} ${f(r[0])}L${c(r[1])} ${f(r[1])}" stroke="#8d9f96" stroke-dasharray="5 4"/>`);for(let g of u){let y=Ze[h.design.blocks.indexOf(g.block)%Ze.length];e+=`<circle data-run="${U(g.id)}" cx="${c(g.x)}" cy="${f(g.y)}" r="${g.review?6:4.5}" fill="${g.excluded?"#fcfcf8":y}" stroke="${g.review?"#b95332":y}" stroke-width="${g.review?2:1}" tabindex="0"><title>${U(g.id)} \xB7 ${U(g.block)} \xB7 ${U(g.label)} \xB7 ${ut(g.y)}${g.excluded?" \xB7 excluded: "+U(g.excluded):""}</title></circle>`}e+=`<text x="407" y="321" text-anchor="middle" font-size="13"><title>${U(x)}</title>${U(Bn(x,76))}</text><text transform="translate(22 166) rotate(-90)" text-anchor="middle" font-size="13"><title>${U(R)}</title>${U(Bn(R,36))}</text>`}return h.design.blocks.forEach((r,i)=>{let c=28+i%3*245,f=350+Math.floor(i/3)*22;e+=`<circle cx="${c}" cy="${f-4}" r="4" fill="${Ze[i%Ze.length]}"/><text x="${c+10}" y="${f}" font-size="13"><title>${U(r)}</title>${U(r.length>28?r.slice(0,25)+"\u2026":r)}</text>`}),`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 ${v}" role="img" aria-label="${U(M)}" style="font-family:Arial,sans-serif;fill:#173e39">${e}</svg>`}function en(h){if(!h.ok)return"";let d=h.coefficients.filter(x=>x.id!=="intercept"),p=Math.max(180,d.length*39+100),s=tn([0,...d.flatMap(x=>x.ci??[x.value])]),u=x=>290+(x-s[0])/(s[1]-s[0])*425,M=`<rect width="760" height="${p}" fill="#fcfcf8"/><text x="24" y="30" font-size="16" font-weight="650">Model coefficients and ${h.model.confidence*100}% intervals</text><path d="M${u(0)} 48V${p-45}" stroke="#bdccc1" stroke-dasharray="5 4"/>`;d.forEach((x,R)=>{let v=67+R*39,e=x.label.length>35?x.label.slice(0,32)+"\u2026":x.label;M+=`<text x="24" y="${v+4}" font-size="13"><title>${U(x.label)}</title>${U(e)}</text>${x.ci?`<path d="M${u(x.ci[0])} ${v}H${u(x.ci[1])}" stroke="#087f79" stroke-width="3"/>`:""}<circle cx="${u(x.value)}" cy="${v}" r="4.5" fill="#087f79"/>`});for(let x=0;x<=4;x++){let R=s[0]+(s[1]-s[0])*x/4;M+=`<text x="${u(R)}" y="${p-24}" font-size="13" text-anchor="middle">${ut(R)}</text>`}return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 ${p}" role="img" aria-label="Model coefficient intervals" style="font-family:Arial,sans-serif;fill:#173e39">${M}</svg>`}var Jn="@page{size:A4;margin:17mm 15mm}*{box-sizing:border-box}body{font-family:Arial,sans-serif;color:#173e39;font-size:10.5pt;line-height:1.45;margin:0}h1{font-size:30pt;line-height:1.08;letter-spacing:-1pt;margin:8mm 0}h2{font-size:19pt;line-height:1.2;margin:3mm 0 5mm}h3{font-size:12pt;margin:6mm 0 2mm}p{overflow-wrap:anywhere}.eyebrow{font-size:9pt;text-transform:uppercase;letter-spacing:1.5pt;color:#087f79}.subtle{color:#526f67}.page{break-before:page}.page:first-child{break-before:auto}.metrics{display:flex;gap:4mm;margin:7mm 0}.metric{flex:1;background:#eef3ea;padding:4mm}.metric strong{display:block;font-size:21pt}table{width:100%;border-collapse:collapse;font-size:9pt;table-layout:fixed}td,th{padding:2.4mm 1.8mm;border-bottom:1px solid #dbe4db;text-align:left;overflow-wrap:anywhere}th{background:#eef3ea}tr{break-inside:avoid}thead{display:table-header-group}svg{display:block;width:100%;height:auto;break-inside:avoid;margin:4mm 0}.note{padding:4mm;background:#f5eddc;border-left:3px solid #c98934}.hash{font-family:monospace;font-size:8pt;overflow-wrap:anywhere}.procedure li{margin-bottom:2.8mm}a{color:#087f79}.source{break-inside:avoid}footer{font-size:8pt;color:#526f67;margin-top:7mm}h2,h3{break-after:avoid}";function Ne(h,d){return`<table><thead><tr>${h.map(p=>`<th>${U(p)}</th>`).join("")}</tr></thead><tbody>${d.map(p=>`<tr>${p.map(s=>`<td>${U(s)}</td>`).join("")}</tr>`).join("")}</tbody></table>`}function xn(h,d=ke(h)){let p=Qe(h),s=h.model.confidence*100,u=Fe(h),M=h.sources.map(x=>`<div class="source"><h3>${U(x.name)}</h3><p>${U(x.unit)} \xB7 mapped ${U(x.mapping.runId)} \u2192 run id, ${U(x.mapping.response)} \u2192 response</p><p class="hash">SHA-256 ${U(x.sha256)}</p></div>`).join("");return`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${U(h.title)} \u2014 experiment report</title><style>${Jn}</style></head><body>+<section class="page"><div class="eyebrow">Signal / Experiment report</div><h1>${U(h.title)}</h1>${h.evidenceNote?`<p class="note">${U(h.evidenceNote)}</p>`:""}<p style="font-size:15pt">${U(h.question)}</p><div class="metrics"><div class="metric"><strong>${h.runs.length}</strong>planned runs</div><div class="metric"><strong>${h.measurements.length}</strong>measured</div><div class="metric"><strong>${d.n}</strong>in primary fit</div></div><h2>The decision</h2><p>${U(h.conclusion||"No conclusion has been recorded. Interpret the measured evidence and confirmation results before deciding what to change.")}</p><h3>Measurement</h3><p>${U(h.response.name)} (${U(h.response.unit)}). Goal: ${U(h.response.goal)}${h.response.goal==="target"?" "+ut(h.response.target)+" "+U(h.response.unit):""}.</p><h3>Independent experimental unit</h3><p>${U(h.protocol.unit)}</p><h3>Planned analysis</h3><p>${U(h.protocol.analysisPlan)}</p><p class="note">${U(d.ok?d.assumptions:d.issue)}</p><footer>Editable source, original CSVs, run sheet, design matrix and a Python reproduction script accompany this report.<strong>Method references</strong><p><a href="https://www.itl.nist.gov/div898/handbook/pri/section3/pri3331.htm">NIST: factorial designs</a> \xB7 <a href="https://www.itl.nist.gov/div898/handbook/pri/section3/pri337.htm">center/control scheduling</a> \xB7 <a href="https://www.itl.nist.gov/div898/handbook/pri/section4/pri46.htm">confirmation runs</a>. Numerical SVD: ml-matrix 6.15.0; Student-t quantiles: jstat 1.9.6. Full notices included.</p></footer></section>+<section class="page"><div class="eyebrow">01 / Protocol</div><h2>A test someone else can repeat</h2>${Ne(["Factor","Planned levels","Unit"],h.factors.map(x=>[x.name,x.levels.join(" / "),x.unit||"category"]))}<h3>Run allocation</h3><p>${h.design.replicates} independent repetitions of every combination per complete block. Blocks: ${U(h.design.blocks.join(", "))}. Seed: ${U(h.design.seed)}. ${h.design.controls} scheduled controls per block; numeric midpoints and the first categorical level.</p><p>${U(h.protocol.randomization)}</p><ol class="procedure">${h.protocol.steps.map(x=>`<li>${U(x)}</li>`).join("")}</ol><p>${U(h.protocol.notes)}</p><p class="subtle">${h.approved?"Protocol approved and locked.":"Protocol not yet approved."} Planned model rank ${p.rank}/${p.parameters}; ${p.df} residual degrees of freedom if every training run is measured.</p></section>+<section class="page"><div class="eyebrow">02 / Observations</div><h2>Keep the evidence visible</h2>${pe(h,d,"run")}<p>Hollow points are excluded with recorded reasons; all originals remain in the delivery. Colors identify the declared blocks.</p><h3>Collection status</h3><p>${d.pending} pending \xB7 ${d.excluded} excluded \xB7 ${d.confirmation} held-out confirmation measurements.</p>${Ne(["Run",h.response.name+" ("+h.response.unit+")","Source / reason"],h.measurements.slice(0,8).map(x=>[x.runId,ut(x.value),x.excluded||(x.origin.kind==="csv"?x.origin.source+", line "+x.origin.row:"Direct entry")]))}<p class="subtle">${h.measurements.length>8?"First eight measurements shown here. ":""}The complete measurements.csv and source files contain every recorded row.</p></section>+<section class="page"><div class="eyebrow">03 / Analysis</div><h2>What the measurements support</h2>${d.ok?`<div class="metrics"><div class="metric"><strong>${ut(d.rmse)}</strong>residual SD (${U(h.response.unit)})</div><div class="metric"><strong>${d.df}</strong>residual df</div><div class="metric"><strong>${ut(d.looRMSE)}</strong>leave-one-out RMSE</div></div>${Ne(["Term","Coefficient",s+"% interval"],d.coefficients.map(x=>[x.label,ut(x.value),Qt(x.ci)]))}<p>Numeric factors are coded \u22121 at the lowest planned level and +1 at the highest; category effects use the first level as reference. Coefficients use these coded units. Intervals are pointwise and model dependent.</p>${en(d)}`:`<p class="note">${U(d.issue)}</p>`}</section>+${d.ok?`<section class="page"><div class="eyebrow">04 / Diagnostics</div><h2>Check what the model has missed</h2>${pe(h,d,"residual")}<p>Review curvature, changing residual spread and run-order patterns. Outlined points cross a leverage or influence review threshold; they remain in the fit.</p>${d.warnings.map(x=>`<p class="note">${U(x)}</p>`).join("")}${d.residuals.some(x=>x.review)?Ne(["Run","Residual","Leverage","Cook\u2019s distance"],d.residuals.filter(x=>x.review).slice(0,8).map(x=>[x.runId,ut(x.residual),ut(x.leverage),ut(x.cook)])):"<p>No observations cross the displayed review thresholds.</p>"}<p class="subtle">Leverage > 2p/n or Cook\u2019s distance > 4/n prompts review, not automatic deletion. At most eight flagged rows are listed here; analysis.json retains every diagnostic. A favorable diagnostic does not establish the experimental assumptions.</p></section>`:""}+<section class="page"><div class="eyebrow">05 / Follow-up and provenance</div><h2>Test the prediction with new runs</h2>${u.length?u.map(x=>`<h3>${U(x.phase)} \xB7 ${U(x.prediction.block)}</h3><p>${U(Se(h,x.prediction.settings))}</p>${Ne(["Frozen prediction","New measurements","Actual minus predicted"],[[ut(x.prediction.mean)+" \xB7 mean CI "+Qt(x.prediction.meanCI),x.n+"/"+x.planned+" measured \xB7 mean "+ut(x.mean)+" \xB7 own CI "+Qt(x.ci),ut(x.difference)]])}<p class="subtle">Original interval for one new observation: ${Qt(x.prediction.predictionCI)}. The observed mean\u2019s interval uses only the new repetitions. It is not a pass/fail test.</p>`).join(""):"<p>No confirmation phase yet. Compare settings, freeze the prediction and collect fresh independent runs before treating a candidate as established.</p>"}<h2>Original files</h2>${M||"<p>No CSV files imported. Direct measurements are recorded in the change log.</p>"}<h3>Change log</h3><p>${h.audit.length} changes preserved in project.signal.json and audit.json, including model changes, corrections and exclusions.</p></section>+</body></html>`}function Mn(h){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${U(h.title)} \u2014 collection sheet</title><style>${Jn}@page{size:A4 landscape;margin:14mm}td{height:11mm}table{font-size:9pt}h1{font-size:23pt}</style></head><body><div class="eyebrow">Signal / Collection sheet</div><h1>${U(h.title)}</h1><p>${U(h.response.name)} in ${U(h.response.unit)} \xB7 one result per ${U(h.protocol.unit)} \xB7 seed ${U(h.design.seed)}</p>${Ne(["Run / order","Phase / block",...h.factors.map(d=>d.name+(d.unit?" ("+d.unit+")":"")),h.response.name+" ("+h.response.unit+")","Notes / departure"],h.runs.map(d=>[d.id+" / "+d.order,d.phase+" / "+d.block+(d.kind==="control"?" \xB7 control":""),...h.factors.map(p=>d.settings[p.id]),"",""]))}<footer>Keep the run ids when importing measurements. Leave unmeasured responses blank. Do not enter predicted values as measured results.</footer></body></html>`}function Kn(h,d,p){let s=ke(h),u={"experiment.html":d,"project.signal.json":JSON.stringify(h,null,2)+`+`,"collection.csv":Me(h),"measurements.csv":Me(h,{blank:!1}),"report.html":xn(h,s),"collection-sheet.html":Mn(h),"analysis.json":JSON.stringify(s,null,2)+`+`,"confirmations.json":JSON.stringify(Fe(h),null,2)+`+`,"audit.json":JSON.stringify(h.audit,null,2)+`+`,"design-matrix.csv":mn([["run_id",...s.columns.map(M=>M.id),"measured_response"],...s.matrix.X.map((M,x)=>[s.matrix.runIds[x],...M,s.matrix.y[x]])]),"charts/collection.svg":pe(h,s,"run"),"charts/residuals.svg":pe(h,s,"residual"),"reproduce.py":p.reproduce,"requirements.txt":p.requirements,"THIRD_PARTY_LICENSES.txt":p.licenses,"README.txt":`SIGNAL \u2014 ${h.title}-function experiment(seed, { count = 120, effect = 12, noise = 9 } = {}) {- const xRng = random(seed, "temperature"),- noiseRng = random(seed, "measurement");- return Array.from({ length: count }, (_, i) => {- const group = i % 2,- x = 15 + xRng() * 70;- return {- id: i + 1,- group,- x,- y: 28 + x * 0.48 + effect * group + normal(noiseRng) * noise,- };- });-}-function stats(values) {- const n = values.length,- mean = n ? values.reduce((a, b) => a + b, 0) / n : 0;- const variance =- n > 1 ? values.reduce((a, b) => a + (b - mean) ** 2, 0) / (n - 1) : 0;- return { n, mean, variance, sd: Math.sqrt(variance) };-}-function regression(points) {- const x = stats(points.map((p) => p.x)),- y = stats(points.map((p) => p.y));- const xx = points.reduce((a, p) => a + (p.x - x.mean) ** 2, 0);- const xy = points.reduce((a, p) => a + (p.x - x.mean) * (p.y - y.mean), 0);- const slope = xx ? xy / xx : 0,- intercept = y.mean - slope * x.mean;- const ss = points.reduce((a, p) => a + (p.y - y.mean) ** 2, 0);- const residual = points.reduce(- (a, p) => a + (p.y - intercept - slope * p.x) ** 2,- 0,- );- return { slope, intercept, r2: ss ? clamp(1 - residual / ss, 0, 1) : 1 };-}-function treatmentEffect(points) {- const a = stats(points.filter((p) => p.group === 0).map((p) => p.y));- const b = stats(points.filter((p) => p.group === 1).map((p) => p.y));- const difference = b.mean - a.mean,- se = Math.sqrt(- a.variance / Math.max(1, a.n) + b.variance / Math.max(1, b.n),- );- return {- a,- b,- difference,- low: difference - 1.96 * se,- high: difference + 1.96 * se,- };-}-function csvRows(points) {- return (- "sample,group,temperature_c,yield_percent\n" +- points- .map(- (p) =>- `${p.id},${p.group ? "treatment" : "control"},${p.x.toFixed(6)},${p.y.toFixed(6)}`,- )- .join("\n") +- "\n"- );-}+Open experiment.html in a modern browser to edit, inspect and continue collecting offline. Open project.signal.json to retain the entire source and original inputs. The studio does not invent missing responses.-</script>-<script>-'use strict';-const $ = (s) => document.querySelector(s);-const $$ = (s) => [...document.querySelectorAll(s)];-const params = new URLSearchParams(location.search);-let seed = (params.get("seed") || "42").slice(0, 128);-const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;-const parentMessage = (message) => {- if (parent !== window) parent.postMessage(message, "*");-};-function toast(message) {- $("#toast").textContent = message;- clearTimeout(toast.timer);- toast.timer = setTimeout(() => {- $("#toast").textContent = "";- }, 3500);-}-function saveFile(name, content, type = "application/json") {- const blob =- content instanceof Blob ? content : new Blob([content], { type });- const url = URL.createObjectURL(blob),- a = document.createElement("a");- a.href = url;- a.download = name;- document.body.append(a);- a.click();- a.remove();- setTimeout(() => URL.revokeObjectURL(url), 30000);-}-function canvasPNG(canvas, name) {- canvas.toBlob((blob) => {- if (blob) saveFile(name, blob);- else toast("Image export failed. Please try again.");- });-}-function setSeed(value) {- seed = String(value).trim().slice(0, 128) || "42";- $("#seed").value = seed;- const url = new URL(location.href);- url.searchParams.set("seed", seed);- try {- history.replaceState(null, "", url);- } catch {- /* Opaque-origin iframe: the shell owns its URL. */- }- parentMessage({ type: "harness:state", seed });- dispatchEvent(new CustomEvent("seedchange", { detail: seed }));-}-$("#seed").value = seed;-$("#seed-form").addEventListener("submit", (e) => {- e.preventDefault();- setSeed($("#seed").value);-});-$("#next-seed").addEventListener("click", () =>- setSeed(/^\d{1,9}$/.test(seed) ? Number(seed) + 1 : hash(seed)),-);-function fitCanvas(canvas, draw, maxDpr = 2) {- const observer = new ResizeObserver(() => {- const box = canvas.getBoundingClientRect(),- dpr = Math.min(devicePixelRatio || 1, maxDpr);- canvas.width = Math.max(1, Math.round(box.width * dpr));- canvas.height = Math.max(1, Math.round(box.height * dpr));- draw?.();- });- observer.observe(canvas);- return observer;-}-const editable = (target) =>- target instanceof Element &&- !!target.closest("input,textarea,select,[contenteditable=true]");-addEventListener("error", (e) =>- parentMessage({ type: "harness:error", message: e.message }),-);-addEventListener("unhandledrejection", (e) =>- parentMessage({- type: "harness:error",- message: String(e.reason?.message || e.reason),- }),-);-function ready() {- document.body.dataset.ready = "true";- parentMessage({ type: "harness:ready", title: document.title, seed });-}+Print collection-sheet.html at actual size, or fill collection.csv without changing run ids. Blank responses are pending. Measurements and corrections remain in the project and audit.json; original CSV bytes are in sources/.-let points = [],- visible = [],- showControl = true,- showTreatment = true,- collected = Infinity,- collectTimer;-const groupColors = ["#73b3b5", "#efc273"];-function experimentOptions() {- return {- effect: +$("#effect").value,- noise: +$("#noise").value,- count: +$("#count").value,- };-}-function drawChart() {- const c = $("#chart"),- ctx = c.getContext("2d"),- w = c.width,- h = c.height;- if (!w || !h) return;- const d = w / c.getBoundingClientRect().width,- m = { l: 53 * d, r: 22 * d, t: 24 * d, b: 48 * d };- const low = Math.floor(Math.min(0, ...points.map((p) => p.y)) / 20) * 20,- high = Math.ceil(Math.max(100, ...points.map((p) => p.y)) / 20) * 20;- const px = (x) => m.l + (x / 100) * (w - m.l - m.r),- py = (y) => h - m.b - ((y - low) / (high - low)) * (h - m.b - m.t);- ctx.clearRect(0, 0, w, h);- ctx.font = `${10 * d}px monospace`;- ctx.lineWidth = d;- ctx.textAlign = "right";- ctx.textBaseline = "middle";- for (let i = 0; i <= 5; i++) {- const y = low + ((high - low) * i) / 5;- ctx.strokeStyle = "#8ea4aa20";- ctx.beginPath();- ctx.moveTo(m.l, py(y));- ctx.lineTo(w - m.r, py(y));- ctx.stroke();- ctx.fillStyle = "#98abb1";- ctx.fillText(y.toFixed(0), m.l - 12 * d, py(y));- const x = i * 20;- ctx.textAlign = "center";- ctx.fillText(x, px(x), h - m.b + 20 * d);- ctx.textAlign = "right";- }- ctx.save();- ctx.translate(15 * d, h / 2);- ctx.rotate(-Math.PI / 2);- ctx.textAlign = "center";- ctx.fillText("Yield (%)", 0, 0);- ctx.restore();- ctx.textAlign = "center";- ctx.fillText("Temperature (°C)", w / 2, h - 10 * d);- for (const group of [0, 1]) {- const subset = visible.filter((p) => p.group === group);- if (subset.length < 2) continue;- const r = regression(subset);- ctx.strokeStyle = groupColors[group];- ctx.globalAlpha = 0.7;- ctx.setLineDash([5 * d, 4 * d]);- ctx.beginPath();- ctx.moveTo(px(10), py(r.intercept + r.slope * 10));- ctx.lineTo(px(90), py(r.intercept + r.slope * 90));- ctx.stroke();- ctx.setLineDash([]);- }- visible.forEach((p) => {- ctx.globalAlpha = 0.85;- ctx.fillStyle = groupColors[p.group];- ctx.beginPath();- ctx.arc(px(p.x), py(p.y), 3.5 * d, 0, Math.PI * 2);- ctx.fill();- });- ctx.globalAlpha = 1;- drawChart.project = (p) => ({ x: px(p.x) / d, y: py(p.y) / d });-}-function drawInterval() {- const c = $("#interval-chart"),- ctx = c.getContext("2d"),- w = c.width,- h = c.height;- const e = treatmentEffect(points.slice(0, collected)),- min = Math.min(-20, e.low - 3),- max = Math.max(30, e.high + 3),- px = (v) => 25 + ((v - min) / (max - min)) * (w - 50);- ctx.clearRect(0, 0, w, h);- ctx.strokeStyle = "#98abb1";- ctx.lineWidth = 1;- ctx.beginPath();- ctx.moveTo(25, h * 0.5);- ctx.lineTo(w - 25, h * 0.5);- ctx.stroke();- ctx.setLineDash([3, 4]);- ctx.beginPath();- ctx.moveTo(px(0), h * 0.15);- ctx.lineTo(px(0), h * 0.7);- ctx.stroke();- ctx.setLineDash([]);- ctx.lineWidth = 7;- ctx.strokeStyle = "#efc273";- ctx.beginPath();- ctx.moveTo(px(e.low), h * 0.5);- ctx.lineTo(px(e.high), h * 0.5);- ctx.stroke();- ctx.fillStyle = "#e9efe9";- ctx.beginPath();- ctx.arc(px(e.difference), h * 0.5, 7, 0, Math.PI * 2);- ctx.fill();- ctx.fillStyle = "#98abb1";- ctx.font = "18px monospace";- ctx.textAlign = "center";- ctx.fillText("0", px(0), h * 0.9);- ctx.fillText("95% interval", w / 2, h * 0.12);-}-function updateBench() {- const partial = points.slice(0, collected);- visible = partial.filter((p) => (p.group ? showTreatment : showControl));- const e = treatmentEffect(partial),- r = regression(visible);- $("#sample-count").textContent = visible.length;- $("#effect-estimate").textContent =- `${e.difference >= 0 ? "+" : ""}${e.difference.toFixed(1)}`;- $("#r-squared").textContent = visible.length > 1 ? r.r2.toFixed(2) : "—";- $("#conclusion").textContent =- e.low > 0- ? "A positive signal emerges."- : e.high < 0- ? "The catalyst reduces yield."- : "The effect is still uncertain.";- $("#interval").textContent =- `95% interval: ${e.low.toFixed(1)} to ${e.high.toFixed(1)} percentage points · both groups, ${partial.length} samples.`;- $("#observations").replaceChildren();- visible.slice(0, 12).forEach((p) => {- const tr = document.createElement("tr");- for (const text of [- p.id,- p.group ? "Catalyst" : "Control",- p.x.toFixed(2),- p.y.toFixed(2),- ]) {- const td = document.createElement("td");- td.textContent = text;- tr.append(td);- }- $("#observations").append(tr);- });- drawChart();- drawInterval();-}-function generateExperiment() {- clearInterval(collectTimer);- collected = Infinity;- $("#run").textContent = "Replay collection";- const options = experimentOptions();- points = experiment(seed, options);- $("#effect-value").value = `${options.effect} pp`;- $("#noise-value").value = `±${options.noise} σ`;- $("#count-value").value = options.count;- updateBench();-}-for (const id of ["effect", "noise", "count"])- $("#" + id).oninput = generateExperiment;-$("#control").onclick = () => {- if (showControl && !showTreatment)- return toast("Keep at least one group visible.");- showControl = !showControl;- $("#control").setAttribute("aria-pressed", showControl);- updateBench();-};-$("#treatment").onclick = () => {- if (showTreatment && !showControl)- return toast("Keep at least one group visible.");- showTreatment = !showTreatment;- $("#treatment").setAttribute("aria-pressed", showTreatment);- updateBench();-};-$("#run").onclick = () => {- if (Number.isFinite(collected)) {- collected = Infinity;- clearInterval(collectTimer);- $("#run").textContent = "Replay collection";- updateBench();- return;- }- collected = 4;- $("#run").textContent = "Finish collection";- updateBench();- collectTimer = setInterval(() => {- collected += 4;- if (collected >= points.length) {- collected = Infinity;- clearInterval(collectTimer);- $("#run").textContent = "Replay collection";- }- updateBench();- }, 90);-};-$("#chart").onpointermove = (e) => {- const box = e.currentTarget.getBoundingClientRect(),- x = e.clientX - box.left,- y = e.clientY - box.top;- let best,- dist = Infinity;- for (const p of visible) {- const pos = drawChart.project(p),- d = Math.hypot(pos.x - x, pos.y - y);- if (d < dist) {- best = p;- dist = d;- }- }- $("#probe").textContent =- best && dist < 25- ? `Sample ${best.id} · ${best.group ? "Catalyst" : "Control"} · ${best.x.toFixed(2)} °C · ${best.y.toFixed(2)}% yield`- : "Hover a point to inspect an observation.";-};-$("#export-csv").onclick = () =>- saveFile(`signal-${hash(seed)}.csv`, csvRows(visible), "text/csv");-fitCanvas($("#chart"), drawChart);-fitCanvas($("#interval-chart"), drawInterval);-addEventListener("seedchange", generateExperiment);-generateExperiment();-ready();+The report describes the model and assumptions. Numeric settings use planned-range coding, categorical terms use the first level as reference and blocks are fixed effects. Confirmation runs remain outside the training fit. A prediction interval describes one new observation; a mean confidence interval describes the model mean. These are pointwise intervals, not a guarantee of an optimum.+To independently repeat the fitted calculations, use Python 3.9\u20133.12, install requirements.txt into an isolated environment, and run python reproduce.py. The script reads the exact delivered matrix and writes reproduction.json. No Python is required for the browser studio.++Original implementation and Signal identity: OpenHarness contributors, MIT. Numerical library notices are included.+`,"LICENSE.txt":p.license};s.ok&&(u["charts/coefficients.svg"]=en(s),u["charts/measured-fitted.svg"]=pe(h,s,"fit")),s.ok&&h.comparison&&(u["comparison.json"]=JSON.stringify(Xe(h,s,h.comparison.a,h.comparison.b),null,2)+`+`);for(let M of h.sources)u["sources/"+M.id+".csv"]=Ge(M.base64);for(let M of h.phases.filter(x=>x.kind!=="plan"))u["followup/"+M.id+".csv"]=Me(h,{phase:M.id});return s.excluded&&(u["sensitivity-all-recorded.json"]=JSON.stringify(ke(h,{includeExcluded:!0}),null,2)+`+`),u}function Wn(h){Array.isArray(h)||(h=Object.entries(h));let d=new TextEncoder,p=[],s=[],u=0;for(let[v,e]of h){let r=d.encode(v),i=typeof e=="string"?d.encode(e):new Uint8Array(e),c=4294967295;for(let N of i){c^=N;for(let $=0;$<8;$++)c=c>>>1^3988292384&-(c&1)}c=(c^4294967295)>>>0;let f=new Uint8Array(30+r.length),g=new DataView(f.buffer);g.setUint32(0,67324752,!0),g.setUint16(4,20,!0),g.setUint16(6,2048,!0),g.setUint16(12,33,!0),g.setUint32(14,c,!0),g.setUint32(18,i.length,!0),g.setUint32(22,i.length,!0),g.setUint16(26,r.length,!0),f.set(r,30);let y=new Uint8Array(46+r.length),k=new DataView(y.buffer);k.setUint32(0,33639248,!0),k.setUint16(4,20,!0),k.setUint16(6,20,!0),k.setUint16(8,2048,!0),k.setUint16(14,33,!0),k.setUint32(16,c,!0),k.setUint32(20,i.length,!0),k.setUint32(24,i.length,!0),k.setUint16(28,r.length,!0),k.setUint32(42,u,!0),y.set(r,46),p.push(f,i),s.push(y),u+=f.length+i.length}let M=s.reduce((v,e)=>v+e.length,0),x=new Uint8Array(22),R=new DataView(x.buffer);return R.setUint32(0,101010256,!0),R.setUint16(8,h.length,!0),R.setUint16(10,h.length,!0),R.setUint32(12,M,!0),R.setUint32(16,u,!0),new Blob([...p,...s,x],{type:"application/zip"})}var Be=JSON.parse(document.querySelector("#signal-data").textContent),Kr=document.documentElement.outerHTML,It=h=>document.querySelector(h),Xn=It("#main"),_e=It("#dialog"),j=xt(Be.project),ne=xe(j),rn="plan",De="run",ct,ge,Tt=null,ve=Be.project.revision,Zt=null,ue=!1,ce=!1,Yn,$n=!1,Ue=null,Le=null,we=null,re,Jt,He=null,Zn="signal-draft:"+j.id,Wo=j.id;var jt=(h,d,p,s="")=>`<label>${U(h)}<input name="${U(d)}" value="${U(p)}" ${s}></label>`,Ft=(h,d,p,s=3,u="")=>`<label>${U(h)}<textarea name="${U(d)}" rows="${s}" ${u}>${U(p)}</textarea></label>`,le=(h,d,p)=>`<option value="${U(h)}" ${p?"selected":""}>${U(d)}</option>`,tr=(h,d="")=>`<span class="pill ${d}">${U(h)}</span>`,Kt=(h,d,p=!1)=>`<div class="metric ${p?"accent":""}"><strong>${U(h)}</strong><span>${U(d)}</span></div>`,Ce=(h,d,p="")=>`<div class="table-scroll"><table ${p}><thead><tr>${h.map(s=>`<th>${U(s)}</th>`).join("")}</tr></thead><tbody>${d.join("")}</tbody></table></div>`,sn=(h,d,p)=>`<div class="hero"><div><div class="eyebrow">${h} / ${["Design a fair test","Keep the evidence","Read the signal","Learn, then test again"][Number(h)-1]}</div><h1>${U(d)}</h1><p>${U(p)}</p></div><div class="stage-number">${h}</div></div>`;function qt(h,d=!1){let p=It("#toast");p.textContent=h,p.hidden=!1,p.classList.toggle("error",d),clearTimeout(Yn),Yn=setTimeout(()=>{p.hidden=!0},d?12e3:6500)}function Xt(h,d,p="application/octet-stream"){let s=d instanceof Blob?d:new Blob([d],{type:p}),u=URL.createObjectURL(s),M=document.createElement("a");M.href=u,M.download=h,M.click(),setTimeout(()=>URL.revokeObjectURL(u),1e4)}function qe(){try{localStorage.setItem(Zn,JSON.stringify({baseRevision:ve,project:j}))}catch{qt("Browser storage is full. Save to your workspace or download the editable project to keep this change.",!0)}}function Ie(){let h=j.design.blocks[0];re={settings:Object.fromEntries(j.factors.map(d=>[d.id,d.levels[0]])),block:h},Jt={settings:Object.fromEntries(j.factors.map(d=>[d.id,d.levels.at(-1)])),block:h}}function te(h,{resetCandidates:d=!1}={}){h=xt(h),An(j,h),j=ne.push(h),ue=!0,ce=!1,d&&Ie(),qe(),ee()}function Wr(h=j){let d=new DOMParser().parseFromString(Kr,"text/html");return d.querySelector("#signal-data").textContent=JSON.stringify({project:h,assets:Be.assets}).replace(/</g,"\\u003c"),d.title=h.title+" \u2014 Signal",`<!doctype html>+`+d.documentElement.outerHTML}function on(){return ce?(qt("Apply your form changes first, or use \u201CDiscard form edits\u201D.",!0),!1):!0}function kn(h){It("#dialog-content").innerHTML=h,_e.open||_e.showModal()}function Yr(){let h=fe(j),d=h?"disabled":"";return sn("01",j.title,j.question)+`<div class="metrics">${Kt(j.runs.length,"runs in your collection sheet",!0)}${Kt(j.factors.length,"factors you can change")}${Kt(j.design.blocks.length,"complete blocks")}${Kt(ge.rank+"/"+ge.parameters,"model terms distinguishable")}</div>+ ${h?`<div class="strip"><strong>${j.approved?"Protocol approved":"Collection has started"}</strong>The original conditions and run order are preserved. Add another phase from Next experiment, or begin a separate project for a different protocol.</div>`:""}+ <form id="plan-form"><div class="two-col"><div>+ <section class="card"><h2>The question</h2><div class="form-grid">${jt("Experiment name","title",j.title,d+' required maxlength="160" class="span-all"')}${Ft("What will this experiment help you decide?","question",j.question,3,d+" required")}${jt("Measured response","response-name",j.response.name,d+" required")}${jt("Response unit","response-unit",j.response.unit,d+" required")}+ <label>Goal<select name="goal" ${d}>${["maximize","minimize","target"].map(p=>le(p,p==="target"?"Approach a target":p==="maximize"?"Larger is better":"Smaller is better",j.response.goal===p)).join("")}</select></label>${jt("Target (used for target goal)","target",j.response.target??0,d+' type="number" step="any"')}</div></section>+ <section class="card"><div class="section-head"><h2>What you can vary</h2><button type="button" data-action="add-factor" ${d}>+ Add factor</button></div><div class="factor-grid">${j.factors.map((p,s)=>`<div class="factor"><div class="factor-head"><strong>FACTOR ${String(s+1).padStart(2,"0")}</strong><button type="button" data-action="remove-factor" data-id="${U(p.id)}" ${d||(j.factors.length===1?"disabled":"")}>Remove</button></div><div class="form-grid">${jt("Name","factor-name-"+p.id,p.name,d+" required")}<label>Type<select name="factor-type-${U(p.id)}" ${d}>${le("number","Numeric",p.type==="number")}${le("category","Category",p.type==="category")}</select></label>${jt("Unit","factor-unit-"+p.id,p.unit,d)}${Ft("Levels \xB7 one per line","factor-levels-"+p.id,p.levels.join(`+`),3,d+" required")}</div></div>`).join("")}</div><p class="helper">Every combination is tested. Numeric factors use the low and high levels to code the model; categories use the first level as the reference.</p></section>+ <section class="card"><h2>A repeatable procedure</h2><div class="form-grid">${Ft("One independent experimental unit","protocol-unit",j.protocol.unit,3,d+" required")}${Ft("How will you randomize and control the conditions?","randomization",j.protocol.randomization,3,d+" required")}${Ft("Procedure \xB7 one step per line","steps",j.protocol.steps.join(`+`),7,d+' required class="span-all"')}${Ft("Analysis planned before collection","analysis-plan",j.protocol.analysisPlan,4,d+" required")}${Ft("Practical notes and departures to record","notes",j.protocol.notes,4,d)}</div></section></div>+ <div><section class="card"><h2>Build your run sheet</h2><div class="form-grid">${jt("Independent repetitions per combination","replicates",j.design.replicates,d+' type="number" min="1" max="20" required')}${jt("Randomization seed","seed",j.design.seed,d+" required")}${Ft("Complete blocks \xB7 one name per line","blocks",j.design.blocks.join(`+`),3,d+" required")}<label>Scheduled controls per block<select name="controls" ${d}>${[0,2,3,4,5].map(p=>le(p,p===0?"None":p+" midpoint / reference controls",j.design.controls===p)).join("")}</select></label></div><p class="helper">A block repeats every combination under a shared condition, such as a shelf or a material lot. Controls bracket and span each block; they use numeric midpoints and the first category level.</p><div class="report-actions"><button class="primary" type="submit" ${d}>Apply plan & rebuild run sheet</button></div></section>+ <section class="card"><h2>Before you collect</h2><div class="check-row"><span>Independent runs</span><span>${j.runs.length}</span></div><div class="check-row"><span>Planned model columns</span><span>${ge.parameters}</span></div><div class="check-row"><span>Identifiable columns</span><span>${ge.rank}</span></div><div class="check-row"><span>Residual degrees of freedom</span><span>${ge.df}</span></div>${ge.rank<ge.parameters?'<div class="strip warn">This design cannot separate all requested model terms. Revise the model or add informative points.</div>':""}<p class="helper">Re-reading one jar, pot or sample does not create another independent run.</p><div class="actions report-actions"><button type="button" data-action="approve" ${h?"disabled":""}>${j.approved?"Approved \u2713":"Approve protocol"}</button><button type="button" data-tab="collect">Collection sheet \u2192</button></div></section>+ <div class="actions"><button type="button" data-action="undo" ${ne.canUndo&&!h?"":"disabled"}>Undo plan edit</button><button type="button" data-action="redo" ${ne.canRedo&&!h?"":"disabled"}>Redo</button><button type="button" data-action="discard-form">Discard form edits</button></div></div></div></form>`}function Gr(){let h=new Map(j.measurements.map(d=>[d.runId,d]));return sn("02","Your evidence, intact.","Use the run sheet in the real world. Import the results or record each measurement here; leave unfinished runs blank.")+`<div class="metrics">${Kt(j.measurements.length,"measured responses",!0)}${Kt(ct.pending,"still to collect")}${Kt(j.sources.length,"original CSV files retained")}${Kt(ct.excluded,"excluded, with reasons")}</div>+ <section class="card"><div class="section-head"><h2>Collection sheet</h2><div class="actions"><button data-action="download-sheet">Download blank CSV</button><button data-action="print-sheet">Printable sheet</button><button data-action="import-csv" class="primary">Import measurements</button></div></div><p class="helper">Response: <strong>${U(j.response.name)} in ${U(j.response.unit)}</strong>. Click a run to record a result, correct a transcription or document an exclusion.</p>+ ${Ce(["Run / order",...j.factors.map(d=>d.name+(d.unit?" \xB7 "+d.unit:"")),"Block","Response \xB7 "+j.response.unit,"State"],j.runs.map(d=>{let p=h.get(d.id);return`<tr data-run="${d.id}"><td><strong>${d.id}</strong><div class="small">${d.order} \xB7 ${d.kind==="control"?"control":d.phase}</div></td>${j.factors.map(s=>`<td>${U(d.settings[s.id])}</td>`).join("")}<td>${U(d.block)}</td><td class="${p?"state-measured":"state-pending"}">${p?ut(p.value):"\u2014"}</td><td><button data-action="measure" data-id="${d.id}">${p?.excluded?"Excluded":p?"Review":"Record"}</button></td></tr>`}))}</section>+ <section class="card"><div class="chart">${pe(j,ct,"run")}</div><div class="plot-tip" id="plot-tip">Hover or focus a point to inspect its run.</div></section>+ <section class="card"><h2>Original files and recorded changes</h2>${j.sources.length?j.sources.map(d=>`<details><summary>${U(d.name)} \xB7 original CSV</summary><p class="small wrap">SHA-256 ${U(d.sha256)}</p><p class="small">${U(d.mapping.runId)} \u2192 run id \xB7 ${U(d.mapping.response)} \u2192 ${U(j.response.name)} \xB7 ${U(d.unit)}</p><button data-action="original-csv" data-id="${U(d.id)}">Download original bytes</button></details>`).join(""):'<p class="muted">No files imported yet. Manual entries keep their own change history.</p>'}<details><summary>Change log \xB7 ${j.audit.length} records</summary>${j.audit.slice().reverse().slice(0,40).map(d=>`<div class="audit-row">${U(d.reason)}<small>${U(d.at)} \xB7 ${U(d.action)}</small></div>`).join("")}<p class="small">The complete log travels with the editable project.</p></details></section>`}function Qr(){let h=j.factors.map(d=>({id:d.id,label:d.name}));for(let d=0;d<j.factors.length;d++)for(let p=d+1;p<j.factors.length;p++)h.push({id:j.factors[d].id+":"+j.factors[p].id,label:j.factors[d].name+" \xD7 "+j.factors[p].name});for(let d of j.factors.filter(p=>p.type==="number"))h.push({id:d.id+"^2",label:d.name+" \xB7 curvature"});return`<form id="model-form"><div class="terms">${h.map(d=>`<label><input type="checkbox" name="term" value="${U(d.id)}" ${j.model.terms.includes(d.id)?"checked":""}>${U(d.label)}</label>`).join("")}<label><input type="checkbox" name="blocks" ${j.model.blocks?"checked":""}>Account for fixed block differences</label></div><label>Pointwise confidence<select name="confidence">${[.8,.9,.95,.99].map(d=>le(d,d*100+"%",j.model.confidence===d)).join("")}</select></label>${Ft("Reason for changing the model","reason","",2,j.measurements.length?"required":"")}<p class="helper">Interactions retain both main effects; curvature retains its numeric main effect. Model changes after looking at results are recorded as exploratory.</p><div class="actions report-actions"><button type="submit">Apply model</button><button type="button" data-action="discard-form">Discard form edits</button></div></form>`}function Xr(){let h=sn("03","What changed the outcome?","Inspect the measurements, the uncertainty and the model\u2019s blind spots before choosing what to try next."),d=`<div class="metrics">${Kt(ct.n,"independent runs in this fit",!0)}${Kt(ct.ok?ut(ct.rmse):"\u2014","residual SD \xB7 "+j.response.unit)}${Kt(ct.ok?ut(ct.looRMSE):"\u2014","leave-one-out prediction RMSE")}${Kt(ct.df,"residual degrees of freedom")}</div>`,p=ct.ok?`<section class="card"><div class="section-head"><h2>Look at the evidence</h2><div class="tabs">${[["run","Run order"],["fit","Measured vs fitted"],["residual","Residuals"]].map(([s,u])=>`<button data-action="plot" data-mode="${s}" class="${De===s?"selected":""}">${u}</button>`).join("")}</div></div><div class="chart">${pe(j,ct,De)}</div><div class="plot-tip" id="plot-tip">Hover or focus a point to inspect its run.</div><p class="helper">${De==="run"?"Look for drift across the collection order or unexpected differences between blocks.":De==="fit"?"The dashed line is a perfect match. Prediction quality on new runs still needs confirmation.":"Look for curvature, changing spread or patterns the chosen terms have missed."}</p></section>+ <section class="card"><h2>Effects, with room for uncertainty</h2><div class="chart">${en(ct)}</div>${Ce(["Model term","Coefficient",j.model.confidence*100+"% interval"],ct.coefficients.map(s=>`<tr><td>${U(s.label)}</td><td>${ut(s.value)}</td><td>${Qt(s.ci)}</td></tr>`))}<p class="helper">Numeric factors are coded from \u22121 to +1 across the planned range. Categories compare with the first level. These are model coefficients, not a ranking of causal importance.</p></section>+ <section class="card"><h2>Measurements worth reviewing</h2>${ct.residuals.some(s=>s.review)?Ce(["Run","Residual","Leverage","Cook\u2019s distance",""],ct.residuals.filter(s=>s.review).map(s=>`<tr><td>${s.runId}</td><td>${ut(s.residual)}</td><td>${ut(s.leverage)}</td><td>${ut(s.cook)}</td><td><button data-action="measure" data-id="${s.runId}">Review original</button></td></tr>`)):'<p class="muted">No rows cross the displayed leverage or influence review thresholds.</p>'}<p class="helper">Leverage > 2p/n or Cook\u2019s distance > 4/n prompts review. Nothing is removed automatically.</p>${ct.excluded?'<button data-action="sensitivity">Compare with all recorded measurements</button>':""}</section>`:`<div class="empty"><h2>${j.measurements.length?"The model needs more evidence.":"Begin with your measurements."}</h2><p>${U(ct.issue)}</p><button data-tab="collect" class="primary">Go to collection</button></div>`;return h+d+`<div class="two-col"><div>${p}</div><div><section class="card"><h2>Your model</h2>${Qr()}</section><section class="card"><h2>Read the uncertainty correctly</h2><p class="small">A mean interval describes the model\u2019s average response at a setting. A prediction interval is wider: it describes one new independent observation.</p><p class="small">The fit assumes independent runs, constant residual variance and a suitable linear mean model with approximately normal errors. The intervals are pointwise; searching many settings does not provide simultaneous coverage.</p>${ct.warnings.map(s=>`<div class="strip warn">${U(s)}</div>`).join("")}<button data-tab="followup" class="primary">Compare the next settings \u2192</button></section></div></div>`}function nn(h,d,p){let s=ct.ok?$e(j,ct,d.settings,d.block):null;return`<div><div class="candidate-title"><h3>${p}</h3>${tr(h.toUpperCase())}</div>${j.factors.map(u=>`<label class="setting">${U(u.name)}${u.unit?" \xB7 "+U(u.unit):""}${u.type==="number"?`<div class="setting-fields"><input type="range" data-candidate="${h}" data-factor="${u.id}" min="${u.levels[0]}" max="${u.levels.at(-1)}" step="${(u.levels.at(-1)-u.levels[0])/100}" value="${d.settings[u.id]}" aria-label="${p} ${U(u.name)} slider"><input type="number" data-candidate="${h}" data-factor="${u.id}" min="${u.levels[0]}" max="${u.levels.at(-1)}" step="any" value="${d.settings[u.id]}" aria-label="${p} ${U(u.name)}"></div>`:`<select data-candidate="${h}" data-factor="${u.id}">${u.levels.map(M=>le(M,M,d.settings[u.id]===M)).join("")}</select>`}</label>`).join("")}<label class="setting">Comparable block<select data-candidate="${h}" data-block="true">${j.design.blocks.map(u=>le(u,u,d.block===u)).join("")}</select></label>${s?`<div class="prediction"><div class="eyebrow">Predicted ${U(j.response.name)}</div><div class="value">${ut(s.mean)} <small style="font-size:17px">${U(j.response.unit)}</small></div><div>${j.model.confidence*100}% mean interval: ${Qt(s.meanCI)}</div><small>One new observation: ${Qt(s.predictionCI)}</small></div>`:'<div class="strip">No response estimate yet. Additional independent runs can help identify the model.</div>'}</div>`}function Gn(){return`<section class="card"><h2>Turn the comparison into a test</h2><form id="followup-form"><div class="form-grid">${jt("Phase name","label","Confirmation "+j.phases.length,"required")}${jt("Independent repetitions per point","repeats",3,'type="number" min="1" max="20" required')}<label class="span-all">Purpose<select name="kind"><option value="confirmation" ${ct.ok&&ct.inferential?"":"disabled"}>Confirm \xB7 keep new data out of original fit</option><option value="extension" ${ct.ok&&ct.inferential?"":"selected"}>Extend \xB7 add new data to the model</option></select></label>${jt("Randomization seed","seed",j.design.seed+"-next-"+j.phases.length,"required")}${Ft("Why this follow-up?","reason","Compare the reference and candidate with fresh independent runs under comparable conditions.",4,"required")}</div><div class="strip">The settings above become labeled, randomized runs. Confirmation keeps a snapshot of today\u2019s forecast. Extension deliberately adds future observations to the training fit.</div><button class="primary" type="submit">Append follow-up runs</button></form></section>`}function Zr(){let h=sn("04","Make the next test count.","Compare candidate settings, freeze the prediction, and put it to a fresh test. The original evidence stays intact.");if(!ct.ok)return h+`<div class="strip warn"><strong>${U(ct.issue)}</strong>You can collect the remaining runs or append an extension at informative settings. Confirmation becomes available after estimating residual uncertainty.</div><div class="two-col"><section class="card"><h2>Choose additional settings</h2><div class="candidate-grid">${nn("a",re,"Point A")}${nn("b",Jt,"Point B")}</div></section><div>${Gn()}</div></div>`;let d=Xe(j,ct,re,Jt),p=M=>j.response.goal==="maximize"?-M:j.response.goal==="minimize"?M:Math.abs(M-j.response.target),s=un(j).map(M=>$e(j,ct,M,Jt.block)).sort((M,x)=>p(M.mean)-p(x.mean)).slice(0,6),u=Fe(j);return h+`<div class="two-col"><div><section class="card"><div class="section-head"><h2>Compare two possibilities</h2>${tr(j.model.confidence*100+"% pointwise intervals")}</div><div class="candidate-grid">${nn("a",re,"Reference")}${nn("b",Jt,"Candidate")}</div><div class="comparison"><div class="eyebrow">Candidate minus reference</div><strong>${ut(d.difference)} ${U(j.response.unit)}</strong><div>Mean difference interval: ${Qt(d.ci)}</div></div><p class="helper">Predictions stay inside the planned ranges. Unmeasured combinations still rely on the model; these intervals do not establish an optimum.</p></section>+ <section class="card"><h2>Explore the planned combinations</h2><p class="helper">The six closest candidates for your stated goal, under the selected block and model. Choose one to compare; this is an exploratory ordering.</p>${Ce(["Settings","Predicted mean",""],s.map((M,x)=>`<tr><td>${U(Se(j,M.settings))}</td><td>${ut(M.mean)} ${U(j.response.unit)}</td><td><button data-action="candidate" data-settings="${U(JSON.stringify(M.settings))}">Compare</button></td></tr>`),'class="ranked"')}</section>+ ${u.length?`<section class="card"><h2>Did the new measurements agree?</h2>${u.map(M=>`<div class="strip"><strong>${U(M.phase)} \xB7 ${M.n}/${M.planned} measured</strong>${U(Se(j,M.prediction.settings))}<div class="form-grid" style="margin-top:15px"><div>Frozen model mean<div class="measure-value">${ut(M.prediction.mean)}</div><span class="small">Mean CI ${Qt(M.prediction.meanCI)}</span></div><div>New measured mean<div class="measure-value">${ut(M.mean)}</div><span class="small">Own CI ${Qt(M.ci)}</span></div></div><p>Actual minus predicted: ${ut(M.difference)} ${U(j.response.unit)}. The original fit does not use these responses.</p><button data-action="phase-csv" data-id="${M.phaseId}">Download this phase\u2019s run sheet</button></div>`).join("")}<p class="helper">Each observed mean interval uses only its fresh repetitions. Comparing it with the original forecast is a diagnostic, not a pass/fail decision rule.</p></section>`:""}</div>+ <div>${Gn()}+ <section class="card"><h2>Record your decision</h2><form id="conclusion-form">${Ft("What do the evidence and practical tradeoffs support?","conclusion",j.conclusion??"",7)}<button type="submit" style="margin-top:14px">Save decision note</button></form><p class="helper">This note accompanies the report. Separate what you measured, what the model predicts and what still needs testing.</p></section><section class="card"><h2>Take the whole experiment with you</h2><p class="small">Keep the source, original files, run sheets, figures, model matrix and Python reproduction script together.</p><div class="actions"><button data-action="report">Download report</button><button data-action="export" class="primary">Export complete kit \u2197</button></div></section></div></div>`}function ee(){ct=ke(j),ge=Qe(j),document.title=j.title+" \u2014 Signal",It("#side-title").textContent=j.title,It("#side-status").innerHTML=`<div class="side-count"><strong>${j.measurements.length}</strong><span class="small">/ ${j.runs.length} measured</span></div><div class="progress"><span style="width:${j.runs.length?j.measurements.length/j.runs.length*100:0}%"></span></div><div class="side-note">${j.approved?"Protocol approved":"Protocol open for review"}<br>${j.sources.length} original files \xB7 ${j.audit.length} recorded changes</div>`;for(let h of document.querySelectorAll("[data-tab]"))h.classList.toggle("active",h.dataset.tab===rn);Xn.innerHTML=(j.evidenceNote?`<div class="strip warn">${U(j.evidenceNote)}</div>`:"")+{plan:Yr,collect:Gr,analyze:Xr,followup:Zr}[rn](),Ae()}function Ae(){It("#save-source").disabled=!Tt||j.id!==Tt.id,It("#connection").textContent=Ue?"Source needs attention \xB7 "+Ue:Tt?j.id!==Tt.id?"Portable project \xB7 download to keep":ue?"Unsaved workspace changes":"Saved in your workspace":"Offline project \xB7 editable and portable";let h=It("#conflict");h.hidden=!Zt&&!He,Zt?h.innerHTML='The workspace source changed while you had a draft. Both versions are available.<div class="actions"><button data-action="download-project">Keep my draft</button><button data-action="incoming-project">Download source</button><button data-action="load-source">Keep draft & load source</button></div>':He&&(h.innerHTML='A previous browser draft belongs to a different source edition.<div class="actions"><button data-action="recovery">Download that draft</button><button data-action="dismiss-recovery">Keep current edition</button></div>')}function to(h){let d=ht(j),p=new FormData(h);return D(!fe(j),"This protocol is locked."),d.title=String(p.get("title")),d.question=String(p.get("question")),d.response={...d.response,name:String(p.get("response-name")),unit:String(p.get("response-unit")),goal:String(p.get("goal")),target:Number(p.get("target"))},d.response.goal==="target"&&D(String(p.get("target")).trim()!=="","Enter a target response."),d.factors=d.factors.map(s=>{let u=String(p.get("factor-type-"+s.id)),M=String(p.get("factor-levels-"+s.id)).split(`+`).map(x=>x.trim()).filter(Boolean);return{...s,name:String(p.get("factor-name-"+s.id)),type:u,unit:String(p.get("factor-unit-"+s.id)),levels:u==="number"?M.map(Number):M}}),d.design={seed:String(p.get("seed")),replicates:Number(p.get("replicates")),blocks:String(p.get("blocks")).split(`+`).map(s=>s.trim()).filter(Boolean),controls:Number(p.get("controls"))},d.protocol={unit:String(p.get("protocol-unit")),randomization:String(p.get("randomization")),steps:String(p.get("steps")).split(`+`).map(s=>s.trim()).filter(Boolean),analysisPlan:String(p.get("analysis-plan")),notes:String(p.get("notes"))},d.model.terms=d.model.terms.filter(s=>!s.endsWith("^2")||d.factors.find(u=>u.id===s.slice(0,-2))?.type==="number"),Bt(d,"plan-edit","Revised the uncollected experimental plan.",{before:{factors:j.factors,response:j.response,design:j.design,protocol:j.protocol,runs:j.runs}}),d.runs=[],d.phases=[],delete d.comparison,cn(d)}function er(h){let d=j.runs.find(s=>s.id===h),p=j.measurements.find(s=>s.runId===h);D(d,"Choose a known run."),kn(`<div class="eyebrow">Run ${U(h)} \xB7 ${U(d.block)}</div><h2>${p?"Review the measurement":"Record what you measured"}</h2><p>${U(Se(j,d.settings))}</p><form id="measurement-form" data-id="${h}"><div class="form-grid">${jt(j.response.name+" ("+j.response.unit+")","value",p?.value??"",'type="number" step="any" required')}${jt("Reason for this entry or correction","reason",p?"":"Direct observation",'required maxlength="600"')}${Ft("Run note","note",p?.note??"",3)}${Ft("Exclusion reason \xB7 leave blank to include","excluded",p?.excluded??"",3)}</div><p class="helper">${p?"Original "+U(p.origin.kind==="csv"?p.origin.source+", line "+p.origin.row:"direct entry")+": "+ut(p.origin.value)+" "+U(j.response.unit)+". Corrections keep this value and the complete change history.":"Enter an actual observation. A blank run is pending; it is never replaced with a model prediction."}</p><div class="actions"><button type="button" data-action="close">Cancel</button><button type="submit" class="primary">${p?"Record change":"Save measurement"}</button></div></form>`)}function eo(){let h=ze(Pe(Le.bytes));we=null,kn(`<div class="eyebrow">Import measurements</div><h2>Match the columns, then review.</h2><p>${U(Le.name)} \xB7 ${h.rows.length} rows \xB7 original bytes will be retained.</p><form id="import-form"><div class="form-grid"><label>Run id column<select name="runId">${h.headers.map(d=>le(d,d,d==="run_id")).join("")}</select></label><label>Measured response column<select name="response">${h.headers.map(d=>le(d,d,d==="response")).join("")}</select></label>${jt("Confirm the response unit","unit",j.response.unit,"required")}</div><p class="helper">Known run ids link each result to its settings. Missing responses remain pending. Duplicate ids, unknown ids, existing results and mismatched settings are rejected together.</p><div id="import-preview"></div><div class="actions"><button type="button" data-action="close">Cancel</button><button type="submit">Preview import</button><button type="button" data-action="commit-import" id="commit-import" class="primary" disabled>Import measurements</button></div></form>`)}async function nr(){let h=new FormData(It("#import-form"));we=await zn(j,Le.bytes,{name:Le.name,mapping:{runId:String(h.get("runId")),response:String(h.get("response"))},unit:String(h.get("unit"))}),It("#import-preview").innerHTML=`<div class="strip"><strong>${we.records.length} measured responses \xB7 ${we.pending} blank cells</strong>Nothing has been applied yet.</div>${Ce(["Run","Measured response","Original line"],we.records.slice(0,5).map(d=>`<tr><td>${d.runId}</td><td>${ut(d.value)} ${U(we.source.unit)}</td><td>${d.row}</td></tr>`))}`,It("#commit-import").disabled=!1}async function no(){D(Tt&&j.id===Tt.id,"Download this portable project or open it in its own workspace."),D(!Zt,"Resolve the source change first; both versions are available.");let h=await me(j),d=await fetch("/api/project",{method:"PUT",headers:{"content-type":"application/json","if-match":ve},body:JSON.stringify(h)}),p=await d.json();if(d.status===409)throw Zt=p.project,Ae(),new Error(p.error);D(d.ok,p.error||"The source could not be saved."),Tt=p.project,ve=Tt.revision,rt(j)===rt(h)&&(j=xt(Tt),ne=xe(j),ue=!1,ce=!1),qe(),ee(),qt(ue?"Saved the submitted edition; your newer changes are still in the draft.":"Saved the complete experiment. The previous source edition is retained in workspace history.")}async function Qn(){if(!($n||!/^https?:$/.test(location.protocol)||!["127.0.0.1","localhost"].includes(location.hostname))){$n=!0;try{let h=await fetch("/api/project");if(h.status===503)return;if(!h.ok){let s=await h.json();Ue!==s.error&&qt("Workspace source needs attention. Your current draft is preserved: "+s.error,!0),Ue=s.error,Ae();return}Ue=null;let d=await h.json();D(d.project,"No source project.");let p=d.project;await me(p),Tt??=p,p.revision!==ve?ue||ce||j.id!==p.id?(Zt=p,Ae()):(Tt=p,ve=p.revision,j=xt(p),ne=xe(j),Ie(),ee()):(Tt=p,Ae())}catch{}finally{$n=!1}}}async function ro(h){let d=h.dataset.action;if(d==="close"){_e.close();return}if(d==="discard-form"){ce=!1,ee();return}if(!(!["original-csv","download-project","incoming-project","recovery","dismiss-recovery"].includes(d)&&!on()))if(d==="open")It("#project-file").value="",It("#project-file").click();else if(d==="download-project")Xt(j.id+".signal.json",JSON.stringify(j,null,2),"application/json");else if(d==="save")await no();else if(d==="export")await me(j),Xt(j.id+"-experiment.zip",Wn(Kn(j,Wr(),Be.assets))),qt("Exported editable studio, original measurements, run sheets, report and reproducible calculations.");else if(d==="report")Xt(j.id+"-report.html",xn(j),"text/html");else if(d==="download-sheet")Xt(j.id+"-collection.csv",Me(j),"text/csv");else if(d==="print-sheet")Xt(j.id+"-collection-sheet.html",Mn(j),"text/html");else if(d==="phase-csv")Xt(j.id+"-"+h.dataset.id+".csv",Me(j,{phase:h.dataset.id}),"text/csv");else if(d==="approve")te(jn(j)),qt("The protocol and original run order are now protected.");else if(d==="undo"||d==="redo")D(!fe(j),"Collected or approved plans use logged revisions."),j=d==="undo"?ne.undo():ne.redo(),ue=!0,qe(),Ie(),ee();else if(d==="add-factor"||d==="remove-factor"){D(!fe(j),"This protocol is locked.");let p=ht(j);if(Bt(p,"plan-edit",d==="add-factor"?"Added a factor before collection.":"Removed a factor before collection.",{before:{factors:j.factors,runs:j.runs}}),d==="add-factor"){D(p.factors.length<6,"Use at most six factors.");let s=1;for(;p.factors.some(M=>M.id==="factor"+s);)s++;let u="factor"+s;p.factors.push({id:u,name:"New factor",type:"number",unit:"",levels:[0,1]}),p.model.terms.push(u)}else p.factors=p.factors.filter(s=>s.id!==h.dataset.id),p.model.terms=p.model.terms.filter(s=>!s.split(":").map(u=>u.replace("^2","")).includes(h.dataset.id));p.runs=[],p.phases=[],delete p.comparison,te(cn(p),{resetCandidates:!0})}else if(d==="measure")er(h.dataset.id);else if(d==="import-csv")It("#csv-file").value="",It("#csv-file").click();else if(d==="commit-import")await nr(),te(Pn(j,we)),_e.close(),qt("Imported measured responses. The original file and exact row references are preserved.");else if(d==="original-csv"){let p=j.sources.find(s=>s.id===h.dataset.id);Xt(p.name,Uint8Array.from(atob(p.base64),s=>s.charCodeAt(0)),"text/csv")}else if(d==="plot")De=h.dataset.mode,ee();else if(d==="candidate"){Jt.settings=JSON.parse(h.dataset.settings);let p=ht(j);p.comparison={a:re,b:Jt},te(p)}else if(d==="sensitivity"){let p=ke(j,{includeExcluded:!0});kn(`<h2>Keep the exclusions visible.</h2><p>The primary fit uses ${ct.n} rows; the sensitivity fit includes all ${p.n} recorded training rows. Confirmation runs stay held out in both.</p>${p.ok&&ct.ok?Ce(["Term","Primary","All recorded","Change"],ct.coefficients.map((s,u)=>`<tr><td>${U(s.label)}</td><td>${ut(s.value)}</td><td>${ut(p.coefficients[u].value)}</td><td>${ut(p.coefficients[u].value-s.value)}</td></tr>`)):`<p>${U(p.issue??ct.issue)}</p>`}<div class="actions"><button data-action="close">Close</button></div>`)}else d==="incoming-project"?Xt(j.id+"-workspace-source.signal.json",JSON.stringify(Zt,null,2),"application/json"):d==="load-source"?(D(Zt,"No source change."),Xt(j.id+"-previous-draft.signal.json",JSON.stringify(j,null,2),"application/json"),j=await me(Zt),Tt=Zt,ve=Tt.revision,Zt=null,ue=!1,ce=!1,ne=xe(j),Ie(),qe(),ee()):d==="recovery"?Xt("recovered-draft.signal.json",JSON.stringify(He.project,null,2),"application/json"):d==="dismiss-recovery"&&(He=null,qe(),Ae())}document.addEventListener("click",h=>{let d=h.target.closest("button");if(d){if(d.dataset.tab){if(!on())return;rn=d.dataset.tab,ee(),window.scrollTo({top:0,behavior:"instant"})}else d.dataset.action&&ro(d).catch(s=>qt(s.message,!0));return}let p=h.target.closest("tr[data-run]");p&&on()&&er(p.dataset.run)});document.addEventListener("submit",h=>{h.preventDefault(),(async()=>{if(h.target.id==="plan-form")te(to(h.target),{resetCandidates:!0}),qt("Updated the plan and randomized the new collection sheet.");else if(h.target.id==="measurement-form"){let d=new FormData(h.target);te(On(j,h.target.dataset.id,{value:d.get("value"),note:String(d.get("note")),excluded:String(d.get("excluded")).trim()||null,reason:String(d.get("reason"))})),_e.close(),qt("Recorded the measurement and its change history.")}else if(h.target.id==="import-form")await nr();else if(h.target.id==="model-form"){let d=new FormData(h.target),p=ht(j),s=d.getAll("term").map(String);for(let M of[...s])for(let x of M.split(":").map(R=>R.replace("^2","")))s.includes(x)||s.unshift(x);let u={terms:s,blocks:d.has("blocks"),confidence:Number(d.get("confidence"))};Bt(p,"model",String(d.get("reason")).trim()||"Revised the model before collecting data.",{before:p.model,after:u,afterCollection:p.measurements.length>0}),p.model=u,te(p),qt("Updated the model. All original measurements are retained.")}else if(h.target.id==="followup-form"){let d=new FormData(h.target),p=[re,Jt].filter((M,x,R)=>R.findIndex(v=>rt(M)===rt(v))===x),s=String(d.get("kind")),u=s==="confirmation"?await Hn(j,ct,p):void 0;te(Tn(j,{points:p,repeats:Number(d.get("repeats")),label:String(d.get("label")),seed:String(d.get("seed")),reason:String(d.get("reason")),kind:s,snapshot:u})),qt("Added a new phase. The original run settings and measurements are unchanged.")}else if(h.target.id==="conclusion-form"){let d=ht(j);d.conclusion=String(new FormData(h.target).get("conclusion")),Bt(d,"decision","Updated the interpretation and decision note.",{before:j.conclusion??"",after:d.conclusion}),te(d),qt("Saved the decision note for the report.")}})().catch(d=>qt(d.message,!0))});document.addEventListener("input",h=>{h.target.closest("#plan-form,#model-form,#conclusion-form,#followup-form")&&(ce=!0),h.target.closest("#import-form")&&(It("#commit-import").disabled=!0,we=null)});document.addEventListener("change",h=>{(async()=>{if(h.target.id==="csv-file"&&h.target.files[0]){let d=h.target.files[0];D(d.size<=1e6,"Use a CSV below 1 MB."),Le={name:d.name,bytes:new Uint8Array(await d.arrayBuffer())},eo()}else if(h.target.id==="project-file"&&h.target.files[0]){let d=h.target.files[0];D(d.size<=5e6,"Use a complete project below 5 MB.");let p=await me(JSON.parse(await d.text()));Xt(j.id+"-before-open.signal.json",JSON.stringify(j,null,2),"application/json"),j=p,ne=xe(j),ue=!0,ce=!1,Zt=null,rn="plan",Ie(),qe(),ee(),qt("Opened the complete experiment and downloaded the previous project for recovery.")}else if(h.target.dataset.candidate){D(on(),"Apply form edits before changing the comparison.");let d=h.target.dataset.candidate,p=ht(d==="a"?re:Jt);if(h.target.dataset.block)p.block=h.target.value;else{let u=j.factors.find(M=>M.id===h.target.dataset.factor);p.settings[u.id]=u.type==="number"?Number(h.target.value):h.target.value}ae(j,p.settings),ct.ok&&$e(j,ct,p.settings,p.block),d==="a"?re=p:Jt=p;let s=ht(j);s.comparison={a:re,b:Jt},te(s)}})().catch(d=>qt(d.message,!0))});for(let h of["pointerover","focusin"])document.addEventListener(h,d=>{let p=d.target.closest("circle[data-run]");p&&It("#plot-tip")&&(It("#plot-tip").textContent=p.querySelector("title").textContent)});window.addEventListener("beforeunload",h=>{ce&&(h.preventDefault(),h.returnValue="")});async function oo(){j=await me(j),ve??=await ye(j),Ie();try{let h=JSON.parse(localStorage.getItem(Zn));h&&(await me(h.project),h.baseRevision===ve?(j=xt(h.project),ue=rt(j)!==rt(xt(Be.project)),ne=xe(j),Ie()):He=h)}catch{}j.comparison&&(re=ht(j.comparison.a),Jt=ht(j.comparison.b)),ee(),await Qn(),setInterval(Qn,2500),document.documentElement.dataset.ready="true"}oo().catch(h=>{Xn.innerHTML=`<div class="strip warn"><h1>Open a valid experiment to continue.</h1><p>${U(h.message)}</p></div>`,qt(h.message,!0)});})();</script></body></html>diff --git a/store/agents/lab-bench/template/bench/project.json b/store/agents/lab-bench/template/bench/project.jsonnew file mode 100644index 000000000..218ce0ccf--- /dev/null+++ b/store/agents/lab-bench/template/bench/project.json@@ -0,0 +1,257 @@+{+ "spec": 1,+ "id": "clearwater",+ "title": "Clearwater Coffee",+ "question": "Which steeping time and coffee dose bring extraction closest to our target, with a repeatable process?",+ "response": {+ "id": "extraction",+ "name": "Extraction yield",+ "unit": "%",+ "goal": "target",+ "target": 19+ },+ "factors": [+ {+ "id": "steep",+ "name": "Steeping time",+ "type": "number",+ "unit": "h",+ "levels": [+ 8,+ 16+ ]+ },+ {+ "id": "dose",+ "name": "Coffee dose",+ "type": "number",+ "unit": "g/L",+ "levels": [+ 60,+ 90+ ]+ }+ ],+ "protocol": {+ "unit": "One separately prepared brewing jar. Repeated readings from the same jar are not independent runs.",+ "randomization": "Prepare separate jars in the randomized order within the water batch. Keep the scheduled midpoint controls at the beginning, middle and end.",+ "analysisPlan": "Use the planned time, dose and interaction terms. Examine residuals and repeatability. Compare two chosen settings, then collect fresh independent confirmation jars.",+ "steps": [+ "Label every jar with its run id before preparation. Keep the coffee lot, water batch, grind and filtering procedure consistent.",+ "Set the planned coffee dose and steeping duration for that jar. Record any preparation departure in its note.",+ "Use the same calibrated measurement procedure for each jar. Record extraction yield in percent; keep raw instrument observations separately.",+ "Enter one final response per independently prepared jar. Review the residual and run-order plots before selecting the next comparison."+ ],+ "notes": "Example protocol. Adapt the procedure to your actual equipment before approving it. Supply measured responses from your own independent runs."+ },+ "approved": false,+ "design": {+ "seed": "clearwater-01",+ "replicates": 3,+ "blocks": [+ "Water batch A"+ ],+ "controls": 3+ },+ "model": {+ "terms": [+ "steep",+ "dose",+ "steep:dose"+ ],+ "blocks": false,+ "confidence": 0.95+ },+ "phases": [+ {+ "id": "initial",+ "label": "Initial experiment",+ "kind": "plan",+ "reason": "Full factorial, independent repetitions and complete blocks.",+ "seed": "clearwater-01"+ }+ ],+ "runs": [+ {+ "id": "r0001",+ "order": 1,+ "phase": "initial",+ "block": "Water batch A",+ "kind": "control",+ "settings": {+ "steep": 12,+ "dose": 75+ }+ },+ {+ "id": "r0002",+ "order": 2,+ "phase": "initial",+ "block": "Water batch A",+ "kind": "factorial",+ "settings": {+ "steep": 8,+ "dose": 60+ }+ },+ {+ "id": "r0003",+ "order": 3,+ "phase": "initial",+ "block": "Water batch A",+ "kind": "factorial",+ "settings": {+ "steep": 8,+ "dose": 90+ }+ },+ {+ "id": "r0004",+ "order": 4,+ "phase": "initial",+ "block": "Water batch A",+ "kind": "factorial",+ "settings": {+ "steep": 16,+ "dose": 60+ }+ },+ {+ "id": "r0005",+ "order": 5,+ "phase": "initial",+ "block": "Water batch A",+ "kind": "factorial",+ "settings": {+ "steep": 8,+ "dose": 90+ }+ },+ {+ "id": "r0006",+ "order": 6,+ "phase": "initial",+ "block": "Water batch A",+ "kind": "factorial",+ "settings": {+ "steep": 16,+ "dose": 90+ }+ },+ {+ "id": "r0007",+ "order": 7,+ "phase": "initial",+ "block": "Water batch A",+ "kind": "factorial",+ "settings": {+ "steep": 16,+ "dose": 60+ }+ },+ {+ "id": "r0008",+ "order": 8,+ "phase": "initial",+ "block": "Water batch A",+ "kind": "control",+ "settings": {+ "steep": 12,+ "dose": 75+ }+ },+ {+ "id": "r0009",+ "order": 9,+ "phase": "initial",+ "block": "Water batch A",+ "kind": "factorial",+ "settings": {+ "steep": 16,+ "dose": 90+ }+ },+ {+ "id": "r0010",+ "order": 10,+ "phase": "initial",+ "block": "Water batch A",+ "kind": "factorial",+ "settings": {+ "steep": 8,+ "dose": 90+ }+ },+ {+ "id": "r0011",+ "order": 11,+ "phase": "initial",+ "block": "Water batch A",+ "kind": "factorial",+ "settings": {+ "steep": 8,+ "dose": 60+ }+ },+ {+ "id": "r0012",+ "order": 12,+ "phase": "initial",+ "block": "Water batch A",+ "kind": "factorial",+ "settings": {+ "steep": 16,+ "dose": 60+ }+ },+ {+ "id": "r0013",+ "order": 13,+ "phase": "initial",+ "block": "Water batch A",+ "kind": "factorial",+ "settings": {+ "steep": 16,+ "dose": 90+ }+ },+ {+ "id": "r0014",+ "order": 14,+ "phase": "initial",+ "block": "Water batch A",+ "kind": "factorial",+ "settings": {+ "steep": 8,+ "dose": 60+ }+ },+ {+ "id": "r0015",+ "order": 15,+ "phase": "initial",+ "block": "Water batch A",+ "kind": "control",+ "settings": {+ "steep": 12,+ "dose": 75+ }+ }+ ],+ "measurements": [],+ "sources": [],+ "audit": [+ {+ "id": "starter-design",+ "at": "2026-09-20T00:00:00.000Z",+ "action": "design",+ "reason": "Generated a randomized run sheet; control positions are scheduled.",+ "previous": {+ "runs": [],+ "phases": []+ },+ "runs": 15+ }+ ],+ "conclusion": ""+}diff --git a/store/agents/lab-bench/template/studio/THIRD_PARTY_LICENSES.txt b/store/agents/lab-bench/template/studio/THIRD_PARTY_LICENSES.txtnew file mode 100644index 000000000..39a2eee4b--- /dev/null+++ b/store/agents/lab-bench/template/studio/THIRD_PARTY_LICENSES.txt@@ -0,0 +1,143 @@+Numerical libraries bundled in Signal++ml-matrix 6.15.0+The MIT License (MIT)++Copyright (c) 2014 Michaël Zasso++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.++++jstat 1.9.6+Copyright (c) 2013 jStat++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in+all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+THE SOFTWARE.+++is-any-array 3.0.0+The MIT License (MIT)++Copyright (c) 2018 cheminfo++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+++ml-array-rescale 2.0.0+MIT License++Copyright (c) 2017 mljs++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+++ml-array-min 2.0.0+MIT License++Copyright (c) 2017 mljs++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+++ml-array-max 2.0.0+MIT License++Copyright (c) 2017 ml.js++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/store/agents/lab-bench/template/studio/analysis.mjs b/store/agents/lab-bench/template/studio/analysis.mjsnew file mode 100644index 000000000..3f6059888--- /dev/null+++ b/store/agents/lab-bench/template/studio/analysis.mjs@@ -0,0 +1,108 @@+import {Matrix, SVD, studentTQuantile} from './math-vendor.mjs';+import {assert, clone, validateProject, settingsValid, canonical, digest} from './project.mjs';++export function columnsFor(p) {+ const columns = [{id: 'intercept', label: 'Intercept', factors: []}];+ const bases = id => {const f = p.factors.find(f => f.id === id); return f.type === 'number' ? [{factor: id, power: 1, label: f.name}] : f.levels.slice(1).map(level => ({factor: id, level, label: `${f.name}: ${level} vs ${f.levels[0]}`}));};+ for (const term of p.model.terms) {+ if (term.endsWith('^2')) {const id = term.slice(0, -2), f = p.factors.find(f => f.id === id); columns.push({id: term, label: `${f.name} squared`, factors: [{factor: id, power: 2}]});}+ else {+ const ids = term.split(':'), groups = ids.map(bases), parts = groups.length === 1 ? groups[0].map(x => [x]) : groups[0].flatMap(a => groups[1].map(b => [a, b]));+ for (const factors of parts) columns.push({id: factors.map(f => f.factor + (f.level === undefined ? '' : '[' + f.level + ']')).join(':'), label: factors.map(f => f.label).join(' × '), factors});+ }+ }+ if (p.model.blocks) for (const block of p.design.blocks.slice(1)) columns.push({id: 'block[' + block + ']', label: `Block: ${block} vs ${p.design.blocks[0]}`, block, factors: []});+ assert(columns.length <= 48, 'The expanded model exceeds 48 columns. Reduce factors, levels or interactions.'); return columns;+}+export function designRow(p, settings, block, columns = columnsFor(p)) {+ settingsValid(p, settings); assert(p.design.blocks.includes(block), 'Choose a declared block.');+ return columns.map(c => c.block !== undefined ? +(block === c.block) : c.factors.reduce((value, term) => {+ const f = p.factors.find(f => f.id === term.factor);+ return value * (f.type === 'category' ? +(settings[f.id] === term.level) : ((settings[f.id] - (f.levels[0] + f.levels.at(-1)) / 2) / ((f.levels.at(-1) - f.levels[0]) / 2)) ** term.power);+ }, 1));+}+const sum = a => a.reduce((s, v) => s + v, 0);+const dot = (a, b) => sum(a.map((v, i) => v * b[i]));+export const mean = a => sum(a) / a.length;+function decomposition(rows, count) {+ if (!rows.length) return {rank: 0, condition: null, df: -count, svd: null};+ const svd = new SVD(new Matrix(rows), {autoTranspose: true}), singular = svd.diagonal;+ const cutoff = singular[0] * 1e-12, rank = singular.filter(x => x > cutoff).length;+ return {rank, condition: rank < count ? null : singular[0] / singular.at(-1), df: rows.length - count, singular, svd};+}+export function plannedAnalysis(p) {+ const columns = columnsFor(p), phases = new Map(p.phases.map(x => [x.id, x]));+ const rows = p.runs.filter(r => phases.get(r.phase).kind !== 'confirmation').map(r => designRow(p, r.settings, r.block, columns));+ const {svd, ...diagnostic} = decomposition(rows, columns.length);+ return {...diagnostic, rows: rows.length, columns: columns.map(c => c.label), parameters: columns.length};+}+export function fitProject(raw, {includeExcluded = false} = {}) {+ const p = validateProject(raw), columns = columnsFor(p), phases = new Map(p.phases.map(x => [x.id, x]));+ const observations = new Map(p.measurements.map(m => [m.runId, m]));+ const used = p.runs.filter(r => phases.get(r.phase).kind !== 'confirmation' && observations.has(r.id) && (includeExcluded || !observations.get(r.id).excluded));+ const X = used.map(r => designRow(p, r.settings, r.block, columns)), y = used.map(r => observations.get(r.id).value);+ const dec = decomposition(X, columns.length), n = y.length, k = columns.length;+ const summary = {n, parameters: k, rank: dec.rank, df: n - k, condition: dec.condition, includeExcluded, columns,+ pending: p.runs.length - p.measurements.length, excluded: p.measurements.filter(m => m.excluded).length,+ confirmation: p.measurements.filter(m => phases.get(p.runs.find(r => r.id === m.runId).phase).kind === 'confirmation').length,+ model: clone(p.model), matrix: {X, y, runIds: used.map(r => r.id)}, warnings: []};+ if (!n) return {...summary, ok: false, issue: 'Collect measurements first. The plan does not contain invented responses.'};+ if (dec.rank < k) return {...summary, ok: false, issue: `These measurements identify ${dec.rank} of ${k} model columns. Collect the missing combinations or simplify the model. Center points alone cannot separate multiple squared effects.`};+ if (n <= k) return {...summary, ok: false, issue: `There are ${n} measured runs and ${k} parameters. Independent repetitions are needed to estimate residual uncertainty.`};+ if (dec.condition > 1e9) return {...summary, ok: false, issue: 'The model is numerically unstable. Redesign the experiment or remove confounded terms.'};+ const inverse = dec.svd.inverse(), beta = inverse.mmul(Matrix.columnVector(y)).to1DArray();+ const normalizedCovariance = inverse.mmul(inverse.transpose()).to2DArray();+ const fitted = X.map(x => dot(x, beta)), residuals = y.map((v, i) => v - fitted[i]), sse = sum(residuals.map(x => x * x));+ const df = n - k, mse = sse / df, scale = Math.max(1, ...y.map(Math.abs));+ const inferential = mse > (Number.EPSILON * scale * 64) ** 2;+ const covariance = normalizedCovariance.map(row => row.map(x => x * mse)), critical = studentTQuantile((1 + p.model.confidence) / 2, df);+ assert(Number.isFinite(critical), 'The uncertainty calculation could not be resolved.');+ const coefficients = columns.map((c, i) => {const se = Math.sqrt(Math.max(0, covariance[i][i])); return {id: c.id, label: c.label, value: beta[i], se: inferential ? se : null, ci: inferential ? [beta[i] - critical * se, beta[i] + critical * se] : null};});+ const residualRows = used.map((run, i) => {+ const leverage = Math.max(0, Math.min(1, dot(X[i], normalizedCovariance.map(row => dot(row, X[i])))));+ const studentized = inferential && 1 - leverage > 1e-10 ? residuals[i] / Math.sqrt(mse * (1 - leverage)) : null;+ const cook = studentized === null ? null : studentized ** 2 * leverage / (k * (1 - leverage));+ return {runId: run.id, order: run.order, block: run.block, settings: clone(run.settings), measured: y[i], fitted: fitted[i], residual: residuals[i], leverage, studentized, cook,+ review: leverage > 2 * k / n || (cook !== null && cook > 4 / n)};+ });+ const sst = sum(y.map(v => (v - mean(y)) ** 2));+ const looRMSE = residualRows.every(r => 1 - r.leverage > 1e-10) ? Math.sqrt(mean(residualRows.map(r => (r.residual / (1 - r.leverage)) ** 2))) : null;+ if (!inferential) summary.warnings.push('Residual variation is zero at numerical precision. Uncertainty intervals are withheld; collect independently varying repeated measurements.');+ if (dec.condition > 1e6) summary.warnings.push('The design is poorly conditioned; coefficients are sensitive to small measurement changes.');+ if (residualRows.some(r => r.review)) summary.warnings.push('Some measurements have high leverage or influence. Review their procedure and provenance; they have not been deleted.');+ if (p.audit.some(e => e.action === 'model' && e.afterCollection)) summary.warnings.push('Model terms changed after data were collected. Treat the revised analysis as exploratory.');+ if (summary.excluded) summary.warnings.push(`${summary.excluded} recorded measurements are excluded with reasons. Compare the sensitivity fit that includes them.`);+ return {...summary, ok: true, inferential, coefficients, beta, covariance, normalizedCovariance, critical, mse, sse, rmse: Math.sqrt(mse),+ r2: sst > (Number.EPSILON * scale * 64) ** 2 ? 1 - sse / sst : null,+ adjustedR2: sst > (Number.EPSILON * scale * 64) ** 2 ? 1 - (sse / df) / (sst / (n - 1)) : null,+ residuals: residualRows, looRMSE,+ assumptions: 'Intervals assume independent experimental units, a correctly specified linear mean model, constant residual variance and approximately normal errors. Intervals are pointwise, without adjustment for searching many settings. Confirmation measurements are held out of this fit.'};+}+export function predict(p, fit, settings, block) {+ assert(fit.ok, fit.issue || 'Fit the measured data first.'); const x = designRow(p, settings, block, fit.columns), prediction = dot(x, fit.beta);+ const variance = Math.max(0, dot(x, fit.covariance.map(row => dot(row, x)))), se = Math.sqrt(variance), predictionSE = Math.sqrt(variance + fit.mse);+ return {settings: clone(settings), block, x, mean: prediction, se: fit.inferential ? se : null,+ meanCI: fit.inferential ? [prediction - fit.critical * se, prediction + fit.critical * se] : null,+ predictionCI: fit.inferential ? [prediction - fit.critical * predictionSE, prediction + fit.critical * predictionSE] : null};+}+export function compare(p, fit, a, b) {+ const A = predict(p, fit, a.settings, a.block), B = predict(p, fit, b.settings, b.block), delta = B.x.map((x, i) => x - A.x[i]);+ const variance = Math.max(0, dot(delta, fit.covariance.map(row => dot(row, delta)))), difference = B.mean - A.mean;+ return {A, B, difference, se: fit.inferential ? Math.sqrt(variance) : null, ci: fit.inferential ? [difference - fit.critical * Math.sqrt(variance), difference + fit.critical * Math.sqrt(variance)] : null};+}+export async function predictionSnapshot(p, fit, points) {+ assert(fit.ok && fit.inferential && !fit.includeExcluded, 'Use a measured primary model with residual uncertainty before planning confirmation.');+ return {trainingRevision: await digest(p), n: fit.n, df: fit.df, model: clone(p.model), columns: clone(fit.columns), matrix: clone(fit.matrix), coefficients: clone(fit.coefficients), covariance: clone(fit.covariance), mse: fit.mse, assumptions: fit.assumptions,+ predictions: points.map(point => predict(p, fit, point.settings, point.block))};+}+export function confirmationResults(p) {+ const measured = new Map(p.measurements.filter(m => !m.excluded).map(m => [m.runId, m]));+ return p.phases.filter(phase => phase.kind === 'confirmation').flatMap(phase => phase.snapshot.predictions.map(prediction => {+ const rows = p.runs.filter(r => r.phase === phase.id && r.block === prediction.block && canonical(r.settings) === canonical(prediction.settings));+ const values = rows.filter(r => measured.has(r.id)).map(r => measured.get(r.id).value), n = values.length;+ const average = n ? mean(values) : null, se = n > 1 ? Math.sqrt(sum(values.map(x => (x - average) ** 2)) / ((n - 1) * n)) : null;+ const critical = n > 1 ? studentTQuantile((1 + phase.snapshot.model.confidence) / 2, n - 1) : null;+ return {phase: phase.label, phaseId: phase.id, prediction, planned: rows.length, n, runIds: rows.map(r => r.id), mean: average,+ ci: se === null ? null : [average - critical * se, average + critical * se], difference: n ? average - prediction.mean : null};+ }));+}diff --git a/store/agents/lab-bench/template/studio/app.js b/store/agents/lab-bench/template/studio/app.jsnew file mode 100644index 000000000..0ef2c2dd3--- /dev/null+++ b/store/agents/lab-bench/template/studio/app.js@@ -0,0 +1,202 @@+import {clone, validateProject, validateTransition, canonical, digest, event, history, planFrozen, settingsValid, assert} from './project.mjs';+import {generatePlan, approveProtocol, appendPhase, combinations, center} from './design.mjs';+import {parseCSV, decode, prepareImport, commitImport, recordMeasurement, verifySources, collectionCSV} from './measurements.mjs';+import {fitProject, plannedAnalysis, predict, compare, predictionSnapshot, confirmationResults} from './analysis.mjs';+import {esc, number, interval, settingLabel, chartSVG, coefficientSVG, reportHTML, runSheetHTML, kitFiles} from './formats.mjs';+import {zipFiles} from './archive.mjs';++const config = JSON.parse(document.querySelector('#signal-data').textContent), originalHTML = document.documentElement.outerHTML;+const $ = s => document.querySelector(s), main = $('#main'), dialog = $('#dialog');+let p = validateProject(config.project), edits = history(p), tab = 'plan', plot = 'run', fit, planned, source = null, baseRevision = config.project.revision, incoming = null, dirty = false, formDirty = false, toastTimer, polling = false, sourceError = null;+let pendingCSV = null, prepared = null, candidateA, candidateB, recovery = null;+const draftKey = 'signal-draft:' + p.id, workspaceId = p.id;+const palettes = ['#087f79','#c36443','#7365a7','#397baf','#bd8720','#b85680','#567c32','#525d69'];+const field = (label, name, value, attrs = '') => `<label>${esc(label)}<input name="${esc(name)}" value="${esc(value)}" ${attrs}></label>`;+const area = (label, name, value, rows = 3, attrs = '') => `<label>${esc(label)}<textarea name="${esc(name)}" rows="${rows}" ${attrs}>${esc(value)}</textarea></label>`;+const option = (value, label, selected) => `<option value="${esc(value)}" ${selected ? 'selected' : ''}>${esc(label)}</option>`;+const pill = (s, type = '') => `<span class="pill ${type}">${esc(s)}</span>`;+const metric = (value, label, accent = false) => `<div class="metric ${accent ? 'accent' : ''}"><strong>${esc(value)}</strong><span>${esc(label)}</span></div>`;+const table = (headers, rows, attrs = '') => `<div class="table-scroll"><table ${attrs}><thead><tr>${headers.map(h => `<th>${esc(h)}</th>`).join('')}</tr></thead><tbody>${rows.join('')}</tbody></table></div>`;+const hero = (step, title, description) => `<div class="hero"><div><div class="eyebrow">${step} / ${['Design a fair test','Keep the evidence','Read the signal','Learn, then test again'][Number(step)-1]}</div><h1>${esc(title)}</h1><p>${esc(description)}</p></div><div class="stage-number">${step}</div></div>`;+function notify(message, error = false) {const el = $('#toast'); el.textContent = message; el.hidden = false; el.classList.toggle('error', error); clearTimeout(toastTimer); toastTimer = setTimeout(() => {el.hidden = true;}, error ? 12000 : 6500);}+function download(name, body, type = 'application/octet-stream') {const blob = body instanceof Blob ? body : new Blob([body], {type}), url = URL.createObjectURL(blob), a = document.createElement('a'); a.href = url; a.download = name; a.click(); setTimeout(() => URL.revokeObjectURL(url), 10000);}+function persist() {try {localStorage.setItem(draftKey, JSON.stringify({baseRevision, project: p}));} catch {notify('Browser storage is full. Save to your workspace or download the editable project to keep this change.', true);}}+function chooseDefaults() {const block = p.design.blocks[0]; candidateA = {settings: Object.fromEntries(p.factors.map(f => [f.id, f.levels[0]])), block}; candidateB = {settings: Object.fromEntries(p.factors.map(f => [f.id, f.levels.at(-1)])), block};}+function changed(next, {resetCandidates = false} = {}) {next = validateProject(next); validateTransition(p, next); p = edits.push(next); dirty = true; formDirty = false; if (resetCandidates) chooseDefaults(); persist(); render();}+function offlineHTML(project = p) {const doc = new DOMParser().parseFromString(originalHTML, 'text/html'); doc.querySelector('#signal-data').textContent = JSON.stringify({project, assets: config.assets}).replace(/</g, '\\u003c'); doc.title = project.title + ' — Signal'; return '<!doctype html>\n' + doc.documentElement.outerHTML;}+function checkForm() {if (!formDirty) return true; notify('Apply your form changes first, or use “Discard form edits”.', true); return false;}+function showDialog(html) {$('#dialog-content').innerHTML = html; if (!dialog.open) dialog.showModal();}+function planView() {+ const frozen = planFrozen(p), disabled = frozen ? 'disabled' : '';+ return hero('01', p.title, p.question) + `<div class="metrics">${metric(p.runs.length, 'runs in your collection sheet', true)}${metric(p.factors.length, 'factors you can change')}${metric(p.design.blocks.length, 'complete blocks')}${metric(planned.rank + '/' + planned.parameters, 'model terms distinguishable')}</div>+ ${frozen ? `<div class="strip"><strong>${p.approved ? 'Protocol approved' : 'Collection has started'}</strong>The original conditions and run order are preserved. Add another phase from Next experiment, or begin a separate project for a different protocol.</div>` : ''}+ <form id="plan-form"><div class="two-col"><div>+ <section class="card"><h2>The question</h2><div class="form-grid">${field('Experiment name','title',p.title,disabled+' required maxlength="160" class="span-all"')}${area('What will this experiment help you decide?','question',p.question,3,disabled+' required')}${field('Measured response','response-name',p.response.name,disabled+' required')}${field('Response unit','response-unit',p.response.unit,disabled+' required')}+ <label>Goal<select name="goal" ${disabled}>${['maximize','minimize','target'].map(x=>option(x, x==='target'?'Approach a target':x==='maximize'?'Larger is better':'Smaller is better',p.response.goal===x)).join('')}</select></label>${field('Target (used for target goal)','target',p.response.target??0,disabled+' type="number" step="any"')}</div></section>+ <section class="card"><div class="section-head"><h2>What you can vary</h2><button type="button" data-action="add-factor" ${disabled}>+ Add factor</button></div><div class="factor-grid">${p.factors.map((f,i)=>`<div class="factor"><div class="factor-head"><strong>FACTOR ${String(i+1).padStart(2,'0')}</strong><button type="button" data-action="remove-factor" data-id="${esc(f.id)}" ${disabled || (p.factors.length===1?'disabled':'')}>Remove</button></div><div class="form-grid">${field('Name','factor-name-'+f.id,f.name,disabled+' required')}<label>Type<select name="factor-type-${esc(f.id)}" ${disabled}>${option('number','Numeric',f.type==='number')}${option('category','Category',f.type==='category')}</select></label>${field('Unit','factor-unit-'+f.id,f.unit,disabled)}${area('Levels · one per line','factor-levels-'+f.id,f.levels.join('\n'),3,disabled+' required')}</div></div>`).join('')}</div><p class="helper">Every combination is tested. Numeric factors use the low and high levels to code the model; categories use the first level as the reference.</p></section>+ <section class="card"><h2>A repeatable procedure</h2><div class="form-grid">${area('One independent experimental unit','protocol-unit',p.protocol.unit,3,disabled+' required')}${area('How will you randomize and control the conditions?','randomization',p.protocol.randomization,3,disabled+' required')}${area('Procedure · one step per line','steps',p.protocol.steps.join('\n'),7,disabled+' required class="span-all"')}${area('Analysis planned before collection','analysis-plan',p.protocol.analysisPlan,4,disabled+' required')}${area('Practical notes and departures to record','notes',p.protocol.notes,4,disabled)}</div></section></div>+ <div><section class="card"><h2>Build your run sheet</h2><div class="form-grid">${field('Independent repetitions per combination','replicates',p.design.replicates,disabled+' type="number" min="1" max="20" required')}${field('Randomization seed','seed',p.design.seed,disabled+' required')}${area('Complete blocks · one name per line','blocks',p.design.blocks.join('\n'),3,disabled+' required')}<label>Scheduled controls per block<select name="controls" ${disabled}>${[0,2,3,4,5].map(x=>option(x,x===0?'None':x+' midpoint / reference controls',p.design.controls===x)).join('')}</select></label></div><p class="helper">A block repeats every combination under a shared condition, such as a shelf or a material lot. Controls bracket and span each block; they use numeric midpoints and the first category level.</p><div class="report-actions"><button class="primary" type="submit" ${disabled}>Apply plan & rebuild run sheet</button></div></section>+ <section class="card"><h2>Before you collect</h2><div class="check-row"><span>Independent runs</span><span>${p.runs.length}</span></div><div class="check-row"><span>Planned model columns</span><span>${planned.parameters}</span></div><div class="check-row"><span>Identifiable columns</span><span>${planned.rank}</span></div><div class="check-row"><span>Residual degrees of freedom</span><span>${planned.df}</span></div>${planned.rank<planned.parameters?'<div class="strip warn">This design cannot separate all requested model terms. Revise the model or add informative points.</div>':''}<p class="helper">Re-reading one jar, pot or sample does not create another independent run.</p><div class="actions report-actions"><button type="button" data-action="approve" ${frozen?'disabled':''}>${p.approved?'Approved ✓':'Approve protocol'}</button><button type="button" data-tab="collect">Collection sheet →</button></div></section>+ <div class="actions"><button type="button" data-action="undo" ${edits.canUndo&&!frozen?'':'disabled'}>Undo plan edit</button><button type="button" data-action="redo" ${edits.canRedo&&!frozen?'':'disabled'}>Redo</button><button type="button" data-action="discard-form">Discard form edits</button></div></div></div></form>`;+}+function collectView() {+ const measurements=new Map(p.measurements.map(m=>[m.runId,m]));+ return hero('02','Your evidence, intact.','Use the run sheet in the real world. Import the results or record each measurement here; leave unfinished runs blank.')++ `<div class="metrics">${metric(p.measurements.length,'measured responses',true)}${metric(fit.pending,'still to collect')}${metric(p.sources.length,'original CSV files retained')}${metric(fit.excluded,'excluded, with reasons')}</div>+ <section class="card"><div class="section-head"><h2>Collection sheet</h2><div class="actions"><button data-action="download-sheet">Download blank CSV</button><button data-action="print-sheet">Printable sheet</button><button data-action="import-csv" class="primary">Import measurements</button></div></div><p class="helper">Response: <strong>${esc(p.response.name)} in ${esc(p.response.unit)}</strong>. Click a run to record a result, correct a transcription or document an exclusion.</p>+ ${table(['Run / order',...p.factors.map(f=>f.name+(f.unit?' · '+f.unit:'')),'Block','Response · '+p.response.unit,'State'],p.runs.map(r=>{const m=measurements.get(r.id);return `<tr data-run="${r.id}"><td><strong>${r.id}</strong><div class="small">${r.order} · ${r.kind==='control'?'control':r.phase}</div></td>${p.factors.map(f=>`<td>${esc(r.settings[f.id])}</td>`).join('')}<td>${esc(r.block)}</td><td class="${m?'state-measured':'state-pending'}">${m?number(m.value):'—'}</td><td><button data-action="measure" data-id="${r.id}">${m?.excluded?'Excluded':m?'Review':'Record'}</button></td></tr>`;}))}</section>+ <section class="card"><div class="chart">${chartSVG(p,fit,'run')}</div><div class="plot-tip" id="plot-tip">Hover or focus a point to inspect its run.</div></section>+ <section class="card"><h2>Original files and recorded changes</h2>${p.sources.length?p.sources.map(s=>`<details><summary>${esc(s.name)} · original CSV</summary><p class="small wrap">SHA-256 ${esc(s.sha256)}</p><p class="small">${esc(s.mapping.runId)} → run id · ${esc(s.mapping.response)} → ${esc(p.response.name)} · ${esc(s.unit)}</p><button data-action="original-csv" data-id="${esc(s.id)}">Download original bytes</button></details>`).join(''):'<p class="muted">No files imported yet. Manual entries keep their own change history.</p>'}<details><summary>Change log · ${p.audit.length} records</summary>${p.audit.slice().reverse().slice(0,40).map(e=>`<div class="audit-row">${esc(e.reason)}<small>${esc(e.at)} · ${esc(e.action)}</small></div>`).join('')}<p class="small">The complete log travels with the editable project.</p></details></section>`;+}+function legend() {return `<div class="legend">${p.design.blocks.map((b,i)=>`<span><i class="dot" style="background:${palettes[i%palettes.length]}"></i>${esc(b)}</span>`).join('')}</div>`;}+function modelControls() {+ const terms=p.factors.map(f=>({id:f.id,label:f.name}));+ for(let i=0;i<p.factors.length;i++)for(let j=i+1;j<p.factors.length;j++)terms.push({id:p.factors[i].id+':'+p.factors[j].id,label:p.factors[i].name+' × '+p.factors[j].name});+ for(const f of p.factors.filter(f=>f.type==='number'))terms.push({id:f.id+'^2',label:f.name+' · curvature'});+ return `<form id="model-form"><div class="terms">${terms.map(t=>`<label><input type="checkbox" name="term" value="${esc(t.id)}" ${p.model.terms.includes(t.id)?'checked':''}>${esc(t.label)}</label>`).join('')}<label><input type="checkbox" name="blocks" ${p.model.blocks?'checked':''}>Account for fixed block differences</label></div><label>Pointwise confidence<select name="confidence">${[.8,.9,.95,.99].map(c=>option(c,c*100+'%',p.model.confidence===c)).join('')}</select></label>${area('Reason for changing the model','reason','',2,p.measurements.length?'required':'')}<p class="helper">Interactions retain both main effects; curvature retains its numeric main effect. Model changes after looking at results are recorded as exploratory.</p><div class="actions report-actions"><button type="submit">Apply model</button><button type="button" data-action="discard-form">Discard form edits</button></div></form>`;+}+function analyzeView() {+ const intro=hero('03','What changed the outcome?','Inspect the measurements, the uncertainty and the model’s blind spots before choosing what to try next.');+ const metrics=`<div class="metrics">${metric(fit.n,'independent runs in this fit',true)}${metric(fit.ok?number(fit.rmse):'—','residual SD · '+p.response.unit)}${metric(fit.ok?number(fit.looRMSE):'—','leave-one-out prediction RMSE')}${metric(fit.df,'residual degrees of freedom')}</div>`;+ const results=!fit.ok?`<div class="empty"><h2>${p.measurements.length?'The model needs more evidence.':'Begin with your measurements.'}</h2><p>${esc(fit.issue)}</p><button data-tab="collect" class="primary">Go to collection</button></div>`:+ `<section class="card"><div class="section-head"><h2>Look at the evidence</h2><div class="tabs">${[['run','Run order'],['fit','Measured vs fitted'],['residual','Residuals']].map(([v,label])=>`<button data-action="plot" data-mode="${v}" class="${plot===v?'selected':''}">${label}</button>`).join('')}</div></div><div class="chart">${chartSVG(p,fit,plot)}</div><div class="plot-tip" id="plot-tip">Hover or focus a point to inspect its run.</div><p class="helper">${plot==='run'?'Look for drift across the collection order or unexpected differences between blocks.':plot==='fit'?'The dashed line is a perfect match. Prediction quality on new runs still needs confirmation.':'Look for curvature, changing spread or patterns the chosen terms have missed.'}</p></section>+ <section class="card"><h2>Effects, with room for uncertainty</h2><div class="chart">${coefficientSVG(fit)}</div>${table(['Model term','Coefficient',p.model.confidence*100+'% interval'],fit.coefficients.map(c=>`<tr><td>${esc(c.label)}</td><td>${number(c.value)}</td><td>${interval(c.ci)}</td></tr>`))}<p class="helper">Numeric factors are coded from −1 to +1 across the planned range. Categories compare with the first level. These are model coefficients, not a ranking of causal importance.</p></section>+ <section class="card"><h2>Measurements worth reviewing</h2>${fit.residuals.some(r=>r.review)?table(['Run','Residual','Leverage','Cook’s distance',''],fit.residuals.filter(r=>r.review).map(r=>`<tr><td>${r.runId}</td><td>${number(r.residual)}</td><td>${number(r.leverage)}</td><td>${number(r.cook)}</td><td><button data-action="measure" data-id="${r.runId}">Review original</button></td></tr>`)):'<p class="muted">No rows cross the displayed leverage or influence review thresholds.</p>'}<p class="helper">Leverage > 2p/n or Cook’s distance > 4/n prompts review. Nothing is removed automatically.</p>${fit.excluded?'<button data-action="sensitivity">Compare with all recorded measurements</button>':''}</section>`;+ return intro+metrics+`<div class="two-col"><div>${results}</div><div><section class="card"><h2>Your model</h2>${modelControls()}</section><section class="card"><h2>Read the uncertainty correctly</h2><p class="small">A mean interval describes the model’s average response at a setting. A prediction interval is wider: it describes one new independent observation.</p><p class="small">The fit assumes independent runs, constant residual variance and a suitable linear mean model with approximately normal errors. The intervals are pointwise; searching many settings does not provide simultaneous coverage.</p>${fit.warnings.map(w=>`<div class="strip warn">${esc(w)}</div>`).join('')}<button data-tab="followup" class="primary">Compare the next settings →</button></section></div></div>`;+}+function candidateCard(key, candidate, label) {+ const prediction=fit.ok?predict(p,fit,candidate.settings,candidate.block):null;+ return `<div><div class="candidate-title"><h3>${label}</h3>${pill(key.toUpperCase())}</div>${p.factors.map(f=>`<label class="setting">${esc(f.name)}${f.unit?' · '+esc(f.unit):''}${f.type==='number'?`<div class="setting-fields"><input type="range" data-candidate="${key}" data-factor="${f.id}" min="${f.levels[0]}" max="${f.levels.at(-1)}" step="${(f.levels.at(-1)-f.levels[0])/100}" value="${candidate.settings[f.id]}" aria-label="${label} ${esc(f.name)} slider"><input type="number" data-candidate="${key}" data-factor="${f.id}" min="${f.levels[0]}" max="${f.levels.at(-1)}" step="any" value="${candidate.settings[f.id]}" aria-label="${label} ${esc(f.name)}"></div>`:`<select data-candidate="${key}" data-factor="${f.id}">${f.levels.map(v=>option(v,v,candidate.settings[f.id]===v)).join('')}</select>`}</label>`).join('')}<label class="setting">Comparable block<select data-candidate="${key}" data-block="true">${p.design.blocks.map(v=>option(v,v,candidate.block===v)).join('')}</select></label>${prediction?`<div class="prediction"><div class="eyebrow">Predicted ${esc(p.response.name)}</div><div class="value">${number(prediction.mean)} <small style="font-size:17px">${esc(p.response.unit)}</small></div><div>${p.model.confidence*100}% mean interval: ${interval(prediction.meanCI)}</div><small>One new observation: ${interval(prediction.predictionCI)}</small></div>`:'<div class="strip">No response estimate yet. Additional independent runs can help identify the model.</div>'}</div>`;+}+function followupControls() { return `<section class="card"><h2>Turn the comparison into a test</h2><form id="followup-form"><div class="form-grid">${field('Phase name','label','Confirmation '+(p.phases.length), 'required')}${field('Independent repetitions per point','repeats',3,'type="number" min="1" max="20" required')}<label class="span-all">Purpose<select name="kind"><option value="confirmation" ${fit.ok&&fit.inferential?'':'disabled'}>Confirm · keep new data out of original fit</option><option value="extension" ${fit.ok&&fit.inferential?'':'selected'}>Extend · add new data to the model</option></select></label>${field('Randomization seed','seed',p.design.seed+'-next-'+p.phases.length,'required')}${area('Why this follow-up?','reason','Compare the reference and candidate with fresh independent runs under comparable conditions.',4,'required')}</div><div class="strip">The settings above become labeled, randomized runs. Confirmation keeps a snapshot of today’s forecast. Extension deliberately adds future observations to the training fit.</div><button class="primary" type="submit">Append follow-up runs</button></form></section>`; }+function followupView() {+ const intro=hero('04','Make the next test count.','Compare candidate settings, freeze the prediction, and put it to a fresh test. The original evidence stays intact.');+ if(!fit.ok)return intro+`<div class="strip warn"><strong>${esc(fit.issue)}</strong>You can collect the remaining runs or append an extension at informative settings. Confirmation becomes available after estimating residual uncertainty.</div><div class="two-col"><section class="card"><h2>Choose additional settings</h2><div class="candidate-grid">${candidateCard('a',candidateA,'Point A')}${candidateCard('b',candidateB,'Point B')}</div></section><div>${followupControls()}</div></div>`;+ const comparison=compare(p,fit,candidateA,candidateB), score=v=>p.response.goal==='maximize'?-v:p.response.goal==='minimize'?v:Math.abs(v-p.response.target);+ const ranked=combinations(p).map(settings=>predict(p,fit,settings,candidateB.block)).sort((a,b)=>score(a.mean)-score(b.mean)).slice(0,6), confirmations=confirmationResults(p);+ return intro+`<div class="two-col"><div><section class="card"><div class="section-head"><h2>Compare two possibilities</h2>${pill(p.model.confidence*100+'% pointwise intervals')}</div><div class="candidate-grid">${candidateCard('a',candidateA,'Reference')}${candidateCard('b',candidateB,'Candidate')}</div><div class="comparison"><div class="eyebrow">Candidate minus reference</div><strong>${number(comparison.difference)} ${esc(p.response.unit)}</strong><div>Mean difference interval: ${interval(comparison.ci)}</div></div><p class="helper">Predictions stay inside the planned ranges. Unmeasured combinations still rely on the model; these intervals do not establish an optimum.</p></section>+ <section class="card"><h2>Explore the planned combinations</h2><p class="helper">The six closest candidates for your stated goal, under the selected block and model. Choose one to compare; this is an exploratory ordering.</p>${table(['Settings','Predicted mean',''],ranked.map((r,i)=>`<tr><td>${esc(settingLabel(p,r.settings))}</td><td>${number(r.mean)} ${esc(p.response.unit)}</td><td><button data-action="candidate" data-settings="${esc(JSON.stringify(r.settings))}">Compare</button></td></tr>`),'class="ranked"')}</section>+ ${confirmations.length?`<section class="card"><h2>Did the new measurements agree?</h2>${confirmations.map(c=>`<div class="strip"><strong>${esc(c.phase)} · ${c.n}/${c.planned} measured</strong>${esc(settingLabel(p,c.prediction.settings))}<div class="form-grid" style="margin-top:15px"><div>Frozen model mean<div class="measure-value">${number(c.prediction.mean)}</div><span class="small">Mean CI ${interval(c.prediction.meanCI)}</span></div><div>New measured mean<div class="measure-value">${number(c.mean)}</div><span class="small">Own CI ${interval(c.ci)}</span></div></div><p>Actual minus predicted: ${number(c.difference)} ${esc(p.response.unit)}. The original fit does not use these responses.</p><button data-action="phase-csv" data-id="${c.phaseId}">Download this phase’s run sheet</button></div>`).join('')}<p class="helper">Each observed mean interval uses only its fresh repetitions. Comparing it with the original forecast is a diagnostic, not a pass/fail decision rule.</p></section>`:''}</div>+ <div>${followupControls()}+ <section class="card"><h2>Record your decision</h2><form id="conclusion-form">${area('What do the evidence and practical tradeoffs support?','conclusion',p.conclusion??'',7)}<button type="submit" style="margin-top:14px">Save decision note</button></form><p class="helper">This note accompanies the report. Separate what you measured, what the model predicts and what still needs testing.</p></section><section class="card"><h2>Take the whole experiment with you</h2><p class="small">Keep the source, original files, run sheets, figures, model matrix and Python reproduction script together.</p><div class="actions"><button data-action="report">Download report</button><button data-action="export" class="primary">Export complete kit ↗</button></div></section></div></div>`;+}+function render() {+ fit=fitProject(p); planned=plannedAnalysis(p); document.title=p.title+' — Signal'; $('#side-title').textContent=p.title;+ $('#side-status').innerHTML=`<div class="side-count"><strong>${p.measurements.length}</strong><span class="small">/ ${p.runs.length} measured</span></div><div class="progress"><span style="width:${p.runs.length?p.measurements.length/p.runs.length*100:0}%"></span></div><div class="side-note">${p.approved?'Protocol approved':'Protocol open for review'}<br>${p.sources.length} original files · ${p.audit.length} recorded changes</div>`;+ for(const el of document.querySelectorAll('[data-tab]'))el.classList.toggle('active',el.dataset.tab===tab);+ main.innerHTML=(p.evidenceNote?`<div class="strip warn">${esc(p.evidenceNote)}</div>`:'')+({plan:planView,collect:collectView,analyze:analyzeView,followup:followupView}[tab])();+ renderConnection();+}+function renderConnection() {+ $('#save-source').disabled=!source||p.id!==source.id;+ $('#connection').textContent=sourceError?('Source needs attention · '+sourceError):source?(p.id!==source.id?'Portable project · download to keep':dirty?'Unsaved workspace changes':'Saved in your workspace'):'Offline project · editable and portable';+ const conflict=$('#conflict'); conflict.hidden=!incoming&&!recovery;+ if(incoming)conflict.innerHTML=`The workspace source changed while you had a draft. Both versions are available.<div class="actions"><button data-action="download-project">Keep my draft</button><button data-action="incoming-project">Download source</button><button data-action="load-source">Keep draft & load source</button></div>`;+ else if(recovery)conflict.innerHTML=`A previous browser draft belongs to a different source edition.<div class="actions"><button data-action="recovery">Download that draft</button><button data-action="dismiss-recovery">Keep current edition</button></div>`;+}+function readPlan(form) {+ const q=clone(p),data=new FormData(form);assert(!planFrozen(p),'This protocol is locked.');+ q.title=String(data.get('title'));q.question=String(data.get('question'));q.response={...q.response,name:String(data.get('response-name')),unit:String(data.get('response-unit')),goal:String(data.get('goal')),target:Number(data.get('target'))};+ if(q.response.goal==='target')assert(String(data.get('target')).trim()!=='','Enter a target response.');+ q.factors=q.factors.map(f=>{const type=String(data.get('factor-type-'+f.id)),levels=String(data.get('factor-levels-'+f.id)).split('\n').map(x=>x.trim()).filter(Boolean);return {...f,name:String(data.get('factor-name-'+f.id)),type,unit:String(data.get('factor-unit-'+f.id)),levels:type==='number'?levels.map(Number):levels};});+ q.design={seed:String(data.get('seed')),replicates:Number(data.get('replicates')),blocks:String(data.get('blocks')).split('\n').map(x=>x.trim()).filter(Boolean),controls:Number(data.get('controls'))};+ q.protocol={unit:String(data.get('protocol-unit')),randomization:String(data.get('randomization')),steps:String(data.get('steps')).split('\n').map(x=>x.trim()).filter(Boolean),analysisPlan:String(data.get('analysis-plan')),notes:String(data.get('notes'))};+ q.model.terms=q.model.terms.filter(t=>!t.endsWith('^2')||q.factors.find(f=>f.id===t.slice(0,-2))?.type==='number');+ event(q,'plan-edit','Revised the uncollected experimental plan.',{before:{factors:p.factors,response:p.response,design:p.design,protocol:p.protocol,runs:p.runs}});q.runs=[];q.phases=[];delete q.comparison;+ return generatePlan(q);+}+function measurementDialog(id) {+ const run=p.runs.find(r=>r.id===id),m=p.measurements.find(m=>m.runId===id);assert(run,'Choose a known run.');+ showDialog(`<div class="eyebrow">Run ${esc(id)} · ${esc(run.block)}</div><h2>${m?'Review the measurement':'Record what you measured'}</h2><p>${esc(settingLabel(p,run.settings))}</p><form id="measurement-form" data-id="${id}"><div class="form-grid">${field(p.response.name+' ('+p.response.unit+')','value',m?.value??'','type="number" step="any" required')}${field('Reason for this entry or correction','reason',m?'':'Direct observation','required maxlength="600"')}${area('Run note','note',m?.note??'',3)}${area('Exclusion reason · leave blank to include','excluded',m?.excluded??'',3)}</div><p class="helper">${m?'Original '+esc(m.origin.kind==='csv'?m.origin.source+', line '+m.origin.row:'direct entry')+': '+number(m.origin.value)+' '+esc(p.response.unit)+'. Corrections keep this value and the complete change history.':'Enter an actual observation. A blank run is pending; it is never replaced with a model prediction.'}</p><div class="actions"><button type="button" data-action="close">Cancel</button><button type="submit" class="primary">${m?'Record change':'Save measurement'}</button></div></form>`);+}+function importDialog() {+ const parsed=parseCSV(decode(pendingCSV.bytes));prepared=null;+ showDialog(`<div class="eyebrow">Import measurements</div><h2>Match the columns, then review.</h2><p>${esc(pendingCSV.name)} · ${parsed.rows.length} rows · original bytes will be retained.</p><form id="import-form"><div class="form-grid"><label>Run id column<select name="runId">${parsed.headers.map(h=>option(h,h,h==='run_id')).join('')}</select></label><label>Measured response column<select name="response">${parsed.headers.map(h=>option(h,h,h==='response')).join('')}</select></label>${field('Confirm the response unit','unit',p.response.unit,'required')}</div><p class="helper">Known run ids link each result to its settings. Missing responses remain pending. Duplicate ids, unknown ids, existing results and mismatched settings are rejected together.</p><div id="import-preview"></div><div class="actions"><button type="button" data-action="close">Cancel</button><button type="submit">Preview import</button><button type="button" data-action="commit-import" id="commit-import" class="primary" disabled>Import measurements</button></div></form>`);+}+async function previewImport() {+ const data=new FormData($('#import-form'));prepared=await prepareImport(p,pendingCSV.bytes,{name:pendingCSV.name,mapping:{runId:String(data.get('runId')),response:String(data.get('response'))},unit:String(data.get('unit'))});+ $('#import-preview').innerHTML=`<div class="strip"><strong>${prepared.records.length} measured responses · ${prepared.pending} blank cells</strong>Nothing has been applied yet.</div>${table(['Run','Measured response','Original line'],prepared.records.slice(0,5).map(r=>`<tr><td>${r.runId}</td><td>${number(r.value)} ${esc(prepared.source.unit)}</td><td>${r.row}</td></tr>`))}`;$('#commit-import').disabled=false;+}+async function saveSource() {+ assert(source&&p.id===source.id,'Download this portable project or open it in its own workspace.');assert(!incoming,'Resolve the source change first; both versions are available.');+ const sent=await verifySources(p),response=await fetch('/api/project',{method:'PUT',headers:{'content-type':'application/json','if-match':baseRevision},body:JSON.stringify(sent)}),body=await response.json();+ if(response.status===409){incoming=body.project;renderConnection();throw new Error(body.error);}+ assert(response.ok,body.error||'The source could not be saved.');source=body.project;baseRevision=source.revision;+ if(canonical(p)===canonical(sent)){p=validateProject(source);edits=history(p);dirty=false;formDirty=false;}+ persist();render();notify(dirty?'Saved the submitted edition; your newer changes are still in the draft.':'Saved the complete experiment. The previous source edition is retained in workspace history.');+}+async function pollSource() {+ if(polling||!/^https?:$/.test(location.protocol)||!['127.0.0.1','localhost'].includes(location.hostname))return;polling=true;+ try{const response=await fetch('/api/project');if(response.status===503)return;if(!response.ok){const err=await response.json();if(sourceError!==err.error)notify('Workspace source needs attention. Your current draft is preserved: '+err.error,true);sourceError=err.error;renderConnection();return;}sourceError=null;const body=await response.json();assert(body.project,'No source project.');const next=body.project;await verifySources(next);source??=next;+ if(next.revision!==baseRevision){if(dirty||formDirty||p.id!==next.id){incoming=next;renderConnection();}else{source=next;baseRevision=next.revision;p=validateProject(next);edits=history(p);chooseDefaults();render();}}else{source=next;renderConnection();}+ }catch{}finally{polling=false;}+}+async function action(button) {+ const name=button.dataset.action;+ if(name==='close'){dialog.close();return;}+ if(name==='discard-form'){formDirty=false;render();return;}+ if(!['original-csv','download-project','incoming-project','recovery','dismiss-recovery'].includes(name)&&!checkForm())return;+ if(name==='open'){$('#project-file').value='';$('#project-file').click();}+ else if(name==='download-project')download(p.id+'.signal.json',JSON.stringify(p,null,2),'application/json');+ else if(name==='save')await saveSource();+ else if(name==='export'){await verifySources(p);download(p.id+'-experiment.zip',zipFiles(kitFiles(p,offlineHTML(),config.assets)));notify('Exported editable studio, original measurements, run sheets, report and reproducible calculations.');}+ else if(name==='report')download(p.id+'-report.html',reportHTML(p),'text/html');+ else if(name==='download-sheet')download(p.id+'-collection.csv',collectionCSV(p),'text/csv');+ else if(name==='print-sheet')download(p.id+'-collection-sheet.html',runSheetHTML(p),'text/html');+ else if(name==='phase-csv')download(p.id+'-'+button.dataset.id+'.csv',collectionCSV(p,{phase:button.dataset.id}),'text/csv');+ else if(name==='approve'){changed(approveProtocol(p));notify('The protocol and original run order are now protected.');}+ else if(name==='undo'||name==='redo'){assert(!planFrozen(p),'Collected or approved plans use logged revisions.');p=name==='undo'?edits.undo():edits.redo();dirty=true;persist();chooseDefaults();render();}+ else if(name==='add-factor'||name==='remove-factor'){+ assert(!planFrozen(p),'This protocol is locked.');const q=clone(p);event(q,'plan-edit',name==='add-factor'?'Added a factor before collection.':'Removed a factor before collection.',{before:{factors:p.factors,runs:p.runs}});+ if(name==='add-factor'){assert(q.factors.length<6,'Use at most six factors.');let n=1;while(q.factors.some(f=>f.id==='factor'+n))n++;const id='factor'+n;q.factors.push({id,name:'New factor',type:'number',unit:'',levels:[0,1]});q.model.terms.push(id);}+ else{q.factors=q.factors.filter(f=>f.id!==button.dataset.id);q.model.terms=q.model.terms.filter(t=>!t.split(':').map(x=>x.replace('^2','')).includes(button.dataset.id));}+ q.runs=[];q.phases=[];delete q.comparison;changed(generatePlan(q),{resetCandidates:true});+ }+ else if(name==='measure')measurementDialog(button.dataset.id);+ else if(name==='import-csv'){$('#csv-file').value='';$('#csv-file').click();}+ else if(name==='commit-import'){await previewImport();changed(commitImport(p,prepared));dialog.close();notify('Imported measured responses. The original file and exact row references are preserved.');}+ else if(name==='original-csv'){const s=p.sources.find(s=>s.id===button.dataset.id);download(s.name,Uint8Array.from(atob(s.base64),x=>x.charCodeAt(0)),'text/csv');}+ else if(name==='plot'){plot=button.dataset.mode;render();}+ else if(name==='candidate'){candidateB.settings=JSON.parse(button.dataset.settings);const q=clone(p);q.comparison={a:candidateA,b:candidateB};changed(q);}+ else if(name==='sensitivity'){+ const all=fitProject(p,{includeExcluded:true});showDialog(`<h2>Keep the exclusions visible.</h2><p>The primary fit uses ${fit.n} rows; the sensitivity fit includes all ${all.n} recorded training rows. Confirmation runs stay held out in both.</p>${all.ok&&fit.ok?table(['Term','Primary','All recorded','Change'],fit.coefficients.map((c,i)=>`<tr><td>${esc(c.label)}</td><td>${number(c.value)}</td><td>${number(all.coefficients[i].value)}</td><td>${number(all.coefficients[i].value-c.value)}</td></tr>`)):`<p>${esc(all.issue??fit.issue)}</p>`}<div class="actions"><button data-action="close">Close</button></div>`);+ }+ else if(name==='incoming-project')download(p.id+'-workspace-source.signal.json',JSON.stringify(incoming,null,2),'application/json');+ else if(name==='load-source'){assert(incoming,'No source change.');download(p.id+'-previous-draft.signal.json',JSON.stringify(p,null,2),'application/json');p=await verifySources(incoming);source=incoming;baseRevision=source.revision;incoming=null;dirty=false;formDirty=false;edits=history(p);chooseDefaults();persist();render();}+ else if(name==='recovery')download('recovered-draft.signal.json',JSON.stringify(recovery.project,null,2),'application/json');+ else if(name==='dismiss-recovery'){recovery=null;persist();renderConnection();}+}+document.addEventListener('click',e=>{+ const button=e.target.closest('button');if(button){if(button.dataset.tab){if(!checkForm())return;tab=button.dataset.tab;render();window.scrollTo({top:0,behavior:'instant'});}else if(button.dataset.action)void action(button).catch(err=>notify(err.message,true));return;}+ const row=e.target.closest('tr[data-run]');if(row&&checkForm())measurementDialog(row.dataset.run);+});+document.addEventListener('submit',e=>{e.preventDefault();void (async()=>{+ if(e.target.id==='plan-form'){changed(readPlan(e.target),{resetCandidates:true});notify('Updated the plan and randomized the new collection sheet.');}+ else if(e.target.id==='measurement-form'){const data=new FormData(e.target);changed(recordMeasurement(p,e.target.dataset.id,{value:data.get('value'),note:String(data.get('note')),excluded:String(data.get('excluded')).trim()||null,reason:String(data.get('reason'))}));dialog.close();notify('Recorded the measurement and its change history.');}+ else if(e.target.id==='import-form')await previewImport();+ else if(e.target.id==='model-form'){+ const data=new FormData(e.target),q=clone(p),terms=data.getAll('term').map(String);for(const t of [...terms])for(const part of t.split(':').map(x=>x.replace('^2','')))if(!terms.includes(part))terms.unshift(part);+ const after={terms,blocks:data.has('blocks'),confidence:Number(data.get('confidence'))};event(q,'model',String(data.get('reason')).trim()||'Revised the model before collecting data.',{before:q.model,after,afterCollection:q.measurements.length>0});q.model=after;changed(q);notify('Updated the model. All original measurements are retained.');+ }+ else if(e.target.id==='followup-form'){+ const data=new FormData(e.target),points=[candidateA,candidateB].filter((x,i,a)=>a.findIndex(y=>canonical(x)===canonical(y))===i),kind=String(data.get('kind'));+ const snapshot=kind==='confirmation'?await predictionSnapshot(p,fit,points):undefined;+ changed(appendPhase(p,{points,repeats:Number(data.get('repeats')),label:String(data.get('label')),seed:String(data.get('seed')),reason:String(data.get('reason')),kind,snapshot}));notify('Added a new phase. The original run settings and measurements are unchanged.');+ }+ else if(e.target.id==='conclusion-form'){const q=clone(p);q.conclusion=String(new FormData(e.target).get('conclusion'));event(q,'decision','Updated the interpretation and decision note.',{before:p.conclusion??'',after:q.conclusion});changed(q);notify('Saved the decision note for the report.');}+})().catch(err=>notify(err.message,true));});+document.addEventListener('input',e=>{if(e.target.closest('#plan-form,#model-form,#conclusion-form,#followup-form'))formDirty=true;if(e.target.closest('#import-form')){$('#commit-import').disabled=true;prepared=null;}});+document.addEventListener('change',e=>{void (async()=>{+ if(e.target.id==='csv-file'&&e.target.files[0]){const file=e.target.files[0];assert(file.size<=1000000,'Use a CSV below 1 MB.');pendingCSV={name:file.name,bytes:new Uint8Array(await file.arrayBuffer())};importDialog();}+ else if(e.target.id==='project-file'&&e.target.files[0]){const file=e.target.files[0];assert(file.size<=5000000,'Use a complete project below 5 MB.');const next=await verifySources(JSON.parse(await file.text()));download(p.id+'-before-open.signal.json',JSON.stringify(p,null,2),'application/json');p=next;edits=history(p);dirty=true;formDirty=false;incoming=null;tab='plan';chooseDefaults();persist();render();notify('Opened the complete experiment and downloaded the previous project for recovery.');}+ else if(e.target.dataset.candidate){assert(checkForm(),'Apply form edits before changing the comparison.');const key=e.target.dataset.candidate,candidate=clone(key==='a'?candidateA:candidateB);if(e.target.dataset.block)candidate.block=e.target.value;else{const f=p.factors.find(f=>f.id===e.target.dataset.factor);candidate.settings[f.id]=f.type==='number'?Number(e.target.value):e.target.value;}settingsValid(p,candidate.settings);if(fit.ok)predict(p,fit,candidate.settings,candidate.block);if(key==='a')candidateA=candidate;else candidateB=candidate;const q=clone(p);q.comparison={a:candidateA,b:candidateB};changed(q);}+})().catch(err=>notify(err.message,true));});+for(const type of ['pointerover','focusin'])document.addEventListener(type,e=>{const circle=e.target.closest('circle[data-run]');if(circle&&$('#plot-tip'))$('#plot-tip').textContent=circle.querySelector('title').textContent;});+window.addEventListener('beforeunload',e=>{if(formDirty){e.preventDefault();e.returnValue='';}});+async function start(){+ p=await verifySources(p);baseRevision??=await digest(p);chooseDefaults();+ try{const saved=JSON.parse(localStorage.getItem(draftKey));if(saved){await verifySources(saved.project);if(saved.baseRevision===baseRevision){p=validateProject(saved.project);dirty=canonical(p)!==canonical(validateProject(config.project));edits=history(p);chooseDefaults();}else recovery=saved;}}catch{}+ if(p.comparison){candidateA=clone(p.comparison.a);candidateB=clone(p.comparison.b);}+ render();await pollSource();setInterval(pollSource,2500);document.documentElement.dataset.ready='true';+}+void start().catch(e=>{main.innerHTML=`<div class="strip warn"><h1>Open a valid experiment to continue.</h1><p>${esc(e.message)}</p></div>`;notify(e.message,true);});diff --git a/store/agents/lab-bench/template/studio/archive.mjs b/store/agents/lab-bench/template/studio/archive.mjsnew file mode 100644index 000000000..0a71dae99--- /dev/null+++ b/store/agents/lab-bench/template/studio/archive.mjs@@ -0,0 +1,21 @@+// ZIP STORE: portable editable delivery without a runtime dependency or a cloud service.+export function zipFiles(files) {+ if (!Array.isArray(files)) files = Object.entries(files);+ const enc = new TextEncoder(), chunks = [], central = []; let offset = 0;+ for (const [name, body] of files) {+ const path = enc.encode(name), bytes = typeof body === 'string' ? enc.encode(body) : new Uint8Array(body);+ let crc = 0xffffffff;+ for (const b of bytes) { crc ^= b; for (let i = 0; i < 8; i++) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1)); }+ crc = (crc ^ 0xffffffff) >>> 0;+ const header = new Uint8Array(30 + path.length), v = new DataView(header.buffer);+ v.setUint32(0, 0x04034b50, true); v.setUint16(4, 20, true); v.setUint16(6, 0x800, true); v.setUint16(12, 33, true);+ v.setUint32(14, crc, true); v.setUint32(18, bytes.length, true); v.setUint32(22, bytes.length, true); v.setUint16(26, path.length, true); header.set(path, 30);+ const row = new Uint8Array(46 + path.length), c = new DataView(row.buffer);+ c.setUint32(0, 0x02014b50, true); c.setUint16(4, 20, true); c.setUint16(6, 20, true); c.setUint16(8, 0x800, true); c.setUint16(14, 33, true);+ c.setUint32(16, crc, true); c.setUint32(20, bytes.length, true); c.setUint32(24, bytes.length, true); c.setUint16(28, path.length, true); c.setUint32(42, offset, true); row.set(path, 46);+ chunks.push(header, bytes); central.push(row); offset += header.length + bytes.length;+ }+ const length = central.reduce((n, row) => n + row.length, 0), end = new Uint8Array(22), e = new DataView(end.buffer);+ e.setUint32(0, 0x06054b50, true); e.setUint16(8, files.length, true); e.setUint16(10, files.length, true); e.setUint32(12, length, true); e.setUint32(16, offset, true);+ return new Blob([...chunks, ...central, end], { type: 'application/zip' });+}diff --git a/store/agents/lab-bench/template/studio/design.mjs b/store/agents/lab-bench/template/studio/design.mjsnew file mode 100644index 000000000..00f4f6e00--- /dev/null+++ b/store/agents/lab-bench/template/studio/design.mjs@@ -0,0 +1,47 @@+import {assert, clone, validateProject, settingsValid, event, planFrozen, canonical} from './project.mjs';+export function random(seed) {+ let state = 2166136261; for (const ch of String(seed)) state = Math.imul(state ^ ch.charCodeAt(0), 16777619);+ return () => {let t = state += 0x6d2b79f5; t = Math.imul(t ^ t >>> 15, t | 1); t ^= t + Math.imul(t ^ t >>> 7, t | 61); return ((t ^ t >>> 14) >>> 0) / 4294967296;};+}+export function shuffle(array, seed) {const a = clone(array), r = random(seed); for (let i = a.length - 1; i > 0; i--) {const j = Math.floor(r() * (i + 1)); [a[i], a[j]] = [a[j], a[i]];} return a;}+export function combinations(p) {+ let points = [{}];+ for (const f of p.factors) {assert(points.length * f.levels.length <= 512, 'The full factorial exceeds 512 combinations. Narrow the factors or levels.'); points = points.flatMap(s => f.levels.map(v => ({...s, [f.id]: v})));}+ return points;+}+export function center(p) {return Object.fromEntries(p.factors.map(f => [f.id, f.type === 'number' ? (f.levels[0] + f.levels.at(-1)) / 2 : f.levels[0]]));}+export function generatePlan(raw) {+ const p = validateProject(raw); assert(!planFrozen(p), 'Collected or approved runs cannot be reshuffled. Append a follow-up.');+ const points = combinations(p), d = p.design;+ const count = (points.length * d.replicates + d.controls) * d.blocks.length;+ assert(count <= 512, `This design needs ${count} runs. Keep it within 512.`);+ const previous = {runs: p.runs, phases: p.phases}; p.runs = []; p.phases = [{id: 'initial', label: 'Initial experiment', kind: 'plan', reason: 'Full factorial, independent repetitions and complete blocks.', seed: d.seed}];+ for (const block of d.blocks) {+ const treatments = shuffle(Array.from({length: d.replicates}, () => points).flat().map(settings => ({kind: 'factorial', settings})), d.seed + ':block:' + block);+ // Controls span the run order. For categorical factors, use the declared reference level.+ const schedule = [];+ for (let i = 0; i <= treatments.length; i++) {+ for (let k = 0; k < d.controls; k++) if (Math.round(k * treatments.length / (d.controls - 1)) === i) schedule.push({kind: 'control', settings: center(p)});+ if (i < treatments.length) schedule.push(treatments[i]);+ }+ for (const row of schedule) {const order = p.runs.length + 1; p.runs.push({id: 'r' + String(order).padStart(4, '0'), order, phase: 'initial', block, ...row});}+ }+ event(p, 'design', 'Generated a randomized run sheet; control positions are scheduled.', {previous, runs: p.runs.length}); return validateProject(p);+}+export function approveProtocol(raw) {const p = validateProject(raw); assert(p.runs.length, 'Generate the run sheet first.'); p.approved = true; event(p, 'approve', 'Approved the protocol and original run order.'); return p;}+export function appendPhase(raw, {points, repeats = 3, label = 'Confirmation', reason, seed, kind = 'confirmation', snapshot}) {+ const p = validateProject(raw); assert(['confirmation', 'extension'].includes(kind), 'Choose a confirmation or an extension.');+ assert(Array.isArray(points) && points.length >= 1 && points.length <= 12 && Number.isInteger(repeats) && repeats >= 1 && repeats <= 20, 'Choose 1–12 points and 1–20 independent repetitions.');+ assert(p.runs.length + points.length * repeats <= 512, 'The follow-up exceeds 512 total runs.');+ for (const point of points) {settingsValid(p, point.settings); assert(p.design.blocks.includes(point.block), 'Choose an existing comparable block. New blocking conditions need a separate design.');}+ const id = 'phase' + (p.phases.length + 1), phase = {id, label, kind, reason, seed};+ if (kind === 'confirmation') {assert(snapshot && snapshot.predictions.length === points.length, 'Freeze the predictions before collecting confirmation measurements.'); phase.snapshot = clone(snapshot);}+ p.phases.push(phase);+ for (const block of p.design.blocks) {+ const rows = Array.from({length: repeats}, () => points.filter(x => x.block === block)).flat();+ for (const point of shuffle(rows, seed + ':' + block)) {const order = p.runs.length + 1; p.runs.push({id: 'r' + String(order).padStart(4, '0'), order, phase: id, block, kind: 'followup', settings: clone(point.settings)});}+ }+ event(p, 'followup', reason, {phase: id, kind, runs: points.length * repeats}); return validateProject(p);+}+export function phaseRows(p, phase) {return p.runs.filter(r => r.phase === phase);}+export function sameSettings(a, b) {return canonical(a) === canonical(b);}diff --git a/store/agents/lab-bench/template/studio/formats.mjs b/store/agents/lab-bench/template/studio/formats.mjsnew file mode 100644index 000000000..4a725b075--- /dev/null+++ b/store/agents/lab-bench/template/studio/formats.mjs@@ -0,0 +1,88 @@+import {canonical} from './project.mjs';+import {fitProject, plannedAnalysis, confirmationResults, compare} from './analysis.mjs';+import {csv, collectionCSV, bytesFromBase64} from './measurements.mjs';+export const esc = x => String(x ?? '').replace(/[&<>"']/g, c => ({'&': '&', '<': '<', '>': '>', '"': '"', "'": '''}[c]));+export const number = (x, digits = 3) => x === null || x === undefined || !Number.isFinite(x) ? '—' : Math.abs(x) !== 0 && (Math.abs(x) < .001 || Math.abs(x) >= 1e6) ? x.toExponential(2) : x.toLocaleString('en-US', {maximumFractionDigits: digits});+const shortLabel = (value, max) => value.length > max ? value.slice(0, max - 1) + '…' : value;+export const interval = x => x ? `${number(x[0])} to ${number(x[1])}` : 'Not available';+export const settingLabel = (p, settings) => p.factors.map(f => `${f.name}: ${settings[f.id]}${f.unit ? ' ' + f.unit : ''}`).join(' · ');+const palette = ['#087f79', '#c36443', '#7365a7', '#397baf', '#bd8720', '#b85680', '#567c32', '#525d69'];+const range = values => {let min = Math.min(...values), max = Math.max(...values); const margin = (max - min || Math.max(1, Math.abs(max) * .1)) * .12; return [min - margin, max + margin];};+export function chartSVG(p, fit, mode = 'run') {+ const measured = new Map(p.measurements.map(m => [m.runId, m]));+ const points = mode === 'run' ? p.runs.filter(r => measured.has(r.id)).map(r => ({id: r.id, x: r.order, y: measured.get(r.id).value, block: r.block, excluded: measured.get(r.id).excluded, label: settingLabel(p, r.settings)})) :+ fit.ok ? fit.residuals.map(r => ({id: r.runId, x: r.fitted, y: mode === 'residual' ? r.residual : r.measured, block: r.block, review: r.review, label: settingLabel(p, r.settings)})) : [];+ const title = mode === 'run' ? 'Measurements in collection order' : mode === 'residual' ? 'Residuals against fitted response' : 'Measured and fitted responses';+ const xlabel = mode === 'run' ? 'Run order' : `Fitted ${p.response.name} (${p.response.unit})`;+ const ylabel = mode === 'residual' ? `Residual (${p.response.unit})` : `${p.response.name} (${p.response.unit})`;+ const height = 355 + Math.ceil(p.design.blocks.length / 3) * 22;+ let body = `<rect width="760" height="${height}" fill="#fcfcf8"/><text x="24" y="29" font-size="16" font-weight="650">${esc(title)}</text>`;+ if (!points.length) body += '<text x="380" y="177" text-anchor="middle" fill="#677b78" font-size="15">Your measurements will appear here.</text>';+ else {+ const xr = range(points.map(x => x.x)), yr = range([...points.map(x => x.y), ...(mode === 'residual' ? [0] : [])]);+ if (mode === 'run') xr.splice(0, 2, 0, Math.max(...points.map(x => x.x)) + 1);+ if (mode === 'fit') {const joint = range(points.flatMap(x => [x.x, x.y])); xr.splice(0, 2, ...joint); yr.splice(0, 2, ...joint);}+ const sx = v => 88 + (v - xr[0]) / (xr[1] - xr[0]) * 638, sy = v => 270 - (v - yr[0]) / (yr[1] - yr[0]) * 205;+ for (let i = 0; i <= 4; i++) {+ const x = mode === 'run' ? 1 + Math.round(i * (xr[1] - 2) / 4) : xr[0] + i * (xr[1] - xr[0]) / 4, y = yr[0] + i * (yr[1] - yr[0]) / 4;+ body += `<path d="M88 ${sy(y)}H726" stroke="#e1e8e3"/><text x="77" y="${sy(y) + 4}" text-anchor="end" font-size="13">${esc(number(y, 2))}</text><text x="${sx(x)}" y="291" text-anchor="middle" font-size="13">${esc(number(x, 2))}</text>`;+ }+ if (mode === 'residual') body += `<path d="M88 ${sy(0)}H726" stroke="#8d9f96" stroke-dasharray="5 4"/>`;+ if (mode === 'fit') body += `<path d="M${sx(xr[0])} ${sy(xr[0])}L${sx(xr[1])} ${sy(xr[1])}" stroke="#8d9f96" stroke-dasharray="5 4"/>`;+ for (const q of points) {+ const color = palette[p.design.blocks.indexOf(q.block) % palette.length];+ body += `<circle data-run="${esc(q.id)}" cx="${sx(q.x)}" cy="${sy(q.y)}" r="${q.review ? 6 : 4.5}" fill="${q.excluded ? '#fcfcf8' : color}" stroke="${q.review ? '#b95332' : color}" stroke-width="${q.review ? 2 : 1}" tabindex="0"><title>${esc(q.id)} · ${esc(q.block)} · ${esc(q.label)} · ${number(q.y)}${q.excluded ? ' · excluded: ' + esc(q.excluded) : ''}</title></circle>`;+ }+ body += `<text x="407" y="321" text-anchor="middle" font-size="13"><title>${esc(xlabel)}</title>${esc(shortLabel(xlabel, 76))}</text><text transform="translate(22 166) rotate(-90)" text-anchor="middle" font-size="13"><title>${esc(ylabel)}</title>${esc(shortLabel(ylabel, 36))}</text>`;+ }+ p.design.blocks.forEach((block, i) => {const x = 28 + i % 3 * 245, y = 350 + Math.floor(i / 3) * 22; body += `<circle cx="${x}" cy="${y - 4}" r="4" fill="${palette[i % palette.length]}"/><text x="${x + 10}" y="${y}" font-size="13"><title>${esc(block)}</title>${esc(block.length > 28 ? block.slice(0, 25) + '…' : block)}</text>`;});+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 ${height}" role="img" aria-label="${esc(title)}" style="font-family:Arial,sans-serif;fill:#173e39">${body}</svg>`;+}+export function coefficientSVG(fit) {+ if (!fit.ok) return '';+ const rows = fit.coefficients.filter(c => c.id !== 'intercept'), height = Math.max(180, rows.length * 39 + 100);+ const span = range([0, ...rows.flatMap(c => c.ci ?? [c.value])]), sx = v => 290 + (v - span[0]) / (span[1] - span[0]) * 425;+ let body = `<rect width="760" height="${height}" fill="#fcfcf8"/><text x="24" y="30" font-size="16" font-weight="650">Model coefficients and ${fit.model.confidence * 100}% intervals</text><path d="M${sx(0)} 48V${height - 45}" stroke="#bdccc1" stroke-dasharray="5 4"/>`;+ rows.forEach((c, i) => {const y = 67 + i * 39, label = c.label.length > 35 ? c.label.slice(0, 32) + '…' : c.label;+ body += `<text x="24" y="${y + 4}" font-size="13"><title>${esc(c.label)}</title>${esc(label)}</text>${c.ci ? `<path d="M${sx(c.ci[0])} ${y}H${sx(c.ci[1])}" stroke="#087f79" stroke-width="3"/>` : ''}<circle cx="${sx(c.value)}" cy="${y}" r="4.5" fill="#087f79"/>`;+ });+ for (let i = 0; i <= 4; i++) {const v = span[0] + (span[1] - span[0]) * i / 4; body += `<text x="${sx(v)}" y="${height - 24}" font-size="13" text-anchor="middle">${number(v)}</text>`;}+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 ${height}" role="img" aria-label="Model coefficient intervals" style="font-family:Arial,sans-serif;fill:#173e39">${body}</svg>`;+}+const reportStyle = `@page{size:A4;margin:17mm 15mm}*{box-sizing:border-box}body{font-family:Arial,sans-serif;color:#173e39;font-size:10.5pt;line-height:1.45;margin:0}h1{font-size:30pt;line-height:1.08;letter-spacing:-1pt;margin:8mm 0}h2{font-size:19pt;line-height:1.2;margin:3mm 0 5mm}h3{font-size:12pt;margin:6mm 0 2mm}p{overflow-wrap:anywhere}.eyebrow{font-size:9pt;text-transform:uppercase;letter-spacing:1.5pt;color:#087f79}.subtle{color:#526f67}.page{break-before:page}.page:first-child{break-before:auto}.metrics{display:flex;gap:4mm;margin:7mm 0}.metric{flex:1;background:#eef3ea;padding:4mm}.metric strong{display:block;font-size:21pt}table{width:100%;border-collapse:collapse;font-size:9pt;table-layout:fixed}td,th{padding:2.4mm 1.8mm;border-bottom:1px solid #dbe4db;text-align:left;overflow-wrap:anywhere}th{background:#eef3ea}tr{break-inside:avoid}thead{display:table-header-group}svg{display:block;width:100%;height:auto;break-inside:avoid;margin:4mm 0}.note{padding:4mm;background:#f5eddc;border-left:3px solid #c98934}.hash{font-family:monospace;font-size:8pt;overflow-wrap:anywhere}.procedure li{margin-bottom:2.8mm}a{color:#087f79}.source{break-inside:avoid}footer{font-size:8pt;color:#526f67;margin-top:7mm}h2,h3{break-after:avoid}`;+function table(headers, rows) {return `<table><thead><tr>${headers.map(h => `<th>${esc(h)}</th>`).join('')}</tr></thead><tbody>${rows.map(row => `<tr>${row.map(c => `<td>${esc(c)}</td>`).join('')}</tr>`).join('')}</tbody></table>`;}+export function reportHTML(p, fit = fitProject(p)) {+ const planned = plannedAnalysis(p), confidence = p.model.confidence * 100, confirmations = confirmationResults(p);+ const sources = p.sources.map(s => `<div class="source"><h3>${esc(s.name)}</h3><p>${esc(s.unit)} · mapped ${esc(s.mapping.runId)} → run id, ${esc(s.mapping.response)} → response</p><p class="hash">SHA-256 ${esc(s.sha256)}</p></div>`).join('');+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${esc(p.title)} — experiment report</title><style>${reportStyle}</style></head><body>+<section class="page"><div class="eyebrow">Signal / Experiment report</div><h1>${esc(p.title)}</h1>${p.evidenceNote?`<p class="note">${esc(p.evidenceNote)}</p>`:''}<p style="font-size:15pt">${esc(p.question)}</p><div class="metrics"><div class="metric"><strong>${p.runs.length}</strong>planned runs</div><div class="metric"><strong>${p.measurements.length}</strong>measured</div><div class="metric"><strong>${fit.n}</strong>in primary fit</div></div><h2>The decision</h2><p>${esc(p.conclusion || 'No conclusion has been recorded. Interpret the measured evidence and confirmation results before deciding what to change.')}</p><h3>Measurement</h3><p>${esc(p.response.name)} (${esc(p.response.unit)}). Goal: ${esc(p.response.goal)}${p.response.goal === 'target' ? ' ' + number(p.response.target) + ' ' + esc(p.response.unit) : ''}.</p><h3>Independent experimental unit</h3><p>${esc(p.protocol.unit)}</p><h3>Planned analysis</h3><p>${esc(p.protocol.analysisPlan)}</p><p class="note">${esc(fit.ok ? fit.assumptions : fit.issue)}</p><footer>Editable source, original CSVs, run sheet, design matrix and a Python reproduction script accompany this report.<strong>Method references</strong><p><a href="https://www.itl.nist.gov/div898/handbook/pri/section3/pri3331.htm">NIST: factorial designs</a> · <a href="https://www.itl.nist.gov/div898/handbook/pri/section3/pri337.htm">center/control scheduling</a> · <a href="https://www.itl.nist.gov/div898/handbook/pri/section4/pri46.htm">confirmation runs</a>. Numerical SVD: ml-matrix 6.15.0; Student-t quantiles: jstat 1.9.6. Full notices included.</p></footer></section>+<section class="page"><div class="eyebrow">01 / Protocol</div><h2>A test someone else can repeat</h2>${table(['Factor', 'Planned levels', 'Unit'], p.factors.map(f => [f.name, f.levels.join(' / '), f.unit || 'category']))}<h3>Run allocation</h3><p>${p.design.replicates} independent repetitions of every combination per complete block. Blocks: ${esc(p.design.blocks.join(', '))}. Seed: ${esc(p.design.seed)}. ${p.design.controls} scheduled controls per block; numeric midpoints and the first categorical level.</p><p>${esc(p.protocol.randomization)}</p><ol class="procedure">${p.protocol.steps.map(s => `<li>${esc(s)}</li>`).join('')}</ol><p>${esc(p.protocol.notes)}</p><p class="subtle">${p.approved ? 'Protocol approved and locked.' : 'Protocol not yet approved.'} Planned model rank ${planned.rank}/${planned.parameters}; ${planned.df} residual degrees of freedom if every training run is measured.</p></section>+<section class="page"><div class="eyebrow">02 / Observations</div><h2>Keep the evidence visible</h2>${chartSVG(p, fit, 'run')}<p>Hollow points are excluded with recorded reasons; all originals remain in the delivery. Colors identify the declared blocks.</p><h3>Collection status</h3><p>${fit.pending} pending · ${fit.excluded} excluded · ${fit.confirmation} held-out confirmation measurements.</p>${table(['Run', p.response.name + ' (' + p.response.unit + ')', 'Source / reason'], p.measurements.slice(0, 8).map(m => [m.runId, number(m.value), m.excluded || (m.origin.kind === 'csv' ? m.origin.source + ', line ' + m.origin.row : 'Direct entry')]))}<p class="subtle">${p.measurements.length > 8 ? 'First eight measurements shown here. ' : ''}The complete measurements.csv and source files contain every recorded row.</p></section>+<section class="page"><div class="eyebrow">03 / Analysis</div><h2>What the measurements support</h2>${fit.ok ? `<div class="metrics"><div class="metric"><strong>${number(fit.rmse)}</strong>residual SD (${esc(p.response.unit)})</div><div class="metric"><strong>${fit.df}</strong>residual df</div><div class="metric"><strong>${number(fit.looRMSE)}</strong>leave-one-out RMSE</div></div>${table(['Term', 'Coefficient', confidence + '% interval'], fit.coefficients.map(c => [c.label, number(c.value), interval(c.ci)]))}<p>Numeric factors are coded −1 at the lowest planned level and +1 at the highest; category effects use the first level as reference. Coefficients use these coded units. Intervals are pointwise and model dependent.</p>${coefficientSVG(fit)}` : `<p class="note">${esc(fit.issue)}</p>`}</section>+${fit.ok ? `<section class="page"><div class="eyebrow">04 / Diagnostics</div><h2>Check what the model has missed</h2>${chartSVG(p, fit, 'residual')}<p>Review curvature, changing residual spread and run-order patterns. Outlined points cross a leverage or influence review threshold; they remain in the fit.</p>${fit.warnings.map(w => `<p class="note">${esc(w)}</p>`).join('')}${fit.residuals.some(r => r.review) ? table(['Run', 'Residual', 'Leverage', 'Cook’s distance'], fit.residuals.filter(r => r.review).slice(0, 8).map(r => [r.runId, number(r.residual), number(r.leverage), number(r.cook)])) : '<p>No observations cross the displayed review thresholds.</p>'}<p class="subtle">Leverage > 2p/n or Cook’s distance > 4/n prompts review, not automatic deletion. At most eight flagged rows are listed here; analysis.json retains every diagnostic. A favorable diagnostic does not establish the experimental assumptions.</p></section>` : ''}+<section class="page"><div class="eyebrow">05 / Follow-up and provenance</div><h2>Test the prediction with new runs</h2>${confirmations.length ? confirmations.map(c => `<h3>${esc(c.phase)} · ${esc(c.prediction.block)}</h3><p>${esc(settingLabel(p, c.prediction.settings))}</p>${table(['Frozen prediction', 'New measurements', 'Actual minus predicted'], [[number(c.prediction.mean) + ' · mean CI ' + interval(c.prediction.meanCI), c.n + '/' + c.planned + ' measured · mean ' + number(c.mean) + ' · own CI ' + interval(c.ci), number(c.difference)]])}<p class="subtle">Original interval for one new observation: ${interval(c.prediction.predictionCI)}. The observed mean’s interval uses only the new repetitions. It is not a pass/fail test.</p>`).join('') : '<p>No confirmation phase yet. Compare settings, freeze the prediction and collect fresh independent runs before treating a candidate as established.</p>'}<h2>Original files</h2>${sources || '<p>No CSV files imported. Direct measurements are recorded in the change log.</p>'}<h3>Change log</h3><p>${p.audit.length} changes preserved in project.signal.json and audit.json, including model changes, corrections and exclusions.</p></section>+</body></html>`;+}+export function runSheetHTML(p) {+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${esc(p.title)} — collection sheet</title><style>${reportStyle}@page{size:A4 landscape;margin:14mm}td{height:11mm}table{font-size:9pt}h1{font-size:23pt}</style></head><body><div class="eyebrow">Signal / Collection sheet</div><h1>${esc(p.title)}</h1><p>${esc(p.response.name)} in ${esc(p.response.unit)} · one result per ${esc(p.protocol.unit)} · seed ${esc(p.design.seed)}</p>${table(['Run / order', 'Phase / block', ...p.factors.map(f => f.name + (f.unit ? ' (' + f.unit + ')' : '')), p.response.name + ' (' + p.response.unit + ')', 'Notes / departure'], p.runs.map(r => [r.id + ' / ' + r.order, r.phase + ' / ' + r.block + (r.kind === 'control' ? ' · control' : ''), ...p.factors.map(f => r.settings[f.id]), '', '']))}<footer>Keep the run ids when importing measurements. Leave unmeasured responses blank. Do not enter predicted values as measured results.</footer></body></html>`;+}+export function kitFiles(p, html, assets) {+ const fit = fitProject(p), files = {+ 'experiment.html': html, 'project.signal.json': JSON.stringify(p, null, 2) + '\n',+ 'collection.csv': collectionCSV(p), 'measurements.csv': collectionCSV(p, {blank: false}),+ 'report.html': reportHTML(p, fit), 'collection-sheet.html': runSheetHTML(p),+ 'analysis.json': JSON.stringify(fit, null, 2) + '\n', 'confirmations.json': JSON.stringify(confirmationResults(p), null, 2) + '\n',+ 'audit.json': JSON.stringify(p.audit, null, 2) + '\n',+ 'design-matrix.csv': csv([['run_id', ...fit.columns.map(c => c.id), 'measured_response'], ...fit.matrix.X.map((row, i) => [fit.matrix.runIds[i], ...row, fit.matrix.y[i]])]),+ 'charts/collection.svg': chartSVG(p, fit, 'run'), 'charts/residuals.svg': chartSVG(p, fit, 'residual'),+ 'reproduce.py': assets.reproduce, 'requirements.txt': assets.requirements, 'THIRD_PARTY_LICENSES.txt': assets.licenses,+ 'README.txt': `SIGNAL — ${p.title}\n\nOpen experiment.html in a modern browser to edit, inspect and continue collecting offline. Open project.signal.json to retain the entire source and original inputs. The studio does not invent missing responses.\n\nPrint collection-sheet.html at actual size, or fill collection.csv without changing run ids. Blank responses are pending. Measurements and corrections remain in the project and audit.json; original CSV bytes are in sources/.\n\nThe report describes the model and assumptions. Numeric settings use planned-range coding, categorical terms use the first level as reference and blocks are fixed effects. Confirmation runs remain outside the training fit. A prediction interval describes one new observation; a mean confidence interval describes the model mean. These are pointwise intervals, not a guarantee of an optimum.\n\nTo independently repeat the fitted calculations, use Python 3.9–3.12, install requirements.txt into an isolated environment, and run python reproduce.py. The script reads the exact delivered matrix and writes reproduction.json. No Python is required for the browser studio.\n\nOriginal implementation and Signal identity: OpenHarness contributors, MIT. Numerical library notices are included.\n`,+ 'LICENSE.txt': assets.license,+ };+ if (fit.ok) {files['charts/coefficients.svg'] = coefficientSVG(fit); files['charts/measured-fitted.svg'] = chartSVG(p, fit, 'fit');}+ if (fit.ok && p.comparison) files['comparison.json'] = JSON.stringify(compare(p, fit, p.comparison.a, p.comparison.b), null, 2) + '\n';+ for (const source of p.sources) files['sources/' + source.id + '.csv'] = bytesFromBase64(source.base64);+ for (const phase of p.phases.filter(x => x.kind !== 'plan')) files['followup/' + phase.id + '.csv'] = collectionCSV(p, {phase: phase.id});+ if (fit.excluded) files['sensitivity-all-recorded.json'] = JSON.stringify(fitProject(p, {includeExcluded: true}), null, 2) + '\n';+ return files;+}diff --git a/store/agents/lab-bench/template/studio/icon.svg b/store/agents/lab-bench/template/studio/icon.svgnew file mode 100644index 000000000..799113fdc--- /dev/null+++ b/store/agents/lab-bench/template/studio/icon.svg@@ -0,0 +1,7 @@+<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96">+ <title>Lab Bench — signal in a flask</title>+ <rect x="4" y="4" width="88" height="88" rx="23" fill="#143740"/>+ <path d="M36 20h24M40 21v22L24 69q-4 7 5 7h38q9 0 5-7L56 43V21" fill="none" stroke="#f2ca7d" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>+ <path d="m32 63 8-7 8 8 9-15 8 14" fill="none" stroke="#89c7bd" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>+ <circle cx="70" cy="30" r="5" fill="#89c7bd"/>+</svg>diff --git a/store/agents/lab-bench/template/studio/math-vendor.mjs b/store/agents/lab-bench/template/studio/math-vendor.mjsnew file mode 100644index 000000000..16aa2303c--- /dev/null+++ b/store/agents/lab-bench/template/studio/math-vendor.mjs@@ -0,0 +1,9 @@+// Generated from pinned ml-matrix / jstat. Full notices: THIRD_PARTY_LICENSES.txt.+var je=Object.create;var Pe=Object.defineProperty;var et=Object.getOwnPropertyDescriptor;var tt=Object.getOwnPropertyNames;var rt=Object.getPrototypeOf,nt=Object.prototype.hasOwnProperty;var Ve=(h,e)=>()=>(e||h((e={exports:{}}).exports,e),e.exports);var ot=(h,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of tt(e))!nt.call(h,s)&&s!==t&&Pe(h,s,{get:()=>e[s],enumerable:!(n=et(e,s))||n.enumerable});return h};var Fe=(h,e,t)=>(t=h!=null?je(rt(h)):{},ot(e||!h||!h.__esModule?Pe(t,"default",{value:h,enumerable:!0}):t,h));var Be=Ve(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});var st=Object.prototype.toString;function K(h){let e=st.call(h);return e.endsWith("Array]")&&!e.includes("Big")}function it(h,e={}){if(!K(h))throw new TypeError("input must be an array");if(h.length===0)throw new TypeError("input must not be empty");let{fromIndex:t=0,toIndex:n=h.length}=e;if(t<0||t>=h.length||!Number.isInteger(t))throw new Error("fromIndex must be a positive integer smaller than length");if(n<=t||n>h.length||!Number.isInteger(n))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");let s=h[t];for(let u=t+1;u<n;u++)h[u]>s&&(s=h[u]);return s}function ut(h,e={}){if(!K(h))throw new TypeError("input must be an array");if(h.length===0)throw new TypeError("input must not be empty");let{fromIndex:t=0,toIndex:n=h.length}=e;if(t<0||t>=h.length||!Number.isInteger(t))throw new Error("fromIndex must be a positive integer smaller than length");if(n<=t||n>h.length||!Number.isInteger(n))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");let s=h[t];for(let u=t+1;u<n;u++)h[u]<s&&(s=h[u]);return s}function Le(h,e={}){if(K(h)){if(h.length===0)throw new TypeError("input must not be empty")}else throw new TypeError("input must be an array");let t;if(e.output!==void 0){if(!K(e.output))throw new TypeError("output option must be an array if specified");t=e.output}else t=new Array(h.length);let n=ut(h),s=it(h);if(n===s)throw new RangeError("minimum and maximum input values are equal. Cannot rescale a constant array");let{min:u=e.autoMinMax?n:0,max:c=e.autoMinMax?s:1}=e;if(u>=c)throw new RangeError("min option must be smaller than max option");let i=(c-u)/(s-n);for(let r=0;r<h.length;r++)t[r]=(h[r]-n)*i+u;return t}var le=" ".repeat(2),Oe=" ".repeat(4);function lt(){return $e(this)}function $e(h,e={}){let{maxRows:t=15,maxColumns:n=10,maxNumSize:s=8,padMinus:u="auto"}=e;return`${h.constructor.name} {+${le}[+${Oe}${ft(h,t,n,s,u)}+${le}]+${le}rows: ${h.rows}+${le}columns: ${h.columns}+}`}function ft(h,e,t,n,s){let{rows:u,columns:c}=h,i=Math.min(u,e),r=Math.min(c,t),o=[];if(s==="auto"){s=!1;e:for(let l=0;l<i;l++)for(let f=0;f<r;f++)if(h.get(l,f)<0){s=!0;break e}}for(let l=0;l<i;l++){let f=[];for(let a=0;a<r;a++)f.push(ct(h.get(l,a),n,s));o.push(`${f.join(" ")}`)}return r!==c&&(o[o.length-1]+=` ... ${c-t} more columns`),i!==u&&o.push(`... ${u-e} more rows`),o.join(`+${Oe}`)}function ct(h,e,t){return(h>=0&&t?` ${De(h,e-1)}`:De(h,e)).padEnd(e)}function De(h,e){let t=h.toString();if(t.length<=e)return t;let n=h.toFixed(e);if(n.length>e&&(n=h.toFixed(Math.max(0,e-(n.length-e)))),n.length<=e&&!n.startsWith("0.000")&&!n.startsWith("-0.000"))return n;let s=h.toExponential(e);return s.length>e&&(s=h.toExponential(Math.max(0,e-(s.length-e)))),s.slice(0)}function ht(h,e){h.prototype.add=function(n){return typeof n=="number"?this.addS(n):this.addM(n)},h.prototype.addS=function(n){for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)+n);return this},h.prototype.addM=function(n){if(n=e.checkMatrix(n),this.rows!==n.rows||this.columns!==n.columns)throw new RangeError("Matrices dimensions must be equal");for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)+n.get(s,u));return this},h.add=function(n,s){return new e(n).add(s)},h.prototype.sub=function(n){return typeof n=="number"?this.subS(n):this.subM(n)},h.prototype.subS=function(n){for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)-n);return this},h.prototype.subM=function(n){if(n=e.checkMatrix(n),this.rows!==n.rows||this.columns!==n.columns)throw new RangeError("Matrices dimensions must be equal");for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)-n.get(s,u));return this},h.sub=function(n,s){return new e(n).sub(s)},h.prototype.subtract=h.prototype.sub,h.prototype.subtractS=h.prototype.subS,h.prototype.subtractM=h.prototype.subM,h.subtract=h.sub,h.prototype.mul=function(n){return typeof n=="number"?this.mulS(n):this.mulM(n)},h.prototype.mulS=function(n){for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)*n);return this},h.prototype.mulM=function(n){if(n=e.checkMatrix(n),this.rows!==n.rows||this.columns!==n.columns)throw new RangeError("Matrices dimensions must be equal");for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)*n.get(s,u));return this},h.mul=function(n,s){return new e(n).mul(s)},h.prototype.multiply=h.prototype.mul,h.prototype.multiplyS=h.prototype.mulS,h.prototype.multiplyM=h.prototype.mulM,h.multiply=h.mul,h.prototype.div=function(n){return typeof n=="number"?this.divS(n):this.divM(n)},h.prototype.divS=function(n){for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)/n);return this},h.prototype.divM=function(n){if(n=e.checkMatrix(n),this.rows!==n.rows||this.columns!==n.columns)throw new RangeError("Matrices dimensions must be equal");for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)/n.get(s,u));return this},h.div=function(n,s){return new e(n).div(s)},h.prototype.divide=h.prototype.div,h.prototype.divideS=h.prototype.divS,h.prototype.divideM=h.prototype.divM,h.divide=h.div,h.prototype.mod=function(n){return typeof n=="number"?this.modS(n):this.modM(n)},h.prototype.modS=function(n){for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)%n);return this},h.prototype.modM=function(n){if(n=e.checkMatrix(n),this.rows!==n.rows||this.columns!==n.columns)throw new RangeError("Matrices dimensions must be equal");for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)%n.get(s,u));return this},h.mod=function(n,s){return new e(n).mod(s)},h.prototype.modulus=h.prototype.mod,h.prototype.modulusS=h.prototype.modS,h.prototype.modulusM=h.prototype.modM,h.modulus=h.mod,h.prototype.and=function(n){return typeof n=="number"?this.andS(n):this.andM(n)},h.prototype.andS=function(n){for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)&n);return this},h.prototype.andM=function(n){if(n=e.checkMatrix(n),this.rows!==n.rows||this.columns!==n.columns)throw new RangeError("Matrices dimensions must be equal");for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)&n.get(s,u));return this},h.and=function(n,s){return new e(n).and(s)},h.prototype.or=function(n){return typeof n=="number"?this.orS(n):this.orM(n)},h.prototype.orS=function(n){for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)|n);return this},h.prototype.orM=function(n){if(n=e.checkMatrix(n),this.rows!==n.rows||this.columns!==n.columns)throw new RangeError("Matrices dimensions must be equal");for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)|n.get(s,u));return this},h.or=function(n,s){return new e(n).or(s)},h.prototype.xor=function(n){return typeof n=="number"?this.xorS(n):this.xorM(n)},h.prototype.xorS=function(n){for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)^n);return this},h.prototype.xorM=function(n){if(n=e.checkMatrix(n),this.rows!==n.rows||this.columns!==n.columns)throw new RangeError("Matrices dimensions must be equal");for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)^n.get(s,u));return this},h.xor=function(n,s){return new e(n).xor(s)},h.prototype.leftShift=function(n){return typeof n=="number"?this.leftShiftS(n):this.leftShiftM(n)},h.prototype.leftShiftS=function(n){for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)<<n);return this},h.prototype.leftShiftM=function(n){if(n=e.checkMatrix(n),this.rows!==n.rows||this.columns!==n.columns)throw new RangeError("Matrices dimensions must be equal");for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)<<n.get(s,u));return this},h.leftShift=function(n,s){return new e(n).leftShift(s)},h.prototype.signPropagatingRightShift=function(n){return typeof n=="number"?this.signPropagatingRightShiftS(n):this.signPropagatingRightShiftM(n)},h.prototype.signPropagatingRightShiftS=function(n){for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)>>n);return this},h.prototype.signPropagatingRightShiftM=function(n){if(n=e.checkMatrix(n),this.rows!==n.rows||this.columns!==n.columns)throw new RangeError("Matrices dimensions must be equal");for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)>>n.get(s,u));return this},h.signPropagatingRightShift=function(n,s){return new e(n).signPropagatingRightShift(s)},h.prototype.rightShift=function(n){return typeof n=="number"?this.rightShiftS(n):this.rightShiftM(n)},h.prototype.rightShiftS=function(n){for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)>>>n);return this},h.prototype.rightShiftM=function(n){if(n=e.checkMatrix(n),this.rows!==n.rows||this.columns!==n.columns)throw new RangeError("Matrices dimensions must be equal");for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)>>>n.get(s,u));return this},h.rightShift=function(n,s){return new e(n).rightShift(s)},h.prototype.zeroFillRightShift=h.prototype.rightShift,h.prototype.zeroFillRightShiftS=h.prototype.rightShiftS,h.prototype.zeroFillRightShiftM=h.prototype.rightShiftM,h.zeroFillRightShift=h.rightShift,h.prototype.not=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,~this.get(n,s));return this},h.not=function(n){return new e(n).not()},h.prototype.abs=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.abs(this.get(n,s)));return this},h.abs=function(n){return new e(n).abs()},h.prototype.acos=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.acos(this.get(n,s)));return this},h.acos=function(n){return new e(n).acos()},h.prototype.acosh=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.acosh(this.get(n,s)));return this},h.acosh=function(n){return new e(n).acosh()},h.prototype.asin=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.asin(this.get(n,s)));return this},h.asin=function(n){return new e(n).asin()},h.prototype.asinh=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.asinh(this.get(n,s)));return this},h.asinh=function(n){return new e(n).asinh()},h.prototype.atan=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.atan(this.get(n,s)));return this},h.atan=function(n){return new e(n).atan()},h.prototype.atanh=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.atanh(this.get(n,s)));return this},h.atanh=function(n){return new e(n).atanh()},h.prototype.cbrt=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.cbrt(this.get(n,s)));return this},h.cbrt=function(n){return new e(n).cbrt()},h.prototype.ceil=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.ceil(this.get(n,s)));return this},h.ceil=function(n){return new e(n).ceil()},h.prototype.clz32=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.clz32(this.get(n,s)));return this},h.clz32=function(n){return new e(n).clz32()},h.prototype.cos=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.cos(this.get(n,s)));return this},h.cos=function(n){return new e(n).cos()},h.prototype.cosh=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.cosh(this.get(n,s)));return this},h.cosh=function(n){return new e(n).cosh()},h.prototype.exp=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.exp(this.get(n,s)));return this},h.exp=function(n){return new e(n).exp()},h.prototype.expm1=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.expm1(this.get(n,s)));return this},h.expm1=function(n){return new e(n).expm1()},h.prototype.floor=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.floor(this.get(n,s)));return this},h.floor=function(n){return new e(n).floor()},h.prototype.fround=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.fround(this.get(n,s)));return this},h.fround=function(n){return new e(n).fround()},h.prototype.log=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.log(this.get(n,s)));return this},h.log=function(n){return new e(n).log()},h.prototype.log1p=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.log1p(this.get(n,s)));return this},h.log1p=function(n){return new e(n).log1p()},h.prototype.log10=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.log10(this.get(n,s)));return this},h.log10=function(n){return new e(n).log10()},h.prototype.log2=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.log2(this.get(n,s)));return this},h.log2=function(n){return new e(n).log2()},h.prototype.round=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.round(this.get(n,s)));return this},h.round=function(n){return new e(n).round()},h.prototype.sign=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.sign(this.get(n,s)));return this},h.sign=function(n){return new e(n).sign()},h.prototype.sin=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.sin(this.get(n,s)));return this},h.sin=function(n){return new e(n).sin()},h.prototype.sinh=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.sinh(this.get(n,s)));return this},h.sinh=function(n){return new e(n).sinh()},h.prototype.sqrt=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.sqrt(this.get(n,s)));return this},h.sqrt=function(n){return new e(n).sqrt()},h.prototype.tan=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.tan(this.get(n,s)));return this},h.tan=function(n){return new e(n).tan()},h.prototype.tanh=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.tanh(this.get(n,s)));return this},h.tanh=function(n){return new e(n).tanh()},h.prototype.trunc=function(){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.trunc(this.get(n,s)));return this},h.trunc=function(n){return new e(n).trunc()},h.pow=function(n,s){return new e(n).pow(s)},h.prototype.pow=function(n){return typeof n=="number"?this.powS(n):this.powM(n)},h.prototype.powS=function(n){for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)**n);return this},h.prototype.powM=function(n){if(n=e.checkMatrix(n),this.rows!==n.rows||this.columns!==n.columns)throw new RangeError("Matrices dimensions must be equal");for(let s=0;s<this.rows;s++)for(let u=0;u<this.columns;u++)this.set(s,u,this.get(s,u)**n.get(s,u));return this}}function M(h,e,t){let n=t?h.rows:h.rows-1;if(e<0||e>n)throw new RangeError("Row index out of range")}function H(h,e,t){let n=t?h.columns:h.columns-1;if(e<0||e>n)throw new RangeError("Column index out of range")}function ne(h,e){if(e.to1DArray&&(e=e.to1DArray()),e.length!==h.columns)throw new RangeError("vector size must be the same as the number of columns");return e}function oe(h,e){if(e.to1DArray&&(e=e.to1DArray()),e.length!==h.rows)throw new RangeError("vector size must be the same as the number of rows");return e}function ze(h,e){if(!K(e))throw new TypeError("row indices must be an array");for(let t=0;t<e.length;t++)if(e[t]<0||e[t]>=h.rows)throw new RangeError("row indices are out of range")}function xe(h,e){if(!K(e))throw new TypeError("column indices must be an array");for(let t=0;t<e.length;t++)if(e[t]<0||e[t]>=h.columns)throw new RangeError("column indices are out of range")}function de(h,e,t,n,s){if(arguments.length!==5)throw new RangeError("expected 4 arguments");if(fe("startRow",e),fe("endRow",t),fe("startColumn",n),fe("endColumn",s),e>t||n>s||e<0||e>=h.rows||t<0||t>=h.rows||n<0||n>=h.columns||s<0||s>=h.columns)throw new RangeError("Submatrix indices are out of range")}function ve(h,e=0){let t=[];for(let n=0;n<h;n++)t.push(e);return t}function fe(h,e){if(typeof e!="number")throw new TypeError(`${h} must be a number`)}function re(h){if(h.isEmpty())throw new Error("Empty matrix has no elements to index")}function mt(h){let e=ve(h.rows);for(let t=0;t<h.rows;++t)for(let n=0;n<h.columns;++n)e[t]+=h.get(t,n);return e}function at(h){let e=ve(h.columns);for(let t=0;t<h.rows;++t)for(let n=0;n<h.columns;++n)e[n]+=h.get(t,n);return e}function gt(h){let e=0;for(let t=0;t<h.rows;t++)for(let n=0;n<h.columns;n++)e+=h.get(t,n);return e}function wt(h){let e=ve(h.rows,1);for(let t=0;t<h.rows;++t)for(let n=0;n<h.columns;++n)e[t]*=h.get(t,n);return e}function pt(h){let e=ve(h.columns,1);for(let t=0;t<h.rows;++t)for(let n=0;n<h.columns;++n)e[n]*=h.get(t,n);return e}function vt(h){let e=1;for(let t=0;t<h.rows;t++)for(let n=0;n<h.columns;n++)e*=h.get(t,n);return e}function dt(h,e,t){let n=h.rows,s=h.columns,u=[];for(let c=0;c<n;c++){let i=0,r=0,o=0;for(let l=0;l<s;l++)o=h.get(c,l)-t[c],i+=o,r+=o*o;e?u.push((r-i*i/s)/(s-1)):u.push((r-i*i/s)/s)}return u}function yt(h,e,t){let n=h.rows,s=h.columns,u=[];for(let c=0;c<s;c++){let i=0,r=0,o=0;for(let l=0;l<n;l++)o=h.get(l,c)-t[c],i+=o,r+=o*o;e?u.push((r-i*i/n)/(n-1)):u.push((r-i*i/n)/n)}return u}function bt(h,e,t){let n=h.rows,s=h.columns,u=n*s,c=0,i=0,r=0;for(let o=0;o<n;o++)for(let l=0;l<s;l++)r=h.get(o,l)-t,c+=r,i+=r*r;return e?(i-c*c/u)/(u-1):(i-c*c/u)/u}function Et(h,e){for(let t=0;t<h.rows;t++)for(let n=0;n<h.columns;n++)h.set(t,n,h.get(t,n)-e[t])}function qt(h,e){for(let t=0;t<h.rows;t++)for(let n=0;n<h.columns;n++)h.set(t,n,h.get(t,n)-e[n])}function kt(h,e){for(let t=0;t<h.rows;t++)for(let n=0;n<h.columns;n++)h.set(t,n,h.get(t,n)-e)}function Rt(h){let e=[];for(let t=0;t<h.rows;t++){let n=0;for(let s=0;s<h.columns;s++)n+=h.get(t,s)**2/(h.columns-1);e.push(Math.sqrt(n))}return e}function It(h,e){for(let t=0;t<h.rows;t++)for(let n=0;n<h.columns;n++)h.set(t,n,h.get(t,n)/e[t])}function Tt(h){let e=[];for(let t=0;t<h.columns;t++){let n=0;for(let s=0;s<h.rows;s++)n+=h.get(s,t)**2/(h.rows-1);e.push(Math.sqrt(n))}return e}function Nt(h,e){for(let t=0;t<h.rows;t++)for(let n=0;n<h.columns;n++)h.set(t,n,h.get(t,n)/e[n])}function zt(h){let e=h.size-1,t=0;for(let n=0;n<h.columns;n++)for(let s=0;s<h.rows;s++)t+=h.get(s,n)**2/e;return Math.sqrt(t)}function xt(h,e){for(let t=0;t<h.rows;t++)for(let n=0;n<h.columns;n++)h.set(t,n,h.get(t,n)/e)}var Q=class h{static from1DArray(e,t,n){if(e*t!==n.length)throw new RangeError("data length does not match given dimensions");let u=new x(e,t);for(let c=0;c<e;c++)for(let i=0;i<t;i++)u.set(c,i,n[c*t+i]);return u}static rowVector(e){let t=new x(1,e.length);for(let n=0;n<e.length;n++)t.set(0,n,e[n]);return t}static columnVector(e){let t=new x(e.length,1);for(let n=0;n<e.length;n++)t.set(n,0,e[n]);return t}static zeros(e,t){return new x(e,t)}static ones(e,t){return new x(e,t).fill(1)}static rand(e,t,n={}){if(typeof n!="object")throw new TypeError("options must be an object");let{random:s=Math.random}=n,u=new x(e,t);for(let c=0;c<e;c++)for(let i=0;i<t;i++)u.set(c,i,s());return u}static randInt(e,t,n={}){if(typeof n!="object")throw new TypeError("options must be an object");let{min:s=0,max:u=1e3,random:c=Math.random}=n;if(!Number.isInteger(s))throw new TypeError("min must be an integer");if(!Number.isInteger(u))throw new TypeError("max must be an integer");if(s>=u)throw new RangeError("min must be smaller than max");let i=u-s,r=new x(e,t);for(let o=0;o<e;o++)for(let l=0;l<t;l++){let f=s+Math.round(c()*i);r.set(o,l,f)}return r}static eye(e,t,n){t===void 0&&(t=e),n===void 0&&(n=1);let s=Math.min(e,t),u=this.zeros(e,t);for(let c=0;c<s;c++)u.set(c,c,n);return u}static diag(e,t,n){let s=e.length;t===void 0&&(t=s),n===void 0&&(n=t);let u=Math.min(s,t,n),c=this.zeros(t,n);for(let i=0;i<u;i++)c.set(i,i,e[i]);return c}static min(e,t){e=this.checkMatrix(e),t=this.checkMatrix(t);let n=e.rows,s=e.columns,u=new x(n,s);for(let c=0;c<n;c++)for(let i=0;i<s;i++)u.set(c,i,Math.min(e.get(c,i),t.get(c,i)));return u}static max(e,t){e=this.checkMatrix(e),t=this.checkMatrix(t);let n=e.rows,s=e.columns,u=new this(n,s);for(let c=0;c<n;c++)for(let i=0;i<s;i++)u.set(c,i,Math.max(e.get(c,i),t.get(c,i)));return u}static checkMatrix(e){return h.isMatrix(e)?e:new x(e)}static isMatrix(e){return e!=null&&e.klass==="Matrix"}get size(){return this.rows*this.columns}apply(e){if(typeof e!="function")throw new TypeError("callback must be a function");for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)e.call(this,t,n);return this}applyAlongAxis(e,t){if(typeof e!="function")throw new TypeError("callback must be a function");let n=[];switch(t){case"row":{for(let s=0;s<this.rows;s++)n.push(e.call(this,this.getRow(s),s));break}case"column":{for(let s=0;s<this.columns;s++)n.push(e.call(this,this.getColumn(s),s));break}default:throw new Error(`invalid option: ${t}`)}return n}to1DArray(){let e=[];for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)e.push(this.get(t,n));return e}to2DArray(){let e=[];for(let t=0;t<this.rows;t++){e.push([]);for(let n=0;n<this.columns;n++)e[t].push(this.get(t,n))}return e}toJSON(){return this.to2DArray()}isRowVector(){return this.rows===1}isColumnVector(){return this.columns===1}isVector(){return this.rows===1||this.columns===1}isSquare(){return this.rows===this.columns}isEmpty(){return this.rows===0||this.columns===0}isSymmetric(){if(this.isSquare()){for(let e=0;e<this.rows;e++)for(let t=0;t<=e;t++)if(this.get(e,t)!==this.get(t,e))return!1;return!0}return!1}isDistance(){if(!this.isSymmetric())return!1;for(let e=0;e<this.rows;e++)if(this.get(e,e)!==0)return!1;return!0}isEchelonForm(){let e=0,t=0,n=-1,s=!0,u=!1;for(;e<this.rows&&s;){for(t=0,u=!1;t<this.columns&&u===!1;)this.get(e,t)===0?t++:this.get(e,t)===1&&t>n?(u=!0,n=t):(s=!1,u=!0);e++}return s}isReducedEchelonForm(){let e=0,t=0,n=-1,s=!0,u=!1;for(;e<this.rows&&s;){for(t=0,u=!1;t<this.columns&&u===!1;)this.get(e,t)===0?t++:this.get(e,t)===1&&t>n?(u=!0,n=t):(s=!1,u=!0);for(let c=t+1;c<this.rows;c++)this.get(e,c)!==0&&(s=!1);e++}return s}echelonForm(){let e=this.clone(),t=0,n=0;for(;t<e.rows&&n<e.columns;){let s=t;for(let u=t;u<e.rows;u++)e.get(u,n)>e.get(s,n)&&(s=u);if(e.get(s,n)===0)n++;else{e.swapRows(t,s);let u=e.get(t,n);for(let c=n;c<e.columns;c++)e.set(t,c,e.get(t,c)/u);for(let c=t+1;c<e.rows;c++){let i=e.get(c,n)/e.get(t,n);e.set(c,n,0);for(let r=n+1;r<e.columns;r++)e.set(c,r,e.get(c,r)-e.get(t,r)*i)}t++,n++}}return e}reducedEchelonForm(){let e=this.echelonForm(),t=e.columns,n=e.rows,s=n-1;for(;s>=0;)if(e.maxRow(s)===0)s--;else{let u=0,c=!1;for(;u<n&&c===!1;)e.get(s,u)===1?c=!0:u++;for(let i=0;i<s;i++){let r=e.get(i,u);for(let o=u;o<t;o++){let l=e.get(i,o)-r*e.get(s,o);e.set(i,o,l)}}s--}return e}set(){throw new Error("set method is unimplemented")}get(){throw new Error("get method is unimplemented")}repeat(e={}){if(typeof e!="object")throw new TypeError("options must be an object");let{rows:t=1,columns:n=1}=e;if(!Number.isInteger(t)||t<=0)throw new TypeError("rows must be a positive integer");if(!Number.isInteger(n)||n<=0)throw new TypeError("columns must be a positive integer");let s=new x(this.rows*t,this.columns*n);for(let u=0;u<t;u++)for(let c=0;c<n;c++)s.setSubMatrix(this,this.rows*u,this.columns*c);return s}fill(e){for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,e);return this}neg(){return this.mulS(-1)}getRow(e){M(this,e);let t=[];for(let n=0;n<this.columns;n++)t.push(this.get(e,n));return t}getRowVector(e){return x.rowVector(this.getRow(e))}setRow(e,t){M(this,e),t=ne(this,t);for(let n=0;n<this.columns;n++)this.set(e,n,t[n]);return this}swapRows(e,t){M(this,e),M(this,t);for(let n=0;n<this.columns;n++){let s=this.get(e,n);this.set(e,n,this.get(t,n)),this.set(t,n,s)}return this}getColumn(e){H(this,e);let t=[];for(let n=0;n<this.rows;n++)t.push(this.get(n,e));return t}getColumnVector(e){return x.columnVector(this.getColumn(e))}setColumn(e,t){H(this,e),t=oe(this,t);for(let n=0;n<this.rows;n++)this.set(n,e,t[n]);return this}swapColumns(e,t){H(this,e),H(this,t);for(let n=0;n<this.rows;n++){let s=this.get(n,e);this.set(n,e,this.get(n,t)),this.set(n,t,s)}return this}addRowVector(e){e=ne(this,e);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)+e[n]);return this}subRowVector(e){e=ne(this,e);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)-e[n]);return this}mulRowVector(e){e=ne(this,e);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)*e[n]);return this}divRowVector(e){e=ne(this,e);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)/e[n]);return this}addColumnVector(e){e=oe(this,e);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)+e[t]);return this}subColumnVector(e){e=oe(this,e);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)-e[t]);return this}mulColumnVector(e){e=oe(this,e);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)*e[t]);return this}divColumnVector(e){e=oe(this,e);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)this.set(t,n,this.get(t,n)/e[t]);return this}mulRow(e,t){M(this,e);for(let n=0;n<this.columns;n++)this.set(e,n,this.get(e,n)*t);return this}mulColumn(e,t){H(this,e);for(let n=0;n<this.rows;n++)this.set(n,e,this.get(n,e)*t);return this}max(e){if(this.isEmpty())return NaN;switch(e){case"row":{let t=new Array(this.rows).fill(Number.NEGATIVE_INFINITY);for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.get(n,s)>t[n]&&(t[n]=this.get(n,s));return t}case"column":{let t=new Array(this.columns).fill(Number.NEGATIVE_INFINITY);for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.get(n,s)>t[s]&&(t[s]=this.get(n,s));return t}case void 0:{let t=this.get(0,0);for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.get(n,s)>t&&(t=this.get(n,s));return t}default:throw new Error(`invalid option: ${e}`)}}maxIndex(){re(this);let e=this.get(0,0),t=[0,0];for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.get(n,s)>e&&(e=this.get(n,s),t[0]=n,t[1]=s);return t}min(e){if(this.isEmpty())return NaN;switch(e){case"row":{let t=new Array(this.rows).fill(Number.POSITIVE_INFINITY);for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.get(n,s)<t[n]&&(t[n]=this.get(n,s));return t}case"column":{let t=new Array(this.columns).fill(Number.POSITIVE_INFINITY);for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.get(n,s)<t[s]&&(t[s]=this.get(n,s));return t}case void 0:{let t=this.get(0,0);for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.get(n,s)<t&&(t=this.get(n,s));return t}default:throw new Error(`invalid option: ${e}`)}}minIndex(){re(this);let e=this.get(0,0),t=[0,0];for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.get(n,s)<e&&(e=this.get(n,s),t[0]=n,t[1]=s);return t}maxRow(e){if(M(this,e),this.isEmpty())return NaN;let t=this.get(e,0);for(let n=1;n<this.columns;n++)this.get(e,n)>t&&(t=this.get(e,n));return t}maxRowIndex(e){M(this,e),re(this);let t=this.get(e,0),n=[e,0];for(let s=1;s<this.columns;s++)this.get(e,s)>t&&(t=this.get(e,s),n[1]=s);return n}minRow(e){if(M(this,e),this.isEmpty())return NaN;let t=this.get(e,0);for(let n=1;n<this.columns;n++)this.get(e,n)<t&&(t=this.get(e,n));return t}minRowIndex(e){M(this,e),re(this);let t=this.get(e,0),n=[e,0];for(let s=1;s<this.columns;s++)this.get(e,s)<t&&(t=this.get(e,s),n[1]=s);return n}maxColumn(e){if(H(this,e),this.isEmpty())return NaN;let t=this.get(0,e);for(let n=1;n<this.rows;n++)this.get(n,e)>t&&(t=this.get(n,e));return t}maxColumnIndex(e){H(this,e),re(this);let t=this.get(0,e),n=[0,e];for(let s=1;s<this.rows;s++)this.get(s,e)>t&&(t=this.get(s,e),n[0]=s);return n}minColumn(e){if(H(this,e),this.isEmpty())return NaN;let t=this.get(0,e);for(let n=1;n<this.rows;n++)this.get(n,e)<t&&(t=this.get(n,e));return t}minColumnIndex(e){H(this,e),re(this);let t=this.get(0,e),n=[0,e];for(let s=1;s<this.rows;s++)this.get(s,e)<t&&(t=this.get(s,e),n[0]=s);return n}diag(){let e=Math.min(this.rows,this.columns),t=[];for(let n=0;n<e;n++)t.push(this.get(n,n));return t}norm(e="frobenius"){switch(e){case"max":return this.max();case"frobenius":return Math.sqrt(this.dot(this));default:throw new RangeError(`unknown norm type: ${e}`)}}cumulativeSum(){let e=0;for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)e+=this.get(t,n),this.set(t,n,e);return this}dot(e){h.isMatrix(e)&&(e=e.to1DArray());let t=this.to1DArray();if(t.length!==e.length)throw new RangeError("vectors do not have the same size");let n=0;for(let s=0;s<t.length;s++)n+=t[s]*e[s];return n}mmul(e){e=x.checkMatrix(e);let t=this.rows,n=this.columns,s=e.columns,u=new x(t,s),c=new Float64Array(n);for(let i=0;i<s;i++){for(let r=0;r<n;r++)c[r]=e.get(r,i);for(let r=0;r<t;r++){let o=0;for(let l=0;l<n;l++)o+=this.get(r,l)*c[l];u.set(r,i,o)}}return u}gram(){let e=this.rows,t=this.columns,n=new Float64Array(t*t);for(let u=0;u<e;u++)for(let c=0;c<t;c++){let i=this.get(u,c);if(i===0)continue;let r=c*t;for(let o=c;o<t;o++)n[r+o]+=i*this.get(u,o)}let s=new x(t,t);for(let u=0;u<t;u++){let c=u*t;for(let i=u;i<t;i++){let r=n[c+i];s.set(u,i,r),s.set(i,u,r)}}return s}transposeMultiply(e){if(e=x.checkMatrix(e),this.rows!==e.rows)throw new RangeError("the number of rows of the two matrices must be equal");let t=this.columns,n=e.columns,s=new x(t,n),u=new Float64Array(n);for(let c=0;c<this.rows;c++){for(let i=0;i<n;i++)u[i]=e.get(c,i);for(let i=0;i<t;i++){let r=this.get(c,i);if(r===0)continue;let o=s.data[i];for(let l=0;l<n;l++)o[l]+=r*u[l]}}return s}mmulByTranspose(e){let t=this.rows,n=this.columns;if(e!==void 0&&e.length!==n)throw new RangeError("scale must have one value per column");let s=new x(t,t),u=new Float64Array(n);for(let c=0;c<t;c++){if(e===void 0)for(let i=0;i<n;i++)u[i]=this.get(c,i);else for(let i=0;i<n;i++)u[i]=e[i]*this.get(c,i);for(let i=c;i<t;i++){let r=0;for(let o=0;o<n;o++)r+=this.get(i,o)*u[o];s.set(i,c,r),s.set(c,i,r)}}return s}mpow(e){if(!this.isSquare())throw new RangeError("Matrix must be square");if(!Number.isInteger(e)||e<0)throw new RangeError("Exponent must be a non-negative integer");let t=x.eye(this.rows),n=this;for(let s=e;s>=1;s/=2)(s&1)!==0&&(t=t.mmul(n)),n=n.mmul(n);return t}strassen2x2(e){e=x.checkMatrix(e);let t=new x(2,2),n=this.get(0,0),s=e.get(0,0),u=this.get(0,1),c=e.get(0,1),i=this.get(1,0),r=e.get(1,0),o=this.get(1,1),l=e.get(1,1),f=(n+o)*(s+l),a=(i+o)*s,w=n*(c-l),g=o*(r-s),p=(n+u)*l,d=(i-n)*(s+c),m=(u-o)*(r+l),v=f+g-p+m,y=w+p,E=a+g,q=f-a+w+d;return t.set(0,0,v),t.set(0,1,y),t.set(1,0,E),t.set(1,1,q),t}strassen3x3(e){e=x.checkMatrix(e);let t=new x(3,3),n=this.get(0,0),s=this.get(0,1),u=this.get(0,2),c=this.get(1,0),i=this.get(1,1),r=this.get(1,2),o=this.get(2,0),l=this.get(2,1),f=this.get(2,2),a=e.get(0,0),w=e.get(0,1),g=e.get(0,2),p=e.get(1,0),d=e.get(1,1),m=e.get(1,2),v=e.get(2,0),y=e.get(2,1),E=e.get(2,2),q=(n+s+u-c-i-l-f)*d,N=(n-c)*(-w+d),R=i*(-a+w+p-d-m-v+E),T=(-n+c+i)*(a-w+d),_=(c+i)*(-a+w),b=n*a,k=(-n+o+l)*(a-g+m),z=(-n+o)*(g-m),I=(o+l)*(-a+g),O=(n+s+u-i-r-o-l)*m,P=l*(-a+g+p-d-m-v+y),C=(-u+l+f)*(d+v-y),D=(u-f)*(d-y),$=u*v,G=(l+f)*(-v+y),U=(-u+i+r)*(m+v-E),B=(u-r)*(m-E),Z=(i+r)*(-v+E),V=s*p,W=r*y,J=c*g,A=o*w,Y=f*E,Je=b+$+V,Ye=q+T+_+b+C+$+G,Ke=b+k+I+O+$+U+Z,Ze=N+R+T+b+$+U+B,Xe=N+T+_+b+W,Ae=$+U+B+Z+J,Me=b+k+z+P+C+D+$,He=C+D+$+G+A,Se=b+k+z+I+Y;return t.set(0,0,Je),t.set(0,1,Ye),t.set(0,2,Ke),t.set(1,0,Ze),t.set(1,1,Xe),t.set(1,2,Ae),t.set(2,0,Me),t.set(2,1,He),t.set(2,2,Se),t}mmulStrassen(e){e=x.checkMatrix(e);let t=this.clone(),n=t.rows,s=t.columns,u=e.rows,c=e.columns;s!==u&&console.warn(`Multiplying ${n} x ${s} and ${u} x ${c} matrix: dimensions do not match.`);function i(f,a,w){let g=f.rows,p=f.columns;if(g===a&&p===w)return f;{let d=h.zeros(a,w);return d=d.setSubMatrix(f,0,0),d}}let r=Math.max(n,u),o=Math.max(s,c);t=i(t,r,o),e=i(e,r,o);function l(f,a,w,g){if(w<=512||g<=512)return f.mmul(a);w%2===1&&g%2===1?(f=i(f,w+1,g+1),a=i(a,w+1,g+1)):w%2===1?(f=i(f,w+1,g),a=i(a,w+1,g)):g%2===1&&(f=i(f,w,g+1),a=i(a,w,g+1));let p=parseInt(f.rows/2,10),d=parseInt(f.columns/2,10),m=f.subMatrix(0,p-1,0,d-1),v=a.subMatrix(0,p-1,0,d-1),y=f.subMatrix(0,p-1,d,f.columns-1),E=a.subMatrix(0,p-1,d,a.columns-1),q=f.subMatrix(p,f.rows-1,0,d-1),N=a.subMatrix(p,a.rows-1,0,d-1),R=f.subMatrix(p,f.rows-1,d,f.columns-1),T=a.subMatrix(p,a.rows-1,d,a.columns-1),_=l(h.add(m,R),h.add(v,T),p,d),b=l(h.add(q,R),v,p,d),k=l(m,h.sub(E,T),p,d),z=l(R,h.sub(N,v),p,d),I=l(h.add(m,y),T,p,d),O=l(h.sub(q,m),h.add(v,E),p,d),P=l(h.sub(y,R),h.add(N,T),p,d),C=h.add(_,z);C.sub(I),C.add(P);let D=h.add(k,I),$=h.add(b,z),G=h.sub(_,b);G.add(k),G.add(O);let U=h.zeros(2*C.rows,2*C.columns);return U=U.setSubMatrix(C,0,0),U=U.setSubMatrix(D,C.rows,0),U=U.setSubMatrix($,0,C.columns),U=U.setSubMatrix(G,C.rows,C.columns),U.subMatrix(0,w-1,0,g-1)}return l(t,e,r,o)}scaleRows(e={}){if(typeof e!="object")throw new TypeError("options must be an object");let{min:t=0,max:n=1}=e;if(!Number.isFinite(t))throw new TypeError("min must be a number");if(!Number.isFinite(n))throw new TypeError("max must be a number");if(t>=n)throw new RangeError("min must be smaller than max");let s=new x(this.rows,this.columns);for(let u=0;u<this.rows;u++){let c=this.getRow(u);c.length>0&&Le(c,{min:t,max:n,output:c}),s.setRow(u,c)}return s}scaleColumns(e={}){if(typeof e!="object")throw new TypeError("options must be an object");let{min:t=0,max:n=1}=e;if(!Number.isFinite(t))throw new TypeError("min must be a number");if(!Number.isFinite(n))throw new TypeError("max must be a number");if(t>=n)throw new RangeError("min must be smaller than max");let s=new x(this.rows,this.columns);for(let u=0;u<this.columns;u++){let c=this.getColumn(u);c.length&&Le(c,{min:t,max:n,output:c}),s.setColumn(u,c)}return s}flipRows(){let e=Math.ceil(this.columns/2);for(let t=0;t<this.rows;t++)for(let n=0;n<e;n++){let s=this.get(t,n),u=this.get(t,this.columns-1-n);this.set(t,n,u),this.set(t,this.columns-1-n,s)}return this}flipColumns(){let e=Math.ceil(this.rows/2);for(let t=0;t<this.columns;t++)for(let n=0;n<e;n++){let s=this.get(n,t),u=this.get(this.rows-1-n,t);this.set(n,t,u),this.set(this.rows-1-n,t,s)}return this}kroneckerProduct(e){e=x.checkMatrix(e);let t=this.rows,n=this.columns,s=e.rows,u=e.columns,c=new x(t*s,n*u);for(let i=0;i<t;i++)for(let r=0;r<n;r++)for(let o=0;o<s;o++)for(let l=0;l<u;l++)c.set(s*i+o,u*r+l,this.get(i,r)*e.get(o,l));return c}kroneckerSum(e){if(e=x.checkMatrix(e),!this.isSquare()||!e.isSquare())throw new Error("Kronecker Sum needs two Square Matrices");let t=this.rows,n=e.rows,s=this.kroneckerProduct(x.eye(n,n)),u=x.eye(t,t).kroneckerProduct(e);return s.add(u)}transpose(){let e=new x(this.columns,this.rows);for(let t=0;t<this.rows;t++)for(let n=0;n<this.columns;n++)e.set(n,t,this.get(t,n));return e}sortRows(e=Ce){for(let t=0;t<this.rows;t++)this.setRow(t,this.getRow(t).sort(e));return this}sortColumns(e=Ce){for(let t=0;t<this.columns;t++)this.setColumn(t,this.getColumn(t).sort(e));return this}subMatrix(e,t,n,s){de(this,e,t,n,s);let u=new x(t-e+1,s-n+1);for(let c=e;c<=t;c++)for(let i=n;i<=s;i++)u.set(c-e,i-n,this.get(c,i));return u}subMatrixRow(e,t,n){if(t===void 0&&(t=0),n===void 0&&(n=this.columns-1),t>n||t<0||t>=this.columns||n<0||n>=this.columns)throw new RangeError("Argument out of range");let s=new x(e.length,n-t+1);for(let u=0;u<e.length;u++)for(let c=t;c<=n;c++){if(e[u]<0||e[u]>=this.rows)throw new RangeError(`Row index out of range: ${e[u]}`);s.set(u,c-t,this.get(e[u],c))}return s}subMatrixColumn(e,t,n){if(t===void 0&&(t=0),n===void 0&&(n=this.rows-1),t>n||t<0||t>=this.rows||n<0||n>=this.rows)throw new RangeError("Argument out of range");let s=new x(n-t+1,e.length);for(let u=0;u<e.length;u++)for(let c=t;c<=n;c++){if(e[u]<0||e[u]>=this.columns)throw new RangeError(`Column index out of range: ${e[u]}`);s.set(c-t,u,this.get(c,e[u]))}return s}setSubMatrix(e,t,n){if(e=x.checkMatrix(e),e.isEmpty())return this;let s=t+e.rows-1,u=n+e.columns-1;de(this,t,s,n,u);for(let c=0;c<e.rows;c++)for(let i=0;i<e.columns;i++)this.set(t+c,n+i,e.get(c,i));return this}concat(e,t="row"){switch(e=x.checkMatrix(e),t){case"row":{if(this.columns!==e.columns)throw new RangeError("both matrices must have the same number of columns");let n=new x(this.rows+e.rows,this.columns);return n.setSubMatrix(this,0,0),n.setSubMatrix(e,this.rows,0),n}case"column":{if(this.rows!==e.rows)throw new RangeError("both matrices must have the same number of rows");let n=new x(this.rows,this.columns+e.columns);return n.setSubMatrix(this,0,0),n.setSubMatrix(e,0,this.columns),n}default:throw new Error(`invalid option: ${t}`)}}selection(e,t){ze(this,e),xe(this,t);let n=new x(e.length,t.length);for(let s=0;s<e.length;s++){let u=e[s];for(let c=0;c<t.length;c++){let i=t[c];n.set(s,c,this.get(u,i))}}return n}trace(){let e=Math.min(this.rows,this.columns),t=0;for(let n=0;n<e;n++)t+=this.get(n,n);return t}clone(){return this.constructor.copy(this,new x(this.rows,this.columns))}static copy(e,t){for(let[n,s,u]of e.entries())t.set(n,s,u);return t}sum(e){switch(e){case"row":return mt(this);case"column":return at(this);case void 0:return gt(this);default:throw new Error(`invalid option: ${e}`)}}product(e){switch(e){case"row":return wt(this);case"column":return pt(this);case void 0:return vt(this);default:throw new Error(`invalid option: ${e}`)}}mean(e){let t=this.sum(e);switch(e){case"row":{for(let n=0;n<this.rows;n++)t[n]/=this.columns;return t}case"column":{for(let n=0;n<this.columns;n++)t[n]/=this.rows;return t}case void 0:return t/this.size;default:throw new Error(`invalid option: ${e}`)}}variance(e,t={}){if(typeof e=="object"&&(t=e,e=void 0),typeof t!="object")throw new TypeError("options must be an object");let{unbiased:n=!0,mean:s=this.mean(e)}=t;if(typeof n!="boolean")throw new TypeError("unbiased must be a boolean");switch(e){case"row":{if(!K(s))throw new TypeError("mean must be an array");return dt(this,n,s)}case"column":{if(!K(s))throw new TypeError("mean must be an array");return yt(this,n,s)}case void 0:{if(typeof s!="number")throw new TypeError("mean must be a number");return bt(this,n,s)}default:throw new Error(`invalid option: ${e}`)}}standardDeviation(e,t){typeof e=="object"&&(t=e,e=void 0);let n=this.variance(e,t);if(e===void 0)return Math.sqrt(n);for(let s=0;s<n.length;s++)n[s]=Math.sqrt(n[s]);return n}center(e,t={}){if(typeof e=="object"&&(t=e,e=void 0),typeof t!="object")throw new TypeError("options must be an object");let{center:n=this.mean(e)}=t;switch(e){case"row":{if(!K(n))throw new TypeError("center must be an array");return Et(this,n),this}case"column":{if(!K(n))throw new TypeError("center must be an array");return qt(this,n),this}case void 0:{if(typeof n!="number")throw new TypeError("center must be a number");return kt(this,n),this}default:throw new Error(`invalid option: ${e}`)}}scale(e,t={}){if(typeof e=="object"&&(t=e,e=void 0),typeof t!="object")throw new TypeError("options must be an object");let n=t.scale;switch(e){case"row":{if(n===void 0)n=Rt(this);else if(!K(n))throw new TypeError("scale must be an array");return It(this,n),this}case"column":{if(n===void 0)n=Tt(this);else if(!K(n))throw new TypeError("scale must be an array");return Nt(this,n),this}case void 0:{if(n===void 0)n=zt(this);else if(typeof n!="number")throw new TypeError("scale must be a number");return xt(this,n),this}default:throw new Error(`invalid option: ${e}`)}}toString(e){return $e(this,e)}[Symbol.iterator](){return this.entries()}*entries(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)yield[e,t,this.get(e,t)]}*values(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)yield this.get(e,t)}};Q.prototype.klass="Matrix";typeof Symbol<"u"&&(Q.prototype[Symbol.for("nodejs.util.inspect.custom")]=lt);function Ce(h,e){return h-e}function _t(h){return h.every(e=>typeof e=="number")}Q.random=Q.rand;Q.randomInt=Q.randInt;Q.diagonal=Q.diag;Q.prototype.diagonal=Q.prototype.diag;Q.identity=Q.eye;Q.prototype.negate=Q.prototype.neg;Q.prototype.tensorProduct=Q.prototype.kroneckerProduct;var x=class h extends Q{data;#e(e,t){if(this.data=[],Number.isInteger(t)&&t>=0)for(let n=0;n<e;n++)this.data.push(new Float64Array(t));else throw new TypeError("nColumns must be a positive integer");this.rows=e,this.columns=t}constructor(e,t){if(super(),h.isMatrix(e))this.#e(e.rows,e.columns),h.copy(e,this);else if(Number.isInteger(e)&&e>=0)this.#e(e,t);else if(K(e)){let n=e;if(e=n.length,t=e?n[0].length:0,typeof t!="number")throw new TypeError("Data must be a 2D array with at least one element");this.data=[];for(let s=0;s<e;s++){if(n[s].length!==t)throw new RangeError("Inconsistent array dimensions");if(!_t(n[s]))throw new TypeError("Input data contains non-numeric values");this.data.push(Float64Array.from(n[s]))}this.rows=e,this.columns=t}else throw new TypeError("First argument must be a positive number or an array")}set(e,t,n){return this.data[e][t]=n,this}get(e,t){return this.data[e][t]}removeRow(e){return M(this,e),this.data.splice(e,1),this.rows-=1,this}addRow(e,t){return t===void 0&&(t=e,e=this.rows),M(this,e,!0),t=Float64Array.from(ne(this,t)),this.data.splice(e,0,t),this.rows+=1,this}removeColumn(e){H(this,e);for(let t=0;t<this.rows;t++){let n=new Float64Array(this.columns-1);for(let s=0;s<e;s++)n[s]=this.data[t][s];for(let s=e+1;s<this.columns;s++)n[s-1]=this.data[t][s];this.data[t]=n}return this.columns-=1,this}addColumn(e,t){typeof t>"u"&&(t=e,e=this.columns),H(this,e,!0),t=oe(this,t);for(let n=0;n<this.rows;n++){let s=new Float64Array(this.columns+1),u=0;for(;u<e;u++)s[u]=this.data[n][u];for(s[u++]=t[n];u<this.columns+1;u++)s[u]=this.data[n][u-1];this.data[n]=s}return this.columns+=1,this}};ht(Q,x);var te=class h extends Q{#e;get size(){return this.#e.size}get rows(){return this.#e.rows}get columns(){return this.#e.columns}get diagonalSize(){return this.rows}static isSymmetricMatrix(e){return x.isMatrix(e)&&e.klassType==="SymmetricMatrix"}static zeros(e){return new this(e)}static ones(e){return new this(e).fill(1)}constructor(e){if(super(),x.isMatrix(e)){if(!e.isSymmetric())throw new TypeError("not symmetric data");this.#e=x.copy(e,new x(e.rows,e.rows))}else if(Number.isInteger(e)&&e>=0)this.#e=new x(e,e);else if(this.#e=new x(e),!this.isSymmetric())throw new TypeError("not symmetric data")}clone(){let e=new h(this.diagonalSize);for(let[t,n,s]of this.upperRightEntries())e.set(t,n,s);return e}toMatrix(){return new x(this)}get(e,t){return this.#e.get(e,t)}set(e,t,n){return this.#e.set(e,t,n),this.#e.set(t,e,n),this}removeCross(e){return this.#e.removeRow(e),this.#e.removeColumn(e),this}addCross(e,t){t===void 0&&(t=e,e=this.diagonalSize);let n=t.slice();return n.splice(e,1),this.#e.addRow(e,n),this.#e.addColumn(e,t),this}applyMask(e){if(e.length!==this.diagonalSize)throw new RangeError("Mask size do not match with matrix size");let t=[];for(let[n,s]of e.entries())s||t.push(n);t.reverse();for(let n of t)this.removeCross(n);return this}toCompact(){let{diagonalSize:e}=this,t=new Array(e*(e+1)/2);for(let n=0,s=0,u=0;u<t.length;u++)t[u]=this.get(s,n),++n>=e&&(n=++s);return t}static fromCompact(e){let t=e.length,n=(Math.sqrt(8*t+1)-1)/2;if(!Number.isInteger(n))throw new TypeError(`This array is not a compact representation of a Symmetric Matrix, ${JSON.stringify(e)}`);let s=new h(n);for(let u=0,c=0,i=0;i<t;i++)s.set(u,c,e[i]),++u>=n&&(u=++c);return s}*upperRightEntries(){for(let e=0,t=0;e<this.diagonalSize;void 0){let n=this.get(e,t);yield[e,t,n],++t>=this.diagonalSize&&(t=++e)}}*upperRightValues(){for(let e=0,t=0;e<this.diagonalSize;void 0)yield this.get(e,t),++t>=this.diagonalSize&&(t=++e)}};te.prototype.klassType="SymmetricMatrix";var me=class h extends te{static isDistanceMatrix(e){return te.isSymmetricMatrix(e)&&e.klassSubType==="DistanceMatrix"}constructor(e){if(super(e),!this.isDistance())throw new TypeError("Provided arguments do no produce a distance matrix")}set(e,t,n){return e===t&&(n=0),super.set(e,t,n)}addCross(e,t){return t===void 0&&(t=e,e=this.diagonalSize),t=t.slice(),t[e]=0,super.addCross(e,t)}toSymmetricMatrix(){return new te(this)}clone(){let e=new h(this.diagonalSize);for(let[t,n,s]of this.upperRightEntries())t!==n&&e.set(t,n,s);return e}toCompact(){let{diagonalSize:e}=this,t=(e-1)*e/2,n=new Array(t);for(let s=1,u=0,c=0;c<n.length;c++)n[c]=this.get(u,s),++s>=e&&(s=++u+1);return n}static fromCompact(e){let t=e.length;if(t===0)return new this(0);let n=(Math.sqrt(8*t+1)+1)/2;if(!Number.isInteger(n))throw new TypeError(`This array is not a compact representation of a DistanceMatrix, ${JSON.stringify(e)}`);let s=new this(n);for(let u=1,c=0,i=0;i<t;i++)s.set(u,c,e[i]),++u>=n&&(u=++c+1);return s}};me.prototype.klassSubType="DistanceMatrix";var S=class extends Q{constructor(e,t,n){super(),this.matrix=e,this.rows=t,this.columns=n}},ye=class extends S{constructor(e,t){H(e,t),super(e,e.rows,1),this.column=t}set(e,t,n){return this.matrix.set(e,this.column,n),this}get(e){return this.matrix.get(e,this.column)}},be=class extends S{constructor(e,t){xe(e,t),super(e,e.rows,t.length),this.columnIndices=t}set(e,t,n){return this.matrix.set(e,this.columnIndices[t],n),this}get(e,t){return this.matrix.get(e,this.columnIndices[t])}},Ee=class extends S{constructor(e){super(e,e.rows,e.columns)}set(e,t,n){return this.matrix.set(e,this.columns-t-1,n),this}get(e,t){return this.matrix.get(e,this.columns-t-1)}},qe=class extends S{constructor(e){super(e,e.rows,e.columns)}set(e,t,n){return this.matrix.set(this.rows-e-1,t,n),this}get(e,t){return this.matrix.get(this.rows-e-1,t)}},ke=class extends S{constructor(e,t){M(e,t),super(e,1,e.columns),this.row=t}set(e,t,n){return this.matrix.set(this.row,t,n),this}get(e,t){return this.matrix.get(this.row,t)}},Re=class extends S{constructor(e,t){ze(e,t),super(e,t.length,e.columns),this.rowIndices=t}set(e,t,n){return this.matrix.set(this.rowIndices[e],t,n),this}get(e,t){return this.matrix.get(this.rowIndices[e],t)}},se=class extends S{constructor(e,t,n){ze(e,t),xe(e,n),super(e,t.length,n.length),this.rowIndices=t,this.columnIndices=n}set(e,t,n){return this.matrix.set(this.rowIndices[e],this.columnIndices[t],n),this}get(e,t){return this.matrix.get(this.rowIndices[e],this.columnIndices[t])}},Ie=class extends S{constructor(e,t,n,s,u){de(e,t,n,s,u),super(e,n-t+1,u-s+1),this.startRow=t,this.startColumn=s}set(e,t,n){return this.matrix.set(this.startRow+e,this.startColumn+t,n),this}get(e,t){return this.matrix.get(this.startRow+e,this.startColumn+t)}},Te=class extends S{constructor(e){super(e,e.columns,e.rows)}set(e,t,n){return this.matrix.set(t,e,n),this}get(e,t){return this.matrix.get(t,e)}},ae=class extends Q{constructor(e,t={}){let{rows:n=1}=t;if(e.length%n!==0)throw new Error("the data length is not divisible by the number of rows");super(),this.rows=n,this.columns=e.length/n,this.data=e}set(e,t,n){let s=this._calculateIndex(e,t);return this.data[s]=n,this}get(e,t){let n=this._calculateIndex(e,t);return this.data[n]}_calculateIndex(e,t){return e*this.columns+t}},X=class extends Q{constructor(e){super(),this.data=e,this.rows=e.length,this.columns=e[0].length}set(e,t,n){return this.data[e][t]=n,this}get(e,t){return this.data[e][t]}};function Pt(h,e){if(K(h))return h[0]&&K(h[0])?new X(h):new ae(h,e);throw new Error("the argument is not an array")}var ie=class{constructor(e){e=X.checkMatrix(e);let t=e.clone(),n=t.rows,s=t.columns,u=new Float64Array(n),c=1,i,r,o,l,f,a,w,g,p;for(i=0;i<n;i++)u[i]=i;for(g=new Float64Array(n),r=0;r<s;r++){for(i=0;i<n;i++)g[i]=t.get(i,r);for(i=0;i<n;i++){for(p=Math.min(i,r),f=0,o=0;o<p;o++)f+=t.get(i,o)*g[o];g[i]-=f,t.set(i,r,g[i])}for(l=r,i=r+1;i<n;i++)Math.abs(g[i])>Math.abs(g[l])&&(l=i);if(l!==r){for(o=0;o<s;o++)a=t.get(l,o),t.set(l,o,t.get(r,o)),t.set(r,o,a);w=u[l],u[l]=u[r],u[r]=w,c=-c}if(r<n&&t.get(r,r)!==0)for(i=r+1;i<n;i++)t.set(i,r,t.get(i,r)/t.get(r,r))}this.LU=t,this.pivotVector=u,this.pivotSign=c}isSingular(){let e=this.LU,t=e.columns;for(let n=0;n<t;n++)if(e.get(n,n)===0)return!0;return!1}solve(e){e=x.checkMatrix(e);let t=this.LU;if(t.rows!==e.rows)throw new Error("Invalid matrix dimensions");if(this.isSingular())throw new Error("LU matrix is singular");let s=e.columns,u=e.subMatrixRow(this.pivotVector,0,s-1),c=t.columns,i,r,o;for(o=0;o<c;o++)for(i=o+1;i<c;i++)for(r=0;r<s;r++)u.set(i,r,u.get(i,r)-u.get(o,r)*t.get(i,o));for(o=c-1;o>=0;o--){for(r=0;r<s;r++)u.set(o,r,u.get(o,r)/t.get(o,o));for(i=0;i<o;i++)for(r=0;r<s;r++)u.set(i,r,u.get(i,r)-u.get(o,r)*t.get(i,o))}return u}get determinant(){let e=this.LU;if(!e.isSquare())throw new Error("Matrix must be square");let t=this.pivotSign,n=e.columns;for(let s=0;s<n;s++)t*=e.get(s,s);return t}get lowerTriangularMatrix(){let e=this.LU,t=e.rows,n=e.columns,s=new x(t,n);for(let u=0;u<t;u++)for(let c=0;c<n;c++)u>c?s.set(u,c,e.get(u,c)):u===c?s.set(u,c,1):s.set(u,c,0);return s}get upperTriangularMatrix(){let e=this.LU,t=e.rows,n=e.columns,s=new x(t,n);for(let u=0;u<t;u++)for(let c=0;c<n;c++)u<=c?s.set(u,c,e.get(u,c)):s.set(u,c,0);return s}get pivotPermutationVector(){return Array.from(this.pivotVector)}};function Ne(h){let e=h.data,t=h.rows;for(let n=0;n<t;n++){let s=e[n];for(let u=n+1;u<t;u++){let c=s[u];s[u]=e[u][n],e[u][n]=c}}return h}function j(h,e){let t=0;return Math.abs(h)>Math.abs(e)?(t=e/h,Math.abs(h)*Math.sqrt(1+t*t)):e!==0?(t=h/e,Math.abs(e)*Math.sqrt(1+t*t)):0}var ue=class{constructor(e){e=X.checkMatrix(e);let t=e.clone(),n=e.rows,s=e.columns,u=new Float64Array(s),c,i,r,o;for(r=0;r<s;r++){let l=0;for(c=r;c<n;c++)l=j(l,t.get(c,r));if(l!==0){for(t.get(r,r)<0&&(l=-l),c=r;c<n;c++)t.set(c,r,t.get(c,r)/l);for(t.set(r,r,t.get(r,r)+1),i=r+1;i<s;i++){for(o=0,c=r;c<n;c++)o+=t.get(c,r)*t.get(c,i);for(o=-o/t.get(r,r),c=r;c<n;c++)t.set(c,i,t.get(c,i)+o*t.get(c,r))}}u[r]=-l}this.QR=t,this.Rdiag=u}solve(e){e=x.checkMatrix(e);let t=this.QR,n=t.rows;if(e.rows!==n)throw new Error("Matrix row dimensions must agree");if(!this.isFullRank())throw new Error("Matrix is rank deficient");let s=e.columns,u=e.clone(),c=t.columns,i,r,o,l;for(o=0;o<c;o++)for(r=0;r<s;r++){for(l=0,i=o;i<n;i++)l+=t.get(i,o)*u.get(i,r);for(l=-l/t.get(o,o),i=o;i<n;i++)u.set(i,r,u.get(i,r)+l*t.get(i,o))}for(o=c-1;o>=0;o--){for(r=0;r<s;r++)u.set(o,r,u.get(o,r)/this.Rdiag[o]);for(i=0;i<o;i++)for(r=0;r<s;r++)u.set(i,r,u.get(i,r)-u.get(o,r)*t.get(i,o))}return u.subMatrix(0,c-1,0,s-1)}isFullRank(){let e=this.QR.columns;for(let t=0;t<e;t++)if(this.Rdiag[t]===0)return!1;return!0}get upperTriangularMatrix(){let e=this.QR,t=e.columns,n=new x(t,t),s,u;for(s=0;s<t;s++)for(u=0;u<t;u++)s<u?n.set(s,u,e.get(s,u)):s===u?n.set(s,u,this.Rdiag[s]):n.set(s,u,0);return n}get orthogonalMatrix(){let e=this.QR,t=e.rows,n=e.columns,s=new x(t,n),u,c,i,r;for(i=n-1;i>=0;i--){for(u=0;u<t;u++)s.set(u,i,0);for(s.set(i,i,1),c=i;c<n;c++)if(e.get(i,i)!==0){for(r=0,u=i;u<t;u++)r+=e.get(u,i)*s.get(u,c);for(r=-r/e.get(i,i),u=i;u<t;u++)s.set(u,c,s.get(u,c)+r*e.get(u,i))}}return s}},ee=class{constructor(e,t={}){if(e=X.checkMatrix(e),e.isEmpty())throw new Error("Matrix must be non-empty");let n=e.rows,s=e.columns,{computeLeftSingularVectors:u=!0,computeRightSingularVectors:c=!0,autoTranspose:i=!1}=t,r=!!u,o=!!c,l=!1,f;if(n<s)if(!i)console.warn("Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose"),f=e.transpose();else{f=e.clone(),n=e.columns,s=e.rows,l=!0;let b=r;r=o,o=b}else f=e.transpose();let a=Math.min(n,s),w=Math.min(n+1,s),g=new Float64Array(w),p=new x(a,n),d=new x(s,s),m=new Float64Array(s),v=new Float64Array(n),y=new Float64Array(w);for(let b=0;b<w;b++)y[b]=b;let E=Math.min(n-1,s),q=Math.max(0,Math.min(s-2,n)),N=Math.max(E,q);for(let b=0;b<N;b++){if(b<E){g[b]=0;for(let k=b;k<n;k++)g[b]=j(g[b],f.get(b,k));if(g[b]!==0){f.get(b,b)<0&&(g[b]=-g[b]);for(let k=b;k<n;k++)f.set(b,k,f.get(b,k)/g[b]);f.set(b,b,f.get(b,b)+1)}g[b]=-g[b]}for(let k=b+1;k<s;k++){if(b<E&&g[b]!==0){let z=0;for(let I=b;I<n;I++)z+=f.get(b,I)*f.get(k,I);z=-z/f.get(b,b);for(let I=b;I<n;I++)f.set(k,I,f.get(k,I)+z*f.get(b,I))}m[k]=f.get(k,b)}if(r&&b<E)for(let k=b;k<n;k++)p.set(b,k,f.get(b,k));if(b<q){m[b]=0;for(let k=b+1;k<s;k++)m[b]=j(m[b],m[k]);if(m[b]!==0){m[b+1]<0&&(m[b]=0-m[b]);for(let k=b+1;k<s;k++)m[k]/=m[b];m[b+1]+=1}if(m[b]=-m[b],b+1<n&&m[b]!==0){for(let k=b+1;k<n;k++)v[k]=0;for(let k=b+1;k<n;k++)for(let z=b+1;z<s;z++)v[k]+=m[z]*f.get(z,k);for(let k=b+1;k<s;k++){let z=-m[k]/m[b+1];for(let I=b+1;I<n;I++)f.set(k,I,f.get(k,I)+z*v[I])}}if(o)for(let k=b+1;k<s;k++)d.set(b,k,m[k])}}let R=Math.min(s,n+1);if(E<s&&(g[E]=f.get(E,E)),n<R&&(g[R-1]=0),q+1<R&&(m[q]=f.get(R-1,q)),m[R-1]=0,r){for(let b=E;b<a;b++){for(let k=0;k<n;k++)p.set(b,k,0);p.set(b,b,1)}for(let b=E-1;b>=0;b--)if(g[b]!==0){for(let k=b+1;k<a;k++){let z=0;for(let I=b;I<n;I++)z+=p.get(b,I)*p.get(k,I);z=-z/p.get(b,b);for(let I=b;I<n;I++)p.set(k,I,p.get(k,I)+z*p.get(b,I))}for(let k=b;k<n;k++)p.set(b,k,-p.get(b,k));p.set(b,b,1+p.get(b,b));for(let k=0;k<b-1;k++)p.set(b,k,0)}else{for(let k=0;k<n;k++)p.set(b,k,0);p.set(b,b,1)}}if(o)for(let b=s-1;b>=0;b--){if(b<q&&m[b]!==0)for(let k=b+1;k<s;k++){let z=0;for(let I=b+1;I<s;I++)z+=d.get(b,I)*d.get(k,I);z=-z/d.get(b,b+1);for(let I=b+1;I<s;I++)d.set(k,I,d.get(k,I)+z*d.get(b,I))}for(let k=0;k<s;k++)d.set(b,k,0);d.set(b,b,1)}let T=R-1,_=Number.EPSILON;for(;R>0;){let b,k;for(b=R-2;b>=-1&&b!==-1;b--){let z=Number.MIN_VALUE+_*Math.abs(g[b]+Math.abs(g[b+1]));if(Math.abs(m[b])<=z||Number.isNaN(m[b])){m[b]=0;break}}if(b===R-2)k=4;else{let z;for(z=R-1;z>=b&&z!==b;z--){let I=(z!==R?Math.abs(m[z]):0)+(z!==b+1?Math.abs(m[z-1]):0);if(Math.abs(g[z])<=_*I){g[z]=0;break}}z===b?k=3:z===R-1?k=1:(k=2,b=z)}switch(b++,k){case 1:{let z=m[R-2];m[R-2]=0;for(let I=R-2;I>=b;I--){let O=j(g[I],z),P=g[I]/O,C=z/O;if(g[I]=O,I!==b&&(z=-C*m[I-1],m[I-1]=P*m[I-1]),o)for(let D=0;D<s;D++)O=P*d.get(I,D)+C*d.get(R-1,D),d.set(R-1,D,-C*d.get(I,D)+P*d.get(R-1,D)),d.set(I,D,O)}break}case 2:{let z=m[b-1];m[b-1]=0;for(let I=b;I<R;I++){let O=j(g[I],z),P=g[I]/O,C=z/O;if(g[I]=O,z=-C*m[I],m[I]=P*m[I],r)for(let D=0;D<n;D++)O=P*p.get(I,D)+C*p.get(b-1,D),p.set(b-1,D,-C*p.get(I,D)+P*p.get(b-1,D)),p.set(I,D,O)}break}case 3:{let z=Math.max(Math.abs(g[R-1]),Math.abs(g[R-2]),Math.abs(m[R-2]),Math.abs(g[b]),Math.abs(m[b])),I=g[R-1]/z,O=g[R-2]/z,P=m[R-2]/z,C=g[b]/z,D=m[b]/z,$=((O+I)*(O-I)+P*P)/2,G=I*P*(I*P),U=0;($!==0||G!==0)&&($<0?U=0-Math.sqrt($*$+G):U=Math.sqrt($*$+G),U=G/($+U));let B=(C+I)*(C-I)+U,Z=C*D;for(let V=b;V<R-1;V++){let W=j(B,Z);W===0&&(W=Number.MIN_VALUE);let J=B/W,A=Z/W;if(V!==b&&(m[V-1]=W),B=J*g[V]+A*m[V],m[V]=J*m[V]-A*g[V],Z=A*g[V+1],g[V+1]=J*g[V+1],o)for(let Y=0;Y<s;Y++)W=J*d.get(V,Y)+A*d.get(V+1,Y),d.set(V+1,Y,-A*d.get(V,Y)+J*d.get(V+1,Y)),d.set(V,Y,W);if(W=j(B,Z),W===0&&(W=Number.MIN_VALUE),J=B/W,A=Z/W,g[V]=W,B=J*m[V]+A*g[V+1],g[V+1]=-A*m[V]+J*g[V+1],Z=A*m[V+1],m[V+1]=J*m[V+1],r&&V<n-1)for(let Y=0;Y<n;Y++)W=J*p.get(V,Y)+A*p.get(V+1,Y),p.set(V+1,Y,-A*p.get(V,Y)+J*p.get(V+1,Y)),p.set(V,Y,W)}m[R-2]=B;break}case 4:{if(g[b]<=0&&(g[b]=g[b]<0?-g[b]:0,o))for(let z=0;z<=T;z++)d.set(b,z,-d.get(b,z));for(;b<T&&!(g[b]>=g[b+1]);){let z=g[b];if(g[b]=g[b+1],g[b+1]=z,o&&b<s-1)for(let I=0;I<s;I++)z=d.get(b+1,I),d.set(b+1,I,d.get(b,I)),d.set(b,I,z);if(r&&b<n-1)for(let I=0;I<n;I++)z=p.get(b+1,I),p.set(b+1,I,p.get(b,I)),p.set(b,I,z);b++}R--;break}}}if(p=p.isSquare()?Ne(p):p.transpose(),d=Ne(d),l){let b=d;d=p,p=b}this.m=n,this.n=s,this.s=g,this.U=p,this.V=d}solve(e){let t=e,n=this.threshold,s=this.s.length,u=x.zeros(s,s);for(let a=0;a<s;a++)Math.abs(this.s[a])<=n?u.set(a,a,0):u.set(a,a,1/this.s[a]);let c=this.U,i=this.rightSingularVectors,r=i.mmul(u),o=i.rows,l=c.rows,f=x.zeros(o,l);for(let a=0;a<o;a++)for(let w=0;w<l;w++){let g=0;for(let p=0;p<s;p++)g+=r.get(a,p)*c.get(w,p);f.set(a,w,g)}return f.mmul(t)}solveForDiagonal(e){return this.solve(x.diag(e))}inverse(){let e=this.V,t=this.threshold,n=e.rows,s=e.columns,u=new x(n,this.s.length);for(let l=0;l<n;l++)for(let f=0;f<s;f++)Math.abs(this.s[f])>t&&u.set(l,f,e.get(l,f)/this.s[f]);let c=this.U,i=c.rows,r=c.columns,o=new x(n,i);for(let l=0;l<n;l++)for(let f=0;f<i;f++){let a=0;for(let w=0;w<r;w++)a+=u.get(l,w)*c.get(f,w);o.set(l,f,a)}return o}get condition(){return this.s[0]/this.s[Math.min(this.m,this.n)-1]}get norm2(){return this.s[0]}get rank(){let e=Math.max(this.m,this.n)*this.s[0]*Number.EPSILON,t=0,n=this.s;for(let s=0,u=n.length;s<u;s++)n[s]>e&&t++;return t}get diagonal(){return Array.from(this.s)}get threshold(){return Number.EPSILON/2*Math.max(this.m,this.n)*this.s[0]}get leftSingularVectors(){return this.U}get rightSingularVectors(){return this.V}get diagonalMatrix(){return x.diag(this.s)}};function Vt(h,e=!1){return h=X.checkMatrix(h),e?new ee(h).inverse():Ue(h,x.eye(h.rows))}function Ue(h,e,t=!1){return h=X.checkMatrix(h),e=X.checkMatrix(e),t?new ee(h).solve(e):h.isSquare()?new ie(h).solve(e):new ue(h).solve(e)}function he(h){if(h=x.checkMatrix(h),h.isSquare()){if(h.columns===0)return 1;let e,t,n,s;if(h.columns===2)return e=h.get(0,0),t=h.get(0,1),n=h.get(1,0),s=h.get(1,1),e*s-t*n;if(h.columns===3){let u,c,i;return u=new se(h,[1,2],[1,2]),c=new se(h,[1,2],[0,2]),i=new se(h,[1,2],[0,1]),e=h.get(0,0),t=h.get(0,1),n=h.get(0,2),e*he(u)-t*he(c)+n*he(i)}else return new ie(h).determinant}else throw Error("determinant can only be calculated for a square matrix")}function Ft(h,e){let t=[];for(let n=0;n<h;n++)n!==e&&t.push(n);return t}function Lt(h,e,t,n=1e-9,s=1e-9){if(h>s)return new Array(e.rows+1).fill(0);{let u=e.addRow(t,[0]);for(let c=0;c<u.rows;c++)Math.abs(u.get(c,0))<n&&u.set(c,0,0);return u.to1DArray()}}function Dt(h,e={}){let{thresholdValue:t=1e-9,thresholdError:n=1e-9}=e;h=x.checkMatrix(h);let s=h.rows,u=new x(s,s);for(let c=0;c<s;c++){let i=x.columnVector(h.getRow(c)),r=h.subMatrixRow(Ft(s,c)).transpose(),l=new ee(r).solve(i),f=x.abs(i).max()||1,a=x.sub(i,r.mmul(l)).abs().max()/f;u.setRow(c,Lt(a,l,c,t,n))}return u}function Ct(h,e=Number.EPSILON){if(h=x.checkMatrix(h),h.isEmpty())return h.transpose();let t=new ee(h,{autoTranspose:!0}),n=t.leftSingularVectors,s=t.rightSingularVectors,u=t.diagonal,c=e*Math.max(h.rows,h.columns)*u[0];for(let i=0;i<u.length;i++)Math.abs(u[i])>c?u[i]=1/u[i]:u[i]=0;return s.mmul(x.diag(u).mmul(n.transpose()))}function Ot(h,e=h,t={}){h=new x(h);let n=!1;if(typeof e=="object"&&!x.isMatrix(e)&&!K(e)?(t=e,e=h,n=!0):e=new x(e),h.rows!==e.rows)throw new TypeError("Both matrices must have the same number of rows");let{center:s=!0}=t;s&&(h=h.center("column"),n||(e=e.center("column")));let u=h.transposeMultiply(e);for(let c=0;c<u.rows;c++)for(let i=0;i<u.columns;i++)u.set(c,i,u.get(c,i)*(1/(h.rows-1)));return u}function $t(h,e=h,t={}){h=new x(h);let n=!1;if(typeof e=="object"&&!x.isMatrix(e)&&!K(e)?(t=e,e=h,n=!0):e=new x(e),h.rows!==e.rows)throw new TypeError("Both matrices must have the same number of rows");let{center:s=!0,scale:u=!0}=t;s&&(h.center("column"),n||e.center("column")),u&&(h.scale("column"),n||e.scale("column"));let c=h.standardDeviation("column",{unbiased:!0}),i=n?c:e.standardDeviation("column",{unbiased:!0}),r=h.transposeMultiply(e);for(let o=0;o<r.rows;o++)for(let l=0;l<r.columns;l++)r.set(o,l,r.get(o,l)*(1/(c[o]*i[l]))*(1/(h.rows-1)));return r}var ge=class{constructor(e,t={}){let{assumeSymmetric:n=!1}=t;if(e=X.checkMatrix(e),!e.isSquare())throw new Error("Matrix is not a square matrix");if(e.isEmpty())throw new Error("Matrix must be non-empty");let s=e.columns,u=new x(s,s),c=new Float64Array(s),i=new Float64Array(s),r=e,o,l,f=!1;if(n?f=!0:f=e.isSymmetric(),f){for(o=0;o<s;o++)for(l=0;l<s;l++)u.set(l,o,r.get(o,l));Ut(s,i,c,u),Bt(s,i,c,u),Ne(u)}else{let a=new x(s,s),w=new Float64Array(s);for(l=0;l<s;l++)for(o=0;o<s;o++)a.set(o,l,r.get(o,l));Qt(s,a,w,u),Gt(s,i,c,u,a)}this.n=s,this.e=i,this.d=c,this.V=u}get realEigenvalues(){return Array.from(this.d)}get imaginaryEigenvalues(){return Array.from(this.e)}get eigenvectorMatrix(){return this.V}get diagonalMatrix(){let e=this.n,t=this.e,n=this.d,s=new x(e,e),u,c;for(u=0;u<e;u++){for(c=0;c<e;c++)s.set(u,c,0);s.set(u,u,n[u]),t[u]>0?s.set(u,u+1,t[u]):t[u]<0&&s.set(u,u-1,t[u])}return s}};function Ut(h,e,t,n){let s,u,c,i,r,o,l,f;for(r=0;r<h;r++)t[r]=n.get(r,h-1);for(i=h-1;i>0;i--){for(f=0,c=0,o=0;o<i;o++)f=f+Math.abs(t[o]);if(f===0)for(e[i]=t[i-1],r=0;r<i;r++)t[r]=n.get(r,i-1),n.set(r,i,0),n.set(i,r,0);else{for(o=0;o<i;o++)t[o]/=f,c+=t[o]*t[o];for(s=t[i-1],u=Math.sqrt(c),s>0&&(u=-u),e[i]=f*u,c=c-s*u,t[i-1]=s-u,r=0;r<i;r++)e[r]=0;for(r=0;r<i;r++){for(s=t[r],n.set(i,r,s),u=e[r]+n.get(r,r)*s,o=r+1;o<=i-1;o++)u+=n.get(r,o)*t[o],e[o]+=n.get(r,o)*s;e[r]=u}for(s=0,r=0;r<i;r++)e[r]/=c,s+=e[r]*t[r];for(l=s/(c+c),r=0;r<i;r++)e[r]-=l*t[r];for(r=0;r<i;r++){for(s=t[r],u=e[r],o=r;o<=i-1;o++)n.set(r,o,n.get(r,o)-(s*e[o]+u*t[o]));t[r]=n.get(r,i-1),n.set(r,i,0)}}t[i]=c}for(i=0;i<h-1;i++){if(n.set(i,h-1,n.get(i,i)),n.set(i,i,1),c=t[i+1],c!==0){for(o=0;o<=i;o++)t[o]=n.get(i+1,o)/c;for(r=0;r<=i;r++){for(u=0,o=0;o<=i;o++)u+=n.get(i+1,o)*n.get(r,o);for(o=0;o<=i;o++)n.set(r,o,n.get(r,o)-u*t[o])}}for(o=0;o<=i;o++)n.set(i+1,o,0)}for(r=0;r<h;r++)t[r]=n.get(r,h-1),n.set(r,h-1,0);n.set(h-1,h-1,1),e[0]=0}function Bt(h,e,t,n){let s,u,c,i,r,o,l,f,a,w,g,p,d,m,v,y;for(c=1;c<h;c++)e[c-1]=e[c];e[h-1]=0;let E=0,q=0,N=Number.EPSILON;for(o=0;o<h;o++){for(q=Math.max(q,Math.abs(t[o])+Math.abs(e[o])),l=o;l<h&&!(Math.abs(e[l])<=N*q);)l++;if(l>o)do{for(s=t[o],f=(t[o+1]-s)/(2*e[o]),a=j(f,1),f<0&&(a=-a),t[o]=e[o]/(f+a),t[o+1]=e[o]*(f+a),w=t[o+1],u=s-t[o],c=o+2;c<h;c++)t[c]-=u;for(E=E+u,f=t[l],g=1,p=g,d=g,m=e[o+1],v=0,y=0,c=l-1;c>=o;c--)for(d=p,p=g,y=v,s=g*e[c],u=g*f,a=j(f,e[c]),e[c+1]=v*a,v=e[c]/a,g=f/a,f=g*t[c]-v*s,t[c+1]=u+v*(g*s+v*t[c]),r=0;r<h;r++)u=n.get(c+1,r),n.set(c+1,r,v*n.get(c,r)+g*u),n.set(c,r,g*n.get(c,r)-v*u);f=-v*y*d*m*e[o]/w,e[o]=v*f,t[o]=g*f}while(Math.abs(e[o])>N*q);t[o]=t[o]+E,e[o]=0}for(c=0;c<h-1;c++){for(r=c,f=t[c],i=c+1;i<h;i++)t[i]<f&&(r=i,f=t[i]);if(r!==c)for(t[r]=t[c],t[c]=f,i=0;i<h;i++)f=n.get(c,i),n.set(c,i,n.get(r,i)),n.set(r,i,f)}}function Qt(h,e,t,n){let s=0,u=h-1,c,i,r,o,l,f,a;for(f=s+1;f<=u-1;f++){for(a=0,o=f;o<=u;o++)a=a+Math.abs(e.get(o,f-1));if(a!==0){for(r=0,o=u;o>=f;o--)t[o]=e.get(o,f-1)/a,r+=t[o]*t[o];for(i=Math.sqrt(r),t[f]>0&&(i=-i),r=r-t[f]*i,t[f]=t[f]-i,l=f;l<h;l++){for(c=0,o=u;o>=f;o--)c+=t[o]*e.get(o,l);for(c=c/r,o=f;o<=u;o++)e.set(o,l,e.get(o,l)-c*t[o])}for(o=0;o<=u;o++){for(c=0,l=u;l>=f;l--)c+=t[l]*e.get(o,l);for(c=c/r,l=f;l<=u;l++)e.set(o,l,e.get(o,l)-c*t[l])}t[f]=a*t[f],e.set(f,f-1,a*i)}}for(o=0;o<h;o++)for(l=0;l<h;l++)n.set(o,l,o===l?1:0);for(f=u-1;f>=s+1;f--)if(e.get(f,f-1)!==0){for(o=f+1;o<=u;o++)t[o]=e.get(o,f-1);for(l=f;l<=u;l++){for(i=0,o=f;o<=u;o++)i+=t[o]*n.get(o,l);for(i=i/t[f]/e.get(f,f-1),o=f;o<=u;o++)n.set(o,l,n.get(o,l)+i*t[o])}}}function Gt(h,e,t,n,s){let u=h-1,c=0,i=h-1,r=Number.EPSILON,o=0,l=0,f=0,a=0,w=0,g=0,p=0,d=0,m,v,y,E,q,N,R,T,_,b,k,z,I,O,P;for(m=0;m<h;m++)for((m<c||m>i)&&(t[m]=s.get(m,m),e[m]=0),v=Math.max(m-1,0);v<h;v++)l=l+Math.abs(s.get(m,v));for(;u>=c;){for(E=u;E>c&&(g=Math.abs(s.get(E-1,E-1))+Math.abs(s.get(E,E)),g===0&&(g=l),!(Math.abs(s.get(E,E-1))<r*g));)E--;if(E===u)s.set(u,u,s.get(u,u)+o),t[u]=s.get(u,u),e[u]=0,u--,d=0;else if(E===u-1){if(R=s.get(u,u-1)*s.get(u-1,u),f=(s.get(u-1,u-1)-s.get(u,u))/2,a=f*f+R,p=Math.sqrt(Math.abs(a)),s.set(u,u,s.get(u,u)+o),s.set(u-1,u-1,s.get(u-1,u-1)+o),T=s.get(u,u),a>=0){for(p=f>=0?f+p:f-p,t[u-1]=T+p,t[u]=t[u-1],p!==0&&(t[u]=T-R/p),e[u-1]=0,e[u]=0,T=s.get(u,u-1),g=Math.abs(T)+Math.abs(p),f=T/g,a=p/g,w=Math.sqrt(f*f+a*a),f=f/w,a=a/w,v=u-1;v<h;v++)p=s.get(u-1,v),s.set(u-1,v,a*p+f*s.get(u,v)),s.set(u,v,a*s.get(u,v)-f*p);for(m=0;m<=u;m++)p=s.get(m,u-1),s.set(m,u-1,a*p+f*s.get(m,u)),s.set(m,u,a*s.get(m,u)-f*p);for(m=c;m<=i;m++)p=n.get(m,u-1),n.set(m,u-1,a*p+f*n.get(m,u)),n.set(m,u,a*n.get(m,u)-f*p)}else t[u-1]=T+f,t[u]=T+f,e[u-1]=p,e[u]=-p;u=u-2,d=0}else{if(T=s.get(u,u),_=0,R=0,E<u&&(_=s.get(u-1,u-1),R=s.get(u,u-1)*s.get(u-1,u)),d===10){for(o+=T,m=c;m<=u;m++)s.set(m,m,s.get(m,m)-T);g=Math.abs(s.get(u,u-1))+Math.abs(s.get(u-1,u-2)),T=_=.75*g,R=-.4375*g*g}if(d===30&&(g=(_-T)/2,g=g*g+R,g>0)){for(g=Math.sqrt(g),_<T&&(g=-g),g=T-R/((_-T)/2+g),m=c;m<=u;m++)s.set(m,m,s.get(m,m)-g);o+=g,T=_=R=.964}for(d=d+1,q=u-2;q>=E&&(p=s.get(q,q),w=T-p,g=_-p,f=(w*g-R)/s.get(q+1,q)+s.get(q,q+1),a=s.get(q+1,q+1)-p-w-g,w=s.get(q+2,q+1),g=Math.abs(f)+Math.abs(a)+Math.abs(w),f=f/g,a=a/g,w=w/g,!(q===E||Math.abs(s.get(q,q-1))*(Math.abs(a)+Math.abs(w))<r*(Math.abs(f)*(Math.abs(s.get(q-1,q-1))+Math.abs(p)+Math.abs(s.get(q+1,q+1))))));)q--;for(m=q+2;m<=u;m++)s.set(m,m-2,0),m>q+2&&s.set(m,m-3,0);for(y=q;y<=u-1&&(O=y!==u-1,y!==q&&(f=s.get(y,y-1),a=s.get(y+1,y-1),w=O?s.get(y+2,y-1):0,T=Math.abs(f)+Math.abs(a)+Math.abs(w),T!==0&&(f=f/T,a=a/T,w=w/T)),T!==0);y++)if(g=Math.sqrt(f*f+a*a+w*w),f<0&&(g=-g),g!==0){for(y!==q?s.set(y,y-1,-g*T):E!==q&&s.set(y,y-1,-s.get(y,y-1)),f=f+g,T=f/g,_=a/g,p=w/g,a=a/f,w=w/f,v=y;v<h;v++)f=s.get(y,v)+a*s.get(y+1,v),O&&(f=f+w*s.get(y+2,v),s.set(y+2,v,s.get(y+2,v)-f*p)),s.set(y,v,s.get(y,v)-f*T),s.set(y+1,v,s.get(y+1,v)-f*_);for(m=0;m<=Math.min(u,y+3);m++)f=T*s.get(m,y)+_*s.get(m,y+1),O&&(f=f+p*s.get(m,y+2),s.set(m,y+2,s.get(m,y+2)-f*w)),s.set(m,y,s.get(m,y)-f),s.set(m,y+1,s.get(m,y+1)-f*a);for(m=c;m<=i;m++)f=T*n.get(m,y)+_*n.get(m,y+1),O&&(f=f+p*n.get(m,y+2),n.set(m,y+2,n.get(m,y+2)-f*w)),n.set(m,y,n.get(m,y)-f),n.set(m,y+1,n.get(m,y+1)-f*a)}}}if(l!==0){for(u=h-1;u>=0;u--)if(f=t[u],a=e[u],a===0)for(E=u,s.set(u,u,1),m=u-1;m>=0;m--){for(R=s.get(m,m)-f,w=0,v=E;v<=u;v++)w=w+s.get(m,v)*s.get(v,u);if(e[m]<0)p=R,g=w;else if(E=m,e[m]===0?s.set(m,u,R!==0?-w/R:-w/(r*l)):(T=s.get(m,m+1),_=s.get(m+1,m),a=(t[m]-f)*(t[m]-f)+e[m]*e[m],N=(T*g-p*w)/a,s.set(m,u,N),s.set(m+1,u,Math.abs(T)>Math.abs(p)?(-w-R*N)/T:(-g-_*N)/p)),N=Math.abs(s.get(m,u)),r*N*N>1)for(v=m;v<=u;v++)s.set(v,u,s.get(v,u)/N)}else if(a<0)for(E=u-1,Math.abs(s.get(u,u-1))>Math.abs(s.get(u-1,u))?(s.set(u-1,u-1,a/s.get(u,u-1)),s.set(u-1,u,-(s.get(u,u)-f)/s.get(u,u-1))):(P=ce(0,-s.get(u-1,u),s.get(u-1,u-1)-f,a),s.set(u-1,u-1,P[0]),s.set(u-1,u,P[1])),s.set(u,u-1,0),s.set(u,u,1),m=u-2;m>=0;m--){for(b=0,k=0,v=E;v<=u;v++)b=b+s.get(m,v)*s.get(v,u-1),k=k+s.get(m,v)*s.get(v,u);if(R=s.get(m,m)-f,e[m]<0)p=R,w=b,g=k;else if(E=m,e[m]===0?(P=ce(-b,-k,R,a),s.set(m,u-1,P[0]),s.set(m,u,P[1])):(T=s.get(m,m+1),_=s.get(m+1,m),z=(t[m]-f)*(t[m]-f)+e[m]*e[m]-a*a,I=(t[m]-f)*2*a,z===0&&I===0&&(z=r*l*(Math.abs(R)+Math.abs(a)+Math.abs(T)+Math.abs(_)+Math.abs(p))),P=ce(T*w-p*b+a*k,T*g-p*k-a*b,z,I),s.set(m,u-1,P[0]),s.set(m,u,P[1]),Math.abs(T)>Math.abs(p)+Math.abs(a)?(s.set(m+1,u-1,(-b-R*s.get(m,u-1)+a*s.get(m,u))/T),s.set(m+1,u,(-k-R*s.get(m,u)-a*s.get(m,u-1))/T)):(P=ce(-w-_*s.get(m,u-1),-g-_*s.get(m,u),p,a),s.set(m+1,u-1,P[0]),s.set(m+1,u,P[1]))),N=Math.max(Math.abs(s.get(m,u-1)),Math.abs(s.get(m,u))),r*N*N>1)for(v=m;v<=u;v++)s.set(v,u-1,s.get(v,u-1)/N),s.set(v,u,s.get(v,u)/N)}for(m=0;m<h;m++)if(m<c||m>i)for(v=m;v<h;v++)n.set(m,v,s.get(m,v));for(v=h-1;v>=c;v--)for(m=c;m<=i;m++){for(p=0,y=c;y<=Math.min(v,i);y++)p=p+n.get(m,y)*s.get(y,v);n.set(m,v,p)}}}function ce(h,e,t,n){let s,u;return Math.abs(t)>Math.abs(n)?(s=n/t,u=t+s*n,[(h+s*e)/u,(e-s*h)/u]):(s=t/n,u=n+s*t,[(s*h+e)/u,(s*e-h)/u])}var we=class{constructor(e){if(e=X.checkMatrix(e),!e.isSymmetric())throw new Error("Matrix is not symmetric");let t=e,n=t.rows,s=new x(n,n),u=!0,c,i,r;for(i=0;i<n;i++){let o=0;for(r=0;r<i;r++){let l=0;for(c=0;c<r;c++)l+=s.get(r,c)*s.get(i,c);l=(t.get(i,r)-l)/s.get(r,r),s.set(i,r,l),o=o+l*l}for(o=t.get(i,i)-o,u&&=o>0,s.set(i,i,Math.sqrt(Math.max(o,0))),r=i+1;r<n;r++)s.set(i,r,0)}this.L=s,this.positiveDefinite=u}isPositiveDefinite(){return this.positiveDefinite}solve(e){e=X.checkMatrix(e);let t=this.L,n=t.rows;if(e.rows!==n)throw new Error("Matrix dimensions do not match");if(this.isPositiveDefinite()===!1)throw new Error("Matrix is not positive definite");let s=e.columns,u=e.clone(),c,i,r;for(r=0;r<n;r++)for(i=0;i<s;i++){for(c=0;c<r;c++)u.set(r,i,u.get(r,i)-u.get(c,i)*t.get(r,c));u.set(r,i,u.get(r,i)/t.get(r,r))}for(r=n-1;r>=0;r--)for(i=0;i<s;i++){for(c=r+1;c<n;c++)u.set(r,i,u.get(r,i)-u.get(c,i)*t.get(c,r));u.set(r,i,u.get(r,i)/t.get(r,r))}return u}get lowerTriangularMatrix(){return this.L}},pe=class{constructor(e,t={}){e=X.checkMatrix(e);let{Y:n}=t,{scaleScores:s=!1,maxIterations:u=1e3,terminationCriteria:c=1e-10}=t,i;if(n){if(K(n)&&typeof n[0]=="number"?n=x.columnVector(n):n=X.checkMatrix(n),n.rows!==e.rows)throw new Error("Y should have the same number of rows as X");i=n.getColumnVector(0)}else i=e.getColumnVector(0);let r=1,o,l,f,a;for(let w=0;w<u&&r>c;w++)f=e.transpose().mmul(i).div(i.transpose().mmul(i).get(0,0)),f=f.div(f.norm()),o=e.mmul(f).div(f.transpose().mmul(f).get(0,0)),w>0&&(r=o.clone().sub(a).pow(2).sum()),a=o.clone(),n?(l=n.transpose().mmul(o).div(o.transpose().mmul(o).get(0,0)),l=l.div(l.norm()),i=n.mmul(l).div(l.transpose().mmul(l).get(0,0))):i=o;if(n){let w=e.transpose().mmul(o).div(o.transpose().mmul(o).get(0,0));w=w.div(w.norm());let g=e.clone().sub(o.clone().mmul(w.transpose())),p=i.transpose().mmul(o).div(o.transpose().mmul(o).get(0,0)),d=n.clone().sub(o.clone().mulS(p.get(0,0)).mmul(l.transpose()));this.t=o,this.p=w.transpose(),this.w=f.transpose(),this.q=l,this.u=i,this.s=o.transpose().mmul(o),this.xResidual=g,this.yResidual=d,this.betas=p}else this.w=f.transpose(),this.s=o.transpose().mmul(o).sqrt(),s?this.t=o.clone().div(this.s.get(0,0)):this.t=o,this.xResidual=e.sub(o.mmul(f.transpose()))}};L.AbstractMatrix=Q;L.CHO=we;L.CholeskyDecomposition=we;L.DistanceMatrix=me;L.EVD=ge;L.EigenvalueDecomposition=ge;L.LU=ie;L.LuDecomposition=ie;L.Matrix=x;L.MatrixColumnSelectionView=be;L.MatrixColumnView=ye;L.MatrixFlipColumnView=Ee;L.MatrixFlipRowView=qe;L.MatrixRowSelectionView=Re;L.MatrixRowView=ke;L.MatrixSelectionView=se;L.MatrixSubView=Ie;L.MatrixTransposeView=Te;L.NIPALS=pe;L.Nipals=pe;L.QR=ue;L.QrDecomposition=ue;L.SVD=ee;L.SingularValueDecomposition=ee;L.SymmetricMatrix=te;L.WrapperMatrix1D=ae;L.WrapperMatrix2D=X;L.correlation=$t;L.covariance=Ot;L.default=x;L.determinant=he;L.inverse=Vt;L.linearDependencies=Dt;L.pseudoInverse=Ct;L.solve=Ue;L.wrap=Pt});var Ge=Ve((_e,Qe)=>{(function(h,e){typeof _e=="object"?Qe.exports=e():typeof define=="function"&&define.amd?define(e):h.jStat=e()})(_e,function(){var h=(function(e,t){var n=Array.prototype.concat,s=Array.prototype.slice,u=Object.prototype.toString;function c(d,m){var v=d>m?d:m;return e.pow(10,17-~~(e.log(v>0?v:-v)*e.LOG10E))}var i=Array.isArray||function(m){return u.call(m)==="[object Array]"};function r(d){return u.call(d)==="[object Function]"}function o(d){return typeof d=="number"?d-d===0:!1}function l(d){return n.apply([],d)}function f(){return new f._init(arguments)}f.fn=f.prototype,f._init=function(m){if(i(m[0]))if(i(m[0][0])){r(m[1])&&(m[0]=f.map(m[0],m[1]));for(var v=0;v<m[0].length;v++)this[v]=m[0][v];this.length=m[0].length}else this[0]=r(m[1])?f.map(m[0],m[1]):m[0],this.length=1;else if(o(m[0]))this[0]=f.seq.apply(null,m),this.length=1;else{if(m[0]instanceof f)return f(m[0].toArray());this[0]=[],this.length=1}return this},f._init.prototype=f.prototype,f._init.constructor=f,f.utils={calcRdx:c,isArray:i,isFunction:r,isNumber:o,toVector:l},f._random_fn=e.random,f.setRandom=function(m){if(typeof m!="function")throw new TypeError("fn is not a function");f._random_fn=m},f.extend=function(m){var v,y;if(arguments.length===1){for(y in m)f[y]=m[y];return this}for(v=1;v<arguments.length;v++)for(y in arguments[v])m[y]=arguments[v][y];return m},f.rows=function(m){return m.length||1},f.cols=function(m){return m[0].length||1},f.dimensions=function(m){return{rows:f.rows(m),cols:f.cols(m)}},f.row=function(m,v){return i(v)?v.map(function(y){return f.row(m,y)}):m[v]},f.rowa=function(m,v){return f.row(m,v)},f.col=function(m,v){if(i(v)){var y=f.arange(m.length).map(function(){return new Array(v.length)});return v.forEach(function(N,R){f.arange(m.length).forEach(function(T){y[T][R]=m[T][N]})}),y}for(var E=new Array(m.length),q=0;q<m.length;q++)E[q]=[m[q][v]];return E},f.cola=function(m,v){return f.col(m,v).map(function(y){return y[0]})},f.diag=function(m){for(var v=f.rows(m),y=new Array(v),E=0;E<v;E++)y[E]=[m[E][E]];return y},f.antidiag=function(m){for(var v=f.rows(m)-1,y=new Array(v),E=0;v>=0;v--,E++)y[E]=[m[E][v]];return y},f.transpose=function(m){var v=[],y,E,q,N,R;for(i(m[0])||(m=[m]),E=m.length,q=m[0].length,R=0;R<q;R++){for(y=new Array(E),N=0;N<E;N++)y[N]=m[N][R];v.push(y)}return v.length===1?v[0]:v},f.map=function(m,v,y){var E,q,N,R,T;for(i(m[0])||(m=[m]),q=m.length,N=m[0].length,R=y?m:new Array(q),E=0;E<q;E++)for(R[E]||(R[E]=new Array(N)),T=0;T<N;T++)R[E][T]=v(m[E][T],E,T);return R.length===1?R[0]:R},f.cumreduce=function(m,v,y){var E,q,N,R,T;for(i(m[0])||(m=[m]),q=m.length,N=m[0].length,R=y?m:new Array(q),E=0;E<q;E++)for(R[E]||(R[E]=new Array(N)),N>0&&(R[E][0]=m[E][0]),T=1;T<N;T++)R[E][T]=v(R[E][T-1],m[E][T]);return R.length===1?R[0]:R},f.alter=function(m,v){return f.map(m,v,!0)},f.create=function(m,v,y){var E=new Array(m),q,N;for(r(v)&&(y=v,v=m),q=0;q<m;q++)for(E[q]=new Array(v),N=0;N<v;N++)E[q][N]=y(q,N);return E};function a(){return 0}f.zeros=function(m,v){return o(v)||(v=m),f.create(m,v,a)};function w(){return 1}f.ones=function(m,v){return o(v)||(v=m),f.create(m,v,w)},f.rand=function(m,v){return o(v)||(v=m),f.create(m,v,f._random_fn)};function g(d,m){return d===m?1:0}f.identity=function(m,v){return o(v)||(v=m),f.create(m,v,g)},f.symmetric=function(m){var v=m.length,y,E;if(m.length!==m[0].length)return!1;for(y=0;y<v;y++)for(E=0;E<v;E++)if(m[E][y]!==m[y][E])return!1;return!0},f.clear=function(m){return f.alter(m,a)},f.seq=function(m,v,y,E){r(E)||(E=!1);var q=[],N=c(m,v),R=(v*N-m*N)/((y-1)*N),T=m,_;for(_=0;T<=v&&_<y;_++,T=(m*N+R*N*_)/N)q.push(E?E(T,_):T);return q},f.arange=function(m,v,y){var E=[],q;if(y=y||1,v===t&&(v=m,m=0),m===v||y===0)return[];if(m<v&&y<0)return[];if(m>v&&y>0)return[];if(y>0)for(q=m;q<v;q+=y)E.push(q);else for(q=m;q>v;q+=y)E.push(q);return E},f.slice=(function(){function d(v,y,E,q){var N,R=[],T=v.length;if(y===t&&E===t&&q===t)return f.copy(v);if(y=y||0,E=E||v.length,y=y>=0?y:T+y,E=E>=0?E:T+E,q=q||1,y===E||q===0)return[];if(y<E&&q<0)return[];if(y>E&&q>0)return[];if(q>0)for(N=y;N<E;N+=q)R.push(v[N]);else for(N=y;N>E;N+=q)R.push(v[N]);return R}function m(v,y){var E,q;if(y=y||{},o(y.row)){if(o(y.col))return v[y.row][y.col];var N=f.rowa(v,y.row);return E=y.col||{},d(N,E.start,E.end,E.step)}if(o(y.col)){var R=f.cola(v,y.col);return q=y.row||{},d(R,q.start,q.end,q.step)}q=y.row||{},E=y.col||{};var T=d(v,q.start,q.end,q.step);return T.map(function(_){return d(_,E.start,E.end,E.step)})}return m})(),f.sliceAssign=function(m,v,y){var E,q;if(o(v.row)){if(o(v.col))return m[v.row][v.col]=y;v.col=v.col||{},v.col.start=v.col.start||0,v.col.end=v.col.end||m[0].length,v.col.step=v.col.step||1,E=f.arange(v.col.start,e.min(m.length,v.col.end),v.col.step);var N=v.row;return E.forEach(function(T,_){m[N][T]=y[_]}),m}if(o(v.col)){v.row=v.row||{},v.row.start=v.row.start||0,v.row.end=v.row.end||m.length,v.row.step=v.row.step||1,q=f.arange(v.row.start,e.min(m[0].length,v.row.end),v.row.step);var R=v.col;return q.forEach(function(T,_){m[T][R]=y[_]}),m}return y[0].length===t&&(y=[y]),v.row.start=v.row.start||0,v.row.end=v.row.end||m.length,v.row.step=v.row.step||1,v.col.start=v.col.start||0,v.col.end=v.col.end||m[0].length,v.col.step=v.col.step||1,q=f.arange(v.row.start,e.min(m.length,v.row.end),v.row.step),E=f.arange(v.col.start,e.min(m[0].length,v.col.end),v.col.step),q.forEach(function(T,_){E.forEach(function(b,k){m[T][b]=y[_][k]})}),m},f.diagonal=function(m){var v=f.zeros(m.length,m.length);return m.forEach(function(y,E){v[E][E]=y}),v},f.copy=function(m){return m.map(function(v){return o(v)?v:v.map(function(y){return y})})};var p=f.prototype;return p.length=0,p.push=Array.prototype.push,p.sort=Array.prototype.sort,p.splice=Array.prototype.splice,p.slice=Array.prototype.slice,p.toArray=function(){return this.length>1?s.call(this):s.call(this)[0]},p.map=function(m,v){return f(f.map(this,m,v))},p.cumreduce=function(m,v){return f(f.cumreduce(this,m,v))},p.alter=function(m){return f.alter(this,m),this},(function(d){for(var m=0;m<d.length;m++)(function(v){p[v]=function(y){var E=this,q;return y?(setTimeout(function(){y.call(E,p[v].call(E))}),this):(q=f[v](this),i(q)?f(q):q)}})(d[m])})("transpose clear symmetric rows cols dimensions diag antidiag".split(" ")),(function(d){for(var m=0;m<d.length;m++)(function(v){p[v]=function(y,E){var q=this;return E?(setTimeout(function(){E.call(q,p[v].call(q,y))}),this):f(f[v](this,y))}})(d[m])})("row col".split(" ")),(function(d){for(var m=0;m<d.length;m++)(function(v){p[v]=function(){return f(f[v].apply(null,arguments))}})(d[m])})("create zeros ones rand identity".split(" ")),f})(Math);return(function(e,t){var n=e.utils.isFunction;function s(i,r){return i-r}function u(i,r,o){return t.max(r,t.min(i,o))}e.sum=function(r){for(var o=0,l=r.length;--l>=0;)o+=r[l];return o},e.sumsqrd=function(r){for(var o=0,l=r.length;--l>=0;)o+=r[l]*r[l];return o},e.sumsqerr=function(r){for(var o=e.mean(r),l=0,f=r.length,a;--f>=0;)a=r[f]-o,l+=a*a;return l},e.sumrow=function(r){for(var o=0,l=r.length;--l>=0;)o+=r[l];return o},e.product=function(r){for(var o=1,l=r.length;--l>=0;)o*=r[l];return o},e.min=function(r){for(var o=r[0],l=0;++l<r.length;)r[l]<o&&(o=r[l]);return o},e.max=function(r){for(var o=r[0],l=0;++l<r.length;)r[l]>o&&(o=r[l]);return o},e.unique=function(r){for(var o={},l=[],f=0;f<r.length;f++)o[r[f]]||(o[r[f]]=!0,l.push(r[f]));return l},e.mean=function(r){return e.sum(r)/r.length},e.meansqerr=function(r){return e.sumsqerr(r)/r.length},e.geomean=function(r){var o=r.map(t.log),l=e.mean(o);return t.exp(l)},e.median=function(r){var o=r.length,l=r.slice().sort(s);return o&1?l[o/2|0]:(l[o/2-1]+l[o/2])/2},e.cumsum=function(r){return e.cumreduce(r,function(o,l){return o+l})},e.cumprod=function(r){return e.cumreduce(r,function(o,l){return o*l})},e.diff=function(r){var o=[],l=r.length,f;for(f=1;f<l;f++)o.push(r[f]-r[f-1]);return o},e.rank=function(i){var r,o=[],l={};for(r=0;r<i.length;r++){var f=i[r];l[f]?l[f]++:(l[f]=1,o.push(f))}var a=o.sort(s),w={},g=1;for(r=0;r<a.length;r++){var f=a[r],p=l[f],d=g,m=g+p-1,v=(d+m)/2;w[f]=v,g+=p}return i.map(function(y){return w[y]})},e.mode=function(r){var o=r.length,l=r.slice().sort(s),f=1,a=0,w=0,g=[],p;for(p=0;p<o;p++)l[p]===l[p+1]?f++:(f>a?(g=[l[p]],a=f,w=0):f===a&&(g.push(l[p]),w++),f=1);return w===0?g[0]:g},e.range=function(r){return e.max(r)-e.min(r)},e.variance=function(r,o){return e.sumsqerr(r)/(r.length-(o?1:0))},e.pooledvariance=function(r){var o=r.reduce(function(f,a){return f+e.sumsqerr(a)},0),l=r.reduce(function(f,a){return f+a.length},0);return o/(l-r.length)},e.deviation=function(i){for(var r=e.mean(i),o=i.length,l=new Array(o),f=0;f<o;f++)l[f]=i[f]-r;return l},e.stdev=function(r,o){return t.sqrt(e.variance(r,o))},e.pooledstdev=function(r){return t.sqrt(e.pooledvariance(r))},e.meandev=function(r){for(var o=e.mean(r),l=[],f=r.length-1;f>=0;f--)l.push(t.abs(r[f]-o));return e.mean(l)},e.meddev=function(r){for(var o=e.median(r),l=[],f=r.length-1;f>=0;f--)l.push(t.abs(r[f]-o));return e.median(l)},e.coeffvar=function(r){return e.stdev(r)/e.mean(r)},e.quartiles=function(r){var o=r.length,l=r.slice().sort(s);return[l[t.round(o/4)-1],l[t.round(o/2)-1],l[t.round(o*3/4)-1]]},e.quantiles=function(r,o,l,f){var a=r.slice().sort(s),w=[o.length],g=r.length,p,d,m,v,y,E;for(typeof l>"u"&&(l=3/8),typeof f>"u"&&(f=3/8),p=0;p<o.length;p++)d=o[p],m=l+d*(1-l-f),v=g*d+m,y=t.floor(u(v,1,g-1)),E=u(v-y,0,1),w[p]=(1-E)*a[y-1]+E*a[y];return w},e.percentile=function(r,o,l){var f=r.slice().sort(s),a=o*(f.length+(l?1:-1))+(l?0:1),w=parseInt(a),g=a-w;return w+1<f.length?f[w-1]+g*(f[w]-f[w-1]):f[w-1]},e.percentileOfScore=function(r,o,l){var f=0,a=r.length,w=!1,g,p;for(l==="strict"&&(w=!0),p=0;p<a;p++)g=r[p],(w&&g<o||!w&&g<=o)&&f++;return f/a},e.histogram=function(r,o){o=o||4;var l=e.min(r),f=(e.max(r)-l)/o,a=r.length,w=[],g;for(g=0;g<o;g++)w[g]=0;for(g=0;g<a;g++)w[t.min(t.floor((r[g]-l)/f),o-1)]+=1;return w},e.covariance=function(r,o){var l=e.mean(r),f=e.mean(o),a=r.length,w=new Array(a),g;for(g=0;g<a;g++)w[g]=(r[g]-l)*(o[g]-f);return e.sum(w)/(a-1)},e.corrcoeff=function(r,o){return e.covariance(r,o)/e.stdev(r,1)/e.stdev(o,1)},e.spearmancoeff=function(i,r){return i=e.rank(i),r=e.rank(r),e.corrcoeff(i,r)},e.stanMoment=function(r,o){for(var l=e.mean(r),f=e.stdev(r),a=r.length,w=0,g=0;g<a;g++)w+=t.pow((r[g]-l)/f,o);return w/r.length},e.skewness=function(r){return e.stanMoment(r,3)},e.kurtosis=function(r){return e.stanMoment(r,4)-3};var c=e.prototype;(function(i){for(var r=0;r<i.length;r++)(function(o){c[o]=function(l,f){var a=[],w=0,g=this;if(n(l)&&(f=l,l=!1),f)return setTimeout(function(){f.call(g,c[o].call(g,l))}),this;if(this.length>1){for(g=l===!0?this:this.transpose();w<g.length;w++)a[w]=e[o](g[w]);return a}return e[o](this[0],l)}})(i[r])})("cumsum cumprod".split(" ")),(function(i){for(var r=0;r<i.length;r++)(function(o){c[o]=function(l,f){var a=[],w=0,g=this;if(n(l)&&(f=l,l=!1),f)return setTimeout(function(){f.call(g,c[o].call(g,l))}),this;if(this.length>1){for(o!=="sumrow"&&(g=l===!0?this:this.transpose());w<g.length;w++)a[w]=e[o](g[w]);return l===!0?e[o](e.utils.toVector(a)):a}return e[o](this[0],l)}})(i[r])})("sum sumsqrd sumsqerr sumrow product min max unique mean meansqerr geomean median diff rank mode range variance deviation stdev meandev meddev coeffvar quartiles histogram skewness kurtosis".split(" ")),(function(i){for(var r=0;r<i.length;r++)(function(o){c[o]=function(){var l=[],f=0,a=this,w=Array.prototype.slice.call(arguments),g;if(n(w[w.length-1])){g=w[w.length-1];var p=w.slice(0,w.length-1);return setTimeout(function(){g.call(a,c[o].apply(a,p))}),this}else{g=void 0;var d=function(v){return e[o].apply(a,[v].concat(w))}}if(this.length>1){for(a=a.transpose();f<a.length;f++)l[f]=d(a[f]);return l}return d(this[0])}})(i[r])})("quantiles percentileOfScore".split(" "))})(h,Math),(function(e,t){e.gammaln=function(s){var u=0,c=[76.18009172947146,-86.50532032941678,24.01409824083091,-1.231739572450155,.001208650973866179,-5395239384953e-18],i=1.000000000190015,r,o,l;for(l=(o=r=s)+5.5,l-=(r+.5)*t.log(l);u<6;u++)i+=c[u]/++o;return t.log(2.5066282746310007*i/r)-l},e.loggam=function(s){var u,c,i,r,o,l,f,a=[.08333333333333333,-.002777777777777778,.0007936507936507937,-.0005952380952380952,.0008417508417508418,-.001917526917526918,.00641025641025641,-.02955065359477124,.1796443723688307,-1.3924322169059];if(u=s,f=0,s==1||s==2)return 0;for(s<=7&&(f=t.floor(7-s),u=s+f),c=1/(u*u),i=2*t.PI,o=a[9],l=8;l>=0;l--)o*=c,o+=a[l];if(r=o/u+.5*t.log(i)+(u-.5)*t.log(u)-u,s<=7)for(l=1;l<=f;l++)r-=t.log(u-1),u-=1;return r},e.gammafn=function(s){var u=[-1.716185138865495,24.76565080557592,-379.80425647094563,629.3311553128184,866.9662027904133,-31451.272968848367,-36144.413418691176,66456.14382024054],c=[-30.8402300119739,315.35062697960416,-1015.1563674902192,-3107.771671572311,22538.11842098015,4755.846277527881,-134659.9598649693,-115132.2596755535],i=!1,r=0,o=0,l=0,f=s,a,w,g,p;if(s>171.6243769536076)return 1/0;if(f<=0)if(p=f%1+36e-17,p)i=(f&1?-1:1)*t.PI/t.sin(t.PI*p),f=1-f;else return 1/0;for(g=f,f<1?w=f++:w=(f-=r=(f|0)-1)-1,a=0;a<8;++a)l=(l+u[a])*w,o=o*w+c[a];if(p=l/o+1,g<f)p/=g;else if(g>f)for(a=0;a<r;++a)p*=f,f++;return i&&(p=i/p),p},e.gammap=function(s,u){return e.lowRegGamma(s,u)*e.gammafn(s)},e.lowRegGamma=function(s,u){var c=e.gammaln(s),i=s,r=1/s,o=r,l=u+1-s,f=1/1e-30,a=1/l,w=a,g=1,p=-~(t.log(s>=1?s:1/s)*8.5+s*.4+17),d;if(u<0||s<=0)return NaN;if(u<s+1){for(;g<=p;g++)r+=o*=u/++i;return r*t.exp(-u+s*t.log(u)-c)}for(;g<=p;g++)d=-g*(g-s),l+=2,a=d*a+l,f=l+d/f,a=1/a,w*=a*f;return 1-w*t.exp(-u+s*t.log(u)-c)},e.factorialln=function(s){return s<0?NaN:e.gammaln(s+1)},e.factorial=function(s){return s<0?NaN:e.gammafn(s+1)},e.combination=function(s,u){return s>170||u>170?t.exp(e.combinationln(s,u)):e.factorial(s)/e.factorial(u)/e.factorial(s-u)},e.combinationln=function(s,u){return e.factorialln(s)-e.factorialln(u)-e.factorialln(s-u)},e.permutation=function(s,u){return e.factorial(s)/e.factorial(s-u)},e.betafn=function(s,u){if(!(s<=0||u<=0))return s+u>170?t.exp(e.betaln(s,u)):e.gammafn(s)*e.gammafn(u)/e.gammafn(s+u)},e.betaln=function(s,u){return e.gammaln(s)+e.gammaln(u)-e.gammaln(s+u)},e.betacf=function(s,u,c){var i=1e-30,r=1,o=u+c,l=u+1,f=u-1,a=1,w=1-o*s/l,g,p,d,m;for(t.abs(w)<i&&(w=i),w=1/w,m=w;r<=100&&(g=2*r,p=r*(c-r)*s/((f+g)*(u+g)),w=1+p*w,t.abs(w)<i&&(w=i),a=1+p/a,t.abs(a)<i&&(a=i),w=1/w,m*=w*a,p=-(u+r)*(o+r)*s/((u+g)*(l+g)),w=1+p*w,t.abs(w)<i&&(w=i),a=1+p/a,t.abs(a)<i&&(a=i),w=1/w,d=w*a,m*=d,!(t.abs(d-1)<3e-7));r++);return m},e.gammapinv=function(s,u){var c=0,i=u-1,r=1e-8,o=e.gammaln(u),l,f,a,w,g,p,d;if(s>=1)return t.max(100,u+100*t.sqrt(u));if(s<=0)return 0;for(u>1?(p=t.log(i),d=t.exp(i*(p-1)-o),g=s<.5?s:1-s,a=t.sqrt(-2*t.log(g)),l=(2.30753+a*.27061)/(1+a*(.99229+a*.04481))-a,s<.5&&(l=-l),l=t.max(.001,u*t.pow(1-1/(9*u)-l/(3*t.sqrt(u)),3))):(a=1-u*(.253+u*.12),s<a?l=t.pow(s/a,1/u):l=1-t.log(1-(s-a)/(1-a)));c<12;c++){if(l<=0)return 0;if(f=e.lowRegGamma(u,l)-s,u>1?a=d*t.exp(-(l-i)+i*(t.log(l)-p)):a=t.exp(-l+i*t.log(l)-o),w=f/a,l-=a=w/(1-.5*t.min(1,w*((u-1)/l-1))),l<=0&&(l=.5*(l+a)),t.abs(a)<r*l)break}return l},e.erf=function(s){var u=[-1.3026537197817094,.6419697923564902,.019476473204185836,-.00956151478680863,-.000946595344482036,.000366839497852761,42523324806907e-18,-20278578112534e-18,-1624290004647e-18,130365583558e-17,15626441722e-18,-85238095915e-18,6529054439e-18,5059343495e-18,-991364156e-18,-227365122e-18,96467911e-18,2394038e-18,-6886027e-18,894487e-18,313092e-18,-112708e-18,381e-18,7106e-18,-1523e-18,-94e-18,121e-18,-28e-18],c=u.length-1,i=!1,r=0,o=0,l,f,a,w;for(s<0&&(s=-s,i=!0),l=2/(2+s),f=4*l-2;c>0;c--)a=r,r=f*r-o+u[c],o=a;return w=l*t.exp(-s*s+.5*(u[0]+f*r)-o),i?w-1:1-w},e.erfc=function(s){return 1-e.erf(s)},e.erfcinv=function(s){var u=0,c,i,r,o;if(s>=2)return-100;if(s<=0)return 100;for(o=s<1?s:2-s,r=t.sqrt(-2*t.log(o/2)),c=-.70711*((2.30753+r*.27061)/(1+r*(.99229+r*.04481))-r);u<2;u++)i=e.erfc(c)-o,c+=i/(1.1283791670955126*t.exp(-c*c)-c*i);return s<1?c:-c},e.ibetainv=function(s,u,c){var i=1e-8,r=u-1,o=c-1,l=0,f,a,w,g,p,d,m,v,y,E,q;if(s<=0)return 0;if(s>=1)return 1;for(u>=1&&c>=1?(w=s<.5?s:1-s,g=t.sqrt(-2*t.log(w)),m=(2.30753+g*.27061)/(1+g*(.99229+g*.04481))-g,s<.5&&(m=-m),v=(m*m-3)/6,y=2/(1/(2*u-1)+1/(2*c-1)),E=m*t.sqrt(v+y)/y-(1/(2*c-1)-1/(2*u-1))*(v+5/6-2/(3*y)),m=u/(u+c*t.exp(2*E))):(f=t.log(u/(u+c)),a=t.log(c/(u+c)),g=t.exp(u*f)/u,p=t.exp(c*a)/c,E=g+p,s<g/E?m=t.pow(u*E*s,1/u):m=1-t.pow(c*E*(1-s),1/c)),q=-e.gammaln(u)-e.gammaln(c)+e.gammaln(u+c);l<10;l++){if(m===0||m===1)return m;if(d=e.ibeta(m,u,c)-s,g=t.exp(r*t.log(m)+o*t.log(1-m)+q),p=d/g,m-=g=p/(1-.5*t.min(1,p*(r/m-o/(1-m)))),m<=0&&(m=.5*(m+g)),m>=1&&(m=.5*(m+g+1)),t.abs(g)<i*m&&l>0)break}return m},e.ibeta=function(s,u,c){var i=s===0||s===1?0:t.exp(e.gammaln(u+c)-e.gammaln(u)-e.gammaln(c)+u*t.log(s)+c*t.log(1-s));return s<0||s>1?!1:s<(u+1)/(u+c+2)?i*e.betacf(s,u,c)/u:1-i*e.betacf(1-s,c,u)/c},e.randn=function(s,u){var c,i,r,o,l;if(u||(u=s),s)return e.create(s,u,function(){return e.randn()});do c=e._random_fn(),i=1.7156*(e._random_fn()-.5),r=c-.449871,o=t.abs(i)+.386595,l=r*r+o*(.196*o-.25472*r);while(l>.27597&&(l>.27846||i*i>-4*t.log(c)*c*c));return i/c},e.randg=function(s,u,c){var i=s,r,o,l,f,a,w;if(c||(c=u),s||(s=1),u)return w=e.zeros(u,c),w.alter(function(){return e.randg(s)}),w;s<1&&(s+=1),r=s-1/3,o=1/t.sqrt(9*r);do{do a=e.randn(),f=1+o*a;while(f<=0);f=f*f*f,l=e._random_fn()}while(l>1-.331*t.pow(a,4)&&t.log(l)>.5*a*a+r*(1-f+t.log(f)));if(s==i)return r*f;do l=e._random_fn();while(l===0);return t.pow(l,1/i)*r*f},(function(n){for(var s=0;s<n.length;s++)(function(u){e.fn[u]=function(){return e(e.map(this,function(c){return e[u](c)}))}})(n[s])})("gammaln gammafn factorial factorialln".split(" ")),(function(n){for(var s=0;s<n.length;s++)(function(u){e.fn[u]=function(){return e(e[u].apply(null,arguments))}})(n[s])})("randn".split(" "))})(h,Math),(function(e,t){(function(i){for(var r=0;r<i.length;r++)(function(o){e[o]=function l(f,a,w){return this instanceof l?(this._a=f,this._b=a,this._c=w,this):new l(f,a,w)},e.fn[o]=function(l,f,a){var w=e[o](l,f,a);return w.data=this,w},e[o].prototype.sample=function(l){var f=this._a,a=this._b,w=this._c;return l?e.alter(l,function(){return e[o].sample(f,a,w)}):e[o].sample(f,a,w)},(function(l){for(var f=0;f<l.length;f++)(function(a){e[o].prototype[a]=function(w){var g=this._a,p=this._b,d=this._c;return!w&&w!==0&&(w=this.data),typeof w!="number"?e.fn.map.call(w,function(m){return e[o][a](m,g,p,d)}):e[o][a](w,g,p,d)}})(l[f])})("pdf cdf inv".split(" ")),(function(l){for(var f=0;f<l.length;f++)(function(a){e[o].prototype[a]=function(){return e[o][a](this._a,this._b,this._c)}})(l[f])})("mean median mode variance".split(" "))})(i[r])})("beta centralF cauchy chisquare exponential gamma invgamma kumaraswamy laplace lognormal noncentralt normal pareto studentt weibull uniform binomial negbin hypgeom poisson triangular tukey arcsine".split(" ")),e.extend(e.beta,{pdf:function(r,o,l){return r>1||r<0?0:o==1&&l==1?1:o<512&&l<512?t.pow(r,o-1)*t.pow(1-r,l-1)/e.betafn(o,l):t.exp((o-1)*t.log(r)+(l-1)*t.log(1-r)-e.betaln(o,l))},cdf:function(r,o,l){return r>1||r<0?(r>1)*1:e.ibeta(r,o,l)},inv:function(r,o,l){return e.ibetainv(r,o,l)},mean:function(r,o){return r/(r+o)},median:function(r,o){return e.ibetainv(.5,r,o)},mode:function(r,o){return(r-1)/(r+o-2)},sample:function(r,o){var l=e.randg(r);return l/(l+e.randg(o))},variance:function(r,o){return r*o/(t.pow(r+o,2)*(r+o+1))}}),e.extend(e.centralF,{pdf:function(r,o,l){var f,a,w;return r<0?0:o<=2?r===0&&o<2?1/0:r===0&&o===2?1:1/e.betafn(o/2,l/2)*t.pow(o/l,o/2)*t.pow(r,o/2-1)*t.pow(1+o/l*r,-(o+l)/2):(f=o*r/(l+r*o),a=l/(l+r*o),w=o*a/2,w*e.binomial.pdf((o-2)/2,(o+l-2)/2,f))},cdf:function(r,o,l){return r<0?0:e.ibeta(o*r/(o*r+l),o/2,l/2)},inv:function(r,o,l){return l/(o*(1/e.ibetainv(r,o/2,l/2)-1))},mean:function(r,o){return o>2?o/(o-2):void 0},mode:function(r,o){return r>2?o*(r-2)/(r*(o+2)):void 0},sample:function(r,o){var l=e.randg(r/2)*2,f=e.randg(o/2)*2;return l/r/(f/o)},variance:function(r,o){if(!(o<=4))return 2*o*o*(r+o-2)/(r*(o-2)*(o-2)*(o-4))}}),e.extend(e.cauchy,{pdf:function(r,o,l){return l<0?0:l/(t.pow(r-o,2)+t.pow(l,2))/t.PI},cdf:function(r,o,l){return t.atan((r-o)/l)/t.PI+.5},inv:function(i,r,o){return r+o*t.tan(t.PI*(i-.5))},median:function(r){return r},mode:function(r){return r},sample:function(r,o){return e.randn()*t.sqrt(1/(2*e.randg(.5)))*o+r}}),e.extend(e.chisquare,{pdf:function(r,o){return r<0?0:r===0&&o===2?.5:t.exp((o/2-1)*t.log(r)-r/2-o/2*t.log(2)-e.gammaln(o/2))},cdf:function(r,o){return r<0?0:e.lowRegGamma(o/2,r/2)},inv:function(i,r){return 2*e.gammapinv(i,.5*r)},mean:function(i){return i},median:function(r){return r*t.pow(1-2/(9*r),3)},mode:function(r){return r-2>0?r-2:0},sample:function(r){return e.randg(r/2)*2},variance:function(r){return 2*r}}),e.extend(e.exponential,{pdf:function(r,o){return r<0?0:o*t.exp(-o*r)},cdf:function(r,o){return r<0?0:1-t.exp(-o*r)},inv:function(i,r){return-t.log(1-i)/r},mean:function(i){return 1/i},median:function(i){return 1/i*t.log(2)},mode:function(){return 0},sample:function(r){return-1/r*t.log(e._random_fn())},variance:function(i){return t.pow(i,-2)}}),e.extend(e.gamma,{pdf:function(r,o,l){return r<0?0:r===0&&o===1?1/l:t.exp((o-1)*t.log(r)-r/l-e.gammaln(o)-o*t.log(l))},cdf:function(r,o,l){return r<0?0:e.lowRegGamma(o,r/l)},inv:function(i,r,o){return e.gammapinv(i,r)*o},mean:function(i,r){return i*r},mode:function(r,o){if(r>1)return(r-1)*o},sample:function(r,o){return e.randg(r)*o},variance:function(r,o){return r*o*o}}),e.extend(e.invgamma,{pdf:function(r,o,l){return r<=0?0:t.exp(-(o+1)*t.log(r)-l/r-e.gammaln(o)+o*t.log(l))},cdf:function(r,o,l){return r<=0?0:1-e.lowRegGamma(o,l/r)},inv:function(i,r,o){return o/e.gammapinv(1-i,r)},mean:function(i,r){return i>1?r/(i-1):void 0},mode:function(r,o){return o/(r+1)},sample:function(r,o){return o/e.randg(r)},variance:function(r,o){if(!(r<=2))return o*o/((r-1)*(r-1)*(r-2))}}),e.extend(e.kumaraswamy,{pdf:function(r,o,l){return r===0&&o===1?l:r===1&&l===1?o:t.exp(t.log(o)+t.log(l)+(o-1)*t.log(r)+(l-1)*t.log(1-t.pow(r,o)))},cdf:function(r,o,l){return r<0?0:r>1?1:1-t.pow(1-t.pow(r,o),l)},inv:function(r,o,l){return t.pow(1-t.pow(1-r,1/l),1/o)},mean:function(i,r){return r*e.gammafn(1+1/i)*e.gammafn(r)/e.gammafn(1+1/i+r)},median:function(r,o){return t.pow(1-t.pow(2,-1/o),1/r)},mode:function(r,o){if(r>=1&&o>=1&&r!==1&&o!==1)return t.pow((r-1)/(r*o-1),1/r)},variance:function(){throw new Error("variance not yet implemented")}}),e.extend(e.lognormal,{pdf:function(r,o,l){return r<=0?0:t.exp(-t.log(r)-.5*t.log(2*t.PI)-t.log(l)-t.pow(t.log(r)-o,2)/(2*l*l))},cdf:function(r,o,l){return r<0?0:.5+.5*e.erf((t.log(r)-o)/t.sqrt(2*l*l))},inv:function(i,r,o){return t.exp(-1.4142135623730951*o*e.erfcinv(2*i)+r)},mean:function(r,o){return t.exp(r+o*o/2)},median:function(r){return t.exp(r)},mode:function(r,o){return t.exp(r-o*o)},sample:function(r,o){return t.exp(e.randn()*o+r)},variance:function(r,o){return(t.exp(o*o)-1)*t.exp(2*r+o*o)}}),e.extend(e.noncentralt,{pdf:function(r,o,l){var f=1e-14;return t.abs(l)<f?e.studentt.pdf(r,o):t.abs(r)<f?t.exp(e.gammaln((o+1)/2)-l*l/2-.5*t.log(t.PI*o)-e.gammaln(o/2)):o/r*(e.noncentralt.cdf(r*t.sqrt(1+2/o),o+2,l)-e.noncentralt.cdf(r,o,l))},cdf:function(r,o,l){var f=1e-14,a=200;if(t.abs(l)<f)return e.studentt.cdf(r,o);var w=!1;r<0&&(w=!0,l=-l);for(var g=e.normal.cdf(-l,0,1),p=f+1,d=p,m=r*r/(r*r+o),v=0,y=t.exp(-l*l/2),E=t.exp(-l*l/2-.5*t.log(2)-e.gammaln(3/2))*l;v<a||d>f||p>f;)d=p,v>0&&(y*=l*l/(2*v),E*=l*l/(2*(v+1/2))),p=y*e.beta.cdf(m,v+.5,o/2)+E*e.beta.cdf(m,v+1,o/2),g+=.5*p,v++;return w?1-g:g}}),e.extend(e.normal,{pdf:function(r,o,l){return t.exp(-.5*t.log(2*t.PI)-t.log(l)-t.pow(r-o,2)/(2*l*l))},cdf:function(r,o,l){return .5*(1+e.erf((r-o)/t.sqrt(2*l*l)))},inv:function(i,r,o){return-1.4142135623730951*o*e.erfcinv(2*i)+r},mean:function(i){return i},median:function(r){return r},mode:function(i){return i},sample:function(r,o){return e.randn()*o+r},variance:function(i,r){return r*r}}),e.extend(e.pareto,{pdf:function(r,o,l){return r<o?0:l*t.pow(o,l)/t.pow(r,l+1)},cdf:function(r,o,l){return r<o?0:1-t.pow(o/r,l)},inv:function(r,o,l){return o/t.pow(1-r,1/l)},mean:function(r,o){if(!(o<=1))return o*t.pow(r,o)/(o-1)},median:function(r,o){return r*(o*t.SQRT2)},mode:function(r){return r},variance:function(i,r){if(!(r<=2))return i*i*r/(t.pow(r-1,2)*(r-2))}}),e.extend(e.studentt,{pdf:function(r,o){return o=o>1e100?1e100:o,1/(t.sqrt(o)*e.betafn(.5,o/2))*t.pow(1+r*r/o,-((o+1)/2))},cdf:function(r,o){var l=o/2;return e.ibeta((r+t.sqrt(r*r+o))/(2*t.sqrt(r*r+o)),l,l)},inv:function(i,r){var o=e.ibetainv(2*t.min(i,1-i),.5*r,.5);return o=t.sqrt(r*(1-o)/o),i>.5?o:-o},mean:function(r){return r>1?0:void 0},median:function(){return 0},mode:function(){return 0},sample:function(r){return e.randn()*t.sqrt(r/(2*e.randg(r/2)))},variance:function(r){return r>2?r/(r-2):r>1?1/0:void 0}}),e.extend(e.weibull,{pdf:function(r,o,l){return r<0||o<0||l<0?0:l/o*t.pow(r/o,l-1)*t.exp(-t.pow(r/o,l))},cdf:function(r,o,l){return r<0?0:1-t.exp(-t.pow(r/o,l))},inv:function(i,r,o){return r*t.pow(-t.log(1-i),1/o)},mean:function(i,r){return i*e.gammafn(1+1/r)},median:function(r,o){return r*t.pow(t.log(2),1/o)},mode:function(r,o){return o<=1?0:r*t.pow((o-1)/o,1/o)},sample:function(r,o){return r*t.pow(-t.log(e._random_fn()),1/o)},variance:function(r,o){return r*r*e.gammafn(1+2/o)-t.pow(e.weibull.mean(r,o),2)}}),e.extend(e.uniform,{pdf:function(r,o,l){return r<o||r>l?0:1/(l-o)},cdf:function(r,o,l){return r<o?0:r<l?(r-o)/(l-o):1},inv:function(i,r,o){return r+i*(o-r)},mean:function(r,o){return .5*(r+o)},median:function(r,o){return e.mean(r,o)},mode:function(){throw new Error("mode is not yet implemented")},sample:function(r,o){return r/2+o/2+(o/2-r/2)*(2*e._random_fn()-1)},variance:function(r,o){return t.pow(o-r,2)/12}});function n(i,r,o,l){for(var f=0,a=1,w=1,g=1,p=0,d=0,m;t.abs((w-d)/w)>l;)d=w,m=-(r+p)*(r+o+p)*i/(r+2*p)/(r+2*p+1),f=w+m*f,a=g+m*a,p=p+1,m=p*(o-p)*i/(r+2*p-1)/(r+2*p),w=f+m*w,g=a+m*g,f=f/g,a=a/g,w=w/g,g=1;return w/r}e.extend(e.binomial,{pdf:function(r,o,l){return l===0||l===1?o*l===r?1:0:e.combination(o,r)*t.pow(l,r)*t.pow(1-l,o-r)},cdf:function(r,o,l){var f,a=1e-10;if(r<0)return 0;if(r>=o)return 1;if(l<0||l>1||o<=0)return NaN;r=t.floor(r);var w=l,g=r+1,p=o-r,d=g+p,m=t.exp(e.gammaln(d)-e.gammaln(p)-e.gammaln(g)+g*t.log(w)+p*t.log(1-w));return w<(g+1)/(d+2)?f=m*n(w,g,p,a):f=1-m*n(1-w,p,g,a),t.round((1-f)*(1/a))/(1/a)}}),e.extend(e.negbin,{pdf:function(r,o,l){return r!==r>>>0?!1:r<0?0:e.combination(r+o-1,o-1)*t.pow(1-l,r)*t.pow(l,o)},cdf:function(r,o,l){var f=0,a=0;if(r<0)return 0;for(;a<=r;a++)f+=e.negbin.pdf(a,o,l);return f}}),e.extend(e.hypgeom,{pdf:function(r,o,l,f){if(r!==r|0)return!1;if(r<0||r<l-(o-f))return 0;if(r>f||r>l)return 0;if(l*2>o)return f*2>o?e.hypgeom.pdf(o-l-f+r,o,o-l,o-f):e.hypgeom.pdf(f-r,o,o-l,f);if(f*2>o)return e.hypgeom.pdf(l-r,o,l,o-f);if(l<f)return e.hypgeom.pdf(r,o,f,l);for(var a=1,w=0,g=0;g<r;g++){for(;a>1&&w<f;)a*=1-l/(o-w),w++;a*=(f-g)*(l-g)/((g+1)*(o-l-f+g+1))}for(;w<f;w++)a*=1-l/(o-w);return t.min(1,t.max(0,a))},cdf:function(r,o,l,f){if(r<0||r<l-(o-f))return 0;if(r>=f||r>=l)return 1;if(l*2>o)return f*2>o?e.hypgeom.cdf(o-l-f+r,o,o-l,o-f):1-e.hypgeom.cdf(f-r-1,o,o-l,f);if(f*2>o)return 1-e.hypgeom.cdf(l-r-1,o,l,o-f);if(l<f)return e.hypgeom.cdf(r,o,f,l);for(var a=1,w=1,g=0,p=0;p<r;p++){for(;a>1&&g<f;){var d=1-l/(o-g);w*=d,a*=d,g++}w*=(f-p)*(l-p)/((p+1)*(o-l-f+p+1)),a+=w}for(;g<f;g++)a*=1-l/(o-g);return t.min(1,t.max(0,a))}}),e.extend(e.poisson,{pdf:function(r,o){return o<0||r%1!==0||r<0?0:t.pow(o,r)*t.exp(-o)/e.factorial(r)},cdf:function(r,o){var l=[],f=0;if(r<0)return 0;for(;f<=r;f++)l.push(e.poisson.pdf(f,o));return e.sum(l)},mean:function(i){return i},variance:function(i){return i},sampleSmall:function(r){var o=1,l=0,f=t.exp(-r);do l++,o*=e._random_fn();while(o>f);return l-1},sampleLarge:function(r){var o=r,l,f,a,w,g,p,d,m,v,y;for(w=t.sqrt(o),g=t.log(o),d=.931+2.53*w,p=-.059+.02483*d,m=1.1239+1.1328/(d-3.4),v=.9277-3.6224/(d-2);;){if(f=t.random()-.5,a=t.random(),y=.5-t.abs(f),l=t.floor((2*p/y+d)*f+o+.43),y>=.07&&a<=v)return l;if(!(l<0||y<.013&&a>y)&&t.log(a)+t.log(m)-t.log(p/(y*y)+d)<=-o+l*g-e.loggam(l+1))return l}},sample:function(r){return r<10?this.sampleSmall(r):this.sampleLarge(r)}}),e.extend(e.triangular,{pdf:function(r,o,l,f){return l<=o||f<o||f>l?NaN:r<o||r>l?0:r<f?2*(r-o)/((l-o)*(f-o)):r===f?2/(l-o):2*(l-r)/((l-o)*(l-f))},cdf:function(r,o,l,f){return l<=o||f<o||f>l?NaN:r<=o?0:r>=l?1:r<=f?t.pow(r-o,2)/((l-o)*(f-o)):1-t.pow(l-r,2)/((l-o)*(l-f))},inv:function(r,o,l,f){return l<=o||f<o||f>l?NaN:r<=(f-o)/(l-o)?o+(l-o)*t.sqrt(r*((f-o)/(l-o))):o+(l-o)*(1-t.sqrt((1-r)*(1-(f-o)/(l-o))))},mean:function(r,o,l){return(r+o+l)/3},median:function(r,o,l){if(l<=(r+o)/2)return o-t.sqrt((o-r)*(o-l))/t.sqrt(2);if(l>(r+o)/2)return r+t.sqrt((o-r)*(l-r))/t.sqrt(2)},mode:function(r,o,l){return l},sample:function(r,o,l){var f=e._random_fn();return f<(l-r)/(o-r)?r+t.sqrt(f*(o-r)*(l-r)):o-t.sqrt((1-f)*(o-r)*(o-l))},variance:function(r,o,l){return(r*r+o*o+l*l-r*o-r*l-o*l)/18}}),e.extend(e.arcsine,{pdf:function(r,o,l){return l<=o?NaN:r<=o||r>=l?0:2/t.PI*t.pow(t.pow(l-o,2)-t.pow(2*r-o-l,2),-.5)},cdf:function(r,o,l){return r<o?0:r<l?2/t.PI*t.asin(t.sqrt((r-o)/(l-o))):1},inv:function(i,r,o){return r+(.5-.5*t.cos(t.PI*i))*(o-r)},mean:function(r,o){return o<=r?NaN:(r+o)/2},median:function(r,o){return o<=r?NaN:(r+o)/2},mode:function(){throw new Error("mode is not yet implemented")},sample:function(r,o){return(r+o)/2+(o-r)/2*t.sin(2*t.PI*e.uniform.sample(0,1))},variance:function(r,o){return o<=r?NaN:t.pow(o-r,2)/8}});function s(i){return i/t.abs(i)}e.extend(e.laplace,{pdf:function(r,o,l){return l<=0?0:t.exp(-t.abs(r-o)/l)/(2*l)},cdf:function(r,o,l){return l<=0?0:r<o?.5*t.exp((r-o)/l):1-.5*t.exp(-(r-o)/l)},mean:function(i){return i},median:function(i){return i},mode:function(i){return i},variance:function(i,r){return 2*r*r},sample:function(r,o){var l=e._random_fn()-.5;return r-o*s(l)*t.log(1-2*t.abs(l))}});function u(i,r,o){var l=12,f=6,a=-30,w=-50,g=60,p=8,d=3,m=2,v=3,y=[.9815606342467192,.9041172563704749,.7699026741943047,.5873179542866175,.3678314989981802,.1252334085114689],E=[.04717533638651183,.10693932599531843,.16007832854334622,.20316742672306592,.2334925365383548,.24914704581340277],q=i*.5;if(q>=p)return 1;var N=2*e.normal.cdf(q,0,1,1,0)-1;N>=t.exp(w/o)?N=t.pow(N,o):N=0;var R;i>d?R=m:R=v;for(var T=q,_=(p-q)/R,b=T+_,k=0,z=o-1,I=1;I<=R;I++){for(var O=0,P=.5*(b+T),C=.5*(b-T),D=1;D<=l;D++){var $,G;f<D?($=l-D+1,G=y[$-1]):($=D,G=-y[$-1]);var U=C*G,B=P+U,Z=B*B;if(Z>g)break;var V=2*e.normal.cdf(B,0,1,1,0),W=2*e.normal.cdf(B,i,1,1,0),J=V*.5-W*.5;J>=t.exp(a/z)&&(J=E[$-1]*t.exp(-(.5*Z))*t.pow(J,z),O+=J)}O*=2*C*o/t.sqrt(2*t.PI),k+=O,T=b,b+=_}return N+=k,N<=t.exp(a/r)?0:(N=t.pow(N,r),N>=1?1:N)}function c(i,r,o){var l=.322232421088,f=.099348462606,a=-1,w=.588581570495,g=-.342242088547,p=.531103462366,d=-.204231210125,m=.10353775285,v=-453642210148e-16,y=.0038560700634,E=.8832,q=.2368,N=1.214,R=1.208,T=1.4142,_=120,b=.5-.5*i,k=t.sqrt(t.log(1/(b*b))),z=k+((((k*v+d)*k+g)*k+a)*k+l)/((((k*y+m)*k+p)*k+w)*k+f);o<_&&(z+=(z*z*z+z)/o/4);var I=E-q*z;return o<_&&(I+=-N/o+R*z/o),z*(I*t.log(r-1)+T)}e.extend(e.tukey,{cdf:function(r,o,l){var f=1,a=o,w=16,g=8,p=-30,d=1e-14,m=100,v=800,y=5e3,E=25e3,q=1,N=.5,R=.25,T=.125,_=[.9894009349916499,.9445750230732326,.8656312023878318,.755404408355003,.6178762444026438,.45801677765722737,.2816035507792589,.09501250983763744],b=[.027152459411754096,.062253523938647894,.09515851168249279,.12462897125553388,.14959598881657674,.16915651939500254,.18260341504492358,.1894506104550685];if(r<=0)return 0;if(l<2||f<1||a<2)return NaN;if(!Number.isFinite(r))return 1;if(l>E)return u(r,f,a);var k=l*.5,z=k*t.log(l)-l*t.log(2)-e.gammaln(k),I=k-1,O=l*.25,P;l<=m?P=q:l<=v?P=N:l<=y?P=R:P=T,z+=t.log(P);for(var C=0,D=1;D<=50;D++){for(var $=0,G=(2*D-1)*P,U=1;U<=w;U++){var B,Z;g<U?(B=U-g-1,Z=z+I*t.log(G+_[B]*P)-(_[B]*P+G)*O):(B=U-1,Z=z+I*t.log(G-_[B]*P)+(_[B]*P-G)*O);var V;if(Z>=p){g<U?V=r*t.sqrt((_[B]*P+G)*.5):V=r*t.sqrt((-(_[B]*P)+G)*.5);var W=u(V,f,a),J=W*b[B]*t.exp(Z);$+=J}}if(D*P>=1&&$<=d)break;C+=$}if($>d)throw new Error("tukey.cdf failed to converge");return C>1&&(C=1),C},inv:function(i,r,o){var l=1,f=r,a=1e-4,w=50;if(o<2||l<1||f<2)return NaN;if(i<0||i>1)return NaN;if(i===0)return 0;if(i===1)return 1/0;var g=c(i,f,o),p=e.tukey.cdf(g,r,o)-i,d;p>0?d=t.max(0,g-1):d=g+1;for(var m=e.tukey.cdf(d,r,o)-i,v,y=1;y<w;y++){v=d-m*(d-g)/(m-p),p=m,g=d,v<0&&(v=0,m=-i),m=e.tukey.cdf(v,r,o)-i,d=v;var E=t.abs(d-g);if(E<a)return v}throw new Error("tukey.inv failed to converge")}})})(h,Math),(function(e,t){var n=Array.prototype.push,s=e.utils.isArray;function u(c){return s(c)||c instanceof e}e.extend({add:function(i,r){return u(r)?(u(r[0])||(r=[r]),e.map(i,function(o,l,f){return o+r[l][f]})):e.map(i,function(o){return o+r})},subtract:function(i,r){return u(r)?(u(r[0])||(r=[r]),e.map(i,function(o,l,f){return o-r[l][f]||0})):e.map(i,function(o){return o-r})},divide:function(i,r){return u(r)?(u(r[0])||(r=[r]),e.multiply(i,e.inv(r))):e.map(i,function(o){return o/r})},multiply:function(i,r){var o,l,f,a,w,g,p,d;if(i.length===void 0&&r.length===void 0)return i*r;if(w=i.length,g=i[0].length,p=e.zeros(w,f=u(r)?r[0].length:g),d=0,u(r)){for(;d<f;d++)for(o=0;o<w;o++){for(a=0,l=0;l<g;l++)a+=i[o][l]*r[l][d];p[o][d]=a}return w===1&&d===1?p[0][0]:p}return e.map(i,function(m){return m*r})},outer:function(i,r){return e.multiply(i.map(function(o){return[o]}),[r])},dot:function(i,r){u(i[0])||(i=[i]),u(r[0])||(r=[r]);for(var o=i[0].length===1&&i.length!==1?e.transpose(i):i,l=r[0].length===1&&r.length!==1?e.transpose(r):r,f=[],a=0,w=o.length,g=o[0].length,p,d;a<w;a++){for(f[a]=[],p=0,d=0;d<g;d++)p+=o[a][d]*l[a][d];f[a]=p}return f.length===1?f[0]:f},pow:function(i,r){return e.map(i,function(o){return t.pow(o,r)})},exp:function(i){return e.map(i,function(r){return t.exp(r)})},log:function(i){return e.map(i,function(r){return t.log(r)})},abs:function(i){return e.map(i,function(r){return t.abs(r)})},norm:function(i,r){var o=0,l=0;for(isNaN(r)&&(r=2),u(i[0])&&(i=i[0]);l<i.length;l++)o+=t.pow(t.abs(i[l]),r);return t.pow(o,1/r)},angle:function(i,r){return t.acos(e.dot(i,r)/(e.norm(i)*e.norm(r)))},aug:function(i,r){var o=[],l;for(l=0;l<i.length;l++)o.push(i[l].slice());for(l=0;l<o.length;l++)n.apply(o[l],r[l]);return o},inv:function(i){for(var r=i.length,o=i[0].length,l=e.identity(r,o),f=e.gauss_jordan(i,l),a=[],w=0,g;w<r;w++)for(a[w]=[],g=o;g<f[0].length;g++)a[w][g-o]=f[w][g];return a},det:function c(i){if(i.length===2)return i[0][0]*i[1][1]-i[0][1]*i[1][0];for(var r=0,o=0;o<i.length;o++){for(var l=[],f=1;f<i.length;f++){l[f-1]=[];for(var a=0;a<i.length;a++)a<o?l[f-1][a]=i[f][a]:a>o&&(l[f-1][a-1]=i[f][a])}var w=o%2?-1:1;r+=c(l)*i[0][o]*w}return r},gauss_elimination:function(i,r){var o=0,l=0,f=i.length,a=i[0].length,w=1,g=0,p=[],d,m,v,y;for(i=e.aug(i,r),d=i[0].length,o=0;o<f;o++){for(m=i[o][o],l=o,y=o+1;y<a;y++)m<t.abs(i[y][o])&&(m=i[y][o],l=y);if(l!=o)for(y=0;y<d;y++)v=i[o][y],i[o][y]=i[l][y],i[l][y]=v;for(l=o+1;l<f;l++)for(w=i[l][o]/i[o][o],y=o;y<d;y++)i[l][y]=i[l][y]-w*i[o][y]}for(o=f-1;o>=0;o--){for(g=0,l=o+1;l<=f-1;l++)g=g+p[l]*i[o][l];p[o]=(i[o][d-1]-g)/i[o][o]}return p},gauss_jordan:function(i,r){var o=e.aug(i,r),l=o.length,f=o[0].length,a=0,w,g,p;for(g=0;g<l;g++){var d=g;for(p=g+1;p<l;p++)t.abs(o[p][g])>t.abs(o[d][g])&&(d=p);var m=o[g];for(o[g]=o[d],o[d]=m,p=g+1;p<l;p++)for(a=o[p][g]/o[g][g],w=g;w<f;w++)o[p][w]-=o[g][w]*a}for(g=l-1;g>=0;g--){for(a=o[g][g],p=0;p<g;p++)for(w=f-1;w>g-1;w--)o[p][w]-=o[g][w]*o[p][g]/a;for(o[g][g]/=a,w=l;w<f;w++)o[g][w]/=a}return o},triaUpSolve:function(i,r){var o=i[0].length,l=e.zeros(1,o)[0],f,a=!1;return r[0].length!=null&&(r=r.map(function(w){return w[0]}),a=!0),e.arange(o-1,-1,-1).forEach(function(w){f=e.arange(w+1,o).map(function(g){return l[g]*i[w][g]}),l[w]=(r[w]-e.sum(f))/i[w][w]}),a?l.map(function(w){return[w]}):l},triaLowSolve:function(i,r){var o=i[0].length,l=e.zeros(1,o)[0],f,a=!1;return r[0].length!=null&&(r=r.map(function(w){return w[0]}),a=!0),e.arange(o).forEach(function(w){f=e.arange(w).map(function(g){return i[w][g]*l[g]}),l[w]=(r[w]-e.sum(f))/i[w][w]}),a?l.map(function(w){return[w]}):l},lu:function(i){var r=i.length,o=e.identity(r),l=e.zeros(i.length,i[0].length),f;return e.arange(r).forEach(function(a){l[0][a]=i[0][a]}),e.arange(1,r).forEach(function(a){e.arange(a).forEach(function(w){f=e.arange(w).map(function(g){return o[a][g]*l[g][w]}),o[a][w]=(i[a][w]-e.sum(f))/l[w][w]}),e.arange(a,r).forEach(function(w){f=e.arange(a).map(function(g){return o[a][g]*l[g][w]}),l[a][w]=i[f.length][w]-e.sum(f)})}),[o,l]},cholesky:function(i){var r=i.length,o=e.zeros(i.length,i[0].length),l;return e.arange(r).forEach(function(f){l=e.arange(f).map(function(a){return t.pow(o[f][a],2)}),o[f][f]=t.sqrt(i[f][f]-e.sum(l)),e.arange(f+1,r).forEach(function(a){l=e.arange(f).map(function(w){return o[f][w]*o[a][w]}),o[a][f]=(i[f][a]-e.sum(l))/o[f][f]})}),o},gauss_jacobi:function(i,r,o,l){for(var f=0,a=0,w=i.length,g=[],p=[],d=[],m,v,y,E;f<w;f++)for(g[f]=[],p[f]=[],d[f]=[],a=0;a<w;a++)f>a?(g[f][a]=i[f][a],p[f][a]=d[f][a]=0):f<a?(p[f][a]=i[f][a],g[f][a]=d[f][a]=0):(d[f][a]=i[f][a],g[f][a]=p[f][a]=0);for(y=e.multiply(e.multiply(e.inv(d),e.add(g,p)),-1),v=e.multiply(e.inv(d),r),m=o,E=e.add(e.multiply(y,o),v),f=2;t.abs(e.norm(e.subtract(E,m)))>l;)m=E,E=e.add(e.multiply(y,m),v),f++;return E},gauss_seidel:function(i,r,o,l){for(var f=0,a=i.length,w=[],g=[],p=[],d,m,v,y,E;f<a;f++)for(w[f]=[],g[f]=[],p[f]=[],d=0;d<a;d++)f>d?(w[f][d]=i[f][d],g[f][d]=p[f][d]=0):f<d?(g[f][d]=i[f][d],w[f][d]=p[f][d]=0):(p[f][d]=i[f][d],w[f][d]=g[f][d]=0);for(y=e.multiply(e.multiply(e.inv(e.add(p,w)),g),-1),v=e.multiply(e.inv(e.add(p,w)),r),m=o,E=e.add(e.multiply(y,o),v),f=2;t.abs(e.norm(e.subtract(E,m)))>l;)m=E,E=e.add(e.multiply(y,m),v),f=f+1;return E},SOR:function(i,r,o,l,f){for(var a=0,w=i.length,g=[],p=[],d=[],m,v,y,E,q;a<w;a++)for(g[a]=[],p[a]=[],d[a]=[],m=0;m<w;m++)a>m?(g[a][m]=i[a][m],p[a][m]=d[a][m]=0):a<m?(p[a][m]=i[a][m],g[a][m]=d[a][m]=0):(d[a][m]=i[a][m],g[a][m]=p[a][m]=0);for(E=e.multiply(e.inv(e.add(d,e.multiply(g,f))),e.subtract(e.multiply(d,1-f),e.multiply(p,f))),y=e.multiply(e.multiply(e.inv(e.add(d,e.multiply(g,f))),r),f),v=o,q=e.add(e.multiply(E,o),y),a=2;t.abs(e.norm(e.subtract(q,v)))>l;)v=q,q=e.add(e.multiply(E,v),y),a++;return q},householder:function(i){for(var r=i.length,o=i[0].length,l=0,f=[],a=[],w,g,p,d,m;l<r-1;l++){for(w=0,d=l+1;d<o;d++)w+=i[d][l]*i[d][l];for(m=i[l+1][l]>0?-1:1,w=m*t.sqrt(w),g=t.sqrt((w*w-i[l+1][l]*w)/2),f=e.zeros(r,1),f[l+1][0]=(i[l+1][l]-w)/(2*g),p=l+2;p<r;p++)f[p][0]=i[p][l]/(2*g);a=e.subtract(e.identity(r,o),e.multiply(e.multiply(f,e.transpose(f)),2)),i=e.multiply(a,e.multiply(i,a))}return i},QR:(function(){var c=e.sum,i=e.arange;function r(o){var l=o.length,f=o[0].length,a=e.zeros(f,f);o=e.copy(o);var w,g,p;for(g=0;g<f;g++){for(a[g][g]=t.sqrt(c(i(l).map(function(d){return o[d][g]*o[d][g]}))),w=0;w<l;w++)o[w][g]=o[w][g]/a[g][g];for(p=g+1;p<f;p++)for(a[g][p]=c(i(l).map(function(d){return o[d][g]*o[d][p]})),w=0;w<l;w++)o[w][p]=o[w][p]-o[w][g]*a[g][p]}return[o,a]}return r})(),lstsq:(function(){function c(r){r=e.copy(r);var o=r.length,l=e.identity(o);return e.arange(o-1,-1,-1).forEach(function(f){e.sliceAssign(l,{row:f},e.divide(e.slice(l,{row:f}),r[f][f])),e.sliceAssign(r,{row:f},e.divide(e.slice(r,{row:f}),r[f][f])),e.arange(f).forEach(function(a){var w=e.multiply(r[a][f],-1),g=e.slice(r,{row:a}),p=e.multiply(e.slice(r,{row:f}),w);e.sliceAssign(r,{row:a},e.add(g,p));var d=e.slice(l,{row:a}),m=e.multiply(e.slice(l,{row:f}),w);e.sliceAssign(l,{row:a},e.add(d,m))})}),l}function i(r,o){var l=!1;o[0].length===void 0&&(o=o.map(function(E){return[E]}),l=!0);var f=e.QR(r),a=f[0],w=f[1],g=r[0].length,p=e.slice(a,{col:{end:g}}),d=e.slice(w,{row:{end:g}}),m=c(d),v=e.transpose(p);v[0].length===void 0&&(v=[v]);var y=e.multiply(e.multiply(m,v),o);return y.length===void 0&&(y=[[y]]),l?y.map(function(E){return E[0]}):y}return i})(),jacobi:function(i){for(var r=1,o=i.length,l=e.identity(o,o),f=[],a,w,g,p,d,m,v,y;r===1;){for(m=i[0][1],p=0,d=1,w=0;w<o;w++)for(g=0;g<o;g++)w!=g&&m<t.abs(i[w][g])&&(m=t.abs(i[w][g]),p=w,d=g);for(i[p][p]===i[d][d]?v=i[p][d]>0?t.PI/4:-t.PI/4:v=t.atan(2*i[p][d]/(i[p][p]-i[d][d]))/2,y=e.identity(o,o),y[p][p]=t.cos(v),y[p][d]=-t.sin(v),y[d][p]=t.sin(v),y[d][d]=t.cos(v),l=e.multiply(l,y),a=e.multiply(e.multiply(e.inv(y),i),y),i=a,r=0,w=1;w<o;w++)for(g=1;g<o;g++)w!=g&&t.abs(i[w][g])>.001&&(r=1)}for(w=0;w<o;w++)f.push(i[w][w]);return[l,f]},rungekutta:function(i,r,o,l,f,a){var w,g,p,d,m;if(a===2)for(;l<=o;)w=r*i(l,f),g=r*i(l+r,f+w),p=f+(w+g)/2,f=p,l=l+r;if(a===4)for(;l<=o;)w=r*i(l,f),g=r*i(l+r/2,f+w/2),d=r*i(l+r/2,f+g/2),m=r*i(l+r,f+d),p=f+(w+2*g+2*d+m)/6,f=p,l=l+r;return f},romberg:function(i,r,o,l){for(var f=0,a=(o-r)/2,w=[],g=[],p=[],d,m,v,y,E;f<l/2;){for(E=i(r),v=r,y=0;v<=o;v=v+a,y++)w[y]=v;for(d=w.length,v=1;v<d-1;v++)E+=(v%2!==0?4:2)*i(w[v]);E=a/3*(E+i(o)),p[f]=E,a/=2,f++}for(m=p.length,d=1;m!==1;){for(v=0;v<m-1;v++)g[v]=(t.pow(4,d)*p[v+1]-p[v])/(t.pow(4,d)-1);m=g.length,p=g,g=[],d++}return p},richardson:function(i,r,o,l){function f(q,N){for(var R=0,T=q.length,_;R<T;R++)q[R]===N&&(_=R);return _}for(var a=t.abs(o-i[f(i,o)+1]),w=0,g=[],p=[],d,m,v,y,E;l>=a;)d=f(i,o+l),m=f(i,o),g[w]=(r[d]-2*r[m]+r[2*m-d])/(l*l),l/=2,w++;for(y=g.length,v=1;y!=1;){for(E=0;E<y-1;E++)p[E]=(t.pow(4,v)*g[E+1]-g[E])/(t.pow(4,v)-1);y=p.length,g=p,p=[],v++}return g},simpson:function(i,r,o,l){for(var f=(o-r)/l,a=i(r),w=[],g=r,p=0,d=1,m;g<=o;g=g+f,p++)w[p]=g;for(m=w.length;d<m-1;d++)a+=(d%2!==0?4:2)*i(w[d]);return f/3*(a+i(o))},hermite:function(i,r,o,l){for(var f=i.length,a=0,w=0,g=[],p=[],d=[],m=[],v;w<f;w++){for(g[w]=1,v=0;v<f;v++)w!=v&&(g[w]*=(l-i[v])/(i[w]-i[v]));for(p[w]=0,v=0;v<f;v++)w!=v&&(p[w]+=1/(i[w]-i[v]));d[w]=(1-2*(l-i[w])*p[w])*(g[w]*g[w]),m[w]=(l-i[w])*(g[w]*g[w]),a+=d[w]*r[w]+m[w]*o[w]}return a},lagrange:function(i,r,o){for(var l=0,f=0,a,w,g=i.length;f<g;f++){for(w=r[f],a=0;a<g;a++)f!=a&&(w*=(o-i[a])/(i[f]-i[a]));l+=w}return l},cubic_spline:function(i,r,o){for(var l=i.length,f=0,a,w=[],g=[],p=[],d=[],m=[],v=[],y=[];f<l-1;f++)m[f]=i[f+1]-i[f];for(p[0]=0,f=1;f<l-1;f++)p[f]=3/m[f]*(r[f+1]-r[f])-3/m[f-1]*(r[f]-r[f-1]);for(f=1;f<l-1;f++)w[f]=[],g[f]=[],w[f][f-1]=m[f-1],w[f][f]=2*(m[f-1]+m[f]),w[f][f+1]=m[f],g[f][0]=p[f];for(d=e.multiply(e.inv(w),g),a=0;a<l-1;a++)v[a]=(r[a+1]-r[a])/m[a]-m[a]*(d[a+1][0]+2*d[a][0])/3,y[a]=(d[a+1][0]-d[a][0])/(3*m[a]);for(a=0;a<l&&!(i[a]>o);a++);return a-=1,r[a]+(o-i[a])*v[a]+e.sq(o-i[a])*d[a]+(o-i[a])*e.sq(o-i[a])*y[a]},gauss_quadrature:function(){throw new Error("gauss_quadrature not yet implemented")},PCA:function(i){var r=i.length,o=i[0].length,l=0,f,a,w=[],g=[],p=[],d=[],m=[],v=[],y=[],E=[],q=[],N=[];for(l=0;l<r;l++)w[l]=e.sum(i[l])/o;for(l=0;l<o;l++)for(y[l]=[],f=0;f<r;f++)y[l][f]=i[f][l]-w[f];for(y=e.transpose(y),l=0;l<r;l++)for(E[l]=[],f=0;f<r;f++)E[l][f]=e.dot([y[l]],[y[f]])/(o-1);for(p=e.jacobi(E),q=p[0],g=p[1],N=e.transpose(q),l=0;l<g.length;l++)for(f=l;f<g.length;f++)g[l]<g[f]&&(a=g[l],g[l]=g[f],g[f]=a,d=N[l],N[l]=N[f],N[f]=d);for(v=e.transpose(y),l=0;l<r;l++)for(m[l]=[],f=0;f<v.length;f++)m[l][f]=e.dot([N[l]],[v[f]]);return[i,g,N,m]}}),(function(c){for(var i=0;i<c.length;i++)(function(r){e.fn[r]=function(o,l){var f=this;return l?(setTimeout(function(){l.call(f,e.fn[r].call(f,o))},15),this):typeof e[r](this,o)=="number"?e[r](this,o):e(e[r](this,o))}})(c[i])})("add divide multiply subtract dot pow exp log abs norm angle".split(" "))})(h,Math),(function(e,t){var n=[].slice,s=e.utils.isNumber,u=e.utils.isArray;e.extend({zscore:function(){var r=n.call(arguments);return s(r[1])?(r[0]-r[1])/r[2]:(r[0]-e.mean(r[1]))/e.stdev(r[1],r[2])},ztest:function(){var r=n.call(arguments),o;return u(r[1])?(o=e.zscore(r[0],r[1],r[3]),r[2]===1?e.normal.cdf(-t.abs(o),0,1):e.normal.cdf(-t.abs(o),0,1)*2):r.length>2?(o=e.zscore(r[0],r[1],r[2]),r[3]===1?e.normal.cdf(-t.abs(o),0,1):e.normal.cdf(-t.abs(o),0,1)*2):(o=r[0],r[1]===1?e.normal.cdf(-t.abs(o),0,1):e.normal.cdf(-t.abs(o),0,1)*2)}}),e.extend(e.fn,{zscore:function(r,o){return(r-this.mean())/this.stdev(o)},ztest:function(r,o,l){var f=t.abs(this.zscore(r,l));return o===1?e.normal.cdf(-f,0,1):e.normal.cdf(-f,0,1)*2}}),e.extend({tscore:function(){var r=n.call(arguments);return r.length===4?(r[0]-r[1])/(r[2]/t.sqrt(r[3])):(r[0]-e.mean(r[1]))/(e.stdev(r[1],!0)/t.sqrt(r[1].length))},ttest:function(){var r=n.call(arguments),o;return r.length===5?(o=t.abs(e.tscore(r[0],r[1],r[2],r[3])),r[4]===1?e.studentt.cdf(-o,r[3]-1):e.studentt.cdf(-o,r[3]-1)*2):s(r[1])?(o=t.abs(r[0]),r[2]==1?e.studentt.cdf(-o,r[1]-1):e.studentt.cdf(-o,r[1]-1)*2):(o=t.abs(e.tscore(r[0],r[1])),r[2]==1?e.studentt.cdf(-o,r[1].length-1):e.studentt.cdf(-o,r[1].length-1)*2)}}),e.extend(e.fn,{tscore:function(r){return(r-this.mean())/(this.stdev(!0)/t.sqrt(this.cols()))},ttest:function(r,o){return o===1?1-e.studentt.cdf(t.abs(this.tscore(r)),this.cols()-1):e.studentt.cdf(-t.abs(this.tscore(r)),this.cols()-1)*2}}),e.extend({anovafscore:function(){var r=n.call(arguments),o,l,f,a,w,g,p,d;if(r.length===1){for(w=new Array(r[0].length),p=0;p<r[0].length;p++)w[p]=r[0][p];r=w}for(l=new Array,p=0;p<r.length;p++)l=l.concat(r[p]);for(f=e.mean(l),o=0,p=0;p<r.length;p++)o=o+r[p].length*t.pow(e.mean(r[p])-f,2);for(o/=r.length-1,g=0,p=0;p<r.length;p++)for(a=e.mean(r[p]),d=0;d<r[p].length;d++)g+=t.pow(r[p][d]-a,2);return g/=l.length-r.length,o/g},anovaftest:function(){var r=n.call(arguments),o,l,f,a;if(s(r[0]))return 1-e.centralF.cdf(r[0],r[1],r[2]);var w=e.anovafscore(r);for(o=r.length-1,f=0,a=0;a<r.length;a++)f=f+r[a].length;return l=f-o-1,1-e.centralF.cdf(w,o,l)},ftest:function(r,o,l){return 1-e.centralF.cdf(r,o,l)}}),e.extend(e.fn,{anovafscore:function(){return e.anovafscore(this.toArray())},anovaftes:function(){var r=0,o;for(o=0;o<this.length;o++)r=r+this[o].length;return e.ftest(this.anovafscore(),this.length-1,r-this.length)}}),e.extend({qscore:function(){var r=n.call(arguments),o,l,f,a,w;return s(r[0])?(o=r[0],l=r[1],f=r[2],a=r[3],w=r[4]):(o=e.mean(r[0]),l=e.mean(r[1]),f=r[0].length,a=r[1].length,w=r[2]),t.abs(o-l)/(w*t.sqrt((1/f+1/a)/2))},qtest:function(){var r=n.call(arguments),o;r.length===3?(o=r[0],r=r.slice(1)):r.length===7?(o=e.qscore(r[0],r[1],r[2],r[3],r[4]),r=r.slice(5)):(o=e.qscore(r[0],r[1],r[2]),r=r.slice(3));var l=r[0],f=r[1];return 1-e.tukey.cdf(o,f,l-f)},tukeyhsd:function(r){for(var o=e.pooledstdev(r),l=r.map(function(d){return e.mean(d)}),f=r.reduce(function(d,m){return d+m.length},0),a=[],w=0;w<r.length;++w)for(var g=w+1;g<r.length;++g){var p=e.qtest(l[w],l[g],r[w].length,r[g].length,o,f,r.length);a.push([[w,g],p])}return a}}),e.extend({normalci:function(){var r=n.call(arguments),o=new Array(2),l;return r.length===4?l=t.abs(e.normal.inv(r[1]/2,0,1)*r[2]/t.sqrt(r[3])):l=t.abs(e.normal.inv(r[1]/2,0,1)*e.stdev(r[2])/t.sqrt(r[2].length)),o[0]=r[0]-l,o[1]=r[0]+l,o},tci:function(){var r=n.call(arguments),o=new Array(2),l;return r.length===4?l=t.abs(e.studentt.inv(r[1]/2,r[3]-1)*r[2]/t.sqrt(r[3])):l=t.abs(e.studentt.inv(r[1]/2,r[2].length-1)*e.stdev(r[2],!0)/t.sqrt(r[2].length)),o[0]=r[0]-l,o[1]=r[0]+l,o},significant:function(r,o){return r<o}}),e.extend(e.fn,{normalci:function(r,o){return e.normalci(r,o,this.toArray())},tci:function(r,o){return e.tci(r,o,this.toArray())}});function c(i,r,o,l){if(i>1||o>1||i<=0||o<=0)throw new Error("Proportions should be greater than 0 and less than 1");var f=(i*r+o*l)/(r+l),a=t.sqrt(f*(1-f)*(1/r+1/l));return(i-o)/a}e.extend(e.fn,{oneSidedDifferenceOfProportions:function(r,o,l,f){var a=c(r,o,l,f);return e.ztest(a,1)},twoSidedDifferenceOfProportions:function(r,o,l,f){var a=c(r,o,l,f);return e.ztest(a,2)}})})(h,Math),h.models=(function(){function e(c){var i=c[0].length,r=h.arange(i).map(function(o){var l=h.arange(i).filter(function(f){return f!==o});return t(h.col(c,o).map(function(f){return f[0]}),h.col(c,l))});return r}function t(c,i){var r=c.length,o=i[0].length-1,l=r-o-1,f=h.lstsq(i,c),a=h.multiply(i,f.map(function(y){return[y]})).map(function(y){return y[0]}),w=h.subtract(c,a),g=h.mean(c),p=h.sum(a.map(function(y){return Math.pow(y-g,2)})),d=h.sum(c.map(function(y,E){return Math.pow(y-a[E],2)})),m=p+d,v=p/m;return{exog:i,endog:c,nobs:r,df_model:o,df_resid:l,coef:f,predict:a,resid:w,ybar:g,SST:m,SSE:p,SSR:d,R2:v}}function n(c){var i=e(c.exog),r=Math.sqrt(c.SSR/c.df_resid),o=i.map(function(g){var p=g.SST,d=g.R2;return r/Math.sqrt(p*(1-d))}),l=c.coef.map(function(g,p){return(g-0)/o[p]}),f=l.map(function(g){var p=h.studentt.cdf(g,c.df_resid);return(p>.5?1-p:p)*2}),a=h.studentt.inv(.975,c.df_resid),w=c.coef.map(function(g,p){var d=a*o[p];return[g-d,g+d]});return{se:o,t:l,p:f,sigmaHat:r,interval95:w}}function s(c){var i=c.R2/c.df_model/((1-c.R2)/c.df_resid),r=function(l,f,a){return h.beta.cdf(l/(a/f+l),f/2,a/2)},o=1-r(i,c.df_model,c.df_resid);return{F_statistic:i,pvalue:o}}function u(c,i){var r=t(c,i),o=n(r),l=s(r),f=1-(1-r.R2)*((r.nobs-1)/r.df_resid);return r.t=o,r.f=l,r.adjust_R2=f,r}return{ols:u}})(),h.extend({buildxmatrix:function(){for(var t=new Array(arguments.length),n=0;n<arguments.length;n++){var s=[1];t[n]=s.concat(arguments[n])}return h(t)},builddxmatrix:function(){for(var t=new Array(arguments[0].length),n=0;n<arguments[0].length;n++){var s=[1];t[n]=s.concat(arguments[0][n])}return h(t)},buildjxmatrix:function(t){for(var n=new Array(t.length),s=0;s<t.length;s++)n[s]=t[s];return h.builddxmatrix(n)},buildymatrix:function(t){return h(t).transpose()},buildjymatrix:function(t){return t.transpose()},matrixmult:function(t,n){var s,u,c,i,r;if(t.cols()==n.rows()){if(n.rows()>1){for(i=[],s=0;s<t.rows();s++)for(i[s]=[],u=0;u<n.cols();u++){for(r=0,c=0;c<t.cols();c++)r+=t.toArray()[s][c]*n.toArray()[c][u];i[s][u]=r}return h(i)}for(i=[],s=0;s<t.rows();s++)for(i[s]=[],u=0;u<n.cols();u++){for(r=0,c=0;c<t.cols();c++)r+=t.toArray()[s][c]*n.toArray()[u];i[s][u]=r}return h(i)}},regress:function(t,n){var s=h.xtranspxinv(t),u=t.transpose(),c=h.matrixmult(h(s),u);return h.matrixmult(c,n)},regresst:function(t,n,s){var u=h.regress(t,n),c={};c.anova={};var i=h.jMatYBar(t,u);c.yBar=i;var r=n.mean();c.anova.residuals=h.residuals(n,i),c.anova.ssr=h.ssr(i,r),c.anova.msr=c.anova.ssr/(t[0].length-1),c.anova.sse=h.sse(n,i),c.anova.mse=c.anova.sse/(n.length-(t[0].length-1)-1),c.anova.sst=h.sst(n,r),c.anova.mst=c.anova.sst/(n.length-1),c.anova.r2=1-c.anova.sse/c.anova.sst,c.anova.r2<0&&(c.anova.r2=0),c.anova.fratio=c.anova.msr/c.anova.mse,c.anova.pvalue=h.anovaftest(c.anova.fratio,t[0].length-1,n.length-(t[0].length-1)-1),c.anova.rmse=Math.sqrt(c.anova.mse),c.anova.r2adj=1-c.anova.mse/c.anova.mst,c.anova.r2adj<0&&(c.anova.r2adj=0),c.stats=new Array(t[0].length);for(var o=h.xtranspxinv(t),l,f,a,w=0;w<u.length;w++)l=Math.sqrt(c.anova.mse*Math.abs(o[w][w])),f=Math.abs(u[w]/l),a=h.ttest(f,n.length-t[0].length-1,s),c.stats[w]=[u[w],l,f,a];return c.regress=u,c},xtranspx:function(t){return h.matrixmult(t.transpose(),t)},xtranspxinv:function(t){var n=h.matrixmult(t.transpose(),t),s=h.inv(n);return s},jMatYBar:function(t,n){var s=h.matrixmult(t,n);return new h(s)},residuals:function(t,n){return h.matrixsubtract(t,n)},ssr:function(t,n){for(var s=0,u=0;u<t.length;u++)s+=Math.pow(t[u]-n,2);return s},sse:function(t,n){for(var s=0,u=0;u<t.length;u++)s+=Math.pow(t[u]-n[u],2);return s},sst:function(t,n){for(var s=0,u=0;u<t.length;u++)s+=Math.pow(t[u]-n,2);return s},matrixsubtract:function(t,n){for(var s=new Array(t.length),u=0;u<t.length;u++){s[u]=new Array(t[u].length);for(var c=0;c<t[u].length;c++)s[u][c]=t[u][c]-n[u][c]}return h(s)}}),h.jStat=h,h})});var F=Fe(Be(),1);var Wt=F.Matrix;var Jt=F.SingularValueDecomposition;var Zt=F.default.Matrix?F.default.Matrix:F.Matrix;var We=Fe(Ge(),1),At=(h,e)=>We.default.studentt.inv(h,e);export{Wt as Matrix,Jt as SVD,At as studentTQuantile};diff --git a/store/agents/lab-bench/template/studio/measurements.mjs b/store/agents/lab-bench/template/studio/measurements.mjsnew file mode 100644index 000000000..74d648177--- /dev/null+++ b/store/agents/lab-bench/template/studio/measurements.mjs@@ -0,0 +1,94 @@+import {assert, clone, validateProject, event, finite, text, digest, canonical} from './project.mjs';+export function parseCSV(input) {+ assert(typeof input === 'string' && input.length <= 1000000, 'Use a UTF-8 CSV below 1 MB.');+ const s = input.replace(/^\uFEFF/, ''), records = []; let cells = [], field = '', quoted = false, closed = false, line = 1, start = 1;+ const endField = () => {cells.push(field); field = ''; closed = false;};+ const endRow = () => {endField(); if (cells.some(x => x !== '')) records.push({row: start, cells}); cells = []; start = line + 1;};+ for (let i = 0; i < s.length; i++) {+ const c = s[i];+ if (quoted) {+ if (c === '"') {if (s[i + 1] === '"') {field += '"'; i++;} else {quoted = false; closed = true;}}+ else {field += c; if (c === '\n' || (c === '\r' && s[i + 1] !== '\n')) line++;}+ } else if (c === '"') {assert(field === '' && !closed, `Unexpected quote at line ${line}.`); quoted = true;}+ else if (c === ',') endField();+ else if (c === '\n' || c === '\r') {if (c === '\r' && s[i + 1] === '\n') i++; endRow(); line++;}+ else {assert(!closed, `Unexpected text after a quoted field at line ${line}.`); field += c;}+ }+ assert(!quoted, 'The CSV ends inside a quoted field.'); if (field || cells.length || closed) endRow();+ assert(records.length >= 1 && records.length <= 1025, 'Include a header and at most 1024 measurement rows.');+ const headers = records.shift().cells.map(x => x.trim());+ assert(headers.length >= 2 && headers.length <= 40 && headers.every(x => text(x, 160)) && new Set(headers).size === headers.length, 'Use 2–40 distinct, nonempty column names.');+ for (const r of records) assert(r.cells.length === headers.length, `Line ${r.row} has ${r.cells.length} cells; the header has ${headers.length}.`);+ return {headers, rows: records.map(r => ({row: r.row, values: Object.fromEntries(headers.map((h, i) => [h, r.cells[i]]))}))};+}+export function numeric(value) {+ const s = String(value).trim(); assert(/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(s) && finite(Number(s)), 'Use a finite decimal measurement, with no unit text or thousands separators.'); return Number(s);+}+export function decode(bytes) {try {return new TextDecoder('utf-8', {fatal: true}).decode(bytes);} catch {throw new Error('The CSV must use UTF-8 text.');}}+export function base64(bytes) {let s = ''; for (let i = 0; i < bytes.length; i += 8192) s += String.fromCharCode(...bytes.subarray(i, i + 8192)); return btoa(s);}+export const bytesFromBase64 = s => Uint8Array.from(atob(s), x => x.charCodeAt(0));+export function mappedRows(p, parsed, mapping, unit, {checkExisting = true} = {}) {+ assert(parsed.headers.includes(mapping.runId) && parsed.headers.includes(mapping.response) && mapping.runId !== mapping.response, 'Map two different columns: run id and measured response.');+ assert(unit === p.response.unit, `Confirm measurements are in ${p.response.unit}. No unit conversion is applied.`);+ const runs = new Map(p.runs.map(r => [r.id, r])), seen = new Set(), measured = new Set(p.measurements.map(m => m.runId)); let pending = 0; const records = [];+ for (const row of parsed.rows) {+ const runId = row.values[mapping.runId].trim(), run = runs.get(runId);+ assert(run, `Line ${row.row}: unknown run id “${runId}”. Use the run sheet ids.`); assert(!seen.has(runId), `Line ${row.row}: duplicate run id ${runId}.`); seen.add(runId);+ for (const f of p.factors) if (Object.hasOwn(row.values, f.id)) {+ const value = f.type === 'number' ? numeric(row.values[f.id]) : row.values[f.id];+ assert(value === run.settings[f.id], `Line ${row.row}: ${f.name} does not match the planned run.`);+ }+ if (Object.hasOwn(row.values, 'block')) assert(row.values.block === run.block, `Line ${row.row}: the block does not match the plan.`);+ if (Object.hasOwn(row.values, 'unit')) assert(row.values.unit === unit, `Line ${row.row}: the response unit does not match.`);+ if (row.values[mapping.response].trim() === '') {pending++; continue;}+ assert(!checkExisting || !measured.has(runId), `${runId} is already measured. Use a logged correction to change it.`);+ let value; try {value = numeric(row.values[mapping.response]);} catch (e) {throw new Error(`Line ${row.row}: ${e.message}`);}+ records.push({runId, value, row: row.row, note: row.values.note ?? ''});+ }+ return {records, pending, rows: parsed.rows.length};+}+export async function prepareImport(raw, bytes, {name, mapping, unit}) {+ const p = validateProject(raw); assert(bytes.length > 0 && bytes.length <= 1000000, 'Use a nonempty CSV below 1 MB.');+ const parsed = parseCSV(decode(bytes)), mapped = mappedRows(p, parsed, mapping, unit);+ assert(mapped.records.length, 'This file has no new measured responses. Blank response cells remain pending.');+ const sha256 = await digest(bytes); assert(!p.sources.some(s => s.sha256 === sha256), 'This original file has already been imported.');+ return {source: {id: 'csv' + (p.sources.length + 1) + '_' + sha256.slice(0, 10), name, base64: base64(bytes), sha256, mapping, unit, importedAt: new Date().toISOString()}, ...mapped};+}+export function commitImport(raw, prepared) {+ const p = validateProject(raw);+ // Reparse at commit so stale previews cannot overwrite a measurement entered in the meantime.+ const source = prepared.source, mapped = mappedRows(p, parseCSV(decode(bytesFromBase64(source.base64))), source.mapping, source.unit);+ assert(!p.sources.some(s => s.id === source.id || s.sha256 === source.sha256), 'This source is already part of the experiment.');+ p.sources.push(clone(source));+ for (const r of mapped.records) p.measurements.push({runId: r.runId, value: r.value, origin: {kind: 'csv', source: source.id, row: r.row, value: r.value}, note: r.note, excluded: null});+ event(p, 'import', `Imported ${mapped.records.length} measured responses from ${source.name}; ${mapped.pending} blank responses remain pending.`, {source: source.id, sha256: source.sha256, runs: mapped.records.map(r => r.runId)});+ return validateProject(p);+}+export function recordMeasurement(raw, runId, {value, note = '', excluded = null, reason}) {+ const p = validateProject(raw); assert(p.runs.some(r => r.id === runId), 'Choose a known run.');+ const n = typeof value === 'number' ? value : numeric(value); assert(finite(n), 'Enter a finite measured value.');+ const i = p.measurements.findIndex(m => m.runId === runId), before = i < 0 ? null : clone(p.measurements[i]);+ const after = {runId, value: n, origin: before?.origin ?? {kind: 'manual', value: n}, note, excluded};+ if (i < 0) p.measurements.push(after); else p.measurements[i] = after;+ event(p, 'measurement', reason, {runId, before, after}); return validateProject(p);+}+export async function verifySources(raw) {+ const p = validateProject(raw);+ for (const source of p.sources) {+ const bytes = bytesFromBase64(source.base64); assert(await digest(bytes) === source.sha256, `Original file hash mismatch: ${source.name}.`);+ const {records} = mappedRows(p, parseCSV(decode(bytes)), source.mapping, source.unit, {checkExisting: false});+ for (const record of records) assert(p.measurements.some(m => m.runId === record.runId && m.origin.source === source.id && m.origin.row === record.row), `Keep every imported measurement; use an exclusion reason instead of deleting ${record.runId}.`);+ for (const m of p.measurements.filter(m => m.origin.kind === 'csv' && m.origin.source === source.id)) {+ const original = records.find(r => r.runId === m.runId && r.row === m.origin.row);+ assert(original?.value === m.origin.value, `Original measurement provenance does not match ${source.name}: ${m.runId}.`);+ }+ }+ return p;+}+export const csvCell = v => '"' + String(v ?? '').replace(/"/g, '""') + '"';+export const csv = rows => rows.map(row => row.map(csvCell).join(',')).join('\r\n') + '\r\n';+export function collectionCSV(p, {blank = true, phase = null} = {}) {+ const measurements = new Map(p.measurements.map(m => [m.runId, m]));+ return csv([['run_id', 'order', 'phase', 'block', 'kind', ...p.factors.map(f => f.id), 'response', 'unit', 'note'],+ ...p.runs.filter(r => !phase || r.phase === phase).map(r => {const m = measurements.get(r.id); return [r.id, r.order, r.phase, r.block, r.kind, ...p.factors.map(f => r.settings[f.id]), blank ? '' : m?.value, p.response.unit, blank ? '' : m?.note];})]);+}diff --git a/store/agents/lab-bench/template/studio/project.mjs b/store/agents/lab-bench/template/studio/project.mjsnew file mode 100644index 000000000..07dbb8730--- /dev/null+++ b/store/agents/lab-bench/template/studio/project.mjs@@ -0,0 +1,149 @@+// A portable experiment, including the original measurements and their history.+export const clone = x => JSON.parse(JSON.stringify(x));+export function assert(ok, message) { if (!ok) throw new Error(message); }+export const text = (x, max = 160, empty = false) => typeof x === 'string' && (empty || x.trim().length > 0) && x.length <= max;+export const identifier = x => typeof x === 'string' && /^[a-z][a-z0-9_-]{0,47}$/.test(x) && !['constructor', 'prototype'].includes(x);+export const finite = x => typeof x === 'number' && Number.isFinite(x) && Math.abs(x) <= 1e12;+const list = (x, max, min = 0) => Array.isArray(x) && x.length >= min && x.length <= max;+export function canonical(x) {+ if (x === null || typeof x !== 'object') return JSON.stringify(x);+ return Array.isArray(x) ? '[' + x.map(canonical).join(',') + ']' : '{' + Object.keys(x).sort().map(k => JSON.stringify(k) + ':' + canonical(x[k])).join(',') + '}';+}+export async function digest(x) {+ const bytes = x instanceof Uint8Array ? x : new TextEncoder().encode(typeof x === 'string' ? x : canonical(x));+ return [...new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))].map(x => x.toString(16).padStart(2, '0')).join('');+}+export function settingsValid(p, settings) {+ assert(settings && Object.keys(settings).length === p.factors.length, 'Every run needs exactly one setting for each factor.');+ for (const f of p.factors) {+ const v = settings[f.id];+ assert(f.type === 'number' ? finite(v) && v >= f.levels[0] && v <= f.levels.at(-1) : f.levels.includes(v), `Keep ${f.name} inside its planned range.`);+ }+ return settings;+}+export function validateProject(raw) {+ assert(raw && new TextEncoder().encode(JSON.stringify(raw)).length <= 5000000, 'Keep the complete project below 5 MB.');+ const p = clone(raw); delete p.revision;+ assert(p.spec === 1 && identifier(p.id) && text(p.title) && text(p.question, 1200), 'Use a version 1 Signal project with an id, title and question.');+ assert(p.response && identifier(p.response.id) && text(p.response.name, 80) && text(p.response.unit, 40), 'Name the continuous response and its measurement unit.');+ assert(['maximize', 'minimize', 'target'].includes(p.response.goal), 'Choose a response goal.');+ assert(p.conclusion === undefined || text(p.conclusion, 8000, true), 'Keep the decision note within 8000 characters.');+ assert(p.evidenceNote === undefined || text(p.evidenceNote, 600), 'Keep the evidence note short and explicit.');+ if (p.response.goal === 'target') assert(finite(p.response.target), 'Enter a finite target response.');+ assert(list(p.factors, 6, 1), 'Use 1–6 experimental factors.');+ const ids = new Set();+ for (const f of p.factors) {+ assert(identifier(f.id) && !ids.has(f.id) && !['run_id', 'response', 'block', 'order', 'phase', 'kind', 'unit', 'note'].includes(f.id), 'Factors need distinct ids, separate from collection columns.'); ids.add(f.id);+ assert(text(f.name, 80) && ['number', 'category'].includes(f.type) && text(f.unit, 40, true), 'Each factor needs a name, type and unit (which can be blank).');+ assert(list(f.levels, 5, 2) && new Set(f.levels).size === f.levels.length, 'Use 2–5 distinct levels per factor.');+ if (f.type === 'number') assert(f.levels.every(finite) && f.levels.every((x, i) => i === 0 || x > f.levels[i - 1]), 'Numeric levels must be finite and increasing.');+ else assert(f.levels.every(x => text(x, 60)), 'Category levels must be short, nonempty names.');+ }+ const protocol = p.protocol;+ assert(protocol && text(protocol.unit, 300) && text(protocol.randomization, 600) && text(protocol.analysisPlan, 1200) && list(protocol.steps, 20, 1) && protocol.steps.every(s => text(s, 1200)), 'Describe the independent experimental unit, randomization, planned analysis and procedure.');+ assert(text(protocol.notes, 4000, true) && typeof p.approved === 'boolean', 'Include protocol notes and approval state.');+ assert(p.design && text(p.design.seed, 100) && Number.isInteger(p.design.replicates) && p.design.replicates >= 1 && p.design.replicates <= 20, 'Use a seed and 1–20 independent repetitions per combination and block.');+ assert(list(p.design.blocks, 8, 1) && p.design.blocks.every(x => text(x, 60)) && new Set(p.design.blocks).size === p.design.blocks.length, 'Name 1–8 distinct complete blocks.');+ assert(Number.isInteger(p.design.controls) && p.design.controls >= 0 && p.design.controls <= 5 && p.design.controls !== 1, 'Choose zero or 2–5 control runs per block (at the beginning, end and between).');+ assert(p.model && list(p.model.terms, 24) && new Set(p.model.terms).size === p.model.terms.length && typeof p.model.blocks === 'boolean', 'Use a distinct list of model terms and a block setting.');+ assert([.8, .9, .95, .99].includes(p.model.confidence), 'Use 80%, 90%, 95% or 99% confidence.');+ for (const term of p.model.terms) {+ assert(typeof term === 'string', 'Model terms must be names.');+ if (term.endsWith('^2')) {+ const f = p.factors.find(x => x.id === term.slice(0, -2));+ assert(f?.type === 'number' && p.model.terms.includes(f.id), 'A quadratic term needs its numeric main effect.');+ } else {+ const parts = term.split(':');+ assert(parts.length <= 2 && new Set(parts).size === parts.length && parts.every(x => ids.has(x)), 'Use main effects, two-factor interactions or numeric quadratic terms.');+ if (parts.length === 2) assert(parts.every(x => p.model.terms.includes(x)), 'An interaction needs both main effects.');+ }+ }+ assert(list(p.phases, 30) && list(p.runs, 512) && list(p.measurements, 512) && list(p.sources, 30) && list(p.audit, 5000), 'This workshop supports up to 512 runs, 30 phases/imports and 5000 recorded changes.');+ const phases = new Set();+ for (const phase of p.phases) {+ assert(identifier(phase.id) && !phases.has(phase.id) && text(phase.label) && ['plan', 'extension', 'confirmation'].includes(phase.kind) && text(phase.reason, 1000) && text(phase.seed, 100), 'Each phase needs a unique id, purpose, reason and seed.'); phases.add(phase.id);+ if (phase.kind === 'confirmation') {+ assert(phase.snapshot && /^[a-f0-9]{64}$/.test(phase.snapshot.trainingRevision) && list(phase.snapshot.predictions, 12, 1), 'Confirmation runs retain their original model and predictions.');+ const snapshot = phase.snapshot, matrix = snapshot.matrix, width = snapshot.columns?.length;+ assert(Number.isInteger(snapshot.n) && snapshot.n > 1 && snapshot.n <= 512 && list(snapshot.columns, 48, 1) && snapshot.columns.every(c => text(c.id) && text(c.label, 300)) && snapshot.df === snapshot.n - width && snapshot.df > 0, 'A confirmation snapshot needs its original measured count, columns and residual degrees of freedom.');+ assert(snapshot.model && [.8, .9, .95, .99].includes(snapshot.model.confidence) && list(snapshot.coefficients, width, width) && list(snapshot.covariance, width, width), 'Retain the original model, coefficients and covariance for confirmation.');+ assert(matrix && list(matrix.X, snapshot.n, snapshot.n) && list(matrix.y, snapshot.n, snapshot.n) && list(matrix.runIds, snapshot.n, snapshot.n) && new Set(matrix.runIds).size === snapshot.n, 'Retain the complete training matrix and run ids with the forecast.');+ assert(matrix.X.every(row => list(row, width, width) && row.every(finite)) && matrix.y.every(finite) && snapshot.coefficients.every(c => Number.isFinite(c.value)) && snapshot.covariance.every(row => list(row, width, width) && row.every(Number.isFinite)) && Number.isFinite(snapshot.mse) && snapshot.mse > 0, 'The frozen analysis must contain finite numerical results.');+ for (const prediction of phase.snapshot.predictions) {+ settingsValid(p, prediction.settings);+ assert(p.design.blocks.includes(prediction.block) && Number.isFinite(prediction.mean) && list(prediction.x, width, width) && prediction.x.every(finite) && list(prediction.meanCI, 2, 2) && list(prediction.predictionCI, 2, 2) && [...prediction.meanCI, ...prediction.predictionCI].every(Number.isFinite) && prediction.meanCI[0] <= prediction.mean && prediction.meanCI[1] >= prediction.mean && prediction.predictionCI[0] <= prediction.meanCI[0] && prediction.predictionCI[1] >= prediction.meanCI[1], 'Confirmation predictions must retain their design row, ordered intervals and named block.');+ }+ }+ }+ const runs = new Map();+ for (const [i, run] of p.runs.entries()) {+ assert(identifier(run.id) && !runs.has(run.id) && run.order === i + 1 && phases.has(run.phase) && p.design.blocks.includes(run.block) && ['factorial', 'control', 'followup'].includes(run.kind), 'Run ids and order must be unique, with a declared phase and block.');+ settingsValid(p, run.settings); runs.set(run.id, run);+ }+ for (const phase of p.phases.filter(x => x.kind === 'confirmation')) {+ const predictions = phase.snapshot.predictions.map(x => canonical({settings: x.settings, block: x.block}));+ assert(new Set(predictions).size === predictions.length, 'Use distinct confirmation points.');+ assert(p.runs.filter(r => r.phase === phase.id).every(r => predictions.includes(canonical({settings: r.settings, block: r.block}))), 'Each confirmation run must match one of its frozen predicted settings.');+ assert(phase.snapshot.matrix.runIds.every(id => runs.has(id) && p.phases.find(x => x.id === runs.get(id).phase)?.kind !== 'confirmation'), 'The frozen training matrix must reference existing non-confirmation runs.');+ }+ const sources = new Map();+ for (const source of p.sources) {+ assert(identifier(source.id) && !sources.has(source.id) && text(source.name, 160) && /^[a-f0-9]{64}$/.test(source.sha256), 'Imported measurements need unique ids, original filenames and SHA-256 hashes.');+ assert(text(source.base64, 1400000) && /^[A-Za-z0-9+/]*={0,2}$/.test(source.base64) && text(source.unit, 40) && source.unit === p.response.unit, 'Keep each original CSV below 1 MB and confirm its response unit.');+ assert(source.mapping && text(source.mapping.runId) && text(source.mapping.response) && source.mapping.runId !== source.mapping.response && text(source.importedAt, 50), 'Map distinct run id and response columns.'); sources.set(source.id, source);+ }+ const measured = new Set();+ for (const m of p.measurements) {+ assert(runs.has(m.runId) && !measured.has(m.runId) && finite(m.value) && text(m.note, 1000, true), 'Each known run may have one finite measurement.'); measured.add(m.runId);+ assert(m.excluded === null || text(m.excluded, 600), 'An excluded measurement needs a recorded reason.');+ assert(m.origin && finite(m.origin.value) && ['manual', 'csv'].includes(m.origin.kind), 'Keep the original measurement and its provenance.');+ if (m.origin.kind === 'csv') assert(sources.has(m.origin.source) && Number.isInteger(m.origin.row) && m.origin.row >= 2, 'CSV measurements must reference their original file and row.');+ }+ const auditIds = new Set();+ for (const event of p.audit) {+ assert(text(event.id, 80) && !auditIds.has(event.id) && text(event.at, 50) && text(event.action, 80) && text(event.reason, 1200), 'Every change in the log needs an id, time, action and reason.'); auditIds.add(event.id);+ }+ for (const m of p.measurements) if (m.value !== m.origin.value || m.excluded) assert(p.audit.some(e => e.action === 'measurement' && e.runId === m.runId && canonical(e.after) === canonical(m)), 'A corrected or excluded result needs its complete logged change and reason.');+ if (p.comparison) for (const point of [p.comparison.a, p.comparison.b]) {assert(point && p.design.blocks.includes(point.block), 'Comparison points need a known block.'); settingsValid(p, point.settings);}+ return p;+}+export function event(p, action, reason, details = {}) {+ assert(text(reason, 1200), 'Record a reason for this change.');+ p.audit.push({id: crypto.randomUUID(), at: new Date().toISOString(), action, reason, ...clone(details)});+}+export const planFrozen = p => p.approved || p.measurements.length > 0;+export function validateTransition(before, after) {+ // Source files are editable; this guards accidental destructive saves, not hostile users.+ assert(before.id === after.id, 'Open a different project in its own workspace; source saves keep this experiment id.');+ assert(canonical(after.audit.slice(0, before.audit.length)) === canonical(before.audit), 'Keep the existing change log.');+ for (const source of before.sources) assert(canonical(after.sources.find(x => x.id === source.id)) === canonical(source), 'Keep every original imported file.');+ if (planFrozen(before)) {+ for (const key of ['factors', 'protocol', 'response', 'design']) assert(canonical(before[key]) === canonical(after[key]), 'The collected or approved protocol is locked. Start a separate experiment to change its factors or measurement method.');+ assert(!before.approved || after.approved, 'Preserve protocol approval.');+ for (const run of before.runs) assert(canonical(after.runs.find(x => x.id === run.id)) === canonical(run), 'Keep existing run settings and order; append a follow-up phase.');+ for (const phase of before.phases) assert(canonical(after.phases.find(x => x.id === phase.id)) === canonical(phase), 'Keep each phase and its original prediction snapshot.');+ }+ const changes = after.audit.slice(before.audit.length);+ for (const m of after.measurements.filter(m => !before.measurements.some(old => old.runId === m.runId))) {+ assert(changes.some(e => e.action === 'measurement' && e.runId === m.runId && e.before === null && canonical(e.after) === canonical(m)) || changes.some(e => e.action === 'import' && e.source === m.origin.source && e.runs?.includes(m.runId)), 'Keep the entry or import event for every new measurement.');+ }+ for (const m of before.measurements) {+ const next = after.measurements.find(x => x.runId === m.runId);+ assert(next && canonical(next.origin) === canonical(m.origin), 'Keep each measured result and its original provenance.');+ if (canonical(m) !== canonical(next)) {+ let state = m;+ for (const e of changes.filter(x => x.runId === m.runId && x.action === 'measurement')) {+ assert(canonical(e.before) === canonical(state), 'Measurement corrections must keep their previous value.'); state = e.after;+ }+ assert(canonical(state) === canonical(next), 'Use a logged correction or exclusion with a reason to change a measured result.');+ }+ }+ if (before.measurements.length && canonical(before.model) !== canonical(after.model)) assert(changes.some(x => x.action === 'model' && canonical(x.before) === canonical(before.model) && canonical(x.after) === canonical(after.model)), 'Record the reason for changing a model after seeing data.');+ return after;+}+export function history(initial, limit = 24) {+ let items = [clone(initial)], at = 0;+ return {get value() {return clone(items[at]);}, get canUndo() {return at > 0;}, get canRedo() {return at < items.length - 1;},+ push(x) {items = items.slice(0, at + 1); items.push(clone(x)); if (items.length > limit) items.shift(); at = items.length - 1; return this.value;},+ undo() {at = Math.max(0, at - 1); return this.value;}, redo() {at = Math.min(items.length - 1, at + 1); return this.value;}};+}diff --git a/store/agents/lab-bench/template/studio/reproduce.py b/store/agents/lab-bench/template/studio/reproduce.pynew file mode 100644index 000000000..4cc3b89d2--- /dev/null+++ b/store/agents/lab-bench/template/studio/reproduce.py@@ -0,0 +1,70 @@+"""Recompute the delivered primary OLS analysis using independent Python libraries.++Run in the delivery directory. This does not infer experimental validity from a model fit.+"""+import json+from pathlib import Path+import numpy as np+import scipy.stats as stats+import statsmodels.api as sm++root = Path(__file__).resolve().parent+analysis = json.loads((root / "analysis.json").read_text())+if not analysis["ok"]:+ raise SystemExit("No estimable primary model: " + analysis["issue"])+x = np.asarray(analysis["matrix"]["X"], dtype=float)+y = np.asarray(analysis["matrix"]["y"], dtype=float)+result = sm.OLS(y, x, missing="raise", hasconst=True).fit()+alpha = 1 - analysis["model"]["confidence"]+influence = result.get_influence()+report = {+ "method": "statsmodels OLS, exact delivered design matrix; conventional covariance",+ "run_ids": analysis["matrix"]["runIds"],+ "n": int(result.nobs), "df": int(result.df_resid),+ "coefficients": result.params.tolist(), "se": result.bse.tolist(),+ "intervals": result.conf_int(alpha=alpha).tolist(),+ "covariance": result.cov_params().tolist(),+ "rmse": float(np.sqrt(result.mse_resid)),+ "fitted": result.fittedvalues.tolist(), "residuals": result.resid.tolist(),+ "leverage": influence.hat_matrix_diag.tolist(),+ "studentized": influence.resid_studentized_internal.tolist(),+ "cook": influence.cooks_distance[0].tolist(),+ "critical": float(stats.t.ppf(1 - alpha / 2, result.df_resid)),+}+np.testing.assert_allclose(result.params, analysis["beta"], rtol=1e-8, atol=1e-8)+np.testing.assert_allclose(result.cov_params(), analysis["covariance"], rtol=1e-8, atol=1e-8)+np.testing.assert_allclose(result.fittedvalues, [r["fitted"] for r in analysis["residuals"]], rtol=1e-8, atol=1e-8)+np.testing.assert_allclose(influence.hat_matrix_diag, [r["leverage"] for r in analysis["residuals"]], rtol=1e-8, atol=1e-8)+if analysis["inferential"]:+ np.testing.assert_allclose(result.conf_int(alpha=alpha), [c["ci"] for c in analysis["coefficients"]], rtol=1e-7, atol=1e-7)+ np.testing.assert_allclose(influence.cooks_distance[0], [r["cook"] for r in analysis["residuals"]], rtol=1e-7, atol=1e-7)++project = json.loads((root / "project.signal.json").read_text())+confirmation_checks = []+for phase in project["phases"]:+ if phase["kind"] != "confirmation":+ continue+ snapshot = phase["snapshot"]+ old_x = np.asarray(snapshot["matrix"]["X"], dtype=float)+ old_y = np.asarray(snapshot["matrix"]["y"], dtype=float)+ frozen = sm.OLS(old_y, old_x, missing="raise", hasconst=True).fit()+ np.testing.assert_allclose(frozen.params, [c["value"] for c in snapshot["coefficients"]], rtol=1e-8, atol=1e-8)+ for point in snapshot["predictions"]:+ prediction = frozen.get_prediction(np.asarray([point["x"]])).summary_frame(alpha=1-snapshot["model"]["confidence"])+ np.testing.assert_allclose(float(prediction["mean"].iloc[0]), point["mean"], rtol=1e-8, atol=1e-8)+ np.testing.assert_allclose(prediction[["mean_ci_lower", "mean_ci_upper"]].iloc[0], point["meanCI"], rtol=1e-7, atol=1e-7)+ np.testing.assert_allclose(prediction[["obs_ci_lower", "obs_ci_upper"]].iloc[0], point["predictionCI"], rtol=1e-7, atol=1e-7)+ confirmation_checks.append({"phase": phase["id"], "predictions": len(snapshot["predictions"]), "training_revision": snapshot["trainingRevision"]})+report["frozen_confirmation_checks"] = confirmation_checks++def clean(value):+ if isinstance(value, float) and not np.isfinite(value):+ return None+ if isinstance(value, list):+ return [clean(v) for v in value]+ if isinstance(value, dict):+ return {k: clean(v) for k, v in value.items()}+ return value++(root / "reproduction.json").write_text(json.dumps(clean(report), indent=2, allow_nan=False) + "\n")+print(f"Verified {report['n']} measured runs, {len(result.params)} coefficients and uncertainty. Wrote reproduction.json.")diff --git a/store/agents/lab-bench/template/studio/requirements.txt b/store/agents/lab-bench/template/studio/requirements.txtnew file mode 100644index 000000000..af88f5ed7--- /dev/null+++ b/store/agents/lab-bench/template/studio/requirements.txt@@ -0,0 +1,4 @@+numpy==1.26.4+scipy==1.13.1+pandas==2.2.3+statsmodels==0.14.6diff --git a/store/agents/lab-bench/template/studio/shell.html b/store/agents/lab-bench/template/studio/shell.htmlnew file mode 100644index 000000000..2ce8b2c52--- /dev/null+++ b/store/agents/lab-bench/template/studio/shell.html@@ -0,0 +1,6 @@+<!doctype html>+<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><title>Signal — Lab Bench</title><!-- FAVICON --><style>/* STUDIO_CSS */</style></head>+<body><header class="topbar"><div class="brand"><span class="mark" aria-hidden="true"><!-- SIGNAL_ICON --></span><span>SIGNAL<small>LAB BENCH</small></span></div><div id="connection" class="connection">Opening experiment…</div><div class="header-actions"><button data-action="open">Open project</button><button data-action="save" id="save-source">Save to workspace</button><button class="primary" data-action="export">Export experiment ↗</button></div></header>+<div id="conflict" hidden></div><div class="workspace"><aside class="sidebar"><div class="eyebrow">Your experiment</div><h2 id="side-title"></h2><nav aria-label="Experiment workflow"><button data-tab="plan"><b>01</b> Plan the test</button><button data-tab="collect"><b>02</b> Collect evidence</button><button data-tab="analyze"><b>03</b> Understand</button><button data-tab="followup"><b>04</b> Next experiment</button></nav><div id="side-status"></div><div class="side-foot">A question. A fair test.<br>A decision you can explain.</div><button data-action="download-project">Download editable project</button></aside><main id="main"></main></div>+<div id="toast" role="status" aria-live="polite" hidden></div><dialog id="dialog"><div id="dialog-content"></div></dialog><input id="project-file" type="file" accept=".json,.signal.json,application/json" hidden><input id="csv-file" type="file" accept=".csv,text/csv" hidden>+<script id="signal-data" type="application/json">SIGNAL_DATA</script><script id="signal-app">/* SIGNAL_APP */</script></body></html>diff --git a/store/agents/lab-bench/template/studio/style.css b/store/agents/lab-bench/template/studio/style.cssnew file mode 100644index 000000000..b8e631ea2--- /dev/null+++ b/store/agents/lab-bench/template/studio/style.css@@ -0,0 +1,5 @@+[hidden]{display:none!important}*{box-sizing:border-box}body{margin:0;background:#eef1e9;color:#183f3b;font-family:Inter,ui-sans-serif,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;font-size:14px;line-height:1.5}button,input,select,textarea{font:inherit;color:inherit}button{cursor:pointer;border:1px solid #ccd8ce;background:#fffefa;padding:10px 15px;border-radius:7px;font-weight:600;line-height:1.35}button:hover{background:#e5eee3}button:disabled{opacity:.48;cursor:default}button.primary{background:#0b736d;border-color:#0b736d;color:white}button.primary:hover{background:#075d59}.quiet{background:none}.danger{color:#a64431}button:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible{outline:3px solid #dc9b38;outline-offset:3px}input,textarea,select{display:block;width:100%;background:#fffefa;border:1px solid #c8d4c9;border-radius:6px;padding:9px 11px;min-height:40px}textarea{resize:vertical;line-height:1.5}input[type=checkbox]{display:inline-block;min-height:0;width:17px;height:17px;vertical-align:middle;accent-color:#0b736d}input[type=range]{padding:0;accent-color:#0b736d}label{display:block;font-size:12px;font-weight:650;letter-spacing:.1px}label input,label select,label textarea{margin-top:5px;font-size:14px;font-weight:400}label:has(input[type=checkbox]){display:flex;align-items:center;gap:9px;font-size:14px;letter-spacing:0}.topbar{display:flex;align-items:center;gap:24px;min-height:88px;padding:18px 30px;background:#fbfcf6;border-bottom:1px solid #cedbd0;position:relative;z-index:2}.brand{display:flex;align-items:center;gap:12px;font-size:21px;font-weight:800;letter-spacing:3px}.brand small{display:block;font-size:8px;letter-spacing:3.4px;font-weight:600}.mark{width:40px;height:40px;display:flex}.mark svg{width:100%;height:100%}.connection{font-size:11px;color:#557569;margin-left:auto;max-width:225px}.header-actions{display:flex;gap:8px}.header-actions button{font-size:12px;padding:10px 12px}.workspace{display:grid;grid-template-columns:236px minmax(0,1fr);max-width:1720px;margin:auto;min-height:calc(100vh - 88px)}.sidebar{padding:31px 24px;border-right:1px solid #cfdbcf;display:flex;flex-direction:column;align-items:stretch;gap:20px;background:#e5eadf}.sidebar h2{font-size:19px;font-weight:650;line-height:1.3;margin:-8px 0 12px;overflow-wrap:anywhere}.eyebrow{text-transform:uppercase;font-size:10px;letter-spacing:1.6px;font-weight:700;color:#578073}.sidebar nav{display:flex;flex-direction:column;gap:5px;margin:0 -10px}.sidebar nav button{display:flex;gap:13px;text-align:left;border-color:transparent;background:none;font-size:13px;padding:14px 12px}.sidebar nav button b{font-size:10px;font-weight:500;line-height:20px;opacity:.65}.sidebar nav button.active{background:#143f39;color:#fafbf4}.side-foot{margin-top:auto;font-family:Georgia,serif;font-size:17px;line-height:1.5;padding-top:35px;color:#6b8171}.sidebar>button{font-size:11px;background:none}.side-count{display:flex;align-items:baseline;gap:6px;margin:20px 0 8px}.side-count strong{font-size:34px;font-weight:550}.progress{height:5px;border-radius:4px;background:#cbd8c9;overflow:hidden}.progress span{display:block;height:100%;background:#0b736d}.small,.muted{color:#678174;font-size:12px}.side-note{font-size:11px;margin-top:12px;line-height:1.7}main{min-width:0;padding:34px 38px 70px}.hero{display:flex;align-items:flex-start;gap:30px;justify-content:space-between;margin-bottom:25px}.hero h1{font-family:Georgia,"Times New Roman",serif;font-size:42px;line-height:1.09;font-weight:400;letter-spacing:-1.4px;margin:9px 0 13px;max-width:850px}.hero p{color:#607e70;margin:0;max-width:720px;font-size:14px}.stage-number{font-size:72px;line-height:1;font-family:Georgia,serif;color:#bdccba;margin-top:13px}.metrics{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin-bottom:24px}.metric{border:1px solid #d3dece;border-radius:8px;padding:16px 18px;background:#f6f8f0}.metric strong{display:block;font-size:31px;line-height:1.2;font-weight:550;letter-spacing:-1px}.metric span{display:block;color:#627c6b;font-size:11px;margin-top:6px}.metric.accent{background:#d5e0bd;border-color:#c9d6b0}.card{background:#fbfcf6;border:1px solid #d2ddcd;border-radius:10px;padding:23px;margin-bottom:18px;min-width:0}.card h2{font-size:18px;letter-spacing:-.4px;margin:0 0 15px;font-weight:650}.card h3{font-size:14px;margin:0 0 12px}.section-head{display:flex;align-items:center;justify-content:space-between;gap:15px;margin-bottom:12px}.section-head h2{margin:0}.actions{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.two-col{display:grid;grid-template-columns:minmax(0,1.35fr) minmax(270px,1fr);gap:20px}.form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:15px}.span-all{grid-column:1/-1}.factor-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}.factor{padding:17px;background:#eff3e9;border:1px solid #d5dfce;border-radius:8px}.factor .form-grid{gap:10px}.factor-head{display:flex;justify-content:space-between;align-items:center;margin-bottom:10px}.factor-head strong{font-size:11px;letter-spacing:1px;color:#72916d}.factor-head button{padding:3px 7px;font-size:11px;border:0;background:none}.helper{color:#667e70;font-size:12px;margin:8px 0 0}.strip{border:1px solid #d4dfcd;background:#eaf0df;border-radius:8px;padding:15px 18px;margin:15px 0;line-height:1.55;font-size:13px}.strip.warn{background:#f7ebd6;border-color:#e7d2a9;color:#745927}.strip strong{display:block;margin-bottom:3px}.pill{display:inline-block;font-size:10px;padding:3px 8px;border-radius:20px;background:#e4edda;color:#56704c;white-space:nowrap}.pill.warn{background:#f2dfb9;color:#795923}.pill.dark{background:#1b534a;color:white}.table-scroll{max-width:100%;overflow:auto}.table-scroll table{min-width:650px}table{width:100%;border-collapse:collapse;font-size:12px}th{text-align:left;font-size:10px;text-transform:uppercase;letter-spacing:.6px;color:#6a826f;padding:11px 12px;background:#edf2e6;border-bottom:1px solid #c8d6c4;white-space:nowrap}td{padding:12px;border-bottom:1px solid #e0e7d9;vertical-align:top}td strong{font-weight:600}tr[data-run]{cursor:pointer}tr[data-run]:hover{background:#edf3e5}td button{font-size:11px;padding:5px 9px;white-space:nowrap}.state-measured{color:#0b736d}.state-pending{color:#8b9780}.state-excluded{color:#a66639}.chart svg{width:100%;height:auto;max-height:440px;display:block}.legend{display:flex;gap:13px;flex-wrap:wrap;margin-top:9px;font-size:10px;color:#557565}.dot{display:inline-block;height:8px;width:8px;border-radius:50%;margin-right:5px}.empty{padding:55px 25px;text-align:center;background:linear-gradient(125deg,#edf2e6,#f8f8ed);border:1px dashed #bccfb4;border-radius:10px}.empty h2{font-family:Georgia,serif;font-size:28px;font-weight:400;margin:0 0 12px}.empty p{max-width:540px;margin:0 auto 22px;color:#658170}.terms{display:grid;gap:9px;margin-bottom:20px}.tabs{display:flex;gap:5px;padding:4px;background:#e8eee0;border-radius:7px}.tabs button{background:none;border:0;font-size:11px;padding:7px 11px}.tabs button.selected{background:#fffefa;box-shadow:0 1px 4px #173b3520}.prediction{background:#173f3a;border-radius:10px;color:#f5f9e9;padding:23px}.prediction .eyebrow{color:#adc5a4}.prediction .value{font-size:45px;letter-spacing:-1.5px;margin:6px 0}.prediction small{color:#abc5ae}.comparison{background:#dce7c3;padding:21px;border-radius:9px;margin-top:16px}.comparison strong{font-size:28px;font-weight:500}.candidate-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:15px}.candidate-title{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px}.candidate-title h3{margin:0}.setting{margin-bottom:15px}.setting .setting-fields{display:flex;gap:12px;align-items:center}.setting input[type=number]{max-width:100px}.ranked td:nth-child(2){font-variant-numeric:tabular-nums;white-space:nowrap}details>summary{cursor:pointer;font-weight:600;font-size:13px;color:#497264;padding:7px 0}details[open]>summary{margin-bottom:12px}dialog{width:min(720px,calc(100vw - 30px));max-height:90vh;overflow:auto;border:1px solid #bfd1bc;padding:28px;border-radius:12px;background:#fcfcf6;color:#183f3b;box-shadow:0 25px 90px #12392e40}dialog::backdrop{background:#14383177;backdrop-filter:blur(3px)}dialog h2{font-family:Georgia,serif;font-weight:400;font-size:29px;margin:0 0 13px}dialog .actions{justify-content:flex-end;margin-top:24px}#toast{position:fixed;right:25px;bottom:24px;max-width:min(650px,calc(100vw - 30px));background:#173f3a;color:#fffefa;padding:15px 20px;border-radius:9px;box-shadow:0 7px 30px #12392e30;font-size:13px;z-index:10}#toast.error{background:#854733}#conflict{padding:16px 30px;background:#f4dfb5;border-bottom:1px solid #d8bb7f;font-size:13px}#conflict .actions{display:inline-flex;margin-left:20px}#conflict button{font-size:11px}.check-row{padding:11px 0;border-bottom:1px solid #dfe6d8;display:flex;justify-content:space-between;gap:18px;font-size:12px}.check-row>span:last-child{text-align:right}.audit-row{padding:12px 0;border-bottom:1px solid #dfe6d8}.audit-row small{color:#789078;display:block;margin-top:4px}.wrap{overflow-wrap:anywhere}.measure-value{font-size:35px;font-variant-numeric:tabular-nums}.plot-tip{font-size:12px;min-height:21px;color:#496f61;margin-top:8px}.report-actions{margin-top:22px}.visually-hidden{position:absolute;width:1px;height:1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}+@media(min-width:1450px){main{padding:40px 52px}.hero h1{font-size:48px}.sidebar{padding:37px 25px}}@media(max-width:1100px){.topbar{padding:15px 20px;gap:15px}.connection{display:none}.header-actions{margin-left:auto}.workspace{grid-template-columns:190px minmax(0,1fr)}.sidebar{padding:25px 16px}main{padding:27px 24px}.two-col{grid-template-columns:1fr}.hero h1{font-size:36px}.stage-number{font-size:60px}}@media(max-width:760px){.topbar{flex-wrap:wrap;padding:15px;gap:12px}.brand{font-size:17px}.brand .mark{width:30px;height:30px}.header-actions{width:100%;display:grid;grid-template-columns:1fr 1fr 1.1fr}.header-actions button{font-size:10px;padding:9px 5px}.workspace{display:block}.sidebar{border-right:0;border-bottom:1px solid #cfdbcf;padding:12px 15px;display:block}.sidebar>.eyebrow,.sidebar>h2,#side-status,.side-foot,.sidebar>button{display:none}.sidebar nav{margin:0;flex-direction:row;gap:4px;justify-content:space-between}.sidebar nav button{font-size:10px;padding:9px 6px;gap:5px;flex:1}.sidebar nav button b{display:none}main{padding:25px 16px 65px}.hero{gap:10px}.hero h1{font-size:32px}.hero p{font-size:12px}.stage-number{font-size:42px}.metrics{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.metric{padding:13px}.metric strong{font-size:26px}.card{padding:17px}.form-grid,.factor-grid,.candidate-grid{grid-template-columns:1fr}.span-all{grid-column:auto}.chart svg{min-height:180px}.section-head{align-items:flex-start;flex-direction:column}.two-col{gap:0}.tabs{flex-wrap:wrap}.candidate-title{margin-top:7px}#conflict{padding:14px}#conflict .actions{margin:10px 0 0}.prediction .value{font-size:37px}}++#plan-form label:has([name="question"]),#plan-form label:has([name="steps"]),#plan-form label:has([name="controls"]){grid-column:1/-1}.factor .form-grid{grid-template-columns:1fr}#plan-form label:has([name="blocks"]){grid-column:1/-1}+.two-col>*,.candidate-grid>*,.form-grid>*{min-width:0}input,textarea,select{max-width:100%;min-width:0}@media(max-width:1100px){.two-col{grid-template-columns:minmax(0,1fr)}}diff --git a/store/agents/lab-bench/template/tools/build.mjs b/store/agents/lab-bench/template/tools/build.mjsnew file mode 100644index 000000000..8f2208460--- /dev/null+++ b/store/agents/lab-bench/template/tools/build.mjs@@ -0,0 +1,37 @@+#!/usr/bin/env node+import {readFile, writeFile, mkdir, realpath, access} from 'node:fs/promises';+import {resolve, join, dirname, sep} from 'node:path';+import {fileURLToPath, pathToFileURL} from 'node:url';+import {validateProject, digest} from '../studio/project.mjs';+import {verifySources} from '../studio/measurements.mjs';+export async function readProject(workspace) {+ const root = await realpath(workspace), path = await realpath(join(root, 'bench/project.json'));+ if (!path.startsWith(join(root, 'bench') + sep)) throw new Error('Keep source inside bench/.');+ return verifySources(JSON.parse(await readFile(path, 'utf8')));+}+export async function toolsDirectory() {+ for (const path of [process.env.LAB_DSH_DIR && join(process.env.LAB_DSH_DIR, 'toolchain'), fileURLToPath(new URL('../../toolchain/', import.meta.url))].filter(Boolean)) {+ try {await access(join(path, 'node_modules/esbuild/lib/main.js')); return path;} catch {}+ }+ throw new Error('Run Lab Bench setup. Set LAB_DSH_DIR when building an installed workspace.');+}+export async function buildBench(workspace, {check = false, project: provided} = {}) {+ const root = resolve(workspace), project = provided ? await verifySources(provided) : await readProject(root);+ project.revision = await digest(project);+ const tools = await toolsDirectory(), {build} = await import(pathToFileURL(join(tools, 'node_modules/esbuild/lib/main.js')).href);+ const app = await build({entryPoints: [join(root, 'studio/app.js')], bundle: true, write: false, format: 'iife', minify: true, target: 'es2022', legalComments: 'inline'});+ const read = name => readFile(join(root, 'studio', name), 'utf8');+ const [shell, css, icon, reproduce, requirements, licenses] = await Promise.all(['shell.html', 'style.css', 'icon.svg', 'reproduce.py', 'requirements.txt', 'THIRD_PARTY_LICENSES.txt'].map(read));+ const license = await readFile(join(tools, '../LICENSE'), 'utf8');+ const assets = {reproduce, requirements, licenses, license};+ const html = shell.replace('/* STUDIO_CSS */', () => css).replace('<!-- SIGNAL_ICON -->', () => icon)+ .replace('<!-- FAVICON -->', () => `<link rel="icon" href="data:image/svg+xml,${encodeURIComponent(icon)}">`)+ .replace('SIGNAL_DATA', () => JSON.stringify({project, assets}).replace(/</g, '\\u003c'))+ .replace('/* SIGNAL_APP */', () => app.outputFiles[0].text.replace(/<\/script/gi, '<\\/script'));+ if (provided) return {html, project, assets};+ const target = join(root, 'bench/index.html');+ if (check) {if (await readFile(target, 'utf8') !== html) throw new Error('Lab studio is stale. Run node tools/build.mjs.');}+ else {await writeFile(target, html); await mkdir(join(root, '.harness'), {recursive: true}); await writeFile(join(root, '.harness/verdict.json'), JSON.stringify({spec: 1, ready: false, artifact: 'bench/index.html', summary: project.title + ' built; measurement, model and report review pending'}) + '\n');}+ return {title: project.title, revision: project.revision};+}+if (process.argv[1] && await realpath(process.argv[1]).catch(() => null) === fileURLToPath(import.meta.url)) console.log(JSON.stringify(await buildBench(resolve(dirname(fileURLToPath(import.meta.url)), '..'), {check: process.argv.includes('--check')})));diff --git a/store/agents/lab-bench/template/tools/check.mjs b/store/agents/lab-bench/template/tools/check.mjsindex 6bc6e9651..1288fd95c 100644--- a/store/agents/lab-bench/template/tools/check.mjs+++ b/store/agents/lab-bench/template/tools/check.mjs@@ -1,75 +1,16 @@-const CONFIG = {"id":"lab-bench","artifact":"bench/index.html"};-// Compiled into each workspace's tools/check.mjs. Tests the model in the ACTUAL edited HTML.-import { readFile, mkdir, writeFile } from "node:fs/promises";-import { createHash } from "node:crypto";-import vm from "node:vm";-import { resolve, dirname } from "node:path";--const args = process.argv.slice(2),- i = args.indexOf("--seeds");-const count = i === -1 ? 32 : Number(args[i + 1]);-if (!Number.isInteger(count) || count < 1 || count > 1000)- throw new Error("--seeds must be an integer from 1 to 1000");-const artifact = resolve(CONFIG.artifact);-const html = await readFile(artifact, "utf8");-const script = html.match(- /<script id="harness-model">([\s\S]*?)<\/script>/,-)?.[1];-if (!script)- throw new Error(- 'Keep the pure model in <script id="harness-model"> so this checker can exercise the actual artifact.',- );-const expressions = {- "generative-art": `const m=artModel(SEED);const p=artPaths(m);({state:m,valid:p.length>0&&p.flat().every(([x,y])=>Number.isFinite(x)&&Number.isFinite(y)),metrics:{paths:p.length,palette:m.palette}})`,- "creative-direction": `const m=directionModel(SEED);const ratio=contrast(m.colors[0],m.colors[1]);({state:m,valid:ratio>=4.5,metrics:{direction:m.name,contrast:ratio}})`,- "lab-bench": `const p=experiment(SEED),e=treatmentEffect(p);({state:p,valid:p.length>1&&p.every(p=>Number.isFinite(p.x)&&Number.isFinite(p.y))&&Number.isFinite(e.low)&&e.low<=e.high,metrics:{samples:p.length,effect:e.difference,interval:[e.low,e.high]}})`,- "music-studio": `const s=musicScore(SEED),r=renderMusic(s);({state:Array.from(r.samples),valid:r.peak>.001&&r.peak<=.95&&r.samples.every(Number.isFinite),metrics:{seconds:r.duration,peak:r.peak,rms:r.rms}})`,- "game-master": `const m=arenaMatch(SEED),s=m.history.at(-1);({state:m,valid:m.history.length>1&&m.history.length<=10000&&s.units.every(u=>u.hp>=0&&u.x>=0&&u.x<m.map.w&&u.y>=0&&u.y<m.map.h),metrics:{turns:s.turn,score:s.score,winner:m.winner}})`,- "drone-pilot": `const s=flyAutopilot(SEED);({state:s,valid:s.finished&&!s.crashed&&s.passed===flightCourse(SEED).length,metrics:{seconds:s.time,passed:s.passed,missed:s.missed}})`,- "voxel-worlds": `const w=voxelWorld(SEED);let p={...w.spawn,vy:0,grounded:true};const clear=playerFits(w,p.x,p.y,p.z);for(let t=0;t<120;t++)p=movePlayer(w,p,{forward:1});({state:Array.from(w.blocks),valid:clear&&playerFits(w,p.x,p.y,p.z),metrics:{blocks:w.blocks.filter(Boolean).length,walkDistance:Math.hypot(p.x-w.spawn.x,p.z-w.spawn.z)}})`,-};-const expression = expressions[CONFIG.id];-const digest = (value) =>- createHash("sha256").update(JSON.stringify(value)).digest("hex");-const results = [];-for (let seed = 0; seed < count; seed++) {- const run = () =>- vm.runInNewContext(- `${script}\n${expression}`,- { SEED: String(seed) },- { timeout: 10000 },- );- try {- const first = run(),- second = run(),- signature = digest(first.state),- repeat = digest(second.state);- results.push({- seed,- ok: first.valid && signature === repeat,- signature,- metrics: first.metrics,- });- } catch (error) {- results.push({ seed, ok: false, error: error.message });- }+#!/usr/bin/env node+import {writeFile, mkdir, realpath} from 'node:fs/promises';+import {resolve, join, dirname} from 'node:path';+import {fileURLToPath} from 'node:url';+import {readProject} from './build.mjs';+import {plannedAnalysis, fitProject, confirmationResults} from '../studio/analysis.mjs';+import {canonical, digest} from '../studio/project.mjs';+export async function checkBench(workspace) {+ const p = await readProject(workspace), fit = fitProject(p), repeated = canonical(fit) === canonical(fitProject(p));+ if (!repeated) throw new Error('The same source produced different analysis.');+ const report = {title: p.title, revision: await digest(p), sourceHashesVerified: p.sources.length, planned: plannedAnalysis(p), analysis: fit, confirmations: confirmationResults(p), repeated,+ scope: 'Checks source integrity, design identifiability and reproducible calculations. Does not establish experimental validity or empirical results without actual measurement and review.'};+ await mkdir(join(workspace, '.harness'), {recursive: true}); await writeFile(join(workspace, '.harness/lab-check.json'), JSON.stringify(report, null, 2) + '\n');+ return {title: p.title, runs: p.runs.length, measured: p.measurements.length, model: fit.ok ? 'estimable' : fit.issue, repeated};}-const passed = results.filter((r) => r.ok).length;-const report = {- spec: 1,- harness: CONFIG.id,- artifact: CONFIG.artifact,- checkedAt: new Date().toISOString(),- modelChecks: { passed, total: count },- scope:- "Pure model invariants and same-process repeatability. Browser interaction, layout, listening and export review still required.",- results,-};-const out = resolve(".harness/model-check.json");-await mkdir(dirname(out), { recursive: true });-await writeFile(out, JSON.stringify(report, null, 2) + "\n");-console.log(- `${CONFIG.id}: ${passed}/${count} model checks passed. Report: ${out}`,-);-console.log(report.scope);-if (passed !== count) process.exitCode = 1;+if (process.argv[1] && await realpath(process.argv[1]).catch(() => null) === fileURLToPath(import.meta.url)) console.log(JSON.stringify(await checkBench(resolve(dirname(fileURLToPath(import.meta.url)), '..'))));diff --git a/store/agents/lab-bench/template/tools/export.mjs b/store/agents/lab-bench/template/tools/export.mjsnew file mode 100644index 000000000..cbfb1331f--- /dev/null+++ b/store/agents/lab-bench/template/tools/export.mjs@@ -0,0 +1,21 @@+#!/usr/bin/env node+import {mkdir, writeFile, readFile, realpath} from 'node:fs/promises';+import {resolve, join, dirname} from 'node:path';+import {fileURLToPath, pathToFileURL} from 'node:url';+import {readProject, buildBench, toolsDirectory} from './build.mjs';+import {kitFiles, esc} from '../studio/formats.mjs';+import {zipFiles} from '../studio/archive.mjs';+export async function exportBench(workspace, destination, {project: provided, pdf = true} = {}) {+ const root = resolve(workspace), out = resolve(destination), project = provided ?? await readProject(root);+ const {html, assets} = await buildBench(root, {project}), files = kitFiles(project, html, assets); await mkdir(out, {recursive: true});+ for (const [name, body] of Object.entries(files)) {const path = join(out, name); await mkdir(dirname(path), {recursive: true}); await writeFile(path, body);}+ if (pdf) {+ const tools = await toolsDirectory(), {chromium} = await import(pathToFileURL(join(tools, 'node_modules/playwright-core/index.mjs')).href), {browserPath} = await import(pathToFileURL(join(tools, 'browser.mjs')).href);+ const browser = await chromium.launch({executablePath: await browserPath(), headless: true});+ try {const page = await browser.newPage(); for (const name of ['report', 'collection-sheet']) {await page.goto(pathToFileURL(join(out, name + '.html')).href); await page.pdf({path: join(out, name + '.pdf'), printBackground: true, preferCSSPageSize: true, displayHeaderFooter: true, headerTemplate: '<span></span>', footerTemplate: `<div style="width:100%;padding:0 15mm;font-family:Arial;font-size:8px;color:#526f67;display:flex;justify-content:space-between"><span>${esc(project.title)} · ${name === 'report' ? 'Experiment report' : 'Collection sheet'}</span><span><span class="pageNumber"></span> / <span class="totalPages"></span></span></div>`}); files[name + '.pdf'] = await readFile(join(out, name + '.pdf'));}}+ finally {await browser.close();}+ }+ await writeFile(join(out, 'experiment-kit.zip'), new Uint8Array(await zipFiles(files).arrayBuffer()));+ return {title: project.title, destination: out, files: Object.keys(files)};+}+if (process.argv[1] && await realpath(process.argv[1]).catch(() => null) === fileURLToPath(import.meta.url)) {const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); console.log(JSON.stringify(await exportBench(root, process.argv[2] ?? join(root, 'delivery'))));}diff --git a/store/agents/lab-bench/test/ACCEPTANCE.md b/store/agents/lab-bench/test/ACCEPTANCE.mdnew file mode 100644index 000000000..d6359cbd5--- /dev/null+++ b/store/agents/lab-bench/test/ACCEPTANCE.md@@ -0,0 +1,101 @@+# Signal acceptance — 2026-09-20++The rebuilt Lab Bench helps a person plan an experiment, collect their measurements, inspect a+declared model and prepare a follow-up. The initial coffee project contains no measurements.+Original logos/icons and the earlier synthetic viewer remain in the repository. Acceptance+response files are explicitly synthetic fixtures, labeled in the studio, reports and Store+examples. They do not establish physical findings or installed-agent prompt completion.++## Observed workflows++- Actual Chrome input edits a plan, saves source and retains its earlier edition. Source conflicts+ and malformed agent edits preserve the browser draft; reloading restores local changes.+- Protocol approval protects factors, response, procedure, run settings and original allocation.+ Collecting a first measurement also freezes the design. Later phases append their own runs.+- Actual file upload previews mapped CSV columns and units, then commits atomically. Unknown or+ duplicate run ids, wrong settings, wrong units and nonfinite values are rejected. Blank responses+ remain pending. Original UTF-8 bytes, SHA-256, physical row numbers and mappings survive delivery.+- Corrections and exclusions retain the original observation and a reasoned history. The+ all-recorded sensitivity fit includes excluded training rows. Diagnostics never delete data.+- A rank-deficient quadratic model is repaired through the real follow-up controls, new settings+ and a fresh CSV. Unsupported rank, residual degrees of freedom and conditioning stop inference.+- Comparison controls freeze forecasts for a confirmation phase; its fresh measurements remain+ outside the training fit. Extension phases explicitly add new observations to the model.+- Browser ZIP exports reopen offline with their complete source. Numeric, categorical and fixed+ block controls work in all six delivered editions. All four stages fit a 390px viewport in each+ edition: 24 responsive views, no horizontal document overflow and no page errors.+- The source bridge checks same-origin JSON writes and revisions, saves history, compiles before+ replacement, and rejects a concurrent writer while the first body is still arriving. Actual+ build/check entry points also run through symlinked workspace paths.++The shared browser runner additionally verifies sibling fetch, localStorage, ES modules and+missing-artifact recovery in the shared web viewer. Signal uses its own local source bridge.++## Three authored briefs, six delivered editions++| Brief | Design | Targeted revision | Primary training rows before → after |+| --- | --- | --- | ---: |+| Clearwater Coffee | Two numeric factors, interaction, independent jars, scheduled midpoint controls | Two new settings, three held-out confirmations each; frozen training fit unchanged | 15 → 15 |+| Canopy Seedlings | Three media, two water levels, two complete shelf blocks | Logged instrument exclusion, exploratory medium × water interaction, all-recorded sensitivity fit | 24 → 23 |+| Fold Paperworks | Two three-level factors, interaction and two quadratic terms | Two new interior settings, two independent observations each, added to training | 18 → 22 |++Approved factor definitions, response, procedure, original runs and original CSVs are unchanged+across each revision. Every edition includes a portable editable studio, project, original files,+collection CSV, measurements, design matrix, analysis, SVG figures, audit, printable sheets and+report, actual PDFs, a complete ZIP, and a Python reproduction script. Confirmations also carry+the original training matrix, coefficients, covariance and forecasts.++`test/verify-delivery.py` independently constructs the coded matrix from the project schema and+uses statsmodels 0.14.6 / SciPy 1.13.1 to check coefficients, covariance, standard errors,+pointwise intervals, residuals, studentization, leverage, Cook's distance, leave-one-out RMSE,+comparisons and predictions. It executes the delivered reproduction script, verifies ZIP contents,+raw source hashes/rows, SVG XML, A4 sizes, PDF text bounds, units and every collection run id.+All six editions pass. Their **12 PDFs / 48 pages** were rendered with Poppler and visually+reviewed. Report charts have block legends and readable integer run-order labels; the observation+summary clearly identifies its first eight rows while the complete data remain in the kit.++Local evidence:++- `/private/tmp/signal-shared-browser/browser-results.json`: shared viewer and seven Signal browser workflows pass.+- `/private/tmp/signal-acceptance-release/acceptance.json`: six exported editions and preserved approved-source hashes.+- `/private/tmp/signal-acceptance-release/independent-verification.json`: independent reader, all six editions, 48 PDF pages.+- `/private/tmp/signal-acceptance-release/browser-reopening.json`: six offline deliveries and 24 responsive views.+- `/private/tmp/signal-print-release/`: final rendered print review.++The 27 package tests, generated-artifact/math-bundle/branding checks, Store catalog/conformance+checks and 421 CLI Store/check tests pass locally. CI repeats package, browser, six-delivery,+offline-reopening and independent-reader checks. Store screenshots come from these actual+reopened deliveries, with the synthetic-data notice visible.++## Reproduce++```sh+sh store/agents/lab-bench/toolchain/setup.sh+node store/agents/lab-bench/toolchain/build-math.mjs --check+node --test store/agents/lab-bench/test/*.test.mjs+node store/agents/lab-bench/test/browser.mjs+node store/agents/lab-bench/test/acceptance.mjs+node store/agents/lab-bench/test/reopen-deliveries.mjs work/experience-evidence/signal-acceptance+python3 -m venv /tmp/signal-statistics-reader+/tmp/signal-statistics-reader/bin/pip install -r store/agents/lab-bench/template/studio/requirements.txt+/tmp/signal-statistics-reader/bin/python store/agents/lab-bench/test/verify-delivery.py work/experience-evidence/signal-acceptance+```++The independent reader requires Python with wheels for the pinned packages and Poppler's+`pdfinfo`/`pdftotext`; CI uses Python 3.12. The product itself does not require Python.++## Method and remaining scope++Complete factorial continuous-response experiments: 1–6 factors, numeric or categorical levels,+independent repetitions, complete fixed blocks, main effects, two-factor interactions and numeric+quadratics. Limits include 512 runs, 48 expanded model columns and 5 MB complete source. SVD+guards rank/conditioning; ordinary least-squares intervals assume independent units, a suitable+mean model, constant variance and approximately normal errors. Intervals are pointwise and do+not adjust for searching settings. Planned-range checks do not prove empirical support throughout+the range. Near-zero residual variation withholds intervals and confirmation forecasts.++No physical experiment, instrument control, clinical trial, mixed/repeated/GLM model, fractional+design, general causal inference, automatic optimum, customer result, real printer or+installed-agent prompt trial is claimed. Chrome and an emulated narrow viewport were exercised;+other browsers and actual phones remain unmeasured. Passing software checks is evidence of the+tested workflow and calculations, not evidence that a practical experimental conclusion is true.diff --git a/store/agents/lab-bench/test/acceptance.mjs b/store/agents/lab-bench/test/acceptance.mjsnew file mode 100644index 000000000..f0f64cee1--- /dev/null+++ b/store/agents/lab-bench/test/acceptance.mjs@@ -0,0 +1,23 @@+import assert from 'node:assert/strict';+import {mkdir, writeFile} from 'node:fs/promises';+import {resolve, join} from 'node:path';+import {fileURLToPath} from 'node:url';+import {measured, revised, kinds} from './fixtures.mjs';+import {validateTransition, canonical, digest} from '../template/studio/project.mjs';+import {fitProject} from '../template/studio/analysis.mjs';+import {exportBench} from '../template/tools/export.mjs';+const pkg = fileURLToPath(new URL('..', import.meta.url)), output = resolve(process.env.LAB_ACCEPTANCE_ROOT ?? 'work/experience-evidence/signal-acceptance');+await mkdir(output, {recursive: true}); const results = [];+for (const kind of kinds) {+ const before = await measured(kind), after = await revised(before, kind); validateTransition(before, after);+ const approved = {factors: before.factors, protocol: before.protocol, response: before.response, design: before.design, runs: before.runs};+ assert.equal(canonical({...approved, factors: after.factors, protocol: after.protocol, response: after.response, design: after.design, runs: after.runs.slice(0, before.runs.length)}), canonical(approved));+ for (const [edition, project] of [['before', before], ['after', after]]) {+ const destination = join(output, kind + '-' + edition), report = await exportBench(join(pkg, 'template'), destination, {project});+ const fit = fitProject(project); assert.equal(fit.ok, true);+ results.push({kind, edition, title: project.title, destination, measured: project.measurements.length, training: fit.n, df: fit.df, parameters: fit.parameters, heldOut: fit.confirmation, excluded: fit.excluded, approvedHash: await digest(approved), files: report.files});+ console.log(`${kind}/${edition}: ${project.measurements.length} measured, ${fit.n} training, ${fit.parameters} coefficients; ${report.files.length} delivered files.`);+ }+}+await writeFile(join(output, 'acceptance.json'), JSON.stringify({scope: 'Authored briefs and explicitly synthetic response fixtures; not actual experiments or installed-agent prompt trials.', results}, null, 2));+console.log(JSON.stringify({output, deliveries: results.length}));diff --git a/store/agents/lab-bench/test/browser.mjs b/store/agents/lab-bench/test/browser.mjsnew file mode 100644index 000000000..16816e749--- /dev/null+++ b/store/agents/lab-bench/test/browser.mjs@@ -0,0 +1,96 @@+import assert from 'node:assert/strict';+import {mkdir, mkdtemp, cp, readFile, writeFile, readdir} from 'node:fs/promises';+import {join, resolve} from 'node:path';+import {fileURLToPath, pathToFileURL} from 'node:url';+import {execFileSync} from 'node:child_process';+import {chromium} from '../toolchain/node_modules/playwright-core/index.mjs';+import {browserPath} from '../toolchain/browser.mjs';+import {createBenchViewer} from '../viewer/viewer.mjs';+import {buildBench} from '../template/tools/build.mjs';+import {fitProject} from '../template/studio/analysis.mjs';+import {canonical} from '../template/studio/project.mjs';+import {syntheticCSV} from './fixtures.mjs';++const pkg = fileURLToPath(new URL('..', import.meta.url)), output = resolve(process.env.LAB_QA_ROOT ?? 'work/experience-evidence/signal-browser');+await mkdir(output, {recursive: true}); const workspace = await mkdtemp(join(output, 'workspace-')); await cp(join(pkg, 'template'), workspace, {recursive: true});+process.env.LAB_DSH_DIR = pkg; await buildBench(workspace);+const server = await createBenchViewer(workspace); await new Promise(r => server.listen(0, '127.0.0.1', r));+const url = 'http://127.0.0.1:' + server.address().port, browser = await chromium.launch({headless: true, executablePath: await browserPath()});+const errors = [], checks = []; let sequence = 0, page;+const check = (name, detail = {}) => {checks.push({name, ok: true, ...detail}); console.log('ok ' + name);};+async function downloadFrom(page, selector, name) {const wait = page.waitForEvent('download'); await page.locator(selector).click(); const download = await wait, path = join(output, name ?? String(++sequence) + '-' + download.suggestedFilename()); await download.saveAs(path); return path;}+async function snapshot(page) {return JSON.parse(await readFile(await downloadFrom(page, '.sidebar>button[data-action="download-project"]'), 'utf8'));}+async function nav(name) {await page.locator('.sidebar [data-tab="' + name + '"]').click();}+async function importCSV(bytes, name = 'synthetic-observations.csv') {+ await nav('collect'); await page.locator('#csv-file').setInputFiles({name, mimeType: 'text/csv', buffer: Buffer.from(bytes)});+ await page.locator('#import-form button[type="submit"]').click(); await page.waitForSelector('#commit-import:enabled'); await page.locator('#commit-import').click(); await page.waitForSelector('#dialog', {state: 'hidden'});+}+try {+ page = await browser.newPage({viewport: {width: 1440, height: 1080}}); page.on('pageerror', e => errors.push(e.message));+ await page.goto(url); await page.waitForSelector('html[data-ready="true"]'); await page.waitForFunction(() => document.querySelector('#connection').textContent === 'Saved in your workspace');+ assert.equal(await page.locator('#project-file').isVisible(), false); assert.equal(await page.locator('#csv-file').isVisible(), false);+ await page.locator('[name="title"]').fill('My coffee experiment'); await page.locator('#plan-form button[type="submit"]').click();+ await page.locator('#save-source').click(); await page.waitForFunction(() => document.querySelector('#connection').textContent === 'Saved in your workspace');+ let saved = JSON.parse(await readFile(join(workspace, 'bench/project.json'), 'utf8')); assert.equal(saved.title, 'My coffee experiment'); assert.equal(saved.measurements.length, 0);+ assert.equal((await readdir(join(workspace, '.harness/history'))).length, 1); check('editable plan saves real source with previous edition history');++ await page.locator('[name="title"]').fill('Draft I want to keep'); await page.locator('#plan-form button[type="submit"]').click();+ saved.title = 'Agent-authored coffee brief'; await writeFile(join(workspace, 'bench/project.json'), JSON.stringify(saved)); await buildBench(workspace);+ await page.waitForSelector('#conflict:not([hidden])'); const oldDraft = JSON.parse(await readFile(await downloadFrom(page, '#conflict [data-action="load-source"]', 'source-conflict-draft.signal.json'), 'utf8')); assert.equal(oldDraft.title, 'Draft I want to keep');+ await page.waitForFunction(() => document.querySelector('[name="title"]').value === 'Agent-authored coffee brief');+ await writeFile(join(workspace, 'bench/project.json'), '{invalid'); await page.waitForFunction(() => document.querySelector('#connection').textContent.includes('Source needs attention'));+ assert.equal((await snapshot(page)).title, saved.title); await writeFile(join(workspace, 'bench/project.json'), JSON.stringify(saved));+ await page.waitForFunction(() => document.querySelector('#connection').textContent === 'Saved in your workspace'); check('agent/browser conflicts and invalid source preserve the current draft');++ await page.locator('[data-action="approve"]').click(); assert.equal(await page.locator('[name="title"]').isDisabled(), true);+ let project = await snapshot(page); const originalRuns = structuredClone(project.runs), originalProtocol = structuredClone(project.protocol);+ await nav('collect'); await page.locator('#csv-file').setInputFiles({name: 'bad.csv', mimeType: 'text/csv', buffer: Buffer.from('run_id,response\nr0001,1\nr0001,2\n')});+ await page.locator('#import-form button[type="submit"]').click(); await page.waitForFunction(() => document.querySelector('#toast').textContent.includes('duplicate run id'));+ assert.equal(await page.locator('#commit-import').isDisabled(), true); await page.locator('#dialog [data-action="close"]').click(); assert.equal((await snapshot(page)).measurements.length, 0);+ const originalCSV = syntheticCSV(project); await importCSV(originalCSV); project = await snapshot(page); assert.equal(project.measurements.length, 15); assert.equal(project.sources.length, 1);+ check('protocol approval and actual CSV preview/import reject duplicates without partial writes');++ await page.locator('[data-action="measure"][data-id="r0002"]').click(); const originalValue = project.measurements.find(m => m.runId === 'r0002').value;+ await page.locator('#measurement-form [name="value"]').fill(String(originalValue + .05)); await page.locator('#measurement-form [name="reason"]').fill('Synthetic fixture: corrected the transcribed final digit.');+ await page.locator('#measurement-form button[type="submit"]').click(); project = await snapshot(page); assert.equal(project.measurements.find(m => m.runId === 'r0002').origin.value, originalValue);+ await page.getByText('synthetic-observations.csv · original CSV', {exact: true}).click(); const originalPath = await downloadFrom(page, '[data-action="original-csv"]', 'original-observations.csv'); assert.deepEqual(await readFile(originalPath), Buffer.from(originalCSV));+ check('logged correction retains the original imported bytes and original measured value');++ await nav('analyze'); await page.getByLabel('Steeping time · curvature', {exact: true}).check(); await page.getByLabel('Coffee dose · curvature', {exact: true}).check(); await page.locator('#model-form [name="reason"]').fill('Synthetic acceptance: test separate curvature and recover an unidentifiable model.'); await page.locator('#model-form button[type="submit"]').click();+ await page.getByText('These measurements identify 5 of 6 model columns.', {exact: false}).first().waitFor();+ await nav('followup'); await page.getByRole('spinbutton', {name: 'Point A Steeping time', exact: true}).fill('12'); await page.getByRole('spinbutton', {name: 'Point A Steeping time', exact: true}).press('Tab');+ await page.getByRole('spinbutton', {name: 'Point B Steeping time', exact: true}).fill('8'); await page.getByRole('spinbutton', {name: 'Point B Steeping time', exact: true}).press('Tab');+ await page.getByRole('spinbutton', {name: 'Point B Coffee dose', exact: true}).fill('75'); await page.getByRole('spinbutton', {name: 'Point B Coffee dose', exact: true}).press('Tab');+ await page.locator('#followup-form [name="repeats"]').fill('2'); await page.locator('#followup-form [name="label"]').fill('Separate the curved effects'); await page.locator('#followup-form button[type="submit"]').click();+ project = await snapshot(page); assert.equal(project.runs.length, 19); assert.equal(project.phases.at(-1).kind, 'extension');+ await importCSV(syntheticCSV(project, 'coffee', project.runs.filter(r => r.phase !== 'initial')), 'synthetic-extension.csv'); project = await snapshot(page); assert.equal(fitProject(project).rank, 6); assert.equal(fitProject(project).ok, true);+ assert.deepEqual(project.runs.slice(0, originalRuns.length), originalRuns); assert.deepEqual(project.protocol, originalProtocol);+ check('unidentifiable curvature is repaired with actual appended settings and fresh measurements');++ await nav('followup'); const prior = fitProject(project);+ await page.getByRole('spinbutton', {name: 'Candidate Steeping time', exact: true}).fill('13'); await page.getByRole('spinbutton', {name: 'Candidate Steeping time', exact: true}).press('Tab');+ await page.locator('#followup-form [name="label"]').fill('Independent confirmation'); await page.locator('#followup-form button[type="submit"]').click();+ project = await snapshot(page); assert.equal(project.phases.at(-1).kind, 'confirmation'); const phase = project.phases.at(-1).id;+ await importCSV(syntheticCSV(project, 'coffee', project.runs.filter(r => r.phase === phase)), 'synthetic-confirmation.csv'); project = await snapshot(page);+ assert.deepEqual(fitProject(project).beta, prior.beta); assert.equal(fitProject(project).confirmation, 6);+ await nav('followup'); await page.locator('#conclusion-form [name="conclusion"]').fill('Synthetic acceptance exercise: compare actual follow-up measurements with the frozen forecast; no empirical coffee result is claimed.'); await page.locator('#conclusion-form button[type="submit"]').click();+ await page.locator('#save-source').click(); await page.waitForFunction(() => document.querySelector('#connection').textContent === 'Saved in your workspace');+ project = await snapshot(page); assert.equal(canonical(JSON.parse(await readFile(join(workspace, 'bench/project.json'), 'utf8'))), canonical(project));+ await page.screenshot({path: join(output, 'desktop-followup.png'), fullPage: true}); check('real comparison controls create held-out confirmation runs with frozen forecasts');++ const kit = await downloadFrom(page, '.header-actions [data-action="export"]', 'browser-experiment.zip'); const unpacked = join(output, 'offline-kit'); await mkdir(unpacked, {recursive: true});+ execFileSync('python3', ['-c', 'import zipfile,sys; z=zipfile.ZipFile(sys.argv[1]); assert z.testzip() is None; z.extractall(sys.argv[2])', kit, unpacked]);+ assert.equal(canonical(JSON.parse(await readFile(join(unpacked, 'project.signal.json'), 'utf8'))), canonical(project));+ const offline = await browser.newPage({viewport: {width: 390, height: 844}}); offline.on('pageerror', e => errors.push(e.message)); await offline.route('http**/*', route => route.abort());+ await offline.goto(pathToFileURL(join(unpacked, 'experiment.html')).href); await offline.waitForSelector('html[data-ready="true"]'); await offline.locator('.sidebar [data-tab="followup"]').click();+ assert.ok(await offline.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)); assert.equal(await offline.locator('#save-source').isDisabled(), true);+ await offline.screenshot({path: join(output, 'mobile-followup.png'), fullPage: true});+ await offline.locator('#conclusion-form [name="conclusion"]').fill('Offline decision saved on this device.'); await offline.locator('#conclusion-form button[type="submit"]').click(); await offline.reload(); await offline.waitForSelector('html[data-ready="true"]'); await offline.locator('.sidebar [data-tab="followup"]').click(); assert.equal(await offline.locator('#conclusion-form [name="conclusion"]').inputValue(), 'Offline decision saved on this device.');+ await offline.close(); check('browser ZIP reopens offline, preserves its complete source and supports a 390px layout and draft recovery');+ await page.reload(); await page.waitForSelector('html[data-ready="true"]'); const reloaded = await snapshot(page); assert.equal(canonical(reloaded), canonical(project));+ assert.deepEqual(errors, []); await writeFile(join(output, 'report.json'), JSON.stringify({workspace, checks, errors, actualBrowser: await browser.version(), scope: 'Real Chrome inputs and portable output; synthetic responses, not a physical experiment or an installed-agent trial.'}, null, 2));+ console.log(JSON.stringify({output, passed: checks.length, errors}));+} catch (error) {+ if (page) await page.screenshot({path: join(output, 'failure.png'), fullPage: true}).catch(() => {});+ await writeFile(join(output, 'failure.json'), JSON.stringify({checks, errors, error: error.stack}, null, 2)); throw error;+} finally {await browser.close(); server.closeAllConnections(); await new Promise(r => server.close(r));}diff --git a/store/agents/lab-bench/test/fixtures.mjs b/store/agents/lab-bench/test/fixtures.mjsnew file mode 100644index 000000000..8ce1fe1b4--- /dev/null+++ b/store/agents/lab-bench/test/fixtures.mjs@@ -0,0 +1,63 @@+// Synthetic acceptance data only. No empirical result or customer trial is represented.+import {readFile} from 'node:fs/promises';+import {clone, event} from '../template/studio/project.mjs';+import {generatePlan, random, approveProtocol, appendPhase} from '../template/studio/design.mjs';+import {csv, prepareImport, commitImport, recordMeasurement} from '../template/studio/measurements.mjs';+import {fitProject, predictionSnapshot} from '../template/studio/analysis.mjs';+export const kinds = ['coffee', 'canopy', 'fold'];+export async function blank(kind = 'coffee') {+ const p = JSON.parse(await readFile(new URL('../template/bench/project.json', import.meta.url), 'utf8'));+ p.phases = []; p.runs = []; p.measurements = []; p.sources = []; p.audit = []; p.approved = false;+ p.protocol.notes = 'Synthetic acceptance fixture; no empirical extraction result is claimed.';+ p.evidenceNote = 'Synthetic acceptance measurements. These fixtures verify the workflow and calculations; they are not empirical findings.';+ if (kind === 'canopy') {+ p.id = 'canopy'; p.title = 'Canopy Seedlings'; p.question = 'How do growing medium and water allocation affect 14-day height gain, accounting for the shelf?';+ p.response = {id: 'growth', name: 'Height gain', unit: 'mm', goal: 'maximize'};+ p.factors = [{id: 'medium', name: 'Growing medium', type: 'category', unit: '', levels: ['Coir', 'Leaf', 'Blend']}, {id: 'water', name: 'Daily water', type: 'number', unit: 'mL', levels: [40, 80]}];+ p.design = {seed: 'canopy-01', replicates: 2, blocks: ['East shelf', 'West shelf'], controls: 0};+ p.model = {terms: ['medium', 'water'], blocks: true, confidence: .95};+ p.protocol = {unit: 'One independently prepared pot with one seedling. Leaves and repeated readings within a pot are not separate runs.', randomization: 'Randomize pots within each shelf. Each shelf contains all medium and water combinations.', analysisPlan: 'Estimate medium and water effects with a fixed shelf effect. Inspect residuals before considering exploratory interactions.', steps: ['Label each pot with its run id and record its initial height using one consistent measurement procedure.', 'Use the planned medium and daily water allocation for that pot. Keep the species, starting stage and container size consistent.', 'Record the 14-day height gain in mm. Record a departure or instrument problem in the run note.'], notes: 'Synthetic acceptance fixture; no plant growth claim is made.'};+ } else if (kind === 'fold') {+ p.id = 'fold'; p.title = 'Fold Paperworks'; p.question = 'Which crease width and flap overlap give the strongest package under our fixed compression procedure?';+ p.response = {id: 'load', name: 'Peak load', unit: 'N', goal: 'maximize'};+ p.factors = [{id: 'crease', name: 'Crease width', type: 'number', unit: 'mm', levels: [3, 6, 9]}, {id: 'overlap', name: 'Flap overlap', type: 'number', unit: 'mm', levels: [10, 20, 30]}];+ p.design = {seed: 'fold-01', replicates: 2, blocks: ['Paper lot A'], controls: 0};+ p.model = {terms: ['crease', 'overlap', 'crease:overlap', 'crease^2', 'overlap^2'], blocks: false, confidence: .9};+ p.protocol = {unit: 'One independently fabricated package. Multiple readings during its compression are one run, summarized as peak load.', randomization: 'Fabricate and test independent packages in the randomized run order within one paper lot.', analysisPlan: 'Fit main, interaction and quadratic terms across the three-level factorial. Inspect residuals and extend with new interior settings.', steps: ['Label the package with the run id. Use the same paper lot, adhesive amount and fabrication process.', 'Measure the planned crease width and flap overlap. Record a departure instead of silently changing its planned values.', 'Use a fixed compression procedure and record one peak load in N for this independent package.'], notes: 'Synthetic acceptance fixture, not a measured or certified packaging strength result.'};+ }+ return generatePlan(p);+}+export function syntheticCSV(p, kind = 'coffee', runs = p.runs) {+ const r = random('acceptance-response:' + kind + ':' + runs.map(x => x.id).join(','));+ const noise = () => (r() + r() + r() + r() + r() + r() - 3);+ const rows = [['run_id', 'block', ...p.factors.map(f => f.id), 'response', 'unit', 'note']];+ for (const run of runs) {+ const s = run.settings; let y;+ if (kind === 'coffee') {const x = (s.steep - 12) / 4, z = (s.dose - 75) / 15; y = 18.3 + 1.6 * x + z - .8 * x * z + noise() * .3;}+ else if (kind === 'canopy') {const x = (s.water - 60) / 20; y = 20 + 3 * x + {Coir: 0, Leaf: 4, Blend: 7}[s.medium] + {Coir: 0, Leaf: 1.2, Blend: -1.8}[s.medium] * x + (run.block === 'West shelf' ? -1.7 : 0) + noise() * .6; if (run.id === 'r0005') y += 5;}+ else {const x = (s.crease - 6) / 3, z = (s.overlap - 20) / 10; y = 60 + 8 * x + 6 * z - 9 * x * x - 7 * z * z + 2 * x * z + noise() * 1.2;}+ rows.push([run.id, run.block, ...p.factors.map(f => s[f.id]), Number(y.toFixed(6)), p.response.unit, 'Synthetic fixture; row ' + run.order + (run.id === 'r0005' && kind === 'canopy' ? '; simulated failed instrument check' : '')]);+ }+ return new TextEncoder().encode('\uFEFF' + csv(rows));+}+export async function measured(kind = 'coffee') {+ const p = approveProtocol(await blank(kind)), bytes = syntheticCSV(p, kind);+ return commitImport(p, await prepareImport(p, bytes, {name: kind + '-synthetic-observations.csv', mapping: {runId: 'run_id', response: 'response'}, unit: p.response.unit}));+}+export async function revised(before, kind) {+ let p = clone(before);+ if (kind === 'canopy') {+ const after = {...p.model, terms: ['medium', 'water', 'medium:water']}; event(p, 'model', 'Acceptance revision: inspect an exploratory medium-by-water interaction.', {before: p.model, after, afterCollection: true}); p.model = after;+ const m = p.measurements.find(m => m.runId === 'r0005');+ p = recordMeasurement(p, m.runId, {...m, excluded: 'Synthetic fixture log identifies a failed instrument check for this run.', reason: 'Use the recorded failed check; retain the value and compare the all-recorded sensitivity fit.'});+ } else {+ const fit = fitProject(p), points = kind === 'coffee' ? [{settings: {steep: 16, dose: 60}, block: p.design.blocks[0]}, {settings: {steep: 12, dose: 84}, block: p.design.blocks[0]}] : [{settings: {crease: 4.5, overlap: 20}, block: p.design.blocks[0]}, {settings: {crease: 6, overlap: 25}, block: p.design.blocks[0]}];+ const phaseKind = kind === 'coffee' ? 'confirmation' : 'extension'; p.comparison = {a: points[0], b: points[1]};+ const snapshot = phaseKind === 'confirmation' ? await predictionSnapshot(p, fit, points) : undefined;+ p = appendPhase(p, {points, repeats: kind === 'coffee' ? 3 : 2, label: kind === 'coffee' ? 'Fresh-jar confirmation' : 'Interior-setting extension', reason: 'Acceptance revision using independent synthetic follow-up observations.', seed: kind + '-followup', kind: phaseKind, snapshot});+ const runs = p.runs.filter(r => r.phase === p.phases.at(-1).id), bytes = syntheticCSV(p, kind, runs);+ p = commitImport(p, await prepareImport(p, bytes, {name: kind + '-synthetic-followup.csv', mapping: {runId: 'run_id', response: 'response'}, unit: p.response.unit}));+ }+ p.conclusion = 'Acceptance exercise only. The synthetic observations demonstrate the stated workflow and model calculations; a practical decision requires the person’s own measured experiment.';+ return p;+}diff --git a/store/agents/lab-bench/test/models.test.mjs b/store/agents/lab-bench/test/models.test.mjsnew file mode 100644index 000000000..10a8a6f97--- /dev/null+++ b/store/agents/lab-bench/test/models.test.mjs@@ -0,0 +1,37 @@+import {test} from 'node:test';+import assert from 'node:assert/strict';+import {blank, measured, revised, syntheticCSV, kinds} from './fixtures.mjs';+import {clone, validateProject, validateTransition, canonical, digest, event} from '../template/studio/project.mjs';+import {generatePlan, approveProtocol, appendPhase} from '../template/studio/design.mjs';+import {parseCSV, prepareImport, commitImport, recordMeasurement, verifySources, csv, numeric} from '../template/studio/measurements.mjs';+import {fitProject, plannedAnalysis, predict, compare, predictionSnapshot, confirmationResults} from '../template/studio/analysis.mjs';+import {kitFiles, chartSVG, reportHTML} from '../template/studio/formats.mjs';++test('complete factorial repetitions and blocks are balanced and independently randomized', async () => {+ const p = await blank('canopy'); assert.equal(p.runs.length, 24);+ for (const block of p.design.blocks) {const counts = new Map(); for (const r of p.runs.filter(r => r.block === block)) counts.set(canonical(r.settings), (counts.get(canonical(r.settings)) ?? 0) + 1); assert.equal(counts.size, 6); assert.ok([...counts.values()].every(x => x === 2));}+ assert.deepEqual(generatePlan(p).runs, p.runs); const q = clone(p); q.design.seed = 'another'; assert.notDeepEqual(generatePlan(q).runs, p.runs);+});+test('midpoint controls bracket and span the randomized treatments', async () => {const p = await blank(); const controls = p.runs.filter(r => r.kind === 'control'); assert.deepEqual(controls.map(r => r.order), [1, 8, 15]); assert.ok(controls.every(r => r.settings.steep === 12 && r.settings.dose === 75));});+test('oversized factorials and malformed protocols fail before generating a run sheet', async () => {const p = await blank(); p.design.replicates = 20; p.design.blocks = Array.from({length: 8}, (_, i) => 'b' + i); p.runs = []; p.phases = []; assert.throws(() => generatePlan(p), /512/); p.design.controls = 1; assert.throws(() => validateProject(p), /control/);});+test('CSV reader preserves quoted commas, newlines, BOM and exact original line references', () => {const data = parseCSV('\uFEFFid,value,note\r\na,2,"a comma, then\na line"\r\nb,3,"a ""quote"""\r\n'); assert.equal(data.rows[0].values.note, 'a comma, then\na line'); assert.equal(data.rows[1].row, 4); assert.equal(data.rows[1].values.note, 'a "quote"'); assert.throws(() => parseCSV('a,b\n1,"bad'), /quoted/);});+test('measurement numbers do not silently coerce blanks, Infinity, thousands separators or units', () => {for (const x of ['', 'NaN', 'Infinity', '1,000', '12 mm', '0x10']) assert.throws(() => numeric(x)); assert.equal(numeric('-2.5e2'), -250);});+test('imports retain raw bytes and hashes, and validate all rows before applying anything', async () => {+ const p = await blank(), bytes = syntheticCSV(p), prepared = await prepareImport(p, bytes, {name: 'synthetic.csv', mapping: {runId: 'run_id', response: 'response'}, unit: '%'}); const q = commitImport(p, prepared);+ assert.equal(q.measurements.length, 15); assert.equal(q.sources[0].sha256, await digest(bytes)); assert.deepEqual(await verifySources(q), q); validateTransition(p, q);+ for (const text of ['run_id,response\nr0001,1\nr0001,2\n', 'run_id,response\nunknown,1\n', 'run_id,response,steep\nr0001,1,99\n']) await assert.rejects(() => prepareImport(p, new TextEncoder().encode(text), {name: 'invalid.csv', mapping: {runId: 'run_id', response: 'response'}, unit: '%'}));+ await assert.rejects(() => prepareImport(p, bytes, {name: 'bad-unit.csv', mapping: {runId: 'run_id', response: 'response'}, unit: 'g/L'}), /unit|Confirm/);+ const tampered = clone(q); tampered.sources[0].sha256 = '0'.repeat(64); await assert.rejects(() => verifySources(tampered), /hash mismatch/); assert.equal(p.measurements.length, 0);+});+test('blank responses stay pending and a stale import cannot overwrite a direct entry', async () => {const p = await blank(), bytes = new TextEncoder().encode('run_id,response\nr0001,12\nr0002,\n'); const prepared = await prepareImport(p, bytes, {name: 'partial.csv', mapping: {runId: 'run_id', response: 'response'}, unit: '%'}); assert.equal(prepared.pending, 1); const q = recordMeasurement(p, 'r0001', {value: 10, reason: 'Direct observation'}); assert.throws(() => commitImport(q, prepared), /already measured/);});+test('collected and approved protocols cannot be reshuffled or changed by a source save', async () => {const p = await measured(); assert.throws(() => generatePlan(p), /reshuffled/); const q = clone(p); q.runs[0].settings.steep = 8; assert.throws(() => validateTransition(p, q), /existing run/); q.runs = clone(p.runs); q.protocol.unit = 'different'; assert.throws(() => validateTransition(p, q), /locked/);});+test('corrections and exclusions preserve origin and require the actual before/after log', async () => {const p = await measured(), m = p.measurements[0]; const q = recordMeasurement(p, m.runId, {value: m.value + .1, note: 'corrected transcription', reason: 'Checked the original notebook'}); validateTransition(p, q); assert.equal(q.measurements[0].origin.value, m.value); const bad = clone(q); bad.audit.pop(); assert.throws(() => validateProject(bad), /logged/); assert.throws(() => validateTransition(p, bad), /logged/); await verifySources(q);});+test('two-level corners and common centers cannot identify separate squared effects', async () => {const p = await measured(); p.model.terms.push('steep^2', 'dose^2'); assert.equal(plannedAnalysis(p).rank, 5); const fit = fitProject(p); assert.equal(fit.ok, false); assert.match(fit.issue, /identify 5 of 6/);});+test('too few repetitions withhold residual uncertainty rather than returning an exact-looking fit', async () => {let p = await blank(); p.design.controls = 0; p.design.replicates = 1; p = generatePlan(p); p = commitImport(p, await prepareImport(p, syntheticCSV(p), {name: 'saturated.csv', mapping: {runId: 'run_id', response: 'response'}, unit: '%'})); assert.equal(fitProject(p).ok, false); assert.match(fitProject(p).issue, /repetitions/);});+test('zero residual variation withholds intervals and confirmation planning', async () => {let p = await blank(); const bytes = new TextEncoder().encode(csv([['id','value'], ...p.runs.map(r => [r.id, 10+r.settings.steep])])); p = commitImport(p, await prepareImport(p, bytes, {name:'exact.csv',mapping:{runId:'id',response:'value'},unit:'%'})); const fit = fitProject(p); assert.equal(fit.inferential,false); assert.equal(predict(p,fit,{steep:12,dose:75},p.design.blocks[0]).meanCI,null); await assert.rejects(()=>predictionSnapshot(p,fit,[{settings:{steep:12,dose:75},block:p.design.blocks[0]}]),/uncertainty/);});+test('predictions respect declared bounds, and shared-fit differences include covariance', async () => {const p=await measured(),f=fitProject(p),point={settings:{steep:12,dose:75},block:p.design.blocks[0]},c=compare(p,f,point,point); assert.equal(c.difference,0);assert.equal(c.se,0);assert.deepEqual(c.ci,[0,0]);const pred=predict(p,f,point.settings,point.block);assert.ok(pred.predictionCI[1]-pred.predictionCI[0]>pred.meanCI[1]-pred.meanCI[0]);assert.throws(()=>predict(p,f,{steep:20,dose:75},point.block),/range/);});+test('fresh confirmation observations cannot improve the fit they are evaluating', async () => {const before=await measured(),after=await revised(before,'coffee'); validateTransition(before,after); const a=fitProject(before),b=fitProject(after); assert.deepEqual(a.beta,b.beta);assert.equal(a.n,b.n);assert.equal(b.confirmation,6);assert.deepEqual(after.runs.slice(0,before.runs.length),before.runs);assert.deepEqual(after.sources[0],before.sources[0]);const results=confirmationResults(after);assert.equal(results.length,2);assert.ok(results.every(x=>x.n===3&&x.ci));assert.equal(after.phases[1].snapshot.matrix.y.length,a.n);});+test('an extension can identify missing curvature without changing previously collected runs', async () => {let p=await measured();p.model.terms.push('steep^2','dose^2');const before=clone(p);p=appendPhase(p,{points:[{settings:{steep:12,dose:60},block:p.design.blocks[0]},{settings:{steep:8,dose:75},block:p.design.blocks[0]}],repeats:2,label:'Resolve curvature',reason:'Add separate axial settings',seed:'axes',kind:'extension'});const runs=p.runs.filter(r=>r.phase!=='initial');p=commitImport(p,await prepareImport(p,syntheticCSV(p,'coffee',runs),{name:'axes.csv',mapping:{runId:'run_id',response:'response'},unit:'%'}));validateTransition(before,p);assert.equal(fitProject(p).ok,true);assert.equal(fitProject(p).rank,6);});+test('all three authored experiments fit reproducibly and keep their approved source through revision', async () => {for(const kind of kinds){const p=await measured(kind),q=await revised(p,kind);validateTransition(p,q);await verifySources(q);const fit=fitProject(q);assert.equal(fit.ok,true,kind);assert.equal(canonical(fit),canonical(fitProject(q)));assert.ok(fit.coefficients.every(c=>Number.isFinite(c.value)));assert.deepEqual(q.factors,p.factors);assert.deepEqual(q.protocol,p.protocol);assert.deepEqual(q.runs.slice(0,p.runs.length),p.runs);assert.deepEqual(q.sources[0],p.sources[0]);}});+test('excluded evidence remains exportable beside the all-recorded sensitivity fit', async () => {const before=await measured('canopy'),p=await revised(before,'canopy');assert.equal(fitProject(p).n,23);assert.equal(fitProject(p,{includeExcluded:true}).n,24);const files=kitFiles(p,'<html/>',{reproduce:'',requirements:'',licenses:'',license:''});assert.ok(files['sensitivity-all-recorded.json']);assert.ok(files['sources/'+p.sources[0].id+'.csv'] instanceof Uint8Array);assert.match(files['audit.json'],/failed instrument/);assert.match(files['report.html'],/synthetic/i);});+test('authored text is escaped in reports and chart labels', async () => {const p=await measured();p.title='<script>alert(1)</script>';p.question='<img src=x onerror=alert(1)>';const html=reportHTML(p);assert.ok(!html.includes(p.title));assert.match(html,/<script>/);p.response.name='<bad>';assert.ok(!chartSVG(p,fitProject(p)).includes('<bad>'));});diff --git a/store/agents/lab-bench/test/reopen-deliveries.mjs b/store/agents/lab-bench/test/reopen-deliveries.mjsnew file mode 100644index 000000000..de8fd8e6c--- /dev/null+++ b/store/agents/lab-bench/test/reopen-deliveries.mjs@@ -0,0 +1,42 @@+import assert from 'node:assert/strict';+import {readFile, writeFile, cp, mkdir} from 'node:fs/promises';+import {resolve, join} from 'node:path';+import {pathToFileURL} from 'node:url';+import {chromium} from '../toolchain/node_modules/playwright-core/index.mjs';+import {browserPath} from '../toolchain/browser.mjs';+import {fitProject, predict} from '../template/studio/analysis.mjs';+import {number} from '../template/studio/formats.mjs';+const root = resolve(process.argv[2] ?? process.env.LAB_ACCEPTANCE_ROOT ?? 'work/experience-evidence/signal-acceptance');+const acceptance = JSON.parse(await readFile(join(root, 'acceptance.json'), 'utf8'));+const browser = await chromium.launch({headless: true, executablePath: await browserPath()}), proof = [], errors = [];+try {+ for (const item of acceptance.results) {+ const p = JSON.parse(await readFile(join(item.destination, 'project.signal.json'), 'utf8')), fit = fitProject(p);+ const context = await browser.newContext({viewport: {width: 1440, height: 1080}}), page = await context.newPage();+ page.on('pageerror', e => errors.push(item.kind + '/' + item.edition + ': ' + e.message)); await page.route('http**/*', route => route.abort());+ await page.goto(pathToFileURL(join(item.destination, 'experiment.html')).href); await page.waitForSelector('html[data-ready="true"]');+ await page.locator('.sidebar [data-tab="analyze"]').click(); assert.ok((await page.locator('.metrics').innerText()).includes(String(fit.n)));+ await page.screenshot({path: join(item.destination, 'studio-analysis.jpg'), type: 'jpeg', quality: 90});+ await page.locator('.sidebar [data-tab="followup"]').click();+ const factor = p.factors.find(f => f.type === 'category') ?? p.factors[0], control = page.locator(`[data-candidate="b"][data-factor="${factor.id}"]`).last();+ const candidate = p.comparison?.b ?? {settings: Object.fromEntries(p.factors.map(f => [f.id, f.levels.at(-1)])), block: p.design.blocks[0]};+ const changed = {...candidate.settings, [factor.id]: factor.type === 'category' ? factor.levels[0] : (factor.levels[0] + factor.levels.at(-1)) / 2};+ if (factor.type === 'category') await control.selectOption(factor.levels[0]); else {await control.fill(String(changed[factor.id])); await control.press('Tab');}+ const expected = predict(p, fit, changed, candidate.block); await page.waitForFunction(expectedText => document.querySelectorAll('.prediction .value')[1].textContent.includes(expectedText), number(expected.mean));+ await page.locator('[data-candidate="b"][data-block]').selectOption(p.design.blocks.at(-1));+ const blocked = predict(p, fit, changed, p.design.blocks.at(-1)); await page.waitForFunction(expectedText => document.querySelectorAll('.prediction .value')[1].textContent.includes(expectedText), number(blocked.mean));+ await page.screenshot({path: join(item.destination, 'studio-followup.jpg'), type: 'jpeg', quality: 90});+ await page.setViewportSize({width: 390, height: 844});+ for (const tab of ['plan', 'collect', 'analyze', 'followup']) {await page.locator('.sidebar [data-tab="' + tab + '"]').click(); assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), item.kind + '/' + tab + ' mobile overflow');}+ await page.screenshot({path: join(item.destination, 'studio-mobile.png'), fullPage: true});+ proof.push({kind: item.kind, edition: item.edition, offline: true, actualFactorControl: factor.type, changedPrediction: blocked.mean, mobileTabs: 4}); await context.close();+ }+ assert.deepEqual(errors, []); await writeFile(join(root, 'browser-reopening.json'), JSON.stringify({proof, errors, browser: await browser.version()}, null, 2));+ console.log(JSON.stringify({deliveriesReopened: proof.length, responsiveViews: proof.length * 4, errors}));+ if (process.argv.includes('--showcase')) {+ const target = new URL('../../../showcase/lab-bench/', import.meta.url); await mkdir(target, {recursive: true});+ for (const [kind, name, view] of [['coffee', 'starter', 'followup'], ['canopy', 'canopy', 'analysis'], ['fold', 'fold', 'followup']]) {+ const item = acceptance.results.find(x => x.kind === kind && x.edition === 'after'); await cp(join(item.destination, 'studio-' + view + '.jpg'), new URL(name + '.jpg', target));+ }+ }+} finally {await browser.close();}diff --git a/store/agents/lab-bench/test/toolchain.test.mjs b/store/agents/lab-bench/test/toolchain.test.mjsindex a50db30db..f1f3681f2 100644--- a/store/agents/lab-bench/test/toolchain.test.mjs+++ b/store/agents/lab-bench/test/toolchain.test.mjs@@ -28,8 +28,10 @@ test('every script the manifest names is in the folder and executable', () => {}})-test('setup installs nothing and succeeds quietly', () => {- assert.deepEqual(run(manifest.toolchain.setup), { code: 0, stdout: '', stderr: '' })+test('setup pins the numerical and build tools and resolves a managed Node runtime', () => {+ const pkg=JSON.parse(readFileSync(join(here,'toolchain/package.json'),'utf8'));+ assert.deepEqual(pkg.dependencies,{'esbuild':'0.27.2','playwright-core':'1.63.0','ml-matrix':'6.15.0','jstat':'1.9.6'});+ assert.match(readFileSync(join(here,'toolchain/install.sh'),'utf8'),/harness_node 20/);})test('doctor says ok when sh is on PATH', () => {@@ -44,7 +46,7 @@ test('init lays out a workspace and seeds a not-ready verdict', () => {})test('the manifest names a viewer package and an HTML artifact', () => {- assert.equal(manifest.viewer.use, 'autonomous/web-viewer')+ assert.equal(manifest.viewer.command, 'toolchain/viewer.sh')assert.deepEqual(manifest.viewer.artifactExtensions, ['.html'])})@@ -61,6 +63,6 @@ test('seed-verdict reflects whether a bench exists', () => {test('the manifest routes the actual nested artifact through the shared viewer', () => {- assert.equal(manifest.viewer.url, 'http://127.0.0.1:${port}/?file=${artifact}')+ assert.equal(manifest.viewer.url, 'http://127.0.0.1:${port}/')assert.ok(manifest.workspace.marker.endsWith('/index.html'))})diff --git a/store/agents/lab-bench/test/verify-delivery.py b/store/agents/lab-bench/test/verify-delivery.pynew file mode 100644index 000000000..49e6dc853--- /dev/null+++ b/store/agents/lab-bench/test/verify-delivery.py@@ -0,0 +1,131 @@+"""Independent reader of actual delivered experiments, raw CSV, numerical results and PDFs."""+import base64+import csv+import hashlib+import io+import json+from pathlib import Path+import subprocess+import sys+import xml.etree.ElementTree as ET+import zipfile+import numpy as np+import scipy.stats as stats+import statsmodels.api as sm++root = Path(sys.argv[1]).resolve()+acceptance = json.loads((root / 'acceptance.json').read_text())+results = []+projects = {}++def basis(project, factor_id, settings):+ factor = next(f for f in project['factors'] if f['id'] == factor_id)+ if factor['type'] == 'category':+ return [float(settings[factor_id] == level) for level in factor['levels'][1:]]+ low, high = factor['levels'][0], factor['levels'][-1]+ return [(2 * settings[factor_id] - low - high) / (high - low)]++def row_for(project, run):+ row = [1.0]+ for term in project['model']['terms']:+ if term.endswith('^2'):+ row.append(basis(project, term[:-2], run['settings'])[0] ** 2)+ elif ':' in term:+ a, b = term.split(':')+ row.extend(x*y for x in basis(project, a, run['settings']) for y in basis(project, b, run['settings']))+ else:+ row.extend(basis(project, term, run['settings']))+ if project['model']['blocks']:+ row.extend(float(run['block'] == block) for block in project['design']['blocks'][1:])+ return row++def pdf_check(path):+ xml = subprocess.check_output(['pdftotext', '-bbox', str(path), '-'])+ tree = ET.fromstring(xml)+ pages = tree.findall('.//{http://www.w3.org/1999/xhtml}page')+ assert pages, path+ words = []+ for page in pages:+ width, height = float(page.attrib['width']), float(page.attrib['height'])+ assert abs(min(width, height)-595.28)<2 and abs(max(width, height)-841.89)<2, (path, width, height)+ for word in page.findall('.//{http://www.w3.org/1999/xhtml}word'):+ x0, y0, x1, y1 = [float(word.attrib[k]) for k in ['xMin','yMin','xMax','yMax']]+ assert -1 <= x0 <= x1 <= width+1 and -1 <= y0 <= y1 <= height+1, (path, word.text, word.attrib)+ words.append(word.text or '')+ return len(pages), ' '.join(words)++for item in acceptance['results']:+ folder = Path(item['destination'])+ project = json.loads((folder / 'project.signal.json').read_text())+ projects[(item['kind'], item['edition'])] = project+ assert 'synthetic' in project['evidenceNote'].lower()+ analysis = json.loads((folder / 'analysis.json').read_text())+ assert analysis['ok'] and analysis['inferential']+ with zipfile.ZipFile(folder / 'experiment-kit.zip') as archive:+ assert archive.testzip() is None+ assert len(archive.namelist()) == len(set(archive.namelist()))+ for name in item['files']:+ assert archive.read(name) == (folder / name).read_bytes(), (folder, name)+ for source in project['sources']:+ raw = base64.b64decode(source['base64'], validate=True)+ assert hashlib.sha256(raw).hexdigest() == source['sha256']+ assert (folder / 'sources' / (source['id']+'.csv')).read_bytes() == raw+ reader = csv.DictReader(io.StringIO(raw.decode('utf-8-sig')))+ rows = {r[source['mapping']['runId']].strip(): r for r in reader}+ for m in [m for m in project['measurements'] if m['origin'].get('source') == source['id']]:+ assert float(rows[m['runId']][source['mapping']['response']]) == m['origin']['value']+ if m['value'] != m['origin']['value'] or m['excluded']:+ assert any(e.get('after') == m and e['reason'] for e in project['audit'] if e['action']=='measurement')+ measured = {m['runId']:m for m in project['measurements']}+ phases = {phase['id']:phase for phase in project['phases']}+ used = [r for r in project['runs'] if r['id'] in measured and not measured[r['id']]['excluded'] and phases[r['phase']]['kind'] != 'confirmation']+ x = np.array([row_for(project, r) for r in used])+ y = np.array([measured[r['id']]['value'] for r in used])+ np.testing.assert_allclose(x, analysis['matrix']['X'], atol=1e-13)+ np.testing.assert_array_equal(y, analysis['matrix']['y'])+ assert [r['id'] for r in used] == analysis['matrix']['runIds']+ result = sm.OLS(y, x, hasconst=True, missing='raise').fit()+ influence = result.get_influence()+ alpha = 1-project['model']['confidence']+ np.testing.assert_allclose(result.params, analysis['beta'], rtol=1e-8, atol=1e-8)+ np.testing.assert_allclose(result.bse, [c['se'] for c in analysis['coefficients']], rtol=1e-8, atol=1e-8)+ np.testing.assert_allclose(result.conf_int(alpha=alpha), [c['ci'] for c in analysis['coefficients']], rtol=1e-7, atol=1e-7)+ np.testing.assert_allclose(result.resid, [r['residual'] for r in analysis['residuals']], rtol=1e-8, atol=1e-8)+ np.testing.assert_allclose(influence.resid_studentized_internal, [r['studentized'] for r in analysis['residuals']], rtol=1e-7, atol=1e-7)+ np.testing.assert_allclose(influence.cooks_distance[0], [r['cook'] for r in analysis['residuals']], rtol=1e-7, atol=1e-7)+ np.testing.assert_allclose(np.sqrt(np.mean((result.resid/(1-influence.hat_matrix_diag))**2)), analysis['looRMSE'], rtol=1e-8, atol=1e-8)+ if (folder / 'comparison.json').exists():+ comparison = json.loads((folder / 'comparison.json').read_text())+ for key in ['A', 'B']:+ point = comparison[key]+ point_x = np.asarray(row_for(project, {'settings':point['settings'], 'block':point['block']}))+ prediction = result.get_prediction(point_x[None,:]).summary_frame(alpha=alpha)+ np.testing.assert_allclose(point['mean'], prediction['mean'].iloc[0], rtol=1e-8, atol=1e-8)+ np.testing.assert_allclose(point['meanCI'], prediction[['mean_ci_lower','mean_ci_upper']].iloc[0], rtol=1e-7, atol=1e-7)+ np.testing.assert_allclose(point['predictionCI'], prediction[['obs_ci_lower','obs_ci_upper']].iloc[0], rtol=1e-7, atol=1e-7)+ delta = np.asarray(comparison['B']['x']) - np.asarray(comparison['A']['x'])+ contrast = result.t_test(delta)+ np.testing.assert_allclose(comparison['ci'], contrast.conf_int(alpha=alpha)[0], rtol=1e-7, atol=1e-7)+ subprocess.run([sys.executable, str(folder/'reproduce.py')], check=True, capture_output=True, text=True)+ for file in (folder/'charts').glob('*.svg'):+ svg = ET.fromstring(file.read_text()); assert svg.attrib['viewBox']+ report_pages, report_text = pdf_check(folder/'report.pdf')+ sheet_pages, sheet_text = pdf_check(folder/'collection-sheet.pdf')+ for text in [report_text, sheet_text]:+ assert project['title'] in text and project['response']['name'] in text+ for r in project['runs']:+ assert r['id'] in sheet_text+ assert 'Synthetic' in report_text or 'synthetic' in report_text+ results.append({'kind':item['kind'],'edition':item['edition'],'training':len(y),'columns':x.shape[1],'df':int(result.df_resid),'reportPages':report_pages,'sheetPages':sheet_pages,'sourcesVerified':len(project['sources']),'independentStatistics':'passed'})++for kind in ['coffee','canopy','fold']:+ before, after = projects[(kind,'before')], projects[(kind,'after')]+ for key in ['factors','protocol','response','design']:+ assert before[key] == after[key], (kind,key)+ assert after['runs'][:len(before['runs'])] == before['runs']+ assert after['sources'][:len(before['sources'])] == before['sources']+ assert after['audit'][:len(before['audit'])] == before['audit']++proof = {'reader':'Python CSV/ZIP/XML, independently constructed matrix, statsmodels 0.14.6 / SciPy 1.13.1 and Poppler','results':results,'pages':sum(r['reportPages']+r['sheetPages'] for r in results)}+(root/'independent-verification.json').write_text(json.dumps(proof,indent=2)+'\n')+print(json.dumps(proof,indent=2))diff --git a/store/agents/lab-bench/test/viewer.test.mjs b/store/agents/lab-bench/test/viewer.test.mjsnew file mode 100644index 000000000..bd9a54870--- /dev/null+++ b/store/agents/lab-bench/test/viewer.test.mjs@@ -0,0 +1,45 @@+import {test} from 'node:test';+import assert from 'node:assert/strict';+import {mkdtemp, cp, rm, readFile, readdir, symlink, writeFile} from 'node:fs/promises';+import {tmpdir} from 'node:os';+import {join} from 'node:path';+import {fileURLToPath} from 'node:url';+import {execFileSync} from 'node:child_process';+import {request} from 'node:http';+import {createBenchViewer} from '../viewer/viewer.mjs';+import {approveProtocol} from '../template/studio/design.mjs';+const pkg = fileURLToPath(new URL('..', import.meta.url));++test('source saves retain history, reject stale/foreign writes and protect approved protocol', async () => {+ const scratch = await mkdtemp(join(tmpdir(), 'signal-viewer-')), root = join(scratch, 'workspace');+ await cp(join(pkg, 'template'), root, {recursive: true}); process.env.LAB_DSH_DIR = pkg;+ const server = await createBenchViewer(root); await new Promise(r => server.listen(0, '127.0.0.1', r)); const url = 'http://127.0.0.1:' + server.address().port;+ try {+ const get = () => fetch(url + '/api/project').then(r => r.json()), before = (await get()).project, next = approveProtocol(before); next.title = 'A real source edit';+ const put = (p, origin = url, revision = before.revision) => fetch(url + '/api/project', {method: 'PUT', headers: {origin, 'content-type': 'application/json', 'if-match': revision}, body: JSON.stringify(p)});+ assert.equal((await put(next, 'https://foreign.example')).status, 403); assert.equal((await put(next)).status, 200);+ const saved = (await get()).project; assert.equal(saved.title, next.title); assert.equal(saved.approved, true);+ const previous = JSON.parse(await readFile(join(root, '.harness/history', (await readdir(join(root, '.harness/history')))[0]), 'utf8')); assert.equal(previous.title, before.title); assert.equal(previous.approved, false);+ assert.equal((await put(before)).status, 409); const changed = {...saved, protocol: {...saved.protocol, unit: 'A different experimental unit'}};+ assert.equal((await put(changed, url, saved.revision)).status, 400); assert.equal((await get()).project.revision, saved.revision);+ assert.equal((await fetch(url + '/files/.harness/history')).status, 404); await symlink('/etc/passwd', join(root, 'outside')); assert.equal((await fetch(url + '/files/outside')).status, 404);+ assert.match(await fetch(url).then(r => r.text()), /A real source edit/);+ // Hold the first body open while a second writer arrives. Acquire the lock before parsing.+ const body = JSON.stringify({...saved, title: 'First concurrent writer'}); let finish;+ const bodyStarted = new Promise(resolve => server.once('request', resolve));+ const pending = new Promise((resolve, reject) => {const req = request(url + '/api/project', {method: 'PUT', headers: {origin: url, 'content-type': 'application/json', 'if-match': saved.revision}}, res => {res.resume(); res.on('end', () => resolve(res.statusCode));}); req.on('error', reject); req.write(body.slice(0, 40)); finish = () => req.end(body.slice(40));});+ await bodyStarted; const second = await put({...saved, title: 'Second concurrent writer'}, url, saved.revision); finish();+ assert.equal(second.status, 409); assert.equal(await pending, 200); assert.equal((await get()).project.title, 'First concurrent writer');+ } finally {server.closeAllConnections(); await new Promise(r => server.close(r)); await rm(scratch, {recursive: true, force: true});}+});+test('build and check execute through actual symlinked workspace paths', async () => {+ const scratch = await mkdtemp(join(tmpdir(), 'signal-entry-')), root = join(scratch, 'real'), link = join(scratch, 'shortcut');+ await cp(join(pkg, 'template'), root, {recursive: true}); await symlink(root, link, 'dir');+ const env = {...process.env, LAB_DSH_DIR: pkg};+ try {+ const built = JSON.parse(execFileSync(process.execPath, [join(link, 'tools/build.mjs')], {cwd: link, env, encoding: 'utf8'})); assert.equal(built.title, 'Clearwater Coffee');+ const checked = JSON.parse(execFileSync(process.execPath, [join(link, 'tools/check.mjs')], {cwd: link, env, encoding: 'utf8'})); assert.equal(checked.runs, 15); assert.equal(checked.measured, 0); assert.equal(checked.repeated, true);+ assert.equal(JSON.parse(await readFile(join(root, '.harness/verdict.json'), 'utf8')).ready, false);+ const report = JSON.parse(await readFile(join(root, '.harness/lab-check.json'), 'utf8')); assert.equal(report.planned.rank, 4); assert.equal(report.sourceHashesVerified, 0);+ } finally {await rm(scratch, {recursive: true, force: true});}+});diff --git a/store/agents/lab-bench/toolchain/browser.mjs b/store/agents/lab-bench/toolchain/browser.mjsnew file mode 100755index 000000000..716322f8d--- /dev/null+++ b/store/agents/lab-bench/toolchain/browser.mjs@@ -0,0 +1,18 @@+import { access, writeFile, readFile } from 'node:fs/promises';+import { execFileSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { join } from 'node:path';+const dir = fileURLToPath(new URL('.', import.meta.url));+export async function browserPath({ install = false } = {}) {+ const candidates = [process.env.BROWSER_EXECUTABLE, '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser', process.env.PROGRAMFILES && join(process.env.PROGRAMFILES, 'Google/Chrome/Application/chrome.exe')].filter(Boolean);+ for (const path of candidates) { try { await access(path); return path; } catch {} }+ process.env.PLAYWRIGHT_BROWSERS_PATH = join(dir, 'browsers');+ const { chromium } = await import('./node_modules/playwright-core/index.mjs');+ const path = chromium.executablePath();+ try { await access(path); return path; } catch {}+ if (!install) throw new Error('Browser missing. Run the Lab Bench setup script.');+ execFileSync(process.execPath, [join(dir, 'node_modules/playwright-core/cli.js'), 'install', 'chromium'], { stdio: 'inherit', env: process.env });+ await access(path); return path;+}+if (process.argv.includes('--install')) console.log(`ok export browser: ${await browserPath({ install: true })}`);+if (process.argv.includes('--check')) console.log(`ok export browser: ${await browserPath()}`);diff --git a/store/agents/lab-bench/toolchain/build-math.mjs b/store/agents/lab-bench/toolchain/build-math.mjsnew file mode 100644index 000000000..c497f7eaa--- /dev/null+++ b/store/agents/lab-bench/toolchain/build-math.mjs@@ -0,0 +1,11 @@+import {readFile,writeFile} from 'node:fs/promises';+import {fileURLToPath} from 'node:url';+import {build} from './node_modules/esbuild/lib/main.js';+const root=new URL('.',import.meta.url),target=new URL('../template/studio/math-vendor.mjs',root);+const result=await build({entryPoints:[fileURLToPath(new URL('math-entry.mjs',root))],bundle:true,format:'esm',write:false,minify:true,target:'es2022',legalComments:'inline'});+const source='// Generated from pinned ml-matrix / jstat. Full notices: THIRD_PARTY_LICENSES.txt.\n'+result.outputFiles[0].text;+const names=['ml-matrix','jstat','is-any-array','ml-array-rescale','ml-array-min','ml-array-max'];let licenses='Numerical libraries bundled in Signal\n\n';+for(const name of names){const path=new URL('node_modules/'+name+'/',root),pkg=JSON.parse(await readFile(new URL('package.json',path),'utf8'));let license;for(const file of ['LICENSE','LICENSE.txt','LICENSE.md']){try{license=await readFile(new URL(file,path),'utf8');break;}catch{}}if(!license)throw new Error('Missing license: '+name);licenses+=name+' '+pkg.version+'\n'+license+'\n\n';}+const notice=new URL('../template/studio/THIRD_PARTY_LICENSES.txt',root);+licenses=licenses.trimEnd()+'\n';+if(process.argv.includes('--check')){if(await readFile(target,'utf8')!==source||await readFile(notice,'utf8')!==licenses)throw new Error('Numerical bundle or licenses are stale.');}else{await writeFile(target,source);await writeFile(notice,licenses);}diff --git a/store/agents/lab-bench/toolchain/doctor.sh b/store/agents/lab-bench/toolchain/doctor.shindex 2c36f430b..7b44b397b 100755--- a/store/agents/lab-bench/toolchain/doctor.sh+++ b/store/agents/lab-bench/toolchain/doctor.sh@@ -1,3 +1,6 @@-#!/usr/bin/env bash-# Doctor: the bench is just a file served by the shared web-viewer; no extra runtime needed.-exit 0+#!/bin/sh+set -eu+here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)+cd "$here"+bash node.sh --input-type=module -e 'if(Number(process.versions.node.split(".")[0])<20)process.exit(1);await import("esbuild");console.log("ok Node and offline experiment build tools")'+bash node.sh browser.mjs --checkdiff --git a/store/agents/lab-bench/toolchain/init-workspace.sh b/store/agents/lab-bench/toolchain/init-workspace.shindex 8d280347f..1a80c9b92 100755--- a/store/agents/lab-bench/toolchain/init-workspace.sh+++ b/store/agents/lab-bench/toolchain/init-workspace.sh@@ -1,12 +1,12 @@#!/bin/sh-# Harness copies the template before this runs. Preserve the user's design log on repeat calls.+# Preserve the person's source and design log on repeat initialization.set -euws="${1:-$PWD}"mkdir -p "$ws/bench" "$ws/.harness"if [ ! -f "$ws/bench/DESIGN.md" ]; then- printf '# Design log — Lab Bench\n\nRecord date, USER or AI, decision, rationale, and whether it remains in the build.\n' > "$ws/bench/DESIGN.md"+ printf '# Experiment decisions — Signal\n\nRecord date, USER or AI, supplied evidence, assumptions, decisions and approved protocol, experimental units and actual evidence.\n' > "$ws/bench/DESIGN.md"ficat > "$ws/.harness/verdict.json" <<JSON-{"spec":1,"ready":false,"summary":"Signal starter available — describe what you want to create","artifact":"bench/index.html","findings":[{"severity":"info","kind":"review_pending","message":"Starter provided; personalized changes need browser verification."}],"phases":[{"id":"build","name":"Build","state":"active"},{"id":"verify","name":"Verify","state":"pending"}],"updatedAt":"$(date -u +%Y-%m-%dT%H:%M:%SZ)"}+{"spec":1,"ready":false,"summary":"Signal experiment workshop — turn a question into a test you can carry out","artifact":"bench/index.html","findings":[{"severity":"info","kind":"review_pending","message":"The coffee plan contains no measured data. Adapt the factors and protocol, collect actual responses, and review the analysis and report."}],"phases":[{"id":"build","name":"Plan","state":"active"},{"id":"verify","name":"Verify","state":"pending"}]}JSONprintf 'initialized by %s\n' "${HARNESS_DSH:-autonomous/lab-bench}" > "$ws/.harness-initialized"diff --git a/store/agents/lab-bench/toolchain/install.sh b/store/agents/lab-bench/toolchain/install.shnew file mode 100755index 000000000..a84e3ecff--- /dev/null+++ b/store/agents/lab-bench/toolchain/install.sh@@ -0,0 +1,9 @@+#!/usr/bin/env bash+set -euo pipefail+here="$(cd "$(dirname "$0")" && pwd)"+. "$here/runtimes.sh"+harness_node 20 || exit 1+cd "$here"+npm ci --ignore-scripts --no-audit --no-fund+node browser.mjs --install+node --input-type=module -e 'await import("esbuild");console.log("ok offline experiment build tools")'diff --git a/store/agents/lab-bench/toolchain/math-entry.mjs b/store/agents/lab-bench/toolchain/math-entry.mjsnew file mode 100644index 000000000..508438607--- /dev/null+++ b/store/agents/lab-bench/toolchain/math-entry.mjs@@ -0,0 +1,3 @@+export {Matrix,SingularValueDecomposition as SVD} from 'ml-matrix';+import jstat from 'jstat';+export const studentTQuantile=(p,df)=>jstat.studentt.inv(p,df);diff --git a/store/agents/lab-bench/toolchain/node.sh b/store/agents/lab-bench/toolchain/node.shnew file mode 100755index 000000000..a527a9f1d--- /dev/null+++ b/store/agents/lab-bench/toolchain/node.sh@@ -0,0 +1,6 @@+#!/usr/bin/env bash+set -euo pipefail+here="$(cd "$(dirname "$0")" && pwd)"+. "$here/runtimes.sh"+harness_node 20 || exit 1+exec node "$@"diff --git a/store/agents/lab-bench/toolchain/package-lock.json b/store/agents/lab-bench/toolchain/package-lock.jsonnew file mode 100644index 000000000..5c3981278--- /dev/null+++ b/store/agents/lab-bench/toolchain/package-lock.json@@ -0,0 +1,535 @@+{+ "name": "signal-build-tools",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "signal-build-tools",+ "dependencies": {+ "esbuild": "0.27.2",+ "jstat": "1.9.6",+ "ml-matrix": "6.15.0",+ "playwright-core": "1.63.0"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz",+ "integrity": "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.2.tgz",+ "integrity": "sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.2.tgz",+ "integrity": "sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.2.tgz",+ "integrity": "sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.2.tgz",+ "integrity": "sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.2.tgz",+ "integrity": "sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.2.tgz",+ "integrity": "sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.2.tgz",+ "integrity": "sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.2.tgz",+ "integrity": "sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.2.tgz",+ "integrity": "sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.2.tgz",+ "integrity": "sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.2.tgz",+ "integrity": "sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==",+ "cpu": [+ "loong64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.2.tgz",+ "integrity": "sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==",+ "cpu": [+ "mips64el"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.2.tgz",+ "integrity": "sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.2.tgz",+ "integrity": "sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==",+ "cpu": [+ "riscv64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.2.tgz",+ "integrity": "sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==",+ "cpu": [+ "s390x"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.2.tgz",+ "integrity": "sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.2.tgz",+ "integrity": "sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.2.tgz",+ "integrity": "sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.2.tgz",+ "integrity": "sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.2.tgz",+ "integrity": "sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.2.tgz",+ "integrity": "sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.2.tgz",+ "integrity": "sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.2.tgz",+ "integrity": "sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.2.tgz",+ "integrity": "sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.2.tgz",+ "integrity": "sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/esbuild": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.2.tgz",+ "integrity": "sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==",+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.27.2",+ "@esbuild/android-arm": "0.27.2",+ "@esbuild/android-arm64": "0.27.2",+ "@esbuild/android-x64": "0.27.2",+ "@esbuild/darwin-arm64": "0.27.2",+ "@esbuild/darwin-x64": "0.27.2",+ "@esbuild/freebsd-arm64": "0.27.2",+ "@esbuild/freebsd-x64": "0.27.2",+ "@esbuild/linux-arm": "0.27.2",+ "@esbuild/linux-arm64": "0.27.2",+ "@esbuild/linux-ia32": "0.27.2",+ "@esbuild/linux-loong64": "0.27.2",+ "@esbuild/linux-mips64el": "0.27.2",+ "@esbuild/linux-ppc64": "0.27.2",+ "@esbuild/linux-riscv64": "0.27.2",+ "@esbuild/linux-s390x": "0.27.2",+ "@esbuild/linux-x64": "0.27.2",+ "@esbuild/netbsd-arm64": "0.27.2",+ "@esbuild/netbsd-x64": "0.27.2",+ "@esbuild/openbsd-arm64": "0.27.2",+ "@esbuild/openbsd-x64": "0.27.2",+ "@esbuild/openharmony-arm64": "0.27.2",+ "@esbuild/sunos-x64": "0.27.2",+ "@esbuild/win32-arm64": "0.27.2",+ "@esbuild/win32-ia32": "0.27.2",+ "@esbuild/win32-x64": "0.27.2"+ }+ },+ "node_modules/is-any-array": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/is-any-array/-/is-any-array-3.0.0.tgz",+ "integrity": "sha512-o4h+tylWykC4BD1vaejp6gDxoM13bwW8FGuNs4yIKpj8xbBJcRxJx8vZpq0dCr7ZDEfeKjmsi/euolKhX6f/ww==",+ "license": "MIT"+ },+ "node_modules/jstat": {+ "version": "1.9.6",+ "resolved": "https://registry.npmjs.org/jstat/-/jstat-1.9.6.tgz",+ "integrity": "sha512-rPBkJbK2TnA8pzs93QcDDPlKcrtZWuuCo2dVR0TFLOJSxhqfWOVCSp8aV3/oSbn+4uY4yw1URtLpHQedtmXfug=="+ },+ "node_modules/ml-array-max": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/ml-array-max/-/ml-array-max-2.0.0.tgz",+ "integrity": "sha512-QQZ4kENwpWmyNb98UXRDFXrmtIXuXtt1+bSbda/2KA85+F+rrJP8hZk6QOkCQXM2Th9mUDYdq/PNByPdT9ID4A==",+ "license": "MIT",+ "dependencies": {+ "is-any-array": "^3.0.0"+ }+ },+ "node_modules/ml-array-min": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/ml-array-min/-/ml-array-min-2.0.0.tgz",+ "integrity": "sha512-GRj6Ky6sW9vGL6yIjgsHmXZ9YgrdmcQ8nCxPqEGeKc6dkfYg1XDYxGFxADUjNuZyoCd5PUscWAS4N+cFaX6hFg==",+ "license": "MIT",+ "dependencies": {+ "is-any-array": "^3.0.0"+ }+ },+ "node_modules/ml-array-rescale": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/ml-array-rescale/-/ml-array-rescale-2.0.0.tgz",+ "integrity": "sha512-2GGtKfSno94/kIloWGvpp/U5Q5vLvLrza+SAaGsLeo6Xj4mEbA6Gqx+oTfZFkxnd1grT2X007HfJNs3T5BsiVg==",+ "license": "MIT",+ "dependencies": {+ "is-any-array": "^3.0.0",+ "ml-array-max": "^2.0.0",+ "ml-array-min": "^2.0.0"+ }+ },+ "node_modules/ml-matrix": {+ "version": "6.15.0",+ "resolved": "https://registry.npmjs.org/ml-matrix/-/ml-matrix-6.15.0.tgz",+ "integrity": "sha512-wFa1v6KP8bKp+fj0nYmRs1Pb5K4zRkXGKsOvLinvILENFIADncm4XlOI+S1M7yuACMGfI6cfk0IifDgd4j5xmw==",+ "license": "MIT",+ "dependencies": {+ "is-any-array": "^3.0.0",+ "ml-array-rescale": "^2.0.0"+ }+ },+ "node_modules/playwright-core": {+ "version": "1.63.0",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",+ "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ }+ }+}diff --git a/store/agents/lab-bench/toolchain/package.json b/store/agents/lab-bench/toolchain/package.jsonnew file mode 100644index 000000000..b10e0e7b4--- /dev/null+++ b/store/agents/lab-bench/toolchain/package.json@@ -0,0 +1,11 @@+{+ "name": "signal-build-tools",+ "private": true,+ "type": "module",+ "dependencies": {+ "esbuild": "0.27.2",+ "playwright-core": "1.63.0",+ "ml-matrix": "6.15.0",+ "jstat": "1.9.6"+ }+}diff --git a/store/agents/lab-bench/toolchain/runtimes.sh b/store/agents/lab-bench/toolchain/runtimes.shnew file mode 100755index 000000000..7223c78dc--- /dev/null+++ b/store/agents/lab-bench/toolchain/runtimes.sh@@ -0,0 +1,192 @@+# shellcheck shell=bash+# runtimes.sh — the interpreters a store package runs on, found on this machine or fetched, never+# asked of the person who pressed Get.+#+# Sourced (not run) by a package's setup, doctor and viewer scripts. A new Mac has Apple's Python 3.9,+# no Homebrew and, for most people, no Node on PATH; a package that answers "brew install [email protected]"+# has failed its install. So:+#+# harness_node 18 node >= 18 on PATH, with npm: the machine's own, else the Node Harness+# itself runs on (~/.harness/runtime/current-node, laid down with the CLI)+# harness_uv uv on PATH: the machine's own, else a pinned, checksummed release+# fetched into ~/.harness/runtime+# harness_venv DIR 3.12 [MIN [BELOW]]+# DIR is a venv on CPython 3.12, which uv downloads when the machine+# has none. A venv already there on a Python in [MIN, BELOW) is kept.+# harness_pip DIR PKG… install into that venv, through uv+# harness_micromamba micromamba, pinned and checksummed, for native libraries PyPI has+# no wheel for (pycairo on macOS)+# harness_conda_env DIR SPEC… DIR is a conda-forge environment with those packages+#+# Every function prints `miss …` and returns 1 when it cannot deliver, so `harness_node 18 || exit 1`+# reads like the rest of a setup script. Nothing here touches the user's shell profile; what it+# installs lands in ~/.harness/runtime or the package's own directory (uv keeps its download cache+# where it always does, which a venv does not depend on).+#+# ONE copy is written by hand: store/tools/runtimes.sh in the OpenHarness repository. Each package+# carries an identical copy (a package installs alone, so it cannot reach this one);+# `node store/tools/sync-runtimes.mjs` rewrites them and the CLI's store spec fails when one drifts.++HARNESS_RUNTIME="${ADAPTER_RUNTIME_DIR:-${HOME:-}/.harness/runtime}"+# The Pythons uv downloads live with Harness's other runtimes, not in uv's own ~/.local/share/uv:+# a package's venv points at its interpreter, and `uv python uninstall` there must not break it.+UV_PYTHON_INSTALL_DIR="${UV_PYTHON_INSTALL_DIR:-$HARNESS_RUNTIME/python}"+export UV_PYTHON_INSTALL_DIR+HARNESS_UV_VERSION=0.12.15+HARNESS_MICROMAMBA_VERSION=2.9.0-0++_harness_platform() {+ case "$(uname -s)-$(uname -m)" in+ Darwin-arm64) echo darwin-arm64 ;;+ Darwin-x86_64) echo darwin-x64 ;;+ Linux-x86_64) echo linux-x64 ;;+ Linux-aarch64 | Linux-arm64) echo linux-arm64 ;;+ *) return 1 ;;+ esac+}++_harness_sha256() {+ if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -d' ' -f1+ else sha256sum "$1" | cut -d' ' -f1; fi+}++# _harness_fetch URL DEST SHA256 — DEST exists only if what arrived matches the pinned checksum.+_harness_fetch() {+ local part="$2.part.$$"+ if ! curl -fsSL --retry 3 --connect-timeout 20 --max-time 900 -o "$part" "$1"; then+ rm -f "$part"; echo "miss could not download $1 — check this machine's internet connection"; return 1+ fi+ if [ "$(_harness_sha256 "$part")" != "$3" ]; then+ rm -f "$part"; echo "miss $1 did not match its pinned checksum; nothing was installed"; return 1+ fi+ mv -f "$part" "$2"+}++_harness_node_at_least() {+ command -v node >/dev/null 2>&1 || return 1+ node -e '+ const [a, b = 0] = process.argv[1].split(".").map(Number)+ const [x, y] = process.versions.node.split(".").map(Number)+ process.exit(x > a || (x === a && y >= b) ? 0 : 1)+ ' "$1" >/dev/null 2>&1+}++harness_node() {+ local min="${1:-18}" recorded saved="$PATH" own=0+ _harness_node_at_least "$min" && own=1+ # A node without npm beside it (a distro's nodejs package) cannot run a setup's `npm ci`.+ if [ "$own" = 1 ] && command -v npm >/dev/null 2>&1; then return 0; fi+ recorded="$(cat "$HARNESS_RUNTIME/current-node" 2>/dev/null || true)"+ # Already Harness's own (a second call, or a wrapper calling a script that asks again): nothing to add.+ if [ "$own" = 1 ] && [ -n "$recorded" ] && [ "$(command -v node)" = "${recorded%/*}/node" ]; then return 0; fi+ if [ -n "$recorded" ] && [ -x "${recorded%/*}/node" ]; then+ PATH="${recorded%/*}:$PATH"; export PATH; hash -r 2>/dev/null || true+ _harness_node_at_least "$min" && return 0+ PATH="$saved"; export PATH; hash -r 2>/dev/null || true+ [ "$own" = 1 ] && return 0+ echo "miss node >= $min — this machine's newest is $("${recorded%/*}/node" -v), Harness's own; update Harness"+ return 1+ fi+ [ "$own" = 1 ] && return 0+ echo "miss node >= $min, and Harness's own Node is not in $HARNESS_RUNTIME — run \`harness start\` once to lay it down"+ return 1+}++harness_uv() {+ local dir asset sum tmp+ command -v uv >/dev/null 2>&1 && return 0+ for dir in "${HOME:-}/.local/bin" "${HOME:-}/.cargo/bin"; do+ [ -n "${HOME:-}" ] || break+ if [ -x "$dir/uv" ]; then PATH="$dir:$PATH"; export PATH; return 0; fi+ done+ dir="$HARNESS_RUNTIME/uv-$HARNESS_UV_VERSION"+ if [ ! -x "$dir/uv" ]; then+ case "$(_harness_platform)" in+ darwin-arm64) asset=uv-aarch64-apple-darwin sum=dc304b9ed1b24174572290fba60ac3f6fe63c73a671f0439e62a91375841964d ;;+ darwin-x64) asset=uv-x86_64-apple-darwin sum=e9ca61775532368fe518ab03e7a354c7ecab8ccb3c7d941c775fcc4a362b801b ;;+ linux-x64) asset=uv-x86_64-unknown-linux-gnu sum=f97935763c04be3e692460a7aaeaaab8fc3b78fcf8b389da820b38ae7423a638 ;;+ linux-arm64) asset=uv-aarch64-unknown-linux-gnu sum=0e9a3499b0587d449c9ff684c0160da607826e4af1cee220bc87f378702d3e08 ;;+ *) echo "miss uv — there is no uv release for $(uname -s) $(uname -m); install it from https://docs.astral.sh/uv/"; return 1 ;;+ esac+ echo " fetching uv $HARNESS_UV_VERSION into $HARNESS_RUNTIME (it brings Python and the packages)"+ mkdir -p "$HARNESS_RUNTIME" || { echo "miss cannot write $HARNESS_RUNTIME"; return 1; }+ tmp="$(mktemp -d "$HARNESS_RUNTIME/.uv.XXXXXX")" || { echo "miss cannot write $HARNESS_RUNTIME"; return 1; }+ if ! _harness_fetch "https://github.com/astral-sh/uv/releases/download/$HARNESS_UV_VERSION/$asset.tar.gz" "$tmp/uv.tar.gz" "$sum"; then+ rm -rf "$tmp"; return 1+ fi+ tar -xzf "$tmp/uv.tar.gz" -C "$tmp" && chmod +x "$tmp/$asset/uv" "$tmp/$asset/uvx" \+ || { rm -rf "$tmp"; echo "miss the uv archive would not unpack"; return 1; }+ # Two installs at once both get here; whichever renames first wins and the other's copy goes.+ # (mv onto a directory that exists would nest the copy inside it, hence the test.)+ [ -e "$dir" ] || mv "$tmp/$asset" "$dir" 2>/dev/null || true+ rm -rf "$tmp"+ [ -x "$dir/uv" ] || { echo "miss uv did not land in $dir"; return 1; }+ fi+ PATH="$dir:$PATH"; export PATH+}++# harness_venv DIR VERSION [MIN [BELOW]] — MIN defaults to VERSION; BELOW is exclusive and optional.+harness_venv() {+ local dir="${1:?harness_venv needs a directory}" want="${2:?harness_venv needs a Python version}"+ local min="${3:-$2}" below="${4:-}"+ if [ -x "$dir/bin/python" ] && "$dir/bin/python" -c '+import sys+at = lambda s: tuple(int(p) for p in s.split("."))+v = sys.version_info[:2]+sys.exit(0 if v >= at(sys.argv[1]) and (not sys.argv[2] or v < at(sys.argv[2])) else 1)+' "$min" "$below" 2>/dev/null; then+ echo "ok $("$dir/bin/python" --version) in $dir"+ return 0+ fi+ harness_uv || return 1+ echo " python $want in $dir (uv downloads it when this machine has none)"+ rm -rf "$dir"+ # only-managed: the same python-build-standalone interpreter on every machine, so a package tested+ # once is tested everywhere — not whichever Homebrew or pyenv Python happened to be first on PATH.+ uv venv --quiet --seed --python "$want" --python-preference only-managed "$dir" \+ || { echo "miss could not make a Python $want environment in $dir"; return 1; }+ echo "ok $("$dir/bin/python" --version) in $dir"+}++harness_pip() {+ local dir="${1:?harness_pip needs a venv}"+ shift+ harness_uv || return 1+ # uv's own error comes first; the miss line is last, so it is the line the store shows.+ uv pip install --quiet --python "$dir/bin/python" "$@" \+ || { echo "miss could not install $* into $dir"; return 1; }+}++harness_micromamba() {+ local dir asset sum+ dir="$HARNESS_RUNTIME/micromamba-$HARNESS_MICROMAMBA_VERSION"+ if [ ! -x "$dir/micromamba" ]; then+ case "$(_harness_platform)" in+ darwin-arm64) asset=micromamba-osx-arm64 sum=ec2a072f028e1a7cf20f3e2e74d5a8127cf5a5f27636375b5359811565f4e5be ;;+ darwin-x64) asset=micromamba-osx-64 sum=1e71054bb3ac9a076e21f7ec48acfef536f9b3f1408f371a942784bf5ef83d8a ;;+ linux-x64) asset=micromamba-linux-64 sum=366cd9cd8be14df1ab8ed50352a82111082a36686b2d389fdb79a92c3fafb3e3 ;;+ linux-arm64) asset=micromamba-linux-aarch64 sum=9f93b974adcb4d166996af969b6cd371287d1a3e52733704727884d9b74cb7a7 ;;+ *) echo "miss micromamba — there is no release for $(uname -s) $(uname -m)"; return 1 ;;+ esac+ echo " fetching micromamba $HARNESS_MICROMAMBA_VERSION into $HARNESS_RUNTIME (native libraries PyPI has no wheel for)"+ mkdir -p "$dir" || { echo "miss cannot write $dir"; return 1; }+ _harness_fetch "https://github.com/mamba-org/micromamba-releases/releases/download/$HARNESS_MICROMAMBA_VERSION/$asset" "$dir/micromamba.$$" "$sum" || return 1+ chmod +x "$dir/micromamba.$$" && mv -f "$dir/micromamba.$$" "$dir/micromamba" \+ || { rm -f "$dir/micromamba.$$"; echo "miss micromamba would not install into $dir"; return 1; }+ fi+ HARNESS_MICROMAMBA="$dir/micromamba"+ export HARNESS_MICROMAMBA+}++# harness_conda_env DIR SPEC… — conda-forge only, packages cached under ~/.harness/runtime/mamba.+harness_conda_env() {+ local dir="${1:?harness_conda_env needs a directory}"+ shift+ # micromamba takes a relative --prefix as a name under its root prefix and "succeeds" there.+ case "$dir" in /*) ;; *) dir="$PWD/$dir" ;; esac+ harness_micromamba || return 1+ MAMBA_ROOT_PREFIX="$HARNESS_RUNTIME/mamba" "$HARNESS_MICROMAMBA" create --yes --quiet \+ --prefix "$dir" --override-channels --channel conda-forge "$@" >/dev/null \+ && [ -d "$dir/conda-meta" ] \+ || { echo "miss could not make the conda-forge environment in $dir ($*)"; return 1; }+}diff --git a/store/agents/lab-bench/toolchain/setup.sh b/store/agents/lab-bench/toolchain/setup.shindex 663e77343..7ccd3d7a1 100755--- a/store/agents/lab-bench/toolchain/setup.sh+++ b/store/agents/lab-bench/toolchain/setup.sh@@ -1,3 +1,4 @@-#!/usr/bin/env bash-# Lab Bench has no toolchain: everything is inline HTML + canvas charting. Nothing to install.-exit 0+#!/bin/sh+set -eu+here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)+exec bash "$here/install.sh"diff --git a/store/agents/lab-bench/toolchain/viewer.sh b/store/agents/lab-bench/toolchain/viewer.shnew file mode 100755index 000000000..c2afe7493--- /dev/null+++ b/store/agents/lab-bench/toolchain/viewer.sh@@ -0,0 +1,4 @@+#!/bin/sh+set -eu+here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)+exec bash "$here/node.sh" "$here/../viewer/viewer.mjs"diff --git a/store/agents/lab-bench/viewer/viewer.mjs b/store/agents/lab-bench/viewer/viewer.mjsnew file mode 100644index 000000000..e51dde97d--- /dev/null+++ b/store/agents/lab-bench/viewer/viewer.mjs@@ -0,0 +1,61 @@+// Local workspace bridge: explicit project saves, optimistic revision checks, recoverable history.+import { createServer } from 'node:http';+import { readFile,writeFile,mkdir,rename,realpath,stat } from 'node:fs/promises';+import { resolve,join,relative,sep,extname } from 'node:path';+import { fileURLToPath } from 'node:url';+import { randomUUID } from 'node:crypto';+import { readProject,buildBench } from '../template/tools/build.mjs';+import { validateProject,digest,validateTransition } from '../template/studio/project.mjs';+import {verifySources} from '../template/studio/measurements.mjs';+export async function createBenchViewer(workspace){+ const root=await realpath(workspace);let saving=false;+ async function current(){const project=await readProject(root);delete project.revision;project.revision=await digest(project);return project;}+ const server=createServer(async(req,res)=>{+ res.setHeader('cache-control','no-store');res.setHeader('x-content-type-options','nosniff');+ const send=(code,body,type='application/json')=>{res.writeHead(code,{'content-type':type});res.end(type==='application/json'?JSON.stringify(body):body);};+ if(!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host??''))return send(403,{error:'Loopback only.'});+ const origin='http://'+req.headers.host;+ if((req.headers.origin&&req.headers.origin!==origin)||req.headers['sec-fetch-site']==='cross-site')return send(403,{error:'Same-origin requests only.'});+ let path;try{path=decodeURIComponent(new URL(req.url,origin).pathname);}catch{return send(400,{error:'Invalid path.'});}+ const mutation=['PUT','POST'].includes(req.method);+ if(mutation&&(req.headers.origin!==origin||!String(req.headers['content-type']).startsWith('application/json')))return send(403,{error:'Use the local studio to save or open a project.'});+ async function body(){let size=0;const chunks=[];for await(const chunk of req){size+=chunk.length;if(size>5000000)throw new Error('Request exceeds 5 MB.');chunks.push(chunk);}return JSON.parse(Buffer.concat(chunks));}+ try{+ if(path==='/api/project'&&req.method==='GET')return saving?send(503,{error:'Source save in progress.'}):send(200,{project:await current()});+ if(path==='/api/project'&&req.method==='PUT'){+ if(saving)return send(409,{project:await current(),error:'Another save is in progress.'});+ saving=true;+ try{+ const project=await verifySources(await body());delete project.revision;+ const before=await current();if(req.headers['if-match']!==before.revision)return send(409,{project:before,error:'The source changed. Keep both versions until you choose.'});+ validateTransition(before,project);const built=await buildBench(root,{project});+ const latest=await current();if(latest.revision!==before.revision)return send(409,{project:latest,error:'The source changed during the build. Keep both versions until you choose.'});+ const history=join(root,'.harness/history');await mkdir(history,{recursive:true});+ await writeFile(join(history,new Date().toISOString().replace(/[:.]/g,'-')+'-'+randomUUID()+'.signal.json'),JSON.stringify(before));+ const target=join(root,'bench/project.json'),temporary=target+'.'+randomUUID()+'.tmp';+ const source={...project};delete source.revision;+ await writeFile(temporary,JSON.stringify(source,null,2)+'\n');+ const preview=join(root,'bench/index.html'),previewTemporary=preview+'.'+randomUUID()+'.tmp';await writeFile(previewTemporary,built.html);+ await rename(temporary,target);await rename(previewTemporary,preview);+ await writeFile(join(root,'.harness/verdict.json'),JSON.stringify({spec:1,ready:false,artifact:'bench/index.html',summary:'Source saved; measurement, model and report review pending'}));+ return send(200,{project:await current()});+ }finally{saving=false;}+ }+ if(req.method!=='GET'&&req.method!=='HEAD')return send(405,{error:'Method not allowed.'});+ if(path==='/'){const html=await readFile(join(root,'bench/index.html'));return send(200,req.method==='HEAD'?'':html,'text/html; charset=utf-8');}+ if(!path.startsWith('/files/'))return send(404,{error:'Not found.'});+ const name=path.slice(7);if(name.split(/[\\/]/).some(s=>s.startsWith('.')||s==='node_modules'))return send(404,{error:'Not found.'});+ const file=await realpath(join(root,name));if(!file.startsWith(root+sep)||relative(root,file).split(sep).some(s=>s.startsWith('.')))return send(404,{error:'Not found.'});+ const info=await stat(file);if(!info.isFile()||info.size>48000000)return send(413,{error:'File unavailable or too large.'});+ const mime={'.html':'text/html; charset=utf-8','.svg':'image/svg+xml','.png':'image/png','.pdf':'application/pdf','.json':'application/json','.ttf':'font/ttf'}[extname(file)]??'application/octet-stream';+ return send(200,req.method==='HEAD'?'':await readFile(file),mime==='application/json'?'application/json; charset=utf-8':mime);+ }catch(error){return send(400,{error:error.code==='ENOENT'?'That file is not available.':error.message});}+ });+ return server;+}+if(process.argv[1]&&await realpath(process.argv[1]).catch(()=>null)===fileURLToPath(import.meta.url)){+ if(!process.env.HARNESS_WORKSPACE)throw new Error('HARNESS_WORKSPACE is required.');+ const port=Number(process.env.HARNESS_VIEWER_PORT);if(!Number.isInteger(port)||port<1||port>65535)throw new Error('HARNESS_VIEWER_PORT must be valid.');+ const server=await createBenchViewer(process.env.HARNESS_WORKSPACE);server.listen(port,'127.0.0.1',()=>console.log(`[signal] http://127.0.0.1:${port}/`));+ for(const signal of ['SIGINT','SIGTERM'])process.once(signal,()=>{server.closeAllConnections();server.close();});+}diff --git a/store/showcase/lab-bench/canopy.jpg b/store/showcase/lab-bench/canopy.jpgnew file mode 100644index 000000000..e9507f510Binary files /dev/null and b/store/showcase/lab-bench/canopy.jpg differdiff --git a/store/showcase/lab-bench/fold.jpg b/store/showcase/lab-bench/fold.jpgnew file mode 100644index 000000000..904679f06Binary files /dev/null and b/store/showcase/lab-bench/fold.jpg differdiff --git a/store/showcase/lab-bench/starter.jpg b/store/showcase/lab-bench/starter.jpgindex 345648182..5aaa8cb20 100644Binary files a/store/showcase/lab-bench/starter.jpg and b/store/showcase/lab-bench/starter.jpg differdiff --git a/store/tools/build-experiences.mjs b/store/tools/build-experiences.mjsindex 7e39c17d2..a84e3c00f 100644--- a/store/tools/build-experiences.mjs+++ b/store/tools/build-experiences.mjs@@ -9,6 +9,7 @@ import { buildBrand } from "../agents/creative-direction/template/tools/build.mjimport { buildWorld } from "../agents/voxel-worlds/template/tools/build.mjs";import { buildFlight } from "../agents/drone-pilot/template/tools/build.mjs";import { buildGame } from "../agents/game-master/template/tools/build.mjs";+import { buildBench } from "../agents/lab-bench/template/tools/build.mjs";const source = new URL("./experiences/", import.meta.url);export const experiences = [{@@ -64,7 +65,7 @@ export async function build({ check = false } = {}) {]);let drift = false;for (const exp of experiences) {- if (["generative-art", "music-studio", "creative-direction", "voxel-worlds", "drone-pilot", "game-master"].includes(exp.id)) {+ if (["generative-art", "music-studio", "creative-direction", "voxel-worlds", "drone-pilot", "game-master", "lab-bench"].includes(exp.id)) {try {const packageRoot = new URL(`../agents/${exp.id}/`, import.meta.url);const icon = await readFile(new URL('brand/icon.svg', packageRoot), 'utf8');@@ -72,7 +73,7 @@ export async function build({ check = false } = {}) {if (check) {if (await readFile(studioIcon, 'utf8') !== icon) throw new Error(`${exp.id}: packaged studio icon is out of date.`);} else await writeFile(studioIcon, icon);- const builder = { 'generative-art': buildArt, 'music-studio': buildMusic, 'creative-direction': buildBrand, 'voxel-worlds': buildWorld, 'drone-pilot': buildFlight, 'game-master': buildGame }[exp.id];+ const builder = { 'generative-art': buildArt, 'music-studio': buildMusic, 'creative-direction': buildBrand, 'voxel-worlds': buildWorld, 'drone-pilot': buildFlight, 'game-master': buildGame, 'lab-bench': buildBench }[exp.id];await builder(fileURLToPath(new URL(`../agents/${exp.id}/template/`, import.meta.url)), { check });} catch (error) {if (!check) throw error;diff --git a/store/tools/experience-tests/README.md b/store/tools/experience-tests/README.mdindex 5be6e2098..445d01316 100644--- a/store/tools/experience-tests/README.md+++ b/store/tools/experience-tests/README.md@@ -1,11 +1,14 @@# Experience verification-Art, Music and Creative Direction have authoring rebuilds listed in the Store for user testing;-their source is inside each package's `template/studio/`, with a drawing program/project or an-editable score or brand project. `build-experiences.mjs` delegates to their package builders.-The four parked packages and the retained original models live in `store/tools/experiences/`.-See [the product review](../../../work/SUPERPOWERS.md) and-[current evidence](../../../work/AUTHORING-REBUILD.md). These are technical checks, not product approval.+The seven authoring rebuilds use source inside each package's `template/studio/` and their own+builders. `build-experiences.mjs` delegates to those builders. The original models remain under+`store/tools/experiences/` as retained history; their tests do not stand in for the rebuilt tools.+See [current release status](../../../work/FIVE-REBUILDS.md). These checks establish technical+behavior and delivered output, not a subjective product response or an installed-agent trial.++Game Master and Lab Bench provide package-local browser/acceptance suites. Lab Bench additionally+reopens all six authored deliveries, exercises numeric/category/block controls, and independently+reconstructs its design matrices with Python statsmodels/SciPy. See each package's `test/ACCEPTANCE.md`.Creative Direction's [evidence](../../../work/FORME-REBUILD.md) includes three distinct briefs,targeted revisions, actual canvas/source saves and independently read print deliveries. Run its@@ -22,7 +25,7 @@ node --test store/agents/generative-art/test/*.test.mjs store/agents/music-studinode --test store/viewers/web-viewer/test/*.test.mjs```-The parked packages include a pure-model checker. Run it **in their workspace**:+Legacy workspaces include a pure-model checker. Run it **in their workspace**:```shnode tools/check.mjs --seeds 100diff --git a/store/tools/experience-tests/browser.mjs b/store/tools/experience-tests/browser.mjsindex d7ef45f34..3b12dba9b 100644--- a/store/tools/experience-tests/browser.mjs+++ b/store/tools/experience-tests/browser.mjs@@ -109,6 +109,11 @@ async function shellRegression() {}async function one(exp) {+ if (exp.id === 'lab-bench') {+ const result = execFileSync(process.execPath, [join(repo, 'store/agents/lab-bench/test/browser.mjs')], { env: { ...process.env, LAB_QA_ROOT: join(output, 'signal-browser') }, encoding: 'utf8', timeout: 180000 });+ results.push({name:'lab-bench-studio',ok:true,output:result.trim()});+ return;+ }if (exp.id === 'game-master') {const result = execFileSync(process.execPath, [join(repo, 'store/agents/game-master/test/browser.mjs')], { env: { ...process.env, GAME_QA_ROOT: join(output, 'relay-browser') }, encoding: 'utf8', timeout: 180000 });results.push({name:'game-master-studio',ok:true,output:result.trim()});diff --git a/work/FIVE-REBUILDS.md b/work/FIVE-REBUILDS.mdindex 290b14cf3..6fd0d0f81 100644--- a/work/FIVE-REBUILDS.md+++ b/work/FIVE-REBUILDS.md@@ -12,8 +12,8 @@ so the user can test it, then move to the next. Do not claim a subjective “wow[the acceptance evidence](../store/agents/voxel-worlds/test/ACCEPTANCE.md).3. **Drone Pilot — published (#151), installed readiness verified on this Mac.** [Survey planning and post-flight evidence](DRONE-REBUILD.md), with actual inputs and explicit simulationboundaries. No claim that a simulation authorizes or validates a real flight.-4. **Game Master — in progress.** Original board/card games: authored rules, human play, component editing, reproducible playtests and printable kits.-5. **Lab Bench — pending.** Analyze the person's observations with reproducible methods and outputs.+4. **Game Master — published (#153), normal install and fresh workspace verified on this Mac.** Original board/card games: authored rules, human play, component editing, reproducible playtests and printable kits. Public catalog, studio and three screenshots match the tested release.+5. **Lab Bench — implementation and local acceptance complete, publication pending.** Plan real experiments, collect measurements with provenance, inspect uncertainty and diagnostics, and prepare follow-up runs with reproducible outputs. Six delivered editions pass independent statistical readers; all 48 PDF pages were visually reviewed. See [the evidence](../store/agents/lab-bench/test/ACCEPTANCE.md).## Creative Direction acceptancediff --git a/work/GAME-REBUILD.md b/work/GAME-REBUILD.mdindex 8ee8b6419..8e0e473e5 100644--- a/work/GAME-REBUILD.md+++ b/work/GAME-REBUILD.md@@ -1,6 +1,6 @@# Game Master — original tabletop-game workshop-Implementation complete; final checks and publication are in progress. The prior arena remains+Published in [#153](https://github.com/autonomous-ai/openharness/pull/153) at `1dee0b70289522d0b7a1091d730b367bb329383a`. Both CI jobs passed at the exact PR head; catalog publisher `35508683804` succeeded. The public catalog, studio HTML and three screenshots match the tested source. Normal installation, doctor, fresh workspace materialization, actual build/check/export commands and the viewer command passed on this Mac. Installed/public package revision: `7a0e20d840a4e163dac81f95fc3c1536d34a5e2d`. The prior arena remainsunder `store/tools/experiences/game-master.*`. Relay branding is preserved. The new package usesordinary authored JavaScript rules and editable component/board data to produce playable tabletopgames and physical kits. Phaser/Godot already cover video-game engine creation in the Store.@@ -20,6 +20,4 @@ symlinked-path CLI entry bug; the tools now resolve real paths and a regressionbuild/check commands through a workspace symlink.No customer/installed-agent prompt trial, fun/balance result, printer trial, native tabletop-simulator import or network multiplayer is claimed. Game Master stays unlisted until publication.-After its tested PR is merged, verify public catalog/artifact/screenshots and normal setup/doctor,-then begin Lab Bench. Do not delete old code or change other sessions' worktrees.+simulator import or network multiplayer is claimed. Evidence is in `/private/tmp/relay-public-bytes.json`, `/private/tmp/relay-installed-workspace.json` and `/private/tmp/relay-installed-viewer.json`. Lab Bench is next. Do not delete old code or change other sessions' worktrees.diff --git a/work/LAB-REBUILD.md b/work/LAB-REBUILD.mdnew file mode 100644index 000000000..b9eace6ac--- /dev/null+++ b/work/LAB-REBUILD.md@@ -0,0 +1,32 @@+# Lab Bench — plan, measure, understand, follow up++Implementation and local acceptance complete; release PR/publication pending. Preserve the original Signal logo/icon and the earlier synthetic viewer under+`store/tools/experiences/lab-bench.*`. The new workshop works with authored experimental plans+and actual user measurements. No synthetic-response generator is part of the product.++The intended delivery is a randomized run sheet, protected protocol, original measurement CSVs,+logged corrections/exclusions, explicit model and design matrix, readable uncertainty/diagnostics,+held-out confirmation runs, portable studio, reports and independently reproducible calculations.+Full factorial designs, numeric/categorical factors, main effects/interactions/quadratics and fixed+blocks are bounded to small continuous-response experiments. Do not imply a generic research engine+or causal inference from arbitrary observational data. A model cannot establish a practical result+before the person carries out the experiment and supplies measured evidence.++Statistical design follows the NIST experimental-design handbook. Numerical tools are pinned+ml-matrix 6.15.0 and jstat 1.9.6, bundled offline with complete notices. Validation must independently+recompute delivered matrices, coefficients, intervals and diagnostics with statsmodels/SciPy;+test unknown/duplicate run ids, raw hashes, missing data, rank/df failures, held-out confirmations,+logged corrections, protocol preservation, source conflicts and actual browser interactions.++The three acceptance briefs are coffee extraction, blocked seedling growth and packaging strength.+Their six delivered editions independently pass statsmodels/SciPy recomputation, source/ZIP/SVG+and PDF checks. All 48 print pages and all three actual Store screenshots were visually reviewed;+six portable studios reopen offline with working controls and 24 narrow-screen views. The seven+browser workflows include protocol protection, real CSV upload/correction, source conflicts,+rank recovery through new runs and held-out confirmation. All 27 package tests and 421 CLI+Store/check tests pass locally. See [the complete evidence and reproducible checks](../store/agents/lab-bench/test/ACCEPTANCE.md).++The response fixtures are explicitly synthetic test data, never empirical product claims.+The candidate has `listed:true`; the public package remains unlisted until release. Normal Store+installation and fresh materialization, exact-head CI, publisher completion, public catalog,+studio and screenshot bytes remain to be verified before reporting publication complete.diff --git a/work/SUPERPOWERS.md b/work/SUPERPOWERS.mdindex 7cbb0813a..3f01751ac 100644--- a/work/SUPERPOWERS.md+++ b/work/SUPERPOWERS.md@@ -13,7 +13,7 @@ trials with real user briefs are still outstanding; listing does not claim those**Next user direction:** improve the other five sequentially. Creative Direction has now beenrebuilt and relisted; see [FORME-REBUILD.md](FORME-REBUILD.md) and the[sequential plan](FIVE-REBUILDS.md). Voxel Worlds is also rebuilt and published (#146);-Drone Pilot is published (#151), and Game Master is in progress. The original withdrawal table below+Drone Pilot is published (#151), and Game Master is published (#153). Lab Bench is in final acceptance. The original withdrawal table belowis retained as history, not a description of the rebuilt Forme product.## Original review of our seven@@ -29,7 +29,7 @@ is retained as history, not a description of the rebuilt Forme product.| Lab Bench | Inspect one synthetic experiment | Cannot do useful analysis on the person's own observations | Withdraw; stop parallel development |All seven initially received `listed:false`. Art and Music have since been rebuilt and relisted-for user testing, followed by Creative Direction, Voxel Worlds and Drone Pilot. Game Master and Lab Bench remain unlisted. Source, logos,+for user testing, followed by Creative Direction, Voxel Worlds, Drone Pilot and Game Master. Lab Bench is a listing candidate pending its tested publication. Source, logos,tests and workspaces stay intact.The shared web viewer remains available: it is infrastructure used by other harnesses.Other sessions' harnesses are outside this withdrawal.