edf2csv 0.8.91 → 0.8.93
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/cli/report.d.ts +2 -1
- package/dist/cli/report.js +23 -9
- package/dist/cli/report.js.map +1 -1
- package/dist/convert/channels.js +12 -8
- package/dist/convert/channels.js.map +1 -1
- package/dist/convert/run.js +24 -6
- package/dist/convert/run.js.map +1 -1
- package/dist/edf/reader.js +6 -4
- package/dist/edf/reader.js.map +1 -1
- package/dist/format/unprintable.d.ts +17 -0
- package/dist/format/unprintable.js +19 -0
- package/dist/format/unprintable.js.map +1 -1
- package/package.json +1 -1
package/dist/cli/report.d.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import type { Diagnostic } from '../edf/errors.js';
|
|
8
8
|
import type { EdfFile } from '../edf/reader.js';
|
|
9
|
+
import { printable } from '../format/unprintable.js';
|
|
9
10
|
import type { ConversionPlan } from '../convert/plan.js';
|
|
10
11
|
import type { ConvertResult } from '../convert/run.js';
|
|
11
12
|
/**
|
|
@@ -50,7 +51,7 @@ export declare function wrap(text: string, indent?: string, width?: number): str
|
|
|
50
51
|
* rather than being silently swallowed. This affects display only: `channels.csv` and
|
|
51
52
|
* `metadata.json` still copy the field verbatim, and CSV quoting already makes that safe.
|
|
52
53
|
*/
|
|
53
|
-
export
|
|
54
|
+
export { printable };
|
|
54
55
|
/**
|
|
55
56
|
* The same protection for text that is meant to span lines.
|
|
56
57
|
*
|
package/dist/cli/report.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
import { describeFormat, formatRates, formatWallClock } from '../edf/header.js';
|
|
8
8
|
import { fixed, formatBytes, formatDuration, plain } from '../format/number.js';
|
|
9
9
|
import { counted, grouped } from '../format/list.js';
|
|
10
|
-
import {
|
|
10
|
+
import { escapeJsonText, printable } from '../format/unprintable.js';
|
|
11
11
|
import { withoutFileRateWarning } from '../convert/plan.js';
|
|
12
12
|
import { VERSION } from '../version.js';
|
|
13
13
|
/** Where terminal prose wraps. The width --help is written to, and the ANSI default. */
|
|
@@ -104,11 +104,10 @@ function table(rows, alignRight) {
|
|
|
104
104
|
* rather than being silently swallowed. This affects display only: `channels.csv` and
|
|
105
105
|
* `metadata.json` still copy the field verbatim, and CSV quoting already makes that safe.
|
|
106
106
|
*/
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
}
|
|
107
|
+
// Defined in src/format/unprintable.ts, beside the character class it uses, since the library's
|
|
108
|
+
// own message builders need it too — see 0.8.92. Re-exported here, which is where every caller
|
|
109
|
+
// in this package already imports it from.
|
|
110
|
+
export { printable };
|
|
112
111
|
/**
|
|
113
112
|
* The same protection for text that is meant to span lines.
|
|
114
113
|
*
|
|
@@ -292,9 +291,24 @@ toStdout = false) {
|
|
|
292
291
|
*/
|
|
293
292
|
const { range } = plan;
|
|
294
293
|
if (!range.isWholeRecording && Number.isFinite(range.startSeconds) && Number.isFinite(range.endSeconds)) {
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
294
|
+
/*
|
|
295
|
+
What the window selects, which is not data records in every mode.
|
|
296
|
+
|
|
297
|
+
`--annotations-only` reads the annotation channel and converts no data records at all —
|
|
298
|
+
the OUTPUT column of the table below says `(no signal data)` for every channel, and the
|
|
299
|
+
line under it says "and no signal data". This counted them anyway:
|
|
300
|
+
|
|
301
|
+
Window 1.000s to 3.000s (2 of 3 data records)
|
|
302
|
+
...
|
|
303
|
+
Would write annotations.csv and channels.csv, and no signal data.
|
|
304
|
+
|
|
305
|
+
The window is not idle in that mode: it decides which events are exported, by onset. So
|
|
306
|
+
the range stays and the parenthetical says what it is doing.
|
|
307
|
+
*/
|
|
308
|
+
const selects = plan.writeSignals
|
|
309
|
+
? `${grouped(range.endRecord - range.startRecord)} of ${counted(file.recordCount, 'data record')}`
|
|
310
|
+
: 'events outside it are not exported';
|
|
311
|
+
lines.push(`Window ${fixed(range.startSeconds, 3)}s to ${fixed(range.endSeconds, 3)}s (${selects})`);
|
|
298
312
|
}
|
|
299
313
|
lines.push(`Size ${formatBytes(file.fileSize)}`);
|
|
300
314
|
if (header.patientId)
|
package/dist/cli/report.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"report.js","sourceRoot":"","sources":["../../src/cli/report.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAChF,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAChF,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAE/F,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAE5D,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAExC,wFAAwF;AACxF,MAAM,YAAY,GAAG,EAAE,CAAC;AAExB,0FAA0F;AAC1F,MAAM,WAAW,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AAElC;;;;;;;GAOG;AACH,MAAM,IAAI,GAAG,uCAAuC,CAAC;AAErD;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,UAAU,IAAI,CAAC,IAAY,EAAE,MAAM,GAAG,EAAE,EAAE,KAAK,GAAG,YAAY;IAClE,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,IAAI,IAAI,GAAG,MAAM,CAAC;IAClB,IAAI,EAAE,GAAG,CAAC,CAAC;IACX,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;QACxC,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QACvB,MA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EAAE,CAAC,CAAC,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;KACtG,EACD,IAAI,EACJ,MAAM,IAAI,SAAS,CACpB,CAAC;IACF,oEAAoE;IACpE,OAAO,cAAc,CAAC,QAAQ,CAAC,CAAC;AAClC,CAAC","sourcesContent":["/**\n * Human-readable output for the terminal.\n *\n * Everything here is plain text with no colour codes, so piping to a file or a log\n * produces exactly what appeared on screen.\n */\n\nimport type { Diagnostic } from '../edf/errors.js';\nimport type { EdfFile } from '../edf/reader.js';\nimport { describeFormat, formatRates, formatWallClock } from '../edf/header.js';\nimport { fixed, formatBytes, formatDuration, plain } from '../format/number.js';\nimport { counted, grouped } from '../format/list.js';\nimport { escapeCharacter, escapeJsonText, unprintablePattern } from '../format/unprintable.js';\nimport type { ConversionPlan } from '../convert/plan.js';\nimport { withoutFileRateWarning } from '../convert/plan.js';\nimport type { ConvertResult } from '../convert/run.js';\nimport { VERSION } from '../version.js';\n\n/** Where terminal prose wraps. The width --help is written to, and the ANSI default. */\nconst WRAP_COLUMNS = 80;\n\n/** The continuation indent under a `warning: ` prefix, which is the only one there is. */\nconst HINT_INDENT = ' '.repeat(9);\n\n/**\n * One unbreakable unit of a wrapped line: a quoted span, or a run of non-space.\n *\n * The lookbehind is what keeps an apostrophe out of it. `the file's own header and it's` has\n * two of them, and without the guard `'s own header and it'` is one quoted span — a token\n * with spaces in it that then refuses to break. A quote opening a span is at the start of a\n * word, so that is what is required of it.\n */\nconst WORD = /(?<=^|[\\s(])(?:\"[^\"]*\"|'[^']*')|\\S+/gu;\n\n/**\n * Greedy word wrap, `indent` on every line including the first.\n *\n * Only free prose goes through this. The aligned parts of `--info` — the `Format`/`Size`\n * key-value lines and the channel table — are laid out in columns, and re-flowing a column\n * is how you turn a table into a paragraph.\n *\n * A word wider than the column is left to overrun rather than broken. The long words here\n * are file paths and quoted channel labels, and neither survives being split across lines:\n * the point of printing a path is that it can be copied back out.\n *\n * A quoted span is one word for the same reason, however many spaces are inside it. The\n * sentence above is the promise, and it held only for the paths that have no spaces in them:\n * an interrupted conversion said `Files already written to \"/tmp/a very long destination\n * folder name with` / `many spaces here indeed\" are incomplete`, splitting the one thing on\n * the line that has to be copied whole — and quoting is what a path with spaces in it is\n * given in the first place. A word wider than the column already overruns rather than\n * breaking; this is that rule reaching the words it was written for.\n *\n * Which is also why the gap between two words is reproduced rather than normalised to one\n * space. Splitting on `\\s+` and rejoining with `' '` re-flowed everything, and a quoted value\n * is not prose: a channel labelled `EEG A` was offered back as `Did you mean \"EEG A\"?`, and\n * a destination given as `-my nightly` as `Write it as one argument instead:\n * '--out=-my nightly'`. Following either gets a different channel or a different directory\n * than the one the sentence is about, and the run before it had already quoted the name\n * correctly on the line above.\n */\nexport function wrap(text: string, indent = '', width = WRAP_COLUMNS): string {\n const lines: string[] = [];\n let line = indent;\n let at = 0;\n for (const match of text.matchAll(WORD)) {\n const piece = match[0];\n const gap = text.slice(at, match.index);\n at = match.index + piece.length;\n if (line === indent) line += piece;\n else if (line.length + gap.length + piece.length <= width) line += gap + piece;\n else {\n lines.push(line);\n line = indent + piece;\n }\n }\n if (line !== indent) lines.push(line);\n return lines.join('\\n');\n}\n\nfunction table(rows: readonly (readonly string[])[], alignRight: ReadonlySet<number>): string {\n if (rows.length === 0) return '';\n const width: number[] = [];\n for (const row of rows) {\n row.forEach((cell, i) => {\n width[i] = Math.max(width[i] ?? 0, cell.length);\n });\n }\n return rows\n .map((row) =>\n row\n .map((cell, i) => {\n const w = width[i] ?? 0;\n return alignRight.has(i) ? cell.padStart(w) : cell.padEnd(w);\n })\n .join(' ')\n .trimEnd(),\n )\n .join('\\n');\n}\n\n/**\n * Make header text safe to print to a terminal.\n *\n * EDF identification fields and channel labels are free text copied verbatim out of the\n * file, and `--info` puts them straight on stdout. A header carrying ANSI escapes could\n * therefore drive the reader's terminal — `\\x1b[2J\\x1b[H` clears the screen and homes the\n * cursor, which is enough to hide the rest of the output or repaint it as something else.\n * Nobody writes an EDF header that way on purpose, which is exactly why a file that does\n * should not be trusted with the terminal.\n *\n * Control bytes are shown as their escape instead, so a corrupt field stays diagnosable\n * rather than being silently swallowed. This affects display only: `channels.csv` and\n * `metadata.json` still copy the field verbatim, and CSV quoting already makes that safe.\n */\nexport function printable(text: string): string {\n // The character class and the escape are shared with the conversion, which asks the same\n // question of an annotation description; see src/format/unprintable.ts.\n return text.replace(unprintablePattern('gu'), escapeCharacter);\n}\n\n/**\n * The same protection for text that is meant to span lines.\n *\n * `printable` escapes newlines along with everything else, which is right for a channel\n * label — one has no business containing a line break, and it would break the `--info`\n * table's alignment. It is wrong for a whole message: several are written on two lines,\n * and Node's own option errors run to three. Escaping those turned the break into text:\n *\n * error: No channel named \"ECQ\". Did you mean \"ECG\"?\\x0aRun with --info to list ...\n *\n * Each line is escaped on its own, so nothing here gains the ability to drive a terminal.\n * A carriage return is still escaped, so no line can be repainted after it is printed —\n * which is the property that mattered. A newline can only add a line, never overwrite one.\n */\nexport function printableLines(text: string, indent = ''): string {\n return text\n .split('\\n')\n .map((line, index) => {\n const safe = printable(line);\n // The first line is the one that follows `error: ` or `warning: `, so it is the line\n // a log gets grepped for, and it stays whole at whatever width it runs to.\n if (index === 0) return safe;\n\n /*\n Callers write the continuation indent one of two ways: most pass it here and leave\n their message lines flush, but the two usage builders bake ` ` into the string\n itself because they are printed without an `error: ` prefix in front. Reading the\n line's own leading space when none was passed keeps both working, and keeps the\n wrap aligned under the same column either way.\n */\n const body = safe.trimStart();\n const pad = indent === '' ? safe.slice(0, safe.length - body.length) : indent;\n\n /*\n A continuation that is a command is copied, not read.\n\n `edf2csv -- \"--chanels\"` is the line the unknown-option error ends on, and it exists\n to be pasted back into the shell. Wrapping puts `edf2csv --` on one line and the\n flag on the next, and what gets pasted is half a command. Prose survives being\n re-flowed and a command does not, so the two are told apart rather than being\n treated alike and hoping today's strings stay short.\n */\n if (body.startsWith('edf2csv ')) return pad + body;\n return wrap(body, pad);\n })\n .join('\\n');\n}\n\n/** The `--info` view: what is in this recording, and what would converting it produce. */\nexport function formatInfo(\n file: EdfFile,\n plan: ConversionPlan,\n /**\n * How many events a conversion would write, when that is already known.\n *\n * Null when it is not. `--info` reads the whole annotation channel of a discontinuous file,\n * because that is where its record times are; a continuous one it reads only far enough to\n * find the origin. So the count is in hand for one of the two, and the line below said \"How\n * many events there are cannot be told from the header\" for both — true of the header, and\n * beside the point on a file whose events had just been read and counted.\n */\n events: number | null = null,\n /**\n * Whether the run would stream to stdout, in which case no file is written at all.\n *\n * The OUTPUT column is \"Named as they will be written. --info is read to find out what a\n * run leaves behind, and a script that opens the name it was given must find a file there\"\n * — and under `--stdout` it named `signals.csv`, or `signals.csv.gz`, for a run that\n * creates no directory and no file. The same table already tells a channel that will not\n * be converted from one the file gives nothing to convert; this is the third thing it\n * could not say.\n */\n toStdout = false,\n): string {\n const { header } = file;\n const lines: string[] = [];\n\n /*\n Escaped, like every other value that came out of the filesystem.\n\n A path is untrusted text: a folder may be named with an ESC byte, and a file name may\n hold a newline on every platform this runs on. The `[n/m]` header a batch prints has\n always escaped it and these two lines did not, so one line of a run reached the terminal\n as `study/esc\\x1b[31mred.edf` and the next as a live colour change — and a name holding a\n newline split `Wrote` across two lines, so the summary reported a path that reads as two.\n NONPRINTABLE_LABEL exists because a header field can carry these bytes; a directory entry\n can carry them just as easily.\n */\n lines.push(`File ${printable(file.path)}`);\n lines.push(`Format ${describeFormat(header)}`);\n /*\n The two raw fields, with edges.\n\n Echoed bare, they ran into each other and into the parenthetical, and a header field is\n free to be empty or to be nothing but padding — `trimField` takes the padding off, so\n both of those arrive here as \"\". A file whose date field is blank printed\n\n Recorded 22.15.00 (unparseable)\n\n where the one value on the line is the *time* and nothing says so, and a file with both\n blank printed `Recorded (unparseable)`: a label, a gap, and a verdict about nothing\n visible. ` . . ` in both fields came out `. . . .`, which is four fields or two\n depending on how the reader counts.\n\n Quoted, which is what `START_TIME_UNREADABLE` — the warning printed under this very line,\n about these very fields — has always done: `(\"\" and \"\")`. Same argument 0.7.x made for the\n time-range refusals, in its words: without them \"the value ran into the sentence ... and\n the surrounding spaces — the actual reason a shell-built argument went wrong — are\n invisible\". `--info --json` has the two as separate strings and never had the problem.\n */\n lines.push(\n `Recorded ${\n formatWallClock(header.startDateTime)?.replace('T', ' ') ??\n `\"${printable(header.startDateRaw)}\" \"${printable(header.startTimeRaw)}\" (unparseable)`\n }`,\n );\n lines.push(\n `Duration ${formatDuration(file.durationSeconds)} (${counted(file.recordCount, 'record')} of ${plain(header.recordDuration)}s)`,\n );\n const elapsedSpan = plan.range.recordingEndSeconds - plan.range.recordingStartSeconds;\n if (Math.abs(elapsedSpan - file.durationSeconds) > 1e-9) {\n /*\n Which way the two differ decides what to call it, and the parenthetical used to say\n \"includes discontinuities\" both ways round.\n\n A span LONGER than the duration is the gap case this line was written for: 3 records of\n 1s covering 11 seconds. A span SHORTER than the duration cannot be a gap — it is records\n that overlap, which an EDF+D file gets when a device re-sends a buffer. Three records of\n 1s starting at 0, 0.5 and 1 print:\n\n Duration 3s (3 records of 1s)\n Time span 2s (includes discontinuities)\n\n A recording covering less time than its own records account for, blamed on gaps it does\n not have — while the warning below it says, correctly, that two records overlap.\n\n A file holding both is described by whichever wins the subtraction, and the overlap\n warning is printed either way.\n */\n const overlapping = elapsedSpan < file.durationSeconds;\n lines.push(\n `Time span ${formatDuration(elapsedSpan)} ` +\n `(${overlapping ? 'records overlap in time' : 'includes discontinuities'})`,\n );\n }\n /*\n Where the samples begin, when that is not zero.\n\n 0.4.9 made the first record's timekeeping TAL the point a recording is timed from, so a\n file whose TALs start at +1000 writes `time_s` from 1000.000 and takes `--start` and\n `--end` on that same clock. None of that appeared here: the report said \"Duration 3s\",\n which reads as 0 to 3, and `--start 0 --end 1` then selected nothing and answered with\n \"The window is inside the recording but lands where there is no data ... Run with --info\n to see where the records actually sit\" — pointing at this report, which was the one place\n the number was missing. It is in `plan.range` already and governs the estimate printed\n below; it was simply never shown.\n */\n const startsAt = plan.range.recordingStartSeconds;\n if (Number.isFinite(startsAt) && Math.abs(startsAt) > 1e-9) {\n // In seconds rather than through formatDuration, because this number is meant to be\n // typed back in: `--start` takes `1000s`, and \"16m 40s\" is not something it accepts.\n // It is also how the empty-window warning renders the window it was given.\n //\n // Through `fixed` rather than `toFixed`, which switches to exponent notation at 1e21 —\n // and `--start 1e+21s` is refused by the time parser with \"uses an unknown unit \\\"e\\\"\",\n // so the one line that says which clock to use handed back a number that clock rejects.\n // Reachable from a conforming file: an EDF+ onset is plain digits of any length, and a\n // record duration large enough to keep samples apart at that magnitude is four\n // characters. `fixed` expands these with BigInt, which is exact past 2^53 where a double\n // carries no fraction anyway, and is byte-for-byte `toFixed` everywhere else.\n lines.push(\n `Timed from ${fixed(startsAt, 3)}s (first sample; --start and --end use this clock)`,\n );\n }\n /*\n And the window, when one was asked for, which this report did not mention at all.\n\n `--info` is the mode whose purpose is to say what a conversion will do, and every other\n flag that changes what gets written is visible in it: `--channels` puts `(not selected)`\n in the OUTPUT column, `--gzip` changes the names there, `--layout long` changes the\n sentence under the table, `--annotations-only` replaces the estimate outright. `--start`\n and `--end` changed one number:\n\n $ edf2csv rec.edf --info $ edf2csv rec.edf --info --start 1s --end 2s\n Duration 3s (3 records of 1s) Duration 3s (3 records of 1s)\n ... ...\n Would write 1,155 rows, roughly 22.2 KB. Would write 385 rows, roughly 7.4 KB.\n\n Byte-for-byte identical otherwise — and the Duration line, which is what a reader checks a\n window against, goes on describing the whole file above an estimate that describes a third\n of it. The window is in `plan.range` already, which is the same thing `Timed from` above\n was added for: it governs the estimate printed below and was simply never shown.\n\n In seconds rather than through `formatDuration`, for the reason that line gives: these are\n numbers meant to be typed back into `--start` and `--end`, and \"16m 40s\" is not one.\n */\n const { range } = plan;\n if (!range.isWholeRecording && Number.isFinite(range.startSeconds) && Number.isFinite(range.endSeconds)) {\n const records = range.endRecord - range.startRecord;\n lines.push(\n `Window ${fixed(range.startSeconds, 3)}s to ${fixed(range.endSeconds, 3)}s ` +\n `(${grouped(records)} of ${counted(file.recordCount, 'data record')})`,\n );\n }\n lines.push(`Size ${formatBytes(file.fileSize)}`);\n if (header.patientId) lines.push(`Patient ${printable(header.patientId)}`);\n if (header.recordingId) lines.push(`Recording ${printable(header.recordingId)}`);\n\n const signals = file.dataSignals;\n lines.push('');\n /*\n Both counts through `counted`, which this function already uses one line up for the record\n count and which exists so a count and its noun cannot disagree.\n\n The annotation-channel half was pluralised by hand when it was fixed — a file carrying two\n of them read \"2 annotation channel\", and EDF+ permits more than one — and the signal half\n had been hand-rolled since it was written. Two spellings of one rule in one line, in the\n file that imports the rule.\n */\n const annotationCount = file.annotationSignals.length;\n const annotationPart =\n annotationCount > 0 ? ` + ${counted(annotationCount, 'annotation channel')}` : '';\n lines.push(`Channels ${counted(signals.length, 'signal')}${annotationPart}`);\n lines.push('');\n\n const rows: string[][] = [['#', 'COLUMN', 'LABEL', 'UNIT', 'RATE', 'RANGE', 'OUTPUT']];\n const fileFor = new Map<number, string>();\n for (const group of plan.groups) {\n for (const channel of group.channels) fileFor.set(channel.signal.index, group.fileName);\n }\n // Rendered as a group so that two channels recorded at different rates never show the\n // same figure in the RATE column, which is the one thing this table is asked to settle.\n const rateText = formatRates(signals.map((signal) => signal.samplingRate));\n for (const [row, signal] of signals.entries()) {\n rows.push([\n String(signal.index),\n printable(plan.columnNames.get(signal.index) ?? ''),\n printable(signal.label),\n printable(signal.physicalDimension),\n `${rateText[row]} Hz`,\n `${signal.physicalMin} to ${signal.physicalMax}`,\n /*\n A channel with no samples was reported as \"(not selected)\", which is a different\n thing and not true when it was named on --channels. `edf2csv rec.edf --info\n --channels unused` said the channel the command asked for had not been chosen, when\n what is actually the case is that the file gives it nothing to convert. The\n NO_SAMPLES warning below the table says so; the table contradicted it.\n */\n /*\n And under --annotations-only nothing was deselected either — the run writes no signal\n table at all, which is the same distinction one paragraph up.\n\n `--info --annotations-only --channels \"EEG Fpz-Cz\"` accepted the name, checked it\n against the file, and then printed \"(not selected)\" against the very channel it had\n just been asked for. The sentence three lines under the table already says the truth,\n \"and no signal data\", and `channels.csv` and `--info --json` both say it too — the\n cell is empty and `output_file` is null. The human table was the one place claiming a\n choice nobody made.\n */\n plan.writeSignals\n ? fileFor.has(signal.index)\n ? toStdout\n ? '(stdout)'\n : (fileFor.get(signal.index) as string)\n : signal.samplesPerRecord === 0\n ? '(no samples)'\n : '(not selected)'\n : '(no signal data)',\n ]);\n }\n /*\n A column head over nothing is not a table.\n\n The line above has just said `Channels 0 signals + 1 annotation channel`, and this then\n printed\n\n # COLUMN LABEL UNIT RATE RANGE OUTPUT\n\n with no row under it — seven headings for a set of no channels, on a recording holding\n only events, which is what `annotations-only.edf` in this repository is and what a\n companion event file out of a scoring system is. The same sentence `--channels \"#0\"` was\n given its own wording for: \"No channel at position #0. This file has signal channels at\n .\" states there are some and then names none.\n\n Nothing goes in its place. The count is stated one line up and the body three lines down\n says what the conversion would write; a table saying \"none\" twice more adds nothing.\n */\n if (signals.length > 0) {\n lines.push(table(rows, new Set([0])));\n lines.push('');\n }\n /*\n From here down --info stops laying out columns and starts explaining itself, so from\n here down it wraps. The key-value lines and the channel table above are aligned to each\n other and must not be re-flowed; these are sentences, and the longest of them ran to 156\n columns — which is not a line anyone reads, it is a line a terminal breaks somewhere.\n --help has been written to 80 since it existed and hints joined it in 0.7.1; --info is\n the mode whose whole purpose is being read by a person, and it was the last one guessing.\n */\n if (plan.groups.length > 1) {\n /*\n And the third thing this sentence could not say, after the OUTPUT column above it.\n\n `--stdout` on a recording with more than one rate is refused — it writes one table and\n this makes several — so no file is written and the run does not happen. The sentence\n described it anyway, three lines under a column saying `(stdout)` and six above the\n warning that the run would be refused:\n\n 0 EEG Fpz-Cz ... 256 Hz -250 to 250 (stdout)\n Sampling rates differ, so channels are written to 3 files, one per rate.\n warning: --stdout would refuse this run: needs exactly one table, but this\n recording produces 3 ...\n\n Three statements about one run, and the middle one names an outcome none of the others\n allows. What the rates decide is how many tables there are; where those go is the\n question this mode has already answered differently.\n */\n lines.push(\n wrap(\n plan.layout === 'long'\n ? `Sampling rates differ, and the long layout puts them in one table anyway: each row ` +\n `carries its own time, so nothing has to line up. No channel is resampled.`\n : toStdout\n ? `Sampling rates differ, so this recording makes ${counted(plan.groups.length, 'table')}, ` +\n `one per rate — more than --stdout can write. Converting into a directory writes one ` +\n `file each; --layout long puts them all in one table.`\n : `Sampling rates differ, so channels are written to ${counted(plan.groups.length, 'file')}, one per rate. ` +\n `No channel is resampled.`,\n ),\n );\n }\n /*\n The estimate describes the signal tables, and says so when that is not what will be\n written.\n\n Under --annotations-only there are no signal tables, and the line read \"Would write 0\n rows, roughly 0 B.\" for a conversion that goes on to write annotations.csv with three\n events in it. --info exists to say what a conversion will do; asserting it will write\n nothing, when it will write a file, is the one thing it must not do.\n\n How many events there are cannot be answered from the header — the annotation channel has\n to be read record by record, which is the scan --info is for avoiding. So it says which\n file, and that the count is not knowable this cheaply, rather than inventing a zero.\n */\n /*\n No signal table to describe, whichever way that came about.\n\n This asked only whether `--annotations-only` had been given. A recording that has no\n signal channels — one holding nothing but EDF+ annotations — has none either, and fell\n through to the estimate line: \"Would write 0 rows, roughly 0 B.\" for a conversion that\n goes on to write an annotations.csv with events in it, beside channels.csv and\n metadata.json. That is the sentence 0.4.51 removed, arriving by the other route.\n */\n if (!plan.writeSignals || plan.groups.length === 0) {\n // Named as they will be written. --info is read to find out what a run leaves behind,\n // and a script that opens the name it was given must find a file there.\n const suffix = plan.gzip ? '.csv.gz' : '.csv';\n lines.push(\n wrap(\n file.annotationSignals.length > 0\n ? events === null\n ? `Would write annotations${suffix} and channels${suffix}, and no signal data. How ` +\n 'many events there are cannot be told from the header, and finding out means ' +\n 'reading the annotation channel record by record.'\n : `Would write annotations${suffix} with ${counted(events, 'event')} and ` +\n `channels${suffix}, and no signal data.`\n : `Would write channels${suffix} and no signal data — and no annotations${suffix} ` +\n 'either, since this recording has no annotation channel.',\n ),\n );\n return lines.join('\\n');\n }\n\n // The estimate counts the characters of the CSV, which is what --gzip then compresses.\n // Reporting it as the size on disk would overstate a compressed conversion several-fold.\n const compressing = plan.gzip;\n lines.push(\n wrap(\n // A window narrow enough to select one sample is an ordinary thing to ask for, and this\n // read \"Would write 1 rows, roughly 22 B.\" — the slip 0.5.74 fixed on the lines above it\n // and missed here, because the recording that test builds never estimates exactly one.\n `Would write ${counted(plan.estimate.rows, 'row')}, roughly ` +\n `${formatBytes(plan.estimate.bytes)}${compressing ? ' before compression' : ''}.`,\n ),\n );\n\n return lines.join('\\n');\n}\n\n/**\n * The `--info` view as JSON, for surveying files from a script.\n *\n * `indent` is 2 for a single recording, matching what this has always printed, and null for\n * a batch — several pretty-printed documents run together are readable by a streaming parser\n * but not by anything that expects one record per line, and a batch is exactly where\n * line-oriented reading is wanted. null rather than undefined because a default parameter\n * takes effect when undefined is passed, which quietly restored the indentation this was\n * meant to drop; JSON.stringify itself wants undefined, so it is translated at the call.\n *\n * `--info` answers \"what is in this recording and what would converting it cost\", which\n * is exactly the question you want to ask across a directory of hundreds of recordings —\n * and the text table is the wrong shape for that. `--json` previously applied only to\n * conversions, so scripts had to parse the aligned columns or convert files just to learn\n * what was in them.\n *\n * Field names match `metadata.json` where the two describe the same thing, so a survey and\n * a conversion can be read by the same code.\n */\nexport function infoJson(\n file: EdfFile,\n plan: ConversionPlan,\n /**\n * The event count, on the files where `--info` has already read and counted them.\n *\n * `formatInfo` has taken this since 0.7.x and prints it — \"Would write annotations.csv with\n * 3 events\" — and the same number was dropped on the way to the JSON, which is the surface\n * a script reads and the reason `--info --json` exists. Null where the count is not in\n * hand, by the same rule `estimate` is null for a run that writes no signal table: a\n * continuous file is read only as far as its origin, so its events have not been counted\n * and there is no honest number to put here.\n */\n events: number | null = null,\n indent: number | null = 2,\n /** See `formatInfo`: under `--stdout` there is no file to name. */\n toStdout = false,\n): string {\n const { header } = file;\n const fileFor = new Map<number, string>();\n for (const group of plan.groups) {\n for (const channel of group.channels) fileFor.set(channel.signal.index, group.fileName);\n }\n\n const document = JSON.stringify(\n {\n tool: TOOL,\n path: file.path,\n bytes: file.fileSize,\n format: describeFormat(header),\n start_datetime_local: formatWallClock(header.startDateTime),\n start_date_raw: header.startDateRaw,\n start_time_raw: header.startTimeRaw,\n patient_id: header.patientId,\n recording_id: header.recordingId,\n data_records: file.recordCount,\n data_records_declared: header.declaredRecordCount,\n record_duration_seconds: header.recordDuration,\n duration_seconds: file.durationSeconds,\n // For a discontinuous file this exceeds duration_seconds by the length of the gaps.\n time_span_seconds: plan.range.recordingEndSeconds - plan.range.recordingStartSeconds,\n // Where `time_s` begins, and the clock `--start` and `--end` are read against. Usually\n // zero; not when the first record's timekeeping TAL puts the recording elsewhere. Both\n // of the fields above are lengths and neither says where that length sits.\n first_sample_seconds: plan.range.recordingStartSeconds,\n /*\n The window, under the names `metadata.json` gives it, which is the rule this document\n follows for everything describing the run.\n\n The text form did not show it either until 0.8.82; here the only trace of `--start`\n and `--end` was `estimate.rows` coming back smaller, with nothing in the document\n saying why. A survey that runs `--info --json` over a folder with a window on the\n command line archives a description of each recording in which the window does not\n appear.\n */\n start_seconds: plan.range.startSeconds,\n end_seconds: plan.range.endSeconds,\n whole_recording: plan.range.isWholeRecording,\n annotation_channels: file.annotationSignals.length,\n // Named as `summaryJson` names the same count, so a prediction and a conversion read\n // the same field.\n annotations: events,\n channels: file.dataSignals.map((signal) => ({\n signal_index: signal.index,\n column: plan.columnNames.get(signal.index) ?? '',\n label: signal.label,\n unit: signal.physicalDimension,\n sampling_rate_hz: signal.samplingRate,\n samples_per_record: signal.samplesPerRecord,\n physical_min: signal.physicalMin,\n physical_max: signal.physicalMax,\n digital_min: signal.digitalMin,\n digital_max: signal.digitalMax,\n transducer: signal.transducer,\n prefiltering: signal.prefiltering,\n /*\n `-`, the placeholder `ConvertResult.outputDir` already uses for this mode, and not\n `null`: null is this document's word for \"would not be converted\", which is a\n different thing from \"converted, to a stream\".\n */\n output_file: fileFor.has(signal.index)\n ? toStdout\n ? '-'\n : (fileFor.get(signal.index) as string)\n : null,\n })),\n /*\n Null rather than zero when the run writes no signal table.\n\n The text form has refused to say \"Would write 0 rows, roughly 0 B.\" since 0.4.51,\n because a run that goes on to write an annotations.csv with events in it has not\n written nothing — and it is `--annotations-only`, or a recording holding only\n annotations, that reaches this. The JSON went on saying it to the surface a script\n reads. There is no estimate for a table that does not exist, and null is how this\n document already says that.\n */\n estimate:\n plan.writeSignals && plan.groups.length > 0\n ? {\n rows: plan.estimate.rows,\n // Character count of the CSV. With --gzip the file on disk is smaller than this.\n bytes: plan.estimate.bytes,\n exceeds_spreadsheet_limit: plan.estimate.exceedsSpreadsheetLimit,\n }\n : { rows: null, bytes: null, exceeds_spreadsheet_limit: false },\n // The plan's mixed-rate warning replaces the header parser's, as it does everywhere\n // else. This was the one consumer left out of that when 0.3.2 made the warning follow\n // --channels, so `--info --json` carried it twice: once counting the rates being\n // converted and once counting every rate in the file, with the same code and severity.\n // The file's own first, then the plan's, which is the order the text form prints them\n // in. Concatenating the other way round listed the same warnings about the same\n // recording in two different sequences depending on which form you asked for.\n warnings: withoutFileRateWarning(file.diagnostics)\n .concat(plan.diagnostics)\n .map((d) => ({ code: d.code, severity: d.severity, message: d.message })),\n },\n null,\n indent ?? undefined,\n );\n // A path is untrusted text on this surface too; see escapeJsonText.\n return escapeJsonText(document);\n}\n\n/**\n * One diagnostic per `warning: ` line, prefixed so warnings are greppable; the hint below it\n * wrapped to the terminal.\n *\n * The hint has been on its own unprefixed continuation line since these gained hints at all,\n * so grepping for `warning:` never picked it up and wrapping it costs nothing that was being\n * relied on — which is what 0.6.132 got wrong when it left every diagnostic long on the\n * grounds that they are one line each. Half of that is true. The `warning:` head is a line\n * per diagnostic and stays one, at whatever width the message runs to; the hint underneath\n * it is prose addressed to a person reading a terminal, and 17 of them ran past 80 columns,\n * the widest to 180. At that width the second half of the advice is wherever the terminal\n * decided to put it, indented under nothing, and the 9-space rule that says \"this belongs to\n * the warning above\" is lost at exactly the moment there is enough text for it to matter.\n */\nexport function formatDiagnostics(diagnostics: readonly Diagnostic[]): string {\n return diagnostics\n .map((d) => {\n // Diagnostics quote channel labels, which come from the file, so they need the\n // same treatment as the --info table.\n const head = `${d.severity}: ${printable(d.message)}`;\n return d.hint ? `${head}\\n${wrap(printable(d.hint), HINT_INDENT)}` : head;\n })\n .join('\\n');\n}\n\nexport function formatSummary(result: ConvertResult): string {\n const lines: string[] = [];\n const rows: string[][] = [];\n for (const file of result.files) {\n // `.csv.gz` is still a CSV, and its rows are still rows. The suffix test dropped the\n // unit from every line of a --gzip summary, so the numbers stood on their own.\n rows.push([\n ` ${file.name}`,\n grouped(file.rows),\n // Singular at one, like every other count this prints: a one-row table is what a\n // narrow window produces, and \"1 rows\" is the same slip 0.5.74 fixed elsewhere.\n /\\.csv(\\.gz)?$/u.test(file.name) ? (file.rows === 1 ? 'row' : 'rows') : '',\n ]);\n }\n lines.push(`Wrote ${printable(result.outputDir)}`); // Escaped; see the File line above.\n lines.push(table(rows, new Set([1])));\n lines.push(`Done in ${elapsed(result.elapsedMs)}.`);\n return lines.join('\\n');\n}\n\n/**\n * How long the run took, in a unit it can be stated in.\n *\n * `elapsedMs` is a difference of two `Date.now()` readings, so it is whole milliseconds, and\n * `(ms / 1000).toFixed(1)` rounds everything under fifty of them to `0.0`. That is the last\n * line of every conversion of a small recording — `--annotations-only` on a three-record\n * file, every fixture in this repository, and the transcript on three documentation pages,\n * all of which read `Done in 0.0s.` for a run that read a file and wrote three.\n *\n * The same refusal `formatDuration` and `formatBytes` make one file over, and for the reason\n * stated there: none of them is a rounding rule, and each declines to print a form the\n * quantity cannot take — 1023.999 KB is not \"1024 KB\", two records of 1e-15s are not \"0s\",\n * and a conversion that happened did not take no time.\n *\n * A clock that reports no change at all has measured something below what it can resolve,\n * which is a different statement from zero and is what it says.\n */\nexport function elapsed(milliseconds: number): string {\n /*\n And the other end of it, which could only say seconds.\n\n This is the one place in the tool that states a length of time without `formatDuration`,\n and it is the line under a summary whose `Duration` field is printed *with* it. A\n conversion of an overnight recording read:\n\n Duration 8h 00m 0s (28800 records of 1s)\n ...\n Done in 412.7s.\n\n Two lengths of time on one screen, one decomposed and one not, from the same program. 412\n seconds is a number a reader has to divide by sixty to hold, which is the whole reason\n `formatDuration` exists and the same complaint `grouped` makes about counts.\n\n Handed over at a minute, since below that the seconds are the readable form — and rounded\n to the tenth this already prints first, because `formatDuration` keeps three decimals and\n \"6m 52.734s\" claims a precision two `Date.now()` readings do not have.\n */\n if (milliseconds >= 60_000) return formatDuration(Math.round(milliseconds / 100) / 10);\n if (milliseconds >= 50) return `${(milliseconds / 1000).toFixed(1)}s`;\n return milliseconds > 0 ? `${milliseconds}ms` : 'under 1ms';\n}\n\n/**\n * Which version produced this record.\n *\n * `metadata.json` has carried it since the file existed, because a conversion should be\n * reproducible later. The two JSON *streams* did not, and they are the ones most likely to\n * outlive the run: `--json` exists to be piped into something, logged, or committed beside a\n * result, where the question a year on is which release's field names and rounding these are.\n * The same shape as metadata.json's, so a consumer reads one field either way.\n */\nconst TOOL = { name: 'edf2csv', version: VERSION } as const;\n\nexport function summaryJson(result: ConvertResult, indent: number | null = 2): string {\n const document = JSON.stringify(\n {\n tool: TOOL,\n output_dir: result.outputDir,\n files: result.files,\n annotations: result.annotationCount,\n duration_seconds: result.file.durationSeconds,\n records: result.file.recordCount,\n elapsed_ms: result.elapsedMs,\n warnings: result.diagnostics.map((d) => ({ code: d.code, severity: d.severity, message: d.message })),\n },\n null,\n indent ?? undefined,\n );\n // A path is untrusted text on this surface too; see escapeJsonText.\n return escapeJsonText(document);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"report.js","sourceRoot":"","sources":["../../src/cli/report.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAChF,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,KAAK,EAAE,MA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CAAC;IACvF,IAAI,YAAY,IAAI,EAAE;QAAE,OAAO,GAAG,CAAC,YAAY,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC;IACtE,OAAO,YAAY,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,YAAY,IAAI,CAAC,CAAC,CAAC,WAAW,CAAC;AAC9D,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,IAAI,GAAG,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,EAAW,CAAC;AAE5D,MAAM,UAAU,WAAW,CAAC,MAAqB,EAAE,SAAwB,CAAC;IAC1E,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,CAC7B;QACE,IAAI,EAAE,IAAI;QACV,UAAU,EAAE,MAAM,CAAC,SAAS;QAC5B,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,WAAW,EAAE,MAAM,CAAC,eAAe;QACnC,gBAAgB,EAAE,MAAM,CAAC,IAAI,CAAC,eAAe;QAC7C,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,WAAW;QAChC,UAAU,EAAE,MAAM,CAAC,SAAS;QAC5B,QAAQ,EAAE,MAAM,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;KACtG,EACD,IAAI,EACJ,MAAM,IAAI,SAAS,CACpB,CAAC;IACF,oEAAoE;IACpE,OAAO,cAAc,CAAC,QAAQ,CAAC,CAAC;AAClC,CAAC","sourcesContent":["/**\n * Human-readable output for the terminal.\n *\n * Everything here is plain text with no colour codes, so piping to a file or a log\n * produces exactly what appeared on screen.\n */\n\nimport type { Diagnostic } from '../edf/errors.js';\nimport type { EdfFile } from '../edf/reader.js';\nimport { describeFormat, formatRates, formatWallClock } from '../edf/header.js';\nimport { fixed, formatBytes, formatDuration, plain } from '../format/number.js';\nimport { counted, grouped } from '../format/list.js';\nimport { escapeJsonText, printable } from '../format/unprintable.js';\nimport type { ConversionPlan } from '../convert/plan.js';\nimport { withoutFileRateWarning } from '../convert/plan.js';\nimport type { ConvertResult } from '../convert/run.js';\nimport { VERSION } from '../version.js';\n\n/** Where terminal prose wraps. The width --help is written to, and the ANSI default. */\nconst WRAP_COLUMNS = 80;\n\n/** The continuation indent under a `warning: ` prefix, which is the only one there is. */\nconst HINT_INDENT = ' '.repeat(9);\n\n/**\n * One unbreakable unit of a wrapped line: a quoted span, or a run of non-space.\n *\n * The lookbehind is what keeps an apostrophe out of it. `the file's own header and it's` has\n * two of them, and without the guard `'s own header and it'` is one quoted span — a token\n * with spaces in it that then refuses to break. A quote opening a span is at the start of a\n * word, so that is what is required of it.\n */\nconst WORD = /(?<=^|[\\s(])(?:\"[^\"]*\"|'[^']*')|\\S+/gu;\n\n/**\n * Greedy word wrap, `indent` on every line including the first.\n *\n * Only free prose goes through this. The aligned parts of `--info` — the `Format`/`Size`\n * key-value lines and the channel table — are laid out in columns, and re-flowing a column\n * is how you turn a table into a paragraph.\n *\n * A word wider than the column is left to overrun rather than broken. The long words here\n * are file paths and quoted channel labels, and neither survives being split across lines:\n * the point of printing a path is that it can be copied back out.\n *\n * A quoted span is one word for the same reason, however many spaces are inside it. The\n * sentence above is the promise, and it held only for the paths that have no spaces in them:\n * an interrupted conversion said `Files already written to \"/tmp/a very long destination\n * folder name with` / `many spaces here indeed\" are incomplete`, splitting the one thing on\n * the line that has to be copied whole — and quoting is what a path with spaces in it is\n * given in the first place. A word wider than the column already overruns rather than\n * breaking; this is that rule reaching the words it was written for.\n *\n * Which is also why the gap between two words is reproduced rather than normalised to one\n * space. Splitting on `\\s+` and rejoining with `' '` re-flowed everything, and a quoted value\n * is not prose: a channel labelled `EEG A` was offered back as `Did you mean \"EEG A\"?`, and\n * a destination given as `-my nightly` as `Write it as one argument instead:\n * '--out=-my nightly'`. Following either gets a different channel or a different directory\n * than the one the sentence is about, and the run before it had already quoted the name\n * correctly on the line above.\n */\nexport function wrap(text: string, indent = '', width = WRAP_COLUMNS): string {\n const lines: string[] = [];\n let line = indent;\n let at = 0;\n for (const match of text.matchAll(WORD)) {\n const piece = match[0];\n const gap = text.slice(at, match.index);\n at = match.index + piece.length;\n if (line === indent) line += piece;\n else if (line.length + gap.length + piece.length <= width) line += gap + piece;\n else {\n lines.push(line);\n line = indent + piece;\n }\n }\n if (line !== indent) lines.push(line);\n return lines.join('\\n');\n}\n\nfunction table(rows: readonly (readonly string[])[], alignRight: ReadonlySet<number>): string {\n if (rows.length === 0) return '';\n const width: number[] = [];\n for (const row of rows) {\n row.forEach((cell, i) => {\n width[i] = Math.max(width[i] ?? 0, cell.length);\n });\n }\n return rows\n .map((row) =>\n row\n .map((cell, i) => {\n const w = width[i] ?? 0;\n return alignRight.has(i) ? cell.padStart(w) : cell.padEnd(w);\n })\n .join(' ')\n .trimEnd(),\n )\n .join('\\n');\n}\n\n/**\n * Make header text safe to print to a terminal.\n *\n * EDF identification fields and channel labels are free text copied verbatim out of the\n * file, and `--info` puts them straight on stdout. A header carrying ANSI escapes could\n * therefore drive the reader's terminal — `\\x1b[2J\\x1b[H` clears the screen and homes the\n * cursor, which is enough to hide the rest of the output or repaint it as something else.\n * Nobody writes an EDF header that way on purpose, which is exactly why a file that does\n * should not be trusted with the terminal.\n *\n * Control bytes are shown as their escape instead, so a corrupt field stays diagnosable\n * rather than being silently swallowed. This affects display only: `channels.csv` and\n * `metadata.json` still copy the field verbatim, and CSV quoting already makes that safe.\n */\n// Defined in src/format/unprintable.ts, beside the character class it uses, since the library's\n// own message builders need it too — see 0.8.92. Re-exported here, which is where every caller\n// in this package already imports it from.\nexport { printable };\n\n/**\n * The same protection for text that is meant to span lines.\n *\n * `printable` escapes newlines along with everything else, which is right for a channel\n * label — one has no business containing a line break, and it would break the `--info`\n * table's alignment. It is wrong for a whole message: several are written on two lines,\n * and Node's own option errors run to three. Escaping those turned the break into text:\n *\n * error: No channel named \"ECQ\". Did you mean \"ECG\"?\\x0aRun with --info to list ...\n *\n * Each line is escaped on its own, so nothing here gains the ability to drive a terminal.\n * A carriage return is still escaped, so no line can be repainted after it is printed —\n * which is the property that mattered. A newline can only add a line, never overwrite one.\n */\nexport function printableLines(text: string, indent = ''): string {\n return text\n .split('\\n')\n .map((line, index) => {\n const safe = printable(line);\n // The first line is the one that follows `error: ` or `warning: `, so it is the line\n // a log gets grepped for, and it stays whole at whatever width it runs to.\n if (index === 0) return safe;\n\n /*\n Callers write the continuation indent one of two ways: most pass it here and leave\n their message lines flush, but the two usage builders bake ` ` into the string\n itself because they are printed without an `error: ` prefix in front. Reading the\n line's own leading space when none was passed keeps both working, and keeps the\n wrap aligned under the same column either way.\n */\n const body = safe.trimStart();\n const pad = indent === '' ? safe.slice(0, safe.length - body.length) : indent;\n\n /*\n A continuation that is a command is copied, not read.\n\n `edf2csv -- \"--chanels\"` is the line the unknown-option error ends on, and it exists\n to be pasted back into the shell. Wrapping puts `edf2csv --` on one line and the\n flag on the next, and what gets pasted is half a command. Prose survives being\n re-flowed and a command does not, so the two are told apart rather than being\n treated alike and hoping today's strings stay short.\n */\n if (body.startsWith('edf2csv ')) return pad + body;\n return wrap(body, pad);\n })\n .join('\\n');\n}\n\n/** The `--info` view: what is in this recording, and what would converting it produce. */\nexport function formatInfo(\n file: EdfFile,\n plan: ConversionPlan,\n /**\n * How many events a conversion would write, when that is already known.\n *\n * Null when it is not. `--info` reads the whole annotation channel of a discontinuous file,\n * because that is where its record times are; a continuous one it reads only far enough to\n * find the origin. So the count is in hand for one of the two, and the line below said \"How\n * many events there are cannot be told from the header\" for both — true of the header, and\n * beside the point on a file whose events had just been read and counted.\n */\n events: number | null = null,\n /**\n * Whether the run would stream to stdout, in which case no file is written at all.\n *\n * The OUTPUT column is \"Named as they will be written. --info is read to find out what a\n * run leaves behind, and a script that opens the name it was given must find a file there\"\n * — and under `--stdout` it named `signals.csv`, or `signals.csv.gz`, for a run that\n * creates no directory and no file. The same table already tells a channel that will not\n * be converted from one the file gives nothing to convert; this is the third thing it\n * could not say.\n */\n toStdout = false,\n): string {\n const { header } = file;\n const lines: string[] = [];\n\n /*\n Escaped, like every other value that came out of the filesystem.\n\n A path is untrusted text: a folder may be named with an ESC byte, and a file name may\n hold a newline on every platform this runs on. The `[n/m]` header a batch prints has\n always escaped it and these two lines did not, so one line of a run reached the terminal\n as `study/esc\\x1b[31mred.edf` and the next as a live colour change — and a name holding a\n newline split `Wrote` across two lines, so the summary reported a path that reads as two.\n NONPRINTABLE_LABEL exists because a header field can carry these bytes; a directory entry\n can carry them just as easily.\n */\n lines.push(`File ${printable(file.path)}`);\n lines.push(`Format ${describeFormat(header)}`);\n /*\n The two raw fields, with edges.\n\n Echoed bare, they ran into each other and into the parenthetical, and a header field is\n free to be empty or to be nothing but padding — `trimField` takes the padding off, so\n both of those arrive here as \"\". A file whose date field is blank printed\n\n Recorded 22.15.00 (unparseable)\n\n where the one value on the line is the *time* and nothing says so, and a file with both\n blank printed `Recorded (unparseable)`: a label, a gap, and a verdict about nothing\n visible. ` . . ` in both fields came out `. . . .`, which is four fields or two\n depending on how the reader counts.\n\n Quoted, which is what `START_TIME_UNREADABLE` — the warning printed under this very line,\n about these very fields — has always done: `(\"\" and \"\")`. Same argument 0.7.x made for the\n time-range refusals, in its words: without them \"the value ran into the sentence ... and\n the surrounding spaces — the actual reason a shell-built argument went wrong — are\n invisible\". `--info --json` has the two as separate strings and never had the problem.\n */\n lines.push(\n `Recorded ${\n formatWallClock(header.startDateTime)?.replace('T', ' ') ??\n `\"${printable(header.startDateRaw)}\" \"${printable(header.startTimeRaw)}\" (unparseable)`\n }`,\n );\n lines.push(\n `Duration ${formatDuration(file.durationSeconds)} (${counted(file.recordCount, 'record')} of ${plain(header.recordDuration)}s)`,\n );\n const elapsedSpan = plan.range.recordingEndSeconds - plan.range.recordingStartSeconds;\n if (Math.abs(elapsedSpan - file.durationSeconds) > 1e-9) {\n /*\n Which way the two differ decides what to call it, and the parenthetical used to say\n \"includes discontinuities\" both ways round.\n\n A span LONGER than the duration is the gap case this line was written for: 3 records of\n 1s covering 11 seconds. A span SHORTER than the duration cannot be a gap — it is records\n that overlap, which an EDF+D file gets when a device re-sends a buffer. Three records of\n 1s starting at 0, 0.5 and 1 print:\n\n Duration 3s (3 records of 1s)\n Time span 2s (includes discontinuities)\n\n A recording covering less time than its own records account for, blamed on gaps it does\n not have — while the warning below it says, correctly, that two records overlap.\n\n A file holding both is described by whichever wins the subtraction, and the overlap\n warning is printed either way.\n */\n const overlapping = elapsedSpan < file.durationSeconds;\n lines.push(\n `Time span ${formatDuration(elapsedSpan)} ` +\n `(${overlapping ? 'records overlap in time' : 'includes discontinuities'})`,\n );\n }\n /*\n Where the samples begin, when that is not zero.\n\n 0.4.9 made the first record's timekeeping TAL the point a recording is timed from, so a\n file whose TALs start at +1000 writes `time_s` from 1000.000 and takes `--start` and\n `--end` on that same clock. None of that appeared here: the report said \"Duration 3s\",\n which reads as 0 to 3, and `--start 0 --end 1` then selected nothing and answered with\n \"The window is inside the recording but lands where there is no data ... Run with --info\n to see where the records actually sit\" — pointing at this report, which was the one place\n the number was missing. It is in `plan.range` already and governs the estimate printed\n below; it was simply never shown.\n */\n const startsAt = plan.range.recordingStartSeconds;\n if (Number.isFinite(startsAt) && Math.abs(startsAt) > 1e-9) {\n // In seconds rather than through formatDuration, because this number is meant to be\n // typed back in: `--start` takes `1000s`, and \"16m 40s\" is not something it accepts.\n // It is also how the empty-window warning renders the window it was given.\n //\n // Through `fixed` rather than `toFixed`, which switches to exponent notation at 1e21 —\n // and `--start 1e+21s` is refused by the time parser with \"uses an unknown unit \\\"e\\\"\",\n // so the one line that says which clock to use handed back a number that clock rejects.\n // Reachable from a conforming file: an EDF+ onset is plain digits of any length, and a\n // record duration large enough to keep samples apart at that magnitude is four\n // characters. `fixed` expands these with BigInt, which is exact past 2^53 where a double\n // carries no fraction anyway, and is byte-for-byte `toFixed` everywhere else.\n lines.push(\n `Timed from ${fixed(startsAt, 3)}s (first sample; --start and --end use this clock)`,\n );\n }\n /*\n And the window, when one was asked for, which this report did not mention at all.\n\n `--info` is the mode whose purpose is to say what a conversion will do, and every other\n flag that changes what gets written is visible in it: `--channels` puts `(not selected)`\n in the OUTPUT column, `--gzip` changes the names there, `--layout long` changes the\n sentence under the table, `--annotations-only` replaces the estimate outright. `--start`\n and `--end` changed one number:\n\n $ edf2csv rec.edf --info $ edf2csv rec.edf --info --start 1s --end 2s\n Duration 3s (3 records of 1s) Duration 3s (3 records of 1s)\n ... ...\n Would write 1,155 rows, roughly 22.2 KB. Would write 385 rows, roughly 7.4 KB.\n\n Byte-for-byte identical otherwise — and the Duration line, which is what a reader checks a\n window against, goes on describing the whole file above an estimate that describes a third\n of it. The window is in `plan.range` already, which is the same thing `Timed from` above\n was added for: it governs the estimate printed below and was simply never shown.\n\n In seconds rather than through `formatDuration`, for the reason that line gives: these are\n numbers meant to be typed back into `--start` and `--end`, and \"16m 40s\" is not one.\n */\n const { range } = plan;\n if (!range.isWholeRecording && Number.isFinite(range.startSeconds) && Number.isFinite(range.endSeconds)) {\n /*\n What the window selects, which is not data records in every mode.\n\n `--annotations-only` reads the annotation channel and converts no data records at all —\n the OUTPUT column of the table below says `(no signal data)` for every channel, and the\n line under it says \"and no signal data\". This counted them anyway:\n\n Window 1.000s to 3.000s (2 of 3 data records)\n ...\n Would write annotations.csv and channels.csv, and no signal data.\n\n The window is not idle in that mode: it decides which events are exported, by onset. So\n the range stays and the parenthetical says what it is doing.\n */\n const selects = plan.writeSignals\n ? `${grouped(range.endRecord - range.startRecord)} of ${counted(file.recordCount, 'data record')}`\n : 'events outside it are not exported';\n lines.push(\n `Window ${fixed(range.startSeconds, 3)}s to ${fixed(range.endSeconds, 3)}s (${selects})`,\n );\n }\n lines.push(`Size ${formatBytes(file.fileSize)}`);\n if (header.patientId) lines.push(`Patient ${printable(header.patientId)}`);\n if (header.recordingId) lines.push(`Recording ${printable(header.recordingId)}`);\n\n const signals = file.dataSignals;\n lines.push('');\n /*\n Both counts through `counted`, which this function already uses one line up for the record\n count and which exists so a count and its noun cannot disagree.\n\n The annotation-channel half was pluralised by hand when it was fixed — a file carrying two\n of them read \"2 annotation channel\", and EDF+ permits more than one — and the signal half\n had been hand-rolled since it was written. Two spellings of one rule in one line, in the\n file that imports the rule.\n */\n const annotationCount = file.annotationSignals.length;\n const annotationPart =\n annotationCount > 0 ? ` + ${counted(annotationCount, 'annotation channel')}` : '';\n lines.push(`Channels ${counted(signals.length, 'signal')}${annotationPart}`);\n lines.push('');\n\n const rows: string[][] = [['#', 'COLUMN', 'LABEL', 'UNIT', 'RATE', 'RANGE', 'OUTPUT']];\n const fileFor = new Map<number, string>();\n for (const group of plan.groups) {\n for (const channel of group.channels) fileFor.set(channel.signal.index, group.fileName);\n }\n // Rendered as a group so that two channels recorded at different rates never show the\n // same figure in the RATE column, which is the one thing this table is asked to settle.\n const rateText = formatRates(signals.map((signal) => signal.samplingRate));\n for (const [row, signal] of signals.entries()) {\n rows.push([\n String(signal.index),\n printable(plan.columnNames.get(signal.index) ?? ''),\n printable(signal.label),\n printable(signal.physicalDimension),\n `${rateText[row]} Hz`,\n `${signal.physicalMin} to ${signal.physicalMax}`,\n /*\n A channel with no samples was reported as \"(not selected)\", which is a different\n thing and not true when it was named on --channels. `edf2csv rec.edf --info\n --channels unused` said the channel the command asked for had not been chosen, when\n what is actually the case is that the file gives it nothing to convert. The\n NO_SAMPLES warning below the table says so; the table contradicted it.\n */\n /*\n And under --annotations-only nothing was deselected either — the run writes no signal\n table at all, which is the same distinction one paragraph up.\n\n `--info --annotations-only --channels \"EEG Fpz-Cz\"` accepted the name, checked it\n against the file, and then printed \"(not selected)\" against the very channel it had\n just been asked for. The sentence three lines under the table already says the truth,\n \"and no signal data\", and `channels.csv` and `--info --json` both say it too — the\n cell is empty and `output_file` is null. The human table was the one place claiming a\n choice nobody made.\n */\n plan.writeSignals\n ? fileFor.has(signal.index)\n ? toStdout\n ? '(stdout)'\n : (fileFor.get(signal.index) as string)\n : signal.samplesPerRecord === 0\n ? '(no samples)'\n : '(not selected)'\n : '(no signal data)',\n ]);\n }\n /*\n A column head over nothing is not a table.\n\n The line above has just said `Channels 0 signals + 1 annotation channel`, and this then\n printed\n\n # COLUMN LABEL UNIT RATE RANGE OUTPUT\n\n with no row under it — seven headings for a set of no channels, on a recording holding\n only events, which is what `annotations-only.edf` in this repository is and what a\n companion event file out of a scoring system is. The same sentence `--channels \"#0\"` was\n given its own wording for: \"No channel at position #0. This file has signal channels at\n .\" states there are some and then names none.\n\n Nothing goes in its place. The count is stated one line up and the body three lines down\n says what the conversion would write; a table saying \"none\" twice more adds nothing.\n */\n if (signals.length > 0) {\n lines.push(table(rows, new Set([0])));\n lines.push('');\n }\n /*\n From here down --info stops laying out columns and starts explaining itself, so from\n here down it wraps. The key-value lines and the channel table above are aligned to each\n other and must not be re-flowed; these are sentences, and the longest of them ran to 156\n columns — which is not a line anyone reads, it is a line a terminal breaks somewhere.\n --help has been written to 80 since it existed and hints joined it in 0.7.1; --info is\n the mode whose whole purpose is being read by a person, and it was the last one guessing.\n */\n if (plan.groups.length > 1) {\n /*\n And the third thing this sentence could not say, after the OUTPUT column above it.\n\n `--stdout` on a recording with more than one rate is refused — it writes one table and\n this makes several — so no file is written and the run does not happen. The sentence\n described it anyway, three lines under a column saying `(stdout)` and six above the\n warning that the run would be refused:\n\n 0 EEG Fpz-Cz ... 256 Hz -250 to 250 (stdout)\n Sampling rates differ, so channels are written to 3 files, one per rate.\n warning: --stdout would refuse this run: needs exactly one table, but this\n recording produces 3 ...\n\n Three statements about one run, and the middle one names an outcome none of the others\n allows. What the rates decide is how many tables there are; where those go is the\n question this mode has already answered differently.\n */\n lines.push(\n wrap(\n plan.layout === 'long'\n ? `Sampling rates differ, and the long layout puts them in one table anyway: each row ` +\n `carries its own time, so nothing has to line up. No channel is resampled.`\n : toStdout\n ? `Sampling rates differ, so this recording makes ${counted(plan.groups.length, 'table')}, ` +\n `one per rate — more than --stdout can write. Converting into a directory writes one ` +\n `file each; --layout long puts them all in one table.`\n : `Sampling rates differ, so channels are written to ${counted(plan.groups.length, 'file')}, one per rate. ` +\n `No channel is resampled.`,\n ),\n );\n }\n /*\n The estimate describes the signal tables, and says so when that is not what will be\n written.\n\n Under --annotations-only there are no signal tables, and the line read \"Would write 0\n rows, roughly 0 B.\" for a conversion that goes on to write annotations.csv with three\n events in it. --info exists to say what a conversion will do; asserting it will write\n nothing, when it will write a file, is the one thing it must not do.\n\n How many events there are cannot be answered from the header — the annotation channel has\n to be read record by record, which is the scan --info is for avoiding. So it says which\n file, and that the count is not knowable this cheaply, rather than inventing a zero.\n */\n /*\n No signal table to describe, whichever way that came about.\n\n This asked only whether `--annotations-only` had been given. A recording that has no\n signal channels — one holding nothing but EDF+ annotations — has none either, and fell\n through to the estimate line: \"Would write 0 rows, roughly 0 B.\" for a conversion that\n goes on to write an annotations.csv with events in it, beside channels.csv and\n metadata.json. That is the sentence 0.4.51 removed, arriving by the other route.\n */\n if (!plan.writeSignals || plan.groups.length === 0) {\n // Named as they will be written. --info is read to find out what a run leaves behind,\n // and a script that opens the name it was given must find a file there.\n const suffix = plan.gzip ? '.csv.gz' : '.csv';\n lines.push(\n wrap(\n file.annotationSignals.length > 0\n ? events === null\n ? `Would write annotations${suffix} and channels${suffix}, and no signal data. How ` +\n 'many events there are cannot be told from the header, and finding out means ' +\n 'reading the annotation channel record by record.'\n : `Would write annotations${suffix} with ${counted(events, 'event')} and ` +\n `channels${suffix}, and no signal data.`\n : `Would write channels${suffix} and no signal data — and no annotations${suffix} ` +\n 'either, since this recording has no annotation channel.',\n ),\n );\n return lines.join('\\n');\n }\n\n // The estimate counts the characters of the CSV, which is what --gzip then compresses.\n // Reporting it as the size on disk would overstate a compressed conversion several-fold.\n const compressing = plan.gzip;\n lines.push(\n wrap(\n // A window narrow enough to select one sample is an ordinary thing to ask for, and this\n // read \"Would write 1 rows, roughly 22 B.\" — the slip 0.5.74 fixed on the lines above it\n // and missed here, because the recording that test builds never estimates exactly one.\n `Would write ${counted(plan.estimate.rows, 'row')}, roughly ` +\n `${formatBytes(plan.estimate.bytes)}${compressing ? ' before compression' : ''}.`,\n ),\n );\n\n return lines.join('\\n');\n}\n\n/**\n * The `--info` view as JSON, for surveying files from a script.\n *\n * `indent` is 2 for a single recording, matching what this has always printed, and null for\n * a batch — several pretty-printed documents run together are readable by a streaming parser\n * but not by anything that expects one record per line, and a batch is exactly where\n * line-oriented reading is wanted. null rather than undefined because a default parameter\n * takes effect when undefined is passed, which quietly restored the indentation this was\n * meant to drop; JSON.stringify itself wants undefined, so it is translated at the call.\n *\n * `--info` answers \"what is in this recording and what would converting it cost\", which\n * is exactly the question you want to ask across a directory of hundreds of recordings —\n * and the text table is the wrong shape for that. `--json` previously applied only to\n * conversions, so scripts had to parse the aligned columns or convert files just to learn\n * what was in them.\n *\n * Field names match `metadata.json` where the two describe the same thing, so a survey and\n * a conversion can be read by the same code.\n */\nexport function infoJson(\n file: EdfFile,\n plan: ConversionPlan,\n /**\n * The event count, on the files where `--info` has already read and counted them.\n *\n * `formatInfo` has taken this since 0.7.x and prints it — \"Would write annotations.csv with\n * 3 events\" — and the same number was dropped on the way to the JSON, which is the surface\n * a script reads and the reason `--info --json` exists. Null where the count is not in\n * hand, by the same rule `estimate` is null for a run that writes no signal table: a\n * continuous file is read only as far as its origin, so its events have not been counted\n * and there is no honest number to put here.\n */\n events: number | null = null,\n indent: number | null = 2,\n /** See `formatInfo`: under `--stdout` there is no file to name. */\n toStdout = false,\n): string {\n const { header } = file;\n const fileFor = new Map<number, string>();\n for (const group of plan.groups) {\n for (const channel of group.channels) fileFor.set(channel.signal.index, group.fileName);\n }\n\n const document = JSON.stringify(\n {\n tool: TOOL,\n path: file.path,\n bytes: file.fileSize,\n format: describeFormat(header),\n start_datetime_local: formatWallClock(header.startDateTime),\n start_date_raw: header.startDateRaw,\n start_time_raw: header.startTimeRaw,\n patient_id: header.patientId,\n recording_id: header.recordingId,\n data_records: file.recordCount,\n data_records_declared: header.declaredRecordCount,\n record_duration_seconds: header.recordDuration,\n duration_seconds: file.durationSeconds,\n // For a discontinuous file this exceeds duration_seconds by the length of the gaps.\n time_span_seconds: plan.range.recordingEndSeconds - plan.range.recordingStartSeconds,\n // Where `time_s` begins, and the clock `--start` and `--end` are read against. Usually\n // zero; not when the first record's timekeeping TAL puts the recording elsewhere. Both\n // of the fields above are lengths and neither says where that length sits.\n first_sample_seconds: plan.range.recordingStartSeconds,\n /*\n The window, under the names `metadata.json` gives it, which is the rule this document\n follows for everything describing the run.\n\n The text form did not show it either until 0.8.82; here the only trace of `--start`\n and `--end` was `estimate.rows` coming back smaller, with nothing in the document\n saying why. A survey that runs `--info --json` over a folder with a window on the\n command line archives a description of each recording in which the window does not\n appear.\n */\n start_seconds: plan.range.startSeconds,\n end_seconds: plan.range.endSeconds,\n whole_recording: plan.range.isWholeRecording,\n annotation_channels: file.annotationSignals.length,\n // Named as `summaryJson` names the same count, so a prediction and a conversion read\n // the same field.\n annotations: events,\n channels: file.dataSignals.map((signal) => ({\n signal_index: signal.index,\n column: plan.columnNames.get(signal.index) ?? '',\n label: signal.label,\n unit: signal.physicalDimension,\n sampling_rate_hz: signal.samplingRate,\n samples_per_record: signal.samplesPerRecord,\n physical_min: signal.physicalMin,\n physical_max: signal.physicalMax,\n digital_min: signal.digitalMin,\n digital_max: signal.digitalMax,\n transducer: signal.transducer,\n prefiltering: signal.prefiltering,\n /*\n `-`, the placeholder `ConvertResult.outputDir` already uses for this mode, and not\n `null`: null is this document's word for \"would not be converted\", which is a\n different thing from \"converted, to a stream\".\n */\n output_file: fileFor.has(signal.index)\n ? toStdout\n ? '-'\n : (fileFor.get(signal.index) as string)\n : null,\n })),\n /*\n Null rather than zero when the run writes no signal table.\n\n The text form has refused to say \"Would write 0 rows, roughly 0 B.\" since 0.4.51,\n because a run that goes on to write an annotations.csv with events in it has not\n written nothing — and it is `--annotations-only`, or a recording holding only\n annotations, that reaches this. The JSON went on saying it to the surface a script\n reads. There is no estimate for a table that does not exist, and null is how this\n document already says that.\n */\n estimate:\n plan.writeSignals && plan.groups.length > 0\n ? {\n rows: plan.estimate.rows,\n // Character count of the CSV. With --gzip the file on disk is smaller than this.\n bytes: plan.estimate.bytes,\n exceeds_spreadsheet_limit: plan.estimate.exceedsSpreadsheetLimit,\n }\n : { rows: null, bytes: null, exceeds_spreadsheet_limit: false },\n // The plan's mixed-rate warning replaces the header parser's, as it does everywhere\n // else. This was the one consumer left out of that when 0.3.2 made the warning follow\n // --channels, so `--info --json` carried it twice: once counting the rates being\n // converted and once counting every rate in the file, with the same code and severity.\n // The file's own first, then the plan's, which is the order the text form prints them\n // in. Concatenating the other way round listed the same warnings about the same\n // recording in two different sequences depending on which form you asked for.\n warnings: withoutFileRateWarning(file.diagnostics)\n .concat(plan.diagnostics)\n .map((d) => ({ code: d.code, severity: d.severity, message: d.message })),\n },\n null,\n indent ?? undefined,\n );\n // A path is untrusted text on this surface too; see escapeJsonText.\n return escapeJsonText(document);\n}\n\n/**\n * One diagnostic per `warning: ` line, prefixed so warnings are greppable; the hint below it\n * wrapped to the terminal.\n *\n * The hint has been on its own unprefixed continuation line since these gained hints at all,\n * so grepping for `warning:` never picked it up and wrapping it costs nothing that was being\n * relied on — which is what 0.6.132 got wrong when it left every diagnostic long on the\n * grounds that they are one line each. Half of that is true. The `warning:` head is a line\n * per diagnostic and stays one, at whatever width the message runs to; the hint underneath\n * it is prose addressed to a person reading a terminal, and 17 of them ran past 80 columns,\n * the widest to 180. At that width the second half of the advice is wherever the terminal\n * decided to put it, indented under nothing, and the 9-space rule that says \"this belongs to\n * the warning above\" is lost at exactly the moment there is enough text for it to matter.\n */\nexport function formatDiagnostics(diagnostics: readonly Diagnostic[]): string {\n return diagnostics\n .map((d) => {\n // Diagnostics quote channel labels, which come from the file, so they need the\n // same treatment as the --info table.\n const head = `${d.severity}: ${printable(d.message)}`;\n return d.hint ? `${head}\\n${wrap(printable(d.hint), HINT_INDENT)}` : head;\n })\n .join('\\n');\n}\n\nexport function formatSummary(result: ConvertResult): string {\n const lines: string[] = [];\n const rows: string[][] = [];\n for (const file of result.files) {\n // `.csv.gz` is still a CSV, and its rows are still rows. The suffix test dropped the\n // unit from every line of a --gzip summary, so the numbers stood on their own.\n rows.push([\n ` ${file.name}`,\n grouped(file.rows),\n // Singular at one, like every other count this prints: a one-row table is what a\n // narrow window produces, and \"1 rows\" is the same slip 0.5.74 fixed elsewhere.\n /\\.csv(\\.gz)?$/u.test(file.name) ? (file.rows === 1 ? 'row' : 'rows') : '',\n ]);\n }\n lines.push(`Wrote ${printable(result.outputDir)}`); // Escaped; see the File line above.\n lines.push(table(rows, new Set([1])));\n lines.push(`Done in ${elapsed(result.elapsedMs)}.`);\n return lines.join('\\n');\n}\n\n/**\n * How long the run took, in a unit it can be stated in.\n *\n * `elapsedMs` is a difference of two `Date.now()` readings, so it is whole milliseconds, and\n * `(ms / 1000).toFixed(1)` rounds everything under fifty of them to `0.0`. That is the last\n * line of every conversion of a small recording — `--annotations-only` on a three-record\n * file, every fixture in this repository, and the transcript on three documentation pages,\n * all of which read `Done in 0.0s.` for a run that read a file and wrote three.\n *\n * The same refusal `formatDuration` and `formatBytes` make one file over, and for the reason\n * stated there: none of them is a rounding rule, and each declines to print a form the\n * quantity cannot take — 1023.999 KB is not \"1024 KB\", two records of 1e-15s are not \"0s\",\n * and a conversion that happened did not take no time.\n *\n * A clock that reports no change at all has measured something below what it can resolve,\n * which is a different statement from zero and is what it says.\n */\nexport function elapsed(milliseconds: number): string {\n /*\n And the other end of it, which could only say seconds.\n\n This is the one place in the tool that states a length of time without `formatDuration`,\n and it is the line under a summary whose `Duration` field is printed *with* it. A\n conversion of an overnight recording read:\n\n Duration 8h 00m 0s (28800 records of 1s)\n ...\n Done in 412.7s.\n\n Two lengths of time on one screen, one decomposed and one not, from the same program. 412\n seconds is a number a reader has to divide by sixty to hold, which is the whole reason\n `formatDuration` exists and the same complaint `grouped` makes about counts.\n\n Handed over at a minute, since below that the seconds are the readable form — and rounded\n to the tenth this already prints first, because `formatDuration` keeps three decimals and\n \"6m 52.734s\" claims a precision two `Date.now()` readings do not have.\n */\n if (milliseconds >= 60_000) return formatDuration(Math.round(milliseconds / 100) / 10);\n if (milliseconds >= 50) return `${(milliseconds / 1000).toFixed(1)}s`;\n return milliseconds > 0 ? `${milliseconds}ms` : 'under 1ms';\n}\n\n/**\n * Which version produced this record.\n *\n * `metadata.json` has carried it since the file existed, because a conversion should be\n * reproducible later. The two JSON *streams* did not, and they are the ones most likely to\n * outlive the run: `--json` exists to be piped into something, logged, or committed beside a\n * result, where the question a year on is which release's field names and rounding these are.\n * The same shape as metadata.json's, so a consumer reads one field either way.\n */\nconst TOOL = { name: 'edf2csv', version: VERSION } as const;\n\nexport function summaryJson(result: ConvertResult, indent: number | null = 2): string {\n const document = JSON.stringify(\n {\n tool: TOOL,\n output_dir: result.outputDir,\n files: result.files,\n annotations: result.annotationCount,\n duration_seconds: result.file.durationSeconds,\n records: result.file.recordCount,\n elapsed_ms: result.elapsedMs,\n warnings: result.diagnostics.map((d) => ({ code: d.code, severity: d.severity, message: d.message })),\n },\n null,\n indent ?? undefined,\n );\n // A path is untrusted text on this surface too; see escapeJsonText.\n return escapeJsonText(document);\n}\n"]}
|
package/dist/convert/channels.js
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { editDistance } from '../format/distance.js';
|
|
11
11
|
import { listed } from '../format/list.js';
|
|
12
|
+
import { printable } from '../format/unprintable.js';
|
|
12
13
|
import { assertOptions, assertSignals } from './options.js';
|
|
13
14
|
/**
|
|
14
15
|
* The name of the column the writer puts in front of the channels, which no channel may take.
|
|
@@ -175,6 +176,9 @@ export function selectChannels(signals, terms) {
|
|
|
175
176
|
const term = rawTerm.trim();
|
|
176
177
|
if (term === '')
|
|
177
178
|
continue;
|
|
179
|
+
// Quoted back into every refusal below, and a `--channels` term is whatever the caller's
|
|
180
|
+
// shell handed over — a newline in one cut the refusal's first line in half. See 0.8.92.
|
|
181
|
+
const shownTerm = printable(term);
|
|
178
182
|
// '#N' addresses a channel by position, but a label may literally be "#5".
|
|
179
183
|
// A real label always wins, so no channel becomes unreachable.
|
|
180
184
|
const literal = byLabel.get(term.toLowerCase());
|
|
@@ -191,7 +195,7 @@ export function selectChannels(signals, terms) {
|
|
|
191
195
|
*/
|
|
192
196
|
const position = term.slice(1);
|
|
193
197
|
if (!/^\d+$/u.test(position)) {
|
|
194
|
-
throw new ChannelSelectionError(`"${
|
|
198
|
+
throw new ChannelSelectionError(`"${shownTerm}" is not a channel position: a position is #0, #1, #2 and so on.\n` +
|
|
195
199
|
positions);
|
|
196
200
|
}
|
|
197
201
|
const index = Number(position);
|
|
@@ -232,7 +236,7 @@ export function selectChannels(signals, terms) {
|
|
|
232
236
|
// The label quoted the way the by-name refusal quotes it — this channel's label
|
|
233
237
|
// is one of the two the specification reserves, so there is nothing else it can
|
|
234
238
|
// be, and the two sentences stay one sentence.
|
|
235
|
-
`${
|
|
239
|
+
`${shownTerm} is this recording's annotation channel ("${annotations.label}"), not a ` +
|
|
236
240
|
`signal: it holds event text rather than samples, so it has no column to ` +
|
|
237
241
|
`select.\n` +
|
|
238
242
|
`Its events are already written to annotations.csv by any conversion of this ` +
|
|
@@ -246,7 +250,7 @@ export function selectChannels(signals, terms) {
|
|
|
246
250
|
grepped for and the one `printableLines` leaves whole at any width, so on a
|
|
247
251
|
40-channel recording this refusal ran to 111 columns where its neighbour ran to 74.
|
|
248
252
|
*/
|
|
249
|
-
throw new ChannelSelectionError(`No channel at position ${
|
|
253
|
+
throw new ChannelSelectionError(`No channel at position ${shownTerm}.\n${positions}`);
|
|
250
254
|
}
|
|
251
255
|
chosen.set(signal.index, signal);
|
|
252
256
|
continue;
|
|
@@ -274,10 +278,10 @@ export function selectChannels(signals, terms) {
|
|
|
274
278
|
// label back would be offering `""` — there is nothing to type. Position is the only
|
|
275
279
|
// way to reach it, and saying so is more use than quoting an empty string twice.
|
|
276
280
|
throw new ChannelSelectionError(owner.label === ''
|
|
277
|
-
? `"${
|
|
281
|
+
? `"${shownTerm}" is a column name, not a channel name: --channels matches the label, ` +
|
|
278
282
|
`and this channel has none.\n` +
|
|
279
283
|
`Use "#${owner.index}" — a channel with no label can only be addressed by position.`
|
|
280
|
-
: `"${
|
|
284
|
+
: `"${shownTerm}" is a column name, not a channel name: --channels matches the label, ` +
|
|
281
285
|
`which for this channel is "${owner.label}".\n` +
|
|
282
286
|
(typeable(owner.label) === null
|
|
283
287
|
? `Use "#${owner.index}" — ${untypeableBecause(owner.label)}, so position is ` +
|
|
@@ -321,8 +325,8 @@ export function selectChannels(signals, terms) {
|
|
|
321
325
|
if (annotationChannel) {
|
|
322
326
|
const exact = annotationChannel.label.toLowerCase() === term.toLowerCase();
|
|
323
327
|
throw new ChannelSelectionError((exact
|
|
324
|
-
? `"${
|
|
325
|
-
: `There is no channel named "${
|
|
328
|
+
? `"${shownTerm}" is this recording's annotation channel, not a signal: it holds event `
|
|
329
|
+
: `There is no channel named "${shownTerm}"; the nearest thing to it is this ` +
|
|
326
330
|
`recording's annotation channel "${annotationChannel.label}", which holds event `) +
|
|
327
331
|
`text rather than samples, so it has no column to select.\n` +
|
|
328
332
|
`Its events are already written to annotations.csv by any conversion of this ` +
|
|
@@ -343,7 +347,7 @@ export function selectChannels(signals, terms) {
|
|
|
343
347
|
conversion as well, where dropping `--channels` alone would convert the whole file
|
|
344
348
|
rather than list anything.
|
|
345
349
|
*/
|
|
346
|
-
throw new ChannelSelectionError(`No channel named "${
|
|
350
|
+
throw new ChannelSelectionError(`No channel named "${shownTerm}".${hint}\n` +
|
|
347
351
|
`Run with --info and no --channels to list the channels in this file.`);
|
|
348
352
|
}
|
|
349
353
|
if (matched.length > 1)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"channels.js","sourceRoot":"","sources":["../../src/convert/channels.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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 { editDistance } from '../format/distance.js';\nimport { listed } from '../format/list.js';\nimport { assertOptions, assertSignals } from './options.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 // The same check `selectChannels` makes below, for the same reason: this is exported, and a\n // string is iterable, so `buildColumnNames('ECG')` came back as a Map rather than an error.\n assertSignals(signals);\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 /*\n The same check `buildPlan` makes, made here too, because this is exported on its own.\n\n `assertOptions` covers `convert`; a caller holding a header and calling this directly got\n the shapes it names in full. `'ECG'` was iterated character by character and answered `No\n channel named \"E\". Did you mean \"ECG\"?` — which reads like a real answer about the file —\n and `[1]`, a position written the way a position is written, came back as `TypeError:\n rawTerm.trim is not a function` from the loop below. Both are the argument being the wrong\n shape, which is the case that checker exists for, and both now say so.\n */\n assertOptions({ channels: terms });\n // And the argument in front of it, which that call has never covered.\n assertSignals(signals);\n\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 /*\n And one channel is not \"channels\", which is the same sentence one item further on.\n\n The zero case above was given its own wording because \"signal channels at .\" states there\n are some and then names none. A file with exactly one got \"This file has signal channels\n at #0.\" — a plural over a list of one, on the line whose job is to say what may be typed\n instead. Single-channel recordings are ordinary; two of this repository's own fixtures are\n one.\n */\n const positions =\n candidates.length === 0\n ? 'This file has no signal channels; it contains only annotations.'\n : candidates.length === 1\n ? `This file has one signal channel, at #${candidates[0]?.index ?? 0}.`\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 /*\n The annotation channel occupies a position, and this denied the position existed.\n\n `candidates` is the signals; the annotation channel is filtered out of it and keeps\n its index in the file — which is what `signal_index` in channels.csv is documented\n as, \"counting the annotation channel if present\", and what `#N` addresses. So on an\n ordinary EDF+ recording of one signal, `--channels \"#1\"` was refused with\n\n No channel at position #1. This file has one signal channel, at #0.\n\n The first sentence is false: #1 is where `EDF Annotations` sits. Asking for the same\n channel by *name* has had the whole explanation since 0.7.x — \"is this recording's\n annotation channel, not a signal ... pass --annotations-only\" — so one tool gave two\n answers to one question depending on how the channel was named, and the answer that\n denied the channel existed is the one reached by the reader who looked its position\n up in channels.csv.\n\n Said here in the words the by-name refusal uses, since it is the same fact.\n */\n /*\n Only on a file that has signal channels to be one of.\n\n On an annotations-only recording every position is the annotation channel, and the\n fact worth having is the one the sentence below already carries: there are no signal\n channels at all, so no position will select anything. Naming the channel at `#0`\n there would answer a narrower question than the reader asked.\n */\n const annotations =\n candidates.length === 0\n ? undefined\n : signals.find((s) => s.isAnnotations && s.index === index);\n if (annotations) {\n throw new ChannelSelectionError(\n // The label quoted the way the by-name refusal quotes it — this channel's label\n // is one of the two the specification reserves, so there is nothing else it can\n // be, and the two sentences stay one sentence.\n `${term} is this recording's annotation channel (\"${annotations.label}\"), not a ` +\n `signal: it holds event text rather than samples, so it has no column to ` +\n `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 /*\n The list of positions is advice, and advice goes on the continuation line.\n\n It sat on the first line here and on the second in the refusal six lines up, which\n is the same sentence about the same thing. The first line is the one a log gets\n grepped for and the one `printableLines` leaves whole at any width, so on a\n 40-channel recording this refusal ran to 111 columns where its neighbour ran to 74.\n */\n throw new ChannelSelectionError(\n `No channel at position ${term}.\\n${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 /*\n And a term that is merely near it, which the paragraph above describes and did not\n cover.\n\n The exact spelling got the whole explanation; one character off got \"No channel named\n \"EDF Annotation\". Run with --info to list the channels in this file\" — which is the\n sentence that comment calls false about the file and a pointer at a table that does\n not list the channel either. `EDF Annotations` on a BDF+ recording is the same miss by\n the prefix, and `--channels annotations` by everything but the noun; all three are how\n somebody who has read about EDF+ actually types it.\n\n Only when no signal label is close, so a suggestion about a real column always wins,\n and by the same distance rule that suggestion uses rather than a second one.\n */\n const hint = suggest(term, candidates);\n const nearAnnotations =\n hint === ''\n ? signals.find(\n (signal) =>\n signal.isAnnotations &&\n signal.label !== '' &&\n nearness(term, signal.label) <= reach(term),\n )\n : undefined;\n const annotationChannel = asAnnotations ?? nearAnnotations;\n if (annotationChannel) {\n const exact = annotationChannel.label.toLowerCase() === term.toLowerCase();\n throw new ChannelSelectionError(\n (exact\n ? `\"${term}\" is this recording's annotation channel, not a signal: it holds event `\n : `There is no channel named \"${term}\"; the nearest thing to it is this ` +\n `recording's annotation channel \"${annotationChannel.label}\", which 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 /*\n Advice that works in the mode it was given in.\n\n `--info` takes `--channels` too — it is how you check a selection before converting\n with it — and a term that matches nothing is refused there exactly as it is here. So\n `edf2csv rec.edf --info --channels nope` answered:\n\n error: No channel named \"nope\".\n Run with --info to list the channels in this file.\n\n which is the command that just printed it. The listing is what `--info` does; what\n stopped it was the `--channels` beside it. Naming both makes the sentence true of a\n conversion as well, where dropping `--channels` alone would convert the whole file\n rather than list anything.\n */\n throw new ChannelSelectionError(\n `No channel named \"${term}\".${hint}\\n` +\n `Run with --info and no --channels 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\n/**\n * How far a label is from what was typed, and how far the suggestion reaches.\n *\n * Two functions ask the same question — the \"did you mean\" list, and the annotation channel\n * one branch above it — and a rule with two copies is a rule that will get two answers.\n */\nfunction nearness(term: string, label: string): number {\n const needle = term.toLowerCase();\n const lower = label.toLowerCase();\n return needle !== '' && lower.includes(needle) ? 0 : editDistance(needle, lower);\n}\n\nfunction reach(term: string): number {\n return Math.max(2, Math.floor(term.length / 3));\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 /*\n A label that contains the term is the answer, however many edits away it is.\n\n Edit distance charges one edit per character the label has and the term does not, so an\n abbreviation — the commonest way to get this wrong — scores worse the more of the label it\n leaves out. On a recording whose channels are `EEG Fpz-Cz` and `ECG`, `--channels EEG` is\n seven edits from the channel it names and one from the other, and the answer was `Did you\n mean \"ECG\"?`: a suggestion that is retypeable, close, and about the wrong signal. Taking it\n converts a heart trace under the belief it is an EEG, and the run succeeds.\n */\n const scored = unique\n .map((label) => ({ label, distance: nearness(term, label) }))\n .filter((c) => c.label !== '' && c.distance <= reach(term))\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"]}
|
|
1
|
+
{"version":3,"file":"channels.js","sourceRoot":"","sources":["../../src/convert/channels.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE5D;;;;;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,4FAA4F;IA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AG,CAAC;AAChD,CAAC;AAED,2FAA2F;AAC3F,SAAS,UAAU,CAAC,KAAa,EAAE,UAAgC;IACjE,OAAO,UAAU,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,KAAK,KAAK,CAAC,EAAE,KAAK,IAAI,CAAC,CAAC;AACzE,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,QAAQ,CAAC,KAAa;IACpC,IAAI,KAAK,KAAK,EAAE,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,IAAI,CAAC;IACrD,IAAI,+BAA+B,CAAC,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IAC7D,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,KAAK,GAAG,CAAC;IACjD,OAAO,IAAI,KAAK,CAAC,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC;AAC/C,CAAC;AAED,yFAAyF;AACzF,SAAS,iBAAiB,CAAC,KAAa;IACtC,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,8CAA8C,CAAC;IAC/E,OAAO,2BAA2B,CAAC;AACrC,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 { editDistance } from '../format/distance.js';\nimport { listed } from '../format/list.js';\nimport { printable } from '../format/unprintable.js';\nimport { assertOptions, assertSignals } from './options.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 // The same check `selectChannels` makes below, for the same reason: this is exported, and a\n // string is iterable, so `buildColumnNames('ECG')` came back as a Map rather than an error.\n assertSignals(signals);\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 /*\n The same check `buildPlan` makes, made here too, because this is exported on its own.\n\n `assertOptions` covers `convert`; a caller holding a header and calling this directly got\n the shapes it names in full. `'ECG'` was iterated character by character and answered `No\n channel named \"E\". Did you mean \"ECG\"?` — which reads like a real answer about the file —\n and `[1]`, a position written the way a position is written, came back as `TypeError:\n rawTerm.trim is not a function` from the loop below. Both are the argument being the wrong\n shape, which is the case that checker exists for, and both now say so.\n */\n assertOptions({ channels: terms });\n // And the argument in front of it, which that call has never covered.\n assertSignals(signals);\n\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 /*\n And one channel is not \"channels\", which is the same sentence one item further on.\n\n The zero case above was given its own wording because \"signal channels at .\" states there\n are some and then names none. A file with exactly one got \"This file has signal channels\n at #0.\" — a plural over a list of one, on the line whose job is to say what may be typed\n instead. Single-channel recordings are ordinary; two of this repository's own fixtures are\n one.\n */\n const positions =\n candidates.length === 0\n ? 'This file has no signal channels; it contains only annotations.'\n : candidates.length === 1\n ? `This file has one signal channel, at #${candidates[0]?.index ?? 0}.`\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 // Quoted back into every refusal below, and a `--channels` term is whatever the caller's\n // shell handed over — a newline in one cut the refusal's first line in half. See 0.8.92.\n const shownTerm = printable(term);\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 `\"${shownTerm}\" 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 /*\n The annotation channel occupies a position, and this denied the position existed.\n\n `candidates` is the signals; the annotation channel is filtered out of it and keeps\n its index in the file — which is what `signal_index` in channels.csv is documented\n as, \"counting the annotation channel if present\", and what `#N` addresses. So on an\n ordinary EDF+ recording of one signal, `--channels \"#1\"` was refused with\n\n No channel at position #1. This file has one signal channel, at #0.\n\n The first sentence is false: #1 is where `EDF Annotations` sits. Asking for the same\n channel by *name* has had the whole explanation since 0.7.x — \"is this recording's\n annotation channel, not a signal ... pass --annotations-only\" — so one tool gave two\n answers to one question depending on how the channel was named, and the answer that\n denied the channel existed is the one reached by the reader who looked its position\n up in channels.csv.\n\n Said here in the words the by-name refusal uses, since it is the same fact.\n */\n /*\n Only on a file that has signal channels to be one of.\n\n On an annotations-only recording every position is the annotation channel, and the\n fact worth having is the one the sentence below already carries: there are no signal\n channels at all, so no position will select anything. Naming the channel at `#0`\n there would answer a narrower question than the reader asked.\n */\n const annotations =\n candidates.length === 0\n ? undefined\n : signals.find((s) => s.isAnnotations && s.index === index);\n if (annotations) {\n throw new ChannelSelectionError(\n // The label quoted the way the by-name refusal quotes it — this channel's label\n // is one of the two the specification reserves, so there is nothing else it can\n // be, and the two sentences stay one sentence.\n `${shownTerm} is this recording's annotation channel (\"${annotations.label}\"), not a ` +\n `signal: it holds event text rather than samples, so it has no column to ` +\n `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 /*\n The list of positions is advice, and advice goes on the continuation line.\n\n It sat on the first line here and on the second in the refusal six lines up, which\n is the same sentence about the same thing. The first line is the one a log gets\n grepped for and the one `printableLines` leaves whole at any width, so on a\n 40-channel recording this refusal ran to 111 columns where its neighbour ran to 74.\n */\n throw new ChannelSelectionError(\n `No channel at position ${shownTerm}.\\n${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 ? `\"${shownTerm}\" 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 : `\"${shownTerm}\" 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 /*\n And a term that is merely near it, which the paragraph above describes and did not\n cover.\n\n The exact spelling got the whole explanation; one character off got \"No channel named\n \"EDF Annotation\". Run with --info to list the channels in this file\" — which is the\n sentence that comment calls false about the file and a pointer at a table that does\n not list the channel either. `EDF Annotations` on a BDF+ recording is the same miss by\n the prefix, and `--channels annotations` by everything but the noun; all three are how\n somebody who has read about EDF+ actually types it.\n\n Only when no signal label is close, so a suggestion about a real column always wins,\n and by the same distance rule that suggestion uses rather than a second one.\n */\n const hint = suggest(term, candidates);\n const nearAnnotations =\n hint === ''\n ? signals.find(\n (signal) =>\n signal.isAnnotations &&\n signal.label !== '' &&\n nearness(term, signal.label) <= reach(term),\n )\n : undefined;\n const annotationChannel = asAnnotations ?? nearAnnotations;\n if (annotationChannel) {\n const exact = annotationChannel.label.toLowerCase() === term.toLowerCase();\n throw new ChannelSelectionError(\n (exact\n ? `\"${shownTerm}\" is this recording's annotation channel, not a signal: it holds event `\n : `There is no channel named \"${shownTerm}\"; the nearest thing to it is this ` +\n `recording's annotation channel \"${annotationChannel.label}\", which 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 /*\n Advice that works in the mode it was given in.\n\n `--info` takes `--channels` too — it is how you check a selection before converting\n with it — and a term that matches nothing is refused there exactly as it is here. So\n `edf2csv rec.edf --info --channels nope` answered:\n\n error: No channel named \"nope\".\n Run with --info to list the channels in this file.\n\n which is the command that just printed it. The listing is what `--info` does; what\n stopped it was the `--channels` beside it. Naming both makes the sentence true of a\n conversion as well, where dropping `--channels` alone would convert the whole file\n rather than list anything.\n */\n throw new ChannelSelectionError(\n `No channel named \"${shownTerm}\".${hint}\\n` +\n `Run with --info and no --channels 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\n/**\n * How far a label is from what was typed, and how far the suggestion reaches.\n *\n * Two functions ask the same question — the \"did you mean\" list, and the annotation channel\n * one branch above it — and a rule with two copies is a rule that will get two answers.\n */\nfunction nearness(term: string, label: string): number {\n const needle = term.toLowerCase();\n const lower = label.toLowerCase();\n return needle !== '' && lower.includes(needle) ? 0 : editDistance(needle, lower);\n}\n\nfunction reach(term: string): number {\n return Math.max(2, Math.floor(term.length / 3));\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 /*\n A label that contains the term is the answer, however many edits away it is.\n\n Edit distance charges one edit per character the label has and the term does not, so an\n abbreviation — the commonest way to get this wrong — scores worse the more of the label it\n leaves out. On a recording whose channels are `EEG Fpz-Cz` and `ECG`, `--channels EEG` is\n seven edits from the channel it names and one from the other, and the answer was `Did you\n mean \"ECG\"?`: a suggestion that is retypeable, close, and about the wrong signal. Taking it\n converts a heart trace under the belief it is an EEG, and the run succeeds.\n */\n const scored = unique\n .map((label) => ({ label, distance: nearness(term, label) }))\n .filter((c) => c.label !== '' && c.distance <= reach(term))\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"]}
|