forked from malariagen/malariagen-data-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathag3.py
2767 lines (2403 loc) · 96.7 KB
/
ag3.py
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 sys
import warnings
from bisect import bisect_left, bisect_right
from textwrap import dedent
import dask
import dask.array as da
import numba
import numpy as np
import pandas as pd
import xarray as xr
import zarr
from .anopheles import (
DEFAULT_GENES_TRACK_HEIGHT,
DEFAULT_GENOME_PLOT_SIZING_MODE,
DEFAULT_GENOME_PLOT_WIDTH,
AnophelesDataResource,
)
try:
# noinspection PyPackageRequirements
from google import colab
except ImportError:
colab = None
import malariagen_data # used for .__version__
from .util import (
DIM_SAMPLE,
DIM_VARIANT,
Region,
da_from_zarr,
init_zarr_store,
xarray_concat,
)
# silence dask performance warnings
dask.config.set(**{"array.slicing.split_large_chunks": False})
MAJOR_VERSION_INT = 3
MAJOR_VERSION_GCS_STR = "v3"
CONFIG_PATH = "v3-config.json"
GCS_URL = "gs://vo_agam_release/"
GENOME_FASTA_PATH = (
"reference/genome/agamp4/Anopheles-gambiae-PEST_CHROMOSOMES_AgamP4.fa"
)
GENOME_FAI_PATH = (
"reference/genome/agamp4/Anopheles-gambiae-PEST_CHROMOSOMES_AgamP4.fa.fai"
)
GENOME_ZARR_PATH = (
"reference/genome/agamp4/Anopheles-gambiae-PEST_CHROMOSOMES_AgamP4.zarr"
)
SITE_ANNOTATIONS_ZARR_PATH = (
"reference/genome/agamp4/Anopheles-gambiae-PEST_SEQANNOTATION_AgamP4.12.zarr"
)
GENOME_REF_ID = "AgamP4"
GENOME_REF_NAME = "Anopheles gambiae (PEST)"
CONTIGS = "2R", "2L", "3R", "3L", "X"
DEFAULT_MAX_COVERAGE_VARIANCE = 0.2
PCA_RESULTS_CACHE_NAME = "ag3_pca_v1"
SNP_ALLELE_COUNTS_CACHE_NAME = "ag3_snp_allele_counts_v2"
FST_GWSS_CACHE_NAME = "ag3_fst_gwss_v1"
H12_CALIBRATION_CACHE_NAME = "ag3_h12_calibration_v1"
H12_GWSS_CACHE_NAME = "ag3_h12_gwss_v1"
H1X_GWSS_CACHE_NAME = "ag3_h1x_gwss_v1"
IHS_GWSS_CACHE_NAME = "ag3_ihs_gwss_v1"
DEFAULT_SITE_MASK = "gamb_colu_arab"
class Ag3(AnophelesDataResource):
"""Provides access to data from Ag3.x releases.
Parameters
----------
url : str
Base path to data. Give "gs://vo_agam_release/" to use Google Cloud
Storage, or a local path on your file system if data have been
downloaded.
cohorts_analysis : str
Cohort analysis version.
species_analysis : {"aim_20200422", "pca_20200422"}, optional
Species analysis version.
site_filters_analysis : str, optional
Site filters analysis version.
bokeh_output_notebook : bool, optional
If True (default), configure bokeh to output plots to the notebook.
results_cache : str, optional
Path to directory on local file system to save results.
log : str or stream, optional
File path or stream output for logging messages.
debug : bool, optional
Set to True to enable debug level logging.
show_progress : bool, optional
If True, show a progress bar during longer-running computations.
check_location : bool, optional
If True, use ipinfo to check the location of the client system.
**kwargs
Passed through to fsspec when setting up file system access.
Examples
--------
Access data from Google Cloud Storage (default):
>>> import malariagen_data
>>> ag3 = malariagen_data.Ag3()
Access data downloaded to a local file system:
>>> ag3 = malariagen_data.Ag3("/local/path/to/vo_agam_release/")
Access data from Google Cloud Storage, with caching on the local file system
in a directory named "gcs_cache":
>>> ag3 = malariagen_data.Ag3(
... "simplecache::gs://vo_agam_release",
... simplecache=dict(cache_storage="gcs_cache"),
... )
Set up caching of some longer-running computations on the local file system,
in a directory named "results_cache":
>>> ag3 = malariagen_data.Ag3(results_cache="results_cache")
"""
contigs = CONTIGS
virtual_contigs = "2RL", "3RL"
_major_version_int = MAJOR_VERSION_INT
_major_version_gcs_str = MAJOR_VERSION_GCS_STR
_genome_fasta_path = GENOME_FASTA_PATH
_genome_fai_path = GENOME_FAI_PATH
_genome_zarr_path = GENOME_ZARR_PATH
_genome_ref_id = GENOME_REF_ID
_genome_ref_name = GENOME_REF_NAME
_gcs_url = GCS_URL
_pca_results_cache_name = PCA_RESULTS_CACHE_NAME
_snp_allele_counts_results_cache_name = SNP_ALLELE_COUNTS_CACHE_NAME
_fst_gwss_results_cache_name = FST_GWSS_CACHE_NAME
_h12_calibration_cache_name = H12_CALIBRATION_CACHE_NAME
_h12_gwss_cache_name = H12_GWSS_CACHE_NAME
_h1x_gwss_cache_name = H1X_GWSS_CACHE_NAME
_ihs_gwss_cache_name = IHS_GWSS_CACHE_NAME
site_mask_ids = ("gamb_colu_arab", "gamb_colu", "arab")
_default_site_mask = DEFAULT_SITE_MASK
_site_annotations_zarr_path = SITE_ANNOTATIONS_ZARR_PATH
phasing_analysis_ids = ("gamb_colu_arab", "gamb_colu", "arab")
_default_phasing_analysis = "gamb_colu_arab"
def __init__(
self,
url=GCS_URL,
bokeh_output_notebook=True,
results_cache=None,
log=sys.stdout,
debug=False,
show_progress=True,
check_location=True,
cohorts_analysis=None,
species_analysis=None,
site_filters_analysis=None,
pre=False,
**kwargs, # used by simplecache, init_filesystem(url, **kwargs)
):
super().__init__(
url=url,
config_path=CONFIG_PATH,
cohorts_analysis=cohorts_analysis,
site_filters_analysis=site_filters_analysis,
bokeh_output_notebook=bokeh_output_notebook,
results_cache=results_cache,
log=log,
debug=debug,
show_progress=show_progress,
check_location=check_location,
pre=pre,
**kwargs, # used by simplecache, init_filesystem(url, **kwargs)
)
# set species analysis version - this is Ag specific currently, hence
# not in parent class
if species_analysis is None:
self._species_analysis = self._config["DEFAULT_SPECIES_ANALYSIS"]
else:
self._species_analysis = species_analysis
# set up caches
self._cache_species_calls = dict()
self._cache_cross_metadata = None
self._cache_cnv_hmm = dict()
self._cache_cnv_coverage_calls = dict()
self._cache_cnv_discordant_read_calls = dict()
self._cache_aim_variants = dict()
@property
def v3_wild(self):
"""Legacy, convenience property to access sample sets from the
3.0 release, excluding the lab crosses."""
return [
x
for x in self.sample_sets(release="3.0")["sample_set"].tolist()
if x != "AG1000G-X"
]
@staticmethod
def _setup_taxon_colors(plot_kwargs=None):
import plotly.express as px
if plot_kwargs is None:
plot_kwargs = dict()
taxon_palette = px.colors.qualitative.Plotly
taxon_color_map = {
"gambiae": taxon_palette[0],
"coluzzii": taxon_palette[1],
"arabiensis": taxon_palette[2],
"gcx1": taxon_palette[3],
"gcx2": taxon_palette[4],
"gcx3": taxon_palette[5],
"intermediate_gambiae_coluzzii": taxon_palette[6],
"intermediate_arabiensis_gambiae": taxon_palette[7],
}
plot_kwargs.setdefault("color_discrete_map", taxon_color_map)
plot_kwargs.setdefault(
"category_orders", {"taxon": list(taxon_color_map.keys())}
)
return plot_kwargs
def __repr__(self):
text = (
f"<MalariaGEN Ag3 API client>\n"
f"Storage URL : {self._url}\n"
f"Data releases available : {', '.join(self.releases)}\n"
f"Results cache : {self._results_cache}\n"
f"Cohorts analysis : {self._cohorts_analysis}\n"
f"Species analysis : {self._species_analysis}\n"
f"Site filters analysis : {self._site_filters_analysis}\n"
f"Software version : malariagen_data {malariagen_data.__version__}\n"
f"Client location : {self._client_location}\n"
f"---\n"
f"Please note that data are subject to terms of use,\n"
f"for more information see https://www.malariagen.net/data\n"
f"or contact data@malariagen.net. For API documentation see \n"
f"https://malariagen.github.io/vector-data/ag3/api.html"
)
return text
def _repr_html_(self):
html = f"""
<table class="malariagen-ag3">
<thead>
<tr>
<th style="text-align: left" colspan="2">MalariaGEN Ag3 API client</th>
</tr>
<tr><td colspan="2" style="text-align: left">
Please note that data are subject to terms of use,
for more information see <a href="https://www.malariagen.net/data">
the MalariaGEN website</a> or contact data@malariagen.net.
See also the <a href="https://malariagen.github.io/vector-data/ag3/api.html">Ag3 API docs</a>.
</td></tr>
</thead>
<tbody>
<tr>
<th style="text-align: left">
Storage URL
</th>
<td>{self._url}</td>
</tr>
<tr>
<th style="text-align: left">
Data releases available
</th>
<td>{', '.join(self.releases)}</td>
</tr>
<tr>
<th style="text-align: left">
Results cache
</th>
<td>{self._results_cache}</td>
</tr>
<tr>
<th style="text-align: left">
Cohorts analysis
</th>
<td>{self._cohorts_analysis}</td>
</tr>
<tr>
<th style="text-align: left">
Species analysis
</th>
<td>{self._species_analysis}</td>
</tr>
<tr>
<th style="text-align: left">
Site filters analysis
</th>
<td>{self._site_filters_analysis}</td>
</tr>
<tr>
<th style="text-align: left">
Software version
</th>
<td>malariagen_data {malariagen_data.__version__}</td>
</tr>
<tr>
<th style="text-align: left">
Client location
</th>
<td>{self._client_location}</td>
</tr>
</tbody>
</table>
"""
return html
def _read_species_calls(self, *, sample_set):
"""Read species calls for a single sample set."""
key = sample_set
try:
df = self._cache_species_calls[key]
except KeyError:
release = self._lookup_release(sample_set=sample_set)
release_path = self._release_to_path(release)
path_prefix = f"{self._base_path}/{release_path}/metadata"
if self._species_analysis == "aim_20220528":
path = f"{path_prefix}/species_calls_aim_20220528/{sample_set}/samples.species_aim.csv"
dtype = {
"aim_species_gambcolu_arabiensis": object,
"aim_species_gambiae_coluzzii": object,
"aim_species": object,
}
# Specify species_cols in case the file is missing
species_cols = (
"aim_species_fraction_arab",
"aim_species_fraction_colu",
"aim_species_fraction_colu_no2L",
"aim_species_gambcolu_arabiensis",
"aim_species_gambiae_coluzzii",
"aim_species",
)
elif self._species_analysis == "aim_20200422":
# TODO this is legacy, deprecate at some point
path = f"{path_prefix}/species_calls_20200422/{sample_set}/samples.species_aim.csv"
dtype = {
"species_gambcolu_arabiensis": object,
"species_gambiae_coluzzii": object,
}
# Specify species_cols in case the file is missing
# N.B., these legacy column prefixes will be normalised downstream
species_cols = (
"aim_fraction_colu",
"aim_fraction_arab",
"species_gambcolu_arabiensis",
"species_gambiae_coluzzii",
)
elif self._species_analysis == "pca_20200422":
# TODO this is legacy, deprecate at some point
path = f"{path_prefix}/species_calls_20200422/{sample_set}/samples.species_pca.csv"
dtype = {
"species_gambcolu_arabiensis": object,
"species_gambiae_coluzzii": object,
}
# Specify species_cols in case the file is missing
# N.B., these legacy column prefixes will be normalised downstream
species_cols = (
"PC1",
"PC2",
"species_gambcolu_arabiensis",
"species_gambiae_coluzzii",
)
else:
raise ValueError(
f"Unknown species calling analysis: {self._species_analysis!r}"
)
# N.B., species calls do not always exist, need to handle FileNotFoundError
try:
with self._fs.open(path) as f:
df = pd.read_csv(
f,
na_values=["", "NA"],
# ensure correct dtype even where all values are missing
dtype=dtype,
)
except FileNotFoundError:
# Get sample ids as an index via general metadata (has caching)
df_general = self._read_general_metadata(sample_set=sample_set)
df_general.set_index("sample_id", inplace=True)
# Create a blank DataFrame with species_cols and sample_id index
df = pd.DataFrame(columns=species_cols, index=df_general.index.copy())
# Revert sample_id index to column
df.reset_index(inplace=True)
# add a single species call column, for convenience
def consolidate_species(s):
species_gambcolu_arabiensis = s["species_gambcolu_arabiensis"]
species_gambiae_coluzzii = s["species_gambiae_coluzzii"]
if species_gambcolu_arabiensis == "arabiensis":
return "arabiensis"
elif species_gambcolu_arabiensis == "intermediate":
return "intermediate_arabiensis_gambiae"
elif species_gambcolu_arabiensis == "gamb_colu":
# look at gambiae_vs_coluzzii
if species_gambiae_coluzzii == "gambiae":
return "gambiae"
elif species_gambiae_coluzzii == "coluzzii":
return "coluzzii"
elif species_gambiae_coluzzii == "intermediate":
return "intermediate_gambiae_coluzzii"
else:
# some individuals, e.g., crosses, have a missing species call
return np.nan
if self._species_analysis == "aim_20200422":
# TODO this is legacy, deprecate at some point
df["species"] = df.apply(consolidate_species, axis=1)
# normalise column prefixes
df = df.rename(
columns={
"aim_fraction_arab": "aim_species_fraction_arab",
"aim_fraction_colu": "aim_species_fraction_colu",
"species_gambcolu_arabiensis": "aim_species_gambcolu_arabiensis",
"species_gambiae_coluzzii": "aim_species_gambiae_coluzzii",
"species": "aim_species",
}
)
elif self._species_analysis == "pca_20200422":
# TODO this is legacy, deprecate at some point
df["species"] = df.apply(consolidate_species, axis=1)
# normalise column prefixes
df = df.rename(
# normalise column prefixes
columns={
"PC1": "pca_species_PC1",
"PC2": "pca_species_PC2",
"species_gambcolu_arabiensis": "pca_species_gambcolu_arabiensis",
"species_gambiae_coluzzii": "pca_species_gambiae_coluzzii",
"species": "pca_species",
}
)
# ensure all column names are lower case
df.columns = [c.lower() for c in df.columns]
self._cache_species_calls[key] = df
return df.copy()
def species_calls(self, sample_sets=None):
"""Access species calls for one or more sample sets.
Parameters
----------
sample_sets : str or list of str, optional
Can be a sample set identifier (e.g., "AG1000G-AO") or a list of
sample set identifiers (e.g., ["AG1000G-BF-A", "AG1000G-BF-B"] or a
release identifier (e.g., "3.0") or a list of release identifiers.
Returns
-------
df : pandas.DataFrame
A dataframe of species calls for one or more sample sets, one row
per sample.
"""
sample_sets = self._prep_sample_sets_param(sample_sets=sample_sets)
# concatenate multiple sample sets
dfs = [self._read_species_calls(sample_set=s) for s in sample_sets]
df = pd.concat(dfs, axis=0, ignore_index=True)
return df
# TODO: generalise (species, cohorts) so we can abstract to parent class
def _sample_metadata(self, *, sample_set):
df = self._read_general_metadata(sample_set=sample_set)
df_species = self._read_species_calls(sample_set=sample_set)
df = df.merge(df_species, on="sample_id", sort=False)
df_cohorts = self._read_cohort_metadata(sample_set=sample_set)
df = df.merge(df_cohorts, on="sample_id", sort=False)
return df
def _transcript_to_gene_name(self, transcript):
df_genome_features = self.genome_features().set_index("ID")
rec_transcript = df_genome_features.loc[transcript]
parent = rec_transcript["Parent"]
rec_parent = df_genome_features.loc[parent]
# manual overrides
if parent == "AGAP004707":
parent_name = "Vgsc/para"
else:
parent_name = rec_parent["Name"]
return parent_name
def cross_metadata(self):
"""Load a dataframe containing metadata about samples in colony crosses,
including which samples are parents or progeny in which crosses.
Returns
-------
df : pandas.DataFrame
A dataframe of sample metadata for colony crosses.
"""
debug = self._log.debug
if self._cache_cross_metadata is None:
path = f"{self._base_path}/v3/metadata/crosses/crosses.fam"
fam_names = [
"cross",
"sample_id",
"father_id",
"mother_id",
"sex",
"phenotype",
]
with self._fs.open(path) as f:
df = pd.read_csv(
f,
sep="\t",
na_values=["", "0"],
names=fam_names,
dtype={"sex": str},
)
debug("convert 'sex' column for consistency with sample metadata")
df.loc[df["sex"] == "1", "sex"] = "M"
df.loc[df["sex"] == "2", "sex"] = "F"
debug("add a 'role' column for convenience")
df["role"] = "progeny"
df.loc[df["mother_id"].isna(), "role"] = "parent"
debug("drop 'phenotype' column, not used")
df.drop("phenotype", axis="columns", inplace=True)
self._cache_cross_metadata = df
return self._cache_cross_metadata.copy()
def _genome_sequence_for_contig(self, *, contig, inline_array, chunks):
"""Obtain the genome sequence for a given contig as an array."""
if contig in self.virtual_contigs:
# handle virtual contig with joined arms
contig_r, contig_l = _chrom_to_contigs(contig)
d_r = super()._genome_sequence_for_contig(
contig=contig_r, inline_array=inline_array, chunks=chunks
)
d_l = super()._genome_sequence_for_contig(
contig=contig_l, inline_array=inline_array, chunks=chunks
)
return da.concatenate([d_r, d_l])
return super()._genome_sequence_for_contig(
contig=contig, inline_array=inline_array, chunks=chunks
)
def _genome_features_for_contig(self, *, contig, attributes):
"""Obtain the genome features for a given contig as a pandas DataFrame."""
if contig in self.virtual_contigs:
contig_r, contig_l = _chrom_to_contigs(contig)
df_r = super()._genome_features_for_contig(
contig=contig_r, attributes=attributes
)
df_l = super()._genome_features_for_contig(
contig=contig_l, attributes=attributes
)
max_r = super().genome_sequence(region=contig_r).shape[0]
df_l = df_l.assign(
start=lambda x: x.start + max_r, end=lambda x: x.end + max_r
)
df = pd.concat([df_r, df_l], axis=0)
df = df.assign(contig=contig)
return df
return super()._genome_features_for_contig(contig=contig, attributes=attributes)
def _snp_genotypes_for_contig(
self, *, contig, sample_set, field, inline_array, chunks
):
"""Access SNP genotypes for a single contig/chromosome and multiple sample sets."""
if contig in self.virtual_contigs:
contig_r, contig_l = _chrom_to_contigs(contig)
d_r = super()._snp_genotypes_for_contig(
contig=contig_r,
sample_set=sample_set,
field=field,
inline_array=inline_array,
chunks=chunks,
)
d_l = super()._snp_genotypes_for_contig(
contig=contig_l,
sample_set=sample_set,
field=field,
inline_array=inline_array,
chunks=chunks,
)
return da.concatenate([d_r, d_l])
return super()._snp_genotypes_for_contig(
contig=contig,
sample_set=sample_set,
field=field,
inline_array=inline_array,
chunks=chunks,
)
def _snp_sites_for_contig(self, contig, *, field, inline_array, chunks):
"""Access SNP sites for a single contig/chromosome."""
if contig in self.virtual_contigs:
contig_r, contig_l = _chrom_to_contigs(contig)
field_r = super()._snp_sites_for_contig(
contig=contig_r, field=field, inline_array=inline_array, chunks=chunks
)
field_l = super()._snp_sites_for_contig(
contig=contig_l, field=field, inline_array=inline_array, chunks=chunks
)
if field == "POS":
max_r = super().genome_sequence(region=contig_r).shape[0]
field_l = field_l + max_r
return da.concatenate([field_r, field_l])
return super()._snp_sites_for_contig(
contig=contig, field=field, inline_array=inline_array, chunks=chunks
)
def _snp_calls_for_contig(self, contig, *, sample_set, inline_array, chunks):
"""Access SNP calls for a single contig/chromosome and a single sample sets as an xarray dataset."""
if contig in self.virtual_contigs:
contig_r, contig_l = _chrom_to_contigs(contig)
ds_r = super()._snp_calls_for_contig(
contig=contig_r,
sample_set=sample_set,
inline_array=inline_array,
chunks=chunks,
)
ds_l = super()._snp_calls_for_contig(
contig=contig_l,
sample_set=sample_set,
inline_array=inline_array,
chunks=chunks,
)
ds = xr.concat([ds_r, ds_l], dim=DIM_VARIANT)
return ds
return super()._snp_calls_for_contig(
contig=contig,
sample_set=sample_set,
inline_array=inline_array,
chunks=chunks,
)
def _snp_variants_for_contig(self, contig, *, inline_array, chunks):
"""Access SNP variants for a single contig/chromosome as an xarray dataset."""
if contig in self.virtual_contigs:
contig_r, contig_l = _chrom_to_contigs(contig)
ds_r = super()._snp_variants_for_contig(
contig=contig_r,
inline_array=inline_array,
chunks=chunks,
)
ds_l = super()._snp_variants_for_contig(
contig=contig_l,
inline_array=inline_array,
chunks=chunks,
)
max_r = super().genome_sequence(region=contig_r).shape[0]
ds_l["variant_position"] = ds_l["variant_position"] + max_r
ds = xr.concat([ds_r, ds_l], dim=DIM_VARIANT)
return ds
return super()._snp_variants_for_contig(
contig=contig,
inline_array=inline_array,
chunks=chunks,
)
def _haplotypes_for_contig(
self, *, contig, sample_set, analysis, inline_array, chunks
):
"""Access haplotypes for a single whole chromosome and a single sample sets."""
if contig in self.virtual_contigs:
contig_r, contig_l = _chrom_to_contigs(contig)
ds_r = super()._haplotypes_for_contig(
contig=contig_r,
sample_set=sample_set,
analysis=analysis,
inline_array=inline_array,
chunks=chunks,
)
ds_l = super()._haplotypes_for_contig(
contig=contig_l,
sample_set=sample_set,
analysis=analysis,
inline_array=inline_array,
chunks=chunks,
)
# handle case where no haplotypes available for given sample set
# then convert genome coordinates
if ds_l is not None:
max_r = super().genome_sequence(region=contig_r).shape[0]
ds_l["variant_position"] = ds_l["variant_position"] + max_r
ds = xr.concat([ds_r, ds_l], dim=DIM_VARIANT)
return ds
return None
return super()._haplotypes_for_contig(
contig=contig,
sample_set=sample_set,
analysis=analysis,
inline_array=inline_array,
chunks=chunks,
)
def open_cnv_hmm(self, sample_set):
"""Open CNV HMM zarr.
Parameters
----------
sample_set : str
Returns
-------
root : zarr.hierarchy.Group
"""
try:
return self._cache_cnv_hmm[sample_set]
except KeyError:
release = self._lookup_release(sample_set=sample_set)
release_path = self._release_to_path(release)
path = f"{self._base_path}/{release_path}/cnv/{sample_set}/hmm/zarr"
store = init_zarr_store(fs=self._fs, path=path)
root = zarr.open_consolidated(store=store)
self._cache_cnv_hmm[sample_set] = root
return root
def _cnv_hmm_dataset(self, *, contig, sample_set, inline_array, chunks):
debug = self._log.debug
coords = dict()
data_vars = dict()
debug("open zarr")
root = self.open_cnv_hmm(sample_set=sample_set)
debug("variant arrays")
pos = root[f"{contig}/variants/POS"]
coords["variant_position"] = (
[DIM_VARIANT],
da_from_zarr(pos, inline_array=inline_array, chunks=chunks),
)
coords["variant_end"] = (
[DIM_VARIANT],
da_from_zarr(
root[f"{contig}/variants/END"], inline_array=inline_array, chunks=chunks
),
)
contig_index = self.contigs.index(contig)
coords["variant_contig"] = (
[DIM_VARIANT],
da.full_like(pos, fill_value=contig_index, dtype="u1"),
)
debug("call arrays")
data_vars["call_CN"] = (
[DIM_VARIANT, DIM_SAMPLE],
da_from_zarr(
root[f"{contig}/calldata/CN"], inline_array=inline_array, chunks=chunks
),
)
data_vars["call_RawCov"] = (
[DIM_VARIANT, DIM_SAMPLE],
da_from_zarr(
root[f"{contig}/calldata/RawCov"],
inline_array=inline_array,
chunks=chunks,
),
)
data_vars["call_NormCov"] = (
[DIM_VARIANT, DIM_SAMPLE],
da_from_zarr(
root[f"{contig}/calldata/NormCov"],
inline_array=inline_array,
chunks=chunks,
),
)
debug("sample arrays")
coords["sample_id"] = (
[DIM_SAMPLE],
da_from_zarr(root["samples"], inline_array=inline_array, chunks=chunks),
)
for field in "sample_coverage_variance", "sample_is_high_variance":
data_vars[field] = (
[DIM_SAMPLE],
da_from_zarr(root[field], inline_array=inline_array, chunks=chunks),
)
debug("set up attributes")
attrs = {"contigs": self.contigs}
debug("create a dataset")
ds = xr.Dataset(data_vars=data_vars, coords=coords, attrs=attrs)
return ds
def cnv_hmm(
self,
region,
sample_sets=None,
sample_query=None,
max_coverage_variance=DEFAULT_MAX_COVERAGE_VARIANCE,
inline_array=True,
chunks="native",
):
"""Access CNV HMM data from CNV calling.
Parameters
----------
region: str or list of str or Region or list of Region
Chromosome arm (e.g., "2L"), gene name (e.g., "AGAP007280"), genomic
region defined with coordinates (e.g., "2L:44989425-44998059") or a
named tuple with genomic location `Region(contig, start, end)`.
Multiple values can be provided as a list, in which case data will
be concatenated, e.g., ["3R", "3L"].
sample_sets : str or list of str, optional
Can be a sample set identifier (e.g., "AG1000G-AO") or a list of
sample set identifiers (e.g., ["AG1000G-BF-A", "AG1000G-BF-B"]) or a
release identifier (e.g., "3.0") or a list of release identifiers.
sample_query : str, optional
A pandas query string which will be evaluated against the sample
metadata e.g., "taxon == 'coluzzii' and country == 'Burkina Faso'".
max_coverage_variance : float, optional
Remove samples if coverage variance exceeds this value.
inline_array : bool, optional
Passed through to dask.array.from_array().
chunks : str, optional
If 'auto' let dask decide chunk size. If 'native' use native zarr
chunks. Also, can be a target size, e.g., '200 MiB'.
Returns
-------
ds : xarray.Dataset
A dataset of CNV HMM calls and associated data.
"""
debug = self._log.debug
debug("normalise parameters")
sample_sets = self._prep_sample_sets_param(sample_sets=sample_sets)
region = self.resolve_region(region)
if isinstance(region, Region):
region = [region]
debug("access CNV HMM data and concatenate as needed")
lx = []
for r in region:
ly = []
for s in sample_sets:
y = self._cnv_hmm_dataset(
contig=r.contig,
sample_set=s,
inline_array=inline_array,
chunks=chunks,
)
ly.append(y)
debug("concatenate data from multiple sample sets")
x = xarray_concat(ly, dim=DIM_SAMPLE)
debug("handle region, do this only once - optimisation")
if r.start is not None or r.end is not None:
start = x["variant_position"].values
end = x["variant_end"].values
index = pd.IntervalIndex.from_arrays(start, end, closed="both")
# noinspection PyArgumentList
other = pd.Interval(r.start, r.end, closed="both")
loc_region = index.overlaps(other)
x = x.isel(variants=loc_region)
lx.append(x)
debug("concatenate data from multiple regions")
ds = xarray_concat(lx, dim=DIM_VARIANT)
debug("handle sample query")
if sample_query is not None:
debug("load sample metadata")
df_samples = self.sample_metadata(sample_sets=sample_sets)
debug("align sample metadata with CNV data")
cnv_samples = ds["sample_id"].values.tolist()
df_samples_cnv = (
df_samples.set_index("sample_id").loc[cnv_samples].reset_index()
)
debug("apply the query")
loc_query_samples = df_samples_cnv.eval(sample_query).values
if np.count_nonzero(loc_query_samples) == 0:
raise ValueError(f"No samples found for query {sample_query!r}")
ds = ds.isel(samples=loc_query_samples)
debug("handle coverage variance filter")
if max_coverage_variance is not None:
cov_var = ds["sample_coverage_variance"].values
loc_pass_samples = cov_var <= max_coverage_variance
ds = ds.isel(samples=loc_pass_samples)
return ds
def open_cnv_coverage_calls(self, sample_set, analysis):
"""Open CNV coverage calls zarr.
Parameters
----------
sample_set : str
analysis : {'gamb_colu', 'arab', 'crosses'}
Returns
-------
root : zarr.hierarchy.Group
"""
key = (sample_set, analysis)
try:
return self._cache_cnv_coverage_calls[key]
except KeyError:
release = self._lookup_release(sample_set=sample_set)
release_path = self._release_to_path(release)
path = f"{self._base_path}/{release_path}/cnv/{sample_set}/coverage_calls/{analysis}/zarr"
# N.B., not all sample_set/analysis combinations exist, need to check
marker = path + "/.zmetadata"
if not self._fs.exists(marker):
raise ValueError(
f"analysis f{analysis!r} not implemented for sample set {sample_set!r}"
)
store = init_zarr_store(fs=self._fs, path=path)
root = zarr.open_consolidated(store=store)
self._cache_cnv_coverage_calls[key] = root
return root
def _cnv_coverage_calls_dataset(
self,
*,
contig,
sample_set,
analysis,
inline_array,
chunks,
):
debug = self._log.debug
coords = dict()
data_vars = dict()
debug("open zarr")
root = self.open_cnv_coverage_calls(sample_set=sample_set, analysis=analysis)
debug("variant arrays")
pos = root[f"{contig}/variants/POS"]
coords["variant_position"] = (
[DIM_VARIANT],
da_from_zarr(pos, inline_array=inline_array, chunks=chunks),
)
coords["variant_end"] = (
[DIM_VARIANT],