-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathgenomics.js
More file actions
3044 lines (2774 loc) · 81.7 KB
/
genomics.js
File metadata and controls
3044 lines (2774 loc) · 81.7 KB
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import axios from 'axios';
import { forkJoin, from, of } from 'rxjs';
import { catchError, finalize, map, mergeMap, pluck } from 'rxjs/operators';
import { min, max, sum, range, median, quantile } from 'd3-array';
import { format } from 'd3-format';
import { nest } from 'd3-collection';
import { scaleThreshold } from 'd3-scale';
import { timeDay, timeMonday } from 'd3-time';
import { timeFormat, timeParse } from 'd3-time-format';
import { bin } from 'd3-array';
import { schemeYlGnBu } from 'd3-scale-chromatic';
import { getEpiTraces, getSparklineTraces } from '@/api/epi-traces.js';
import CURATED from '@/assets/genomics/curated_lineages.json';
import MUTATIONS from '@/assets/genomics/curated_mutations.json';
import NT_MAP from '@/assets/genomics/sarscov2_NC045512_genes_nt.json';
import WHO_REGIONS from '@/assets/genomics/who_regions.json';
import orderBy from 'lodash/orderBy';
import uniq from 'lodash/uniq';
import store from '@/store';
const parseDate = timeParse('%Y-%m-%d');
const formatDate = timeFormat('%e %B %Y');
const formatDateTime = timeFormat('%e %B %Y %I:%M %p');
const formatDateShort = timeFormat('%e %b %Y');
const formatPercent = format('.0%');
axios.interceptors.request.use(
(config) => {
// Pass GISAID param to API via headers
// * BEFORE COMPLIATION, YOU NEED to run `export VUE_APP_API_ACCESS={key}`*
config.headers.Authorization = `Bearer ${process.env.VUE_APP_API_ACCESS}`;
return config;
},
(error) => {
return Promise.reject(error);
},
);
const capitalize = (value) => {
if (!value) return '';
value = value.toString();
return value !== 'of'
? value.charAt(0).toUpperCase() + value.slice(1)
: value;
};
const titleCase = (value) => {
if (value) {
const values = value.split(' ');
return values.map((d) => capitalize(d)).join(' ');
}
};
export const lookupLineageDetails = (
apiurl,
mutationObj,
prevalenceThreshold,
) => {
const queryStr = mutationObj.reportQuery.muts
? `pangolin_lineage=${mutationObj.reportQuery.pango}&mutations=${mutationObj.reportQuery.muts}`
: `pangolin_lineage=${mutationObj.reportQuery.pango}`;
return forkJoin([getVariantTotal(apiurl, queryStr)]).pipe(
map(([total]) => {
mutationObj['lineage_count'] = total;
// sort the mutation synonyms
if (mutationObj.mutation_synonyms) {
mutationObj.mutation_synonyms.sort();
}
// translate dates into human-readable formats
if (mutationObj.dateModified) {
const parsedDate = parseDate(mutationObj.dateModified);
mutationObj['dateModifiedFormatted'] = formatDateShort(parsedDate);
}
// sort the classifications, format the dates
if (mutationObj.classifications) {
mutationObj.classifications = orderBy(
mutationObj.classifications,
['author'],
['asc'],
);
// mutationObj.classifications = orderBy(mutationObj.classifications, [reportIDSorter, "dateModified", "author"], ["asc"]);
mutationObj.classifications.forEach((d) => {
const parsedDate = parseDate(d.dateModified);
d['dateModifiedFormatted'] = parsedDate
? formatDateShort(parsedDate)
: null;
});
// Add outbreak's classification on the first instance
if (
!mutationObj.classifications.filter((d) => d.author === 'outbreak')
.length
) {
const outbreakVariantType =
mutationObj.variantType === 'Variant of Concern'
? 'VOC'
: mutationObj.variantType === 'Variant of Interest'
? 'VOI'
: 'VUM';
mutationObj.classifications.push({
author: 'outbreak',
dateModified: mutationObj.dateModified,
dateModifiedFormatted: formatDateShort(
parseDate(mutationObj.dateModified),
),
variantType: outbreakVariantType,
});
}
// create classification table
mutationObj['classificationTable'] = nest()
.key((d) => d.variantType)
// .key(d => d.author)
.rollup((values) => {
let obj = {};
// WARNING: this assumes that there aren't duplicate author keys.
// should be okay if the curation is okay.
values.forEach((d) => {
const reportLink =
d.url && d.dateModifiedFormatted
? `<a href="${d.url}" target="_blank">${d.dateModifiedFormatted}</a>`
: d.url
? `<a href="${d.url}" target="_blank">report</a>`
: d.dateModifiedFormatted
? d.dateModifiedFormatted
: null;
const reportType =
d.variantType === 'VOC'
? 'Variant of Concern'
: d.variantType === 'VOI'
? 'Variant of Interest'
: d.variantType === 'VUI'
? 'Variants under Investigation'
: d.variantType === 'VUM'
? 'Variants under Monitoring'
: null;
const ttip = reportLink
? d.author === 'outbreak'
? `<b>${reportType}</b> classification by <b>outbreak.info</b>`
: `View <b>${reportType}</b> classification by <b>${d.author}</b>`
: null;
obj[d.author] = {
dateModified: d.dateModifiedFormatted,
url: d.url,
report: reportLink,
ttip: ttip,
};
});
return obj;
})
.entries(mutationObj.classifications);
mutationObj['classificationTable'] = arr2Obj(
mutationObj['classificationTable'],
'key',
'value',
);
}
}),
);
};
const arr2Obj = (arr, keyVar, valVar) => {
return arr.reduce((r, e) => {
r[e[keyVar]] = e[valVar];
return r;
}, {});
};
// sort the mutations by position within the genes
const compareMutationLocation = (a, b) => {
if (!(a.gene in NT_MAP) || !(b.gene in NT_MAP)) return 0;
if (NT_MAP[a.gene].start < NT_MAP[b.gene].start) return -1;
if (NT_MAP[a.gene].start > NT_MAP[b.gene].start) return 0;
return a.codon_num < b.codon_num ? -1 : 0;
};
const addTotal2Mutation = (apiurl, mutation) => {
return getVariantTotal(apiurl, `mutations=${mutation.mutation_name}`).pipe(
map((total) => {
mutation['lineage_count'] = total;
}),
);
};
export const addTotals2Mutations = (apiurl) => {
return forkJoin(
...MUTATIONS.map((mutation) => addTotal2Mutation(apiurl, mutation)),
);
};
export const getCuratedMutations = (apiurl, prevalenceThreshold) => {
const query = MUTATIONS.map((mutation) => mutation.mutation_name);
return forkJoin([
getMutationsByLineage(apiurl, query, prevalenceThreshold, false, true),
addTotals2Mutations(apiurl),
]).pipe(
map(([lineagesByMutation, totals]) => {
// sort by codon num, then alpha
let curated = orderBy(MUTATIONS, ['codon_num', 'mutation_name']);
// Merge in the lineages
curated.forEach((mutation) => {
mutation['lineages'] = lineagesByMutation[mutation.mutation_name].map(
(d) => d.pangolin_lineage,
);
console.log(mutation);
mutation[
'aquaria'
] = `https://aquaria.app/SARS-CoV-2/${mutation.mutation_name.replace(
':',
'?',
)}`;
});
// nest by MOC/MOI
curated = nest()
.key((d) => d.variantType)
.entries(curated);
curated.forEach((d) => {
d['id'] =
d.key === 'Mutation of Concern'
? 'moc'
: d.key === 'Mutation of Interest'
? 'moi'
: 'unknown';
});
curated = orderBy(curated, [reportTypeSorter], ['asc']);
return curated;
}),
);
};
export const getSublineageMutations = (
apiurl,
prevalenceThreshold,
sMutationsOnly = true,
) => {
const query = CURATED.map((d) => d.pango_descendants).join(',');
return getCharacteristicMutations(apiurl, query, 0, false).pipe(
map((charMuts) => {
// pull out the characteristic mutations and bind to the curated list.
let curated = orderBy(CURATED, ['variantType']);
// loop over each curated report; attach the associated lineages / characteristic mutations with it.
curated.forEach((report) => {
let mutations_in_report = [];
report.pango_descendants.forEach((lineage) => {
// flat map the mutations within the lineages associated with that group
if (Object.keys(charMuts).includes(lineage)) {
mutations_in_report.push(charMuts[lineage]);
}
});
// flat map the mutations to collapse the sublineages down into a long list.
report['mutations'] = mutations_in_report.flatMap((d) => d);
if (sMutationsOnly) {
report.mutations = report.mutations.filter((d) => d.gene === 'S');
}
const prevalentMutations = uniq(
report.mutations
.filter((d) => d.prevalence > prevalenceThreshold)
.map((d) => d.mutation),
);
report.mutations = report.mutations.filter((x) =>
prevalentMutations.includes(x.mutation),
);
});
const voc = CURATED.filter(
(d) => d.variantType === 'Variant of Concern',
).flatMap((d) => d.char_muts_query);
const voc_parent = CURATED.filter(
(d) => d.variantType === 'Variant of Concern',
).map((d) => d.label);
const voi = CURATED.filter(
(d) => d.variantType === 'Variant of Interest',
).flatMap((d) => d.char_muts_query);
const voi_parent = CURATED.filter(
(d) => d.variantType === 'Variant of Interest',
).map((d) => d.label);
curated = nest()
.key((d) => d.variantType)
.entries(curated);
curated.forEach((d) => {
d['id'] =
d.key === 'Variant of Concern'
? 'voc'
: d.key === 'Variant of Interest'
? 'voi'
: d.key === 'Variant under Monitoring'
? 'vum'
: 'unknown';
});
curated = orderBy(curated, [reportTypeSorter], ['asc']);
return {
md: curated,
voc: voc,
voc_parent: voc_parent,
voi: voi,
voi_parent: voi_parent,
};
}),
);
};
export const getCuratedList = (
apiurl,
prevalenceThreshold,
sMutationsOnly = true,
) => {
const query = CURATED.filter((d) => d.showOnHomepage).map(
(d) => d.char_muts_parent_query,
);
// 2022-11-08: maybe temp: remove the characteristic mutations breakdowns to just show totals
return forkJoin(
...query.map((d) =>
getCumPrevalence(apiurl, `pangolin_lineage=${d}`, 'Worldwide', 0),
),
).pipe(
map((totals) => {
totals = totals.flatMap((d) => d);
// pull out the characteristic mutations and bind to the curated list.
let curated = orderBy(CURATED, ['variantType']);
// loop over each curated report; attach the associated lineages / characteristic mutations with it.
curated.forEach((report) => {
report['showSublineages'] = false;
report['mutations'] = [];
report['mutationsYDomain'] = [];
const total = totals.filter(
(d) => d.mutation_string === report.char_muts_parent_query,
);
report['lineage_count'] =
total.length === 1 ? total[0].lineage_count.toLocaleString() : null;
});
curated = nest()
.key((d) => d.variantType)
.entries(curated);
curated.forEach((d) => {
d['id'] =
d.key === 'Variant of Concern'
? 'voc'
: d.key === 'Variant of Interest'
? 'voi'
: d.key === 'Variant under Monitoring'
? 'vum'
: d.key === 'Previously Circulating Variant of Concern'
? 'previous_voc'
: d.key === 'De-escalated'
? 'deescalated'
: 'unknown';
});
curated = orderBy(curated, [reportTypeSorter], ['asc']);
return {
md: curated,
};
}),
);
// return forkJoin(
// ...query.map((d) =>
// getCharacteristicMutations(
// apiurl,
// d,
// store.state.genomics.characteristicThreshold,
// false,
// ),
// ),
// ).pipe(
// map((charMuts) => {
// // flatten array of objects to a single object.
// charMuts = Object.assign(...charMuts);
//
// // pull out the characteristic mutations and bind to the curated list.
// let curated = orderBy(CURATED, ['variantType']);
// // loop over each curated report; attach the associated lineages / characteristic mutations with it.
// curated.forEach((report) => {
// report['showSublineages'] = false;
// report['mutations'] = Object.keys(charMuts).includes(
// report.char_muts_parent_query,
// )
// ? charMuts[report.char_muts_parent_query]
// : [];
// report['mutationsYDomain'] = uniq(
// report.mutations.map((d) => d.pangolin_lineage),
// );
// report['lineage_count'] = report.mutations[0]
// ? report.mutations[0].lineage_count.toLocaleString()
// : null;
//
// if (sMutationsOnly) {
// report.mutations = report.mutations.filter((d) => d.gene == 'S');
// }
//
// // const prevalentMutations = uniq(report.mutations.filter(d => d.prevalence > prevalenceThreshold).map(d => d.mutation));
// // report.mutations = report.mutations.filter(x => prevalentMutations.includes(x.mutation))
// });
//
// curated = nest()
// .key((d) => d.variantType)
// .entries(curated);
//
// curated.forEach((d) => {
// d['id'] =
// d.key == 'Variant of Concern'
// ? 'voc'
// : d.key == 'Variant of Interest'
// ? 'voi'
// : d.key == 'Variant under Monitoring'
// ? 'vum'
// : d.key == 'Previously Circulating Variant of Concern'
// ? 'previous_voc'
// : d.key == 'De-escalated'
// ? 'deescalated'
// : 'unknown';
// });
//
// curated = orderBy(curated, [reportTypeSorter], ['asc']);
//
// return {
// md: curated,
// };
// }),
// );
};
export const getReportList = (
apiurl,
prevalenceThreshold = store.state.genomics.characteristicThreshold,
) => {
store.state.admin.reportloading = true;
return forkJoin([
getDateUpdated(apiurl),
getCuratedList(apiurl, prevalenceThreshold),
]).pipe(
map(([dateUpdated, md]) => {
return {
...md,
dateUpdated: dateUpdated.lastUpdated,
};
}),
catchError((e) => {
console.log('%c Error in getting report list data!', 'color: red');
console.log(e);
return of([]);
}),
finalize(() => (store.state.admin.reportloading = false)),
);
};
const filterCuratedTypes = (d) => {
return (
(d.variantType === 'Variant of Concern' ||
d.variantType === 'Variant of Interest' ||
d.variantType === 'Mutation of Concern') &&
d.reportType !== 'Lineage + Mutation'
);
};
export const getLocationBasics = (apiurl) => {
store.state.admin.reportloading = true;
let ofInterest = CURATED.filter(
(d) => d.variantType === 'Variant of Concern',
).filter((d) => filterCuratedTypes(d));
ofInterest = orderBy(ofInterest, [locationTableSorter, 'mutation_name']);
const curated = nest()
.key((d) => d.variantType)
.rollup((values) => values.map((d) => d.label))
.entries(ofInterest);
return forkJoin([
getSequenceCount(apiurl, null, true),
getDateUpdated(apiurl),
]).pipe(
map(([total, dateUpdated]) => {
return {
dateUpdated: dateUpdated.lastUpdated,
total: total,
curated: curated,
};
}),
catchError((e) => {
console.log('%c Error in getting report list data!', 'color: red');
console.log(e);
return of([]);
}),
finalize(() => (store.state.admin.reportloading = false)),
);
};
export const buildQueryStr = (
lineageString,
mutationArr,
md = null,
bulkQuery = false,
) => {
let queryStr = '';
if (md) {
if (bulkQuery) {
// curated sequences, which should contain an array of pangolin lineages to join
queryStr += md.reportQuery.pango.join(' OR ');
} else {
queryStr += `pangolin_lineage=${md.reportQuery.pango.join(' OR ')}`;
}
if (mutationArr) {
queryStr += `&mutations=${mutationArr.join(' AND ')}`;
}
} else {
if (lineageString) {
queryStr += `pangolin_lineage=${lineageString}`;
}
// variant reports, e.g. B.1.1.7 + S:E484K
if (lineageString && mutationArr) {
queryStr += `&`;
}
if (mutationArr) {
queryStr += `mutations=${mutationArr.join(' AND ')}`;
}
}
return queryStr;
};
// go back from query string into parameters.
const parseStrQuery = (query) => {
let pango = null;
let muts = [];
const queryPieces = query.split('&');
queryPieces.forEach((d) => {
if (d.includes('pangolin_lineage=')) {
const pango_portion = d.split('pangolin_lineage=');
pango = pango_portion[1];
}
if (d.includes('mutations=')) {
const muts_portion = d.split('mutations=');
muts = muts.concat(muts_portion[1].split(' AND '));
}
});
return {
pango: pango,
muts: muts,
};
};
// Report data for a Situation Report page.
// Returns: date updated, location dictionary metadata, characteristic mutations, lineage/sublineage totals, lineage/sublineage prevalences over time, subnational data for choropleths.
export const getReportData = (
apiurl,
alias,
locations,
mutationArr,
lineageString,
location,
totalThreshold,
ndays,
defaultLocations = ['USA', 'USA_US-CA'],
) => {
store.state.admin.reportloading = true;
// clean up the locations data
// ensure it's an array
locations = typeof locations == 'string' ? [locations] : locations;
// if not specified, use the default
if (!locations) {
locations = defaultLocations;
}
// if "selected" isn't included in the locations, add it.
if (!locations.includes(location)) {
locations.push(location);
}
// add the world
locations.push('Worldwide');
// ensure locations are unique
locations = uniq(locations);
// lookup WHO name in curated dictionary
const filtered = CURATED.filter(
(d) => alias && d.label.toLowerCase() === alias.toLowerCase(),
);
let md;
let queryStr;
// Check if the value exists within the curated list
// pull out the sublineage queries
if (filtered.length === 1) {
md = filtered[0];
queryStr = buildQueryStr(lineageString, mutationArr, md);
} else {
queryStr = buildQueryStr(lineageString, mutationArr);
}
return forkJoin([
getDateUpdated(apiurl),
findAllLocationMetadata(apiurl, locations, location),
getCharacteristicMutations(apiurl, lineageString),
getMutationDetails(apiurl, mutationArr),
getMutationsByLineage(apiurl, mutationArr),
getCumPrevalences(apiurl, queryStr, locations, totalThreshold),
getSublineageTotals(apiurl, md, location),
getTemporalPrevalence(apiurl, location, queryStr, null),
getSublineagePrevalence(apiurl, md, location),
getPositiveLocations(apiurl, queryStr, 'Worldwide'),
getPositiveLocations(apiurl, queryStr, 'USA'),
getLocationPrevalence(apiurl, queryStr, location, ndays),
]).pipe(
map(
([
dateUpdated,
locations,
characteristicMuts,
mutationDetails,
mutationsByLineage,
locPrev,
sublineagePrev,
longitudinal,
longitudinalSublineages,
countries,
states,
choroData,
]) => {
// attach names to cum prevalences
locPrev.forEach((d) => {
const filtered = locations.filter((loc) => loc.id === d.location_id);
if (filtered.length === 1) {
d['name'] = filtered[0].label;
}
});
return {
dateUpdated: dateUpdated,
locations: locations,
locPrev: locPrev,
sublineagePrev: sublineagePrev.data,
sublineageTotalStacked: sublineagePrev.stacked,
longitudinal: longitudinal[0]['data'],
longitudinalSublineages: longitudinalSublineages.longitudinal,
lineagesByDay: longitudinalSublineages.streamgraph,
choroData: choroData,
countries: countries,
states: states,
md: md,
mutations: characteristicMuts,
mutationDetails: mutationDetails,
mutationsByLineage: mutationsByLineage,
};
},
),
catchError((e) => {
console.log('%c Error in getting initial report data!', 'color: red');
console.log(e);
return of([]);
}),
finalize(() => (store.state.admin.reportloading = false)),
);
};
// Only updates the report data for /situation-reports for a change to the choropleth window.
export const updateChoroData = (
apiurl,
alias,
mutationArr,
lineageString,
location,
ndays,
) => {
store.state.admin.reportloading = true;
location = location ? location : 'Worldwide';
// lookup WHO name in curated dictionary
const filtered = CURATED.filter(
(d) => alias && d.label.toLowerCase() === alias.toLowerCase(),
);
let md;
let queryStr;
// Check if the value exists within the curated list
// pull out the sublineage queries
if (filtered.length === 1) {
md = filtered[0];
queryStr = buildQueryStr(lineageString, mutationArr, md);
} else {
queryStr = buildQueryStr(lineageString, mutationArr);
}
return getLocationPrevalence(apiurl, queryStr, location, ndays).pipe(
map((d) => {
return d;
}),
catchError((e) => {
console.log('%c Error in updating choropleth data!', 'color: red');
console.log(e);
return of([]);
}),
finalize(() => (store.state.admin.reportloading = false)),
);
};
export const getSublineageTotals = (apiurl, md, location) => {
if (md && md.pango_descendants) {
const queryStr = `pangolin_lineage=${md.pango_descendants.join(',')}`;
return getCumPrevalence(apiurl, queryStr, location, 0).pipe(
map((results) => {
// sort in descending order of frequency
results.sort((a, b) => b.lineage_count - a.lineage_count);
const stacked = results.map((d) => {
const obj = {};
obj[d.mutation_string] = d.lineage_count;
return obj;
});
return {
data: results,
stacked: Object.assign(...stacked),
};
}),
catchError((e) => {
console.log(
`%c Error in getting sublineage cumulative prevalence data!`,
'color: red',
);
console.log(e);
return of([]);
}),
);
}
return of([]);
};
export const getSublineagePrevalence = (apiurl, md, location) => {
if (md) {
const queryStr = `pangolin_lineage=${md.pango_descendants.join(',')}`;
return getTemporalPrevalence(apiurl, location, queryStr).pipe(
map((results) => {
results = results.filter((d) => d);
const nested = nest()
.key((d) => d.date)
.rollup((values) => {
const total = sum(values, (d) => d.lineage_count_rolling);
// loop over the values for each day
return values.map((value) => {
let obj = {};
// calculate the percent total of that given day
obj[value.mutation_string] = total
? value.lineage_count_rolling / total
: 0;
return obj;
});
})
.entries(results.flatMap((d) => d.data))
.map((d) => {
return {
date_time: parseDate(d.key),
...Object.assign(...d.value),
};
});
// fill in the zeros, or the streamgraph will look busted
// and will only show the lineages appearing on the first date.
const lineageDomain = results.map((d) => d.label);
nested.forEach((date_obj) => {
lineageDomain.forEach((lineage) => {
if (!Object.keys(date_obj).includes(lineage)) {
date_obj[lineage] = 0;
}
});
});
nested.sort((a, b) => a.date_time - b.date_time);
return {
longitudinal: results,
streamgraph: nested,
};
}),
catchError((e) => {
console.log(
'%c Error in getting prevalence of sublineages over time!',
'color: red',
);
console.log(e);
return of([]);
}),
);
}
return of([]);
};
export const updateLocationData = (
apiurl,
alias,
mutationArr,
lineageString,
locations,
location,
totalThreshold,
ndays,
) => {
// lookup WHO name in curated dictionary
const filtered = CURATED.filter(
(d) => alias && d.label.toLowerCase() === alias.toLowerCase(),
);
let md;
let queryStr;
// Check if the value exists within the curated list
if (filtered.length === 1) {
md = filtered[0];
queryStr = buildQueryStr(lineageString, mutationArr, md);
} else {
queryStr = buildQueryStr(lineageString, mutationArr);
}
store.state.admin.reportloading = true;
if (!locations || !locations.length) {
locations = [location];
}
if (typeof locations == 'string') {
locations = [locations];
}
locations.push('Worldwide');
// ensure locations are unique
locations = uniq(locations);
return forkJoin([
findAllLocationMetadata(apiurl, locations, location),
getTemporalPrevalence(apiurl, location, queryStr, null),
getLocationPrevalence(apiurl, queryStr, location, ndays),
getCumPrevalences(apiurl, queryStr, locations, totalThreshold),
getSublineageTotals(apiurl, md, location),
getSublineagePrevalence(apiurl, md, location),
]).pipe(
map(
([
locations,
longitudinal,
byLocation,
locPrev,
sublineagePrev,
longitudinalSublineages,
]) => {
// attach names to cum prevalences
locPrev.forEach((d) => {
const filtered = locations.filter((loc) => loc.id === d.location_id);
if (filtered.length === 1) {
d['name'] = filtered[0].label;
}
});
return {
locations: locations,
longitudinal: longitudinal[0]['data'],
longitudinalSublineages: longitudinalSublineages.longitudinal,
lineagesByDay: longitudinalSublineages.streamgraph,
byCountry: byLocation,
locPrev: locPrev,
sublineagePrev: sublineagePrev.data,
sublineageTotalStacked: sublineagePrev.stacked,
};
},
),
catchError((e) => {
console.log('%c Error in updating report location data!', 'color: red');
console.log(e);
return of([]);
}),
finalize(() => (store.state.admin.reportloading = false)),
);
};
export const getMutationDetails = (apiurl, mutationString) => {
if (!mutationString) return of([]);
const url = `${apiurl}mutation-details?mutations=${mutationString}`;
return from(
axios.get(url, {
headers: {
'Content-Type': 'application/json',
},
}),
).pipe(
pluck('data', 'results'),
map((results) => {
return results;
}),
catchError((e) => {
console.log('%c Error in getting mutation details!', 'color: red');
console.log(e);
return of([]);
}),
);
};
export const getMutationsByLineage = (
apiurl,
mutationArr,
proportionThreshold = 0,
returnFlat = true,
andLogic = false,
) => {
if (!mutationArr) return of([]);
const queryStr = andLogic ? mutationArr.join(' AND ') : mutationArr.join(',');
const url = `${apiurl}mutations-by-lineage?mutations=${queryStr}&frequency=${proportionThreshold}`;
return from(
axios.get(url, {
headers: {
'Content-Type': 'application/json',
},
}),
).pipe(
pluck('data', 'results'),
map((results) => {
if (returnFlat) {
let res = Object.keys(results).map((mutation_key) =>
results[mutation_key].map((d) => {
d['mutation_string'] = mutation_key;
d['pangolin_lineage'] = d['pangolin_lineage'].toUpperCase();
d['proportion_formatted'] =
d.proportion >= 0.005 ? formatPercent(d['proportion']) : '< 0.5%';
return d;
}),
);
return [].concat(...res);
} else {
Object.keys(results).forEach((mutation_key) => {
results[mutation_key].sort((a, b) =>
a.pangolin_lineage < b.pangolin_lineage ? -1 : 1,
);
});
return results;
}
}),
catchError((e) => {
console.log('%c Error in getting mutations by lineage!', 'color: red');
console.log(e);
return of([]);
}),
);
};
const cleanSelectors = (id) => {
return id
.replace(/:/g, '_')
.replace(/\//g, '_')
.replace(/\*\s\[/g, '_')
.replace(/\s\(/g, '_')
.replace(/\)\]/g, '_')
.replace(/\s\+\s/g, '--')
.replace(/:/g, '_')
.replace(/\*/g, 'stop')
.replace(/\(/g, '')
.replace(/\)/g, '')
.replace(/\./g, '-')