-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathanopheles.py
More file actions
1537 lines (1420 loc) · 58.6 KB
/
anopheles.py
File metadata and controls
1537 lines (1420 loc) · 58.6 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
from typing import Any, Dict, Mapping, Optional, Tuple, Sequence
import allel # type: ignore
import bokeh.layouts
import bokeh.models
import bokeh.palettes
import bokeh.plotting
import numpy as np
import pandas as pd
import plotly.express as px # type: ignore
import plotly.graph_objects as go # type: ignore
from numpydoc_decorator import doc # type: ignore
from .anoph.safe_query import validate_query
from .anoph import (
aim_params,
base_params,
dash_params,
gplt_params,
hapnet_params,
ihs_params,
plotly_params,
)
from .anoph.karyotype import AnophelesKaryotypeAnalysis
from .anoph.aim_data import AnophelesAimData
from .anoph.base import AnophelesBase
from .anoph.genome_features import AnophelesGenomeFeaturesData
from .anoph.genome_sequence import AnophelesGenomeSequenceData
from .anoph.hap_data import AnophelesHapData, hap_params
from .anoph.hap_frq import AnophelesHapFrequencyAnalysis
from .anoph.igv import AnophelesIgv
from .anoph.pca import AnophelesPca
from .anoph.distance import AnophelesDistanceAnalysis
from .anoph.sample_metadata import AnophelesSampleMetadata
from .anoph.snp_data import AnophelesSnpData
from .anoph.to_plink import PlinkConverter
from .anoph.ld import AnophelesLdAnalysis
from .anoph.to_vcf import SnpVcfExporter
from .anoph.g123 import AnophelesG123Analysis
from .anoph.fst import AnophelesFstAnalysis
from .anoph.h12 import AnophelesH12Analysis
from .anoph.h1x import AnophelesH1XAnalysis
from .anoph.phenotypes import AnophelesPhenotypeData
from .mjn import _median_joining_network, _mjn_graph
from .anoph.hapclust import AnophelesHapClustAnalysis
from .anoph.describe import AnophelesDescribe
from .anoph.dipclust import AnophelesDipClustAnalysis
from .anoph.heterozygosity import AnophelesHetAnalysis
from .anoph.xpehh import AnophelesXpehhAnalysis
from .util import (
CacheMiss,
Region, # noqa: F401 (re-exported via __init__.py)
_check_types,
_jackknife_ci,
_plotly_discrete_legend,
)
# N.B., we are in the process of breaking up the AnophelesDataResource
# class into multiple parent classes like AnophelesGenomeSequenceData
# and AnophelesBase. This is work in progress, and further PRs are
# expected to factor out functions defined here in to separate classes.
# For more information, see:
#
# https://github.com/malariagen/malariagen-data-python/issues/366
#
# N.B., we are making use of multiple inheritance here, using co-operative
# classes. Because of the way that multiple inheritance works in Python,
# it is important that these parent classes are provided in a particular
# order. Otherwise the linearization of parent classes will fail. For
# more information about superclass linearization and method resolution
# order in Python, the following links may be useful.
#
# https://en.wikipedia.org/wiki/C3_linearization
# https://rhettinger.wordpress.com/2011/05/26/super-considered-super/
# work around pycharm failing to recognise that doc() is callable
# noinspection PyCallingNonCallable
class AnophelesDataResource(
AnophelesDipClustAnalysis,
AnophelesHapClustAnalysis,
AnophelesXpehhAnalysis,
AnophelesH1XAnalysis,
AnophelesH12Analysis,
AnophelesG123Analysis,
AnophelesFstAnalysis,
AnophelesHetAnalysis,
AnophelesHapFrequencyAnalysis,
AnophelesDistanceAnalysis,
AnophelesPca,
PlinkConverter,
AnophelesLdAnalysis,
SnpVcfExporter,
AnophelesIgv,
AnophelesKaryotypeAnalysis,
AnophelesAimData,
AnophelesHapData,
AnophelesSnpData,
AnophelesSampleMetadata,
AnophelesGenomeFeaturesData,
AnophelesGenomeSequenceData,
AnophelesDescribe,
AnophelesBase,
AnophelesPhenotypeData,
):
"""Anopheles data resources."""
def __init__(
self,
url,
public_url,
config_path,
cohorts_analysis: Optional[str],
aim_analysis: Optional[str],
aim_metadata_dtype: Optional[Mapping[str, Any]],
aim_ids: Optional[aim_params.aim_ids],
aim_palettes: Optional[aim_params.aim_palettes],
site_filters_analysis: Optional[str],
discordant_read_calls_analysis: Optional[str],
default_site_mask: Optional[str],
default_phasing_analysis: Optional[str],
default_coverage_calls_analysis: Optional[str],
bokeh_output_notebook: bool,
results_cache: Optional[str],
log,
debug,
show_progress,
check_location,
pre,
gcs_default_url: Optional[str],
gcs_region_urls: Mapping[str, str],
major_version_number: int,
major_version_path: str,
gff_gene_type: str,
gff_gene_name_attribute: str,
gff_default_attributes: Tuple[str, ...],
tqdm_class,
storage_options: Mapping,
taxon_colors: Optional[Mapping[str, str]] = None,
aim_species_colors: Optional[Mapping[str, str]] = None,
virtual_contigs: Optional[Mapping[str, Sequence[str]]] = None,
gene_names: Optional[Mapping[str, str]] = None,
inversion_tag_path: Optional[str] = None,
unrestricted_use_only: Optional[bool] = None,
surveillance_use_only: Optional[bool] = None,
plink_chrom_map: Optional[Mapping[str, int]] = None,
):
super().__init__(
url=url,
public_url=public_url,
config_path=config_path,
bokeh_output_notebook=bokeh_output_notebook,
log=log,
debug=debug,
show_progress=show_progress,
check_location=check_location,
pre=pre,
gcs_default_url=gcs_default_url,
gcs_region_urls=gcs_region_urls,
major_version_number=major_version_number,
major_version_path=major_version_path,
storage_options=storage_options,
gff_gene_type=gff_gene_type,
gff_gene_name_attribute=gff_gene_name_attribute,
gff_default_attributes=gff_default_attributes,
cohorts_analysis=cohorts_analysis,
aim_analysis=aim_analysis,
aim_metadata_dtype=aim_metadata_dtype,
aim_ids=aim_ids,
aim_palettes=aim_palettes,
site_filters_analysis=site_filters_analysis,
discordant_read_calls_analysis=discordant_read_calls_analysis,
default_site_mask=default_site_mask,
default_phasing_analysis=default_phasing_analysis,
default_coverage_calls_analysis=default_coverage_calls_analysis,
results_cache=results_cache,
tqdm_class=tqdm_class,
taxon_colors=taxon_colors,
aim_species_colors=aim_species_colors,
virtual_contigs=virtual_contigs,
gene_names=gene_names,
inversion_tag_path=inversion_tag_path,
unrestricted_use_only=unrestricted_use_only,
surveillance_use_only=surveillance_use_only,
plink_chrom_map=plink_chrom_map,
)
def _get_ihs_gwss_cache_name(self):
"""Safely resolve the ihs gwss cache name.
Supports class attribute, property, or legacy method override.
Falls back to the default "ihs_gwss_v1" if resolution fails.
See also: https://github.com/malariagen/malariagen-data-python/issues/1151
"""
try:
name = self._ihs_gwss_cache_name
# Handle legacy case where _ihs_gwss_cache_name might be a
# callable method rather than a property or class attribute.
if callable(name):
name = name()
if isinstance(name, str) and len(name) > 0:
return name
except NotImplementedError:
pass
# Fallback to default.
return "ihs_gwss_v1"
@staticmethod
def _make_gene_cnv_label(gene_id, gene_name, cnv_type):
label = gene_id
if isinstance(gene_name, str):
label += f" ({gene_name})"
label += f" {cnv_type}"
return label
def _block_jackknife_cohort_diversity_stats(
self, *, cohort_label, ac, n_jack, confidence_level
):
debug = self._log.debug
debug("set up for diversity calculations")
n_sites = ac.shape[0]
ac = allel.AlleleCountsArray(ac)
n = ac.sum(axis=1).max() # number of chromosomes sampled
n_sites = min(n_sites, ac.shape[0]) # number of sites
block_length = n_sites // n_jack # number of sites in each block
n_sites_j = n_sites - block_length # number of sites in each jackknife resample
debug("compute scaling constants")
a1 = np.sum(1 / np.arange(1, n))
a2 = np.sum(1 / (np.arange(1, n) ** 2))
b1 = (n + 1) / (3 * (n - 1))
b2 = 2 * (n**2 + n + 3) / (9 * n * (n - 1))
c1 = b1 - (1 / a1)
c2 = b2 - ((n + 2) / (a1 * n)) + (a2 / (a1**2))
e1 = c1 / a1
e2 = c2 / (a1**2 + a2)
debug(
"compute some intermediates ahead of time, to minimise computation during jackknife resampling"
)
mpd_data = allel.mean_pairwise_difference(ac, fill=0)
# N.B., here we compute the number of segregating sites as the number
# of alleles minus 1. This follows the sgkit and tskit implementations,
# and is different from scikit-allel.
seg_data = ac.allelism() - 1
debug("compute estimates from all data")
theta_pi_abs_data = np.sum(mpd_data)
theta_pi_data = theta_pi_abs_data / n_sites
S_data = np.sum(seg_data)
theta_w_abs_data = S_data / a1
theta_w_data = theta_w_abs_data / n_sites
d_data = theta_pi_abs_data - theta_w_abs_data
d_stdev_data = np.sqrt((e1 * S_data) + (e2 * S_data * (S_data - 1)))
tajima_d_data = d_data / d_stdev_data
debug("set up for jackknife resampling")
jack_theta_pi = []
jack_theta_w = []
jack_tajima_d = []
debug("begin jackknife resampling")
for i in range(n_jack):
# locate block to delete
block_start = i * block_length
block_stop = block_start + block_length
loc_j = np.ones(n_sites, dtype=bool)
loc_j[block_start:block_stop] = False
if np.count_nonzero(loc_j) != n_sites_j:
raise RuntimeError(
f"Internal error in jackknife resampling: expected {n_sites_j} "
f"sites after block deletion, got {np.count_nonzero(loc_j)}"
)
# resample data and compute statistics
# theta_pi
mpd_j = mpd_data[loc_j]
theta_pi_abs_j = np.sum(mpd_j)
theta_pi_j = theta_pi_abs_j / n_sites_j
jack_theta_pi.append(theta_pi_j)
# theta_w
seg_j = seg_data[loc_j]
S_j = np.sum(seg_j)
theta_w_abs_j = S_j / a1
theta_w_j = theta_w_abs_j / n_sites_j
jack_theta_w.append(theta_w_j)
# tajima_d
d_j = theta_pi_abs_j - theta_w_abs_j
d_stdev_j = np.sqrt((e1 * S_j) + (e2 * S_j * (S_j - 1)))
tajima_d_j = d_j / d_stdev_j
jack_tajima_d.append(tajima_d_j)
# calculate jackknife stats
(
theta_pi_estimate,
theta_pi_bias,
theta_pi_std_err,
theta_pi_ci_err,
theta_pi_ci_low,
theta_pi_ci_upp,
) = _jackknife_ci(
stat_data=theta_pi_data,
jack_stat=jack_theta_pi,
confidence_level=confidence_level,
)
(
theta_w_estimate,
theta_w_bias,
theta_w_std_err,
theta_w_ci_err,
theta_w_ci_low,
theta_w_ci_upp,
) = _jackknife_ci(
stat_data=theta_w_data,
jack_stat=jack_theta_w,
confidence_level=confidence_level,
)
(
tajima_d_estimate,
tajima_d_bias,
tajima_d_std_err,
tajima_d_ci_err,
tajima_d_ci_low,
tajima_d_ci_upp,
) = _jackknife_ci(
stat_data=tajima_d_data,
jack_stat=jack_tajima_d,
confidence_level=confidence_level,
)
return dict(
cohort=cohort_label,
theta_pi=theta_pi_data,
theta_pi_estimate=theta_pi_estimate,
theta_pi_bias=theta_pi_bias,
theta_pi_std_err=theta_pi_std_err,
theta_pi_ci_err=theta_pi_ci_err,
theta_pi_ci_low=theta_pi_ci_low,
theta_pi_ci_upp=theta_pi_ci_upp,
theta_w=theta_w_data,
theta_w_estimate=theta_w_estimate,
theta_w_bias=theta_w_bias,
theta_w_std_err=theta_w_std_err,
theta_w_ci_err=theta_w_ci_err,
theta_w_ci_low=theta_w_ci_low,
theta_w_ci_upp=theta_w_ci_upp,
tajima_d=tajima_d_data,
tajima_d_estimate=tajima_d_estimate,
tajima_d_bias=tajima_d_bias,
tajima_d_std_err=tajima_d_std_err,
tajima_d_ci_err=tajima_d_ci_err,
tajima_d_ci_low=tajima_d_ci_low,
tajima_d_ci_upp=tajima_d_ci_upp,
)
@_check_types
@doc(
summary="""
Compute genetic diversity summary statistics for a cohort of
individuals.
""",
returns="""
A pandas series with summary statistics (theta pi, Watterson's theta and Tajima's D)
and their estimate, bias, standard error, confidence interval error, confidence interval lower value,
and confidence interval upper value. The series also contains the cohort under study, its taxon, its year
of collection, its month of collection, its country of collection, the ISO code of its first administrative
level of collection, the name of its first administrative level of collection, the name of its second administrative
level of collection, the longitude of its location of collection, and the latitude of its location of collection.
""",
)
def cohort_diversity_stats(
self,
cohort: base_params.cohort,
cohort_size: base_params.cohort_size,
region: base_params.regions,
min_cohort_size: Optional[base_params.min_cohort_size] = None,
max_cohort_size: Optional[base_params.max_cohort_size] = None,
site_mask: Optional[base_params.site_mask] = base_params.DEFAULT,
site_class: Optional[base_params.site_class] = None,
sample_sets: Optional[base_params.sample_sets] = None,
random_seed: base_params.random_seed = 42,
n_jack: base_params.n_jack = 200,
confidence_level: base_params.confidence_level = 0.95,
chunks: base_params.chunks = base_params.native_chunks,
inline_array: base_params.inline_array = base_params.inline_array_default,
) -> pd.Series:
debug = self._log.debug
# Change this name if you ever change the behaviour of this function, to
# invalidate any previously cached data.
name = "cohort_diversity_stats_v1"
debug("process cohort parameter")
cohort_query = None
if isinstance(cohort, str):
# assume it is one of the predefined cohorts
cohort_label = cohort
df_samples = self.sample_metadata(sample_sets=sample_sets)
cohort_cols = [c for c in df_samples.columns if c.startswith("cohort_")]
for c in cohort_cols:
if cohort in set(df_samples[c]):
cohort_query = f"{c} == '{cohort}'"
break
if cohort_query is None:
raise ValueError(f"unknown cohort: {cohort}")
elif isinstance(cohort, (list, tuple)) and len(cohort) == 2:
cohort_label, cohort_query = cohort
else:
raise TypeError(f"invalid cohort parameter: {cohort!r}")
params = dict(
cohort_label=cohort_label,
cohort_query=cohort_query,
cohort_size=cohort_size,
region=region,
min_cohort_size=min_cohort_size,
max_cohort_size=max_cohort_size,
site_mask=site_mask,
site_class=site_class,
sample_sets=sample_sets,
random_seed=random_seed,
n_jack=n_jack,
confidence_level=confidence_level,
chunks=chunks,
inline_array=inline_array,
)
# Try to retrieve results from the cache.
try:
results = self.results_cache_get(name=name, params=params)
stats = {
key: value.item()
if isinstance(value, np.ndarray) and value.shape == ()
else value
for key, value in results.items()
}
except CacheMiss:
debug("access allele counts")
ac = self.snp_allele_counts(
region=region,
site_mask=site_mask,
site_class=site_class,
sample_query=cohort_query,
sample_sets=sample_sets,
cohort_size=cohort_size,
min_cohort_size=min_cohort_size,
max_cohort_size=max_cohort_size,
random_seed=random_seed,
chunks=chunks,
inline_array=inline_array,
)
debug("compute diversity stats")
stats = self._block_jackknife_cohort_diversity_stats(
cohort_label=cohort_label,
ac=ac,
n_jack=n_jack,
confidence_level=confidence_level,
)
cache_results = {key: np.asarray(value) for key, value in stats.items()}
self.results_cache_set(name=name, params=params, results=cache_results)
debug("compute some extra cohort variables")
df_samples = self.sample_metadata(
sample_sets=sample_sets, sample_query=cohort_query
)
extra_fields = [
("taxon", "unique"),
("year", "unique"),
("month", "unique"),
("country", "unique"),
("admin1_iso", "unique"),
("admin1_name", "unique"),
("admin2_name", "unique"),
("longitude", "mean"),
("latitude", "mean"),
]
for field, agg in extra_fields:
if agg == "unique":
vals = df_samples[field].dropna().sort_values().unique()
if len(vals) == 0:
val = np.nan
elif len(vals) == 1:
val = vals[0]
else:
val = vals.tolist()
elif agg == "mean":
vals = df_samples[field].dropna()
if len(vals) == 0:
val = np.nan
else:
val = np.mean(vals)
else:
val = np.nan
stats[field] = val
return pd.Series(stats)
@_check_types
@doc(
summary="""
Compute genetic diversity summary statistics for multiple cohorts.
""",
returns="""
A DataFrame where each row provides summary statistics and their
confidence intervals for a single cohort. The columns are
the value, the estimate, the bias, the standard error,
the confidence interval error, the confidence interval lower value,
the confidence interval upper value for each summary statistics (theta pi, Watterson's theta and Tajima's D),
the taxon of the cohort, its year
of collection, its month of collection, its country of collection, the ISO code of its first administrative
level of collection, the name of its first administrative level of collection, the name of its second administrative
level of collection, the longitude of its location of collection, and the latitude of its location of collection.
""",
)
def diversity_stats(
self,
cohorts: base_params.cohorts,
cohort_size: base_params.cohort_size,
region: base_params.regions,
site_mask: Optional[base_params.site_mask] = base_params.DEFAULT,
site_class: Optional[base_params.site_class] = None,
sample_query: Optional[base_params.sample_query] = None,
sample_query_options: Optional[base_params.sample_query_options] = None,
sample_sets: Optional[base_params.sample_sets] = None,
random_seed: base_params.random_seed = 42,
n_jack: base_params.n_jack = 200,
confidence_level: base_params.confidence_level = 0.95,
chunks: base_params.chunks = base_params.native_chunks,
inline_array: base_params.inline_array = base_params.inline_array_default,
) -> pd.DataFrame:
# Normalise cohorts parameter.
cohort_queries = self._setup_cohort_queries(
cohorts=cohorts,
sample_sets=sample_sets,
sample_query=sample_query,
sample_query_options=sample_query_options,
cohort_size=cohort_size,
min_cohort_size=None,
)
# Compute diversity stats for cohorts.
all_stats = []
for cohort_label, cohort_query in cohort_queries.items():
stats = self.cohort_diversity_stats(
cohort=(cohort_label, cohort_query),
cohort_size=cohort_size,
region=region,
site_mask=site_mask,
site_class=site_class,
sample_sets=sample_sets,
random_seed=random_seed,
n_jack=n_jack,
confidence_level=confidence_level,
chunks=chunks,
inline_array=inline_array,
)
all_stats.append(stats)
df_stats = pd.DataFrame(all_stats)
return df_stats
@_check_types
@doc(
summary="Plot diversity summary statistics for multiple cohorts.",
parameters=dict(
df_stats="Output from `diversity_stats()`.",
bar_plot_height="Height of bar plots in pixels (px).",
bar_width="Width per bar in pixels (px).",
scatter_plot_height="Height of scatter plot in pixels (px).",
scatter_plot_width="Width of scatter plot in pixels (px).",
plot_kwargs="Extra plotting parameters.",
),
)
def plot_diversity_stats(
self,
df_stats: pd.DataFrame,
color: plotly_params.color = None,
bar_plot_height: int = 450,
bar_width: int = 30,
scatter_plot_height: int = 500,
scatter_plot_width: int = 500,
template: plotly_params.template = "plotly_white",
color_discrete_sequence: plotly_params.color_discrete_sequence = None,
color_discrete_map: plotly_params.color_discrete_map = None,
category_orders: plotly_params.category_order = None,
plot_kwargs: Optional[Mapping] = None,
show: plotly_params.show = True,
renderer: plotly_params.renderer = None,
) -> Optional[Tuple[go.Figure, ...]]:
# Handle color.
(
color_prepped,
color_discrete_map_prepped,
category_orders_prepped,
) = self._setup_sample_colors_plotly(
data=df_stats,
color=color,
color_discrete_map=color_discrete_map,
color_discrete_sequence=color_discrete_sequence,
category_orders=category_orders,
)
del color
del color_discrete_map
del color_discrete_sequence
del category_orders
# Set up common plotting parameters.
default_plot_kwargs = dict(
hover_name="cohort",
hover_data=[
"taxon",
"country",
"admin1_iso",
"admin1_name",
"admin2_name",
"longitude",
"latitude",
"year",
"month",
],
labels={
"theta_pi_estimate": "θ<sub>π</sub>",
"theta_w_estimate": "θ<sub>𝑤</sub>",
"tajima_d_estimate": "𝐷",
"cohort": "Cohort",
"taxon": "Taxon",
"country": "Country",
},
color=color_prepped,
color_discrete_map=color_discrete_map_prepped,
category_orders=category_orders_prepped,
template=template,
)
# Finalise parameters.
if plot_kwargs is None:
plot_kwargs = dict()
default_plot_kwargs.update(plot_kwargs)
plot_kwargs = default_plot_kwargs
bar_plot_width = 300 + bar_width * len(df_stats)
# Nucleotide diversity bar plot.
fig1 = px.bar(
data_frame=df_stats,
x="cohort",
y="theta_pi_estimate",
error_y="theta_pi_ci_err",
title="Nucleotide diversity",
height=bar_plot_height,
width=bar_plot_width,
**plot_kwargs,
)
# Watterson's estimator bar plot.
fig2 = px.bar(
data_frame=df_stats,
x="cohort",
y="theta_w_estimate",
error_y="theta_w_ci_err",
title="Watterson's estimator",
height=bar_plot_height,
width=bar_plot_width,
**plot_kwargs,
)
# Tajima's D bar plot.
fig3 = px.bar(
data_frame=df_stats,
x="cohort",
y="tajima_d_estimate",
error_y="tajima_d_ci_err",
title="Tajima's D",
height=bar_plot_height,
width=bar_plot_width,
**plot_kwargs,
)
# Scatter plot comparing diversity estimators.
fig4 = px.scatter(
data_frame=df_stats,
x="theta_pi_estimate",
y="theta_w_estimate",
error_x="theta_pi_ci_err",
error_y="theta_w_ci_err",
title="Diversity estimators",
width=scatter_plot_width,
height=scatter_plot_height,
**plot_kwargs,
)
if show: # pragma: no cover
fig1.show(renderer=renderer)
fig2.show(renderer=renderer)
fig3.show(renderer=renderer)
fig4.show(renderer=renderer)
return (fig1, fig2, fig3, fig4)
@_check_types
@doc(
summary="Run iHS GWSS.",
returns=dict(
x="An array containing the window centre point genomic positions.",
ihs="An array with iHS statistic values for each window.",
),
)
def ihs_gwss(
self,
contig: base_params.contig,
analysis: hap_params.analysis = base_params.DEFAULT,
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,
window_size: ihs_params.window_size = ihs_params.window_size_default,
percentiles: ihs_params.percentiles = ihs_params.percentiles_default,
standardize: ihs_params.standardize = True,
standardization_bins: Optional[ihs_params.standardization_bins] = None,
standardization_n_bins: ihs_params.standardization_n_bins = ihs_params.standardization_n_bins_default,
standardization_diagnostics: ihs_params.standardization_diagnostics = False,
filter_min_maf: ihs_params.filter_min_maf = ihs_params.filter_min_maf_default,
compute_min_maf: ihs_params.compute_min_maf = ihs_params.compute_min_maf_default,
min_ehh: ihs_params.min_ehh = ihs_params.min_ehh_default,
max_gap: ihs_params.max_gap = ihs_params.max_gap_default,
gap_scale: ihs_params.gap_scale = ihs_params.gap_scale_default,
include_edges: ihs_params.include_edges = True,
use_threads: ihs_params.use_threads = True,
min_cohort_size: Optional[
base_params.min_cohort_size
] = ihs_params.min_cohort_size_default,
max_cohort_size: Optional[
base_params.max_cohort_size
] = ihs_params.max_cohort_size_default,
random_seed: base_params.random_seed = 42,
chunks: base_params.chunks = base_params.native_chunks,
inline_array: base_params.inline_array = base_params.inline_array_default,
) -> Tuple[np.ndarray, np.ndarray]:
# change this name if you ever change the behaviour of this function, to
# invalidate any previously cached data
name = self._get_ihs_gwss_cache_name()
params = dict(
contig=contig,
analysis=self._prep_phasing_analysis_param(analysis=analysis),
window_size=window_size,
percentiles=percentiles,
standardize=standardize,
standardization_bins=standardization_bins,
standardization_n_bins=standardization_n_bins,
standardization_diagnostics=standardization_diagnostics,
filter_min_maf=filter_min_maf,
compute_min_maf=compute_min_maf,
min_ehh=min_ehh,
include_edges=include_edges,
max_gap=max_gap,
gap_scale=gap_scale,
use_threads=use_threads,
sample_sets=self._prep_sample_sets_param(sample_sets=sample_sets),
# N.B., do not be tempted to convert this sample query into integer
# indices using _prep_sample_selection_params, because the indices
# are different in the haplotype data.
sample_query=self._prep_sample_query_param(sample_query=sample_query),
sample_query_options=sample_query_options,
min_cohort_size=min_cohort_size,
max_cohort_size=max_cohort_size,
random_seed=random_seed,
)
try:
results = self.results_cache_get(name=name, params=params)
except CacheMiss:
results = self._ihs_gwss(chunks=chunks, inline_array=inline_array, **params)
self.results_cache_set(name=name, params=params, results=results)
x = results["x"]
ihs = results["ihs"]
return x, ihs
def _ihs_gwss(
self,
*,
contig,
analysis,
sample_sets,
sample_query,
sample_query_options,
window_size,
percentiles,
standardize,
standardization_bins,
standardization_n_bins,
standardization_diagnostics,
filter_min_maf,
compute_min_maf,
min_ehh,
max_gap,
gap_scale,
include_edges,
use_threads,
min_cohort_size,
max_cohort_size,
random_seed,
chunks,
inline_array,
):
ds_haps = self.haplotypes(
region=contig,
analysis=analysis,
sample_query=sample_query,
sample_query_options=sample_query_options,
sample_sets=sample_sets,
min_cohort_size=min_cohort_size,
max_cohort_size=max_cohort_size,
random_seed=random_seed,
chunks=chunks,
inline_array=inline_array,
)
gt = allel.GenotypeDaskArray(ds_haps["call_genotype"].data)
with self._dask_progress(desc="Load haplotypes"):
ht = gt.to_haplotypes().compute()
with self._spinner(desc="Compute IHS"):
ac = ht.count_alleles(max_allele=1)
pos = ds_haps["variant_position"].values
if filter_min_maf > 0:
af = ac.to_frequencies()
maf = np.min(af, axis=1)
maf_filter = maf > filter_min_maf
ht = ht.compress(maf_filter, axis=0)
pos = pos[maf_filter]
ac = ac[maf_filter]
# compute iHS
ihs = allel.ihs(
h=ht,
pos=pos,
min_maf=compute_min_maf,
min_ehh=min_ehh,
include_edges=include_edges,
max_gap=max_gap,
gap_scale=gap_scale,
use_threads=use_threads,
)
# remove any NaNs
na_mask = ~np.isnan(ihs)
ihs = ihs[na_mask]
pos = pos[na_mask]
ac = ac[na_mask]
# take absolute value
ihs = np.fabs(ihs)
if standardize:
ihs, _ = allel.standardize_by_allele_count(
score=ihs,
aac=ac[:, 1],
bins=standardization_bins,
n_bins=standardization_n_bins,
diagnostics=standardization_diagnostics,
)
if window_size:
ihs = allel.moving_statistic(
ihs, statistic=np.percentile, size=window_size, q=percentiles
)
pos = allel.moving_statistic(pos, statistic=np.mean, size=window_size)
results = dict(x=pos, ihs=ihs)
return results
@_check_types
@doc(
summary="Run and plot iHS GWSS data.",
)
def plot_ihs_gwss_track(
self,
contig: base_params.contig,
analysis: hap_params.analysis = base_params.DEFAULT,
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,
window_size: ihs_params.window_size = ihs_params.window_size_default,
percentiles: ihs_params.percentiles = ihs_params.percentiles_default,
standardize: ihs_params.standardize = True,
standardization_bins: Optional[ihs_params.standardization_bins] = None,
standardization_n_bins: ihs_params.standardization_n_bins = ihs_params.standardization_n_bins_default,
standardization_diagnostics: ihs_params.standardization_diagnostics = False,
filter_min_maf: ihs_params.filter_min_maf = ihs_params.filter_min_maf_default,
compute_min_maf: ihs_params.compute_min_maf = ihs_params.compute_min_maf_default,
min_ehh: ihs_params.min_ehh = ihs_params.min_ehh_default,
max_gap: ihs_params.max_gap = ihs_params.max_gap_default,
gap_scale: ihs_params.gap_scale = ihs_params.gap_scale_default,
include_edges: ihs_params.include_edges = True,
use_threads: ihs_params.use_threads = True,
min_cohort_size: Optional[
base_params.min_cohort_size
] = ihs_params.min_cohort_size_default,
max_cohort_size: Optional[
base_params.max_cohort_size
] = ihs_params.max_cohort_size_default,
random_seed: base_params.random_seed = 42,
palette: ihs_params.palette = ihs_params.palette_default,
title: Optional[gplt_params.title] = None,
sizing_mode: gplt_params.sizing_mode = gplt_params.sizing_mode_default,
width: gplt_params.width = gplt_params.width_default,
height: gplt_params.height = 200,
show: gplt_params.show = True,
x_range: Optional[gplt_params.x_range] = None,
output_backend: gplt_params.output_backend = gplt_params.output_backend_default,
chunks: base_params.chunks = base_params.native_chunks,
inline_array: base_params.inline_array = base_params.inline_array_default,
) -> gplt_params.optional_figure:
# compute ihs
x, ihs = self.ihs_gwss(
contig=contig,
analysis=analysis,
window_size=window_size,
percentiles=percentiles,
standardize=standardize,
standardization_bins=standardization_bins,
standardization_n_bins=standardization_n_bins,
standardization_diagnostics=standardization_diagnostics,
filter_min_maf=filter_min_maf,
compute_min_maf=compute_min_maf,
min_ehh=min_ehh,
max_gap=max_gap,
gap_scale=gap_scale,
include_edges=include_edges,
use_threads=use_threads,
min_cohort_size=min_cohort_size,
max_cohort_size=max_cohort_size,
sample_query=sample_query,
sample_query_options=sample_query_options,
sample_sets=sample_sets,
random_seed=random_seed,
chunks=chunks,
inline_array=inline_array,
)
if len(x) == 0:
raise ValueError(
"No iHS values remain after filtering. "
"Try relaxing filter_min_maf or min_ehh parameters."
)
# determine X axis range
x_min = x[0]
x_max = x[-1]
if x_range is None:
x_range = bokeh.models.Range1d(x_min, x_max, bounds="auto")
# create a figure
xwheel_zoom = bokeh.models.WheelZoomTool(
dimensions="width", maintain_focus=False
)
if title is None:
title = sample_query
fig = bokeh.plotting.figure(
title=title,
tools=[
"xpan",
"xzoom_in",
"xzoom_out",
xwheel_zoom,
"reset",
"save",
"crosshair",
],
active_inspect=None,
active_scroll=xwheel_zoom,
active_drag="xpan",
sizing_mode=sizing_mode,
width=width,
height=height,
toolbar_location="above",
x_range=x_range,
output_backend=output_backend,
)
if window_size:
if isinstance(percentiles, int):
percentiles = (percentiles,)
# Ensure percentiles are sorted so that colors make sense.
percentiles = tuple(sorted(percentiles))