-
Notifications
You must be signed in to change notification settings - Fork 238
/
aggregators.py
1839 lines (1478 loc) · 64.9 KB
/
aggregators.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 difflib
from functools import wraps, update_wrapper
import hail as hl
from hail.expr import (ExpressionException, Expression, ArrayExpression,
SetExpression, BooleanExpression, Int64Expression, NumericExpression,
DictExpression, StructExpression, Float64Expression, StringExpression,
NDArrayNumericExpression, expr_any, expr_oneof, expr_array, expr_set,
expr_bool, expr_numeric, expr_int32, expr_int64, expr_float64, expr_call,
expr_str, expr_ndarray, unify_all, construct_expr, Indices, Aggregation,
to_expr)
from hail.expr.types import (hail_type, tint32, tint64, tfloat32, tfloat64,
tbool, tcall, tset, tarray, tstruct, tdict, ttuple, tstr)
from hail.expr.functions import rbind, float32, _quantile_from_cdf
import hail.ir as ir
from hail.typecheck import (TypeChecker, typecheck_method, typecheck,
sequenceof, func_spec, identity, nullable, oneof)
from hail.utils import wrap_to_list
from hail.utils.java import Env
class AggregableChecker(TypeChecker):
def __init__(self, coercer):
self.coercer = coercer
super(AggregableChecker, self).__init__()
def expects(self):
return self.coercer.expects()
def format(self, arg):
return self.coercer.format(arg)
def check(self, x, caller, param):
x = self.coercer.check(x, caller, param)
if len(x._ir.search(lambda node: isinstance(node, ir.BaseApplyAggOp))) == 0:
raise ExpressionException(f"{caller} must be placed outside of an aggregation. See "
"https://discuss.hail.is/t/breaking-change-redesign-of-aggregator-interface/701")
return x
agg_expr = AggregableChecker
class AggFunc(object):
def __init__(self):
self._as_scan = False
self._agg_bindings = set()
def correct_prefix(self):
return "scan" if self._as_scan else "agg"
def incorrect_prefix(self):
return "agg" if self._as_scan else "scan"
def correct_plural(self):
return "scans" if self._as_scan else "aggregations"
def incorrect_plural(self):
return "aggregations" if self._as_scan else "scans"
def check_scan_agg_compatibility(self, caller, node):
if self._as_scan != isinstance(node, ir.ApplyScanOp):
raise ExpressionException(
"'{correct}.{caller}' cannot contain {incorrect}"
.format(correct=self.correct_prefix(),
caller=caller,
incorrect=self.incorrect_plural()))
@typecheck_method(agg_op=str,
seq_op_args=sequenceof(expr_any),
ret_type=hail_type,
init_op_args=sequenceof(expr_any))
def __call__(self, agg_op, seq_op_args, ret_type, init_op_args=()):
indices, aggregations = unify_all(*seq_op_args, *init_op_args)
if aggregations:
raise ExpressionException('Cannot aggregate an already-aggregated expression')
for a in seq_op_args + init_op_args:
_check_agg_bindings(a, self._agg_bindings)
if self._as_scan:
x = ir.ApplyScanOp(agg_op,
[expr._ir for expr in init_op_args],
[expr._ir for expr in seq_op_args])
aggs = aggregations
else:
x = ir.ApplyAggOp(agg_op,
[expr._ir for expr in init_op_args],
[expr._ir for expr in seq_op_args])
aggs = aggregations.push(Aggregation(*seq_op_args, *init_op_args))
return construct_expr(x, ret_type, Indices(indices.source, set()), aggs)
@typecheck_method(f=func_spec(1, expr_any),
array_agg_expr=expr_oneof(expr_array(), expr_set()))
def explode(self, f, array_agg_expr):
if array_agg_expr._aggregations:
raise ExpressionException("'{}.explode' does not support an already-aggregated expression as the argument to 'collection'".format(self.correct_prefix()))
_check_agg_bindings(array_agg_expr, self._agg_bindings)
if isinstance(array_agg_expr.dtype, tset):
array_agg_expr = hl.array(array_agg_expr)
elt = array_agg_expr.dtype.element_type
var = Env.get_uid()
ref = construct_expr(ir.Ref(var), elt, array_agg_expr._indices)
self._agg_bindings.add(var)
aggregated = f(ref)
_check_agg_bindings(aggregated, self._agg_bindings)
self._agg_bindings.remove(var)
if not self._as_scan and not aggregated._aggregations:
raise ExpressionException("'{}.explode' must take mapping that contains aggregation expression.".format(self.correct_prefix()))
indices, _ = unify_all(array_agg_expr, aggregated)
aggregations = hl.utils.LinkedList(Aggregation)
if not self._as_scan:
aggregations = aggregations.push(Aggregation(array_agg_expr, aggregated))
return construct_expr(ir.AggExplode(ir.ToStream(array_agg_expr._ir), var, aggregated._ir, self._as_scan),
aggregated.dtype,
Indices(indices.source, aggregated._indices.axes),
aggregations)
@typecheck_method(condition=expr_bool,
aggregation=agg_expr(expr_any))
def filter(self, condition, aggregation):
if condition._aggregations:
raise ExpressionException(f"'hl.{self.correct_prefix()}.filter' does not "
f"support an already-aggregated expression as the argument to 'condition'")
if not self._as_scan and not aggregation._aggregations:
raise ExpressionException(f"'hl.{self.correct_prefix()}.filter' "
f"must have aggregation in argument to 'aggregation'")
_check_agg_bindings(condition, self._agg_bindings)
_check_agg_bindings(aggregation, self._agg_bindings)
indices, _ = unify_all(condition, aggregation)
aggregations = hl.utils.LinkedList(Aggregation)
if not self._as_scan:
aggregations = aggregations.push(Aggregation(condition, aggregation))
return construct_expr(ir.AggFilter(condition._ir, aggregation._ir, self._as_scan),
aggregation.dtype,
Indices(indices.source, aggregation._indices.axes),
aggregations)
def group_by(self, group, aggregation):
if group._aggregations:
raise ExpressionException(f"'hl.{self.correct_prefix()}.group_by' "
f"does not support an already-aggregated expression as the argument to 'group'")
if not self._as_scan and not aggregation._aggregations:
raise ExpressionException(f"'hl.{self.correct_prefix()}.group_by' "
f"must have aggregation in argument to 'aggregation'")
_check_agg_bindings(group, self._agg_bindings)
_check_agg_bindings(aggregation, self._agg_bindings)
indices, _ = unify_all(group, aggregation)
aggregations = hl.utils.LinkedList(Aggregation)
if not self._as_scan:
aggregations = aggregations.push(Aggregation(aggregation))
return construct_expr(ir.AggGroupBy(group._ir, aggregation._ir, self._as_scan),
tdict(group.dtype, aggregation.dtype),
Indices(indices.source, aggregation._indices.axes),
aggregations)
def array_agg(self, array, f):
if array._aggregations:
raise ExpressionException(f"'hl.{self.correct_prefix()}.array_agg' "
f"does not support an already-aggregated expression as the argument to 'array'")
_check_agg_bindings(array, self._agg_bindings)
elt = array.dtype.element_type
var = Env.get_uid()
ref = construct_expr(ir.Ref(var), elt, array._indices)
self._agg_bindings.add(var)
aggregated = f(ref)
_check_agg_bindings(aggregated, self._agg_bindings)
self._agg_bindings.remove(var)
if not self._as_scan and not aggregated._aggregations:
raise ExpressionException(f"'hl.{self.correct_prefix()}.array_agg' "
f"must take mapping that contains aggregation expression.")
indices, _ = unify_all(array, aggregated)
aggregations = hl.utils.LinkedList(Aggregation)
if not self._as_scan:
aggregations = aggregations.push(Aggregation(array, aggregated))
return construct_expr(ir.AggArrayPerElement(array._ir, var, 'unused', aggregated._ir, self._as_scan),
tarray(aggregated.dtype),
Indices(indices.source, aggregated._indices.axes),
aggregations)
@property
def context(self):
if self._as_scan:
return 'scan'
else:
return 'agg'
_agg_func = AggFunc()
def _check_agg_bindings(expr, bindings):
bound_references = {ref.name for ref in expr._ir.search(
lambda x: isinstance(x, ir.Ref)
and not isinstance(x, ir.TopLevelReference)
and not x.name.startswith('__uid_scan')
and not x.name.startswith('__uid_agg'))}
free_variables = bound_references - expr._ir.bound_variables - bindings
if free_variables:
raise ExpressionException("dynamic variables created by 'hl.bind' or lambda methods like 'hl.map' may not be aggregated")
@typecheck(expr=expr_numeric, k=int)
def approx_cdf(expr, k=100):
"""Produce a summary of the distribution of values.
Notes
-----
This method returns a struct containing two arrays: `values` and `ranks`.
The `values` array contains an ordered sample of values seen. The `ranks`
array is one longer, and contains the approximate ranks for the
corresponding values.
These represent a summary of the CDF of the distribution of values. In
particular, for any value `x = values(i)` in the summary, we estimate that
there are `ranks(i)` values strictly less than `x`, and that there are
`ranks(i+1)` values less than or equal to `x`. For any value `y` (not
necessarily in the summary), we estimate CDF(y) to be `ranks(i)`, where `i`
is such that `values(i-1) < y ≤ values(i)`.
An alternative intuition is that the summary encodes a compressed
approximation to the sorted list of values. For example, values=[0,2,5,6,9]
and ranks=[0,3,4,5,8,10] represents the approximation [0,0,0,2,5,6,6,6,9,9],
with the value `values(i)` occupying indices `ranks(i)` (inclusive) to
`ranks(i+1)` (exclusive).
The returned struct also contains an array `_compaction_counts`, which is
used internally to support downstream error estimation.
Warning
-------
This is an approximate and nondeterministic method.
Parameters
----------
expr : :class:`.Expression`
Expression to collect.
k : :obj:`int`
Parameter controlling the accuracy vs. memory usage tradeoff.
Returns
-------
:class:`.StructExpression`
Struct containing `values` and `ranks` arrays.
"""
res = _agg_func('ApproxCDF', [hl.float64(expr)],
tstruct(values=tarray(tfloat64), ranks=tarray(tint64), _compaction_counts=tarray(tint32)),
init_op_args=[k])
conv = {
tint32: lambda x: x.map(hl.int),
tint64: lambda x: x.map(hl.int64),
tfloat32: lambda x: x.map(hl.float32),
tfloat64: identity
}
return hl.struct(values=conv[expr.dtype](res.values), ranks=res.ranks, _compaction_counts=res._compaction_counts)
@typecheck(expr=expr_numeric, qs=expr_oneof(expr_numeric, expr_array(expr_numeric)), k=int)
def approx_quantiles(expr, qs, k=100) -> Expression:
"""Compute an array of approximate quantiles.
Examples
--------
Estimate the median of the `HT` field.
>>> table1.aggregate(hl.agg.approx_quantiles(table1.HT, 0.5)) # doctest: +SKIP_OUTPUT_CHECK
64
Estimate the quartiles of the `HT` field.
>>> table1.aggregate(hl.agg.approx_quantiles(table1.HT, [0, 0.25, 0.5, 0.75, 1])) # doctest: +SKIP_OUTPUT_CHECK
[50, 60, 64, 71, 86]
Warning
-------
This is an approximate and nondeterministic method.
Parameters
----------
expr : :class:`.Expression`
Expression to collect.
qs : :class:`.NumericExpression` or :class:`.ArrayNumericExpression`
Number or array of numbers between 0 and 1.
k : :obj:`int`
Parameter controlling the accuracy vs. memory usage tradeoff. Increasing k increases both memory use and accuracy.
Returns
-------
:class:`.NumericExpression` or :class:`.ArrayNumericExpression`
If `qs` is a single number, returns the estimated quantile.
If `qs` is an array, returns the array of estimated quantiles.
"""
if isinstance(qs.dtype, tarray):
return rbind(approx_cdf(expr, k), lambda cdf: qs.map(lambda q: _quantile_from_cdf(cdf, float32(q))))
else:
return _quantile_from_cdf(approx_cdf(expr, k), qs)
@typecheck(expr=expr_numeric, k=int)
def approx_median(expr, k=100) -> Expression:
"""Compute the approximate median. This function is a shorthand for `approx_quantiles(expr, .5, k)`
Examples
--------
Estimate the median of the `HT` field.
>>> table1.aggregate(hl.agg.approx_median(table1.HT)) # doctest: +SKIP_OUTPUT_CHECK
64
Warning
-------
This is an approximate and nondeterministic method.
Parameters
----------
expr : :class:`.Expression`
Expression to collect.
k : :obj:`int`
Parameter controlling the accuracy vs. memory usage tradeoff. Increasing k increases both memory use and accuracy.
See Also
--------
:func:`approx_quantiles`
Returns
-------
:class:`.NumericExpression`
The estimated median.
"""
return approx_quantiles(expr, .5, k)
@typecheck(expr=expr_any)
def collect(expr) -> ArrayExpression:
"""Collect records into an array.
Examples
--------
Collect the `ID` field where `HT` is greater than 68:
>>> table1.aggregate(hl.agg.filter(table1.HT > 68, hl.agg.collect(table1.ID)))
[2, 3]
Notes
-----
The element order of the resulting array is not guaranteed, and in some
cases is non-deterministic.
Use :meth:`collect_as_set` to collect unique items.
Warning
-------
Collecting a large number of items can cause out-of-memory exceptions.
Parameters
----------
expr : :class:`.Expression`
Expression to collect.
Returns
-------
:class:`.ArrayExpression`
Array of all `expr` records.
"""
return _agg_func('Collect', [expr], tarray(expr.dtype))
@typecheck(expr=expr_any)
def collect_as_set(expr) -> SetExpression:
"""Collect records into a set.
Examples
--------
Collect the unique `ID` field where `HT` is greater than 68:
>>> table1.aggregate(hl.agg.filter(table1.HT > 68, hl.agg.collect_as_set(table1.ID)))
{2, 3}
Warning
-------
Collecting a large number of items can cause out-of-memory exceptions.
Parameters
----------
expr : :class:`.Expression`
Expression to collect.
Returns
-------
:class:`.SetExpression`
Set of unique `expr` records.
"""
return _agg_func('CollectAsSet', [expr], tset(expr.dtype))
@typecheck()
def count() -> Int64Expression:
"""Count the number of records.
Examples
--------
Group by the `SEX` field and count the number of rows in each category:
>>> (table1.group_by(table1.SEX)
... .aggregate(n=hl.agg.count())
... .show())
+-----+-------+
| SEX | n |
+-----+-------+
| str | int64 |
+-----+-------+
| "F" | 2 |
| "M" | 2 |
+-----+-------+
Returns
-------
:class:`.Expression` of type :py:data:`.tint64`
Total number of records.
"""
return _agg_func('Count', [], tint64)
@typecheck(condition=expr_bool)
def count_where(condition) -> Int64Expression:
"""Count the number of records where a predicate is ``True``.
Examples
--------
Count the number of individuals with `HT` greater than 68:
>>> table1.aggregate(hl.agg.count_where(table1.HT > 68))
2
Parameters
----------
condition : :class:`.BooleanExpression`
Criteria for inclusion.
Returns
-------
:class:`.Expression` of type :py:data:`.tint64`
Total number of records where `condition` is ``True``.
"""
return _agg_func('Sum', [hl.int64(condition)], tint64)
@typecheck(condition=expr_bool)
def any(condition) -> BooleanExpression:
"""Returns ``True`` if `condition` is ``True`` for any record.
Examples
--------
>>> (table1.group_by(table1.SEX)
... .aggregate(any_over_70 = hl.agg.any(table1.HT > 70))
... .show())
+-----+-------------+
| SEX | any_over_70 |
+-----+-------------+
| str | bool |
+-----+-------------+
| "F" | false |
| "M" | true |
+-----+-------------+
Notes
-----
If there are no records to aggregate, the result is ``False``.
Missing records are not considered. If every record is missing,
the result is also ``False``.
Parameters
----------
condition : :class:`.BooleanExpression`
Condition to test.
Returns
-------
:class:`.BooleanExpression`
"""
return count_where(condition) > 0
@typecheck(condition=expr_bool)
def all(condition) -> BooleanExpression:
"""Returns ``True`` if `condition` is ``True`` for every record.
Examples
--------
>>> (table1.group_by(table1.SEX)
... .aggregate(all_under_70 = hl.agg.all(table1.HT < 70))
... .show())
+-----+--------------+
| SEX | all_under_70 |
+-----+--------------+
| str | bool |
+-----+--------------+
| "F" | false |
| "M" | false |
+-----+--------------+
Notes
-----
If there are no records to aggregate, the result is ``True``.
Missing records are not considered. If every record is missing,
the result is also ``True``.
Parameters
----------
condition : :class:`.BooleanExpression`
Condition to test.
Returns
-------
:class:`.BooleanExpression`
"""
return count_where(~condition) == 0
@typecheck(expr=expr_any, weight=nullable(expr_numeric))
def counter(expr, *, weight=None) -> DictExpression:
"""Count the occurrences of each unique record and return a dictionary.
Examples
--------
Count the number of individuals for each unique `SEX` value:
>>> table1.aggregate(hl.agg.counter(table1.SEX))
{'F': 2, 'M': 2}
<BLANKLINE>
Compute the total height for each unique `SEX` value:
>>> table1.aggregate(hl.agg.counter(table1.SEX, weight=table1.HT))
{'F': 130, 'M': 137}
<BLANKLINE>
Notes
-----
If you need a more complex grouped aggregation than :func:`counter`
supports, try using :func:`group_by`.
This aggregator method returns a dict expression whose key type is the
same type as `expr` and whose value type is :class:`.Expression` of type :py:data:`.tint64`.
This dict contains a key for each unique value of `expr`, and the value
is the number of times that key was observed.
Ensure that the result can be stored in memory on a single machine.
Warning
-------
Using :meth:`counter` with a large number of unique items can cause
out-of-memory exceptions.
Parameters
----------
expr : :class:`.Expression`
Expression to count by key.
weight : :class:`.NumericExpression`, optional
Expression by which to weight each occurence (when unspecified,
it is effectively ``1``)
Returns
-------
:class:`.DictExpression`
Dictionary with the number of occurrences of each unique record.
"""
if weight is None:
return _agg_func.group_by(expr, count())
return _agg_func.group_by(expr, hl.agg.sum(weight))
@typecheck(expr=expr_any,
n=int,
ordering=nullable(oneof(expr_any, func_spec(1, expr_any))))
def take(expr, n, ordering=None) -> ArrayExpression:
"""Take `n` records of `expr`, optionally ordered by `ordering`.
Examples
--------
Take 3 elements of field `X`:
>>> table1.aggregate(hl.agg.take(table1.X, 3))
[5, 6, 7]
Take the `ID` and `HT` fields, ordered by `HT` (descending):
>>> table1.aggregate(hl.agg.take(hl.struct(ID=table1.ID, HT=table1.HT),
... 3,
... ordering=-table1.HT))
[Struct(ID=2, HT=72), Struct(ID=3, HT=70), Struct(ID=1, HT=65)]
Notes
-----
The resulting array can include fewer than `n` elements if there are fewer
than `n` total records.
The `ordering` argument may be an expression, a function, or ``None``.
If `ordering` is an expression, this expression's type should be one with
a natural ordering (e.g. numeric).
If `ordering` is a function, it will be evaluated on each record of `expr`
to compute the value used for ordering. In the above example,
``ordering=-table1.HT`` and ``ordering=lambda x: -x.HT`` would be
equivalent.
If `ordering` is ``None``, then there is no guaranteed ordering on the
elements taken, and and the results may be non-deterministic.
Missing values are always sorted **last**.
Parameters
----------
expr : :class:`.Expression`
Expression to store.
n : :class:`.Expression` of type :py:data:`.tint32`
Number of records to take.
ordering : :class:`.Expression` or function ((arg) -> :class:`.Expression`) or None
Optional ordering on records.
Returns
-------
:class:`.ArrayExpression`
Array of up to `n` records of `expr`.
"""
n = to_expr(n)
if ordering is None:
return _agg_func('Take', [expr], tarray(expr.dtype), [n])
else:
return _agg_func('TakeBy', [expr, ordering], tarray(expr.dtype), [n])
@typecheck(expr=expr_numeric)
def min(expr) -> NumericExpression:
"""Compute the minimum `expr`.
Examples
--------
Compute the minimum value of `HT`:
>>> table1.aggregate(hl.agg.min(table1.HT))
60
Notes
-----
This function returns the minimum non-missing value. If there are no
non-missing values, then the result is missing.
For back-compatibility reasons, this function also ignores NaN, in contrast
with :func:`.functions.min`. The behavior is similar to
:func:`.functions.nanmin`.
Parameters
----------
expr : :class:`.NumericExpression`
Numeric expression.
Returns
-------
:class:`.NumericExpression`
Minimum value of all `expr` records, same type as `expr`.
"""
return _agg_func('Min', [expr], expr.dtype)
@typecheck(expr=expr_numeric)
def max(expr) -> NumericExpression:
"""Compute the maximum `expr`.
Examples
--------
Compute the maximum value of `HT`:
>>> table1.aggregate(hl.agg.max(table1.HT))
72
Notes
-----
This function returns the maximum non-missing value. If there are no
non-missing values, then the result is missing.
For back-compatibility reasons, this function also ignores NaN, in contrast
with :func:`.functions.max`. The behavior is similar to
:func:`.functions.nanmax`.
Parameters
----------
expr : :class:`.NumericExpression`
Numeric expression.
Returns
-------
:class:`.NumericExpression`
Maximum value of all `expr` records, same type as `expr`.
"""
return _agg_func('Max', [expr], expr.dtype)
@typecheck(expr=expr_oneof(expr_int64, expr_float64))
def sum(expr):
"""Compute the sum of all records of `expr`.
Examples
--------
Compute the sum of field `C1`:
>>> table1.aggregate(hl.agg.sum(table1.C1))
25
Notes
-----
Missing values are ignored (treated as zero).
If `expr` is an expression of type :py:data:`.tint32`, :py:data:`.tint64`,
or :py:data:`.tbool`, then the result is an expression of type
:py:data:`.tint64`. If `expr` is an expression of type :py:data:`.tfloat32`
or :py:data:`.tfloat64`, then the result is an expression of type
:py:data:`.tfloat64`.
Warning
-------
Boolean values are cast to integers before computing the sum.
Parameters
----------
expr : :class:`.NumericExpression`
Numeric expression.
Returns
-------
:class:`.Expression` of type :py:data:`.tint64` or :py:data:`.tfloat64`
Sum of records of `expr`.
"""
return _agg_func('Sum', [expr], expr.dtype)
@typecheck(expr=expr_array(expr_oneof(expr_int64, expr_float64)))
def array_sum(expr) -> ArrayExpression:
"""Compute the coordinate-wise sum of all records of `expr`.
Examples
--------
Compute the sum of `C1` and `C2`:
>>> table1.aggregate(hl.agg.array_sum([table1.C1, table1.C2]))
[25, 282]
Notes
------
All records must have the same length. Each coordinate is summed
independently as described in :func:`sum`.
Parameters
----------
expr : :class:`.ArrayNumericExpression`
Returns
-------
:class:`.ArrayExpression` with element type :py:data:`.tint64` or :py:data:`.tfloat64`
"""
return array_agg(hl.agg.sum, expr)
@typecheck(expr=expr_ndarray())
def ndarray_sum(expr) -> NDArrayNumericExpression:
""" Compute the sum of all records of `expr` of the same shape.
:param expr:
:return:
"""
return _agg_func("NDArraySum", [expr], expr.dtype)
@typecheck(expr=expr_float64)
def mean(expr) -> Float64Expression:
"""Compute the mean value of records of `expr`.
Examples
--------
Compute the mean of field `HT`:
>>> table1.aggregate(hl.agg.mean(table1.HT))
66.75
Notes
-----
Missing values are ignored.
Parameters
----------
expr : :class:`.NumericExpression`
Numeric expression.
Returns
-------
:class:`.Expression` of type :py:data:`.tfloat64`
Mean value of records of `expr`.
"""
return hl.bind(lambda expr: sum(expr) / count_where(hl.is_defined(expr)), expr, _ctx=_agg_func.context)
@typecheck(expr=expr_float64)
def stats(expr) -> StructExpression:
"""Compute a number of useful statistics about `expr`.
Examples
--------
Compute statistics about field `HT`:
>>> table1.aggregate(hl.agg.stats(table1.HT)) #doctest: +SKIP
Struct(mean=66.75, stdev=4.656984002549289, min=60.0, max=72.0, n=4, sum=267.0)
Notes
-----
Computes a struct with the following fields:
- `min` (:py:data:`.tfloat64`) - Minimum value.
- `max` (:py:data:`.tfloat64`) - Maximum value.
- `mean` (:py:data:`.tfloat64`) - Mean value,
- `stdev` (:py:data:`.tfloat64`) - Standard deviation.
- `n` (:py:data:`.tint64`) - Number of non-missing records.
- `sum` (:py:data:`.tfloat64`) - Sum.
Parameters
----------
expr : :class:`.NumericExpression`
Numeric expression.
Returns
-------
:class:`.StructExpression`
Struct expression with fields `mean`, `stdev`, `min`, `max`,
`n`, and `sum`.
"""
return hl.bind(
lambda expr: hl.bind(
lambda aggs: hl.bind(
lambda mean: hl.struct(
mean=mean,
stdev=hl.sqrt(hl.float64(
aggs.sumsq - (2 * mean * aggs.sum) + (aggs.n_def * mean ** 2)) / aggs.n_def),
min=hl.float64(aggs.min),
max=hl.float64(aggs.max),
n=aggs.n_def,
sum=hl.float64(aggs.sum)
), hl.float64(aggs.sum) / aggs.n_def),
hl.struct(n_def=count_where(hl.is_defined(expr)),
sum=sum(expr),
sumsq=sum(expr ** 2),
min=min(expr),
max=max(expr))),
expr, _ctx=_agg_func.context)
@typecheck(expr=expr_oneof(expr_int64, expr_float64))
def product(expr):
"""Compute the product of all records of `expr`.
Examples
--------
Compute the product of field `C1`:
>>> table1.aggregate(hl.agg.product(table1.C1))
440
Notes
-----
Missing values are ignored (treated as one).
If `expr` is an expression of type :py:data:`.tint32`, :py:data:`.tint64` or
:py:data:`.tbool`, then the result is an expression of type
:py:data:`.tint64`. If `expr` is an expression of type :py:data:`.tfloat32`
or :py:data:`.tfloat64`, then the result is an expression of type
:py:data:`.tfloat64`.
Warning
-------
Boolean values are cast to integers before computing the product.
Parameters
----------
expr : :class:`.NumericExpression`
Numeric expression.
Returns
-------
:class:`.Expression` of type :py:data:`.tint64` or :py:data:`.tfloat64`
Product of records of `expr`.
"""
return _agg_func('Product', [expr], expr.dtype)
@typecheck(predicate=expr_bool)
def fraction(predicate) -> Float64Expression:
"""Compute the fraction of records where `predicate` is ``True``.
Examples
--------
Compute the fraction of rows where `SEX` is "F" and `HT` > 65:
>>> table1.aggregate(hl.agg.fraction((table1.SEX == 'F') & (table1.HT > 65)))
0.25
Notes
-----
Missing values for `predicate` are treated as ``False``.
Parameters
----------
predicate : :class:`.BooleanExpression`
Boolean predicate.
Returns
-------
:class:`.Expression` of type :py:data:`.tfloat64`
Fraction of records where `predicate` is ``True``.
"""
return hl.bind(lambda n: hl.cond(n == 0, hl.null(hl.tfloat64),
hl.float64(filter(predicate, count())) / n),
count())
@typecheck(expr=expr_call)
def hardy_weinberg_test(expr) -> StructExpression:
"""Performs test of Hardy-Weinberg equilibrium.
Examples
--------
Test each row of a dataset:
>>> dataset_result = dataset.annotate_rows(hwe = hl.agg.hardy_weinberg_test(dataset.GT))
Test each row on a sub-population:
>>> dataset_result = dataset.annotate_rows(
... hwe_eas = hl.agg.filter(dataset.pop == 'EAS',
... hl.agg.hardy_weinberg_test(dataset.GT)))
Notes
-----
This method performs the test described in :func:`.functions.hardy_weinberg_test` based solely on
the counts of homozygous reference, heterozygous, and homozygous variant calls.
The resulting struct expression has two fields:
- `het_freq_hwe` (:py:data:`.tfloat64`) - Expected frequency
of heterozygous calls under Hardy-Weinberg equilibrium.
- `p_value` (:py:data:`.tfloat64`) - p-value from test of Hardy-Weinberg
equilibrium.
Hail computes the exact p-value with mid-p-value correction, i.e. the
probability of a less-likely outcome plus one-half the probability of an
equally-likely outcome. See this `document <LeveneHaldane.pdf>`__ for
details on the Levene-Haldane distribution and references.
Warning
-------
Non-diploid calls (``ploidy != 2``) are ignored in the counts. While the
counts are defined for multiallelic variants, this test is only statistically
rigorous in the biallelic setting; use :func:`~hail.methods.split_multi`
to split multiallelic variants beforehand.
Parameters
----------
expr : :class:`.CallExpression`
Call to test for Hardy-Weinberg equilibrium.
Returns
-------
:class:`.StructExpression`
Struct expression with fields `het_freq_hwe` and `p_value`.
"""
return hl.rbind(
hl.rbind(
expr,
lambda call: filter(call.ploidy == 2, counter(call.n_alt_alleles())
.map_values(lambda i: hl.case()
.when(i < 1 << 31, hl.int(i))