edf2csv 0.7.218 → 0.7.220
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/convert/plan.js +15 -6
- package/dist/convert/plan.js.map +1 -1
- package/dist/edf/header.js +6 -1
- package/dist/edf/header.js.map +1 -1
- package/package.json +1 -1
package/dist/convert/plan.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
import { formatRate, formatRates } from '../edf/header.js';
|
|
12
12
|
import { decimalsAreClamped, decimalsForSignal, makeScaler } from '../edf/scale.js';
|
|
13
13
|
import { UTF8_BOM, csvRow, escapeCsvField } from '../format/csv.js';
|
|
14
|
-
import { listed } from '../format/list.js';
|
|
14
|
+
import { counted, listed } from '../format/list.js';
|
|
15
15
|
import { fixed, timeDecimals } from '../format/number.js';
|
|
16
16
|
import { TIME_COLUMN, buildColumnNames, renamedByCollision, selectChannels } from './channels.js';
|
|
17
17
|
import { assertOptions } from './options.js';
|
|
@@ -256,7 +256,7 @@ export function buildPlan(input, options = {}) {
|
|
|
256
256
|
*/
|
|
257
257
|
const untimeable = groups.some((group) => !Number.isFinite(group.rate));
|
|
258
258
|
if (writeSignals && groups.length > 0 && estimate.rows === 0 && !untimeable) {
|
|
259
|
-
diagnostics.push(emptyWindow(range, input.recordCount));
|
|
259
|
+
diagnostics.push(emptyWindow(range, input.recordCount, groups.length));
|
|
260
260
|
}
|
|
261
261
|
if (estimate.exceedsSpreadsheetLimit) {
|
|
262
262
|
diagnostics.push({
|
|
@@ -469,16 +469,25 @@ function widthOf(magnitude, decimals, signed = false) {
|
|
|
469
469
|
* happens to line up with the window; --strict turns it into a failure for those who want
|
|
470
470
|
* that.
|
|
471
471
|
*/
|
|
472
|
-
function emptyWindow(range, recordCount) {
|
|
472
|
+
function emptyWindow(range, recordCount, fileCount) {
|
|
473
473
|
const asked = !range.isWholeRecording;
|
|
474
|
+
/*
|
|
475
|
+
One rate is one file, which is nearly every recording, and this said "files" either way:
|
|
476
|
+
"so the signal files hold their headers and no data" over a single signals.csv. The count
|
|
477
|
+
is `plan.groups.length` and the caller has had it all along — it is the same number the
|
|
478
|
+
mixed-rate warning three functions up counts to decide whether to fire at all.
|
|
479
|
+
*/
|
|
480
|
+
const tables = fileCount === 1
|
|
481
|
+
? 'the signal file holds its header and no data'
|
|
482
|
+
: 'the signal files hold their headers and no data';
|
|
474
483
|
return {
|
|
475
484
|
code: 'EMPTY_WINDOW',
|
|
476
485
|
severity: 'warning',
|
|
477
486
|
message: asked
|
|
478
487
|
? `No samples fall inside the requested window (${fixed(range.startSeconds, 3)}s to ` +
|
|
479
|
-
`${fixed(range.endSeconds, 3)}s), so
|
|
480
|
-
: `This recording's ${recordCount
|
|
481
|
-
`
|
|
488
|
+
`${fixed(range.endSeconds, 3)}s), so ${tables}.`
|
|
489
|
+
: `This recording's ${counted(recordCount, 'data record')} carry no samples in range, ` +
|
|
490
|
+
`so ${tables}.`,
|
|
482
491
|
hint: asked
|
|
483
492
|
? /*
|
|
484
493
|
Which of the two it was, rather than the second one always.
|
package/dist/convert/plan.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plan.js","sourceRoot":"","sources":["../../src/convert/plan.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAIH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACpF,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACpE,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3C,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAClG,O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,SAAS,GAAG,SAAS,GAAG,KAAK,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QACzE;;;;;;;;;;;UAWE;QACF,KAAK,IAAI,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,GAAG,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QAC3F,iFAAiF;QACjF,yFAAyF;QACzF,qFAAqF;QACrF,qBAAqB;QACrB,IAAI,GAAG;YAAE,KAAK,IAAI,SAAS,CAAC;IAC9B,CAAC;IAED,IAAI,MAAM,KAAK,MAAM,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC3C,IAAI,QAAQ,GAAG,CAAC,GAAG,qBAAqB;YAAE,OAAO,GAAG,IAAI,CAAC;QACzD,KAAK,IAAI,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACvE,IAAI,GAAG;YAAE,KAAK,IAAI,SAAS,CAAC;IAC9B,CAAC;IAED,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,uBAAuB,EAAE,OAAO,EAAE,CAAC;AAC3D,CAAC","sourcesContent":["/**\n * Turning a request into a concrete conversion plan.\n *\n * The plan is where the tool's central promise is enforced: channels recorded at\n * different sampling rates are never merged into one table. A single wide CSV can\n * only hold mixed rates by inventing samples for the slow channels — MNE, for\n * instance, expands three genuine 1 Hz temperature readings into 768 interpolated\n * values without warning. Instead each distinct rate gets its own file, so every\n * number in every output file is a number that was actually recorded.\n */\n\nimport type { Diagnostic } from '../edf/errors.js';\nimport type { EdfSignal } from '../edf/header.js';\nimport { formatRate, formatRates } from '../edf/header.js';\nimport { decimalsAreClamped, decimalsForSignal, makeScaler } from '../edf/scale.js';\nimport { UTF8_BOM, csvRow, escapeCsvField } from '../format/csv.js';\nimport { listed } from '../format/list.js';\nimport { fixed, timeDecimals } from '../format/number.js';\nimport { TIME_COLUMN, buildColumnNames, renamedByCollision, selectChannels } from './channels.js';\nimport { assertOptions } from './options.js';\nimport { countSamplesInRange, resolveRange } from './time-range.js';\nimport type { ResolvedRange } from './time-range.js';\n\nexport interface PlannedChannel {\n signal: EdfSignal;\n column: string;\n decimals: number;\n}\n\nexport interface RateGroup {\n /** Sampling rate in Hz shared by every channel in this group. */\n rate: number;\n samplesPerRecord: number;\n fileName: string;\n timeDecimals: number;\n channels: PlannedChannel[];\n}\n\nexport interface PlanInput {\n signals: readonly EdfSignal[];\n recordDuration: number;\n recordCount: number;\n hasAnnotationChannel: boolean;\n /**\n * True start time of each data record, supplied for discontinuous files. The\n * requested time window is resolved against these rather than against\n * `recordCount * recordDuration`, which for a file with gaps is the amount of\n * data rather than the span of time it covers.\n */\n recordStarts?: Float64Array | null | undefined;\n}\n\nexport interface PlanOptions {\n channels?: readonly string[] | undefined;\n start?: number | undefined;\n /** The `--start` value exactly as typed, for error messages. */\n startText?: string | undefined;\n duration?: number | undefined;\n end?: number | undefined;\n /** The `--end` value exactly as typed, for error messages. */\n endText?: string | undefined;\n annotationsOnly?: boolean | undefined;\n /** Force a fixed number of decimals instead of deriving it per channel. */\n decimals?: number | undefined;\n /** Compress each CSV with gzip, giving every one of them a `.gz` name. */\n gzip?: boolean | undefined;\n /** Start each CSV with a UTF-8 byte order mark, so Excel reads it as UTF-8. */\n bom?: boolean | undefined;\n /**\n * How the samples are arranged in the CSV.\n *\n * `'wide'`, the default, gives one column per channel and one file per sampling rate.\n * `'long'` gives one file, three columns — `time_s`, `channel`, `value` — and one row per\n * sample. See ConversionPlan.layout for why that is the only way to put channels recorded\n * at different rates in one table without inventing samples.\n */\n layout?: 'wide' | 'long' | undefined;\n}\n\nexport interface ConversionPlan {\n groups: RateGroup[];\n /**\n * How the samples are arranged. `'wide'` is a column per channel and a file per rate;\n * `'long'` is `time_s,channel,value`, one row per sample, all rates in one file.\n *\n * The wide layout has to split a mixed-rate recording across files: a 100 Hz channel and\n * a 1 Hz channel share no rows, and putting them in one wide table means either 99 empty\n * cells out of every hundred or inventing the samples that would fill them. In the long\n * layout each sample carries its own time, so nothing has to line up and nothing is\n * invented — which also makes it the one layout `--stdout` can stream for such a file.\n */\n layout: 'wide' | 'long';\n\n /**\n * Whether the CSVs will be compressed.\n *\n * Recorded rather than inferred from the group file names. Under `--annotations-only`\n * there are no groups to read it off, and `--info` named `annotations.csv` for a run that\n * wrote `annotations.csv.gz`.\n */\n gzip: boolean;\n range: ResolvedRange;\n columnNames: Map<number, string>;\n writeSignals: boolean;\n diagnostics: Diagnostic[];\n estimate: OutputEstimate;\n}\n\nexport interface OutputEstimate {\n /** Total data rows across every signal file. */\n rows: number;\n /**\n * Approximate size of the signal CSVs as CSV text, which under `gzip` is not their size on\n * disk: what is counted here is what the compressor is handed, and the file holds what it\n * produces. `--info` writes \"before compression\" beside this number for that reason, and\n * `infoJson` calls it a character count.\n */\n bytes: number;\n /** True when any single file would exceed Excel's row limit. */\n exceedsSpreadsheetLimit: boolean;\n}\n\nconst BOM_BYTES = Buffer.byteLength(UTF8_BOM);\n\n/** Excel and most spreadsheet tools stop at 1,048,576 rows including the header. */\nexport const SPREADSHEET_ROW_LIMIT = 1_048_576;\n\nexport function buildPlan(input: PlanInput, options: PlanOptions = {}): ConversionPlan {\n // First, and before a directory is created or a stream opened, so a rejected option\n // leaves nothing behind. See assertOptions for what used to get through.\n assertOptions(options);\n\n const diagnostics: Diagnostic[] = [];\n const columnNames = buildColumnNames(input.signals);\n\n // A channel whose own label was taken by something else in the header. Usually that is\n // another channel's disambiguating suffix — the duplicate-label warning is about the labels\n // that collided, this is about the channel that lost its name to them. The other way is a\n // channel labelled `time_s`, where what took the name is the time column itself, which every\n // signals.csv begins with and no file supplies.\n /*\n \"so its column is\" was a sentence about the wide layout, printed in both.\n\n A long signals.csv has three columns — time_s, channel, value — and none of them is a\n label: a channel appears there as a value in the `channel` column. So a `--layout long`\n run was told that a column had been renamed to avoid colliding with a column neither of\n them has, under a hint promising that \"column names are unique\" about a set of three\n fixed strings the file never got from the header.\n\n The rename is right in both layouts, which is why only the noun moves. The names have to\n agree between the `channel` cells and channels.csv and across runs, and the `pivot` the\n documentation gives for turning a long table back into a wide one would otherwise put a\n `time_s` column against a `time_s` index — the collision one step later.\n */\n const inLongLayout = (options.layout ?? 'wide') === 'long';\n for (const signal of renamedByCollision(input.signals, columnNames)) {\n const taker =\n signal.label === TIME_COLUMN\n ? 'the name of the time column every signals.csv starts with'\n : `also the column name another channel's \"_ch\" suffix produces`;\n diagnostics.push({\n code: 'DUPLICATE_LABEL',\n severity: 'warning',\n message:\n `Signal ${signal.index} is labelled \"${signal.label}\", which is ${taker}, ` +\n `so ${inLongLayout ? 'it is named' : 'its column is'} \"${columnNames.get(signal.index)}\"` +\n `${inLongLayout ? ' in the channel column' : ''}.`,\n hint: inLongLayout\n ? 'Channel names are unique; look this channel up in channels.csv by its signal_index.'\n : 'Column names are unique; look this channel up in channels.csv by its signal_index.',\n });\n }\n\n const range = resolveRange({\n start: options.start,\n startText: options.startText,\n duration: options.duration,\n end: options.end,\n endText: options.endText,\n recordDuration: input.recordDuration,\n recordCount: input.recordCount,\n recordStarts: input.recordStarts,\n });\n\n const writeSignals = options.annotationsOnly !== true;\n\n let chosen: EdfSignal[] = input.signals.filter((s) => !s.isAnnotations);\n\n /*\n Channel names are checked even under --annotations-only, where the selection is not\n otherwise used.\n\n Skipping the check meant `--channels TYPO --annotations-only` exited 0 in silence while\n the same typo without the flag was a usage error, and `--channels \"\"` stayed an error\n in both — so a mistyped name was the one form of bad input the tool accepted quietly.\n Everywhere else a term matching nothing is reported rather than ignored; a flag that\n happens not to apply is a poor reason to make an exception.\n */\n if (options.channels && options.channels.length > 0) {\n const selection = selectChannels(input.signals, options.channels);\n if (writeSignals) chosen = selection.signals;\n for (const { term, matched } of selection.ambiguous) {\n diagnostics.push({\n code: 'DUPLICATE_LABEL',\n severity: 'warning',\n message:\n `\"${term}\" matches ${matched.length} channels (positions ` +\n `${listed(matched.map((s) => `#${s.index}`))}); all of them were selected.`,\n hint: `Use --channels \"#${matched[0]?.index ?? 0}\" to pick just one.`,\n });\n }\n }\n\n const layout = options.layout ?? 'wide';\n const groups = writeSignals\n ? groupByRate(chosen, columnNames, options.decimals, options.gzip === true, layout)\n : [];\n const estimate = estimateOutput(\n groups,\n range,\n input.recordDuration,\n input.recordStarts,\n options.bom === true,\n layout,\n );\n\n /*\n The mixed-rate warning describes what this conversion does, not what the file holds.\n\n The header parser raises its own, which is right for `parseHeader` — but it sees every\n channel and knows nothing about `--channels`. Converting one channel out of a three-rate\n recording therefore announced \"3 different sampling rates ... written to one file per\n rate\" over a run that wrote one file, in the same output where `--info` had already\n marked the other two \"(not selected)\". Selecting two of the three was wrong the other\n way: still \"3\".\n\n Callers combining these with a file's own diagnostics drop that copy in favour of this\n one; see `withoutFileRateWarning`.\n */\n if (groups.length > 1) {\n diagnostics.push({\n code: 'MIXED_SAMPLING_RATES',\n severity: 'warning',\n message:\n `Channels use ${groups.length} different sampling rates ` +\n `(${listed(formatRates(groups.map((g) => g.rate)).map((r) => `${r} Hz`))}).`,\n hint:\n layout === 'long'\n ? 'They share one table, each row carrying its own time, so no channel is resampled.'\n : 'They are written to one file per rate so no channel is resampled.',\n });\n }\n\n /*\n A time column that cannot tell two samples apart.\n\n Sample times are written to at most fifteen decimal places, which separates everything a\n terminating rate can reach — every power of two through 32768 Hz and far past it. Below\n that interval the column repeats: at 3e15 Hz, whose reciprocal never terminates, the rows\n of one record carry the same time_s, so joining or plotting on it silently collapses\n samples that are genuinely distinct. Nothing is lost from the file — every sample is\n there, in order — but the column stops being an identifier, and that is worth saying\n rather than leaving to be discovered.\n\n This said nine places and a gigahertz, and illustrated it with 1 ns records — all three of\n which stopped being true when 0.4.55 raised the search bound. Fifteen places resolve\n 1e-15 s, so a nanosecond interval is written exactly and that recording raises nothing at\n all. warnings-and-errors.md was corrected then and carries a note saying so; the comment\n it was written from was not, and the hint printed four lines below here has said \"the\n fifteen places a double can hold exactly\" ever since.\n */\n for (const group of groups) {\n const step = group.rate > 0 ? 1 / group.rate : 0;\n /*\n The limit of the same failure, which read as the absence of it.\n\n `samplesPerRecord / recordDuration` is a double, and a record duration of 1e-308 with\n four samples in it is Infinity. `1 / Infinity` is 0, so `step > 0` was false and this\n said nothing — while every sample was dropped, the run exited 0, and the only warning\n printed was EMPTY_WINDOW's \"This recording's 2 data records carry no samples in range\",\n which is untrue twice over: the records carry eight samples and no range was asked for.\n\n One power of ten away, at 1e-300, the rate is 4e300 and the file converts with the\n warning below. Same guard `decimalsAreClamped` had before 0.5.83, in the column next\n door: a step of exactly zero means no resolution at all, not nothing to report.\n\n Its own branch because the hint below is false here — no rows are written at all, so\n \"Every sample is written, in order\" would be the third untrue sentence.\n */\n if (!Number.isFinite(group.rate)) {\n diagnostics.push({\n code: 'TIME_RESOLUTION',\n severity: 'warning',\n message:\n `Channels in ${group.fileName} work out to a sampling rate of ${formatRate(group.rate)} Hz ` +\n `— their samples per record over a record duration too small to divide into — so ` +\n `their samples cannot be placed in time and no rows are written for them.`,\n hint:\n 'Check the record duration in the header. One power of ten larger and the same ' +\n 'file converts, with consecutive rows carrying the same time_s.',\n });\n } else if (step > 0 && step < 10 ** -group.timeDecimals) {\n diagnostics.push({\n code: 'TIME_RESOLUTION',\n severity: 'warning',\n message:\n `Channels at ${formatRate(group.rate)} Hz sample faster than the time column can ` +\n `distinguish, so consecutive rows in ${group.fileName} carry the same time_s value.`,\n /*\n \"or convert one rate at a time with --channels\" was advice that does nothing.\n\n It parses, it runs, it exits 0, and the warning comes back word for word — so\n somebody who followed it had every reason to think the column had been fixed. In\n the wide layout each rate already has its own file and its own precision, and\n `timeDecimals` is a function of the rate alone, so a narrowed conversion writes the\n same column it wrote before. In the long layout the shared column takes the finest\n precision *in the conversion*, and dropping rates can only make it coarser — never\n fine enough to separate samples that were already inseparable.\n\n Nor is there another option that would: --decimals sets the value precision and\n says so, and every rate that reaches this warning has already been given the\n fifteen places that are the ceiling. The first sentence was the whole of the\n answer, so it is the whole of the hint.\n */\n hint:\n 'Every sample is written, in order. Use the row number rather than time_s to tell ' +\n 'them apart: the column already carries the fifteen places a double can hold ' +\n 'exactly, so no option or selection separates them.',\n });\n }\n }\n\n /*\n The same failure as TIME_RESOLUTION, one column over.\n\n A channel whose quantization step is below 1e-98 needs more decimals than `toFixed` can\n print, so consecutive digital codes round to the same text and the arithmetic the FAQ\n gives for recovering them stops working. That used to happen at 1e-20 and silently — see\n MAX_DERIVED_DECIMALS. It is rare now, but \"rare\" is the reason to say so rather than the\n reason not to.\n\n Asked of the ceiling, not of the precision in use, and so asked whatever `--decimals`\n says. `--decimals 2` on a channel needing 3 is a trade the caller made knowingly, and\n reporting it was reporting the flag back at the person who typed it — every channel of an\n ordinary EEG raised this, and since --strict turns any diagnostic into exit 1,\n `--decimals 2 --strict` could not succeed on any recording at all.\n\n 0.5.10 fixed that by skipping the check whenever `--decimals` was given, which suppressed\n the real case along with the false one: at `--decimals 20` a channel stepping by 1e-106\n printed every code it had as `0.00000000000000000000`, and said nothing. The question is\n not who chose the precision. It is whether any precision the tool can print would\n separate consecutive codes.\n */\n for (const group of groups) {\n const short = group.channels.filter((c) => decimalsAreClamped(c.signal));\n if (short.length === 0) continue;\n diagnostics.push({\n code: 'VALUE_RESOLUTION',\n severity: 'warning',\n message:\n `${listed(short.map((c) => c.column))} ${short.length === 1 ? 'steps' : 'step'} by less ` +\n `than any number of decimals this can print, so some consecutive samples round to ` +\n `the same value in ${group.fileName}.`,\n hint:\n 'Every sample is written, in order, and the physical values are computed at full ' +\n 'precision either way. What is lost is only in the printed text.',\n });\n }\n\n /*\n A window that selects nothing is a fact about the plan, so the plan is where it is raised.\n\n It was pushed by `convert()` from the rows actually written, which meant `--info` never\n said it: `--info --start 0.31 --end 0.39` on a 10 Hz recording printed \"Would write 0\n rows\" with no warning and exited 0 under `--strict`, while converting the same window\n warned and exited 1. The hint says \"Run with --info to see where the records actually\n sit\" — advising the reader into the one mode that would not tell them.\n\n The estimate's row count is exact, which `npm run estimate` checks across every fixture\n crossed with every option set, so raising it from the plan says the same thing the rows\n would have.\n */\n /*\n Not when a rate above already explained it. EMPTY_WINDOW says the records \"carry no\n samples in range\", and on a recording whose rate overflowed to Infinity that is untrue\n twice: the records carry their samples, and no range was asked for. The rate warning is\n the accurate account of the same zero.\n */\n const untimeable = groups.some((group) => !Number.isFinite(group.rate));\n if (writeSignals && groups.length > 0 && estimate.rows === 0 && !untimeable) {\n diagnostics.push(emptyWindow(range, input.recordCount));\n }\n\n if (estimate.exceedsSpreadsheetLimit) {\n diagnostics.push({\n code: 'LARGE_OUTPUT',\n severity: 'warning',\n message:\n `At least one output file will have more than ${SPREADSHEET_ROW_LIMIT.toLocaleString('en-US')} ` +\n `rows, which is more than Excel or Numbers can open.`,\n hint: 'Use --start and --duration to convert a section, or read the file with pandas or R.',\n });\n }\n\n return { groups, layout, gzip: options.gzip === true, range, columnNames, writeSignals, diagnostics, estimate };\n}\n\n/**\n * Partition channels by sampling rate, largest first.\n *\n * The common case — every channel at one rate — collapses to a single group and a\n * single `signals.csv`, so the honest behaviour costs nothing when there is nothing\n * to be honest about.\n */\nfunction groupByRate(\n signals: readonly EdfSignal[],\n columnNames: Map<number, string>,\n forcedDecimals: number | undefined,\n gzip: boolean,\n layout: 'wide' | 'long',\n): RateGroup[] {\n const byRate = new Map<number, EdfSignal[]>();\n for (const signal of signals) {\n // A channel with no samples has no sampling rate to group by, and would\n // otherwise produce an empty \"0hz\" file. The header parser already warned.\n if (signal.samplesPerRecord === 0) continue;\n const bucket = byRate.get(signal.samplingRate);\n if (bucket) bucket.push(signal);\n else byRate.set(signal.samplingRate, [signal]);\n }\n\n const rates = [...byRate.keys()].sort((a, b) => b - a);\n // The long layout writes one table whatever the rates are, so every group names it.\n const single = rates.length === 1 || layout === 'long';\n\n /*\n Two distinct rates can produce the same slug, because the slug rounds to six decimal\n places. Rates come from samplesPerRecord / recordDuration and every channel shares the\n record duration, so the closest two rates can be is 1 / recordDuration — which drops\n below 1e-6 once a record is longer than about eleven days. Absurd, but the header\n permits it, and the failure was silent and destructive: both groups opened a write\n stream on the same path, so the file ended up holding interleaved rows from both\n channels under a header naming only one of them.\n\n Distinct rates therefore get distinct files, always. The suffix is only ever reached by\n a collision, so ordinary recordings keep the names they have always had.\n\n Naming from the whole set of rates at once removes most of those collisions before the\n suffix has to. Rounding each rate on its own gave 1e-6 Hz and 1.25e-6 Hz the same slug,\n and the numbering below then produced signals_0_000001hz.csv and signals_0_000001hz_2.csv\n — two files that no longer overwrite each other, but of which only one is named for the\n rate it holds. The suffix stays as the backstop for anything this still cannot separate.\n */\n const suffix = gzip ? '.csv.gz' : '.csv';\n const slugs = formatRates(rates).map(slugFor);\n const used = new Set<string>();\n const uniqueName = (index: number): string => {\n const base = `signals_${slugs[index]}`;\n let name = `${base}${suffix}`;\n for (let n = 2; used.has(name); n++) name = `${base}_${n}${suffix}`;\n used.add(name);\n return name;\n };\n\n return rates.map((rate, index) => {\n const members = byRate.get(rate) ?? [];\n const first = members[0];\n return {\n rate,\n samplesPerRecord: first ? first.samplesPerRecord : 0,\n fileName: single ? `signals${suffix}` : uniqueName(index),\n /*\n In the long layout every rate shares a `time_s` column, so they share its precision:\n the finest any of them needs. Writing 100 Hz at three places and 256 Hz at eight in\n the same column would make the column's meaning depend on the row.\n */\n timeDecimals: layout === 'long' ? Math.max(...rates.map(timeDecimals)) : timeDecimals(rate),\n channels: members.map((signal) => ({\n signal,\n column: columnNames.get(signal.index) ?? `signal_${signal.index}`,\n decimals: forcedDecimals ?? decimalsForSignal(signal),\n })),\n };\n });\n}\n\n/**\n * A file's diagnostics with the header's mixed-rate warning removed.\n *\n * `buildPlan` raises that warning for the channels actually being converted, so keeping both\n * would either duplicate it or contradict it. The header parser's copy stays where it is, for\n * callers reading a header without planning a conversion.\n */\nexport function withoutFileRateWarning(diagnostics: readonly Diagnostic[]): Diagnostic[] {\n return diagnostics.filter((d) => d.code !== 'MIXED_SAMPLING_RATES');\n}\n\n/** `256hz`, `12_5hz` — safe in a filename on every platform. */\nfunction slugFor(rendered: string): string {\n return `${rendered.replace('.', '_')}hz`;\n}\n\n/**\n * One rate's slug, rendered on its own.\n *\n * The names a conversion writes come from `formatRates` over the whole set, which widens the\n * precision until rates that differ read as differing — so on a recording carrying both,\n * 1e-6 Hz and 1.25e-6 Hz are `0_000001hz` and `0_00000125hz`. This renders one rate with no\n * set to separate it from, and both of those come back `0_000001hz`.\n *\n * Which is right for the question it is asked, and was worth saying: a caller reaching for the\n * exported slug function to predict a filename got a name the tool does not write, on exactly\n * the rates the reference warns `formatRate` collapses. The two now spell a rendered rate the\n * same way, through the line above, so only the rendering differs and nothing can drift.\n */\nexport function rateSlug(rate: number): string {\n return slugFor(formatRate(rate));\n}\n\n/**\n * Characters the time column occupies, measured over both ends of the window and signed.\n *\n * Both estimates measured the column against `range.endSeconds` alone, unsigned — while the\n * value column two lines below already allowed for a sign when either bound is negative. A\n * recording timed from before zero prints `-100.000` where that budgeted for `100.000`, so\n * every row came out a byte short: 203 predicted against 216 written, and 131 against 159 on\n * a shorter one. An estimate reading low is the one direction the correctness page says it\n * never goes — \"no byte count under the truth\" is what the estimate sweep asserts over every\n * fixture, and no fixture began before zero.\n *\n * The far end is not always the widest: from -100s to -97s it is the start.\n */\nfunction timeWidthFor(range: ResolvedRange, decimals: number): number {\n return widthOf(\n Math.max(Math.abs(range.startSeconds), Math.abs(range.endSeconds)),\n decimals,\n range.startSeconds < 0 || range.endSeconds < 0,\n );\n}\n\n/**\n * How wide a value cell can print, from the channel's own calibration.\n *\n * Zero when that calibration holds no mapping — a digital range of one point, a physical span\n * that overflows or underflows a double — because such a channel writes an empty cell for\n * every sample rather than a number, which is the whole point of `makeScaler` returning NaN.\n *\n * Budgeting a full-width number for one broke the bound this estimate states beside never\n * reading low. A single-channel recording whose digital minimum equals its maximum, at\n * `--decimals 20`, was predicted at 651 bytes and wrote 151 — 4.31x, against a documented wall\n * of three. No fixture reaches it because `degenerate-range.edf` has two ordinary channels\n * beside its flat one, whose real cells pad the total back under the wall.\n *\n * Asked of `makeScaler` rather than restated here, for the reason `csvRow` measures the header\n * row: the function that decides whether a cell gets a number is the one that can still be\n * right when the rule changes. Both ends of the declared range are probed, so a calibration\n * that is finite anywhere keeps its full width and the estimate cannot start reading low.\n */\nfunction valueWidthOf(channel: PlannedChannel): number {\n const scale = makeScaler(channel.signal);\n const blank =\n !Number.isFinite(scale(channel.signal.digitalMin)) &&\n !Number.isFinite(scale(channel.signal.digitalMax));\n if (blank) return 0;\n return widthOf(\n Math.max(Math.abs(channel.signal.physicalMin), Math.abs(channel.signal.physicalMax)),\n channel.decimals,\n channel.signal.physicalMin < 0 || channel.signal.physicalMax < 0,\n );\n}\n\n/** Integer digits in `Number.MAX_VALUE`, which is the widest a finite double prints. */\nconst MAX_DOUBLE_DIGITS = 309;\n\n/** Characters a fixed-decimal number of this magnitude occupies, sign included. */\nfunction widthOf(magnitude: number, decimals: number, signed = false): number {\n const size = Math.abs(magnitude);\n const sign = signed ? 1 : 0;\n const fraction = decimals > 0 ? 1 + decimals : 0;\n\n /*\n Cells are written with toFixed, which rounds. Taking the integer digits from the floor of\n the bound therefore under-counted whenever rounding carried into a new digit: a channel\n bounded at 9999.999 and written to zero decimals produces \"10000\", five characters where\n the floor of 9999.999 suggests four. Every cell on such a channel was a byte short, and\n `--info` reported 127 KB for a file that came out 131 KB.\n\n Measuring the bound as rendered removes that. toFixed switches to exponential notation\n past 1e21, so the arithmetic form still covers magnitudes beyond it.\n */\n /*\n A bound that is not a number bounds nothing, so the widest cell it can produce is taken\n instead: 309 digits, which is `Number.MAX_VALUE` written out.\n\n One digit was budgeted, and the estimate read low — the one direction the correctness page\n says it never goes. `latest` is `recordCount * recordDuration`, so a header stating a\n record duration near the top of a double overflows it while every sample time under it\n stays finite and prints in full. Three records of 1e308, eight samples:\n\n Would write 8 rows, roughly 115 B. signals.csv is 2,244 bytes.\n\n Each of those rows carries a 313-character time cell. `fixed` writes an empty cell for a\n value that is itself non-finite, so nothing wider than this is ever printed.\n */\n if (!Number.isFinite(size)) return sign + MAX_DOUBLE_DIGITS + fraction;\n if (size < 1e21) return sign + size.toFixed(Math.min(decimals, 100)).length;\n return sign + (Math.floor(Math.log10(size)) + 1) + fraction;\n}\n\n/**\n * Raised when the conversion had signal tables to fill and put no data rows in any of them.\n *\n * A window can land where there are no samples without being past the end of the recording:\n * between the last sample and the nominal end of the last record, or — on a discontinuous\n * file — inside a gap. `--start 2 --end 10` on a recording whose records sit at 0s, 1s and\n * 10s asks for eight seconds that contain no data at all.\n *\n * What came out was a signals.csv holding its header and nothing else, exit 0, no warning,\n * and `--strict` passing. The closing summary does say \"signals.csv 0 rows\" and --json\n * carries `rows: 0`, so it was not quite invisible — but a header-only file is exactly what\n * a successful extraction of an empty range looks like, and everywhere else that a request\n * produces nothing this tool says so: a --channels term matching nothing is an error, and\n * --annotations-only on a file with no events raises NO_ANNOTATIONS. A warning rather than\n * an error because a batch of five hundred recordings should not stop for one whose gap\n * happens to line up with the window; --strict turns it into a failure for those who want\n * that.\n */\nfunction emptyWindow(range: ResolvedRange, recordCount: number): Diagnostic {\n const asked = !range.isWholeRecording;\n return {\n code: 'EMPTY_WINDOW',\n severity: 'warning',\n message: asked\n ? `No samples fall inside the requested window (${fixed(range.startSeconds, 3)}s to ` +\n `${fixed(range.endSeconds, 3)}s), so the signal files hold their headers and no data.`\n : `This recording's ${recordCount} data records carry no samples in range, so the ` +\n `signal files hold their headers and no data.`,\n hint: asked\n ? /*\n Which of the two it was, rather than the second one always.\n\n A recording does not have to start at zero: its first record's timekeeping TAL is\n what it is timed from, so a file whose records begin at 1000s is asked for with\n `--start 1000`. `--start 0 --end 1` on that file was told \"The window is inside the\n recording but lands where there is no data — past the last sample, or inside a gap\n in a discontinuous file\", when the window sits entirely before the recording and\n neither offered explanation applies to it. A start at or past the *end* is already\n an error, so the window being outside can only mean it is before the beginning.\n */\n range.endSeconds <= range.recordingStartSeconds\n ? `This recording starts at ${fixed(range.recordingStartSeconds, 3)}s, so the whole ` +\n 'window sits before it. --start and --end are read on the recording\\'s own clock, ' +\n 'which --info prints as \"Timed from\".'\n : 'The window is inside the recording but lands where there is no data — past the ' +\n 'last sample, or inside a gap in a discontinuous file. Run with --info to see where ' +\n 'the records actually sit.'\n : 'Run with --info to see what the header declares.',\n };\n}\n\nfunction estimateOutput(\n groups: readonly RateGroup[],\n range: ResolvedRange,\n recordDuration: number,\n recordStarts: Float64Array | null | undefined,\n bom: boolean,\n layout: 'wide' | 'long',\n): OutputEstimate {\n let rows = 0;\n let bytes = 0;\n let exceeds = false;\n // One table in the long layout, so the row limit applies to the sum rather than the\n // largest group, and the header and mark are counted once rather than once per group.\n let longRows = 0;\n\n for (const group of groups) {\n let groupRows = 0;\n for (let record = range.startRecord; record < range.endRecord; record++) {\n const recordStart = recordStarts\n ? (recordStarts[record] ?? record * recordDuration)\n : record * recordDuration;\n groupRows += countSamplesInRange({\n recordStart,\n rate: group.rate,\n samplesPerRecord: group.samplesPerRecord,\n startSeconds: range.startSeconds,\n endSeconds: range.endSeconds,\n });\n }\n if (layout === 'long') {\n // A row per sample per channel rather than a row per sample time.\n const groupCells = groupRows * group.channels.length;\n rows += groupCells;\n longRows += groupCells;\n /*\n `time_s,channel,value`: the time, the channel name as it will be escaped into the\n cell, and the widest the value can print. Same over-counting rule as the wide\n layout — the declared physical range bounds a cell, and most samples sit under it.\n */\n const timeWidth = timeWidthFor(range, group.timeDecimals);\n for (const channel of group.channels) {\n const valueWidth = valueWidthOf(channel);\n const nameWidth = Buffer.byteLength(escapeCsvField(channel.column));\n // Two commas and the newline.\n bytes += groupRows * (timeWidth + nameWidth + valueWidth + 3);\n }\n continue;\n }\n\n rows += groupRows;\n if (groupRows + 1 > SPREADSHEET_ROW_LIMIT) exceeds = true;\n\n /*\n Width per cell, from the channel's own calibration rather than a flat allowance.\n\n The old `decimals + 6` budgeted six characters for the sign, integer part and decimal\n point on every channel, whatever it actually held. That over-counted a millivolt\n channel spanning ±5 by four characters a cell and ran 30-55% high across the fixture\n set — on a number people use to decide whether a conversion is worth starting.\n\n The channel's declared physical range is what bounds a cell, so that bound is what is\n used. Most samples sit below it, so this still reads high, which is the direction a\n size estimate should err in.\n\n One case is outside the bound rather than under it: nothing obliges a recording to keep\n its samples inside the digital range it declares, and one that does not maps outside the\n physical range too. Such a file can convert larger than the estimate. Clamping the data\n to make the estimate true is not a trade worth making — the samples are what they are.\n */\n const timeWidth = timeWidthFor(range, group.timeDecimals);\n const cellWidth = group.channels.reduce((sum, c) => sum + valueWidthOf(c), 0);\n // One comma per channel, plus the newline.\n bytes += groupRows * (timeWidth + cellWidth + group.channels.length + 1);\n /*\n The header row, measured as it will be written rather than as the labels are stored.\n\n A column name is quoted when it contains a comma, a quote, a carriage return or a line\n feed, and every quote inside it is doubled. Counting the raw label under-counted\n that row: three channels labelled `a,b,c,d,e`, `x\"y` and `plain` write a 32-byte header\n and were budgeted 27. EDF labels are free text, so commas in them are ordinary — a montage\n written as `EEG Fpz-Cz, ref` is exactly the kind of thing this is for.\n\n csvRow is the function that writes it, so it is the function that measures it. Nothing\n else is in a position to stay correct when the quoting rules change.\n */\n bytes += Buffer.byteLength(csvRow(['time_s', ...group.channels.map((c) => c.column)])) + 1;\n // Three bytes per file under --bom. Small, but exactly known — unlike the sample\n // overshoot two paragraphs up, which is the one thing here that can read under what gets\n // written and cannot be counted in advance. On a one-row conversion three bytes is a\n // tenth of the file.\n if (bom) bytes += BOM_BYTES;\n }\n\n if (layout === 'long' && groups.length > 0) {\n if (longRows + 1 > SPREADSHEET_ROW_LIMIT) exceeds = true;\n bytes += Buffer.byteLength(csvRow(['time_s', 'channel', 'value'])) + 1;\n if (bom) bytes += BOM_BYTES;\n }\n\n return { rows, bytes, exceedsSpreadsheetLimit: exceeds };\n}\n"]}
|
|
1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,CAAC;QAC3C,IAAI,QAAQ,GAAG,CAAC,GAAG,qBAAqB;YAAE,OAAO,GAAG,IAAI,CAAC;QACzD,KAAK,IAAI,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACvE,IAAI,GAAG;YAAE,KAAK,IAAI,SAAS,CAAC;IAC9B,CAAC;IAED,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,uBAAuB,EAAE,OAAO,EAAE,CAAC;AAC3D,CAAC","sourcesContent":["/**\n * Turning a request into a concrete conversion plan.\n *\n * The plan is where the tool's central promise is enforced: channels recorded at\n * different sampling rates are never merged into one table. A single wide CSV can\n * only hold mixed rates by inventing samples for the slow channels — MNE, for\n * instance, expands three genuine 1 Hz temperature readings into 768 interpolated\n * values without warning. Instead each distinct rate gets its own file, so every\n * number in every output file is a number that was actually recorded.\n */\n\nimport type { Diagnostic } from '../edf/errors.js';\nimport type { EdfSignal } from '../edf/header.js';\nimport { formatRate, formatRates } from '../edf/header.js';\nimport { decimalsAreClamped, decimalsForSignal, makeScaler } from '../edf/scale.js';\nimport { UTF8_BOM, csvRow, escapeCsvField } from '../format/csv.js';\nimport { counted, listed } from '../format/list.js';\nimport { fixed, timeDecimals } from '../format/number.js';\nimport { TIME_COLUMN, buildColumnNames, renamedByCollision, selectChannels } from './channels.js';\nimport { assertOptions } from './options.js';\nimport { countSamplesInRange, resolveRange } from './time-range.js';\nimport type { ResolvedRange } from './time-range.js';\n\nexport interface PlannedChannel {\n signal: EdfSignal;\n column: string;\n decimals: number;\n}\n\nexport interface RateGroup {\n /** Sampling rate in Hz shared by every channel in this group. */\n rate: number;\n samplesPerRecord: number;\n fileName: string;\n timeDecimals: number;\n channels: PlannedChannel[];\n}\n\nexport interface PlanInput {\n signals: readonly EdfSignal[];\n recordDuration: number;\n recordCount: number;\n hasAnnotationChannel: boolean;\n /**\n * True start time of each data record, supplied for discontinuous files. The\n * requested time window is resolved against these rather than against\n * `recordCount * recordDuration`, which for a file with gaps is the amount of\n * data rather than the span of time it covers.\n */\n recordStarts?: Float64Array | null | undefined;\n}\n\nexport interface PlanOptions {\n channels?: readonly string[] | undefined;\n start?: number | undefined;\n /** The `--start` value exactly as typed, for error messages. */\n startText?: string | undefined;\n duration?: number | undefined;\n end?: number | undefined;\n /** The `--end` value exactly as typed, for error messages. */\n endText?: string | undefined;\n annotationsOnly?: boolean | undefined;\n /** Force a fixed number of decimals instead of deriving it per channel. */\n decimals?: number | undefined;\n /** Compress each CSV with gzip, giving every one of them a `.gz` name. */\n gzip?: boolean | undefined;\n /** Start each CSV with a UTF-8 byte order mark, so Excel reads it as UTF-8. */\n bom?: boolean | undefined;\n /**\n * How the samples are arranged in the CSV.\n *\n * `'wide'`, the default, gives one column per channel and one file per sampling rate.\n * `'long'` gives one file, three columns — `time_s`, `channel`, `value` — and one row per\n * sample. See ConversionPlan.layout for why that is the only way to put channels recorded\n * at different rates in one table without inventing samples.\n */\n layout?: 'wide' | 'long' | undefined;\n}\n\nexport interface ConversionPlan {\n groups: RateGroup[];\n /**\n * How the samples are arranged. `'wide'` is a column per channel and a file per rate;\n * `'long'` is `time_s,channel,value`, one row per sample, all rates in one file.\n *\n * The wide layout has to split a mixed-rate recording across files: a 100 Hz channel and\n * a 1 Hz channel share no rows, and putting them in one wide table means either 99 empty\n * cells out of every hundred or inventing the samples that would fill them. In the long\n * layout each sample carries its own time, so nothing has to line up and nothing is\n * invented — which also makes it the one layout `--stdout` can stream for such a file.\n */\n layout: 'wide' | 'long';\n\n /**\n * Whether the CSVs will be compressed.\n *\n * Recorded rather than inferred from the group file names. Under `--annotations-only`\n * there are no groups to read it off, and `--info` named `annotations.csv` for a run that\n * wrote `annotations.csv.gz`.\n */\n gzip: boolean;\n range: ResolvedRange;\n columnNames: Map<number, string>;\n writeSignals: boolean;\n diagnostics: Diagnostic[];\n estimate: OutputEstimate;\n}\n\nexport interface OutputEstimate {\n /** Total data rows across every signal file. */\n rows: number;\n /**\n * Approximate size of the signal CSVs as CSV text, which under `gzip` is not their size on\n * disk: what is counted here is what the compressor is handed, and the file holds what it\n * produces. `--info` writes \"before compression\" beside this number for that reason, and\n * `infoJson` calls it a character count.\n */\n bytes: number;\n /** True when any single file would exceed Excel's row limit. */\n exceedsSpreadsheetLimit: boolean;\n}\n\nconst BOM_BYTES = Buffer.byteLength(UTF8_BOM);\n\n/** Excel and most spreadsheet tools stop at 1,048,576 rows including the header. */\nexport const SPREADSHEET_ROW_LIMIT = 1_048_576;\n\nexport function buildPlan(input: PlanInput, options: PlanOptions = {}): ConversionPlan {\n // First, and before a directory is created or a stream opened, so a rejected option\n // leaves nothing behind. See assertOptions for what used to get through.\n assertOptions(options);\n\n const diagnostics: Diagnostic[] = [];\n const columnNames = buildColumnNames(input.signals);\n\n // A channel whose own label was taken by something else in the header. Usually that is\n // another channel's disambiguating suffix — the duplicate-label warning is about the labels\n // that collided, this is about the channel that lost its name to them. The other way is a\n // channel labelled `time_s`, where what took the name is the time column itself, which every\n // signals.csv begins with and no file supplies.\n /*\n \"so its column is\" was a sentence about the wide layout, printed in both.\n\n A long signals.csv has three columns — time_s, channel, value — and none of them is a\n label: a channel appears there as a value in the `channel` column. So a `--layout long`\n run was told that a column had been renamed to avoid colliding with a column neither of\n them has, under a hint promising that \"column names are unique\" about a set of three\n fixed strings the file never got from the header.\n\n The rename is right in both layouts, which is why only the noun moves. The names have to\n agree between the `channel` cells and channels.csv and across runs, and the `pivot` the\n documentation gives for turning a long table back into a wide one would otherwise put a\n `time_s` column against a `time_s` index — the collision one step later.\n */\n const inLongLayout = (options.layout ?? 'wide') === 'long';\n for (const signal of renamedByCollision(input.signals, columnNames)) {\n const taker =\n signal.label === TIME_COLUMN\n ? 'the name of the time column every signals.csv starts with'\n : `also the column name another channel's \"_ch\" suffix produces`;\n diagnostics.push({\n code: 'DUPLICATE_LABEL',\n severity: 'warning',\n message:\n `Signal ${signal.index} is labelled \"${signal.label}\", which is ${taker}, ` +\n `so ${inLongLayout ? 'it is named' : 'its column is'} \"${columnNames.get(signal.index)}\"` +\n `${inLongLayout ? ' in the channel column' : ''}.`,\n hint: inLongLayout\n ? 'Channel names are unique; look this channel up in channels.csv by its signal_index.'\n : 'Column names are unique; look this channel up in channels.csv by its signal_index.',\n });\n }\n\n const range = resolveRange({\n start: options.start,\n startText: options.startText,\n duration: options.duration,\n end: options.end,\n endText: options.endText,\n recordDuration: input.recordDuration,\n recordCount: input.recordCount,\n recordStarts: input.recordStarts,\n });\n\n const writeSignals = options.annotationsOnly !== true;\n\n let chosen: EdfSignal[] = input.signals.filter((s) => !s.isAnnotations);\n\n /*\n Channel names are checked even under --annotations-only, where the selection is not\n otherwise used.\n\n Skipping the check meant `--channels TYPO --annotations-only` exited 0 in silence while\n the same typo without the flag was a usage error, and `--channels \"\"` stayed an error\n in both — so a mistyped name was the one form of bad input the tool accepted quietly.\n Everywhere else a term matching nothing is reported rather than ignored; a flag that\n happens not to apply is a poor reason to make an exception.\n */\n if (options.channels && options.channels.length > 0) {\n const selection = selectChannels(input.signals, options.channels);\n if (writeSignals) chosen = selection.signals;\n for (const { term, matched } of selection.ambiguous) {\n diagnostics.push({\n code: 'DUPLICATE_LABEL',\n severity: 'warning',\n message:\n `\"${term}\" matches ${matched.length} channels (positions ` +\n `${listed(matched.map((s) => `#${s.index}`))}); all of them were selected.`,\n hint: `Use --channels \"#${matched[0]?.index ?? 0}\" to pick just one.`,\n });\n }\n }\n\n const layout = options.layout ?? 'wide';\n const groups = writeSignals\n ? groupByRate(chosen, columnNames, options.decimals, options.gzip === true, layout)\n : [];\n const estimate = estimateOutput(\n groups,\n range,\n input.recordDuration,\n input.recordStarts,\n options.bom === true,\n layout,\n );\n\n /*\n The mixed-rate warning describes what this conversion does, not what the file holds.\n\n The header parser raises its own, which is right for `parseHeader` — but it sees every\n channel and knows nothing about `--channels`. Converting one channel out of a three-rate\n recording therefore announced \"3 different sampling rates ... written to one file per\n rate\" over a run that wrote one file, in the same output where `--info` had already\n marked the other two \"(not selected)\". Selecting two of the three was wrong the other\n way: still \"3\".\n\n Callers combining these with a file's own diagnostics drop that copy in favour of this\n one; see `withoutFileRateWarning`.\n */\n if (groups.length > 1) {\n diagnostics.push({\n code: 'MIXED_SAMPLING_RATES',\n severity: 'warning',\n message:\n `Channels use ${groups.length} different sampling rates ` +\n `(${listed(formatRates(groups.map((g) => g.rate)).map((r) => `${r} Hz`))}).`,\n hint:\n layout === 'long'\n ? 'They share one table, each row carrying its own time, so no channel is resampled.'\n : 'They are written to one file per rate so no channel is resampled.',\n });\n }\n\n /*\n A time column that cannot tell two samples apart.\n\n Sample times are written to at most fifteen decimal places, which separates everything a\n terminating rate can reach — every power of two through 32768 Hz and far past it. Below\n that interval the column repeats: at 3e15 Hz, whose reciprocal never terminates, the rows\n of one record carry the same time_s, so joining or plotting on it silently collapses\n samples that are genuinely distinct. Nothing is lost from the file — every sample is\n there, in order — but the column stops being an identifier, and that is worth saying\n rather than leaving to be discovered.\n\n This said nine places and a gigahertz, and illustrated it with 1 ns records — all three of\n which stopped being true when 0.4.55 raised the search bound. Fifteen places resolve\n 1e-15 s, so a nanosecond interval is written exactly and that recording raises nothing at\n all. warnings-and-errors.md was corrected then and carries a note saying so; the comment\n it was written from was not, and the hint printed four lines below here has said \"the\n fifteen places a double can hold exactly\" ever since.\n */\n for (const group of groups) {\n const step = group.rate > 0 ? 1 / group.rate : 0;\n /*\n The limit of the same failure, which read as the absence of it.\n\n `samplesPerRecord / recordDuration` is a double, and a record duration of 1e-308 with\n four samples in it is Infinity. `1 / Infinity` is 0, so `step > 0` was false and this\n said nothing — while every sample was dropped, the run exited 0, and the only warning\n printed was EMPTY_WINDOW's \"This recording's 2 data records carry no samples in range\",\n which is untrue twice over: the records carry eight samples and no range was asked for.\n\n One power of ten away, at 1e-300, the rate is 4e300 and the file converts with the\n warning below. Same guard `decimalsAreClamped` had before 0.5.83, in the column next\n door: a step of exactly zero means no resolution at all, not nothing to report.\n\n Its own branch because the hint below is false here — no rows are written at all, so\n \"Every sample is written, in order\" would be the third untrue sentence.\n */\n if (!Number.isFinite(group.rate)) {\n diagnostics.push({\n code: 'TIME_RESOLUTION',\n severity: 'warning',\n message:\n `Channels in ${group.fileName} work out to a sampling rate of ${formatRate(group.rate)} Hz ` +\n `— their samples per record over a record duration too small to divide into — so ` +\n `their samples cannot be placed in time and no rows are written for them.`,\n hint:\n 'Check the record duration in the header. One power of ten larger and the same ' +\n 'file converts, with consecutive rows carrying the same time_s.',\n });\n } else if (step > 0 && step < 10 ** -group.timeDecimals) {\n diagnostics.push({\n code: 'TIME_RESOLUTION',\n severity: 'warning',\n message:\n `Channels at ${formatRate(group.rate)} Hz sample faster than the time column can ` +\n `distinguish, so consecutive rows in ${group.fileName} carry the same time_s value.`,\n /*\n \"or convert one rate at a time with --channels\" was advice that does nothing.\n\n It parses, it runs, it exits 0, and the warning comes back word for word — so\n somebody who followed it had every reason to think the column had been fixed. In\n the wide layout each rate already has its own file and its own precision, and\n `timeDecimals` is a function of the rate alone, so a narrowed conversion writes the\n same column it wrote before. In the long layout the shared column takes the finest\n precision *in the conversion*, and dropping rates can only make it coarser — never\n fine enough to separate samples that were already inseparable.\n\n Nor is there another option that would: --decimals sets the value precision and\n says so, and every rate that reaches this warning has already been given the\n fifteen places that are the ceiling. The first sentence was the whole of the\n answer, so it is the whole of the hint.\n */\n hint:\n 'Every sample is written, in order. Use the row number rather than time_s to tell ' +\n 'them apart: the column already carries the fifteen places a double can hold ' +\n 'exactly, so no option or selection separates them.',\n });\n }\n }\n\n /*\n The same failure as TIME_RESOLUTION, one column over.\n\n A channel whose quantization step is below 1e-98 needs more decimals than `toFixed` can\n print, so consecutive digital codes round to the same text and the arithmetic the FAQ\n gives for recovering them stops working. That used to happen at 1e-20 and silently — see\n MAX_DERIVED_DECIMALS. It is rare now, but \"rare\" is the reason to say so rather than the\n reason not to.\n\n Asked of the ceiling, not of the precision in use, and so asked whatever `--decimals`\n says. `--decimals 2` on a channel needing 3 is a trade the caller made knowingly, and\n reporting it was reporting the flag back at the person who typed it — every channel of an\n ordinary EEG raised this, and since --strict turns any diagnostic into exit 1,\n `--decimals 2 --strict` could not succeed on any recording at all.\n\n 0.5.10 fixed that by skipping the check whenever `--decimals` was given, which suppressed\n the real case along with the false one: at `--decimals 20` a channel stepping by 1e-106\n printed every code it had as `0.00000000000000000000`, and said nothing. The question is\n not who chose the precision. It is whether any precision the tool can print would\n separate consecutive codes.\n */\n for (const group of groups) {\n const short = group.channels.filter((c) => decimalsAreClamped(c.signal));\n if (short.length === 0) continue;\n diagnostics.push({\n code: 'VALUE_RESOLUTION',\n severity: 'warning',\n message:\n `${listed(short.map((c) => c.column))} ${short.length === 1 ? 'steps' : 'step'} by less ` +\n `than any number of decimals this can print, so some consecutive samples round to ` +\n `the same value in ${group.fileName}.`,\n hint:\n 'Every sample is written, in order, and the physical values are computed at full ' +\n 'precision either way. What is lost is only in the printed text.',\n });\n }\n\n /*\n A window that selects nothing is a fact about the plan, so the plan is where it is raised.\n\n It was pushed by `convert()` from the rows actually written, which meant `--info` never\n said it: `--info --start 0.31 --end 0.39` on a 10 Hz recording printed \"Would write 0\n rows\" with no warning and exited 0 under `--strict`, while converting the same window\n warned and exited 1. The hint says \"Run with --info to see where the records actually\n sit\" — advising the reader into the one mode that would not tell them.\n\n The estimate's row count is exact, which `npm run estimate` checks across every fixture\n crossed with every option set, so raising it from the plan says the same thing the rows\n would have.\n */\n /*\n Not when a rate above already explained it. EMPTY_WINDOW says the records \"carry no\n samples in range\", and on a recording whose rate overflowed to Infinity that is untrue\n twice: the records carry their samples, and no range was asked for. The rate warning is\n the accurate account of the same zero.\n */\n const untimeable = groups.some((group) => !Number.isFinite(group.rate));\n if (writeSignals && groups.length > 0 && estimate.rows === 0 && !untimeable) {\n diagnostics.push(emptyWindow(range, input.recordCount, groups.length));\n }\n\n if (estimate.exceedsSpreadsheetLimit) {\n diagnostics.push({\n code: 'LARGE_OUTPUT',\n severity: 'warning',\n message:\n `At least one output file will have more than ${SPREADSHEET_ROW_LIMIT.toLocaleString('en-US')} ` +\n `rows, which is more than Excel or Numbers can open.`,\n hint: 'Use --start and --duration to convert a section, or read the file with pandas or R.',\n });\n }\n\n return { groups, layout, gzip: options.gzip === true, range, columnNames, writeSignals, diagnostics, estimate };\n}\n\n/**\n * Partition channels by sampling rate, largest first.\n *\n * The common case — every channel at one rate — collapses to a single group and a\n * single `signals.csv`, so the honest behaviour costs nothing when there is nothing\n * to be honest about.\n */\nfunction groupByRate(\n signals: readonly EdfSignal[],\n columnNames: Map<number, string>,\n forcedDecimals: number | undefined,\n gzip: boolean,\n layout: 'wide' | 'long',\n): RateGroup[] {\n const byRate = new Map<number, EdfSignal[]>();\n for (const signal of signals) {\n // A channel with no samples has no sampling rate to group by, and would\n // otherwise produce an empty \"0hz\" file. The header parser already warned.\n if (signal.samplesPerRecord === 0) continue;\n const bucket = byRate.get(signal.samplingRate);\n if (bucket) bucket.push(signal);\n else byRate.set(signal.samplingRate, [signal]);\n }\n\n const rates = [...byRate.keys()].sort((a, b) => b - a);\n // The long layout writes one table whatever the rates are, so every group names it.\n const single = rates.length === 1 || layout === 'long';\n\n /*\n Two distinct rates can produce the same slug, because the slug rounds to six decimal\n places. Rates come from samplesPerRecord / recordDuration and every channel shares the\n record duration, so the closest two rates can be is 1 / recordDuration — which drops\n below 1e-6 once a record is longer than about eleven days. Absurd, but the header\n permits it, and the failure was silent and destructive: both groups opened a write\n stream on the same path, so the file ended up holding interleaved rows from both\n channels under a header naming only one of them.\n\n Distinct rates therefore get distinct files, always. The suffix is only ever reached by\n a collision, so ordinary recordings keep the names they have always had.\n\n Naming from the whole set of rates at once removes most of those collisions before the\n suffix has to. Rounding each rate on its own gave 1e-6 Hz and 1.25e-6 Hz the same slug,\n and the numbering below then produced signals_0_000001hz.csv and signals_0_000001hz_2.csv\n — two files that no longer overwrite each other, but of which only one is named for the\n rate it holds. The suffix stays as the backstop for anything this still cannot separate.\n */\n const suffix = gzip ? '.csv.gz' : '.csv';\n const slugs = formatRates(rates).map(slugFor);\n const used = new Set<string>();\n const uniqueName = (index: number): string => {\n const base = `signals_${slugs[index]}`;\n let name = `${base}${suffix}`;\n for (let n = 2; used.has(name); n++) name = `${base}_${n}${suffix}`;\n used.add(name);\n return name;\n };\n\n return rates.map((rate, index) => {\n const members = byRate.get(rate) ?? [];\n const first = members[0];\n return {\n rate,\n samplesPerRecord: first ? first.samplesPerRecord : 0,\n fileName: single ? `signals${suffix}` : uniqueName(index),\n /*\n In the long layout every rate shares a `time_s` column, so they share its precision:\n the finest any of them needs. Writing 100 Hz at three places and 256 Hz at eight in\n the same column would make the column's meaning depend on the row.\n */\n timeDecimals: layout === 'long' ? Math.max(...rates.map(timeDecimals)) : timeDecimals(rate),\n channels: members.map((signal) => ({\n signal,\n column: columnNames.get(signal.index) ?? `signal_${signal.index}`,\n decimals: forcedDecimals ?? decimalsForSignal(signal),\n })),\n };\n });\n}\n\n/**\n * A file's diagnostics with the header's mixed-rate warning removed.\n *\n * `buildPlan` raises that warning for the channels actually being converted, so keeping both\n * would either duplicate it or contradict it. The header parser's copy stays where it is, for\n * callers reading a header without planning a conversion.\n */\nexport function withoutFileRateWarning(diagnostics: readonly Diagnostic[]): Diagnostic[] {\n return diagnostics.filter((d) => d.code !== 'MIXED_SAMPLING_RATES');\n}\n\n/** `256hz`, `12_5hz` — safe in a filename on every platform. */\nfunction slugFor(rendered: string): string {\n return `${rendered.replace('.', '_')}hz`;\n}\n\n/**\n * One rate's slug, rendered on its own.\n *\n * The names a conversion writes come from `formatRates` over the whole set, which widens the\n * precision until rates that differ read as differing — so on a recording carrying both,\n * 1e-6 Hz and 1.25e-6 Hz are `0_000001hz` and `0_00000125hz`. This renders one rate with no\n * set to separate it from, and both of those come back `0_000001hz`.\n *\n * Which is right for the question it is asked, and was worth saying: a caller reaching for the\n * exported slug function to predict a filename got a name the tool does not write, on exactly\n * the rates the reference warns `formatRate` collapses. The two now spell a rendered rate the\n * same way, through the line above, so only the rendering differs and nothing can drift.\n */\nexport function rateSlug(rate: number): string {\n return slugFor(formatRate(rate));\n}\n\n/**\n * Characters the time column occupies, measured over both ends of the window and signed.\n *\n * Both estimates measured the column against `range.endSeconds` alone, unsigned — while the\n * value column two lines below already allowed for a sign when either bound is negative. A\n * recording timed from before zero prints `-100.000` where that budgeted for `100.000`, so\n * every row came out a byte short: 203 predicted against 216 written, and 131 against 159 on\n * a shorter one. An estimate reading low is the one direction the correctness page says it\n * never goes — \"no byte count under the truth\" is what the estimate sweep asserts over every\n * fixture, and no fixture began before zero.\n *\n * The far end is not always the widest: from -100s to -97s it is the start.\n */\nfunction timeWidthFor(range: ResolvedRange, decimals: number): number {\n return widthOf(\n Math.max(Math.abs(range.startSeconds), Math.abs(range.endSeconds)),\n decimals,\n range.startSeconds < 0 || range.endSeconds < 0,\n );\n}\n\n/**\n * How wide a value cell can print, from the channel's own calibration.\n *\n * Zero when that calibration holds no mapping — a digital range of one point, a physical span\n * that overflows or underflows a double — because such a channel writes an empty cell for\n * every sample rather than a number, which is the whole point of `makeScaler` returning NaN.\n *\n * Budgeting a full-width number for one broke the bound this estimate states beside never\n * reading low. A single-channel recording whose digital minimum equals its maximum, at\n * `--decimals 20`, was predicted at 651 bytes and wrote 151 — 4.31x, against a documented wall\n * of three. No fixture reaches it because `degenerate-range.edf` has two ordinary channels\n * beside its flat one, whose real cells pad the total back under the wall.\n *\n * Asked of `makeScaler` rather than restated here, for the reason `csvRow` measures the header\n * row: the function that decides whether a cell gets a number is the one that can still be\n * right when the rule changes. Both ends of the declared range are probed, so a calibration\n * that is finite anywhere keeps its full width and the estimate cannot start reading low.\n */\nfunction valueWidthOf(channel: PlannedChannel): number {\n const scale = makeScaler(channel.signal);\n const blank =\n !Number.isFinite(scale(channel.signal.digitalMin)) &&\n !Number.isFinite(scale(channel.signal.digitalMax));\n if (blank) return 0;\n return widthOf(\n Math.max(Math.abs(channel.signal.physicalMin), Math.abs(channel.signal.physicalMax)),\n channel.decimals,\n channel.signal.physicalMin < 0 || channel.signal.physicalMax < 0,\n );\n}\n\n/** Integer digits in `Number.MAX_VALUE`, which is the widest a finite double prints. */\nconst MAX_DOUBLE_DIGITS = 309;\n\n/** Characters a fixed-decimal number of this magnitude occupies, sign included. */\nfunction widthOf(magnitude: number, decimals: number, signed = false): number {\n const size = Math.abs(magnitude);\n const sign = signed ? 1 : 0;\n const fraction = decimals > 0 ? 1 + decimals : 0;\n\n /*\n Cells are written with toFixed, which rounds. Taking the integer digits from the floor of\n the bound therefore under-counted whenever rounding carried into a new digit: a channel\n bounded at 9999.999 and written to zero decimals produces \"10000\", five characters where\n the floor of 9999.999 suggests four. Every cell on such a channel was a byte short, and\n `--info` reported 127 KB for a file that came out 131 KB.\n\n Measuring the bound as rendered removes that. toFixed switches to exponential notation\n past 1e21, so the arithmetic form still covers magnitudes beyond it.\n */\n /*\n A bound that is not a number bounds nothing, so the widest cell it can produce is taken\n instead: 309 digits, which is `Number.MAX_VALUE` written out.\n\n One digit was budgeted, and the estimate read low — the one direction the correctness page\n says it never goes. `latest` is `recordCount * recordDuration`, so a header stating a\n record duration near the top of a double overflows it while every sample time under it\n stays finite and prints in full. Three records of 1e308, eight samples:\n\n Would write 8 rows, roughly 115 B. signals.csv is 2,244 bytes.\n\n Each of those rows carries a 313-character time cell. `fixed` writes an empty cell for a\n value that is itself non-finite, so nothing wider than this is ever printed.\n */\n if (!Number.isFinite(size)) return sign + MAX_DOUBLE_DIGITS + fraction;\n if (size < 1e21) return sign + size.toFixed(Math.min(decimals, 100)).length;\n return sign + (Math.floor(Math.log10(size)) + 1) + fraction;\n}\n\n/**\n * Raised when the conversion had signal tables to fill and put no data rows in any of them.\n *\n * A window can land where there are no samples without being past the end of the recording:\n * between the last sample and the nominal end of the last record, or — on a discontinuous\n * file — inside a gap. `--start 2 --end 10` on a recording whose records sit at 0s, 1s and\n * 10s asks for eight seconds that contain no data at all.\n *\n * What came out was a signals.csv holding its header and nothing else, exit 0, no warning,\n * and `--strict` passing. The closing summary does say \"signals.csv 0 rows\" and --json\n * carries `rows: 0`, so it was not quite invisible — but a header-only file is exactly what\n * a successful extraction of an empty range looks like, and everywhere else that a request\n * produces nothing this tool says so: a --channels term matching nothing is an error, and\n * --annotations-only on a file with no events raises NO_ANNOTATIONS. A warning rather than\n * an error because a batch of five hundred recordings should not stop for one whose gap\n * happens to line up with the window; --strict turns it into a failure for those who want\n * that.\n */\nfunction emptyWindow(range: ResolvedRange, recordCount: number, fileCount: number): Diagnostic {\n const asked = !range.isWholeRecording;\n /*\n One rate is one file, which is nearly every recording, and this said \"files\" either way:\n \"so the signal files hold their headers and no data\" over a single signals.csv. The count\n is `plan.groups.length` and the caller has had it all along — it is the same number the\n mixed-rate warning three functions up counts to decide whether to fire at all.\n */\n const tables =\n fileCount === 1\n ? 'the signal file holds its header and no data'\n : 'the signal files hold their headers and no data';\n return {\n code: 'EMPTY_WINDOW',\n severity: 'warning',\n message: asked\n ? `No samples fall inside the requested window (${fixed(range.startSeconds, 3)}s to ` +\n `${fixed(range.endSeconds, 3)}s), so ${tables}.`\n : `This recording's ${counted(recordCount, 'data record')} carry no samples in range, ` +\n `so ${tables}.`,\n hint: asked\n ? /*\n Which of the two it was, rather than the second one always.\n\n A recording does not have to start at zero: its first record's timekeeping TAL is\n what it is timed from, so a file whose records begin at 1000s is asked for with\n `--start 1000`. `--start 0 --end 1` on that file was told \"The window is inside the\n recording but lands where there is no data — past the last sample, or inside a gap\n in a discontinuous file\", when the window sits entirely before the recording and\n neither offered explanation applies to it. A start at or past the *end* is already\n an error, so the window being outside can only mean it is before the beginning.\n */\n range.endSeconds <= range.recordingStartSeconds\n ? `This recording starts at ${fixed(range.recordingStartSeconds, 3)}s, so the whole ` +\n 'window sits before it. --start and --end are read on the recording\\'s own clock, ' +\n 'which --info prints as \"Timed from\".'\n : 'The window is inside the recording but lands where there is no data — past the ' +\n 'last sample, or inside a gap in a discontinuous file. Run with --info to see where ' +\n 'the records actually sit.'\n : 'Run with --info to see what the header declares.',\n };\n}\n\nfunction estimateOutput(\n groups: readonly RateGroup[],\n range: ResolvedRange,\n recordDuration: number,\n recordStarts: Float64Array | null | undefined,\n bom: boolean,\n layout: 'wide' | 'long',\n): OutputEstimate {\n let rows = 0;\n let bytes = 0;\n let exceeds = false;\n // One table in the long layout, so the row limit applies to the sum rather than the\n // largest group, and the header and mark are counted once rather than once per group.\n let longRows = 0;\n\n for (const group of groups) {\n let groupRows = 0;\n for (let record = range.startRecord; record < range.endRecord; record++) {\n const recordStart = recordStarts\n ? (recordStarts[record] ?? record * recordDuration)\n : record * recordDuration;\n groupRows += countSamplesInRange({\n recordStart,\n rate: group.rate,\n samplesPerRecord: group.samplesPerRecord,\n startSeconds: range.startSeconds,\n endSeconds: range.endSeconds,\n });\n }\n if (layout === 'long') {\n // A row per sample per channel rather than a row per sample time.\n const groupCells = groupRows * group.channels.length;\n rows += groupCells;\n longRows += groupCells;\n /*\n `time_s,channel,value`: the time, the channel name as it will be escaped into the\n cell, and the widest the value can print. Same over-counting rule as the wide\n layout — the declared physical range bounds a cell, and most samples sit under it.\n */\n const timeWidth = timeWidthFor(range, group.timeDecimals);\n for (const channel of group.channels) {\n const valueWidth = valueWidthOf(channel);\n const nameWidth = Buffer.byteLength(escapeCsvField(channel.column));\n // Two commas and the newline.\n bytes += groupRows * (timeWidth + nameWidth + valueWidth + 3);\n }\n continue;\n }\n\n rows += groupRows;\n if (groupRows + 1 > SPREADSHEET_ROW_LIMIT) exceeds = true;\n\n /*\n Width per cell, from the channel's own calibration rather than a flat allowance.\n\n The old `decimals + 6` budgeted six characters for the sign, integer part and decimal\n point on every channel, whatever it actually held. That over-counted a millivolt\n channel spanning ±5 by four characters a cell and ran 30-55% high across the fixture\n set — on a number people use to decide whether a conversion is worth starting.\n\n The channel's declared physical range is what bounds a cell, so that bound is what is\n used. Most samples sit below it, so this still reads high, which is the direction a\n size estimate should err in.\n\n One case is outside the bound rather than under it: nothing obliges a recording to keep\n its samples inside the digital range it declares, and one that does not maps outside the\n physical range too. Such a file can convert larger than the estimate. Clamping the data\n to make the estimate true is not a trade worth making — the samples are what they are.\n */\n const timeWidth = timeWidthFor(range, group.timeDecimals);\n const cellWidth = group.channels.reduce((sum, c) => sum + valueWidthOf(c), 0);\n // One comma per channel, plus the newline.\n bytes += groupRows * (timeWidth + cellWidth + group.channels.length + 1);\n /*\n The header row, measured as it will be written rather than as the labels are stored.\n\n A column name is quoted when it contains a comma, a quote, a carriage return or a line\n feed, and every quote inside it is doubled. Counting the raw label under-counted\n that row: three channels labelled `a,b,c,d,e`, `x\"y` and `plain` write a 32-byte header\n and were budgeted 27. EDF labels are free text, so commas in them are ordinary — a montage\n written as `EEG Fpz-Cz, ref` is exactly the kind of thing this is for.\n\n csvRow is the function that writes it, so it is the function that measures it. Nothing\n else is in a position to stay correct when the quoting rules change.\n */\n bytes += Buffer.byteLength(csvRow(['time_s', ...group.channels.map((c) => c.column)])) + 1;\n // Three bytes per file under --bom. Small, but exactly known — unlike the sample\n // overshoot two paragraphs up, which is the one thing here that can read under what gets\n // written and cannot be counted in advance. On a one-row conversion three bytes is a\n // tenth of the file.\n if (bom) bytes += BOM_BYTES;\n }\n\n if (layout === 'long' && groups.length > 0) {\n if (longRows + 1 > SPREADSHEET_ROW_LIMIT) exceeds = true;\n bytes += Buffer.byteLength(csvRow(['time_s', 'channel', 'value'])) + 1;\n if (bom) bytes += BOM_BYTES;\n }\n\n return { rows, bytes, exceedsSpreadsheetLimit: exceeds };\n}\n"]}
|
package/dist/edf/header.js
CHANGED
|
@@ -69,7 +69,12 @@ function startsFormula(text) {
|
|
|
69
69
|
return true;
|
|
70
70
|
if (!/^[+-]./u.test(text))
|
|
71
71
|
return false;
|
|
72
|
-
|
|
72
|
+
// `\.\d*` and not `\.\d+`, which is the spelling DECIMAL_FIELD and DECIMAL_DURATION both
|
|
73
|
+
// use for the same question. A trailing point is a number with nothing after it — Excel
|
|
74
|
+
// opens `+1.` as 1 — and one character of difference between three copies of one grammar
|
|
75
|
+
// had this warning firing on a field the paragraph above exempts by name, and failing
|
|
76
|
+
// --strict for it.
|
|
77
|
+
return !/^[+-](?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/u.test(text);
|
|
73
78
|
}
|
|
74
79
|
/**
|
|
75
80
|
* A byte the terminal treats as an instruction rather than as text.
|
package/dist/edf/header.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"header.js","sourceRoot":"","sources":["../../src/edf/header.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAC5C,iFAAiF;AACjF,sFAAsF;AACtF,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE1C,gEAAgE;AAChE,MAAM,CAAC,MAAM,iBAAiB,GAAG,iBAAiB,CAAC;AACnD,uDAAuD;AACvD,MAAM,CAAC,MAAM,qBAAqB,GAAG,iBAAiB,CAAC;AAEvD,MAAM,CAAC,MAAM,kBAAkB,GAAG,GAAG,CAAC;AACtC,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,CAAC;AA2EvC;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,SAAS,aAAa,CAAC,IAAY;IACjC,IAAI,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IACrC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;QAAE,OAAO,KAAK,CAAC;IACxC,OAAO,CAAC,iDAAiD,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACvE,CAAC;AAED;;;;;;GAMG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,GAAG,CAAC;AACxF,CAAC;AAED,qEAAqE;AACrE,MAAM,UAAU,UAAU,CAAC,EAAU;IACnC,IAAI,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC,EAAE,CAAC;QACzB;;;;;;;;;;UAUE;QACF,MAAM,IAAI,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;QACxB,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACzE,CAAC;IACD,MAAM,OAAO,GAAG,MAAM,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IACtC,qFAAqF;IACrF,sFAAsF;IACtF,sFAAsF;IACtF,8EAA8E;IAC9E,IAAI,OAAO,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;IAC9C,OAAO,MAAM,CAAC,OAAO,CAAC,CAAC;AACzB,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,WAAW,CAAC,KAAwB;IAClD,MAAM,OAAO,GAAG,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IACtC,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC;IACrC,OAAO,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC;AACtF,CAAC","sourcesContent":["/**\n * EDF / EDF+ header parsing.\n *\n * Layout (all fields are ASCII, left-justified, space-padded):\n *\n * fixed header, 256 bytes\n * 0 8 version ('0', or 255 + 'BIOSEMI' for BDF)\n * 8 80 patient identification\n * 88 80 recording identification\n * 168 8 start date dd.mm.yy\n * 176 8 start time hh.mm.ss\n * 184 8 number of bytes in the header record\n * 192 44 reserved ('EDF+C' / 'EDF+D' live here)\n * 236 8 number of data records (-1 if unknown)\n * 244 8 duration of a data record, in seconds (may be fractional)\n * 252 4 number of signals (ns)\n *\n * signal header, ns * 256 bytes, stored FIELD-major rather than signal-major:\n * all ns labels, then all ns transducer types, and so on.\n * ns * 16 label\n * ns * 80 transducer type\n * ns * 8 physical dimension\n * ns * 8 physical minimum\n * ns * 8 physical maximum\n * ns * 8 digital minimum\n * ns * 8 digital maximum\n * ns * 80 prefiltering\n * ns * 8 number of samples in each data record\n * ns * 32 reserved\n */\n\nimport { EdfError } from './errors.js';\nimport type { Diagnostic } from './errors.js';\nimport { counted, listed } from '../format/list.js';\nimport { plain } from '../format/number.js';\n// The shell-quoting rule for a label, shared rather than repeated: this hint and\n// `--channels`' own \"did you mean\" have to print the same command for the same label.\nimport { typeable } from '../convert/channels.js';\nimport { decodeLatin1 } from './bytes.js';\n\n/** Label the EDF+ spec reserves for the annotations channel. */\nexport const ANNOTATIONS_LABEL = 'EDF Annotations';\n/** BDF+ uses its own spelling for the same channel. */\nexport const BDF_ANNOTATIONS_LABEL = 'BDF Annotations';\n\nexport const FIXED_HEADER_BYTES = 256;\nexport const SIGNAL_HEADER_BYTES = 256;\n\nexport interface EdfSignal {\n /** Position in the file, 0-based. Stable even when labels collide. */\n index: number;\n label: string;\n transducer: string;\n physicalDimension: string;\n physicalMin: number;\n physicalMax: number;\n digitalMin: number;\n digitalMax: number;\n prefiltering: string;\n samplesPerRecord: number;\n reserved: string;\n /** True for the EDF+ 'EDF Annotations' channel, which carries text, not signal. */\n isAnnotations: boolean;\n /** samplesPerRecord / recordDuration, in Hz. */\n samplingRate: number;\n /** Byte offset of this signal's samples within one data record. */\n byteOffsetInRecord: number;\n}\n\nexport interface EdfHeader {\n version: string;\n patientId: string;\n recordingId: string;\n /** Raw 'dd.mm.yy' as written in the file. */\n startDateRaw: string;\n /** Raw 'hh.mm.ss' as written in the file. */\n startTimeRaw: string;\n /** Resolved start instant, or null when the file's date/time fields are unusable. */\n startDateTime: Date | null;\n /**\n * Header size in bytes, computed from the signal count rather than read from the field.\n *\n * Every data record offset is derived from this, so it has to be the one the layout\n * actually uses: 256 for the fixed header plus 256 per signal. A writer that fills the\n * field in carelessly is common enough to have its own warning, HEADER_BYTES_MISMATCH,\n * and trusting the field over the arithmetic would put every sample at the wrong offset.\n */\n headerBytes: number;\n /**\n * What the header's own length field says, which need not be the above.\n *\n * Exposed for the same reason `declaredRecordCount` is: the two disagreeing is a fact\n * about the file, and a caller checking how a recording was written should be able to see\n * what it claimed rather than only what was believed.\n */\n declaredHeaderBytes: number;\n reserved: string;\n isEdfPlus: boolean;\n /** True for BioSemi BDF/BDF+ files, whose samples are 3 bytes rather than 2. */\n isBdf: boolean;\n /** 'EDF+C' continuous, 'EDF+D' discontinuous, or null for plain EDF. */\n continuity: 'EDF+C' | 'EDF+D' | null;\n /** As declared in the header. -1 means \"unknown\", which the spec permits. */\n declaredRecordCount: number;\n recordDuration: number;\n signalCount: number;\n signals: EdfSignal[];\n bytesPerSample: number;\n recordBytes: number;\n}\n\n/** Everything derived by combining the header with the file's real size. */\nexport interface EdfHeaderInfo {\n header: EdfHeader;\n /** Record count implied by the actual file size — the one we trust for reading. */\n recordCount: number;\n /** Bytes after the last complete data record. */\n trailingBytes: number;\n diagnostics: Diagnostic[];\n}\n\n/**\n * Whether a spreadsheet reads this field as the start of a formula rather than as text.\n *\n * `=` and `@` unconditionally; every list of these characters names two more, and this had\n * `-` as an exception with the reason written out on the warnings page: \"a lone `-` is a\n * real convention for no unit ... and neither is evaluated unless what follows it parses as a\n * formula\". Which is the condition, and it was not being applied — nothing with a leading\n * minus was flagged at all. A channel labelled `-2+3` opens as a column headed `1`, and\n * `-HYPERLINK(\"http://...\",\"EEG\")` is a name the spreadsheet resolves, in silence.\n *\n * So the exception is what it says it is rather than the whole character. A lone `-` is left\n * as text by every spreadsheet and is not flagged; a field that is entirely a number reads as\n * that number, which is what the header says, and is not flagged either. Anything else after\n * the minus is arithmetic or a name.\n *\n * And `+` takes the same exception, which it did not. It is the same rule in the spreadsheet —\n * Lotus compatibility, which converts a leading `+` or `-` to a formula when what follows one\n * parses as a formula and leaves it as text when it does not — so the two signs cannot differ\n * here for a reason that comes from the sign. A channel labelled `+100` was warned about as\n * something a spreadsheet \"reads as the start of a formula rather than as text\", over a cell\n * that opens as 100, which is what the header says; `-100` beside it said nothing, and under\n * `--strict` the difference was an exit code. `+1+1` is still arithmetic and still flagged.\n */\nfunction startsFormula(text: string): boolean {\n if (/^[=@]/u.test(text)) return true;\n if (!/^[+-]./u.test(text)) return false;\n return !/^[+-](?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[eE][+-]?\\d+)?$/u.test(text);\n}\n\n/**\n * A byte the terminal treats as an instruction rather than as text.\n *\n * C0 and C1, plus DEL. Tab is included deliberately: it is harmless to a terminal but it\n * makes a CSV column name that cannot be typed or matched reliably, which is the other half\n * of what this warning is for.\n */\nfunction isControlCharacter(character: string): boolean {\n const code = character.codePointAt(0) as number;\n return code <= 0x1f || (code >= 0x7f && code <= 0x9f);\n}\n\nconst dec = (buf: Uint8Array, start: number, len: number): string =>\n decodeLatin1(buf, start, start + len);\n\n/** EDF fields are space-padded; trailing NULs also occur in files written by sloppy tools. */\nconst trimField = (s: string): string => s.replace(/[\\0\\s]+$/u, '').replace(/^\\s+/u, '');\n\n/**\n * How many signals the fixed header says there are, read exactly as `parseHeader` will.\n *\n * `EdfFile.open` needs this before it can know how much header to read, and it used to work\n * it out with its own `Number(...)` — which was NUL-tolerant but not comma-tolerant, unlike\n * every other numeric field here. A header written with a comma decimal separator, which\n * COMMA_DECIMAL exists to accept and which the documentation lists this field among, was\n * therefore never given its signal headers at all, and the file died on a message that\n * contradicted itself: \"needs a 768-byte header, but the file is only 848 bytes\".\n *\n * Sharing the parse is what keeps the two from disagreeing again about which files are\n * readable. Null means \"not a usable count\", and the caller reads no further header — the\n * real error then comes from `parseHeader`, which is the one place that decides.\n */\nexport function peekSignalCount(fixed: Uint8Array): number | null {\n const text = normaliseNumberField(dec(fixed, 252, 4)).text;\n if (!DECIMAL_FIELD.test(text)) return null;\n const count = Number(text);\n return Number.isInteger(count) && count > 0 ? count : null;\n}\n\n/**\n * What EDF allows a numeric field to look like, which is less than `Number()` allows.\n *\n * A sign, digits, an optional fractional part, an optional exponent — the spec's own grammar,\n * plus the exponent form the 8-character physical bounds need to reach a magnetometer's range\n * and which real headers use.\n *\n * `Number()` accepts a great deal more, and every one of those forms is a header this tool\n * would have read as a number nobody wrote. A physical maximum of `0x64` came out as 100: it\n * printed as `-100 to 100` in the channel table, went into channels.csv as `physical_max,100`,\n * and set the gain every sample on that channel was scaled by — a whole calibration invented\n * from four bytes that are not a decimal number, exit 0, no diagnostic. `0b1100100` and `0o144`\n * are the same hundred, and `0x02` in the signal-count field is a two-channel recording.\n *\n * The same mistake as `#0x2` reaching channel 2 through `--channels`, `--decimals 0o5` writing\n * five places and `--jobs 0x10` running sixteen, all of which have their own comments and their\n * own fixes. Those were values somebody typed. These are the fields every number in the output\n * is computed from, and the page describing them says \"all fields are ASCII\" and gives the\n * layout digit by digit.\n */\nconst DECIMAL_FIELD = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?$/u;\n\n/** A numeric header field, trimmed and with a comma decimal separator turned into a dot. */\nfunction normaliseNumberField(raw: string): { text: string; sawComma: boolean } {\n const text = trimField(raw);\n // Some writers emit a comma decimal separator despite the spec requiring '.'.\n if (text.includes(',') && !text.includes('.')) {\n return { text: text.replace(',', '.'), sawComma: true };\n }\n return { text, sawComma: false };\n}\n\nfunction parseNumberField(\n raw: string,\n field: string,\n { integer = false, sawComma }: { integer?: boolean; sawComma?: { value: boolean } } = {},\n): number {\n const normalised = normaliseNumberField(raw);\n const text = normalised.text;\n if (normalised.sawComma && sawComma) sawComma.value = true;\n if (text === '') {\n throw new EdfError('BAD_HEADER_FIELD', `Header field \"${field}\" is empty.`);\n }\n const n = DECIMAL_FIELD.test(text) ? Number(text) : NaN;\n if (!Number.isFinite(n)) {\n throw new EdfError(\n 'BAD_HEADER_FIELD',\n `Header field \"${field}\" is not a number (found ${JSON.stringify(text)}).`,\n 'The file may be truncated, byte-shifted, or not an EDF file at all.',\n );\n }\n if (integer && !Number.isInteger(n)) {\n throw new EdfError(\n 'BAD_HEADER_FIELD',\n `Header field \"${field}\" must be a whole number (found ${JSON.stringify(text)}).`,\n );\n }\n return n;\n}\n\n/** Whether the start time names the sixtieth second. See LEAP_SECOND_START. */\nfunction namesLeapSecond(timeRaw: string): boolean {\n const t = /^(\\d{2})[.:\\-](\\d{2})[.:\\-](\\d{2})$/u.exec(trimField(timeRaw));\n return t !== null && Number(t[3]) === 60;\n}\n\nconst MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];\n\n/**\n * The date an EDF+ recording ID states, which is the only place the file writes a full year.\n *\n * EDF+ requires the recording identification field to begin `Startdate dd-MMM-yyyy`, and\n * requires it to agree with the header's own date field. It is a four-digit year, so it says\n * something the eight-character date field physically cannot.\n */\nfunction recordingIdStartdate(\n recordingId: string,\n): { day: number; month: number; year: number } | null {\n const stated = /^Startdate\\s+(\\d{2})-([A-Za-z]{3})-(\\d{4})(?:\\s|$)/u.exec(recordingId.trim());\n if (!stated) return null;\n const month = MONTHS.indexOf((stated[2] as string).toUpperCase()) + 1;\n if (month === 0) return null;\n return { day: Number(stated[1]), month, year: Number(stated[3]) };\n}\n\n/**\n * EDF stores a two-digit year. The spec pins the century: 85-99 mean 1985-1999\n * and 00-84 mean 2000-2084. Files outside 1985-2084 cannot express their date.\n *\n * Which is why EDF+ writes it again in full, in the recording identification field, and why\n * that is used here when it is there. The rule alone reports a recording made in 1984 as 2084\n * and one made in 2085 as 1985 — a hundred years out, on a file that states the year plainly\n * four fields earlier. Taken only where the two agree about everything the header can express:\n * the same day, the same month, and a four-digit year ending in the two digits the header\n * wrote. A recording ID that contradicts the header is a different problem and is left to the\n * spec's rule, which is at least the one the format defines.\n */\nfunction resolveStartDateTime(\n dateRaw: string,\n timeRaw: string,\n recordingId = '',\n): Date | null {\n const d = /^(\\d{2})[.\\-/](\\d{2})[.\\-/](\\d{2})$/u.exec(trimField(dateRaw));\n const t = /^(\\d{2})[.:\\-](\\d{2})[.:\\-](\\d{2})$/u.exec(trimField(timeRaw));\n if (!d || !t) return null;\n\n const dd = Number(d[1]);\n const mm = Number(d[2]);\n const yy = Number(d[3]);\n const hh = Number(t[1]);\n const mi = Number(t[2]);\n const ss = Number(t[3]);\n\n if (mm < 1 || mm > 12 || dd < 1 || dd > 31 || hh > 23 || mi > 59 || ss > 60) return null;\n\n const stated = recordingIdStartdate(recordingId);\n const year =\n stated !== null && stated.day === dd && stated.month === mm && stated.year % 100 === yy\n ? stated.year\n : yy >= 85\n ? 1900 + yy\n : 2000 + yy;\n const date = new Date(Date.UTC(year, mm - 1, dd, hh, mi, Math.min(ss, 59)));\n // Reject dates that rolled over, e.g. 31.02.\n if (date.getUTCMonth() !== mm - 1 || date.getUTCDate() !== dd) return null;\n return date;\n}\n\n/**\n * Parse the fixed 256-byte header plus the per-signal header block.\n *\n * @param buf At least FIXED_HEADER_BYTES + ns * SIGNAL_HEADER_BYTES bytes.\n * @param fileSize Total size of the file on disk, used to derive the real record count.\n */\nexport function parseHeader(buf: Uint8Array, fileSize: number): EdfHeaderInfo {\n const diagnostics: Diagnostic[] = [];\n const sawComma = { value: false };\n\n if (buf.length < FIXED_HEADER_BYTES) {\n throw new EdfError(\n 'FILE_TOO_SMALL',\n `File is ${counted(fileSize, 'byte')}; an EDF header alone needs at least ${FIXED_HEADER_BYTES}.`,\n );\n }\n\n // BDF (BioSemi) marks itself with byte 255 followed by 'BIOSEMI', and stores\n // 3-byte samples instead of 2. Everything else about the layout is identical.\n const isBdf = buf[0] === 0xff && dec(buf, 1, 7) === 'BIOSEMI';\n const version = isBdf ? 'BIOSEMI' : trimField(dec(buf, 0, 8));\n\n const patientId = trimField(dec(buf, 8, 80));\n const recordingId = trimField(dec(buf, 88, 80));\n const startDateRaw = trimField(dec(buf, 168, 8));\n const startTimeRaw = trimField(dec(buf, 176, 8));\n const headerBytes = parseNumberField(dec(buf, 184, 8), 'number of header bytes', {\n integer: true,\n sawComma,\n });\n const reserved = trimField(dec(buf, 192, 44));\n const declaredRecordCount = parseNumberField(dec(buf, 236, 8), 'number of data records', {\n integer: true,\n sawComma,\n });\n const recordDuration = parseNumberField(dec(buf, 244, 8), 'duration of a data record', {\n sawComma,\n });\n const signalCount = parseNumberField(dec(buf, 252, 4), 'number of signals', {\n integer: true,\n sawComma,\n });\n\n if (signalCount <= 0) {\n throw new EdfError(\n 'INVALID_SIGNAL_COUNT',\n `Header declares ${signalCount} signals; expected at least 1.`,\n );\n }\n if (!(recordDuration > 0)) {\n throw new EdfError(\n 'INVALID_RECORD_DURATION',\n `Header declares a data record duration of ${plain(recordDuration)}s; expected a positive number.`,\n );\n }\n\n const expectedHeaderBytes = FIXED_HEADER_BYTES + signalCount * SIGNAL_HEADER_BYTES;\n if (buf.length < expectedHeaderBytes) {\n throw new EdfError(\n 'FILE_TOO_SMALL',\n /*\n Which of the two is actually short.\n\n The file size was quoted either way, so a caller that had read too little — the\n signal count parsed one way here and another way there — produced arithmetic that\n refuted itself: \"needs a 768-byte header, but the file is only 848 bytes\". A reader\n following that looks for a truncation that is not there.\n */\n `File declares ${counted(signalCount, 'signal')}, which needs a ${expectedHeaderBytes}-byte header, ` +\n (fileSize < expectedHeaderBytes\n ? `but the file is only ${fileSize} bytes.`\n : `but only ${buf.length} bytes of it were handed to the parser.`),\n );\n }\n if (headerBytes !== expectedHeaderBytes) {\n diagnostics.push({\n code: 'HEADER_BYTES_MISMATCH',\n severity: 'warning',\n message:\n `Header says it is ${headerBytes} bytes, but ${counted(signalCount, 'signal')} ` +\n `${signalCount === 1 ? 'requires' : 'require'} ${expectedHeaderBytes} bytes. ` +\n `Using the value computed from the signal count.`,\n });\n }\n\n // Signal headers are field-major: all labels, then all transducers, and so on.\n const base = FIXED_HEADER_BYTES;\n const readField = (offsetUnits: number, width: number, i: number): string =>\n dec(buf, base + offsetUnits * signalCount + i * width, width);\n\n // EDF+ writes 'EDF+C'/'EDF+D' here; BDF+ writes 'BDF+C'/'BDF+D'. The two mean the\n // same thing, so both are normalised to a single continuity marker.\n const continuityTag = /^(?:EDF|BDF)\\+([CD])/u.exec(reserved);\n const continuity: 'EDF+C' | 'EDF+D' | null =\n continuityTag === null ? null : continuityTag[1] === 'D' ? 'EDF+D' : 'EDF+C';\n\n const signals: EdfSignal[] = [];\n let byteOffsetInRecord = 0;\n const bytesPerSample = isBdf ? 3 : 2;\n const seenLabels = new Map<string, number[]>();\n const emptyLabels: number[] = [];\n\n for (let i = 0; i < signalCount; i++) {\n const label = trimField(readField(0, 16, i));\n const transducer = trimField(readField(16, 80, i));\n const physicalDimension = trimField(readField(96, 8, i));\n const physicalMin = parseNumberField(readField(104, 8, i), `physical minimum (signal ${i})`, {\n sawComma,\n });\n const physicalMax = parseNumberField(readField(112, 8, i), `physical maximum (signal ${i})`, {\n sawComma,\n });\n const digitalMin = parseNumberField(readField(120, 8, i), `digital minimum (signal ${i})`, {\n integer: true,\n sawComma,\n });\n const digitalMax = parseNumberField(readField(128, 8, i), `digital maximum (signal ${i})`, {\n integer: true,\n sawComma,\n });\n const prefiltering = trimField(readField(136, 80, i));\n const samplesPerRecord = parseNumberField(\n readField(216, 8, i),\n `samples per record (signal ${i})`,\n { integer: true, sawComma },\n );\n const sigReserved = trimField(readField(224, 32, i));\n\n if (samplesPerRecord < 0) {\n throw new EdfError(\n 'BAD_HEADER_FIELD',\n `Signal ${i} (\"${label}\") declares ${samplesPerRecord} samples per record.`,\n );\n }\n\n const isAnnotations = label === ANNOTATIONS_LABEL || label === BDF_ANNOTATIONS_LABEL;\n\n signals.push({\n index: i,\n label,\n transducer,\n physicalDimension,\n physicalMin,\n physicalMax,\n digitalMin,\n digitalMax,\n prefiltering,\n samplesPerRecord,\n reserved: sigReserved,\n isAnnotations,\n samplingRate: samplesPerRecord / recordDuration,\n byteOffsetInRecord,\n });\n byteOffsetInRecord += samplesPerRecord * bytesPerSample;\n\n if (!isAnnotations) {\n /*\n A label is free text out of the file, and it becomes a column name in signals.csv.\n\n `--info` has escaped control bytes since it was written, because an ANSI escape in a\n header can drive the reader's terminal — `\\x1b[2J` clears the screen. The CSV had no\n such protection and needed none for correctness: quoting makes any byte safe for a\n parser, and this still passes the label through exactly as the file gives it, because\n losing what the header says is not an improvement.\n\n What was missing is the sentence saying so. A recording whose channel is labelled\n `\\x1b[2Jgone` converted with no warning at all, and `cat signals.csv` then cleared\n the terminal — while a script referencing that column by name carried an invisible\n control character in it. NONPRINTABLE_LABEL has been declared and documented as\n reserved since 0.1; this is it doing its job.\n */\n /*\n Which of the two fields carries them, because the consequences are not the same.\n\n The message said \"label or unit\", and then said the bytes \"will appear in the CSV\n column name\" and that \"the name cannot be typed\" — both of which are about the label.\n A channel labelled plainly `ECG` in a unit of `u\\x07V` got all of it: its column is\n `ECG`, `--channels ECG` selects it and exits 0, and the byte is in channels.csv's\n `unit` cell, which the warning never mentioned. Three sentences, none of them true of\n the file that raised it, on a warning whose whole purpose is to say where an invisible\n byte went.\n */\n /*\n All four free-text fields, not the two that were checked.\n\n `transducer` and `prefiltering` are free text out of the header exactly as the label\n and the unit are, and they land in channels.csv exactly as the unit does — so an ESC\n byte in a transducer field reached the CSV raw with nothing said, and `cat\n channels.csv` would drive the terminal. That is the hazard this warning exists for,\n two columns over. 0.5.71 made it name which field carries them; this is the rest of\n the fields it can name.\n */\n const fields = [\n ['label', label],\n ['unit', physicalDimension],\n ['transducer', transducer],\n ['prefiltering', prefiltering],\n ] as const;\n const affected = fields.filter(([, text]) => [...text].some(isControlCharacter));\n const control = affected.flatMap(([, text]) => [...text].filter(isControlCharacter));\n if (control.length > 0) {\n const shown = [...new Set(control)]\n .map((c) => `\\\\x${(c.codePointAt(0) as number).toString(16).padStart(2, '0')}`)\n .join(', ');\n const plural = control.length === 1 ? '' : 's';\n const inLabel = affected.some(([name]) => name === 'label');\n // \"label and unit\", not \"label, unit\" — `listed` is for long enumerations that get\n // truncated, and this is a sentence with at most four items in it.\n const names = affected.map(([name]) => name);\n const named =\n names.length === 1\n ? (names[0] as string)\n : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1] as string}`;\n // Where they land, which is the question the reader has. A label becomes a column\n // name in signals.csv; the other three are cells of channels.csv and nothing else.\n // Named down to the cell when there is one of them, because that is the answer to\n // \"where did it go\" — `channels.csv` alone leaves a reader scanning fourteen columns.\n const cells = affected.filter(([name]) => name !== 'label').map(([name]) => name);\n const where =\n cells.length === 1 ? `channels.csv's ${cells[0] as string} cell` : 'channels.csv';\n const lands =\n inLabel && cells.length > 0\n ? `which will appear in the CSV column name and in ${where}`\n : inLabel\n ? 'which will appear in the CSV column name'\n : `which will appear in ${where}`;\n diagnostics.push({\n code: 'NONPRINTABLE_LABEL',\n severity: 'warning',\n message:\n `Signal ${i}'s ${named} ${affected.length === 1 ? 'contains' : 'contain'} ` +\n `${control.length} control character${plural} (${shown}), ${lands} exactly as the ` +\n `header has ${control.length === 1 ? 'it' : 'them'}.`,\n hint:\n /*\n Every branch has to print a command that works.\n\n The middle one quoted the label back, which is right until the label is empty:\n an unlabelled channel got `--channels \"\"`, and that exits 2 with \"--channels was\n given but lists no channel names\". A hint whose command fails is worse than no\n hint, and this warning's whole job is to say how to reach a channel whose header\n text you cannot type. `EMPTY_LABEL` already says the position is the only way in\n for such a channel; so does this now.\n\n A comma is the third way. `--channels` separates names with one, and splits on\n every occurrence, so a channel labelled `EEG Fpz-Cz, ref` cannot be selected by\n name at all: the quoted-back advice printed `--channels \"EEG Fpz-Cz, ref\"`, which\n exits 2 with `No channel named \"EEG Fpz-Cz\"` — a channel the file does not have,\n named after half of one it does. Commas in labels are ordinary, since EDF labels\n are free text, and the CSV header quotes them; only this one hint claimed\n something about them that isn't so.\n */\n /*\n And a fourth way, which this branch printed straight past.\n\n A shell expands `$`, a backtick and a backslash inside double quotes, so a\n channel labelled `EEG $ref` was answered with `--channels \"EEG $ref\"` — which\n arrives as `EEG ` and exits 2 on a channel the file does not have. A backtick\n opens a command substitution and the pasted line does not even finish. That is\n the failure 0.7.18 fixed for `--channels`' own suggestion, and `typeable` is the\n rule it fixed it with: double quotes where they survive, single quotes where\n they do not, null where nothing does. Asking it settles which branch this takes\n as well, so the two cannot disagree about one label again.\n */\n (typeable(label) === null\n ? `Address the channel by position with --channels \"#${i}\" rather than by name, ` +\n `since ${\n inLabel\n ? 'the name cannot be typed'\n : label === ''\n ? 'it has no label'\n : 'a comma in the label would read as two names'\n }. `\n : `The column name is unaffected, so --channels ${typeable(label) as string} still selects it. `) +\n 'Printing the CSV to a terminal may do more than print it.',\n });\n }\n\n /*\n Header text a spreadsheet will run rather than read.\n\n The same four free-text fields, asked a different question. `=`, `+` and `@` start a\n formula in Excel, LibreOffice and Sheets no matter which file the cell came from, and\n these fields land in a CSV header row and in channels.csv verbatim — so a channel\n labelled `=1+1` opens as a column headed 2, and `=HYPERLINK(...)` opens as a link\n nobody in the reading chain wrote. SECURITY.md already calls these fields\n attacker-controlled because they reach filenames; this is where they reach a program\n that executes text.\n\n Not `-`, which the same advice usually includes. A lone `-` is a real convention for\n \"no unit\" and appears in the fixtures, a leading `-` on a montage label is ordinary,\n and neither is executed unless what follows parses as a formula — so warning on it\n would fire on files that are fine, which is how a warning gets ignored.\n\n Said, not fixed. Prefixing the cell with a quote is the usual mitigation and would mean\n writing something the header does not say, which is the one thing this tool refuses to\n do; NONPRINTABLE_LABEL answers control bytes the same way.\n */\n const formulaic = fields.filter(([, text]) => startsFormula(text));\n if (formulaic.length > 0) {\n const names = formulaic.map(([name]) => name);\n const named =\n names.length === 1\n ? (names[0] as string)\n : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1] as string}`;\n const shown = [...new Set(formulaic.map(([, text]) => text[0] as string))].join(', ');\n diagnostics.push({\n code: 'FORMULA_LABEL',\n severity: 'warning',\n message:\n `Signal ${i}'s ${named} ${formulaic.length === 1 ? 'starts' : 'start'} with ` +\n `${shown}, which Excel, LibreOffice and Google Sheets read as the start of a ` +\n `formula rather than as text.`,\n hint:\n 'The text is written exactly as the header has it, so the cell is what the ' +\n 'recording says. Open the CSV with pandas or R, or import it into the ' +\n 'spreadsheet as text, if you do not want it evaluated.',\n });\n }\n\n if (label === '') {\n // Collected, not reported here: what this channel's column ends up called depends on\n // whether some later channel is literally labelled `signal_<i>`, and inside this loop\n // the later channels do not exist yet. See the pass below.\n emptyLabels.push(i);\n } else {\n // Collected rather than reported here: a label repeated five times should\n // produce one warning naming all five, not four near-identical pairs.\n const seen = seenLabels.get(label);\n if (seen) seen.push(i);\n else seenLabels.set(label, [i]);\n }\n\n if (samplesPerRecord === 0) {\n diagnostics.push({\n code: 'NO_SAMPLES',\n severity: 'warning',\n message: `Signal ${i} (\"${label}\") carries no samples at all (0 per data record).`,\n hint: 'It is described in channels.csv but left out of the converted data.',\n });\n }\n\n /*\n Too large to represent, and too small — the second was silent.\n\n The gain is the span divided by the digital range, and a span of 2e-320 over 65,535\n codes is 3e-325: below the smallest subnormal double, so it underflows to +0. The\n scaler's flat-range branch then handed every code the same physical value, and a\n channel of 65,536 distinct readings became one repeated number with nothing raised at\n all. One power of ten away, at 1e-319, the same file raises VALUE_RESOLUTION.\n\n Both are the same fact about the header — the span cannot be turned into a mapping —\n so both get this code, and both leave the cells empty rather than filling them with a\n value the header cannot justify.\n */\n const span = physicalMax - physicalMin;\n const underflowed = span !== 0 && span / (digitalMax - digitalMin) === 0;\n if (!Number.isFinite(span) || underflowed) {\n diagnostics.push({\n code: 'UNUSABLE_PHYSICAL_RANGE',\n severity: 'warning',\n message:\n `Signal ${i} (\"${label}\") declares a physical range from ${physicalMin} to ` +\n `${physicalMax}, whose span is too ${underflowed ? 'small' : 'large'} to ` +\n `represent, so its values cannot be scaled.`,\n hint: 'Its cells are left empty rather than filled with a value the header cannot justify.',\n });\n } else if (digitalMax === digitalMin) {\n diagnostics.push({\n code: 'DEGENERATE_DIGITAL_RANGE',\n severity: 'warning',\n message:\n `Signal ${i} (\"${label}\") has digital minimum equal to digital maximum ` +\n `(${digitalMin}), so its values cannot be scaled.`,\n hint: 'Its cells are left empty rather than filled with a value the header cannot justify.',\n });\n } else if (physicalMax === physicalMin) {\n diagnostics.push({\n code: 'DEGENERATE_PHYSICAL_RANGE',\n severity: 'warning',\n message:\n `Signal ${i} (\"${label}\") has physical minimum equal to physical maximum ` +\n `(${physicalMin}), so every sample converts to the same value.`,\n });\n } else if ((physicalMax - physicalMin) * (digitalMax - digitalMin) < 0) {\n /*\n Polarity is inverted when the gain is negative, and the gain is\n (physicalMax - physicalMin) / (digitalMax - digitalMin) — so it is the sign of the\n two spans together that matters, not the physical pair alone.\n\n Testing only `physicalMax < physicalMin` was wrong in both directions. A file with\n its DIGITAL bounds reversed is just as inverted and drew no warning at all, handing\n back sign-flipped EEG with nothing to indicate it. A file with BOTH pairs reversed\n has a positive gain and is not inverted, yet was warned about — a message that was\n simply untrue of that recording.\n */\n const reversed =\n physicalMax < physicalMin\n ? `physical minimum ${physicalMin} above physical maximum ${physicalMax}`\n : `digital minimum ${digitalMin} above digital maximum ${digitalMax}`;\n diagnostics.push({\n code: 'INVERTED_PHYSICAL_RANGE',\n severity: 'warning',\n message: `Signal ${i} (\"${label}\") declares ${reversed}, which inverts its polarity.`,\n hint: 'The values are converted exactly as the header specifies, inversion included.',\n });\n }\n }\n }\n\n /*\n What an unlabelled channel is actually called, which the message used to guess.\n\n A channel with no label takes `signal_<index>` — unless another channel is literally\n labelled that, which EDF permits, since labels are free text and nothing enforces anything\n about them. Then both collide and both are suffixed. The warning said \"It will appear as\n \"signal_0\"\" while the file's header read `time_s,signal_0_ch0,signal_0_ch1`: the one\n sentence the run printed named a column that exists in neither signals.csv nor\n channels.csv.\n\n The other half was silent. The channel that genuinely carries the label `signal_0` lost\n its own column name to a collision with a synthesised one, and nothing said so —\n DUPLICATE_LABEL did not fire, because the two labels are not the same label. Both halves\n are one sentence here, because they are one event.\n\n No specific suffixed name is quoted. The suffix rule has a second pass for names that are\n still shared afterwards, and a message that hard-coded `_ch<index>` would be guessing again\n in exactly the way this is fixing.\n */\n for (const index of emptyLabels) {\n const taken = seenLabels.get(`signal_${index}`);\n diagnostics.push({\n code: 'EMPTY_LABEL',\n severity: 'warning',\n message:\n taken === undefined\n ? `Signal ${index} has no label. It will appear as \"signal_${index}\".`\n : `Signal ${index} has no label, so it takes the name \"signal_${index}\" — which ` +\n `${taken.length === 1 ? 'signal' : 'signals'} ${listed(taken.map(String))} already ` +\n `${taken.length === 1 ? 'carries' : 'carry'} as a label, so both columns are ` +\n `suffixed with their position instead.`,\n });\n }\n\n /*\n A timestamp that is not one.\n\n EDF gives the start date and time eight characters each, and nothing stops a writer\n putting `32.13.99` and `25.61.61` there. `--info` has always echoed the raw fields with\n \"(unparseable)\" beside them, but nothing was raised: the conversion exited 0, `--strict`\n passed, and metadata.json recorded `start_datetime_local: null` with no note against it.\n\n Every other unusable header field reports itself — a degenerate digital range, a physical\n span that cannot be represented, a comma decimal separator, a header whose declared size\n disagrees with its signal count. This was the one that did not, and it is the field\n output-files points at for turning `time_s` into an absolute instant.\n */\n /*\n The sixtieth second, which is a second UTC has and a calendar date does not.\n\n `resolveStartDateTime` admits `ss === 60` on purpose — a recorder synchronised to UTC\n through a leap second writes `23.59.60`, and refusing it would throw away a date that is\n otherwise perfectly good over one second. What it then does is `Math.min(ss, 59)`, because\n `Date.UTC(..., 60)` rolls over into the next minute and would move the instant the other\n way, by fifty-nine seconds more.\n\n Keeping the nearest instant is the right answer. Keeping it in silence was not: `--info`\n printed `Recorded 2020-01-01 23:59:59` and metadata.json recorded the same, for a header\n that says `23.59.60`, with `--strict` exiting 0. Every other header field this tool cannot\n represent exactly says so — a comma decimal separator, a physical span that overflows, a\n record count that disagrees with the file — and this is the field `time_s` is documented as\n being added to.\n */\n if (\n namesLeapSecond(startTimeRaw) &&\n resolveStartDateTime(startDateRaw, startTimeRaw, recordingId) !== null\n ) {\n diagnostics.push({\n code: 'LEAP_SECOND_START',\n severity: 'warning',\n message:\n `The header's start time (\"${startTimeRaw}\") names the sixtieth second of a minute, ` +\n `which no calendar date has.`,\n hint:\n 'It is recorded as the fifty-ninth second, one second earlier, since that is the ' +\n 'nearest instant a date can hold. time_s is unaffected — it counts from the start of ' +\n 'the recording either way.',\n });\n }\n\n /*\n Two dates in one header, disagreeing.\n\n EDF+ requires the recording identification field's `Startdate` to be the header's start\n date. Where it is, its four digits settle the century — see resolveStartDateTime. Where it\n is not, one of the two is wrong and there is no way to tell which, so the date field is\n used, being the one the format defines. That was done in silence, on a header that plainly\n contradicts itself:\n\n Recorded 2002-03-02 22:15:00\n Recording Startdate 05-MAR-2002 PSG-1234/2002 NN Telemetry03\n\n The same shape as a record count that disagrees with the file, or a declared header size\n that disagrees with the signal count, both of which have said so for versions.\n */\n const statedDate = recordingIdStartdate(recordingId);\n const headerDate = /^(\\d{2})[.\\-/](\\d{2})[.\\-/](\\d{2})$/u.exec(trimField(startDateRaw));\n if (statedDate !== null && headerDate !== null) {\n const day = Number(headerDate[1]);\n const month = Number(headerDate[2]);\n const yy = Number(headerDate[3]);\n if (statedDate.day !== day || statedDate.month !== month || statedDate.year % 100 !== yy) {\n diagnostics.push({\n code: 'START_DATE_MISMATCH',\n severity: 'warning',\n message:\n `The header's start date (\"${startDateRaw}\") and the date its recording ` +\n `identification states (\"${String(statedDate.day).padStart(2, '0')}-` +\n `${MONTHS[statedDate.month - 1] as string}-${statedDate.year}\") are different ` +\n `dates, which EDF+ does not permit.`,\n hint:\n 'The start date field is used, since that is the one the format defines. Which of ' +\n 'the two is right is not knowable from the file, so start_datetime_local may name ' +\n 'the wrong day.',\n });\n }\n }\n\n if (resolveStartDateTime(startDateRaw, startTimeRaw, recordingId) === null) {\n diagnostics.push({\n code: 'START_TIME_UNREADABLE',\n severity: 'warning',\n message:\n `The header's start date and time (\"${startDateRaw}\" and ` +\n `\"${startTimeRaw}\") are not a date and a time, so the recording has ` +\n `no start instant.`,\n hint:\n 'time_s is unaffected — it counts from the start of the recording either way. What ' +\n 'cannot be done is turning it into a wall-clock instant, and metadata.json records ' +\n 'start_datetime_local as null.',\n });\n }\n\n for (const [label, indices] of seenLabels) {\n if (indices.length < 2) continue;\n diagnostics.push({\n code: 'DUPLICATE_LABEL',\n severity: 'warning',\n /*\n Cut by the function that cuts every other list in a sentence here.\n\n `join` names all of them, however many there are, and a header may declare as many\n channels as it likes under one label: a 200-channel montage all labelled `T8-P8` — which\n is exactly the kind of file this warning is for, since CHB-MIT ships two of them —\n produced a single 1,100-character line of positions with the sentence that mattered at\n the front of it. `listed` shows eight and counts the rest, which is what the rate\n warning, the leftover-file warning, the channel-position lists in `--channels` and the\n `EMPTY_LABEL` message one loop up all already do. This was the last `join` of a\n file-controlled list left in a diagnostic.\n\n Two positions render identically either way, so the ordinary duplicate reads as it\n always has.\n */\n /*\n Positions written `#N`, which is how a position is written everywhere it is meant to be\n typed: `--channels \"#0\"`, \"This file has signal channels at #0, #1, #2\", and this\n warning's own namesake from channel selection — \"(positions #0, #1); all of them were\n selected\". This one said \"(positions 0, 1)\", two paragraphs above the page that tells\n the reader to \"address it by position with #N\". The number is the same; the form that\n works is not.\n */\n message: `${indices.length} signals share the label \"${label}\" (positions ${listed(indices.map((i) => `#${i}`))}).`,\n hint: 'Their columns are suffixed with the signal number so they stay distinguishable.',\n });\n }\n\n const recordBytes = byteOffsetInRecord;\n if (recordBytes <= 0) {\n throw new EdfError(\n 'NO_SAMPLES',\n 'No signal in this file carries any samples (every channel declares 0 samples per record).',\n );\n }\n\n if (sawComma.value) {\n diagnostics.push({\n code: 'COMMA_DECIMAL',\n severity: 'warning',\n message: 'Some header numbers use a comma decimal separator, which the EDF spec does not allow.',\n hint: 'They were read as decimal points. Check the values in the channel table.',\n });\n }\n\n const dataBytes = fileSize - expectedHeaderBytes;\n if (dataBytes < 0) {\n // With the two figures, like the other two FILE_TOO_SMALL messages and unlike this one,\n // which named neither — the same thing the NO_DATA_RECORDS message below was fixed for:\n // \"the message carried no figures at all, so nothing in it could be checked against the\n // file\". Reached by a caller handing `parseHeader` a header and a smaller size than the\n // one it came out of, which is a mismatch worth being able to see.\n throw new EdfError(\n 'FILE_TOO_SMALL',\n `File is ${counted(fileSize, 'byte')}, which is less than the ${expectedHeaderBytes} ` +\n `its own header occupies.`,\n );\n }\n const recordCount = Math.floor(dataBytes / recordBytes);\n const trailingBytes = dataBytes - recordCount * recordBytes;\n\n if (recordCount === 0) {\n /*\n Which of the two, and with the numbers.\n\n \"The recording was probably interrupted before any data was written\" is right about an\n empty file and wrong about the other way to get here: a header declaring records larger\n than the data present. A 606 KB file holding 589 KB of samples — 60% of one record, more\n than half a million readings — was told no data was written, and the message carried no\n figures at all, so nothing in it could be checked against the file. The declared record\n size is the thing to look at, and it was the one thing not said.\n\n Still an error either way. A record is the unit the format is addressed in, and there is\n nothing smaller to convert.\n */\n const empty = dataBytes === 0;\n throw new EdfError(\n 'NO_DATA_RECORDS',\n empty\n ? 'The file contains a header and no data at all.'\n : `The file contains ${counted(dataBytes, 'byte')} of data, which is less than the ` +\n `${recordBytes} its header says one data record takes.`,\n empty\n ? 'The recording was probably interrupted before any data was written.'\n : 'Either the recording was cut short part way through its first record, or the ' +\n 'header describes records larger than the ones actually written. Check the ' +\n 'samples-per-record fields against the file size.',\n );\n }\n\n if (declaredRecordCount === -1) {\n diagnostics.push({\n code: 'RECORD_COUNT_UNKNOWN',\n severity: 'warning',\n message:\n `The header does not say how many data records the file has (-1), which the spec allows ` +\n `for recordings still in progress. Using the ${counted(recordCount, 'record')} the file actually contains.`,\n });\n } else if (declaredRecordCount !== recordCount) {\n diagnostics.push({\n code: 'RECORD_COUNT_MISMATCH',\n severity: 'warning',\n // Both counts through `counted`, not only the second. A header declaring one record\n // over a file holding three read \"declares 1 data records\" — the slip the sentence\n // beside it has been holding to since it was written.\n message:\n `The header declares ${counted(declaredRecordCount, 'data record')} but the file ` +\n `contains ${recordCount}. Converting the ${counted(recordCount, 'record')} that ${recordCount === 1 ? 'is' : 'are'} present.`,\n hint:\n declaredRecordCount > recordCount\n ? 'The recording looks truncated. It may have been cut short or copied incompletely.'\n : 'The file is longer than its header claims.',\n });\n }\n\n if (trailingBytes > 0) {\n diagnostics.push({\n code: 'TRAILING_BYTES',\n severity: 'warning',\n message: `${counted(trailingBytes, 'byte')} after the last complete data record ${trailingBytes === 1 ? 'was' : 'were'} ignored.`,\n });\n }\n\n const isEdfPlus = continuity !== null;\n if (continuity === 'EDF+D') {\n diagnostics.push({\n code: 'DISCONTINUOUS',\n severity: 'warning',\n message:\n `This is a discontinuous (${isBdf ? 'BDF+D' : 'EDF+D'}) recording: its data records are ` +\n `not contiguous in time.`,\n hint: 'Each row carries its true recording time, so gaps stay visible instead of being closed.',\n });\n }\n\n const dataSignals = signals.filter((s) => !s.isAnnotations);\n if (dataSignals.length === 0) {\n diagnostics.push({\n code: 'NO_SIGNAL_CHANNELS',\n severity: 'warning',\n message: 'This file has no signal channels; it contains only EDF+ annotations.',\n });\n }\n\n // A channel declaring zero samples per record has no sampling rate to speak of — it is\n // reported separately as NO_SAMPLES and no file is written for it. Counting its nominal\n // 0 Hz as a rate made a single-rate recording warn that it used \"2 different sampling\n // rates (4 Hz, 0 Hz)\" and claim it was splitting output it never split.\n const rates = new Set(dataSignals.filter((s) => s.samplesPerRecord > 0).map((s) => s.samplingRate));\n if (rates.size > 1) {\n diagnostics.push({\n code: 'MIXED_SAMPLING_RATES',\n severity: 'warning',\n message:\n `Channels use ${rates.size} different sampling rates ` +\n `(${listed(formatRates([...rates].sort((a, b) => b - a)).map((r) => `${r} Hz`))}).`,\n hint: 'They are written to one file per rate so no channel is resampled.',\n });\n }\n\n return {\n header: {\n version,\n patientId,\n recordingId,\n startDateRaw,\n startTimeRaw,\n startDateTime: resolveStartDateTime(startDateRaw, startTimeRaw, recordingId),\n headerBytes: expectedHeaderBytes,\n declaredHeaderBytes: headerBytes,\n reserved,\n isEdfPlus,\n isBdf,\n continuity,\n declaredRecordCount,\n recordDuration,\n signalCount,\n signals,\n bytesPerSample,\n recordBytes,\n },\n recordCount,\n trailingBytes,\n diagnostics,\n };\n}\n\n/**\n * The recording start as a zone-less wall clock, \"YYYY-MM-DDTHH:MM:SS\".\n *\n * EDF stores the start time as local wall-clock digits with no timezone anywhere in\n * the format. `startDateTime` is built with Date.UTC purely so those digits survive a\n * round trip unshifted, which makes it a carrier for the wall clock rather than a\n * real instant. Serialising it with `toISOString()` would append a Z and assert UTC,\n * and any reader converting to local time would then shift the recording by their own\n * offset: 13:43:04 in the file becomes 08:43:04 in New York. The Z is omitted because\n * the file genuinely does not say which zone it meant.\n */\nexport function formatWallClock(date: Date | null): string | null {\n if (!date) return null;\n return date.toISOString().slice(0, 19);\n}\n\n/**\n * The recording's format, as `--info`, `metadata.json` and `--json` all name it.\n *\n * `\"EDF\"`, `\"BDF\"`, or one of `\"EDF+ (continuous)\"`, `\"EDF+ (discontinuous)\"`,\n * `\"BDF+ (continuous)\"`, `\"BDF+ (discontinuous)\"`. A BDF+ file reports its own spelling even\n * though `continuity` normalises the marker to the `EDF+` form.\n *\n * This said `EDF+ (EDF+D)` and `BDF+ (EDF+C)`, which are not strings it can return — the\n * parenthetical is the word, not the marker. It is a one-line doc comment on a public export,\n * so it is what a TypeScript consumer's editor shows and what `dist/edf/header.d.ts` ships,\n * and the value it describes is `recording.format` in every metadata.json this tool writes.\n * A consumer branching on the tooltip's spelling never matches. Every documentation page had\n * it right; this was the only place that did not.\n */\nexport function describeFormat(header: EdfHeader): string {\n const base = header.isBdf ? 'BDF' : 'EDF';\n if (!header.isEdfPlus) return base;\n return `${base}+ (${header.continuity === 'EDF+D' ? 'discontinuous' : 'continuous'})`;\n}\n\n/** Render a sampling rate without trailing noise: 256, 0.5, 12.5. */\nexport function formatRate(hz: number): string {\n if (Number.isInteger(hz)) {\n /*\n The same six decimals, in the notation `toFixed` cannot reach.\n\n Every double past 2^53 is an integer, so this branch takes every large rate — and\n `String` switches to exponent form at 1e21 and carries the full seventeen digits with\n it. Four samples in a record of 1e-300s is 3.9999999999999996e+300, which is exactly the\n float noise the rounding below exists to remove, printed in a `RATE` column of otherwise\n plain numbers and pasted into an output filename by `rateSlug`. Below 1e21 `String` is\n already exact and is left alone, so an integer rate a file can really state — 2^53\n samples in a second — is not rounded to something it is not.\n */\n const text = String(hz);\n return text.includes('e') ? String(Number(hz.toExponential(6))) : text;\n }\n const rounded = Number(hz.toFixed(6));\n // A rate below 5e-7 rounds away to \"0\", which reads as \"this channel has no sampling\n // rate\" and made the mixed-rate warning contradict itself: it announced two different\n // rates and then printed both as \"0 Hz\". Exponent form keeps a real rate legible, and\n // keeps distinct rates distinct in the channel table and in output filenames.\n if (rounded === 0) return hz.toExponential(3);\n return String(rounded);\n}\n\n/**\n * Renders a group of rates so that rates which differ read as differing.\n *\n * `formatRate` rounds to six decimals, which is what keeps an ordinary rate free of\n * float noise — 30 samples in a 0.1-second record is 299.99999999999994 as a double,\n * and belongs on screen as 300. Two rates separated by less than that round to one\n * string, so a file carrying 1e-6 Hz and 1.25e-6 Hz warned that it used \"2 different\n * sampling rates (0.000001 Hz, 0.000001 Hz)\" and named both files the same thing.\n *\n * That is the contradiction the exponent fallback above already removes for rates that\n * round away to zero; this is the same one a step further out. On a collision every rate\n * in the group switches to its shortest exact form, which is unique for distinct values,\n * rather than only the pair that collided — one column in one notation reads better than\n * two.\n */\nexport function formatRates(rates: readonly number[]): string[] {\n const rounded = rates.map(formatRate);\n const distinct = new Set(rates).size;\n return new Set(rounded).size === distinct ? rounded : rates.map((hz) => String(hz));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"header.js","sourceRoot":"","sources":["../../src/edf/header.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;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M,CAAC,EAAE,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACzE,CAAC;IACD,MAAM,OAAO,GAAG,MAAM,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IACtC,qFAAqF;IACrF,sFAAsF;IACtF,sFAAsF;IACtF,8EAA8E;IAC9E,IAAI,OAAO,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;IAC9C,OAAO,MAAM,CAAC,OAAO,CAAC,CAAC;AACzB,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,WAAW,CAAC,KAAwB;IAClD,MAAM,OAAO,GAAG,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IACtC,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC;IACrC,OAAO,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC;AACtF,CAAC","sourcesContent":["/**\n * EDF / EDF+ header parsing.\n *\n * Layout (all fields are ASCII, left-justified, space-padded):\n *\n * fixed header, 256 bytes\n * 0 8 version ('0', or 255 + 'BIOSEMI' for BDF)\n * 8 80 patient identification\n * 88 80 recording identification\n * 168 8 start date dd.mm.yy\n * 176 8 start time hh.mm.ss\n * 184 8 number of bytes in the header record\n * 192 44 reserved ('EDF+C' / 'EDF+D' live here)\n * 236 8 number of data records (-1 if unknown)\n * 244 8 duration of a data record, in seconds (may be fractional)\n * 252 4 number of signals (ns)\n *\n * signal header, ns * 256 bytes, stored FIELD-major rather than signal-major:\n * all ns labels, then all ns transducer types, and so on.\n * ns * 16 label\n * ns * 80 transducer type\n * ns * 8 physical dimension\n * ns * 8 physical minimum\n * ns * 8 physical maximum\n * ns * 8 digital minimum\n * ns * 8 digital maximum\n * ns * 80 prefiltering\n * ns * 8 number of samples in each data record\n * ns * 32 reserved\n */\n\nimport { EdfError } from './errors.js';\nimport type { Diagnostic } from './errors.js';\nimport { counted, listed } from '../format/list.js';\nimport { plain } from '../format/number.js';\n// The shell-quoting rule for a label, shared rather than repeated: this hint and\n// `--channels`' own \"did you mean\" have to print the same command for the same label.\nimport { typeable } from '../convert/channels.js';\nimport { decodeLatin1 } from './bytes.js';\n\n/** Label the EDF+ spec reserves for the annotations channel. */\nexport const ANNOTATIONS_LABEL = 'EDF Annotations';\n/** BDF+ uses its own spelling for the same channel. */\nexport const BDF_ANNOTATIONS_LABEL = 'BDF Annotations';\n\nexport const FIXED_HEADER_BYTES = 256;\nexport const SIGNAL_HEADER_BYTES = 256;\n\nexport interface EdfSignal {\n /** Position in the file, 0-based. Stable even when labels collide. */\n index: number;\n label: string;\n transducer: string;\n physicalDimension: string;\n physicalMin: number;\n physicalMax: number;\n digitalMin: number;\n digitalMax: number;\n prefiltering: string;\n samplesPerRecord: number;\n reserved: string;\n /** True for the EDF+ 'EDF Annotations' channel, which carries text, not signal. */\n isAnnotations: boolean;\n /** samplesPerRecord / recordDuration, in Hz. */\n samplingRate: number;\n /** Byte offset of this signal's samples within one data record. */\n byteOffsetInRecord: number;\n}\n\nexport interface EdfHeader {\n version: string;\n patientId: string;\n recordingId: string;\n /** Raw 'dd.mm.yy' as written in the file. */\n startDateRaw: string;\n /** Raw 'hh.mm.ss' as written in the file. */\n startTimeRaw: string;\n /** Resolved start instant, or null when the file's date/time fields are unusable. */\n startDateTime: Date | null;\n /**\n * Header size in bytes, computed from the signal count rather than read from the field.\n *\n * Every data record offset is derived from this, so it has to be the one the layout\n * actually uses: 256 for the fixed header plus 256 per signal. A writer that fills the\n * field in carelessly is common enough to have its own warning, HEADER_BYTES_MISMATCH,\n * and trusting the field over the arithmetic would put every sample at the wrong offset.\n */\n headerBytes: number;\n /**\n * What the header's own length field says, which need not be the above.\n *\n * Exposed for the same reason `declaredRecordCount` is: the two disagreeing is a fact\n * about the file, and a caller checking how a recording was written should be able to see\n * what it claimed rather than only what was believed.\n */\n declaredHeaderBytes: number;\n reserved: string;\n isEdfPlus: boolean;\n /** True for BioSemi BDF/BDF+ files, whose samples are 3 bytes rather than 2. */\n isBdf: boolean;\n /** 'EDF+C' continuous, 'EDF+D' discontinuous, or null for plain EDF. */\n continuity: 'EDF+C' | 'EDF+D' | null;\n /** As declared in the header. -1 means \"unknown\", which the spec permits. */\n declaredRecordCount: number;\n recordDuration: number;\n signalCount: number;\n signals: EdfSignal[];\n bytesPerSample: number;\n recordBytes: number;\n}\n\n/** Everything derived by combining the header with the file's real size. */\nexport interface EdfHeaderInfo {\n header: EdfHeader;\n /** Record count implied by the actual file size — the one we trust for reading. */\n recordCount: number;\n /** Bytes after the last complete data record. */\n trailingBytes: number;\n diagnostics: Diagnostic[];\n}\n\n/**\n * Whether a spreadsheet reads this field as the start of a formula rather than as text.\n *\n * `=` and `@` unconditionally; every list of these characters names two more, and this had\n * `-` as an exception with the reason written out on the warnings page: \"a lone `-` is a\n * real convention for no unit ... and neither is evaluated unless what follows it parses as a\n * formula\". Which is the condition, and it was not being applied — nothing with a leading\n * minus was flagged at all. A channel labelled `-2+3` opens as a column headed `1`, and\n * `-HYPERLINK(\"http://...\",\"EEG\")` is a name the spreadsheet resolves, in silence.\n *\n * So the exception is what it says it is rather than the whole character. A lone `-` is left\n * as text by every spreadsheet and is not flagged; a field that is entirely a number reads as\n * that number, which is what the header says, and is not flagged either. Anything else after\n * the minus is arithmetic or a name.\n *\n * And `+` takes the same exception, which it did not. It is the same rule in the spreadsheet —\n * Lotus compatibility, which converts a leading `+` or `-` to a formula when what follows one\n * parses as a formula and leaves it as text when it does not — so the two signs cannot differ\n * here for a reason that comes from the sign. A channel labelled `+100` was warned about as\n * something a spreadsheet \"reads as the start of a formula rather than as text\", over a cell\n * that opens as 100, which is what the header says; `-100` beside it said nothing, and under\n * `--strict` the difference was an exit code. `+1+1` is still arithmetic and still flagged.\n */\nfunction startsFormula(text: string): boolean {\n if (/^[=@]/u.test(text)) return true;\n if (!/^[+-]./u.test(text)) return false;\n // `\\.\\d*` and not `\\.\\d+`, which is the spelling DECIMAL_FIELD and DECIMAL_DURATION both\n // use for the same question. A trailing point is a number with nothing after it — Excel\n // opens `+1.` as 1 — and one character of difference between three copies of one grammar\n // had this warning firing on a field the paragraph above exempts by name, and failing\n // --strict for it.\n return !/^[+-](?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?$/u.test(text);\n}\n\n/**\n * A byte the terminal treats as an instruction rather than as text.\n *\n * C0 and C1, plus DEL. Tab is included deliberately: it is harmless to a terminal but it\n * makes a CSV column name that cannot be typed or matched reliably, which is the other half\n * of what this warning is for.\n */\nfunction isControlCharacter(character: string): boolean {\n const code = character.codePointAt(0) as number;\n return code <= 0x1f || (code >= 0x7f && code <= 0x9f);\n}\n\nconst dec = (buf: Uint8Array, start: number, len: number): string =>\n decodeLatin1(buf, start, start + len);\n\n/** EDF fields are space-padded; trailing NULs also occur in files written by sloppy tools. */\nconst trimField = (s: string): string => s.replace(/[\\0\\s]+$/u, '').replace(/^\\s+/u, '');\n\n/**\n * How many signals the fixed header says there are, read exactly as `parseHeader` will.\n *\n * `EdfFile.open` needs this before it can know how much header to read, and it used to work\n * it out with its own `Number(...)` — which was NUL-tolerant but not comma-tolerant, unlike\n * every other numeric field here. A header written with a comma decimal separator, which\n * COMMA_DECIMAL exists to accept and which the documentation lists this field among, was\n * therefore never given its signal headers at all, and the file died on a message that\n * contradicted itself: \"needs a 768-byte header, but the file is only 848 bytes\".\n *\n * Sharing the parse is what keeps the two from disagreeing again about which files are\n * readable. Null means \"not a usable count\", and the caller reads no further header — the\n * real error then comes from `parseHeader`, which is the one place that decides.\n */\nexport function peekSignalCount(fixed: Uint8Array): number | null {\n const text = normaliseNumberField(dec(fixed, 252, 4)).text;\n if (!DECIMAL_FIELD.test(text)) return null;\n const count = Number(text);\n return Number.isInteger(count) && count > 0 ? count : null;\n}\n\n/**\n * What EDF allows a numeric field to look like, which is less than `Number()` allows.\n *\n * A sign, digits, an optional fractional part, an optional exponent — the spec's own grammar,\n * plus the exponent form the 8-character physical bounds need to reach a magnetometer's range\n * and which real headers use.\n *\n * `Number()` accepts a great deal more, and every one of those forms is a header this tool\n * would have read as a number nobody wrote. A physical maximum of `0x64` came out as 100: it\n * printed as `-100 to 100` in the channel table, went into channels.csv as `physical_max,100`,\n * and set the gain every sample on that channel was scaled by — a whole calibration invented\n * from four bytes that are not a decimal number, exit 0, no diagnostic. `0b1100100` and `0o144`\n * are the same hundred, and `0x02` in the signal-count field is a two-channel recording.\n *\n * The same mistake as `#0x2` reaching channel 2 through `--channels`, `--decimals 0o5` writing\n * five places and `--jobs 0x10` running sixteen, all of which have their own comments and their\n * own fixes. Those were values somebody typed. These are the fields every number in the output\n * is computed from, and the page describing them says \"all fields are ASCII\" and gives the\n * layout digit by digit.\n */\nconst DECIMAL_FIELD = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?$/u;\n\n/** A numeric header field, trimmed and with a comma decimal separator turned into a dot. */\nfunction normaliseNumberField(raw: string): { text: string; sawComma: boolean } {\n const text = trimField(raw);\n // Some writers emit a comma decimal separator despite the spec requiring '.'.\n if (text.includes(',') && !text.includes('.')) {\n return { text: text.replace(',', '.'), sawComma: true };\n }\n return { text, sawComma: false };\n}\n\nfunction parseNumberField(\n raw: string,\n field: string,\n { integer = false, sawComma }: { integer?: boolean; sawComma?: { value: boolean } } = {},\n): number {\n const normalised = normaliseNumberField(raw);\n const text = normalised.text;\n if (normalised.sawComma && sawComma) sawComma.value = true;\n if (text === '') {\n throw new EdfError('BAD_HEADER_FIELD', `Header field \"${field}\" is empty.`);\n }\n const n = DECIMAL_FIELD.test(text) ? Number(text) : NaN;\n if (!Number.isFinite(n)) {\n throw new EdfError(\n 'BAD_HEADER_FIELD',\n `Header field \"${field}\" is not a number (found ${JSON.stringify(text)}).`,\n 'The file may be truncated, byte-shifted, or not an EDF file at all.',\n );\n }\n if (integer && !Number.isInteger(n)) {\n throw new EdfError(\n 'BAD_HEADER_FIELD',\n `Header field \"${field}\" must be a whole number (found ${JSON.stringify(text)}).`,\n );\n }\n return n;\n}\n\n/** Whether the start time names the sixtieth second. See LEAP_SECOND_START. */\nfunction namesLeapSecond(timeRaw: string): boolean {\n const t = /^(\\d{2})[.:\\-](\\d{2})[.:\\-](\\d{2})$/u.exec(trimField(timeRaw));\n return t !== null && Number(t[3]) === 60;\n}\n\nconst MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];\n\n/**\n * The date an EDF+ recording ID states, which is the only place the file writes a full year.\n *\n * EDF+ requires the recording identification field to begin `Startdate dd-MMM-yyyy`, and\n * requires it to agree with the header's own date field. It is a four-digit year, so it says\n * something the eight-character date field physically cannot.\n */\nfunction recordingIdStartdate(\n recordingId: string,\n): { day: number; month: number; year: number } | null {\n const stated = /^Startdate\\s+(\\d{2})-([A-Za-z]{3})-(\\d{4})(?:\\s|$)/u.exec(recordingId.trim());\n if (!stated) return null;\n const month = MONTHS.indexOf((stated[2] as string).toUpperCase()) + 1;\n if (month === 0) return null;\n return { day: Number(stated[1]), month, year: Number(stated[3]) };\n}\n\n/**\n * EDF stores a two-digit year. The spec pins the century: 85-99 mean 1985-1999\n * and 00-84 mean 2000-2084. Files outside 1985-2084 cannot express their date.\n *\n * Which is why EDF+ writes it again in full, in the recording identification field, and why\n * that is used here when it is there. The rule alone reports a recording made in 1984 as 2084\n * and one made in 2085 as 1985 — a hundred years out, on a file that states the year plainly\n * four fields earlier. Taken only where the two agree about everything the header can express:\n * the same day, the same month, and a four-digit year ending in the two digits the header\n * wrote. A recording ID that contradicts the header is a different problem and is left to the\n * spec's rule, which is at least the one the format defines.\n */\nfunction resolveStartDateTime(\n dateRaw: string,\n timeRaw: string,\n recordingId = '',\n): Date | null {\n const d = /^(\\d{2})[.\\-/](\\d{2})[.\\-/](\\d{2})$/u.exec(trimField(dateRaw));\n const t = /^(\\d{2})[.:\\-](\\d{2})[.:\\-](\\d{2})$/u.exec(trimField(timeRaw));\n if (!d || !t) return null;\n\n const dd = Number(d[1]);\n const mm = Number(d[2]);\n const yy = Number(d[3]);\n const hh = Number(t[1]);\n const mi = Number(t[2]);\n const ss = Number(t[3]);\n\n if (mm < 1 || mm > 12 || dd < 1 || dd > 31 || hh > 23 || mi > 59 || ss > 60) return null;\n\n const stated = recordingIdStartdate(recordingId);\n const year =\n stated !== null && stated.day === dd && stated.month === mm && stated.year % 100 === yy\n ? stated.year\n : yy >= 85\n ? 1900 + yy\n : 2000 + yy;\n const date = new Date(Date.UTC(year, mm - 1, dd, hh, mi, Math.min(ss, 59)));\n // Reject dates that rolled over, e.g. 31.02.\n if (date.getUTCMonth() !== mm - 1 || date.getUTCDate() !== dd) return null;\n return date;\n}\n\n/**\n * Parse the fixed 256-byte header plus the per-signal header block.\n *\n * @param buf At least FIXED_HEADER_BYTES + ns * SIGNAL_HEADER_BYTES bytes.\n * @param fileSize Total size of the file on disk, used to derive the real record count.\n */\nexport function parseHeader(buf: Uint8Array, fileSize: number): EdfHeaderInfo {\n const diagnostics: Diagnostic[] = [];\n const sawComma = { value: false };\n\n if (buf.length < FIXED_HEADER_BYTES) {\n throw new EdfError(\n 'FILE_TOO_SMALL',\n `File is ${counted(fileSize, 'byte')}; an EDF header alone needs at least ${FIXED_HEADER_BYTES}.`,\n );\n }\n\n // BDF (BioSemi) marks itself with byte 255 followed by 'BIOSEMI', and stores\n // 3-byte samples instead of 2. Everything else about the layout is identical.\n const isBdf = buf[0] === 0xff && dec(buf, 1, 7) === 'BIOSEMI';\n const version = isBdf ? 'BIOSEMI' : trimField(dec(buf, 0, 8));\n\n const patientId = trimField(dec(buf, 8, 80));\n const recordingId = trimField(dec(buf, 88, 80));\n const startDateRaw = trimField(dec(buf, 168, 8));\n const startTimeRaw = trimField(dec(buf, 176, 8));\n const headerBytes = parseNumberField(dec(buf, 184, 8), 'number of header bytes', {\n integer: true,\n sawComma,\n });\n const reserved = trimField(dec(buf, 192, 44));\n const declaredRecordCount = parseNumberField(dec(buf, 236, 8), 'number of data records', {\n integer: true,\n sawComma,\n });\n const recordDuration = parseNumberField(dec(buf, 244, 8), 'duration of a data record', {\n sawComma,\n });\n const signalCount = parseNumberField(dec(buf, 252, 4), 'number of signals', {\n integer: true,\n sawComma,\n });\n\n if (signalCount <= 0) {\n throw new EdfError(\n 'INVALID_SIGNAL_COUNT',\n `Header declares ${signalCount} signals; expected at least 1.`,\n );\n }\n if (!(recordDuration > 0)) {\n throw new EdfError(\n 'INVALID_RECORD_DURATION',\n `Header declares a data record duration of ${plain(recordDuration)}s; expected a positive number.`,\n );\n }\n\n const expectedHeaderBytes = FIXED_HEADER_BYTES + signalCount * SIGNAL_HEADER_BYTES;\n if (buf.length < expectedHeaderBytes) {\n throw new EdfError(\n 'FILE_TOO_SMALL',\n /*\n Which of the two is actually short.\n\n The file size was quoted either way, so a caller that had read too little — the\n signal count parsed one way here and another way there — produced arithmetic that\n refuted itself: \"needs a 768-byte header, but the file is only 848 bytes\". A reader\n following that looks for a truncation that is not there.\n */\n `File declares ${counted(signalCount, 'signal')}, which needs a ${expectedHeaderBytes}-byte header, ` +\n (fileSize < expectedHeaderBytes\n ? `but the file is only ${fileSize} bytes.`\n : `but only ${buf.length} bytes of it were handed to the parser.`),\n );\n }\n if (headerBytes !== expectedHeaderBytes) {\n diagnostics.push({\n code: 'HEADER_BYTES_MISMATCH',\n severity: 'warning',\n message:\n `Header says it is ${headerBytes} bytes, but ${counted(signalCount, 'signal')} ` +\n `${signalCount === 1 ? 'requires' : 'require'} ${expectedHeaderBytes} bytes. ` +\n `Using the value computed from the signal count.`,\n });\n }\n\n // Signal headers are field-major: all labels, then all transducers, and so on.\n const base = FIXED_HEADER_BYTES;\n const readField = (offsetUnits: number, width: number, i: number): string =>\n dec(buf, base + offsetUnits * signalCount + i * width, width);\n\n // EDF+ writes 'EDF+C'/'EDF+D' here; BDF+ writes 'BDF+C'/'BDF+D'. The two mean the\n // same thing, so both are normalised to a single continuity marker.\n const continuityTag = /^(?:EDF|BDF)\\+([CD])/u.exec(reserved);\n const continuity: 'EDF+C' | 'EDF+D' | null =\n continuityTag === null ? null : continuityTag[1] === 'D' ? 'EDF+D' : 'EDF+C';\n\n const signals: EdfSignal[] = [];\n let byteOffsetInRecord = 0;\n const bytesPerSample = isBdf ? 3 : 2;\n const seenLabels = new Map<string, number[]>();\n const emptyLabels: number[] = [];\n\n for (let i = 0; i < signalCount; i++) {\n const label = trimField(readField(0, 16, i));\n const transducer = trimField(readField(16, 80, i));\n const physicalDimension = trimField(readField(96, 8, i));\n const physicalMin = parseNumberField(readField(104, 8, i), `physical minimum (signal ${i})`, {\n sawComma,\n });\n const physicalMax = parseNumberField(readField(112, 8, i), `physical maximum (signal ${i})`, {\n sawComma,\n });\n const digitalMin = parseNumberField(readField(120, 8, i), `digital minimum (signal ${i})`, {\n integer: true,\n sawComma,\n });\n const digitalMax = parseNumberField(readField(128, 8, i), `digital maximum (signal ${i})`, {\n integer: true,\n sawComma,\n });\n const prefiltering = trimField(readField(136, 80, i));\n const samplesPerRecord = parseNumberField(\n readField(216, 8, i),\n `samples per record (signal ${i})`,\n { integer: true, sawComma },\n );\n const sigReserved = trimField(readField(224, 32, i));\n\n if (samplesPerRecord < 0) {\n throw new EdfError(\n 'BAD_HEADER_FIELD',\n `Signal ${i} (\"${label}\") declares ${samplesPerRecord} samples per record.`,\n );\n }\n\n const isAnnotations = label === ANNOTATIONS_LABEL || label === BDF_ANNOTATIONS_LABEL;\n\n signals.push({\n index: i,\n label,\n transducer,\n physicalDimension,\n physicalMin,\n physicalMax,\n digitalMin,\n digitalMax,\n prefiltering,\n samplesPerRecord,\n reserved: sigReserved,\n isAnnotations,\n samplingRate: samplesPerRecord / recordDuration,\n byteOffsetInRecord,\n });\n byteOffsetInRecord += samplesPerRecord * bytesPerSample;\n\n if (!isAnnotations) {\n /*\n A label is free text out of the file, and it becomes a column name in signals.csv.\n\n `--info` has escaped control bytes since it was written, because an ANSI escape in a\n header can drive the reader's terminal — `\\x1b[2J` clears the screen. The CSV had no\n such protection and needed none for correctness: quoting makes any byte safe for a\n parser, and this still passes the label through exactly as the file gives it, because\n losing what the header says is not an improvement.\n\n What was missing is the sentence saying so. A recording whose channel is labelled\n `\\x1b[2Jgone` converted with no warning at all, and `cat signals.csv` then cleared\n the terminal — while a script referencing that column by name carried an invisible\n control character in it. NONPRINTABLE_LABEL has been declared and documented as\n reserved since 0.1; this is it doing its job.\n */\n /*\n Which of the two fields carries them, because the consequences are not the same.\n\n The message said \"label or unit\", and then said the bytes \"will appear in the CSV\n column name\" and that \"the name cannot be typed\" — both of which are about the label.\n A channel labelled plainly `ECG` in a unit of `u\\x07V` got all of it: its column is\n `ECG`, `--channels ECG` selects it and exits 0, and the byte is in channels.csv's\n `unit` cell, which the warning never mentioned. Three sentences, none of them true of\n the file that raised it, on a warning whose whole purpose is to say where an invisible\n byte went.\n */\n /*\n All four free-text fields, not the two that were checked.\n\n `transducer` and `prefiltering` are free text out of the header exactly as the label\n and the unit are, and they land in channels.csv exactly as the unit does — so an ESC\n byte in a transducer field reached the CSV raw with nothing said, and `cat\n channels.csv` would drive the terminal. That is the hazard this warning exists for,\n two columns over. 0.5.71 made it name which field carries them; this is the rest of\n the fields it can name.\n */\n const fields = [\n ['label', label],\n ['unit', physicalDimension],\n ['transducer', transducer],\n ['prefiltering', prefiltering],\n ] as const;\n const affected = fields.filter(([, text]) => [...text].some(isControlCharacter));\n const control = affected.flatMap(([, text]) => [...text].filter(isControlCharacter));\n if (control.length > 0) {\n const shown = [...new Set(control)]\n .map((c) => `\\\\x${(c.codePointAt(0) as number).toString(16).padStart(2, '0')}`)\n .join(', ');\n const plural = control.length === 1 ? '' : 's';\n const inLabel = affected.some(([name]) => name === 'label');\n // \"label and unit\", not \"label, unit\" — `listed` is for long enumerations that get\n // truncated, and this is a sentence with at most four items in it.\n const names = affected.map(([name]) => name);\n const named =\n names.length === 1\n ? (names[0] as string)\n : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1] as string}`;\n // Where they land, which is the question the reader has. A label becomes a column\n // name in signals.csv; the other three are cells of channels.csv and nothing else.\n // Named down to the cell when there is one of them, because that is the answer to\n // \"where did it go\" — `channels.csv` alone leaves a reader scanning fourteen columns.\n const cells = affected.filter(([name]) => name !== 'label').map(([name]) => name);\n const where =\n cells.length === 1 ? `channels.csv's ${cells[0] as string} cell` : 'channels.csv';\n const lands =\n inLabel && cells.length > 0\n ? `which will appear in the CSV column name and in ${where}`\n : inLabel\n ? 'which will appear in the CSV column name'\n : `which will appear in ${where}`;\n diagnostics.push({\n code: 'NONPRINTABLE_LABEL',\n severity: 'warning',\n message:\n `Signal ${i}'s ${named} ${affected.length === 1 ? 'contains' : 'contain'} ` +\n `${control.length} control character${plural} (${shown}), ${lands} exactly as the ` +\n `header has ${control.length === 1 ? 'it' : 'them'}.`,\n hint:\n /*\n Every branch has to print a command that works.\n\n The middle one quoted the label back, which is right until the label is empty:\n an unlabelled channel got `--channels \"\"`, and that exits 2 with \"--channels was\n given but lists no channel names\". A hint whose command fails is worse than no\n hint, and this warning's whole job is to say how to reach a channel whose header\n text you cannot type. `EMPTY_LABEL` already says the position is the only way in\n for such a channel; so does this now.\n\n A comma is the third way. `--channels` separates names with one, and splits on\n every occurrence, so a channel labelled `EEG Fpz-Cz, ref` cannot be selected by\n name at all: the quoted-back advice printed `--channels \"EEG Fpz-Cz, ref\"`, which\n exits 2 with `No channel named \"EEG Fpz-Cz\"` — a channel the file does not have,\n named after half of one it does. Commas in labels are ordinary, since EDF labels\n are free text, and the CSV header quotes them; only this one hint claimed\n something about them that isn't so.\n */\n /*\n And a fourth way, which this branch printed straight past.\n\n A shell expands `$`, a backtick and a backslash inside double quotes, so a\n channel labelled `EEG $ref` was answered with `--channels \"EEG $ref\"` — which\n arrives as `EEG ` and exits 2 on a channel the file does not have. A backtick\n opens a command substitution and the pasted line does not even finish. That is\n the failure 0.7.18 fixed for `--channels`' own suggestion, and `typeable` is the\n rule it fixed it with: double quotes where they survive, single quotes where\n they do not, null where nothing does. Asking it settles which branch this takes\n as well, so the two cannot disagree about one label again.\n */\n (typeable(label) === null\n ? `Address the channel by position with --channels \"#${i}\" rather than by name, ` +\n `since ${\n inLabel\n ? 'the name cannot be typed'\n : label === ''\n ? 'it has no label'\n : 'a comma in the label would read as two names'\n }. `\n : `The column name is unaffected, so --channels ${typeable(label) as string} still selects it. `) +\n 'Printing the CSV to a terminal may do more than print it.',\n });\n }\n\n /*\n Header text a spreadsheet will run rather than read.\n\n The same four free-text fields, asked a different question. `=`, `+` and `@` start a\n formula in Excel, LibreOffice and Sheets no matter which file the cell came from, and\n these fields land in a CSV header row and in channels.csv verbatim — so a channel\n labelled `=1+1` opens as a column headed 2, and `=HYPERLINK(...)` opens as a link\n nobody in the reading chain wrote. SECURITY.md already calls these fields\n attacker-controlled because they reach filenames; this is where they reach a program\n that executes text.\n\n Not `-`, which the same advice usually includes. A lone `-` is a real convention for\n \"no unit\" and appears in the fixtures, a leading `-` on a montage label is ordinary,\n and neither is executed unless what follows parses as a formula — so warning on it\n would fire on files that are fine, which is how a warning gets ignored.\n\n Said, not fixed. Prefixing the cell with a quote is the usual mitigation and would mean\n writing something the header does not say, which is the one thing this tool refuses to\n do; NONPRINTABLE_LABEL answers control bytes the same way.\n */\n const formulaic = fields.filter(([, text]) => startsFormula(text));\n if (formulaic.length > 0) {\n const names = formulaic.map(([name]) => name);\n const named =\n names.length === 1\n ? (names[0] as string)\n : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1] as string}`;\n const shown = [...new Set(formulaic.map(([, text]) => text[0] as string))].join(', ');\n diagnostics.push({\n code: 'FORMULA_LABEL',\n severity: 'warning',\n message:\n `Signal ${i}'s ${named} ${formulaic.length === 1 ? 'starts' : 'start'} with ` +\n `${shown}, which Excel, LibreOffice and Google Sheets read as the start of a ` +\n `formula rather than as text.`,\n hint:\n 'The text is written exactly as the header has it, so the cell is what the ' +\n 'recording says. Open the CSV with pandas or R, or import it into the ' +\n 'spreadsheet as text, if you do not want it evaluated.',\n });\n }\n\n if (label === '') {\n // Collected, not reported here: what this channel's column ends up called depends on\n // whether some later channel is literally labelled `signal_<i>`, and inside this loop\n // the later channels do not exist yet. See the pass below.\n emptyLabels.push(i);\n } else {\n // Collected rather than reported here: a label repeated five times should\n // produce one warning naming all five, not four near-identical pairs.\n const seen = seenLabels.get(label);\n if (seen) seen.push(i);\n else seenLabels.set(label, [i]);\n }\n\n if (samplesPerRecord === 0) {\n diagnostics.push({\n code: 'NO_SAMPLES',\n severity: 'warning',\n message: `Signal ${i} (\"${label}\") carries no samples at all (0 per data record).`,\n hint: 'It is described in channels.csv but left out of the converted data.',\n });\n }\n\n /*\n Too large to represent, and too small — the second was silent.\n\n The gain is the span divided by the digital range, and a span of 2e-320 over 65,535\n codes is 3e-325: below the smallest subnormal double, so it underflows to +0. The\n scaler's flat-range branch then handed every code the same physical value, and a\n channel of 65,536 distinct readings became one repeated number with nothing raised at\n all. One power of ten away, at 1e-319, the same file raises VALUE_RESOLUTION.\n\n Both are the same fact about the header — the span cannot be turned into a mapping —\n so both get this code, and both leave the cells empty rather than filling them with a\n value the header cannot justify.\n */\n const span = physicalMax - physicalMin;\n const underflowed = span !== 0 && span / (digitalMax - digitalMin) === 0;\n if (!Number.isFinite(span) || underflowed) {\n diagnostics.push({\n code: 'UNUSABLE_PHYSICAL_RANGE',\n severity: 'warning',\n message:\n `Signal ${i} (\"${label}\") declares a physical range from ${physicalMin} to ` +\n `${physicalMax}, whose span is too ${underflowed ? 'small' : 'large'} to ` +\n `represent, so its values cannot be scaled.`,\n hint: 'Its cells are left empty rather than filled with a value the header cannot justify.',\n });\n } else if (digitalMax === digitalMin) {\n diagnostics.push({\n code: 'DEGENERATE_DIGITAL_RANGE',\n severity: 'warning',\n message:\n `Signal ${i} (\"${label}\") has digital minimum equal to digital maximum ` +\n `(${digitalMin}), so its values cannot be scaled.`,\n hint: 'Its cells are left empty rather than filled with a value the header cannot justify.',\n });\n } else if (physicalMax === physicalMin) {\n diagnostics.push({\n code: 'DEGENERATE_PHYSICAL_RANGE',\n severity: 'warning',\n message:\n `Signal ${i} (\"${label}\") has physical minimum equal to physical maximum ` +\n `(${physicalMin}), so every sample converts to the same value.`,\n });\n } else if ((physicalMax - physicalMin) * (digitalMax - digitalMin) < 0) {\n /*\n Polarity is inverted when the gain is negative, and the gain is\n (physicalMax - physicalMin) / (digitalMax - digitalMin) — so it is the sign of the\n two spans together that matters, not the physical pair alone.\n\n Testing only `physicalMax < physicalMin` was wrong in both directions. A file with\n its DIGITAL bounds reversed is just as inverted and drew no warning at all, handing\n back sign-flipped EEG with nothing to indicate it. A file with BOTH pairs reversed\n has a positive gain and is not inverted, yet was warned about — a message that was\n simply untrue of that recording.\n */\n const reversed =\n physicalMax < physicalMin\n ? `physical minimum ${physicalMin} above physical maximum ${physicalMax}`\n : `digital minimum ${digitalMin} above digital maximum ${digitalMax}`;\n diagnostics.push({\n code: 'INVERTED_PHYSICAL_RANGE',\n severity: 'warning',\n message: `Signal ${i} (\"${label}\") declares ${reversed}, which inverts its polarity.`,\n hint: 'The values are converted exactly as the header specifies, inversion included.',\n });\n }\n }\n }\n\n /*\n What an unlabelled channel is actually called, which the message used to guess.\n\n A channel with no label takes `signal_<index>` — unless another channel is literally\n labelled that, which EDF permits, since labels are free text and nothing enforces anything\n about them. Then both collide and both are suffixed. The warning said \"It will appear as\n \"signal_0\"\" while the file's header read `time_s,signal_0_ch0,signal_0_ch1`: the one\n sentence the run printed named a column that exists in neither signals.csv nor\n channels.csv.\n\n The other half was silent. The channel that genuinely carries the label `signal_0` lost\n its own column name to a collision with a synthesised one, and nothing said so —\n DUPLICATE_LABEL did not fire, because the two labels are not the same label. Both halves\n are one sentence here, because they are one event.\n\n No specific suffixed name is quoted. The suffix rule has a second pass for names that are\n still shared afterwards, and a message that hard-coded `_ch<index>` would be guessing again\n in exactly the way this is fixing.\n */\n for (const index of emptyLabels) {\n const taken = seenLabels.get(`signal_${index}`);\n diagnostics.push({\n code: 'EMPTY_LABEL',\n severity: 'warning',\n message:\n taken === undefined\n ? `Signal ${index} has no label. It will appear as \"signal_${index}\".`\n : `Signal ${index} has no label, so it takes the name \"signal_${index}\" — which ` +\n `${taken.length === 1 ? 'signal' : 'signals'} ${listed(taken.map(String))} already ` +\n `${taken.length === 1 ? 'carries' : 'carry'} as a label, so both columns are ` +\n `suffixed with their position instead.`,\n });\n }\n\n /*\n A timestamp that is not one.\n\n EDF gives the start date and time eight characters each, and nothing stops a writer\n putting `32.13.99` and `25.61.61` there. `--info` has always echoed the raw fields with\n \"(unparseable)\" beside them, but nothing was raised: the conversion exited 0, `--strict`\n passed, and metadata.json recorded `start_datetime_local: null` with no note against it.\n\n Every other unusable header field reports itself — a degenerate digital range, a physical\n span that cannot be represented, a comma decimal separator, a header whose declared size\n disagrees with its signal count. This was the one that did not, and it is the field\n output-files points at for turning `time_s` into an absolute instant.\n */\n /*\n The sixtieth second, which is a second UTC has and a calendar date does not.\n\n `resolveStartDateTime` admits `ss === 60` on purpose — a recorder synchronised to UTC\n through a leap second writes `23.59.60`, and refusing it would throw away a date that is\n otherwise perfectly good over one second. What it then does is `Math.min(ss, 59)`, because\n `Date.UTC(..., 60)` rolls over into the next minute and would move the instant the other\n way, by fifty-nine seconds more.\n\n Keeping the nearest instant is the right answer. Keeping it in silence was not: `--info`\n printed `Recorded 2020-01-01 23:59:59` and metadata.json recorded the same, for a header\n that says `23.59.60`, with `--strict` exiting 0. Every other header field this tool cannot\n represent exactly says so — a comma decimal separator, a physical span that overflows, a\n record count that disagrees with the file — and this is the field `time_s` is documented as\n being added to.\n */\n if (\n namesLeapSecond(startTimeRaw) &&\n resolveStartDateTime(startDateRaw, startTimeRaw, recordingId) !== null\n ) {\n diagnostics.push({\n code: 'LEAP_SECOND_START',\n severity: 'warning',\n message:\n `The header's start time (\"${startTimeRaw}\") names the sixtieth second of a minute, ` +\n `which no calendar date has.`,\n hint:\n 'It is recorded as the fifty-ninth second, one second earlier, since that is the ' +\n 'nearest instant a date can hold. time_s is unaffected — it counts from the start of ' +\n 'the recording either way.',\n });\n }\n\n /*\n Two dates in one header, disagreeing.\n\n EDF+ requires the recording identification field's `Startdate` to be the header's start\n date. Where it is, its four digits settle the century — see resolveStartDateTime. Where it\n is not, one of the two is wrong and there is no way to tell which, so the date field is\n used, being the one the format defines. That was done in silence, on a header that plainly\n contradicts itself:\n\n Recorded 2002-03-02 22:15:00\n Recording Startdate 05-MAR-2002 PSG-1234/2002 NN Telemetry03\n\n The same shape as a record count that disagrees with the file, or a declared header size\n that disagrees with the signal count, both of which have said so for versions.\n */\n const statedDate = recordingIdStartdate(recordingId);\n const headerDate = /^(\\d{2})[.\\-/](\\d{2})[.\\-/](\\d{2})$/u.exec(trimField(startDateRaw));\n if (statedDate !== null && headerDate !== null) {\n const day = Number(headerDate[1]);\n const month = Number(headerDate[2]);\n const yy = Number(headerDate[3]);\n if (statedDate.day !== day || statedDate.month !== month || statedDate.year % 100 !== yy) {\n diagnostics.push({\n code: 'START_DATE_MISMATCH',\n severity: 'warning',\n message:\n `The header's start date (\"${startDateRaw}\") and the date its recording ` +\n `identification states (\"${String(statedDate.day).padStart(2, '0')}-` +\n `${MONTHS[statedDate.month - 1] as string}-${statedDate.year}\") are different ` +\n `dates, which EDF+ does not permit.`,\n hint:\n 'The start date field is used, since that is the one the format defines. Which of ' +\n 'the two is right is not knowable from the file, so start_datetime_local may name ' +\n 'the wrong day.',\n });\n }\n }\n\n if (resolveStartDateTime(startDateRaw, startTimeRaw, recordingId) === null) {\n diagnostics.push({\n code: 'START_TIME_UNREADABLE',\n severity: 'warning',\n message:\n `The header's start date and time (\"${startDateRaw}\" and ` +\n `\"${startTimeRaw}\") are not a date and a time, so the recording has ` +\n `no start instant.`,\n hint:\n 'time_s is unaffected — it counts from the start of the recording either way. What ' +\n 'cannot be done is turning it into a wall-clock instant, and metadata.json records ' +\n 'start_datetime_local as null.',\n });\n }\n\n for (const [label, indices] of seenLabels) {\n if (indices.length < 2) continue;\n diagnostics.push({\n code: 'DUPLICATE_LABEL',\n severity: 'warning',\n /*\n Cut by the function that cuts every other list in a sentence here.\n\n `join` names all of them, however many there are, and a header may declare as many\n channels as it likes under one label: a 200-channel montage all labelled `T8-P8` — which\n is exactly the kind of file this warning is for, since CHB-MIT ships two of them —\n produced a single 1,100-character line of positions with the sentence that mattered at\n the front of it. `listed` shows eight and counts the rest, which is what the rate\n warning, the leftover-file warning, the channel-position lists in `--channels` and the\n `EMPTY_LABEL` message one loop up all already do. This was the last `join` of a\n file-controlled list left in a diagnostic.\n\n Two positions render identically either way, so the ordinary duplicate reads as it\n always has.\n */\n /*\n Positions written `#N`, which is how a position is written everywhere it is meant to be\n typed: `--channels \"#0\"`, \"This file has signal channels at #0, #1, #2\", and this\n warning's own namesake from channel selection — \"(positions #0, #1); all of them were\n selected\". This one said \"(positions 0, 1)\", two paragraphs above the page that tells\n the reader to \"address it by position with #N\". The number is the same; the form that\n works is not.\n */\n message: `${indices.length} signals share the label \"${label}\" (positions ${listed(indices.map((i) => `#${i}`))}).`,\n hint: 'Their columns are suffixed with the signal number so they stay distinguishable.',\n });\n }\n\n const recordBytes = byteOffsetInRecord;\n if (recordBytes <= 0) {\n throw new EdfError(\n 'NO_SAMPLES',\n 'No signal in this file carries any samples (every channel declares 0 samples per record).',\n );\n }\n\n if (sawComma.value) {\n diagnostics.push({\n code: 'COMMA_DECIMAL',\n severity: 'warning',\n message: 'Some header numbers use a comma decimal separator, which the EDF spec does not allow.',\n hint: 'They were read as decimal points. Check the values in the channel table.',\n });\n }\n\n const dataBytes = fileSize - expectedHeaderBytes;\n if (dataBytes < 0) {\n // With the two figures, like the other two FILE_TOO_SMALL messages and unlike this one,\n // which named neither — the same thing the NO_DATA_RECORDS message below was fixed for:\n // \"the message carried no figures at all, so nothing in it could be checked against the\n // file\". Reached by a caller handing `parseHeader` a header and a smaller size than the\n // one it came out of, which is a mismatch worth being able to see.\n throw new EdfError(\n 'FILE_TOO_SMALL',\n `File is ${counted(fileSize, 'byte')}, which is less than the ${expectedHeaderBytes} ` +\n `its own header occupies.`,\n );\n }\n const recordCount = Math.floor(dataBytes / recordBytes);\n const trailingBytes = dataBytes - recordCount * recordBytes;\n\n if (recordCount === 0) {\n /*\n Which of the two, and with the numbers.\n\n \"The recording was probably interrupted before any data was written\" is right about an\n empty file and wrong about the other way to get here: a header declaring records larger\n than the data present. A 606 KB file holding 589 KB of samples — 60% of one record, more\n than half a million readings — was told no data was written, and the message carried no\n figures at all, so nothing in it could be checked against the file. The declared record\n size is the thing to look at, and it was the one thing not said.\n\n Still an error either way. A record is the unit the format is addressed in, and there is\n nothing smaller to convert.\n */\n const empty = dataBytes === 0;\n throw new EdfError(\n 'NO_DATA_RECORDS',\n empty\n ? 'The file contains a header and no data at all.'\n : `The file contains ${counted(dataBytes, 'byte')} of data, which is less than the ` +\n `${recordBytes} its header says one data record takes.`,\n empty\n ? 'The recording was probably interrupted before any data was written.'\n : 'Either the recording was cut short part way through its first record, or the ' +\n 'header describes records larger than the ones actually written. Check the ' +\n 'samples-per-record fields against the file size.',\n );\n }\n\n if (declaredRecordCount === -1) {\n diagnostics.push({\n code: 'RECORD_COUNT_UNKNOWN',\n severity: 'warning',\n message:\n `The header does not say how many data records the file has (-1), which the spec allows ` +\n `for recordings still in progress. Using the ${counted(recordCount, 'record')} the file actually contains.`,\n });\n } else if (declaredRecordCount !== recordCount) {\n diagnostics.push({\n code: 'RECORD_COUNT_MISMATCH',\n severity: 'warning',\n // Both counts through `counted`, not only the second. A header declaring one record\n // over a file holding three read \"declares 1 data records\" — the slip the sentence\n // beside it has been holding to since it was written.\n message:\n `The header declares ${counted(declaredRecordCount, 'data record')} but the file ` +\n `contains ${recordCount}. Converting the ${counted(recordCount, 'record')} that ${recordCount === 1 ? 'is' : 'are'} present.`,\n hint:\n declaredRecordCount > recordCount\n ? 'The recording looks truncated. It may have been cut short or copied incompletely.'\n : 'The file is longer than its header claims.',\n });\n }\n\n if (trailingBytes > 0) {\n diagnostics.push({\n code: 'TRAILING_BYTES',\n severity: 'warning',\n message: `${counted(trailingBytes, 'byte')} after the last complete data record ${trailingBytes === 1 ? 'was' : 'were'} ignored.`,\n });\n }\n\n const isEdfPlus = continuity !== null;\n if (continuity === 'EDF+D') {\n diagnostics.push({\n code: 'DISCONTINUOUS',\n severity: 'warning',\n message:\n `This is a discontinuous (${isBdf ? 'BDF+D' : 'EDF+D'}) recording: its data records are ` +\n `not contiguous in time.`,\n hint: 'Each row carries its true recording time, so gaps stay visible instead of being closed.',\n });\n }\n\n const dataSignals = signals.filter((s) => !s.isAnnotations);\n if (dataSignals.length === 0) {\n diagnostics.push({\n code: 'NO_SIGNAL_CHANNELS',\n severity: 'warning',\n message: 'This file has no signal channels; it contains only EDF+ annotations.',\n });\n }\n\n // A channel declaring zero samples per record has no sampling rate to speak of — it is\n // reported separately as NO_SAMPLES and no file is written for it. Counting its nominal\n // 0 Hz as a rate made a single-rate recording warn that it used \"2 different sampling\n // rates (4 Hz, 0 Hz)\" and claim it was splitting output it never split.\n const rates = new Set(dataSignals.filter((s) => s.samplesPerRecord > 0).map((s) => s.samplingRate));\n if (rates.size > 1) {\n diagnostics.push({\n code: 'MIXED_SAMPLING_RATES',\n severity: 'warning',\n message:\n `Channels use ${rates.size} different sampling rates ` +\n `(${listed(formatRates([...rates].sort((a, b) => b - a)).map((r) => `${r} Hz`))}).`,\n hint: 'They are written to one file per rate so no channel is resampled.',\n });\n }\n\n return {\n header: {\n version,\n patientId,\n recordingId,\n startDateRaw,\n startTimeRaw,\n startDateTime: resolveStartDateTime(startDateRaw, startTimeRaw, recordingId),\n headerBytes: expectedHeaderBytes,\n declaredHeaderBytes: headerBytes,\n reserved,\n isEdfPlus,\n isBdf,\n continuity,\n declaredRecordCount,\n recordDuration,\n signalCount,\n signals,\n bytesPerSample,\n recordBytes,\n },\n recordCount,\n trailingBytes,\n diagnostics,\n };\n}\n\n/**\n * The recording start as a zone-less wall clock, \"YYYY-MM-DDTHH:MM:SS\".\n *\n * EDF stores the start time as local wall-clock digits with no timezone anywhere in\n * the format. `startDateTime` is built with Date.UTC purely so those digits survive a\n * round trip unshifted, which makes it a carrier for the wall clock rather than a\n * real instant. Serialising it with `toISOString()` would append a Z and assert UTC,\n * and any reader converting to local time would then shift the recording by their own\n * offset: 13:43:04 in the file becomes 08:43:04 in New York. The Z is omitted because\n * the file genuinely does not say which zone it meant.\n */\nexport function formatWallClock(date: Date | null): string | null {\n if (!date) return null;\n return date.toISOString().slice(0, 19);\n}\n\n/**\n * The recording's format, as `--info`, `metadata.json` and `--json` all name it.\n *\n * `\"EDF\"`, `\"BDF\"`, or one of `\"EDF+ (continuous)\"`, `\"EDF+ (discontinuous)\"`,\n * `\"BDF+ (continuous)\"`, `\"BDF+ (discontinuous)\"`. A BDF+ file reports its own spelling even\n * though `continuity` normalises the marker to the `EDF+` form.\n *\n * This said `EDF+ (EDF+D)` and `BDF+ (EDF+C)`, which are not strings it can return — the\n * parenthetical is the word, not the marker. It is a one-line doc comment on a public export,\n * so it is what a TypeScript consumer's editor shows and what `dist/edf/header.d.ts` ships,\n * and the value it describes is `recording.format` in every metadata.json this tool writes.\n * A consumer branching on the tooltip's spelling never matches. Every documentation page had\n * it right; this was the only place that did not.\n */\nexport function describeFormat(header: EdfHeader): string {\n const base = header.isBdf ? 'BDF' : 'EDF';\n if (!header.isEdfPlus) return base;\n return `${base}+ (${header.continuity === 'EDF+D' ? 'discontinuous' : 'continuous'})`;\n}\n\n/** Render a sampling rate without trailing noise: 256, 0.5, 12.5. */\nexport function formatRate(hz: number): string {\n if (Number.isInteger(hz)) {\n /*\n The same six decimals, in the notation `toFixed` cannot reach.\n\n Every double past 2^53 is an integer, so this branch takes every large rate — and\n `String` switches to exponent form at 1e21 and carries the full seventeen digits with\n it. Four samples in a record of 1e-300s is 3.9999999999999996e+300, which is exactly the\n float noise the rounding below exists to remove, printed in a `RATE` column of otherwise\n plain numbers and pasted into an output filename by `rateSlug`. Below 1e21 `String` is\n already exact and is left alone, so an integer rate a file can really state — 2^53\n samples in a second — is not rounded to something it is not.\n */\n const text = String(hz);\n return text.includes('e') ? String(Number(hz.toExponential(6))) : text;\n }\n const rounded = Number(hz.toFixed(6));\n // A rate below 5e-7 rounds away to \"0\", which reads as \"this channel has no sampling\n // rate\" and made the mixed-rate warning contradict itself: it announced two different\n // rates and then printed both as \"0 Hz\". Exponent form keeps a real rate legible, and\n // keeps distinct rates distinct in the channel table and in output filenames.\n if (rounded === 0) return hz.toExponential(3);\n return String(rounded);\n}\n\n/**\n * Renders a group of rates so that rates which differ read as differing.\n *\n * `formatRate` rounds to six decimals, which is what keeps an ordinary rate free of\n * float noise — 30 samples in a 0.1-second record is 299.99999999999994 as a double,\n * and belongs on screen as 300. Two rates separated by less than that round to one\n * string, so a file carrying 1e-6 Hz and 1.25e-6 Hz warned that it used \"2 different\n * sampling rates (0.000001 Hz, 0.000001 Hz)\" and named both files the same thing.\n *\n * That is the contradiction the exponent fallback above already removes for rates that\n * round away to zero; this is the same one a step further out. On a collision every rate\n * in the group switches to its shortest exact form, which is unique for distinct values,\n * rather than only the pair that collided — one column in one notation reads better than\n * two.\n */\nexport function formatRates(rates: readonly number[]): string[] {\n const rounded = rates.map(formatRate);\n const distinct = new Set(rates).size;\n return new Set(rounded).size === distinct ? rounded : rates.map((hz) => String(hz));\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "edf2csv",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.220",
|
|
4
4
|
"description": "Convert EDF, EDF+ and BDF biosignal recordings (European Data Format) to CSV from the command line. Local, streaming, and never resamples or alters units.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"edf",
|