Agent API (window.midas)

A JavaScript API for controlling MIDAS programmatically from AI agents, Playwright, or other external tools.

Overview

Availability

  • Project screen: All methods are available, except the methods that create a project (project.openFile(), project.createFromBuffer(), project.createFromUrl(), project.openSample(), project.createEmpty()), which return a LAUNCHER_ONLY error
  • Launcher screen: help(), the methods that open or create a project (project.open(), project.openUrl(), project.openFile(), project.createFromBuffer(), project.createFromUrl(), project.openSample(), project.createEmpty()), the methods that list projects and samples (project.listSaved(), project.listSamples()), project.getLoadState(), the list of signing keys (project.listSigningKeys()), and datasets.cancelReading() are available. Other methods return a NO_PROJECT error

Opening a Project

A page of MIDAS opens one project, and MIDAS reloads the page to open another project. project.open(), project.openUrl(), and project.openFile() with sandbox: true return their result first, and then the page reloads. The other methods that create a project save it to browser storage and return its projectId without opening it, so open it with project.open(projectId).

The reload replaces window.midas, and changes that were not saved with project.save() are lost. Call project.save() before you open another project. On the new page, call project.getLoadState() until its state is "ready" before you call other methods. Whether window.midas exists does not tell whether the project is open. When you call code in the page with a tool such as Playwright's page.evaluate(), calls made while the page reloads fail. Retry the failed calls until getLoadState() returns "ready".

const created = await window.midas.project.createFromBuffer(new TextEncoder().encode('x,y\n1,2'), { name: 'My Data' });
await window.midas.project.open(created.data.projectId);
// After the page reloads
const state = await window.midas.project.getLoadState();
// state.data: { state: 'ready', projectId: 'project-xxx' }

Quick Start for AI Agents

  1. Call status() to check the current project state (datasets, tabs, models)
  2. Call datasets.list() and datasets.describe(id) to understand the available data
  3. Read Data Model to understand persistence, dataset types, and graph specification

Usage

From DevTools Console

Open the browser DevTools and call methods directly in the console.

// Check project status
const result = await window.midas.status();
console.log(result.data);
// { datasets: 3, tabs: 2, models: 1, ... }

From Playwright

const result = await page.evaluate(async () => {
  return await window.midas.datasets.list();
});
console.log(result.data);
// [{ id: '...', name: 'Iris', rows: 150, columns: 5, type: 'primary' }, ...]

Viewing Help

Called without arguments, help() returns methods, the list of available method names, and errors, a description of the structure of a failure response. Pass a method name to get the detail of that method: description (purpose and behavior), signature, params (one entry per argument; nested arguments are written with dots, such as options.limit), returns (the structure of the result), errors (failures that return a specific error code, with the condition for each), and example.

const help = window.midas.help();
console.log(help.methods);        // ["help(methodName?)", "status()", ...]
console.log(help.documentation);  // "https://midas-app.org/docs/en/agent-api.md"

const detail = window.midas.help('datasets.query');
console.log(detail.signature);
console.log(detail.params);       // [{ name: "sql", description: "..." }, { name: "options.limit", ... }, ...]
console.log(detail.errors);       // [{ code: "SQL_PARSE_ERROR", when: "..." }, ...]

Response Format

All methods except help() are async and return a unified APIResult<T> response. help() is synchronous and directly returns the method name index, or the detail of the method you name. Methods other than help() do not reject the Promise. When a defect in MIDAS stops a method, the method returns a failure response (success: false) whose error.code is INTERNAL_ERROR.

// Success
{
  success: true,
  message: "Found 3 datasets",
  data: [...]
}

// Failure
{
  success: false,
  message: "Dataset not found",
  error: {
    code: "DATASET_NOT_FOUND",
    message: "No dataset with ID 'abc'",
    suggestion: "Use datasets.list() to see available datasets"
  }
}

A warnings field may be included when the operation succeeds but there are points to note. For example, models.run() stores data preparation warnings in the top-level warnings and model execution warnings in data.warnings.

// Example response with warnings
{
  success: true,
  message: "Model run completed",
  warnings: ["Non-integer values detected in the trials column(s). ..."],
  data: {
    runId: '...',
    warnings: ["Possible complete or quasi-complete separation detected. ..."],
    ...
  }
}

Data Model

Persistence

API operations modify the in-memory project state. Nothing is written to browser storage until you call project.save(). If you reload the page without saving, all changes from that session are lost.

The methods that create a new project are an exception. project.openFile(), project.createFromBuffer(), project.createFromUrl(), project.openSample(), and project.createEmpty() write the new project to browser storage before they return. openFile() with sandbox: true does not save the project to browser storage.

// Modify a dataset's schema
await window.midas.datasets.setColumnSchema('ds_001', { ... });

// At this point, the change exists only in memory

await window.midas.project.save();
// Now written to browser storage

Dataset Types

datasets.list() returns two types of datasets.

Primary — Original data imported from CSV or other files. The data itself is stored in the project file.

Derived — Data created by a transformation such as SQL or cross-tabulation. The project file stores the operation definition (e.g., which SQL was executed) rather than the data itself. The data is a cache and is not included in the project file by default; in that case, derived datasets are recomputed by re-running their operation after the project is opened, and the results of operations that reference datasets reflect the current contents of the input datasets. For the setting that saves the computed data in the project file, see Datasets. Change this setting with datasets.setSaveDataWithProject(). Use parentIds to inspect dependency relationships.

const result = await window.midas.datasets.list();
// [
//   { id: 'ds_001', name: 'Sales', type: 'primary', ... },
//   { id: 'derived_001', name: 'Monthly Total', type: 'derived', parentIds: ['ds_001'], ... }
// ]

MIDAS also creates temporary Ephemeral Datasets for internal rendering, but these are not included in datasets.list().

File Import Rules

When importing Parquet and JSON files, and when importing with sql, MIDAS builds the dataset by the following rules. For CSV type detection and the list of data types, see Data Types.

Parquet and JSON

MIDAS does not detect types from how the values in a Parquet file are written; it determines MIDAS data types from the type each column has in the file, as follows.

Parquet columnMIDAS data type
Signed integers, and unsigned integers of 32 bits or fewerint64
DECIMAL with no fractional part and 18 or fewer digitsint64
Floating-point numbersfloat64
Booleansboolean
Stringsstring
Datesdate
Timestampsdatetime
Lists, structs, and mapsstring holding the value as a JSON string
DECIMAL with a fractional part, 64-bit unsigned integers, times, UUIDs, and other types not listed abovestring

MIDAS makes DECIMAL with a fractional part string because converting it to float64 would change values that cannot be represented as double-precision floating-point numbers to other nearby values.

MIDAS imports JSON files written in UTF-8 that hold an array of objects or a sequence of objects. When you write a sequence of objects in a file with the .jsonl or .ndjson extension, you must write one object per line. MIDAS makes each object one row and its keys columns, and orders the columns by where each key first appears in the file. For an object that lacks a key, MIDAS sets the value in that key's column to missing. MIDAS does not import JSON containing keys that differ only in the case of letters.

For JSON, MIDAS determines the type from the kinds of all values of each key.

Values of the keyMIDAS data type
Only booleansboolean
Only integersint64
Only numbers, at least one with a decimal point or exponentfloat64
Only strings of the form 2024-01-15date
Only strings of the form 2024-01-15 10:30:00 or 2024-01-15T10:30:00Zdatetime
Only other strings, or two or more of booleans, numbers, and stringsstring
Contains objects or arraysstring holding the value as a JSON string

Of JSON date-time strings, MIDAS makes only the form without an offset and the form with Z datetime. Date-times with an offset such as +09:00 become string. A value enclosed in quotes, such as "true", is a string, so it does not make a boolean column.

When a Parquet or JSON column that MIDAS maps to int64, date, or datetime contains even one value that the type cannot represent, MIDAS makes the column string and shows a warning. Such values are integers whose absolute value exceeds 2^53, and dates and date-times whose year is outside 1 to 9999.

MIDAS turns empty strings and floating-point NaN and ±Infinity in Parquet and JSON into missing values, because string columns do not hold empty strings and float64 columns do not hold NaN and ±Infinity. MIDAS rounds times finer than milliseconds down to the millisecond, toward earlier times, and reports the number of truncated values, because datetime has only millisecond precision.

Reading SQL

The reading SQL is a single SELECT statement that refers only to the original file, and MIDAS runs it in DuckDB. This SQL can refer only to the result of passing getvariable('source_file') to a file-reading function such as read_csv, read_parquet, or read_json, and to names defined with WITH.

The reading SQL cannot use WITH RECURSIVE or options that skip unreadable rows, such as ignore_errors. WITH RECURSIVE is not allowed because a recursion that never ends cannot be stopped without restarting DuckDB. Options that skip unreadable rows are not allowed because MIDAS fails the whole import when a row is unreadable, so that the same file always produces the same dataset.

The columns of the SQL result must have one of the types BOOLEAN, TINYINT, SMALLINT, INTEGER, BIGINT, UTINYINT, USMALLINT, UINTEGER, FLOAT, DOUBLE, VARCHAR, DATE, or TIMESTAMP. TIMESTAMP in this list also includes the types with a time zone and the types with second, millisecond, and nanosecond precision. CAST columns of other types, such as DECIMAL, in the SQL.

If the SQL result contains an integer whose absolute value exceeds 2^53, or a date or date-time whose year is outside 1 to 9999, MIDAS does not import the result. Unlike Parquet and JSON, MIDAS does not change columns of the SQL result to string. For the SQL result too, MIDAS truncates times finer than milliseconds to milliseconds, and turns NaN, ±Infinity, and empty strings into missing values.

MIDAS also uses the saved SQL as is when reloading the dataset.

Report Element Lifecycle

A report consists of two parts: Markdown text called content, and elements such as graphs and model summaries. A line in the content that contains only a reference like {{graph_builder:element_001}} renders the corresponding element at that position.

reports.addGraph() and reports.addModelSummary() create an element and insert a reference into the content in one step. reports.removeElement() removes both the element and its content reference.

When a model or dataset is deleted, any report elements that depend on it are automatically removed.

Graph Specification

Custom Graph configuration has two levels, the graph level and the layer level. In multi-panel mode a panel level sits between them.

Graph level — Settings that apply to the entire graph: data source, coordinate system (coordinates), faceting (facets), axis scales (scales), and the brush selection direction (brush). Specified via tabs.configureGraph() or reports.addGraph().

Panel level — Present only in multi-panel mode (panels). Panels are stacked vertically and share the X axis, and each panel has its own layers (layers), Y axis scale (yScale), relative height (heightRatio), and name (name). In multi-panel mode only the layers of each panel are rendered; the graph-level layers and facets are not used. See panels under tabs.configureGraph() for how to set it up.

Layer level — A drawing unit that combines a geom (geom: points, lines, bars, etc.), statistical transformations (stats), and aesthetic mapping (aes: which columns map to the x-axis, color, size, etc.). Multiple layers can be stacked on a single graph. Add layers with tabs.addGraphLayer(). Each layer can configure its own scale for each aesthetic via scales.

The graph-level globalAes serves as the default for all layers, and each layer's aes can override it.

For full configuration details, see Custom Graph and Custom Graph Reference.

Method Reference

status()

Get the current project status.

const result = await window.midas.status();
// result.data:
// {
//   datasets: 3,
//   derivedDatasets: 1,
//   tabs: 2,
//   models: 1,
//   reports: 1,
//   activeDatasetId: 'ds_001',
//   activeTabId: 'tab_001'
// }

activeTabId is the tab at the front of the active pane. It is null when that pane holds no tabs.

project

project.save()

Save the project to browser storage. See Privacy and Security for details on storage.

await window.midas.project.save();

Returns a SANDBOX_MODE error in sandbox mode (projects that are not saved to browser storage, such as one opened from a URL).

save() waits for the user's confirmation before it overwrites changes made in another browser tab or window. If another tab or window has changed the project saved in the browser since this tab opened or last saved it, save() shows a confirmation dialog on the screen and does not return until the user chooses. When the user declines to replace it, save() writes nothing and returns a USER_CANCELLED error. If the page changes before the user answers, MIDAS closes the confirmation dialog, and save() writes nothing and returns a USER_CANCELLED error. See Save to Browser for the dialog.

project.exportMds(options?)

exportMds() exports the project as the binary of an MDS file and returns the file content as an ArrayBuffer. For a project opened from a signed MDS file, MIDAS carries the provenance into the exported file.

MIDAS signs the file with a passkey registered in this browser. For each signature the browser asks the user to verify themselves, so exportMds() does not return until the verification is done.

Pass the fingerprint of the key to sign with in options.fingerprint. If omitted, MIDAS signs with the default key. Use project.listSigningKeys() to look up the fingerprints of the keys.

The failures that exportMds() returns with specific error codes are:

  • NO_SIGNING_KEY: this browser has no signing key, or only the previous signing key remains
  • NOT_FOUND: the key of options.fingerprint is not registered
  • SIGNING_NOT_ALLOWED: the user closed the verification screen, the verification timed out, the page was not focused, the passkey was deleted from the password manager or security key, or another passkey confirmation from MIDAS has not finished

If the page does not have focus when MIDAS asks for the signature, as when the call is made from the DevTools console, the browser refuses to sign. Registering a key involves creating or choosing a passkey, so the Agent API cannot do it; the user registers a key in the Signing Keys tab of the Settings dialog or in the export dialog.

const result = await window.midas.project.exportMds();
// result.data: { data: ArrayBuffer, size: 12345, suggestedFilename: 'MyProject.mds' }

// Sign with a key other than the default key
await window.midas.project.exportMds({ fingerprint: 'a1b2c3d4e5f60718293a4b5c6d7e8f90' });

project.downloadMds(options?)

Download the project as an MDS file through the browser. Carrying over the provenance, choosing the signing key with options.fingerprint, the user verification, and the errors are the same as exportMds().

const result = await window.midas.project.downloadMds();
// result.data: { filename: 'MyProject.mds' }

project.listSigningKeys()

List the signing keys registered in this browser. Use it to choose the key that project.exportMds() and project.downloadMds() sign with. keys is an array of the registered keys, oldest registration first. Each element has the fields fingerprint (the fingerprint), publicKey (the public key in Base64 SPKI form), name (the signer name), isDefault (whether it is the default key), and registeredAt (the registration time). publicKey is the same value as publicKey in the public key file written by Export Public Key in the Signing Keys tab. legacyKeyPending is true while the previous signing key remains in this browser.

Registering keys, removing keys from this browser, changing the default key, and changing the signer name are not available in the Agent API. The user does them in the Signing Keys tab of the Settings dialog.

const result = await window.midas.project.listSigningKeys();
// result.data: { keys: [{ fingerprint: 'a1b2c3d4e5f60718293a4b5c6d7e8f90', publicKey: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...', name: 'Alice',
//                         isDefault: true, registeredAt: '2026-10-17T00:00:00.000Z' }],
//                legacyKeyPending: false }

project.getLastSavedToBrowser()

Get the time shown after Saved to browser in the menu bar. project.save() advances this time, and exportMds() and downloadMds() do not. See Save to Browser for the other operations that advance it.

const result = await window.midas.project.getLastSavedToBrowser();
// result.data: { savedAt: '2026-10-17T05:32:05.000Z' }

savedAt is a UTC time in ISO 8601 format. It is null for a project in sandbox mode.

project.open(projectId)

Open a project saved in browser storage. MIDAS reloads the page to open it, even when it is the project already open; see Opening a Project.

const result = await window.midas.project.open('project-xxx');
// result.data: { projectId: 'project-xxx' }

If the current project has unsaved changes, a confirmation dialog is shown. Returns USER_CANCELLED if the user declines.

project.listSaved()

List the projects saved in browser storage, most recently saved first. projectId is the ID to pass to project.open(), and lastModified is the time the project was last saved to browser storage (null when MIDAS has no record of it).

const result = await window.midas.project.listSaved();
// result.data: { projects: [{ projectId: 'project-xxx', name: 'My Data', lastModified: '2026-10-17T05:32:05.000Z', size: 12345 }] }

project.getLoadState()

Get whether this page is opening a project. state is "none" on the launcher screen, "loading" while the project opens, "ready" when the other methods can use the project, and "failed" when MIDAS could not open the project. "ready" comes with projectId, and "failed" comes with error, the message MIDAS shows on the screen.

const result = await window.midas.project.getLoadState();
// result.data: { state: 'ready', projectId: 'project-xxx' }

project.openFile(data, options?)

Save a project from MDS binary data (Uint8Array) to browser storage. Without sandbox, openFile() does not open the project; open it with project.open().

const buf = await fetch('/project.mds').then(r => r.arrayBuffer());
const result = await window.midas.project.openFile(new Uint8Array(buf));
// result.data: { projectId: 'project-xxx' }

Options:

  • sandbox (boolean, default: false) — When true, assigns a new ID and opens the project in sandbox mode without saving the project to browser storage. MIDAS reloads the page to open it, as described in Opening a Project. To pass the file to the reloaded page, MIDAS writes the file to browser storage temporarily and deletes it once the reloaded page reads it. Therefore, reloading the sandbox page afterwards does not open the project again
  • onDuplicate ('overwrite' | 'copy', default: 'overwrite') — Behavior when a project with the same ID already exists in browser storage. 'overwrite' replaces the existing project; 'copy' assigns a new ID only when a duplicate exists

openFile() is available only on the launcher screen and returns LAUNCHER_ONLY on the project screen. Signature warnings are not shown as a dialog; they are reported via the warnings array in the response.

project.openUrl(url, options?)

Fetch an MDS file from a URL and open it. Always opens in sandbox mode (not saved to browser storage). openUrl() fetches the file to check that it opens and returns the warnings. Then MIDAS reloads the page at the URL #mds=<url>, which fetches the file again, as described in Opening a Project.

const result = await window.midas.project.openUrl('https://example.com/project.mds');
// result.data: { projectId: 'project-xxx' }

Options:

  • signal (AbortSignal) — Used to abort the fetch by openUrl()

If the current project has unsaved changes, a confirmation dialog is shown. Returns USER_CANCELLED if the user declines. The warnings about the URL, the file size, the signature, and a file from a newer version are not shown as dialogs, either by openUrl() or by the reloaded page; they are reported via the warnings array in the response. However, when the file that the reloaded page fetches again differs from the file that openUrl() checked, the warnings do not apply to it, so the reloaded page shows the warnings about the signature and a file from a newer version as dialogs, and MIDAS opens the project with an ID other than the returned projectId.

project.createFromBuffer(data, options?)

Create a new project from CSV, TSV, Parquet, or JSON binary data (ArrayBuffer or a TypedArray such as Uint8Array) and save it to browser storage. The data is read in the same way as datasets.importFromBuffer(), and the project has one primary dataset that keeps the data as its original file. createFromBuffer() does not open the project; open it with project.open().

const csv = new TextEncoder().encode('x,y\n1,2\n3,4');
const result = await window.midas.project.createFromBuffer(csv, { name: 'My Data' });
// result.data: { projectId: 'project-xxx', datasetId: 'dataset_...', format: 'csv' }

The returned datasetId is the ID of the created dataset and has the same meaning as id in datasets.importFromBuffer(). format is the format the data was read as.

The options are those of datasets.importFromBuffer() without overwrite, with the same meanings. name also becomes the project name.

  • name (string) — Dataset name. Defaults to fileName without its extension when the extension is .csv, .tsv, .parquet, .json, .jsonl, or .ndjson, or "Untitled" when fileName is also omitted
  • format ("csv" | "parquet" | "json") — Format to read the data as. When omitted, it follows the extension of fileName, and is "csv" when fileName is also omitted
  • fileName (string) — Name of the original file, with its extension. Defaults to buffer.csv, buffer.parquet, or buffer.json
  • hasHeader (boolean, default: true) — Whether the first row is a header. Used only for CSV and TSV
  • encoding ("utf-8" | "shift_jis" | "euc-jp") — Character encoding. When omitted, encoding is auto-detected from the byte sequence. Used only for CSV and TSV
  • delimiter ("," | "\t" | ";" | "|") — Delimiter. When omitted, tab when the extension of fileName is .tsv or .txt, comma otherwise. Used only for CSV and TSV
  • sql (string) — The reading SQL. When omitted, the data is read with the SQL that MIDAS builds from the format and the CSV and TSV settings. When given, it is handled as sql of datasets.importFromURL()

project.createFromUrl(url, options?)

Fetch a CSV, TSV, Parquet, or JSON file from a URL, create a new project from it, and save the project to browser storage. The file is read in the same way as datasets.importFromURL(), and the project has one primary dataset that keeps the fetched file as its original file. createFromUrl() does not open the project; open it with project.open().

const result = await window.midas.project.createFromUrl('https://example.com/data.parquet');
// result.data: { projectId: 'project-xxx', datasetId: 'dataset_...', format: 'parquet' }

The return value is the same as that of project.createFromBuffer(). The options are those of datasets.importFromURL() without overwrite, plus signal. name also becomes the project name.

  • name (string) — Dataset name. When omitted, the name is inferred from the URL
  • format ("csv" | "parquet" | "json") — Format to read the file as. When omitted, it follows the extension in the path of the URL, then the Content-Type of the response. When neither determines it, the format is "parquet" if the file starts with the mark of a Parquet file (PAR1), and "csv" otherwise
  • hasHeader (boolean, default: true) — Whether the first row is a header. Used only for CSV and TSV
  • encoding ("utf-8" | "shift_jis" | "euc-jp") — Character encoding. When omitted, encoding is auto-detected from the Content-Type charset and the byte sequence. Used only for CSV and TSV
  • delimiter ("," | "\t" | ";" | "|") — Delimiter. When omitted, it follows the file name extension in the URL: tab for .tsv and .txt, comma otherwise. Used only for CSV and TSV
  • sql (string) — The reading SQL. When omitted, the file is read with the SQL that MIDAS builds from the format and the CSV and TSV settings. When given, it is handled as sql of datasets.importFromURL()
  • signal (AbortSignal) — Used to abort the fetch

project.openSample(sampleId)

Create a new project from a built-in sample dataset and save it to browser storage. The project is named Sample: {name}. openSample() does not open the project; open it with project.open().

const result = await window.midas.project.openSample('penguins');
// result.data: { projectId: 'project-xxx' }

openSample() is available only on the launcher screen and returns LAUNCHER_ONLY on the project screen. Returns FETCH_ERROR when fetching the sample data fails.

project.listSamples()

List the built-in sample datasets available to project.openSample().

const result = await window.midas.project.listSamples();
// result.data: { samples: [{ id: 'penguins', name: 'Palmer Penguins', rows: 344, columns: 8,
//                            purpose: 'Classification, visualization', recommended: true }, ...] }

project.createEmpty(name?)

Create a new project with no datasets and save it to browser storage. createEmpty() does not open the project; project.open() opens it on the Project Overview tab. Add datasets afterwards with datasets.create(), datasets.generateSynthetic(), datasets.importFromBuffer(), or datasets.importFromURL().

const result = await window.midas.project.createEmpty('Design Study');
// result.data: { projectId: 'project-xxx' }

The name argument (string, default: "Untitled Project") is the project name. createEmpty() is available only on the launcher screen and returns LAUNCHER_ONLY on the project screen.

datasets

datasets.list()

List all datasets in the project.

const result = await window.midas.datasets.list();
// result.data: [{ id, name, rows, columns, type, parentIds?, evaluationState?, evaluationError?, saveDataWithProject?, preventReload? }, ...]

type is either 'primary' (imported data) or 'derived' (created by SQL or other operations). parentIds lists the source dataset IDs a derived dataset depends on; it is empty for a derived dataset created from SQL that references no dataset (such as generate_series). Only derived datasets have saveDataWithProject, which tells whether the setting to save the computed data in the project file is enabled. Change the setting with datasets.setSaveDataWithProject(). Only primary datasets have preventReload, which tells whether the setting that prevents reloads is enabled. Change the setting with datasets.setPreventReload().

rows is the number of rows, and it is null for a derived dataset whose row count is unknown. Methods that read data, such as datasets.profile() and datasets.fetch(), compute the derived dataset and then return its row count.

evaluationState is the evaluation state of a derived dataset, and only derived datasets have it. datasets.list() only reads the state and does not start an evaluation. The value is one of the following five.

  • 'unevaluated': The dataset has no row data, and no evaluation is running
  • 'evaluating': An evaluation is running
  • 'evaluated': The evaluation finished, and the dataset has row data
  • 'failed': The evaluation failed. evaluationError holds the reason
  • 'cancelled': The evaluation was cancelled

rows is independent of evaluationState. A derived dataset whose row count from its previous evaluation is known has that count in rows even when it is 'unevaluated', 'evaluating', 'failed', or 'cancelled'.

datasets.describe(id)

Get detailed information about a dataset. Accepts a dataset ID or name (case-insensitive).

const result = await window.midas.datasets.describe('Iris');
// result.data:
// {
//   id: 'ds_001',
//   name: 'Iris',
//   type: 'primary',
//   rowCount: 150,
//   columns: [
//     { id: 'col_001', name: 'sepal_length', type: 'float64', scale: 'ratio' },
//     { id: 'col_002', name: 'species', type: 'enum', scale: 'nominal', enumName: 'species_enum' },
//     ...
//   ],
//   source: { format: 'csv', fileName: 'iris.csv', encoding: 'utf-8', preset: { ... }, sqlFromPreset: true, sql: 'SELECT ...', ... }
// }

rowCount is the number of rows. Like rows of datasets.list(), it is null for a derived dataset whose row count is unknown.

evaluationState and evaluationError mean the same as in datasets.list(), and only derived datasets have them. datasets.describe() also only reads the state and does not start an evaluation.

Each column entry contains id, name, and type. scale, enumName, displayFormat, and defaultDisplayFormat are optional. enumName is present when the column type is enum, indicating the associated enum definition name. displayFormat holds the format set with datasets.setColumnDisplayFormat() and is absent for columns with no format. defaultDisplayFormat holds the default display format. For a column of an analysis result table, it is the display format the analysis chooses for the column. For a column that a Derived Dataset includes from its input dataset, it is the display format of the same column in the input dataset. Each kind held in displayFormat takes precedence over the same kind in defaultDisplayFormat. The internal row number column (Row #) added by MIDAS is not included in columns.

A primary dataset imported from a file also returns source. source holds the original file (fileName, size, sha256, crc32, format, and encoding for CSV and TSV) and the definition that creates the dataset from the file: the preset settings preset, sqlFromPreset, which tells whether sql was built from the preset, the reading SQL sql, and the columns of the result of the SQL columns. The contents of preset depend on the format. For CSV and TSV, preset holds the delimiter, the header setting, and the header value, column name, and determined type of each column. For Parquet, the columns of preset hold the original name of each column (source), its DuckDB type in the file (sourceType), the column name, and the type, and preset also holds the type of a row at import, rowType. For JSON, the columns of preset hold the key of each column (key), the kind of its values found at import (kind: "boolean", "integer", "number", "large-integer", "string", "text", "date", "datetime", or "json"), and the column name, and preset also holds the layout of the file, format ("array", "newline_delimited", or "unstructured"). The rows of the dataset are the rows of the result of applying sql to the original file, except the excluded rows.

For a derived dataset whose operation can be edited, operation holds the definition of the operation the dataset is computed from. The editable operation types are those in the editingDatasetId table of tabs.open(). operation has the shape the project stores, so its fields depend on operation.type. For example, a dataset created with datasets.derive() has an operation with type: 'sql_query' and the SQL in query. Primary datasets, and derived datasets whose operation cannot be edited, such as those saved from a model, do not return operation.

A dataset with a description returns it as description. A dataset without one does not return description. Set the description with datasets.setDescription().

For a derived dataset, saveDataWithProject tells whether the setting to save the computed data in the project file is enabled. Primary datasets do not return saveDataWithProject.

For a primary dataset, preventReload tells whether the setting that prevents reloads is enabled.

datasets.profile(id)

Get column-level summary statistics for a dataset. Accepts a dataset ID or name (case-insensitive). A derived dataset that has not been evaluated yet is evaluated before it is read.

const result = await window.midas.datasets.profile('Iris');
// result.data:
// {
//   id: 'ds_001',
//   name: 'Iris',
//   rowCount: 150,
//   columns: [
//     {
//       name: 'sepal_length', type: 'float64', scale: 'ratio',
//       nullCount: 0, uniqueCount: 35,
//       min: 4.3, max: 7.9, mean: 5.843, median: 5.8, sd: 0.828
//     },
//     {
//       name: 'species', type: 'string', scale: 'nominal',
//       nullCount: 0, uniqueCount: 3,
//       topValues: [
//         { value: 'setosa', count: 50 },
//         { value: 'versicolor', count: 50 },
//         { value: 'virginica', count: 50 }
//       ]
//     },
//     ...
//   ]
// }

Every column includes nullCount and uniqueCount. uniqueCount counts all distinct non-null values. Numeric columns (int64, float64) additionally include min, max, mean, median, and sd (sample standard deviation, Bessel-corrected with n-1 divisor). min through sd are null when no valid numeric values exist. sd is also null when only one valid value exists (n < 2). mean, median, and sd are null when the column spans a range too wide to compute them in double precision. String and enum columns include topValues (up to 5 most frequent values). The internal row number column (Row #) added by MIDAS is not included in the results.

datasets.query(sql, options?)

Execute a SQL query and return rows (read-only, no dataset creation). SQL follows DuckDB syntax.

const result = await window.midas.datasets.query(
  'SELECT species, AVG(sepal_length) as avg_sl FROM Iris GROUP BY species'
);
// result.data: { columns: ['species', 'avg_sl'], totalRows: 3, returnedRows: 3, rows: [...] }

Table names in FROM and JOIN are dataset names in the project. Matching is case-insensitive, and dataset IDs are not accepted. Use datasets.list() to see the available names. For dataset names containing spaces or non-ASCII characters, use double quotes in SQL (e.g., SELECT * FROM "My Dataset"). The dataset the query runs against is resolved from the first table reference. If no dataset matches, a DATASET_NOT_FOUND error is returned.

Use options.limit and options.offset for pagination. When limit is omitted, all rows are returned. Even with SELECT *, the internal row number column (Row #) added by MIDAS is not included in the results. To include row numbers, create an explicit column such as SELECT ROW_NUMBER() OVER ().

If DuckDB cannot parse the SQL, a SQL_PARSE_ERROR error is returned. Double-quote identifiers that collide with SQL keywords, such as column aliases (e.g., SELECT x AS "order"). SQL that parses but references no table returns a NO_TARGET error.

Column names in the result cannot start with __midas_.

datasets.derive(sql, name, options?)

Execute a SQL query and save the result as a new derived dataset. SQL follows DuckDB syntax.

const result = await window.midas.datasets.derive(
  'SELECT species, AVG(sepal_length) as avg_sl FROM Iris GROUP BY species',
  'Species Averages'
);
// result.data: { id: 'derived_...', name: 'Species Averages', rowCount: 3, columnCount: 2, overwrote: false,
//                lineage: { traceable: true } }

Table names in FROM and JOIN are dataset names in the project. Matching is case-insensitive, and dataset IDs are not accepted. Use datasets.list() to see the available names. For dataset names containing spaces or non-ASCII characters, use double quotes in SQL (e.g., SELECT * FROM "My Dataset"). The source dataset is resolved from the first table reference. If no dataset matches, a DATASET_NOT_FOUND error is returned.

The result data is evaluated and held in memory when derive() completes, so it can be read immediately with datasets.fetch() or datasets.profile(). By default, if a derived dataset with the same name exists, it is updated in place. The existing dataset ID is preserved, so references from tabs and dependent datasets remain valid. Caches of derived datasets that depend on the overwritten dataset, along with estimates of dependent models, are invalidated and re-evaluated with the new data on next access. Set options.overwrite to false to prevent overwriting; if a derived dataset with the same name already exists, an error is returned.

The row numbers (Row #) of the result are the values of its Row # column when the result has one. The column may be carried from the source dataset or defined by the SQL, and its values must be integers with no null and no duplicate, otherwise the call fails. SQL whose result changes on every run (random(), USING SAMPLE) is not guaranteed to behave. See The SQL Query Editor Tab for details.

Column names in the result cannot start with __midas_.

If the output name resolves to the same dataset ID as any table referenced in the SQL's FROM / JOIN clauses, or to any ancestor of those referenced tables (a dataset that one of the referenced tables was derived from), the operation would create a dependency cycle and is rejected with a SELF_REFERENCE error (e.g., derive('SELECT species, COUNT(*) FROM Iris GROUP BY species', 'Iris'), or, given a chain Iris → A → B, derive('SELECT * FROM B', 'A')). If the output name matches an existing primary dataset, a NAME_CONFLICT error is returned (primary datasets cannot be overwritten by derived methods). If a derived dataset with the same name was created by a different method (e.g., trying to overwrite an addColumns dataset with derive), an OPERATION_TYPE_MISMATCH error is returned. If a referenced table name or the output name matches multiple existing datasets case-insensitively, an AMBIGUOUS_TABLE_NAME error is returned.

When the SQL references multiple tables (via JOIN or subqueries), all referenced datasets are stored as the derived dataset's parentIds.

The lineage field of the result reports whether row lineage of the created dataset — one hop to its input datasets — can be traced with datasets.traceRowLineage(). The check reads only the structure of the SQL and does not evaluate the data. Queries containing window functions, set operations such as UNION, or subqueries and CTEs that aggregate with GROUP BY cannot be traced. In that case lineage.traceable is false, reason classifies why, and warnings explains it; see datasets.traceRowLineage() for the list of classifications. An untraceable dataset cannot lead back to the original rows through Contributing rows or graph drill-down, so this field lets you decide at creation time to restructure the query, for example by splitting each aggregation step into its own derived dataset. If the check itself fails, lineage is omitted.

To bring external data in, use datasets.importFromURL or datasets.importFromBuffer.

datasets.importFromURL(url, options?)

Fetch a CSV, TSV, Parquet, or JSON file from an external URL and import it as a primary dataset whose column types are determined. The format is format; when omitted, MIDAS determines it from the extension in the path of the URL, then from the Content-Type of the response. When neither determines it, MIDAS reads the file as Parquet if it starts with the mark of a Parquet file (PAR1), and as CSV otherwise. MIDAS saves the file and the SQL that creates the dataset from the file (the reading SQL) in the project, and the values of the dataset are the result of applying the SQL to the file. Column types are determined once, at import (Data Types). The source of datasets.describe() shows the saved file and SQL. Because the values follow the file, datasets.setCellValues() cannot change them; when the file is updated, read it again with datasets.reload().

const result = await window.midas.datasets.importFromURL(
  'https://example.com/data.csv'
);
// result.data: { id: 'dataset_...', name: 'data', rowCount: 100, columnCount: 5, format: 'csv' }

format is the format the file was read as ("csv", "parquet", or "json").

The options properties are:

  • name: Dataset name after import. When omitted, the name is inferred from the URL.
  • format: The format to read ("csv", "parquet", "json"). "csv" covers CSV and TSV. When omitted, it is determined as described above.
  • hasHeader: Whether to treat the first row as a header. Defaults to true. When false, columns are named Column1, Column2, and so on.
  • encoding: Character encoding ("utf-8", "shift_jis", "euc-jp"). When omitted, encoding is auto-detected from the Content-Type charset and the byte sequence. An unsupported charset is ignored and the byte sequence alone decides. When auto-detected, the result reports the detected encoding as detectedEncoding.
  • delimiter: Delimiter (",", "\t", ";", "|"). When omitted, it follows the file name extension in the URL: tab for .tsv and .txt, comma otherwise.
  • sql: The reading SQL. When omitted, the file is read with the SQL that MIDAS builds from the format and the CSV and TSV settings.
  • overwrite: Whether to replace an existing dataset with the same name. Defaults to false. MIDAS does not replace a dataset whose reloads are prevented (datasets.setPreventReload()), and the method returns an INVALID_INPUT error.

hasHeader, encoding, and delimiter are used only for reading CSV and TSV. The column types and column names of Parquet and JSON files are determined as described in Parquet and JSON, and result.warnings includes the columns read as string because of their values and the number of values that MIDAS changed while reading. When sql is given, MIDAS reads the file with the given SQL and saves that SQL, together with the format and the CSV and TSV settings, in the dataset. This is the same processing as importing with SQL edited in the Import Data dialog. The rules of the SQL, the types of the result columns, and the values that stop the import are as described in Reading SQL. For example, SELECT * FROM read_parquet(getvariable('source_file')) WHERE id > 0 reads only the rows of a Parquet file whose id is positive. For CSV and TSV, MIDAS converts the file to UTF-8 from the encoding given by encoding, or from the detected encoding when encoding is omitted, and the SQL reads the converted file. When the given SQL is the same string as the SQL that MIDAS builds, the file is imported as when sql is omitted. For a dataset imported with a value of sql that differs from the SQL that MIDAS builds, source.sqlFromPreset of datasets.describe() is false. No method returns the SQL that MIDAS builds before the import; import without sql and read source.sql of datasets.describe().

If a dataset with the same name (case-insensitive) already exists, the method returns a DATASET_ALREADY_EXISTS error. Set options.overwrite to true to replace the existing dataset in place (ID preserved). After the replacement, columns with the same name as an existing column keep their column IDs and manual settings (scale, display format). The column types are determined again from the new file, so a column with the same ID can get another type. With sql, the column types are the types of the result of the SQL. Saved models and derived datasets that reference a column whose type changed can fail to re-estimate or evaluate. Columns are matched by their current names, so a column renamed after import is carried over only when the new data has a column with the renamed name. Columns whose names do not exist in the existing dataset get new column IDs. In a pair of a <name> (raw) primary dataset that holds all columns as text without its original file and a <name> derived dataset that converts its types, the derived dataset cannot be overwritten, and the method returns a NAME_CONFLICT error. To update the data of the pair, read <name> (raw) again with datasets.reload(). The returned columnCount matches the number of columns in the source file; with sql, it is the number of result columns of the SQL. The internal row number column (Row #) added by MIDAS is not included in the count.

When the reading is stopped with datasets.cancelReading() or with Stop or Force Stop in MIDAS, the method returns USER_CANCELLED and adds no dataset.

datasets.importFromBuffer(data, options?)

Import CSV, TSV, Parquet, or JSON data from an ArrayBuffer or TypedArray (Uint8Array, Node.js Buffer, etc.) as a dataset. Use this when you want to load a local file from a Playwright test without spinning up an HTTP server. The format is format; when omitted, MIDAS determines it from the extension of fileName, and reads the data as CSV when fileName is also omitted.

// Playwright: load a local CSV via page.evaluate
import { readFileSync } from 'fs';
const csvBytes = Array.from(readFileSync('fixtures/sales.csv'));

const result = await page.evaluate(async (bytes) => {
  const buffer = new Uint8Array(bytes).buffer;
  return await window.midas.datasets.importFromBuffer(buffer, {
    name: 'Sales',
  });
}, csvBytes);
// result.data: { id: 'dataset_...', name: 'Sales', rowCount: 500, columnCount: 7, format: 'csv' }

The options properties are:

  • name: Dataset name after import. Defaults to fileName without its extension when the extension is .csv, .tsv, .parquet, .json, .jsonl, or .ndjson, or "Untitled" when fileName is also omitted.
  • format: The format to read ("csv", "parquet", "json"). Defaults to the format of the extension of fileName, or "csv" when fileName is also omitted.
  • fileName: The name of the original file, with its extension. It becomes the name of the original file in Dataset Metadata. Defaults to buffer.csv, buffer.parquet, or buffer.json. When format is omitted, give an extension of a format MIDAS reads.
  • hasHeader: Whether to treat the first row as a header. Defaults to true.
  • encoding: Character encoding ("utf-8", "shift_jis", "euc-jp"). When omitted, encoding is auto-detected from the byte sequence. When auto-detected, the result reports the detected encoding as detectedEncoding.
  • delimiter: Delimiter (",", "\t", ";", "|"). Defaults to tab when the extension of fileName is .tsv or .txt, and "," otherwise.
  • sql: The reading SQL. Defaults to the SQL that MIDAS builds from the format and the CSV and TSV settings. When given, it is handled as in importFromURL.
  • overwrite: Whether to replace an existing dataset with the same name. Defaults to false.

As with importFromURL, hasHeader, encoding, and delimiter are used only for reading CSV and TSV. Specify the delimiter with delimiter; pass "\t" for TSV data. The returned columnCount matches the number of columns in the source file; with sql, it is the number of result columns of the SQL. The internal row number column (Row #) added by MIDAS is not included in the count.

Datasets are created the same way as importFromURL: one primary dataset whose column types are determined is created, and the data and the reading SQL are saved in the project. The returned id and name point to this dataset. If a dataset with the same name (case-insensitive) already exists, the method returns a DATASET_ALREADY_EXISTS error. Set overwrite: true to replace the existing dataset in place (ID preserved). Column IDs and manual settings are carried over by the same rules as importFromURL, and neither the derived dataset of a <name> (raw) pair nor a dataset whose reloads are prevented can be overwritten, as with importFromURL. When the reading is stopped with datasets.cancelReading() or with Stop or Force Stop in MIDAS, the method returns USER_CANCELLED and adds no dataset.

datasets.generateSynthetic(spec, options)

Generate a synthetic dataset from a data generating process (DGP). This is the same feature as the Synthetic Data Generator tab; the tab's page explains the meaning of distributions, expressions, factors, By, and presets. This section covers the API-specific format: the spec JSON, the options, and the error codes. listSyntheticPresets returns ready-made specs for common designs.

// Generate linear-regression data: y = 1 + 2x + noise (error sd = 0.5)
const result = await window.midas.datasets.generateSynthetic(
  {
    nodes: [
      { name: 'x', dist: { kind: 'normal', mean: { type: 'const', value: 0 }, sd: { type: 'const', value: 1 } } },
      {
        name: 'y',
        dist: {
          kind: 'normal',
          mean: {
            type: 'binary', op: '+',
            left: { type: 'const', value: 1 },
            right: { type: 'binary', op: '*', left: { type: 'const', value: 2 }, right: { type: 'ref', name: 'x' } },
          },
          sd: { type: 'const', value: 0.5 },
        },
      },
    ],
  },
  { name: 'Linear', rows: 200, seed: 42 }
);
// result.data: { id: 'synthetic_...', name: 'Linear', rowCount: 200, columnCount: 2 }

Each element of spec.nodes is one column of the output dataset. Choose a distribution with dist.kind:

  • normal (mean, sd) / uniform (min, max) / gamma (shape, scale) / weibull (shape, scale): continuous values (float64 columns)
  • poisson (lambda) / bernoulli (p): non-negative integers (int64 columns)
  • categorical (levels, weights?): string labels (enum column). weights are relative; sampling is uniform when weights is omitted
  • deterministic (value): a noise-free transformed column. When the top level of the expression is a comparison, the column is a 0/1 indicator and becomes an int64 column; otherwise it is float64

The row structure is declared with spec.factors (an array of factors, each { name, levels }), spec.rowsPerCell (the rows per cell, 1 when omitted), and spec.time (the time column, { name, length }). These correspond to the Factors section, Rows per cell, and Time column of the tab; when declared, the row count is implied by them and options.rows can be omitted. A node's by (an array of column names) corresponds to the By field of the tab and samples the column once per group. See the tab's page for the meaning of factors and By.

The categorical columns and the factor columns become enum columns that reference an enum definition whose values follow the order of levels. MIDAS adds the needed enum definitions to the list of enum definitions together with the dataset. When overwrite: true replaces a dataset, MIDAS chooses the definitions treating the replaced synthetic dataset as the dataset before the edit. See Category Order on the tab's page for how the definitions are chosen and for the rules that make some columns, such as a column with more than 50 levels, string columns.

Distribution parameters are expressions (Expr) in JSON, combining the following nodes.

  • Constant: { type: 'const', value }
  • Reference to another column: { type: 'ref', name }
  • Binary operation: { type: 'binary', op, left, right }. op is one of the arithmetic operators + - * / and the comparisons < <= > >=
  • Unary minus: { type: 'unary', op: '-', operand }
  • Function: { type: 'call', fn, args }. args is an array of argument expressions; exp, log, sqrt, logistic, and abs take one argument, pow, min, and max take two
  • Categorical branch: { type: 'cases', over, map, default? }
  • Past reference: { type: 'lag', name, k }. k is a positive integer, usable only with a time dimension

The vocabulary is the same as the tab's text expressions. See Expression Syntax and the survival data example for the values comparisons return, the rules of cases and lag, and how to compose survival data.

The options properties are:

  • name: Dataset name (required).
  • rows: Number of rows to generate (1 or more, up to 10,000,000). When spec.factors or spec.time is present, this can be omitted and the row count implied by them is used; when given, it must match that row count. Required when the spec has neither.
  • seed: Random seed (required), an integer from −2,147,483,648 to 2,147,483,647 (a signed 32-bit integer). In the same version of MIDAS and the same browser, the same spec, rows, and seed reproduce the same data.
  • overwrite: Whether to replace an existing synthetic dataset with the same name. Defaults to false.

By default, the generated data is not saved to the MDS file; the spec and seed are kept in the generation operation, and the data is regenerated from that operation on reload. See Editing a Saved Dataset for the scope of reproducibility and how to freeze values.

A linear predictor can be mapped into the range 0 to 1 with logistic and to positive values with exp.

If a dataset with the same name already exists and overwrite is false, the method returns DATASET_ALREADY_EXISTS. Only a synthetic dataset created the same way can be replaced with overwrite: true: a name clash with a primary dataset returns NAME_CONFLICT, and a clash with a dataset created by a different method returns OPERATION_TYPE_MISMATCH.

datasets.listSyntheticPresets()

List the built-in synthetic data presets. There are three: multilevel (random intercept), repeated measures (subject × time), and correlated random intercept and slope. They are the same presets the Preset selector of the Synthetic Data Generator tab offers.

const presets = await window.midas.datasets.listSyntheticPresets();
// presets.data: [{ id, label, description, spec, rowCount }, ...]
await window.midas.datasets.generateSynthetic(presets.data[0].spec, { name: 'Schools', seed: 42 });

Each entry carries the following fields.

  • id: the identifier of the preset
  • label: the name shown in the UI
  • description: a description of the design
  • spec: the DGP spec
  • rowCount: the row count implied by the factors

Pass the spec to generateSynthetic as is, or edit it first. Every preset has factors, so the row count is implied by the spec and options.rows is not needed. See Presets for what each preset generates and the constraints on which models MIDAS can fit to it.

datasets.reload(options?)

Reload datasets that were originally imported from a URL or a file, updating them from their original sources.

// Reload all URL- and file-sourced datasets
const result = await window.midas.datasets.reload();
// result.data: { reloaded: [{ datasetId, name, rowCount, previousRowCount, source, clearedExcludedRowCount, clearedRowCommentCount }], failed: [], needsFileSelection: [], prevented: [], stopped: false }

// Reload a specific dataset only
const result = await window.midas.datasets.reload({
  datasetId: 'primary_abc123',
});

URL-sourced datasets are re-fetched from their stored URL. File-sourced datasets are read from the file last selected in the Reload dialog. Re-requesting file read permission needs a user gesture, so the API only reads files whose permission is still granted. Datasets that cannot be reloaded automatically are returned in result.data.needsFileSelection with a reason (no-handle, file-missing, or permission-required); they need a file selection or permission grant in the Reload dialog.

MIDAS does not reload a dataset whose reloads are prevented, and returns it in result.data.prevented with datasetId and name. When reloads of a dataset are prevented while it is being read, MIDAS leaves the dataset unchanged and puts it in result.data.failed. Change the setting with datasets.setPreventReload().

When options.datasetId is specified, only that dataset is reloaded. It accepts a dataset ID or a dataset name (case-insensitive). When omitted, all primary datasets that were imported from a URL or a file are targeted. If the specified dataset does not exist, the method returns a DATASET_NOT_FOUND error.

A dataset imported from a file (one for which datasets.describe() returns source) is read with the reading SQL used at import. A CSV or TSV file is read with the encoding used at import. Column types are not determined again, and the new file replaces the original file. Values that cannot be converted to the column types become null, and the reload succeeds. A dataset whose source.sqlFromPreset is false is reloaded with the saved SQL alone.

A dataset for which source is not returned is read with the header setting of the first import and with the delimiter recorded in the dataset, which is usually the one it was last read with. To read it with another delimiter, pass options.delimiter (",", "\t", ";", or "|") together with options.datasetId. The delimiter used is saved and used for later reloads.

Reload preserves the dataset ID, name, derived datasets, and model bindings. Excluded rows and row comments are cleared. Added columns and reordering are allowed.

result.data.reloaded contains information about successfully reloaded datasets (datasetId, name, updated rowCount, previousRowCount, and source, the URL or file name the dataset was read from). An entry for a reload that made values null, that truncated times to milliseconds, or that fetched from a URL not in the trusted URL list also has warnings. Each entry also reports how many excluded rows and row comments that reload cleared, as clearedExcludedRowCount and clearedRowCommentCount. result.data.failed contains information about failed datasets (datasetId, name, source, and error). When some datasets fail, success is still true. success is false only when all reloads fail.

When the reading is stopped with datasets.cancelReading() or in the UI, result.data.stopped is true, and result.data.failed contains the stopped dataset and the datasets not yet reloaded. MIDAS does not reload them. When every reload failed and the reload was stopped, the method returns a USER_CANCELLED error.

datasets.cancelReading(options?)

Stop the reading of data files in progress. The method stops the reading done by datasets.importFromURL(), datasets.importFromBuffer(), datasets.reload(), project.createFromBuffer(), and project.createFromUrl(). It also stops the reading in the Import Data dialog and the reload dialog, and in Data > Reload All Datasets. The method can be called on the launcher screen too.

// Stop reading (call it while another call, such as importFromBuffer, has not returned)
const result = await window.midas.datasets.cancelReading();
// result.data: { forceStopped: false, interruptedOperations: [] }

// Restart DuckDB when the reading did not stop
const forced = await window.midas.datasets.cancelReading({ force: true });
// forced.data: { forceStopped: true, interruptedOperations: ['Saving or exporting the project'] }

A stopped import fails with a USER_CANCELLED error and adds no dataset. A stopped datasets.reload() lists the stopped dataset and the datasets not yet reloaded in result.data.failed. datasets.importFromURL(), datasets.reload(), and project.createFromUrl() also stop while they fetch a file from a URL. The method does not stop saving, exporting, or opening a project.

Some SQL does not stop without options.force. A reading call that has not returned a few seconds after datasets.cancelReading() did not stop. With options.force: true, the method restarts DuckDB to stop it. Restarting DuckDB also cancels running SQL queries and makes the other file operations in progress fail. Unlike the UI, the method does not ask for confirmation, and returns the failed operations in result.data.interruptedOperations. When saving the project fails this way, the unsaved changes stay in MIDAS, and project.save() can save them again.

datasets.addColumns(datasetId, input)

Add computed columns to a dataset. datasetId accepts a dataset ID or name (case-insensitive). The result is created as a new derived dataset. expression follows DuckDB SQL expression syntax. SQL functions such as CASE WHEN and CAST are supported.

const result = await window.midas.datasets.addColumns('Iris', {
  columns: [
    { name: 'bmi', expression: 'weight / (height * height)' }
  ]
});
// result.data: { id: 'derived_...', name: '...', rowCount: 150, columnCount: 6 }

Use outputName to specify the output dataset name. If a derived dataset with the same name exists, it is updated in place, preserving the existing dataset ID. If outputName resolves to the source datasetId or any of its ancestors (datasets it was derived from), a SELF_REFERENCE error is returned to prevent a dependency cycle; if it collides with an existing primary dataset, a NAME_CONFLICT error is returned. If the existing dataset was created by a different method, an OPERATION_TYPE_MISMATCH error is returned. If outputName matches multiple existing datasets case-insensitively, an AMBIGUOUS_TABLE_NAME error is returned.

datasets.addOrthogonalPolynomials(datasetId, input)

Add orthogonal polynomial columns to a dataset. datasetId accepts a dataset ID or name (case-insensitive). Used as explanatory variables in polynomial regression.

const result = await window.midas.datasets.addOrthogonalPolynomials('Iris', {
  column: 'temperature',
  degree: 3
});
// result.data: { id: 'derived_...', name: '...', rowCount: 150, columnCount: 8, columnNames: ['temperature_poly1', 'temperature_poly2', 'temperature_poly3'] }

Maximum degree is 30. Use outputName to specify the output dataset name. If outputName resolves to the source datasetId or any of its ancestors (datasets it was derived from), a SELF_REFERENCE error is returned to prevent a dependency cycle; if it collides with an existing primary dataset, a NAME_CONFLICT error is returned. If the existing dataset was created by a different method, an OPERATION_TYPE_MISMATCH error is returned. If outputName matches multiple existing datasets case-insensitively, an AMBIGUOUS_TABLE_NAME error is returned.

datasets.reshapeWideToLong(datasetId, input)

Unpivot (melt) a dataset from wide to long format. datasetId accepts a dataset ID or name (case-insensitive). idColumns/valueColumns accept column names or IDs. Same transformation as the Reshape tab's Wide to Long mode; the result is created as a new derived dataset.

const result = await window.midas.datasets.reshapeWideToLong('Scores', {
  idColumns: ['subject'],
  valueColumns: ['test1', 'test2', 'test3'],
  variableName: 'test',
  valueName: 'score'
});
// result.data: { id: 'derived_...', name: 'Scores (Long)', rowCount: 30, columnCount: 3 }

Columns listed in idColumns are copied as-is; each column in valueColumns is expanded into its own row. Row count becomes the source row count times the number of value columns. variableName (default variable) names the column that holds the original column name; valueName (default value) names the column that holds the value. Use outputName to specify the output dataset name. If a derived dataset with the same name exists, it is updated in place, preserving the existing dataset ID. If outputName resolves to the source datasetId or any of its ancestors, a SELF_REFERENCE error is returned; if it collides with an existing primary dataset, NAME_CONFLICT; if the existing dataset was created by a different method, OPERATION_TYPE_MISMATCH; if outputName matches multiple existing datasets case-insensitively, AMBIGUOUS_TABLE_NAME.

datasets.reshapeLongToWide(datasetId, input)

Pivot a dataset from long to wide format. datasetId accepts a dataset ID or name (case-insensitive). idColumns/variableColumn/valueColumn accept column names or IDs. Same transformation as the Reshape tab's Long to Wide mode; the result is created as a new derived dataset.

const result = await window.midas.datasets.reshapeLongToWide('Scores', {
  idColumns: ['subject'],
  variableColumn: 'test',
  valueColumn: 'score'
});
// result.data: { id: 'derived_...', name: 'Scores (Wide)', rowCount: 10, columnCount: 4 }

Rows are grouped by the combination of idColumns values; each distinct value of variableColumn becomes a new column, populated from valueColumn. As in the Reshape tab, the new columns are ordered by a rule derived from the type of variableColumn. When two values give column names that are equal when uppercase and lowercase letters (A to Z) are not distinguished, such as a and A, or when a value gives the name of an idColumns column, the column that comes later in this order gets a sequential number. For example, the columns for the values a and A are named A and a_1. Use outputName to specify the output dataset name. If a derived dataset with the same name exists, it is updated in place, preserving the existing dataset ID. If outputName resolves to the source datasetId or any of its ancestors, a SELF_REFERENCE error is returned; if it collides with an existing primary dataset, NAME_CONFLICT; if the existing dataset was created by a different method, OPERATION_TYPE_MISMATCH; if outputName matches multiple existing datasets case-insensitively, AMBIGUOUS_TABLE_NAME.

datasets.sample(datasetId, input)

Draw rows from a dataset and create a new derived dataset. datasetId accepts a dataset ID or name (case-insensitive). stratumColumn/unitColumn accept column names or IDs. Same operation as the Sampling tab.

const result = await window.midas.datasets.sample('Survey', {
  withReplacement: true,
  size: 100,
  replicates: 200,
  seed: 1
});
// result.data: { id: 'derived_...', name: 'Survey (Sample)', rowCount: 20000, columnCount: 8 }

In the same version of MIDAS, the same input and seed give the same result from the same data. MIDAS draws the sample again with the same seed when the source dataset or the dataset given in size changes.

MIDAS draws separately within each stratum. With stratumColumn, the rows that share a value in that column form one stratum, and the rows with a missing value in that column form one stratum. Without stratumColumn, the whole dataset is one stratum. One draw takes one sampling unit. A sampling unit is one row when unitColumn is omitted, and all rows of the stratum that share a value in that column when it is given. Rows that share a value but belong to different strata are separate sampling units.

size is the number of sampling units drawn from each stratum in one replicate. 'same' means the number of sampling units the stratum has, 'minus_one' means that number minus 1, and a positive integer means that number in every stratum. With { dataset, stratumColumn, sizeColumn }, MIDAS reads the number for each stratum from the dataset dataset. That dataset has one row for each stratum, with the stratum value in the stratumColumn column and an integer of 0 or more in the sizeColumn column. A row with a missing value in the stratumColumn column gives the number for the stratum of missing values. When m sampling units are drawn from a stratum that has n, the expected total of a column over the drawn rows is m/n times its total over the stratum.

The output stacks the number of replicates given in replicates. replicates is an integer from 1 to 10,000,000, and its default is 1. MIDAS puts three columns before the source columns. Replicate is the replicate number starting from 1, Draw is the order of the draw within the replicate starting from 1, and Source Row # is the Row # of the source row. The rows of one sampling unit share a Draw value. A sampling unit drawn twice with replacement gets two Draw values and has the same value in the unitColumn column both times, so Replicate and Draw together identify a drawn sampling unit. When the source dataset has a column whose name is equal when uppercase and lowercase letters (A to Z) are not distinguished, the added column gets a sequential number such as Replicate_1.

Use outputName to specify the output dataset name. If a derived dataset with the same name exists, it is updated in place, preserving the existing dataset ID.

datasets.dummyCode(datasetId, input)

Convert categorical columns to 0/1 dummy variables (treatment coding). datasetId accepts a dataset ID or name (case-insensitive). columns/includedColumns/keepOriginalColumns accept column names or IDs. Same transformation as the Dummy Coding tab; the result is created as a new derived dataset.

const result = await window.midas.datasets.dummyCode('Iris', {
  columns: ['species'],
  referenceCategories: { species: 'setosa' }
});
// result.data: { id: 'derived_...', name: 'Iris (Dummy Coded)', rowCount: 150, columnCount: 6,
//   encodedColumns: [{ column: 'species', referenceCategory: 'setosa', dummyVariableCount: 2 }] }

Each column in columns is converted from k categories into k-1 dummy variables, omitting a reference category (by default, the first category in the category order). Use referenceCategories to set the reference category per column. includedColumns controls which columns pass through to the output (in addition to the dummy-coded columns); when omitted, all source columns except Row # are included, and columns not listed there are dropped. keepOriginalColumns (a subset of columns) keeps the source column in the output alongside its dummy variables. scaleOverrides sets the measurement scale recorded on pass-through columns in the output; the dummy variable columns themselves are always recorded as ratio scale. When categories differ only in uppercase and lowercase letters (A to Z), such as Male and male, or a dummy variable name equals a pass-through column name in that sense, the later dummy variable gets a sequential number, such as sex_male_1. Use outputName to specify the output dataset name. If a derived dataset with the same name exists, it is updated in place, preserving the existing dataset ID. If outputName resolves to the source datasetId or any of its ancestors, a SELF_REFERENCE error is returned; if it collides with an existing primary dataset, NAME_CONFLICT; if the existing dataset was created by a different method, OPERATION_TYPE_MISMATCH; if outputName matches multiple existing datasets case-insensitively, AMBIGUOUS_TABLE_NAME.

datasets.filter(datasetId, input)

Filter a dataset's rows by an expression, creating a new derived dataset. datasetId accepts a dataset ID or name (case-insensitive). Same transformation as the Filtered Data tab's Save as Dataset; the filter is re-evaluated whenever the source data changes.

const result = await window.midas.datasets.filter('Iris', {
  expression: "species = 'setosa' AND sepal_length > 5"
});
// result.data: { id: 'derived_...', name: 'Iris (Filtered)', rowCount: 22, columnCount: 5 }

expression uses the same syntax as the Filtered Data tab's filter input. Missing values follow the same rule as the Data Table filter. A negated condition returns every row that the condition before negation does not match, so species != 'setosa' includes the rows where species is missing. IS NULL and IS NOT NULL are the only syntax that tests whether a value is missing. Besides a column, a condition can test a stat function; see Stat Functions for the syntax and the list of functions. Use outputName to specify the output dataset name. If a derived dataset with the same name exists, it is updated in place, preserving the existing dataset ID. If outputName resolves to the source datasetId or any of its ancestors, a SELF_REFERENCE error is returned; if it collides with an existing primary dataset, NAME_CONFLICT; if the existing dataset was created by a different method, OPERATION_TYPE_MISMATCH; if outputName matches multiple existing datasets case-insensitively, AMBIGUOUS_TABLE_NAME.

datasets.setColumnSchema(datasetId, columnId, schema)

Change a column's data type, measurement scale, or enum definition. datasetId accepts a dataset ID or name (case-insensitive).

const result = await window.midas.datasets.setColumnSchema('Iris', 'col_002', {
  type: 'enum',
  scale: 'nominal',
  enumName: 'species_enum'
});
// result.data: { datasetId: 'ds_001', columnId: 'col_002', createdDerived: true, derivedDatasetId: 'derived_...', overwrote: false }

schema accepts type, scale, enumName, timezone, and numberNotation. At least one of type, scale, and enumName is required. Changing the data type involves SQL type conversion, which creates a new derived dataset. If a derived dataset with the same output name already exists, it is updated in place, preserving the existing dataset ID. If outputName points to the source dataset itself or any of its ancestors (datasets it was derived from), a SELF_REFERENCE error is returned to prevent a dependency cycle; if it collides with an existing primary dataset, a NAME_CONFLICT error is returned. If the existing dataset was created by a different method, an OPERATION_TYPE_MISMATCH error is returned. If outputName matches multiple existing datasets case-insensitively, an AMBIGUOUS_TABLE_NAME error is returned. Changing only the measurement scale updates metadata in place without creating a derived dataset.

When converting to enum type, all column values must be in the enum definition or NULL. The rules for matching column values against the enum definition are the same as in The Convert Column Types Tab.

When converting a string column to datetime, timezone sets the timezone name (e.g., Asia/Tokyo) in which values without a timezone offset are interpreted. When omitted, values are interpreted as UTC. A value with an offset is interpreted with its own offset regardless of the setting. The accepted names and the interpretation rules are the same as the Timezone setting in The Convert Column Types Tab.

When converting a string column to int64 or float64, numberNotation sets the number notation of the values in the form { decimalSeparator, thousandsSeparator }. decimalSeparator is the decimal mark, "." or ",". thousandsSeparator is the thousands separator, one of ",", ".", " ", and "'"; when omitted, the notation has no thousands separator. The two must be different characters. For example, specify { decimalSeparator: ".", thousandsSeparator: "," } for values like 12,340, and { decimalSeparator: ",", thousandsSeparator: "." } for values like 1.234,5. For a conversion to int64, only thousandsSeparator affects the result. When numberNotation is omitted or null, values are read in the notation without a thousands separator and with . as the decimal mark. The rules for the accepted values, including that a value with one separator followed by three digits (1,234) converts with either notation, are the same as the Number notation setting in The Convert Column Types Tab.

datasets.previewTypeConversion(datasetId, conversions)

Count, over all rows of a dataset, the values that column type conversions cannot convert. The counted values are the same as those in the Result column of The Convert Column Types Tab. This method converts nothing and does not change the dataset. The conversion rules are the same as those of the Convert Column Types tab and of type conversion with datasets.setColumnSchema(). datasetId accepts a dataset ID or name (case-insensitive).

const result = await window.midas.datasets.previewTypeConversion('Survey', [
  { columnName: 'age', toType: 'int64', onError: 'exclude' },
  { columnName: 'visited', toType: 'date', onError: 'null' }
]);
// result.data: {
//   datasetId: 'ds_001', rowCount: 120, excludedRowCount: 7,
//   columns: [
//     { columnName: 'age', fromType: 'string', toType: 'int64', onError: 'exclude', converted: true,
//       failedCount: 7, distinctCount: 4,
//       examples: [{ value: 'NA', count: 3 }, { value: '?', count: 2 }, { value: '1.5', count: 1 }] },
//     { columnName: 'visited', fromType: 'string', toType: 'date', onError: 'null', converted: true,
//       failedCount: 0, distinctCount: 0, examples: [] }
//   ]
// }

Each element of conversions specifies the conversion of one column. The elements have the same shape as the elements of operation.conversions that datasets.describe() returns for a column_type_conversion derived dataset. The conversions of an existing derived dataset can therefore be passed as they are to find the values they cannot convert in another dataset. columnName is a column name or column ID, toType is the target type, and onError is what happens to a value that cannot be converted (null, exclude, or fail). For a conversion to enum, enumName names the enum definition. For a conversion from a string column to datetime, timezone, and for a conversion from a string column to int64 or float64, numberNotation have the same meaning as in datasets.setColumnSchema().

rowCount in the result is the number of rows of the dataset, and columns lists the result for each column in the order of conversions. columnName in columns is the column name even when a column ID was specified. failedCount is the number of rows with a value that cannot be converted, and distinctCount is the number of distinct such values. examples returns up to three such values in descending order of row count, and values with the same row count in ascending order of the text. For a numeric column, 10 comes before 9. Each value in examples is the original value as text, before surrounding whitespace is removed, so values that differ only in surrounding whitespace are counted as different values. Missing values (NULL and, in string columns, values that are empty after removing surrounding whitespace) are not counted as values that cannot be converted. When a column already has the type toType, the column is not converted, so converted is false and all counts are 0. For an enum column, this is the case when enumName is the enum definition of the column.

onError does not change which values are counted as values that cannot be converted; it affects only excludedRowCount. excludedRowCount is the number of rows with a value that cannot be converted in any column whose onError is exclude. A row that cannot be converted in several columns counts as one row. When no column uses exclude, excludedRowCount is 0.

If a specified column is not in the dataset, a COLUMN_NOT_FOUND error is returned; if no enum definition has the name enumName, an ENUM_NOT_FOUND error is returned.

datasets.rename(id, newName)

Renames a dataset. Accepts a dataset ID or a dataset name (case-insensitive). The data-table tabs that show the dataset also take the new name.

const result = await window.midas.datasets.rename('Iris', 'Iris 2024');
// result.data: { datasetId: 'ds_001', previousName: 'Iris', name: 'Iris 2024' }

SQL queries of derived datasets that reference this dataset are rewritten to the new name. The SQL Query Editor tab page describes which names are rewritten. Once the rename completes, queries that still use the previous name fail. The derived datasets whose queries are rewritten, and the derived datasets and models that depend on them, are recomputed.

datasets.setDescription(id, description)

Sets the description of a dataset. This is the same description you edit in the Dataset Metadata dialog in the UI. id accepts a dataset ID or a dataset name (case-insensitive).

const result = await window.midas.datasets.setDescription('Iris', "Fisher's iris measurements");
// result.data: { datasetId: 'ds_001', previousDescription: '', description: "Fisher's iris measurements" }

description is stored as given. An empty string removes the description. previousDescription and description are empty strings when there is no description. Read the description you set from description in datasets.describe().

The description is not used in any computation or model estimation, so setting it does not recompute the derived datasets, models, or tab results that depend on this dataset.

datasets.setSaveDataWithProject(id, save)

Sets whether the computed data of a derived dataset is saved in the project file. This is the same setting as Save data with project in the UI, described in Datasets. id accepts a dataset ID or a dataset name (case-insensitive).

const result = await window.midas.datasets.setSaveDataWithProject('Monthly Total', true);
// result.data: { datasetId: 'derived_001', previousSaveDataWithProject: false, saveDataWithProject: true }

When save is true, the next project file you save contains the data that has been computed at the time of saving. Data that has not been computed at that time is not included, and is recomputed when it is first needed after the project is opened. When save is false, the project file contains only the definition of the operation, and MIDAS re-runs the operation when the data is first needed after the project is opened.

Changing the setting changes neither the data nor the project file at that moment. The change does not recompute any dataset. The project file changes the next time you call project.save(), project.exportMds(), or project.downloadMds().

Only derived datasets have this setting.

datasets.retryEvaluation(id)

Evaluates a derived dataset again after its evaluation failed or was cancelled. This is the same operation as Retry in MIDAS. id accepts a dataset ID or a dataset name (case-insensitive).

const result = await window.midas.datasets.retryEvaluation('Monthly Total');
// result.data: { datasetId: 'derived_001', name: 'Monthly Total', rowCount: 12 }

MIDAS keeps the result of an evaluation that failed or was cancelled, and does not evaluate the dataset again until its inputs change or the evaluation is retried with this method or with Retry. A kept cancellation is returned as a USER_CANCELLED error.

An evaluation is cancelled when DuckDB is restarted while the evaluation is running, with Force Stop in MIDAS or with datasets.cancelReading({ force: true }).

retryEvaluation() discards the kept failures of the dataset, of the datasets it is derived from, and of the datasets that depend on those, and then evaluates the dataset. MIDAS estimates again the models whose re-estimation failed among the models that the dataset and the datasets it is derived from use, and the models fitted to the datasets whose failures it discards. A dataset that already has its data is not evaluated again, and the method returns its row count. When the evaluation fails again, MIDAS keeps the new failure. When the evaluation is cancelled, the method returns a USER_CANCELLED error.

datasets.setPreventReload(id, prevent)

Sets whether reloads of a primary dataset are prevented. This is the same setting as Prevent Reload in the UI, described in Prevent Reload. id accepts a dataset ID or a dataset name (case-insensitive).

const result = await window.midas.datasets.setPreventReload('Survey 2025', true);
// result.data: { datasetId: 'primary_001', previousPreventReload: false, preventReload: true }

When prevent is true, MIDAS rejects the operations that replace the contents of the dataset. datasets.reload() and reloads in the UI do not read the dataset again. This setting does not affect editing values with datasets.setCellValues() or with Edit Data in the UI.

datasets.renameColumn(datasetId, columnId, newName)

Renames a column. datasetId accepts a dataset ID or name, and columnId accepts a column ID or name.

const result = await window.midas.datasets.renameColumn('Iris', 'sepal_length', 'sepal length (cm)');
// result.data: { datasetId: 'ds_001', columnId: 'col_001', previousName: 'sepal_length', name: 'sepal length (cm)' }

A column name is also its SQL identifier. SQL queries written against the old name stop matching, so update them yourself after renaming. Renaming invalidates the caches of derived datasets, models, and report elements that depend on this dataset, and they are recomputed.

Columns of a derived dataset cannot be renamed. Their names come from the definition of the dataset, such as its SQL query or its type conversion settings, and every evaluation rebuilds them from that definition. To change a name in a SQL derived dataset, change the AS alias in the query. The column names of a type conversion dataset come from the column names of the dataset it converts, so rename the columns there, or build a dataset from a query that names the columns with AS aliases. Columns of a primary dataset imported from a file can be renamed.

datasets.setColumnDisplayFormat(datasetId, columnId, format)

Sets how a column's values are displayed. datasetId accepts a dataset ID or name, and columnId accepts a column ID or name.

const result = await window.midas.datasets.setColumnDisplayFormat('Issues', 'number', {
  link: { urlTemplate: 'http://example.com/issues/{number}' }
});
// result.data: {
//   datasetId: 'ds_001', columnId: 'col_001',
//   displayFormat: { link: { urlTemplate: 'http://example.com/issues/{number}' } }
// }

A display format consists of two kinds, a link display and a number format, and format names only the kinds to change as keys. link: { urlTemplate } displays values as links. Each {column_name} in urlTemplate is replaced with that column's value from the same row, URL-encoded. A row with a missing value in a referenced column shows plain text instead of a link. number: { formatSpec } displays values with a number format, where formatSpec takes a non-empty Python-compatible format spec. A number format can be set on numeric columns (float64 or int64) only.

The two kinds are independent settings. A kind not named in format keeps its current setting, and a kind set to null is cleared and returns to the same kind in defaultDisplayFormat. When defaultDisplayFormat does not have that kind, the number format becomes the default number format in Settings, and the link display is removed. Passing null as format clears both kinds. The returned displayFormat is the display format after the change, or null when no kind is left.

The format is set on the column, so it applies wherever the column is shown. It also applies to a column that a Derived Dataset includes from this column, for each kind not set on that column. If re-evaluation turns the column into a non-numeric type, MIDAS does not apply the number format until the column becomes numeric again.

A Data Table tab can set a format that applies to that tab alone. Coefficient tables in analysis tabs such as GLM and GLMM have tab-local formats in the same way. These tab formats are view state and are neither readable nor writable from this API. A tab format takes precedence over the column's format kind by kind. A kind set on the tab keeps showing the tab's format even after you change the column's format here, and a kind not set on the tab shows the column's format. When a coefficient table is saved with Save as Dataset, the tab formats at that moment are carried into the dataset as column formats, which this API can then read and write.

Links are rendered only in projects you created yourself and in projects from MDS files whose trust level is Official or Trusted. The trust level of an MDS file is the lowest trust level among everyone in its provenance. In projects whose trust level is Unknown, the format is still stored, but values are shown as plain text instead of links.

datasets.download(id, options)

Downloads a dataset as a CSV, TSV, or JSON file, the same way the Export button in the data table does. Accepts a dataset ID or a dataset name (case-insensitive).

const result = await window.midas.datasets.download('Iris', {
  format: 'csv',
  fileName: 'iris-export',
  encoding: 'shift_jis'
});
// result.data: {
//   datasetId: 'ds_001', fileName: 'iris-export.csv', format: 'csv',
//   rowCount: 150, unrepresentableCharacters: []
// }

format is required. When fileName is omitted the dataset name is used, and the extension is replaced to match the format. CSV and TSV accept includeHeaders (default true), encoding (utf-8, shift_jis, euc-jp), and, for UTF-8, bom. JSON is always UTF-8. Characters the encoding cannot represent are replaced with HTML character references (such as &#233;). Replaced characters are listed in unrepresentableCharacters, at most the first 10 distinct ones, and the warning text carries the total count.

Filters, sorting, and row selection applied in a data table tab are view state rather than part of the dataset, so they cannot be passed here. Narrow the rows with datasets.derive() first when you need a subset.

datasets.create(name, options)

Creates a dataset with the given columns. Every cell starts as a missing value.

const result = await window.midas.datasets.create('Measurements', {
  columns: [
    { name: 'subject', type: 'string' },
    { name: 'score', type: 'float64', scale: 'ratio' }
  ],
  rowCount: 3
});
// result.data: { id: 'manual_...', name: 'Measurements', columnIds: ['col_0_...', 'col_1_...'], rowCount: 3 }

When scale is omitted the measurement scale is inferred from the column type. Write values with datasets.setCellValues(). A column type is one of string, int64, float64, boolean, date, and datetime. Create an enum column as string, then convert it with datasets.setColumnSchema(), passing enumName.

datasets.setCellValues(id, values)

Sets individual cell values in a dataset that holds its own values. Accepts a dataset ID or a dataset name (case-insensitive).

const result = await window.midas.datasets.setCellValues('Measurements', [
  { row: 0, column: 'subject', value: 'A' },
  { row: 0, column: 'score', value: 12.5 }
]);
// result.data: { datasetId: 'manual_...', updatedCells: 2 }

row is a 0-based row position in the data, not in the order the Data Table shows after sorting or filtering. column is a column ID or name. Written values cannot be undone. The dataset keeps no record of the previous values, so the original data is no longer recoverable from the project. Derived datasets, models, and report elements that depend on this dataset are invalidated and recomputed.

Editing cells in the data table converts the text you type into the column type, but this API does not convert values. value has to match the data type of the column. null writes a missing value into a column of any type. A value for an enum column has to be a value of the enum definition as written. A date column takes a YYYY-MM-DD string, and a datetime column takes an ISO 8601 string such as 2024-01-15T10:30:00Z; a datetime without a UTC offset is read as UTC, and both are stored in the same normalized form the data table uses. All input is validated before anything is written, so a single invalid entry leaves the dataset untouched.

This method writes to the rows that were at the given row positions when it was called. On the call, each row is replaced with the Row # of that row, and the write looks up the row with that Row #. If another operation excludes a different row before the write and the positions shift, the method still writes to the same rows.

Values in a derived dataset come from its operation, so they cannot be set cell by cell. A primary dataset imported from a file cannot be edited either, because its values follow the saved file. To correct values, fix the file and read it again with datasets.reload(), or create a derived dataset with corrected values with datasets.derive(). Primary datasets without a saved original file can be edited: datasets created with datasets.create() or in the UI, and <name> (raw) datasets that hold all columns as text.

datasets.excludeRows(datasetId, rows, reason?)

Excludes rows of a dataset that holds its own values, the same as Exclude this row in the Data Table. For what exclusion does to the dataset, see Excluding and Restoring Rows. Accepts a dataset ID or a dataset name (case-insensitive).

const result = await window.midas.datasets.excludeRows(
  'Measurements',
  { filter: "subject IN ('P07', 'P12')" },
  'Withdrew consent'
);
// result.data: { datasetId: 'ds_001', excludedRowNumbers: [6, 11], rowCount: 98 }

rows takes either an array of 0-based row indices or { filter } with an expression in the filter expression, the same forms as datasets.selectRows(). A row index is the position of the row in the data, not in the sorted or filtered order of the Data Table. reason is shown in the Excluded Rows dialog and may be omitted. Derived datasets, models, and report elements that depend on the dataset are invalidated and recomputed without the excluded rows. A filter that matches no rows excludes nothing and still succeeds. All input is validated before anything is written, so an array with an index at or beyond the row count leaves the dataset untouched.

The returned excludedRowNumbers are the Row # values of the excluded rows, the row numbers shown in the Data Table. Excluded rows are no longer in the data and have no row index, so datasets.restoreRows() identifies them by Row #. Row # values stay the same when other rows are excluded or restored. A row that another operation excludes or deletes while this method is running is left out of excludedRowNumbers.

While a Data Table tab has the dataset open in Edit Mode, this method returns an EDIT_MODE_ACTIVE error. Ask the user to finish editing, then call the method again.

A derived dataset has no rows of its own to exclude. Exclude the rows of its source primary dataset instead; the derived dataset is rebuilt from the data without the excluded rows when it is recomputed. To map rows selected on a derived dataset to the rows of its source, use datasets.traceRowLineage().

datasets.listExcludedRows(datasetId)

Returns the excluded rows of a dataset that holds its own values. Accepts a dataset ID or a dataset name (case-insensitive).

const result = await window.midas.datasets.listExcludedRows('Measurements');
// result.data: { datasetId: 'ds_001', excludedRows: [
//   { rowNumber: 6, reason: 'Withdrew consent', excludedAt: '2026-10-06T09:15:00.000Z', values: { subject: 'P07', weight: '250' } }
// ] }

excludedRows is in ascending Row # order. reason is null for rows excluded without a reason, excludedAt is the time of the exclusion in ISO 8601, and values holds the values at the time of the exclusion, keyed by column name.

datasets.restoreRows(datasetId, rowNumbers)

Restores excluded rows, the same as Restore, Restore Selected, and Restore All in the Excluded Rows dialog. Accepts a dataset ID or a dataset name (case-insensitive).

const result = await window.midas.datasets.restoreRows('Measurements', [6, 11]);
// result.data: { datasetId: 'ds_001', restoredRowNumbers: [6, 11], rowCount: 100 }

// Restore every excluded row
await window.midas.datasets.restoreRows('Measurements', 'all');

rowNumbers takes the Row # values returned by datasets.excludeRows() or datasets.listExcludedRows(), or 'all'. A restored row returns to its position in Row # order. Derived datasets, models, and report elements that depend on the dataset are invalidated and recomputed.

Restoring discards the reason and the time of the exclusion, and they cannot be recovered. The Excluded Rows dialog asks for confirmation before Restore All for this reason, but this method does not ask. Read them with datasets.listExcludedRows() first if they are needed.

A row that another operation, such as the Excluded Rows dialog, restores while this method is running is left out of restoredRowNumbers. 'all' on a dataset without excluded rows succeeds without changes. With 'all', restoredRowNumbers lists the rows that were excluded when the rows were restored. In Edit Mode, this method returns an EDIT_MODE_ACTIVE error for the same reason as datasets.excludeRows().

datasets.listRowComments(datasetId)

Returns the row comments of a dataset that holds its own values. Accepts a dataset ID or a dataset name (case-insensitive).

const result = await window.midas.datasets.listRowComments('Measurements');
// result.data: { datasetId: 'ds_001', comments: [
//   { rowNumber: 3, row: 3, comment: 'Checked against the paper form', commentedAt: '2026-10-06T09:20:00.000Z' }
// ] }

comments is in ascending Row # order and includes comments on excluded rows, since excluding a row keeps its comment. row is the current 0-based row index in the data, or null when the row is excluded.

datasets.setRowComments(datasetId, rows, comment)

Sets the same comment on rows of a dataset that holds its own values, the same as Add comment and Edit comment in the Data Table. Accepts a dataset ID or a dataset name (case-insensitive).

const result = await window.midas.datasets.setRowComments('Measurements', [3], 'Checked against the paper form');
// result.data: { datasetId: 'ds_001', rowNumbers: [3] }

rows takes an array of 0-based row indices or { filter }, the same forms as in datasets.excludeRows(). A comment already on a row is replaced. Remove comments with datasets.removeRowComments(). The returned rowNumbers are the Row # values of the commented rows.

Unlike the Data Table, this method works while the dataset is in Edit Mode. This method takes row indices in the saved data and attaches each comment to a Row #, so pending edits do not change which row gets the comment.

datasets.removeRowComments(datasetId, rowNumbers)

Removes row comments of a dataset that holds its own values. Accepts a dataset ID or a dataset name (case-insensitive).

const result = await window.midas.datasets.removeRowComments('Measurements', [3]);
// result.data: { datasetId: 'ds_001', removedRowNumbers: [3] }

rowNumbers takes the Row # values returned by datasets.listRowComments().

datasets.dependents(id)

Returns what datasets.remove() would delete together with the dataset, without changing anything. Accepts a dataset ID or name (case-insensitive).

const result = await window.midas.datasets.dependents('Iris');
// result.data: { datasetId: 'ds_001', name: 'Iris',
//   derivedDatasets: [{ id: 'ds_002', name: 'Setosa' }],
//   models: [{ id: 'model_001', name: 'Sepal fit', type: 'linear_regression' }],
//   reportElements: [{ reportId: 'report_001', reportName: 'Report 1', elements: [{ id: 'el_001', type: 'model_stats' }] }],
//   tabs: [{ id: 'tab_001', title: 'Setosa', type: 'data-table' }] }

derivedDatasets and models are the derived datasets and models that depend on the dataset directly or indirectly. reportElements are the report elements that reference the dataset or any derived dataset or model deleted with it. tabs are the tabs in the active workspace that would be closed.

datasets.remove(id)

Remove a dataset from the project. Accepts a dataset ID or name (case-insensitive).

const result = await window.midas.datasets.remove('Iris');
// result.data: the same shape as datasets.dependents()

datasets.remove() also deletes the derived datasets and models that depend on the dataset directly or indirectly. It removes the report elements that reference the dataset or anything deleted with it, and closes the tabs in the active workspace that show any of them. You can check what will be deleted beforehand with datasets.dependents(). To rename a dataset, use datasets.rename(). If you create a derived dataset under the new name and then remove the original, the new derived dataset depends on the original and is deleted with it.

datasets.fetch(id, options?)

Fetch row data from a dataset without side effects. Accepts a dataset ID or name (case-insensitive).

const result = await window.midas.datasets.fetch('Iris', { limit: 5, offset: 0 });
// result.data: {
//   datasetId: 'ds_001', name: 'Iris', totalRows: 150, returnedRows: 5,
//   columns: ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'],
//   rows: [{ sepal_length: 5.1, sepal_width: 3.5, ... }, ...]
// }

Use limit and offset to control the range of rows returned. When omitted, all rows are returned. The internal row number column (Row #) added by MIDAS is not included in the results. A derived dataset that has not been evaluated yet is evaluated before it is read.

datasets.buildMapping(datasetId, columnId, input)

Generate a value → canonical mapping dataset from unique values in a string or enum column.

// Key Collision: fullwidth normalize → lowercase
const result = await window.midas.datasets.buildMapping('ds_001', 'city', {
  method: { type: 'key_collision', normalizers: ['fullwidth', 'case'] }
});
// result.data: { id: 'primary_...', changedCount: 3, valueCount: 7 }

// Nearest Neighbor: edit distance
const result2 = await window.midas.datasets.buildMapping('ds_001', 'city', {
  method: { type: 'nearest_neighbor', method: 'levenshtein', threshold: 2 }
});

method.type must be 'key_collision' or 'nearest_neighbor'.

Key Collision applies deterministic normalizer functions in order to produce the initial canonical value. Specify the application order in normalizers. Available normalizers: 'trim' (strip surrounding whitespace), 'fullwidth' (NFKC normalization), 'kana' (katakana → hiragana), 'case' (lowercase), 'fingerprint' (lowercase, strip punctuation, deduplicate tokens, sort tokens).

Nearest Neighbor groups nearby values by distance and sets the most frequent value in each cluster as the initial canonical. method must be 'levenshtein' (edit distance). threshold (default: 2) sets the distance cutoff. Maximum unique values: 10,000.

Use overrides to override the canonical for specific values. Use name to set the dataset name (default: {source}_{column}_mapping).

The result is a Primary DataSet with value and canonical columns.

datasets.normalize(datasetId, columnId, mappingDatasetId, input?)

Normalize source data using a mapping dataset. Applies the value → canonical transformation via SQL JOIN.

const result = await window.midas.datasets.normalize('ds_001', 'city', mp.data.id, {
  mode: 'replace'
});
// result.data: { id: 'derived_...', name: 'sales_normalized', rowCount: 100, columnCount: 5,
//                lineage: { traceable: true } }

mode is 'add' (default) to append a {column}_normalized column, or 'replace' to replace the original column with COALESCE(canonical, original_value). Use name to set the output dataset name (default: {source}_normalized). Any dataset with value and canonical columns can be used as the mapping dataset. The lineage field of the result is the same static row-lineage check as datasets.derive().

If a derived dataset with the same name and the same definition already exists, normalize() reuses it instead of creating a new dataset. The definition is the same when the source dataset, the column, the mapping dataset, and mode all match. The result then has reused: true, and its id and name are those of the existing dataset. A same-name derived dataset with a different definition returns a DATASET_ALREADY_EXISTS error, and a same-name primary dataset returns a NAME_CONFLICT error.

datasets.traceRowLineage(datasetId, rowIndices)

Trace one hop of row-level lineage: find the rows of the input datasets that contributed to the given rows of a derived dataset. For a dataset built by Wide to Long in reshape, it collects the rows of the input dataset whose ID Columns values equal those of the requested row and whose value in the column named in the requested row's variable name column equals the value in the requested row's value column.

const result = await window.midas.datasets.traceRowLineage('sales_by_region', [0]);
// result.data: { traceable: true, contributions: [{ datasetId: 'ds_001', datasetName: 'sales', rowIndices: [0, 3, 7] }] }

rowIndices are 0-based row indices within the target dataset. The returned contributions lists the contributing rows per input dataset, so a JOIN yields multiple entries. Each rowIndices is sorted and deduplicated. Passing several rows returns their contributions combined, without a per-row breakdown; call once per row to attribute rows individually.

Traceable SQL shapes: GROUP BY aggregations (including expression keys, GROUP BY by ordinal or output alias, and GROUP BY ALL, which keys on the output columns without aggregate functions), JOIN, FROM subquery and CTE, plain projection and WHERE filter, DISTINCT, and whole-table aggregation (all rows of the input dataset contribute). When a FROM subquery or CTE is a whole-table aggregation without GROUP BY, every input dataset row that passes its WHERE and JOIN contributes to each outer row. Datasets created by Convert Column Types are traceable the same way. Datasets built by filter, crosstab, or reshape (wide/long) are also traceable, matched by the column values of the input dataset. A diagnostic dataset saved with models.saveAsDataset(id, 'diagnostics') from a GLM, linear regression, or GLMM model is traceable to the dataset the model was fitted to, and a dataset created by datasets.sample() is traceable to the sampled dataset. Like filter, these two are matched by column values, using all columns of the input dataset except Row #.

When a query cannot be traced, it returns traceable: false with a reason.

  • window-function: contains a window function or a QUALIFY clause
  • set-operation: contains a set operation such as UNION
  • nondeterministic: contains TABLESAMPLE or a LIMIT without ORDER BY, or the re-evaluated input dataset has no row with the Row # of a row of a diagnostic dataset with saveDataWithProject enabled
  • nested-aggregation: a FROM subquery or CTE aggregates with GROUP BY, GROUP BY ALL, GROUP BY (), or HAVING. A whole-table aggregation without GROUP BY also counts when its FROM contains another subquery or CTE, or when it refers to an outer table
  • nested-distinct-limit: a FROM subquery or CTE uses DISTINCT followed by LIMIT, so the selected rows cannot be matched to rows of the input dataset
  • ambiguous-group-keys: a GROUP BY key is not in the output, so its value cannot be read per row. This includes GROUP BY ALL where * becomes a key
  • no-parent-table: the FROM cannot be resolved to a registered dataset
  • no-parent-dataset: the dataset is derived but has no input dataset to trace (for example a query with no dataset in its FROM, such as SELECT 1)
  • not-derived: the target is not a derived dataset
  • unsupported-operation: the derived dataset was built by an unsupported operation
  • parse-failed: the query's structure could not be analyzed

Some reasons include a detail string with specifics: the table name that could not be resolved (no-parent-table), the original operation type (unsupported-operation), TABLESAMPLE, or the name of the subquery or CTE where the shape was detected (nested-aggregation, nested-distinct-limit).

datasets.openContributingRows(datasetId, rowIndices, targetDatasetId?)

Drill down from a derived dataset to its contributing rows: trace row-level lineage with the same rules as traceRowLineage, then open the contributing rows of the input dataset in a Contributing rows tab. For a JOIN, one tab is opened per contributing input dataset.

Pass targetDatasetId (a dataset ID or name) to jump straight to a specific ancestor: the hops are composed internally and only that ancestor's contributing-rows view is opened (no intermediate tabs). Omitting it goes back one hop to the input datasets.

Calling it again on the rows of an opened Contributing rows view goes back one more hop, to the input datasets of the opened dataset. It stops at a primary dataset or a derived dataset with no input dataset to trace, returning traceable: false with reason: 'no-parent-dataset'.

The temporary view shown in a Filtered Data tab also works as a starting point. That view keeps its filter condition and the dataset it was filtered from even before it is saved, so the datasetId of the tab returned by tabs.list() can be passed directly.

const result = await window.midas.datasets.openContributingRows('sales_by_region', [0]);
// result.data: { traceable: true, opened: [{ datasetId: 'dataset-ephemeral-...', parentDatasetId: 'ds_001', parentName: 'sales', rowCount: 12 }] }

// Drill one more hop up from the opened Contributing rows view
const next = await window.midas.datasets.openContributingRows(result.data.opened[0].datasetId, [0]);

// Jump straight to a specific ancestor (opens only that ancestor's view, no intermediate tabs)
const jumped = await window.midas.datasets.openContributingRows('sales_by_region', [0], 'sales_raw');

The handling of rowIndices and the traceable/untraceable decision rules are the same as traceRowLineage. When the rows cannot be traced, nothing is opened and the result is traceable: false with a reason. Because this opens a tab, it returns a NO_CONTAINER error when no tab container is active (for example, when called outside a project view).

The opened ephemeral datasets carry their lineage. "Save as Dataset" on the tab promotes one to a persistent dataset (a RowLineageOperation) that re-traces the contributing rows on each re-evaluation. When the view depends on other unsaved Filtered Data or Contributing rows views, or on the diagnostic dataset held by a GLM Diagnostics or Residual Diagnostics tab, for example when it was traced from an unsaved Filtered Data view, the save also stores those views as datasets and points the saved lineage at them, so a saved dataset never refers to an Ephemeral Dataset. A view whose recipe matches an existing derived dataset is not duplicated; the saved lineage refers to the existing dataset.

A saved dataset keeps the values used to match the rows of the input dataset when it was saved, and collects the rows that match those values again on each re-evaluation. Rows whose values change so that they no longer match drop out of the contributing rows. When the rows were traced from a dataset built by Wide to Long, rows that matched only by a column removed from Value Columns after the save also drop out of the contributing rows.

datasets.selectRows(datasetId, rows)

Selects rows of a dataset. It writes the same selection state the UI reads, so the selected rows are highlighted in the Data Table, Statistics, and Graph Builder tabs showing that dataset. The call corresponds to the UI operations described in Row Selection and the Filtered Data Tab as follows. An array of 0-based row indices makes the same selection as clicking rows in the Data Table, and { filter } makes a selection that carries a condition, like a rectangle selection in Graph Builder. An empty array clears the selection. Besides columns, the filter expression can test stat functions.

// Select by row index
await window.midas.datasets.selectRows('bike_daily', [0, 1, 2]);

// Select by condition (same syntax as the Data Table filter)
const result = await window.midas.datasets.selectRows('bike_daily', { filter: 'cnt > 8000' });
// result.data: { datasetId: 'ds_001', selectedRows: [ ... ], selectedColumns: [], selectionExpression: '"cnt" > 8000' }

// Clear the selection
await window.midas.datasets.selectRows('bike_daily', []);

The indices are stored in ascending order.

When the selection is made by condition, the result and the selection state carry selectionExpression. It is not the string you passed but a normalized form with column names in double quotes, and it can be passed back to rows.filter as is. A selection with a condition can be opened as a Filtered Data tab by right-clicking a chart in the Statistics tab or a graph in Graph Builder and choosing Open as Filtered Data, and Save as Dataset there promotes it to a derived dataset. A selection made by row index carries no condition, and that menu item is not shown.

Besides persistent datasets, the temporary view of an open Filtered Data tab or Contributing rows tab can be targeted. Pass the datasetId of the tab returned by tabs.list(). When the source dataset of a temporary view changes, MIDAS clears the row selection of that view.

The selection is view state and is not saved in the project file. Statistics in the Statistics tab and model estimation are not affected by it. To compute on a subset of rows, create a derived dataset with datasets.filter() or datasets.derive().

datasets.getSelection(datasetId)

Returns the current selection state of a dataset. Selections made in the UI (clicking rows or columns in the Data Table, rectangle selection in Graph Builder, clicking histogram bins in Statistics) and selections made with selectRows() are read from the same state.

const result = await window.midas.datasets.getSelection('bike_daily');
// result.data: { datasetId: 'ds_001', selectedRows: [3, 8, 21], selectedColumns: ['cnt'], selectionExpression: '"cnt" > 8000' }

selectedRows is an ascending array of 0-based row indices into the dataset. When the Data Table narrows the rows with a filter, the indices still refer to positions in the original dataset, not positions after the filter. selectedColumns holds the names of the selected columns. selectionExpression is present only when the selection was made by condition. When nothing is selected, selectedRows and selectedColumns are empty arrays. As with selectRows(), datasetId also accepts a temporary view.

enums

enums.create(name, values)

Create an enum definition. Up to 50 values can be specified.

const result = await window.midas.enums.create('color', ['red', 'green', 'blue']);
// result.data: { name: 'color', valueCount: 3 }

enums.list()

List all enum definitions.

const result = await window.midas.enums.list();
// result.data: [{ name: 'color', values: ['red', 'green', 'blue'] }, ...]

enums.update(name, values)

Update the values of an existing enum definition.

await window.midas.enums.update('color', ['red', 'green', 'blue', 'yellow']);

Up to 50 values can be specified. Removing values is rejected with ENUM_VALUE_MISMATCH if any dataset still contains the removed values in a column of this enum type. Use Convert Column Types first to null-out or exclude those values, or keep the values in the enum definition.

When the values or their order change, MIDAS recomputes the results computed from the datasets that have a column of this enum type. The affected results are the same as when you edit the definition in the Manage Enums tab.

enums.remove(name)

Remove an enum definition. Returns an ENUM_IN_USE error if columns still reference this enum.

await window.midas.enums.remove('color');

tabs

tabs.list()

List the tabs open in the current workspace. Tabs in other workspaces are not included.

const result = await window.midas.tabs.list();
// result.data: [{ id, type, title, paneId, isActive, datasetId?, targetDatasetId?, editingDatasetId?, reportId?, modelId? }, ...]

paneId is the ID of the pane holding the tab. isActive is true for the tab shown at the front of that pane. One tab is at the front of each pane, so with several panes open, several tabs have isActive: true. Use layout.get() to see how the panes are arranged.

When a tab displays or references a resource, the entry carries its ID as datasetId (the dataset the tab uses; Mapping dataset for an Apply Mapping tab), targetDatasetId (Target dataset of an Apply Mapping tab), editingDatasetId (the dataset whose operation an edit tab edits), reportId, or modelId. These keys appear only on tabs that have them. Statistics and Selected Columns tabs, however, hold no dataset and show the active dataset, so datasetId does not tell which dataset these two tabs show. To find the tabs that use a given dataset, report, or model, including tabs in other workspaces, use tabs.listByResource().

tabs.listByResource(target)

List the tabs that display or reference a dataset, report, or model, in every workspace of the project.

// Find the tabs displaying or referencing dataset ds_001
const result = await window.midas.tabs.listByResource({ datasetId: 'ds_001' });
// result.data: [{ id, type, title, workspaceName, inCurrentWorkspace, datasetId?, targetDatasetId?, editingDatasetId?, reportId?, modelId? }, ...]

Pass exactly one of datasetId, reportId, or modelId in target. datasetId accepts a dataset ID or a dataset name matched case-insensitively. A tab matches a dataset when its datasetId, targetDatasetId, or editingDatasetId is that dataset. Statistics and Selected Columns tabs hold no dataset, so they never match.

workspaceName is the name of the workspace holding the tab. Workspace names are not necessarily unique, so when several workspaces share a name, the result does not tell which of them holds the tab. inCurrentWorkspace is true for a tab in the current workspace. Only those tabs can be passed to tabs.activate(), layout.split(), and the other methods that take a tab ID, because those methods act on the tabs of the current workspace only. The resource ID keys have the same meaning as in tabs.list().

tabs.activate(tabId)

Bring an open tab to the front, as clicking the tab does. The pane holding the tab becomes the active pane, so later calls to tabs.open() put their new tab there.

await window.midas.tabs.activate('tab_001');

tabs.open(config)

Open a new tab. datasetId accepts a dataset ID or name (case-insensitive). For a graph-builder tab, the dataset is bound to the tab, so it shows in the dataset selector and in tabs.getGraphBuilder(). When datasetId is omitted, a tab that selects a dataset (graph-builder, crosstab, reshape, and the model and transform tabs) opens with the active dataset at the time of the call. The query of a sql-editor tab reads the datasets named in its FROM clause, so passing datasetId for a sql-editor tab returns an INVALID_INPUT error. Name the datasets to read in the query of initialQuery.

A data-table tab is always named after the dataset it shows.

Some tabs are opened only once per workspace. The content of report, model-detail, glm-diagnostics, sql-query-viewer, computed-column, column-type-conversion, and orthogonal-polynomials is determined by the target you pass, and the content of project-overview, project-lineage, project-diff, enum-definition, and help is determined by the tab type alone. When a tab with the same content is already open, it is brought to the front instead of a new tab being created, and the returned id is the ID of that existing tab. If that tab sits in another pane, that pane becomes the active one. Later tabs.open() calls then put their new tab there.

The statistics and selected-columns tabs are opened only once per pane. They are meant to sit next to a data table, so activating another pane and calling tabs.open() again opens a second one there. When the active pane already holds a tab of the same type, that tab is brought to the front. These two tabs have no dataset of their own: they show the active dataset, including the filter of its Data Table tab. To see the statistics of a specific dataset, open that dataset in a data-table tab first.

Passing the ID or name of a derived dataset as editingDatasetId opens the same edit tab as Edit Operation... in Project Overview. Saving in the edit tab updates the definition of the operation while keeping the dataset ID. Set type to the tab that edits the dataset's operation, as listed in the table below. The operation type is available as operation.type from datasets.describe().

Operation typeTab type
sql_querysql-editor
synthetic_generationsynthetic-data-generator
crosstabcrosstab
dummy_codingdummy-coding
wide_to_long, long_to_widereshape
samplingsampling
computed_columncomputed-column
column_type_conversioncolumn-type-conversion
filterfiltered-data

tabs.open() rejects datasets that cannot be edited and settings that do not fit an edit tab. A type that differs from the table returns an INVALID_TAB_TYPE_FOR_OPERATION error, whose suggestion names the right type. Edit tabs of sql-editor, synthetic-data-generator, computed-column, and column-type-conversion for the same dataset are opened only once per workspace.

Every tab not listed above opens a new tab on each call. This covers tabs that hold their own input, such as sql-editor opened without a dataset to edit.

// Open Graph Builder
const result = await window.midas.tabs.open({
  type: 'graph-builder',
  title: 'My Graph',
  datasetId: 'ds_001'
});
// result.data: { id: 'tab_...', type: 'graph-builder', title: 'My Graph' }

// Open SQL Query Editor
const result2 = await window.midas.tabs.open({
  type: 'sql-editor',
  initialQuery: 'SELECT species, COUNT(*) AS n FROM Iris GROUP BY species',
  initialOutputName: 'Species Counts'
});

// Open the edit tab of a derived dataset created from SQL
const result3 = await window.midas.tabs.open({
  type: 'sql-editor',
  editingDatasetId: 'Iris Subset'
});

Available tab types:

TypeDescription
graph-builderGraph Builder
sql-editorSQL Query Editor
synthetic-data-generatorSynthetic Data Generator
glmGLM
glmmGLMM
random-forestRandom Forest
linear-regressionLinear Regression
pcaPCA
statisticsDescriptive Statistics
crosstabCrosstab
anovaANOVA
kaplan-meierKaplan-Meier
cox-regressionCox Regression
arimaARIMA
data-tableData Table
reportReport (requires reportId)
computed-columnComputed Column
dummy-codingDummy Coding
orthogonal-polynomialsOrthogonal Polynomials
reshapeReshape
samplingSampling
column-type-conversionType Conversion
enum-definitionEnum Definition
project-overviewProject Overview
project-lineageProject Lineage
selected-columnsSelected Columns
filtered-dataFiltered Data
model-detailModel Detail (requires modelId)
glm-diagnosticsGLM Diagnostics (requires modelId)
glm-predictionGLM Prediction (requires modelId)
sql-query-viewerSQL Query Viewer
variant-normalizationNormalize Variants
apply-mappingApply Mapping
project-diffProject Diff
helpHelp

report tabs require reportId, and model-detail, glm-diagnostics, and glm-prediction tabs require modelId. Set modelId to the ID of a saved model obtained from models.list().

The column selection that the selected-columns tab displays is view state for humans operating the screen. The API can read it with datasets.getSelection() but has no operation to write it. Agents can get column statistics with datasets.profile() instead.

// Open a Model Detail tab
const result3 = await window.midas.tabs.open({
  type: 'model-detail',
  modelId: 'model_001'
});

The glm-diagnostics tab opens both GLM and linear regression (linear_regression) models. For a linear regression model, it hides the Deviance/Pearson residual toggle and changes the heading to Residual Diagnostics.

models.run() supports nine model types: glm, glmm, random_forest, arima, linear_regression, anova, pca, kaplan_meier, and cox_regression. The corresponding tabs (glm, glmm, random-forest, arima, linear-regression, anova, pca, kaplan-meier, cox-regression) plus other analysis tabs (crosstab, statistics) can all be opened with tabs.open(), but only the nine types above can be run programmatically — the rest must be configured and run through the GUI.

tabs.duplicate(tabId)

Duplicate an analysis tab, opening an independent copy next to it. The copy keeps the current settings (predictors, orders, response, and so on) but not the run results or the saved-model state. Only analysis tabs can be duplicated: glm, glmm, anova, linear-regression, cox-regression, kaplan-meier, pca, random-forest, and arima. Other tab types return an INVALID_TAB_TYPE_FOR_OPERATION error.

const result = await window.midas.tabs.duplicate('arima_001');
// result.data: { id, type, title }

tabs.close(id)

Close a tab.

await window.midas.tabs.close('tab_001');

tabs.closeOthers(keepTabId)

Close all tabs except the specified one.

const result = await window.midas.tabs.closeOthers('tab_001');
// result.data: { closedCount: 3 }

tabs.getGraphBuilder(tabId)

Get Graph Builder tab configuration.

const result = await window.midas.tabs.getGraphBuilder('tab_001');
// result.data: { tabId, graphType, datasetId, config, aspectRatio,
//   availableColumns, lineageTargetDatasetId, availableLineageTargets,
//   renderStatus?, renderStatusMessage?, renderWarnings? }

renderStatus tells whether the graph is rendered with the current configuration. Its values mean the same as renderStatus in reports.getContent(), and renderStatusMessage gives the reason when it is not 'ok'. renderStatus can change when the data changes, without a call to an API that changes the graph's configuration. renderStatus and renderWarnings are evaluated only when a dataset is selected. The evaluation uses the data after the tab's filter expression is applied, the same data the preview draws.

renderWarnings holds the diagnostics shown above the Graph Builder preview for the current configuration, one message per element. A layer that reports the labelContent diagnostic draws none of its labels, and a layer that reports the filter diagnostic draws nothing, while the rest of the graph is rendered. The exception is a warning that the panel count exceeds the limit configured in Settings (Max Facet Panels): with this warning, renderStatus is 'error' and the graph is not rendered. The field is omitted when there is no diagnostic. Pair Plot shows no diagnostics in the preview, so this field is always omitted for Pair Plot. A diagnostic that depends on the rendered size appears only in the on-screen warning and is not included in this field. For a graph with facets, and for a Histogram with groupMode set to 'faceted', diagnostics are evaluated per panel and arrive in the same form as the preview warning strip: each line is prefixed with the title of the panel that reported it, and a warning common to all panels is merged into a single All panels: line.

tabs.addGraphLayer(tabId, layer, options?)

Add a layer to a custom graph. Only works when graphType is 'custom'.

On a tab in multi-panel mode, name the target panel with panelIndex in the third argument options. On success, result.data holds layerIndex (the index within that panel) and panelIndex. See panels under configureGraph for how to set up multi-panel mode.

await window.midas.tabs.addGraphLayer('tab_001', {
  geom: { type: 'line' },
  aes: { y: 'pop' }
}, { panelIndex: 1 });
// result.data: { layerIndex: 1, panelIndex: 1 }
const result = await window.midas.tabs.addGraphLayer('tab_001', {
  geom: { type: 'point' },
  aes: { x: 'sepal_length', y: 'sepal_width', color: 'species' }
});
// result.data: { layerIndex: 0 }

Aesthetic mappings (aes) accept column names or column IDs. Column names are resolved case-insensitively. Available properties are x, y, color, fill, stroke, size, shape, alpha, linetype, ymin, ymax, label, group, and weight. The properties aes accepts depend on the geom type — for example, Point and Line do not read fill. weight maps a numeric column of frequency weights; it does not affect how the geom is drawn, and only stats that support weights (roc) read it. aes accepts column references only; set a fixed color, size, or opacity in geom.defaults, not in aes. The keys each geometry accepts in geom.defaults are listed in the Custom Graph Reference. When stats is omitted, identity is used by default. When position is omitted, bar geom defaults to { type: "stack" } (stacked); other geoms default to identity. Use scales to configure per-layer scales (color, fill, shape, linetype, size, alpha). See configureGraph for details.

A key whose value is undefined counts as omitted.

A layer goes through the per-layer validation the renderer runs before it is saved. A layer that fails validation is still saved and the call succeeds. Anything that failed validation is reported in warnings, and the graph does not render until it is fixed.

When using the Text or Label geom ({ type: 'text' }, { type: 'label' }) with aggregating stats (summary, count, bin, etc.), the column mapped via aes.label is lost during aggregation. Use geom.defaults.labelContent to reference stat output variables instead.

await window.midas.tabs.addGraphLayer(tabId, {
  geom: {
    type: 'label',
    defaults: {
      labelContent: { field: '$y', format: '.1f', prefix: 'Mean: ' }
    }
  },
  stats: [{ type: 'summary', params: { outputs: [{ fun: 'mean', to: 'y' }] } }],
});

labelContent properties:

PropertyTypeDescription
fieldstringField to display. A stat variable ($x, $y, $n, etc.), a column name, or a column ID. Column names are resolved case-insensitively. A value that cannot be resolved returns a COLUMN_NOT_FOUND error
formatstringd3-format specifier (e.g. .2f, ,.0f). It applies only to numeric values
prefixstringString prepended to the formatted value
suffixstringString appended to the formatted value

When labelContent is set, aes.label is not required.

The Text geom draws the text at the point, and the Label geom draws it in a box with a leader line.

Layers also accept these optional properties:

PropertyTypeDescription
namestringDisplay name for the layer
filterstringFilter expression that narrows this layer's data. Uses the same syntax as the Data Table filter input (see Filter Expressions) and is validated by the same rules, so an expression with a syntax error, an unknown column, a value that does not match the column's type, NULL written as a value, LIKE or ILIKE on a column other than string and enum, a LIKE or ILIKE pattern that is not a string, an order comparison on a column whose measurement scale is nominal, or an order comparison of an enum column with a value outside its enum definition returns INVALID_INPUT
visiblebooleanShow or hide the layer (default true)
yAxis'primary' | 'secondary'Which Y axis to use
showLegend'auto' | 'show' | 'hide'Legend visibility for this layer
clickSelectionbooleanEnable click-to-select on data points (default true, or false for a layer whose stat is smooth, density, or cookcontour)
tooltiparray | { content: 'encoding' }Content shown when hovering a data point. See below

Set tooltip to an array of field definitions to show specific values on hover, or to { content: 'encoding' } to auto-generate fields from the layer's aes. When the layer's position is fill, the auto-generated $y field is labeled with (% of total) and its value is shown as a percentage. A $y field given in the array is also shown as a percentage when format is omitted, and labeled % of total when both format and label are omitted. The denominator is the sum of absolute values at each x position. With the same setting, the auto-generated title of the proportion axis also gets the (% of total) suffix and its ticks use percent format. When the layer's stat has yScale density or proportion, the tooltip label and the axis title use % of total, groups weighted equally instead. See Stack as 100% Proportions for details. Omitting tooltip shows no tooltip.

await window.midas.tabs.addGraphLayer(tabId, {
  geom: { type: 'point' },
  aes: { x: 'sepal_length', y: 'sepal_width' },
  tooltip: [
    { field: '$x', label: 'Sepal Length' },
    { field: 'species' }
  ]
});

Tooltip field properties:

PropertyTypeDescription
fieldstringStat variable ($x, $y, $n, etc.) or a column name or ID
labelstringCustom label (omit for no label, value only)
formatstringd3-format specifier (e.g. .2f, ,.0f). It applies only to numeric values
type'datetime' | 'date'Formats the field as a date or datetime string

See Custom Graph Reference for the list of geom, stat, and position types. Each stat's params are documented there with their accepted values and defaults. For facets, coordinates, and other graph-level options, see Custom Graph.

tabs.updateGraphLayer(tabId, layerIndex, layer, options?)

Partially update an existing layer. Only the specified fields are changed; omitted fields retain their current values. Each specified field is replaced as a whole by the value passed and is not merged with the current value; for example, passing geom drops any geom.defaults keys it does not include. The fields are the same as in addGraphLayer: name, geom, aes, stats, position, scales, tooltip, filter, visible, yAxis, showLegend, and clickSelection can be changed with the same meaning. On a tab in multi-panel mode, name the target panel with panelIndex in the fourth argument options; layerIndex is then the index within that panel.

await window.midas.tabs.updateGraphLayer('tab_001', 0, {
  geom: { type: 'line' }
});

When the geom or stats change and the current position (or the geom default when position is unset) is not allowed by the resulting geom and stat combination, position is automatically reset to identity and a warning is returned.

The updated layer also goes through the same validation as addGraphLayer. The validation looks at the result of merging the update into the existing layer, not at the update itself.

An update that changes only the geom keeps the existing aes.

Pass scales: null to remove layer-specific scales and fall back to the default scales. Pass position: null to reset position to the default (unset). Pass tooltip: null to remove the tooltip. Pass filter: null or an empty string to remove the layer filter.

tabs.removeGraphLayer(tabId, layerIndex, options?)

Remove a layer. On a tab in multi-panel mode, name the target panel with panelIndex in the third argument options; layerIndex is then the index within that panel. The last layer of a panel can be removed, but the graph does not render until every panel has a layer again, and warnings reports this.

await window.midas.tabs.removeGraphLayer('tab_001', 0);

tabs.moveToPane(tabId, toPaneId, options?)

Move a tab to a different pane. Take the ID of the destination pane from layout.get(), or, when you create a pane to lay tabs out side by side, from what layout.split() returns. The moved tab becomes the front tab of the destination pane, and the destination pane becomes the active pane. New tabs that tabs.open() creates afterwards therefore open in the destination pane.

options.index sets where the tab goes in the destination pane. The position is counted from 0 in the order of the tabs in the pane after the move. When it is omitted, the tab goes to the end of the destination pane. Passing the tab's current pane as toPaneId together with options.index reorders the tab within that pane, without changing the front tab or the active pane. Passing the tab's current pane without options.index leaves the tab where it is.

await window.midas.tabs.moveToPane('tab_001', 'pane_002');
await window.midas.tabs.moveToPane('tab_003', 'pane_002', { index: 0 });

tabs.setDataset(tabId, datasetId)

Switch a tab's dataset. datasetId accepts a dataset ID or name (case-insensitive). For a graph-builder tab, the new dataset shows in the dataset selector and in tabs.getGraphBuilder(). statistics and selected-columns tabs cannot be the target of this method, because they show the active dataset. Of the other tab types, this method accepts only those whose open tab follows the change: data-table, sql-query-viewer, graph-builder, crosstab, reshape, sampling, variant-normalization, glm, glmm, linear-regression, random-forest, pca, anova, arima, kaplan-meier, and cox-regression.

computed-column, dummy-coding, orthogonal-polynomials, and column-type-conversion tabs belong to this rejected group. The Agent API runs the same operations on a dataset directly with datasets.addColumns(), datasets.dummyCode(), datasets.addOrthogonalPolynomials(), and datasets.setColumnSchema().

Settings that refer to columns follow the same rules as choosing a dataset in the tab's own selector. A crosstab tab keeps fields whose name exists in the new dataset (value fields also need a numeric or boolean column), and a reshape or sampling tab keeps column settings whose name exists there. A graph-builder tab clears its filter expression and lineageTargetDatasetId. For a Custom Graph, the layers are also checked against the new dataset for values outside the valid range of a log or sqrt axis, as in configureGraph, and problems are reported in result.warnings. Tabs that select variables by column ID, such as regression, survival analysis, and PCA, clear their variable selections. A data-table tab has no dataset selector; switching its dataset resets its filter expression, sort, column widths, and the column display formats set on that tab only. Passing the tab's current dataset leaves its settings unchanged.

const result = await window.midas.tabs.setDataset('tab_001', 'ds_002');
// result.warnings: ["Removed fields not present in the selected dataset: region"]

tabs.configureGraph(tabId, config)

Configure a Graph Builder tab in one call. Select the chart type with graphType. datasetId accepts a dataset ID or name (case-insensitive); pass an empty string to clear it. Column names are resolved case-insensitively.

The graph type is graphType when it is passed, otherwise custom when layers is passed, and otherwise the type the tab already has. filterExpression sets a filter expression that narrows the rows of the whole graph, in the same syntax as the Data Table filter input.

await window.midas.tabs.configureGraph('tab_001', {
  graphType: 'custom',
  datasetId: 'ds_001',
  layers: [
    { geom: { type: 'point' }, aes: { x: 'weight', y: 'height', color: 'group' } }
  ],
  aspectRatio: '4:3'
});

Use coordinates to set the coordinate system. 'flipped' swaps the X and Y axes. 'cartesian' resets to the default Cartesian coordinates.

await window.midas.tabs.configureGraph('tab_001', {
  coordinates: 'flipped'
});

Use scales to configure axis scales. When calling configureGraph with scales, only the specified axes are updated; unspecified axes retain their existing settings. An axis you do not specify gets its scale inferred from the scale and type of the column mapped to it: columns with a nominal or ordinal scale become categorical, other date and datetime columns become time, and other numeric columns become linear. On an ordinal enum column, the inferred categorical scale gets limits set to the enum definition order. Scales you specify explicitly take precedence.

await window.midas.tabs.configureGraph('tab_001', {
  scales: { y: { type: 'log', title: 'Log scale' } }
});

y2 is the scale of the secondary Y axis on the right, which layers with yAxis: 'secondary' use. Passing scales: { y2: null } to configureGraph makes MIDAS remove scales.y2 and stop drawing the secondary Y axis.

Each axis (x, y, y2) in scales accepts:

PropertyTypeDescription
type'linear' | 'log' | 'sqrt' | 'time' | 'categorical'Scale type
titlestringAxis title
domain{ min?, max? }Range for continuous scales (not applicable for categorical)
tickCountnumberNumber of ticks (not applicable for categorical)
limitsstring[]Category display order (categorical only)
breaksstring[]Subset of categories to display (categorical only)
labelsRecord<string, string>Custom display names for categories (categorical only)
labelRotation'auto' | 0 | 45 | 90Label rotation angle
zoomEnabledbooleanfalse keeps this axis fixed during zoom and pan (not applicable for categorical; default true)
titlePaddingnumberGap between the axis title and the tick labels (pixels; default 15 on the X axis and 6 on the Y axis)
labelPaddingnumberGap between the tick labels and the tick marks (pixels; default 3)

limits sets the category display order on the axis. The values listed in limits come first in that order, and values not listed follow them.

Per-layer scales are set via layers[].scales, which accepts the color, fill, shape, linetype, size, and alpha aesthetics. Per-layer tooltips are set via layers[].tooltip (see addGraphLayer).

await window.midas.tabs.configureGraph('tab_001', {
  graphType: 'custom',
  datasetId: 'ds_001',
  layers: [{
    geom: { type: 'tile' },
    aes: { x: 'col_x', y: 'col_y', fill: 'col_value' },
    scales: { fill: { scaleType: 'sequential', paletteId: 'viridis' } }
  }]
});

Each color / fill scale accepts:

PropertyTypeDescription
scaleType'categorical' | 'sequential' | 'diverging' | 'threshold'Color scale type
paletteIdstringPalette ID. See Custom Graph Reference for available values
domain{ min?, max?, center? }Domain for continuous scales
legendPosition'right' | 'left' | 'top' | 'bottom' | 'none'Legend position
legendTitlestringLegend title
thresholdsnumber[]Threshold values (threshold type)
thresholdColorsstring[]Colors for each region (threshold type, length = thresholds.length + 1)
thresholdVariable'x' | 'y'Variable used for threshold comparison (threshold type, default 'y')

The effective scaleType is determined from the specified value, the column type, and the stats of the layer. Here, a column usable for a continuous color scale is an int64 or float64 column with an interval or ratio scale. When omitted, an aesthetic that a Summary stat uses as its input or as an output target uses sequential if no column is assigned or the column is usable for a continuous color scale, and categorical otherwise. Otherwise, fill uses sequential for a column usable for a continuous color scale and categorical for other columns, and color uses categorical. A color or fill whose scaleType is categorical splits the points into groups. When sequential or diverging is specified for a column that is not numeric, MIDAS gives priority to the column type, renders the aesthetic with a categorical scale, and reports the mismatch in the warnings of the configuring call's response and in the diagnostics (renderWarnings). However, when a diverging paletteId is also specified, the palette is incompatible with the effective categorical scale, so validation fails and the graph is not rendered. A sequential palette remains usable with a categorical scale and does not cause this error. The incompatible combination is reported in the warnings of the configuring call's response, and reports.addGraph / reports.updateElement return renderStatus: 'error'.

Each shape / linetype scale accepts:

PropertyTypeDescription
shapes('circle' | 'square' | 'triangle' | 'diamond' | 'cross' | 'plus')[]Shapes assigned to categories, in order (shape aesthetic)
linetypes('solid' | 'dashed' | 'dotted')[]Line styles assigned to categories, in order (linetype aesthetic)
legendPosition'right' | 'left' | 'top' | 'bottom' | 'none'Legend position
legendTitlestringLegend title

The first entry in the list goes to the first category. When there are more categories than entries, the list repeats from the start. The legend position applies to the whole graph: it is taken from the first legend-showing layer, searching its color, fill, shape, and linetype scales in that order. Only aesthetics with a column mapped are searched, so a legendPosition set on an aesthetic without a column does not affect the legend and is reported in warnings.

The size / alpha scales accept a range only. Neither aesthetic draws a legend.

PropertyTypeDescription
range{ min?, max? }Range of drawn values. Defaults are 2-20 (pixels) for size and 0.2-1 for alpha
await window.midas.tabs.configureGraph('tab_001', {
  graphType: 'custom',
  datasetId: 'ds_001',
  layers: [{
    geom: { type: 'point' },
    aes: { x: 'weight', y: 'mpg', shape: 'origin', size: 'horsepower' },
    scales: {
      shape: { shapes: ['square', 'triangle', 'diamond'], legendTitle: 'Origin' },
      size: { range: { min: 4, max: 30 } }
    }
  }]
});

Use facets to split the graph into panels by one or two categorical variables. Two modes are supported: wrap (single variable, auto-arranged panels) and grid (row and/or column variables).

// Facet wrap: split by one variable
await window.midas.tabs.configureGraph('tab_001', {
  facets: { type: 'wrap', variable: 'species', ncol: 3, scales: 'free_y' }
});

// Facet grid: split by row and/or column variables
await window.midas.tabs.configureGraph('tab_001', {
  facets: { type: 'grid', rows: 'region', cols: 'year' }
});

// Remove facets
await window.midas.tabs.configureGraph('tab_001', { facets: null });

Use panels to set up multi-panel mode. Multi-panel mode is the same feature as Enable Multi-Panel Mode in the Multi-Panel section of the Graph Builder: it stacks several panels vertically, shares the X axis among them, and moves zoom and pan together. Each panel holds the layers to draw in layers. yScale is the panel's own Y axis scale and accepts the same properties as each axis in scales; a panel without it uses scales.y. heightRatio is the relative height (default 1), and name is the label shown at the top left of the panel.

In multi-panel mode only the layers of each panel are rendered; the graph-level layers and facets are not. Edit the layers of a panel with addGraphLayer / updateGraphLayer / removeGraphLayer, passing panelIndex. Setting panels removes any existing facets, which warnings reports. Pass panels: null to return to a single panel; when layers is not passed in the same call, the layers of all panels are concatenated in order into the graph's layers.

A panel in multi-panel mode has no secondary Y axis, and MIDAS draws every layer in a panel on the Y axis of that panel. Each panel has its own Y axis, so quantities of different magnitudes go in separate panels. In multi-panel mode MIDAS does not use the graph's scales.y2, and includes layers with yAxis: 'secondary' in the range of the panel's Y axis. Both settings stay in the graph and take effect again when panels: null returns it to a single panel, provided that scales.y2 is set and the coordinates are not flipped.

await window.midas.tabs.configureGraph('tab_001', {
  graphType: 'custom',
  datasetId: 'ds_001',
  globalAes: { x: 'year' },
  panels: [
    { name: 'Life expectancy', layers: [{ geom: { type: 'line' }, aes: { y: 'lifeExp' } }], heightRatio: 2 },
    { name: 'Population', layers: [{ geom: { type: 'line' }, aes: { y: 'pop' } }], yScale: { type: 'log' } }
  ]
});

// Return to a single panel
await window.midas.tabs.configureGraph('tab_001', { panels: null });

Use brush to set the direction of brush selection. Brush selection is the operation of dragging over a range in the Select mode of the graph toolbar to select the rows of the elements in the range. With direction 'xy' the selection is a two-dimensional rectangle, with 'x' it is a range along the X axis, and with 'y' it is a range along the Y axis. The default is 'xy'. Pass brush: null to return to the default. A graph with no selectable layer in the direction does not show the Select mode button. Selection Conditions describes which layers can be selected.

await window.midas.tabs.configureGraph('tab_001', { brush: { direction: 'x' } });

Omitting facets preserves the current setting.

Facet wrap properties:

PropertyTypeDescription
type'wrap'Facet wrap mode
variablestringColumn name or ID to facet by (required)
ncolnumberNumber of columns, an integer of 1 or more (auto-calculated if omitted)
nrownumberNumber of rows, an integer of 1 or more (auto-calculated if omitted)
completebooleanAfter the summary stat aggregates, adds a point whose aggregated value is 0 at each X value that has no data. When the column assigned to Y is used as a position without being aggregated (as in a heatmap), the points are added at the X and Y pairs that have no data. When color or another aesthetic splits the data into series, the points are added for each series. The candidate X and Y values are collected from the data of all panels
scales'fixed' | 'free_x' | 'free_y' | 'free'Axis scale sharing across panels (default: 'fixed')

Facet grid properties:

PropertyTypeDescription
type'grid'Facet grid mode
rowsstringColumn name or ID for row faceting
colsstringColumn name or ID for column faceting
completebooleanAfter the summary stat aggregates, adds a point whose aggregated value is 0 at each X value that has no data. When the column assigned to Y is used as a position without being aggregated (as in a heatmap), the points are added at the X and Y pairs that have no data. When color or another aesthetic splits the data into series, the points are added for each series. The candidate X and Y values are collected from the data of all panels
scales'fixed' | 'free_x' | 'free_y' | 'free'Axis scale sharing across panels (default: 'fixed')

At least one of rows or cols is required for facet grid.

For the simple graph types — histogram, scatter, timeseries, bar, pairplot, and datetime_histogram — set the fields specific to that type via graphType. layers, panels, globalAes, scales, coordinates, facets, and brush are fields of custom only.

await window.midas.tabs.configureGraph('tab_001', {
  graphType: 'histogram',
  datasetId: 'ds_001',
  column: 'sepal_length',
  bins: 20
});

Column fields such as column, xColumn, and categoryColumn accept either a column name or a column ID. The type-specific fields are:

Graph typeFields
histogramcolumn, bins, relativeFrequency, showDensity, orientation, groupByColumn, groupMode, facetNcol, showAnnotations
scatterxColumn, yColumn, colorColumn, referenceLines, xScaleType, yScaleType, density options (displayMode, densityVisualization, densityBandwidth, contourLevels, densityColorScale)
timeseriesxColumn, yColumns, rangeColumns, rangeOpacity
barcategoryColumn, valueColumns, aggregation, groupByColumn, orientation, showValues, stackMode, sortOrder, topN
pairplotcolumns
datetime_histogramcolumn, interval, showTrend

The bins field of histogram is an integer between 1 and 100. For a column whose values are all integers, the bin width is the range of the values divided by bins, rounded up to an integer, and the number of bins differs from bins. The bins are determined in the same way as integerBins of the Bin stat.

For bar, valueColumns takes an array with one element: the column to aggregate, or '$count' for a row count. aggregation is the aggregation method of the column (sum, average, median, min, or max; the default is average) and is not used with '$count'. groupByColumn takes a categorical column other than categoryColumn that splits the bars into series; pass null to remove it.

For bar, topN sets the number of categories to show, as an integer of 1 or more. To remove a stored topN and show all categories, pass topN: null; to keep the current value, omit topN.

The boxplot and heatmap graph types cannot be configured; passing either returns an INVALID_GRAPH_TYPE error. For a box plot, use graphType: "custom" with a layer of geom: { type: "boxplot" } and stats: [{ type: "boxplot" }].

Every configurable graph type accepts lineageTargetDatasetId (ID or name). When datasetId is a derived dataset (for example a GROUP BY aggregate, or a filter or reshape of the original rows), set this to an ancestor so that clicking an element selects the underlying rows and double-clicking opens their contributing rows in a Contributing rows tab. The value must be a contributing-rows ancestor of datasetId; check the candidates with getGraphBuilder's availableLineageTargets. Pass an empty string or null to reset to the graph's own dataset.

Even a valid ancestor can be untraceable at runtime if a hop between datasetId and the target uses a window function or a set operation.

models

models.list()

List the models saved in the project, including ones waiting to be re-estimated.

const result = await window.midas.models.list();
// result.data: [{ id, type, name, datasetId, family?, estimationState, estimationError? }, ...]

type is one of 'glm', 'glmm', 'random_forest', 'arima', 'linear_regression', or 'anova'.

family is present for GLM, GLMM, and linear regression models.

estimationState is the estimation state of the model. models.list() only reads the state and does not start an estimation. The value is one of the following four.

  • 'unestimated': The model has no estimates, and no estimation is running
  • 'estimating': An estimation is running
  • 'estimated': The model has estimates
  • 'failed': The estimation failed. estimationError holds the reason

models.run(config)

Run a model. Set config.type to 'glm', 'glmm', 'random_forest', 'arima', 'linear_regression', 'anova', 'pca', 'kaplan_meier', or 'cox_regression'. datasetId accepts a dataset ID or name (case-insensitive) and must refer to a primary or derived dataset. Columns can be specified by name (case-insensitive). The result is returned directly without opening a tab. To persist the model for later use with models.list() and models.describe(), call models.save() with the returned runId. Unsaved run results are kept in memory, up to 20. Beyond that limit, the oldest unsaved results are discarded first, and a discarded runId can no longer be passed to models.save(). All unsaved results are also lost on page reload.

GLM, GLMM, linear regression, and Random Forest accept only the columns that the selectors on the corresponding tab can pick. A categorical predictor is used by creating dummy variables with datasets.dummyCode() and passing the generated columns.

GLM (type: 'glm'):

const result = await window.midas.models.run({
  type: 'glm',
  datasetId: 'ds_001',
  yColumn: 'sepal_length',
  xColumns: ['sepal_width', 'petal_length'],
  family: 'gaussian'
});
// result.data:
// {
//   type: 'glm',
//   runId: '...',
//   family: 'gaussian',
//   link: 'identity',
//   coefficients: [
//     { variable: '(Intercept)', estimate: 2.25, se: 1.02, ciLower: 0.23, ciUpper: 4.27, expEstimate: null, expCiLower: null, expCiUpper: null },
//     ...
//   ],
//   inference: { distribution: 't', df: 147 },
//   fit: { deviance: 42.3, nullDeviance: 234.7, aic: 183.94, bic: 193.47, iterations: 5, converged: true },
//   inSampleAccuracy: { kind: 'continuous', n: 150, r2: 0.82, rmse: 0.53, mae: 0.42 },
//   diagnosticSummary: { nObservations: 150, nIncomplete: 0, degreesOfFreedom: 147, dispersionParameter: 0.29 },
//   warnings: []
// }

inSampleAccuracy holds prediction accuracy metrics computed on the fitting data itself, using the same calculation as the In-Sample Prediction Accuracy Metrics shown on the GLM tab right after Run. kind follows the family: gaussian returns 'continuous' (r2, rmse, mae), binomial returns 'binary' (brier, auc, with n being the total number of trials), and gamma, poisson, and negative-binomial return 'deviance' (rmse, mae, meanDeviance). Values that cannot be computed are null, and the whole field is null when no valid rows remain.

Fields in coefficients:

FieldDescription
estimateCoefficient estimate on the link scale
seStandard error of the estimate
ciLower / ciUpperLower and upper bounds of the Wald confidence interval. The reference distribution is reported in inference; see the family-by-family table below
expEstimate / expCiLower / expCiUpperThe exp() transformation of the estimate and confidence interval. See below for interpretation and the links for which these are null

The meaning of diagnosticSummary.dispersionParameter depends on the family. For gaussian it is the estimate of the dispersion parameter φ, the deviance divided by the residual degrees of freedom n−p. For gamma it is also the estimate of φ, Pearson χ² divided by n−p. For these families it is used to compute the SEs and confidence intervals. For poisson, binomial, and negative-binomial with a specified θ, SEs are computed with φ = 1, and this field contains deviance/(n−p). This value is for checking whether the variance of the data matches the variance the family assumes; it is null when the residual degrees of freedom is 0. For negative-binomial with an automatically estimated θ, SEs are computed with φ = 1 and this field is 1.0.

GLMM (type: 'glmm'):

Specify the random-intercept grouping variable with groupColumn. family accepts 'gaussian', 'binomial', 'poisson', or 'gamma' (default 'gaussian'). With 'binomial', GLMM treats each row as a single trial, so a yColumn containing any value other than 0 or 1 returns MODEL_EXECUTION_ERROR. link, includeIntercept, confidenceLevel, and signal can also be specified with the same meaning as for GLM. maxIterations defaults to 100 and tolerance to 1e-6. These two set the iteration limit and the tolerance of the golden-section part of the search over the relative covariance parameter θ\theta. The evaluations at points over the search range are fixed in number and do not count toward the iteration limit. The iterations that compute the fixed effects and random effects for each θ\theta have their own limits. See GLMM for background on the model.

const result = await window.midas.models.run({
  type: 'glmm',
  datasetId: 'ds_001',
  yColumn: 'sepal_length',
  xColumns: ['sepal_width', 'petal_length'],
  groupColumn: 'species',
  family: 'gaussian'
});
// result.data:
// {
//   type: 'glmm',
//   runId: '...',
//   family: 'gaussian',
//   link: 'identity',
//   fixedEffects: [{ variable: '(Intercept)', estimate: 2.35, se: 0.87, df: 2.31, ... }, ...],
//   inference: { distribution: 't-per-coefficient', method: 'kenward-roger' },
//   randomEffects: { groupColumn: 'species', variance: 0.42, residualVariance: 0.14, icc: 0.75, blup: [...] },
//   fit: { logLikelihood: -72.1, aic: 154.2, bic: 169.3, iterations: 8, converged: true },
//   diagnosticSummary: { nObservations: 150, nGroups: 3, nFixedEffects: 3, nIncomplete: 0, groupSizes: [...] },
//   warnings: []
// }

link, includeIntercept, confidenceLevel are also available as optional parameters, with the same meaning as in GLM. maxIterations defaults to 100 and tolerance to 1e-6.

The reference distribution of GLMM fixed-effect confidence intervals depends on the family and link. For gaussian + identity (LMM), the standard errors are corrected by the Kenward-Roger method, inference is { distribution: 't-per-coefficient', method: 'kenward-roger' }, and each coefficient's df carries the degrees of freedom of its t-distribution. A coefficient whose df is null has no computable degrees of freedom and its confidence interval is also null. When the correction cannot be computed numerically, warnings reports it and the result falls back to the unadjusted standard errors with { distribution: 'normal', df: null }. All other combinations use Wald approximations based on the standard normal distribution, with inference set to { distribution: 'normal', df: null }. When the number of groups is small, intervals based on the standard normal approximation can fall below the nominal coverage. See GLMM Fundamentals: Fixed Effect Inference for details.

When the estimation iterations cannot continue and the estimate cannot be determined, GLMM returns no result and raises a NUMERICAL_ERROR. This failure occurs, for example, when an inverse link applied to gamma cannot keep the linear predictor positive, or when the iterations that compute the fixed effects and random effects do not converge near the optimal relative covariance parameter. See GLMM tab: Convergence Issues for details.

Fields in randomEffects:

  • variance — variance of the random intercepts, σ²_u
  • residualVariance — for gaussian, the residual variance σ²_e; for gamma, the estimated dispersion parameter φ. Not returned for binomial and poisson, where φ is fixed at 1 by theory
  • icc — intraclass correlation coefficient σ²_u / (σ²_u + σ²_e). σ²_e is the REML-estimated residual variance for gaussian + identity, π²/3 for binomial + logit, and 1 for binomial + probit — the latter two are latent-scale values. For all other family-link combinations, no latent-scale residual variance is defined and icc is null
  • blup — predicted random intercepts per group. For LMM (gaussian + identity) these are BLUPs (Best Linear Unbiased Predictions): the group mean of the residuals from the fixed-effects prediction (y − Xβ̂), shrunk toward 0. For the other family and link combinations they are the conditional modes of the random intercepts at the estimated fixed effects and variance components. In both cases, groups with fewer observations are shrunk more toward 0. standardError quantifies the prediction uncertainty: for LMM it is the conditional prediction error standard deviation, and for the other combinations it is an approximation based on the Laplace approximation. rank is the rank in descending order of estimate

For LMM (gaussian + identity), fit.logLikelihood is the REML log-likelihood, and fit.aic and fit.bic are based on it. REML-based AIC/BIC cannot be used to compare models with different fixed-effects structures. For the other family and link combinations, the log-likelihood is a Laplace approximation.

Random Forest (type: 'random_forest'):

Set taskType to 'classification' or 'regression'. The metrics field contains fitting-set (resubstitution) evaluation metrics. For an estimate of generalization performance, use oobScore.

const result = await window.midas.models.run({
  type: 'random_forest',
  datasetId: 'ds_001',
  yColumn: 'species',
  xColumns: ['sepal_length', 'sepal_width', 'petal_length', 'petal_width'],
  taskType: 'classification',
  nEstimators: 100,
  randomState: 42
});
// result.data:
// {
//   type: 'random_forest',
//   runId: '...',
//   taskType: 'classification',
//   tuningParameters: { nEstimators: 100, maxDepth: null, ... },
//   featureImportances: [{ feature: 'petal_length', importance: 0.45 }, ...],
//   permutationImportances: [{ feature: 'petal_length', importance: 0.38 }, ...],
//   metrics: { taskType: 'classification', accuracy: 0.96, precision: 0.96, recall: 0.96, f1Score: 0.96, nClasses: 3 },
//   nSamples: 150,
//   oobScore: 0.95,
//   responseDegenerate: false,
//   warnings: []
// }

For regression tasks, metrics contains { taskType: 'regression', mse, rmse, mae, r2 }. metrics values are computed on the fitting data (resubstitution) and are not available from models.describe(). For an estimate of generalization performance, use oobScore (OOB accuracy for classification, OOB R² for regression). For regression, when the response has effectively no variation, R² is undefined, so r2 and the regression oobScore are null. For both task types, oobScore is null when no samples or only one sample has out-of-bag predictions. For regression, oobScore is also null when the responses of the out-of-bag samples have effectively no variation. For classification, when the response has only one class, the metrics values are trivially 100%, oobScore is 100% unless it is null for one of the reasons above, and the importances are all 0. responseDegenerate is true in both degenerate cases (a regression response with effectively no variation, a classification response with only one class), so a script can detect them without matching the warning text. permutationImportances is the mean decrease in OOB prediction accuracy when each predictor is shuffled. Values can be negative. A negative value means that the mean of the per-tree OOB prediction accuracy was higher after shuffling that predictor than before shuffling.

ParameterTypeDefaultDescription
nEstimatorsnumber100Number of trees
maxDepthnumber | nullnullMaximum tree depth (null for unlimited)
minSamplesSplitnumber2Minimum samples to split a node
minSamplesLeafnumber1Minimum samples in a leaf node
maxFeatures'sqrt' | 'log2' | null | number'sqrt'Number of predictors to consider at each split
randomStatenumber42Random seed
signalAbortSignal—Used to cancel the run in progress

The Random Forest run in models.run() executes on a Web Worker and does not block the main thread, as does the Random Forest prediction in models.predict().

inference identifies the reference distribution used for ciLower and ciUpper. distribution: 't' indicates a t distribution with df degrees of freedom; distribution: 'normal' indicates a standard normal distribution, in which case df is null. Only the GLMM LMM case (gaussian + identity) uses distribution: 't-per-coefficient', because the degrees of freedom differ per coefficient; they are reported in each coefficient entry's df rather than at the model level.

The family-by-family mapping is shown below. The critical value follows t(n−p) exactly only for Gaussian with the identity link. Other dispersion-estimating families apply a t distribution as a small-sample convention, while families marked asymptotic use the standard normal approximation.

familylinkReference distributionNature
gaussianidentityt(n−p)Exact
gaussiannon-identityt(n−p)Small-sample convention
gammaanyt(n−p)Small-sample convention
poissonanyStandard normalAsymptotic
binomialanyStandard normalAsymptotic
negative-binomialanyStandard normalAsymptotic

ciLower and ciUpper are the Wald confidence interval estimate ± criticalValue × se for each coefficient. The confidence level follows the confidenceLevel parameter (default 95). The critical value is the (1 + confidenceLevel/100) / 2 quantile of the reference distribution reported in inference.

expEstimate, expCiLower, and expCiUpper are the exp() transformation of the link-scale estimate and confidence interval. For logit link, these correspond to odds ratios (OR); for Poisson and Negative Binomial with log link, incidence rate ratios (IRR); for Gamma and Gaussian with log link, multiplicative effects. For identity, inverse, and probit links, these fields are null.

fit.aic and fit.bic are number | null. They are null when the log-likelihood constant is undefined (e.g., non-integer weights in Binomial, or a saturated model).

Rows with missing values in any response or explanatory variable are excluded from analysis. The number of excluded rows is available in diagnosticSummary.nIncomplete.

When the model does not converge within the maximum number of iterations, or when the search for θ does not converge for Negative Binomial with estimated θ, the result is returned with fit.converged: false, and message also reads "did not converge". When a result is returned, coefficient se values are never null. When SEs cannot be computed — for example, a non-positive-definite covariance matrix, a rank-deficient design matrix, or a variance that overflows or becomes undefined because a predictor or the response spans an extreme range — no result is returned and a NUMERICAL_ERROR error is raised instead. For the extreme-range case, rescale or standardize the predictors and response, then refit. A NUMERICAL_ERROR is also raised when the iteration diverges or when the linear predictor leaves the domain of the link function. The iteration is judged to diverge when a coefficient exceeds 1e10 in absolute value, or when a Negative Binomial iteration produces a fitted mean outside the valid range. The linear predictor leaves the link's domain, for example, when an inverse link applied to Gamma makes the linear predictor zero or negative.

Specify family as 'gaussian' (default), 'binomial', 'poisson', 'gamma', or 'negative-binomial'. See GLM for guidance on choosing a family. Use link to set the link function. When omitted, the default link for the family is used. Only the links listed under "Available links" below are accepted; any other combination returns an INVALID_INPUT error.

familyDefault linkAvailable links
gaussianidentityidentity, log
binomiallogitlogit, probit
poissonloglog, identity
gammainverseinverse, log, identity
negative-binomialloglog

Optional parameters:

ParameterTypeDefaultDescription
includeInterceptbooleantrueInclude intercept term
maxIterationsnumber100Maximum number of iterations
tolerancenumber1e-6Convergence threshold: the upper limit on the size of the change that one more update would make to the coefficients, measured by their estimated covariance matrix
binomialResponseobject-Binomial response format. See below
thetanumber-Shape parameter θ of the negative binomial. Must be a positive finite number; any other value returns an INVALID_INPUT error. When omitted, estimated via profile likelihood
offsetColumnstring-Offset column (e.g., the log of exposure for Poisson regression)
confidenceLevelnumber95Confidence level for confidence intervals (50–99.99)
signalAbortSignal—Used to cancel the run in progress

The GLM, GLMM, linear regression, and Cox regression runs in models.run() also fit the model on a Web Worker and do not block the main thread.

When theta is omitted and estimated automatically, coefficient SEs and confidence intervals are computed treating the estimated θ as fixed. The estimation uncertainty of θ itself is not propagated into the SEs.

binomialResponse specification:

Specifies the response variable format when family: 'binomial'. When binomialResponse is omitted, binary format is assumed.

  • { format: 'binary' } -- Binary 0/1 data. Specify the response variable with yColumn. This format treats each row as a single trial, so a value other than 0 or 1 in yColumn in a row used in the fit, including a proportion, returns MODEL_EXECUTION_ERROR
  • { format: 'grouped', successesColumn: '...', trialsColumn: '...' } -- Successes/trials pair. yColumn is not specified with this format
// Grouped Binomial example
const result = await window.midas.models.run({
  type: 'glm',
  datasetId: 'ds_001',
  binomialResponse: { format: 'grouped', successesColumn: 'defects', trialsColumn: 'inspected' },
  xColumns: ['temperature', 'pressure'],
  family: 'binomial',
  link: 'logit'
});

ARIMA (type: 'arima'):

Fit an ARIMA(p,d,q) model to a single time-series column. Specify order as [p, d, q] for manual order selection, or use autoSelect for automatic order selection. Setting seasonalPeriod to 2 or more turns the model into ARIMA(p,d,q)(P,D,Q)[s] (SARIMA) with seasonal orders. Automatic selection sets the differencing orders by tests first and chooses the remaining orders by AIC or BIC under that differencing. The differencing order d is set with the KPSS test. In seasonal models, the seasonal differencing order D is set first with the OCSB test, and KPSS is applied to the seasonally differenced series. For why differencing orders are not compared across by AIC/BIC, see Automatic ARIMA Order Selection; for the tab workflow, see The ARIMA Tab.

ParameterTypeDefaultDescription
seriesColumnstring(required)Column name for the time series. A numeric column: int64, float64, or boolean with an interval or ratio scale
order[number, number, number]—[p, d, q] — AR order, differencing order, MA order. Omit to use autoSelect
seasonalPeriodnumber1Seasonal period s: the number of observations per cycle, e.g. 12 for the yearly cycle of monthly data. Integer from 1 to 366. 1 means non-seasonal
seasonalOrder[number, number, number][0, 0, 0][P, D, Q] — seasonal AR order, seasonal differencing order, seasonal MA order. P and Q range 0–2, D ranges 0–1. Used when seasonalPeriod is 2 or more and order is specified
autoSelectobject{ maxP: 3, maxD: 1, maxQ: 3, maxSeasonalP: 1, maxSeasonalQ: 1, criterion: 'aic' }Auto order selection. Used when order is omitted
autoSelect.maxPnumber3Maximum AR order to search, 0–5
autoSelect.maxDnumber1Maximum differencing order, 0–2; the KPSS-based choice of d never exceeds it
autoSelect.maxQnumber3Maximum MA order to search, 0–5
autoSelect.maxSeasonalPnumber1Maximum seasonal AR order to search, 0–2. Effective when seasonalPeriod is 2 or more
autoSelect.maxSeasonalQnumber1Maximum seasonal MA order to search, 0–2. Effective when seasonalPeriod is 2 or more
autoSelect.criterion'aic' | 'bic''aic'Information criterion for choosing the remaining orders under fixed differencing
includeInterceptbooleantrueInclude a constant term: the series mean when d + D = 0, a drift when d + D = 1. Omitted when d + D is 2 or more, where it would correspond to a polynomial trend
includeTrendbooleanfalseInclude a deterministic linear trend term. The time regressor is generated internally from the position of each valid observation (t = 1, 2, ...), and the slope is estimated only when d + D = 0 (the intercept is then the level at t = 0). When d + D = 1 the slope is represented by the drift term if a constant is included, and when d + D is 2 or more differencing removes the trend; in both cases it is not estimated separately and a warning is reported. In automatic selection, when no seasonal difference is taken (D = 0), the KPSS test on the undifferenced series switches to the variant whose null hypothesis is trend stationarity (decision threshold 0.146)
confidenceLevelnumber95Confidence level for coefficient CIs
signalAbortSignal—Used to cancel the run in progress

The ARIMA run in models.run() executes on a Web Worker and does not block the main thread.

The response includes coefficients (AR/MA/SAR/SMA/Intercept/Trend with CIs), seasonalOrder, fit (AIC, BIC, log-likelihood, σ², convergence), residualDiagnostics (ACF and PACF of residuals), and nObservations. When the fit did not converge, fit.aic and fit.bic are null, because the likelihood is not maximized. A coefficient whose standard error cannot be computed has a null se and null CI bounds; this happens, for example, when coefficients are pinned at the stationarity or invertibility boundary and the variance-covariance matrix is unavailable. When autoSelect is used, differencingSelection records the KPSS-based choice of d (the selected d, the KPSS statistic at each order, and the variant and decision threshold used at each order), and orderSearch contains the AIC/BIC for all candidate (p, q, P, Q) orders searched under that differencing. Every entry in orderSearch shares the same (d, D). Each entry carries a status of converged, not-converged, or failed. A not-converged candidate is one whose iteration stopped before converging, and a different order or differencing order may converge. A failed candidate is one that could not be fitted at all, for example because too few observations remain after differencing or the differenced series has zero variance, and error holds the reason. A candidate whose status is not converged has null aic and bic, because its likelihood is not maximized or could not be evaluated. The number of non-converged candidates is reported in orderSearchNonConvergedCount and the number of failed candidates in orderSearchFailedCount. When seasonalPeriod is 2 or more, seasonalDifferencingSelection also records the OCSB-based choice of D (the selected D, the OCSB statistic, and the decision threshold).

The residualDiagnostics.acf and .pacf arrays start at lag 0, and a lag at which the sample autocorrelation cannot be computed holds null. When the residuals have zero variance, every element including lag 0 is null, because the sample autocorrelation is a ratio whose numerator and denominator are both zero. The partial autocorrelation is also null at every lag beyond one at which the innovation variance of the Durbin-Levinson recursion reaches zero.

A fit whose optimization did not converge is not a failure; it is returned with fit.converged set to false.

Non-finite values (NaN, Infinity, null) in the series are dropped. When observations are dropped, a warning is included in the response. There is no fixed minimum number of observations. A warning is also included when the model's total differencing d + D is 2 or more, where the constant term is omitted; when includeTrend is requested but d + D is 1 or more, where the trend slope is not estimated separately; when a coefficient's standard error could not be computed; when an autoregressive or moving-average root is close to the unit circle, where estimates and their normal-approximation confidence intervals may be unreliable; and when an autoregressive or moving-average coefficient of a point reached from another starting point lies in the likelihood-ratio confidence set at confidenceLevel but outside the reported confidence interval, where the coefficients are weakly identified (not checked when the fit did not converge, nor for coefficients whose standard errors cannot be computed). models.describe() returns the same warnings for a saved model.

// Manual order
const result = await window.midas.models.run({
  type: 'arima',
  datasetId: 'ds_001',
  seriesColumn: 'temperature',
  order: [1, 1, 1]
});

// Auto order selection
const result2 = await window.midas.models.run({
  type: 'arima',
  datasetId: 'ds_001',
  seriesColumn: 'temperature',
  autoSelect: { maxP: 5, maxD: 2, maxQ: 5, criterion: 'bic' }
});

Linear Regression (type: 'linear_regression'):

Fit a linear regression by ordinary least squares.

ParameterTypeDefaultDescription
yColumnstring(required)Response variable column name
xColumnsstring[](required)Explanatory variable column names
includeInterceptbooleantrueInclude intercept term
confidenceLevelnumber95Confidence level for confidence intervals
signalAbortSignal—Used to cancel the run in progress

In the response, coefficients has the same shape as for GLM, and inference is always a t distribution. fit contains the same fields as for GLM plus rSquared, adjustedRSquared, residualStdError, and mae. residualStdError is the square root of the residual sum of squares divided by the residual degrees of freedom n−p, and mae is the mean of the absolute residuals (divided by n). residualStdError is a different quantity from the rmse returned among the GLM prediction accuracy metrics, which divides the residual sum of squares by the number of observations n. rSquared, adjustedRSquared, residualStdError, and mae are null when the response has effectively no variation (responseDegenerate: true), in which case the coefficient se values and confidence intervals are also null. For a model without an intercept, rSquared is an uncentered R² and is not comparable to the centered R² of an intercept model. mae is only available on the run result; it is not included in models.describe() for saved models.

const result = await window.midas.models.run({
  type: 'linear_regression',
  datasetId: 'ds_001',
  yColumn: 'sepal_length',
  xColumns: ['sepal_width', 'petal_length']
});
// result.data: { type: 'linear_regression', runId, coefficients, inference,
//   fit: { ..., rSquared: 0.84, adjustedRSquared: 0.84, residualStdError: 0.33, mae: 0.26 }, diagnosticSummary, warnings }

ANOVA (type: 'anova'):

Run a one-way or two-way analysis of variance. The number of elements in factorColumns determines which.

ParameterTypeDefaultDescription
responseColumnstring(required)Response variable column name
factorColumnsstring[](required)Factor columns. One element for one-way, two for two-way
includeInteractionbooleantrueInclude the interaction term in two-way ANOVA
ssType'I' | 'III''III'Sum-of-squares decomposition type for two-way ANOVA
confidenceLevelnumber95Confidence level for Tukey HSD (50–99.99)
postHocbooleantrueCompute Tukey HSD (one-way only)

Column eligibility follows the measurement scale, the same rule the ANOVA tab selectors use. responseColumn accepts columns with an interval or ratio scale, and factorColumns accepts columns with a nominal or ordinal scale.

The response includes mode ('one-way' or 'two-way'), anovaTable (sum of squares, degrees of freedom, mean square, and the effect sizes η² and ω² per effect (partial η² and partial ω² for two-way), plus residuals and total), groupStatistics (n, mean, standard deviation, minimum, and maximum per group), nObservations, nExcluded, and exclusions. For one-way ANOVA with postHoc enabled, tukeyHSD (pairwise mean differences with SEs and confidence intervals) is also included. The postHoc setting is stored with models saved via models.save and is preserved when the model is re-estimated after a dataset reload. Because two-way ANOVA never computes Tukey HSD, the stored value is always false for two-way models.

When the model reproduces every response value exactly, the error variance cannot be estimated, and the quantities that depend on it are null. A residual sum of squares below floating-point precision relative to the response variation counts as an exact reproduction, so a response whose values are identical within each group is covered. In that case anovaTable.residuals.ms and the effect sizes are null, tukeyHSD is omitted even with postHoc enabled, the sums of squares and group means are still returned, and warnings explains why.

exclusions breaks down the rows excluded for missing or invalid values. byGroup counts excluded rows per group (factor level for one-way, level combination for two-way), and factorMissing counts excluded rows whose factor value is missing and which therefore belong to no group. When exclusion removes every row of a level, droppedLevelsA and droppedLevelsB list the label and row count; when both factor levels survive but every row of a cell is excluded, droppedCells lists it. In two-way ANOVA with the interaction term, however, a cell emptied by exclusion makes the run itself fail with an empty-cell error, so droppedCells and its warnings are returned only without the interaction term.

const result = await window.midas.models.run({
  type: 'anova',
  datasetId: 'ds_001',
  responseColumn: 'sepal_length',
  factorColumns: ['species']
});
// result.data: { type: 'anova', runId, mode: 'one-way',
//   anovaTable: { ssType, rows: [{ source, ss, df, ms, etaSquared, omegaSquared }, ...], residuals, total },
//   groupStatistics: [{ label, n, mean, std, min, max }, ...],
//   tukeyHSD: { comparisons: [{ group1, group2, meanDiff, se, ciLower, ciUpper }, ...], confidenceLevel },
//   nObservations: 150, nExcluded: 0,
//   exclusions: { byGroup: [], factorMissing: 0, droppedLevelsA: [], droppedLevelsB: [], droppedCells: [] },
//   warnings: [] }

PCA (type: 'pca'):

Runs a principal component analysis. Rows where any of the selected columns is missing are excluded, and their count is returned as nExcluded.

ParameterTypeDefaultDescription
columnsstring[](required)Numeric columns to analyze. At least 2
preprocessing'standardize' | 'center' | 'none''standardize'Preprocessing
nComponentsnumberall componentsMaximum number of components to return

The response contains components (eigenvalue, explained variance ratio, and cumulative variance ratio per component) and loadings (the coefficient of each variable on each component). Component scores are not returned because they are as long as the data. Use Save as Dataset on the PCA tab when you need them.

const result = await window.midas.models.run({
  type: 'pca',
  datasetId: 'ds_001',
  columns: ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
});
// result.data: { type: 'pca', runId, nObservations: 150, nVariables: 4, nComponents: 4,
//   nExcluded: 0, preprocessing: 'standardize',
//   components: [{ component: 1, eigenvalue, explainedVarianceRatio, cumulativeVarianceRatio }, ...],
//   loadings: [{ variable: 'sepal_length', values: [...] }, ...], warnings: [] }

Kaplan-Meier (type: 'kaplan_meier'):

Estimates the survival function with the Kaplan-Meier method. eventColumn must be an int64 or boolean column, and 1 or true counts as an observed event. With groupColumn the estimation is done per group; without it the result has a single group named 'All'. groupColumn accepts columns whose measurement scale is nominal or ordinal. Rows whose group value is missing are collected into one group whose group name is null. The groups in the result follow the same order as the legend of the graph in the Kaplan-Meier tab, which is the enum definition order for enum columns. The group whose name is null comes last.

ParameterTypeDefaultDescription
timeColumnstring(required)Observation time column
eventColumnstring(required)Event indicator column
groupColumnstringnoneColumn that defines the groups
confidenceLevelnumber95Confidence level (50-99.99)
taunumbersmallest of the maximum observed times across groupsRMST restriction time (a positive number)
survivalTimesnumber[]noneTimes at which to read the survival probability (numbers of 0 or more, in ascending order)

Each entry of groups carries the number of observations and events, the median survival time with its confidence interval, and the event times (times) with the matching survival probabilities, confidence bands, risk set sizes, event counts, and censoring counts. lower and upper of medianSurvivalTimeCI are determined separately, whether or not the group has a median survival time. lower is null when the lower confidence limit of the survival function never falls to 0.5 or below at a time where the survival probability is above 0, and upper is null when the upper confidence limit never does.

survivalAtTimes in each entry of groups holds the estimates at the times in survivalTimes, in the same order. Each element has the time (time), the risk set size at that time (nRisk), the survival probability S(t)S(t) (survival), its standard error by Greenwood's formula (se), and the confidence interval (ciLower, ciUpper). The interval is the same pointwise log-transformed interval as survivalCILower and survivalCIUpper; it is not a simultaneous interval and is not adjusted for multiplicity. At a time after the group's last observed time, survival, se, and the interval are null, except that survival is 0 in a group whose S(t)S(t) reached 0 at its last observed time. Before the group's first event time and at a time where S(t)=0S(t) = 0, se and the interval are null. The values mean the same as in the Survival at Specified Times table of the Kaplan-Meier tab. Without survivalTimes, survivalAtTimes is empty.

rmst carries the restricted mean survival time (RMST), the area under the survival curve from 0 to tau. tau is the restriction time actually used and defaultTau is its default. groups lists the RMST estimate, standard error, and confidence interval per group; in a group whose variance estimate is 0, the estimate, standard error, and interval are null. differences lists, for every pair of groups, the difference group1 minus group2 with its standard error and confidence interval, and is empty with a single group. These differences are not adjusted for multiple comparisons. The standard errors are based on the Greenwood variance, and both intervals are normal-approximation Wald intervals truncated to the range of the estimate, which is 0 to tau for RMST and -tau to tau for a difference. When tau exceeds the default, the survival curve is extrapolated as constant beyond the last observed time, which can overstate the RMST and understate its uncertainty.

const result = await window.midas.models.run({
  type: 'kaplan_meier',
  datasetId: 'ds_001',
  timeColumn: 'time',
  eventColumn: 'DEATH_EVENT',
  groupColumn: 'sex_label',
  survivalTimes: [100, 200]
});
// result.data: { type: 'kaplan_meier', runId, confidenceLevel: 95, nExcluded: 0,
//   groups: [{ group: 'female', nObservations, nEvents, medianSurvivalTime, medianSurvivalTimeCI,
//     times: [...], survival: [...], survivalCILower: [...], survivalCIUpper: [...],
//     nRisk: [...], nEvent: [...], nCensor: [...],
//     survivalAtTimes: [{ time: 100, nRisk, survival, se, ciLower, ciUpper }, ...] }, ...],
//   rmst: { tau, defaultTau,
//     groups: [{ group: 'female', rmst, se, ciLower, ciUpper }, ...],
//     differences: [{ group1: 'female', group2: 'male', difference, se, ciLower, ciUpper }] },
//   warnings: [] }

To put the survival curve in a report, pass a layer with the survival stat to reports.addGraph(). The layer sets stats: [{ type: 'survival', params: { confLevel } }] and maps the time column to x, the event indicator column to y, and the group column to color. confLevel is a percentage, like confidenceLevel. The confidence interval is a pointwise interval at each time, and Custom Graph Reference describes how it is constructed.

await window.midas.reports.addGraph(reportId, {
  datasetId: 'ds_001',
  globalAes: { x: 'time', y: 'DEATH_EVENT', color: 'sex_label' },
  layers: [
    {
      name: 'CI Band',
      geom: { type: 'ribbon', defaults: { alpha: 0.15, curveType: 'stepAfter' } },
      stats: [{ type: 'survival', params: { confLevel: 95 } }],
      showLegend: 'hide',
    },
    {
      name: 'KM Curve',
      geom: { type: 'step', defaults: { strokeWidth: 2 } },
      stats: [{ type: 'survival', params: { confLevel: 95 } }],
      scales: { color: { legendPosition: 'bottom' } },
    },
  ],
  scales: {
    x: { title: 'Time' },
    y: { title: 'Survival Probability', domain: { min: 0, max: 1 } },
  },
});

Cox regression (type: 'cox_regression'):

Fits a Cox proportional hazards model. eventColumn must be an int64 or boolean column, and covariates must be columns whose measurement scale is interval or ratio. Rows where the time, the event, or any covariate is missing are excluded, and their count is returned as nExcluded. The exclusions field carries the breakdown: missingTimeOrEvent counts rows dropped for a missing time or event value, and missingCovariates counts rows dropped for a missing covariate. The two are counted exclusively, so they sum to nExcluded. Tied event times are handled with the Efron method.

ParameterTypeDefaultDescription
timeColumnstring(required)Observation time column
eventColumnstring(required)Event indicator column
covariatesstring[](required)Numeric covariate columns. At least 1
maxIterationsnumber100Maximum Newton-Raphson iterations
tolerancenumber1e-9Convergence threshold: the upper limit on the size of the change that one more update would make to the coefficients, measured by their estimated covariance matrix
confidenceLevelnumber95Confidence level for hazard ratios (50-99.99)
signalAbortSignal—Used to cancel the run in progress

Each entry of coefficients carries the log hazard ratio, its standard error, and the hazard ratio with its confidence interval. The response also reports the log partial likelihood, AIC, the concordance index with its standard error, the convergence state, and the iteration count. The intervals are Wald intervals on the log hazard ratio, exponentiated.

When the iteration stops before meeting the convergence criterion, the result is returned with converged: false. This result has null for the values that assume the maximum partial likelihood estimate: each coefficient's coefficient, standardError, hazardRatio, hazardRatioCILower, and hazardRatioCIUpper, and logPartialLikelihood, aic, concordance, concordanceSE, diagnostics, and baseline. The coefficients at the point where the iteration stopped are in lastIterateCoefficient, and the partial log-likelihood there is in lastIterateLogPartialLikelihood; neither is an estimate. stopReason gives the reason the iteration stopped: 'max-iterations' (maxIterations was reached), 'step-halving-failed' (each of the 10 step lengths tried along the update direction decreased the partial log-likelihood by more than the acceptance threshold, which is 1e-10 times one plus the absolute value of the partial log-likelihood at the previous iteration), or 'direction-unsolvable' (the information matrix could not be solved, so the update direction could not be computed). When the fit converged, stopReason is null. When separation, a singular information matrix, or a variance that is not a finite positive value is found at the point where the iteration stopped, a NUMERICAL_ERROR error is returned instead of a result that did not converge.

diagnostics carries the proportional hazards diagnostics. proportionalHazards lists rho per covariate, the Pearson correlation between the scaled Schoenfeld residuals and the time transform g(t) = 1 − KM(t−); it is null with fewer than 2 events, or when the residuals or the time transform have zero variance. rho alone does not show how large the departure from proportional hazards is or what pattern it takes, so judge it together with schoenfeldResiduals. schoenfeldResiduals lists the raw (raw) and scaled (scaled) residuals per event, both in the order of covariates, and timeTransform lists g(t) per event. The Schoenfeld residual scatter plots in the Diagnostics section of the Cox regression tab plot time of schoenfeldResiduals on the x-axis and scaled on the y-axis. schoenfeldTrends holds, per covariate, the curve that smooths scaled against time with LOESS, and the tab draws this curve over each scatter plot. The LOESS is a local linear regression with tricube weights and a span of 0.75. Each element has the covariate name name, the times time, and the LOESS predictions value at those times. time holds the distinct event times. When there are more than 101 distinct event times, time holds no more than 200 of them: the 101 event times whose ranks in ascending order are evenly spaced, together with the event time nearest to each of 101 evenly spaced points from the first to the last event time. The log(−log S) plot in the same section is a display-only plot that groups the observations by one covariate chosen in the tab (one group per value when the covariate has five or fewer distinct values, otherwise two groups split at the median), and the points of its curves are not returned.

logLogGroups returns, per covariate, the number of observations and events in each group, the same values as the table below the log(−log S) plot. Each element has the covariate name name and the array of groups groups, in the order of covariates. Each element of groups has the group label label, the number of observations nObservations, the number of events nEvents (including events at time 0), and plotted, which tells whether the group's curve is drawn. Groups formed per value are listed in ascending order of value, and the two groups of a median split are listed lower group first. plotted is false for a group that does not have two or more event times after time 0 at which the survival probability is strictly between 0 and 1.

baseline carries the baseline survival function: for each event time in times, the cumulative baseline hazard cumHazard (H₀(t)), the baseline survival survival (S₀(t) = exp(−H₀(t))), the risk set size nRisk, and the event count nEvent. cumHazardCILower/cumHazardCIUpper and survivalCILower/survivalCIUpper are pointwise confidence intervals at confidenceLevel, constructed on the log H₀ scale (the log(−log S₀) scale for S₀) with a variance that combines the baseline hazard increments and the coefficient estimates (formulation). They are individual intervals at each time point, not a simultaneous band, and both bounds are null at a time point where the interval cannot be computed. The baseline is the estimate for an observation whose covariates are all 0. For a covariate such as age whose observed range does not include 0, S₀(t) is an extrapolation, so compute S(t | X) = exp(−H₀(t)·exp(β'X)) from cumHazard at realistic covariate values X, such as the sample means, to check the survival function. Compute it from cumHazard rather than from survival, because S₀(t) rounds to exactly 1 when H₀(t) is smaller than about 1e-16, and the power S₀(t)^exp(β'X) then returns 1 for every X. survivalDegenerate is true when S₀(t) is within 1e-6 of 0 or 1 at every time.

const result = await window.midas.models.run({
  type: 'cox_regression',
  datasetId: 'ds_001',
  timeColumn: 'time',
  eventColumn: 'DEATH_EVENT',
  covariates: ['age', 'ejection_fraction']
});
// result.data: { type: 'cox_regression', runId, confidenceLevel: 95,
//   coefficients: [{ name: 'age', coefficient, standardError, hazardRatio,
//     hazardRatioCILower, hazardRatioCIUpper }, ...],
//   logPartialLikelihood, aic, concordance, concordanceSE, converged, stopReason: null, iterations,
//   nObservations, nEvents, nExcluded,
//   exclusions: { missingTimeOrEvent, missingCovariates },
//   diagnostics: { proportionalHazards: [{ name: 'age', rho }, ...],
//     schoenfeldResiduals: [{ time, raw: [...], scaled: [...] }, ...], timeTransform: [...],
//     schoenfeldTrends: [{ name: 'age', time: [...], value: [...] }, ...],
//     logLogGroups: [{ name: 'age', groups: [{ label: '<= 60', nObservations, nEvents, plotted: true }, ...] }, ...] },
//   baseline: { times: [...], cumHazard: [...], cumHazardCILower: [...], cumHazardCIUpper: [...],
//     survival: [...], survivalCILower: [...], survivalCIUpper: [...], nRisk: [...], nEvent: [...],
//     survivalDegenerate: false },
//   warnings: [] }

PCA, Kaplan-Meier, and Cox regression results are not stored as models. Read the results directly from the return value of models.run(). To save Kaplan-Meier and Cox regression tables as datasets, use models.saveKaplanMeierTable() and models.saveCoxTable(). To add Cox regression results to a report, use reports.addCoxRegression().

models.save(runId, name?)

Save a model run result to the project. After saving, the model is available via models.list() and models.describe().

const run = await window.midas.models.run({ ... });
const saved = await window.midas.models.save(run.data.runId, 'My Model');
// saved.data: { id: '...', name: 'My Model' }

If you have changed the dataset used for fitting, a dataset it was derived from, or an Enum definition since models.run(), models.save() saves the model as a model awaiting re-estimation, and MIDAS re-estimates it from the data at the time of saving. The same applies when you have changed only the display format of a column.

A diagnostic dataset, which holds the diagnostic statistics of each observation, is created by passing 'diagnostics' to models.saveAsDataset(). The key columns of a GLM diagnostic dataset are fitted_values, deviance_residuals, pearson_residuals, response_residuals, standardized_residuals, leverage, and cooks_distance; for linear regression it has neither pearson_residuals nor response_residuals.

models.saveAsDataset(id, artifact, options?)

Saves a model artifact as a derived dataset, so that later SQL, graphs, and reports can use it directly.

The artifacts are coefficients (GLM, linear regression, and GLMM fixed effects), covariance (the covariance matrix of GLM and linear regression), blup (GLMM random effects), diagnostics (the diagnostic dataset of GLM, linear regression, and GLMM), and binned_residuals (one row per bin of the binned residual plots of a Binomial GLM with the Binary response format). Asking for an artifact the model does not have returns UNSUPPORTED_MODEL_TYPE.

diagnostics is the fitting dataset with per-observation diagnostic columns added; for GLM and linear regression it is the dataset that Save as Dataset in the diagnostics tab saves. Every model type has fitted values and residuals, and only GLM and linear regression have leverage and Cook's Distance.

For a GLM, diagnostics and binned_residuals are computed by refitting the model on the current data of the fitting dataset.

binned_residuals has one row per bin of a binned residual plot, where the bins divide the observations by the value of xAxis. It is the dataset that Save as Dataset of a binned residual plot in the diagnostics tab saves. Its columns are bin, x_mean, x_min, x_max, n, mean_residual, lower_2se, and upper_2se. The method returns UNSUPPORTED_MODEL_TYPE for a model other than a Binomial GLM with the Binary response format. It returns COLUMN_NOT_FOUND when the xAxis column is not in the fitting dataset. Give a predictor named fitted by its column ID. To draw the plot of the diagnostics tab in a report, pass this dataset to reports.addGraph() with x_mean on the horizontal axis, mean_residual as points, and lower_2se and upper_2se as dashed lines, and draw a horizontal line at 0.

When a dataset of the same artifact, that is, a dataset with the same operation, is already in the project, the method returns that dataset instead of creating a new one, and the name option is not applied. The returned rowCount and columnCount are those of the returned dataset.

OptionTypeDefaultDescription
namestringderived from the model name and artifactName of the output dataset. A name already in use gets a numeric suffix
confidenceLevelnumber95Interval level of the coefficient table of coefficients (50-99.99)
xAxisstring"fitted"For binned_residuals, the horizontal axis that the observations are binned by: "fitted" (fitted probability) or the name or ID of a predictor of the model

Predictions are not covered here. The fitted values in diagnostics have no standard errors or intervals. For GLM and linear regression, models.predict() returns predicted values with standard errors and intervals, for the fitting data as well as for new data.

const result = await window.midas.models.saveAsDataset('model_001', 'coefficients', {
  confidenceLevel: 99,
});
// result.data: { id: 'derived_...', name: 'My GLM Coefficients', rowCount: 3,
//   columnCount: 7, artifact: 'coefficients', modelType: 'glm' }

models.saveKaplanMeierTable(config, table, options?)

Saves a table of the Kaplan-Meier tab as a derived dataset. The dataset is the same one that Save as Dataset of that table in the tab saves. Kaplan-Meier results are not saved as models, so this method takes the estimation inputs in config instead of a model ID. The saved dataset is a derived dataset whose input dataset is the source dataset, and MIDAS builds its row data again when the input dataset changes (Saving as a Dataset).

config is the Kaplan-Meier config of models.run() without type. Pass one of the following as table. The columns are those of the table in the Kaplan-Meier tab, and the confidence intervals are computed at the level of confidenceLevel and placed in the numeric columns Lower nn% and Upper nn%. In RMST Difference, the interval columns are Lower nn% (Unadjusted) and Upper nn% (Unadjusted), which show that the intervals are not adjusted for multiplicity.

tableTableRequired config
'summary'Summary StatisticsNone
'survival_at_times'Survival at Specified TimesAt least one time in survivalTimes
'number_at_risk'Number at Risk, in a long format with one row per pair of group and timeNone
'rmst'RMSTNone
'rmst_difference'RMST Difference. Each difference is the RMST of the earlier group minus that of the later group in the order of the table, and the intervals are not adjusted for multiplicityA groupColumn with two or more groups

For 'rmst' and 'rmst_difference', omitting tau uses the default and fixes that value in the dataset. The table holds the τ\tau used in its Tau column.

OptionTypeDefaultDescription
namestringbuilt from the table and the dataset nameName of the output dataset.

When name is omitted, the default name gets a numeric suffix if it is already in use. In addition, when a dataset of the same table, that is, a dataset with the same operation, is already in the project, the method returns that dataset instead of creating a new one. The returned tau is the restriction time used by 'rmst' and 'rmst_difference', and null for the other tables. nExcluded is the number of rows excluded for a missing time or event value.

const result = await window.midas.models.saveKaplanMeierTable({
  datasetId: 'ds_001',
  timeColumn: 'time',
  eventColumn: 'event',
  groupColumn: 'arm',
  survivalTimes: [100, 200],
}, 'survival_at_times', { name: 'Survival at 100 and 200 days' });
// result.data: { id: 'derived_...', name: 'Survival at 100 and 200 days', rowCount: 4,
//   columnCount: 8, table: 'survival_at_times', tau: null, nExcluded: 0, warnings: [] }

models.saveCoxTable(config, table, options?)

Saves a table of the Cox Regression tab as a derived dataset. The dataset is the same one that Add to Report in the tab registers. For the coefficients table and Baseline Cumulative Hazard, it is also the same one that Save as Dataset in the tab registers. Cox regression results are not saved as models, so this method takes the fitting inputs in config instead of a model ID. The saved dataset is a derived dataset whose input dataset is the source dataset, and MIDAS builds its row data again when the input dataset changes (Saving as a Dataset).

config is the Cox regression config of models.run() without type, maxIterations, and tolerance. The iterations use the default settings, as in the tab. Pass one of the following as table. The columns are those of the table in the Cox Regression tab, and the confidence intervals are computed at the level of confidenceLevel.

tableTable
'coefficients'Coefficients table (Variable, Coef, SE, HR, HR Lower nn%, HR Upper nn%)
'baseline_hazard'Baseline Cumulative Hazard (Time, At Risk, Events, H0(t), S0(t), and their intervals)
'adjusted_survival'Adjusted survival curve (Time, Survival Probability, Lower nn%, Upper nn%), with a row at time 0 and a row at each event time
OptionTypeDefaultDescription
namestringbuilt from the table and the dataset nameName of the output dataset.
covariateValuesRecord<string, number>the mean of each covariate over the rows used in the fitCovariate values of 'adjusted_survival', keyed by covariate column name or ID. Covariates not given use the mean, the same default as the tab.

When name is omitted, the default name gets a numeric suffix if it is already in use. In addition, when a dataset of the same table, that is, a dataset with the same operation, is already in the project, the method returns that dataset instead of creating a new one. The covariate values of 'adjusted_survival' are fixed in the dataset, including when the means are used. The returned covariateValues are the values used by 'adjusted_survival', and null for the other tables. nExcluded and exclusions are the numbers of rows excluded for a missing time or event value and for a missing covariate value. warnings are the warnings of the fit, such as signs of separation, and for 'baseline_hazard' they include a note when S0(t) is within 1e-6 of 0 or 1 at every time. The saved dataset does not carry these warnings.

const result = await window.midas.models.saveCoxTable({
  datasetId: 'ds_001',
  timeColumn: 'time',
  eventColumn: 'event',
  covariates: ['age', 'sex'],
}, 'coefficients');
// result.data: { id: 'derived_...', name: 'Cox Coefficients - ds_001', rowCount: 2,
//   columnCount: 7, table: 'coefficients', covariateValues: null, nExcluded: 0,
//   exclusions: { missingTimeOrEvent: 0, missingCovariates: 0 }, warnings: [] }

models.predict(id, config)

Predicts new data with a saved model and stores the result as a derived dataset. GLM, linear regression, and Random Forest are supported; other model types return UNSUPPORTED_MODEL_TYPE. datasetId accepts a dataset ID or name and must contain every predictor column the model was fitted with.

ParameterTypeDefaultDescription
datasetIdstring(required)Dataset to predict
namestringderived from the model nameName of the output dataset. A name already in use gets a numeric suffix
includeOriginalDatabooleantrueGLM, linear regression: keep the columns of the source dataset in the output
confidenceLevelsnumber[][95]Levels for the confidence interval of the mean (50-99.99)
predictionLevelsnumber[][95]Levels for the prediction interval of a single new observation (50-99.99)
signalAbortSignal—Used to cancel a Random Forest prediction in progress

For GLM and linear regression the output adds the fitted values, the linear predictor, and the standard error, plus a pair of bound columns for each level in confidenceLevels and predictionLevels. The predictor and offset columns must be numeric (int64, float64) or boolean; boolean values are read as true = 1 and false = 0. Rows with a missing predictor or offset keep their row with null values. nSkipped is the number of rows whose predicted value is null. For Binomial GLMs, when the dataset contains the response column (and the trials column for the successes-and-trials format), the output also adds observed-outcome columns regardless of includeOriginalData: glm_observed for binary responses, or glm_observed_proportion and glm_trials for the successes-and-trials format.

For Random Forest the output keeps the predictor columns the model was fitted with and adds the predicted value (and one probability column per class for classification). Columns that are not predictors, including the response, are dropped. The output has as many rows as the source; rows with a missing predictor get a null prediction and are counted in nSkipped. confidenceLevels, predictionLevels, and includeOriginalData are settings of GLM and linear regression only.

const result = await window.midas.models.predict('model_001', {
  datasetId: 'New Patients',
  confidenceLevels: [95],
  predictionLevels: [90, 95],
});
// result.data: { id: 'ds_...', name: 'GLM Predictions: Recovery Model', rowCount: 40,
//   columnCount: 12, modelType: 'glm', nSkipped: 0,
//   accuracy: { kind: 'continuous', n: 40, r2: 0.78, rmse: 0.61, mae: 0.47 },
//   onFittingData: false, warnings: [] }

accuracy holds the prediction accuracy metrics computed on the response column of the predicted dataset, using the same calculation as the Prediction Accuracy Metrics on the GLM Prediction tab. GLM and linear regression return it when the dataset contains the response column (and the trials column for the successes-and-trials format), computed on the rows with a valid response and prediction. The shape is the same as inSampleAccuracy of a GLM models.run(): gaussian returns 'continuous' (r2, rmse, mae), binomial returns 'binary' (brier, auc, with n being the total number of trials), and gamma, poisson, and negative-binomial return 'deviance' (rmse, mae, meanDeviance). Values that cannot be computed are null. rmse divides by the number of rows n; fit.residualStdError of a linear regression models.run() divides by the residual degrees of freedom n - p, so the two differ on the same data. accuracy is null when the dataset has no response column, for Random Forest, when no row has a valid response and prediction, and when the trials column is missing; in the last two cases warnings states the reason. A ROC curve can be drawn when kind is 'binary' and auc is not null. Its data are the glm_predicted column and the observed-outcome columns of the created dataset, so the roc stat of a graph can draw the same curve as the tab.

onFittingData is true when the predicted dataset is the one the model was fitted on. accuracy is then an in-sample measure, the case in which the GLM Prediction tab shows a note below the metrics. Metrics on data not used for fitting are typically less favorable.

models.describe(id)

Get model details. Supports GLM, GLMM, Random Forest, ARIMA, Linear Regression, and ANOVA. The response structure varies by model type (check result.data.type). Models can be created via models.run() + models.save() or through the GUI.

GLM returns coefficients, fit statistics (AIC, BIC, deviance), diagnostic summary, and metadata.

GLMM returns fixed effects (same format as GLM coefficients), random effects (group variable, variance, ICC, BLUP), fit statistics (log-likelihood, iterations, convergence), and diagnostic summary. Warnings raised during fitting are returned in warnings. It is omitted for models with no warnings and for models saved before this information was persisted.

Random Forest returns task type (classification/regression), tuningParameters, the OOB score, MDI variable importances (if available), and OOB permutation importances (when computed). oobScore is OOB accuracy for classification and OOB R² for regression. It is null when the score cannot be computed, and warnings states the reason; the conditions are the same as described for Random Forest under models.run(). responseDegenerate is true when the response was degenerate at fitting time (no variation for regression, a single class for classification); models saved before this field was persisted omit it.

ARIMA returns the orders (p, d, q and the seasonal orders), coefficients (AR/MA/SAR/SMA/Intercept/Trend with CIs), fit statistics (AIC, BIC, log-likelihood, σ², convergence), and residualDiagnostics (ACF and PACF of residuals). The residual diagnostics from models.run() are persisted, so they are available without refitting. The acf and pacf arrays are empty for models saved before this was added, and a lag at which the autocorrelation cannot be computed holds null. For the conditions under which a lag is null, see the ARIMA notes under models.run().

Linear Regression returns coefficients (same shape as GLM; inference is always a t distribution), fit statistics (R², adjusted R², Residual Std. Error, AIC, BIC), diagnostic summary, metadata, and responseDegenerate. When responseDegenerate is true, rSquared, adjustedRSquared, residualStdError, and the coefficient se values and confidence intervals are null, as in models.run().

ANOVA returns the ANOVA table (sum of squares, degrees of freedom, mean square, and the effect sizes η² and ω², which are partial η² and partial ω² for two-way), group statistics, Tukey HSD (only when computed), and metadata. The response structure is the same as described for ANOVA under models.run(). exclusions is omitted for models saved before this information was persisted.

const result = await window.midas.models.describe('model_001');
// GLM example - result.data:
// {
//   type: 'glm',
//   family: 'gaussian',
//   link: 'identity',
//   id: 'model_001',
//   name: 'My Model',
//   metadata: {
//     createdAt: '2025-01-15T10:30:00Z',
//     fittingDatasetId: 'ds_001',
//     predictors: ['sepal_width', 'petal_length'],
//     response: 'sepal_length',
//     sampleSize: 150
//   },
//   coefficients: [
//     { variable: '(Intercept)', estimate: 2.25, se: 1.02, ciLower: 0.23, ciUpper: 4.27, expEstimate: null, expCiLower: null, expCiUpper: null },
//     { variable: 'sepal_width', estimate: 0.60, se: 0.24, ciLower: 0.13, ciUpper: 1.07, expEstimate: null, expCiLower: null, expCiUpper: null },
//     ...
//   ],
//   inference: { distribution: 't', df: 147 },
//   fit: { deviance: 42.3, nullDeviance: 234.7, aic: 183.94, bic: 193.47, iterations: 5, converged: true },
//   diagnosticSummary: { ... }
// }

For GLMM, the coefficients under fixedEffects have the same shape as GLM coefficients. inference follows the same rule as models.run(): LMMs estimated with Kenward-Roger inference report { distribution: 't-per-coefficient', method: 'kenward-roger' } with a per-coefficient df, while other families and models saved before Kenward-Roger was introduced report { distribution: 'normal', df: null }. Random Forest does not include inference, coefficients, or fit fields.

// GLMM example - result.data:
// {
//   type: 'glmm',
//   family: 'gaussian',
//   link: 'identity',
//   id: 'model_002',
//   name: 'Mixed Model',
//   metadata: { createdAt: '2025-01-15T10:30:00Z', fittingDatasetId: 'ds_001', predictors: ['x1'], response: 'y', sampleSize: 200 },
//   fixedEffects: [
//     { variable: '(Intercept)', estimate: 3.14, se: 0.85, df: 8.7, ciLower: 1.21, ciUpper: 5.07, expEstimate: null, expCiLower: null, expCiUpper: null },
//     { variable: 'x1', estimate: 0.52, se: 0.18, df: 182.4, ciLower: 0.16, ciUpper: 0.88, expEstimate: null, expCiLower: null, expCiUpper: null }
//   ],
//   inference: { distribution: 't-per-coefficient', method: 'kenward-roger' },
//   randomEffects: {
//     groupColumn: 'school',
//     variance: 1.23,
//     residualVariance: 4.56,
//     icc: 0.212,
//     blup: [{ groupId: 'A', estimate: 0.45, standardError: 0.21, rank: 1 }, { groupId: 'B', estimate: -0.32, standardError: 0.19, rank: 2 }]
//   },
//   fit: { logLikelihood: -447.05, aic: 902.1, bic: 915.3, iterations: 12, converged: true },
//   diagnosticSummary: { nObservations: 200, nGroups: 10, nFixedEffects: 2, nIncomplete: 0, groupSizes: [{ groupId: 'A', size: 20 }, { groupId: 'B', size: 15 }, { groupId: 'C', size: 25 }] }
// }
// Random Forest example - result.data:
// {
//   type: 'random_forest',
//   id: 'model_003',
//   name: 'RF Classifier',
//   metadata: { createdAt: '2025-01-15T10:30:00Z', fittingDatasetId: 'ds_001', predictors: ['x1', 'x2', 'x3'], response: 'species', sampleSize: 150 },
//   taskType: 'classification',
//   tuningParameters: {
//     nEstimators: 100,
//     maxDepth: null,
//     minSamplesSplit: 2,
//     minSamplesLeaf: 1,
//     maxFeatures: 'sqrt',
//     randomState: 42
//   },
//   featureImportances: [
//     { feature: 'x1', importance: 0.45 },
//     { feature: 'x2', importance: 0.35 },
//     { feature: 'x3', importance: 0.20 }
//   ],
//   permutationImportances: [
//     { feature: 'x1', importance: 0.38 },
//     { feature: 'x2', importance: 0.42 },
//     { feature: 'x3', importance: 0.12 }
//   ]
// }

featureImportances is MDI (Mean Decrease in Impurity). permutationImportances is OOB permutation importance — the mean decrease in OOB prediction accuracy when each predictor is shuffled; it is undefined when not computed. Values can be negative. A negative value means that the mean of the per-tree OOB prediction accuracy was higher after shuffling that predictor than before shuffling. Both arrays follow the order of metadata.predictors.

models.retryEstimation(id)

Estimates again, with the same data, a model whose re-estimation failed. This is the same operation as Retry in the failure message that tabs and report elements showing the model display.

const result = await window.midas.models.retryEstimation('model_001');
// result.data: { modelId: 'model_001', name: 'Sepal fit' }

MIDAS keeps the failure of a re-estimation and does not estimate the model again until the dataset used for fitting changes or you retry.

retryEstimation() discards the kept failure of the model, discards the same kept failures for the dataset used for fitting as datasets.retryEvaluation() does, discards the kept failures of the datasets that use the model, and then estimates the model. A model that has estimates is not estimated again.

models.dependents(id)

Returns what models.remove() would delete together with the model, without changing anything.

const result = await window.midas.models.dependents('model_001');
// result.data: { modelId: 'model_001', name: 'Sepal fit',
//   derivedDatasets: [{ id: 'ds_002', name: 'Sepal fit Coefficients' }, { id: 'ds_003', name: 'Large effects' }],
//   models: [{ id: 'model_002', name: 'Second stage', type: 'linear_regression' }],
//   reportElements: [{ reportId: 'report_001', reportName: 'Report 1', elements: [{ id: 'el_001', type: 'model_stats' }] }],
//   tabs: [{ id: 'tab_001', title: 'Sepal fit', type: 'model-detail' }] }

derivedDatasets are the derived datasets that depend on the model directly or indirectly: every dataset saved from the model, such as coefficient tables, diagnostic datasets, and prediction results, and the datasets derived from them. models are the models fitted on those derived datasets, and do not include the model itself. reportElements are the report elements that reference the model or any derived dataset or model deleted with it. tabs are the tabs in the active workspace that would be closed.

models.remove(id)

Removes a model from the project.

const result = await window.midas.models.remove('model_001');
// result.data: the same shape as models.dependents()

You can check what will be deleted beforehand with models.dependents().

models.configure(tabId, config)

Configures a model tab. Set config.type to the model type, which must match the type of the tab. The available types are glm, glmm, random_forest, arima, linear_regression, anova, pca, kaplan_meier, and cox_regression. Every field other than type is optional, and only the fields you pass are changed. The dataset name passed as datasetId and column names are resolved case-insensitively. Changing datasetId to another dataset clears the variable selections.

The available fields are those of models.run() for that model type that the tab holds as settings. You can set the dataset, the variable selection, the model settings, the convergence controls, and the confidence level. Fields the tab has no setting for are given only when running with models.run(). ANOVA postHoc is one such field, so whether Tukey HSD is computed is decided by models.run(). Cox regression maxIterations and tolerance are the others: the Cox regression tab has no inputs for the convergence controls. On a negative binomial GLM tab, passing theta switches the tab to a manual theta (useManualTheta: true), and passing useManualTheta: false returns it to automatic estimation of theta. On GLM and GLMM tabs, changing family without passing link resets the link to the family's default, as choosing a family again in the UI does.

The columns you pass must be of a kind the GUI selector can pick. PCA columns, Cox regression covariates, and the survival timeColumn must be numeric columns, eventColumn must be an int64 or boolean column, and the Kaplan-Meier groupColumn must be a categorical column. The GLM, GLMM, linear regression, Random Forest, ARIMA, and ANOVA columns follow the same rules as in models.run().

PCA nComponents is the maximum number of components to keep, and passing null removes the limit so that all components are kept. Kaplan-Meier tau is the RMST restriction time (a positive number), and passing null returns it to the default (the smallest of the maximum observed times across groups). Changing timeColumn also returns tau to the default. Kaplan-Meier survivalTimes are the times at which the Survival at Specified Times table reads the survival probability, and passing null clears them. Changing timeColumn also clears them. Passing null as groupColumn stops grouping and estimates a single curve.

When the tab already shows results and you change a setting that affects them, those results no longer belong to the current settings, so they are removed from the view and replaced with a message prompting another run. Restoring the previous settings brings the results back. Use models.run() to get results, or run the analysis again in the GUI. Which settings affect the results is the same as on each tab's page; confidenceLevel on GLM, GLMM, linear regression, Cox regression, and ARIMA tabs only changes how the intervals are displayed, so the results are kept.

await window.midas.models.configure('glm_001', {
  type: 'glm',
  family: 'binomial',
  link: 'logit',
  yColumn: 'outcome',
  xColumns: ['age', 'treatment'],
});

await window.midas.models.configure('arima_001', {
  type: 'arima',
  seriesColumn: 'sales',
  order: [1, 1, 1],
  seasonalPeriod: 12,
});

reports

Report text content can be modified with two methods: addContent() appends Markdown to the end of the existing content; setContent() replaces the entire content. Both methods preserve the report's elements — only the text is affected.

reports.create(name, description?)

Create a new report.

const result = await window.midas.reports.create('Analysis Report');
// result.data: { id: 'report_...', name: 'Analysis Report' }

reports.list()

List reports.

const result = await window.midas.reports.list();
// result.data: [{ id, name, elementCount }, ...]

reports.rename(reportId, newName)

Rename a report. The report title and the labels of the report's tabs change to the new name. Several reports can have the same name.

const result = await window.midas.reports.rename(reportId, 'Weekly Report');
// result.data: { reportId, previousName: 'Analysis Report', name: 'Weekly Report' }

reports.getContent(reportId)

Get report content.

const result = await window.midas.reports.getContent('report_001');
// result.data: { content: '## Analysis Results\n...', elements: [{ id, type, title, renderStatus, renderStatusMessage?, renderWarnings? }, ...] }

renderStatus is included for every element. 'ok' means no issue preventing rendering was detected, 'empty' means data rows exist but no renderable points remain, and 'error' means the element cannot render due to a missing dataset, unloaded data, a validation error in the configuration (required columns not selected, a column type the axis does not accept, a palette incompatible with the scale type, etc.), or a facet panel count above the limit configured in Settings (Max Facet Panels). For graph elements, the check uses the data after the element's filter expression is applied, the same data the report view draws, and verifies that renderable points exist. Pair Plot elements are the exception: they are only checked for dataset existence, load state, and configuration validity, and their 'ok' does not mean the rendered output was verified.

reports.getContent evaluates a derived dataset that an element references before determining renderStatus, if the dataset has not been evaluated yet.

Graph elements also carry renderWarnings when the graph has diagnostics. The kinds of diagnostic are the same as in tabs.getGraphBuilder(). Pair Plot shows no warnings in the report view either, so Pair Plot elements do not carry renderWarnings.

reports.setContent(reportId, content)

Replace all text content of the report. Text added by addContent() or addModelSummary() is also replaced.

Elements whose {{type:id}} references are removed from the content are not automatically deleted. They remain in the report's elements and are shown again when you put a line that contains only {{type:id}} back into the content. To permanently remove an element, use reports.removeElement().

const result = await window.midas.reports.setContent('report_001', '## Updated Results\n...');
// result.data: { contentLength: 42 }
// result.warnings: ['Element reference {{data_table:xxx}} not found in report elements']  // when unregistered references exist

reports.addContent(reportId, markdown)

Append Markdown text to the end of a report.

await window.midas.reports.addContent('report_001', '## Analysis Results\n\nThe model shows...');

reports.addDataTable(reportId, datasetId, options?)

Add a dataset to a report as a data table element. datasetId accepts a dataset ID or name (case-insensitive). The element is registered as type: 'data_table' under report.elements, and a {{data_table:elementId}} reference is appended to the content.

const result = await window.midas.reports.addDataTable('report_001', 'Species Averages', {
  columns: ['species', 'avg_sl'],
  maxRows: 10
});
// result.data: { elementId, reportId, renderStatus, renderStatusMessage? }

Options:

  • columns (string[] | 'all') — Columns to display, as an array of column names or column IDs. With 'all', the element shows every column of the dataset at render time and automatically follows later column additions, renames, and removals. When omitted, the element stores an explicit list of all columns at creation time and does not follow later schema changes
  • maxRows (number) — Maximum number of rows to display. An integer from 1 to 1000. When omitted, all rows are displayed (up to 1000)

A derived dataset that has not been evaluated yet is evaluated before the table is added. renderStatus is 'empty' when the dataset has no rows, and 'ok' otherwise.

reports.addCoxRegression(reportId, config, table, options?)

Adds a result of the Cox Regression tab to a report, in the same way as Add to Report in the tab. The table is registered as the same derived dataset as models.saveCoxTable(), and the element displays that dataset. config, table, and options mean the same as in models.saveCoxTable(). The confidence intervals are computed at the level of confidenceLevel, and the dataset is registered under the default name when name is omitted. 'coefficients' and 'baseline_hazard' become type: 'data_table' elements that show all columns, and 'adjusted_survival' becomes a type: 'graph_builder' element that draws the survival curve and its confidence band.

const result = await window.midas.reports.addCoxRegression('report_001', {
  datasetId: 'ds_001',
  timeColumn: 'time',
  eventColumn: 'event',
  covariates: ['age', 'sex'],
}, 'adjusted_survival', { covariateValues: { sex: 1 } });
// result.data: { elementId, reportId, elementType: 'graph_builder', datasetId, datasetName,
//   datasetReused: false, covariateValues: { age: 62.4, sex: 1 }, warnings: [] }

datasetReused shows whether a dataset of the same table already existed and the element refers to it instead of a newly registered one. warnings are the same as in models.saveCoxTable() and are not displayed in the report element.

reports.updateDataTable(reportId, elementId, options)

Change the display columns and maximum rows of an existing data_table element. The element keeps its ID and its position in the report content.

const result = await window.midas.reports.updateDataTable('report_001', 'table-xxx', {
  columns: 'all'
});
// result.data: { elementId, reportId }

Options:

  • columns (string[] | 'all') — Columns to display. Same meaning as in addDataTable().
  • maxRows (number) — Maximum number of rows to display. An integer from 1 to 1000

Specify at least one of columns and maxRows. Use updateElement() to change graph_builder elements.

reports.addModelSummary(reportId, modelId)

Add a model summary to a report. Supports GLM, GLMM, Linear Regression, Random Forest, ARIMA, and ANOVA.

All model types use the element-reference scheme (the same as addGraph). For GLM, GLMM, and Linear Regression, the coefficient table is added as a type: 'data_table' element under report.elements, and a {{data_table:elementId}} reference is inserted into the report content. For Random Forest, Feature Importance is added as a type: 'data_table' element (Feature and MDI columns, plus a Permutation column when permutation importances are available; sorted by Permutation descending when available, otherwise by MDI descending) when featureImportances is available. The underlying derived dataset is registered in project.datasets, so it also appears in the Data tab listing. Every data_table element this method registers (including the BLUP, ANOVA Type I/III, Prediction Intervals, ARIMA coefficient, and ANOVA tables described below) has display columns 'all', so it shows every column of the derived dataset at render time (the same as columns: 'all' in addDataTable()). Deleting a model automatically removes associated coefficient datasets and prunes any report element that references the deleted datasets or model — data_table, model_stats, graph_builder, crosstab, statistics_summary, and anova.

For GLM, GLMM, and Linear Regression, the Model Fit / Random Effects / OLS Fit summary is registered as a type: 'model_stats' element under report.elements, and a {{model_stats:elementId}} reference is inserted into the report content. The element stores only the model id and resolves values from project.models[modelId] at render time, so when the same model id is refitted and project.models is overwritten, existing reports automatically reflect the new values.

GLM and GLMM coefficient tables share the same base columns: Variable, Estimate, Std. Error, Lower N%, Upper N%. LMMs (gaussian + identity GLMMs) estimated with Kenward-Roger inference add a df column after Std. Error. For logit and log links, exp-transformed columns are appended: OR / IRR / exp(Est.), exp(Lower N%), exp(Upper N%). N is the confidence level saved with the model (confidenceLevel, default 95). GLM coefficient tables also include a trailing VIF column (null for the intercept row, for models without an intercept, and for every predictor at once when the correlation matrix of the coefficients is singular). Linear Regression coefficient tables additionally include Std. Coef. and VIF. Std. Coef. is null for the intercept row, and null for every predictor row at once for models without an intercept, for a degenerate response, and when a standard deviation cannot be computed in double precision. Confidence intervals are Wald-type (estimate ± criticalValue × SE). For GLM, the critical value depends on family and link: families that estimate the dispersion parameter ϕ\phi from data use t1−α/2, n−pt_{1-\alpha/2,\, n-p}, while families with ϕ=1\phi = 1 use z1−α/2z_{1-\alpha/2} (see the table under models.run()). For GLMM fixed effects, LMMs with Kenward-Roger inference use a t distribution with per-coefficient degrees of freedom, and other combinations use the standard normal distribution. Linear Regression always uses the t distribution.

What each model type renders:

  • GLM: The model_stats element renders a Model Fit section with AIC, BIC, Residual Deviance, Null Deviance, and Convergence (with the iteration count).
  • GLMM: When BLUP data exists, a BLUP table (Group, Conditional Mode, Std. Error, Rank — sorted by estimate descending) is added as a data_table element, with a ### Random Effects (BLUP) heading and {{data_table:blupElementId}} reference in the content (result.data.blupElementId returns the id). The model_stats element renders a Random Effects section with Group Variable, Number of Groups, Random Intercept Variance, ICC, and, for families that estimate a dispersion parameter, a residual variance row; and a Model Fit section with Log-Likelihood, AIC, BIC, Convergence (with the iteration count), Observations, and N incomplete (only when rows were excluded for missing values). For LMM (Gaussian + identity link), labels read REML Log-Likelihood and ICC; for every other family+link combination, they read Log-Likelihood (Laplace) and ICC (latent scale). The ICC row shows a value only for LMM and Binomial + logit/probit. For Poisson, Gamma, and Gaussian + log, no theoretically grounded latent-scale residual variance exists, so the ICC row reads N/A (ICC not defined). The residual variance row appears for Gaussian and Gamma. For Gaussian, the value of this row is the estimate of the conditional variance of the response σe2\sigma_e^2 whatever the link, so the row reads Residual Variance. For Gamma, the value of this row is the estimate of the dispersion parameter ϕ\phi, and the conditional variance of the response is ϕμ2\phi\mu^2, so the row reads Dispersion (φ). A Warnings section follows when the model has warnings.
  • Linear Regression: Five elements are registered — coefficient table, ANOVA Type I, ANOVA Type III, Prediction Intervals (per-observation prediction / confidence intervals), and a model_stats element. The model_stats element renders an OLS Fit section with R², Adjusted R², Residual Std. Error, and Observations, plus an Information Criteria section with AIC and BIC. Convergence is not shown because it is trivial for OLS.
  • Random Forest: A Feature Importance data_table element (Feature and MDI columns, plus a Permutation column when permutation importances are available; sorted by Permutation descending when available, otherwise by MDI descending) when featureImportances is available, and a model_stats element rendering a Model Configuration section (Task Type, Number of Trees, Max Depth, Min Samples Split, Min Samples Leaf, Max Features) and OOB Accuracy (classification) or OOB R² (regression).
  • ARIMA: The coefficient table (AR, MA, SAR, SMA, Intercept or Drift, and Trend terms with confidence intervals) is added as a data_table element, and the model_stats element renders a Model Fit section with Order (including the seasonal (P, D, Q)[s] part for seasonal models), Log-Likelihood, AIC, BIC, σ², Converged, and Observations.
  • ANOVA: ANOVA Table and Group Statistics are registered as data_table elements. For one-way ANOVA with a computed Tukey HSD, a Tukey HSD table is also added. The model_stats element renders an ANOVA Fit section with Design (one-way or two-way, and whether the two-way model includes the interaction), Sum of Squares (two-way only, Type I or Type III), Observations, and N excluded (only when rows were excluded), followed by a Warnings section when the model has warnings (degenerate response, condition number, dropped factor levels, and so on). N excluded carries notes for the excluded rows that no Group Statistics row accounts for: rows with a missing factor value, and rows in groups left with no valid observations. Group Statistics has Group, N, Excluded (only when the model has excluded rows), Mean, Std. Dev., Lower/Upper N% (Individual) (an individual CI per group using the pooled MSE from the ANOVA table, not adjusted for multiple comparisons), Min, and Max columns. Tukey HSD has Group 1, Group 2, Mean Diff, Std. Error, Lower/Upper N% (Simultaneous) (the family-wise CI from the Tukey-Kramer method), plus q Critical, MSE, and DF columns (the pooled values used to compute the CI, repeated on every row); the content also notes that Std. Error is the standard error of the mean difference with CI half-width q_critical × Std. Error / √2, and that Tukey HSD assumes equal population variances.
const result = await window.midas.reports.addModelSummary('report_001', 'model_001');
// result.data: { reportId, addedText, elementId?, statsElementId?, anovaTypeIElementId?, anovaTypeIIIElementId?, groupStatisticsElementId?, tukeyHSDElementId?, predictionIntervalsElementId?, blupElementId? }
// - elementId: id of the coefficient / Feature Importance / ANOVA Table data_table element (RF: only when featureImportances is non-empty)
// - statsElementId: id of the model_stats element that renders Model Fit / Random Effects / OLS Fit / Model Configuration / ANOVA Fit
// - blupElementId: id of the BLUP data_table element for GLMM (only when BLUP data exists)
// - anovaTypeIElementId / anovaTypeIIIElementId / predictionIntervalsElementId: Linear Regression only
// - groupStatisticsElementId: id of the Group Statistics table for ANOVA
// - tukeyHSDElementId: id of the Tukey HSD table for ANOVA (only when Tukey HSD is computed)

When called multiple times for the same model, the coefficients dataset is reused when an existing derived dataset has both the same name and an identical operation definition. Calling this method after refitting the same model with different fit conditions returns APIResult.success === false with a A dataset named "X" already exists error, because the derived dataset would have the same name but a different operation definition. To record summaries for multiple fit configurations, either delete the previous model or save the new model under a different name before calling this method. Report elements and text are added anew each time.

reports.addGraph(reportId, config)

Add a graph to a report as a report element. Creates a Custom Graph without opening a tab. datasetId accepts a dataset ID or name (case-insensitive). Column names are also resolved case-insensitively. Axis scales (scales), per-layer scales (layers[].scales), per-layer tooltips (layers[].tooltip, see addGraphLayer), facets (facets), and the brush selection direction (brush) can be specified. Passing panels instead of layers creates a multi-panel graph. Each panel needs at least one layer. A panel without yScale uses scales.y, and when scales.y is also omitted, its Y axis scale is inferred from the type of the y column mapped in the panel's first layer. See configureGraph for the facets, panels, and brush property reference. globalAes sets the aes shared by every layer. filterExpression sets a filter expression that narrows the rows of the whole graph, in the same syntax as the Data Table filter input. For a graph that draws an intermediate aggregate, set lineageTargetDatasetId (an ancestor of datasetId) to make selection and drill-down act on the underlying data (see configureGraph).

const result = await window.midas.reports.addGraph('report_001', {
  datasetId: 'ds_001',
  layers: [
    { geom: { type: 'point' }, aes: { x: 'weight', y: 'height' } }
  ],
  title: 'Weight vs Height',
  aspectRatio: 'custom',
  height: 500,
});
// result.data: { elementId, reportId, renderStatus, renderStatusMessage?, renderWarnings? }

renderStatus indicates the rendering outcome. 'ok' means the geom of at least one layer draws something. 'empty' means the geom of no layer draws anything. 'error' means the graph fails validation (a column type the axis does not accept, a palette incompatible with the scale type, a missing required aesthetic, etc.) and cannot render. renderStatusMessage provides a reason when the status is not 'ok'. renderWarnings is also included when the graph has diagnostics. The kinds of diagnostic are the same as in tabs.getGraphBuilder(), and the same content also appears as a warning above the graph in the report view.

Faceted graphs are evaluated with the same data processing as the actual rendering. MIDAS splits the data into panels, computes the domains shared across all panels, and then evaluates each panel individually. States that appear only after panel splitting are detected by this evaluation, so renderStatus and renderWarnings match the rendered result. Each line of renderWarnings carries the title of the panel that reported it, and a warning reported identically by every panel is merged into a single line prefixed with All panels:. When the number of panels exceeds the limit configured in Settings (Max Facet Panels), the graph is not rendered and renderStatus is 'error'.

The graph is stored as a report element and a {{graph_builder:elementId}} reference is appended to the report content.

See Custom Graph Reference for the list of geom, stat, and position types. Each stat's params are documented there with their accepted values and defaults. For facets, coordinates, and other graph-level options, see Custom Graph.

coordinates accepts 'flipped' or 'cartesian'. When 'flipped' is specified, the X and Y axes are swapped. Defaults to 'cartesian'.

aspectRatio accepts '16:9', '4:3', '1:1', '3:4', '9:16', or 'custom'. Defaults to '16:9'. When a preset value other than 'custom' is specified, the aspect ratio determines the displayed height and height is not used for rendering. When 'custom' is specified, height sets the height. height defaults to 400, minimum 300, maximum 5000.

reports.updateElement(reportId, elementId, config)

Replace the configuration of an existing graph_builder element (full replacement). The element retains its ID and position in the report content. config has the same structure as addGraph (datasetId accepts a dataset ID or name). The element's width and layout are not part of config and are preserved after the update.

const result = await window.midas.reports.updateElement('report_001', 'graph-xxx', {
  datasetId: 'ds_001',
  layers: [
    { geom: { type: 'bar' }, aes: { x: 'category', y: 'count' } }
  ],
  title: 'Updated Chart',
});
// result.data: { elementId, reportId, renderStatus, renderStatusMessage?, renderWarnings? }

renderStatus, renderStatusMessage, and renderWarnings mean the same as in addGraph().

The display columns and maximum rows of a data_table element can be changed with updateDataTable().

reports.removeElement(reportId, elementId)

Remove an element from a report and its {{type:elementId}} reference from the content. Supports all element types (graph_builder, data_table, model_stats, crosstab, statistics_summary, anova). Associated resources (derived datasets, models) are not deleted.

await window.midas.reports.removeElement('report_001', 'graph-xxx');
// result.data: { elementId, reportId }

reports.scrollTo(reportId, target)

Move the report view to an element or a heading. Specify exactly one of elementId and heading in target. A heading resolves from either an anchor name such as model-fit or the heading text itself. After the move, the target stays in view until the user starts scrolling, even when a table above it finishes evaluating and changes height.

The report must be open in a tab. When it is not, the call returns NOT_FOUND with a suggestion pointing to tabs.open(). When it is open, the tab is brought to the front before scrolling.

Elements added with reports.addGraph(), reports.addDataTable(), reports.addModelSummary(), or reports.addCoxRegression() come into view automatically the next time the report is shown. Use this method to move to an arbitrary position.

await window.midas.reports.scrollTo('report_001', { heading: 'Model Fit' });
// result.data: { reportId, anchor: 'model-fit' }

await window.midas.reports.scrollTo('report_001', { elementId: 'graph-xxx' });
// result.data: { reportId, elementId: 'graph-xxx' }

reports.remove(reportId)

Remove a report from the project. Closes any open tabs that reference the report.

await window.midas.reports.remove('report_001');

layout

layout.split(config)

Split a pane to create a new area.

const result = await window.midas.layout.split({
  tabId: 'tab_001',
  direction: 'horizontal'  // 'horizontal' or 'vertical'
});
// result.data: { newPaneId: 'pane_...', originalPaneId: 'pane_...' }

Use the returned newPaneId with tabs.moveToPane() to place tabs in the new pane.

layout.get()

Get how the panes are arranged. To move a tab into a pane you did not create with layout.split() yourself, take its ID from here and pass it to tabs.moveToPane().

const result = await window.midas.layout.get();
// result.data: { rootPane, activePaneId }

rootPane is a tree of panes. Each node is either a split or a pane: type is 'split' for a split and 'container' for a pane.

A split describes how its area is divided. direction is 'horizontal' for a left-right split and 'vertical' for a top-bottom one. splitRatio is the share taken by the first of the two children. children holds them in order: left then right for a horizontal split, top then bottom for a vertical one.

A pane holds tabs. Each entry of tabs has the same shape as in tabs.list(). activeTabId is the tab shown at the front, or null when the pane has no tabs. activePaneId names the pane operated on last, so compare a pane's id against it to tell whether that pane is the active one.

Both kinds of node carry rect, the position and size within the layout area expressed as fractions of the whole, with the origin at the top-left. It comes from the split ratios, so it does not account for the width of the resizers between panes.

A pane also carries viewportRect, the measured position and size of its DOM element in viewport coordinates, in pixels and on the same basis as getBoundingClientRect(). It is null before the pane is rendered. Resizing the window and dragging a resizer both change it, so read it again when matching it against a screenshot.

// In a layout whose right half is split top and bottom, move a tab into the lower pane
const { rootPane } = (await window.midas.layout.get()).data;
const [, right] = rootPane.children;
const [, rightBottom] = right.children;
await window.midas.tabs.moveToPane('tab_001', rightBottom.id);

Reference

  • Live reference: Run window.midas.help() in the project screen