forked from malariagen/malariagen-data-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsample_metadata.py
More file actions
1889 lines (1650 loc) · 74 KB
/
Copy pathsample_metadata.py
File metadata and controls
1889 lines (1650 loc) · 74 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 difflib
import io
import json
import re
from itertools import cycle
from typing import (
Any,
Callable,
DefaultDict,
Dict,
List,
Mapping,
Optional,
Sequence,
Tuple,
Union,
)
from collections import defaultdict
import warnings
import ipyleaflet # type: ignore
import numpy as np
import pandas as pd
import plotly.express as px # type: ignore
from numpydoc_decorator import doc # type: ignore
from ..util import _check_types
from . import base_params, map_params, plotly_params
from .base import AnophelesBase
class AnophelesSampleMetadata(AnophelesBase):
def __init__(
self,
cohorts_analysis: Optional[str] = None,
aim_analysis: Optional[str] = None,
aim_metadata_dtype: Optional[Mapping[str, Any]] = None,
taxon_colors: Optional[Mapping[str, str]] = None,
aim_species_colors: Optional[Mapping[str, str]] = None,
**kwargs,
):
# N.B., this class is designed to work cooperatively, and
# so it's important that any remaining parameters are passed
# to the superclass constructor.
super().__init__(**kwargs)
# If provided, this analysis version will override the
# default value provided in the release configuration.
self._cohorts_analysis_override = cohorts_analysis
# If provided, this analysis version will override the
# default value provided in the release configuration.
self._aim_analysis_override = aim_analysis
# N.B., the expected AIM metadata columns may vary between
# data resources, and so column names and dtype need to be
# passed in as parameters.
self._aim_metadata_columns: Optional[List[str]] = None
self._aim_metadata_dtype: Optional[Mapping[str, Any]] = {}
# Only apply the `aim_metadata_dtype` if it is a type of `Mapping`.
if isinstance(aim_metadata_dtype, Mapping):
# Convert all of the column names to lowercase.
prepared_aim_metadata_dtype_dict = {
k.lower(): v for k, v in aim_metadata_dtype.items()
}
# Get all the column names from the prepared dict.
self._aim_metadata_columns = list(prepared_aim_metadata_dtype_dict.keys())
# Update the _aim_metadata_dtype with the prepared dict.
self._aim_metadata_dtype.update(prepared_aim_metadata_dtype_dict)
# Add the sample_id to the _aim_metadata_dtype.
self._aim_metadata_dtype["sample_id"] = "object"
# Set up taxon colors.
self._taxon_colors = taxon_colors
self._aim_species_colors = aim_species_colors
# Set up extra metadata.
self._extra_metadata: List = []
# Initialize cache attributes.
self._cache_sample_metadata: Dict = dict()
self._cache_cohorts: Dict = dict()
self._cache_cohort_geometries: Dict = dict()
def _metadata_paths(
self,
*,
sample_sets: List[str],
path_template: str,
aim_analysis: Optional[str] = None,
cohorts_analysis: Optional[str] = None,
) -> Dict[str, str]:
paths = dict()
for sample_set in sample_sets:
release = self.lookup_release(sample_set=sample_set)
release_path = self._release_to_path(release=release)
if aim_analysis:
path = path_template.format(
release_path=release_path,
sample_set=sample_set,
aim_analysis=aim_analysis,
)
elif cohorts_analysis:
path = path_template.format(
release_path=release_path,
sample_set=sample_set,
cohorts_analysis=cohorts_analysis,
)
else:
path = path_template.format(
release_path=release_path, sample_set=sample_set
)
paths[sample_set] = path
return paths
def _parse_metadata_paths(
self,
path_template: str,
parse_metadata_func: Callable[[str, Union[bytes, Exception]], pd.DataFrame],
sample_sets: List[str],
aim_analysis: Optional[str] = None,
cohorts_analysis: Optional[str] = None,
) -> pd.DataFrame:
# Note: we don't use `_prep_sample_sets_param` in this function because that can cause a circular dependency, eventually raising a `RecursionError`.
# For instance, `_prep_sample_sets_param` uses `_relevant_sample_sets`, which uses `_surveillance_flags`, which uses `_parse_metadata_paths`.
# Instead, use `_prep_sample_sets_param` to prepare `sample_sets` as a `List[str]` before passing it to this function.
# Obtain paths for all files we need to fetch.
file_paths: Mapping[str, str] = self._metadata_paths(
sample_sets=sample_sets,
path_template=path_template,
aim_analysis=aim_analysis,
cohorts_analysis=cohorts_analysis,
)
# Fetch all files. N.B., here is an optimisation, this allows us to fetch
# multiple files concurrently.
files: Mapping[str, Union[bytes, Exception]] = self.read_files(
paths=file_paths.values(), on_error="return"
)
# Parse files into DataFrames.
dfs = []
for sample_set in sample_sets:
path = file_paths[sample_set]
data = files[path]
df = parse_metadata_func(sample_set, data)
dfs.append(df)
# Concatenate all DataFrames.
df_ret = pd.concat(dfs, axis=0, ignore_index=True)
return df_ret
def _parse_general_metadata(
self, sample_set: str, data: Union[bytes, Exception]
) -> pd.DataFrame:
if isinstance(data, bytes):
dtype_dict = {
"sample_id": "object",
"partner_sample_id": "object",
"contributor": "object",
"country": "object",
"location": "object",
"year": "int64",
"month": "int64",
"latitude": "float64",
"longitude": "float64",
"sex_call": "object",
}
# `dict[str, str]` is incompatible with the `dtype` of `pd.read_csv`
dtype: DefaultDict[str, str] = defaultdict(lambda: "object", dtype_dict)
df = pd.read_csv(io.BytesIO(data), dtype=dtype, na_values="")
# Ensure all column names are lower case.
df.columns = [c.lower() for c in df.columns] # type: ignore
# Add a couple of columns for convenience.
df["sample_set"] = sample_set
release = self.lookup_release(sample_set=sample_set)
df["release"] = release
# Derive a quarter column from month.
# Vectorized operation: quarter = ((month - 1) // 3) + 1 if month > 0 else -1
df["quarter"] = np.where(df["month"] > 0, ((df["month"] - 1) // 3) + 1, -1)
# Add study columns.
study_info = self.lookup_study_info(sample_set=sample_set)
for column in study_info:
df[column] = study_info[column]
# Add terms-of-use columns.
terms_of_use_info = self.lookup_terms_of_use_info(sample_set=sample_set)
for column in terms_of_use_info:
df[column] = terms_of_use_info[column]
return df
else:
raise data
@_check_types
@doc(
summary="""
Read general sample metadata for one or more sample sets into a pandas
DataFrame.
""",
returns="A pandas DataFrame, one row per sample.",
)
def general_metadata(
self, sample_sets: Optional[base_params.sample_sets] = None
) -> pd.DataFrame:
prepared_sample_sets = self._prep_sample_sets_param(sample_sets=sample_sets)
del sample_sets
return self._parse_metadata_paths(
path_template="{release_path}/metadata/general/{sample_set}/samples.meta.csv",
parse_metadata_func=self._parse_general_metadata,
sample_sets=prepared_sample_sets,
)
@property
def _sequence_qc_metadata_dtype(self):
# Note: tests expect an ordered dictionary.
# Note: insertion order in dictionary keys is guaranteed since Python 3.7
# Note: using nullable dtypes (e.g. Int64 instead of int64) to allow missing data.
dtype = {
"sample_id": "object",
"mean_cov": "Float64",
"median_cov": "Int64",
"modal_cov": "Int64",
}
for contig in sorted(self.config["CONTIGS"]):
dtype[f"mean_cov_{contig}"] = "Float64"
dtype[f"median_cov_{contig}"] = "Int64"
dtype[f"mode_cov_{contig}"] = "Int64"
dtype.update(
{
"frac_gen_cov": "Float64",
"divergence": "Float64",
"contam_pct": "Float64",
"contam_LLR": "Float64",
}
)
return dtype
def _parse_sequence_qc_metadata(
self, sample_set: str, data: Union[bytes, Exception]
) -> pd.DataFrame:
if isinstance(data, bytes):
# Get the dtype of the constant columns.
dtype_dict = self._sequence_qc_metadata_dtype
# `dict[str, str]` is incompatible with the `dtype` of `pd.read_csv`
dtype: DefaultDict[str, str] = defaultdict(lambda: "object", dtype_dict)
# Read the CSV using the dtype dict.
df = pd.read_csv(io.BytesIO(data), dtype=dtype, na_values="")
return df
elif isinstance(data, FileNotFoundError):
# Sequence QC metadata are missing for this sample set,
# so return a blank DataFrame.
# Copy the sample ids from the general metadata.
df_general = self.general_metadata(sample_sets=sample_set)
df = df_general[["sample_id"]].copy()
# Add the sequence QC columns with appropriate missing values.
# For each column, set the value to either NA or NaN.
for c, datum_dtype in self._sequence_qc_metadata_dtype.items():
if pd.api.types.is_integer_dtype(datum_dtype):
# Note: this creates a column with dtype int64.
df[c] = -1
else:
# Note: this creates a column with dtype float64.
df[c] = np.nan
# Set the column data types.
df = df.astype(self._sequence_qc_metadata_dtype)
return df
else:
raise data
@_check_types
@doc(
summary="""
Access sequence QC metadata for one or more sample sets.
""",
returns="""A pandas DataFrame, one row per sample. The columns are:
`sample_id` is the identifier of the sample,
`partner_sample_id` is the identifier of the sample used by the partners who contributed it,
`contributor` is the partner who contributed the sample,
`country` is the country the sample was collected in,
`location` is the location the sample was collected in,
`year` is the year the sample was collected,
`month` is the month the sample was collected,
`latitude` is the latitude of the location the sample was collected in,
`longitude` is the longitude of the location the sample was collected in,
`sex_call` is the sex of the sample,
`sample_set` is the sample set containing the sample,
`release` is the release containing the sample,
`quarter` is the quarter of the year the sample was collected,
`study_id* is the identifier of the study the sample set containing the sample came from,
`study_url` is the URL of the study the sample set containing the sample came from,
`terms_of_use_expiry_date` is the date the terms of use for the sample expire,
`terms_of_use_url` is the URL of the terms of use for the sample,
`unrestricted_use` indicates whether the sample can be used without restrictions (e.g., if the terms of use of expired),
`mean_cov` is mean value of the coverage,
`median_cov` is the median value of the coverage,
`modal_cov` is the mode of the coverage,
`mean_cov_2L` is mean value of the coverage on 2L,
`median_cov_2L` is the median value of the coverage on 2L,
`mode_cov_2L` is the mode of the coverage on 2L,
`mean_cov_2R` is mean value of the coverage on 2R,
`median_cov_2R` is the median value of the coverage on 2R,
`mode_cov_2R` is the mode of the coverage on 2R,
`mean_cov_3L` is mean value of the coverage on 3L,
`median_cov_3L` is the median value of the coverage on 3L,
`mode_cov_3L` is the mode of the coverage on 3L,
`mean_cov_3R` is mean value of the coverage on 3R,
`median_cov_3R` is the median value of the coverage on 3R,
`mode_cov_3R` is the mode of the coverage on 3R,
`mean_cov_X` is mean value of the coverage on X,
`median_cov_X` is the median value of the coverage on X,
`mode_cov_X` is the mode of the coverage on X,
`frac_gen_cov` is the faction of the genome covered,
`divergence` is the divergence,
`contam_pct` is the percentage of contamination,
`contam_LLR` is the log-likelihood ratio of contamination,
`aim_species_fraction_arab` is the fraction of the gambcolu vs. arabiensis AIMs that indicated arabiensis (this column is only present for *Ag3*),
`aim_species_fraction_colu` is the fraction of the gambiae vs. coluzzii AIMs that indicated coluzzii (this column is only present for *Ag3*),
`aim_species_fraction_colu_no2l` is the fraction of the gambiae vs. coluzzii AIMs that indicated coluzzii, not including the chromosome arm 2L which contains an introgression (this column is only present for *Ag3*),
`aim_species_gambcolu_arabiensis` is the taxonomic group assigned by the gambcolu vs. arabiensis AIMs (this column is only present for *Ag3*),
`aim_species_gambiae_coluzzi` is the taxonomic group assigned by the gambiae vs. coluzzii AIMs (this column is only present for *Ag3*),
`aim_species_gambcolu_arabiensis` is the taxonomic group assigned by the combination of both AIMs analyses (this column is only present for *Ag3*),
`country_iso` is the ISO code of the country the sample was collected in,
`admin1_name` is the name of the first administrative level the sample was collected in,
`admin1_iso` is the ISO code of the first administrative level the sample was collected in,
`admin2_name` is the name of the second administrative level the sample was collected in,
`taxon` is the taxon assigned to the sample by the combination of the AIMs analysis and the cohort analysis,
`cohort_admin1_year` is the cohort the sample belongs to when samples are grouped by first administrative level and year,
`cohort_admin1_month` is the cohort the sample belongs to when samples are grouped by first administrative level and month,
`cohort_admin1_quarter` is the cohort the sample belongs to when samples are grouped by first administrative level and quarter,
`cohort_admin2_year` is the cohort the sample belongs to when samples are grouped by second administrative level and year,
`cohort_admin2_month` is the cohort the sample belongs to when samples are grouped by second administrative level and month,
`cohort_admin2_quarter` is the cohort the sample belong to when samples are grouped by second administrative level and quarter.
""",
)
def sequence_qc_metadata(
self, sample_sets: Optional[base_params.sample_sets] = None
) -> pd.DataFrame:
prepared_sample_sets = self._prep_sample_sets_param(sample_sets=sample_sets)
del sample_sets
return self._parse_metadata_paths(
path_template="{release_path}/metadata/curation/{sample_set}/sequence_qc_stats.csv",
parse_metadata_func=self._parse_sequence_qc_metadata,
sample_sets=prepared_sample_sets,
)
def _parse_surveillance_flags(
self, sample_set: str, data: Union[bytes, Exception]
) -> pd.DataFrame:
# Get the current warning filters.
original_warning_filters = warnings.filters[:]
# Specify the expected data type for each column.
# Note: "bool" is not nullable and does not support `NaN`, which is required when missing data.
# Otherwise `NaN` will be mis-translated to `True` when the dtype is applied to the DataFrame.
dtype_dict = {
"sample_id": "object",
"is_surveillance": "boolean",
}
# `dict[str, str]` is incompatible with the `dtype` of `pd.read_csv`
dtype: DefaultDict[str, str] = defaultdict(lambda: "object", dtype_dict)
if isinstance(data, bytes):
# Read the CSV data.
df = pd.read_csv(io.BytesIO(data), dtype=dtype, na_values="")
# If there are any nulls in these data, show a warning.
if df.isnull().values.any():
# Trigger the warning.
warnings.simplefilter("default", UserWarning)
warnings.warn(
f"WARNING: The surveillance flags data contains null values for sample set {sample_set}",
UserWarning,
)
# Restore the original warning filters.
warnings.filters = original_warning_filters
# Ensure all column names are lower case.
df.columns = [c.lower() for c in df.columns] # type: ignore
return df
elif isinstance(data, FileNotFoundError):
# Surveillance flags are missing for this sample set.
# Show a warning and return a blank DataFrame.
# Trigger the warning.
warnings.simplefilter("default", UserWarning)
warnings.warn(
f"WARNING: The surveillance flags data is missing for sample set {sample_set}",
UserWarning,
)
# Restore the original warning filters.
warnings.filters = original_warning_filters
# Get a copy of the sample ids.
df_general = self.general_metadata(sample_sets=sample_set)
df = df_general[["sample_id"]].copy()
# Set each column value to null.
df["is_surveillance"] = np.nan
# Set the data type.
df = df.astype(dtype)
return df
else:
raise data
@_check_types
@doc(
summary="""
Access surveillance flags for one or more sample sets.
""",
parameters=dict(
sample_sets="List of sample sets.",
),
returns="""A pandas DataFrame, one row per sample. The columns are:
`sample_id` is the identifier of the sample,
`is_surveillance` indicates whether the sample can be used for surveillance,
""",
)
def _surveillance_flags(self, sample_sets: List[str]) -> pd.DataFrame:
# Note: we don't use `_prep_sample_sets_param` in this function because that can cause a circular dependency, eventually raising a `RecursionError`.
# For instance, `_prep_sample_sets_param` uses `_relevant_sample_sets`, which uses `_surveillance_flags`.
# Instead, use `_prep_sample_sets_param` to prepare `sample_sets` as a `List[str]` before passing it to this function.
return self._parse_metadata_paths(
path_template="{release_path}/metadata/general/{sample_set}/surveillance.flags.csv",
parse_metadata_func=self._parse_surveillance_flags,
sample_sets=sample_sets,
)
@property
def _cohorts_analysis(self):
if self._cohorts_analysis_override:
return self._cohorts_analysis_override
else:
# N.B., this will return None if the key is not present in the
# config.
return self.config.get("DEFAULT_COHORTS_ANALYSIS")
@property
def _cohorts_metadata_columns(self):
# Handle changes to columns used in different analyses.
cols = None
if self._cohorts_analysis:
if self._cohorts_analysis < "20230223":
cols = (
"country_iso",
"admin1_name",
"admin1_iso",
"admin2_name",
"taxon",
"cohort_admin1_year",
"cohort_admin1_month",
"cohort_admin2_year",
"cohort_admin2_month",
)
# We assume that cohorts analyses from "20230223" onwards always include quarter
# columns.
else:
cols = (
"country_iso",
"admin1_name",
"admin1_iso",
"admin2_name",
"taxon",
"cohort_admin1_year",
"cohort_admin1_month",
"cohort_admin1_quarter",
"cohort_admin2_year",
"cohort_admin2_month",
"cohort_admin2_quarter",
)
return cols
@property
def _cohorts_metadata_dtype(self):
cols = self._cohorts_metadata_columns
if cols:
# All columns are string columns.
dtype = {c: "object" for c in cols}
dtype["sample_id"] = "object"
return dtype
def _parse_cohorts_metadata(
self, sample_set: str, data: Union[bytes, Exception]
) -> pd.DataFrame:
if isinstance(data, bytes):
# Parse CSV data.
dtype_dict = self._cohorts_metadata_dtype
# `dict[str, str]` is incompatible with the `dtype` of `pd.read_csv`
dtype: DefaultDict[str, str] = defaultdict(lambda: "object", dtype_dict)
df = pd.read_csv(io.BytesIO(data), dtype=dtype, na_values="")
# Ensure all column names are lower case.
df.columns = [c.lower() for c in df.columns] # type: ignore
# Rename some columns for consistent naming.
df.rename(
columns={
"adm1_iso": "admin1_iso",
"adm1_name": "admin1_name",
"adm2_name": "admin2_name",
},
inplace=True,
)
return df
elif isinstance(data, FileNotFoundError):
# Cohorts metadata are missing for this sample set, fill with a blank
# DataFrame.
df_general = self.general_metadata(sample_sets=sample_set)
df = df_general[["sample_id"]].copy()
for c in self._cohorts_metadata_columns:
df[c] = np.nan
df = df.astype(self._cohorts_metadata_dtype)
return df
else:
raise data
def _require_cohorts_analysis(self):
if not self._cohorts_analysis:
raise NotImplementedError(
"Cohorts data not available for this data resource."
)
@_check_types
@doc(
summary="""
Access cohort membership metadata for one or more sample sets.
""",
returns="A pandas DataFrame, one row per sample.",
)
def cohorts_metadata(
self, sample_sets: Optional[base_params.sample_sets] = None
) -> pd.DataFrame:
self._require_cohorts_analysis()
prepared_sample_sets = self._prep_sample_sets_param(sample_sets=sample_sets)
del sample_sets
return self._parse_metadata_paths(
path_template="{release_path}/metadata/cohorts_{cohorts_analysis}/{sample_set}/samples.cohorts.csv",
parse_metadata_func=self._parse_cohorts_metadata,
sample_sets=prepared_sample_sets,
cohorts_analysis=self._cohorts_analysis,
)
@property
def _aim_analysis(self):
if self._aim_analysis_override:
return self._aim_analysis_override
else:
# N.B., this will return None if the key is not present in the
# config.
return self.config.get("DEFAULT_AIM_ANALYSIS")
def _parse_aim_metadata(
self, sample_set: str, data: Union[bytes, Exception]
) -> pd.DataFrame:
assert self._aim_metadata_columns is not None
assert self._aim_metadata_dtype is not None
if isinstance(data, bytes):
# Parse CSV data but don't apply the dtype yet.
df = pd.read_csv(io.BytesIO(data), na_values="")
# Convert all column names to lowercase.
df.columns = [c.lower() for c in df.columns] # type: ignore
# For each column in the DataFrame...
for c in df.columns:
# Apply the corresponding dtype from `_aim_metadata_dtype`.
# Convert the type to a NumPy dtype.
col_dtype_as_np = np.dtype(self._aim_metadata_dtype[c])
df[c] = df[c].astype(col_dtype_as_np)
return df
elif isinstance(data, FileNotFoundError):
# AIM data are missing for this sample set, fill with a blank DataFrame.
df_general = self.general_metadata(sample_sets=sample_set)
df = df_general[["sample_id"]].copy()
for c in self._aim_metadata_columns:
df[c] = np.nan
df = df.astype(self._aim_metadata_dtype)
return df
else:
raise data
def _require_aim_analysis(self):
if not self._aim_analysis:
raise NotImplementedError("AIM data not available for this data resource.")
@_check_types
@doc(
summary="""
Access ancestry-informative marker (AIM) metadata for one or more
sample sets.
""",
returns="A pandas DataFrame, one row per sample.",
)
def aim_metadata(
self, sample_sets: Optional[base_params.sample_sets] = None
) -> pd.DataFrame:
self._require_aim_analysis()
prepared_sample_sets = self._prep_sample_sets_param(sample_sets=sample_sets)
del sample_sets
return self._parse_metadata_paths(
path_template="{release_path}/metadata/species_calls_aim_{aim_analysis}/{sample_set}/samples.species_aim.csv",
parse_metadata_func=self._parse_aim_metadata,
sample_sets=prepared_sample_sets,
aim_analysis=self._aim_analysis,
)
@_check_types
@doc(
summary="""
Add extra sample metadata, e.g., including additional columns
which you would like to use to query and group samples.
""",
parameters=dict(
data="""
A data frame with one row per sample. Must include either a
"sample_id" or "partner_sample_id" column.
""",
on="""
Name of column to use when merging with sample metadata.
""",
),
notes="""
The values in the column containing sample identifiers must be
unique.
""",
)
def add_extra_metadata(self, data: pd.DataFrame, on: str = "sample_id"):
# Check parameters.
if not isinstance(data, pd.DataFrame):
raise TypeError("`data` parameter must be a pandas DataFrame")
if on not in data.columns:
raise ValueError(f"dataframe does not contain column {on!r}")
if on not in {"sample_id", "partner_sample_id"}:
raise ValueError(
"`on` parameter must be either 'sample_id' or 'partner_sample_id'"
)
# Check for uniqueness.
if not data[on].is_unique:
raise ValueError(f"column {on!r} does not have unique values")
# check there are matching samples.
df_samples = self.sample_metadata()
loc_isec = data[on].isin(df_samples[on])
if not loc_isec.any():
raise ValueError("no matching samples found")
# store extra metadata
self._extra_metadata.append((on, data.copy()))
@doc(
summary="Clear any extra metadata previously added",
)
def clear_extra_metadata(self):
self._extra_metadata = []
@_check_types
@doc(
summary="Access sample metadata for one or more sample sets.",
returns="A dataframe of sample metadata, one row per sample.",
notes="""
Some samples in the dataset are lab crosses — mosquitoes bred in
the laboratory that have no real collection date. These samples
use ``year=-1`` and ``month=-1`` as sentinel values. They may
cause unexpected results in date-based analyses (e.g.,
``pd.to_datetime`` will fail on negative year values).
To exclude lab cross samples, use::
df = api.sample_metadata(sample_query="year >= 0")
""",
)
def sample_metadata(
self,
sample_sets: Optional[base_params.sample_sets] = None,
sample_query: Optional[base_params.sample_query] = None,
sample_query_options: Optional[base_params.sample_query_options] = None,
sample_indices: Optional[base_params.sample_indices] = None,
) -> pd.DataFrame:
# Check that either sample_query xor sample_indices are provided.
base_params._validate_sample_selection_params(
sample_query=sample_query, sample_indices=sample_indices
)
# Prepare parameters.
prepared_sample_sets = self._prep_sample_sets_param(sample_sets=sample_sets)
prepared_sample_query = self._prep_sample_query_param(sample_query=sample_query)
# Delete original parameters to prevent accidental use.
del sample_sets
del sample_query
# Determine the cache key.
cache_key = tuple(prepared_sample_sets)
try:
# Attempt to retrieve from the cache.
df_samples = self._cache_sample_metadata[cache_key]
except KeyError:
with self._spinner(desc="Load sample metadata"):
## Build a single DataFrame using all available metadata.
# Get the general sample metadata.
# Note: this includes study and terms-of-use info.
df_samples = self.general_metadata(sample_sets=prepared_sample_sets)
# Merge with the sequence QC metadata.
# Note: merging can change column dtypes, e.g. due to new NaNs.
df_sequence_qc = self.sequence_qc_metadata(
sample_sets=prepared_sample_sets
)
df_samples = df_samples.merge(
df_sequence_qc, on="sample_id", sort=False, how="left"
)
# Merge with the surveillance flags.
# Note: merging can change column dtypes, e.g. due to new NaNs.
df_surveillance_flags = self._surveillance_flags(
sample_sets=prepared_sample_sets
)
df_samples = df_samples.merge(
df_surveillance_flags, on="sample_id", sort=False, how="left"
)
# If available, merge with the AIM metadata.
if self._aim_analysis:
df_aim = self.aim_metadata(sample_sets=prepared_sample_sets)
df_samples = df_samples.merge(
df_aim, on="sample_id", sort=False, how="left"
)
# If available, merge with the cohorts metadata.
if self._cohorts_analysis:
df_cohorts = self.cohorts_metadata(sample_sets=prepared_sample_sets)
df_samples = df_samples.merge(
df_cohorts, on="sample_id", sort=False, how="left"
)
# Store sample metadata in the cache.
self._cache_sample_metadata[cache_key] = df_samples
# Add extra metadata.
for on, data in self._extra_metadata:
df_samples = df_samples.merge(data, how="left", on=on)
# Apply the sample_query, if there is one.
# Note: this might have been internally modified, e.g. `is_surveillance == True`.
if prepared_sample_query is not None:
# Assume a pandas query string.
sample_query_options = sample_query_options or {}
# Save a reference to the pre-query DataFrame so we can detect
# zero-result queries and provide a helpful warning.
df_before_query = df_samples
# Use the python engine in order to support extension array dtypes, e.g. Float64, Int64, boolean.
df_samples = df_samples.query(
prepared_sample_query, **sample_query_options, engine="python"
)
df_samples = df_samples.reset_index(drop=True)
# Warn if query returned zero results on a non-empty dataset.
# Provide fuzzy-match suggestions so users can spot typos,
# case mismatches, or partial-value issues.
if len(df_samples) == 0 and len(df_before_query) > 0:
hint_lines = [
f"sample_metadata() returned 0 samples for query: {prepared_sample_query!r}.",
]
# Extract column == 'value' pairs from the query.
col_val_pairs = re.findall(
r"\b(\w+)\s*==\s*['\"]([^'\"]+)['\"]",
prepared_sample_query,
)
for col_name, queried_val in col_val_pairs:
# If the column name is not recognised, suggest
# close column names.
if col_name not in df_before_query.columns:
close_cols = difflib.get_close_matches(
col_name,
df_before_query.columns.tolist(),
n=3,
cutoff=0.6,
)
if close_cols:
hint_lines.append(
f"Column {col_name!r} not found. "
f"Did you mean: {close_cols}?"
)
continue
# For string columns, suggest close values.
if df_before_query[col_name].dtype == object:
valid_vals = (
df_before_query[col_name].dropna().unique().tolist()
)
close_vals = difflib.get_close_matches(
queried_val, valid_vals, n=5, cutoff=0.6
)
if close_vals:
hint_lines.append(
f"Value {queried_val!r} not found in "
f"column {col_name!r}. "
f"Did you mean: {close_vals}?"
)
warnings.warn("\n".join(hint_lines), UserWarning, stacklevel=2)
# Apply the sample_indices, if there are any.
# Note: this might need to apply to the result of an internal sample_query, e.g. `is_surveillance == True`.
if sample_indices is not None:
# Assume it is an indexer.
df_samples = df_samples.iloc[sample_indices]
df_samples = df_samples.reset_index(drop=True)
return df_samples.copy()
@_check_types
@doc(
summary="""
Create a pivot table showing numbers of samples available by space,
time and taxon.
""",
parameters=dict(
index="Sample metadata columns to use for the pivot table index.",
columns="Sample metadata columns to use for the pivot table columns.",
),
returns="Pivot table of sample counts. One row per admin2_year cohort. Unless otherwise specified using the `columns` parameters, the samples are grouped according to their taxon and then counted.",
)
def count_samples(
self,
sample_sets: Optional[base_params.sample_sets] = None,
sample_query: Optional[base_params.sample_query] = None,
sample_query_options: Optional[base_params.sample_query_options] = None,
sample_indices: Optional[base_params.sample_indices] = None,
index: Union[str, Sequence[str]] = (
"country",
"admin1_iso",
"admin1_name",
"admin2_name",
"year",
),
columns: Union[str, Sequence[str]] = "taxon",
) -> pd.DataFrame:
# Load sample metadata.
df_samples = self.sample_metadata(
sample_sets=sample_sets,
sample_query=sample_query,
sample_query_options=sample_query_options,
sample_indices=sample_indices,
)
# Create pivot table.
df_pivot = df_samples.pivot_table(
index=index,
columns=columns,
values="sample_id",
aggfunc="count",
fill_value=0,
)
return df_pivot
@_check_types
@doc(
summary="""
Plot an interactive map showing sampling locations using ipyleaflet.
""",
parameters=dict(
min_samples="""
Minimum number of samples required to show a marker for a given
location.
""",
count_by="""
Metadata column to report counts of samples by for each location.
""",
),
returns="Ipyleaflet map widget.",
)
def plot_samples_interactive_map(
self,
sample_sets: Optional[base_params.sample_sets] = None,
sample_query: Optional[base_params.sample_query] = None,
sample_query_options: Optional[base_params.sample_query_options] = None,
sample_indices: Optional[base_params.sample_indices] = None,
basemap: Optional[map_params.basemap] = map_params.basemap_default,
center: map_params.center = map_params.center_default,
zoom: map_params.zoom = map_params.zoom_default,
height: map_params.height = map_params.height_default,
width: map_params.width = map_params.width_default,
min_samples: int = 1,
count_by: str = "taxon",
) -> ipyleaflet.Map:
# Normalise height and width to string
if isinstance(height, int):
height = f"{height}px"
if isinstance(width, int):
width = f"{width}px"
# Load sample metadata.
df_samples = self.sample_metadata(
sample_sets=sample_sets,
sample_query=sample_query,
sample_query_options=sample_query_options,
sample_indices=sample_indices,
)
# Pivot taxa by locations.
location_composite_key = [
"country",
"admin1_iso",
"admin1_name",
"admin2_name",
"location",
"latitude",
"longitude",
]
df_pivot = df_samples.pivot_table(
index=location_composite_key,
columns=count_by,
values="sample_id",
aggfunc="count",
fill_value=0,
)
# Append aggregations to pivot.
df_location_aggs = df_samples.groupby(location_composite_key).agg(
{
"year": lambda x: ", ".join(str(y) for y in sorted(x.unique())),
"sample_set": lambda x: ", ".join(str(y) for y in sorted(x.unique())),
"contributor": lambda x: ", ".join(str(y) for y in sorted(x.unique())),
}
)
df_pivot = df_pivot.merge(
df_location_aggs, on=location_composite_key, validate="one_to_one"
)
# Handle basemap.
basemap_abbrevs = map_params.basemap_abbrevs
# Determine basemap_provider via basemap
if isinstance(basemap, str):
# Interpret string
# Support case-insensitive basemap abbreviations
basemap_str = basemap.lower()
if basemap_str not in basemap_abbrevs:
raise ValueError(
f"Basemap abbreviation not recognised: {basemap_str!r}; try one of {list(basemap_abbrevs.keys())}"
)
basemap_provider = basemap_abbrevs[basemap_str]
elif basemap is None:
# Default.