Skip to content

Unit

kloppy.domain.Unit

Bases: Enum

Unit to measure distances on a pitch.

ATTRIBUTE DESCRIPTION
METERS

Meters

TYPE: str

YARDS

Yards

TYPE: str

CENTIMETERS

Centimeters

TYPE: str

FEET

Feet

TYPE: str

NORMED

Normalized to a unit square

TYPE: str

METERS class-attribute instance-attribute

METERS = 'm'

YARDS class-attribute instance-attribute

YARDS = 'y'

CENTIMETERS class-attribute instance-attribute

CENTIMETERS = 'cm'

FEET class-attribute instance-attribute

FEET = 'ft'

NORMED class-attribute instance-attribute

NORMED = 'normed'

convert

convert(to_unit, value)

Converts a value from one unit to another.

PARAMETER DESCRIPTION
to_unit

The unit to convert to

TYPE: Unit

value

The value to convert

TYPE: float

Returns: The value converted to the target unit

Source code in kloppy/domain/models/pitch.py
def convert(self, to_unit: "Unit", value: float) -> float:
    """Converts a value from one unit to another.

    Arguments:
        to_unit: The unit to convert to
        value: The value to convert
    Returns:
        The value converted to the target unit
    """
    conversion_factors = {
        (Unit.METERS, Unit.METERS): 1,
        (Unit.METERS, Unit.YARDS): 1.09361,
        (Unit.METERS, Unit.CENTIMETERS): 100,
        (Unit.METERS, Unit.FEET): 3.281,
    }
    if self == to_unit:
        return value
    elif self == Unit.NORMED or to_unit == Unit.NORMED:
        raise ValueError("Cannot convert to or from a normed unit")

    factor_to_meter = conversion_factors.get((Unit.METERS, self))
    factor_from_meter = conversion_factors.get((Unit.METERS, to_unit))
    assert (
        factor_to_meter is not None
    ), f"Conversion factor for {self} is not defined"
    assert (
        factor_from_meter is not None
    ), f"Conversion factor for {to_unit} is not defined"
    return value / factor_to_meter * factor_from_meter