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

Add random laplace number and div_or_else function #155

Merged
merged 2 commits into from
Nov 23, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions quinn/math.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""Math routines for PySpark."""
from __future__ import annotations

from typing import Optional, Union

from pyspark.sql import Column
from pyspark.sql import functions as F # noqa: N812


def rand_laplace(
mu: Union[float, Column],
beta: Union[float, Column],
seed: Optional[int] = None,
) -> Column:
"""Generate random numbers from Laplace(mu, beta).
:param mu: mu parameter of Laplace distribution
:param beta: beta parameter of Laplace distribution
:param seed: random seed value (optional, default None)
:returns: column with random numbers
"""
if not isinstance(mu, Column):
mu = F.lit(mu)

if not isinstance(beta, Column):
beta = F.lit(beta)

u = F.rand(seed)

return (
F.when(u < F.lit(0.5), mu + beta * F.log(2 * u))
.otherwise(mu - beta * F.log(2 * (1 - u)))
.alias("laplace_random")
)


def div_or_else(
cola: Column,
colb: Column,
default: Union[float, Column] = 0.0,
) -> Column:
"""Return result of division of cola by colb or default if colb is zero.
:param cola: dividend
:param colb: divisor
:param default: default value
:returns: result of division or zero
"""
if not isinstance(default, Column):
default = F.lit(default)

return F.when(colb == F.lit(0.0), default).otherwise(cola / colb)