edf2csv 0.9.14 → 0.9.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/convert/options.js
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* These run at the top of `buildPlan`, which every path goes through before a directory is
|
|
15
15
|
* created or a stream is opened, so a rejected option leaves nothing behind.
|
|
16
16
|
*/
|
|
17
|
+
import { counted, grouped } from '../format/list.js';
|
|
17
18
|
/** A problem with the options a caller passed, as opposed to a problem with the file. */
|
|
18
19
|
export class OptionError extends Error {
|
|
19
20
|
constructor(message) {
|
|
@@ -466,6 +467,32 @@ export function assertRecordShape(input) {
|
|
|
466
467
|
*/
|
|
467
468
|
if (recordStarts !== null && recordStarts !== undefined) {
|
|
468
469
|
const starts = recordStarts;
|
|
470
|
+
/*
|
|
471
|
+
And one for every record, which is what the field is documented to be: "True start time
|
|
472
|
+
of each data record". A shorter list is not a partial answer, it is a shorter recording:
|
|
473
|
+
|
|
474
|
+
resolveRange({ recordDuration: 1, recordCount: 3, recordStarts: [0] })
|
|
475
|
+
{ startSeconds: 0, endSeconds: 1, startRecord: 0, endRecord: 1,
|
|
476
|
+
isWholeRecording: true }
|
|
477
|
+
|
|
478
|
+
One record of the three, called the whole recording — the same contradiction the check
|
|
479
|
+
below removes for a list of strings, reached by leaving entries out instead of filling
|
|
480
|
+
them wrongly. `span` reads the earliest and latest off whatever it is given and
|
|
481
|
+
`selectRecords` matches only the indexes it holds, so a list of one describes a file of
|
|
482
|
+
one however many records the caller said there were.
|
|
483
|
+
|
|
484
|
+
Empty is the exception, and it is not a short list: `[]` is how "no record times are
|
|
485
|
+
known" arrives, which the two functions below already answer by falling back to
|
|
486
|
+
contiguous positions. `null` says the same thing and is the form the reader hands over.
|
|
487
|
+
*/
|
|
488
|
+
if (starts.length !== 0 && starts.length !== recordCount) {
|
|
489
|
+
// Both counts through the helpers, like every other sentence that puts one number
|
|
490
|
+
// against another: the phrase exists to compare them.
|
|
491
|
+
throw new OptionError(`recordStarts has ${grouped(starts.length)} of the ` +
|
|
492
|
+
`${counted(recordCount, 'record start time')} this recording needs. It is ` +
|
|
493
|
+
`where each data record really sits, so a shorter list describes a shorter ` +
|
|
494
|
+
`recording; pass null, or an empty list, where none are known.`);
|
|
495
|
+
}
|
|
469
496
|
for (let at = 0; at < starts.length; at++) {
|
|
470
497
|
const start = starts[at];
|
|
471
498
|
if (start === null || start === undefined || Number.isFinite(start))
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.js","sourceRoot":"","sources":["../../src/convert/options.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,yFAAyF;AACzF,MAAM,OAAO,WAAY,SAAQ,KAAK;IACpC,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;IAC5B,CAAC;CACF;AAED;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,EAAE,CAAC;AAE/B,MAAM,UAAU,aAAa,CAAC,OAkB7B;IACC;;;;;;;;;;;;;;;;;;;;;MAqBE;IACF,2FAA2F;IAC3F,uFAAuF;IACvF,yEAAyE;IACzE,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC9E,MAAM,IAAI,WAAW,CACnB,6CAA6C,aAAa,CAAC,OAAO,CAAC,oBAAoB;YACrF,oDAAoD,CACvD,CAAC;IACJ,CAAC;IACD;;;;;;;;;;;;;;;;;MAiBE;IACF,KAAK,MAAM,IAAI,IAAI,CAAC,WAAW,EAAE,cAAc,EAAE,SAAS,CAAU,EAAE,CAAC;QACrE,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;QAC5B,IAAI,KAAK,KAAK,SAAS,IAAI,OAAO,KAAK,KAAK,QAAQ,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M,MAAM,GAAG,YAAkC,CAAC;QAClD,KAAK,IAAI,EAAE,GAAG,CAAC,EAAE,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,EAAE,EAAE,EAAE,CAAC;YAC1C,MAAM,KAAK,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;YACzB,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;gBAAE,SAAS;YAC9E,MAAM,IAAI,WAAW,CACnB,gBAAgB,EAAE,kEAAkE;gBAClF,kBAAkB,aAAa,CAAC,KAAK,CAAC,4CAA4C;gBAClF,8EAA8E,CACjF,CAAC;QACJ,CAAC;IACH,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,eAAe,CAAC,KAAc;IAC5C,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,MAAM,IAAI,WAAW,CAAC,4CAA4C,aAAa,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC7F,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC;AAC5F,CAAC","sourcesContent":["/**\n * Checking the options a caller passed, before anything is written.\n *\n * The command line has always validated these — `--decimals 1.5` is a usage error and always\n * has been — and the library did not, so the same value behaved differently depending on how\n * it arrived. `convert(file, { decimals: NaN })` resolved successfully having written whole\n * numbers into a column the caller had asked for decimals in, which is the worst of the\n * three: no error, no warning, and output that looks like a deliberate choice. `decimals: -1`\n * reached `toFixed` and came back as a bare RangeError from deep inside the formatter, naming\n * nothing the caller had written. `start: NaN` created the output directory, wrote\n * signals.csv, and then failed with a message about the input being unreadable — a partial\n * conversion, blamed on the file.\n *\n * These run at the top of `buildPlan`, which every path goes through before a directory is\n * created or a stream is opened, so a rejected option leaves nothing behind.\n */\n\n/** A problem with the options a caller passed, as opposed to a problem with the file. */\nexport class OptionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'OptionError';\n }\n}\n\n/**\n * The largest `--decimals` accepts, and what both documentation pages state.\n *\n * Not a limit of `toFixed`, whatever this comment used to say. `toFixed` takes 0 to 100 and\n * throws a RangeError at 101 — which is exactly the belief `MAX_DERIVED_DECIMALS` in\n * edf/scale.ts exists to correct, having once clamped the *derived* precision to 20 on the\n * same wrong grounds and rounded a magnetometer channel needing 23 places onto a grid three\n * digital codes wide, losing 69% of its samples in silence.\n *\n * Twenty is a bound on a number a person types by hand, not on what the format can express.\n * The derived precision, which nobody types, runs to 100 and says so.\n */\nexport const MAX_DECIMALS = 20;\n\nexport function assertOptions(options: {\n decimals?: number | undefined;\n start?: number | undefined;\n duration?: number | undefined;\n end?: number | undefined;\n layout?: string | undefined;\n channels?: readonly string[] | undefined;\n outputDir?: string | undefined;\n annotationsOnly?: boolean | undefined;\n gzip?: boolean | undefined;\n bom?: boolean | undefined;\n force?: boolean | undefined;\n checksum?: boolean | undefined;\n toStdout?: boolean | undefined;\n onProgress?: unknown;\n startText?: unknown;\n durationText?: unknown;\n endText?: unknown;\n}): void {\n /*\n The bag itself, before anything is read out of it.\n\n Every check below reads `options.decimals` and its neighbours, and both functions that run\n this declare the parameter with a default of `{}` — which covers `undefined` and nothing\n else. So a value that is not an object had its properties read off it, came back\n `undefined`, and meant what `undefined` means here: that option was not given.\n\n convert('rec.edf', 'out') // converts to rec_csv, and reports success\n buildPlan(input, 42) // the whole recording, wide, three decimals\n convert('rec.edf', null) // TypeError: Cannot read properties of null\n\n `convert(file, 'out')` is the one that costs something. The second parameter is an option\n bag and the string looks like a destination, which is a mistake worth making — and the\n rows went to `<recording>_csv` beside the input, a directory the caller had not named,\n with `result.outputDir` reporting where they really went to nobody who was reading it.\n That is the sentence `outputDir: null` has at the top of this file, arrived at through the\n argument in front of it.\n\n `resolveRange` was given this check on its own bag in 0.8.75 and `readRecords` on its in\n 0.9.2. These are the last two exported functions that take one.\n */\n // An array is an object and carries none of these properties, so it went the same way as a\n // string with none of the same visibility — `convert(file, ['a.edf', 'b.edf'])` is the\n // second-argument twin of the mistake `assertInputPath` was written for.\n if (typeof options !== 'object' || options === null || Array.isArray(options)) {\n throw new OptionError(\n `options must be an object of options, got ${describeValue(options)}. The destination ` +\n `goes in it as outputDir; omit it for the defaults.`,\n );\n }\n /*\n The three options that exist only to be quoted back, quoted back unexamined.\n\n `startText`, `durationText` and `endText` carry the value exactly as the caller's user\n typed it, so a refusal names that rather than its parsed form — \"--start \\\"4h\\\"\" rather\n than \"--start 14400s\". Nothing asked whether they were text, and they reach the sentence\n as they are:\n\n convert(file, { start: 99, startText: {} })\n TimeRangeError: --start \"[object Object]\" is at or past the end of this 3s recording.\n\n convert(file, { start: 1, end: 0.5, endText: [] })\n TimeRangeError: The requested window ends at \"\", which is not after its start at 1s.\n\n `[object Object]` is the string `assertInputPath`'s own docstring names as the reason that\n function exists, and the empty quotation is the hole `describeValue` was written to stop —\n both in the one place whose entire purpose is to show the reader what they typed.\n */\n for (const name of ['startText', 'durationText', 'endText'] as const) {\n const value = options[name];\n if (value !== undefined && typeof value !== 'string') {\n throw new OptionError(\n `${name} must be the value as it was typed, got ${describeValue(value)}. It is quoted ` +\n `back in the window errors so they name what was given rather than its parsed form.`,\n );\n }\n }\n const { decimals } = options;\n if (decimals !== undefined) {\n if (!Number.isInteger(decimals) || decimals < 0 || decimals > MAX_DECIMALS) {\n throw new OptionError(\n `decimals must be a whole number between 0 and ${MAX_DECIMALS}, got ${describeValue(decimals)}.`,\n );\n }\n }\n\n /*\n `start` and `end` are positions on the recording's own clock, `duration` is a length.\n\n All three were held above zero, which is right for a length and wrong for a position: a\n recording timed from its first record's timekeeping annotation may sit before zero, and\n -100 is then where its first sample is. So a caller could read `plan.range` back as\n `recordingStartSeconds: -100` and not be allowed to ask for it — the same wall\n `parseTimeSpec` put in front of the command line until 0.5.120.\n\n Non-finite is still refused for all three, since NaN reaches a comparison as false and\n would take the whole recording without saying so.\n */\n for (const name of ['start', 'duration', 'end'] as const) {\n const value = options[name];\n if (value === undefined) continue;\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new OptionError(`${name} must be a number of seconds, got ${describeValue(value)}.`);\n }\n /*\n A length below zero is refused for what it is, rather than for not being a number.\n\n `duration: -1` came back as \"duration must be a number of seconds, got -1\", which is\n not the reason and not true: -1 is a number of seconds, and this same call accepts it\n for `start` and for `end`, where a recording timed from before zero makes it an\n ordinary position. What is wrong is that a duration is a length, and no length is\n negative — which is what the command line says for the same value, and what the API\n reference has always said this check enforces.\n */\n if (name === 'duration' && value < 0) {\n throw new OptionError(`duration is a length of time, so it cannot be ${describeValue(value)}.`);\n }\n }\n\n /*\n Two words, and a caller who writes a third means something the tool cannot do.\n\n The command line has always rejected `--layout tall`. The library took it, put it in\n `plan.layout` for the caller to read back, and wrote the wide layout — so a programmatic\n caller with a typo got a conversion that was not the one they asked for, described by a\n plan that agreed with the typo. Every other option that has a shape is checked here; this\n one was added in 0.5.0 and never joined them.\n */\n const { layout } = options;\n if (layout !== undefined && layout !== 'wide' && layout !== 'long') {\n throw new OptionError(`layout must be \"wide\" or \"long\", got ${describeValue(layout)}.`);\n }\n\n /*\n A selection that names nothing is not the absence of a selection.\n\n `buildPlan` asks `options.channels.length > 0` before selecting, so an empty array fell\n through to the branch that means \"no channels option was given\" — and `convert(file, {\n channels: [] })` wrote every channel in the recording, resolved, and said nothing. That is\n the one shape of this the command line has always refused, in as many words: \"Returning\n undefined here would mean 'no --channels given' and convert everything, which is the\n opposite of what someone passing an empty list is asking for.\"\n\n A list of blanks is the same request written differently — it is what `''.split(',')`\n produces, which is how a caller building the array from user input arrives here — and it\n reached `selectChannels` and came back \"No channels were selected\", a sentence about the\n file rather than about the call. Both are the option being wrong, so both are refused\n here, before a directory exists.\n */\n /*\n An empty destination, refused here rather than by the filesystem.\n\n `convert(file, { outputDir: '' })` went the whole way to `mkdir('')` and came back a\n `ConversionError`: \"Cannot create \\\"\\\": part of the path does not exist. Check the path\n exists and that you have permission to write there.\" Advice about a path and a permission\n for a value that is neither, and a failure class that means the conversion went wrong\n where the option did.\n\n The command line refused this at 0.6.x, with the reasoning that `--out \"$DEST\"` and `DEST`\n unset is how it gets written by accident — and left the library, which a caller building\n the path in code reaches the same way. Not trimmed, for the reason given there: a\n directory whose name is a space is a strange thing to ask for, but it is a thing the\n filesystem has and a path is not a keyword.\n */\n /*\n And its shape, which was the one option with a value and no check on it.\n\n The empty string was refused and nothing else was, so `outputDir` failed two ways that the\n paragraph above describes for the flags. A value of the wrong type reached `path.join` and\n came back as a Node error about an argument this caller never passed:\n\n convert('rec.edf', { outputDir: 42 })\n TypeError: The \"path\" argument must be of type string. Received type number (42)\n\n And `null` — which is what `JSON.parse` of a config file gives for a field left unset, the\n same door `1` and `'true'` come through — was not an error at all. It is not `undefined`,\n so it never meant \"use the default\", but every read of it is `?? default` or a truthiness\n test, so that is what it did: the rows went to `<recording>_csv` beside the input, a\n directory the caller had not named, and the run reported success.\n */\n const { outputDir } = options;\n if (outputDir !== undefined && typeof outputDir !== 'string') {\n throw new OptionError(`outputDir must be a path, got ${describeValue(outputDir)}.`);\n }\n if (outputDir === '') {\n throw new OptionError('outputDir is empty. Give a directory, for example \"./converted\".');\n }\n\n /*\n The six flags, every one of which is read as `=== true` where it is read.\n\n Which means a value that is not a boolean is not merely tolerated: it is taken as the\n opposite of what it says. `convert(file, { annotationsOnly: 'true' })` wrote every signal\n the caller had asked to leave out; `{ gzip: 1 }` wrote plain CSVs under names ending\n `.csv`, so a caller who then opened `signals.csv.gz` found nothing there. No error, no\n warning, and output that looks like a deliberate choice — which is the sentence at the\n top of this file, describing the case it was written for.\n\n `1` and `'true'` are how a flag arrives from `JSON.parse` of a config file, from a query\n string, or from a CLI wrapper that did not coerce; none of them is a caller being\n careless in a way TypeScript would catch, since the callers this reaches are the ones not\n using it. The layout check above states the rule these were missing from: \"Every other\n option that has a shape is checked here.\"\n */\n for (const name of ['annotationsOnly', 'gzip', 'bom', 'force', 'checksum', 'toStdout'] as const) {\n const value = options[name];\n if (value !== undefined && typeof value !== 'boolean') {\n throw new OptionError(`${name} must be true or false, got ${describeValue(value)}.`);\n }\n }\n\n /*\n The one option that is called rather than read, and the only one that was not checked.\n\n `convert` invokes it as `options.onProgress?.(...)` once a record has been written, so a\n value that is not a function passes every check here, opens the destination, writes rows\n into it and then fails from inside the loop:\n\n convert('rec.edf', { outputDir: 'out', onProgress: 'every record' })\n ConversionError: The onProgress callback threw: options.onProgress is not a function\n\n A callback that threw is what that sentence reports, and no callback was given; the text\n after the colon names an expression inside this package. Worse is what it leaves: `out`\n exists with a half-written signals.csv in it, which is the case the paragraph at the top\n of this file describes — \"`start: NaN` created the output directory, wrote signals.csv,\n and then failed with a message about the input being unreadable — a partial conversion,\n blamed on the file\". Checked here, the same call writes nothing and says which argument\n is wrong.\n */\n const { onProgress } = options;\n if (onProgress !== undefined && typeof onProgress !== 'function') {\n throw new OptionError(`onProgress must be a function, got ${describeValue(onProgress)}.`);\n }\n\n const { channels } = options;\n if (channels !== undefined) {\n /*\n A list of strings, checked as one. `selectChannels` calls `.trim()` on every term, so a\n caller who passed the string `'ECG'` had it iterated character by character and was told\n `No channel named \"E\"`, and one who passed `[1]` — a position, reasonably enough — got\n `TypeError: rawTerm.trim is not a function` out of the middle of the selector, naming\n nothing they had written. Both are the option being the wrong shape, which is the case\n this function exists for.\n */\n if (!Array.isArray(channels) || channels.some((term) => typeof term !== 'string')) {\n throw new OptionError(`channels must be a list of channel names, got ${describeValue(channels)}.`);\n }\n if (channels.every((term) => term.trim() === '')) {\n throw new OptionError('channels was given but lists no channel names.');\n }\n }\n}\n\n/**\n * The channel list two exported functions take, checked the way their other argument is.\n *\n * `selectChannels(signals, terms)` has checked `terms` since 0.6.x — \"`'ECG'` was iterated\n * character by character and answered `No channel named \\\"E\\\"`… naming nothing the caller had\n * written\" — and never checked `signals`, which is the argument in front of it. Passing one\n * signal where the list goes, or a header where its `signals` goes, came back as\n * `TypeError: signals.filter is not a function`: a local of this package, over a value the\n * caller did write.\n *\n * `buildColumnNames` is worse off, because a string is iterable. `buildColumnNames('ECG')`\n * returned `Map { null => 'undefined_chundefined' }` and no error at all — a column name for a\n * channel that does not exist, keyed by a position that is not one.\n *\n * The bad entry is named by position rather than the whole list being printed back: a header\n * may declare hundreds of channels, and a message is not the place for all of them.\n */\nexport function assertSignals(signals: unknown): void {\n if (!Array.isArray(signals)) {\n throw new OptionError(\n `signals must be the channel list from a header, got ${describeValue(signals)}.`,\n );\n }\n /*\n The fields the callers read, not just the one that identifies a channel.\n\n This asked for `index` and stopped, and its callers go on to read `label` and\n `isAnnotations` off the same objects. So a list of channel-shaped objects without them\n passed the check that exists to say \"these are not channels from a header\" and failed one\n line further in, or did not fail at all:\n\n selectChannels([{ index: 0 }], ['ECG'])\n TypeError: Cannot read properties of undefined (reading 'toLowerCase')\n\n selectChannels([{ index: 0, label: 42 }], ['42'])\n TypeError: signal.label.toLowerCase is not a function\n\n buildColumnNames([{ index: 0 }])\n Map { 0 => null }\n\n The first two are the failure this function was written to remove, one level down — a\n local of this package named at a caller who wrote neither. The third is worse: a column\n name of `null`, where a channel with no label at all is named `signal_0`, so `null` is not\n a name this tool ever writes.\n */\n const FIELDS = [\n ['index', 'number'],\n ['label', 'string'],\n ['isAnnotations', 'boolean'],\n ] as const;\n for (const [at, signal] of signals.entries()) {\n if (typeof signal !== 'object' || signal === null) {\n throw new OptionError(\n `signals[${at}] is not a channel from a header, got ${describeValue(signal)}.`,\n );\n }\n const fields = signal as Record<string, unknown>;\n const wrong = FIELDS.find(([name, kind]) => typeof fields[name] !== kind);\n if (wrong === undefined) continue;\n const [name, kind] = wrong;\n throw new OptionError(\n `signals[${at}].${name} must be a ${kind}, got ${describeValue(fields[name])}. A channel ` +\n `from a header carries ${FIELDS.map(([f]) => f).join(', ')}.`,\n );\n }\n}\n\n/**\n * What `buildPlan` is told about the recording, checked the way what it is asked for is.\n *\n * `assertOptions` runs at the top of `buildPlan` and covers the second argument completely.\n * The first was not looked at, and it is the one carrying the numbers every figure in the plan\n * is derived from. Two of them missing produced a plan rather than an error:\n *\n * buildPlan({ signals, recordDuration: 1 }, {})\n * // groups: 3, estimate.rows: 0, range.endSeconds: null\n *\n * A plan saying the conversion writes nothing, handed back as an answer — which is the \"takes\n * the whole recording without saying so\" this checker exists to stop, one field over. A record\n * count below zero was worse: it came back as\n *\n * TimeRangeError: --start 0s is at or past the end of this -5s recording.\n *\n * a flag the caller never passed, about a recording that cannot exist, blaming the request for\n * the input. And `recordDuration: '1'` was coerced by the arithmetic and accepted, where the\n * same string is refused for `end` two functions down.\n *\n * A real header cannot produce any of them: the parser refuses a record duration that is not a\n * positive number, \"Infinity\" included.\n */\nexport function assertPlanInput(input: {\n signals?: unknown;\n recordDuration?: unknown;\n recordCount?: unknown;\n}): void {\n assertSignals(input.signals);\n assertRecordShape(input);\n assertPlannableSignals(input.signals as readonly Record<string, unknown>[]);\n}\n\n/**\n * The two numbers on a channel that `buildPlan` reads and `assertSignals` does not ask about.\n *\n * `assertSignals` asks for `index`, `label` and `isAnnotations`, which is what its other two\n * callers read — they name columns and match terms. `buildPlan` goes further: it groups the\n * channels by `samplingRate` and counts rows from `samplesPerRecord`, and asked nothing of\n * either. So a list of channel-shaped objects carrying the three fields it does check reached\n * the rate formatter and came back\n *\n * buildPlan({ signals: [{ index: 0, label: 'ECG', isAnnotations: false }], … }, {})\n * OptionError: hz must be a sampling rate in hertz, got undefined.\n *\n * naming `hz`, a parameter of a function three calls down, at a caller who passed `signals`.\n * That is the failure `assertSignals` exists to remove, and it is the same one its own\n * docstring quotes for `label`.\n *\n * The values it takes are the ones a header can really state, which is wider than it looks:\n * `samplesPerRecord` may be zero — that is what `NO_SAMPLES` reports — and a rate may be zero\n * or `Infinity`, because a record duration small enough to overflow the division is five\n * characters in an eight-character field. What a header cannot state is a fractional or\n * negative sample count, and those went through as arithmetic:\n *\n * samplesPerRecord: 2.5 // estimate.rows: 394.5, half a row\n * samplesPerRecord: -4 // estimate.rows falls, with nothing said\n *\n * Split out rather than folded into `assertSignals`, for the reason `assertRecordShape` gives\n * one function down: `selectChannels` and `buildColumnNames` never look at either field, and a\n * checker should not demand what its caller does not read.\n */\nfunction assertPlannableSignals(signals: readonly Record<string, unknown>[]): void {\n for (const [at, signal] of signals.entries()) {\n const rate = signal['samplingRate'];\n if (typeof rate !== 'number' || Number.isNaN(rate) || rate < 0) {\n throw new OptionError(\n `signals[${at}].samplingRate must be a sampling rate in hertz, got ` +\n `${describeValue(rate)}. It is samplesPerRecord over the record duration, and it is ` +\n `what the channels are grouped into output files by.`,\n );\n }\n const samples = signal['samplesPerRecord'];\n if (!Number.isInteger(samples) || (samples as number) < 0) {\n throw new OptionError(\n `signals[${at}].samplesPerRecord must be a whole number of samples, got ` +\n `${describeValue(samples)}. Every row this plan counts comes from it.`,\n );\n }\n }\n}\n\n/**\n * The two numbers a window is measured against, apart from the channel list.\n *\n * `resolveRange` is exported on its own and has its own signature block on the api page, and\n * `buildPlan` calls it — so it was covered only from above. Called directly it took both\n * numbers unexamined and answered with a range:\n *\n * resolveRange({ recordDuration: 1 }) // recordCount undefined\n * // { startSeconds: 0, endSeconds: null, startRecord: 0, endRecord: 0 }\n *\n * A range over no records, returned as a fact about a recording. Its own opening comment\n * already says why that is the wrong answer — \"no error, no warning, and a range read back as\n * `startSeconds: null, startRecord: null`, which is the 'takes the whole recording without\n * saying so'\" — about the three fields it does check. `resolveRange(42)` went the same way,\n * since reading `.start` off a number is `undefined` rather than a throw.\n *\n * Split out rather than calling `assertPlanInput`, which would demand a channel list this\n * function never looks at.\n */\nexport function assertRecordShape(input: {\n recordDuration?: unknown;\n recordCount?: unknown;\n recordStarts?: unknown;\n}): void {\n const { recordDuration, recordCount, recordStarts } = input ?? {};\n if (typeof recordDuration !== 'number' || !Number.isFinite(recordDuration) || recordDuration <= 0) {\n throw new OptionError(\n `recordDuration must be a positive number of seconds, got ${describeValue(recordDuration)}.`,\n );\n }\n if (!Number.isInteger(recordCount) || (recordCount as number) < 0) {\n throw new OptionError(\n `recordCount must be a whole number of data records, got ${describeValue(recordCount)}.`,\n );\n }\n /*\n And where the records really sit, which is what makes a discontinuous file's span longer\n than its duration. Nothing asked what it was, and the two ways of getting it wrong fail\n differently:\n\n resolveRange({ recordDuration: 1, recordCount: 3, recordStarts: 'x' })\n { startSeconds: 0, endSeconds: 3, startRecord: 0, endRecord: 0, isWholeRecording: true }\n\n A string is iterable, so it spreads to its characters and the span comes out over no\n records at all — a range that says it is the whole recording and covers none of it, which\n is a contradiction rather than an answer.\n\n resolveRange({ ..., recordStarts: 42 })\n TypeError: recordStarts is not iterable\n\n which names this function's own parameter at a caller holding the wrong thing. A list is\n what it takes: the `Float64Array` the reader builds, or an ordinary array — `readAnnotations`\n hands back `(number | null)[]`, and a null start is a record whose position is not known,\n which this already allows for.\n */\n if (\n recordStarts !== null &&\n recordStarts !== undefined &&\n !Array.isArray(recordStarts) &&\n !ArrayBuffer.isView(recordStarts)\n ) {\n throw new OptionError(\n `recordStarts must be a list of record start times, or null, got ` +\n `${describeValue(recordStarts)}. It is where the records really sit, which is what ` +\n `makes a discontinuous recording span more time than it holds.`,\n );\n }\n /*\n And what is in the list, which is where the failure above actually lands.\n\n That check asks whether the argument is a list and stops, and the contradiction its own\n paragraph describes for a string comes straight back from a list of them:\n\n resolveRange({ recordDuration: 1, recordCount: 3, recordStarts: ['a', 'b', 'c'] })\n { startSeconds: 0, endSeconds: 3, startRecord: 0, endRecord: 0, isWholeRecording: true }\n\n A range that calls itself the whole recording and covers none of it. `span` reads each\n start to find the earliest and the latest, and every comparison against a string is false,\n so it falls back to the contiguous span — which is why `endSeconds` looks right. Then\n `selectRecords` compares the same strings again and matches no record at all. `NaN` takes\n the identical route, and `NaN` is what a list built by parsing text arrives as.\n\n A record whose position is unknown is `null`, which `readAnnotations` really does hand\n back and which the code below already places from its neighbours. That is the one\n non-number this takes.\n */\n if (recordStarts !== null && recordStarts !== undefined) {\n const starts = recordStarts as ArrayLike<unknown>;\n for (let at = 0; at < starts.length; at++) {\n const start = starts[at];\n if (start === null || start === undefined || Number.isFinite(start)) continue;\n throw new OptionError(\n `recordStarts[${at}] must be the second that record starts at, or null where it is ` +\n `not known, got ${describeValue(start)}. A start that is not a number matches no ` +\n `record, so the window comes back empty and calls itself the whole recording.`,\n );\n }\n }\n}\n\n/**\n * The recording to read, checked before it is opened.\n *\n * `EdfFile.open` hands whatever it is given to `fs`, and the refusal comes back as an\n * `EdfError` coded `UNREADABLE`, hinted \"Check the path is spelled the way it is on disk and\n * that you have permission to read it\" — advice about a path, over a value that is not one,\n * filed as a problem with the recording rather than with the call. `convert({ input: 'a.edf' })`,\n * which is the option-bag shape the second parameter has, answered `Cannot read \"[object\n * Object]\"`; `convert(['a.edf', 'b.edf'])` answered `Cannot read \"a.edf,b.edf\"`, a path the\n * caller never wrote, because `String` of an array joins it with commas.\n *\n * The empty string is left to `fs`, which has no such file and says so truthfully — the same\n * reasoning `outputDir` states for not trimming: a path is not a keyword.\n */\nexport function assertInputPath(input: unknown): void {\n if (typeof input !== 'string') {\n throw new OptionError(`input must be a path to a recording, got ${describeValue(input)}.`);\n }\n}\n\n/**\n * How a rejected value reads in the refusal: numbers bare, everything else quoted so its\n * type is visible.\n *\n * `JSON.stringify` has no text for a function or a symbol — it returns `undefined`, not a\n * string — so `layout: () => 'long'` came back as `layout must be \"wide\" or \"long\", got\n * undefined.`, which names the one value that does not raise this: every option here is\n * optional, and `undefined` is how a caller says they are not passing it. `input` was worse,\n * since `convert(undefined)` and `convert(someFunction)` then produced the same sentence, and\n * the first is a forgotten argument while the second is a wrong one.\n *\n * Exported because time-range.ts had the identical function, fixed there and not here — the\n * same two-copies-of-one-helper the derived precision and the pluraliser were each pulled\n * together for.\n */\nexport function describeValue(value: unknown): string {\n return typeof value === 'number' ? String(value) : JSON.stringify(value) ?? String(value);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"options.js","sourceRoot":"","sources":["../../src/convert/options.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAErD,yFAAyF;AACzF,MAAM,OAAO,WAAY,SAAQ,KAAK;IACpC,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;IAC5B,CAAC;CACF;AAED;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,EAAE,CAAC;AAE/B,MAAM,UAAU,aAAa,CAAC,OAkB7B;IACC;;;;;;;;;;;;;;;;;;;;;MAqBE;IACF,2FAA2F;IAC3F,uFAAuF;IACvF,yEAAyE;IACzE,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC9E,MAAM,IAAI,WAAW,CACnB,6CAA6C,aAAa,CAAC,OAAO,CAAC,oBAAoB;YACrF,oDAAoD,CACvD,CAAC;IACJ,CAAC;IACD;;;;;;;;;;;;;;;;;MAiBE;IACF,KAAK,MAAM,IAAI,IAAI,CAAC,WAAW,EAAE,cAAc,EAAE,SAAS,CAAU,EAAE,CAAC;QACrE,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;QAC5B,IAAI,KAAK,KAAK,SAAS,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YACrD,MAAM,IAAI,WAAW,CACnB,GAAG,IAAI,2CAA2C,aAAa,CAAC,KAAK,CAAC,iBAAiB;gBACrF,oFAAoF,CACvF,CAAC;QACJ,CAAC;IACH,CAAC;IACD,MAAM,EAAE,QAAQ,EAA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AsD;YACtD,MAAM,IAAI,WAAW,CACnB,oBAAoB,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU;gBAClD,GAAG,OAAO,CAAC,WAAqB,EAAE,mBAAmB,CAAC,+BAA+B;gBACrF,4EAA4E;gBAC5E,+DAA+D,CAClE,CAAC;QACJ,CAAC;QACD,KAAK,IAAI,EAAE,GAAG,CAAC,EAAE,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,EAAE,EAAE,EAAE,CAAC;YAC1C,MAAM,KAAK,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;YACzB,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;gBAAE,SAAS;YAC9E,MAAM,IAAI,WAAW,CACnB,gBAAgB,EAAE,kEAAkE;gBAClF,kBAAkB,aAAa,CAAC,KAAK,CAAC,4CAA4C;gBAClF,8EAA8E,CACjF,CAAC;QACJ,CAAC;IACH,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,eAAe,CAAC,KAAc;IAC5C,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,MAAM,IAAI,WAAW,CAAC,4CAA4C,aAAa,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC7F,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC;AAC5F,CAAC","sourcesContent":["/**\n * Checking the options a caller passed, before anything is written.\n *\n * The command line has always validated these — `--decimals 1.5` is a usage error and always\n * has been — and the library did not, so the same value behaved differently depending on how\n * it arrived. `convert(file, { decimals: NaN })` resolved successfully having written whole\n * numbers into a column the caller had asked for decimals in, which is the worst of the\n * three: no error, no warning, and output that looks like a deliberate choice. `decimals: -1`\n * reached `toFixed` and came back as a bare RangeError from deep inside the formatter, naming\n * nothing the caller had written. `start: NaN` created the output directory, wrote\n * signals.csv, and then failed with a message about the input being unreadable — a partial\n * conversion, blamed on the file.\n *\n * These run at the top of `buildPlan`, which every path goes through before a directory is\n * created or a stream is opened, so a rejected option leaves nothing behind.\n */\n\nimport { counted, grouped } from '../format/list.js';\n\n/** A problem with the options a caller passed, as opposed to a problem with the file. */\nexport class OptionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'OptionError';\n }\n}\n\n/**\n * The largest `--decimals` accepts, and what both documentation pages state.\n *\n * Not a limit of `toFixed`, whatever this comment used to say. `toFixed` takes 0 to 100 and\n * throws a RangeError at 101 — which is exactly the belief `MAX_DERIVED_DECIMALS` in\n * edf/scale.ts exists to correct, having once clamped the *derived* precision to 20 on the\n * same wrong grounds and rounded a magnetometer channel needing 23 places onto a grid three\n * digital codes wide, losing 69% of its samples in silence.\n *\n * Twenty is a bound on a number a person types by hand, not on what the format can express.\n * The derived precision, which nobody types, runs to 100 and says so.\n */\nexport const MAX_DECIMALS = 20;\n\nexport function assertOptions(options: {\n decimals?: number | undefined;\n start?: number | undefined;\n duration?: number | undefined;\n end?: number | undefined;\n layout?: string | undefined;\n channels?: readonly string[] | undefined;\n outputDir?: string | undefined;\n annotationsOnly?: boolean | undefined;\n gzip?: boolean | undefined;\n bom?: boolean | undefined;\n force?: boolean | undefined;\n checksum?: boolean | undefined;\n toStdout?: boolean | undefined;\n onProgress?: unknown;\n startText?: unknown;\n durationText?: unknown;\n endText?: unknown;\n}): void {\n /*\n The bag itself, before anything is read out of it.\n\n Every check below reads `options.decimals` and its neighbours, and both functions that run\n this declare the parameter with a default of `{}` — which covers `undefined` and nothing\n else. So a value that is not an object had its properties read off it, came back\n `undefined`, and meant what `undefined` means here: that option was not given.\n\n convert('rec.edf', 'out') // converts to rec_csv, and reports success\n buildPlan(input, 42) // the whole recording, wide, three decimals\n convert('rec.edf', null) // TypeError: Cannot read properties of null\n\n `convert(file, 'out')` is the one that costs something. The second parameter is an option\n bag and the string looks like a destination, which is a mistake worth making — and the\n rows went to `<recording>_csv` beside the input, a directory the caller had not named,\n with `result.outputDir` reporting where they really went to nobody who was reading it.\n That is the sentence `outputDir: null` has at the top of this file, arrived at through the\n argument in front of it.\n\n `resolveRange` was given this check on its own bag in 0.8.75 and `readRecords` on its in\n 0.9.2. These are the last two exported functions that take one.\n */\n // An array is an object and carries none of these properties, so it went the same way as a\n // string with none of the same visibility — `convert(file, ['a.edf', 'b.edf'])` is the\n // second-argument twin of the mistake `assertInputPath` was written for.\n if (typeof options !== 'object' || options === null || Array.isArray(options)) {\n throw new OptionError(\n `options must be an object of options, got ${describeValue(options)}. The destination ` +\n `goes in it as outputDir; omit it for the defaults.`,\n );\n }\n /*\n The three options that exist only to be quoted back, quoted back unexamined.\n\n `startText`, `durationText` and `endText` carry the value exactly as the caller's user\n typed it, so a refusal names that rather than its parsed form — \"--start \\\"4h\\\"\" rather\n than \"--start 14400s\". Nothing asked whether they were text, and they reach the sentence\n as they are:\n\n convert(file, { start: 99, startText: {} })\n TimeRangeError: --start \"[object Object]\" is at or past the end of this 3s recording.\n\n convert(file, { start: 1, end: 0.5, endText: [] })\n TimeRangeError: The requested window ends at \"\", which is not after its start at 1s.\n\n `[object Object]` is the string `assertInputPath`'s own docstring names as the reason that\n function exists, and the empty quotation is the hole `describeValue` was written to stop —\n both in the one place whose entire purpose is to show the reader what they typed.\n */\n for (const name of ['startText', 'durationText', 'endText'] as const) {\n const value = options[name];\n if (value !== undefined && typeof value !== 'string') {\n throw new OptionError(\n `${name} must be the value as it was typed, got ${describeValue(value)}. It is quoted ` +\n `back in the window errors so they name what was given rather than its parsed form.`,\n );\n }\n }\n const { decimals } = options;\n if (decimals !== undefined) {\n if (!Number.isInteger(decimals) || decimals < 0 || decimals > MAX_DECIMALS) {\n throw new OptionError(\n `decimals must be a whole number between 0 and ${MAX_DECIMALS}, got ${describeValue(decimals)}.`,\n );\n }\n }\n\n /*\n `start` and `end` are positions on the recording's own clock, `duration` is a length.\n\n All three were held above zero, which is right for a length and wrong for a position: a\n recording timed from its first record's timekeeping annotation may sit before zero, and\n -100 is then where its first sample is. So a caller could read `plan.range` back as\n `recordingStartSeconds: -100` and not be allowed to ask for it — the same wall\n `parseTimeSpec` put in front of the command line until 0.5.120.\n\n Non-finite is still refused for all three, since NaN reaches a comparison as false and\n would take the whole recording without saying so.\n */\n for (const name of ['start', 'duration', 'end'] as const) {\n const value = options[name];\n if (value === undefined) continue;\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new OptionError(`${name} must be a number of seconds, got ${describeValue(value)}.`);\n }\n /*\n A length below zero is refused for what it is, rather than for not being a number.\n\n `duration: -1` came back as \"duration must be a number of seconds, got -1\", which is\n not the reason and not true: -1 is a number of seconds, and this same call accepts it\n for `start` and for `end`, where a recording timed from before zero makes it an\n ordinary position. What is wrong is that a duration is a length, and no length is\n negative — which is what the command line says for the same value, and what the API\n reference has always said this check enforces.\n */\n if (name === 'duration' && value < 0) {\n throw new OptionError(`duration is a length of time, so it cannot be ${describeValue(value)}.`);\n }\n }\n\n /*\n Two words, and a caller who writes a third means something the tool cannot do.\n\n The command line has always rejected `--layout tall`. The library took it, put it in\n `plan.layout` for the caller to read back, and wrote the wide layout — so a programmatic\n caller with a typo got a conversion that was not the one they asked for, described by a\n plan that agreed with the typo. Every other option that has a shape is checked here; this\n one was added in 0.5.0 and never joined them.\n */\n const { layout } = options;\n if (layout !== undefined && layout !== 'wide' && layout !== 'long') {\n throw new OptionError(`layout must be \"wide\" or \"long\", got ${describeValue(layout)}.`);\n }\n\n /*\n A selection that names nothing is not the absence of a selection.\n\n `buildPlan` asks `options.channels.length > 0` before selecting, so an empty array fell\n through to the branch that means \"no channels option was given\" — and `convert(file, {\n channels: [] })` wrote every channel in the recording, resolved, and said nothing. That is\n the one shape of this the command line has always refused, in as many words: \"Returning\n undefined here would mean 'no --channels given' and convert everything, which is the\n opposite of what someone passing an empty list is asking for.\"\n\n A list of blanks is the same request written differently — it is what `''.split(',')`\n produces, which is how a caller building the array from user input arrives here — and it\n reached `selectChannels` and came back \"No channels were selected\", a sentence about the\n file rather than about the call. Both are the option being wrong, so both are refused\n here, before a directory exists.\n */\n /*\n An empty destination, refused here rather than by the filesystem.\n\n `convert(file, { outputDir: '' })` went the whole way to `mkdir('')` and came back a\n `ConversionError`: \"Cannot create \\\"\\\": part of the path does not exist. Check the path\n exists and that you have permission to write there.\" Advice about a path and a permission\n for a value that is neither, and a failure class that means the conversion went wrong\n where the option did.\n\n The command line refused this at 0.6.x, with the reasoning that `--out \"$DEST\"` and `DEST`\n unset is how it gets written by accident — and left the library, which a caller building\n the path in code reaches the same way. Not trimmed, for the reason given there: a\n directory whose name is a space is a strange thing to ask for, but it is a thing the\n filesystem has and a path is not a keyword.\n */\n /*\n And its shape, which was the one option with a value and no check on it.\n\n The empty string was refused and nothing else was, so `outputDir` failed two ways that the\n paragraph above describes for the flags. A value of the wrong type reached `path.join` and\n came back as a Node error about an argument this caller never passed:\n\n convert('rec.edf', { outputDir: 42 })\n TypeError: The \"path\" argument must be of type string. Received type number (42)\n\n And `null` — which is what `JSON.parse` of a config file gives for a field left unset, the\n same door `1` and `'true'` come through — was not an error at all. It is not `undefined`,\n so it never meant \"use the default\", but every read of it is `?? default` or a truthiness\n test, so that is what it did: the rows went to `<recording>_csv` beside the input, a\n directory the caller had not named, and the run reported success.\n */\n const { outputDir } = options;\n if (outputDir !== undefined && typeof outputDir !== 'string') {\n throw new OptionError(`outputDir must be a path, got ${describeValue(outputDir)}.`);\n }\n if (outputDir === '') {\n throw new OptionError('outputDir is empty. Give a directory, for example \"./converted\".');\n }\n\n /*\n The six flags, every one of which is read as `=== true` where it is read.\n\n Which means a value that is not a boolean is not merely tolerated: it is taken as the\n opposite of what it says. `convert(file, { annotationsOnly: 'true' })` wrote every signal\n the caller had asked to leave out; `{ gzip: 1 }` wrote plain CSVs under names ending\n `.csv`, so a caller who then opened `signals.csv.gz` found nothing there. No error, no\n warning, and output that looks like a deliberate choice — which is the sentence at the\n top of this file, describing the case it was written for.\n\n `1` and `'true'` are how a flag arrives from `JSON.parse` of a config file, from a query\n string, or from a CLI wrapper that did not coerce; none of them is a caller being\n careless in a way TypeScript would catch, since the callers this reaches are the ones not\n using it. The layout check above states the rule these were missing from: \"Every other\n option that has a shape is checked here.\"\n */\n for (const name of ['annotationsOnly', 'gzip', 'bom', 'force', 'checksum', 'toStdout'] as const) {\n const value = options[name];\n if (value !== undefined && typeof value !== 'boolean') {\n throw new OptionError(`${name} must be true or false, got ${describeValue(value)}.`);\n }\n }\n\n /*\n The one option that is called rather than read, and the only one that was not checked.\n\n `convert` invokes it as `options.onProgress?.(...)` once a record has been written, so a\n value that is not a function passes every check here, opens the destination, writes rows\n into it and then fails from inside the loop:\n\n convert('rec.edf', { outputDir: 'out', onProgress: 'every record' })\n ConversionError: The onProgress callback threw: options.onProgress is not a function\n\n A callback that threw is what that sentence reports, and no callback was given; the text\n after the colon names an expression inside this package. Worse is what it leaves: `out`\n exists with a half-written signals.csv in it, which is the case the paragraph at the top\n of this file describes — \"`start: NaN` created the output directory, wrote signals.csv,\n and then failed with a message about the input being unreadable — a partial conversion,\n blamed on the file\". Checked here, the same call writes nothing and says which argument\n is wrong.\n */\n const { onProgress } = options;\n if (onProgress !== undefined && typeof onProgress !== 'function') {\n throw new OptionError(`onProgress must be a function, got ${describeValue(onProgress)}.`);\n }\n\n const { channels } = options;\n if (channels !== undefined) {\n /*\n A list of strings, checked as one. `selectChannels` calls `.trim()` on every term, so a\n caller who passed the string `'ECG'` had it iterated character by character and was told\n `No channel named \"E\"`, and one who passed `[1]` — a position, reasonably enough — got\n `TypeError: rawTerm.trim is not a function` out of the middle of the selector, naming\n nothing they had written. Both are the option being the wrong shape, which is the case\n this function exists for.\n */\n if (!Array.isArray(channels) || channels.some((term) => typeof term !== 'string')) {\n throw new OptionError(`channels must be a list of channel names, got ${describeValue(channels)}.`);\n }\n if (channels.every((term) => term.trim() === '')) {\n throw new OptionError('channels was given but lists no channel names.');\n }\n }\n}\n\n/**\n * The channel list two exported functions take, checked the way their other argument is.\n *\n * `selectChannels(signals, terms)` has checked `terms` since 0.6.x — \"`'ECG'` was iterated\n * character by character and answered `No channel named \\\"E\\\"`… naming nothing the caller had\n * written\" — and never checked `signals`, which is the argument in front of it. Passing one\n * signal where the list goes, or a header where its `signals` goes, came back as\n * `TypeError: signals.filter is not a function`: a local of this package, over a value the\n * caller did write.\n *\n * `buildColumnNames` is worse off, because a string is iterable. `buildColumnNames('ECG')`\n * returned `Map { null => 'undefined_chundefined' }` and no error at all — a column name for a\n * channel that does not exist, keyed by a position that is not one.\n *\n * The bad entry is named by position rather than the whole list being printed back: a header\n * may declare hundreds of channels, and a message is not the place for all of them.\n */\nexport function assertSignals(signals: unknown): void {\n if (!Array.isArray(signals)) {\n throw new OptionError(\n `signals must be the channel list from a header, got ${describeValue(signals)}.`,\n );\n }\n /*\n The fields the callers read, not just the one that identifies a channel.\n\n This asked for `index` and stopped, and its callers go on to read `label` and\n `isAnnotations` off the same objects. So a list of channel-shaped objects without them\n passed the check that exists to say \"these are not channels from a header\" and failed one\n line further in, or did not fail at all:\n\n selectChannels([{ index: 0 }], ['ECG'])\n TypeError: Cannot read properties of undefined (reading 'toLowerCase')\n\n selectChannels([{ index: 0, label: 42 }], ['42'])\n TypeError: signal.label.toLowerCase is not a function\n\n buildColumnNames([{ index: 0 }])\n Map { 0 => null }\n\n The first two are the failure this function was written to remove, one level down — a\n local of this package named at a caller who wrote neither. The third is worse: a column\n name of `null`, where a channel with no label at all is named `signal_0`, so `null` is not\n a name this tool ever writes.\n */\n const FIELDS = [\n ['index', 'number'],\n ['label', 'string'],\n ['isAnnotations', 'boolean'],\n ] as const;\n for (const [at, signal] of signals.entries()) {\n if (typeof signal !== 'object' || signal === null) {\n throw new OptionError(\n `signals[${at}] is not a channel from a header, got ${describeValue(signal)}.`,\n );\n }\n const fields = signal as Record<string, unknown>;\n const wrong = FIELDS.find(([name, kind]) => typeof fields[name] !== kind);\n if (wrong === undefined) continue;\n const [name, kind] = wrong;\n throw new OptionError(\n `signals[${at}].${name} must be a ${kind}, got ${describeValue(fields[name])}. A channel ` +\n `from a header carries ${FIELDS.map(([f]) => f).join(', ')}.`,\n );\n }\n}\n\n/**\n * What `buildPlan` is told about the recording, checked the way what it is asked for is.\n *\n * `assertOptions` runs at the top of `buildPlan` and covers the second argument completely.\n * The first was not looked at, and it is the one carrying the numbers every figure in the plan\n * is derived from. Two of them missing produced a plan rather than an error:\n *\n * buildPlan({ signals, recordDuration: 1 }, {})\n * // groups: 3, estimate.rows: 0, range.endSeconds: null\n *\n * A plan saying the conversion writes nothing, handed back as an answer — which is the \"takes\n * the whole recording without saying so\" this checker exists to stop, one field over. A record\n * count below zero was worse: it came back as\n *\n * TimeRangeError: --start 0s is at or past the end of this -5s recording.\n *\n * a flag the caller never passed, about a recording that cannot exist, blaming the request for\n * the input. And `recordDuration: '1'` was coerced by the arithmetic and accepted, where the\n * same string is refused for `end` two functions down.\n *\n * A real header cannot produce any of them: the parser refuses a record duration that is not a\n * positive number, \"Infinity\" included.\n */\nexport function assertPlanInput(input: {\n signals?: unknown;\n recordDuration?: unknown;\n recordCount?: unknown;\n}): void {\n assertSignals(input.signals);\n assertRecordShape(input);\n assertPlannableSignals(input.signals as readonly Record<string, unknown>[]);\n}\n\n/**\n * The two numbers on a channel that `buildPlan` reads and `assertSignals` does not ask about.\n *\n * `assertSignals` asks for `index`, `label` and `isAnnotations`, which is what its other two\n * callers read — they name columns and match terms. `buildPlan` goes further: it groups the\n * channels by `samplingRate` and counts rows from `samplesPerRecord`, and asked nothing of\n * either. So a list of channel-shaped objects carrying the three fields it does check reached\n * the rate formatter and came back\n *\n * buildPlan({ signals: [{ index: 0, label: 'ECG', isAnnotations: false }], … }, {})\n * OptionError: hz must be a sampling rate in hertz, got undefined.\n *\n * naming `hz`, a parameter of a function three calls down, at a caller who passed `signals`.\n * That is the failure `assertSignals` exists to remove, and it is the same one its own\n * docstring quotes for `label`.\n *\n * The values it takes are the ones a header can really state, which is wider than it looks:\n * `samplesPerRecord` may be zero — that is what `NO_SAMPLES` reports — and a rate may be zero\n * or `Infinity`, because a record duration small enough to overflow the division is five\n * characters in an eight-character field. What a header cannot state is a fractional or\n * negative sample count, and those went through as arithmetic:\n *\n * samplesPerRecord: 2.5 // estimate.rows: 394.5, half a row\n * samplesPerRecord: -4 // estimate.rows falls, with nothing said\n *\n * Split out rather than folded into `assertSignals`, for the reason `assertRecordShape` gives\n * one function down: `selectChannels` and `buildColumnNames` never look at either field, and a\n * checker should not demand what its caller does not read.\n */\nfunction assertPlannableSignals(signals: readonly Record<string, unknown>[]): void {\n for (const [at, signal] of signals.entries()) {\n const rate = signal['samplingRate'];\n if (typeof rate !== 'number' || Number.isNaN(rate) || rate < 0) {\n throw new OptionError(\n `signals[${at}].samplingRate must be a sampling rate in hertz, got ` +\n `${describeValue(rate)}. It is samplesPerRecord over the record duration, and it is ` +\n `what the channels are grouped into output files by.`,\n );\n }\n const samples = signal['samplesPerRecord'];\n if (!Number.isInteger(samples) || (samples as number) < 0) {\n throw new OptionError(\n `signals[${at}].samplesPerRecord must be a whole number of samples, got ` +\n `${describeValue(samples)}. Every row this plan counts comes from it.`,\n );\n }\n }\n}\n\n/**\n * The two numbers a window is measured against, apart from the channel list.\n *\n * `resolveRange` is exported on its own and has its own signature block on the api page, and\n * `buildPlan` calls it — so it was covered only from above. Called directly it took both\n * numbers unexamined and answered with a range:\n *\n * resolveRange({ recordDuration: 1 }) // recordCount undefined\n * // { startSeconds: 0, endSeconds: null, startRecord: 0, endRecord: 0 }\n *\n * A range over no records, returned as a fact about a recording. Its own opening comment\n * already says why that is the wrong answer — \"no error, no warning, and a range read back as\n * `startSeconds: null, startRecord: null`, which is the 'takes the whole recording without\n * saying so'\" — about the three fields it does check. `resolveRange(42)` went the same way,\n * since reading `.start` off a number is `undefined` rather than a throw.\n *\n * Split out rather than calling `assertPlanInput`, which would demand a channel list this\n * function never looks at.\n */\nexport function assertRecordShape(input: {\n recordDuration?: unknown;\n recordCount?: unknown;\n recordStarts?: unknown;\n}): void {\n const { recordDuration, recordCount, recordStarts } = input ?? {};\n if (typeof recordDuration !== 'number' || !Number.isFinite(recordDuration) || recordDuration <= 0) {\n throw new OptionError(\n `recordDuration must be a positive number of seconds, got ${describeValue(recordDuration)}.`,\n );\n }\n if (!Number.isInteger(recordCount) || (recordCount as number) < 0) {\n throw new OptionError(\n `recordCount must be a whole number of data records, got ${describeValue(recordCount)}.`,\n );\n }\n /*\n And where the records really sit, which is what makes a discontinuous file's span longer\n than its duration. Nothing asked what it was, and the two ways of getting it wrong fail\n differently:\n\n resolveRange({ recordDuration: 1, recordCount: 3, recordStarts: 'x' })\n { startSeconds: 0, endSeconds: 3, startRecord: 0, endRecord: 0, isWholeRecording: true }\n\n A string is iterable, so it spreads to its characters and the span comes out over no\n records at all — a range that says it is the whole recording and covers none of it, which\n is a contradiction rather than an answer.\n\n resolveRange({ ..., recordStarts: 42 })\n TypeError: recordStarts is not iterable\n\n which names this function's own parameter at a caller holding the wrong thing. A list is\n what it takes: the `Float64Array` the reader builds, or an ordinary array — `readAnnotations`\n hands back `(number | null)[]`, and a null start is a record whose position is not known,\n which this already allows for.\n */\n if (\n recordStarts !== null &&\n recordStarts !== undefined &&\n !Array.isArray(recordStarts) &&\n !ArrayBuffer.isView(recordStarts)\n ) {\n throw new OptionError(\n `recordStarts must be a list of record start times, or null, got ` +\n `${describeValue(recordStarts)}. It is where the records really sit, which is what ` +\n `makes a discontinuous recording span more time than it holds.`,\n );\n }\n /*\n And what is in the list, which is where the failure above actually lands.\n\n That check asks whether the argument is a list and stops, and the contradiction its own\n paragraph describes for a string comes straight back from a list of them:\n\n resolveRange({ recordDuration: 1, recordCount: 3, recordStarts: ['a', 'b', 'c'] })\n { startSeconds: 0, endSeconds: 3, startRecord: 0, endRecord: 0, isWholeRecording: true }\n\n A range that calls itself the whole recording and covers none of it. `span` reads each\n start to find the earliest and the latest, and every comparison against a string is false,\n so it falls back to the contiguous span — which is why `endSeconds` looks right. Then\n `selectRecords` compares the same strings again and matches no record at all. `NaN` takes\n the identical route, and `NaN` is what a list built by parsing text arrives as.\n\n A record whose position is unknown is `null`, which `readAnnotations` really does hand\n back and which the code below already places from its neighbours. That is the one\n non-number this takes.\n */\n if (recordStarts !== null && recordStarts !== undefined) {\n const starts = recordStarts as ArrayLike<unknown>;\n /*\n And one for every record, which is what the field is documented to be: \"True start time\n of each data record\". A shorter list is not a partial answer, it is a shorter recording:\n\n resolveRange({ recordDuration: 1, recordCount: 3, recordStarts: [0] })\n { startSeconds: 0, endSeconds: 1, startRecord: 0, endRecord: 1,\n isWholeRecording: true }\n\n One record of the three, called the whole recording — the same contradiction the check\n below removes for a list of strings, reached by leaving entries out instead of filling\n them wrongly. `span` reads the earliest and latest off whatever it is given and\n `selectRecords` matches only the indexes it holds, so a list of one describes a file of\n one however many records the caller said there were.\n\n Empty is the exception, and it is not a short list: `[]` is how \"no record times are\n known\" arrives, which the two functions below already answer by falling back to\n contiguous positions. `null` says the same thing and is the form the reader hands over.\n */\n if (starts.length !== 0 && starts.length !== recordCount) {\n // Both counts through the helpers, like every other sentence that puts one number\n // against another: the phrase exists to compare them.\n throw new OptionError(\n `recordStarts has ${grouped(starts.length)} of the ` +\n `${counted(recordCount as number, 'record start time')} this recording needs. It is ` +\n `where each data record really sits, so a shorter list describes a shorter ` +\n `recording; pass null, or an empty list, where none are known.`,\n );\n }\n for (let at = 0; at < starts.length; at++) {\n const start = starts[at];\n if (start === null || start === undefined || Number.isFinite(start)) continue;\n throw new OptionError(\n `recordStarts[${at}] must be the second that record starts at, or null where it is ` +\n `not known, got ${describeValue(start)}. A start that is not a number matches no ` +\n `record, so the window comes back empty and calls itself the whole recording.`,\n );\n }\n }\n}\n\n/**\n * The recording to read, checked before it is opened.\n *\n * `EdfFile.open` hands whatever it is given to `fs`, and the refusal comes back as an\n * `EdfError` coded `UNREADABLE`, hinted \"Check the path is spelled the way it is on disk and\n * that you have permission to read it\" — advice about a path, over a value that is not one,\n * filed as a problem with the recording rather than with the call. `convert({ input: 'a.edf' })`,\n * which is the option-bag shape the second parameter has, answered `Cannot read \"[object\n * Object]\"`; `convert(['a.edf', 'b.edf'])` answered `Cannot read \"a.edf,b.edf\"`, a path the\n * caller never wrote, because `String` of an array joins it with commas.\n *\n * The empty string is left to `fs`, which has no such file and says so truthfully — the same\n * reasoning `outputDir` states for not trimming: a path is not a keyword.\n */\nexport function assertInputPath(input: unknown): void {\n if (typeof input !== 'string') {\n throw new OptionError(`input must be a path to a recording, got ${describeValue(input)}.`);\n }\n}\n\n/**\n * How a rejected value reads in the refusal: numbers bare, everything else quoted so its\n * type is visible.\n *\n * `JSON.stringify` has no text for a function or a symbol — it returns `undefined`, not a\n * string — so `layout: () => 'long'` came back as `layout must be \"wide\" or \"long\", got\n * undefined.`, which names the one value that does not raise this: every option here is\n * optional, and `undefined` is how a caller says they are not passing it. `input` was worse,\n * since `convert(undefined)` and `convert(someFunction)` then produced the same sentence, and\n * the first is a forgotten argument while the second is a wrong one.\n *\n * Exported because time-range.ts had the identical function, fixed there and not here — the\n * same two-copies-of-one-helper the derived precision and the pluraliser were each pulled\n * together for.\n */\nexport function describeValue(value: unknown): string {\n return typeof value === 'number' ? String(value) : JSON.stringify(value) ?? String(value);\n}\n"]}
|
package/dist/convert/timing.js
CHANGED
|
@@ -41,7 +41,33 @@ export function deriveRecordStarts(file, annotationData) {
|
|
|
41
41
|
// own comment names and which nothing was using it for.
|
|
42
42
|
message: `${counted(annotationData.malformed, 'annotation entry', 'annotation entries')} ` +
|
|
43
43
|
`${annotationData.malformed === 1 ? 'was' : 'were'} unreadable and could not be exported.`,
|
|
44
|
-
|
|
44
|
+
/*
|
|
45
|
+
"The rest were exported normally" was said whether or not there was a rest.
|
|
46
|
+
|
|
47
|
+
A writer that cannot state an onset tends not to manage it anywhere, so a file whose
|
|
48
|
+
every event entry is unreadable is the ordinary way here — and it was answered with
|
|
49
|
+
the count of what was lost and a sentence saying the remainder came through, over an
|
|
50
|
+
annotations.csv holding its header and no rows:
|
|
51
|
+
|
|
52
|
+
warning: 2 annotation entries were unreadable and could not be exported.
|
|
53
|
+
The rest were exported normally. ...
|
|
54
|
+
|
|
55
|
+
Wrote scoring_csv
|
|
56
|
+
annotations.csv 0 rows
|
|
57
|
+
|
|
58
|
+
Four lines apart, the summary settling it. Same shape as the "No event was lost"
|
|
59
|
+
sentence forty lines down, which was corrected for the same reason: a hint true of
|
|
60
|
+
most files is not true of the one it is printed over.
|
|
61
|
+
|
|
62
|
+
Said without counting, rather than by counting. What makes the old sentence wrong is
|
|
63
|
+
that it asserts a remainder exists; what it was for is the assurance that nothing
|
|
64
|
+
readable was dropped, and that holds however many were readable. Counting instead
|
|
65
|
+
would have split `--info` from a conversion — the scan behind `--info` stops at the
|
|
66
|
+
first record that states a time and never counts the events, which is the bound that
|
|
67
|
+
keeps it a header read.
|
|
68
|
+
*/
|
|
69
|
+
hint: 'Every entry that could be read was exported. The file may have been written by a ' +
|
|
70
|
+
'non-conforming tool.',
|
|
45
71
|
});
|
|
46
72
|
}
|
|
47
73
|
/*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"timing.js","sourceRoot":"","sources":["../../src/convert/timing.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAUnD;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,qBAAqB,CACnC,WAAkC,EAClC,OAAgB;IAEhB,IAAI,OAAO;QAAE,OAAO,CAAC,GAAG,WAAW,CAAC,CAAC;IACrC,OAAO,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,EA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AAM,CAAC,aAAa,IAAI,CAAC,CAAC,MAAM,CAAC,gBAAgB,GAAG,CAAC,CAAC;YAAE,SAAS;QACrE,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,cAAc,GAAG,MAAM,CAAC,gBAAgB,CAAC;QAClE,IAAI,IAAI,GAAG,CAAC,IAAI,IAAI,GAAG,QAAQ;YAAE,QAAQ,GAAG,IAAI,CAAC;IACnD,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,SAAS,cAAc,CAAC,MAAc,EAAE,IAAa;IACnD;;;;;;;;;MASE;IACF,MAAM,IAAI,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC;QAClC,CAAC,CAAC,GAAG,YAAY,CAAC,MAAM,CAAC,2BAA2B;QACpD,CAAC,CAAC,wDAAwD,CAAC;IAC7D,OAAO;QACL,IAAI,EAAE,eAAe;QACrB,QAAQ,EAAE,SAAS;QACnB,OAAO,EACL,qDAAqD,IAAI,6BAA6B;YACtF,OAAO,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,gDAAgD;YAC/F,uDAAuD;QACzD,IAAI,EACF,qFAAqF;YACrF,0FAA0F;KAC7F,CAAC;AACJ,CAAC","sourcesContent":["import type { Diagnostic } from '../edf/errors.js';\nimport type { EdfFile } from '../edf/reader.js';\nimport { counted, grouped, listed } from '../format/list.js';\nimport { plainSeconds } from '../format/number.js';\n\nexport interface AnnotationTimingData {\n recordStarts: (number | null)[];\n malformed: number;\n /** Unreadable TALs in first position, which carry timing rather than an event. */\n malformedTimekeeping?: number;\n malformedTimekeepingWithText?: number;\n}\n\n/**\n * The EDF+D warning's promise, withdrawn when the file cannot keep it.\n *\n * The header parser raises DISCONTINUOUS with the hint \"Each row carries its true recording\n * time, so gaps stay visible instead of being closed\" — which is what an EDF+D conversion\n * does, when the record times can be read. When they cannot, the very next warning in the\n * same run says the opposite: \"Times are written as if the records were contiguous. Any gaps\n * are lost.\" Two warnings, printed together, and the second denies the first.\n *\n * The parser cannot know: whether the starts can be derived is settled here, after the\n * annotation channel has been read. So the hint is amended where the answer is, the same way\n * `withoutFileRateWarning` drops a header diagnostic the plan has superseded.\n */\nexport function withTimingPromiseKept(\n diagnostics: readonly Diagnostic[],\n derived: boolean,\n): Diagnostic[] {\n if (derived) return [...diagnostics];\n return diagnostics.map((d) =>\n d.code === 'DISCONTINUOUS' && d.hint?.includes('gaps stay visible')\n ? {\n ...d,\n hint:\n 'Where its records sit in time is not recorded in this file, so they are written ' +\n 'as if contiguous — see the warning below.',\n }\n : d,\n );\n}\n\n/**\n * Resolve the true start time of every data record.\n *\n * Continuous recordings need no table because their record positions are\n * arithmetic. EDF+D recordings carry their positions in the annotation channel;\n * missing or malformed timekeeping entries are reported before falling back.\n */\nexport function deriveRecordStarts(\n file: EdfFile,\n annotationData: AnnotationTimingData,\n): { starts: Float64Array | null; diagnostics: Diagnostic[] } {\n const diagnostics: Diagnostic[] = [];\n\n if (annotationData.malformed > 0) {\n diagnostics.push({\n code: 'ANNOTATION_DECODE_FAILED',\n severity: 'warning',\n // Through `counted`, with the irregular plural spelled out — which is the case its\n // own comment names and which nothing was using it for.\n message:\n `${counted(annotationData.malformed, 'annotation entry', 'annotation entries')} ` +\n `${annotationData.malformed === 1 ? 'was' : 'were'} unreadable and could not be exported.`,\n hint: 'The rest were exported normally. The file may have been written by a non-conforming tool.',\n });\n }\n\n\n /*\n A timekeeping TAL is not an event, and saying it \"could not be exported\" describes the\n wrong loss twice over.\n\n These were counted among the annotations, so a file with one unreadable timekeeping TAL\n and three good events announced \"1 annotation entry was unreadable and could not be\n exported\" — while exporting all three. Nothing was missing from annotations.csv; what\n went missing was a record's position in time, which the message never mentioned.\n */\n const lostTimekeeping = annotationData.malformedTimekeeping ?? 0;\n const withText = annotationData.malformedTimekeepingWithText ?? 0;\n // The EDF+D branch below raises its own, which names the records and is more specific.\n // Saying both would report one problem twice.\n if (lostTimekeeping > 0 && file.header.continuity !== 'EDF+D') {\n const one = lostTimekeeping === 1;\n diagnostics.push({\n code: 'ANNOTATION_DECODE_FAILED',\n severity: 'warning',\n // Through `counted`, like the four other counts of \"data record\" in this file. This one\n // spelled the noun and the verb by hand — `record${one ? '' : 's'} carr${one ? 'ies' :\n // 'y'}` — while its nearest neighbour, sixty lines down and about the same records,\n // writes `${counted(n, 'data record')} ${one ? 'carries' : 'carry'}`. Same phrase, same\n // file, two spellings, and only one of them can be checked against the helper.\n message:\n `${counted(lostTimekeeping, 'data record')} ${one ? 'carries' : 'carry'} a timekeeping ` +\n `annotation that could not be read, so ${one ? 'it does' : 'they do'} not say where in ` +\n `time ${one ? 'it sits' : 'they sit'}.`,\n hint:\n /*\n \"No event was lost\" was said whatever the entry held.\n\n A first-position TAL states the record's start time and may carry events after it,\n which the specification allows and writers do. When one of those cannot be parsed\n the events go with it: a six-event file came out with two, and the only warning\n about it said in so many words that nothing had gone. Those entries are counted\n among the unreadable ones now, which is the warning printed above this one; this\n sentence keeps to what is true of the entries it is actually about.\n */\n /*\n Grouped, like the count of the same records one line above it.\n\n The message says `counted(lostTimekeeping, 'data record')`; the hint under it counts\n a subset of those records and spelled the number by hand. When the subset is all of\n them — which is the ordinary case, since a writer that cannot state an onset tends\n not to manage it anywhere — the two print the same number two lines apart, one\n grouped and one not:\n\n warning: 1,010 data records carry a timekeeping annotation that could not be\n read, so they do not say where in time they sit.\n 1010 of them also carried event text, which went with them and is\n counted above.\n */\n (withText > 0\n ? `${withText === 1 ? 'One of them' : `${grouped(withText)} of them`} also carried event text, ` +\n `which went with ${withText === 1 ? 'it' : 'them'} and is counted above. A ` +\n `timekeeping annotation itself states a record's start time and is never exported. `\n : 'No event was lost — a timekeeping annotation states a record\\'s start time and ' +\n 'is never exported. ') + 'Times are derived from the records that could be read.',\n });\n }\n\n /*\n A continuous recording's records are contiguous, but the first one need not sit at zero.\n\n EDF+ puts the header's start time and every annotation onset on one origin, and says the\n first data record's timekeeping TAL \"always starts with +0.X\", stating the fraction of a\n second by which that record follows it. Ignoring that fraction timed the samples from 0\n while the events kept their true onsets, so the two ended up on origins half a second\n apart — an event at +0.75 in a 4 Hz recording whose first TAL reads +0.5 landed on sample\n 3 instead of sample 1. The same file marked EDF+D, byte-identical but for the reserved\n field, placed it correctly, which is what gives the omission away.\n\n Records stay contiguous, which is what continuous means: only the origin moves. A first\n TAL of +0 needs no table at all, and that is nearly every file.\n */\n if (file.header.continuity !== 'EDF+D') {\n if (file.header.continuity !== 'EDF+C') {\n /*\n An annotation channel the reserved field never claimed.\n\n Without an `EDF+C` or `EDF+D` marker this is a plain EDF file, so the origin is not\n applied and the samples are timed from zero. The annotation channel is found by label\n rather than by the marker, though, so its events are still read and exported — with\n the onsets the file gives them.\n\n On a file whose timekeeping says the records start at 1000s, that put signals.csv at\n 0.000 and the event at 1000.5 in annotations.csv: two files from one conversion, a\n thousand seconds apart, and nothing said so. output-files promises the opposite —\n \"`onset_s` is on the same clock as `time_s` in the signal files\".\n\n Reported rather than repaired. Which clock is right is not knowable from here: the\n marker says plain EDF and the annotation channel says otherwise, and picking one would\n move either the samples or the events by the origin on a guess.\n */\n const stated = annotationData.recordStarts.find((start) => start !== null) ?? null;\n const base = file.header.isBdf ? 'BDF' : 'EDF';\n const plus = `${base}+`;\n if (stated !== null && Math.abs(stated) > 0) {\n diagnostics.push({\n code: 'MISSING_EDF_PLUS_MARKER',\n severity: 'warning',\n // The markers as this file spells them, which is what the contradiction warning\n // sixty lines down already does and what NO_SIGNAL_CHANNELS was fixed for. A BDF\n // recording was told to \"Mark the file EDF+C\" — not a value BDF+ defines — and\n // that it \"is read as plain EDF\", which it is not.\n message:\n `This file has an annotation channel stating that its records begin at ` +\n `${plainSeconds(stated)}s, but its reserved field carries no ${plus}C or ${plus}D ` +\n `marker — so it is read as plain ${base}, time_s counts from zero, and the two ` +\n `disagree by ${plainSeconds(stated)}s.`,\n hint:\n `annotations.csv keeps the onsets the file gives, so its events and signals.csv ` +\n `are on different clocks. Mark the file ${plus}C, or subtract the offset from ` +\n `the onsets, before joining them.`,\n });\n }\n return { starts: null, diagnostics };\n }\n\n /*\n The origin comes from whichever record first states one, not from record 0 alone.\n\n Reading only `recordStarts[0]` meant a single unreadable timekeeping TAL threw the\n origin away and timed the whole file from zero — while records 1 and 2, saying plainly\n that they start at 1.5s and 2.5s, went unread. A recording whose records sit at 0.5s,\n 1.5s and 2.5s came out with every sample 0.5s earlier than the file states, against\n annotation onsets that kept their true values. That is precisely the mismatch 0.4.9\n fixed, arriving through the one hole left in it, and the byte-identical EDF+D twin\n timed it correctly, which is what gives it away.\n\n Continuity is what makes this recoverable: record i sits at `origin + i * duration`,\n so any readable record determines the origin for all of them.\n */\n const origin = originOf(annotationData.recordStarts, file.header.recordDuration);\n if (origin === null) return { starts: null, diagnostics };\n\n const contiguous = new Float64Array(file.recordCount);\n for (let i = 0; i < file.recordCount; i++) {\n contiguous[i] = origin + i * file.header.recordDuration;\n }\n\n /*\n A file marked continuous whose own records disagree about it.\n\n Nothing looked at records past the first, so an EDF+C file whose records are in fact\n spread out was timed as though they were contiguous and said nothing. The records are\n being read here anyway, so the contradiction costs nothing to notice — and it is the\n file, not the reader, that has to be wrong for this to fire.\n\n Compared against what the file can express, not for equality. 0.4.41 asked whether the\n two doubles were the same, which they are not: a recording of 0.1s records sitting at\n 0.1, 0.2, 0.3 ... is contiguous by construction, and 0.1 + 2 * 0.1 is\n 0.30000000000000004. Two of its eight records were reported as contradicting\n continuity, on an ordinary file — and under --strict that was a failed run. The\n smallest interval the recording distinguishes is one sample of its fastest channel;\n anything below half of that is arithmetic, not a gap. `canCarry` has already refused\n origins where the double spacing swamps that interval, so the representation error is\n under the tolerance by construction rather than by hope.\n */\n const tolerance = finestInterval(file) / 2;\n const contradicting = annotationData.recordStarts.filter(\n (declared, i) =>\n typeof declared === 'number' && Math.abs(declared - (contiguous[i] as number)) > tolerance,\n ).length;\n if (contradicting > 0) {\n const continuous = file.header.isBdf ? 'BDF+C' : 'EDF+C';\n const discontinuous = file.header.isBdf ? 'BDF+D' : 'EDF+D';\n diagnostics.push({\n code: 'DISCONTINUOUS',\n severity: 'warning',\n /*\n The markers as the file spells them.\n\n `continuity` normalises `BDF+C` to the internal `EDF+C` tag, and that tag reached\n the message: a BDF+ recording was told it is \"marked continuous (EDF+C)\" — a string\n it does not contain — and advised that it \"should have been marked EDF+D\", which is\n not a value BDF+ defines. A reader grepping the header for either finds nothing.\n\n The sibling discontinuous warning has done this since 0.3.x: `${'$'}{isBdf ? 'BDF+D' :\n 'EDF+D'}`. Same code, same header field, and the continuous branch never got it.\n */\n /*\n Both counts grouped, which is the whole point of the sentence: it puts one against\n the other. 0.8.5 gave `counted` the grouping and went through the bare numbers\n standing beside it — including this exact phrase in the ANNOTATION_DECODE_FAILED\n warning eighty lines down, `${grouped(missing.length)} of ${counted(...)}` — and\n missed this one, so a three-thousand-record file read \"2999 of its 3,000 data\n records\", three words apart.\n */\n message:\n `This file is marked continuous (${continuous}), but ${grouped(contradicting)} of its ` +\n `${counted(file.recordCount, 'data record')} ` +\n `${contradicting === 1 ? 'says it starts' : 'say they start'} somewhere other than ` +\n `where continuity puts ${contradicting === 1 ? 'it' : 'them'}.`,\n hint:\n `Times are written as if the records were contiguous, which is what ${continuous} ` +\n `means. If the recording really has gaps, the file should have been marked ` +\n `${discontinuous}.`,\n });\n }\n const first = origin;\n const last = contiguous[file.recordCount - 1] ?? first;\n if (!canCarry(last, file)) {\n diagnostics.push(unusableOrigin(first, file));\n return { starts: null, diagnostics };\n }\n /*\n An origin of zero is the same as no origin, for timing. It is not the same for the\n check above.\n\n This returned early on `origin === 0`, which is right about the times — contiguous\n starts from zero are what timing from zero already produces — and skipped the\n contradiction check on the way past. So an EDF+C file whose records say 0, 5 and 10 on\n one-second records went unreported, while the same file shifted one second, saying 1, 6\n and 11, was reported. The contradiction is in records 1 and 2 either way; where record 0\n happens to sit decides nothing about it.\n */\n if (origin === 0) return { starts: null, diagnostics };\n return { starts: contiguous, diagnostics };\n }\n\n if (file.annotationSignals.length === 0) {\n diagnostics.push({\n code: 'DISCONTINUOUS',\n severity: 'warning',\n message:\n 'This file is marked discontinuous but has no annotation channel, so where its ' +\n 'records sit in time is not recorded anywhere.',\n hint: 'Times are written as if the records were contiguous. Any gaps are lost.',\n });\n return { starts: null, diagnostics };\n }\n\n /*\n A record with no readable time is placed from the origin the other records establish,\n not from zero.\n\n `i * recordDuration` assumed the recording began at zero, which is the one thing the\n other records are in a position to contradict: a file starting at 0.5s put its\n unreadable record at 0.000 while its neighbours sat at 1.5s and 2.5s. The guess is still\n a guess — a discontinuous file may have a gap exactly there — and it is still reported\n below, but starting it from where the recording actually begins is strictly closer, and\n it makes an EDF+D file agree with its byte-identical EDF+C twin about record 0.\n */\n const base = originOf(annotationData.recordStarts, file.header.recordDuration) ?? 0;\n const starts = new Float64Array(file.recordCount);\n const missing: number[] = [];\n for (let i = 0; i < file.recordCount; i++) {\n const declared = annotationData.recordStarts[i];\n if (declared === null || declared === undefined) {\n missing.push(i);\n starts[i] = base + i * file.header.recordDuration;\n } else {\n starts[i] = declared;\n }\n }\n\n if (missing.length > 0) {\n /*\n Cut by the function that cuts every other list in a sentence here.\n\n This one rolled its own: five items and a bare `…`, where `listed` shows eight and counts\n what it left — \"and 32 more\" on the rate warning, \"and 112 more\" on the leftover files.\n The count is the honest half, and 0.7.58 taught the shared one not to hide a single item\n behind a phrase longer than the item. None of that reached this message, because it was\n never asking. Two implementations of one job, differing in the limit and in what they say\n about the tail.\n */\n const shown = listed(missing.map(String));\n // \"1 of 3 data records carry ... their true position\" — the subject is the one, not the three.\n const one = missing.length === 1;\n diagnostics.push({\n code: 'ANNOTATION_DECODE_FAILED',\n severity: 'warning',\n message:\n `${grouped(missing.length)} of ${counted(file.recordCount, 'data record')} ${one ? 'carries' : 'carry'} no ` +\n `readable timekeeping annotation (record${one ? '' : 's'} ${shown}), so ` +\n `${one ? 'its' : 'their'} true position in time is unknown.`,\n hint: one\n ? 'That record is timed as if it were contiguous; treat its timestamp as unreliable.'\n : 'Those records are timed as if they were contiguous; treat their timestamps as unreliable.',\n });\n }\n\n /*\n Furthest from zero, in either direction.\n\n This took the signed maximum and seeded it with 0, so a recording whose records all sit\n at negative onsets never got past the seed: `furthest` stayed 0, which any interval can\n carry. Then the samples collapsed anyway, because the arithmetic that defeats a large\n positive origin defeats a large negative one identically — at -1e16 seconds, adding a\n 1-second sample interval leaves the double unchanged.\n\n A four-record recording of eight samples wrote two rows, exit 0, no warning. Its\n byte-for-byte positive mirror wrote all eight and explained why it had to time them from\n zero. Same file, same failure, opposite sign, opposite outcome — and the silent one is\n the one that loses data, which is exactly what unusableOrigin exists to prevent.\n */\n let furthest = 0;\n for (const start of starts) if (Math.abs(start) > Math.abs(furthest)) furthest = start;\n if (!canCarry(furthest, file)) {\n diagnostics.push(unusableOrigin(furthest, file));\n return { starts: null, diagnostics };\n }\n\n /*\n Two ways a record can put the time column out of order, and only one was being looked for.\n\n A record starting before the one before it is the obvious case. The other is a record\n starting before the one before it *ends*: starts of 0, 0.5 and 1.0 on one-second records\n are strictly increasing, so nothing fired, and the rows still came out 0.25, 0.5, 0.75,\n 0.5 — because record 0's samples run to 0.75 while record 1 begins at 0.5. Overlapping\n acquisition is what a device does when it re-sends a buffer, and the reader has no more\n to say about it than about the reversed case: every sample is written, in file order,\n with the time the file gives it.\n\n Contiguity is not overlap. A continuous recording has `starts[i] === starts[i-1] +\n duration` exactly, so the comparison is made strict by a fraction of the finest interval\n the recording can express — the same measure the origin check uses.\n */\n const slack = finestInterval(file) / 2;\n let outOfOrder = 0;\n let overlapping = 0;\n for (let i = 1; i < starts.length; i++) {\n const previous = starts[i - 1] as number;\n const current = starts[i] as number;\n if (current < previous) outOfOrder++;\n else if (current + slack < previous + file.header.recordDuration) overlapping++;\n }\n if (outOfOrder > 0) {\n diagnostics.push({\n code: 'DISCONTINUOUS',\n severity: 'warning',\n message:\n `${counted(outOfOrder, 'data record')} ` +\n `${outOfOrder === 1 ? 'starts' : 'start'} earlier than the record before ` +\n `${outOfOrder === 1 ? 'it' : 'them'}.`,\n hint: 'Rows are written in file order, so the time column will not increase monotonically.',\n });\n }\n if (overlapping > 0) {\n diagnostics.push({\n code: 'DISCONTINUOUS',\n severity: 'warning',\n message:\n `${counted(overlapping, 'data record')} ` +\n `${overlapping === 1 ? 'starts' : 'start'} before the record before ` +\n `${overlapping === 1 ? 'it' : 'them'} ends, so ${overlapping === 1 ? 'its' : 'their'} ` +\n `samples overlap in time.`,\n /*\n An overlap does not always put the column out of order, and this said it did.\n\n The two counts above share a sentence and only one of them earns it. A record starting\n *earlier* than the one before it steps the column back by construction. A record\n starting before the one before it *ends* need not: what decides is whether it begins\n after the previous record's last sample, and the last sample is one interval short of\n the record's end. Three-tenths of a second of overlap on a one-second record sampled\n twice a second writes\n\n time_s,A\n 0.000\n 0.500\n 0.700\n 1.200\n\n which increases at every step, under a warning saying it would not. Both records do\n describe 0.700 to 1.000, which is the thing that is true either way and is what the\n sentence says now.\n */\n hint:\n 'Rows are written in file order, and two records describe the same stretch of time. ' +\n 'Where they overlap by more than one sample interval the time column steps backwards.',\n });\n }\n\n return { starts, diagnostics };\n}\n\n/**\n * The recording's origin, from the first record that states where it is.\n *\n * Records of a continuous recording sit end to end, so record `i` beginning at `t` puts the\n * origin at `t - i * duration`. Any one readable timekeeping TAL is therefore enough, which\n * is what stops one unreadable entry from costing the whole file its position in time.\n */\nfunction originOf(recordStarts: readonly (number | null)[], recordDuration: number): number | null {\n for (const [index, declared] of recordStarts.entries()) {\n if (typeof declared !== 'number') continue;\n const origin = declared - index * recordDuration;\n return Number.isFinite(origin) ? origin : null;\n }\n return null;\n}\n\n/**\n * Whether times this far out can still tell one sample from the next.\n *\n * A double spaces its values further apart the larger they get: at 1e16 the gap is 2\n * seconds, so `t + 1` is `t`. Past that point a recording's declared origin stops being a\n * position and becomes a wall — the arithmetic that places records and samples returns the\n * origin itself, whatever is added to it.\n *\n * The finest thing that has to survive is the gap between two consecutive samples of the\n * fastest channel, since that is what the time column is made of. If that survives, so does\n * a whole record.\n */\nfunction canCarry(origin: number, file: EdfFile): boolean {\n if (!Number.isFinite(origin)) return false;\n // Asked of the origin furthest from zero, whichever side it is on: the spacing of doubles\n // grows with magnitude, not with value, so -1e16 and +1e16 fail this identically.\n return origin + finestInterval(file) > origin;\n}\n\n/**\n * The shortest span this recording can tell apart: one sample of its fastest channel.\n *\n * The time column is made of these, so nothing below one is a distinction the file is in a\n * position to make — which is what makes it the right size for both the \"can this origin\n * still separate two samples\" question and the \"is this record really somewhere else\"\n * question.\n */\nfunction finestInterval(file: EdfFile): number {\n let interval = file.header.recordDuration;\n for (const signal of file.header.signals) {\n if (signal.isAnnotations || !(signal.samplesPerRecord > 0)) continue;\n const step = file.header.recordDuration / signal.samplesPerRecord;\n if (step > 0 && step < interval) interval = step;\n }\n return interval;\n}\n\n/**\n * An origin the file's own arithmetic cannot express, reported rather than acted on.\n *\n * Two things went wrong when this was taken at face value, both of them quiet. A file whose\n * records all collapsed onto one instant made the recording zero seconds long, and the\n * window resolver — which had no reason to suspect the recording rather than the request —\n * blamed a flag nobody had passed:\n *\n * error: --start 100000000000000000s is at or past the end of this\n * 100000000000000000s recording.\n *\n * Slightly below that, the collapse is partial: `records[i].start + recordDuration` equals\n * the start again, so the test for \"does this record overlap the window\" fails for every\n * record whose neighbour rounded onto it. A twelve-row recording wrote four rows, exit 0,\n * no warning — the eight that vanished looked exactly like a file that never had them.\n *\n * Timing from zero is what the file did before 0.4.9 taught it to honour the first\n * timekeeping TAL, and at this magnitude it is the only column that can hold distinct\n * values. The origin is lost, so this says so.\n */\nfunction unusableOrigin(origin: number, file: EdfFile): Diagnostic {\n /*\n `Infinity` is a token, not a distance.\n\n `plain` expands exponent notation and hands anything else back, so a non-finite origin\n arrived on screen as \"place it Infinitys from its own start date\" — the exact form\n `formatDuration` exists to keep off the screen, its comment naming \"NaNs\" and \"Infinitys\"\n as what the fallback used to print, and the word the rest of this tool uses for the same\n quantity is \"unknown\". The origin overflows for the reason the recording's length does:\n a record duration near the top of a double, multiplied out over three records, leaves it.\n */\n const away = Number.isFinite(origin)\n ? `${plainSeconds(origin)}s from its own start date`\n : 'further from its own start date than a number can hold';\n return {\n code: 'DISCONTINUOUS',\n severity: 'warning',\n message:\n `This recording's timekeeping annotations place it ${away}, which is too far out for ` +\n `its ${plainSeconds(file.header.recordDuration)}s records to be told apart: at that magnitude ` +\n `adding a sample interval leaves the number unchanged.`,\n hint:\n 'Sample times are written from zero instead, so every row is present and the column ' +\n 'increases. Add the onsets in annotations.csv to recover absolute times if you need them.',\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"timing.js","sourceRoot":"","sources":["../../src/convert/timing.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAUnD;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,qBAAqB,CACnC,WAAkC,EAClC,OAAgB;IAEhB,IAAI,OAAO;QAAE,OAAO,CAAC,GAAG,WAAW,CAAC,CAAC;IACrC,OAAO,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAC3B,CAAC,CAAC,IAAI,KAAK,eAAe,IAAI,CAAC,CAAC,IAAI,EAAE,QAAQ,CAAC,mBAAmB,CAAC;QACjE,CAAC,CAAC;YACE,GAAG,CAAC;YACJ,IAAI,EACF,kFAAkF;gBAClF,2CAA2C;SAC9C;QACH,CAAC,CAAC,CAAC,CACN,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAChC,IAAa,EACb,cAAoC;IAEpC,MAAM,WAAW,GAAiB,EAAE,CAAC;IAErC,IAAI,cAAc,CAAC,SAAS,GAAG,CAAC,EAAE,CAAC;QACjC,WAAW,CAAC,IAAI,CAAC;YACf,IAAI,EAAE,0BAA0B;YAChC,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E;IACF,MAAM,IAAI,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC;QAClC,CAAC,CAAC,GAAG,YAAY,CAAC,MAAM,CAAC,2BAA2B;QACpD,CAAC,CAAC,wDAAwD,CAAC;IAC7D,OAAO;QACL,IAAI,EAAE,eAAe;QACrB,QAAQ,EAAE,SAAS;QACnB,OAAO,EACL,qDAAqD,IAAI,6BAA6B;YACtF,OAAO,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,gDAAgD;YAC/F,uDAAuD;QACzD,IAAI,EACF,qFAAqF;YACrF,0FAA0F;KAC7F,CAAC;AACJ,CAAC","sourcesContent":["import type { Diagnostic } from '../edf/errors.js';\nimport type { EdfFile } from '../edf/reader.js';\nimport { counted, grouped, listed } from '../format/list.js';\nimport { plainSeconds } from '../format/number.js';\n\nexport interface AnnotationTimingData {\n recordStarts: (number | null)[];\n malformed: number;\n /** Unreadable TALs in first position, which carry timing rather than an event. */\n malformedTimekeeping?: number;\n malformedTimekeepingWithText?: number;\n}\n\n/**\n * The EDF+D warning's promise, withdrawn when the file cannot keep it.\n *\n * The header parser raises DISCONTINUOUS with the hint \"Each row carries its true recording\n * time, so gaps stay visible instead of being closed\" — which is what an EDF+D conversion\n * does, when the record times can be read. When they cannot, the very next warning in the\n * same run says the opposite: \"Times are written as if the records were contiguous. Any gaps\n * are lost.\" Two warnings, printed together, and the second denies the first.\n *\n * The parser cannot know: whether the starts can be derived is settled here, after the\n * annotation channel has been read. So the hint is amended where the answer is, the same way\n * `withoutFileRateWarning` drops a header diagnostic the plan has superseded.\n */\nexport function withTimingPromiseKept(\n diagnostics: readonly Diagnostic[],\n derived: boolean,\n): Diagnostic[] {\n if (derived) return [...diagnostics];\n return diagnostics.map((d) =>\n d.code === 'DISCONTINUOUS' && d.hint?.includes('gaps stay visible')\n ? {\n ...d,\n hint:\n 'Where its records sit in time is not recorded in this file, so they are written ' +\n 'as if contiguous — see the warning below.',\n }\n : d,\n );\n}\n\n/**\n * Resolve the true start time of every data record.\n *\n * Continuous recordings need no table because their record positions are\n * arithmetic. EDF+D recordings carry their positions in the annotation channel;\n * missing or malformed timekeeping entries are reported before falling back.\n */\nexport function deriveRecordStarts(\n file: EdfFile,\n annotationData: AnnotationTimingData,\n): { starts: Float64Array | null; diagnostics: Diagnostic[] } {\n const diagnostics: Diagnostic[] = [];\n\n if (annotationData.malformed > 0) {\n diagnostics.push({\n code: 'ANNOTATION_DECODE_FAILED',\n severity: 'warning',\n // Through `counted`, with the irregular plural spelled out — which is the case its\n // own comment names and which nothing was using it for.\n message:\n `${counted(annotationData.malformed, 'annotation entry', 'annotation entries')} ` +\n `${annotationData.malformed === 1 ? 'was' : 'were'} unreadable and could not be exported.`,\n /*\n \"The rest were exported normally\" was said whether or not there was a rest.\n\n A writer that cannot state an onset tends not to manage it anywhere, so a file whose\n every event entry is unreadable is the ordinary way here — and it was answered with\n the count of what was lost and a sentence saying the remainder came through, over an\n annotations.csv holding its header and no rows:\n\n warning: 2 annotation entries were unreadable and could not be exported.\n The rest were exported normally. ...\n\n Wrote scoring_csv\n annotations.csv 0 rows\n\n Four lines apart, the summary settling it. Same shape as the \"No event was lost\"\n sentence forty lines down, which was corrected for the same reason: a hint true of\n most files is not true of the one it is printed over.\n\n Said without counting, rather than by counting. What makes the old sentence wrong is\n that it asserts a remainder exists; what it was for is the assurance that nothing\n readable was dropped, and that holds however many were readable. Counting instead\n would have split `--info` from a conversion — the scan behind `--info` stops at the\n first record that states a time and never counts the events, which is the bound that\n keeps it a header read.\n */\n hint:\n 'Every entry that could be read was exported. The file may have been written by a ' +\n 'non-conforming tool.',\n });\n }\n\n\n /*\n A timekeeping TAL is not an event, and saying it \"could not be exported\" describes the\n wrong loss twice over.\n\n These were counted among the annotations, so a file with one unreadable timekeeping TAL\n and three good events announced \"1 annotation entry was unreadable and could not be\n exported\" — while exporting all three. Nothing was missing from annotations.csv; what\n went missing was a record's position in time, which the message never mentioned.\n */\n const lostTimekeeping = annotationData.malformedTimekeeping ?? 0;\n const withText = annotationData.malformedTimekeepingWithText ?? 0;\n // The EDF+D branch below raises its own, which names the records and is more specific.\n // Saying both would report one problem twice.\n if (lostTimekeeping > 0 && file.header.continuity !== 'EDF+D') {\n const one = lostTimekeeping === 1;\n diagnostics.push({\n code: 'ANNOTATION_DECODE_FAILED',\n severity: 'warning',\n // Through `counted`, like the four other counts of \"data record\" in this file. This one\n // spelled the noun and the verb by hand — `record${one ? '' : 's'} carr${one ? 'ies' :\n // 'y'}` — while its nearest neighbour, sixty lines down and about the same records,\n // writes `${counted(n, 'data record')} ${one ? 'carries' : 'carry'}`. Same phrase, same\n // file, two spellings, and only one of them can be checked against the helper.\n message:\n `${counted(lostTimekeeping, 'data record')} ${one ? 'carries' : 'carry'} a timekeeping ` +\n `annotation that could not be read, so ${one ? 'it does' : 'they do'} not say where in ` +\n `time ${one ? 'it sits' : 'they sit'}.`,\n hint:\n /*\n \"No event was lost\" was said whatever the entry held.\n\n A first-position TAL states the record's start time and may carry events after it,\n which the specification allows and writers do. When one of those cannot be parsed\n the events go with it: a six-event file came out with two, and the only warning\n about it said in so many words that nothing had gone. Those entries are counted\n among the unreadable ones now, which is the warning printed above this one; this\n sentence keeps to what is true of the entries it is actually about.\n */\n /*\n Grouped, like the count of the same records one line above it.\n\n The message says `counted(lostTimekeeping, 'data record')`; the hint under it counts\n a subset of those records and spelled the number by hand. When the subset is all of\n them — which is the ordinary case, since a writer that cannot state an onset tends\n not to manage it anywhere — the two print the same number two lines apart, one\n grouped and one not:\n\n warning: 1,010 data records carry a timekeeping annotation that could not be\n read, so they do not say where in time they sit.\n 1010 of them also carried event text, which went with them and is\n counted above.\n */\n (withText > 0\n ? `${withText === 1 ? 'One of them' : `${grouped(withText)} of them`} also carried event text, ` +\n `which went with ${withText === 1 ? 'it' : 'them'} and is counted above. A ` +\n `timekeeping annotation itself states a record's start time and is never exported. `\n : 'No event was lost — a timekeeping annotation states a record\\'s start time and ' +\n 'is never exported. ') + 'Times are derived from the records that could be read.',\n });\n }\n\n /*\n A continuous recording's records are contiguous, but the first one need not sit at zero.\n\n EDF+ puts the header's start time and every annotation onset on one origin, and says the\n first data record's timekeeping TAL \"always starts with +0.X\", stating the fraction of a\n second by which that record follows it. Ignoring that fraction timed the samples from 0\n while the events kept their true onsets, so the two ended up on origins half a second\n apart — an event at +0.75 in a 4 Hz recording whose first TAL reads +0.5 landed on sample\n 3 instead of sample 1. The same file marked EDF+D, byte-identical but for the reserved\n field, placed it correctly, which is what gives the omission away.\n\n Records stay contiguous, which is what continuous means: only the origin moves. A first\n TAL of +0 needs no table at all, and that is nearly every file.\n */\n if (file.header.continuity !== 'EDF+D') {\n if (file.header.continuity !== 'EDF+C') {\n /*\n An annotation channel the reserved field never claimed.\n\n Without an `EDF+C` or `EDF+D` marker this is a plain EDF file, so the origin is not\n applied and the samples are timed from zero. The annotation channel is found by label\n rather than by the marker, though, so its events are still read and exported — with\n the onsets the file gives them.\n\n On a file whose timekeeping says the records start at 1000s, that put signals.csv at\n 0.000 and the event at 1000.5 in annotations.csv: two files from one conversion, a\n thousand seconds apart, and nothing said so. output-files promises the opposite —\n \"`onset_s` is on the same clock as `time_s` in the signal files\".\n\n Reported rather than repaired. Which clock is right is not knowable from here: the\n marker says plain EDF and the annotation channel says otherwise, and picking one would\n move either the samples or the events by the origin on a guess.\n */\n const stated = annotationData.recordStarts.find((start) => start !== null) ?? null;\n const base = file.header.isBdf ? 'BDF' : 'EDF';\n const plus = `${base}+`;\n if (stated !== null && Math.abs(stated) > 0) {\n diagnostics.push({\n code: 'MISSING_EDF_PLUS_MARKER',\n severity: 'warning',\n // The markers as this file spells them, which is what the contradiction warning\n // sixty lines down already does and what NO_SIGNAL_CHANNELS was fixed for. A BDF\n // recording was told to \"Mark the file EDF+C\" — not a value BDF+ defines — and\n // that it \"is read as plain EDF\", which it is not.\n message:\n `This file has an annotation channel stating that its records begin at ` +\n `${plainSeconds(stated)}s, but its reserved field carries no ${plus}C or ${plus}D ` +\n `marker — so it is read as plain ${base}, time_s counts from zero, and the two ` +\n `disagree by ${plainSeconds(stated)}s.`,\n hint:\n `annotations.csv keeps the onsets the file gives, so its events and signals.csv ` +\n `are on different clocks. Mark the file ${plus}C, or subtract the offset from ` +\n `the onsets, before joining them.`,\n });\n }\n return { starts: null, diagnostics };\n }\n\n /*\n The origin comes from whichever record first states one, not from record 0 alone.\n\n Reading only `recordStarts[0]` meant a single unreadable timekeeping TAL threw the\n origin away and timed the whole file from zero — while records 1 and 2, saying plainly\n that they start at 1.5s and 2.5s, went unread. A recording whose records sit at 0.5s,\n 1.5s and 2.5s came out with every sample 0.5s earlier than the file states, against\n annotation onsets that kept their true values. That is precisely the mismatch 0.4.9\n fixed, arriving through the one hole left in it, and the byte-identical EDF+D twin\n timed it correctly, which is what gives it away.\n\n Continuity is what makes this recoverable: record i sits at `origin + i * duration`,\n so any readable record determines the origin for all of them.\n */\n const origin = originOf(annotationData.recordStarts, file.header.recordDuration);\n if (origin === null) return { starts: null, diagnostics };\n\n const contiguous = new Float64Array(file.recordCount);\n for (let i = 0; i < file.recordCount; i++) {\n contiguous[i] = origin + i * file.header.recordDuration;\n }\n\n /*\n A file marked continuous whose own records disagree about it.\n\n Nothing looked at records past the first, so an EDF+C file whose records are in fact\n spread out was timed as though they were contiguous and said nothing. The records are\n being read here anyway, so the contradiction costs nothing to notice — and it is the\n file, not the reader, that has to be wrong for this to fire.\n\n Compared against what the file can express, not for equality. 0.4.41 asked whether the\n two doubles were the same, which they are not: a recording of 0.1s records sitting at\n 0.1, 0.2, 0.3 ... is contiguous by construction, and 0.1 + 2 * 0.1 is\n 0.30000000000000004. Two of its eight records were reported as contradicting\n continuity, on an ordinary file — and under --strict that was a failed run. The\n smallest interval the recording distinguishes is one sample of its fastest channel;\n anything below half of that is arithmetic, not a gap. `canCarry` has already refused\n origins where the double spacing swamps that interval, so the representation error is\n under the tolerance by construction rather than by hope.\n */\n const tolerance = finestInterval(file) / 2;\n const contradicting = annotationData.recordStarts.filter(\n (declared, i) =>\n typeof declared === 'number' && Math.abs(declared - (contiguous[i] as number)) > tolerance,\n ).length;\n if (contradicting > 0) {\n const continuous = file.header.isBdf ? 'BDF+C' : 'EDF+C';\n const discontinuous = file.header.isBdf ? 'BDF+D' : 'EDF+D';\n diagnostics.push({\n code: 'DISCONTINUOUS',\n severity: 'warning',\n /*\n The markers as the file spells them.\n\n `continuity` normalises `BDF+C` to the internal `EDF+C` tag, and that tag reached\n the message: a BDF+ recording was told it is \"marked continuous (EDF+C)\" — a string\n it does not contain — and advised that it \"should have been marked EDF+D\", which is\n not a value BDF+ defines. A reader grepping the header for either finds nothing.\n\n The sibling discontinuous warning has done this since 0.3.x: `${'$'}{isBdf ? 'BDF+D' :\n 'EDF+D'}`. Same code, same header field, and the continuous branch never got it.\n */\n /*\n Both counts grouped, which is the whole point of the sentence: it puts one against\n the other. 0.8.5 gave `counted` the grouping and went through the bare numbers\n standing beside it — including this exact phrase in the ANNOTATION_DECODE_FAILED\n warning eighty lines down, `${grouped(missing.length)} of ${counted(...)}` — and\n missed this one, so a three-thousand-record file read \"2999 of its 3,000 data\n records\", three words apart.\n */\n message:\n `This file is marked continuous (${continuous}), but ${grouped(contradicting)} of its ` +\n `${counted(file.recordCount, 'data record')} ` +\n `${contradicting === 1 ? 'says it starts' : 'say they start'} somewhere other than ` +\n `where continuity puts ${contradicting === 1 ? 'it' : 'them'}.`,\n hint:\n `Times are written as if the records were contiguous, which is what ${continuous} ` +\n `means. If the recording really has gaps, the file should have been marked ` +\n `${discontinuous}.`,\n });\n }\n const first = origin;\n const last = contiguous[file.recordCount - 1] ?? first;\n if (!canCarry(last, file)) {\n diagnostics.push(unusableOrigin(first, file));\n return { starts: null, diagnostics };\n }\n /*\n An origin of zero is the same as no origin, for timing. It is not the same for the\n check above.\n\n This returned early on `origin === 0`, which is right about the times — contiguous\n starts from zero are what timing from zero already produces — and skipped the\n contradiction check on the way past. So an EDF+C file whose records say 0, 5 and 10 on\n one-second records went unreported, while the same file shifted one second, saying 1, 6\n and 11, was reported. The contradiction is in records 1 and 2 either way; where record 0\n happens to sit decides nothing about it.\n */\n if (origin === 0) return { starts: null, diagnostics };\n return { starts: contiguous, diagnostics };\n }\n\n if (file.annotationSignals.length === 0) {\n diagnostics.push({\n code: 'DISCONTINUOUS',\n severity: 'warning',\n message:\n 'This file is marked discontinuous but has no annotation channel, so where its ' +\n 'records sit in time is not recorded anywhere.',\n hint: 'Times are written as if the records were contiguous. Any gaps are lost.',\n });\n return { starts: null, diagnostics };\n }\n\n /*\n A record with no readable time is placed from the origin the other records establish,\n not from zero.\n\n `i * recordDuration` assumed the recording began at zero, which is the one thing the\n other records are in a position to contradict: a file starting at 0.5s put its\n unreadable record at 0.000 while its neighbours sat at 1.5s and 2.5s. The guess is still\n a guess — a discontinuous file may have a gap exactly there — and it is still reported\n below, but starting it from where the recording actually begins is strictly closer, and\n it makes an EDF+D file agree with its byte-identical EDF+C twin about record 0.\n */\n const base = originOf(annotationData.recordStarts, file.header.recordDuration) ?? 0;\n const starts = new Float64Array(file.recordCount);\n const missing: number[] = [];\n for (let i = 0; i < file.recordCount; i++) {\n const declared = annotationData.recordStarts[i];\n if (declared === null || declared === undefined) {\n missing.push(i);\n starts[i] = base + i * file.header.recordDuration;\n } else {\n starts[i] = declared;\n }\n }\n\n if (missing.length > 0) {\n /*\n Cut by the function that cuts every other list in a sentence here.\n\n This one rolled its own: five items and a bare `…`, where `listed` shows eight and counts\n what it left — \"and 32 more\" on the rate warning, \"and 112 more\" on the leftover files.\n The count is the honest half, and 0.7.58 taught the shared one not to hide a single item\n behind a phrase longer than the item. None of that reached this message, because it was\n never asking. Two implementations of one job, differing in the limit and in what they say\n about the tail.\n */\n const shown = listed(missing.map(String));\n // \"1 of 3 data records carry ... their true position\" — the subject is the one, not the three.\n const one = missing.length === 1;\n diagnostics.push({\n code: 'ANNOTATION_DECODE_FAILED',\n severity: 'warning',\n message:\n `${grouped(missing.length)} of ${counted(file.recordCount, 'data record')} ${one ? 'carries' : 'carry'} no ` +\n `readable timekeeping annotation (record${one ? '' : 's'} ${shown}), so ` +\n `${one ? 'its' : 'their'} true position in time is unknown.`,\n hint: one\n ? 'That record is timed as if it were contiguous; treat its timestamp as unreliable.'\n : 'Those records are timed as if they were contiguous; treat their timestamps as unreliable.',\n });\n }\n\n /*\n Furthest from zero, in either direction.\n\n This took the signed maximum and seeded it with 0, so a recording whose records all sit\n at negative onsets never got past the seed: `furthest` stayed 0, which any interval can\n carry. Then the samples collapsed anyway, because the arithmetic that defeats a large\n positive origin defeats a large negative one identically — at -1e16 seconds, adding a\n 1-second sample interval leaves the double unchanged.\n\n A four-record recording of eight samples wrote two rows, exit 0, no warning. Its\n byte-for-byte positive mirror wrote all eight and explained why it had to time them from\n zero. Same file, same failure, opposite sign, opposite outcome — and the silent one is\n the one that loses data, which is exactly what unusableOrigin exists to prevent.\n */\n let furthest = 0;\n for (const start of starts) if (Math.abs(start) > Math.abs(furthest)) furthest = start;\n if (!canCarry(furthest, file)) {\n diagnostics.push(unusableOrigin(furthest, file));\n return { starts: null, diagnostics };\n }\n\n /*\n Two ways a record can put the time column out of order, and only one was being looked for.\n\n A record starting before the one before it is the obvious case. The other is a record\n starting before the one before it *ends*: starts of 0, 0.5 and 1.0 on one-second records\n are strictly increasing, so nothing fired, and the rows still came out 0.25, 0.5, 0.75,\n 0.5 — because record 0's samples run to 0.75 while record 1 begins at 0.5. Overlapping\n acquisition is what a device does when it re-sends a buffer, and the reader has no more\n to say about it than about the reversed case: every sample is written, in file order,\n with the time the file gives it.\n\n Contiguity is not overlap. A continuous recording has `starts[i] === starts[i-1] +\n duration` exactly, so the comparison is made strict by a fraction of the finest interval\n the recording can express — the same measure the origin check uses.\n */\n const slack = finestInterval(file) / 2;\n let outOfOrder = 0;\n let overlapping = 0;\n for (let i = 1; i < starts.length; i++) {\n const previous = starts[i - 1] as number;\n const current = starts[i] as number;\n if (current < previous) outOfOrder++;\n else if (current + slack < previous + file.header.recordDuration) overlapping++;\n }\n if (outOfOrder > 0) {\n diagnostics.push({\n code: 'DISCONTINUOUS',\n severity: 'warning',\n message:\n `${counted(outOfOrder, 'data record')} ` +\n `${outOfOrder === 1 ? 'starts' : 'start'} earlier than the record before ` +\n `${outOfOrder === 1 ? 'it' : 'them'}.`,\n hint: 'Rows are written in file order, so the time column will not increase monotonically.',\n });\n }\n if (overlapping > 0) {\n diagnostics.push({\n code: 'DISCONTINUOUS',\n severity: 'warning',\n message:\n `${counted(overlapping, 'data record')} ` +\n `${overlapping === 1 ? 'starts' : 'start'} before the record before ` +\n `${overlapping === 1 ? 'it' : 'them'} ends, so ${overlapping === 1 ? 'its' : 'their'} ` +\n `samples overlap in time.`,\n /*\n An overlap does not always put the column out of order, and this said it did.\n\n The two counts above share a sentence and only one of them earns it. A record starting\n *earlier* than the one before it steps the column back by construction. A record\n starting before the one before it *ends* need not: what decides is whether it begins\n after the previous record's last sample, and the last sample is one interval short of\n the record's end. Three-tenths of a second of overlap on a one-second record sampled\n twice a second writes\n\n time_s,A\n 0.000\n 0.500\n 0.700\n 1.200\n\n which increases at every step, under a warning saying it would not. Both records do\n describe 0.700 to 1.000, which is the thing that is true either way and is what the\n sentence says now.\n */\n hint:\n 'Rows are written in file order, and two records describe the same stretch of time. ' +\n 'Where they overlap by more than one sample interval the time column steps backwards.',\n });\n }\n\n return { starts, diagnostics };\n}\n\n/**\n * The recording's origin, from the first record that states where it is.\n *\n * Records of a continuous recording sit end to end, so record `i` beginning at `t` puts the\n * origin at `t - i * duration`. Any one readable timekeeping TAL is therefore enough, which\n * is what stops one unreadable entry from costing the whole file its position in time.\n */\nfunction originOf(recordStarts: readonly (number | null)[], recordDuration: number): number | null {\n for (const [index, declared] of recordStarts.entries()) {\n if (typeof declared !== 'number') continue;\n const origin = declared - index * recordDuration;\n return Number.isFinite(origin) ? origin : null;\n }\n return null;\n}\n\n/**\n * Whether times this far out can still tell one sample from the next.\n *\n * A double spaces its values further apart the larger they get: at 1e16 the gap is 2\n * seconds, so `t + 1` is `t`. Past that point a recording's declared origin stops being a\n * position and becomes a wall — the arithmetic that places records and samples returns the\n * origin itself, whatever is added to it.\n *\n * The finest thing that has to survive is the gap between two consecutive samples of the\n * fastest channel, since that is what the time column is made of. If that survives, so does\n * a whole record.\n */\nfunction canCarry(origin: number, file: EdfFile): boolean {\n if (!Number.isFinite(origin)) return false;\n // Asked of the origin furthest from zero, whichever side it is on: the spacing of doubles\n // grows with magnitude, not with value, so -1e16 and +1e16 fail this identically.\n return origin + finestInterval(file) > origin;\n}\n\n/**\n * The shortest span this recording can tell apart: one sample of its fastest channel.\n *\n * The time column is made of these, so nothing below one is a distinction the file is in a\n * position to make — which is what makes it the right size for both the \"can this origin\n * still separate two samples\" question and the \"is this record really somewhere else\"\n * question.\n */\nfunction finestInterval(file: EdfFile): number {\n let interval = file.header.recordDuration;\n for (const signal of file.header.signals) {\n if (signal.isAnnotations || !(signal.samplesPerRecord > 0)) continue;\n const step = file.header.recordDuration / signal.samplesPerRecord;\n if (step > 0 && step < interval) interval = step;\n }\n return interval;\n}\n\n/**\n * An origin the file's own arithmetic cannot express, reported rather than acted on.\n *\n * Two things went wrong when this was taken at face value, both of them quiet. A file whose\n * records all collapsed onto one instant made the recording zero seconds long, and the\n * window resolver — which had no reason to suspect the recording rather than the request —\n * blamed a flag nobody had passed:\n *\n * error: --start 100000000000000000s is at or past the end of this\n * 100000000000000000s recording.\n *\n * Slightly below that, the collapse is partial: `records[i].start + recordDuration` equals\n * the start again, so the test for \"does this record overlap the window\" fails for every\n * record whose neighbour rounded onto it. A twelve-row recording wrote four rows, exit 0,\n * no warning — the eight that vanished looked exactly like a file that never had them.\n *\n * Timing from zero is what the file did before 0.4.9 taught it to honour the first\n * timekeeping TAL, and at this magnitude it is the only column that can hold distinct\n * values. The origin is lost, so this says so.\n */\nfunction unusableOrigin(origin: number, file: EdfFile): Diagnostic {\n /*\n `Infinity` is a token, not a distance.\n\n `plain` expands exponent notation and hands anything else back, so a non-finite origin\n arrived on screen as \"place it Infinitys from its own start date\" — the exact form\n `formatDuration` exists to keep off the screen, its comment naming \"NaNs\" and \"Infinitys\"\n as what the fallback used to print, and the word the rest of this tool uses for the same\n quantity is \"unknown\". The origin overflows for the reason the recording's length does:\n a record duration near the top of a double, multiplied out over three records, leaves it.\n */\n const away = Number.isFinite(origin)\n ? `${plainSeconds(origin)}s from its own start date`\n : 'further from its own start date than a number can hold';\n return {\n code: 'DISCONTINUOUS',\n severity: 'warning',\n message:\n `This recording's timekeeping annotations place it ${away}, which is too far out for ` +\n `its ${plainSeconds(file.header.recordDuration)}s records to be told apart: at that magnitude ` +\n `adding a sample interval leaves the number unchanged.`,\n hint:\n 'Sample times are written from zero instead, so every row is present and the column ' +\n 'increases. Add the onsets in annotations.csv to recover absolute times if you need them.',\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "edf2csv",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.16",
|
|
4
4
|
"description": "Convert EDF, EDF+ and BDF biosignal recordings (European Data Format) to CSV from the command line. Local, streaming, and never resamples or alters units.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"edf",
|