Functional Weave
Code in Python

manufacturing.tolerance-check@1.0.0

impl/python.py

1,894 bytes · the Python implementation · view raw

from .manufacturing_tolerance_check_types import ToleranceCheck

LIMIT = 10**12


def _micrometres(name: str, value: int) -> int:
    if isinstance(value, bool) or not isinstance(value, int) or value > LIMIT or value < -LIMIT:
        raise ValueError("%s must be a whole number of micrometres within ±10^12, received %r" % (name, value))
    return value


def check_tolerance(measured: int, nominal: int, upper_deviation: int, lower_deviation: int) -> ToleranceCheck:
    """Check a measurement against nominal plus its upper and lower deviations.

    The deviations are signed and independent, so a tolerance band that lies
    wholly above or below nominal (an H7 hole, a g6 shaft) is checked
    correctly; a symmetric band is just ``+t, -t``.
    """
    _micrometres("measured", measured)
    _micrometres("nominal", nominal)
    _micrometres("upperDeviation", upper_deviation)
    _micrometres("lowerDeviation", lower_deviation)
    if lower_deviation > upper_deviation:
        raise ValueError(
            "lowerDeviation must not be greater than upperDeviation, received %d and %d"
            % (lower_deviation, upper_deviation)
        )
    lower_limit = nominal + lower_deviation
    upper_limit = nominal + upper_deviation
    deviation = measured - nominal
    if measured > upper_limit:
        return ToleranceCheck(
            passed=False, status="above", deviation=deviation,
            lower_limit=lower_limit, upper_limit=upper_limit, out_by=measured - upper_limit,
        )
    if measured < lower_limit:
        return ToleranceCheck(
            passed=False, status="below", deviation=deviation,
            lower_limit=lower_limit, upper_limit=upper_limit, out_by=lower_limit - measured,
        )
    return ToleranceCheck(
        passed=True, status="within", deviation=deviation,
        lower_limit=lower_limit, upper_limit=upper_limit, out_by=0,
    )