edf2csv 0.7.93 → 0.7.95
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/channels.js
CHANGED
|
@@ -127,6 +127,21 @@ export function selectChannels(signals, terms) {
|
|
|
127
127
|
}
|
|
128
128
|
const chosen = new Map();
|
|
129
129
|
const ambiguous = [];
|
|
130
|
+
/*
|
|
131
|
+
A file may have no signal channels at all, and both position errors below assumed it had
|
|
132
|
+
some. `listed([])` is the empty string, so `--channels "#0"` on an annotations-only
|
|
133
|
+
recording — one of this tool's own fixtures — was refused with
|
|
134
|
+
|
|
135
|
+
No channel at position #0. This file has signal channels at .
|
|
136
|
+
|
|
137
|
+
a sentence that states there are channels and then names none, ending mid-clause. The
|
|
138
|
+
conversion already raises NO_SIGNAL_CHANNELS for this file and says what it is, so the
|
|
139
|
+
fact was known one layer up; the message that a `--channels` user actually reaches was
|
|
140
|
+
the one that did not have it.
|
|
141
|
+
*/
|
|
142
|
+
const positions = candidates.length === 0
|
|
143
|
+
? 'This file has no signal channels; it contains only annotations.'
|
|
144
|
+
: `This file has signal channels at ${listed(candidates.map((s) => `#${s.index}`))}.`;
|
|
130
145
|
for (const rawTerm of terms) {
|
|
131
146
|
const term = rawTerm.trim();
|
|
132
147
|
if (term === '')
|
|
@@ -148,13 +163,12 @@ export function selectChannels(signals, terms) {
|
|
|
148
163
|
const position = term.slice(1);
|
|
149
164
|
if (!/^\d+$/u.test(position)) {
|
|
150
165
|
throw new ChannelSelectionError(`"${term}" is not a channel position: a position is #0, #1, #2 and so on.\n` +
|
|
151
|
-
|
|
166
|
+
positions);
|
|
152
167
|
}
|
|
153
168
|
const index = Number(position);
|
|
154
169
|
const signal = candidates.find((s) => s.index === index);
|
|
155
170
|
if (!signal) {
|
|
156
|
-
throw new ChannelSelectionError(`No channel at position ${term}.
|
|
157
|
-
`${listed(candidates.map((s) => `#${s.index}`))}.`);
|
|
171
|
+
throw new ChannelSelectionError(`No channel at position ${term}. ${positions}`);
|
|
158
172
|
}
|
|
159
173
|
chosen.set(signal.index, signal);
|
|
160
174
|
continue;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"channels.js","sourceRoot":"","sources":["../../src/convert/channels.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAE3C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,QAAQ,CAAC;AAEpC,MAAM,OAAO,qBAAsB,SAAQ,KAAK;IAC9C,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,uBAAuB,CAAC;IACtC,CAAC;CACF;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,gBAAgB,CAAC,OAA6B;IAC5D,MAAM,MAAM,GAAG,IAAI,GAAG,EAAkB,CAAC;IACzC,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,MAAM,CAAC,aAAa;YAAE,SAAS;QACnC,MAAM,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC;QAC9B,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IAChD,CAAC;IAED,MAAM,KAAK,GAAG,IAAI,GAAG,EAAkB,CAAC;IACxC,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,MAAM,CAAC,aAAa;YAAE,SAAS;QACnC,MAAM,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC;QAC9B,MAAM,UAAU,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;QAC/C,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,UAAU,CAAC,C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AC;QACf,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACnC,MAAM,IAAI,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,UAAU,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YACjE,OAAO,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,CACnB,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,EACzB,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,EACtB,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,IAAI,CAC9B,CAAC;QACJ,CAAC;QACD,MAAM,IAAI,GAAG,QAAQ,CAAC;QACtB,QAAQ,GAAG,OAAO,CAAC;QACnB,OAAO,GAAG,IAAI,CAAC;IACjB,CAAC;IACD,OAAO,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AACjC,CAAC","sourcesContent":["/**\n * Channel naming and selection.\n *\n * Two real-world facts drive this module. EDF labels are free text that routinely\n * contain spaces and punctuation (\"EEG Fpz-Cz\"), and they are not guaranteed to be\n * unique — CHB-MIT recordings ship two channels both labelled \"T8-P8\", and some\n * carry a channel labelled \"-\". Labels are therefore preserved verbatim in output,\n * and only disambiguated when the file itself is ambiguous.\n */\n\nimport type { EdfSignal } from '../edf/header.js';\nimport { listed } from '../format/list.js';\n\n/**\n * The name of the column the writer puts in front of the channels, which no channel may take.\n *\n * Exported and used by the writer rather than repeated there, because the whole point of\n * reserving it here is that the two cannot drift apart.\n */\nexport const TIME_COLUMN = 'time_s';\n\nexport class ChannelSelectionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ChannelSelectionError';\n }\n}\n\n/**\n * Column name for a signal.\n *\n * Names are derived from the whole file, not from the current selection, so a given\n * channel always produces the same column regardless of which channels were asked\n * for. Duplicated labels get a `_ch<index>` suffix pointing at their position in\n * the file, which is the only thing that reliably tells them apart.\n */\nexport function buildColumnNames(signals: readonly EdfSignal[]): Map<number, string> {\n const counts = new Map<string, number>();\n for (const signal of signals) {\n if (signal.isAnnotations) continue;\n const base = baseName(signal);\n counts.set(base, (counts.get(base) ?? 0) + 1);\n }\n\n const names = new Map<number, string>();\n for (const signal of signals) {\n if (signal.isAnnotations) continue;\n const base = baseName(signal);\n const duplicated = (counts.get(base) ?? 0) > 1;\n names.set(signal.index, duplicated ? `${base}_ch${signal.index}` : base);\n }\n\n /*\n The suffix has to be checked against the file, not only against the label it disambiguates.\n\n Counting collisions on the raw label alone made the suffix a guess: `_ch<index>` is unique\n among the channels sharing that label, and nothing stopped it from landing on a label some\n other channel already had. A file labelled T8, T8, T8_ch0 — all three legal, since EDF\n labels are free text and nothing enforces uniqueness — produced\n\n time_s,T8_ch0,T8_ch1,T8_ch0\n\n two columns with one name, while the warning beside it said the suffix kept them\n \"distinguishable\". channels.csv listed the same name against two signal indices, so the\n join it exists for could not resolve it either, and `df[\"T8_ch0\"]` in pandas or R returns\n one of the two with nothing to say which.\n\n Anything still shared after the first pass takes its own position as well. That is unique\n by construction, so the loop settles immediately in practice; the bound is there because\n a second round could in principle land on yet another literal label.\n\n The time column counts as taken, for the same reason. It is a name this file does not\n supply and the writer does, and a channel labelled `time_s` collided with it in silence:\n the header came out `time_s,time_s,ECG`, channels.csv named the channel's column `time_s`,\n and every read-back the documentation gives — `index_col=\"time_s\"`, `pop(\"time_s\")`,\n `pivot(index=\"time_s\")` — resolves that to one of the two columns without saying which.\n pandas and Python's own `csv.DictReader` resolve it opposite ways round.\n */\n for (let round = 0; round < 8; round++) {\n const taken = new Map<string, number>([[TIME_COLUMN, 1]]);\n for (const name of names.values()) taken.set(name, (taken.get(name) ?? 0) + 1);\n\n const clashing = [...names].filter(([, name]) => (taken.get(name) ?? 0) > 1);\n if (clashing.length === 0) break;\n for (const [index, name] of clashing) names.set(index, `${name}_ch${index}`);\n }\n return names;\n}\n\nfunction baseName(signal: EdfSignal): string {\n return signal.label === '' ? `signal_${signal.index}` : signal.label;\n}\n\n/**\n * Channels whose column name was pushed off their own label to keep the header unique.\n *\n * A channel genuinely labelled `T8_ch0` loses that name when another label's disambiguating\n * suffix wants it, and the resulting column is the one thing in the output that no longer\n * matches the file. Silence there is what made the collision hard to see in the first place:\n * the only warning raised was about the *other* label.\n */\nexport function renamedByCollision(\n signals: readonly EdfSignal[],\n columnNames: ReadonlyMap<number, string>,\n): EdfSignal[] {\n const counts = new Map<string, number>();\n for (const signal of signals) {\n if (signal.isAnnotations) continue;\n const base = baseName(signal);\n counts.set(base, (counts.get(base) ?? 0) + 1);\n }\n return signals.filter(\n (signal) =>\n !signal.isAnnotations &&\n (counts.get(baseName(signal)) ?? 0) === 1 &&\n columnNames.get(signal.index) !== baseName(signal),\n );\n}\n\nexport interface ChannelSelection {\n signals: EdfSignal[];\n /** Labels that matched more than one channel, so the user knows why they got extras. */\n ambiguous: { term: string; matched: EdfSignal[] }[];\n}\n\n/**\n * Resolve a `--channels` specification against the file's signals.\n *\n * Matching is case-insensitive on the exact label, with `#<index>` available to\n * address a specific channel when labels collide. A term that matches nothing is an\n * error rather than a silent omission: quietly dropping a requested channel would\n * hand the user a CSV that is missing data they explicitly asked for.\n */\nexport function selectChannels(signals: readonly EdfSignal[], terms: readonly string[]): ChannelSelection {\n const candidates = signals.filter((s) => !s.isAnnotations);\n const byLabel = new Map<string, EdfSignal[]>();\n for (const signal of candidates) {\n const key = signal.label.toLowerCase();\n const bucket = byLabel.get(key);\n if (bucket) bucket.push(signal);\n else byLabel.set(key, [signal]);\n }\n\n const chosen = new Map<number, EdfSignal>();\n const ambiguous: { term: string; matched: EdfSignal[] }[] = [];\n\n for (const rawTerm of terms) {\n const term = rawTerm.trim();\n if (term === '') continue;\n\n // '#N' addresses a channel by position, but a label may literally be \"#5\".\n // A real label always wins, so no channel becomes unreachable.\n const literal = byLabel.get(term.toLowerCase());\n if (term.startsWith('#') && (!literal || literal.length === 0)) {\n /*\n A position must be written in plain digits.\n\n `Number()` was doing the parsing, and it accepts a great deal more than a position:\n `#0x2` reached channel 2 through hex, `#0b1` channel 1 through binary, `#1e0` and\n `#2.0` and `# 2` all landed somewhere, and `#` on its own became `Number('')`, which\n is 0. Every one of them selected a channel and exited 0, so a slip did not fail —\n it quietly converted a different channel than the one asked for, which for this tool\n is the worst way to be wrong.\n */\n const position = term.slice(1);\n if (!/^\\d+$/u.test(position)) {\n throw new ChannelSelectionError(\n `\"${term}\" is not a channel position: a position is #0, #1, #2 and so on.\\n` +\n `This file has signal channels at ${listed(candidates.map((s) => `#${s.index}`))}.`,\n );\n }\n const index = Number(position);\n const signal = candidates.find((s) => s.index === index);\n if (!signal) {\n throw new ChannelSelectionError(\n `No channel at position ${term}. This file has signal channels at ` +\n `${listed(candidates.map((s) => `#${s.index}`))}.`,\n );\n }\n chosen.set(signal.index, signal);\n continue;\n }\n\n const matched = byLabel.get(term.toLowerCase());\n if (!matched || matched.length === 0) {\n /*\n The one term that is certainly not a typo: a column name.\n\n Matching is on the label, and where a label collides the column gains a `_ch<index>`\n suffix — so `T8-P8_ch1` is a name this tool invented, prints in the COLUMN column of\n --info, writes into channels.csv and puts at the head of signals.csv, and then\n rejects with \"No channel named \"T8-P8_ch1\". Run with --info to list the channels in\n this file\", which is where the user copied it from. The reference documents the trap;\n the message a user actually hits did not.\n\n Answered where it is asked instead, and with the thing that works: `#<index>` selects\n one channel of a colliding pair, which is exactly what someone reaching for the\n suffixed column name wants and the only way to get it.\n */\n const columns = buildColumnNames(candidates);\n const owner = candidates.find(\n (signal) => (columns.get(signal.index) ?? '').toLowerCase() === term.toLowerCase(),\n );\n if (owner) {\n // A channel with no label at all gets the column `signal_<index>`, and offering its\n // label back would be offering `\"\"` — there is nothing to type. Position is the only\n // way to reach it, and saying so is more use than quoting an empty string twice.\n throw new ChannelSelectionError(\n owner.label === ''\n ? `\"${term}\" is a column name, not a channel name: --channels matches the label, ` +\n `and this channel has none.\\n` +\n `Use \"#${owner.index}\" — a channel with no label can only be addressed by position.`\n : `\"${term}\" is a column name, not a channel name: --channels matches the label, ` +\n `which for this channel is \"${owner.label}\".\\n` +\n (typeable(owner.label) === null\n ? `Use \"#${owner.index}\" — ${untypeableBecause(owner.label)}, so position is ` +\n `the only way to reach it.`\n : `Use \"#${owner.index}\" to select just this one, or ${typeable(owner.label)} ` +\n `for every channel sharing that label.`),\n );\n }\n /*\n The annotation channel is a channel, and this said the file had none by that name.\n\n `EDF Annotations` is a label the file really carries — the spec reserves it, --info\n counts it on the \"Channels\" line, and it is the name anyone reading about EDF+ meets\n first. Asking for it got \"No channel named \"EDF Annotations\". Run with --info to list\n the channels in this file\", which is false about the file and points at a table that\n does not list it either, so following the advice returns the reader to the same\n message. What they were after is already being written: every conversion of a file\n with this channel writes annotations.csv from it.\n */\n const asAnnotations = signals.find(\n (signal) => signal.isAnnotations && signal.label.toLowerCase() === term.toLowerCase(),\n );\n if (asAnnotations) {\n throw new ChannelSelectionError(\n `\"${term}\" is this recording's annotation channel, not a signal: it holds event ` +\n `text rather than samples, so it has no column to select.\\n` +\n `Its events are already written to annotations.csv by any conversion of this ` +\n `file — pass --annotations-only for those and no signal data.`,\n );\n }\n throw new ChannelSelectionError(\n `No channel named \"${term}\".${suggest(term, candidates)}\\n` +\n `Run with --info to list the channels in this file.`,\n );\n }\n if (matched.length > 1) ambiguous.push({ term, matched: [...matched] });\n for (const signal of matched) chosen.set(signal.index, signal);\n }\n\n const selected = [...chosen.values()].sort((a, b) => a.index - b.index);\n if (selected.length === 0) {\n throw new ChannelSelectionError('No channels were selected.');\n }\n return { signals: selected, ambiguous };\n}\n\nfunction suggest(term: string, candidates: readonly EdfSignal[]): string {\n // Duplicated labels would otherwise be suggested twice, which reads like two\n // different options while naming the same thing.\n const unique = [...new Set(candidates.map((s) => s.label))];\n const scored = unique\n .map((label) => ({ label, distance: editDistance(term.toLowerCase(), label.toLowerCase()) }))\n .filter((c) => c.label !== '' && c.distance <= Math.max(2, Math.floor(term.length / 3)))\n .sort((a, b) => a.distance - b.distance);\n if (scored.length === 0) return '';\n /*\n A suggestion is something to retype, so it has to be retypeable.\n\n `Did you mean \"EEG \"A1\"\"?` collapses in a shell to `EEG A1`, which this then rejects with\n the same sentence and the same suggestion — a loop the reader cannot get out of by doing\n what it says. Same failure the header parser's `--channels` advice was fixed for in\n 0.7.18, and the branch above it here; a label carrying `$` or a backtick is the same thing\n again, since a shell expands both inside double quotes.\n\n Where nothing can be typed — a label with a comma, which --channels splits after the shell\n has finished with it, or one with a control byte in it — the position is offered instead.\n It is not the name they asked about, but it is the answer to what they wanted.\n */\n /*\n Cut to three, and the rest counted rather than dropped.\n\n `.slice(0, 3)` said nothing about what it left. On a recording with channels ECG1 to ECG5,\n `--channels ECG` is one edit from all five and the answer was `Did you mean \"ECG1\", \"ECG2\",\n \"ECG3\"?` — three of five equally good answers, with nothing to say the list was cut. A\n reader has no way to tell ECG4 from a channel that does not exist, and this sentence is the\n only place the tool offers to tell them what does.\n\n Through `listed`, which every other list in a sentence goes through: it counts what it\n leaves, and shows a fourth item rather than hiding it behind a phrase longer than the item.\n */\n const offered = scored.map((c) => typeable(c.label) ?? `\"#${positionOf(c.label, candidates)}\"`);\n return ` Did you mean ${listed(offered, 3)}?`;\n}\n\n/** The first channel carrying this label, for a suggestion that cannot be made by name. */\nfunction positionOf(label: string, candidates: readonly EdfSignal[]): number {\n return candidates.find((signal) => signal.label === label)?.index ?? 0;\n}\n\n/**\n * The label written so that typing it back selects this channel, or null when nothing does.\n *\n * Double quotes wherever they survive, since they also show where the label begins and ends\n * and every documented example is written that way. They do not survive a label containing a\n * quote of their own, and — less obviously — a shell still expands `$`, a backtick and a\n * backslash inside them, so `EEG $ref` would arrive as `EEG ` with nothing said. Those go in\n * single quotes, the one POSIX form with no escapes inside it, where a single quote in the\n * label closes, escapes and reopens.\n *\n * Two labels have no form at all. `--channels` splits its list on commas after the shell has\n * finished quoting, so no quoting reaches a label with one in it; and a control character\n * cannot be typed. Both take a position instead, which is what NONPRINTABLE_LABEL already\n * says for the same two reasons.\n */\nexport function typeable(label: string): string | null {\n if (label === '' || label.includes(',')) return null;\n if (/[\\u0000-\\u001f\\u007f-\\u009f]/u.test(label)) return null;\n if (!/[\"$`\\\\]/u.test(label)) return `\"${label}\"`;\n return `'${label.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\n/** Why a label has no typeable form, for the sentence that offers a position instead. */\nfunction untypeableBecause(label: string): string {\n if (label.includes(',')) return 'a comma in the label would read as two names';\n return 'the label cannot be typed';\n}\n\n/** Levenshtein distance, two-row variant. */\nfunction editDistance(a: string, b: string): number {\n if (a === b) return 0;\n if (a.length === 0) return b.length;\n if (b.length === 0) return a.length;\n\n let previous = Array.from({ length: b.length + 1 }, (_, i) => i);\n let current = new Array<number>(b.length + 1).fill(0);\n\n for (let i = 1; i <= a.length; i++) {\n current[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;\n current[j] = Math.min(\n (current[j - 1] ?? 0) + 1,\n (previous[j] ?? 0) + 1,\n (previous[j - 1] ?? 0) + cost,\n );\n }\n const swap = previous;\n previous = current;\n current = swap;\n }\n return previous[b.length] ?? 0;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"channels.js","sourceRoot":"","sources":["../../src/convert/channels.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAE3C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,QAAQ,CAAC;AAEpC,MAAM,OAAO,qBAAsB,SAAQ,KAAK;IAC9C,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CA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I,CAAC,CAAC,GAAG,CAAC,EACzB,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,EACtB,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,IAAI,CAC9B,CAAC;QACJ,CAAC;QACD,MAAM,IAAI,GAAG,QAAQ,CAAC;QACtB,QAAQ,GAAG,OAAO,CAAC;QACnB,OAAO,GAAG,IAAI,CAAC;IACjB,CAAC;IACD,OAAO,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AACjC,CAAC","sourcesContent":["/**\n * Channel naming and selection.\n *\n * Two real-world facts drive this module. EDF labels are free text that routinely\n * contain spaces and punctuation (\"EEG Fpz-Cz\"), and they are not guaranteed to be\n * unique — CHB-MIT recordings ship two channels both labelled \"T8-P8\", and some\n * carry a channel labelled \"-\". Labels are therefore preserved verbatim in output,\n * and only disambiguated when the file itself is ambiguous.\n */\n\nimport type { EdfSignal } from '../edf/header.js';\nimport { listed } from '../format/list.js';\n\n/**\n * The name of the column the writer puts in front of the channels, which no channel may take.\n *\n * Exported and used by the writer rather than repeated there, because the whole point of\n * reserving it here is that the two cannot drift apart.\n */\nexport const TIME_COLUMN = 'time_s';\n\nexport class ChannelSelectionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ChannelSelectionError';\n }\n}\n\n/**\n * Column name for a signal.\n *\n * Names are derived from the whole file, not from the current selection, so a given\n * channel always produces the same column regardless of which channels were asked\n * for. Duplicated labels get a `_ch<index>` suffix pointing at their position in\n * the file, which is the only thing that reliably tells them apart.\n */\nexport function buildColumnNames(signals: readonly EdfSignal[]): Map<number, string> {\n const counts = new Map<string, number>();\n for (const signal of signals) {\n if (signal.isAnnotations) continue;\n const base = baseName(signal);\n counts.set(base, (counts.get(base) ?? 0) + 1);\n }\n\n const names = new Map<number, string>();\n for (const signal of signals) {\n if (signal.isAnnotations) continue;\n const base = baseName(signal);\n const duplicated = (counts.get(base) ?? 0) > 1;\n names.set(signal.index, duplicated ? `${base}_ch${signal.index}` : base);\n }\n\n /*\n The suffix has to be checked against the file, not only against the label it disambiguates.\n\n Counting collisions on the raw label alone made the suffix a guess: `_ch<index>` is unique\n among the channels sharing that label, and nothing stopped it from landing on a label some\n other channel already had. A file labelled T8, T8, T8_ch0 — all three legal, since EDF\n labels are free text and nothing enforces uniqueness — produced\n\n time_s,T8_ch0,T8_ch1,T8_ch0\n\n two columns with one name, while the warning beside it said the suffix kept them\n \"distinguishable\". channels.csv listed the same name against two signal indices, so the\n join it exists for could not resolve it either, and `df[\"T8_ch0\"]` in pandas or R returns\n one of the two with nothing to say which.\n\n Anything still shared after the first pass takes its own position as well. That is unique\n by construction, so the loop settles immediately in practice; the bound is there because\n a second round could in principle land on yet another literal label.\n\n The time column counts as taken, for the same reason. It is a name this file does not\n supply and the writer does, and a channel labelled `time_s` collided with it in silence:\n the header came out `time_s,time_s,ECG`, channels.csv named the channel's column `time_s`,\n and every read-back the documentation gives — `index_col=\"time_s\"`, `pop(\"time_s\")`,\n `pivot(index=\"time_s\")` — resolves that to one of the two columns without saying which.\n pandas and Python's own `csv.DictReader` resolve it opposite ways round.\n */\n for (let round = 0; round < 8; round++) {\n const taken = new Map<string, number>([[TIME_COLUMN, 1]]);\n for (const name of names.values()) taken.set(name, (taken.get(name) ?? 0) + 1);\n\n const clashing = [...names].filter(([, name]) => (taken.get(name) ?? 0) > 1);\n if (clashing.length === 0) break;\n for (const [index, name] of clashing) names.set(index, `${name}_ch${index}`);\n }\n return names;\n}\n\nfunction baseName(signal: EdfSignal): string {\n return signal.label === '' ? `signal_${signal.index}` : signal.label;\n}\n\n/**\n * Channels whose column name was pushed off their own label to keep the header unique.\n *\n * A channel genuinely labelled `T8_ch0` loses that name when another label's disambiguating\n * suffix wants it, and the resulting column is the one thing in the output that no longer\n * matches the file. Silence there is what made the collision hard to see in the first place:\n * the only warning raised was about the *other* label.\n */\nexport function renamedByCollision(\n signals: readonly EdfSignal[],\n columnNames: ReadonlyMap<number, string>,\n): EdfSignal[] {\n const counts = new Map<string, number>();\n for (const signal of signals) {\n if (signal.isAnnotations) continue;\n const base = baseName(signal);\n counts.set(base, (counts.get(base) ?? 0) + 1);\n }\n return signals.filter(\n (signal) =>\n !signal.isAnnotations &&\n (counts.get(baseName(signal)) ?? 0) === 1 &&\n columnNames.get(signal.index) !== baseName(signal),\n );\n}\n\nexport interface ChannelSelection {\n signals: EdfSignal[];\n /** Labels that matched more than one channel, so the user knows why they got extras. */\n ambiguous: { term: string; matched: EdfSignal[] }[];\n}\n\n/**\n * Resolve a `--channels` specification against the file's signals.\n *\n * Matching is case-insensitive on the exact label, with `#<index>` available to\n * address a specific channel when labels collide. A term that matches nothing is an\n * error rather than a silent omission: quietly dropping a requested channel would\n * hand the user a CSV that is missing data they explicitly asked for.\n */\nexport function selectChannels(signals: readonly EdfSignal[], terms: readonly string[]): ChannelSelection {\n const candidates = signals.filter((s) => !s.isAnnotations);\n const byLabel = new Map<string, EdfSignal[]>();\n for (const signal of candidates) {\n const key = signal.label.toLowerCase();\n const bucket = byLabel.get(key);\n if (bucket) bucket.push(signal);\n else byLabel.set(key, [signal]);\n }\n\n const chosen = new Map<number, EdfSignal>();\n const ambiguous: { term: string; matched: EdfSignal[] }[] = [];\n /*\n A file may have no signal channels at all, and both position errors below assumed it had\n some. `listed([])` is the empty string, so `--channels \"#0\"` on an annotations-only\n recording — one of this tool's own fixtures — was refused with\n\n No channel at position #0. This file has signal channels at .\n\n a sentence that states there are channels and then names none, ending mid-clause. The\n conversion already raises NO_SIGNAL_CHANNELS for this file and says what it is, so the\n fact was known one layer up; the message that a `--channels` user actually reaches was\n the one that did not have it.\n */\n const positions =\n candidates.length === 0\n ? 'This file has no signal channels; it contains only annotations.'\n : `This file has signal channels at ${listed(candidates.map((s) => `#${s.index}`))}.`;\n\n for (const rawTerm of terms) {\n const term = rawTerm.trim();\n if (term === '') continue;\n\n // '#N' addresses a channel by position, but a label may literally be \"#5\".\n // A real label always wins, so no channel becomes unreachable.\n const literal = byLabel.get(term.toLowerCase());\n if (term.startsWith('#') && (!literal || literal.length === 0)) {\n /*\n A position must be written in plain digits.\n\n `Number()` was doing the parsing, and it accepts a great deal more than a position:\n `#0x2` reached channel 2 through hex, `#0b1` channel 1 through binary, `#1e0` and\n `#2.0` and `# 2` all landed somewhere, and `#` on its own became `Number('')`, which\n is 0. Every one of them selected a channel and exited 0, so a slip did not fail —\n it quietly converted a different channel than the one asked for, which for this tool\n is the worst way to be wrong.\n */\n const position = term.slice(1);\n if (!/^\\d+$/u.test(position)) {\n throw new ChannelSelectionError(\n `\"${term}\" is not a channel position: a position is #0, #1, #2 and so on.\\n` +\n positions,\n );\n }\n const index = Number(position);\n const signal = candidates.find((s) => s.index === index);\n if (!signal) {\n throw new ChannelSelectionError(\n `No channel at position ${term}. ${positions}`,\n );\n }\n chosen.set(signal.index, signal);\n continue;\n }\n\n const matched = byLabel.get(term.toLowerCase());\n if (!matched || matched.length === 0) {\n /*\n The one term that is certainly not a typo: a column name.\n\n Matching is on the label, and where a label collides the column gains a `_ch<index>`\n suffix — so `T8-P8_ch1` is a name this tool invented, prints in the COLUMN column of\n --info, writes into channels.csv and puts at the head of signals.csv, and then\n rejects with \"No channel named \"T8-P8_ch1\". Run with --info to list the channels in\n this file\", which is where the user copied it from. The reference documents the trap;\n the message a user actually hits did not.\n\n Answered where it is asked instead, and with the thing that works: `#<index>` selects\n one channel of a colliding pair, which is exactly what someone reaching for the\n suffixed column name wants and the only way to get it.\n */\n const columns = buildColumnNames(candidates);\n const owner = candidates.find(\n (signal) => (columns.get(signal.index) ?? '').toLowerCase() === term.toLowerCase(),\n );\n if (owner) {\n // A channel with no label at all gets the column `signal_<index>`, and offering its\n // label back would be offering `\"\"` — there is nothing to type. Position is the only\n // way to reach it, and saying so is more use than quoting an empty string twice.\n throw new ChannelSelectionError(\n owner.label === ''\n ? `\"${term}\" is a column name, not a channel name: --channels matches the label, ` +\n `and this channel has none.\\n` +\n `Use \"#${owner.index}\" — a channel with no label can only be addressed by position.`\n : `\"${term}\" is a column name, not a channel name: --channels matches the label, ` +\n `which for this channel is \"${owner.label}\".\\n` +\n (typeable(owner.label) === null\n ? `Use \"#${owner.index}\" — ${untypeableBecause(owner.label)}, so position is ` +\n `the only way to reach it.`\n : `Use \"#${owner.index}\" to select just this one, or ${typeable(owner.label)} ` +\n `for every channel sharing that label.`),\n );\n }\n /*\n The annotation channel is a channel, and this said the file had none by that name.\n\n `EDF Annotations` is a label the file really carries — the spec reserves it, --info\n counts it on the \"Channels\" line, and it is the name anyone reading about EDF+ meets\n first. Asking for it got \"No channel named \"EDF Annotations\". Run with --info to list\n the channels in this file\", which is false about the file and points at a table that\n does not list it either, so following the advice returns the reader to the same\n message. What they were after is already being written: every conversion of a file\n with this channel writes annotations.csv from it.\n */\n const asAnnotations = signals.find(\n (signal) => signal.isAnnotations && signal.label.toLowerCase() === term.toLowerCase(),\n );\n if (asAnnotations) {\n throw new ChannelSelectionError(\n `\"${term}\" is this recording's annotation channel, not a signal: it holds event ` +\n `text rather than samples, so it has no column to select.\\n` +\n `Its events are already written to annotations.csv by any conversion of this ` +\n `file — pass --annotations-only for those and no signal data.`,\n );\n }\n throw new ChannelSelectionError(\n `No channel named \"${term}\".${suggest(term, candidates)}\\n` +\n `Run with --info to list the channels in this file.`,\n );\n }\n if (matched.length > 1) ambiguous.push({ term, matched: [...matched] });\n for (const signal of matched) chosen.set(signal.index, signal);\n }\n\n const selected = [...chosen.values()].sort((a, b) => a.index - b.index);\n if (selected.length === 0) {\n throw new ChannelSelectionError('No channels were selected.');\n }\n return { signals: selected, ambiguous };\n}\n\nfunction suggest(term: string, candidates: readonly EdfSignal[]): string {\n // Duplicated labels would otherwise be suggested twice, which reads like two\n // different options while naming the same thing.\n const unique = [...new Set(candidates.map((s) => s.label))];\n const scored = unique\n .map((label) => ({ label, distance: editDistance(term.toLowerCase(), label.toLowerCase()) }))\n .filter((c) => c.label !== '' && c.distance <= Math.max(2, Math.floor(term.length / 3)))\n .sort((a, b) => a.distance - b.distance);\n if (scored.length === 0) return '';\n /*\n A suggestion is something to retype, so it has to be retypeable.\n\n `Did you mean \"EEG \"A1\"\"?` collapses in a shell to `EEG A1`, which this then rejects with\n the same sentence and the same suggestion — a loop the reader cannot get out of by doing\n what it says. Same failure the header parser's `--channels` advice was fixed for in\n 0.7.18, and the branch above it here; a label carrying `$` or a backtick is the same thing\n again, since a shell expands both inside double quotes.\n\n Where nothing can be typed — a label with a comma, which --channels splits after the shell\n has finished with it, or one with a control byte in it — the position is offered instead.\n It is not the name they asked about, but it is the answer to what they wanted.\n */\n /*\n Cut to three, and the rest counted rather than dropped.\n\n `.slice(0, 3)` said nothing about what it left. On a recording with channels ECG1 to ECG5,\n `--channels ECG` is one edit from all five and the answer was `Did you mean \"ECG1\", \"ECG2\",\n \"ECG3\"?` — three of five equally good answers, with nothing to say the list was cut. A\n reader has no way to tell ECG4 from a channel that does not exist, and this sentence is the\n only place the tool offers to tell them what does.\n\n Through `listed`, which every other list in a sentence goes through: it counts what it\n leaves, and shows a fourth item rather than hiding it behind a phrase longer than the item.\n */\n const offered = scored.map((c) => typeable(c.label) ?? `\"#${positionOf(c.label, candidates)}\"`);\n return ` Did you mean ${listed(offered, 3)}?`;\n}\n\n/** The first channel carrying this label, for a suggestion that cannot be made by name. */\nfunction positionOf(label: string, candidates: readonly EdfSignal[]): number {\n return candidates.find((signal) => signal.label === label)?.index ?? 0;\n}\n\n/**\n * The label written so that typing it back selects this channel, or null when nothing does.\n *\n * Double quotes wherever they survive, since they also show where the label begins and ends\n * and every documented example is written that way. They do not survive a label containing a\n * quote of their own, and — less obviously — a shell still expands `$`, a backtick and a\n * backslash inside them, so `EEG $ref` would arrive as `EEG ` with nothing said. Those go in\n * single quotes, the one POSIX form with no escapes inside it, where a single quote in the\n * label closes, escapes and reopens.\n *\n * Two labels have no form at all. `--channels` splits its list on commas after the shell has\n * finished quoting, so no quoting reaches a label with one in it; and a control character\n * cannot be typed. Both take a position instead, which is what NONPRINTABLE_LABEL already\n * says for the same two reasons.\n */\nexport function typeable(label: string): string | null {\n if (label === '' || label.includes(',')) return null;\n if (/[\\u0000-\\u001f\\u007f-\\u009f]/u.test(label)) return null;\n if (!/[\"$`\\\\]/u.test(label)) return `\"${label}\"`;\n return `'${label.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\n/** Why a label has no typeable form, for the sentence that offers a position instead. */\nfunction untypeableBecause(label: string): string {\n if (label.includes(',')) return 'a comma in the label would read as two names';\n return 'the label cannot be typed';\n}\n\n/** Levenshtein distance, two-row variant. */\nfunction editDistance(a: string, b: string): number {\n if (a === b) return 0;\n if (a.length === 0) return b.length;\n if (b.length === 0) return a.length;\n\n let previous = Array.from({ length: b.length + 1 }, (_, i) => i);\n let current = new Array<number>(b.length + 1).fill(0);\n\n for (let i = 1; i <= a.length; i++) {\n current[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;\n current[j] = Math.min(\n (current[j - 1] ?? 0) + 1,\n (previous[j] ?? 0) + 1,\n (previous[j - 1] ?? 0) + cost,\n );\n }\n const swap = previous;\n previous = current;\n current = swap;\n }\n return previous[b.length] ?? 0;\n}\n"]}
|
package/dist/format/number.js
CHANGED
|
@@ -237,6 +237,27 @@ export function formatDuration(seconds) {
|
|
|
237
237
|
// as 59 minutes and 59.9996 seconds and then printed as "59m 60s" — a duration that
|
|
238
238
|
// cannot exist. Rounding first carries the extra second into the minute where it belongs.
|
|
239
239
|
const total = Math.round(seconds * 1000) / 1000;
|
|
240
|
+
/*
|
|
241
|
+
A duration shorter than the rounding is not a duration of zero.
|
|
242
|
+
|
|
243
|
+
Three decimals is the right precision for a recording measured in hours, and it collapses
|
|
244
|
+
everything under half a millisecond to "0s". `repeating-fast.edf` — two records of 1e-15s,
|
|
245
|
+
six samples, one of this repository's own fixtures — printed
|
|
246
|
+
|
|
247
|
+
Duration 0s (2 records of 1e-15s)
|
|
248
|
+
|
|
249
|
+
and refused `--start 0.5` with "is at or past the end of this 0s recording". A reader is
|
|
250
|
+
told the file holds nothing, on the line they look at first, about a file that converts to
|
|
251
|
+
six rows; the record duration two columns over already contradicts it. Same shape as the
|
|
252
|
+
other end of this function, which stops decomposing past 2^53 and prints the seconds
|
|
253
|
+
instead, and as the byte size above, which does not round 1023.999 KB into the next unit.
|
|
254
|
+
|
|
255
|
+
Written through `plain` rather than interpolated, for the reason the comment above gives:
|
|
256
|
+
`${1e-15}` is exponent notation, and the sentence this feeds is one whose whole job is to
|
|
257
|
+
say what `--start` may be given — and `--start 1e-15s` is refused as an unknown unit "e".
|
|
258
|
+
*/
|
|
259
|
+
if (total === 0 && seconds > 0)
|
|
260
|
+
return `${plain(seconds)}s`;
|
|
240
261
|
const h = Math.floor(total / 3600);
|
|
241
262
|
const m = Math.floor((total % 3600) / 60);
|
|
242
263
|
const s = Math.round((total - h * 3600 - m * 60) * 1000) / 1000;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"number.js","sourceRoot":"","sources":["../../src/format/number.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,qFAAqF;AACrF,MAAM,eAAe,GAAG,CAAC,IAAI,EAAE,CAAC;AAyBhC;;;;;;;;GAQG;AACH,MAAM,kBAAkB,GAAG,CAAC,IAAI,EAAE,CAAC;AAEnC,MAAM,UAAU,oBAAoB;IAClC,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,CAAC;AAC3C,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,KAAK,CAAC,KAAa,EAAE,QAAgB;IACnD,qFAAqF;IACrF,oFAAoF;IACpF,mFAAmF;IACnF,iFAAiF;IACjF,gCAAgC;IAChC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,EAAE,CAA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AM,GAAG,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC5C,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAC9B,WAAW,CAAC,MAAM,CAAC,GAAG,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;QAC7E,YAAY,CAAC,MAAM,CAAC,GAAG,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC3D,CAAC;IAED,OAAO,CAAC,WAAmB,EAAE,MAAc,EAAU,EAAE;QACrD;;;;;;UAME;QACF,IACE,MAAM,GAAG,CAAC;YACV,MAAM,IAAI,gBAAgB;YAC1B,CAAC,MAAM,CAAC,SAAS,CAAC,WAAW,CAAC;YAC9B,WAAW,GAAG,CAAC,EACf,CAAC;YACD,OAAO,MAAM,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;QACrC,CAAC;QACD,MAAM,KAAK,GAAG,WAAW,GAAI,WAAW,CAAC,MAAM,CAAY,CAAC;QAC5D;;;;;;;;;;;;UAYE;QACF,IAAI,KAAK,IAAI,IAAI;YAAE,OAAO,MAAM,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;QACtD,OAAO,GAAG,KAAK,GAAG,YAAY,CAAC,MAAM,CAAW,EAAE,CAAC;IACrD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Number formatting for CSV cells.\n *\n * A one-hour, 23-channel, 256 Hz recording is about 21 million numeric cells, so\n * this is the hottest code in a conversion. Two things keep it cheap:\n *\n * - Every sample in a channel comes from a bounded set of integers (digitalMin to\n * digitalMax, typically 4096 distinct values for a 12-bit ADC). The formatted\n * text for a digital code never changes, so it is computed once and reused.\n * - The cache fills lazily. Real recordings visit only a fraction of the range,\n * and a channel with an implausibly wide range falls back to direct formatting\n * rather than reserving memory it will never use.\n */\n\nimport type { EdfSignal } from '../edf/header.js';\nimport { makeScaler } from '../edf/scale.js';\n\n/** Widest digital range worth caching: 16 bits of pointers is 512 KB per channel. */\nconst MAX_CACHED_SPAN = 1 << 16;\n\n/**\n * How many cached sample slots a conversion has left to spend.\n *\n * MAX_CACHED_SPAN is a bound on one channel, and a bound on one channel is not a bound: a\n * file may declare as many channels as it likes, and each was handed its own cache. A\n * channel declaring the ordinary full 16-bit digital range takes the whole 512 KB, so a\n * 256-channel montage reserved 134 MB of pointers before writing a row — a 7.9 MB\n * recording that needed a 192 MB heap and died with a V8 out-of-memory fatal error under\n * anything smaller. The caches were the live set; nothing else in the conversion came near\n * them. It is the same shape of mistake the offset budget below was made to fix, one level\n * over: there the unbounded count was rate groups, here it is channels.\n *\n * One budget for the whole conversion leaves the ordinary recording exactly as it was and\n * puts a ceiling on the dense montage: the same 256-channel file now holds its caches to\n * 16 MB and converts under a 48 MB heap. Channels ask in the order the groups are written,\n * which is fastest rate first, so the cache goes to the channels with the most cells to\n * format. The ones that miss out fall back to formatting directly, which produces\n * identical text — the output is byte-for-byte what it was.\n */\nexport interface SampleCacheBudget {\n remaining: number;\n}\n\n/**\n * Slots for the whole conversion: 16 MB of pointers if every one is claimed.\n *\n * Enough that a full 32-channel montage declaring the whole 16-bit range keeps every cache\n * it had before, and 512 channels of an ordinary 12-bit ADC do too. Past that the extra\n * channels format directly, which costs about a quarter of the conversion's time on a\n * recording where almost none of them are cached — against a file that did not convert at\n * all under a 128 MB heap.\n */\nconst MAX_CACHED_SAMPLES = 1 << 21;\n\nexport function newSampleCacheBudget(): SampleCacheBudget {\n return { remaining: MAX_CACHED_SAMPLES };\n}\n\n/**\n * Format with a fixed number of decimals, normalising negative zero.\n *\n * Without this, a sample that scales to a very small negative value prints as\n * \"-0.000\", which looks like a distinct measurement but is not.\n */\nexport function fixed(value: number, decimals: number): string {\n // An undefined value becomes an empty cell rather than the text \"NaN\" or \"Infinity\".\n // A channel whose header leaves the digital-to-physical mapping undefined scales to\n // NaN, and an empty field is the CSV convention for \"no value here\" — the same one\n // annotations.csv uses for an absent duration. Readers parse it back as NaN / NA\n // rather than as a measurement.\n if (!Number.isFinite(value)) return '';\n\n // toFixed switches to exponent notation at 1e21, which would put \"1e+21\" in a column\n // whose every other cell is plain fixed-decimal — and a reader parsing the column as\n // decimal text has no reason to expect it. Reachable because EDF's 8-character physical\n // range fields accept exponent form, so a header may legitimately say \"1e30\".\n //\n // Above 2^53 a double carries no fractional part anyway, so the integer expansion is\n // exact rather than an approximation of one.\n if (Math.abs(value) >= 1e21) {\n const whole = BigInt(Math.trunc(value)).toString();\n return decimals > 0 ? `${whole}.${'0'.repeat(decimals)}` : whole;\n }\n\n const text = value.toFixed(decimals);\n if (text.charCodeAt(0) !== 45 /* - */) return text;\n // Cheap check for \"-0\", \"-0.0\", \"-0.000\"...\n for (let i = 1; i < text.length; i++) {\n const c = text.charCodeAt(i);\n if (c === 46 /* . */ || c === 48 /* 0 */) continue;\n return text;\n }\n return text.slice(1);\n}\n\n/**\n * A number as plain decimal text, at any magnitude.\n *\n * `String()` switches to exponent notation twice — above 1e21 and below 1e-6 — and\n * annotations.csv wrote its `onset_s` and `duration_s` through it. An EDF+ TAL states its\n * onset as ordinary decimal text, so a file saying `+0.0000001` came back as `1e-7` in a\n * column whose every other cell is a plain decimal, beside a `time_s` the documentation says\n * it \"joins directly\" with. It does not: pandas reads the column as object rather than\n * float64 once one cell is exponent text, and a `merge` on it matches nothing.\n *\n * `fixed` cannot answer this. It needs a decimal count, and these two columns are documented\n * as carrying \"their natural numeric form ... without padding to a fixed decimal count\" —\n * asking for enough places to hold 1e-7 would rewrite `0.1` as `0.10000000000000000555`.\n * Expanding the notation instead touches only the values that are in it and leaves every\n * other cell byte-for-byte what it was.\n */\nexport function plain(value: number): string {\n const text = String(value);\n const e = text.indexOf('e');\n if (e === -1) return text;\n const negative = text.charCodeAt(0) === 45 /* - */;\n const mantissa = text.slice(negative ? 1 : 0, e);\n const dot = mantissa.indexOf('.');\n // Where the point sits once the exponent is spent, counted in significant digits.\n const point = (dot === -1 ? mantissa.length : dot) + Number(text.slice(e + 1));\n const digits = dot === -1 ? mantissa : mantissa.slice(0, dot) + mantissa.slice(dot + 1);\n const sign = negative ? '-' : '';\n if (point <= 0) return `${sign}0.${'0'.repeat(-point)}${digits}`;\n if (point >= digits.length) return `${sign}${digits}${'0'.repeat(point - digits.length)}`;\n return `${sign}${digits.slice(0, point)}.${digits.slice(point)}`;\n}\n\n/** Maps a raw digital sample to its formatted physical value. */\nexport type SampleFormatter = (digital: number) => string;\n\nexport function makeSampleFormatter(\n signal: EdfSignal,\n decimals: number,\n budget: SampleCacheBudget = newSampleCacheBudget(),\n): SampleFormatter {\n const scale = makeScaler(signal);\n const low = Math.min(signal.digitalMin, signal.digitalMax);\n const high = Math.max(signal.digitalMin, signal.digitalMax);\n const span = high - low + 1;\n\n if (\n !Number.isFinite(span) ||\n span <= 0 ||\n span > MAX_CACHED_SPAN ||\n span > budget.remaining\n ) {\n return (digital: number): string => fixed(scale(digital), decimals);\n }\n budget.remaining -= span;\n\n /*\n The cache covers the channel's declared digital range, not the whole int16 domain.\n\n Allocating 65536 slots regardless of span cost 512 KB of pointers per channel, which a\n dense montage cannot afford: a 400-channel recording needed over 200 MB of cache alone\n and died with a V8 out-of-memory fatal error before writing a row. Sizing to the\n declared span makes the ordinary 12-bit channel 32 KB instead — the same 400 channels\n now fit in about 13 MB. Channels that declare the full range still take the whole 512 KB,\n which is what the budget above is for.\n\n Samples outside the declared range still occur in non-conforming files. They simply\n miss the cache and are formatted directly, which produces identical text.\n */\n const cache = new Array<string | undefined>(span);\n return (digital: number): string => {\n const slot = digital - low;\n if (slot >= 0 && slot < span) {\n const hit = cache[slot];\n if (hit !== undefined) return hit;\n const text = fixed(scale(digital), decimals);\n cache[slot] = text;\n return text;\n }\n return fixed(scale(digital), decimals);\n };\n}\n\n/**\n * Decimals for the time column.\n *\n * The interval between samples is 1/rate, which has a terminating decimal expansion of d\n * places exactly when 10^d divides evenly by the rate. Writing that many places makes sample\n * times exact rather than rounded, so `time_s * rate` comes back as a whole number instead\n * of 8191.999999.\n *\n * The search used to stop at nine places, and the comment here claimed \"every rate in common\n * use clears this — 256 Hz needs 8 places, 512 Hz needs 9\". The next two powers of two do\n * not: 1/1024 needs ten places and 1/2048 needs eleven, and those are the rates a BioSemi\n * ActiveTwo records at by default. Both fell through to the rounding fallback, so the two\n * most common high-rate EEG recordings got exactly the behaviour this function exists to\n * avoid — 0.0009766 for an interval of 0.0009765625.\n *\n * A rate of 2^a * 5^b terminates in max(a, b) places, so fifteen covers every power of two up\n * to 32768 Hz, far past anything that records biosignals. Rates with a repeating expansion\n * (3 Hz, say) still fall back to enough places to keep consecutive samples distinct, and that\n * fallback keeps its own cap.\n *\n * Fifteen and not more, because the test below has to stay exact: 10^16 is past 2^53, where a\n * double can no longer hold every integer, and `Number.isInteger(10 ** 17 / 3)` is true — so a\n * larger bound reports a terminating expansion for rates that have none, and 3 Hz would ask\n * for seventeen decimals of a number that repeats forever.\n *\n * The fallback is bounded by the same fifteen. It used to stop at nine, which defeated the\n * one thing it exists to do: at 3e10 Hz — non-terminating, so no exact expansion to find —\n * the interval is 3.3e-11 and nine places rounded every sample in a record to the same\n * timestamp. A column that cannot tell two samples apart is not keeping them distinct, which\n * is what this branch is for.\n */\nconst MAX_TIME_DECIMALS = 15;\n\nexport function timeDecimals(samplingRate: number): number {\n if (!(samplingRate > 0) || !Number.isFinite(samplingRate)) return 3;\n for (let d = 0; d <= MAX_TIME_DECIMALS; d++) {\n if (Number.isInteger(10 ** d / samplingRate)) return Math.max(3, d);\n }\n return Math.min(MAX_TIME_DECIMALS, Math.max(3, Math.ceil(Math.log10(samplingRate)) + 3));\n}\n\n/** Human-readable byte size for warnings and summaries. */\nexport function formatBytes(bytes: number): string {\n const units = ['B', 'KB', 'MB', 'GB', 'TB'];\n let value = bytes;\n let unit = 0;\n while (value >= 1024 && unit < units.length - 1) {\n value /= 1024;\n unit++;\n }\n let rounded = value >= 100 || unit === 0 ? Math.round(value) : Number(value.toFixed(1));\n // Rounding can carry into the next unit, and the unit was chosen before it: 1,048,575 bytes\n // is 1023.999 KB, which printed as \"1024 KB\". The same slip formatDuration below fixed by\n // rounding before splitting, one function up.\n if (rounded === 1024 && unit < units.length - 1) {\n unit++;\n rounded = 1;\n }\n return `${rounded} ${units[unit]}`;\n}\n\n/** Human-readable duration: 1h 05m 12s. */\nexport function formatDuration(seconds: number): string {\n // A duration that is not a number cannot be broken into hours and minutes, and saying so\n // beats the alternative: the fallback below rendered these as \"NaNs\" and \"Infinitys\".\n if (!Number.isFinite(seconds)) return 'unknown';\n\n /*\n Past 2^53 the decomposition stops being arithmetic and starts being noise.\n\n `total - h * 3600 - m * 60` cannot be exact once `total` exceeds what a double can hold\n as a whole number, and the error lands in the seconds field, where it shows up as a\n value that cannot exist. A header declaring a record duration of 1e300 printed:\n\n Duration 8.333333333333333e+296h 48m -2880s\n\n Forty-eight minutes and minus forty-eight seconds, under an hours field in exponent\n notation. The seconds are the honest form for a figure this size — nobody reads\n 285 million years as hours — and the record count and duration are printed beside it\n anyway, so a corrupt header stays just as visible.\n\n Written through `fixed` rather than by interpolation, which is the same 1e21 cliff again:\n `${seconds}` switches to exponent notation exactly where `toFixed` does, so the fallback\n put a token back that this tool's own parser refuses. `--start 4000000000000000000000` on\n a recording of three 1e21-second records was answered with\n\n --start \"4000000000000000000000\" is at or past the end of this 3e+21s recording.\n\n a sentence whose whole job is to say what window there is to ask for, ending in a length\n `--start` and `--duration` reject with \"uses an unknown unit \\\"e\\\"\". `formatSeconds` in\n time-range.ts was fixed for this in the other half of that same message, and its comment\n quotes this half as part of what was wrong. `fixed` expands these with BigInt, which is\n exact past 2^53 where a double carries no fraction anyway.\n */\n if (seconds < 0 || seconds >= Number.MAX_SAFE_INTEGER) return `${fixed(seconds, 0)}s`;\n\n // Round to the precision that will actually be printed BEFORE splitting into units.\n // Splitting first left the remainder to be rounded on its own, so 3599.9996 s decomposed\n // as 59 minutes and 59.9996 seconds and then printed as \"59m 60s\" — a duration that\n // cannot exist. Rounding first carries the extra second into the minute where it belongs.\n const total = Math.round(seconds * 1000) / 1000;\n const h = Math.floor(total / 3600);\n const m = Math.floor((total % 3600) / 60);\n const s = Math.round((total - h * 3600 - m * 60) * 1000) / 1000;\n const sText = Number.isInteger(s) ? String(s) : s.toFixed(3).replace(/\\.?0+$/u, '');\n if (h > 0) return `${h}h ${String(m).padStart(2, '0')}m ${sText}s`;\n if (m > 0) return `${m}m ${sText}s`;\n return `${sText}s`;\n}\n\n/** A record can declare a great many samples; two arrays this size is the cost of caching. */\nconst MAX_CACHED_OFFSETS = 1 << 20;\n\n/**\n * How many cached offsets a conversion has left to spend.\n *\n * The cap used to be per rate group, and a file may hold as many rate groups as it has\n * channels. Twelve channels at twelve rates just under the cap — a 25 MB file — took\n * 1.66 GB and 36 seconds, where a 92 MB file at one rate takes 283 MB and finishes in a\n * fraction of that; twenty-four of them never finished at all. A per-group limit is not a\n * limit, since nothing bounds the number of groups.\n *\n * One budget for the whole conversion makes the single-group case identical to what it was\n * and the many-group case bounded. Groups ask in order of rate, fastest first, so the cache\n * goes to the tables with the most rows to write and the ones that miss out are the ones\n * that would have gained least.\n */\nexport interface OffsetBudget {\n remaining: number;\n}\n\nexport function newOffsetBudget(): OffsetBudget {\n return { remaining: MAX_CACHED_OFFSETS };\n}\n\n/**\n * Formats the time column, reusing the part of it that repeats.\n *\n * Every value cell is already cached — a channel has at most `digitalMax - digitalMin + 1`\n * distinct readings, so the same handful of strings serve millions of rows. The time column\n * had no such luck: it rises monotonically, so no two rows share a string and `toFixed` ran\n * once per row. On a ten-million-row conversion that was a third of the total time, more\n * than reading the file and writing the CSV put together.\n *\n * What repeats is the offset within a record. Sample `s` sits at `s / rate` from the start of\n * whichever record holds it, and there are only `samplesPerRecord` such offsets in the whole\n * recording. Splitting each into whole seconds and printed fraction turns the per-row work\n * into one integer addition and a concatenation:\n *\n * record starting at 42s, sample 7 of a 100 Hz record\n * -> 42 + 0 whole seconds, fraction \".070\" -> \"42.070\"\n *\n * The decomposition is only valid when the record starts on a whole, non-negative second,\n * which is what lets the fraction come entirely from the offset. A record starting at 0.5 s would mix the\n * two, so those fall back to formatting the sum directly. Continuous recordings start every\n * record at `index * recordDuration`, so this holds for all of them whose record duration is\n * a whole number of seconds, and for discontinuous files it holds per record depending on\n * where that record actually starts.\n */\nexport function makeTimeFormatter(\n samplesPerRecord: number,\n rate: number,\n decimals: number,\n budget: OffsetBudget = newOffsetBudget(),\n): (recordStart: number, sample: number) => string {\n const usable = rate > 0 && Number.isFinite(rate);\n\n /** The sum, formatted. Right only where the decomposition below does not apply. */\n const summed = (recordStart: number, sample: number): string =>\n fixed(recordStart + sample / rate, decimals);\n\n /*\n The same decomposition the table holds, computed on the spot.\n\n This used to be the sum, and that made the time column two columns depending on how much\n of the budget above was left. `recordStart + sample / rate` cannot carry the fraction once\n the record start is large: at a start of 1e9 and 30 kHz the exact instant is\n 1000000000.0000333333, and the double nearest the sum prints as 1000000000.00003338 —\n the last two places are the addition's rounding, not the recording's clock.\n\n Which of the two a rate group got was decided by the groups ahead of it, since they ask\n from one budget fastest first. So a recording whose fast channel takes the table left its\n slow channel adding doubles, and the same channel asked for on its own got the table:\n\n edf2csv far.edf --out whole -> 1000000000.00003338\n edf2csv far.edf --out one --channels slow -> 1000000000.00003333\n\n Two files from one recording disagreeing about when a sample was taken, in a tool whose\n documentation says `--channels` selects columns and changes nothing else. The narrowing\n sweep asserts exactly that and could not see it: its fixtures are small enough that the\n budget never runs out, so both conversions took the table.\n\n The sum is still the answer where the decomposition has nothing to stand on — a record\n starting on a fraction or before zero, where the whole part and the fraction are not\n separable — and past 1e21, where the whole part stops printing in full.\n */\n const composed = (recordStart: number, sample: number): string => {\n const text = fixed(sample / rate, decimals);\n const dot = text.indexOf('.');\n const whole = recordStart + (dot === -1 ? Number(text) : Number(text.slice(0, dot)));\n if (whole >= 1e21) return summed(recordStart, sample);\n return dot === -1 ? `${whole}` : `${whole}${text.slice(dot)}`;\n };\n\n /** What every row gets when the table is not there to be read. */\n const direct = (recordStart: number, sample: number): string =>\n usable && sample >= 0 && Number.isInteger(recordStart) && recordStart >= 0\n ? composed(recordStart, sample)\n : summed(recordStart, sample);\n\n if (!usable || samplesPerRecord <= 0 || samplesPerRecord > budget.remaining) {\n return direct;\n }\n budget.remaining -= samplesPerRecord;\n\n // Whole seconds and printed fraction of each offset, taken from the formatted offset\n // itself so that an offset which rounds up to the next second (0.9996 at three places)\n // carries that second rather than losing it.\n const wholeOffset = new Float64Array(samplesPerRecord);\n const fractionText: string[] = new Array<string>(samplesPerRecord);\n for (let sample = 0; sample < samplesPerRecord; sample++) {\n const text = fixed(sample / rate, decimals);\n const dot = text.indexOf('.');\n wholeOffset[sample] = dot === -1 ? Number(text) : Number(text.slice(0, dot));\n fractionText[sample] = dot === -1 ? '' : text.slice(dot);\n }\n\n return (recordStart: number, sample: number): string => {\n /*\n Non-negative only. Appending a fraction to a negative whole part moves the time the\n wrong way: a record at -5 s and an offset of half a second is -4.5, but \"-5\" and\n \".500\" concatenate to -5.500. Recording times start at zero, so this is unreachable\n from a well-formed file — an EDF+ timekeeping TAL is free to carry a negative onset\n though, and that is enough reason for the fast path to decline it.\n */\n if (\n sample < 0 ||\n sample >= samplesPerRecord ||\n !Number.isInteger(recordStart) ||\n recordStart < 0\n ) {\n return direct(recordStart, sample);\n }\n const whole = recordStart + (wholeOffset[sample] as number);\n /*\n The same 1e21 cliff `fixed` guards against, arriving through the back door.\n\n `${whole}` is the implicit Number-to-String conversion, which switches to exponent\n notation at 1e21 exactly as `toFixed` does — and then the cached fraction is glued onto\n the end of it, so the cell reads \"1e+21.000\". That is not a number in any notation:\n pandas and R both parse it as NaN, and a column of ordinary decimals ends in a run of\n them. A header may legitimately say `1e21` in its 8-character record-duration field, so\n three records are enough to reach it.\n\n The slow path already expands these with BigInt. One comparison per row keeps that\n correct without giving up the cache for the other twenty million.\n */\n if (whole >= 1e21) return summed(recordStart, sample);\n return `${whole}${fractionText[sample] as string}`;\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"number.js","sourceRoot":"","sources":["../../src/format/number.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,qFAAqF;AACrF,MAAM,eAAe,GAAG,CAAC,IAAI,EAAE,CAAC;AAyBhC;;;;;;;;GAQG;AACH,MAAM,kBAAkB,GAAG,CAAC,IAAI,EAAE,CAAC;AAEnC,MAAM,UAAU,oBAAoB;IAClC,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,CAAC;AAC3C,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,KAAK,CAAC,KAAa,EAAE,QAAgB;IACnD,qFAAqF;IACrF,oFAAoF;IACpF,mFAAmF;IACnF,iFAAiF;IACjF,gCAAgC;IAChC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IAEvC,qFAAqF;IACrF,qFAAqF;IACrF,wFAAwF;IACxF,8EAA8E;IAC9E,EAAE;IACF,qFAAqF;IACrF,6CAA6C;IAC7C,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,IAAI,EAAE,CAAC;QAC5B,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;QACnD,OAAO,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,KAAK,IAAI,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;IACnE,CAAC;IAED,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACrC,IAAI,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CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC3D,CAAC;IAED,OAAO,CAAC,WAAmB,EAAE,MAAc,EAAU,EAAE;QACrD;;;;;;UAME;QACF,IACE,MAAM,GAAG,CAAC;YACV,MAAM,IAAI,gBAAgB;YAC1B,CAAC,MAAM,CAAC,SAAS,CAAC,WAAW,CAAC;YAC9B,WAAW,GAAG,CAAC,EACf,CAAC;YACD,OAAO,MAAM,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;QACrC,CAAC;QACD,MAAM,KAAK,GAAG,WAAW,GAAI,WAAW,CAAC,MAAM,CAAY,CAAC;QAC5D;;;;;;;;;;;;UAYE;QACF,IAAI,KAAK,IAAI,IAAI;YAAE,OAAO,MAAM,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;QACtD,OAAO,GAAG,KAAK,GAAG,YAAY,CAAC,MAAM,CAAW,EAAE,CAAC;IACrD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Number formatting for CSV cells.\n *\n * A one-hour, 23-channel, 256 Hz recording is about 21 million numeric cells, so\n * this is the hottest code in a conversion. Two things keep it cheap:\n *\n * - Every sample in a channel comes from a bounded set of integers (digitalMin to\n * digitalMax, typically 4096 distinct values for a 12-bit ADC). The formatted\n * text for a digital code never changes, so it is computed once and reused.\n * - The cache fills lazily. Real recordings visit only a fraction of the range,\n * and a channel with an implausibly wide range falls back to direct formatting\n * rather than reserving memory it will never use.\n */\n\nimport type { EdfSignal } from '../edf/header.js';\nimport { makeScaler } from '../edf/scale.js';\n\n/** Widest digital range worth caching: 16 bits of pointers is 512 KB per channel. */\nconst MAX_CACHED_SPAN = 1 << 16;\n\n/**\n * How many cached sample slots a conversion has left to spend.\n *\n * MAX_CACHED_SPAN is a bound on one channel, and a bound on one channel is not a bound: a\n * file may declare as many channels as it likes, and each was handed its own cache. A\n * channel declaring the ordinary full 16-bit digital range takes the whole 512 KB, so a\n * 256-channel montage reserved 134 MB of pointers before writing a row — a 7.9 MB\n * recording that needed a 192 MB heap and died with a V8 out-of-memory fatal error under\n * anything smaller. The caches were the live set; nothing else in the conversion came near\n * them. It is the same shape of mistake the offset budget below was made to fix, one level\n * over: there the unbounded count was rate groups, here it is channels.\n *\n * One budget for the whole conversion leaves the ordinary recording exactly as it was and\n * puts a ceiling on the dense montage: the same 256-channel file now holds its caches to\n * 16 MB and converts under a 48 MB heap. Channels ask in the order the groups are written,\n * which is fastest rate first, so the cache goes to the channels with the most cells to\n * format. The ones that miss out fall back to formatting directly, which produces\n * identical text — the output is byte-for-byte what it was.\n */\nexport interface SampleCacheBudget {\n remaining: number;\n}\n\n/**\n * Slots for the whole conversion: 16 MB of pointers if every one is claimed.\n *\n * Enough that a full 32-channel montage declaring the whole 16-bit range keeps every cache\n * it had before, and 512 channels of an ordinary 12-bit ADC do too. Past that the extra\n * channels format directly, which costs about a quarter of the conversion's time on a\n * recording where almost none of them are cached — against a file that did not convert at\n * all under a 128 MB heap.\n */\nconst MAX_CACHED_SAMPLES = 1 << 21;\n\nexport function newSampleCacheBudget(): SampleCacheBudget {\n return { remaining: MAX_CACHED_SAMPLES };\n}\n\n/**\n * Format with a fixed number of decimals, normalising negative zero.\n *\n * Without this, a sample that scales to a very small negative value prints as\n * \"-0.000\", which looks like a distinct measurement but is not.\n */\nexport function fixed(value: number, decimals: number): string {\n // An undefined value becomes an empty cell rather than the text \"NaN\" or \"Infinity\".\n // A channel whose header leaves the digital-to-physical mapping undefined scales to\n // NaN, and an empty field is the CSV convention for \"no value here\" — the same one\n // annotations.csv uses for an absent duration. Readers parse it back as NaN / NA\n // rather than as a measurement.\n if (!Number.isFinite(value)) return '';\n\n // toFixed switches to exponent notation at 1e21, which would put \"1e+21\" in a column\n // whose every other cell is plain fixed-decimal — and a reader parsing the column as\n // decimal text has no reason to expect it. Reachable because EDF's 8-character physical\n // range fields accept exponent form, so a header may legitimately say \"1e30\".\n //\n // Above 2^53 a double carries no fractional part anyway, so the integer expansion is\n // exact rather than an approximation of one.\n if (Math.abs(value) >= 1e21) {\n const whole = BigInt(Math.trunc(value)).toString();\n return decimals > 0 ? `${whole}.${'0'.repeat(decimals)}` : whole;\n }\n\n const text = value.toFixed(decimals);\n if (text.charCodeAt(0) !== 45 /* - */) return text;\n // Cheap check for \"-0\", \"-0.0\", \"-0.000\"...\n for (let i = 1; i < text.length; i++) {\n const c = text.charCodeAt(i);\n if (c === 46 /* . */ || c === 48 /* 0 */) continue;\n return text;\n }\n return text.slice(1);\n}\n\n/**\n * A number as plain decimal text, at any magnitude.\n *\n * `String()` switches to exponent notation twice — above 1e21 and below 1e-6 — and\n * annotations.csv wrote its `onset_s` and `duration_s` through it. An EDF+ TAL states its\n * onset as ordinary decimal text, so a file saying `+0.0000001` came back as `1e-7` in a\n * column whose every other cell is a plain decimal, beside a `time_s` the documentation says\n * it \"joins directly\" with. It does not: pandas reads the column as object rather than\n * float64 once one cell is exponent text, and a `merge` on it matches nothing.\n *\n * `fixed` cannot answer this. It needs a decimal count, and these two columns are documented\n * as carrying \"their natural numeric form ... without padding to a fixed decimal count\" —\n * asking for enough places to hold 1e-7 would rewrite `0.1` as `0.10000000000000000555`.\n * Expanding the notation instead touches only the values that are in it and leaves every\n * other cell byte-for-byte what it was.\n */\nexport function plain(value: number): string {\n const text = String(value);\n const e = text.indexOf('e');\n if (e === -1) return text;\n const negative = text.charCodeAt(0) === 45 /* - */;\n const mantissa = text.slice(negative ? 1 : 0, e);\n const dot = mantissa.indexOf('.');\n // Where the point sits once the exponent is spent, counted in significant digits.\n const point = (dot === -1 ? mantissa.length : dot) + Number(text.slice(e + 1));\n const digits = dot === -1 ? mantissa : mantissa.slice(0, dot) + mantissa.slice(dot + 1);\n const sign = negative ? '-' : '';\n if (point <= 0) return `${sign}0.${'0'.repeat(-point)}${digits}`;\n if (point >= digits.length) return `${sign}${digits}${'0'.repeat(point - digits.length)}`;\n return `${sign}${digits.slice(0, point)}.${digits.slice(point)}`;\n}\n\n/** Maps a raw digital sample to its formatted physical value. */\nexport type SampleFormatter = (digital: number) => string;\n\nexport function makeSampleFormatter(\n signal: EdfSignal,\n decimals: number,\n budget: SampleCacheBudget = newSampleCacheBudget(),\n): SampleFormatter {\n const scale = makeScaler(signal);\n const low = Math.min(signal.digitalMin, signal.digitalMax);\n const high = Math.max(signal.digitalMin, signal.digitalMax);\n const span = high - low + 1;\n\n if (\n !Number.isFinite(span) ||\n span <= 0 ||\n span > MAX_CACHED_SPAN ||\n span > budget.remaining\n ) {\n return (digital: number): string => fixed(scale(digital), decimals);\n }\n budget.remaining -= span;\n\n /*\n The cache covers the channel's declared digital range, not the whole int16 domain.\n\n Allocating 65536 slots regardless of span cost 512 KB of pointers per channel, which a\n dense montage cannot afford: a 400-channel recording needed over 200 MB of cache alone\n and died with a V8 out-of-memory fatal error before writing a row. Sizing to the\n declared span makes the ordinary 12-bit channel 32 KB instead — the same 400 channels\n now fit in about 13 MB. Channels that declare the full range still take the whole 512 KB,\n which is what the budget above is for.\n\n Samples outside the declared range still occur in non-conforming files. They simply\n miss the cache and are formatted directly, which produces identical text.\n */\n const cache = new Array<string | undefined>(span);\n return (digital: number): string => {\n const slot = digital - low;\n if (slot >= 0 && slot < span) {\n const hit = cache[slot];\n if (hit !== undefined) return hit;\n const text = fixed(scale(digital), decimals);\n cache[slot] = text;\n return text;\n }\n return fixed(scale(digital), decimals);\n };\n}\n\n/**\n * Decimals for the time column.\n *\n * The interval between samples is 1/rate, which has a terminating decimal expansion of d\n * places exactly when 10^d divides evenly by the rate. Writing that many places makes sample\n * times exact rather than rounded, so `time_s * rate` comes back as a whole number instead\n * of 8191.999999.\n *\n * The search used to stop at nine places, and the comment here claimed \"every rate in common\n * use clears this — 256 Hz needs 8 places, 512 Hz needs 9\". The next two powers of two do\n * not: 1/1024 needs ten places and 1/2048 needs eleven, and those are the rates a BioSemi\n * ActiveTwo records at by default. Both fell through to the rounding fallback, so the two\n * most common high-rate EEG recordings got exactly the behaviour this function exists to\n * avoid — 0.0009766 for an interval of 0.0009765625.\n *\n * A rate of 2^a * 5^b terminates in max(a, b) places, so fifteen covers every power of two up\n * to 32768 Hz, far past anything that records biosignals. Rates with a repeating expansion\n * (3 Hz, say) still fall back to enough places to keep consecutive samples distinct, and that\n * fallback keeps its own cap.\n *\n * Fifteen and not more, because the test below has to stay exact: 10^16 is past 2^53, where a\n * double can no longer hold every integer, and `Number.isInteger(10 ** 17 / 3)` is true — so a\n * larger bound reports a terminating expansion for rates that have none, and 3 Hz would ask\n * for seventeen decimals of a number that repeats forever.\n *\n * The fallback is bounded by the same fifteen. It used to stop at nine, which defeated the\n * one thing it exists to do: at 3e10 Hz — non-terminating, so no exact expansion to find —\n * the interval is 3.3e-11 and nine places rounded every sample in a record to the same\n * timestamp. A column that cannot tell two samples apart is not keeping them distinct, which\n * is what this branch is for.\n */\nconst MAX_TIME_DECIMALS = 15;\n\nexport function timeDecimals(samplingRate: number): number {\n if (!(samplingRate > 0) || !Number.isFinite(samplingRate)) return 3;\n for (let d = 0; d <= MAX_TIME_DECIMALS; d++) {\n if (Number.isInteger(10 ** d / samplingRate)) return Math.max(3, d);\n }\n return Math.min(MAX_TIME_DECIMALS, Math.max(3, Math.ceil(Math.log10(samplingRate)) + 3));\n}\n\n/** Human-readable byte size for warnings and summaries. */\nexport function formatBytes(bytes: number): string {\n const units = ['B', 'KB', 'MB', 'GB', 'TB'];\n let value = bytes;\n let unit = 0;\n while (value >= 1024 && unit < units.length - 1) {\n value /= 1024;\n unit++;\n }\n let rounded = value >= 100 || unit === 0 ? Math.round(value) : Number(value.toFixed(1));\n // Rounding can carry into the next unit, and the unit was chosen before it: 1,048,575 bytes\n // is 1023.999 KB, which printed as \"1024 KB\". The same slip formatDuration below fixed by\n // rounding before splitting, one function up.\n if (rounded === 1024 && unit < units.length - 1) {\n unit++;\n rounded = 1;\n }\n return `${rounded} ${units[unit]}`;\n}\n\n/** Human-readable duration: 1h 05m 12s. */\nexport function formatDuration(seconds: number): string {\n // A duration that is not a number cannot be broken into hours and minutes, and saying so\n // beats the alternative: the fallback below rendered these as \"NaNs\" and \"Infinitys\".\n if (!Number.isFinite(seconds)) return 'unknown';\n\n /*\n Past 2^53 the decomposition stops being arithmetic and starts being noise.\n\n `total - h * 3600 - m * 60` cannot be exact once `total` exceeds what a double can hold\n as a whole number, and the error lands in the seconds field, where it shows up as a\n value that cannot exist. A header declaring a record duration of 1e300 printed:\n\n Duration 8.333333333333333e+296h 48m -2880s\n\n Forty-eight minutes and minus forty-eight seconds, under an hours field in exponent\n notation. The seconds are the honest form for a figure this size — nobody reads\n 285 million years as hours — and the record count and duration are printed beside it\n anyway, so a corrupt header stays just as visible.\n\n Written through `fixed` rather than by interpolation, which is the same 1e21 cliff again:\n `${seconds}` switches to exponent notation exactly where `toFixed` does, so the fallback\n put a token back that this tool's own parser refuses. `--start 4000000000000000000000` on\n a recording of three 1e21-second records was answered with\n\n --start \"4000000000000000000000\" is at or past the end of this 3e+21s recording.\n\n a sentence whose whole job is to say what window there is to ask for, ending in a length\n `--start` and `--duration` reject with \"uses an unknown unit \\\"e\\\"\". `formatSeconds` in\n time-range.ts was fixed for this in the other half of that same message, and its comment\n quotes this half as part of what was wrong. `fixed` expands these with BigInt, which is\n exact past 2^53 where a double carries no fraction anyway.\n */\n if (seconds < 0 || seconds >= Number.MAX_SAFE_INTEGER) return `${fixed(seconds, 0)}s`;\n\n // Round to the precision that will actually be printed BEFORE splitting into units.\n // Splitting first left the remainder to be rounded on its own, so 3599.9996 s decomposed\n // as 59 minutes and 59.9996 seconds and then printed as \"59m 60s\" — a duration that\n // cannot exist. Rounding first carries the extra second into the minute where it belongs.\n const total = Math.round(seconds * 1000) / 1000;\n /*\n A duration shorter than the rounding is not a duration of zero.\n\n Three decimals is the right precision for a recording measured in hours, and it collapses\n everything under half a millisecond to \"0s\". `repeating-fast.edf` — two records of 1e-15s,\n six samples, one of this repository's own fixtures — printed\n\n Duration 0s (2 records of 1e-15s)\n\n and refused `--start 0.5` with \"is at or past the end of this 0s recording\". A reader is\n told the file holds nothing, on the line they look at first, about a file that converts to\n six rows; the record duration two columns over already contradicts it. Same shape as the\n other end of this function, which stops decomposing past 2^53 and prints the seconds\n instead, and as the byte size above, which does not round 1023.999 KB into the next unit.\n\n Written through `plain` rather than interpolated, for the reason the comment above gives:\n `${1e-15}` is exponent notation, and the sentence this feeds is one whose whole job is to\n say what `--start` may be given — and `--start 1e-15s` is refused as an unknown unit \"e\".\n */\n if (total === 0 && seconds > 0) return `${plain(seconds)}s`;\n const h = Math.floor(total / 3600);\n const m = Math.floor((total % 3600) / 60);\n const s = Math.round((total - h * 3600 - m * 60) * 1000) / 1000;\n const sText = Number.isInteger(s) ? String(s) : s.toFixed(3).replace(/\\.?0+$/u, '');\n if (h > 0) return `${h}h ${String(m).padStart(2, '0')}m ${sText}s`;\n if (m > 0) return `${m}m ${sText}s`;\n return `${sText}s`;\n}\n\n/** A record can declare a great many samples; two arrays this size is the cost of caching. */\nconst MAX_CACHED_OFFSETS = 1 << 20;\n\n/**\n * How many cached offsets a conversion has left to spend.\n *\n * The cap used to be per rate group, and a file may hold as many rate groups as it has\n * channels. Twelve channels at twelve rates just under the cap — a 25 MB file — took\n * 1.66 GB and 36 seconds, where a 92 MB file at one rate takes 283 MB and finishes in a\n * fraction of that; twenty-four of them never finished at all. A per-group limit is not a\n * limit, since nothing bounds the number of groups.\n *\n * One budget for the whole conversion makes the single-group case identical to what it was\n * and the many-group case bounded. Groups ask in order of rate, fastest first, so the cache\n * goes to the tables with the most rows to write and the ones that miss out are the ones\n * that would have gained least.\n */\nexport interface OffsetBudget {\n remaining: number;\n}\n\nexport function newOffsetBudget(): OffsetBudget {\n return { remaining: MAX_CACHED_OFFSETS };\n}\n\n/**\n * Formats the time column, reusing the part of it that repeats.\n *\n * Every value cell is already cached — a channel has at most `digitalMax - digitalMin + 1`\n * distinct readings, so the same handful of strings serve millions of rows. The time column\n * had no such luck: it rises monotonically, so no two rows share a string and `toFixed` ran\n * once per row. On a ten-million-row conversion that was a third of the total time, more\n * than reading the file and writing the CSV put together.\n *\n * What repeats is the offset within a record. Sample `s` sits at `s / rate` from the start of\n * whichever record holds it, and there are only `samplesPerRecord` such offsets in the whole\n * recording. Splitting each into whole seconds and printed fraction turns the per-row work\n * into one integer addition and a concatenation:\n *\n * record starting at 42s, sample 7 of a 100 Hz record\n * -> 42 + 0 whole seconds, fraction \".070\" -> \"42.070\"\n *\n * The decomposition is only valid when the record starts on a whole, non-negative second,\n * which is what lets the fraction come entirely from the offset. A record starting at 0.5 s would mix the\n * two, so those fall back to formatting the sum directly. Continuous recordings start every\n * record at `index * recordDuration`, so this holds for all of them whose record duration is\n * a whole number of seconds, and for discontinuous files it holds per record depending on\n * where that record actually starts.\n */\nexport function makeTimeFormatter(\n samplesPerRecord: number,\n rate: number,\n decimals: number,\n budget: OffsetBudget = newOffsetBudget(),\n): (recordStart: number, sample: number) => string {\n const usable = rate > 0 && Number.isFinite(rate);\n\n /** The sum, formatted. Right only where the decomposition below does not apply. */\n const summed = (recordStart: number, sample: number): string =>\n fixed(recordStart + sample / rate, decimals);\n\n /*\n The same decomposition the table holds, computed on the spot.\n\n This used to be the sum, and that made the time column two columns depending on how much\n of the budget above was left. `recordStart + sample / rate` cannot carry the fraction once\n the record start is large: at a start of 1e9 and 30 kHz the exact instant is\n 1000000000.0000333333, and the double nearest the sum prints as 1000000000.00003338 —\n the last two places are the addition's rounding, not the recording's clock.\n\n Which of the two a rate group got was decided by the groups ahead of it, since they ask\n from one budget fastest first. So a recording whose fast channel takes the table left its\n slow channel adding doubles, and the same channel asked for on its own got the table:\n\n edf2csv far.edf --out whole -> 1000000000.00003338\n edf2csv far.edf --out one --channels slow -> 1000000000.00003333\n\n Two files from one recording disagreeing about when a sample was taken, in a tool whose\n documentation says `--channels` selects columns and changes nothing else. The narrowing\n sweep asserts exactly that and could not see it: its fixtures are small enough that the\n budget never runs out, so both conversions took the table.\n\n The sum is still the answer where the decomposition has nothing to stand on — a record\n starting on a fraction or before zero, where the whole part and the fraction are not\n separable — and past 1e21, where the whole part stops printing in full.\n */\n const composed = (recordStart: number, sample: number): string => {\n const text = fixed(sample / rate, decimals);\n const dot = text.indexOf('.');\n const whole = recordStart + (dot === -1 ? Number(text) : Number(text.slice(0, dot)));\n if (whole >= 1e21) return summed(recordStart, sample);\n return dot === -1 ? `${whole}` : `${whole}${text.slice(dot)}`;\n };\n\n /** What every row gets when the table is not there to be read. */\n const direct = (recordStart: number, sample: number): string =>\n usable && sample >= 0 && Number.isInteger(recordStart) && recordStart >= 0\n ? composed(recordStart, sample)\n : summed(recordStart, sample);\n\n if (!usable || samplesPerRecord <= 0 || samplesPerRecord > budget.remaining) {\n return direct;\n }\n budget.remaining -= samplesPerRecord;\n\n // Whole seconds and printed fraction of each offset, taken from the formatted offset\n // itself so that an offset which rounds up to the next second (0.9996 at three places)\n // carries that second rather than losing it.\n const wholeOffset = new Float64Array(samplesPerRecord);\n const fractionText: string[] = new Array<string>(samplesPerRecord);\n for (let sample = 0; sample < samplesPerRecord; sample++) {\n const text = fixed(sample / rate, decimals);\n const dot = text.indexOf('.');\n wholeOffset[sample] = dot === -1 ? Number(text) : Number(text.slice(0, dot));\n fractionText[sample] = dot === -1 ? '' : text.slice(dot);\n }\n\n return (recordStart: number, sample: number): string => {\n /*\n Non-negative only. Appending a fraction to a negative whole part moves the time the\n wrong way: a record at -5 s and an offset of half a second is -4.5, but \"-5\" and\n \".500\" concatenate to -5.500. Recording times start at zero, so this is unreachable\n from a well-formed file — an EDF+ timekeeping TAL is free to carry a negative onset\n though, and that is enough reason for the fast path to decline it.\n */\n if (\n sample < 0 ||\n sample >= samplesPerRecord ||\n !Number.isInteger(recordStart) ||\n recordStart < 0\n ) {\n return direct(recordStart, sample);\n }\n const whole = recordStart + (wholeOffset[sample] as number);\n /*\n The same 1e21 cliff `fixed` guards against, arriving through the back door.\n\n `${whole}` is the implicit Number-to-String conversion, which switches to exponent\n notation at 1e21 exactly as `toFixed` does — and then the cached fraction is glued onto\n the end of it, so the cell reads \"1e+21.000\". That is not a number in any notation:\n pandas and R both parse it as NaN, and a column of ordinary decimals ends in a run of\n them. A header may legitimately say `1e21` in its 8-character record-duration field, so\n three records are enough to reach it.\n\n The slow path already expands these with BigInt. One comparison per row keeps that\n correct without giving up the cache for the other twenty million.\n */\n if (whole >= 1e21) return summed(recordStart, sample);\n return `${whole}${fractionText[sample] as string}`;\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "edf2csv",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.95",
|
|
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",
|