Skip to content

Commit cf366cb

Browse files
authored
Merge pull request #917 from VisLab/duplicate_columns
Duplicate columns closes #896
2 parents 522b9a7 + 52f8891 commit cf366cb

10 files changed

Lines changed: 279 additions & 43 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,15 @@ testSpecs`.
9797
`Delay` or `Duration` in `s`, `second`, `seconds` or no unit converts as is;
9898
`ms` or `minute` is still TEMPORAL_TAG_ERROR.
9999
The dead `ReservedChecker.checkNonTopGroups` is removed (hed-tests e2753fb).
100+
- A column name repeated in the header of a TSV file is TABULAR_INVALID, one
101+
error per repeated name, and the file is not validated further
102+
(specification 3.2.10; #896; hed-tests
103+
`tabular-invalid-duplicate-column-name`). `parseTSV` and `convertParsedTSVData` merged
104+
the repeated columns into one array, misaligning every row, and the merged
105+
annotations surfaced as a misleading TAG_EXPRESSION_REPEATED or not at all;
106+
they now keep only the first column of a repeated name. The new
107+
`findDuplicateHeaders` export returns the repeated names, and `BidsTsvFile`
108+
has a `duplicateColumns` property.
100109

101110
### Dependencies
102111

‎index.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ export {
1616

1717
export { IssueError, Issue } from './src/issues/issues'
1818

19-
export { parseTSV } from './src/bids/tsvParser'
19+
export { findDuplicateHeaders, parseTSV } from './src/bids/tsvParser'
2020

2121
// Export parser functions for HED string validation
2222

‎spec_tests/hedTests.spec.js‎

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -218,11 +218,8 @@ describe('HED validation using the hed-tests JSON suite', () => {
218218
const header = `\n[${error_code} ${name}](${statusOf(expected)})\tSTRING: "${str}"`
219219
const hTsv = `onset\tHED\n5.4\t${str}\n`
220220
const issues = runValidation(() => {
221-
const parsedTsv = parseTSV(hTsv)
222-
assert.instanceOf(parsedTsv, Map, `${str} cannot be parsed`)
223-
return new BidsTsvFile('string', { path: 'string test tsv' }, parsedTsv, {}, newDefManager()).validate(
224-
hedSchemas,
225-
)
221+
assert.instanceOf(parseTSV(hTsv), Map, `${str} cannot be parsed`)
222+
return new BidsTsvFile('string', { path: 'string test tsv' }, hTsv, {}, newDefManager()).validate(hedSchemas)
226223
})
227224
assertErrors(expected, issues, header)
228225
}
@@ -238,22 +235,21 @@ describe('HED validation using the hed-tests JSON suite', () => {
238235
const eventsValidator = function (events, expected) {
239236
const header = `\n[${error_code} ${name}](${statusOf(expected)})\tEvents:\n"${events}"`
240237
const issues = runValidation(() => {
241-
const parsedTsv = parseTSV(events)
242-
assert.instanceOf(parsedTsv, Map, `${events} cannot be parsed`)
243-
return new BidsTsvFile('events', { path: 'events test' }, parsedTsv, {}, newDefManager()).validate(hedSchemas)
238+
assert.instanceOf(parseTSV(events), Map, `${events} cannot be parsed`)
239+
// The TSV text, not a parsed Map: a Map cannot hold a repeated column name (TABULAR_INVALID).
240+
return new BidsTsvFile('events', { path: 'events test' }, events, {}, newDefManager()).validate(hedSchemas)
244241
})
245242
assertErrors(expected, issues, header)
246243
}
247244

248245
const comboValidator = function (side, events, expected) {
249246
const header = `\n[${error_code} ${name}](${statusOf(expected)})\tCOMBO\t"${side}"\n"${events}"`
250247
const issues = runValidation(() => {
251-
const parsedTsv = parseTSV(events)
252-
assert.instanceOf(parsedTsv, Map, `${events} cannot be parsed`)
248+
assert.instanceOf(parseTSV(events), Map, `${events} cannot be parsed`)
253249
return new BidsTsvFile(
254250
'events',
255251
{ path: 'combo test tsv' },
256-
parsedTsv,
252+
events,
257253
JSON.parse(side),
258254
newDefManager(),
259255
).validate(hedSchemas)

‎src/bids/tsvParser.js‎

Lines changed: 108 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -9,53 +9,133 @@ const normalizeEOL = (str) => str.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
99
const isContentfulRow = (row) => row && !/^\s*$/.test(row)
1010

1111
/**
12-
* Parse a TSV file
12+
* Split TSV contents into trimmed cells, one array per contentful row; the first row is the header.
1313
*
1414
* @param {string} contents The contents of a TSV file.
15-
* @returns {Map<string, string[]>} The parsed contents of the TSV file.
15+
* @returns {string[][]} The rows of the file.
1616
*/
17-
export function parseTSV(contents) {
18-
const columns = new Map()
19-
const rows = stripBOM(normalizeEOL(contents))
17+
const splitRows = (contents) =>
18+
stripBOM(normalizeEOL(contents))
2019
.split('\n')
2120
.filter(isContentfulRow)
2221
.map((str) => str.split('\t').map((cell) => cell.trim()))
23-
const headers = rows.length ? rows[0] : []
2422

25-
headers.forEach((x) => {
26-
columns.set(x, [])
23+
/**
24+
* Build the column map of a table, keeping only the first column of a repeated header name.
25+
*
26+
* A repeated name is an error (specification 3.2.10, TABULAR_INVALID) that {@link findDuplicateHeaders} detects;
27+
* keeping one column per name keeps every column aligned with the rows instead of interleaving two columns.
28+
*
29+
* @param {string[]} headers The column names.
30+
* @param {string[][]} rows The rows; rows[0] is skipped as the header row.
31+
* @returns {Map<string, string[]>} The cells of each column.
32+
*/
33+
function buildColumns(headers, rows) {
34+
const firstIndex = new Map()
35+
headers.forEach((header, index) => {
36+
if (!firstIndex.has(header)) {
37+
firstIndex.set(header, index)
38+
}
2739
})
28-
for (let i = 1; i < rows.length; i++) {
29-
for (let j = 0; j < headers.length; j++) {
30-
columns.get(headers[j])?.push(rows[i][j])
40+
const columns = new Map()
41+
for (const [header, index] of firstIndex) {
42+
columns.set(
43+
header,
44+
rows.slice(1).map((row) => row[index]),
45+
)
46+
}
47+
return columns
48+
}
49+
50+
/**
51+
* Return the names that appear more than once in a list of column names.
52+
*
53+
* @param {string[]} headers The column names.
54+
* @returns {string[]} Each repeated name once, in order of its second appearance.
55+
*/
56+
function repeatedNames(headers) {
57+
const seen = new Set()
58+
const repeated = new Set()
59+
for (const header of headers) {
60+
if (seen.has(header)) {
61+
repeated.add(header)
3162
}
63+
seen.add(header)
3264
}
33-
for (const [key, value] of columns) {
34-
columns.set(key, value)
65+
return [...repeated]
66+
}
67+
68+
/**
69+
* Parse a TSV file
70+
*
71+
* A column name repeated in the header keeps only its first column (see {@link findDuplicateHeaders}).
72+
*
73+
* @param {string} contents The contents of a TSV file.
74+
* @returns {Map<string, string[]>} The parsed contents of the TSV file.
75+
*/
76+
export function parseTSV(contents) {
77+
const rows = splitRows(contents)
78+
return buildColumns(rows.length ? rows[0] : [], rows)
79+
}
80+
81+
/**
82+
* Find the column names that appear more than once in the header of TSV contents.
83+
*
84+
* @param {string} contents The contents of a TSV file.
85+
* @returns {string[]} Each repeated name once; empty when every name is unique.
86+
*/
87+
export function findDuplicateHeaders(contents) {
88+
return repeatedNames(headerCells(contents))
89+
}
90+
91+
/**
92+
* Return the trimmed cells of the first contentful line of TSV contents, without splitting the other lines.
93+
*
94+
* Line breaks are \r\n, \r or \n, as in {@link splitRows}, so the result equals the header row that
95+
* {@link parseTSV} uses.
96+
*
97+
* @param {string} contents The contents of a TSV file.
98+
* @returns {string[]} The header cells; empty when the contents have no contentful line.
99+
*/
100+
function headerCells(contents) {
101+
const text = stripBOM(contents)
102+
const lineBreak = /\r\n|\r|\n/g
103+
let start = 0
104+
while (start <= text.length) {
105+
lineBreak.lastIndex = start
106+
const match = lineBreak.exec(text)
107+
const line = text.slice(start, match ? match.index : text.length)
108+
if (isContentfulRow(line)) {
109+
return line.split('\t').map((cell) => cell.trim())
110+
}
111+
if (!match) {
112+
break
113+
}
114+
start = lineBreak.lastIndex
35115
}
36-
return columns
116+
return []
37117
}
118+
119+
/**
120+
* Find the column names that appear more than once in parsed TSV data in the old BIDS format.
121+
*
122+
* @param {{headers: string[], rows: string[][]}} oldParsedTsv Parsed TSV data using the old format
123+
* @returns {string[]} Each repeated name once; empty when every name is unique.
124+
*/
125+
export function findDuplicateParsedHeaders(oldParsedTsv) {
126+
return repeatedNames(oldParsedTsv.headers)
127+
}
128+
38129
/**
39130
* Convert parsed TSV file data from the old BIDS format to the new BIDS format.
40131
*
132+
* A column name repeated in the headers keeps only its first column (see {@link findDuplicateParsedHeaders}).
133+
*
41134
* @param {{headers: string[], rows: string[][]}} oldParsedTsv Parsed TSV data using the old format
42135
* @returns {Map<string, string[]>} The parsed contents of the TSV file, using the new format.
43136
*/
44137
export function convertParsedTSVData(oldParsedTsv) {
45-
const columns = new Map()
46-
47-
oldParsedTsv.headers.forEach((x) => {
48-
columns.set(x, [])
49-
})
50-
for (let i = 1; i < oldParsedTsv.rows.length; i++) {
51-
for (let j = 0; j < oldParsedTsv.headers.length; j++) {
52-
columns.get(oldParsedTsv.headers[j])?.push(oldParsedTsv.rows[i][j])
53-
}
54-
}
55-
for (const [key, value] of columns) {
56-
columns.set(key, value)
57-
}
58-
return columns
138+
return buildColumns(oldParsedTsv.headers, oldParsedTsv.rows)
59139
}
60140

61141
export default parseTSV

‎src/bids/types/tsv.js‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import isPlainObject from 'lodash/isPlainObject'
77

88
import { BidsFile } from './file'
9-
import { convertParsedTSVData, parseTSV } from '../tsvParser'
9+
import { convertParsedTSVData, findDuplicateHeaders, findDuplicateParsedHeaders, parseTSV } from '../tsvParser'
1010
import { BidsSidecar } from './json'
1111
import BidsHedTsvValidator from '../validator/tsvValidator'
1212
import { IssueError } from '../../issues/issues'
@@ -21,6 +21,12 @@ export class BidsTsvFile extends BidsFile {
2121
*/
2222
parsedTsv
2323

24+
/**
25+
* The column names that appear more than once in the header (TABULAR_INVALID); empty for Map data.
26+
* @type {string[]}
27+
*/
28+
duplicateColumns
29+
2430
/**
2531
* HED strings in the "HED" column of the TSV data.
2632
* @type {string[]}
@@ -38,10 +44,13 @@ export class BidsTsvFile extends BidsFile {
3844

3945
if (typeof tsvData === 'string') {
4046
this.parsedTsv = parseTSV(tsvData)
47+
this.duplicateColumns = findDuplicateHeaders(tsvData)
4148
} else if (tsvData instanceof Map) {
4249
this.parsedTsv = new Map(tsvData)
50+
this.duplicateColumns = []
4351
} else if (isPlainObject(tsvData)) {
4452
this.parsedTsv = convertParsedTSVData(tsvData)
53+
this.duplicateColumns = findDuplicateParsedHeaders(tsvData)
4554
} else {
4655
const msg = 'The tsvData was not a string, Map or plain object, so a BidsTsvFile could not be created.'
4756
IssueError.generateAndThrow('internalError', { message: msg, filePath: file.path })

‎src/bids/validator/tsvValidator.js‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,14 @@ export class BidsHedTsvValidator extends BidsValidator {
4343
* Validate a BIDS TSV file. This method returns the complete issue list for convenience.
4444
*/
4545
validate() {
46+
// A repeated column name makes the rows unassemblable: report it and stop (specification 3.2.10).
47+
if (this.tsvFile.duplicateColumns.length > 0) {
48+
for (const column of this.tsvFile.duplicateColumns) {
49+
this.errors.push(BidsHedIssue.fromHedIssue(generateIssue('duplicateTsvColumn', { column }), this.tsvFile.file))
50+
}
51+
return
52+
}
53+
4654
// Validate the BIDS sidecar if it exists and return if there are errors
4755
if (this.tsvFile.mergedSidecar) {
4856
const issues = this.tsvFile.mergedSidecar.validate(this.hedSchemas)

‎src/issues/data.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -487,6 +487,11 @@ export default {
487487
message: stringTemplate`HED standard schema version ${'version'} is deprecated. Please upgrade to a newer version.`,
488488
},
489489
// BIDS issues
490+
duplicateTsvColumn: {
491+
hedCode: 'TABULAR_INVALID',
492+
level: 'error',
493+
message: stringTemplate`Column "${'column'}" appears more than once in the header of the tabular file.`,
494+
},
490495
sidecarKeyMissing: {
491496
hedCode: 'SIDECAR_KEY_MISSING',
492497
level: 'warning',

0 commit comments

Comments
 (0)