@abi-software/flatmapvuer 1.20.1-demo.2 → 1.21.1-demo.0

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.
@@ -1,9 +1,20 @@
1
1
  import { querySingleConnectivityList } from '@abi-software/map-utilities';
2
2
 
3
- // remove duplicates by stringifying the objects
3
+ // remove duplicates by comparing the stringified objects, keeping the original elements
4
4
  const removeDuplicates = function (arrayOfAnything) {
5
5
  if (!arrayOfAnything) return [];
6
- return [...new Set(arrayOfAnything.map((e) => JSON.stringify(e)))].map((e) => JSON.parse(e));
6
+ const seen = new Set();
7
+ return arrayOfAnything.filter((e) => {
8
+ const key = JSON.stringify(e);
9
+ if (seen.has(key)) return false;
10
+ seen.add(key);
11
+ return true;
12
+ });
13
+ };
14
+
15
+ // set of stringified elements for exact matching of nodes
16
+ const toKeySet = function (arrayOfAnything) {
17
+ return new Set((arrayOfAnything || []).map((e) => JSON.stringify(e)));
7
18
  };
8
19
 
9
20
  // remove duplicates for terms with id (UBERON or ILX) and name properties
@@ -23,7 +34,34 @@ const removeDuplicateTerms = function (arrayOfTerms) {
23
34
  };
24
35
 
25
36
  const cachedLabels = {};
26
- const cachedTaxonLabels = [];
37
+ // taxon => label
38
+ const cachedTaxonLabels = new Map();
39
+ // taxon => in-flight queryLabels promise, shared by concurrent callers
40
+ const pendingTaxonLabels = new Map();
41
+
42
+ // Cache of raw connectivity responses (as promises, so concurrent requests are shared).
43
+ // Flatmaps are immutable per uuid, so responses can be reused. Least recently used are evicted.
44
+ const MAX_CACHED_RESPONSES = 100;
45
+ const cachedResponses = new Map();
46
+
47
+ const cachedRequest = function (key, request) {
48
+ if (cachedResponses.has(key)) {
49
+ const cached = cachedResponses.get(key);
50
+ // move to the end to mark as most recently used
51
+ cachedResponses.delete(key);
52
+ cachedResponses.set(key, cached);
53
+ return cached;
54
+ }
55
+ const promise = request().catch((error) => {
56
+ if (cachedResponses.get(key) === promise) cachedResponses.delete(key);
57
+ throw error;
58
+ });
59
+ cachedResponses.set(key, promise);
60
+ if (cachedResponses.size > MAX_CACHED_RESPONSES) {
61
+ cachedResponses.delete(cachedResponses.keys().next().value);
62
+ }
63
+ return promise;
64
+ };
27
65
 
28
66
  const findTaxonomyLabel = async function (flatmapAPI, taxonomy) {
29
67
  if (cachedLabels && Object.hasOwn(cachedLabels, taxonomy)) {
@@ -52,42 +90,37 @@ const findTaxonomyLabel = async function (flatmapAPI, taxonomy) {
52
90
  };
53
91
 
54
92
  const findTaxonomyLabels = async function (mapImp, taxonomies) {
55
- const intersectionTaxonomies = taxonomies.filter((taxonomy) =>
56
- cachedTaxonLabels.some((obj) => obj.taxon === taxonomy),
57
- );
58
-
59
- const foundCachedTaxonLabels = cachedTaxonLabels.filter((obj) =>
60
- intersectionTaxonomies.includes(obj.taxon),
61
- );
62
-
63
- const leftoverTaxonomies = taxonomies.filter(
64
- (taxonomy) => !intersectionTaxonomies.includes(taxonomy),
93
+ const uniqueTaxonomies = [...new Set(taxonomies)];
94
+ const leftoverTaxonomies = uniqueTaxonomies.filter(
95
+ (taxonomy) => !cachedTaxonLabels.has(taxonomy) && !pendingTaxonLabels.has(taxonomy),
65
96
  );
66
97
 
67
- if (!leftoverTaxonomies.length) {
68
- return foundCachedTaxonLabels;
69
- } else {
70
- const entityLabels = await mapImp.queryLabels(leftoverTaxonomies);
71
- if (entityLabels.length) {
72
- entityLabels.forEach((entityLabel) => {
73
- let { entity: taxon, label } = entityLabel;
74
- if (label === 'Mammalia') {
75
- label = 'Mammalia not otherwise specified';
76
- }
77
- const item = { taxon, label };
78
- foundCachedTaxonLabels.push(item);
79
- cachedTaxonLabels.push(item);
98
+ if (leftoverTaxonomies.length) {
99
+ const request = mapImp
100
+ .queryLabels(leftoverTaxonomies)
101
+ .then((entityLabels) => {
102
+ (entityLabels || []).forEach((entityLabel) => {
103
+ let { entity: taxon, label } = entityLabel;
104
+ if (label === 'Mammalia') {
105
+ label = 'Mammalia not otherwise specified';
106
+ }
107
+ cachedTaxonLabels.set(taxon, label);
108
+ });
109
+ })
110
+ .finally(() => {
111
+ leftoverTaxonomies.forEach((taxonomy) => pendingTaxonLabels.delete(taxonomy));
80
112
  });
81
- return foundCachedTaxonLabels;
82
- }
113
+ leftoverTaxonomies.forEach((taxonomy) => pendingTaxonLabels.set(taxonomy, request));
83
114
  }
84
- };
85
115
 
86
- const inArray = function (ar1, ar2) {
87
- if (!ar1 || !ar2) return false;
88
- let as1 = JSON.stringify(ar1);
89
- let as2 = JSON.stringify(ar2);
90
- return as1.indexOf(as2) !== -1;
116
+ const pending = new Set(
117
+ uniqueTaxonomies.map((taxonomy) => pendingTaxonLabels.get(taxonomy)).filter(Boolean),
118
+ );
119
+ await Promise.all(pending);
120
+
121
+ return uniqueTaxonomies
122
+ .filter((taxonomy) => cachedTaxonLabels.has(taxonomy))
123
+ .map((taxon) => ({ taxon, label: cachedTaxonLabels.get(taxon) }));
91
124
  };
92
125
 
93
126
  const compareNames = (a, b) => {
@@ -108,75 +141,120 @@ const compareNames = (a, b) => {
108
141
  return 0;
109
142
  };
110
143
 
144
+ // The per path data which is reset for every connectivity query
145
+ const createConnectivityState = function () {
146
+ return {
147
+ destinations: [],
148
+ origins: [],
149
+ components: [],
150
+ destinationsWithDatasets: [],
151
+ originsWithDatasets: [],
152
+ componentsWithDatasets: [],
153
+ destinationsCombinations: [],
154
+ originsCombinations: [],
155
+ componentsCombinations: [],
156
+ singleConnectivityList: [],
157
+ rawURLs: [],
158
+ expertConsultants: [],
159
+ };
160
+ };
161
+
162
+ // Add the SCKAN and Map combination and its map nodes for searching datasets
163
+ const addCombination = function (combinations, withDatasets, value, mapNodeLabels) {
164
+ const { sckanNodeId, sckanNodeLabel, mapNodeId, mapNodeLabel } = value;
165
+ combinations.push({
166
+ sckanId: sckanNodeId,
167
+ sckanLabel: sckanNodeLabel,
168
+ mapId: mapNodeId,
169
+ mapLabel: mapNodeLabel,
170
+ });
171
+ mapNodeId.forEach((id, i) => {
172
+ const stringId = typeof id === 'string' ? id : id[0];
173
+ if (stringId) {
174
+ withDatasets.push({
175
+ id: stringId,
176
+ name: mapNodeLabels[i],
177
+ });
178
+ }
179
+ });
180
+ };
181
+
111
182
  let FlatmapQueries = function () {
112
183
  this.initialise = function (flatmapAPI) {
113
184
  this.flatmapAPI = flatmapAPI;
114
- this.destinations = [];
115
- this.origins = [];
116
- this.components = [];
117
- this.destinationsWithDatasets = [];
118
- this.originsWithDatasets = [];
119
- this.componentsWithDatasets = [];
120
- this.destinationsCombinations = [];
121
- this.originsCombinations = [];
122
- this.componentsCombinations = [];
123
- this.singleConnectivityList = [];
185
+ Object.assign(this, createConnectivityState());
124
186
  this.hasSingleConnectivityList = false;
125
- this.rawURLs = [];
126
- this.expertConsultants = [];
127
187
  this.controller = undefined;
128
188
  this.uberons = [];
129
189
  this.lookUp = [];
130
190
  this.connectivitySource = 'map'; // 'sckan'
131
191
  this.noMapConnectivity = false;
192
+ this._requestId = 0;
132
193
  };
133
194
 
134
- this.createTooltipData = async function (mapImp, eventData) {
195
+ this._buildTooltipData = async function (data, mapImp, eventData) {
135
196
  let hyperlinks;
136
- if (eventData.feature.hyperlinks && eventData.feature.hyperlinks.length > 0) {
197
+ if (eventData.feature?.hyperlinks && eventData.feature.hyperlinks.length > 0) {
137
198
  hyperlinks = eventData.feature.hyperlinks;
138
199
  } else {
139
- hyperlinks = this.rawURLs;
200
+ hyperlinks = data.rawURLs;
140
201
  }
141
202
  let taxonomyLabel = undefined;
142
203
  if (eventData.provenanceTaxonomy) {
143
204
  taxonomyLabel = [];
144
205
  try {
145
206
  const entityLabels = await findTaxonomyLabels(mapImp, eventData.provenanceTaxonomy);
146
- if (entityLabels.length) {
147
- entityLabels.forEach((entityLabel) => {
148
- const { label } = entityLabel;
149
- taxonomyLabel.push(label);
150
- });
151
- }
207
+ entityLabels.forEach((entityLabel) => {
208
+ taxonomyLabel.push(entityLabel.label);
209
+ });
152
210
  } catch (error) {
153
211
  console.log(error);
154
212
  }
155
213
  }
156
214
 
157
215
  let tooltipData = {
158
- destinations: this.destinations,
159
- origins: this.origins,
160
- components: this.components,
161
- destinationsWithDatasets: removeDuplicateTerms(this.destinationsWithDatasets),
162
- originsWithDatasets: removeDuplicateTerms(this.originsWithDatasets),
163
- componentsWithDatasets: removeDuplicateTerms(this.componentsWithDatasets),
164
- destinationsCombinations: this.destinationsCombinations,
165
- originsCombinations: this.originsCombinations,
166
- componentsCombinations: this.componentsCombinations,
167
- hasSingleConnectivityList: this.singleConnectivityList.length > 0,
216
+ destinations: data.destinations,
217
+ origins: data.origins,
218
+ components: data.components,
219
+ destinationsWithDatasets: removeDuplicateTerms(data.destinationsWithDatasets),
220
+ originsWithDatasets: removeDuplicateTerms(data.originsWithDatasets),
221
+ componentsWithDatasets: removeDuplicateTerms(data.componentsWithDatasets),
222
+ destinationsCombinations: data.destinationsCombinations,
223
+ originsCombinations: data.originsCombinations,
224
+ componentsCombinations: data.componentsCombinations,
225
+ hasSingleConnectivityList: data.singleConnectivityList.length > 0,
168
226
  title: eventData.label,
169
227
  featureId: eventData.resource,
170
228
  hyperlinks: hyperlinks,
171
- 'expert-consultants': this.expertConsultants,
229
+ 'expert-consultants': data.expertConsultants,
172
230
  provenanceTaxonomy: eventData.provenanceTaxonomy,
173
231
  provenanceTaxonomyLabel: taxonomyLabel,
174
- connectivitySource: this.connectivitySource,
175
- noMapConnectivity: this.noMapConnectivity,
232
+ connectivitySource: data.connectivitySource,
233
+ noMapConnectivity: data.noMapConnectivity,
176
234
  };
177
235
  return tooltipData;
178
236
  };
179
237
 
238
+ this.createTooltipData = async function (mapImp, eventData) {
239
+ return this._buildTooltipData(this, mapImp, eventData);
240
+ };
241
+
242
+ // Query the knowledge and create the tooltip data without using the instance state,
243
+ // so tooltips for multiple paths can be created in parallel.
244
+ this.queryTooltipData = async function (mapImp, eventData) {
245
+ const keastIds = eventData.resource;
246
+ let data = {
247
+ ...createConnectivityState(),
248
+ connectivitySource: 'map',
249
+ noMapConnectivity: false,
250
+ };
251
+ if (keastIds && keastIds.length > 0 && keastIds[0]) {
252
+ const { state } = await this._fetchConnectivity(mapImp, keastIds[0], 'map', true);
253
+ data = { ...data, ...state };
254
+ }
255
+ return this._buildTooltipData(data, mapImp, eventData);
256
+ };
257
+
180
258
  this.updateTooltipData = function (tooltipEntry) {
181
259
  return {
182
260
  ...tooltipEntry,
@@ -205,21 +283,25 @@ let FlatmapQueries = function () {
205
283
  return labelList;
206
284
  };
207
285
 
208
- this.createLabelLookup = async function (mapImp, uberons) {
209
- let uberonMap = {};
210
- this.uberons = [];
286
+ this._buildLabelLookup = async function (mapImp, uberons) {
287
+ const lookUp = {};
288
+ const uberonList = [];
211
289
  const entityLabels = await findTaxonomyLabels(mapImp, uberons);
212
- if (entityLabels.length) {
213
- entityLabels.forEach((entityLabel) => {
214
- const { taxon: entity, label } = entityLabel;
215
- uberonMap[entity] = label;
216
- this.uberons.push({
217
- id: entity,
218
- name: label,
219
- });
290
+ entityLabels.forEach((entityLabel) => {
291
+ const { taxon: entity, label } = entityLabel;
292
+ lookUp[entity] = label;
293
+ uberonList.push({
294
+ id: entity,
295
+ name: label,
220
296
  });
221
- }
222
- return uberonMap;
297
+ });
298
+ return { lookUp, uberons: uberonList };
299
+ };
300
+
301
+ this.createLabelLookup = async function (mapImp, uberons) {
302
+ const { lookUp, uberons: uberonList } = await this._buildLabelLookup(mapImp, uberons);
303
+ this.uberons = uberonList;
304
+ return lookUp;
223
305
  };
224
306
 
225
307
  this.buildConnectivitySqlStatement = function (keastIds) {
@@ -247,57 +329,30 @@ let FlatmapQueries = function () {
247
329
  };
248
330
 
249
331
  this.findAllIdsFromConnectivity = function (connectivity) {
250
- let dnodes = connectivity.connectivity.flat(); // get nodes from edgelist
251
- let nodes = [...new Set(dnodes)]; // remove duplicates
252
- let found = [];
253
- nodes.forEach((n) => {
254
- if (Array.isArray(n)) {
255
- found.push(n.flat());
256
- } else {
257
- found.push(n);
258
- }
259
- });
260
- return [...new Set(found.flat())];
332
+ // edges => nodes => [id, [ids]] => ids
333
+ return [...new Set(connectivity.connectivity.flat(3))];
261
334
  };
262
335
 
263
336
  this.flattenConnectivity = function (connectivity) {
264
- let dnodes = connectivity.flat(); // get nodes from edgelist
265
- let nodes = [...new Set(dnodes)]; // remove duplicates
266
- let found = [];
267
- nodes.forEach((n) => {
268
- if (Array.isArray(n)) {
269
- found.push(n.flat());
270
- } else {
271
- found.push(n);
272
- }
273
- });
274
- return found.flat();
337
+ // nodes => [id, [ids]] => ids
338
+ return connectivity.flat(3);
275
339
  };
276
340
 
277
341
  this.findComponents = function (connectivity, axons, dendrites, somas) {
278
342
  let dnodes = connectivity.connectivity.flat(); // get nodes from edgelist
279
343
  let nodes = removeDuplicates(dnodes);
280
344
 
281
- let found = [];
282
- let terminal = false;
283
- nodes.forEach((node) => {
284
- terminal = false;
285
- // Check if the node is an destination or origin (note that they are labelled dendrite and axon as opposed to origin and destination)
286
- if (inArray(axons, node)) {
287
- terminal = true;
288
- }
289
- if (somas && inArray(somas, node)) {
290
- terminal = true;
291
- }
292
- if (inArray(dendrites, node)) {
293
- terminal = true;
294
- }
295
- if (!terminal) {
296
- found.push(node);
297
- }
298
- });
345
+ // Stringify the terminals once instead of for every node, then match the node as a substring
346
+ const terminals = [axons, somas, dendrites]
347
+ .filter((terminal) => terminal)
348
+ .map((terminal) => JSON.stringify(terminal));
299
349
 
300
- return found;
350
+ // Keep the nodes which are not destinations or origins
351
+ // (note that they are labelled dendrite and axon as opposed to origin and destination)
352
+ return nodes.filter((node) => {
353
+ const nodeKey = JSON.stringify(node);
354
+ return !terminals.some((terminal) => terminal.indexOf(nodeKey) !== -1);
355
+ });
301
356
  };
302
357
 
303
358
  this.retrieveFlatmapKnowledgeForEvent = async function (mapImp, eventData) {
@@ -306,25 +361,14 @@ let FlatmapQueries = function () {
306
361
 
307
362
  // set up the abort controller
308
363
  this.controller = new AbortController();
364
+ // invalidate any query in progress
365
+ this._requestId++;
309
366
 
310
367
  const keastIds = eventData.resource;
311
- this.destinations = [];
312
- this.origins = [];
313
- this.components = [];
314
- this.destinationsWithDatasets = [];
315
- this.originsWithDatasets = [];
316
- this.componentsWithDatasets = [];
317
- this.destinationsCombinations = [];
318
- this.originsCombinations = [];
319
- this.componentsCombinations = [];
320
- this.singleConnectivityList = [];
321
- this.rawURLs = [];
322
- this.expertConsultants = [];
368
+ Object.assign(this, createConnectivityState());
323
369
  if (!keastIds || keastIds.length === 0 || !keastIds[0]) return;
324
370
 
325
- let prom1 = await this.queryForConnectivityNew(mapImp, keastIds[0]); // This on returns a promise so dont need 'await'
326
- let results = await Promise.all([prom1]);
327
- return results;
371
+ return [await this.queryForConnectivityNew(mapImp, keastIds[0])];
328
372
  };
329
373
 
330
374
  this.queryForConnectivityNew = async function (
@@ -332,6 +376,28 @@ let FlatmapQueries = function () {
332
376
  keastId,
333
377
  connectivitySource = 'map',
334
378
  processConnectivity = true,
379
+ ) {
380
+ const requestId = ++this._requestId;
381
+ const { state, value } = await this._fetchConnectivity(
382
+ mapImp,
383
+ keastId,
384
+ connectivitySource,
385
+ processConnectivity,
386
+ );
387
+ // Only update the instance state if no newer query has started meanwhile
388
+ if (requestId === this._requestId) {
389
+ Object.assign(this, state);
390
+ }
391
+ return value;
392
+ };
393
+
394
+ // Query and process the connectivity of a path without changing the instance state.
395
+ // Returns the state to apply and the value returned by queryForConnectivityNew.
396
+ this._fetchConnectivity = async function (
397
+ mapImp,
398
+ keastId,
399
+ connectivitySource,
400
+ processConnectivity,
335
401
  ) {
336
402
  // The new service, CQ27, is available for SCKAN knowledge sources from 2026 onward.
337
403
  const sourceMatch = /^sckan-(\d{4})/.exec(mapImp.knowledgeSource || '');
@@ -339,82 +405,77 @@ let FlatmapQueries = function () {
339
405
  const isCq27ServiceAvailable = sourceYear >= 2026;
340
406
  const mapUUID = mapImp.mapMetadata.uuid;
341
407
  const flatmapAPI = this.flatmapAPI;
342
- this.connectivitySource = isCq27ServiceAvailable ? 'sckan' : connectivitySource;
343
-
344
- if (isCq27ServiceAvailable) {
345
- this.singleConnectivityList = await querySingleConnectivityList(flatmapAPI, mapUUID, keastId);
346
- }
408
+ const state = createConnectivityState();
409
+ state.connectivitySource = isCq27ServiceAvailable ? 'sckan' : connectivitySource;
410
+
411
+ // Start both queries together as they are independent
412
+ const singleConnectivityListRequest = isCq27ServiceAvailable
413
+ ? cachedRequest(`cq27|${flatmapAPI}|${mapUUID}|${keastId}`, () =>
414
+ querySingleConnectivityList(flatmapAPI, mapUUID, keastId),
415
+ ).catch(() => [])
416
+ : Promise.resolve([]);
417
+ const querySckanKnowledge = () =>
418
+ cachedRequest(`sckan|${flatmapAPI}|${mapUUID}|${keastId}`, () =>
419
+ mapImp.queryKnowledge(keastId),
420
+ );
421
+ const connectivityRequest =
422
+ state.connectivitySource === 'map'
423
+ ? cachedRequest(`map|${flatmapAPI}|${mapUUID}|${keastId}`, () =>
424
+ this.queryMapConnectivity(mapUUID, keastId),
425
+ )
426
+ : querySckanKnowledge();
427
+
428
+ let value = false;
429
+ try {
430
+ let response = await connectivityRequest;
431
+ state.singleConnectivityList = await singleConnectivityListRequest;
432
+ if (this.checkConnectivityExists(response)) {
433
+ if (state.connectivitySource === 'map') {
434
+ state.noMapConnectivity = false;
435
+ }
436
+ } else if (state.connectivitySource === 'map') {
437
+ // switch to SCKAN
438
+ // when there has no connectivity data from Map
439
+ // and add the noMapConnectivity flag to disable the option
440
+ state.connectivitySource = 'sckan';
441
+ state.noMapConnectivity = true;
442
+ response = await querySckanKnowledge().catch(() => undefined);
443
+ } else {
444
+ response = undefined;
445
+ }
347
446
 
348
- return new Promise((resolve) => {
349
- const queryAPI =
350
- this.connectivitySource === 'map'
351
- ? this.queryMapConnectivity(mapImp.mapMetadata.uuid, keastId)
352
- : mapImp.queryKnowledge(keastId);
353
-
354
- queryAPI
355
- .then((response) => {
356
- if (this.checkConnectivityExists(response)) {
357
- if (this.connectivitySource === 'map') {
358
- this.noMapConnectivity = false;
359
- }
360
- let connectivity = response;
361
- if (processConnectivity) {
362
- this.processConnectivity(mapImp, connectivity).then((processedConnectivity) => {
363
- // response.references is publication urls
364
- if (response.references) {
365
- // with publications from both PubMed and Others
366
- this.rawURLs = [...response.references];
367
- }
368
- if (response['expert-consultants']) {
369
- this.expertConsultants = [...response['expert-consultants']];
370
- }
371
- resolve(processedConnectivity);
372
- });
373
- } else resolve(connectivity);
374
- } else if (this.connectivitySource === 'map') {
375
- // switch to SCKAN
376
- // when there has no connectivity data from Map
377
- // and add the noMapConnectivity flag to disable the option
378
- this.connectivitySource = 'sckan';
379
- this.noMapConnectivity = true;
380
- mapImp
381
- .queryKnowledge(keastId)
382
- .then((fallbackResponse) => {
383
- if (this.checkConnectivityExists(fallbackResponse)) {
384
- let connectivity = fallbackResponse;
385
- if (processConnectivity) {
386
- this.processConnectivity(mapImp, connectivity).then((processedConnectivity) => {
387
- // response.references is publication urls
388
- if (fallbackResponse.references) {
389
- // with publications from both PubMed and Others
390
- this.rawURLs = [...fallbackResponse.references];
391
- }
392
- if (fallbackResponse['expert-consultants']) {
393
- this.expertConsultants = [...fallbackResponse['expert-consultants']];
394
- }
395
- resolve(processedConnectivity);
396
- });
397
- } else resolve(connectivity);
398
- } else {
399
- resolve(false);
400
- }
401
- })
402
- .catch(() => resolve(false));
403
- } else {
404
- resolve(false);
447
+ if (this.checkConnectivityExists(response)) {
448
+ value = response;
449
+ if (processConnectivity) {
450
+ const processed = await this._processConnectivity(
451
+ mapImp,
452
+ response,
453
+ state.singleConnectivityList,
454
+ );
455
+ Object.assign(state, processed.state);
456
+ value = processed.value;
457
+ // response.references is publication urls
458
+ if (response.references) {
459
+ // with publications from both PubMed and Others
460
+ state.rawURLs = [...response.references];
405
461
  }
406
- })
407
- .catch((error) => {
408
- if (error.name === 'AbortError') {
409
- // This error is from AbortController's abort method.
410
- } else {
411
- // console.error('Error:', error)
412
- // TODO: to update after queryKnowledge method update
413
- console.warn(`Unable to get the knowledge for the entity ${keastId}.`);
462
+ if (response['expert-consultants']) {
463
+ state.expertConsultants = [...response['expert-consultants']];
414
464
  }
415
- resolve(false);
416
- });
417
- });
465
+ }
466
+ }
467
+ } catch (error) {
468
+ state.singleConnectivityList = await singleConnectivityListRequest;
469
+ if (error.name === 'AbortError') {
470
+ // This error is from AbortController's abort method.
471
+ } else {
472
+ // console.error('Error:', error)
473
+ // TODO: to update after queryKnowledge method update
474
+ console.warn(`Unable to get the knowledge for the entity ${keastId}.`);
475
+ }
476
+ value = false;
477
+ }
478
+ return { state, value };
418
479
  };
419
480
 
420
481
  this.queryMapConnectivity = async function (mapuuid, pathId) {
@@ -449,9 +510,11 @@ let FlatmapQueries = function () {
449
510
  if (this.connectivityExists(data)) {
450
511
  let connectivity = JSON.parse(data.values[0][0]);
451
512
  if (processConnectivity) {
452
- this.processConnectivity(mapImp, connectivity).then((processedConnectivity) => {
453
- resolve(processedConnectivity);
454
- });
513
+ this.processConnectivity(mapImp, connectivity)
514
+ .then((processedConnectivity) => {
515
+ resolve(processedConnectivity);
516
+ })
517
+ .catch(() => resolve(false));
455
518
  } else resolve(connectivity);
456
519
  } else {
457
520
  resolve(false);
@@ -473,16 +536,11 @@ let FlatmapQueries = function () {
473
536
  };
474
537
 
475
538
  this.connectivityExists = function (data) {
476
- if (
477
- data.values &&
478
- data.values.length > 0 &&
479
- JSON.parse(data.values[0][0]).connectivity &&
480
- JSON.parse(data.values[0][0]).connectivity.length > 0
481
- ) {
482
- return true;
483
- } else {
484
- return false;
539
+ if (data.values && data.values.length > 0) {
540
+ const connectivity = JSON.parse(data.values[0][0]).connectivity;
541
+ return !!(connectivity && connectivity.length > 0);
485
542
  }
543
+ return false;
486
544
  };
487
545
 
488
546
  // This function is used to determine if a node is a single node or a node with multiple children
@@ -525,154 +583,151 @@ let FlatmapQueries = function () {
525
583
  return label;
526
584
  };
527
585
 
528
- this.flattenAndFindDatasets = function (dendrites, components, axons) {
586
+ // Returns the anatomy with datasets and the SCKAN and Map combinations
587
+ this._findDatasets = function (dendrites, components, axons, uberons, singleConnectivityList) {
529
588
  // process the nodes for finding datasets (Note this is not critical to the tooltip, only for the 'search on components' button)
530
- let dendritesFlat = this.flattenConnectivity(dendrites);
531
- let componentsFlat = this.flattenConnectivity(components);
532
- let axonsFlat = this.flattenConnectivity(axons);
589
+ const dendritesFlat = new Set(this.flattenConnectivity(dendrites));
590
+ const componentsFlat = new Set(this.flattenConnectivity(components));
591
+ const axonsFlat = new Set(this.flattenConnectivity(axons));
533
592
 
534
593
  // Filter for the anatomy which is annotated on datasets
535
- this.originsWithDatasets = this.uberons
536
- .filter((ub) => dendritesFlat.indexOf(ub.id) !== -1)
537
- .sort(compareNames);
538
- this.componentsWithDatasets = this.uberons
539
- .filter((ub) => componentsFlat.indexOf(ub.id) !== -1)
540
- .sort(compareNames);
541
- this.destinationsWithDatasets = this.uberons
542
- .filter((ub) => axonsFlat.indexOf(ub.id) !== -1)
543
- .sort(compareNames);
594
+ const result = {
595
+ originsWithDatasets: uberons.filter((ub) => dendritesFlat.has(ub.id)).sort(compareNames),
596
+ componentsWithDatasets: uberons.filter((ub) => componentsFlat.has(ub.id)).sort(compareNames),
597
+ destinationsWithDatasets: uberons.filter((ub) => axonsFlat.has(ub.id)).sort(compareNames),
598
+ destinationsCombinations: [],
599
+ originsCombinations: [],
600
+ componentsCombinations: [],
601
+ };
544
602
 
545
603
  // Get combinations of SCKAN and Map
546
- if (this.singleConnectivityList.length > 0) {
547
- this.singleConnectivityList.forEach((value) => {
548
- const { sckanNodeId, sckanNodeLabel, mapNodeId, mapNodeLabel } = value;
549
-
604
+ if (singleConnectivityList.length > 0) {
605
+ const axonKeys = toKeySet(axons);
606
+ const dendriteKeys = toKeySet(dendrites);
607
+ const componentKeys = toKeySet(components);
608
+ singleConnectivityList.forEach((value) => {
550
609
  // The base ID is SCKAN ID
551
- if (axons.find((axon) => JSON.stringify(axon) === JSON.stringify(sckanNodeId))) {
552
- this.destinationsCombinations.push({
553
- sckanId: sckanNodeId,
554
- sckanLabel: sckanNodeLabel,
555
- mapId: mapNodeId,
556
- mapLabel: mapNodeLabel,
557
- });
558
- mapNodeId.forEach((id, i) => {
559
- const stringId = typeof id === 'string' ? id : id[0];
560
- if (stringId) {
561
- this.destinationsWithDatasets.push({
562
- id: stringId,
563
- name: mapNodeLabel.split(',')[i],
564
- });
565
- }
566
- });
610
+ const sckanKey = JSON.stringify(value.sckanNodeId);
611
+ const mapNodeLabels = value.mapNodeLabel.split(',');
612
+ if (axonKeys.has(sckanKey)) {
613
+ addCombination(
614
+ result.destinationsCombinations,
615
+ result.destinationsWithDatasets,
616
+ value,
617
+ mapNodeLabels,
618
+ );
567
619
  }
568
- if (
569
- dendrites.find((dendrite) => JSON.stringify(dendrite) === JSON.stringify(sckanNodeId))
570
- ) {
571
- this.originsCombinations.push({
572
- sckanId: sckanNodeId,
573
- sckanLabel: sckanNodeLabel,
574
- mapId: mapNodeId,
575
- mapLabel: mapNodeLabel,
576
- });
577
- mapNodeId.forEach((id, i) => {
578
- const stringId = typeof id === 'string' ? id : id[0];
579
- if (stringId) {
580
- this.originsWithDatasets.push({
581
- id: stringId,
582
- name: mapNodeLabel.split(',')[i],
583
- });
584
- }
585
- });
620
+ if (dendriteKeys.has(sckanKey)) {
621
+ addCombination(
622
+ result.originsCombinations,
623
+ result.originsWithDatasets,
624
+ value,
625
+ mapNodeLabels,
626
+ );
586
627
  }
587
- if (
588
- components.find((component) => JSON.stringify(component) === JSON.stringify(sckanNodeId))
589
- ) {
590
- this.componentsCombinations.push({
591
- sckanId: sckanNodeId,
592
- sckanLabel: sckanNodeLabel,
593
- mapId: mapNodeId,
594
- mapLabel: mapNodeLabel,
595
- });
596
- mapNodeId.forEach((id, i) => {
597
- const stringId = typeof id === 'string' ? id : id[0];
598
- if (stringId) {
599
- this.componentsWithDatasets.push({
600
- id: stringId,
601
- name: mapNodeLabel.split(',')[i],
602
- });
603
- }
604
- });
628
+ if (componentKeys.has(sckanKey)) {
629
+ addCombination(
630
+ result.componentsCombinations,
631
+ result.componentsWithDatasets,
632
+ value,
633
+ mapNodeLabels,
634
+ );
605
635
  }
606
636
  });
607
637
  }
638
+ return result;
608
639
  };
609
640
 
610
- this.processConnectivity = function (mapImp, connectivity) {
611
- return new Promise((resolve) => {
612
- let dendrites = [];
613
- let axons = [];
614
- let somas = undefined;
615
- if (connectivity && connectivity['node-phenotypes']) {
616
- const sourceKey = ['ilxtr:hasSomaLocatedIn'];
617
- const destinationKey = [
618
- 'ilxtr:hasAxonPresynapticElementIn',
619
- 'ilxtr:hasAxonSensorySubcellularElementIn',
620
- ];
621
- sourceKey.forEach((key) => {
622
- if (key in connectivity['node-phenotypes']) {
623
- dendrites.push(...connectivity['node-phenotypes'][key]);
624
- }
625
- });
626
- dendrites = removeDuplicates(dendrites);
627
- destinationKey.forEach((key) => {
628
- if (key in connectivity['node-phenotypes']) {
629
- axons.push(...connectivity['node-phenotypes'][key]);
630
- }
631
- });
632
- axons = removeDuplicates(axons);
633
- } else {
634
- // Remove duplicates
635
- axons = removeDuplicates(connectivity.axons);
636
- //Somas will become part of origins, support this for future proof
637
- if (connectivity.somas && connectivity.somas.length > 0) {
638
- dendrites.push(...connectivity.somas);
641
+ this.flattenAndFindDatasets = function (dendrites, components, axons) {
642
+ Object.assign(
643
+ this,
644
+ this._findDatasets(dendrites, components, axons, this.uberons, this.singleConnectivityList),
645
+ );
646
+ };
647
+
648
+ // Process the connectivity without changing the instance state.
649
+ // Returns the state to apply and the processed connectivity.
650
+ this._processConnectivity = async function (mapImp, connectivity, singleConnectivityList) {
651
+ let dendrites = [];
652
+ let axons = [];
653
+ let somas = undefined;
654
+ if (connectivity && connectivity['node-phenotypes']) {
655
+ const sourceKey = ['ilxtr:hasSomaLocatedIn'];
656
+ const destinationKey = [
657
+ 'ilxtr:hasAxonPresynapticElementIn',
658
+ 'ilxtr:hasAxonSensorySubcellularElementIn',
659
+ ];
660
+ sourceKey.forEach((key) => {
661
+ if (key in connectivity['node-phenotypes']) {
662
+ dendrites.push(...connectivity['node-phenotypes'][key]);
639
663
  }
640
- if (connectivity.dendrites && connectivity.dendrites.length > 0) {
641
- dendrites.push(...connectivity.dendrites);
664
+ });
665
+ dendrites = removeDuplicates(dendrites);
666
+ destinationKey.forEach((key) => {
667
+ if (key in connectivity['node-phenotypes']) {
668
+ axons.push(...connectivity['node-phenotypes'][key]);
642
669
  }
643
- dendrites = removeDuplicates(dendrites);
644
- somas = connectivity.somas;
670
+ });
671
+ axons = removeDuplicates(axons);
672
+ } else {
673
+ // Remove duplicates
674
+ axons = removeDuplicates(connectivity.axons);
675
+ //Somas will become part of origins, support this for future proof
676
+ if (connectivity.somas && connectivity.somas.length > 0) {
677
+ dendrites.push(...connectivity.somas);
645
678
  }
679
+ if (connectivity.dendrites && connectivity.dendrites.length > 0) {
680
+ dendrites.push(...connectivity.dendrites);
681
+ }
682
+ dendrites = removeDuplicates(dendrites);
683
+ somas = connectivity.somas;
684
+ }
646
685
 
647
- const components = this.findComponents(connectivity, axons, dendrites, somas);
648
- // Create list of ids to get labels for
649
- const conIds = this.findAllIdsFromConnectivity(connectivity);
650
- // Create readable labels from the nodes. Setting this to 'this.origins' updates the display
651
- this.createLabelLookup(mapImp, conIds).then((lookUp) => {
652
- this.origins = dendrites
653
- .map((d) => this.createLabelFromNeuralNode(d, lookUp))
654
- .sort(compareNames);
655
- this.components = components
656
- .map((c) => this.createLabelFromNeuralNode(c, lookUp))
657
- .sort(compareNames);
658
- this.destinations = axons
659
- .map((a) => this.createLabelFromNeuralNode(a, lookUp))
660
- .sort(compareNames);
661
- this.flattenAndFindDatasets(dendrites, components, axons);
662
- resolve({
663
- ids: {
664
- dendrites: dendrites,
665
- components: components,
666
- axons: axons,
667
- },
668
- labels: {
669
- origins: this.origins,
670
- components: this.components,
671
- destinations: this.destinations,
672
- },
673
- });
674
- });
675
- });
686
+ const components = this.findComponents(connectivity, axons, dendrites, somas);
687
+ // Create list of ids to get labels for
688
+ const conIds = this.findAllIdsFromConnectivity(connectivity);
689
+ // Create readable labels from the nodes. Setting this to 'this.origins' updates the display
690
+ const { lookUp, uberons } = await this._buildLabelLookup(mapImp, conIds);
691
+ const origins = dendrites
692
+ .map((d) => this.createLabelFromNeuralNode(d, lookUp))
693
+ .sort(compareNames);
694
+ const componentLabels = components
695
+ .map((c) => this.createLabelFromNeuralNode(c, lookUp))
696
+ .sort(compareNames);
697
+ const destinations = axons
698
+ .map((a) => this.createLabelFromNeuralNode(a, lookUp))
699
+ .sort(compareNames);
700
+ return {
701
+ state: {
702
+ uberons,
703
+ origins,
704
+ components: componentLabels,
705
+ destinations,
706
+ ...this._findDatasets(dendrites, components, axons, uberons, singleConnectivityList),
707
+ },
708
+ value: {
709
+ ids: {
710
+ dendrites: dendrites,
711
+ components: components,
712
+ axons: axons,
713
+ },
714
+ labels: {
715
+ origins,
716
+ components: componentLabels,
717
+ destinations,
718
+ },
719
+ },
720
+ };
721
+ };
722
+
723
+ this.processConnectivity = async function (mapImp, connectivity) {
724
+ const { state, value } = await this._processConnectivity(
725
+ mapImp,
726
+ connectivity,
727
+ this.singleConnectivityList,
728
+ );
729
+ Object.assign(this, state);
730
+ return value;
676
731
  };
677
732
 
678
733
  this.buildPubmedSqlStatement = function (keastIds) {