Skip to content

tea_tasting.utils #

Useful functions and classes.

check_scalar(value, name='value', *, typ=None, ge=None, gt=None, le=None, lt=None, ne=None, in_=None) #

Check if a scalar parameter meets specified type and value constraints.

Parameters:

Name Type Description Default
value R

Parameter value.

required
name str

Parameter name.

'value'
typ Any

Acceptable data types.

None
ge Any

If not None, check that parameter value is greater than or equal to ge.

None
gt Any

If not None, check that parameter value is greater than gt.

None
le Any

If not None, check that parameter value is less than or equal to le.

None
lt Any

If not None, check that parameter value is less than lt.

None
ne Any

If not None, check that parameter value is not equal to ne.

None
in_ Any

If not None, check that parameter value is in in_.

None

Returns:

Type Description
R

Parameter value.

Source code in src/tea_tasting/utils.py
def check_scalar(  # noqa: PLR0913
    value: R,
    name: str = "value",
    *,
    typ: Any = None,
    ge: Any = None,
    gt: Any = None,
    le: Any = None,
    lt: Any = None,
    ne: Any = None,
    in_: Any = None,
) -> R:
    """Check if a scalar parameter meets specified type and value constraints.

    Args:
        value: Parameter value.
        name: Parameter name.
        typ: Acceptable data types.
        ge: If not `None`, check that parameter value is greater than
            or equal to `ge`.
        gt: If not `None`, check that parameter value is greater than `gt`.
        le: If not `None`, check that parameter value is less than or equal to `le`.
        lt: If not `None`, check that parameter value is less than `lt`.
        ne: If not `None`, check that parameter value is not equal to `ne`.
        in_: If not `None`, check that parameter value is in `in_`.

    Returns:
        Parameter value.
    """
    if typ is not None and not isinstance(value, typ):
        raise TypeError(f"{name} must be an instance of {typ}.")
    if ge is not None and value < ge:
        raise ValueError(f"{name} == {value}, must be >= {ge}.")
    if gt is not None and value <= gt:
        raise ValueError(f"{name} == {value}, must be > {gt}.")
    if le is not None and value > le:
        raise ValueError(f"{name} == {value}, must be <= {le}.")
    if lt is not None and value >= lt:
        raise ValueError(f"{name} == {value}, must be < {lt}.")
    if ne is not None and value == ne:
        raise ValueError(f"{name} == {value}, must be != {ne}.")
    if in_ is not None and value not in in_:
        raise ValueError(f"{name} == {value}, must be in {in_}.")
    return value

auto_check(value, name) #

Automatically check a parameter's type and value based on its name.

The following parameter names are supported: "alpha", "alternative", "confidence_level", "correction", "equal_var", "n_obs", "n_resamples", "power", "ratio", "use_t".

Parameters:

Name Type Description Default
value R

Parameter value.

required
name str

Parameter name.

required

Returns:

Type Description
R

Parameter value.

Source code in src/tea_tasting/utils.py
def auto_check(value: R, name: str) -> R:  # noqa: C901, PLR0912
    """Automatically check a parameter's type and value based on its name.

    The following parameter names are supported: `"alpha"`, `"alternative"`,
    `"confidence_level"`, `"correction"`, `"equal_var"`, `"n_obs"`,
    `"n_resamples"`, `"power"`, `"ratio"`, `"use_t"`.

    Args:
        value: Parameter value.
        name: Parameter name.

    Returns:
        Parameter value.
    """
    if name == "alpha":
        check_scalar(value, name, typ=float, gt=0, lt=1)
    if name == "alternative":
        check_scalar(value, name, typ=str, in_={"two-sided", "greater", "less"})
    elif name == "confidence_level":
        check_scalar(value, name, typ=float, gt=0, lt=1)
    elif name == "correction":
        check_scalar(value, name, typ=bool)
    elif name == "equal_var":
        check_scalar(value, name, typ=bool)
    elif name == "n_obs":
        check_scalar(value, name, typ=int | Sequence | None)
        if isinstance(value, int):
            check_scalar(value, name, gt=1)
        if isinstance(value, Sequence):
            for val in value:
                check_scalar(val, name, typ=int, gt=1)
    elif name == "n_resamples":
        check_scalar(value, name, typ=int, gt=0)
    elif name == "power":
        check_scalar(value, name, typ=float, gt=0, lt=1)
    elif name == "ratio":
        check_scalar(value, name, typ=float | int, gt=0)
    elif name == "use_t":
        check_scalar(value, name, typ=bool)
    return value

format_num(val, sig=3, *, pct=False, nan='-', inf='∞', fixed_point_limit=0.001, thousands_sep=None, decimal_point=None) #

Format a number according to specified formatting rules.

Parameters:

Name Type Description Default
val float | int | None

Number to format.

required
sig int

Number of significant digits.

3
pct bool

If True, format as a percentage.

False
nan str

Replacement for None and nan values.

'-'
inf str

Replacement for infinite values.

'∞'
fixed_point_limit float

Limit, below which number is formatted as exponential.

0.001
thousands_sep str | None

Thousands separator. If None, the value from locales is used.

None
decimal_point str | None

Decimal point symbol. If None, the value from locales is used.

None

Returns:

Type Description
str

Formatted number.

Source code in src/tea_tasting/utils.py
def format_num(
    val: float | int | None,
    sig: int = 3,
    *,
    pct: bool = False,
    nan: str = "-",
    inf: str = "∞",
    fixed_point_limit: float = 0.001,
    thousands_sep: str | None = None,
    decimal_point: str | None = None,
) -> str:
    """Format a number according to specified formatting rules.

    Args:
        val: Number to format.
        sig: Number of significant digits.
        pct: If `True`, format as a percentage.
        nan: Replacement for `None` and `nan` values.
        inf: Replacement for infinite values.
        fixed_point_limit: Limit, below which number is formatted as exponential.
        thousands_sep: Thousands separator. If `None`, the value from locales is used.
        decimal_point: Decimal point symbol. If `None`, the value from locales is used.

    Returns:
        Formatted number.
    """
    if val is None or math.isnan(val):
        return nan

    if math.isinf(val):
        return inf if val > 0 else "-" + inf

    if pct:
        val = val * 100

    if abs(val) < fixed_point_limit:
        precision = max(0, sig - 1)
        typ = "e" if val != 0 else "f"
    else:
        precision = max(0, sig - 1 - int(math.floor(math.log10(abs(val)))))
        val = round(val, precision)
        # Repeat in order to format 99.999 as "100", not "100.0".
        precision = max(0, sig - 1 - int(math.floor(math.log10(abs(val)))))
        typ = "f"

    result = format(val, f"_.{precision}{typ}")

    if thousands_sep is None:
        thousands_sep = locale.localeconv().get("thousands_sep", "_")  # type: ignore
    if thousands_sep is not None and thousands_sep != "_":
        result = result.replace("_", thousands_sep)

    if decimal_point is None:
        decimal_point = locale.localeconv().get("decimal_point", ".")  # type: ignore
    if decimal_point is not None and decimal_point != ".":
        result = result.replace(".", decimal_point)

    if pct:
        return result + "%"

    return result

get_and_format_num(data, key) #

Get and format dictionary value.

Parameters:

Name Type Description Default
data dict[str, Any]

Dictionary.

required
key str

Key.

required

Returns:

Type Description
str

Formatted value.

Formatting rules
  • If a name starts with "rel_" or equals to "power" consider it a percentage value. Round percentage values to 2 significant digits, multiply by 100 and add "%".
  • Round other values to 3 significant values.
  • If value is less than 0.001, format it in exponential presentation.
  • If a name ends with "_ci", consider it a confidence interval. Look up for attributes "{name}_lower" and "{name}_upper", and format the interval as "[{lower_bound}, {lower_bound}]".
Source code in src/tea_tasting/utils.py
def get_and_format_num(data: dict[str, Any], key: str) -> str:
    """Get and format dictionary value.

    Args:
        data: Dictionary.
        key: Key.

    Returns:
        Formatted value.

    Formatting rules:
        - If a name starts with `"rel_"` or equals to `"power"` consider it
            a percentage value. Round percentage values to 2 significant digits,
            multiply by `100` and add `"%"`.
        - Round other values to 3 significant values.
        - If value is less than `0.001`, format it in exponential presentation.
        - If a name ends with `"_ci"`, consider it a confidence interval.
            Look up for attributes `"{name}_lower"` and `"{name}_upper"`,
            and format the interval as `"[{lower_bound}, {lower_bound}]"`.
    """
    if key.endswith("_ci"):
        ci_lower = get_and_format_num(data, key + "_lower")
        ci_upper = get_and_format_num(data, key + "_upper")
        return f"[{ci_lower}, {ci_upper}]"

    val = data.get(key)
    if not isinstance(val, float | int | None):
        return str(val)

    sig, pct = (2, True) if key.startswith("rel_") or key == "power" else (3, False)
    return format_num(val, sig=sig, pct=pct)

PrettyDictsMixin #

Bases: ABC

Pretty representation of a sequence of dictionaries.

Default formatting rules
  • If a name starts with "rel_" or equals to "power" consider it a percentage value. Round percentage values to 2 significant digits, multiply by 100 and add "%".
  • Round other values to 3 significant values.
  • If value is less than 0.001, format it in exponential presentation.
  • If a name ends with "_ci", consider it a confidence interval. Look up for attributes "{name}_lower" and "{name}_upper", and format the interval as "[{lower_bound}, {lower_bound}]".

to_dicts() abstractmethod #

Convert the object to a sequence of dictionaries.

Source code in src/tea_tasting/utils.py
@abc.abstractmethod
def to_dicts(self) -> Sequence[dict[str, Any]]:
    """Convert the object to a sequence of dictionaries."""

to_pandas() #

Convert the object to a Pandas DataFrame.

Source code in src/tea_tasting/utils.py
def to_pandas(self) -> pd.DataFrame:
    """Convert the object to a Pandas DataFrame."""
    return pd.DataFrame.from_records(self.to_dicts())

to_pretty(keys=None, formatter=get_and_format_num) #

Convert the object to a Pandas Dataframe with formatted values.

Parameters:

Name Type Description Default
keys Sequence[str] | None

Keys to convert. If a key is not defined in the dictionary it's assumed to be None.

None
formatter Callable[[dict[str, Any], str], str]

Custom formatter function. It should accept a dictionary of metric result attributes and an attribute name, and return a formatted attribute value.

get_and_format_num

Returns:

Type Description
DataFrame

Pandas Dataframe with formatted values.

Default formatting rules
  • If a name starts with "rel_" or equals to "power" consider it a percentage value. Round percentage values to 2 significant digits, multiply by 100 and add "%".
  • Round other values to 3 significant values.
  • If value is less than 0.001, format it in exponential presentation.
  • If a name ends with "_ci", consider it a confidence interval. Look up for attributes "{name}_lower" and "{name}_upper", and format the interval as "[{lower_bound}, {lower_bound}]".
Source code in src/tea_tasting/utils.py
def to_pretty(
    self,
    keys: Sequence[str] | None = None,
    formatter: Callable[[dict[str, Any], str], str] = get_and_format_num,
) -> pd.DataFrame:
    """Convert the object to a Pandas Dataframe with formatted values.

    Args:
        keys: Keys to convert. If a key is not defined in the dictionary
            it's assumed to be `None`.
        formatter: Custom formatter function. It should accept a dictionary
            of metric result attributes and an attribute name, and return
            a formatted attribute value.

    Returns:
        Pandas Dataframe with formatted values.

    Default formatting rules:
        - If a name starts with `"rel_"` or equals to `"power"` consider it
            a percentage value. Round percentage values to 2 significant digits,
            multiply by `100` and add `"%"`.
        - Round other values to 3 significant values.
        - If value is less than `0.001`, format it in exponential presentation.
        - If a name ends with `"_ci"`, consider it a confidence interval.
            Look up for attributes `"{name}_lower"` and `"{name}_upper"`,
            and format the interval as `"[{lower_bound}, {lower_bound}]"`.
    """
    if keys is None:
        keys = self.default_keys
    return pd.DataFrame.from_records(
        {key: formatter(data, key) for key in keys}
        for data in self.to_dicts()
    )

to_string(keys=None, formatter=get_and_format_num) #

Convert the object to a string.

Parameters:

Name Type Description Default
keys Sequence[str] | None

Keys to convert. If a key is not defined in the dictionary it's assumed to be None.

None
formatter Callable[[dict[str, Any], str], str]

Custom formatter function. It should accept a dictionary of metric result attributes and an attribute name, and return a formatted attribute value.

get_and_format_num

Returns:

Type Description
str

A table with results rendered as string.

Default formatting rules
  • If a name starts with "rel_" or equals to "power" consider it a percentage value. Round percentage values to 2 significant digits, multiply by 100 and add "%".
  • Round other values to 3 significant values.
  • If value is less than 0.001, format it in exponential presentation.
  • If a name ends with "_ci", consider it a confidence interval. Look up for attributes "{name}_lower" and "{name}_upper", and format the interval as "[{lower_bound}, {lower_bound}]".
Source code in src/tea_tasting/utils.py
def to_string(
    self,
    keys: Sequence[str] | None = None,
    formatter: Callable[[dict[str, Any], str], str] = get_and_format_num,
) -> str:
    """Convert the object to a string.

    Args:
        keys: Keys to convert. If a key is not defined in the dictionary
            it's assumed to be `None`.
        formatter: Custom formatter function. It should accept a dictionary
            of metric result attributes and an attribute name, and return
            a formatted attribute value.

    Returns:
        A table with results rendered as string.

    Default formatting rules:
        - If a name starts with `"rel_"` or equals to `"power"` consider it
            a percentage value. Round percentage values to 2 significant digits,
            multiply by `100` and add `"%"`.
        - Round other values to 3 significant values.
        - If value is less than `0.001`, format it in exponential presentation.
        - If a name ends with `"_ci"`, consider it a confidence interval.
            Look up for attributes `"{name}_lower"` and `"{name}_upper"`,
            and format the interval as `"[{lower_bound}, {lower_bound}]"`.
    """
    return self.to_pretty(keys, formatter).to_string(index=False)

to_html(keys=None, formatter=get_and_format_num) #

Convert the object to HTML.

Parameters:

Name Type Description Default
keys Sequence[str] | None

Keys to convert. If a key is not defined in the dictionary it's assumed to be None.

None
formatter Callable[[dict[str, Any], str], str]

Custom formatter function. It should accept a dictionary of metric result attributes and an attribute name, and return a formatted attribute value.

get_and_format_num

Returns:

Type Description
str

A table with results rendered as HTML.

Default formatting rules
  • If a name starts with "rel_" or equals to "power" consider it a percentage value. Round percentage values to 2 significant digits, multiply by 100 and add "%".
  • Round other values to 3 significant values.
  • If value is less than 0.001, format it in exponential presentation.
  • If a name ends with "_ci", consider it a confidence interval. Look up for attributes "{name}_lower" and "{name}_upper", and format the interval as "[{lower_bound}, {lower_bound}]".
Source code in src/tea_tasting/utils.py
def to_html(
    self,
    keys: Sequence[str] | None = None,
    formatter: Callable[[dict[str, Any], str], str] = get_and_format_num,
) -> str:
    """Convert the object to HTML.

    Args:
        keys: Keys to convert. If a key is not defined in the dictionary
            it's assumed to be `None`.
        formatter: Custom formatter function. It should accept a dictionary
            of metric result attributes and an attribute name, and return
            a formatted attribute value.

    Returns:
        A table with results rendered as HTML.

    Default formatting rules:
        - If a name starts with `"rel_"` or equals to `"power"` consider it
            a percentage value. Round percentage values to 2 significant digits,
            multiply by `100` and add `"%"`.
        - Round other values to 3 significant values.
        - If value is less than `0.001`, format it in exponential presentation.
        - If a name ends with `"_ci"`, consider it a confidence interval.
            Look up for attributes `"{name}_lower"` and `"{name}_upper"`,
            and format the interval as `"[{lower_bound}, {lower_bound}]"`.
    """
    return self.to_pretty(keys, formatter).to_html(index=False)

ReprMixin #

A mixin class that provides a method for generating a string representation.

Representation string is generated based on parameters values saved in attributes.

div(numer, denom, fill_zero_div='auto') #

Perform division, providing specified results for cases of division by zero.

Parameters:

Name Type Description Default
numer float | int

Numerator.

required
denom float | int

Denominator.

required
fill_zero_div float | int | Literal['auto']

Result if denominator is zero.

'auto'

Returns:

Type Description
float | int

Result of the division.

If fill_zero_div is equal "auto", return:

  • nan if numerator is equal to 0,
  • inf if numerator is greater than 0,
  • -inf if numerator is less than 0.
Source code in src/tea_tasting/utils.py
def div(
    numer: float | int,
    denom: float | int,
    fill_zero_div: float | int | Literal["auto"] = "auto",
) -> float |int:
    """Perform division, providing specified results for cases of division by zero.

    Args:
        numer: Numerator.
        denom: Denominator.
        fill_zero_div: Result if denominator is zero.

    Returns:
        Result of the division.

    If `fill_zero_div` is equal `"auto"`, return:

    - `nan` if numerator is equal to `0`,
    - `inf` if numerator is greater than `0`,
    - `-inf` if numerator is less than `0`.
    """
    if denom != 0:
        return numer / denom
    if fill_zero_div != "auto":
        return fill_zero_div
    if numer == 0:
        return float("nan")
    return float("inf") if numer > 0 else float("-inf")

Float #

Bases: _NumericBase, float

Float that gracefully handles division by zero errors.

Int #

Bases: _NumericBase, int

Integer that gracefully handles division by zero errors.

numeric(value, fill_zero_div='auto') #

Float or integer that gracefully handles division by zero errors.

Source code in src/tea_tasting/utils.py
def numeric(
    value: Any,
    fill_zero_div: float | int | Literal["auto"] = "auto",
) -> Numeric:
    """Float or integer that gracefully handles division by zero errors."""
    if isinstance(value, int):
        return Int(value, fill_zero_div)
    if isinstance(value, float):
        return Float(value, fill_zero_div)
    try:
        return Int(value, fill_zero_div)
    except ValueError:
        return Float(value, fill_zero_div)