-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfetchData.js
363 lines (349 loc) · 11.3 KB
/
fetchData.js
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import fetch from "node-fetch";
import { search } from "fast-fuzzy";
import { htmlToText } from "html-to-text";
import { filterObjectArray } from "./utils/arrayUtils.js";
import config from "./config.js";
import { dataRetrievalConstants } from "./constants/dataRetrieval.js";
const {
IDC_API_BASE_URL,
IDC_COLLECTION_BASE_URL,
IDC_API_COLLECTIONS_ENDPOINT,
TCIA_API_BASE_URL,
TCIA_COLLECTION_BASE_URL,
TCIA_API_COLLECTIONS_ENDPOINT,
TCIA_API_SERIES_ENDPOINT,
} = dataRetrievalConstants;
/**
* Retrieves image collection data from the IDC API and filters for collections relevant to ICDC.
*
* @async
* @returns {Promise<string[]>} - Promise that resolves with an array of IDC collections.
* @throws {Error} - Throws error if there is an issue with the IDC response.
*/
async function getIdcCollections() {
try {
const response = await fetch(
`${IDC_API_BASE_URL}${IDC_API_COLLECTIONS_ENDPOINT}`
);
if (!response.ok) {
throw new Error(
`IDC collection request failed (${response.status}): ${response.statusText}`
);
}
const data = await response.json();
return filterObjectArray(data["collections"], "collection_id", "icdc_");
} catch (error) {
console.error("Error fetching IDC collections: ", error.message);
throw new Error(`IDC internal server error: ${error.message}`);
}
}
/**
* Retrieves image collection data from the TCIA API and filters for collection IDs relevant to ICDC.
*
* @async
* @returns {Promise<string[]>} - Promise that resolves with an array of TCIA collection IDs.
* @throws {Error} - Throws error if there is an issue with the TCIA response.
*/
async function getTciaCollections() {
try {
const response = await fetch(
`${TCIA_API_BASE_URL}${TCIA_API_COLLECTIONS_ENDPOINT}`
);
if (!response.ok) {
throw new Error(
`TCIA collection request failed (${response.status}): ${response.statusText}`
);
}
const data = await response.json();
return filterObjectArray(data, "Collection", "ICDC-").map(
(obj) => obj.Collection
);
} catch (error) {
console.error("Error fetching TCIA collections: ", error.message);
throw new Error(`TCIA internal server error: ${error.message}`);
}
}
/**
* Retrieves data from TCIA API for a specific TCIA image collection.
*
* @async
* @param {string} collection_id - ID of TCIA image collection.
* @returns {Promise<Object>} - Promise that resolves with data for specified TCIA collection.
* @throws {Error} - Throws error if there is an issue with the TCIA response.
*/
async function getTciaCollectionData(collection_id) {
try {
const response = await fetch(
`${TCIA_API_BASE_URL}${TCIA_API_SERIES_ENDPOINT}${collection_id}`
);
if (!response.ok) {
throw new Error(
`TCIA collection request failed (${response.status}): ${response.statusText}`
);
}
return await response.json();
} catch (error) {
console.error("Error fetching TCIA collection data: ", error.message);
throw new Error(`TCIA internal server error: ${error.message}`);
}
}
/**
* Retrieves study data from the ICDC backend via a GraphQL query.
*
* @async
* @returns {Promise<Object[]>} - Promise that resolves with an array of ICDC study data objects.
* @throws {Error} - Throws error if there is an issue with the ICDC response.
*/
async function getIcdcStudyData() {
try {
const body = JSON.stringify({
query: `{
studiesByProgram {
clinical_study_designation
numberOfImageCollections
numberOfCRDCNodes
}
}`,
});
const response = await fetch(config.BENTO_BACKEND_GRAPHQL_URI, {
method: "POST",
body: body,
});
if (!response.ok) {
throw new Error(
`ICDC studies request failed (${response.status}): ${response.statusText}`
);
}
const responseJson = await response.json();
if (!responseJson?.data?.studiesByProgram) {
throw new Error("ICDC response missing required data");
}
return responseJson.data.studiesByProgram;
} catch (error) {
console.error("Error fetching ICDC study data: ", error.message);
throw new Error(`ICDC internal server error: ${error.message}`);
}
}
/**
* Iterates a list of TCIA collection names and gets corresponding metadata for each collection.
*
* @async
* @param {string[]} tciaCollections - Array of TCIA collection names.
* @returns {Object} - Object containing collection data.
*/
async function getTciaCollectionsData(tciaCollections) {
const results = await Promise.all(
tciaCollections.map(async (collection) => {
const data = await getTciaCollectionData(collection);
return { [collection]: data };
})
);
return Object.assign({}, ...results);
}
/**
* Maps collection metadata to a specified IDC collection.
*
* @param {string} collectionId - IDC collection name.
* @param {Object[]} idcCollections - An array of IDC collection data objects.
* @param {string} icdcStudy - ICDC study name.
* @returns {Object} - Object containing metadata for specified IDC collection.
*/
function getIdcCollectionMetadata(collectionId, idcCollections, icdcStudy) {
let idcCollectionMetadata = idcCollections.find(
(obj) => obj.collection_id === collectionId
);
// handle oddly-formatted response HTML for GLIOMA01
const cleanedDescText = htmlToText(idcCollectionMetadata["description"], {
wordwrap: null,
});
if (icdcStudy.clinical_study_designation === "GLIOMA01") {
idcCollectionMetadata["description"] = cleanedDescText
.replace(/\n\n|\s*\[.*?\]\s*/g, " ")
.replace(/ \./g, ".")
.replace(" ICDC-Glioma", "");
} else {
idcCollectionMetadata["description"] = cleanedDescText;
}
return idcCollectionMetadata;
}
/**
* Maps collection metadata to a specified TCIA collection.
*
* @param {string} collectionId - TCIA collection name.
* @param {Object[]} tciaCollectionsData - Object containing data for TCIA collections.
* @param {string} icdcStudy - ICDC study name.
* @returns {Object} - Object containing metadata for specified TCIA collection.
*/
function getTciaCollectionMetadata(
collectionId,
tciaCollectionsData,
icdcStudy
) {
let tciaCollectionMetadata = tciaCollectionsData[collectionId];
let totalImages = tciaCollectionMetadata.reduce(
(tot, obj) => tot + parseInt(obj.ImageCount),
0
);
const totalPatients = [
...new Set(tciaCollectionMetadata.map((obj) => obj.PatientID)),
].length;
const uniqueModalities = [
...new Set(tciaCollectionMetadata.map((obj) => obj.Modality)),
];
const uniqueBodypartsExamined = [
...new Set(tciaCollectionMetadata.map((obj) => obj.BodyPartExamined)),
];
// hardcode inaccessible TCIA data for GLIOMA01
if (icdcStudy.clinical_study_designation === "GLIOMA01") {
uniqueModalities.push("Histopathology");
totalImages += 84;
}
return {
Collection: collectionId,
Aggregate_PatientID: totalPatients,
Aggregate_Modality: uniqueModalities,
Aggregate_BodyPartExamined: uniqueBodypartsExamined,
Aggregate_ImageCount: totalImages,
};
}
/**
* Matches any ICDC-relevant external data to specific ICDC study.
*
* @async
* @param {string} icdcStudy - ICDC study name.
* @param {Object[]} idcCollections - Array of IDC collection data objects.
* @param {string[]} tciaCollections - Array of TCIA collection names.
* @param {string} tciaCollectionsData - Object containing data for TCIA collections.
* @returns {Promise<Object[]>} - Promise that resolves with array of data collection objects matched to corresponding ICDC study.
*/
async function mapMatchesToStudy(
icdcStudy,
idcCollections,
tciaCollections,
tciaCollectionsData
) {
let collectionUrls = [];
// fuzzy match strings using damerau-levenshtein distance
let idcMatches = search(
icdcStudy.clinical_study_designation,
idcCollections.map((obj) => obj.collection_id)
);
let tciaMatches = search(
icdcStudy.clinical_study_designation,
tciaCollections
);
if (idcMatches.length !== 0) {
const idcResults = await Promise.all(
idcMatches.map(async (match) => {
const idcCollectionUrl = `${IDC_COLLECTION_BASE_URL}${match}`;
const idcCollectionMetadata = await getIdcCollectionMetadata(
match,
idcCollections,
icdcStudy
);
return {
repository: "IDC",
url: idcCollectionUrl,
metadata: idcCollectionMetadata,
};
})
);
collectionUrls.push(...idcResults);
}
if (tciaMatches.length !== 0) {
const tciaResults = await Promise.all(
tciaMatches
.filter((match) => tciaCollectionsData[match]?.length > 0)
.map(async (match) => {
const tciaCollectionUrl = `${TCIA_COLLECTION_BASE_URL}${match}`;
let tciaCollectionMetadata = await getTciaCollectionMetadata(
match,
tciaCollectionsData,
icdcStudy
);
return {
repository: "TCIA",
url: tciaCollectionUrl,
metadata: tciaCollectionMetadata,
};
})
);
collectionUrls.push(...tciaResults);
}
return collectionUrls;
}
/**
* Collects/assembles external data collection metadata and counts for corresponding ICDC studies.
*
* @async
* @param {string[]} icdcStudies - Array of ICDC study names.
* @param {Object[]} idcCollections - Array of IDC collection data objects.
* @param {string[]} tciaCollections - Array of TCIA collection names.
* @param {Object[]} tciaCollectionsData - Object containing data for TCIA collections.
* @returns {Promise<Object[]>} - Promise that resolves with an array of external data collection mappings to relevant ICDC studies.
*/
async function collectMappings(
icdcStudies,
idcCollections,
tciaCollections,
tciaCollectionsData
) {
const mappings = await Promise.all(
icdcStudies.map(async (study) => {
const collectionUrls = await mapMatchesToStudy(
study,
idcCollections,
tciaCollections,
tciaCollectionsData
);
if (study?.numberOfCRDCNodes > 0) {
return {
CRDCLinks: collectionUrls,
numberOfCRDCNodes: study?.numberOfCRDCNodes,
numberOfImageCollections: study?.numberOfImageCollections,
clinical_study_designation: study?.clinical_study_designation,
};
}
return null;
})
);
return mappings.filter(Boolean);
}
/**
* Maps ICDC-related data from external APIs to corresponding ICDC studies.
*
* @async
* @returns {Promise<Object[]>} - Promise that resolves with an array of data collection mappings.
*/
async function mapExternalDataToStudies() {
try {
const [icdcStudies, idcCollections, tciaCollections] = await Promise.all([
getIcdcStudyData(),
getIdcCollections(),
getTciaCollections(),
]);
const tciaCollectionsData = await getTciaCollectionsData(tciaCollections);
const collectionMappings = await collectMappings(
icdcStudies,
idcCollections,
tciaCollections,
tciaCollectionsData
);
return collectionMappings;
} catch (error) {
console.error(error);
return error;
}
}
export {
getIdcCollections,
getTciaCollections,
getTciaCollectionData,
getTciaCollectionsData,
getIcdcStudyData,
getIdcCollectionMetadata,
getTciaCollectionMetadata,
mapMatchesToStudy,
collectMappings,
mapExternalDataToStudies,
};