-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcontext.ts
341 lines (314 loc) · 9.57 KB
/
context.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import type {
Associations,
Context,
Dataset,
Gzip,
NiftiHeader,
Ome,
Subject,
Subjects,
Tiff,
} from '@bids/schema/context'
import type { Schema } from '../types/schema.ts'
import type { BIDSFile } from '../types/filetree.ts'
import { FileTree } from '../types/filetree.ts'
import { ColumnsMap } from '../types/columns.ts'
import { readEntities } from './entities.ts'
import { DatasetIssues } from '../issues/datasetIssues.ts'
import { walkBack } from '../files/inheritance.ts'
import { parseGzip } from '../files/gzip.ts'
import { loadTSV } from '../files/tsv.ts'
import { parseTIFF } from '../files/tiff.ts'
import { loadJSON } from '../files/json.ts'
import { loadHeader } from '../files/nifti.ts'
import { buildAssociations } from './associations.ts'
import type { ValidatorOptions } from '../setup/options.ts'
import { logger } from '../utils/logger.ts'
export class BIDSContextDataset implements Dataset {
#dataset_description: Record<string, unknown> = {}
tree: FileTree
ignored: string[]
datatypes: string[]
modalities: string[]
subjects: Subjects
issues: DatasetIssues
sidecarKeyValidated: Set<string>
options?: ValidatorOptions
schema: Schema
pseudofileExtensions: Set<string>
constructor(
args: Partial<BIDSContextDataset>,
) {
this.schema = args.schema || {} as unknown as Schema
this.dataset_description = args.dataset_description || {}
this.tree = args.tree || new FileTree('/unknown', 'unknown')
this.ignored = args.ignored || []
this.datatypes = args.datatypes || []
this.modalities = args.modalities || []
this.sidecarKeyValidated = new Set<string>()
if (args.options) {
this.options = args.options
}
this.issues = args.issues || new DatasetIssues()
this.pseudofileExtensions = new Set<string>(
args.schema
? Object.values(this.schema.objects.extensions)
?.map((ext) => ext.value)
?.filter((ext) => ext.endsWith('/'))
: [],
)
this.subjects = args.subjects || {
sub_dirs: this.tree.directories.map((dir) => dir.name).filter((dir) =>
dir.startsWith('sub-')
),
}
}
get dataset_description(): Record<string, unknown> {
return this.#dataset_description
}
set dataset_description(value: Record<string, unknown>) {
this.#dataset_description = value
if (!this.dataset_description.DatasetType) {
this.dataset_description.DatasetType = this.dataset_description.GeneratedBy
? 'derivative'
: 'raw'
}
}
isPseudoFile(file: FileTree): boolean {
const { suffix, extension, entities } = readEntities(file.name)
return (
suffix !== '' &&
Object.keys(entities).length > 0 &&
this.pseudofileExtensions.has(`${extension}/`)
)
}
}
class BIDSContextDatasetSubjects implements Subjects {
sub_dirs: string[]
participant_id?: string[]
phenotype?: string[]
constructor(
sub_dirs?: string[],
participant_id?: string[],
phenotype?: string[],
) {
this.sub_dirs = sub_dirs ? sub_dirs : []
this.participant_id = participant_id
this.phenotype = phenotype
}
}
export class BIDSContext implements Context {
dataset: BIDSContextDataset
subject: Subject
// path: string <- getter
// size: number <- getter
entities: Record<string, string>
datatype: string
suffix: string
extension: string
modality: string
sidecar: Record<string, any>
associations: Associations
columns: Record<string, string[]>
json: Record<string, any>
gzip?: Gzip
nifti_header?: NiftiHeader
ome?: Ome
tiff?: Tiff
file: BIDSFile
filenameRules: string[]
sidecarKeyOrigin: Record<string, string>
constructor(
file: BIDSFile,
dsContext?: BIDSContextDataset,
fileTree?: FileTree,
) {
this.filenameRules = []
this.file = file
const bidsEntities = readEntities(file.name)
this.suffix = bidsEntities.suffix
this.extension = bidsEntities.extension
this.entities = bidsEntities.entities
this.dataset = dsContext ? dsContext : new BIDSContextDataset({ tree: fileTree })
this.subject = {} as Subject
this.datatype = ''
this.modality = ''
this.sidecar = {}
this.sidecarKeyOrigin = {}
this.columns = new ColumnsMap() as Record<string, string[]>
this.json = {}
this.associations = {} as Associations
}
get schema(): Schema {
return this.dataset.schema
}
get size(): number {
return this.file.size
}
get path(): string {
return this.file.path
}
/**
* Implementation specific absolute path for the dataset root
*
* In the browser, this is always at the root
*/
get datasetPath(): string {
return this.dataset.tree.path
}
/**
* Walks the fileTree backwards from the current file to the root,
* loading any valid json sidecars found.
* Earlier (deeper) sidecars take precedence over later ones.
*/
async loadSidecar() {
if (this.extension === '.json') {
return
}
let sidecars: BIDSFile[] = []
try {
sidecars = [...walkBack(this.file)]
} catch (error) {
if (
error && typeof error === 'object' && 'code' in error &&
error.code === 'MULTIPLE_INHERITABLE_FILES'
) {
// @ts-expect-error
this.dataset.issues.add(error)
} else {
throw error
}
}
for (const file of sidecars) {
const json = await loadJSON(file).catch((error) => {
if (error.key) {
this.dataset.issues.add({ code: error.key, location: file.path })
return {}
} else {
throw error
}
})
this.sidecar = { ...json, ...this.sidecar }
Object.keys(json).map((x) => this.sidecarKeyOrigin[x] ??= file.path)
}
// Hack: round RepetitionTime to 3 decimal places; schema should add rounding function
if (typeof this.sidecar.RepetitionTime === 'number') {
this.sidecar.RepetitionTime = Math.round(this.sidecar.RepetitionTime * 1000) / 1000
}
}
async loadNiftiHeader(): Promise<void> {
if (
!this.extension.startsWith('.nii') || this.dataset?.options?.ignoreNiftiHeaders
) return
this.nifti_header = await loadHeader(this.file).catch((error) => {
if (error.key) {
this.dataset.issues.add({ code: error.key, location: this.file.path })
return undefined
} else {
throw error
}
})
}
async loadColumns(): Promise<void> {
if (this.extension !== '.tsv') {
return
}
this.columns = await loadTSV(this.file)
.catch((error) => {
if (error.key) {
this.dataset.issues.add({ code: error.key, location: this.file.path })
}
logger.warn(
`tsv file could not be opened by loadColumns '${this.file.path}'`,
)
logger.debug(error)
return new Map<string, string[]>() as ColumnsMap
}) as Record<string, string[]>
return
}
async loadAssociations(): Promise<void> {
this.associations = await buildAssociations(this.file, this.dataset.issues)
return
}
async loadJSON(): Promise<void> {
if (this.extension !== '.json') {
return
}
this.json = await loadJSON(this.file).catch((error) => {
if (error.key) {
this.dataset.issues.add({ code: error.key, location: this.file.path })
return {}
} else {
throw error
}
})
}
async loadGzip(): Promise<void> {
if (!this.extension.endsWith('.gz')) {
return
}
this.gzip = await parseGzip(this.file, 512).catch((error) => {
logger.debug('Error parsing gzip header', error)
return undefined
})
}
async loadTIFF(): Promise<void> {
if (!this.extension.endsWith('.tif') && !this.extension.endsWith('.btf')) {
return
}
const { tiff, ome } = await parseTIFF(this.file, this.extension.startsWith('.ome')).catch(
(error) => {
logger.debug('Error parsing tiff header', error)
return { tiff: undefined, ome: undefined }
},
)
this.tiff = tiff
this.ome = ome
}
// This is currently done for every file. It should be done once for the dataset.
async loadSubjects(): Promise<void> {
if (this.dataset.subjects != null) {
return
}
this.dataset.subjects = new BIDSContextDatasetSubjects()
// Load subject dirs from the file tree
this.dataset.subjects.sub_dirs = this.dataset.tree.directories
.filter((dir) => dir.name.startsWith('sub-'))
.map((dir) => dir.name)
// Load participants from participants.tsv
const participants_tsv = this.dataset.tree.get('participants.tsv') as BIDSFile
if (participants_tsv) {
const participantsData = await loadTSV(participants_tsv)
this.dataset.subjects.participant_id = participantsData[
'participant_id'
] as string[]
}
// Load phenotype from phenotype/*.tsv
const phenotype_dir = this.dataset.tree.get('phenotype') as FileTree
if (phenotype_dir) {
const phenotypeFiles = phenotype_dir.files.filter((file) => file.name.endsWith('.tsv'))
// Collect observed participant_ids
const seen = new Set() as Set<string>
for (const file of phenotypeFiles) {
const phenotypeData = await loadTSV(file)
const participant_id = phenotypeData['participant_id'] as string[]
if (participant_id) {
participant_id.forEach((id) => seen.add(id))
}
}
this.dataset.subjects.phenotype = Array.from(seen)
}
}
async asyncLoads() {
await Promise.allSettled([
this.loadSubjects(),
this.loadSidecar(),
this.loadColumns(),
this.loadAssociations(),
this.loadNiftiHeader(),
this.loadJSON(),
this.loadGzip(),
this.loadTIFF(),
])
}
}