Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[hail] hl.range supports a single argument #6903

Merged
merged 4 commits into from Aug 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 12 additions & 3 deletions hail/python/hail/expr/functions.py
Expand Up @@ -1880,23 +1880,29 @@ def qpois(p, lamb, lower_tail=True, log_p=False) -> Float64Expression:
return _func("qpois", tint32, p, lamb, lower_tail, log_p)


@typecheck(start=expr_int32, stop=expr_int32, step=expr_int32)
def range(start, stop, step=1) -> ArrayNumericExpression:
@typecheck(start=expr_int32, stop=nullable(expr_int32), step=expr_int32)
def range(start, stop=None, step=1) -> ArrayNumericExpression:
"""Returns an array of integers from `start` to `stop` by `step`.

Examples
--------

>>> hl.eval(hl.range(0, 10))
>>> hl.eval(hl.range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> hl.eval(hl.range(3, 10))
[3, 4, 5, 6, 7, 8, 9]

>>> hl.eval(hl.range(0, 10, step=3))
[0, 3, 6, 9]

Notes
-----
The range includes `start`, but excludes `stop`.

If provided exactly one argument, the argument is interpreted as `stop` and
`start` is set to zero. This matches the behavior Python's ``range``.

Parameters
----------
start : int or :class:`.Expression` of type :py:data:`.tint32`
Expand All @@ -1910,6 +1916,9 @@ def range(start, stop, step=1) -> ArrayNumericExpression:
-------
:class:`.ArrayInt32Expression`
"""
if stop is None:
stop = start
start = hl.literal(0)
return apply_expr(lambda sta, sto, ste: ArrayRange(sta, sto, ste), tarray(tint32), start, stop, step)


Expand Down
16 changes: 16 additions & 0 deletions hail/python/test/hail/expr/test_expr.py
Expand Up @@ -41,6 +41,22 @@ def test_random_function(rand_f):
test_random_function(lambda: hl.rand_cat(hl.array([1, 1, 1, 1])))
test_random_function(lambda: hl.rand_dirichlet(hl.array([1, 1, 1, 1])))

def test_range(self):
def same_as_python(*args):
self.assertEqual(hl.eval(hl.range(*args)), list(range(*args)))

same_as_python(10)
same_as_python(3, 10)
same_as_python(3, 10, 2)
same_as_python(3, 10, 3)
same_as_python(-5)
same_as_python(10, -5)
same_as_python(10, -5, -1)
same_as_python(10, -5, -4)

with self.assertRaisesRegex(hl.utils.FatalError, 'Array range cannot have step size 0'):
hl.eval(hl.range(0, 1, 0))

def test_seeded_sampling(self):
sampled1 = hl.utils.range_table(50, 6).filter(hl.rand_bool(0.5))
sampled2 = hl.utils.range_table(50, 5).filter(hl.rand_bool(0.5))
Expand Down